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