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.
25 type clientHandshakeState struct {
27 serverHello *serverHelloMsg
30 finishedHash finishedHash
32 session *ClientSessionState
35 func (c *Conn) makeClientHello() (*clientHelloMsg, ecdheParameters, error) {
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")
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")
46 nextProtosLength += 1 + l
49 if nextProtosLength > 0xffff {
50 return nil, nil, errors.New("tls: NextProtos values too large")
53 supportedVersions := config.supportedVersions()
54 if len(supportedVersions) == 0 {
55 return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
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
66 hello := &clientHelloMsg{
67 vers: clientHelloVersion,
68 compressionMethods: []uint8{compressionNone},
69 random: make([]byte, 32),
70 sessionId: make([]byte, 32),
73 serverName: hostnameInSNI(config.ServerName),
74 supportedCurves: config.curvePreferences(),
75 supportedPoints: []uint8{pointFormatUncompressed},
76 secureRenegotiationSupported: true,
77 alpnProtocols: config.NextProtos,
78 supportedVersions: supportedVersions,
82 hello.secureRenegotiation = c.clientFinished[:]
85 possibleCipherSuites := config.cipherSuites()
86 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
88 for _, suiteId := range possibleCipherSuites {
89 for _, suite := range cipherSuites {
90 if suite.id != suiteId {
93 // Don't advertise TLS 1.2-only cipher suites unless
94 // we're attempting TLS 1.2.
95 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
98 hello.cipherSuites = append(hello.cipherSuites, suiteId)
103 _, err := io.ReadFull(config.rand(), hello.random)
105 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
108 // A random session ID is used to detect when the server accepted a ticket
109 // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
110 // a compatibility measure (see RFC 8446, Section 4.1.2).
111 if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
112 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
115 if hello.vers >= VersionTLS12 {
116 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
118 if testingOnlyForceClientHelloSignatureAlgorithms != nil {
119 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
122 var params ecdheParameters
123 if hello.supportedVersions[0] == VersionTLS13 {
124 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13()...)
126 curveID := config.curvePreferences()[0]
127 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
128 return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
130 params, err = generateECDHEParameters(config.rand(), curveID)
134 hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
137 return hello, params, nil
140 func (c *Conn) clientHandshake() (err error) {
142 c.config = defaultConfig()
145 // This may be a renegotiation handshake, in which case some fields
149 hello, ecdheParams, err := c.makeClientHello()
154 cacheKey, session, earlySecret, binderKey := c.loadSession(hello)
155 if cacheKey != "" && session != nil {
157 // If we got a handshake failure when resuming a session, throw away
158 // the session ticket. See RFC 5077, Section 3.2.
160 // RFC 8446 makes no mention of dropping tickets on failure, but it
161 // does require servers to abort on invalid binders, so we need to
162 // delete tickets to recover from a corrupted PSK.
164 c.config.ClientSessionCache.Put(cacheKey, nil)
169 if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
173 msg, err := c.readHandshake()
178 serverHello, ok := msg.(*serverHelloMsg)
180 c.sendAlert(alertUnexpectedMessage)
181 return unexpectedMessageError(serverHello, msg)
184 if err := c.pickTLSVersion(serverHello); err != nil {
188 if c.vers == VersionTLS13 {
189 hs := &clientHandshakeStateTLS13{
191 serverHello: serverHello,
193 ecdheParams: ecdheParams,
195 earlySecret: earlySecret,
196 binderKey: binderKey,
199 // In TLS 1.3, session tickets are delivered after the handshake.
200 return hs.handshake()
203 hs := &clientHandshakeState{
205 serverHello: serverHello,
210 if err := hs.handshake(); err != nil {
214 // If we had a successful handshake and hs.session is different from
215 // the one already cached - cache a new one.
216 if cacheKey != "" && hs.session != nil && session != hs.session {
217 c.config.ClientSessionCache.Put(cacheKey, hs.session)
223 func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
224 session *ClientSessionState, earlySecret, binderKey []byte) {
225 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
226 return "", nil, nil, nil
229 hello.ticketSupported = true
231 if hello.supportedVersions[0] == VersionTLS13 {
232 // Require DHE on resumption as it guarantees forward secrecy against
233 // compromise of the session ticket key. See RFC 8446, Section 4.2.9.
234 hello.pskModes = []uint8{pskModeDHE}
237 // Session resumption is not allowed if renegotiating because
238 // renegotiation is primarily used to allow a client to send a client
239 // certificate, which would be skipped if session resumption occurred.
240 if c.handshakes != 0 {
241 return "", nil, nil, nil
244 // Try to resume a previously negotiated TLS session, if available.
245 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
246 session, ok := c.config.ClientSessionCache.Get(cacheKey)
247 if !ok || session == nil {
248 return cacheKey, nil, nil, nil
251 // Check that version used for the previous session is still valid.
253 for _, v := range hello.supportedVersions {
254 if v == session.vers {
260 return cacheKey, nil, nil, nil
263 // Check that the cached server certificate is not expired, and that it's
264 // valid for the ServerName. This should be ensured by the cache key, but
265 // protect the application from a faulty ClientSessionCache implementation.
266 if !c.config.InsecureSkipVerify {
267 if len(session.verifiedChains) == 0 {
268 // The original connection had InsecureSkipVerify, while this doesn't.
269 return cacheKey, nil, nil, nil
271 serverCert := session.serverCertificates[0]
272 if c.config.time().After(serverCert.NotAfter) {
273 // Expired certificate, delete the entry.
274 c.config.ClientSessionCache.Put(cacheKey, nil)
275 return cacheKey, nil, nil, nil
277 if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
278 return cacheKey, nil, nil, nil
282 if session.vers != VersionTLS13 {
283 // In TLS 1.2 the cipher suite must match the resumed session. Ensure we
284 // are still offering it.
285 if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
286 return cacheKey, nil, nil, nil
289 hello.sessionTicket = session.sessionTicket
293 // Check that the session ticket is not expired.
294 if c.config.time().After(session.useBy) {
295 c.config.ClientSessionCache.Put(cacheKey, nil)
296 return cacheKey, nil, nil, nil
299 // In TLS 1.3 the KDF hash must match the resumed session. Ensure we
300 // offer at least one cipher suite with that hash.
301 cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
302 if cipherSuite == nil {
303 return cacheKey, nil, nil, nil
305 cipherSuiteOk := false
306 for _, offeredID := range hello.cipherSuites {
307 offeredSuite := cipherSuiteTLS13ByID(offeredID)
308 if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
314 return cacheKey, nil, nil, nil
317 // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
318 ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
319 identity := pskIdentity{
320 label: session.sessionTicket,
321 obfuscatedTicketAge: ticketAge + session.ageAdd,
323 hello.pskIdentities = []pskIdentity{identity}
324 hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
326 // Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
327 psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
328 session.nonce, cipherSuite.hash.Size())
329 earlySecret = cipherSuite.extract(psk, nil)
330 binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
331 transcript := cipherSuite.hash.New()
332 transcript.Write(hello.marshalWithoutBinders())
333 pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
334 hello.updateBinders(pskBinders)
339 func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
340 peerVersion := serverHello.vers
341 if serverHello.supportedVersion != 0 {
342 peerVersion = serverHello.supportedVersion
345 vers, ok := c.config.mutualVersion([]uint16{peerVersion})
347 c.sendAlert(alertProtocolVersion)
348 return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
359 // Does the handshake, either a full one or resumes old session. Requires hs.c,
360 // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
361 func (hs *clientHandshakeState) handshake() error {
364 isResume, err := hs.processServerHello()
369 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
371 // No signatures of the handshake are needed in a resumption.
372 // Otherwise, in a full handshake, if we don't have any certificates
373 // configured then we will never send a CertificateVerify message and
374 // thus no signatures are needed in that case either.
375 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
376 hs.finishedHash.discardHandshakeBuffer()
379 hs.finishedHash.Write(hs.hello.marshal())
380 hs.finishedHash.Write(hs.serverHello.marshal())
384 if err := hs.establishKeys(); err != nil {
387 if err := hs.readSessionTicket(); err != nil {
390 if err := hs.readFinished(c.serverFinished[:]); err != nil {
393 c.clientFinishedIsFirst = false
394 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
397 if _, err := c.flush(); err != nil {
401 if err := hs.doFullHandshake(); err != nil {
404 if err := hs.establishKeys(); err != nil {
407 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
410 if _, err := c.flush(); err != nil {
413 c.clientFinishedIsFirst = true
414 if err := hs.readSessionTicket(); err != nil {
417 if err := hs.readFinished(c.serverFinished[:]); err != nil {
422 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
423 c.didResume = isResume
424 atomic.StoreUint32(&c.handshakeStatus, 1)
429 func (hs *clientHandshakeState) pickCipherSuite() error {
430 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
431 hs.c.sendAlert(alertHandshakeFailure)
432 return errors.New("tls: server chose an unconfigured cipher suite")
435 hs.c.cipherSuite = hs.suite.id
439 func (hs *clientHandshakeState) doFullHandshake() error {
442 msg, err := c.readHandshake()
446 certMsg, ok := msg.(*certificateMsg)
447 if !ok || len(certMsg.certificates) == 0 {
448 c.sendAlert(alertUnexpectedMessage)
449 return unexpectedMessageError(certMsg, msg)
451 hs.finishedHash.Write(certMsg.marshal())
453 if c.handshakes == 0 {
454 // If this is the first handshake on a connection, process and
455 // (optionally) verify the server's certificates.
456 if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
460 // This is a renegotiation handshake. We require that the
461 // server's identity (i.e. leaf certificate) is unchanged and
462 // thus any previous trust decision is still valid.
464 // See https://mitls.org/pages/attacks/3SHAKE for the
465 // motivation behind this requirement.
466 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
467 c.sendAlert(alertBadCertificate)
468 return errors.New("tls: server's identity changed during renegotiation")
472 msg, err = c.readHandshake()
477 cs, ok := msg.(*certificateStatusMsg)
479 // RFC4366 on Certificate Status Request:
480 // The server MAY return a "certificate_status" message.
482 if !hs.serverHello.ocspStapling {
483 // If a server returns a "CertificateStatus" message, then the
484 // server MUST have included an extension of type "status_request"
485 // with empty "extension_data" in the extended server hello.
487 c.sendAlert(alertUnexpectedMessage)
488 return errors.New("tls: received unexpected CertificateStatus message")
490 hs.finishedHash.Write(cs.marshal())
492 c.ocspResponse = cs.response
494 msg, err = c.readHandshake()
500 keyAgreement := hs.suite.ka(c.vers)
502 skx, ok := msg.(*serverKeyExchangeMsg)
504 hs.finishedHash.Write(skx.marshal())
505 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
507 c.sendAlert(alertUnexpectedMessage)
511 msg, err = c.readHandshake()
517 var chainToSend *Certificate
518 var certRequested bool
519 certReq, ok := msg.(*certificateRequestMsg)
522 hs.finishedHash.Write(certReq.marshal())
524 cri := certificateRequestInfoFromMsg(certReq)
525 if chainToSend, err = c.getClientCertificate(cri); err != nil {
526 c.sendAlert(alertInternalError)
530 msg, err = c.readHandshake()
536 shd, ok := msg.(*serverHelloDoneMsg)
538 c.sendAlert(alertUnexpectedMessage)
539 return unexpectedMessageError(shd, msg)
541 hs.finishedHash.Write(shd.marshal())
543 // If the server requested a certificate then we have to send a
544 // Certificate message, even if it's empty because we don't have a
545 // certificate to send.
547 certMsg = new(certificateMsg)
548 certMsg.certificates = chainToSend.Certificate
549 hs.finishedHash.Write(certMsg.marshal())
550 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
555 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
557 c.sendAlert(alertInternalError)
561 hs.finishedHash.Write(ckx.marshal())
562 if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
567 if chainToSend != nil && len(chainToSend.Certificate) > 0 {
568 certVerify := &certificateVerifyMsg{}
570 key, ok := chainToSend.PrivateKey.(crypto.Signer)
572 c.sendAlert(alertInternalError)
573 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
577 var sigHash crypto.Hash
578 if c.vers >= VersionTLS12 {
579 signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
581 c.sendAlert(alertIllegalParameter)
584 sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
586 return c.sendAlert(alertInternalError)
588 certVerify.hasSignatureAlgorithm = true
589 certVerify.signatureAlgorithm = signatureAlgorithm
591 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
593 c.sendAlert(alertIllegalParameter)
598 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
599 signOpts := crypto.SignerOpts(sigHash)
600 if sigType == signatureRSAPSS {
601 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
603 certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
605 c.sendAlert(alertInternalError)
609 hs.finishedHash.Write(certVerify.marshal())
610 if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
615 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
616 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
617 c.sendAlert(alertInternalError)
618 return errors.New("tls: failed to write to key log: " + err.Error())
621 hs.finishedHash.discardHandshakeBuffer()
626 func (hs *clientHandshakeState) establishKeys() error {
629 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
630 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
631 var clientCipher, serverCipher interface{}
632 var clientHash, serverHash macFunction
633 if hs.suite.cipher != nil {
634 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
635 clientHash = hs.suite.mac(c.vers, clientMAC)
636 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
637 serverHash = hs.suite.mac(c.vers, serverMAC)
639 clientCipher = hs.suite.aead(clientKey, clientIV)
640 serverCipher = hs.suite.aead(serverKey, serverIV)
643 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
644 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
648 func (hs *clientHandshakeState) serverResumedSession() bool {
649 // If the server responded with the same sessionId then it means the
650 // sessionTicket is being used to resume a TLS session.
651 return hs.session != nil && hs.hello.sessionId != nil &&
652 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
655 func (hs *clientHandshakeState) processServerHello() (bool, error) {
658 if err := hs.pickCipherSuite(); err != nil {
662 if hs.serverHello.compressionMethod != compressionNone {
663 c.sendAlert(alertUnexpectedMessage)
664 return false, errors.New("tls: server selected unsupported compression format")
667 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
668 c.secureRenegotiation = true
669 if len(hs.serverHello.secureRenegotiation) != 0 {
670 c.sendAlert(alertHandshakeFailure)
671 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
675 if c.handshakes > 0 && c.secureRenegotiation {
676 var expectedSecureRenegotiation [24]byte
677 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
678 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
679 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
680 c.sendAlert(alertHandshakeFailure)
681 return false, errors.New("tls: incorrect renegotiation extension contents")
685 clientDidALPN := len(hs.hello.alpnProtocols) > 0
686 serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
688 if !clientDidALPN && serverHasALPN {
689 c.sendAlert(alertHandshakeFailure)
690 return false, errors.New("tls: server advertised unrequested ALPN extension")
694 c.clientProtocol = hs.serverHello.alpnProtocol
695 c.clientProtocolFallback = false
697 c.scts = hs.serverHello.scts
699 if !hs.serverResumedSession() {
703 if hs.session.vers != c.vers {
704 c.sendAlert(alertHandshakeFailure)
705 return false, errors.New("tls: server resumed a session with a different version")
708 if hs.session.cipherSuite != hs.suite.id {
709 c.sendAlert(alertHandshakeFailure)
710 return false, errors.New("tls: server resumed a session with a different cipher suite")
713 // Restore masterSecret and peerCerts from previous state
714 hs.masterSecret = hs.session.masterSecret
715 c.peerCertificates = hs.session.serverCertificates
716 c.verifiedChains = hs.session.verifiedChains
720 func (hs *clientHandshakeState) readFinished(out []byte) error {
723 if err := c.readChangeCipherSpec(); err != nil {
727 msg, err := c.readHandshake()
731 serverFinished, ok := msg.(*finishedMsg)
733 c.sendAlert(alertUnexpectedMessage)
734 return unexpectedMessageError(serverFinished, msg)
737 verify := hs.finishedHash.serverSum(hs.masterSecret)
738 if len(verify) != len(serverFinished.verifyData) ||
739 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
740 c.sendAlert(alertHandshakeFailure)
741 return errors.New("tls: server's Finished message was incorrect")
743 hs.finishedHash.Write(serverFinished.marshal())
748 func (hs *clientHandshakeState) readSessionTicket() error {
749 if !hs.serverHello.ticketSupported {
754 msg, err := c.readHandshake()
758 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
760 c.sendAlert(alertUnexpectedMessage)
761 return unexpectedMessageError(sessionTicketMsg, msg)
763 hs.finishedHash.Write(sessionTicketMsg.marshal())
765 hs.session = &ClientSessionState{
766 sessionTicket: sessionTicketMsg.ticket,
768 cipherSuite: hs.suite.id,
769 masterSecret: hs.masterSecret,
770 serverCertificates: c.peerCertificates,
771 verifiedChains: c.verifiedChains,
772 receivedAt: c.config.time(),
778 func (hs *clientHandshakeState) sendFinished(out []byte) error {
781 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
785 finished := new(finishedMsg)
786 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
787 hs.finishedHash.Write(finished.marshal())
788 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
791 copy(out, finished.verifyData)
795 // verifyServerCertificate parses and verifies the provided chain, setting
796 // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
797 func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
798 certs := make([]*x509.Certificate, len(certificates))
799 for i, asn1Data := range certificates {
800 cert, err := x509.ParseCertificate(asn1Data)
802 c.sendAlert(alertBadCertificate)
803 return errors.New("tls: failed to parse certificate from server: " + err.Error())
808 if !c.config.InsecureSkipVerify {
809 opts := x509.VerifyOptions{
810 IsBoring: isBoringCertificate,
812 Roots: c.config.RootCAs,
813 CurrentTime: c.config.time(),
814 DNSName: c.config.ServerName,
815 Intermediates: x509.NewCertPool(),
817 for _, cert := range certs[1:] {
818 opts.Intermediates.AddCert(cert)
821 c.verifiedChains, err = certs[0].Verify(opts)
823 c.sendAlert(alertBadCertificate)
828 if c.config.VerifyPeerCertificate != nil {
829 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
830 c.sendAlert(alertBadCertificate)
835 switch certs[0].PublicKey.(type) {
836 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
839 c.sendAlert(alertUnsupportedCertificate)
840 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
843 c.peerCertificates = certs
848 // tls11SignatureSchemes contains the signature schemes that we synthesise for
849 // a TLS <= 1.1 connection, based on the supported certificate types.
851 tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
852 tls11SignatureSchemesECDSA = tls11SignatureSchemes[:3]
853 tls11SignatureSchemesRSA = tls11SignatureSchemes[3:]
856 // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
857 // <= 1.2 CertificateRequest, making an effort to fill in missing information.
858 func certificateRequestInfoFromMsg(certReq *certificateRequestMsg) *CertificateRequestInfo {
859 var rsaAvail, ecAvail bool
860 for _, certType := range certReq.certificateTypes {
862 case certTypeRSASign:
864 case certTypeECDSASign:
869 cri := &CertificateRequestInfo{
870 AcceptableCAs: certReq.certificateAuthorities,
873 if !certReq.hasSignatureAlgorithm {
874 // Prior to TLS 1.2, the signature schemes were not
875 // included in the certificate request message. In this
876 // case we use a plausible list based on the acceptable
877 // certificate types.
879 case rsaAvail && ecAvail:
880 cri.SignatureSchemes = tls11SignatureSchemes
882 cri.SignatureSchemes = tls11SignatureSchemesRSA
884 cri.SignatureSchemes = tls11SignatureSchemesECDSA
889 // Filter the signature schemes based on the certificate types.
890 // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
891 cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
892 for _, sigScheme := range certReq.supportedSignatureAlgorithms {
893 sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
898 case signatureECDSA, signatureEd25519:
900 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
902 case signatureRSAPSS, signaturePKCS1v15:
904 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
912 func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
913 if c.config.GetClientCertificate != nil {
914 return c.config.GetClientCertificate(cri)
917 // We need to search our list of client certs for one
918 // where SignatureAlgorithm is acceptable to the server and the
919 // Issuer is in AcceptableCAs.
920 for i, chain := range c.config.Certificates {
922 for _, alg := range signatureSchemesForCertificate(c.vers, &chain) {
923 if isSupportedSignatureAlgorithm(alg, cri.SignatureSchemes) {
932 if len(cri.AcceptableCAs) == 0 {
936 for j, cert := range chain.Certificate {
937 x509Cert := chain.Leaf
938 // Parse the certificate if this isn't the leaf node, or if
939 // chain.Leaf was nil.
940 if j != 0 || x509Cert == nil {
942 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
943 c.sendAlert(alertInternalError)
944 return nil, errors.New("tls: failed to parse configured certificate chain #" + strconv.Itoa(i) + ": " + err.Error())
948 for _, ca := range cri.AcceptableCAs {
949 if bytes.Equal(x509Cert.RawIssuer, ca) {
956 // No acceptable certificate found. Don't send a certificate.
957 return new(Certificate), nil
960 // clientSessionCacheKey returns a key used to cache sessionTickets that could
961 // be used to resume previously negotiated TLS sessions with a server.
962 func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
963 if len(config.ServerName) > 0 {
964 return config.ServerName
966 return serverAddr.String()
969 // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
970 // given list of possible protocols and a list of the preference order. The
971 // first list must not be empty. It returns the resulting protocol and flag
972 // indicating if the fallback case was reached.
973 func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
974 for _, s := range preferenceProtos {
975 for _, c := range protos {
982 return protos[0], true
985 // hostnameInSNI converts name into an appropriate hostname for SNI.
986 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
987 // See RFC 6066, Section 3.
988 func hostnameInSNI(name string) string {
990 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
991 host = host[1 : len(host)-1]
993 if i := strings.LastIndex(host, "%"); i > 0 {
996 if net.ParseIP(host) != nil {
999 for len(name) > 0 && name[len(name)-1] == '.' {
1000 name = name[:len(name)-1]