github.com/FISCO-BCOS/crypto@v0.0.0-20200202032121-bd8ab0b5d4f1/tls/handshake_server.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 "crypto" 9 "github.com/FISCO-BCOS/crypto/ecdsa" 10 "crypto/ed25519" 11 "crypto/rsa" 12 "crypto/subtle" 13 "github.com/FISCO-BCOS/crypto/x509" 14 "errors" 15 "fmt" 16 "io" 17 "sync/atomic" 18 ) 19 20 // serverHandshakeState contains details of a server handshake in progress. 21 // It's discarded once the handshake has completed. 22 type serverHandshakeState struct { 23 c *Conn 24 clientHello *clientHelloMsg 25 hello *serverHelloMsg 26 suite *cipherSuite 27 ecdhOk bool 28 ecSignOk bool 29 rsaDecryptOk bool 30 rsaSignOk bool 31 sessionState *sessionState 32 finishedHash finishedHash 33 masterSecret []byte 34 cert *Certificate 35 } 36 37 // serverHandshake performs a TLS handshake as a server. 38 func (c *Conn) serverHandshake() error { 39 // If this is the first server handshake, we generate a random key to 40 // encrypt the tickets with. 41 c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) }) 42 43 clientHello, err := c.readClientHello() 44 if err != nil { 45 return err 46 } 47 48 if c.vers == VersionTLS13 { 49 hs := serverHandshakeStateTLS13{ 50 c: c, 51 clientHello: clientHello, 52 } 53 return hs.handshake() 54 } 55 56 hs := serverHandshakeState{ 57 c: c, 58 clientHello: clientHello, 59 } 60 return hs.handshake() 61 } 62 63 func (hs *serverHandshakeState) handshake() error { 64 c := hs.c 65 66 if err := hs.processClientHello(); err != nil { 67 return err 68 } 69 70 // For an overview of TLS handshaking, see RFC 5246, Section 7.3. 71 c.buffering = true 72 if hs.checkForResumption() { 73 // The client has included a session ticket and so we do an abbreviated handshake. 74 if err := hs.doResumeHandshake(); err != nil { 75 return err 76 } 77 if err := hs.establishKeys(); err != nil { 78 return err 79 } 80 // ticketSupported is set in a resumption handshake if the 81 // ticket from the client was encrypted with an old session 82 // ticket key and thus a refreshed ticket should be sent. 83 if hs.hello.ticketSupported { 84 if err := hs.sendSessionTicket(); err != nil { 85 return err 86 } 87 } 88 if err := hs.sendFinished(c.serverFinished[:]); err != nil { 89 return err 90 } 91 if _, err := c.flush(); err != nil { 92 return err 93 } 94 c.clientFinishedIsFirst = false 95 if err := hs.readFinished(nil); err != nil { 96 return err 97 } 98 c.didResume = true 99 } else { 100 // The client didn't include a session ticket, or it wasn't 101 // valid so we do a full handshake. 102 if err := hs.pickCipherSuite(); err != nil { 103 return err 104 } 105 if err := hs.doFullHandshake(); err != nil { 106 return err 107 } 108 if err := hs.establishKeys(); err != nil { 109 return err 110 } 111 if err := hs.readFinished(c.clientFinished[:]); err != nil { 112 return err 113 } 114 c.clientFinishedIsFirst = true 115 c.buffering = true 116 if err := hs.sendSessionTicket(); err != nil { 117 return err 118 } 119 if err := hs.sendFinished(nil); err != nil { 120 return err 121 } 122 if _, err := c.flush(); err != nil { 123 return err 124 } 125 } 126 127 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random) 128 atomic.StoreUint32(&c.handshakeStatus, 1) 129 130 return nil 131 } 132 133 // readClientHello reads a ClientHello message and selects the protocol version. 134 func (c *Conn) readClientHello() (*clientHelloMsg, error) { 135 msg, err := c.readHandshake() 136 if err != nil { 137 return nil, err 138 } 139 clientHello, ok := msg.(*clientHelloMsg) 140 if !ok { 141 c.sendAlert(alertUnexpectedMessage) 142 return nil, unexpectedMessageError(clientHello, msg) 143 } 144 145 if c.config.GetConfigForClient != nil { 146 chi := clientHelloInfo(c, clientHello) 147 if newConfig, err := c.config.GetConfigForClient(chi); err != nil { 148 c.sendAlert(alertInternalError) 149 return nil, err 150 } else if newConfig != nil { 151 newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) }) 152 c.config = newConfig 153 } 154 } 155 156 clientVersions := clientHello.supportedVersions 157 if len(clientHello.supportedVersions) == 0 { 158 clientVersions = supportedVersionsFromMax(clientHello.vers) 159 } 160 c.vers, ok = c.config.mutualVersion(false, clientVersions) 161 if !ok { 162 c.sendAlert(alertProtocolVersion) 163 return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions) 164 } 165 c.haveVers = true 166 c.in.version = c.vers 167 c.out.version = c.vers 168 169 return clientHello, nil 170 } 171 172 func (hs *serverHandshakeState) processClientHello() error { 173 c := hs.c 174 175 hs.hello = new(serverHelloMsg) 176 hs.hello.vers = c.vers 177 178 supportedCurve := false 179 preferredCurves := c.config.curvePreferences() 180 Curves: 181 for _, curve := range hs.clientHello.supportedCurves { 182 for _, supported := range preferredCurves { 183 if supported == curve { 184 supportedCurve = true 185 break Curves 186 } 187 } 188 } 189 190 supportedPointFormat := false 191 for _, pointFormat := range hs.clientHello.supportedPoints { 192 if pointFormat == pointFormatUncompressed { 193 supportedPointFormat = true 194 break 195 } 196 } 197 hs.ecdhOk = supportedCurve && supportedPointFormat 198 199 foundCompression := false 200 // We only support null compression, so check that the client offered it. 201 for _, compression := range hs.clientHello.compressionMethods { 202 if compression == compressionNone { 203 foundCompression = true 204 break 205 } 206 } 207 208 if !foundCompression { 209 c.sendAlert(alertHandshakeFailure) 210 return errors.New("tls: client does not support uncompressed connections") 211 } 212 213 hs.hello.random = make([]byte, 32) 214 serverRandom := hs.hello.random 215 // Downgrade protection canaries. See RFC 8446, Section 4.1.3. 216 maxVers := c.config.maxSupportedVersion(false) 217 if maxVers >= VersionTLS12 && c.vers < maxVers { 218 if c.vers == VersionTLS12 { 219 copy(serverRandom[24:], downgradeCanaryTLS12) 220 } else { 221 copy(serverRandom[24:], downgradeCanaryTLS11) 222 } 223 serverRandom = serverRandom[:24] 224 } 225 _, err := io.ReadFull(c.config.rand(), serverRandom) 226 if err != nil { 227 c.sendAlert(alertInternalError) 228 return err 229 } 230 231 if len(hs.clientHello.secureRenegotiation) != 0 { 232 c.sendAlert(alertHandshakeFailure) 233 return errors.New("tls: initial handshake had non-empty renegotiation extension") 234 } 235 236 hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported 237 hs.hello.compressionMethod = compressionNone 238 if len(hs.clientHello.serverName) > 0 { 239 c.serverName = hs.clientHello.serverName 240 } 241 242 if len(hs.clientHello.alpnProtocols) > 0 { 243 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback { 244 hs.hello.alpnProtocol = selectedProto 245 c.clientProtocol = selectedProto 246 } 247 } else { 248 // Although sending an empty NPN extension is reasonable, Firefox has 249 // had a bug around this. Best to send nothing at all if 250 // c.config.NextProtos is empty. See 251 // https://golang.org/issue/5445. 252 if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 { 253 hs.hello.nextProtoNeg = true 254 hs.hello.nextProtos = c.config.NextProtos 255 } 256 } 257 258 hs.cert, err = c.config.getCertificate(clientHelloInfo(c, hs.clientHello)) 259 if err != nil { 260 c.sendAlert(alertInternalError) 261 return err 262 } 263 if hs.clientHello.scts { 264 hs.hello.scts = hs.cert.SignedCertificateTimestamps 265 } 266 267 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok { 268 switch priv.Public().(type) { 269 case *ecdsa.PublicKey: 270 hs.ecSignOk = true 271 case ed25519.PublicKey: 272 hs.ecSignOk = true 273 case *rsa.PublicKey: 274 hs.rsaSignOk = true 275 default: 276 c.sendAlert(alertInternalError) 277 return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public()) 278 } 279 } 280 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok { 281 switch priv.Public().(type) { 282 case *rsa.PublicKey: 283 hs.rsaDecryptOk = true 284 default: 285 c.sendAlert(alertInternalError) 286 return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public()) 287 } 288 } 289 290 return nil 291 } 292 293 func (hs *serverHandshakeState) pickCipherSuite() error { 294 c := hs.c 295 296 var preferenceList, supportedList []uint16 297 if c.config.PreferServerCipherSuites { 298 preferenceList = c.config.cipherSuites() 299 supportedList = hs.clientHello.cipherSuites 300 } else { 301 preferenceList = hs.clientHello.cipherSuites 302 supportedList = c.config.cipherSuites() 303 } 304 305 for _, id := range preferenceList { 306 if hs.setCipherSuite(id, supportedList, c.vers) { 307 break 308 } 309 } 310 311 if hs.suite == nil { 312 c.sendAlert(alertHandshakeFailure) 313 return errors.New("tls: no cipher suite supported by both client and server") 314 } 315 316 for _, id := range hs.clientHello.cipherSuites { 317 if id == TLS_FALLBACK_SCSV { 318 // The client is doing a fallback connection. See RFC 7507. 319 if hs.clientHello.vers < c.config.maxSupportedVersion(false) { 320 c.sendAlert(alertInappropriateFallback) 321 return errors.New("tls: client using inappropriate protocol fallback") 322 } 323 break 324 } 325 } 326 327 return nil 328 } 329 330 // checkForResumption reports whether we should perform resumption on this connection. 331 func (hs *serverHandshakeState) checkForResumption() bool { 332 c := hs.c 333 334 if c.config.SessionTicketsDisabled { 335 return false 336 } 337 338 plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket) 339 if plaintext == nil { 340 return false 341 } 342 hs.sessionState = &sessionState{usedOldKey: usedOldKey} 343 ok := hs.sessionState.unmarshal(plaintext) 344 if !ok { 345 return false 346 } 347 348 // Never resume a session for a different TLS version. 349 if c.vers != hs.sessionState.vers { 350 return false 351 } 352 353 cipherSuiteOk := false 354 // Check that the client is still offering the ciphersuite in the session. 355 for _, id := range hs.clientHello.cipherSuites { 356 if id == hs.sessionState.cipherSuite { 357 cipherSuiteOk = true 358 break 359 } 360 } 361 if !cipherSuiteOk { 362 return false 363 } 364 365 // Check that we also support the ciphersuite from the session. 366 if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) { 367 return false 368 } 369 370 sessionHasClientCerts := len(hs.sessionState.certificates) != 0 371 needClientCerts := requiresClientCert(c.config.ClientAuth) 372 if needClientCerts && !sessionHasClientCerts { 373 return false 374 } 375 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 376 return false 377 } 378 379 return true 380 } 381 382 func (hs *serverHandshakeState) doResumeHandshake() error { 383 c := hs.c 384 385 hs.hello.cipherSuite = hs.suite.id 386 // We echo the client's session ID in the ServerHello to let it know 387 // that we're doing a resumption. 388 hs.hello.sessionId = hs.clientHello.sessionId 389 hs.hello.ticketSupported = hs.sessionState.usedOldKey 390 hs.finishedHash = newFinishedHash(c.vers, hs.suite) 391 hs.finishedHash.discardHandshakeBuffer() 392 hs.finishedHash.Write(hs.clientHello.marshal()) 393 hs.finishedHash.Write(hs.hello.marshal()) 394 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 395 return err 396 } 397 398 if err := c.processCertsFromClient(Certificate{ 399 Certificate: hs.sessionState.certificates, 400 }); err != nil { 401 return err 402 } 403 404 hs.masterSecret = hs.sessionState.masterSecret 405 406 return nil 407 } 408 409 func (hs *serverHandshakeState) doFullHandshake() error { 410 c := hs.c 411 412 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 { 413 hs.hello.ocspStapling = true 414 } 415 416 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled 417 hs.hello.cipherSuite = hs.suite.id 418 419 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite) 420 if c.config.ClientAuth == NoClientCert { 421 // No need to keep a full record of the handshake if client 422 // certificates won't be used. 423 hs.finishedHash.discardHandshakeBuffer() 424 } 425 hs.finishedHash.Write(hs.clientHello.marshal()) 426 hs.finishedHash.Write(hs.hello.marshal()) 427 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 428 return err 429 } 430 431 certMsg := new(certificateMsg) 432 certMsg.certificates = hs.cert.Certificate 433 hs.finishedHash.Write(certMsg.marshal()) 434 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 435 return err 436 } 437 438 if hs.hello.ocspStapling { 439 certStatus := new(certificateStatusMsg) 440 certStatus.response = hs.cert.OCSPStaple 441 hs.finishedHash.Write(certStatus.marshal()) 442 if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil { 443 return err 444 } 445 } 446 447 keyAgreement := hs.suite.ka(c.vers) 448 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello) 449 if err != nil { 450 c.sendAlert(alertHandshakeFailure) 451 return err 452 } 453 if skx != nil { 454 hs.finishedHash.Write(skx.marshal()) 455 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil { 456 return err 457 } 458 } 459 460 var certReq *certificateRequestMsg 461 if c.config.ClientAuth >= RequestClientCert { 462 // Request a client certificate 463 certReq = new(certificateRequestMsg) 464 certReq.certificateTypes = []byte{ 465 byte(certTypeRSASign), 466 byte(certTypeECDSASign), 467 } 468 if c.vers >= VersionTLS12 { 469 certReq.hasSignatureAlgorithm = true 470 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithmsTLS12 471 } 472 473 // An empty list of certificateAuthorities signals to 474 // the client that it may send any certificate in response 475 // to our request. When we know the CAs we trust, then 476 // we can send them down, so that the client can choose 477 // an appropriate certificate to give to us. 478 if c.config.ClientCAs != nil { 479 certReq.certificateAuthorities = c.config.ClientCAs.Subjects() 480 } 481 hs.finishedHash.Write(certReq.marshal()) 482 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil { 483 return err 484 } 485 } 486 487 helloDone := new(serverHelloDoneMsg) 488 hs.finishedHash.Write(helloDone.marshal()) 489 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil { 490 return err 491 } 492 493 if _, err := c.flush(); err != nil { 494 return err 495 } 496 497 var pub crypto.PublicKey // public key for client auth, if any 498 499 msg, err := c.readHandshake() 500 if err != nil { 501 return err 502 } 503 504 // If we requested a client certificate, then the client must send a 505 // certificate message, even if it's empty. 506 if c.config.ClientAuth >= RequestClientCert { 507 certMsg, ok := msg.(*certificateMsg) 508 if !ok { 509 c.sendAlert(alertUnexpectedMessage) 510 return unexpectedMessageError(certMsg, msg) 511 } 512 hs.finishedHash.Write(certMsg.marshal()) 513 514 if err := c.processCertsFromClient(Certificate{ 515 Certificate: certMsg.certificates, 516 }); err != nil { 517 return err 518 } 519 if len(certMsg.certificates) != 0 { 520 pub = c.peerCertificates[0].PublicKey 521 } 522 523 msg, err = c.readHandshake() 524 if err != nil { 525 return err 526 } 527 } 528 529 // Get client key exchange 530 ckx, ok := msg.(*clientKeyExchangeMsg) 531 if !ok { 532 c.sendAlert(alertUnexpectedMessage) 533 return unexpectedMessageError(ckx, msg) 534 } 535 hs.finishedHash.Write(ckx.marshal()) 536 537 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers) 538 if err != nil { 539 c.sendAlert(alertHandshakeFailure) 540 return err 541 } 542 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random) 543 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil { 544 c.sendAlert(alertInternalError) 545 return err 546 } 547 548 // If we received a client cert in response to our certificate request message, 549 // the client will send us a certificateVerifyMsg immediately after the 550 // clientKeyExchangeMsg. This message is a digest of all preceding 551 // handshake-layer messages that is signed using the private key corresponding 552 // to the client's certificate. This allows us to verify that the client is in 553 // possession of the private key of the certificate. 554 if len(c.peerCertificates) > 0 { 555 msg, err = c.readHandshake() 556 if err != nil { 557 return err 558 } 559 certVerify, ok := msg.(*certificateVerifyMsg) 560 if !ok { 561 c.sendAlert(alertUnexpectedMessage) 562 return unexpectedMessageError(certVerify, msg) 563 } 564 565 // Determine the signature type. 566 _, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, certReq.supportedSignatureAlgorithms, c.vers) 567 if err != nil { 568 c.sendAlert(alertIllegalParameter) 569 return err 570 } 571 572 signed, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret) 573 if err == nil { 574 err = verifyHandshakeSignature(sigType, pub, hashFunc, signed, certVerify.signature) 575 } 576 if err != nil { 577 c.sendAlert(alertBadCertificate) 578 return errors.New("tls: could not validate signature of connection nonces: " + err.Error()) 579 } 580 581 hs.finishedHash.Write(certVerify.marshal()) 582 } 583 584 hs.finishedHash.discardHandshakeBuffer() 585 586 return nil 587 } 588 589 func (hs *serverHandshakeState) establishKeys() error { 590 c := hs.c 591 592 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := 593 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) 594 595 var clientCipher, serverCipher interface{} 596 var clientHash, serverHash macFunction 597 598 if hs.suite.aead == nil { 599 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */) 600 clientHash = hs.suite.mac(c.vers, clientMAC) 601 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */) 602 serverHash = hs.suite.mac(c.vers, serverMAC) 603 } else { 604 clientCipher = hs.suite.aead(clientKey, clientIV) 605 serverCipher = hs.suite.aead(serverKey, serverIV) 606 } 607 608 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash) 609 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash) 610 611 return nil 612 } 613 614 func (hs *serverHandshakeState) readFinished(out []byte) error { 615 c := hs.c 616 617 if err := c.readChangeCipherSpec(); err != nil { 618 return err 619 } 620 621 if hs.hello.nextProtoNeg { 622 msg, err := c.readHandshake() 623 if err != nil { 624 return err 625 } 626 nextProto, ok := msg.(*nextProtoMsg) 627 if !ok { 628 c.sendAlert(alertUnexpectedMessage) 629 return unexpectedMessageError(nextProto, msg) 630 } 631 hs.finishedHash.Write(nextProto.marshal()) 632 c.clientProtocol = nextProto.proto 633 } 634 635 msg, err := c.readHandshake() 636 if err != nil { 637 return err 638 } 639 clientFinished, ok := msg.(*finishedMsg) 640 if !ok { 641 c.sendAlert(alertUnexpectedMessage) 642 return unexpectedMessageError(clientFinished, msg) 643 } 644 645 verify := hs.finishedHash.clientSum(hs.masterSecret) 646 if len(verify) != len(clientFinished.verifyData) || 647 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { 648 c.sendAlert(alertHandshakeFailure) 649 return errors.New("tls: client's Finished message is incorrect") 650 } 651 652 hs.finishedHash.Write(clientFinished.marshal()) 653 copy(out, verify) 654 return nil 655 } 656 657 func (hs *serverHandshakeState) sendSessionTicket() error { 658 if !hs.hello.ticketSupported { 659 return nil 660 } 661 662 c := hs.c 663 m := new(newSessionTicketMsg) 664 665 var certsFromClient [][]byte 666 for _, cert := range c.peerCertificates { 667 certsFromClient = append(certsFromClient, cert.Raw) 668 } 669 state := sessionState{ 670 vers: c.vers, 671 cipherSuite: hs.suite.id, 672 masterSecret: hs.masterSecret, 673 certificates: certsFromClient, 674 } 675 var err error 676 m.ticket, err = c.encryptTicket(state.marshal()) 677 if err != nil { 678 return err 679 } 680 681 hs.finishedHash.Write(m.marshal()) 682 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { 683 return err 684 } 685 686 return nil 687 } 688 689 func (hs *serverHandshakeState) sendFinished(out []byte) error { 690 c := hs.c 691 692 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { 693 return err 694 } 695 696 finished := new(finishedMsg) 697 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret) 698 hs.finishedHash.Write(finished.marshal()) 699 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { 700 return err 701 } 702 703 c.cipherSuite = hs.suite.id 704 copy(out, finished.verifyData) 705 706 return nil 707 } 708 709 // processCertsFromClient takes a chain of client certificates either from a 710 // Certificates message or from a sessionState and verifies them. It returns 711 // the public key of the leaf certificate. 712 func (c *Conn) processCertsFromClient(certificate Certificate) error { 713 certificates := certificate.Certificate 714 certs := make([]*x509.Certificate, len(certificates)) 715 var err error 716 for i, asn1Data := range certificates { 717 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil { 718 c.sendAlert(alertBadCertificate) 719 return errors.New("tls: failed to parse client certificate: " + err.Error()) 720 } 721 } 722 723 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) { 724 c.sendAlert(alertBadCertificate) 725 return errors.New("tls: client didn't provide a certificate") 726 } 727 728 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 { 729 opts := x509.VerifyOptions{ 730 Roots: c.config.ClientCAs, 731 CurrentTime: c.config.time(), 732 Intermediates: x509.NewCertPool(), 733 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, 734 } 735 736 for _, cert := range certs[1:] { 737 opts.Intermediates.AddCert(cert) 738 } 739 740 chains, err := certs[0].Verify(opts) 741 if err != nil { 742 c.sendAlert(alertBadCertificate) 743 return errors.New("tls: failed to verify client's certificate: " + err.Error()) 744 } 745 746 c.verifiedChains = chains 747 } 748 749 if c.config.VerifyPeerCertificate != nil { 750 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { 751 c.sendAlert(alertBadCertificate) 752 return err 753 } 754 } 755 756 if len(certs) == 0 { 757 return nil 758 } 759 760 switch certs[0].PublicKey.(type) { 761 case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey: 762 default: 763 c.sendAlert(alertUnsupportedCertificate) 764 return fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey) 765 } 766 767 c.peerCertificates = certs 768 c.ocspResponse = certificate.OCSPStaple 769 c.scts = certificate.SignedCertificateTimestamps 770 return nil 771 } 772 773 // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState 774 // suite if that cipher suite is acceptable to use. 775 // It returns a bool indicating if the suite was set. 776 func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool { 777 for _, supported := range supportedCipherSuites { 778 if id != supported { 779 continue 780 } 781 candidate := cipherSuiteByID(id) 782 if candidate == nil { 783 continue 784 } 785 // Don't select a ciphersuite which we can't 786 // support for this client. 787 if candidate.flags&suiteECDHE != 0 { 788 if !hs.ecdhOk { 789 continue 790 } 791 if candidate.flags&suiteECSign != 0 { 792 if !hs.ecSignOk { 793 continue 794 } 795 } else if !hs.rsaSignOk { 796 continue 797 } 798 } else if !hs.rsaDecryptOk { 799 continue 800 } 801 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 { 802 continue 803 } 804 hs.suite = candidate 805 return true 806 } 807 return false 808 } 809 810 func clientHelloInfo(c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo { 811 supportedVersions := clientHello.supportedVersions 812 if len(clientHello.supportedVersions) == 0 { 813 supportedVersions = supportedVersionsFromMax(clientHello.vers) 814 } 815 816 return &ClientHelloInfo{ 817 CipherSuites: clientHello.cipherSuites, 818 ServerName: clientHello.serverName, 819 SupportedCurves: clientHello.supportedCurves, 820 SupportedPoints: clientHello.supportedPoints, 821 SignatureSchemes: clientHello.supportedSignatureAlgorithms, 822 SupportedProtos: clientHello.alpnProtocols, 823 SupportedVersions: supportedVersions, 824 Conn: c.conn, 825 } 826 }