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