handshake_client_tls13.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. // Copyright 2018 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 tls
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto"
  9. "crypto/hmac"
  10. "crypto/rsa"
  11. "errors"
  12. "hash"
  13. "time"
  14. "crypto/ecdh"
  15. )
  16. type clientHandshakeStateTLS13 struct {
  17. c *Conn
  18. ctx context.Context
  19. serverHello *serverHelloMsg
  20. hello *clientHelloMsg
  21. ecdheKey *ecdh.PrivateKey
  22. session *ClientSessionState
  23. earlySecret []byte
  24. binderKey []byte
  25. certReq *certificateRequestMsgTLS13
  26. usingPSK bool
  27. sentDummyCCS bool
  28. suite *cipherSuiteTLS13
  29. transcript hash.Hash
  30. masterSecret []byte
  31. trafficSecret []byte // client_application_traffic_secret_0
  32. }
  33. // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheKey, and,
  34. // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
  35. func (hs *clientHandshakeStateTLS13) handshake() error {
  36. c := hs.c
  37. if needFIPS() {
  38. return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
  39. }
  40. // The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
  41. // sections 4.1.2 and 4.1.3.
  42. if c.handshakes > 0 {
  43. c.sendAlert(alertProtocolVersion)
  44. return errors.New("tls: server selected TLS 1.3 in a renegotiation")
  45. }
  46. // Consistency check on the presence of a keyShare and its parameters.
  47. if hs.ecdheKey == nil || len(hs.hello.keyShares) != 1 {
  48. return c.sendAlert(alertInternalError)
  49. }
  50. if err := hs.checkServerHelloOrHRR(); err != nil {
  51. return err
  52. }
  53. hs.transcript = hs.suite.hash.New()
  54. hs.transcript.Write(hs.hello.marshal())
  55. if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
  56. if err := hs.sendDummyChangeCipherSpec(); err != nil {
  57. return err
  58. }
  59. if err := hs.processHelloRetryRequest(); err != nil {
  60. return err
  61. }
  62. }
  63. hs.transcript.Write(hs.serverHello.marshal())
  64. c.buffering = true
  65. if err := hs.processServerHello(); err != nil {
  66. return err
  67. }
  68. if err := hs.sendDummyChangeCipherSpec(); err != nil {
  69. return err
  70. }
  71. if err := hs.establishHandshakeKeys(); err != nil {
  72. return err
  73. }
  74. if err := hs.readServerParameters(); err != nil {
  75. return err
  76. }
  77. if err := hs.readServerCertificate(); err != nil {
  78. return err
  79. }
  80. if err := hs.readServerFinished(); err != nil {
  81. return err
  82. }
  83. if err := hs.sendClientCertificate(); err != nil {
  84. return err
  85. }
  86. if err := hs.sendClientFinished(); err != nil {
  87. return err
  88. }
  89. if _, err := c.flush(); err != nil {
  90. return err
  91. }
  92. c.isHandshakeComplete.Store(true)
  93. return nil
  94. }
  95. // checkServerHelloOrHRR does validity checks that apply to both ServerHello and
  96. // HelloRetryRequest messages. It sets hs.suite.
  97. func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
  98. c := hs.c
  99. if hs.serverHello.supportedVersion == 0 {
  100. c.sendAlert(alertMissingExtension)
  101. return errors.New("tls: server selected TLS 1.3 using the legacy version field")
  102. }
  103. if hs.serverHello.supportedVersion != VersionTLS13 {
  104. c.sendAlert(alertIllegalParameter)
  105. return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
  106. }
  107. if hs.serverHello.vers != VersionTLS12 {
  108. c.sendAlert(alertIllegalParameter)
  109. return errors.New("tls: server sent an incorrect legacy version")
  110. }
  111. if hs.serverHello.ocspStapling ||
  112. hs.serverHello.ticketSupported ||
  113. hs.serverHello.secureRenegotiationSupported ||
  114. len(hs.serverHello.secureRenegotiation) != 0 ||
  115. len(hs.serverHello.alpnProtocol) != 0 ||
  116. len(hs.serverHello.scts) != 0 {
  117. c.sendAlert(alertUnsupportedExtension)
  118. return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
  119. }
  120. if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
  121. c.sendAlert(alertIllegalParameter)
  122. return errors.New("tls: server did not echo the legacy session ID")
  123. }
  124. if hs.serverHello.compressionMethod != compressionNone {
  125. c.sendAlert(alertIllegalParameter)
  126. return errors.New("tls: server selected unsupported compression format")
  127. }
  128. selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
  129. if hs.suite != nil && selectedSuite != hs.suite {
  130. c.sendAlert(alertIllegalParameter)
  131. return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
  132. }
  133. if selectedSuite == nil {
  134. c.sendAlert(alertIllegalParameter)
  135. return errors.New("tls: server chose an unconfigured cipher suite")
  136. }
  137. hs.suite = selectedSuite
  138. c.cipherSuite = hs.suite.id
  139. return nil
  140. }
  141. // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
  142. // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
  143. func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
  144. if hs.sentDummyCCS {
  145. return nil
  146. }
  147. hs.sentDummyCCS = true
  148. _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
  149. return err
  150. }
  151. // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
  152. // resends hs.hello, and reads the new ServerHello into hs.serverHello.
  153. func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
  154. c := hs.c
  155. // The first ClientHello gets double-hashed into the transcript upon a
  156. // HelloRetryRequest. (The idea is that the server might offload transcript
  157. // storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
  158. chHash := hs.transcript.Sum(nil)
  159. hs.transcript.Reset()
  160. hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
  161. hs.transcript.Write(chHash)
  162. hs.transcript.Write(hs.serverHello.marshal())
  163. // The only HelloRetryRequest extensions we support are key_share and
  164. // cookie, and clients must abort the handshake if the HRR would not result
  165. // in any change in the ClientHello.
  166. if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
  167. c.sendAlert(alertIllegalParameter)
  168. return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
  169. }
  170. if hs.serverHello.cookie != nil {
  171. hs.hello.cookie = hs.serverHello.cookie
  172. }
  173. if hs.serverHello.serverShare.group != 0 {
  174. c.sendAlert(alertDecodeError)
  175. return errors.New("tls: received malformed key_share extension")
  176. }
  177. // If the server sent a key_share extension selecting a group, ensure it's
  178. // a group we advertised but did not send a key share for, and send a key
  179. // share for it this time.
  180. if curveID := hs.serverHello.selectedGroup; curveID != 0 {
  181. curveOK := false
  182. for _, id := range hs.hello.supportedCurves {
  183. if id == curveID {
  184. curveOK = true
  185. break
  186. }
  187. }
  188. if !curveOK {
  189. c.sendAlert(alertIllegalParameter)
  190. return errors.New("tls: server selected unsupported group")
  191. }
  192. if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); sentID == curveID {
  193. c.sendAlert(alertIllegalParameter)
  194. return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
  195. }
  196. if _, ok := curveForCurveID(curveID); !ok {
  197. c.sendAlert(alertInternalError)
  198. return errors.New("tls: CurvePreferences includes unsupported curve")
  199. }
  200. key, err := generateECDHEKey(c.config.rand(), curveID)
  201. if err != nil {
  202. c.sendAlert(alertInternalError)
  203. return err
  204. }
  205. hs.ecdheKey = key
  206. hs.hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
  207. }
  208. hs.hello.raw = nil
  209. if len(hs.hello.pskIdentities) > 0 {
  210. pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
  211. if pskSuite == nil {
  212. return c.sendAlert(alertInternalError)
  213. }
  214. if pskSuite.hash == hs.suite.hash {
  215. // Update binders and obfuscated_ticket_age.
  216. ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond)
  217. hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd
  218. transcript := hs.suite.hash.New()
  219. transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
  220. transcript.Write(chHash)
  221. transcript.Write(hs.serverHello.marshal())
  222. transcript.Write(hs.hello.marshalWithoutBinders())
  223. pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
  224. hs.hello.updateBinders(pskBinders)
  225. } else {
  226. // Server selected a cipher suite incompatible with the PSK.
  227. hs.hello.pskIdentities = nil
  228. hs.hello.pskBinders = nil
  229. }
  230. }
  231. hs.transcript.Write(hs.hello.marshal())
  232. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  233. return err
  234. }
  235. msg, err := c.readHandshake()
  236. if err != nil {
  237. return err
  238. }
  239. serverHello, ok := msg.(*serverHelloMsg)
  240. if !ok {
  241. c.sendAlert(alertUnexpectedMessage)
  242. return unexpectedMessageError(serverHello, msg)
  243. }
  244. hs.serverHello = serverHello
  245. if err := hs.checkServerHelloOrHRR(); err != nil {
  246. return err
  247. }
  248. return nil
  249. }
  250. func (hs *clientHandshakeStateTLS13) processServerHello() error {
  251. c := hs.c
  252. if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
  253. c.sendAlert(alertUnexpectedMessage)
  254. return errors.New("tls: server sent two HelloRetryRequest messages")
  255. }
  256. if len(hs.serverHello.cookie) != 0 {
  257. c.sendAlert(alertUnsupportedExtension)
  258. return errors.New("tls: server sent a cookie in a normal ServerHello")
  259. }
  260. if hs.serverHello.selectedGroup != 0 {
  261. c.sendAlert(alertDecodeError)
  262. return errors.New("tls: malformed key_share extension")
  263. }
  264. if hs.serverHello.serverShare.group == 0 {
  265. c.sendAlert(alertIllegalParameter)
  266. return errors.New("tls: server did not send a key share")
  267. }
  268. if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); hs.serverHello.serverShare.group != sentID {
  269. c.sendAlert(alertIllegalParameter)
  270. return errors.New("tls: server selected unsupported group")
  271. }
  272. if !hs.serverHello.selectedIdentityPresent {
  273. return nil
  274. }
  275. if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
  276. c.sendAlert(alertIllegalParameter)
  277. return errors.New("tls: server selected an invalid PSK")
  278. }
  279. if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
  280. return c.sendAlert(alertInternalError)
  281. }
  282. pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
  283. if pskSuite == nil {
  284. return c.sendAlert(alertInternalError)
  285. }
  286. if pskSuite.hash != hs.suite.hash {
  287. c.sendAlert(alertIllegalParameter)
  288. return errors.New("tls: server selected an invalid PSK and cipher suite pair")
  289. }
  290. hs.usingPSK = true
  291. c.didResume = true
  292. c.peerCertificates = hs.session.serverCertificates
  293. c.verifiedChains = hs.session.verifiedChains
  294. c.ocspResponse = hs.session.ocspResponse
  295. c.scts = hs.session.scts
  296. return nil
  297. }
  298. func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
  299. c := hs.c
  300. peerKey, err := hs.ecdheKey.Curve().NewPublicKey(hs.serverHello.serverShare.data)
  301. if err != nil {
  302. c.sendAlert(alertIllegalParameter)
  303. return errors.New("tls: invalid server key share")
  304. }
  305. sharedKey, err := hs.ecdheKey.ECDH(peerKey)
  306. if err != nil {
  307. c.sendAlert(alertIllegalParameter)
  308. return errors.New("tls: invalid server key share")
  309. }
  310. earlySecret := hs.earlySecret
  311. if !hs.usingPSK {
  312. earlySecret = hs.suite.extract(nil, nil)
  313. }
  314. handshakeSecret := hs.suite.extract(sharedKey,
  315. hs.suite.deriveSecret(earlySecret, "derived", nil))
  316. clientSecret := hs.suite.deriveSecret(handshakeSecret,
  317. clientHandshakeTrafficLabel, hs.transcript)
  318. c.out.setTrafficSecret(hs.suite, clientSecret)
  319. serverSecret := hs.suite.deriveSecret(handshakeSecret,
  320. serverHandshakeTrafficLabel, hs.transcript)
  321. c.in.setTrafficSecret(hs.suite, serverSecret)
  322. err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
  323. if err != nil {
  324. c.sendAlert(alertInternalError)
  325. return err
  326. }
  327. err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
  328. if err != nil {
  329. c.sendAlert(alertInternalError)
  330. return err
  331. }
  332. hs.masterSecret = hs.suite.extract(nil,
  333. hs.suite.deriveSecret(handshakeSecret, "derived", nil))
  334. return nil
  335. }
  336. func (hs *clientHandshakeStateTLS13) readServerParameters() error {
  337. c := hs.c
  338. msg, err := c.readHandshake()
  339. if err != nil {
  340. return err
  341. }
  342. encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
  343. if !ok {
  344. c.sendAlert(alertUnexpectedMessage)
  345. return unexpectedMessageError(encryptedExtensions, msg)
  346. }
  347. hs.transcript.Write(encryptedExtensions.marshal())
  348. if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol); err != nil {
  349. c.sendAlert(alertUnsupportedExtension)
  350. return err
  351. }
  352. c.clientProtocol = encryptedExtensions.alpnProtocol
  353. return nil
  354. }
  355. func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
  356. c := hs.c
  357. // Either a PSK or a certificate is always used, but not both.
  358. // See RFC 8446, Section 4.1.1.
  359. if hs.usingPSK {
  360. // Make sure the connection is still being verified whether or not this
  361. // is a resumption. Resumptions currently don't reverify certificates so
  362. // they don't call verifyServerCertificate. See Issue 31641.
  363. if c.config.VerifyConnection != nil {
  364. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  365. c.sendAlert(alertBadCertificate)
  366. return err
  367. }
  368. }
  369. return nil
  370. }
  371. msg, err := c.readHandshake()
  372. if err != nil {
  373. return err
  374. }
  375. certReq, ok := msg.(*certificateRequestMsgTLS13)
  376. if ok {
  377. hs.transcript.Write(certReq.marshal())
  378. hs.certReq = certReq
  379. msg, err = c.readHandshake()
  380. if err != nil {
  381. return err
  382. }
  383. }
  384. certMsg, ok := msg.(*certificateMsgTLS13)
  385. if !ok {
  386. c.sendAlert(alertUnexpectedMessage)
  387. return unexpectedMessageError(certMsg, msg)
  388. }
  389. if len(certMsg.certificate.Certificate) == 0 {
  390. c.sendAlert(alertDecodeError)
  391. return errors.New("tls: received empty certificates message")
  392. }
  393. hs.transcript.Write(certMsg.marshal())
  394. c.scts = certMsg.certificate.SignedCertificateTimestamps
  395. c.ocspResponse = certMsg.certificate.OCSPStaple
  396. if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
  397. return err
  398. }
  399. msg, err = c.readHandshake()
  400. if err != nil {
  401. return err
  402. }
  403. certVerify, ok := msg.(*certificateVerifyMsg)
  404. if !ok {
  405. c.sendAlert(alertUnexpectedMessage)
  406. return unexpectedMessageError(certVerify, msg)
  407. }
  408. // See RFC 8446, Section 4.4.3.
  409. if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
  410. c.sendAlert(alertIllegalParameter)
  411. return errors.New("tls: certificate used with invalid signature algorithm")
  412. }
  413. sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
  414. if err != nil {
  415. return c.sendAlert(alertInternalError)
  416. }
  417. if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
  418. c.sendAlert(alertIllegalParameter)
  419. return errors.New("tls: certificate used with invalid signature algorithm")
  420. }
  421. signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
  422. if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
  423. sigHash, signed, certVerify.signature); err != nil {
  424. c.sendAlert(alertDecryptError)
  425. return errors.New("tls: invalid signature by the server certificate: " + err.Error())
  426. }
  427. hs.transcript.Write(certVerify.marshal())
  428. return nil
  429. }
  430. func (hs *clientHandshakeStateTLS13) readServerFinished() error {
  431. c := hs.c
  432. msg, err := c.readHandshake()
  433. if err != nil {
  434. return err
  435. }
  436. finished, ok := msg.(*finishedMsg)
  437. if !ok {
  438. c.sendAlert(alertUnexpectedMessage)
  439. return unexpectedMessageError(finished, msg)
  440. }
  441. expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
  442. if !hmac.Equal(expectedMAC, finished.verifyData) {
  443. c.sendAlert(alertDecryptError)
  444. return errors.New("tls: invalid server finished hash")
  445. }
  446. hs.transcript.Write(finished.marshal())
  447. // Derive secrets that take context through the server Finished.
  448. hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
  449. clientApplicationTrafficLabel, hs.transcript)
  450. serverSecret := hs.suite.deriveSecret(hs.masterSecret,
  451. serverApplicationTrafficLabel, hs.transcript)
  452. c.in.setTrafficSecret(hs.suite, serverSecret)
  453. err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
  454. if err != nil {
  455. c.sendAlert(alertInternalError)
  456. return err
  457. }
  458. err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
  459. if err != nil {
  460. c.sendAlert(alertInternalError)
  461. return err
  462. }
  463. c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
  464. return nil
  465. }
  466. func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
  467. c := hs.c
  468. if hs.certReq == nil {
  469. return nil
  470. }
  471. cert, err := c.getClientCertificate(&CertificateRequestInfo{
  472. AcceptableCAs: hs.certReq.certificateAuthorities,
  473. SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
  474. Version: c.vers,
  475. ctx: hs.ctx,
  476. })
  477. if err != nil {
  478. return err
  479. }
  480. certMsg := new(certificateMsgTLS13)
  481. certMsg.certificate = *cert
  482. certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
  483. certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
  484. hs.transcript.Write(certMsg.marshal())
  485. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  486. return err
  487. }
  488. // If we sent an empty certificate message, skip the CertificateVerify.
  489. if len(cert.Certificate) == 0 {
  490. return nil
  491. }
  492. certVerifyMsg := new(certificateVerifyMsg)
  493. certVerifyMsg.hasSignatureAlgorithm = true
  494. certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
  495. if err != nil {
  496. // getClientCertificate returned a certificate incompatible with the
  497. // CertificateRequestInfo supported signature algorithms.
  498. c.sendAlert(alertHandshakeFailure)
  499. return err
  500. }
  501. sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
  502. if err != nil {
  503. return c.sendAlert(alertInternalError)
  504. }
  505. signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
  506. signOpts := crypto.SignerOpts(sigHash)
  507. if sigType == signatureRSAPSS {
  508. signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
  509. }
  510. sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
  511. if err != nil {
  512. c.sendAlert(alertInternalError)
  513. return errors.New("tls: failed to sign handshake: " + err.Error())
  514. }
  515. certVerifyMsg.signature = sig
  516. hs.transcript.Write(certVerifyMsg.marshal())
  517. if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
  518. return err
  519. }
  520. return nil
  521. }
  522. func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
  523. c := hs.c
  524. finished := &finishedMsg{
  525. verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
  526. }
  527. hs.transcript.Write(finished.marshal())
  528. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  529. return err
  530. }
  531. c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
  532. if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
  533. c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
  534. resumptionLabel, hs.transcript)
  535. }
  536. return nil
  537. }
  538. func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
  539. if !c.isClient {
  540. c.sendAlert(alertUnexpectedMessage)
  541. return errors.New("tls: received new session ticket from a client")
  542. }
  543. if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
  544. return nil
  545. }
  546. // See RFC 8446, Section 4.6.1.
  547. if msg.lifetime == 0 {
  548. return nil
  549. }
  550. lifetime := time.Duration(msg.lifetime) * time.Second
  551. if lifetime > maxSessionTicketLifetime {
  552. c.sendAlert(alertIllegalParameter)
  553. return errors.New("tls: received a session ticket with invalid lifetime")
  554. }
  555. cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
  556. if cipherSuite == nil || c.resumptionSecret == nil {
  557. return c.sendAlert(alertInternalError)
  558. }
  559. // Save the resumption_master_secret and nonce instead of deriving the PSK
  560. // to do the least amount of work on NewSessionTicket messages before we
  561. // know if the ticket will be used. Forward secrecy of resumed connections
  562. // is guaranteed by the requirement for pskModeDHE.
  563. session := &ClientSessionState{
  564. sessionTicket: msg.label,
  565. vers: c.vers,
  566. cipherSuite: c.cipherSuite,
  567. masterSecret: c.resumptionSecret,
  568. serverCertificates: c.peerCertificates,
  569. verifiedChains: c.verifiedChains,
  570. receivedAt: c.config.time(),
  571. nonce: msg.nonce,
  572. useBy: c.config.time().Add(lifetime),
  573. ageAdd: msg.ageAdd,
  574. ocspResponse: c.ocspResponse,
  575. scts: c.scts,
  576. }
  577. cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
  578. c.config.ClientSessionCache.Put(cacheKey, session)
  579. return nil
  580. }