github.com/ooni/psiphon/tunnel-core@v0.0.0-20230105123940-fe12a24c96ee/oovendor/qtls-go1-15/handshake_client_tls13.go (about) 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 5 package qtls 6 7 import ( 8 "bytes" 9 "crypto" 10 "crypto/hmac" 11 "crypto/rsa" 12 "encoding/binary" 13 "errors" 14 "fmt" 15 "hash" 16 "sync/atomic" 17 "time" 18 19 "golang.org/x/crypto/cryptobyte" 20 ) 21 22 type clientHandshakeStateTLS13 struct { 23 c *Conn 24 serverHello *serverHelloMsg 25 hello *clientHelloMsg 26 ecdheParams ecdheParameters 27 28 session *clientSessionState 29 earlySecret []byte 30 binderKey []byte 31 32 certReq *certificateRequestMsgTLS13 33 usingPSK bool 34 sentDummyCCS bool 35 suite *cipherSuiteTLS13 36 transcript hash.Hash 37 masterSecret []byte 38 trafficSecret []byte // client_application_traffic_secret_0 39 } 40 41 // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and, 42 // optionally, hs.session, hs.earlySecret and hs.binderKey to be set. 43 func (hs *clientHandshakeStateTLS13) handshake() error { 44 c := hs.c 45 46 // The server must not select TLS 1.3 in a renegotiation. See RFC 8446, 47 // sections 4.1.2 and 4.1.3. 48 if c.handshakes > 0 { 49 c.sendAlert(alertProtocolVersion) 50 return errors.New("tls: server selected TLS 1.3 in a renegotiation") 51 } 52 53 // Consistency check on the presence of a keyShare and its parameters. 54 if hs.ecdheParams == nil || len(hs.hello.keyShares) != 1 { 55 return c.sendAlert(alertInternalError) 56 } 57 58 if err := hs.checkServerHelloOrHRR(); err != nil { 59 return err 60 } 61 62 hs.transcript = hs.suite.hash.New() 63 hs.transcript.Write(hs.hello.marshal()) 64 65 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 66 if err := hs.sendDummyChangeCipherSpec(); err != nil { 67 return err 68 } 69 if err := hs.processHelloRetryRequest(); err != nil { 70 return err 71 } 72 } 73 74 hs.transcript.Write(hs.serverHello.marshal()) 75 76 c.buffering = true 77 if err := hs.processServerHello(); err != nil { 78 return err 79 } 80 if err := hs.sendDummyChangeCipherSpec(); err != nil { 81 return err 82 } 83 if err := hs.establishHandshakeKeys(); err != nil { 84 return err 85 } 86 if err := hs.readServerParameters(); err != nil { 87 return err 88 } 89 if err := hs.readServerCertificate(); err != nil { 90 return err 91 } 92 if err := hs.readServerFinished(); err != nil { 93 return err 94 } 95 if err := hs.sendClientCertificate(); err != nil { 96 return err 97 } 98 if err := hs.sendClientFinished(); err != nil { 99 return err 100 } 101 if _, err := c.flush(); err != nil { 102 return err 103 } 104 105 atomic.StoreUint32(&c.handshakeStatus, 1) 106 107 return nil 108 } 109 110 // checkServerHelloOrHRR does validity checks that apply to both ServerHello and 111 // HelloRetryRequest messages. It sets hs.suite. 112 func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error { 113 c := hs.c 114 115 if hs.serverHello.supportedVersion == 0 { 116 c.sendAlert(alertMissingExtension) 117 return errors.New("tls: server selected TLS 1.3 using the legacy version field") 118 } 119 120 if hs.serverHello.supportedVersion != VersionTLS13 { 121 c.sendAlert(alertIllegalParameter) 122 return errors.New("tls: server selected an invalid version after a HelloRetryRequest") 123 } 124 125 if hs.serverHello.vers != VersionTLS12 { 126 c.sendAlert(alertIllegalParameter) 127 return errors.New("tls: server sent an incorrect legacy version") 128 } 129 130 if hs.serverHello.ocspStapling || 131 hs.serverHello.ticketSupported || 132 hs.serverHello.secureRenegotiationSupported || 133 len(hs.serverHello.secureRenegotiation) != 0 || 134 len(hs.serverHello.alpnProtocol) != 0 || 135 len(hs.serverHello.scts) != 0 { 136 c.sendAlert(alertUnsupportedExtension) 137 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3") 138 } 139 140 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { 141 c.sendAlert(alertIllegalParameter) 142 return errors.New("tls: server did not echo the legacy session ID") 143 } 144 145 if hs.serverHello.compressionMethod != compressionNone { 146 c.sendAlert(alertIllegalParameter) 147 return errors.New("tls: server selected unsupported compression format") 148 } 149 150 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite) 151 if hs.suite != nil && selectedSuite != hs.suite { 152 c.sendAlert(alertIllegalParameter) 153 return errors.New("tls: server changed cipher suite after a HelloRetryRequest") 154 } 155 if selectedSuite == nil { 156 c.sendAlert(alertIllegalParameter) 157 return errors.New("tls: server chose an unconfigured cipher suite") 158 } 159 hs.suite = selectedSuite 160 c.cipherSuite = hs.suite.id 161 162 return nil 163 } 164 165 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 166 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 167 func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 168 if hs.sentDummyCCS { 169 return nil 170 } 171 hs.sentDummyCCS = true 172 173 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 174 return err 175 } 176 177 // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and 178 // resends hs.hello, and reads the new ServerHello into hs.serverHello. 179 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { 180 c := hs.c 181 182 // The first ClientHello gets double-hashed into the transcript upon a 183 // HelloRetryRequest. (The idea is that the server might offload transcript 184 // storage to the client in the cookie.) See RFC 8446, Section 4.4.1. 185 chHash := hs.transcript.Sum(nil) 186 hs.transcript.Reset() 187 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 188 hs.transcript.Write(chHash) 189 hs.transcript.Write(hs.serverHello.marshal()) 190 191 // The only HelloRetryRequest extensions we support are key_share and 192 // cookie, and clients must abort the handshake if the HRR would not result 193 // in any change in the ClientHello. 194 if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil { 195 c.sendAlert(alertIllegalParameter) 196 return errors.New("tls: server sent an unnecessary HelloRetryRequest message") 197 } 198 199 if hs.serverHello.cookie != nil { 200 hs.hello.cookie = hs.serverHello.cookie 201 } 202 203 if hs.serverHello.serverShare.group != 0 { 204 c.sendAlert(alertDecodeError) 205 return errors.New("tls: received malformed key_share extension") 206 } 207 208 // If the server sent a key_share extension selecting a group, ensure it's 209 // a group we advertised but did not send a key share for, and send a key 210 // share for it this time. 211 if curveID := hs.serverHello.selectedGroup; curveID != 0 { 212 curveOK := false 213 for _, id := range hs.hello.supportedCurves { 214 if id == curveID { 215 curveOK = true 216 break 217 } 218 } 219 if !curveOK { 220 c.sendAlert(alertIllegalParameter) 221 return errors.New("tls: server selected unsupported group") 222 } 223 if hs.ecdheParams.CurveID() == curveID { 224 c.sendAlert(alertIllegalParameter) 225 return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share") 226 } 227 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { 228 c.sendAlert(alertInternalError) 229 return errors.New("tls: CurvePreferences includes unsupported curve") 230 } 231 params, err := generateECDHEParameters(c.config.rand(), curveID) 232 if err != nil { 233 c.sendAlert(alertInternalError) 234 return err 235 } 236 hs.ecdheParams = params 237 hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}} 238 } 239 240 hs.hello.raw = nil 241 if len(hs.hello.pskIdentities) > 0 { 242 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 243 if pskSuite == nil { 244 return c.sendAlert(alertInternalError) 245 } 246 if pskSuite.hash == hs.suite.hash { 247 // Update binders and obfuscated_ticket_age. 248 ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond) 249 hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd 250 251 transcript := hs.suite.hash.New() 252 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 253 transcript.Write(chHash) 254 transcript.Write(hs.serverHello.marshal()) 255 transcript.Write(hs.hello.marshalWithoutBinders()) 256 pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)} 257 hs.hello.updateBinders(pskBinders) 258 } else { 259 // Server selected a cipher suite incompatible with the PSK. 260 hs.hello.pskIdentities = nil 261 hs.hello.pskBinders = nil 262 } 263 } 264 265 if hs.hello.earlyData && c.extraConfig != nil && c.extraConfig.Rejected0RTT != nil { 266 c.extraConfig.Rejected0RTT() 267 } 268 hs.hello.earlyData = false // disable 0-RTT 269 270 hs.transcript.Write(hs.hello.marshal()) 271 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 272 return err 273 } 274 275 msg, err := c.readHandshake() 276 if err != nil { 277 return err 278 } 279 280 serverHello, ok := msg.(*serverHelloMsg) 281 if !ok { 282 c.sendAlert(alertUnexpectedMessage) 283 return unexpectedMessageError(serverHello, msg) 284 } 285 hs.serverHello = serverHello 286 287 if err := hs.checkServerHelloOrHRR(); err != nil { 288 return err 289 } 290 291 return nil 292 } 293 294 func (hs *clientHandshakeStateTLS13) processServerHello() error { 295 c := hs.c 296 297 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 298 c.sendAlert(alertUnexpectedMessage) 299 return errors.New("tls: server sent two HelloRetryRequest messages") 300 } 301 302 if len(hs.serverHello.cookie) != 0 { 303 c.sendAlert(alertUnsupportedExtension) 304 return errors.New("tls: server sent a cookie in a normal ServerHello") 305 } 306 307 if hs.serverHello.selectedGroup != 0 { 308 c.sendAlert(alertDecodeError) 309 return errors.New("tls: malformed key_share extension") 310 } 311 312 if hs.serverHello.serverShare.group == 0 { 313 c.sendAlert(alertIllegalParameter) 314 return errors.New("tls: server did not send a key share") 315 } 316 if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() { 317 c.sendAlert(alertIllegalParameter) 318 return errors.New("tls: server selected unsupported group") 319 } 320 321 if !hs.serverHello.selectedIdentityPresent { 322 return nil 323 } 324 325 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) { 326 c.sendAlert(alertIllegalParameter) 327 return errors.New("tls: server selected an invalid PSK") 328 } 329 330 if len(hs.hello.pskIdentities) != 1 || hs.session == nil { 331 return c.sendAlert(alertInternalError) 332 } 333 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 334 if pskSuite == nil { 335 return c.sendAlert(alertInternalError) 336 } 337 if pskSuite.hash != hs.suite.hash { 338 c.sendAlert(alertIllegalParameter) 339 return errors.New("tls: server selected an invalid PSK and cipher suite pair") 340 } 341 342 hs.usingPSK = true 343 c.didResume = true 344 c.peerCertificates = hs.session.serverCertificates 345 c.verifiedChains = hs.session.verifiedChains 346 c.ocspResponse = hs.session.ocspResponse 347 c.scts = hs.session.scts 348 return nil 349 } 350 351 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error { 352 c := hs.c 353 354 sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data) 355 if sharedKey == nil { 356 c.sendAlert(alertIllegalParameter) 357 return errors.New("tls: invalid server key share") 358 } 359 360 earlySecret := hs.earlySecret 361 if !hs.usingPSK { 362 earlySecret = hs.suite.extract(nil, nil) 363 } 364 handshakeSecret := hs.suite.extract(sharedKey, 365 hs.suite.deriveSecret(earlySecret, "derived", nil)) 366 367 clientSecret := hs.suite.deriveSecret(handshakeSecret, 368 clientHandshakeTrafficLabel, hs.transcript) 369 c.out.exportKey(EncryptionHandshake, hs.suite, clientSecret) 370 c.out.setTrafficSecret(hs.suite, clientSecret) 371 serverSecret := hs.suite.deriveSecret(handshakeSecret, 372 serverHandshakeTrafficLabel, hs.transcript) 373 c.in.exportKey(EncryptionHandshake, hs.suite, serverSecret) 374 c.in.setTrafficSecret(hs.suite, serverSecret) 375 376 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret) 377 if err != nil { 378 c.sendAlert(alertInternalError) 379 return err 380 } 381 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret) 382 if err != nil { 383 c.sendAlert(alertInternalError) 384 return err 385 } 386 387 hs.masterSecret = hs.suite.extract(nil, 388 hs.suite.deriveSecret(handshakeSecret, "derived", nil)) 389 390 return nil 391 } 392 393 func (hs *clientHandshakeStateTLS13) readServerParameters() error { 394 c := hs.c 395 396 msg, err := c.readHandshake() 397 if err != nil { 398 return err 399 } 400 401 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) 402 if !ok { 403 c.sendAlert(alertUnexpectedMessage) 404 return unexpectedMessageError(encryptedExtensions, msg) 405 } 406 if hs.c.extraConfig != nil && hs.c.extraConfig.ReceivedExtensions != nil { 407 hs.c.extraConfig.ReceivedExtensions(typeEncryptedExtensions, encryptedExtensions.additionalExtensions) 408 } 409 hs.transcript.Write(encryptedExtensions.marshal()) 410 411 if len(encryptedExtensions.alpnProtocol) != 0 && len(hs.hello.alpnProtocols) == 0 { 412 c.sendAlert(alertUnsupportedExtension) 413 return errors.New("tls: server advertised unrequested ALPN extension") 414 } 415 if c.extraConfig != nil && c.extraConfig.EnforceNextProtoSelection { 416 if len(encryptedExtensions.alpnProtocol) == 0 { 417 // the server didn't select an ALPN 418 c.sendAlert(alertNoApplicationProtocol) 419 return errors.New("ALPN negotiation failed. Server didn't offer any protocols") 420 } 421 if _, fallback := mutualProtocol([]string{encryptedExtensions.alpnProtocol}, hs.c.config.NextProtos); fallback { 422 // the protocol selected by the server was not offered 423 c.sendAlert(alertNoApplicationProtocol) 424 return fmt.Errorf("ALPN negotiation failed. Server offered: %q", encryptedExtensions.alpnProtocol) 425 } 426 } 427 c.clientProtocol = encryptedExtensions.alpnProtocol 428 // Notify the caller if 0-RTT was rejected. 429 if !encryptedExtensions.earlyData && hs.hello.earlyData && c.extraConfig != nil && c.extraConfig.Rejected0RTT != nil { 430 c.extraConfig.Rejected0RTT() 431 } 432 c.used0RTT = encryptedExtensions.earlyData 433 434 return nil 435 } 436 437 func (hs *clientHandshakeStateTLS13) readServerCertificate() error { 438 c := hs.c 439 440 // Either a PSK or a certificate is always used, but not both. 441 // See RFC 8446, Section 4.1.1. 442 if hs.usingPSK { 443 // Make sure the connection is still being verified whether or not this 444 // is a resumption. Resumptions currently don't reverify certificates so 445 // they don't call verifyServerCertificate. See Issue 31641. 446 if c.config.VerifyConnection != nil { 447 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 448 c.sendAlert(alertBadCertificate) 449 return err 450 } 451 } 452 return nil 453 } 454 455 msg, err := c.readHandshake() 456 if err != nil { 457 return err 458 } 459 460 certReq, ok := msg.(*certificateRequestMsgTLS13) 461 if ok { 462 hs.transcript.Write(certReq.marshal()) 463 464 hs.certReq = certReq 465 466 msg, err = c.readHandshake() 467 if err != nil { 468 return err 469 } 470 } 471 472 certMsg, ok := msg.(*certificateMsgTLS13) 473 if !ok { 474 c.sendAlert(alertUnexpectedMessage) 475 return unexpectedMessageError(certMsg, msg) 476 } 477 if len(certMsg.certificate.Certificate) == 0 { 478 c.sendAlert(alertDecodeError) 479 return errors.New("tls: received empty certificates message") 480 } 481 hs.transcript.Write(certMsg.marshal()) 482 483 c.scts = certMsg.certificate.SignedCertificateTimestamps 484 c.ocspResponse = certMsg.certificate.OCSPStaple 485 486 if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil { 487 return err 488 } 489 490 msg, err = c.readHandshake() 491 if err != nil { 492 return err 493 } 494 495 certVerify, ok := msg.(*certificateVerifyMsg) 496 if !ok { 497 c.sendAlert(alertUnexpectedMessage) 498 return unexpectedMessageError(certVerify, msg) 499 } 500 501 // See RFC 8446, Section 4.4.3. 502 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) { 503 c.sendAlert(alertIllegalParameter) 504 return errors.New("tls: certificate used with invalid signature algorithm") 505 } 506 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 507 if err != nil { 508 return c.sendAlert(alertInternalError) 509 } 510 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 511 c.sendAlert(alertIllegalParameter) 512 return errors.New("tls: certificate used with invalid signature algorithm") 513 } 514 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 515 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 516 sigHash, signed, certVerify.signature); err != nil { 517 c.sendAlert(alertDecryptError) 518 return errors.New("tls: invalid signature by the server certificate: " + err.Error()) 519 } 520 521 hs.transcript.Write(certVerify.marshal()) 522 523 return nil 524 } 525 526 func (hs *clientHandshakeStateTLS13) readServerFinished() error { 527 c := hs.c 528 529 msg, err := c.readHandshake() 530 if err != nil { 531 return err 532 } 533 534 finished, ok := msg.(*finishedMsg) 535 if !ok { 536 c.sendAlert(alertUnexpectedMessage) 537 return unexpectedMessageError(finished, msg) 538 } 539 540 expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 541 if !hmac.Equal(expectedMAC, finished.verifyData) { 542 c.sendAlert(alertDecryptError) 543 return errors.New("tls: invalid server finished hash") 544 } 545 546 hs.transcript.Write(finished.marshal()) 547 548 // Derive secrets that take context through the server Finished. 549 550 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 551 clientApplicationTrafficLabel, hs.transcript) 552 serverSecret := hs.suite.deriveSecret(hs.masterSecret, 553 serverApplicationTrafficLabel, hs.transcript) 554 c.in.exportKey(EncryptionApplication, hs.suite, serverSecret) 555 c.in.setTrafficSecret(hs.suite, serverSecret) 556 557 err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret) 558 if err != nil { 559 c.sendAlert(alertInternalError) 560 return err 561 } 562 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret) 563 if err != nil { 564 c.sendAlert(alertInternalError) 565 return err 566 } 567 568 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 569 570 return nil 571 } 572 573 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error { 574 c := hs.c 575 576 if hs.certReq == nil { 577 return nil 578 } 579 580 cert, err := c.getClientCertificate(&CertificateRequestInfo{ 581 AcceptableCAs: hs.certReq.certificateAuthorities, 582 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms, 583 Version: c.vers, 584 }) 585 if err != nil { 586 return err 587 } 588 589 certMsg := new(certificateMsgTLS13) 590 591 certMsg.certificate = *cert 592 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0 593 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0 594 595 hs.transcript.Write(certMsg.marshal()) 596 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 597 return err 598 } 599 600 // If we sent an empty certificate message, skip the CertificateVerify. 601 if len(cert.Certificate) == 0 { 602 return nil 603 } 604 605 certVerifyMsg := new(certificateVerifyMsg) 606 certVerifyMsg.hasSignatureAlgorithm = true 607 608 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms) 609 if err != nil { 610 // getClientCertificate returned a certificate incompatible with the 611 // CertificateRequestInfo supported signature algorithms. 612 c.sendAlert(alertHandshakeFailure) 613 return err 614 } 615 616 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm) 617 if err != nil { 618 return c.sendAlert(alertInternalError) 619 } 620 621 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 622 signOpts := crypto.SignerOpts(sigHash) 623 if sigType == signatureRSAPSS { 624 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 625 } 626 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 627 if err != nil { 628 c.sendAlert(alertInternalError) 629 return errors.New("tls: failed to sign handshake: " + err.Error()) 630 } 631 certVerifyMsg.signature = sig 632 633 hs.transcript.Write(certVerifyMsg.marshal()) 634 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil { 635 return err 636 } 637 638 return nil 639 } 640 641 func (hs *clientHandshakeStateTLS13) sendClientFinished() error { 642 c := hs.c 643 644 finished := &finishedMsg{ 645 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 646 } 647 648 hs.transcript.Write(finished.marshal()) 649 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { 650 return err 651 } 652 653 c.out.exportKey(EncryptionApplication, hs.suite, hs.trafficSecret) 654 c.out.setTrafficSecret(hs.suite, hs.trafficSecret) 655 656 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil { 657 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, 658 resumptionLabel, hs.transcript) 659 } 660 661 return nil 662 } 663 664 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error { 665 if !c.isClient { 666 c.sendAlert(alertUnexpectedMessage) 667 return errors.New("tls: received new session ticket from a client") 668 } 669 670 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { 671 return nil 672 } 673 674 // See RFC 8446, Section 4.6.1. 675 if msg.lifetime == 0 { 676 return nil 677 } 678 lifetime := time.Duration(msg.lifetime) * time.Second 679 if lifetime > maxSessionTicketLifetime { 680 c.sendAlert(alertIllegalParameter) 681 return errors.New("tls: received a session ticket with invalid lifetime") 682 } 683 684 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) 685 if cipherSuite == nil || c.resumptionSecret == nil { 686 return c.sendAlert(alertInternalError) 687 } 688 689 // We need to save the max_early_data_size that the server sent us, in order 690 // to decide if we're going to try 0-RTT with this ticket. 691 // However, at the same time, the qtls.ClientSessionTicket needs to be equal to 692 // the tls.ClientSessionTicket, so we can't just add a new field to the struct. 693 // We therefore abuse the nonce field (which is a byte slice) 694 nonceWithEarlyData := make([]byte, len(msg.nonce)+4) 695 binary.BigEndian.PutUint32(nonceWithEarlyData, msg.maxEarlyData) 696 copy(nonceWithEarlyData[4:], msg.nonce) 697 698 var appData []byte 699 if c.extraConfig != nil && c.extraConfig.GetAppDataForSessionState != nil { 700 appData = c.extraConfig.GetAppDataForSessionState() 701 } 702 var b cryptobyte.Builder 703 b.AddUint16(clientSessionStateVersion) // revision 704 b.AddUint32(msg.maxEarlyData) 705 b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { 706 b.AddBytes(appData) 707 }) 708 b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { 709 b.AddBytes(msg.nonce) 710 }) 711 712 // Save the resumption_master_secret and nonce instead of deriving the PSK 713 // to do the least amount of work on NewSessionTicket messages before we 714 // know if the ticket will be used. Forward secrecy of resumed connections 715 // is guaranteed by the requirement for pskModeDHE. 716 session := &clientSessionState{ 717 sessionTicket: msg.label, 718 vers: c.vers, 719 cipherSuite: c.cipherSuite, 720 masterSecret: c.resumptionSecret, 721 serverCertificates: c.peerCertificates, 722 verifiedChains: c.verifiedChains, 723 receivedAt: c.config.time(), 724 nonce: b.BytesOrPanic(), 725 useBy: c.config.time().Add(lifetime), 726 ageAdd: msg.ageAdd, 727 ocspResponse: c.ocspResponse, 728 scts: c.scts, 729 } 730 731 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config) 732 c.config.ClientSessionCache.Put(cacheKey, toClientSessionState(session)) 733 734 return nil 735 }