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

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