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