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