handshake_client_tls13.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. "sync/atomic"
  14. "time"
  15. )
  16. type clientHandshakeStateTLS13 struct {
  17. c *Conn
  18. ctx context.Context
  19. serverHello *serverHelloMsg
  20. hello *clientHelloMsg
  21. ecdheParams ecdheParameters
  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.ecdheParams, 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.ecdheParams == 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. atomic.StoreUint32(&c.handshakeStatus, 1)
  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 hs.ecdheParams.CurveID() == curveID {
  193. c.sendAlert(alertIllegalParameter)
  194. return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
  195. }
  196. if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
  197. c.sendAlert(alertInternalError)
  198. return errors.New("tls: CurvePreferences includes unsupported curve")
  199. }
  200. params, err := generateECDHEParameters(c.config.rand(), curveID)
  201. if err != nil {
  202. c.sendAlert(alertInternalError)
  203. return err
  204. }
  205. hs.ecdheParams = params
  206. hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
  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 hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() {
  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. sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data)
  301. if sharedKey == nil {
  302. c.sendAlert(alertIllegalParameter)
  303. return errors.New("tls: invalid server key share")
  304. }
  305. earlySecret := hs.earlySecret
  306. if !hs.usingPSK {
  307. earlySecret = hs.suite.extract(nil, nil)
  308. }
  309. handshakeSecret := hs.suite.extract(sharedKey,
  310. hs.suite.deriveSecret(earlySecret, "derived", nil))
  311. clientSecret := hs.suite.deriveSecret(handshakeSecret,
  312. clientHandshakeTrafficLabel, hs.transcript)
  313. c.out.setTrafficSecret(hs.suite, clientSecret)
  314. serverSecret := hs.suite.deriveSecret(handshakeSecret,
  315. serverHandshakeTrafficLabel, hs.transcript)
  316. c.in.setTrafficSecret(hs.suite, serverSecret)
  317. err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
  318. if err != nil {
  319. c.sendAlert(alertInternalError)
  320. return err
  321. }
  322. err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
  323. if err != nil {
  324. c.sendAlert(alertInternalError)
  325. return err
  326. }
  327. hs.masterSecret = hs.suite.extract(nil,
  328. hs.suite.deriveSecret(handshakeSecret, "derived", nil))
  329. return nil
  330. }
  331. func (hs *clientHandshakeStateTLS13) readServerParameters() error {
  332. c := hs.c
  333. msg, err := c.readHandshake()
  334. if err != nil {
  335. return err
  336. }
  337. encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
  338. if !ok {
  339. c.sendAlert(alertUnexpectedMessage)
  340. return unexpectedMessageError(encryptedExtensions, msg)
  341. }
  342. hs.transcript.Write(encryptedExtensions.marshal())
  343. if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol); err != nil {
  344. c.sendAlert(alertUnsupportedExtension)
  345. return err
  346. }
  347. c.clientProtocol = encryptedExtensions.alpnProtocol
  348. return nil
  349. }
  350. func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
  351. c := hs.c
  352. // Either a PSK or a certificate is always used, but not both.
  353. // See RFC 8446, Section 4.1.1.
  354. if hs.usingPSK {
  355. // Make sure the connection is still being verified whether or not this
  356. // is a resumption. Resumptions currently don't reverify certificates so
  357. // they don't call verifyServerCertificate. See Issue 31641.
  358. if c.config.VerifyConnection != nil {
  359. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  360. c.sendAlert(alertBadCertificate)
  361. return err
  362. }
  363. }
  364. return nil
  365. }
  366. msg, err := c.readHandshake()
  367. if err != nil {
  368. return err
  369. }
  370. certReq, ok := msg.(*certificateRequestMsgTLS13)
  371. if ok {
  372. hs.transcript.Write(certReq.marshal())
  373. hs.certReq = certReq
  374. msg, err = c.readHandshake()
  375. if err != nil {
  376. return err
  377. }
  378. }
  379. certMsg, ok := msg.(*certificateMsgTLS13)
  380. if !ok {
  381. c.sendAlert(alertUnexpectedMessage)
  382. return unexpectedMessageError(certMsg, msg)
  383. }
  384. if len(certMsg.certificate.Certificate) == 0 {
  385. c.sendAlert(alertDecodeError)
  386. return errors.New("tls: received empty certificates message")
  387. }
  388. hs.transcript.Write(certMsg.marshal())
  389. c.scts = certMsg.certificate.SignedCertificateTimestamps
  390. c.ocspResponse = certMsg.certificate.OCSPStaple
  391. if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
  392. return err
  393. }
  394. msg, err = c.readHandshake()
  395. if err != nil {
  396. return err
  397. }
  398. certVerify, ok := msg.(*certificateVerifyMsg)
  399. if !ok {
  400. c.sendAlert(alertUnexpectedMessage)
  401. return unexpectedMessageError(certVerify, msg)
  402. }
  403. // See RFC 8446, Section 4.4.3.
  404. if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
  405. c.sendAlert(alertIllegalParameter)
  406. return errors.New("tls: certificate used with invalid signature algorithm")
  407. }
  408. sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
  409. if err != nil {
  410. return c.sendAlert(alertInternalError)
  411. }
  412. if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
  413. c.sendAlert(alertIllegalParameter)
  414. return errors.New("tls: certificate used with invalid signature algorithm")
  415. }
  416. signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
  417. if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
  418. sigHash, signed, certVerify.signature); err != nil {
  419. c.sendAlert(alertDecryptError)
  420. return errors.New("tls: invalid signature by the server certificate: " + err.Error())
  421. }
  422. hs.transcript.Write(certVerify.marshal())
  423. return nil
  424. }
  425. func (hs *clientHandshakeStateTLS13) readServerFinished() error {
  426. c := hs.c
  427. msg, err := c.readHandshake()
  428. if err != nil {
  429. return err
  430. }
  431. finished, ok := msg.(*finishedMsg)
  432. if !ok {
  433. c.sendAlert(alertUnexpectedMessage)
  434. return unexpectedMessageError(finished, msg)
  435. }
  436. expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
  437. if !hmac.Equal(expectedMAC, finished.verifyData) {
  438. c.sendAlert(alertDecryptError)
  439. return errors.New("tls: invalid server finished hash")
  440. }
  441. hs.transcript.Write(finished.marshal())
  442. // Derive secrets that take context through the server Finished.
  443. hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
  444. clientApplicationTrafficLabel, hs.transcript)
  445. serverSecret := hs.suite.deriveSecret(hs.masterSecret,
  446. serverApplicationTrafficLabel, hs.transcript)
  447. c.in.setTrafficSecret(hs.suite, serverSecret)
  448. err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
  449. if err != nil {
  450. c.sendAlert(alertInternalError)
  451. return err
  452. }
  453. err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
  454. if err != nil {
  455. c.sendAlert(alertInternalError)
  456. return err
  457. }
  458. c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
  459. return nil
  460. }
  461. func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
  462. c := hs.c
  463. if hs.certReq == nil {
  464. return nil
  465. }
  466. cert, err := c.getClientCertificate(&CertificateRequestInfo{
  467. AcceptableCAs: hs.certReq.certificateAuthorities,
  468. SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
  469. Version: c.vers,
  470. ctx: hs.ctx,
  471. })
  472. if err != nil {
  473. return err
  474. }
  475. certMsg := new(certificateMsgTLS13)
  476. certMsg.certificate = *cert
  477. certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
  478. certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
  479. hs.transcript.Write(certMsg.marshal())
  480. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  481. return err
  482. }
  483. // If we sent an empty certificate message, skip the CertificateVerify.
  484. if len(cert.Certificate) == 0 {
  485. return nil
  486. }
  487. certVerifyMsg := new(certificateVerifyMsg)
  488. certVerifyMsg.hasSignatureAlgorithm = true
  489. certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
  490. if err != nil {
  491. // getClientCertificate returned a certificate incompatible with the
  492. // CertificateRequestInfo supported signature algorithms.
  493. c.sendAlert(alertHandshakeFailure)
  494. return err
  495. }
  496. sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
  497. if err != nil {
  498. return c.sendAlert(alertInternalError)
  499. }
  500. signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
  501. signOpts := crypto.SignerOpts(sigHash)
  502. if sigType == signatureRSAPSS {
  503. signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
  504. }
  505. sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
  506. if err != nil {
  507. c.sendAlert(alertInternalError)
  508. return errors.New("tls: failed to sign handshake: " + err.Error())
  509. }
  510. certVerifyMsg.signature = sig
  511. hs.transcript.Write(certVerifyMsg.marshal())
  512. if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
  513. return err
  514. }
  515. return nil
  516. }
  517. func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
  518. c := hs.c
  519. finished := &finishedMsg{
  520. verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
  521. }
  522. hs.transcript.Write(finished.marshal())
  523. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  524. return err
  525. }
  526. c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
  527. if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
  528. c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
  529. resumptionLabel, hs.transcript)
  530. }
  531. return nil
  532. }
  533. func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
  534. if !c.isClient {
  535. c.sendAlert(alertUnexpectedMessage)
  536. return errors.New("tls: received new session ticket from a client")
  537. }
  538. if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
  539. return nil
  540. }
  541. // See RFC 8446, Section 4.6.1.
  542. if msg.lifetime == 0 {
  543. return nil
  544. }
  545. lifetime := time.Duration(msg.lifetime) * time.Second
  546. if lifetime > maxSessionTicketLifetime {
  547. c.sendAlert(alertIllegalParameter)
  548. return errors.New("tls: received a session ticket with invalid lifetime")
  549. }
  550. cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
  551. if cipherSuite == nil || c.resumptionSecret == nil {
  552. return c.sendAlert(alertInternalError)
  553. }
  554. // Save the resumption_master_secret and nonce instead of deriving the PSK
  555. // to do the least amount of work on NewSessionTicket messages before we
  556. // know if the ticket will be used. Forward secrecy of resumed connections
  557. // is guaranteed by the requirement for pskModeDHE.
  558. session := &ClientSessionState{
  559. sessionTicket: msg.label,
  560. vers: c.vers,
  561. cipherSuite: c.cipherSuite,
  562. masterSecret: c.resumptionSecret,
  563. serverCertificates: c.peerCertificates,
  564. verifiedChains: c.verifiedChains,
  565. receivedAt: c.config.time(),
  566. nonce: msg.nonce,
  567. useBy: c.config.time().Add(lifetime),
  568. ageAdd: msg.ageAdd,
  569. ocspResponse: c.ocspResponse,
  570. scts: c.scts,
  571. }
  572. cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
  573. c.config.ClientSessionCache.Put(cacheKey, session)
  574. return nil
  575. }