您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

handshake_client.go 28 KiB

Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9 年前
Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9 年前
Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9 年前
Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9 年前
Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9 年前
Add DTLS timeout and retransmit tests. This extends the packet adaptor protocol to send three commands: type command = | Packet of []byte | Timeout of time.Duration | TimeoutAck When the shim processes a Timeout in BIO_read, it sends TimeoutAck, fails the BIO_read, returns out of the SSL stack, advances the clock, calls DTLSv1_handle_timeout, and continues. If the Go side sends Timeout right between sending handshake flight N and reading flight N+1, the shim won't read the Timeout until it has sent flight N+1 (it only processes packet commands in BIO_read), so the TimeoutAck comes after N+1. Go then drops all packets before the TimeoutAck, thus dropping one transmit of flight N+1 without having to actually process the packets to determine the end of the flight. The shim then sees the updated clock, calls DTLSv1_handle_timeout, and re-sends flight N+1 for Go to process for real. When dropping packets, Go checks the epoch and increments sequence numbers so that we can continue to be strict here. This requires tracking the initial sequence number of the next epoch. The final Finished message takes an additional special-case to test. DTLS triggers retransmits on either a timeout or seeing a stale flight. OpenSSL only implements the former which should be sufficient (and is necessary) EXCEPT for the final Finished message. If the peer's final Finished message is lost, it won't be waiting for a message from us, so it won't time out anything. That retransmit must be triggered on stale message, so we retransmit the Finished message in Go. Change-Id: I3ffbdb1de525beb2ee831b304670a3387877634c Reviewed-on: https://boringssl-review.googlesource.com/3212 Reviewed-by: Adam Langley <agl@google.com>
9 年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "bytes"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/rsa"
  10. "crypto/subtle"
  11. "crypto/x509"
  12. "encoding/asn1"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "math/big"
  17. "net"
  18. "strconv"
  19. )
  20. type clientHandshakeState struct {
  21. c *Conn
  22. serverHello *serverHelloMsg
  23. hello *clientHelloMsg
  24. suite *cipherSuite
  25. finishedHash finishedHash
  26. masterSecret []byte
  27. session *ClientSessionState
  28. finishedBytes []byte
  29. }
  30. func (c *Conn) clientHandshake() error {
  31. if c.config == nil {
  32. c.config = defaultConfig()
  33. }
  34. if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
  35. return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
  36. }
  37. c.sendHandshakeSeq = 0
  38. c.recvHandshakeSeq = 0
  39. nextProtosLength := 0
  40. for _, proto := range c.config.NextProtos {
  41. if l := len(proto); l > 255 {
  42. return errors.New("tls: invalid NextProtos value")
  43. } else {
  44. nextProtosLength += 1 + l
  45. }
  46. }
  47. if nextProtosLength > 0xffff {
  48. return errors.New("tls: NextProtos values too large")
  49. }
  50. hello := &clientHelloMsg{
  51. isDTLS: c.isDTLS,
  52. vers: c.config.maxVersion(),
  53. compressionMethods: []uint8{compressionNone},
  54. random: make([]byte, 32),
  55. ocspStapling: true,
  56. serverName: c.config.ServerName,
  57. supportedCurves: c.config.curvePreferences(),
  58. supportedPoints: []uint8{pointFormatUncompressed},
  59. nextProtoNeg: len(c.config.NextProtos) > 0,
  60. secureRenegotiation: []byte{},
  61. alpnProtocols: c.config.NextProtos,
  62. duplicateExtension: c.config.Bugs.DuplicateExtension,
  63. channelIDSupported: c.config.ChannelID != nil,
  64. npnLast: c.config.Bugs.SwapNPNAndALPN,
  65. extendedMasterSecret: c.config.maxVersion() >= VersionTLS10,
  66. srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
  67. srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
  68. customExtension: c.config.Bugs.CustomExtension,
  69. }
  70. if c.config.Bugs.SendClientVersion != 0 {
  71. hello.vers = c.config.Bugs.SendClientVersion
  72. }
  73. if c.config.Bugs.NoExtendedMasterSecret {
  74. hello.extendedMasterSecret = false
  75. }
  76. if c.config.Bugs.NoSupportedCurves {
  77. hello.supportedCurves = nil
  78. }
  79. if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
  80. if c.config.Bugs.BadRenegotiationInfo {
  81. hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
  82. hello.secureRenegotiation[0] ^= 0x80
  83. } else {
  84. hello.secureRenegotiation = c.clientVerify
  85. }
  86. }
  87. if c.config.Bugs.NoRenegotiationInfo {
  88. hello.secureRenegotiation = nil
  89. }
  90. possibleCipherSuites := c.config.cipherSuites()
  91. hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
  92. NextCipherSuite:
  93. for _, suiteId := range possibleCipherSuites {
  94. for _, suite := range cipherSuites {
  95. if suite.id != suiteId {
  96. continue
  97. }
  98. // Don't advertise TLS 1.2-only cipher suites unless
  99. // we're attempting TLS 1.2.
  100. if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
  101. continue
  102. }
  103. // Don't advertise non-DTLS cipher suites on DTLS.
  104. if c.isDTLS && suite.flags&suiteNoDTLS != 0 && !c.config.Bugs.EnableAllCiphersInDTLS {
  105. continue
  106. }
  107. hello.cipherSuites = append(hello.cipherSuites, suiteId)
  108. continue NextCipherSuite
  109. }
  110. }
  111. if c.config.Bugs.SendRenegotiationSCSV {
  112. hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
  113. }
  114. if c.config.Bugs.SendFallbackSCSV {
  115. hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
  116. }
  117. _, err := io.ReadFull(c.config.rand(), hello.random)
  118. if err != nil {
  119. c.sendAlert(alertInternalError)
  120. return errors.New("tls: short read from Rand: " + err.Error())
  121. }
  122. if hello.vers >= VersionTLS12 && !c.config.Bugs.NoSignatureAndHashes {
  123. hello.signatureAndHashes = c.config.signatureAndHashesForClient()
  124. }
  125. var session *ClientSessionState
  126. var cacheKey string
  127. sessionCache := c.config.ClientSessionCache
  128. if sessionCache != nil {
  129. hello.ticketSupported = !c.config.SessionTicketsDisabled
  130. // Try to resume a previously negotiated TLS session, if
  131. // available.
  132. cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
  133. candidateSession, ok := sessionCache.Get(cacheKey)
  134. if ok {
  135. ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
  136. // Check that the ciphersuite/version used for the
  137. // previous session are still valid.
  138. cipherSuiteOk := false
  139. for _, id := range hello.cipherSuites {
  140. if id == candidateSession.cipherSuite {
  141. cipherSuiteOk = true
  142. break
  143. }
  144. }
  145. versOk := candidateSession.vers >= c.config.minVersion() &&
  146. candidateSession.vers <= c.config.maxVersion()
  147. if ticketOk && versOk && cipherSuiteOk {
  148. session = candidateSession
  149. }
  150. }
  151. }
  152. if session != nil {
  153. if session.sessionTicket != nil {
  154. hello.sessionTicket = session.sessionTicket
  155. if c.config.Bugs.CorruptTicket {
  156. hello.sessionTicket = make([]byte, len(session.sessionTicket))
  157. copy(hello.sessionTicket, session.sessionTicket)
  158. if len(hello.sessionTicket) > 0 {
  159. offset := 40
  160. if offset > len(hello.sessionTicket) {
  161. offset = len(hello.sessionTicket) - 1
  162. }
  163. hello.sessionTicket[offset] ^= 0x40
  164. }
  165. }
  166. // A random session ID is used to detect when the
  167. // server accepted the ticket and is resuming a session
  168. // (see RFC 5077).
  169. sessionIdLen := 16
  170. if c.config.Bugs.OversizedSessionId {
  171. sessionIdLen = 33
  172. }
  173. hello.sessionId = make([]byte, sessionIdLen)
  174. if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
  175. c.sendAlert(alertInternalError)
  176. return errors.New("tls: short read from Rand: " + err.Error())
  177. }
  178. } else {
  179. hello.sessionId = session.sessionId
  180. }
  181. }
  182. var helloBytes []byte
  183. if c.config.Bugs.SendV2ClientHello {
  184. // Test that the peer left-pads random.
  185. hello.random[0] = 0
  186. v2Hello := &v2ClientHelloMsg{
  187. vers: hello.vers,
  188. cipherSuites: hello.cipherSuites,
  189. // No session resumption for V2ClientHello.
  190. sessionId: nil,
  191. challenge: hello.random[1:],
  192. }
  193. helloBytes = v2Hello.marshal()
  194. c.writeV2Record(helloBytes)
  195. } else {
  196. helloBytes = hello.marshal()
  197. c.writeRecord(recordTypeHandshake, helloBytes)
  198. }
  199. c.dtlsFlushHandshake()
  200. if err := c.simulatePacketLoss(nil); err != nil {
  201. return err
  202. }
  203. msg, err := c.readHandshake()
  204. if err != nil {
  205. return err
  206. }
  207. if c.isDTLS {
  208. helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
  209. if ok {
  210. if helloVerifyRequest.vers != VersionTLS10 {
  211. // Per RFC 6347, the version field in
  212. // HelloVerifyRequest SHOULD be always DTLS
  213. // 1.0. Enforce this for testing purposes.
  214. return errors.New("dtls: bad HelloVerifyRequest version")
  215. }
  216. hello.raw = nil
  217. hello.cookie = helloVerifyRequest.cookie
  218. helloBytes = hello.marshal()
  219. c.writeRecord(recordTypeHandshake, helloBytes)
  220. c.dtlsFlushHandshake()
  221. if err := c.simulatePacketLoss(nil); err != nil {
  222. return err
  223. }
  224. msg, err = c.readHandshake()
  225. if err != nil {
  226. return err
  227. }
  228. }
  229. }
  230. serverHello, ok := msg.(*serverHelloMsg)
  231. if !ok {
  232. c.sendAlert(alertUnexpectedMessage)
  233. return unexpectedMessageError(serverHello, msg)
  234. }
  235. c.vers, ok = c.config.mutualVersion(serverHello.vers)
  236. if !ok {
  237. c.sendAlert(alertProtocolVersion)
  238. return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers)
  239. }
  240. c.haveVers = true
  241. suite := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite)
  242. if suite == nil {
  243. c.sendAlert(alertHandshakeFailure)
  244. return fmt.Errorf("tls: server selected an unsupported cipher suite")
  245. }
  246. if c.config.Bugs.RequireRenegotiationInfo && serverHello.secureRenegotiation == nil {
  247. return errors.New("tls: renegotiation extension missing")
  248. }
  249. if len(c.clientVerify) > 0 && !c.config.Bugs.NoRenegotiationInfo {
  250. var expectedRenegInfo []byte
  251. expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
  252. expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
  253. if !bytes.Equal(serverHello.secureRenegotiation, expectedRenegInfo) {
  254. c.sendAlert(alertHandshakeFailure)
  255. return fmt.Errorf("tls: renegotiation mismatch")
  256. }
  257. }
  258. if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
  259. if serverHello.customExtension != *expected {
  260. return fmt.Errorf("tls: bad custom extension contents %q", serverHello.customExtension)
  261. }
  262. }
  263. hs := &clientHandshakeState{
  264. c: c,
  265. serverHello: serverHello,
  266. hello: hello,
  267. suite: suite,
  268. finishedHash: newFinishedHash(c.vers, suite),
  269. session: session,
  270. }
  271. hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
  272. hs.writeServerHash(hs.serverHello.marshal())
  273. if c.config.Bugs.EarlyChangeCipherSpec > 0 {
  274. hs.establishKeys()
  275. c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
  276. }
  277. isResume, err := hs.processServerHello()
  278. if err != nil {
  279. return err
  280. }
  281. if isResume {
  282. if c.config.Bugs.EarlyChangeCipherSpec == 0 {
  283. if err := hs.establishKeys(); err != nil {
  284. return err
  285. }
  286. }
  287. if err := hs.readSessionTicket(); err != nil {
  288. return err
  289. }
  290. if err := hs.readFinished(c.firstFinished[:]); err != nil {
  291. return err
  292. }
  293. if err := hs.sendFinished(nil, isResume); err != nil {
  294. return err
  295. }
  296. } else {
  297. if err := hs.doFullHandshake(); err != nil {
  298. return err
  299. }
  300. if err := hs.establishKeys(); err != nil {
  301. return err
  302. }
  303. if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
  304. return err
  305. }
  306. // Most retransmits are triggered by a timeout, but the final
  307. // leg of the handshake is retransmited upon re-receiving a
  308. // Finished.
  309. if err := c.simulatePacketLoss(func() {
  310. c.writeRecord(recordTypeHandshake, hs.finishedBytes)
  311. c.dtlsFlushHandshake()
  312. }); err != nil {
  313. return err
  314. }
  315. if err := hs.readSessionTicket(); err != nil {
  316. return err
  317. }
  318. if err := hs.readFinished(nil); err != nil {
  319. return err
  320. }
  321. }
  322. if sessionCache != nil && hs.session != nil && session != hs.session {
  323. sessionCache.Put(cacheKey, hs.session)
  324. }
  325. c.didResume = isResume
  326. c.handshakeComplete = true
  327. c.cipherSuite = suite
  328. copy(c.clientRandom[:], hs.hello.random)
  329. copy(c.serverRandom[:], hs.serverHello.random)
  330. copy(c.masterSecret[:], hs.masterSecret)
  331. return nil
  332. }
  333. func (hs *clientHandshakeState) doFullHandshake() error {
  334. c := hs.c
  335. var leaf *x509.Certificate
  336. if hs.suite.flags&suitePSK == 0 {
  337. msg, err := c.readHandshake()
  338. if err != nil {
  339. return err
  340. }
  341. certMsg, ok := msg.(*certificateMsg)
  342. if !ok || len(certMsg.certificates) == 0 {
  343. c.sendAlert(alertUnexpectedMessage)
  344. return unexpectedMessageError(certMsg, msg)
  345. }
  346. hs.writeServerHash(certMsg.marshal())
  347. certs := make([]*x509.Certificate, len(certMsg.certificates))
  348. for i, asn1Data := range certMsg.certificates {
  349. cert, err := x509.ParseCertificate(asn1Data)
  350. if err != nil {
  351. c.sendAlert(alertBadCertificate)
  352. return errors.New("tls: failed to parse certificate from server: " + err.Error())
  353. }
  354. certs[i] = cert
  355. }
  356. leaf = certs[0]
  357. if !c.config.InsecureSkipVerify {
  358. opts := x509.VerifyOptions{
  359. Roots: c.config.RootCAs,
  360. CurrentTime: c.config.time(),
  361. DNSName: c.config.ServerName,
  362. Intermediates: x509.NewCertPool(),
  363. }
  364. for i, cert := range certs {
  365. if i == 0 {
  366. continue
  367. }
  368. opts.Intermediates.AddCert(cert)
  369. }
  370. c.verifiedChains, err = leaf.Verify(opts)
  371. if err != nil {
  372. c.sendAlert(alertBadCertificate)
  373. return err
  374. }
  375. }
  376. switch leaf.PublicKey.(type) {
  377. case *rsa.PublicKey, *ecdsa.PublicKey:
  378. break
  379. default:
  380. c.sendAlert(alertUnsupportedCertificate)
  381. return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", leaf.PublicKey)
  382. }
  383. c.peerCertificates = certs
  384. }
  385. if hs.serverHello.ocspStapling {
  386. msg, err := c.readHandshake()
  387. if err != nil {
  388. return err
  389. }
  390. cs, ok := msg.(*certificateStatusMsg)
  391. if !ok {
  392. c.sendAlert(alertUnexpectedMessage)
  393. return unexpectedMessageError(cs, msg)
  394. }
  395. hs.writeServerHash(cs.marshal())
  396. if cs.statusType == statusTypeOCSP {
  397. c.ocspResponse = cs.response
  398. }
  399. }
  400. msg, err := c.readHandshake()
  401. if err != nil {
  402. return err
  403. }
  404. keyAgreement := hs.suite.ka(c.vers)
  405. skx, ok := msg.(*serverKeyExchangeMsg)
  406. if ok {
  407. hs.writeServerHash(skx.marshal())
  408. err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
  409. if err != nil {
  410. c.sendAlert(alertUnexpectedMessage)
  411. return err
  412. }
  413. msg, err = c.readHandshake()
  414. if err != nil {
  415. return err
  416. }
  417. }
  418. var chainToSend *Certificate
  419. var certRequested bool
  420. certReq, ok := msg.(*certificateRequestMsg)
  421. if ok {
  422. certRequested = true
  423. // RFC 4346 on the certificateAuthorities field:
  424. // A list of the distinguished names of acceptable certificate
  425. // authorities. These distinguished names may specify a desired
  426. // distinguished name for a root CA or for a subordinate CA;
  427. // thus, this message can be used to describe both known roots
  428. // and a desired authorization space. If the
  429. // certificate_authorities list is empty then the client MAY
  430. // send any certificate of the appropriate
  431. // ClientCertificateType, unless there is some external
  432. // arrangement to the contrary.
  433. hs.writeServerHash(certReq.marshal())
  434. var rsaAvail, ecdsaAvail bool
  435. for _, certType := range certReq.certificateTypes {
  436. switch certType {
  437. case CertTypeRSASign:
  438. rsaAvail = true
  439. case CertTypeECDSASign:
  440. ecdsaAvail = true
  441. }
  442. }
  443. // We need to search our list of client certs for one
  444. // where SignatureAlgorithm is RSA and the Issuer is in
  445. // certReq.certificateAuthorities
  446. findCert:
  447. for i, chain := range c.config.Certificates {
  448. if !rsaAvail && !ecdsaAvail {
  449. continue
  450. }
  451. for j, cert := range chain.Certificate {
  452. x509Cert := chain.Leaf
  453. // parse the certificate if this isn't the leaf
  454. // node, or if chain.Leaf was nil
  455. if j != 0 || x509Cert == nil {
  456. if x509Cert, err = x509.ParseCertificate(cert); err != nil {
  457. c.sendAlert(alertInternalError)
  458. return errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
  459. }
  460. }
  461. switch {
  462. case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
  463. case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
  464. default:
  465. continue findCert
  466. }
  467. if len(certReq.certificateAuthorities) == 0 {
  468. // they gave us an empty list, so just take the
  469. // first RSA cert from c.config.Certificates
  470. chainToSend = &chain
  471. break findCert
  472. }
  473. for _, ca := range certReq.certificateAuthorities {
  474. if bytes.Equal(x509Cert.RawIssuer, ca) {
  475. chainToSend = &chain
  476. break findCert
  477. }
  478. }
  479. }
  480. }
  481. msg, err = c.readHandshake()
  482. if err != nil {
  483. return err
  484. }
  485. }
  486. shd, ok := msg.(*serverHelloDoneMsg)
  487. if !ok {
  488. c.sendAlert(alertUnexpectedMessage)
  489. return unexpectedMessageError(shd, msg)
  490. }
  491. hs.writeServerHash(shd.marshal())
  492. // If the server requested a certificate then we have to send a
  493. // Certificate message, even if it's empty because we don't have a
  494. // certificate to send.
  495. if certRequested {
  496. certMsg := new(certificateMsg)
  497. if chainToSend != nil {
  498. certMsg.certificates = chainToSend.Certificate
  499. }
  500. hs.writeClientHash(certMsg.marshal())
  501. c.writeRecord(recordTypeHandshake, certMsg.marshal())
  502. }
  503. preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
  504. if err != nil {
  505. c.sendAlert(alertInternalError)
  506. return err
  507. }
  508. if ckx != nil {
  509. if c.config.Bugs.EarlyChangeCipherSpec < 2 {
  510. hs.writeClientHash(ckx.marshal())
  511. }
  512. c.writeRecord(recordTypeHandshake, ckx.marshal())
  513. }
  514. if hs.serverHello.extendedMasterSecret && c.vers >= VersionTLS10 {
  515. hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
  516. c.extendedMasterSecret = true
  517. } else {
  518. if c.config.Bugs.RequireExtendedMasterSecret {
  519. return errors.New("tls: extended master secret required but not supported by peer")
  520. }
  521. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
  522. }
  523. if chainToSend != nil {
  524. var signed []byte
  525. certVerify := &certificateVerifyMsg{
  526. hasSignatureAndHash: c.vers >= VersionTLS12,
  527. }
  528. // Determine the hash to sign.
  529. var signatureType uint8
  530. switch c.config.Certificates[0].PrivateKey.(type) {
  531. case *ecdsa.PrivateKey:
  532. signatureType = signatureECDSA
  533. case *rsa.PrivateKey:
  534. signatureType = signatureRSA
  535. default:
  536. c.sendAlert(alertInternalError)
  537. return errors.New("unknown private key type")
  538. }
  539. if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
  540. certReq.signatureAndHashes = c.config.signatureAndHashesForClient()
  541. }
  542. certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, c.config.signatureAndHashesForClient(), signatureType)
  543. if err != nil {
  544. c.sendAlert(alertInternalError)
  545. return err
  546. }
  547. digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret)
  548. if err != nil {
  549. c.sendAlert(alertInternalError)
  550. return err
  551. }
  552. if c.config.Bugs.InvalidCertVerifySignature {
  553. digest[0] ^= 0x80
  554. }
  555. switch key := c.config.Certificates[0].PrivateKey.(type) {
  556. case *ecdsa.PrivateKey:
  557. var r, s *big.Int
  558. r, s, err = ecdsa.Sign(c.config.rand(), key, digest)
  559. if err == nil {
  560. signed, err = asn1.Marshal(ecdsaSignature{r, s})
  561. }
  562. case *rsa.PrivateKey:
  563. signed, err = rsa.SignPKCS1v15(c.config.rand(), key, hashFunc, digest)
  564. default:
  565. err = errors.New("unknown private key type")
  566. }
  567. if err != nil {
  568. c.sendAlert(alertInternalError)
  569. return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
  570. }
  571. certVerify.signature = signed
  572. hs.writeClientHash(certVerify.marshal())
  573. c.writeRecord(recordTypeHandshake, certVerify.marshal())
  574. }
  575. c.dtlsFlushHandshake()
  576. hs.finishedHash.discardHandshakeBuffer()
  577. return nil
  578. }
  579. func (hs *clientHandshakeState) establishKeys() error {
  580. c := hs.c
  581. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  582. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  583. var clientCipher, serverCipher interface{}
  584. var clientHash, serverHash macFunction
  585. if hs.suite.cipher != nil {
  586. clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
  587. clientHash = hs.suite.mac(c.vers, clientMAC)
  588. serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
  589. serverHash = hs.suite.mac(c.vers, serverMAC)
  590. } else {
  591. clientCipher = hs.suite.aead(clientKey, clientIV)
  592. serverCipher = hs.suite.aead(serverKey, serverIV)
  593. }
  594. c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
  595. c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
  596. return nil
  597. }
  598. func (hs *clientHandshakeState) serverResumedSession() bool {
  599. // If the server responded with the same sessionId then it means the
  600. // sessionTicket is being used to resume a TLS session.
  601. return hs.session != nil && hs.hello.sessionId != nil &&
  602. bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
  603. }
  604. func (hs *clientHandshakeState) processServerHello() (bool, error) {
  605. c := hs.c
  606. if hs.serverHello.compressionMethod != compressionNone {
  607. c.sendAlert(alertUnexpectedMessage)
  608. return false, errors.New("tls: server selected unsupported compression format")
  609. }
  610. clientDidNPN := hs.hello.nextProtoNeg
  611. clientDidALPN := len(hs.hello.alpnProtocols) > 0
  612. serverHasNPN := hs.serverHello.nextProtoNeg
  613. serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
  614. if !clientDidNPN && serverHasNPN {
  615. c.sendAlert(alertHandshakeFailure)
  616. return false, errors.New("server advertised unrequested NPN extension")
  617. }
  618. if !clientDidALPN && serverHasALPN {
  619. c.sendAlert(alertHandshakeFailure)
  620. return false, errors.New("server advertised unrequested ALPN extension")
  621. }
  622. if serverHasNPN && serverHasALPN {
  623. c.sendAlert(alertHandshakeFailure)
  624. return false, errors.New("server advertised both NPN and ALPN extensions")
  625. }
  626. if serverHasALPN {
  627. c.clientProtocol = hs.serverHello.alpnProtocol
  628. c.clientProtocolFallback = false
  629. c.usedALPN = true
  630. }
  631. if !hs.hello.channelIDSupported && hs.serverHello.channelIDRequested {
  632. c.sendAlert(alertHandshakeFailure)
  633. return false, errors.New("server advertised unrequested Channel ID extension")
  634. }
  635. if hs.serverHello.srtpProtectionProfile != 0 {
  636. if hs.serverHello.srtpMasterKeyIdentifier != "" {
  637. return false, errors.New("tls: server selected SRTP MKI value")
  638. }
  639. found := false
  640. for _, p := range c.config.SRTPProtectionProfiles {
  641. if p == hs.serverHello.srtpProtectionProfile {
  642. found = true
  643. break
  644. }
  645. }
  646. if !found {
  647. return false, errors.New("tls: server advertised unsupported SRTP profile")
  648. }
  649. c.srtpProtectionProfile = hs.serverHello.srtpProtectionProfile
  650. }
  651. if hs.serverResumedSession() {
  652. // For test purposes, assert that the server never accepts the
  653. // resumption offer on renegotiation.
  654. if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
  655. return false, errors.New("tls: server resumed session on renegotiation")
  656. }
  657. // Restore masterSecret and peerCerts from previous state
  658. hs.masterSecret = hs.session.masterSecret
  659. c.peerCertificates = hs.session.serverCertificates
  660. c.extendedMasterSecret = hs.session.extendedMasterSecret
  661. hs.finishedHash.discardHandshakeBuffer()
  662. return true, nil
  663. }
  664. return false, nil
  665. }
  666. func (hs *clientHandshakeState) readFinished(out []byte) error {
  667. c := hs.c
  668. c.readRecord(recordTypeChangeCipherSpec)
  669. if err := c.in.error(); err != nil {
  670. return err
  671. }
  672. msg, err := c.readHandshake()
  673. if err != nil {
  674. return err
  675. }
  676. serverFinished, ok := msg.(*finishedMsg)
  677. if !ok {
  678. c.sendAlert(alertUnexpectedMessage)
  679. return unexpectedMessageError(serverFinished, msg)
  680. }
  681. if c.config.Bugs.EarlyChangeCipherSpec == 0 {
  682. verify := hs.finishedHash.serverSum(hs.masterSecret)
  683. if len(verify) != len(serverFinished.verifyData) ||
  684. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  685. c.sendAlert(alertHandshakeFailure)
  686. return errors.New("tls: server's Finished message was incorrect")
  687. }
  688. }
  689. c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
  690. copy(out, serverFinished.verifyData)
  691. hs.writeServerHash(serverFinished.marshal())
  692. return nil
  693. }
  694. func (hs *clientHandshakeState) readSessionTicket() error {
  695. c := hs.c
  696. // Create a session with no server identifier. Either a
  697. // session ID or session ticket will be attached.
  698. session := &ClientSessionState{
  699. vers: c.vers,
  700. cipherSuite: hs.suite.id,
  701. masterSecret: hs.masterSecret,
  702. handshakeHash: hs.finishedHash.server.Sum(nil),
  703. serverCertificates: c.peerCertificates,
  704. }
  705. if !hs.serverHello.ticketSupported {
  706. if c.config.Bugs.ExpectNewTicket {
  707. return errors.New("tls: expected new ticket")
  708. }
  709. if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
  710. session.sessionId = hs.serverHello.sessionId
  711. hs.session = session
  712. }
  713. return nil
  714. }
  715. msg, err := c.readHandshake()
  716. if err != nil {
  717. return err
  718. }
  719. sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
  720. if !ok {
  721. c.sendAlert(alertUnexpectedMessage)
  722. return unexpectedMessageError(sessionTicketMsg, msg)
  723. }
  724. session.sessionTicket = sessionTicketMsg.ticket
  725. hs.session = session
  726. hs.writeServerHash(sessionTicketMsg.marshal())
  727. return nil
  728. }
  729. func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
  730. c := hs.c
  731. var postCCSBytes []byte
  732. seqno := hs.c.sendHandshakeSeq
  733. if hs.serverHello.nextProtoNeg {
  734. nextProto := new(nextProtoMsg)
  735. proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
  736. nextProto.proto = proto
  737. c.clientProtocol = proto
  738. c.clientProtocolFallback = fallback
  739. nextProtoBytes := nextProto.marshal()
  740. hs.writeHash(nextProtoBytes, seqno)
  741. seqno++
  742. postCCSBytes = append(postCCSBytes, nextProtoBytes...)
  743. }
  744. if hs.serverHello.channelIDRequested {
  745. encryptedExtensions := new(encryptedExtensionsMsg)
  746. if c.config.ChannelID.Curve != elliptic.P256() {
  747. return fmt.Errorf("tls: Channel ID is not on P-256.")
  748. }
  749. var resumeHash []byte
  750. if isResume {
  751. resumeHash = hs.session.handshakeHash
  752. }
  753. r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, hs.finishedHash.hashForChannelID(resumeHash))
  754. if err != nil {
  755. return err
  756. }
  757. channelID := make([]byte, 128)
  758. writeIntPadded(channelID[0:32], c.config.ChannelID.X)
  759. writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
  760. writeIntPadded(channelID[64:96], r)
  761. writeIntPadded(channelID[96:128], s)
  762. encryptedExtensions.channelID = channelID
  763. c.channelID = &c.config.ChannelID.PublicKey
  764. encryptedExtensionsBytes := encryptedExtensions.marshal()
  765. hs.writeHash(encryptedExtensionsBytes, seqno)
  766. seqno++
  767. postCCSBytes = append(postCCSBytes, encryptedExtensionsBytes...)
  768. }
  769. finished := new(finishedMsg)
  770. if c.config.Bugs.EarlyChangeCipherSpec == 2 {
  771. finished.verifyData = hs.finishedHash.clientSum(nil)
  772. } else {
  773. finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
  774. }
  775. copy(out, finished.verifyData)
  776. if c.config.Bugs.BadFinished {
  777. finished.verifyData[0]++
  778. }
  779. c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
  780. hs.finishedBytes = finished.marshal()
  781. hs.writeHash(hs.finishedBytes, seqno)
  782. postCCSBytes = append(postCCSBytes, hs.finishedBytes...)
  783. if c.config.Bugs.FragmentAcrossChangeCipherSpec {
  784. c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
  785. postCCSBytes = postCCSBytes[5:]
  786. }
  787. c.dtlsFlushHandshake()
  788. if !c.config.Bugs.SkipChangeCipherSpec &&
  789. c.config.Bugs.EarlyChangeCipherSpec == 0 {
  790. c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
  791. }
  792. if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
  793. c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
  794. }
  795. if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
  796. c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
  797. return errors.New("tls: simulating post-CCS alert")
  798. }
  799. if !c.config.Bugs.SkipFinished {
  800. c.writeRecord(recordTypeHandshake, postCCSBytes)
  801. c.dtlsFlushHandshake()
  802. }
  803. return nil
  804. }
  805. func (hs *clientHandshakeState) writeClientHash(msg []byte) {
  806. // writeClientHash is called before writeRecord.
  807. hs.writeHash(msg, hs.c.sendHandshakeSeq)
  808. }
  809. func (hs *clientHandshakeState) writeServerHash(msg []byte) {
  810. // writeServerHash is called after readHandshake.
  811. hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
  812. }
  813. func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
  814. if hs.c.isDTLS {
  815. // This is somewhat hacky. DTLS hashes a slightly different format.
  816. // First, the TLS header.
  817. hs.finishedHash.Write(msg[:4])
  818. // Then the sequence number and reassembled fragment offset (always 0).
  819. hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
  820. // Then the reassembled fragment (always equal to the message length).
  821. hs.finishedHash.Write(msg[1:4])
  822. // And then the message body.
  823. hs.finishedHash.Write(msg[4:])
  824. } else {
  825. hs.finishedHash.Write(msg)
  826. }
  827. }
  828. // clientSessionCacheKey returns a key used to cache sessionTickets that could
  829. // be used to resume previously negotiated TLS sessions with a server.
  830. func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
  831. if len(config.ServerName) > 0 {
  832. return config.ServerName
  833. }
  834. return serverAddr.String()
  835. }
  836. // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
  837. // given list of possible protocols and a list of the preference order. The
  838. // first list must not be empty. It returns the resulting protocol and flag
  839. // indicating if the fallback case was reached.
  840. func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
  841. for _, s := range preferenceProtos {
  842. for _, c := range protos {
  843. if s == c {
  844. return s, false
  845. }
  846. }
  847. }
  848. return protos[0], true
  849. }
  850. // writeIntPadded writes x into b, padded up with leading zeros as
  851. // needed.
  852. func writeIntPadded(b []byte, x *big.Int) {
  853. for i := range b {
  854. b[i] = 0
  855. }
  856. xb := x.Bytes()
  857. copy(b[len(b)-len(xb):], xb)
  858. }