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.
24 type clientHandshakeState struct {
26 serverHello *serverHelloMsg
29 finishedHash finishedHash
31 session *ClientSessionState
34 func (c *Conn) makeClientHello() (*clientHelloMsg, ecdheParameters, error) {
36 if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
37 return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
41 for _, proto := range config.NextProtos {
42 if l := len(proto); l == 0 || l > 255 {
43 return nil, nil, errors.New("tls: invalid NextProtos value")
45 nextProtosLength += 1 + l
48 if nextProtosLength > 0xffff {
49 return nil, nil, errors.New("tls: NextProtos values too large")
52 supportedVersions := config.supportedVersions(true)
53 if len(supportedVersions) == 0 {
54 return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
57 clientHelloVersion := supportedVersions[0]
58 // The version at the beginning of the ClientHello was capped at TLS 1.2
59 // for compatibility reasons. The supported_versions extension is used
60 // to negotiate versions now. See RFC 8446, Section 4.2.1.
61 if clientHelloVersion > VersionTLS12 {
62 clientHelloVersion = VersionTLS12
65 hello := &clientHelloMsg{
66 vers: clientHelloVersion,
67 compressionMethods: []uint8{compressionNone},
68 random: make([]byte, 32),
69 sessionId: make([]byte, 32),
72 serverName: hostnameInSNI(config.ServerName),
73 supportedCurves: config.curvePreferences(),
74 supportedPoints: []uint8{pointFormatUncompressed},
75 nextProtoNeg: len(config.NextProtos) > 0,
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))
89 for _, suiteId := range possibleCipherSuites {
90 for _, suite := range cipherSuites {
91 if suite.id != suiteId {
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 {
99 hello.cipherSuites = append(hello.cipherSuites, suiteId)
100 continue NextCipherSuite
104 _, err := io.ReadFull(config.rand(), hello.random)
106 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
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())
116 if hello.vers >= VersionTLS12 {
117 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
119 if testingOnlyForceClientHelloSignatureAlgorithms != nil {
120 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
123 var params ecdheParameters
124 if hello.supportedVersions[0] == VersionTLS13 {
125 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13()...)
127 curveID := config.curvePreferences()[0]
128 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
129 return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
131 params, err = generateECDHEParameters(config.rand(), curveID)
135 hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
138 return hello, params, nil
141 func (c *Conn) clientHandshake() (err error) {
143 c.config = defaultConfig()
146 // This may be a renegotiation handshake, in which case some fields
150 hello, ecdheParams, err := c.makeClientHello()
155 cacheKey, session, earlySecret, binderKey := c.loadSession(hello)
156 if cacheKey != "" && session != nil {
158 // If we got a handshake failure when resuming a session, throw away
159 // the session ticket. See RFC 5077, Section 3.2.
161 // RFC 8446 makes no mention of dropping tickets on failure, but it
162 // does require servers to abort on invalid binders, so we need to
163 // delete tickets to recover from a corrupted PSK.
165 c.config.ClientSessionCache.Put(cacheKey, nil)
170 if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
174 msg, err := c.readHandshake()
179 serverHello, ok := msg.(*serverHelloMsg)
181 c.sendAlert(alertUnexpectedMessage)
182 return unexpectedMessageError(serverHello, msg)
185 if err := c.pickTLSVersion(serverHello); err != nil {
189 if c.vers == VersionTLS13 {
190 hs := &clientHandshakeStateTLS13{
192 serverHello: serverHello,
194 ecdheParams: ecdheParams,
196 earlySecret: earlySecret,
197 binderKey: binderKey,
200 // In TLS 1.3, session tickets are delivered after the handshake.
201 return hs.handshake()
204 hs := &clientHandshakeState{
206 serverHello: serverHello,
211 if err := hs.handshake(); err != nil {
215 // If we had a successful handshake and hs.session is different from
216 // the one already cached - cache a new one.
217 if cacheKey != "" && hs.session != nil && session != hs.session {
218 c.config.ClientSessionCache.Put(cacheKey, hs.session)
224 func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
225 session *ClientSessionState, earlySecret, binderKey []byte) {
226 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
227 return "", nil, nil, nil
230 hello.ticketSupported = true
232 if hello.supportedVersions[0] == VersionTLS13 {
233 // Require DHE on resumption as it guarantees forward secrecy against
234 // compromise of the session ticket key. See RFC 8446, Section 4.2.9.
235 hello.pskModes = []uint8{pskModeDHE}
238 // Session resumption is not allowed if renegotiating because
239 // renegotiation is primarily used to allow a client to send a client
240 // certificate, which would be skipped if session resumption occurred.
241 if c.handshakes != 0 {
242 return "", nil, nil, nil
245 // Try to resume a previously negotiated TLS session, if available.
246 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
247 session, ok := c.config.ClientSessionCache.Get(cacheKey)
248 if !ok || session == nil {
249 return cacheKey, nil, nil, nil
252 // Check that version used for the previous session is still valid.
254 for _, v := range hello.supportedVersions {
255 if v == session.vers {
261 return cacheKey, nil, nil, nil
264 // Check that the cached server certificate is not expired, and that it's
265 // valid for the ServerName. This should be ensured by the cache key, but
266 // protect the application from a faulty ClientSessionCache implementation.
267 if !c.config.InsecureSkipVerify {
268 if len(session.verifiedChains) == 0 {
269 // The original connection had InsecureSkipVerify, while this doesn't.
270 return cacheKey, nil, nil, nil
272 serverCert := session.serverCertificates[0]
273 if c.config.time().After(serverCert.NotAfter) {
274 // Expired certificate, delete the entry.
275 c.config.ClientSessionCache.Put(cacheKey, nil)
276 return cacheKey, nil, nil, nil
278 if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
279 return cacheKey, nil, nil, nil
283 if session.vers != VersionTLS13 {
284 // In TLS 1.2 the cipher suite must match the resumed session. Ensure we
285 // are still offering it.
286 if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
287 return cacheKey, nil, nil, nil
290 hello.sessionTicket = session.sessionTicket
294 // Check that the session ticket is not expired.
295 if c.config.time().After(session.useBy) {
296 c.config.ClientSessionCache.Put(cacheKey, nil)
297 return cacheKey, nil, nil, nil
300 // In TLS 1.3 the KDF hash must match the resumed session. Ensure we
301 // offer at least one cipher suite with that hash.
302 cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
303 if cipherSuite == nil {
304 return cacheKey, nil, nil, nil
306 cipherSuiteOk := false
307 for _, offeredID := range hello.cipherSuites {
308 offeredSuite := cipherSuiteTLS13ByID(offeredID)
309 if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
315 return cacheKey, nil, nil, nil
318 // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
319 ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
320 identity := pskIdentity{
321 label: session.sessionTicket,
322 obfuscatedTicketAge: ticketAge + session.ageAdd,
324 hello.pskIdentities = []pskIdentity{identity}
325 hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
327 // Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
328 psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
329 session.nonce, cipherSuite.hash.Size())
330 earlySecret = cipherSuite.extract(psk, nil)
331 binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
332 transcript := cipherSuite.hash.New()
333 transcript.Write(hello.marshalWithoutBinders())
334 pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
335 hello.updateBinders(pskBinders)
340 func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
341 peerVersion := serverHello.vers
342 if serverHello.supportedVersion != 0 {
343 peerVersion = serverHello.supportedVersion
346 vers, ok := c.config.mutualVersion(true, []uint16{peerVersion})
348 c.sendAlert(alertProtocolVersion)
349 return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
360 // Does the handshake, either a full one or resumes old session. Requires hs.c,
361 // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
362 func (hs *clientHandshakeState) handshake() error {
365 isResume, err := hs.processServerHello()
370 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
372 // No signatures of the handshake are needed in a resumption.
373 // Otherwise, in a full handshake, if we don't have any certificates
374 // configured then we will never send a CertificateVerify message and
375 // thus no signatures are needed in that case either.
376 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
377 hs.finishedHash.discardHandshakeBuffer()
380 hs.finishedHash.Write(hs.hello.marshal())
381 hs.finishedHash.Write(hs.serverHello.marshal())
385 if err := hs.establishKeys(); err != nil {
388 if err := hs.readSessionTicket(); err != nil {
391 if err := hs.readFinished(c.serverFinished[:]); err != nil {
394 c.clientFinishedIsFirst = false
395 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
398 if _, err := c.flush(); err != nil {
402 if err := hs.doFullHandshake(); err != nil {
405 if err := hs.establishKeys(); err != nil {
408 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
411 if _, err := c.flush(); err != nil {
414 c.clientFinishedIsFirst = true
415 if err := hs.readSessionTicket(); err != nil {
418 if err := hs.readFinished(c.serverFinished[:]); err != nil {
423 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
424 c.didResume = isResume
425 atomic.StoreUint32(&c.handshakeStatus, 1)
430 func (hs *clientHandshakeState) pickCipherSuite() error {
431 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
432 hs.c.sendAlert(alertHandshakeFailure)
433 return errors.New("tls: server chose an unconfigured cipher suite")
436 hs.c.cipherSuite = hs.suite.id
440 func (hs *clientHandshakeState) doFullHandshake() error {
443 msg, err := c.readHandshake()
447 certMsg, ok := msg.(*certificateMsg)
448 if !ok || len(certMsg.certificates) == 0 {
449 c.sendAlert(alertUnexpectedMessage)
450 return unexpectedMessageError(certMsg, msg)
452 hs.finishedHash.Write(certMsg.marshal())
454 if c.handshakes == 0 {
455 // If this is the first handshake on a connection, process and
456 // (optionally) verify the server's certificates.
457 if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
461 // This is a renegotiation handshake. We require that the
462 // server's identity (i.e. leaf certificate) is unchanged and
463 // thus any previous trust decision is still valid.
465 // See https://mitls.org/pages/attacks/3SHAKE for the
466 // motivation behind this requirement.
467 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
468 c.sendAlert(alertBadCertificate)
469 return errors.New("tls: server's identity changed during renegotiation")
473 msg, err = c.readHandshake()
478 cs, ok := msg.(*certificateStatusMsg)
480 // RFC4366 on Certificate Status Request:
481 // The server MAY return a "certificate_status" message.
483 if !hs.serverHello.ocspStapling {
484 // If a server returns a "CertificateStatus" message, then the
485 // server MUST have included an extension of type "status_request"
486 // with empty "extension_data" in the extended server hello.
488 c.sendAlert(alertUnexpectedMessage)
489 return errors.New("tls: received unexpected CertificateStatus message")
491 hs.finishedHash.Write(cs.marshal())
493 c.ocspResponse = cs.response
495 msg, err = c.readHandshake()
501 keyAgreement := hs.suite.ka(c.vers)
503 skx, ok := msg.(*serverKeyExchangeMsg)
505 hs.finishedHash.Write(skx.marshal())
506 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
508 c.sendAlert(alertUnexpectedMessage)
512 msg, err = c.readHandshake()
518 var chainToSend *Certificate
519 var certRequested bool
520 certReq, ok := msg.(*certificateRequestMsg)
523 hs.finishedHash.Write(certReq.marshal())
525 cri := certificateRequestInfoFromMsg(certReq)
526 if chainToSend, err = c.getClientCertificate(cri); err != nil {
527 c.sendAlert(alertInternalError)
531 msg, err = c.readHandshake()
537 shd, ok := msg.(*serverHelloDoneMsg)
539 c.sendAlert(alertUnexpectedMessage)
540 return unexpectedMessageError(shd, msg)
542 hs.finishedHash.Write(shd.marshal())
544 // If the server requested a certificate then we have to send a
545 // Certificate message, even if it's empty because we don't have a
546 // certificate to send.
548 certMsg = new(certificateMsg)
549 certMsg.certificates = chainToSend.Certificate
550 hs.finishedHash.Write(certMsg.marshal())
551 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
556 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
558 c.sendAlert(alertInternalError)
562 hs.finishedHash.Write(ckx.marshal())
563 if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
568 if chainToSend != nil && len(chainToSend.Certificate) > 0 {
569 certVerify := &certificateVerifyMsg{
570 hasSignatureAlgorithm: c.vers >= VersionTLS12,
573 key, ok := chainToSend.PrivateKey.(crypto.Signer)
575 c.sendAlert(alertInternalError)
576 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
579 signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
581 c.sendAlert(alertInternalError)
584 // SignatureAndHashAlgorithm was introduced in TLS 1.2.
585 if certVerify.hasSignatureAlgorithm {
586 certVerify.signatureAlgorithm = signatureAlgorithm
588 digest, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
590 c.sendAlert(alertInternalError)
593 signOpts := crypto.SignerOpts(hashFunc)
594 if sigType == signatureRSAPSS {
595 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
597 certVerify.signature, err = key.Sign(c.config.rand(), digest, signOpts)
599 c.sendAlert(alertInternalError)
603 hs.finishedHash.Write(certVerify.marshal())
604 if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
609 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
610 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
611 c.sendAlert(alertInternalError)
612 return errors.New("tls: failed to write to key log: " + err.Error())
615 hs.finishedHash.discardHandshakeBuffer()
620 func (hs *clientHandshakeState) establishKeys() error {
623 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
624 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
625 var clientCipher, serverCipher interface{}
626 var clientHash, serverHash macFunction
627 if hs.suite.cipher != nil {
628 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
629 clientHash = hs.suite.mac(c.vers, clientMAC)
630 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
631 serverHash = hs.suite.mac(c.vers, serverMAC)
633 clientCipher = hs.suite.aead(clientKey, clientIV)
634 serverCipher = hs.suite.aead(serverKey, serverIV)
637 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
638 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
642 func (hs *clientHandshakeState) serverResumedSession() bool {
643 // If the server responded with the same sessionId then it means the
644 // sessionTicket is being used to resume a TLS session.
645 return hs.session != nil && hs.hello.sessionId != nil &&
646 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
649 func (hs *clientHandshakeState) processServerHello() (bool, error) {
652 if err := hs.pickCipherSuite(); err != nil {
656 if hs.serverHello.compressionMethod != compressionNone {
657 c.sendAlert(alertUnexpectedMessage)
658 return false, errors.New("tls: server selected unsupported compression format")
661 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
662 c.secureRenegotiation = true
663 if len(hs.serverHello.secureRenegotiation) != 0 {
664 c.sendAlert(alertHandshakeFailure)
665 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
669 if c.handshakes > 0 && c.secureRenegotiation {
670 var expectedSecureRenegotiation [24]byte
671 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
672 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
673 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
674 c.sendAlert(alertHandshakeFailure)
675 return false, errors.New("tls: incorrect renegotiation extension contents")
679 clientDidNPN := hs.hello.nextProtoNeg
680 clientDidALPN := len(hs.hello.alpnProtocols) > 0
681 serverHasNPN := hs.serverHello.nextProtoNeg
682 serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
684 if !clientDidNPN && serverHasNPN {
685 c.sendAlert(alertHandshakeFailure)
686 return false, errors.New("tls: server advertised unrequested NPN extension")
689 if !clientDidALPN && serverHasALPN {
690 c.sendAlert(alertHandshakeFailure)
691 return false, errors.New("tls: server advertised unrequested ALPN extension")
694 if serverHasNPN && serverHasALPN {
695 c.sendAlert(alertHandshakeFailure)
696 return false, errors.New("tls: server advertised both NPN and ALPN extensions")
700 c.clientProtocol = hs.serverHello.alpnProtocol
701 c.clientProtocolFallback = false
703 c.scts = hs.serverHello.scts
705 if !hs.serverResumedSession() {
709 if hs.session.vers != c.vers {
710 c.sendAlert(alertHandshakeFailure)
711 return false, errors.New("tls: server resumed a session with a different version")
714 if hs.session.cipherSuite != hs.suite.id {
715 c.sendAlert(alertHandshakeFailure)
716 return false, errors.New("tls: server resumed a session with a different cipher suite")
719 // Restore masterSecret and peerCerts from previous state
720 hs.masterSecret = hs.session.masterSecret
721 c.peerCertificates = hs.session.serverCertificates
722 c.verifiedChains = hs.session.verifiedChains
726 func (hs *clientHandshakeState) readFinished(out []byte) error {
729 if err := c.readChangeCipherSpec(); err != nil {
733 msg, err := c.readHandshake()
737 serverFinished, ok := msg.(*finishedMsg)
739 c.sendAlert(alertUnexpectedMessage)
740 return unexpectedMessageError(serverFinished, msg)
743 verify := hs.finishedHash.serverSum(hs.masterSecret)
744 if len(verify) != len(serverFinished.verifyData) ||
745 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
746 c.sendAlert(alertHandshakeFailure)
747 return errors.New("tls: server's Finished message was incorrect")
749 hs.finishedHash.Write(serverFinished.marshal())
754 func (hs *clientHandshakeState) readSessionTicket() error {
755 if !hs.serverHello.ticketSupported {
760 msg, err := c.readHandshake()
764 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
766 c.sendAlert(alertUnexpectedMessage)
767 return unexpectedMessageError(sessionTicketMsg, msg)
769 hs.finishedHash.Write(sessionTicketMsg.marshal())
771 hs.session = &ClientSessionState{
772 sessionTicket: sessionTicketMsg.ticket,
774 cipherSuite: hs.suite.id,
775 masterSecret: hs.masterSecret,
776 serverCertificates: c.peerCertificates,
777 verifiedChains: c.verifiedChains,
778 receivedAt: c.config.time(),
784 func (hs *clientHandshakeState) sendFinished(out []byte) error {
787 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
790 if hs.serverHello.nextProtoNeg {
791 nextProto := new(nextProtoMsg)
792 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
793 nextProto.proto = proto
794 c.clientProtocol = proto
795 c.clientProtocolFallback = fallback
797 hs.finishedHash.Write(nextProto.marshal())
798 if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
803 finished := new(finishedMsg)
804 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
805 hs.finishedHash.Write(finished.marshal())
806 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
809 copy(out, finished.verifyData)
813 // verifyServerCertificate parses and verifies the provided chain, setting
814 // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
815 func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
816 certs := make([]*x509.Certificate, len(certificates))
817 for i, asn1Data := range certificates {
818 cert, err := x509.ParseCertificate(asn1Data)
820 c.sendAlert(alertBadCertificate)
821 return errors.New("tls: failed to parse certificate from server: " + err.Error())
826 if !c.config.InsecureSkipVerify {
827 opts := x509.VerifyOptions{
828 IsBoring: isBoringCertificate,
830 Roots: c.config.RootCAs,
831 CurrentTime: c.config.time(),
832 DNSName: c.config.ServerName,
833 Intermediates: x509.NewCertPool(),
836 for i, cert := range certs {
840 opts.Intermediates.AddCert(cert)
843 c.verifiedChains, err = certs[0].Verify(opts)
845 c.sendAlert(alertBadCertificate)
850 if c.config.VerifyPeerCertificate != nil {
851 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
852 c.sendAlert(alertBadCertificate)
857 switch certs[0].PublicKey.(type) {
858 case *rsa.PublicKey, *ecdsa.PublicKey:
861 c.sendAlert(alertUnsupportedCertificate)
862 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
865 c.peerCertificates = certs
870 // tls11SignatureSchemes contains the signature schemes that we synthesise for
871 // a TLS <= 1.1 connection, based on the supported certificate types.
873 tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
874 tls11SignatureSchemesECDSA = tls11SignatureSchemes[:3]
875 tls11SignatureSchemesRSA = tls11SignatureSchemes[3:]
878 // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
879 // <= 1.2 CertificateRequest, making an effort to fill in missing information.
880 func certificateRequestInfoFromMsg(certReq *certificateRequestMsg) *CertificateRequestInfo {
881 var rsaAvail, ecdsaAvail bool
882 for _, certType := range certReq.certificateTypes {
884 case certTypeRSASign:
886 case certTypeECDSASign:
891 cri := &CertificateRequestInfo{
892 AcceptableCAs: certReq.certificateAuthorities,
895 if !certReq.hasSignatureAlgorithm {
896 // Prior to TLS 1.2, the signature schemes were not
897 // included in the certificate request message. In this
898 // case we use a plausible list based on the acceptable
899 // certificate types.
901 case rsaAvail && ecdsaAvail:
902 cri.SignatureSchemes = tls11SignatureSchemes
904 cri.SignatureSchemes = tls11SignatureSchemesRSA
906 cri.SignatureSchemes = tls11SignatureSchemesECDSA
911 // In TLS 1.2, the signature schemes apply to both the certificate chain and
912 // the leaf key, while the certificate types only apply to the leaf key.
913 // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
914 // Filter the signature schemes based on the certificate type.
915 cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
916 for _, sigScheme := range certReq.supportedSignatureAlgorithms {
917 switch signatureFromSignatureScheme(sigScheme) {
920 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
922 case signatureRSAPSS, signaturePKCS1v15:
924 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
932 func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
933 if c.config.GetClientCertificate != nil {
934 return c.config.GetClientCertificate(cri)
937 // We need to search our list of client certs for one
938 // where SignatureAlgorithm is acceptable to the server and the
939 // Issuer is in AcceptableCAs.
940 for i, chain := range c.config.Certificates {
942 for _, alg := range signatureSchemesForCertificate(&chain) {
943 if isSupportedSignatureAlgorithm(alg, cri.SignatureSchemes) {
952 if len(cri.AcceptableCAs) == 0 {
956 for j, cert := range chain.Certificate {
957 x509Cert := chain.Leaf
958 // Parse the certificate if this isn't the leaf node, or if
959 // chain.Leaf was nil.
960 if j != 0 || x509Cert == nil {
962 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
963 c.sendAlert(alertInternalError)
964 return nil, errors.New("tls: failed to parse configured certificate chain #" + strconv.Itoa(i) + ": " + err.Error())
968 for _, ca := range cri.AcceptableCAs {
969 if bytes.Equal(x509Cert.RawIssuer, ca) {
976 // No acceptable certificate found. Don't send a certificate.
977 return new(Certificate), nil
980 // clientSessionCacheKey returns a key used to cache sessionTickets that could
981 // be used to resume previously negotiated TLS sessions with a server.
982 func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
983 if len(config.ServerName) > 0 {
984 return config.ServerName
986 return serverAddr.String()
989 // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
990 // given list of possible protocols and a list of the preference order. The
991 // first list must not be empty. It returns the resulting protocol and flag
992 // indicating if the fallback case was reached.
993 func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
994 for _, s := range preferenceProtos {
995 for _, c := range protos {
1002 return protos[0], true
1005 // hostnameInSNI converts name into an approriate hostname for SNI.
1006 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
1007 // See RFC 6066, Section 3.
1008 func hostnameInSNI(name string) string {
1010 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
1011 host = host[1 : len(host)-1]
1013 if i := strings.LastIndex(host, "%"); i > 0 {
1016 if net.ParseIP(host) != nil {
1019 for len(name) > 0 && name[len(name)-1] == '.' {
1020 name = name[:len(name)-1]