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