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.
26 type clientHandshakeState struct {
29 serverHello *serverHelloMsg
32 finishedHash finishedHash
34 session *ClientSessionState
37 var testingOnlyForceClientHelloSignatureAlgorithms []SignatureScheme
39 func (c *Conn) makeClientHello() (*clientHelloMsg, *ecdh.PrivateKey, error) {
41 if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
42 return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
46 for _, proto := range config.NextProtos {
47 if l := len(proto); l == 0 || l > 255 {
48 return nil, nil, errors.New("tls: invalid NextProtos value")
50 nextProtosLength += 1 + l
53 if nextProtosLength > 0xffff {
54 return nil, nil, errors.New("tls: NextProtos values too large")
57 supportedVersions := config.supportedVersions(roleClient)
58 if len(supportedVersions) == 0 {
59 return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
62 clientHelloVersion := config.maxSupportedVersion(roleClient)
63 // The version at the beginning of the ClientHello was capped at TLS 1.2
64 // for compatibility reasons. The supported_versions extension is used
65 // to negotiate versions now. See RFC 8446, Section 4.2.1.
66 if clientHelloVersion > VersionTLS12 {
67 clientHelloVersion = VersionTLS12
70 hello := &clientHelloMsg{
71 vers: clientHelloVersion,
72 compressionMethods: []uint8{compressionNone},
73 random: make([]byte, 32),
76 serverName: hostnameInSNI(config.ServerName),
77 supportedCurves: config.curvePreferences(),
78 supportedPoints: []uint8{pointFormatUncompressed},
79 secureRenegotiationSupported: true,
80 alpnProtocols: config.NextProtos,
81 supportedVersions: supportedVersions,
85 hello.secureRenegotiation = c.clientFinished[:]
88 preferenceOrder := cipherSuitesPreferenceOrder
89 if !hasAESGCMHardwareSupport {
90 preferenceOrder = cipherSuitesPreferenceOrderNoAES
92 configCipherSuites := config.cipherSuites()
93 hello.cipherSuites = make([]uint16, 0, len(configCipherSuites))
95 for _, suiteId := range preferenceOrder {
96 suite := mutualCipherSuite(configCipherSuites, suiteId)
100 // Don't advertise TLS 1.2-only cipher suites unless
101 // we're attempting TLS 1.2.
102 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
105 hello.cipherSuites = append(hello.cipherSuites, suiteId)
108 _, err := io.ReadFull(config.rand(), hello.random)
110 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
113 // A random session ID is used to detect when the server accepted a ticket
114 // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
115 // a compatibility measure (see RFC 8446, Section 4.1.2).
117 // The session ID is not set for QUIC connections (see RFC 9001, Section 8.4).
119 hello.sessionId = make([]byte, 32)
120 if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
121 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
125 if hello.vers >= VersionTLS12 {
126 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
128 if testingOnlyForceClientHelloSignatureAlgorithms != nil {
129 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
132 var key *ecdh.PrivateKey
133 if hello.supportedVersions[0] == VersionTLS13 {
134 if hasAESGCMHardwareSupport {
135 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
137 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
140 curveID := config.curvePreferences()[0]
141 if _, ok := curveForCurveID(curveID); !ok {
142 return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
144 key, err = generateECDHEKey(config.rand(), curveID)
148 hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
152 p, err := c.quicGetTransportParameters()
159 hello.quicTransportParameters = p
162 return hello, key, nil
165 func (c *Conn) clientHandshake(ctx context.Context) (err error) {
167 c.config = defaultConfig()
170 // This may be a renegotiation handshake, in which case some fields
174 hello, ecdheKey, err := c.makeClientHello()
178 c.serverName = hello.serverName
180 cacheKey, session, earlySecret, binderKey, err := c.loadSession(hello)
184 if cacheKey != "" && session != nil {
186 // If we got a handshake failure when resuming a session, throw away
187 // the session ticket. See RFC 5077, Section 3.2.
189 // RFC 8446 makes no mention of dropping tickets on failure, but it
190 // does require servers to abort on invalid binders, so we need to
191 // delete tickets to recover from a corrupted PSK.
193 c.config.ClientSessionCache.Put(cacheKey, nil)
198 if _, err := c.writeHandshakeRecord(hello, nil); err != nil {
202 // serverHelloMsg is not included in the transcript
203 msg, err := c.readHandshake(nil)
208 serverHello, ok := msg.(*serverHelloMsg)
210 c.sendAlert(alertUnexpectedMessage)
211 return unexpectedMessageError(serverHello, msg)
214 if err := c.pickTLSVersion(serverHello); err != nil {
218 // If we are negotiating a protocol version that's lower than what we
219 // support, check for the server downgrade canaries.
220 // See RFC 8446, Section 4.1.3.
221 maxVers := c.config.maxSupportedVersion(roleClient)
222 tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
223 tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
224 if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
225 maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
226 c.sendAlert(alertIllegalParameter)
227 return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
230 if c.vers == VersionTLS13 {
231 hs := &clientHandshakeStateTLS13{
234 serverHello: serverHello,
238 earlySecret: earlySecret,
239 binderKey: binderKey,
242 // In TLS 1.3, session tickets are delivered after the handshake.
243 return hs.handshake()
246 hs := &clientHandshakeState{
249 serverHello: serverHello,
254 if err := hs.handshake(); err != nil {
258 // If we had a successful handshake and hs.session is different from
259 // the one already cached - cache a new one.
260 if cacheKey != "" && hs.session != nil && session != hs.session {
261 c.config.ClientSessionCache.Put(cacheKey, hs.session)
267 func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
268 session *ClientSessionState, earlySecret, binderKey []byte, err error) {
269 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
270 return "", nil, nil, nil, nil
273 hello.ticketSupported = true
275 if hello.supportedVersions[0] == VersionTLS13 {
276 // Require DHE on resumption as it guarantees forward secrecy against
277 // compromise of the session ticket key. See RFC 8446, Section 4.2.9.
278 hello.pskModes = []uint8{pskModeDHE}
281 // Session resumption is not allowed if renegotiating because
282 // renegotiation is primarily used to allow a client to send a client
283 // certificate, which would be skipped if session resumption occurred.
284 if c.handshakes != 0 {
285 return "", nil, nil, nil, nil
288 // Try to resume a previously negotiated TLS session, if available.
289 cacheKey = c.clientSessionCacheKey()
291 return "", nil, nil, nil, nil
293 session, ok := c.config.ClientSessionCache.Get(cacheKey)
294 if !ok || session == nil {
295 return cacheKey, nil, nil, nil, nil
298 // Check that version used for the previous session is still valid.
300 for _, v := range hello.supportedVersions {
301 if v == session.vers {
307 return cacheKey, nil, nil, nil, nil
310 // Check that the cached server certificate is not expired, and that it's
311 // valid for the ServerName. This should be ensured by the cache key, but
312 // protect the application from a faulty ClientSessionCache implementation.
313 if !c.config.InsecureSkipVerify {
314 if len(session.verifiedChains) == 0 {
315 // The original connection had InsecureSkipVerify, while this doesn't.
316 return cacheKey, nil, nil, nil, nil
318 serverCert := session.serverCertificates[0]
319 if c.config.time().After(serverCert.NotAfter) {
320 // Expired certificate, delete the entry.
321 c.config.ClientSessionCache.Put(cacheKey, nil)
322 return cacheKey, nil, nil, nil, nil
324 if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
325 return cacheKey, nil, nil, nil, nil
329 if session.vers != VersionTLS13 {
330 // In TLS 1.2 the cipher suite must match the resumed session. Ensure we
331 // are still offering it.
332 if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
333 return cacheKey, nil, nil, nil, nil
336 hello.sessionTicket = session.sessionTicket
340 // Check that the session ticket is not expired.
341 if c.config.time().After(session.useBy) {
342 c.config.ClientSessionCache.Put(cacheKey, nil)
343 return cacheKey, nil, nil, nil, nil
346 // In TLS 1.3 the KDF hash must match the resumed session. Ensure we
347 // offer at least one cipher suite with that hash.
348 cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
349 if cipherSuite == nil {
350 return cacheKey, nil, nil, nil, nil
352 cipherSuiteOk := false
353 for _, offeredID := range hello.cipherSuites {
354 offeredSuite := cipherSuiteTLS13ByID(offeredID)
355 if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
361 return cacheKey, nil, nil, nil, nil
364 // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
365 ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
366 identity := pskIdentity{
367 label: session.sessionTicket,
368 obfuscatedTicketAge: ticketAge + session.ageAdd,
370 hello.pskIdentities = []pskIdentity{identity}
371 hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
373 // Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
374 psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
375 session.nonce, cipherSuite.hash.Size())
376 earlySecret = cipherSuite.extract(psk, nil)
377 binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
378 transcript := cipherSuite.hash.New()
379 helloBytes, err := hello.marshalWithoutBinders()
381 return "", nil, nil, nil, err
383 transcript.Write(helloBytes)
384 pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
385 if err := hello.updateBinders(pskBinders); err != nil {
386 return "", nil, nil, nil, err
392 func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
393 peerVersion := serverHello.vers
394 if serverHello.supportedVersion != 0 {
395 peerVersion = serverHello.supportedVersion
398 vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion})
400 c.sendAlert(alertProtocolVersion)
401 return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
412 // Does the handshake, either a full one or resumes old session. Requires hs.c,
413 // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
414 func (hs *clientHandshakeState) handshake() error {
417 isResume, err := hs.processServerHello()
422 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
424 // No signatures of the handshake are needed in a resumption.
425 // Otherwise, in a full handshake, if we don't have any certificates
426 // configured then we will never send a CertificateVerify message and
427 // thus no signatures are needed in that case either.
428 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
429 hs.finishedHash.discardHandshakeBuffer()
432 if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil {
435 if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil {
440 c.didResume = isResume
442 if err := hs.establishKeys(); err != nil {
445 if err := hs.readSessionTicket(); err != nil {
448 if err := hs.readFinished(c.serverFinished[:]); err != nil {
451 c.clientFinishedIsFirst = false
452 // Make sure the connection is still being verified whether or not this
453 // is a resumption. Resumptions currently don't reverify certificates so
454 // they don't call verifyServerCertificate. See Issue 31641.
455 if c.config.VerifyConnection != nil {
456 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
457 c.sendAlert(alertBadCertificate)
461 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
464 if _, err := c.flush(); err != nil {
468 if err := hs.doFullHandshake(); err != nil {
471 if err := hs.establishKeys(); err != nil {
474 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
477 if _, err := c.flush(); err != nil {
480 c.clientFinishedIsFirst = true
481 if err := hs.readSessionTicket(); err != nil {
484 if err := hs.readFinished(c.serverFinished[:]); err != nil {
489 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
490 c.isHandshakeComplete.Store(true)
495 func (hs *clientHandshakeState) pickCipherSuite() error {
496 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
497 hs.c.sendAlert(alertHandshakeFailure)
498 return errors.New("tls: server chose an unconfigured cipher suite")
501 hs.c.cipherSuite = hs.suite.id
505 func (hs *clientHandshakeState) doFullHandshake() error {
508 msg, err := c.readHandshake(&hs.finishedHash)
512 certMsg, ok := msg.(*certificateMsg)
513 if !ok || len(certMsg.certificates) == 0 {
514 c.sendAlert(alertUnexpectedMessage)
515 return unexpectedMessageError(certMsg, msg)
518 msg, err = c.readHandshake(&hs.finishedHash)
523 cs, ok := msg.(*certificateStatusMsg)
525 // RFC4366 on Certificate Status Request:
526 // The server MAY return a "certificate_status" message.
528 if !hs.serverHello.ocspStapling {
529 // If a server returns a "CertificateStatus" message, then the
530 // server MUST have included an extension of type "status_request"
531 // with empty "extension_data" in the extended server hello.
533 c.sendAlert(alertUnexpectedMessage)
534 return errors.New("tls: received unexpected CertificateStatus message")
537 c.ocspResponse = cs.response
539 msg, err = c.readHandshake(&hs.finishedHash)
545 if c.handshakes == 0 {
546 // If this is the first handshake on a connection, process and
547 // (optionally) verify the server's certificates.
548 if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
552 // This is a renegotiation handshake. We require that the
553 // server's identity (i.e. leaf certificate) is unchanged and
554 // thus any previous trust decision is still valid.
556 // See https://mitls.org/pages/attacks/3SHAKE for the
557 // motivation behind this requirement.
558 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
559 c.sendAlert(alertBadCertificate)
560 return errors.New("tls: server's identity changed during renegotiation")
564 keyAgreement := hs.suite.ka(c.vers)
566 skx, ok := msg.(*serverKeyExchangeMsg)
568 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
570 c.sendAlert(alertUnexpectedMessage)
574 msg, err = c.readHandshake(&hs.finishedHash)
580 var chainToSend *Certificate
581 var certRequested bool
582 certReq, ok := msg.(*certificateRequestMsg)
586 cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
587 if chainToSend, err = c.getClientCertificate(cri); err != nil {
588 c.sendAlert(alertInternalError)
592 msg, err = c.readHandshake(&hs.finishedHash)
598 shd, ok := msg.(*serverHelloDoneMsg)
600 c.sendAlert(alertUnexpectedMessage)
601 return unexpectedMessageError(shd, msg)
604 // If the server requested a certificate then we have to send a
605 // Certificate message, even if it's empty because we don't have a
606 // certificate to send.
608 certMsg = new(certificateMsg)
609 certMsg.certificates = chainToSend.Certificate
610 if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
615 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
617 c.sendAlert(alertInternalError)
621 if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
626 if chainToSend != nil && len(chainToSend.Certificate) > 0 {
627 certVerify := &certificateVerifyMsg{}
629 key, ok := chainToSend.PrivateKey.(crypto.Signer)
631 c.sendAlert(alertInternalError)
632 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
636 var sigHash crypto.Hash
637 if c.vers >= VersionTLS12 {
638 signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
640 c.sendAlert(alertIllegalParameter)
643 sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
645 return c.sendAlert(alertInternalError)
647 certVerify.hasSignatureAlgorithm = true
648 certVerify.signatureAlgorithm = signatureAlgorithm
650 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
652 c.sendAlert(alertIllegalParameter)
657 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
658 signOpts := crypto.SignerOpts(sigHash)
659 if sigType == signatureRSAPSS {
660 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
662 certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
664 c.sendAlert(alertInternalError)
668 if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
673 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
674 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
675 c.sendAlert(alertInternalError)
676 return errors.New("tls: failed to write to key log: " + err.Error())
679 hs.finishedHash.discardHandshakeBuffer()
684 func (hs *clientHandshakeState) establishKeys() error {
687 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
688 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
689 var clientCipher, serverCipher any
690 var clientHash, serverHash hash.Hash
691 if hs.suite.cipher != nil {
692 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
693 clientHash = hs.suite.mac(clientMAC)
694 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
695 serverHash = hs.suite.mac(serverMAC)
697 clientCipher = hs.suite.aead(clientKey, clientIV)
698 serverCipher = hs.suite.aead(serverKey, serverIV)
701 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
702 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
706 func (hs *clientHandshakeState) serverResumedSession() bool {
707 // If the server responded with the same sessionId then it means the
708 // sessionTicket is being used to resume a TLS session.
709 return hs.session != nil && hs.hello.sessionId != nil &&
710 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
713 func (hs *clientHandshakeState) processServerHello() (bool, error) {
716 if err := hs.pickCipherSuite(); err != nil {
720 if hs.serverHello.compressionMethod != compressionNone {
721 c.sendAlert(alertUnexpectedMessage)
722 return false, errors.New("tls: server selected unsupported compression format")
725 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
726 c.secureRenegotiation = true
727 if len(hs.serverHello.secureRenegotiation) != 0 {
728 c.sendAlert(alertHandshakeFailure)
729 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
733 if c.handshakes > 0 && c.secureRenegotiation {
734 var expectedSecureRenegotiation [24]byte
735 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
736 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
737 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
738 c.sendAlert(alertHandshakeFailure)
739 return false, errors.New("tls: incorrect renegotiation extension contents")
743 if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
744 c.sendAlert(alertUnsupportedExtension)
747 c.clientProtocol = hs.serverHello.alpnProtocol
749 c.scts = hs.serverHello.scts
751 if !hs.serverResumedSession() {
755 if hs.session.vers != c.vers {
756 c.sendAlert(alertHandshakeFailure)
757 return false, errors.New("tls: server resumed a session with a different version")
760 if hs.session.cipherSuite != hs.suite.id {
761 c.sendAlert(alertHandshakeFailure)
762 return false, errors.New("tls: server resumed a session with a different cipher suite")
765 // Restore masterSecret, peerCerts, and ocspResponse from previous state
766 hs.masterSecret = hs.session.masterSecret
767 c.peerCertificates = hs.session.serverCertificates
768 c.verifiedChains = hs.session.verifiedChains
769 c.ocspResponse = hs.session.ocspResponse
770 // Let the ServerHello SCTs override the session SCTs from the original
771 // connection, if any are provided
772 if len(c.scts) == 0 && len(hs.session.scts) != 0 {
773 c.scts = hs.session.scts
779 // checkALPN ensure that the server's choice of ALPN protocol is compatible with
780 // the protocols that we advertised in the Client Hello.
781 func checkALPN(clientProtos []string, serverProto string, quic bool) error {
782 if serverProto == "" {
783 if quic && len(clientProtos) > 0 {
784 // RFC 9001, Section 8.1
785 return errors.New("tls: server did not select an ALPN protocol")
789 if len(clientProtos) == 0 {
790 return errors.New("tls: server advertised unrequested ALPN extension")
792 for _, proto := range clientProtos {
793 if proto == serverProto {
797 return errors.New("tls: server selected unadvertised ALPN protocol")
800 func (hs *clientHandshakeState) readFinished(out []byte) error {
803 if err := c.readChangeCipherSpec(); err != nil {
807 // finishedMsg is included in the transcript, but not until after we
808 // check the client version, since the state before this message was
809 // sent is used during verification.
810 msg, err := c.readHandshake(nil)
814 serverFinished, ok := msg.(*finishedMsg)
816 c.sendAlert(alertUnexpectedMessage)
817 return unexpectedMessageError(serverFinished, msg)
820 verify := hs.finishedHash.serverSum(hs.masterSecret)
821 if len(verify) != len(serverFinished.verifyData) ||
822 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
823 c.sendAlert(alertHandshakeFailure)
824 return errors.New("tls: server's Finished message was incorrect")
827 if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil {
835 func (hs *clientHandshakeState) readSessionTicket() error {
836 if !hs.serverHello.ticketSupported {
841 msg, err := c.readHandshake(&hs.finishedHash)
845 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
847 c.sendAlert(alertUnexpectedMessage)
848 return unexpectedMessageError(sessionTicketMsg, msg)
851 hs.session = &ClientSessionState{
852 sessionTicket: sessionTicketMsg.ticket,
854 cipherSuite: hs.suite.id,
855 masterSecret: hs.masterSecret,
856 serverCertificates: c.peerCertificates,
857 verifiedChains: c.verifiedChains,
858 receivedAt: c.config.time(),
859 ocspResponse: c.ocspResponse,
866 func (hs *clientHandshakeState) sendFinished(out []byte) error {
869 if err := c.writeChangeCipherRecord(); err != nil {
873 finished := new(finishedMsg)
874 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
875 if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
878 copy(out, finished.verifyData)
882 // verifyServerCertificate parses and verifies the provided chain, setting
883 // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
884 func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
885 activeHandles := make([]*activeCert, len(certificates))
886 certs := make([]*x509.Certificate, len(certificates))
887 for i, asn1Data := range certificates {
888 cert, err := clientCertCache.newCert(asn1Data)
890 c.sendAlert(alertBadCertificate)
891 return errors.New("tls: failed to parse certificate from server: " + err.Error())
893 activeHandles[i] = cert
897 if !c.config.InsecureSkipVerify {
898 opts := x509.VerifyOptions{
899 Roots: c.config.RootCAs,
900 CurrentTime: c.config.time(),
901 DNSName: c.config.ServerName,
902 Intermediates: x509.NewCertPool(),
905 for _, cert := range certs[1:] {
906 opts.Intermediates.AddCert(cert)
909 c.verifiedChains, err = certs[0].Verify(opts)
911 c.sendAlert(alertBadCertificate)
912 return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
916 switch certs[0].PublicKey.(type) {
917 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
920 c.sendAlert(alertUnsupportedCertificate)
921 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
924 c.activeCertHandles = activeHandles
925 c.peerCertificates = certs
927 if c.config.VerifyPeerCertificate != nil {
928 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
929 c.sendAlert(alertBadCertificate)
934 if c.config.VerifyConnection != nil {
935 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
936 c.sendAlert(alertBadCertificate)
944 // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
945 // <= 1.2 CertificateRequest, making an effort to fill in missing information.
946 func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
947 cri := &CertificateRequestInfo{
948 AcceptableCAs: certReq.certificateAuthorities,
953 var rsaAvail, ecAvail bool
954 for _, certType := range certReq.certificateTypes {
956 case certTypeRSASign:
958 case certTypeECDSASign:
963 if !certReq.hasSignatureAlgorithm {
964 // Prior to TLS 1.2, signature schemes did not exist. In this case we
965 // make up a list based on the acceptable certificate types, to help
966 // GetClientCertificate and SupportsCertificate select the right certificate.
967 // The hash part of the SignatureScheme is a lie here, because
968 // TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
970 case rsaAvail && ecAvail:
971 cri.SignatureSchemes = []SignatureScheme{
972 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
973 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
976 cri.SignatureSchemes = []SignatureScheme{
977 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
980 cri.SignatureSchemes = []SignatureScheme{
981 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
987 // Filter the signature schemes based on the certificate types.
988 // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
989 cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
990 for _, sigScheme := range certReq.supportedSignatureAlgorithms {
991 sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
996 case signatureECDSA, signatureEd25519:
998 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1000 case signatureRSAPSS, signaturePKCS1v15:
1002 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1010 func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
1011 if c.config.GetClientCertificate != nil {
1012 return c.config.GetClientCertificate(cri)
1015 for _, chain := range c.config.Certificates {
1016 if err := cri.SupportsCertificate(&chain); err != nil {
1022 // No acceptable certificate found. Don't send a certificate.
1023 return new(Certificate), nil
1026 // clientSessionCacheKey returns a key used to cache sessionTickets that could
1027 // be used to resume previously negotiated TLS sessions with a server.
1028 func (c *Conn) clientSessionCacheKey() string {
1029 if len(c.config.ServerName) > 0 {
1030 return c.config.ServerName
1033 return c.conn.RemoteAddr().String()
1038 // hostnameInSNI converts name into an appropriate hostname for SNI.
1039 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
1040 // See RFC 6066, Section 3.
1041 func hostnameInSNI(name string) string {
1043 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
1044 host = host[1 : len(host)-1]
1046 if i := strings.LastIndex(host, "%"); i > 0 {
1049 if net.ParseIP(host) != nil {
1052 for len(name) > 0 && name[len(name)-1] == '.' {
1053 name = name[:len(name)-1]