gitlab.com/go-extension/tls@v0.0.0-20240304171319-e6745021905e/handshake_client.go (about) 1 // Copyright 2009 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/ecdh" 12 "crypto/ecdsa" 13 "crypto/ed25519" 14 "crypto/rsa" 15 "crypto/subtle" 16 "crypto/x509" 17 "errors" 18 "fmt" 19 "hash" 20 "io" 21 "net" 22 "strings" 23 "sync" 24 "time" 25 ) 26 27 type clientHandshakeState struct { 28 c *Conn 29 ctx context.Context 30 serverHello *serverHelloMsg 31 hello *clientHelloMsg 32 suite *cipherSuite 33 finishedHash finishedHash 34 masterSecret []byte 35 session *SessionState 36 ticket []byte // a fresh ticket received during this handshake 37 extensions []Extension 38 } 39 40 var testingOnlyForceClientHelloSignatureAlgorithms []SignatureScheme 41 42 func (c *Conn) makeClientHello() (*clientHelloMsg, *ecdh.PrivateKey, error) { 43 config := c.config 44 if len(config.ServerName) == 0 && !config.InsecureSkipVerify { 45 return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config") 46 } 47 48 nextProtosLength := 0 49 for _, proto := range config.NextProtos { 50 if l := len(proto); l == 0 || l > 255 { 51 return nil, nil, errors.New("tls: invalid NextProtos value") 52 } else { 53 nextProtosLength += 1 + l 54 } 55 } 56 if nextProtosLength > 0xffff { 57 return nil, nil, errors.New("tls: NextProtos values too large") 58 } 59 60 supportedVersions := config.supportedVersions(roleClient) 61 if len(supportedVersions) == 0 { 62 return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion") 63 } 64 65 clientHelloVersion := config.maxSupportedVersion(roleClient) 66 // The version at the beginning of the ClientHello was capped at TLS 1.2 67 // for compatibility reasons. The supported_versions extension is used 68 // to negotiate versions now. See RFC 8446, Section 4.2.1. 69 if clientHelloVersion > VersionTLS12 { 70 clientHelloVersion = VersionTLS12 71 } 72 73 hello := &clientHelloMsg{ 74 vers: clientHelloVersion, 75 compressionMethods: []uint8{compressionNone}, 76 random: make([]byte, 32), 77 extendedMasterSecret: true, 78 ocspStapling: true, 79 scts: true, 80 serverName: hostnameInSNI(config.ServerName), 81 supportedCompressionAlgorithmsCert: config.certCompressionPreferences(), 82 supportedPoints: []uint8{pointFormatUncompressed}, 83 secureRenegotiationSupported: true, 84 alpnProtocols: config.NextProtos, 85 supportedVersions: supportedVersions, 86 } 87 88 if c.config.maxSupportedVersion(roleClient) >= VersionTLS13 { 89 for alpn := range config.NextProtoSettings { 90 hello.alpsProtocols = append(hello.alpsProtocols, alpn) 91 } 92 } 93 94 if c.handshakes > 0 { 95 hello.secureRenegotiation = c.clientFinished[:] 96 } 97 98 configCipherSuites := config.cipherSuites() 99 hello.cipherSuites = make([]uint16, 0, len(configCipherSuites)) 100 101 var preferenceOrder []uint16 102 switch { 103 case config.PreferCipherSuites: 104 preferenceOrder = configCipherSuites 105 case hasAESGCMHardwareSupport: 106 preferenceOrder = cipherSuitesPreferenceOrder 107 default: 108 preferenceOrder = cipherSuitesPreferenceOrderNoAES 109 } 110 111 for _, suiteId := range preferenceOrder { 112 if IsGREASE(suiteId) { 113 hello.cipherSuites = append(hello.cipherSuites, c.GREASE()) 114 continue 115 } 116 117 suite := mutualCipherSuite(configCipherSuites, suiteId) 118 suite13 := mutualCipherSuiteTLS13(configCipherSuites, suiteId) 119 switch { 120 case suite != nil: 121 // Don't advertise TLS 1.2-only cipher suites unless 122 // we're attempting TLS 1.2. 123 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 { 124 continue 125 } 126 127 if config.MinVersion > VersionTLS12 { 128 continue 129 } 130 case suite13 != nil: 131 if config.maxSupportedVersion(roleClient) < VersionTLS13 { 132 continue 133 } 134 default: 135 continue 136 } 137 138 hello.cipherSuites = append(hello.cipherSuites, suiteId) 139 } 140 141 if len(hello.cipherSuites) == 0 { 142 return nil, nil, errors.New("tls: not vaild cipher suite provided") 143 } 144 145 _, err := io.ReadFull(config.rand(), hello.random) 146 if err != nil { 147 return nil, nil, errors.New("tls: short read from Rand: " + err.Error()) 148 } 149 150 // A random session ID is used to detect when the server accepted a ticket 151 // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as 152 // a compatibility measure (see RFC 8446, Section 4.1.2). 153 // 154 // The session ID is not set for QUIC connections (see RFC 9001, Section 8.4). 155 if c.quic == nil { 156 hello.sessionId = make([]byte, 32) 157 if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil { 158 return nil, nil, errors.New("tls: short read from Rand: " + err.Error()) 159 } 160 } 161 162 if hello.vers >= VersionTLS12 { 163 hello.supportedSignatureAlgorithms = config.signatureAlgorithmsPreferences() 164 } 165 if testingOnlyForceClientHelloSignatureAlgorithms != nil { 166 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms 167 } 168 169 var key *ecdh.PrivateKey 170 for _, curveID := range config.curvePreferences() { 171 if IsGREASE(uint16(curveID)) { 172 groupId := CurveID(c.GREASE()) 173 hello.supportedCurves = append(hello.supportedCurves, groupId) 174 if config.maxSupportedVersion(c.isClient) >= VersionTLS13 { 175 hello.keyShares = append(hello.keyShares, keyShare{group: groupId, data: []byte{0}}) 176 } 177 continue 178 } 179 180 if _, ok := curveForCurveID(curveID); !ok { 181 return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve") 182 } 183 hello.supportedCurves = append(hello.supportedCurves, curveID) 184 185 if config.maxSupportedVersion(roleClient) < VersionTLS13 || key != nil { 186 continue 187 } 188 189 key, err = generateECDHEKey(config.rand(), curveID) 190 if err != nil { 191 return nil, nil, err 192 } 193 194 hello.keyShares = append(hello.keyShares, keyShare{group: curveID, data: key.PublicKey().Bytes()}) 195 } 196 197 grease_extensions_ids := make([]uint16, 0) 198 for _, extension := range c.config.getExtensions() { 199 if extension == nil { 200 continue 201 } 202 203 extension = extension.Clone() 204 switch extension := extension.(type) { 205 case *GREASEExtension: 206 switch len(grease_extensions_ids) { 207 case 0: 208 extension.Id = c.GREASE() 209 case 1: 210 extension.Id = c.GREASE() 211 if extension.Id == grease_extensions_ids[0] { 212 extension.Id ^= 0x1010 213 } 214 215 extension.Data = []byte{0} 216 default: 217 return nil, nil, errors.New("at most 2 grease extensions are supported") 218 } 219 grease_extensions_ids = append(grease_extensions_ids, extension.Id) 220 221 hello.extensions = append(hello.extensions, extension) 222 default: 223 hello.extensions = append(hello.extensions, extension) 224 } 225 } 226 227 if c.quic != nil { 228 p, err := c.quicGetTransportParameters() 229 if err != nil { 230 return nil, nil, err 231 } 232 if p == nil { 233 p = []byte{} 234 } 235 hello.quicTransportParameters = p 236 } 237 238 return hello, key, nil 239 } 240 241 func (c *Conn) makeEncryptedClientHello(hello *clientHelloMsg) error { 242 config := c.config 243 244 supportedVersions := config.supportedVersionsFromMin(roleClient, VersionTLS13) 245 if len(supportedVersions) == 0 { 246 return errors.New("tls: no supported versions satisfy MinVersion and MaxVersion") 247 } 248 249 hello.supportedVersions = supportedVersions 250 return nil 251 } 252 253 func (c *Conn) clientHandshake(ctx context.Context) (err error) { 254 if c.config == nil { 255 c.config = defaultConfig() 256 } 257 258 // This may be a renegotiation handshake, in which case some fields 259 // need to be reset. 260 c.didResume = false 261 262 helloBase, ecdheKey, err := c.makeClientHello() 263 if err != nil { 264 return err 265 } 266 267 if c.config.echCanOffer() { 268 // If the ECH extension will be offered in this handshake, then the 269 // ClientHelloInner must not offer TLS 1.2 or below. 270 err := c.makeEncryptedClientHello(helloBase) 271 if err != nil { 272 return err 273 } 274 } 275 276 hello, helloInner, err := c.echOfferOrGrease(helloBase) 277 if err != nil { 278 return err 279 } 280 281 helloResumed := hello 282 if c.ech.offered { 283 helloResumed = helloInner 284 } 285 286 session, earlySecret, binderKey, err := c.loadSession(helloResumed) 287 if err != nil { 288 return err 289 } 290 if session != nil { 291 defer func() { 292 // If we got a handshake failure when resuming a session, throw away 293 // the session ticket. See RFC 5077, Section 3.2. 294 // 295 // RFC 8446 makes no mention of dropping tickets on failure, but it 296 // does require servers to abort on invalid binders, so we need to 297 // delete tickets to recover from a corrupted PSK. 298 if err != nil { 299 if cacheKey := c.clientSessionCacheKey(); cacheKey != "" { 300 c.config.ClientSessionCache.Put(cacheKey, nil) 301 } 302 } 303 }() 304 } 305 306 hello.automaticPadding(c.config.MinClientHelloSize) 307 if c.config.ShuffleExtensions { 308 hello.automaticShuffle() 309 } 310 311 if _, err := c.writeHandshakeRecord(hello, nil); err != nil { 312 return err 313 } 314 315 handshakeFn := func() error { 316 // serverHelloMsg is not included in the transcript 317 msg, err := c.readHandshake(nil) 318 if err != nil { 319 return err 320 } 321 322 serverHello, ok := msg.(*serverHelloMsg) 323 if !ok { 324 c.sendAlert(alertUnexpectedMessage) 325 return unexpectedMessageError(serverHello, msg) 326 } 327 328 if err := c.pickTLSVersion(serverHello); err != nil { 329 return err 330 } 331 332 extensions := hello.extensions 333 for _, extension := range serverHello.extensions { 334 switch extension := extension.(type) { 335 case nil: 336 case *UnimplementedExtension: 337 for _, ext := range extensions { 338 if ext.ExtensionId() == extension.ExtensionId() { 339 ext.NegotiatedVersion(c.vers) 340 341 if !ext.Unmarshal(typeServerHello, extension.Data) { 342 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 343 } 344 break 345 } 346 } 347 } 348 } 349 350 // If we are negotiating a protocol version that's lower than what we 351 // support, check for the server downgrade canaries. 352 // See RFC 8446, Section 4.1.3. 353 maxVers := c.config.maxSupportedVersion(roleClient) 354 tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12 355 tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11 356 if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) || 357 maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade { 358 c.sendAlert(alertIllegalParameter) 359 return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox") 360 } 361 362 if c.vers == VersionTLS13 { 363 hs := &clientHandshakeStateTLS13{ 364 c: c, 365 ctx: ctx, 366 serverHello: serverHello, 367 hello: hello, 368 helloInner: helloInner, 369 ecdheKey: ecdheKey, 370 session: session, 371 earlySecret: earlySecret, 372 binderKey: binderKey, 373 extensions: extensions, 374 sentDummyCCS: hello.earlyData, 375 } 376 377 // In TLS 1.3, session tickets are delivered after the handshake. 378 return hs.handshake() 379 } 380 381 c.serverName = hello.serverName 382 hs := &clientHandshakeState{ 383 c: c, 384 ctx: ctx, 385 serverHello: serverHello, 386 hello: hello, 387 session: session, 388 extensions: extensions, 389 } 390 391 if err := hs.handshake(); err != nil { 392 return err 393 } 394 395 return nil 396 } 397 398 if hello.earlyData { 399 c.vers = VersionTLS13 400 c.in.version = VersionTLS13 401 c.out.version = VersionTLS13 402 403 if err := c.writeChangeCipherRecord(); err != nil { 404 return err 405 } 406 407 suite := cipherSuiteTLS13ByID(session.cipherSuite) 408 transcript := suite.hash.New() 409 if err := transcriptMsg(hello, transcript); err != nil { 410 return err 411 } 412 413 earlyTrafficSecret := suite.deriveSecret(earlySecret, clientEarlyTrafficLabel, transcript) 414 if c.quic == nil { 415 c.out.setTrafficSecret(suite, QUICEncryptionLevelEarly, earlyTrafficSecret) 416 } else { 417 c.quicSetWriteSecret(QUICEncryptionLevelEarly, suite.id, earlyTrafficSecret) 418 } 419 420 err = c.config.writeKeyLog(keyLogLabelClientEarly, hello.random, earlyTrafficSecret) 421 if err != nil { 422 c.sendAlert(alertInternalError) 423 return err 424 } 425 426 c.handshakeState.Store(handshake0RTT) 427 428 go func() { 429 c.handshakeErr = handshakeFn() 430 431 c.earlyNotify.L.Lock() 432 c.earlyNotify.Broadcast() 433 c.earlyNotify.L.Unlock() 434 }() 435 return nil 436 } 437 438 return handshakeFn() 439 } 440 441 func (c *Conn) loadSession(hello *clientHelloMsg) ( 442 session *SessionState, earlySecret, binderKey []byte, err error) { 443 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil || c.config.ECHEnabled { 444 return nil, nil, nil, nil 445 } 446 447 hello.ticketSupported = true 448 449 if c.config.maxSupportedVersion(c.isClient) >= VersionTLS13 { 450 // Require DHE on resumption as it guarantees forward secrecy against 451 // compromise of the session ticket key. See RFC 8446, Section 4.2.9. 452 hello.pskModes = []uint8{pskModeDHE} 453 } 454 455 // Session resumption is not allowed if renegotiating because 456 // renegotiation is primarily used to allow a client to send a client 457 // certificate, which would be skipped if session resumption occurred. 458 if c.handshakes != 0 { 459 return nil, nil, nil, nil 460 } 461 462 // Try to resume a previously negotiated TLS session, if available. 463 cacheKey := c.clientSessionCacheKey() 464 if cacheKey == "" { 465 return nil, nil, nil, nil 466 } 467 cs, ok := c.config.ClientSessionCache.Get(cacheKey) 468 if !ok || cs == nil { 469 return nil, nil, nil, nil 470 } 471 session = cs.session 472 473 // Check that version used for the previous session is still valid. 474 versOk := false 475 for _, v := range hello.supportedVersions { 476 if v == session.version { 477 versOk = true 478 break 479 } 480 } 481 if !versOk { 482 return nil, nil, nil, nil 483 } 484 485 // Check that the cached server certificate is not expired, and that it's 486 // valid for the ServerName. This should be ensured by the cache key, but 487 // protect the application from a faulty ClientSessionCache implementation. 488 if c.config.time().After(session.peerCertificates[0].NotAfter) { 489 // Expired certificate, delete the entry. 490 c.config.ClientSessionCache.Put(cacheKey, nil) 491 return nil, nil, nil, nil 492 } 493 if !c.config.InsecureSkipVerify { 494 if len(session.verifiedChains) == 0 { 495 // The original connection had InsecureSkipVerify, while this doesn't. 496 return nil, nil, nil, nil 497 } 498 if err := session.peerCertificates[0].VerifyHostname(c.config.ServerName); err != nil { 499 return nil, nil, nil, nil 500 } 501 } 502 503 if session.version != VersionTLS13 { 504 // In TLS 1.2 the cipher suite must match the resumed session. Ensure we 505 // are still offering it. 506 if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil { 507 return nil, nil, nil, nil 508 } 509 510 hello.sessionTicket = cs.ticket 511 return 512 } 513 514 // Check that the session ticket is not expired. 515 if c.config.time().After(time.Unix(int64(session.useBy), 0)) { 516 c.config.ClientSessionCache.Put(cacheKey, nil) 517 return nil, nil, nil, nil 518 } 519 520 // In TLS 1.3 the KDF hash must match the resumed session. Ensure we 521 // offer at least one cipher suite with that hash. 522 cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite) 523 if cipherSuite == nil { 524 return nil, nil, nil, nil 525 } 526 cipherSuiteOk := false 527 for _, offeredID := range hello.cipherSuites { 528 offeredSuite := cipherSuiteTLS13ByID(offeredID) 529 if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash { 530 cipherSuiteOk = true 531 break 532 } 533 } 534 if !cipherSuiteOk { 535 return nil, nil, nil, nil 536 } 537 538 if c.config.Allow0RTT && session.MaxEarlyData > 0 { 539 // For 0-RTT, the cipher suite has to match exactly, and we need to be 540 // offering the same ALPN. 541 if mutualCipherSuiteTLS13(hello.cipherSuites, session.cipherSuite) != nil { 542 if len(hello.alpnProtocols) == 0 && session.alpnProtocol == "" { 543 c.earlyNotify = sync.NewCond(&sync.Mutex{}) 544 c.maxEarlyData = session.MaxEarlyData 545 hello.earlyData = true 546 } else { 547 for _, alpn := range hello.alpnProtocols { 548 if alpn == session.alpnProtocol { 549 c.earlyNotify = sync.NewCond(&sync.Mutex{}) 550 c.maxEarlyData = session.MaxEarlyData 551 hello.earlyData = true 552 break 553 } 554 } 555 } 556 } 557 } 558 559 // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1. 560 ticketAge := c.config.time().Sub(time.Unix(int64(session.createdAt), 0)) 561 identity := pskIdentity{ 562 label: cs.ticket, 563 obfuscatedTicketAge: uint32(ticketAge/time.Millisecond) + session.ageAdd, 564 } 565 hello.pskIdentities = []pskIdentity{identity} 566 hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())} 567 568 // Compute the PSK binders. See RFC 8446, Section 4.2.11.2. 569 earlySecret = cipherSuite.extract(session.secret, nil) 570 binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil) 571 transcript := cipherSuite.hash.New() 572 573 hello.automaticPadding(c.config.MinClientHelloSize) 574 575 helloBytes, err := hello.marshalWithoutBinders() 576 if err != nil { 577 return nil, nil, nil, err 578 } 579 transcript.Write(helloBytes) 580 pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)} 581 if err := hello.updateBinders(pskBinders); err != nil { 582 return nil, nil, nil, err 583 } 584 585 return 586 } 587 588 func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error { 589 peerVersion := serverHello.vers 590 if serverHello.supportedVersion != 0 { 591 peerVersion = serverHello.supportedVersion 592 } 593 594 vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion}) 595 if !ok { 596 c.sendAlert(alertProtocolVersion) 597 return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion) 598 } 599 600 c.vers = vers 601 c.haveVers = true 602 c.in.version = vers 603 c.out.version = vers 604 605 return nil 606 } 607 608 // Does the handshake, either a full one or resumes old session. Requires hs.c, 609 // hs.hello, hs.serverHello, and, optionally, hs.session to be set. 610 func (hs *clientHandshakeState) handshake() error { 611 c := hs.c 612 613 if c.handshakeState.CompareAndSwap(handshake0RTT, handshakeRunning) { 614 c.earlyNotify.L.Lock() 615 c.earlyDataEOF = true 616 c.earlyNotify.L.Unlock() 617 618 c.out.cipher = nil 619 } 620 621 isResume, err := hs.processServerHello() 622 if err != nil { 623 return err 624 } 625 626 hs.finishedHash = newFinishedHash(c.vers, hs.suite) 627 628 // No signatures of the handshake are needed in a resumption. 629 // Otherwise, in a full handshake, if we don't have any certificates 630 // configured then we will never send a CertificateVerify message and 631 // thus no signatures are needed in that case either. 632 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) { 633 hs.finishedHash.discardHandshakeBuffer() 634 } 635 636 if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil { 637 return err 638 } 639 if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil { 640 return err 641 } 642 643 c.buffering = true 644 c.didResume = isResume 645 if isResume { 646 if err := hs.establishKeys(); err != nil { 647 return err 648 } 649 if err := hs.readSessionTicket(); err != nil { 650 return err 651 } 652 if err := hs.readFinished(c.serverFinished[:]); err != nil { 653 return err 654 } 655 c.clientFinishedIsFirst = false 656 // Make sure the connection is still being verified whether or not this 657 // is a resumption. Resumptions currently don't reverify certificates so 658 // they don't call verifyServerCertificate. See Issue 31641. 659 if c.config.VerifyConnection != nil { 660 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 661 c.sendAlert(alertBadCertificate) 662 return err 663 } 664 } 665 if err := hs.sendFinished(c.clientFinished[:]); err != nil { 666 return err 667 } 668 if _, err := c.flush(); err != nil { 669 return err 670 } 671 } else { 672 if err := hs.doFullHandshake(); err != nil { 673 return err 674 } 675 if err := hs.establishKeys(); err != nil { 676 return err 677 } 678 if err := hs.sendFinished(c.clientFinished[:]); err != nil { 679 return err 680 } 681 if _, err := c.flush(); err != nil { 682 return err 683 } 684 c.clientFinishedIsFirst = true 685 if err := hs.readSessionTicket(); err != nil { 686 return err 687 } 688 if err := hs.readFinished(c.serverFinished[:]); err != nil { 689 return err 690 } 691 } 692 if err := c.setup(); err != nil { 693 return err 694 } 695 if err := hs.saveSessionTicket(); err != nil { 696 return err 697 } 698 if err := hs.sendClientData(); err != nil { 699 return err 700 } 701 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random) 702 c.handshakeState.Store(handshakeCompleted) 703 return nil 704 } 705 706 func (hs *clientHandshakeState) pickCipherSuite() error { 707 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil { 708 hs.c.sendAlert(alertHandshakeFailure) 709 return errors.New("tls: server chose an unconfigured cipher suite") 710 } 711 712 hs.c.cipherSuite = hs.suite.id 713 return nil 714 } 715 716 func (hs *clientHandshakeState) doFullHandshake() error { 717 c := hs.c 718 719 msg, err := c.readHandshake(&hs.finishedHash) 720 if err != nil { 721 return err 722 } 723 certMsg, ok := msg.(*certificateMsg) 724 if !ok || len(certMsg.certificates) == 0 { 725 c.sendAlert(alertUnexpectedMessage) 726 return unexpectedMessageError(certMsg, msg) 727 } 728 729 msg, err = c.readHandshake(&hs.finishedHash) 730 if err != nil { 731 return err 732 } 733 734 cs, ok := msg.(*certificateStatusMsg) 735 if ok { 736 // RFC4366 on Certificate Status Request: 737 // The server MAY return a "certificate_status" message. 738 739 if !hs.serverHello.ocspStapling { 740 // If a server returns a "CertificateStatus" message, then the 741 // server MUST have included an extension of type "status_request" 742 // with empty "extension_data" in the extended server hello. 743 744 c.sendAlert(alertUnexpectedMessage) 745 return errors.New("tls: received unexpected CertificateStatus message") 746 } 747 748 c.ocspResponse = cs.response 749 750 msg, err = c.readHandshake(&hs.finishedHash) 751 if err != nil { 752 return err 753 } 754 } 755 756 if c.handshakes == 0 { 757 // If this is the first handshake on a connection, process and 758 // (optionally) verify the server's certificates. 759 if err := c.verifyServerCertificate(certMsg.certificates); err != nil { 760 return err 761 } 762 } else { 763 // This is a renegotiation handshake. We require that the 764 // server's identity (i.e. leaf certificate) is unchanged and 765 // thus any previous trust decision is still valid. 766 // 767 // See https://mitls.org/pages/attacks/3SHAKE for the 768 // motivation behind this requirement. 769 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) { 770 c.sendAlert(alertBadCertificate) 771 return errors.New("tls: server's identity changed during renegotiation") 772 } 773 } 774 775 keyAgreement := hs.suite.ka(c.vers) 776 777 skx, ok := msg.(*serverKeyExchangeMsg) 778 if ok { 779 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx) 780 if err != nil { 781 c.sendAlert(alertUnexpectedMessage) 782 return err 783 } 784 785 msg, err = c.readHandshake(&hs.finishedHash) 786 if err != nil { 787 return err 788 } 789 } 790 791 var chainToSend *Certificate 792 var certRequested bool 793 certReq, ok := msg.(*certificateRequestMsg) 794 if ok { 795 certRequested = true 796 797 cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq) 798 if chainToSend, err = c.getClientCertificate(cri); err != nil { 799 c.sendAlert(alertInternalError) 800 return err 801 } 802 803 msg, err = c.readHandshake(&hs.finishedHash) 804 if err != nil { 805 return err 806 } 807 } 808 809 shd, ok := msg.(*serverHelloDoneMsg) 810 if !ok { 811 c.sendAlert(alertUnexpectedMessage) 812 return unexpectedMessageError(shd, msg) 813 } 814 815 // If the server requested a certificate then we have to send a 816 // Certificate message, even if it's empty because we don't have a 817 // certificate to send. 818 if certRequested { 819 certMsg = new(certificateMsg) 820 certMsg.certificates = chainToSend.Certificate 821 if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil { 822 return err 823 } 824 } 825 826 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0]) 827 if err != nil { 828 c.sendAlert(alertInternalError) 829 return err 830 } 831 if ckx != nil { 832 if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil { 833 return err 834 } 835 } 836 837 if hs.serverHello.extendedMasterSecret { 838 c.extMasterSecret = true 839 hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, 840 hs.finishedHash.Sum()) 841 } else { 842 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, 843 hs.hello.random, hs.serverHello.random) 844 } 845 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil { 846 c.sendAlert(alertInternalError) 847 return errors.New("tls: failed to write to key log: " + err.Error()) 848 } 849 850 if chainToSend != nil && len(chainToSend.Certificate) > 0 { 851 certVerify := &certificateVerifyMsg{} 852 853 key, ok := chainToSend.PrivateKey.(crypto.Signer) 854 if !ok { 855 c.sendAlert(alertInternalError) 856 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey) 857 } 858 859 var sigType uint8 860 var sigHash crypto.Hash 861 if c.vers >= VersionTLS12 { 862 signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms) 863 if err != nil { 864 c.sendAlert(alertIllegalParameter) 865 return err 866 } 867 sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm) 868 if err != nil { 869 return c.sendAlert(alertInternalError) 870 } 871 certVerify.hasSignatureAlgorithm = true 872 certVerify.signatureAlgorithm = signatureAlgorithm 873 } else { 874 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public()) 875 if err != nil { 876 c.sendAlert(alertIllegalParameter) 877 return err 878 } 879 } 880 881 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash) 882 signOpts := crypto.SignerOpts(sigHash) 883 if sigType == signatureRSAPSS { 884 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 885 } 886 certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts) 887 if err != nil { 888 c.sendAlert(alertInternalError) 889 return err 890 } 891 892 if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil { 893 return err 894 } 895 } 896 897 hs.finishedHash.discardHandshakeBuffer() 898 899 return nil 900 } 901 902 func (hs *clientHandshakeState) establishKeys() error { 903 c := hs.c 904 905 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := 906 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) 907 var clientCipher, serverCipher any 908 var clientHash, serverHash hash.Hash 909 if hs.suite.cipher != nil { 910 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) 911 clientHash = hs.suite.mac(clientMAC) 912 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) 913 serverHash = hs.suite.mac(serverMAC) 914 } else { 915 clientCipher = hs.suite.aead(clientKey, clientIV) 916 serverCipher = hs.suite.aead(serverKey, serverIV) 917 } 918 919 c.in.key, c.in.iv = serverKey, serverIV 920 c.out.key, c.out.iv = clientKey, clientIV 921 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash) 922 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash) 923 return nil 924 } 925 926 func (hs *clientHandshakeState) serverResumedSession() bool { 927 // If the server responded with the same sessionId then it means the 928 // sessionTicket is being used to resume a TLS session. 929 return hs.session != nil && hs.hello.sessionId != nil && 930 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) 931 } 932 933 func (hs *clientHandshakeState) processServerHello() (bool, error) { 934 c := hs.c 935 936 if err := hs.pickCipherSuite(); err != nil { 937 return false, err 938 } 939 940 if hs.serverHello.compressionMethod != compressionNone { 941 c.sendAlert(alertUnexpectedMessage) 942 return false, errors.New("tls: server selected unsupported compression format") 943 } 944 945 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported { 946 c.secureRenegotiation = true 947 if len(hs.serverHello.secureRenegotiation) != 0 { 948 c.sendAlert(alertHandshakeFailure) 949 return false, errors.New("tls: initial handshake had non-empty renegotiation extension") 950 } 951 } 952 953 if c.handshakes > 0 && c.secureRenegotiation { 954 var expectedSecureRenegotiation [24]byte 955 copy(expectedSecureRenegotiation[:], c.clientFinished[:]) 956 copy(expectedSecureRenegotiation[12:], c.serverFinished[:]) 957 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) { 958 c.sendAlert(alertHandshakeFailure) 959 return false, errors.New("tls: incorrect renegotiation extension contents") 960 } 961 } 962 963 if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil { 964 c.sendAlert(alertUnsupportedExtension) 965 return false, err 966 } 967 c.clientProtocol = hs.serverHello.alpnProtocol 968 969 c.scts = hs.serverHello.scts 970 971 if !hs.serverResumedSession() { 972 return false, nil 973 } 974 975 if hs.session.version != c.vers { 976 c.sendAlert(alertHandshakeFailure) 977 return false, errors.New("tls: server resumed a session with a different version") 978 } 979 980 if hs.session.cipherSuite != hs.suite.id { 981 c.sendAlert(alertHandshakeFailure) 982 return false, errors.New("tls: server resumed a session with a different cipher suite") 983 } 984 985 // RFC 7627, Section 5.3 986 if hs.session.extMasterSecret != hs.serverHello.extendedMasterSecret { 987 c.sendAlert(alertHandshakeFailure) 988 return false, errors.New("tls: server resumed a session with a different EMS extension") 989 } 990 991 // Restore master secret and certificates from previous state 992 hs.masterSecret = hs.session.secret 993 c.extMasterSecret = hs.session.extMasterSecret 994 c.peerCertificates = hs.session.peerCertificates 995 c.activeCertHandles = hs.c.activeCertHandles 996 c.verifiedChains = hs.session.verifiedChains 997 c.ocspResponse = hs.session.ocspResponse 998 // Let the ServerHello SCTs override the session SCTs from the original 999 // connection, if any are provided 1000 if len(c.scts) == 0 && len(hs.session.scts) != 0 { 1001 c.scts = hs.session.scts 1002 } 1003 1004 return true, nil 1005 } 1006 1007 // checkALPN ensure that the server's choice of ALPN protocol is compatible with 1008 // the protocols that we advertised in the Client Hello. 1009 func checkALPN(clientProtos []string, serverProto string, quic bool) error { 1010 if serverProto == "" { 1011 if quic && len(clientProtos) > 0 { 1012 // RFC 9001, Section 8.1 1013 return errors.New("tls: server did not select an ALPN protocol") 1014 } 1015 return nil 1016 } 1017 if len(clientProtos) == 0 { 1018 return errors.New("tls: server advertised unrequested ALPN extension") 1019 } 1020 for _, proto := range clientProtos { 1021 if proto == serverProto { 1022 return nil 1023 } 1024 } 1025 return errors.New("tls: server selected unadvertised ALPN protocol") 1026 } 1027 1028 func (hs *clientHandshakeState) readFinished(out []byte) error { 1029 c := hs.c 1030 1031 if err := c.readChangeCipherSpec(); err != nil { 1032 return err 1033 } 1034 1035 // finishedMsg is included in the transcript, but not until after we 1036 // check the client version, since the state before this message was 1037 // sent is used during verification. 1038 msg, err := c.readHandshake(nil) 1039 if err != nil { 1040 return err 1041 } 1042 serverFinished, ok := msg.(*finishedMsg) 1043 if !ok { 1044 c.sendAlert(alertUnexpectedMessage) 1045 return unexpectedMessageError(serverFinished, msg) 1046 } 1047 1048 verify := hs.finishedHash.serverSum(hs.masterSecret) 1049 if len(verify) != len(serverFinished.verifyData) || 1050 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { 1051 c.sendAlert(alertHandshakeFailure) 1052 return errors.New("tls: server's Finished message was incorrect") 1053 } 1054 1055 if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil { 1056 return err 1057 } 1058 1059 copy(out, verify) 1060 return nil 1061 } 1062 1063 func (hs *clientHandshakeState) readSessionTicket() error { 1064 if !hs.serverHello.ticketSupported { 1065 return nil 1066 } 1067 c := hs.c 1068 1069 if !hs.hello.ticketSupported { 1070 c.sendAlert(alertIllegalParameter) 1071 return errors.New("tls: server sent unrequested session ticket") 1072 } 1073 1074 msg, err := c.readHandshake(&hs.finishedHash) 1075 if err != nil { 1076 return err 1077 } 1078 sessionTicketMsg, ok := msg.(*newSessionTicketMsg) 1079 if !ok { 1080 c.sendAlert(alertUnexpectedMessage) 1081 return unexpectedMessageError(sessionTicketMsg, msg) 1082 } 1083 1084 hs.ticket = sessionTicketMsg.ticket 1085 return nil 1086 } 1087 1088 func (hs *clientHandshakeState) saveSessionTicket() error { 1089 if hs.ticket == nil { 1090 return nil 1091 } 1092 c := hs.c 1093 1094 cacheKey := c.clientSessionCacheKey() 1095 if cacheKey == "" { 1096 return nil 1097 } 1098 1099 session, err := c.sessionState() 1100 if err != nil { 1101 return err 1102 } 1103 session.secret = hs.masterSecret 1104 1105 cs := &ClientSessionState{ticket: hs.ticket, session: session} 1106 c.config.ClientSessionCache.Put(cacheKey, cs) 1107 return nil 1108 } 1109 1110 func (hs *clientHandshakeState) sendFinished(out []byte) error { 1111 c := hs.c 1112 1113 if err := c.writeChangeCipherRecord(); err != nil { 1114 return err 1115 } 1116 1117 finished := new(finishedMsg) 1118 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) 1119 if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil { 1120 return err 1121 } 1122 copy(out, finished.verifyData) 1123 return nil 1124 } 1125 1126 func (hs *clientHandshakeState) sendClientData() error { 1127 c := hs.c 1128 defer c.earlyData.Reset() 1129 1130 if c.earlyData.Len() == 0 { 1131 return nil 1132 } 1133 1134 _, err := c.writeRecordLocked(recordTypeApplicationData, c.earlyData.Bytes()) 1135 return err 1136 } 1137 1138 // defaultMaxRSAKeySize is the maximum RSA key size in bits that we are willing 1139 // to verify the signatures of during a TLS handshake. 1140 const defaultMaxRSAKeySize = 8192 1141 1142 func checkKeySize(n int) (max int, ok bool) { 1143 return defaultMaxRSAKeySize, n <= defaultMaxRSAKeySize 1144 } 1145 1146 // verifyServerCertificate parses and verifies the provided chain, setting 1147 // c.verifiedChains and c.peerCertificates or sending the appropriate alert. 1148 func (c *Conn) verifyServerCertificate(certificates [][]byte) error { 1149 activeHandles := make([]*activeCert, len(certificates)) 1150 certs := make([]*x509.Certificate, len(certificates)) 1151 for i, asn1Data := range certificates { 1152 cert, err := globalCertCache.newCert(asn1Data) 1153 if err != nil { 1154 c.sendAlert(alertBadCertificate) 1155 return errors.New("tls: failed to parse certificate from server: " + err.Error()) 1156 } 1157 if cert.cert.PublicKeyAlgorithm == x509.RSA { 1158 n := cert.cert.PublicKey.(*rsa.PublicKey).N.BitLen() 1159 if max, ok := checkKeySize(n); !ok { 1160 c.sendAlert(alertBadCertificate) 1161 return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", max) 1162 } 1163 } 1164 activeHandles[i] = cert 1165 certs[i] = cert.cert 1166 } 1167 1168 if !c.config.InsecureSkipVerify { 1169 dnsName := c.config.ServerName 1170 if c.ech.offered && !c.ech.accepted { 1171 dnsName = c.serverName 1172 } 1173 1174 opts := x509.VerifyOptions{ 1175 Roots: c.config.RootCAs, 1176 CurrentTime: c.config.time(), 1177 DNSName: dnsName, 1178 Intermediates: x509.NewCertPool(), 1179 } 1180 1181 for _, cert := range certs[1:] { 1182 opts.Intermediates.AddCert(cert) 1183 } 1184 var err error 1185 c.verifiedChains, err = certs[0].Verify(opts) 1186 if err != nil { 1187 c.sendAlert(alertBadCertificate) 1188 return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err} 1189 } 1190 } 1191 1192 switch certs[0].PublicKey.(type) { 1193 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey: 1194 break 1195 default: 1196 c.sendAlert(alertUnsupportedCertificate) 1197 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey) 1198 } 1199 1200 c.activeCertHandles = activeHandles 1201 c.peerCertificates = certs 1202 1203 if c.config.VerifyPeerCertificate != nil { 1204 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { 1205 c.sendAlert(alertBadCertificate) 1206 return err 1207 } 1208 } 1209 1210 if c.config.VerifyConnection != nil { 1211 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 1212 c.sendAlert(alertBadCertificate) 1213 return err 1214 } 1215 } 1216 1217 return nil 1218 } 1219 1220 // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS 1221 // <= 1.2 CertificateRequest, making an effort to fill in missing information. 1222 func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo { 1223 cri := &CertificateRequestInfo{ 1224 AcceptableCAs: certReq.certificateAuthorities, 1225 Version: vers, 1226 ctx: ctx, 1227 } 1228 1229 var rsaAvail, ecAvail bool 1230 for _, certType := range certReq.certificateTypes { 1231 switch certType { 1232 case certTypeRSASign: 1233 rsaAvail = true 1234 case certTypeECDSASign: 1235 ecAvail = true 1236 } 1237 } 1238 1239 if !certReq.hasSignatureAlgorithm { 1240 // Prior to TLS 1.2, signature schemes did not exist. In this case we 1241 // make up a list based on the acceptable certificate types, to help 1242 // GetClientCertificate and SupportsCertificate select the right certificate. 1243 // The hash part of the SignatureScheme is a lie here, because 1244 // TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA. 1245 switch { 1246 case rsaAvail && ecAvail: 1247 cri.SignatureSchemes = []SignatureScheme{ 1248 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, 1249 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1, 1250 } 1251 case rsaAvail: 1252 cri.SignatureSchemes = []SignatureScheme{ 1253 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1, 1254 } 1255 case ecAvail: 1256 cri.SignatureSchemes = []SignatureScheme{ 1257 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, 1258 } 1259 } 1260 return cri 1261 } 1262 1263 // Filter the signature schemes based on the certificate types. 1264 // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated"). 1265 cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms)) 1266 for _, sigScheme := range certReq.supportedSignatureAlgorithms { 1267 sigType, _, err := typeAndHashFromSignatureScheme(sigScheme) 1268 if err != nil { 1269 continue 1270 } 1271 switch sigType { 1272 case signatureECDSA, signatureEd25519: 1273 if ecAvail { 1274 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme) 1275 } 1276 case signatureRSAPSS, signaturePKCS1v15: 1277 if rsaAvail { 1278 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme) 1279 } 1280 } 1281 } 1282 1283 return cri 1284 } 1285 1286 func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) { 1287 if c.config.GetClientCertificate != nil { 1288 return c.config.GetClientCertificate(cri) 1289 } 1290 1291 for _, chain := range c.config.Certificates { 1292 if err := cri.SupportsCertificate(&chain); err != nil { 1293 continue 1294 } 1295 return &chain, nil 1296 } 1297 1298 // No acceptable certificate found. Don't send a certificate. 1299 return new(Certificate), nil 1300 } 1301 1302 // clientSessionCacheKey returns a key used to cache sessionTickets that could 1303 // be used to resume previously negotiated TLS sessions with a server. 1304 func (c *Conn) clientSessionCacheKey() string { 1305 if len(c.config.ServerName) > 0 { 1306 return c.config.ServerName 1307 } 1308 if c.conn != nil { 1309 return c.conn.RemoteAddr().String() 1310 } 1311 return "" 1312 } 1313 1314 // hostnameInSNI converts name into an appropriate hostname for SNI. 1315 // Literal IP addresses and absolute FQDNs are not permitted as SNI values. 1316 // See RFC 6066, Section 3. 1317 func hostnameInSNI(name string) string { 1318 host := name 1319 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' { 1320 host = host[1 : len(host)-1] 1321 } 1322 if i := strings.LastIndex(host, "%"); i > 0 { 1323 host = host[:i] 1324 } 1325 if net.ParseIP(host) != nil { 1326 return "" 1327 } 1328 for len(name) > 0 && name[len(name)-1] == '.' { 1329 name = name[:len(name)-1] 1330 } 1331 return name 1332 }