handshake_client_tls13.go 20 KB

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