gitlab.com/go-extension/tls@v0.0.0-20240304171319-e6745021905e/handshake_server_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 tls 6 7 import ( 8 "bytes" 9 "context" 10 "crypto" 11 "crypto/hmac" 12 "crypto/rsa" 13 "encoding/binary" 14 "errors" 15 "fmt" 16 "hash" 17 "io" 18 "sync" 19 "time" 20 ) 21 22 // maxClientPSKIdentities is the number of client PSK identities the server will 23 // attempt to validate. It will ignore the rest not to let cheap ClientHello 24 // messages cause too much work in session ticket decryption attempts. 25 const maxClientPSKIdentities = 5 26 27 type serverHandshakeStateTLS13 struct { 28 c *Conn 29 ctx context.Context 30 clientHello *clientHelloMsg 31 hello *serverHelloMsg 32 sentDummyCCS bool 33 usingPSK bool 34 usingALPS bool 35 earlyData bool 36 suite *cipherSuiteTLS13 37 certCompressionAlgorithm CertCompressionAlgorithm 38 cert *Certificate 39 sigAlg SignatureScheme 40 clientHandshakeSecret []byte 41 earlySecret []byte 42 sharedKey []byte 43 handshakeSecret []byte 44 masterSecret []byte 45 trafficSecret []byte // client_application_traffic_secret_0 46 transcript hash.Hash 47 clientFinished []byte 48 extensions []Extension 49 } 50 51 func (hs *serverHandshakeStateTLS13) echIsInner() bool { 52 return len(hs.clientHello.ech) == 1 && hs.clientHello.ech[0] == echClientHelloInnerVariant 53 } 54 55 func (hs *serverHandshakeStateTLS13) handshake() error { 56 c := hs.c 57 // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2. 58 if err := hs.processClientHello(); err != nil { 59 return err 60 } 61 if err := hs.checkForResumption(); err != nil { 62 return err 63 } 64 65 if hs.earlyData && c.quic == nil { 66 go hs.doEarlyHandshake() 67 } else { 68 if err := hs.doFullHandshake(); err != nil { 69 return err 70 } 71 } 72 73 return nil 74 } 75 76 func (hs *serverHandshakeStateTLS13) processClientHello() error { 77 c := hs.c 78 79 hs.hello = new(serverHelloMsg) 80 81 // TLS 1.3 froze the ServerHello.legacy_version field, and uses 82 // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1. 83 hs.hello.vers = VersionTLS12 84 hs.hello.supportedVersion = c.vers 85 hs.hello.extensions = hs.extensions 86 87 if len(hs.clientHello.supportedVersions) == 0 { 88 c.sendAlert(alertIllegalParameter) 89 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3") 90 } 91 92 // Abort if the client is doing a fallback and landing lower than what we 93 // support. See RFC 7507, which however does not specify the interaction 94 // with supported_versions. The only difference is that with 95 // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4] 96 // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case, 97 // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to 98 // TLS 1.2, because a TLS 1.3 server would abort here. The situation before 99 // supported_versions was not better because there was just no way to do a 100 // TLS 1.4 handshake without risking the server selecting TLS 1.3. 101 for _, id := range hs.clientHello.cipherSuites { 102 if id == TLS_FALLBACK_SCSV { 103 // Use c.vers instead of max(supported_versions) because an attacker 104 // could defeat this by adding an arbitrary high version otherwise. 105 if c.vers < c.config.maxSupportedVersion(roleServer) { 106 c.sendAlert(alertInappropriateFallback) 107 return errors.New("tls: client using inappropriate protocol fallback") 108 } 109 break 110 } 111 } 112 113 if len(hs.clientHello.compressionMethods) != 1 || 114 hs.clientHello.compressionMethods[0] != compressionNone { 115 c.sendAlert(alertIllegalParameter) 116 return errors.New("tls: TLS 1.3 client supports illegal compression methods") 117 } 118 119 hs.hello.random = make([]byte, 32) 120 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil { 121 c.sendAlert(alertInternalError) 122 return err 123 } 124 125 if len(hs.clientHello.secureRenegotiation) != 0 { 126 c.sendAlert(alertHandshakeFailure) 127 return errors.New("tls: initial handshake had non-empty renegotiation extension") 128 } 129 130 if hs.clientHello.earlyData && len(hs.clientHello.pskIdentities) == 0 { 131 c.sendAlert(alertIllegalParameter) 132 return errors.New("tls: early_data without pre_shared_key") 133 } 134 135 hs.hello.sessionId = hs.clientHello.sessionId 136 hs.hello.compressionMethod = compressionNone 137 138 configCipherSuites := c.config.cipherSuites() 139 preferenceList := make([]uint16, 0, len(configCipherSuites)) 140 141 var preferenceOrder []uint16 142 switch { 143 case c.config.PreferCipherSuites: 144 preferenceOrder = configCipherSuites 145 case !hasAESGCMHardwareSupport, !aesgcmPreferred(hs.clientHello.cipherSuites): 146 preferenceOrder = defaultCipherSuitesTLS13NoAES 147 default: 148 preferenceOrder = defaultCipherSuitesTLS13 149 } 150 151 for _, suiteID := range preferenceOrder { 152 if IsGREASE(suiteID) { 153 continue 154 } 155 156 for _, id := range configCipherSuites { 157 if IsGREASE(id) { 158 continue 159 } 160 161 if id == suiteID { 162 preferenceList = append(preferenceList, id) 163 break 164 } 165 } 166 } 167 168 for _, suiteID := range preferenceList { 169 hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID) 170 if hs.suite != nil { 171 break 172 } 173 } 174 175 if hs.suite == nil { 176 c.sendAlert(alertHandshakeFailure) 177 return errors.New("tls: no cipher suite supported by both client and server") 178 } 179 c.cipherSuite = hs.suite.id 180 hs.hello.cipherSuite = hs.suite.id 181 hs.transcript = hs.suite.hash.New() 182 183 // Pick the ECDHE group in server preference order, but give priority to 184 // groups with a key share, to avoid a HelloRetryRequest round-trip. 185 var selectedGroup CurveID 186 var clientKeyShare *keyShare 187 GroupSelection: 188 for _, preferredGroup := range c.config.curvePreferences() { 189 if IsGREASE(uint16(preferredGroup)) { 190 continue 191 } 192 193 for _, ks := range hs.clientHello.keyShares { 194 if IsGREASE(uint16(ks.group)) { 195 continue 196 } 197 198 if ks.group == preferredGroup { 199 selectedGroup = ks.group 200 clientKeyShare = &ks 201 break GroupSelection 202 } 203 } 204 if selectedGroup != 0 { 205 continue 206 } 207 for _, group := range hs.clientHello.supportedCurves { 208 if group == preferredGroup { 209 selectedGroup = group 210 break 211 } 212 } 213 } 214 if selectedGroup == 0 { 215 c.sendAlert(alertHandshakeFailure) 216 return errors.New("tls: no ECDHE curve supported by both client and server") 217 } 218 if clientKeyShare == nil { 219 if err := hs.doHelloRetryRequest(selectedGroup); err != nil { 220 return err 221 } 222 clientKeyShare = &hs.clientHello.keyShares[0] 223 } 224 225 if _, ok := curveForCurveID(selectedGroup); !ok { 226 c.sendAlert(alertInternalError) 227 return errors.New("tls: CurvePreferences includes unsupported curve") 228 } 229 key, err := generateECDHEKey(c.config.rand(), selectedGroup) 230 if err != nil { 231 c.sendAlert(alertInternalError) 232 return err 233 } 234 hs.hello.serverShare = keyShare{group: selectedGroup, data: key.PublicKey().Bytes()} 235 peerKey, err := key.Curve().NewPublicKey(clientKeyShare.data) 236 if err != nil { 237 c.sendAlert(alertIllegalParameter) 238 return errors.New("tls: invalid client key share") 239 } 240 hs.sharedKey, err = key.ECDH(peerKey) 241 if err != nil { 242 c.sendAlert(alertIllegalParameter) 243 return errors.New("tls: invalid client key share") 244 } 245 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil) 246 if err != nil { 247 c.sendAlert(alertNoApplicationProtocol) 248 return err 249 } 250 c.clientProtocol = selectedProto 251 252 protoSetting, ok := c.config.negotiateALPS(selectedProto, hs.clientHello.alpsProtocols) 253 if ok { 254 hs.usingALPS = true 255 c.serverProtocolSetting = protoSetting 256 } 257 258 if c.quic != nil { 259 // RFC 9001 Section 4.2: Clients MUST NOT offer TLS versions older than 1.3. 260 for _, v := range hs.clientHello.supportedVersions { 261 if v < VersionTLS13 { 262 c.sendAlert(alertProtocolVersion) 263 return errors.New("tls: client offered TLS version older than TLS 1.3") 264 } 265 } 266 // RFC 9001 Section 8.2. 267 if hs.clientHello.quicTransportParameters == nil { 268 c.sendAlert(alertMissingExtension) 269 return errors.New("tls: client did not send a quic_transport_parameters extension") 270 } 271 c.quicSetTransportParameters(hs.clientHello.quicTransportParameters) 272 } else { 273 if hs.clientHello.quicTransportParameters != nil { 274 c.sendAlert(alertUnsupportedExtension) 275 return errors.New("tls: client sent an unexpected quic_transport_parameters extension") 276 } 277 } 278 279 AlgorithmSelection: 280 for _, preferredAlgorithm := range c.config.certCompressionPreferences() { 281 for _, algorithm := range hs.clientHello.supportedCompressionAlgorithmsCert { 282 if algorithm == preferredAlgorithm { 283 hs.certCompressionAlgorithm = algorithm 284 break AlgorithmSelection 285 } 286 } 287 } 288 289 c.serverName = hs.clientHello.serverName 290 return nil 291 } 292 293 func (hs *serverHandshakeStateTLS13) checkForResumption() error { 294 c := hs.c 295 296 if c.config.SessionTicketsDisabled || c.config.ECHEnabled { 297 return nil 298 } 299 300 modeOK := false 301 for _, mode := range hs.clientHello.pskModes { 302 if mode == pskModeDHE { 303 modeOK = true 304 break 305 } 306 } 307 if !modeOK { 308 return nil 309 } 310 311 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) { 312 c.sendAlert(alertIllegalParameter) 313 return errors.New("tls: invalid or missing PSK binders") 314 } 315 if len(hs.clientHello.pskIdentities) == 0 { 316 return nil 317 } 318 319 for i, identity := range hs.clientHello.pskIdentities { 320 if i >= maxClientPSKIdentities { 321 break 322 } 323 324 var sessionState *SessionState 325 if c.config.UnwrapSession != nil { 326 var err error 327 sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked()) 328 if err != nil { 329 return err 330 } 331 if sessionState == nil { 332 continue 333 } 334 } else { 335 plaintext := c.config.decryptTicket(identity.label, c.ticketKeys) 336 if plaintext == nil { 337 continue 338 } 339 var err error 340 sessionState, err = ParseSessionState(plaintext) 341 if err != nil { 342 continue 343 } 344 } 345 346 if sessionState.version != VersionTLS13 { 347 continue 348 } 349 serverAge := c.config.time().Sub(time.Unix(int64(sessionState.createdAt), 0)) 350 if serverAge > maxSessionTicketLifetime { 351 continue 352 } 353 354 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite) 355 if pskSuite == nil || pskSuite.hash != hs.suite.hash { 356 continue 357 } 358 359 // PSK connections don't re-establish client certificates, but carry 360 // them over in the session ticket. Ensure the presence of client certs 361 // in the ticket is consistent with the configured requirements. 362 sessionHasClientCerts := len(sessionState.peerCertificates) != 0 363 needClientCerts := requiresClientCert(c.config.ClientAuth) 364 if needClientCerts && !sessionHasClientCerts { 365 continue 366 } 367 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 368 continue 369 } 370 if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) { 371 continue 372 } 373 if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven && 374 len(sessionState.verifiedChains) == 0 { 375 continue 376 } 377 378 hs.earlySecret = hs.suite.extract(sessionState.secret, nil) 379 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil) 380 // Clone the transcript in case a HelloRetryRequest was recorded. 381 transcript := cloneHash(hs.transcript, hs.suite.hash) 382 if transcript == nil { 383 c.sendAlert(alertInternalError) 384 return errors.New("tls: internal error: failed to clone hash") 385 } 386 clientHelloBytes, err := hs.clientHello.marshalWithoutBinders() 387 if err != nil { 388 c.sendAlert(alertInternalError) 389 return err 390 } 391 transcript.Write(clientHelloBytes) 392 pskBinder := hs.suite.finishedHash(binderKey, transcript) 393 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) { 394 c.sendAlert(alertDecryptError) 395 return errors.New("tls: invalid PSK binder") 396 } 397 398 c.didResume = true 399 c.peerCertificates = sessionState.peerCertificates 400 c.ocspResponse = sessionState.ocspResponse 401 c.scts = sessionState.scts 402 c.verifiedChains = sessionState.verifiedChains 403 404 hs.hello.selectedIdentityPresent = true 405 hs.hello.selectedIdentity = uint16(i) 406 hs.usingPSK = true 407 408 if !hs.clientHello.earlyData { 409 return nil 410 } 411 412 if sessionState.MaxEarlyData == 0 { 413 c.sendAlert(alertUnsupportedExtension) 414 return errors.New("tls: client sent unexpected early data") 415 } 416 417 c.handshakeState.Store(handshake0RTT) 418 419 if !c.config.Allow0RTT { 420 return nil 421 } 422 423 clientAge := time.Duration(identity.obfuscatedTicketAge-sessionState.ageAdd) * time.Millisecond 424 if clientAge-serverAge > maxSessionTicketSkewAllowance || clientAge-serverAge < -maxSessionTicketSkewAllowance { 425 return nil 426 } 427 428 if sessionState.cipherSuite != hs.suite.id || sessionState.alpnProtocol != c.clientProtocol || !bytes.Equal(c.serverProtocolSetting, sessionState.alpnServerSetting) { 429 return nil 430 } 431 432 hs.earlyData = true 433 c.earlyNotify = sync.NewCond(&sync.Mutex{}) 434 c.clientProtocolSetting = sessionState.alpnClientSetting 435 c.maxEarlyData = sessionState.MaxEarlyData 436 437 transcript = hs.suite.hash.New() 438 if err := transcriptMsg(hs.clientHello, transcript); err != nil { 439 return err 440 } 441 earlyTrafficSecret := hs.suite.deriveSecret(hs.earlySecret, clientEarlyTrafficLabel, transcript) 442 if c.quic == nil { 443 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelEarly, earlyTrafficSecret) 444 } else { 445 c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret) 446 } 447 return nil 448 } 449 450 return nil 451 } 452 453 func (hs *serverHandshakeStateTLS13) doFullHandshake() error { 454 c := hs.c 455 456 if err := hs.pickCertificate(); err != nil { 457 return err 458 } 459 c.buffering = true 460 if err := hs.sendServerParameters(); err != nil { 461 return err 462 } 463 if err := hs.sendServerCertificate(); err != nil { 464 return err 465 } 466 if err := hs.sendServerFinished(); err != nil { 467 return err 468 } 469 // Note that at this point we could start sending application data without 470 // waiting for the client's second flight, but the application might not 471 // expect the lack of replay protection of the ClientHello parameters. 472 if _, err := c.flush(); err != nil { 473 return err 474 } 475 if err := hs.readClientParameters(); err != nil { 476 return err 477 } 478 if err := hs.readClientCertificate(); err != nil { 479 return err 480 } 481 if err := hs.readClientFinished(); err != nil { 482 return err 483 } 484 if err := c.setup(); err != nil { 485 return err 486 } 487 488 c.handshakeState.Store(handshakeCompleted) 489 return nil 490 } 491 492 func (hs *serverHandshakeStateTLS13) doEarlyHandshake() { 493 c := hs.c 494 495 err := func() error { 496 c.buffering = true 497 if err := hs.sendServerParameters(); err != nil { 498 return err 499 } 500 if err := hs.sendServerFinished(); err != nil { 501 return err 502 } 503 // Note that at this point we could start sending application data without 504 // waiting for the client's second flight, but the application might not 505 // expect the lack of replay protection of the ClientHello parameters. 506 if _, err := c.flush(); err != nil { 507 return err 508 } 509 if err := hs.readClientEarlyData(); err != nil { 510 return err 511 } 512 if err := hs.readClientFinished(); err != nil { 513 return err 514 } 515 if err := c.setup(); err != nil { 516 return err 517 } 518 519 c.handshakeState.Store(handshakeCompleted) 520 return nil 521 }() 522 523 if err != nil { 524 c.handshakeErr = err 525 } 526 527 c.earlyNotify.L.Lock() 528 c.earlyNotify.Broadcast() 529 c.earlyNotify.L.Unlock() 530 } 531 532 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler 533 // interfaces implemented by standard library hashes to clone the state of in 534 // to a new instance of h. It returns nil if the operation fails. 535 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash { 536 // Recreate the interface to avoid importing encoding. 537 type binaryMarshaler interface { 538 MarshalBinary() (data []byte, err error) 539 UnmarshalBinary(data []byte) error 540 } 541 marshaler, ok := in.(binaryMarshaler) 542 if !ok { 543 return nil 544 } 545 state, err := marshaler.MarshalBinary() 546 if err != nil { 547 return nil 548 } 549 out := h.New() 550 unmarshaler, ok := out.(binaryMarshaler) 551 if !ok { 552 return nil 553 } 554 if err := unmarshaler.UnmarshalBinary(state); err != nil { 555 return nil 556 } 557 return out 558 } 559 560 func (hs *serverHandshakeStateTLS13) pickCertificate() error { 561 c := hs.c 562 563 // Only one of PSK and certificates are used at a time. 564 if hs.usingPSK { 565 return nil 566 } 567 568 // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3. 569 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 { 570 return c.sendAlert(alertMissingExtension) 571 } 572 573 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello)) 574 if err != nil { 575 if err == errNoCertificates { 576 c.sendAlert(alertUnrecognizedName) 577 } else { 578 c.sendAlert(alertInternalError) 579 } 580 return err 581 } 582 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms) 583 if err != nil { 584 // getCertificate returned a certificate that is unsupported or 585 // incompatible with the client's signature algorithms. 586 c.sendAlert(alertHandshakeFailure) 587 return err 588 } 589 hs.cert = certificate 590 591 return nil 592 } 593 594 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 595 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 596 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 597 if hs.c.quic != nil { 598 return nil 599 } 600 if hs.sentDummyCCS { 601 return nil 602 } 603 hs.sentDummyCCS = true 604 605 return hs.c.writeChangeCipherRecord() 606 } 607 608 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error { 609 c := hs.c 610 611 if hs.clientHello.earlyData { 612 c.handshakeState.Store(handshake0RTT) 613 } 614 615 // The first ClientHello gets double-hashed into the transcript upon a 616 // HelloRetryRequest. See RFC 8446, Section 4.4.1. 617 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { 618 return err 619 } 620 chHash := hs.transcript.Sum(nil) 621 hs.transcript.Reset() 622 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 623 hs.transcript.Write(chHash) 624 625 helloRetryRequest := &serverHelloMsg{ 626 vers: hs.hello.vers, 627 random: helloRetryRequestRandom, 628 sessionId: hs.hello.sessionId, 629 cipherSuite: hs.hello.cipherSuite, 630 compressionMethod: hs.hello.compressionMethod, 631 supportedVersion: hs.hello.supportedVersion, 632 selectedGroup: selectedGroup, 633 extensions: hs.hello.extensions, 634 } 635 636 // Decide whether to send "encrypted_client_hello" extension. 637 if hs.echIsInner() { 638 // Confirm ECH acceptance if this is the inner handshake. 639 echAcceptConfHRRTranscript := cloneHash(hs.transcript, hs.suite.hash) 640 if echAcceptConfHRRTranscript == nil { 641 c.sendAlert(alertInternalError) 642 return errors.New("tls: internal error: failed to clone hash") 643 } 644 645 helloRetryRequest.ech = zeros[:8] 646 echAcceptConfHRR, err := helloRetryRequest.marshal() 647 if err != nil { 648 return fmt.Errorf("tls: ech: HRR.marshal(): %w", err) 649 } 650 echAcceptConfHRRTranscript.Write(echAcceptConfHRR) 651 echAcceptConfHRRSignal := hs.suite.expandLabel( 652 hs.suite.extract(hs.clientHello.random, nil), 653 echAcceptConfHRRLabel, 654 echAcceptConfHRRTranscript.Sum(nil), 655 8) 656 657 helloRetryRequest.ech = echAcceptConfHRRSignal 658 helloRetryRequest.raw = nil 659 } else if c.ech.greased { 660 // draft-ietf-tls-esni-13, Section 7.1: 661 // 662 // If sending a HelloRetryRequest, the server MAY include an 663 // "encrypted_client_hello" extension with a payload of 8 random bytes; 664 // see Section 10.9.4 for details. 665 helloRetryRequest.ech = make([]byte, 8) 666 if _, err := io.ReadFull(c.config.rand(), helloRetryRequest.ech); err != nil { 667 c.sendAlert(alertInternalError) 668 return fmt.Errorf("tls: internal error: rng failure: %s", err) 669 } 670 } 671 672 if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil { 673 return err 674 } 675 676 if err := hs.sendDummyChangeCipherSpec(); err != nil { 677 return err 678 } 679 680 // clientHelloMsg is not included in the transcript. 681 msg, err := c.readHandshake(nil) 682 if err != nil { 683 return err 684 } 685 686 clientHello, ok := msg.(*clientHelloMsg) 687 if !ok { 688 c.sendAlert(alertUnexpectedMessage) 689 return unexpectedMessageError(clientHello, msg) 690 } 691 692 clientHello, err = c.echAcceptOrReject(clientHello, true) // afterHRR == true 693 if err != nil { 694 return fmt.Errorf("tls: %s", err) // Alert sent 695 } 696 697 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup { 698 c.sendAlert(alertIllegalParameter) 699 return errors.New("tls: client sent invalid key share in second ClientHello") 700 } 701 702 if clientHello.earlyData { 703 c.sendAlert(alertIllegalParameter) 704 return errors.New("tls: client indicated early data in second ClientHello") 705 } 706 707 if illegalClientHelloChange(clientHello, hs.clientHello) { 708 c.sendAlert(alertIllegalParameter) 709 return errors.New("tls: client illegally modified second ClientHello") 710 } 711 712 hs.clientHello = clientHello 713 return nil 714 } 715 716 // illegalClientHelloChange reports whether the two ClientHello messages are 717 // different, with the exception of the changes allowed before and after a 718 // HelloRetryRequest. See RFC 8446, Section 4.1.2. 719 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool { 720 if len(ch.supportedVersions) != len(ch1.supportedVersions) || 721 len(ch.cipherSuites) != len(ch1.cipherSuites) || 722 len(ch.supportedCurves) != len(ch1.supportedCurves) || 723 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) || 724 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) || 725 len(ch.alpnProtocols) != len(ch1.alpnProtocols) { 726 return true 727 } 728 for i := range ch.supportedVersions { 729 if ch.supportedVersions[i] != ch1.supportedVersions[i] { 730 return true 731 } 732 } 733 for i := range ch.cipherSuites { 734 if ch.cipherSuites[i] != ch1.cipherSuites[i] { 735 return true 736 } 737 } 738 for i := range ch.supportedCurves { 739 if ch.supportedCurves[i] != ch1.supportedCurves[i] { 740 return true 741 } 742 } 743 for i := range ch.supportedSignatureAlgorithms { 744 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] { 745 return true 746 } 747 } 748 for i := range ch.supportedSignatureAlgorithmsCert { 749 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] { 750 return true 751 } 752 } 753 for i := range ch.alpnProtocols { 754 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] { 755 return true 756 } 757 } 758 return ch.vers != ch1.vers || 759 !bytes.Equal(ch.random, ch1.random) || 760 !bytes.Equal(ch.sessionId, ch1.sessionId) || 761 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) || 762 ch.serverName != ch1.serverName || 763 ch.ocspStapling != ch1.ocspStapling || 764 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) || 765 ch.ticketSupported != ch1.ticketSupported || 766 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) || 767 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported || 768 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) || 769 ch.scts != ch1.scts || 770 !bytes.Equal(ch.cookie, ch1.cookie) || 771 !bytes.Equal(ch.pskModes, ch1.pskModes) 772 } 773 774 func (hs *serverHandshakeStateTLS13) sendServerParameters() error { 775 c := hs.c 776 777 // Confirm ECH acceptance. 778 if hs.echIsInner() { 779 // Clear the last 8 bytes of the ServerHello.random in preparation for 780 // computing the confirmation hint. 781 copy(hs.hello.random[24:], zeros[:8]) 782 783 // Set the last 8 bytes of ServerHello.random to a string derived from 784 // the inner handshake. 785 echAcceptConfTranscript := cloneHash(hs.transcript, hs.suite.hash) 786 if echAcceptConfTranscript == nil { 787 c.sendAlert(alertInternalError) 788 return errors.New("tls: internal error: failed to clone hash") 789 } 790 chMarshalled, err := hs.clientHello.marshal() 791 if err != nil { 792 return fmt.Errorf("tls: ech: clientHello.marshal(): %w", err) 793 } 794 echAcceptConfTranscript.Write(chMarshalled) 795 hMarshalled, err := hs.hello.marshal() 796 if err != nil { 797 return fmt.Errorf("tls: ech: hello.marshal(): %w", err) 798 } 799 echAcceptConfTranscript.Write(hMarshalled) 800 801 echAcceptConf := hs.suite.expandLabel( 802 hs.suite.extract(hs.clientHello.random, nil), 803 echAcceptConfLabel, 804 echAcceptConfTranscript.Sum(nil), 805 8) 806 807 copy(hs.hello.random[24:], echAcceptConf) 808 hs.hello.raw = nil 809 } 810 811 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { 812 return err 813 } 814 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { 815 return err 816 } 817 818 if err := hs.sendDummyChangeCipherSpec(); err != nil { 819 return err 820 } 821 822 earlySecret := hs.earlySecret 823 if earlySecret == nil { 824 earlySecret = hs.suite.extract(nil, nil) 825 } 826 hs.handshakeSecret = hs.suite.extract(hs.sharedKey, 827 hs.suite.deriveSecret(earlySecret, "derived", nil)) 828 829 hs.clientHandshakeSecret = hs.suite.deriveSecret(hs.handshakeSecret, 830 clientHandshakeTrafficLabel, hs.transcript) 831 if !hs.earlyData { 832 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, hs.clientHandshakeSecret) 833 } 834 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret, 835 serverHandshakeTrafficLabel, hs.transcript) 836 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret) 837 838 if c.quic != nil { 839 if c.hand.Len() != 0 { 840 c.sendAlert(alertUnexpectedMessage) 841 } 842 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret) 843 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, hs.clientHandshakeSecret) 844 } 845 846 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, hs.clientHandshakeSecret) 847 if err != nil { 848 c.sendAlert(alertInternalError) 849 return err 850 } 851 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret) 852 if err != nil { 853 c.sendAlert(alertInternalError) 854 return err 855 } 856 857 encryptedExtensions := new(encryptedExtensionsMsg) 858 encryptedExtensions.alpnProtocol = c.clientProtocol 859 if hs.usingALPS { 860 encryptedExtensions.alps = true 861 encryptedExtensions.alpnSetting = c.serverProtocolSetting 862 } 863 encryptedExtensions.earlyData = hs.earlyData 864 if c.quic != nil { 865 p, err := c.quicGetTransportParameters() 866 if err != nil { 867 return err 868 } 869 encryptedExtensions.quicTransportParameters = p 870 } 871 if !c.ech.accepted && len(c.ech.retryConfigs) > 0 { 872 encryptedExtensions.ech = c.ech.retryConfigs 873 } 874 encryptedExtensions.extensions = hs.extensions 875 876 if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil { 877 return err 878 } 879 return nil 880 } 881 882 // negotiateALPS picks a shared ALPS protocol that both sides support in server 883 // preference order. If ALPS is not configured or the peer doesn't support it, 884 // it returns nil and false. 885 func (config *Config) negotiateALPS(selectedProto string, clientProtos []string) ([]byte, bool) { 886 if selectedProto == "" || len(clientProtos) == 0 || len(config.NextProtoSettings) == 0 { 887 return nil, false 888 } 889 890 protoSetting, ok := config.NextProtoSettings[selectedProto] 891 if !ok { 892 return nil, false 893 } 894 895 for _, c := range clientProtos { 896 if selectedProto == c { 897 return protoSetting, true 898 } 899 } 900 901 return nil, false 902 } 903 904 func (hs *serverHandshakeStateTLS13) requestClientCert() bool { 905 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK 906 } 907 908 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error { 909 c := hs.c 910 911 // Only one of PSK and certificates are used at a time. 912 if hs.usingPSK { 913 return nil 914 } 915 916 if hs.requestClientCert() { 917 // Request a client certificate 918 certReq := new(certificateRequestMsgTLS13) 919 certReq.ocspStapling = true 920 certReq.scts = true 921 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms() 922 if c.config.ClientCAs != nil { 923 certReq.certificateAuthorities = c.config.ClientCAs.Subjects() 924 } 925 926 if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil { 927 return err 928 } 929 } 930 931 certMsg := new(certificateMsgTLS13) 932 933 certMsg.certificate = *hs.cert 934 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0 935 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 936 937 var msg handshakeMessage = certMsg 938 if hs.certCompressionAlgorithm != 0 { 939 var err error 940 msg, err = certMsg.compress(hs.certCompressionAlgorithm) 941 if err != nil { 942 c.sendAlert(alertInternalError) 943 return err 944 } 945 } 946 947 if _, err := hs.c.writeHandshakeRecord(msg, hs.transcript); err != nil { 948 return err 949 } 950 951 certVerifyMsg := new(certificateVerifyMsg) 952 certVerifyMsg.hasSignatureAlgorithm = true 953 certVerifyMsg.signatureAlgorithm = hs.sigAlg 954 955 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg) 956 if err != nil { 957 return c.sendAlert(alertInternalError) 958 } 959 960 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 961 signOpts := crypto.SignerOpts(sigHash) 962 if sigType == signatureRSAPSS { 963 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 964 } 965 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 966 if err != nil { 967 public := hs.cert.PrivateKey.(crypto.Signer).Public() 968 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS && 969 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS 970 c.sendAlert(alertHandshakeFailure) 971 } else { 972 c.sendAlert(alertInternalError) 973 } 974 return errors.New("tls: failed to sign handshake: " + err.Error()) 975 } 976 certVerifyMsg.signature = sig 977 978 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil { 979 return err 980 } 981 982 return nil 983 } 984 985 func (hs *serverHandshakeStateTLS13) sendServerFinished() error { 986 c := hs.c 987 988 finished := &finishedMsg{ 989 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 990 } 991 992 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil { 993 return err 994 } 995 996 // Derive secrets that take context through the server Finished. 997 998 hs.masterSecret = hs.suite.extract(nil, 999 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil)) 1000 1001 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 1002 clientApplicationTrafficLabel, hs.transcript) 1003 serverSecret := hs.suite.deriveSecret(hs.masterSecret, 1004 serverApplicationTrafficLabel, hs.transcript) 1005 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret) 1006 1007 if c.quic != nil { 1008 if c.hand.Len() != 0 { 1009 // TODO: Handle this in setTrafficSecret? 1010 c.sendAlert(alertUnexpectedMessage) 1011 } 1012 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret) 1013 } 1014 1015 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) 1016 if err != nil { 1017 c.sendAlert(alertInternalError) 1018 return err 1019 } 1020 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret) 1021 if err != nil { 1022 c.sendAlert(alertInternalError) 1023 return err 1024 } 1025 1026 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 1027 1028 // If we did not request client certificates, at this point we can 1029 // precompute the client finished and roll the transcript forward to send 1030 // session tickets in our first flight. 1031 if !hs.requestClientCert() { 1032 if err := hs.sendSessionTickets(); err != nil { 1033 return err 1034 } 1035 } 1036 1037 return nil 1038 } 1039 1040 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { 1041 if hs.c.config.SessionTicketsDisabled || hs.c.config.ECHEnabled { 1042 return false 1043 } 1044 1045 // QUIC tickets are sent by QUICConn.SendSessionTicket, not automatically. 1046 if hs.c.quic != nil { 1047 return false 1048 } 1049 1050 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. 1051 for _, pskMode := range hs.clientHello.pskModes { 1052 if pskMode == pskModeDHE { 1053 return true 1054 } 1055 } 1056 return false 1057 } 1058 1059 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { 1060 c := hs.c 1061 1062 hs.clientFinished = hs.suite.finishedHash(hs.clientHandshakeSecret, hs.transcript) 1063 finishedMsg := &finishedMsg{ 1064 verifyData: hs.clientFinished, 1065 } 1066 if err := transcriptMsg(finishedMsg, hs.transcript); err != nil { 1067 return err 1068 } 1069 1070 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, 1071 resumptionLabel, hs.transcript) 1072 1073 if !hs.shouldSendSessionTickets() { 1074 return nil 1075 } 1076 return c.sendSessionTicket(c.config.maxEarlyData()) 1077 } 1078 1079 func (c *Conn) sendSessionTicket(maxEarlyData uint32) error { 1080 suite := cipherSuiteTLS13ByID(c.cipherSuite) 1081 if suite == nil { 1082 return errors.New("tls: internal error: unknown cipher suite") 1083 } 1084 // ticket_nonce, which must be unique per connection, is always left at 1085 // zero because we only ever send one ticket per connection. 1086 psk := suite.expandLabel(c.resumptionSecret, "resumption", 1087 nil, suite.hash.Size()) 1088 1089 m := new(newSessionTicketMsgTLS13) 1090 1091 // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1 1092 ageAdd := make([]byte, 4) 1093 _, err := c.config.rand().Read(ageAdd) 1094 if err != nil { 1095 return err 1096 } 1097 1098 state, err := c.sessionState() 1099 if err != nil { 1100 return err 1101 } 1102 state.secret = psk 1103 state.MaxEarlyData = maxEarlyData 1104 if c.config.WrapSession != nil { 1105 m.label, err = c.config.WrapSession(c.connectionStateLocked(), state) 1106 if err != nil { 1107 return err 1108 } 1109 } else { 1110 stateBytes, err := state.Bytes() 1111 if err != nil { 1112 c.sendAlert(alertInternalError) 1113 return err 1114 } 1115 m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys) 1116 if err != nil { 1117 return err 1118 } 1119 } 1120 m.lifetime = uint32(maxSessionTicketLifetime / time.Second) 1121 m.ageAdd = binary.LittleEndian.Uint32(ageAdd) 1122 1123 // ticket_nonce, which must be unique per connection, is always left at 1124 // zero because we only ever send one ticket per connection. 1125 m.nonce = nil 1126 1127 m.maxEarlyData = maxEarlyData 1128 1129 if _, err := c.writeHandshakeRecord(m, nil); err != nil { 1130 return err 1131 } 1132 1133 return nil 1134 } 1135 1136 func (c *Conn) handleEndOfEarlyData() error { 1137 if c.handshakeState.Load() != handshake0RTT { 1138 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1139 } 1140 1141 if c.earlyDataEOF { 1142 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1143 } 1144 1145 c.earlyNotify.L.Lock() 1146 c.earlyDataEOF = true 1147 c.earlyNotify.Broadcast() 1148 c.earlyNotify.L.Unlock() 1149 1150 c.earlyNotify.L.Lock() 1151 c.earlyNotify.Wait() 1152 c.earlyNotify.L.Unlock() 1153 return c.handshakeErr 1154 } 1155 1156 func (hs *serverHandshakeStateTLS13) readClientEarlyData() error { 1157 c := hs.c 1158 1159 c.earlyNotify.L.Lock() 1160 defer c.earlyNotify.L.Unlock() 1161 1162 if !hs.earlyData || c.earlyDataEOF { 1163 return nil 1164 } 1165 1166 if c.in.TryLock() { 1167 msg, err := c.readHandshake(nil) 1168 if err != nil { 1169 return err 1170 } 1171 1172 endOfEarlyData, ok := msg.(*endOfEarlyDataMsg) 1173 if !ok { 1174 c.sendAlert(alertUnexpectedMessage) 1175 return unexpectedMessageError(endOfEarlyData, msg) 1176 } 1177 1178 c.in.Unlock() 1179 } else { 1180 c.earlyNotify.Wait() 1181 } 1182 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, hs.clientHandshakeSecret) 1183 return c.handshakeErr 1184 } 1185 1186 func (hs *serverHandshakeStateTLS13) readClientParameters() error { 1187 c := hs.c 1188 1189 if hs.earlyData || !hs.usingALPS { 1190 return nil 1191 } 1192 1193 msg, err := c.readHandshake(hs.transcript) 1194 if err != nil { 1195 return err 1196 } 1197 1198 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) 1199 if !ok { 1200 c.sendAlert(alertUnexpectedMessage) 1201 return unexpectedMessageError(encryptedExtensions, msg) 1202 } 1203 1204 if !encryptedExtensions.alps { 1205 return c.sendAlert(alertMissingExtension) 1206 } 1207 1208 c.clientProtocolSetting = encryptedExtensions.alpnSetting 1209 1210 return nil 1211 } 1212 1213 func (hs *serverHandshakeStateTLS13) readClientCertificate() error { 1214 c := hs.c 1215 1216 if !hs.requestClientCert() { 1217 // Make sure the connection is still being verified whether or not 1218 // the server requested a client certificate. 1219 if c.config.VerifyConnection != nil { 1220 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 1221 c.sendAlert(alertBadCertificate) 1222 return err 1223 } 1224 } 1225 return nil 1226 } 1227 1228 // If we requested a client certificate, then the client must send a 1229 // certificate message. If it's empty, no CertificateVerify is sent. 1230 1231 msg, err := c.readHandshake(hs.transcript) 1232 if err != nil { 1233 return err 1234 } 1235 1236 var certMsg *certificateMsgTLS13 1237 switch msg := msg.(type) { 1238 case *certificateMsgTLS13: 1239 certMsg = msg 1240 case *compressedCertificateMsg: 1241 if !c.config.supportsCertCompression(CertCompressionAlgorithm(msg.algorithm)) { 1242 c.sendAlert(alertIllegalParameter) 1243 return errors.New("tls: server selected unsupported algorithm") 1244 } 1245 certMsg, err = msg.decompress() 1246 if err != nil { 1247 c.sendAlert(alertBadCertificate) 1248 return err 1249 } 1250 default: 1251 c.sendAlert(alertUnexpectedMessage) 1252 return unexpectedMessageError(certMsg, msg) 1253 } 1254 1255 if err := c.processCertsFromClient(certMsg.certificate); err != nil { 1256 return err 1257 } 1258 1259 if c.config.VerifyConnection != nil { 1260 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 1261 c.sendAlert(alertBadCertificate) 1262 return err 1263 } 1264 } 1265 1266 if len(certMsg.certificate.Certificate) != 0 { 1267 // certificateVerifyMsg is included in the transcript, but not until 1268 // after we verify the handshake signature, since the state before 1269 // this message was sent is used. 1270 msg, err = c.readHandshake(nil) 1271 if err != nil { 1272 return err 1273 } 1274 1275 certVerify, ok := msg.(*certificateVerifyMsg) 1276 if !ok { 1277 c.sendAlert(alertUnexpectedMessage) 1278 return unexpectedMessageError(certVerify, msg) 1279 } 1280 1281 // See RFC 8446, Section 4.4.3. 1282 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { 1283 c.sendAlert(alertIllegalParameter) 1284 return errors.New("tls: client certificate used with invalid signature algorithm") 1285 } 1286 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 1287 if err != nil { 1288 return c.sendAlert(alertInternalError) 1289 } 1290 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 1291 c.sendAlert(alertIllegalParameter) 1292 return errors.New("tls: client certificate used with invalid signature algorithm") 1293 } 1294 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 1295 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 1296 sigHash, signed, certVerify.signature); err != nil { 1297 c.sendAlert(alertDecryptError) 1298 return errors.New("tls: invalid signature by the client certificate: " + err.Error()) 1299 } 1300 1301 if err := transcriptMsg(certVerify, hs.transcript); err != nil { 1302 return err 1303 } 1304 } 1305 1306 // If we waited until the client certificates to send session tickets, we 1307 // are ready to do it now. 1308 if err := hs.sendSessionTickets(); err != nil { 1309 return err 1310 } 1311 1312 return nil 1313 } 1314 1315 func (hs *serverHandshakeStateTLS13) readClientFinished() error { 1316 c := hs.c 1317 1318 // finishedMsg is not included in the transcript. 1319 msg, err := c.readHandshake(nil) 1320 if err != nil { 1321 return err 1322 } 1323 1324 finished, ok := msg.(*finishedMsg) 1325 if !ok { 1326 c.sendAlert(alertUnexpectedMessage) 1327 return unexpectedMessageError(finished, msg) 1328 } 1329 1330 if !hmac.Equal(hs.clientFinished, finished.verifyData) { 1331 c.sendAlert(alertDecryptError) 1332 return errors.New("tls: invalid client finished hash") 1333 } 1334 1335 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret) 1336 1337 return nil 1338 }