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