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 *SessionState // the session being resumed
35 ticket []byte // a fresh ticket received during this handshake
38 var testingOnlyForceClientHelloSignatureAlgorithms []SignatureScheme
40 func (c *Conn) makeClientHello() (*clientHelloMsg, *ecdh.PrivateKey, error) {
42 if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
43 return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
47 for _, proto := range config.NextProtos {
48 if l := len(proto); l == 0 || l > 255 {
49 return nil, nil, errors.New("tls: invalid NextProtos value")
51 nextProtosLength += 1 + l
54 if nextProtosLength > 0xffff {
55 return nil, nil, errors.New("tls: NextProtos values too large")
58 supportedVersions := config.supportedVersions(roleClient)
59 if len(supportedVersions) == 0 {
60 return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
63 clientHelloVersion := config.maxSupportedVersion(roleClient)
64 // The version at the beginning of the ClientHello was capped at TLS 1.2
65 // for compatibility reasons. The supported_versions extension is used
66 // to negotiate versions now. See RFC 8446, Section 4.2.1.
67 if clientHelloVersion > VersionTLS12 {
68 clientHelloVersion = VersionTLS12
71 hello := &clientHelloMsg{
72 vers: clientHelloVersion,
73 compressionMethods: []uint8{compressionNone},
74 random: make([]byte, 32),
77 serverName: hostnameInSNI(config.ServerName),
78 supportedCurves: config.curvePreferences(),
79 supportedPoints: []uint8{pointFormatUncompressed},
80 secureRenegotiationSupported: true,
81 alpnProtocols: config.NextProtos,
82 supportedVersions: supportedVersions,
86 hello.secureRenegotiation = c.clientFinished[:]
89 preferenceOrder := cipherSuitesPreferenceOrder
90 if !hasAESGCMHardwareSupport {
91 preferenceOrder = cipherSuitesPreferenceOrderNoAES
93 configCipherSuites := config.cipherSuites()
94 hello.cipherSuites = make([]uint16, 0, len(configCipherSuites))
96 for _, suiteId := range preferenceOrder {
97 suite := mutualCipherSuite(configCipherSuites, suiteId)
101 // Don't advertise TLS 1.2-only cipher suites unless
102 // we're attempting TLS 1.2.
103 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
106 hello.cipherSuites = append(hello.cipherSuites, suiteId)
109 _, err := io.ReadFull(config.rand(), hello.random)
111 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
114 // A random session ID is used to detect when the server accepted a ticket
115 // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
116 // a compatibility measure (see RFC 8446, Section 4.1.2).
118 // The session ID is not set for QUIC connections (see RFC 9001, Section 8.4).
120 hello.sessionId = make([]byte, 32)
121 if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
122 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
126 if hello.vers >= VersionTLS12 {
127 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
129 if testingOnlyForceClientHelloSignatureAlgorithms != nil {
130 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
133 var key *ecdh.PrivateKey
134 if hello.supportedVersions[0] == VersionTLS13 {
135 if hasAESGCMHardwareSupport {
136 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
138 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
141 curveID := config.curvePreferences()[0]
142 if _, ok := curveForCurveID(curveID); !ok {
143 return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
145 key, err = generateECDHEKey(config.rand(), curveID)
149 hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
153 p, err := c.quicGetTransportParameters()
160 hello.quicTransportParameters = p
163 return hello, key, nil
166 func (c *Conn) clientHandshake(ctx context.Context) (err error) {
168 c.config = defaultConfig()
171 // This may be a renegotiation handshake, in which case some fields
175 hello, ecdheKey, err := c.makeClientHello()
179 c.serverName = hello.serverName
181 session, earlySecret, binderKey, err := c.loadSession(hello)
187 // If we got a handshake failure when resuming a session, throw away
188 // the session ticket. See RFC 5077, Section 3.2.
190 // RFC 8446 makes no mention of dropping tickets on failure, but it
191 // does require servers to abort on invalid binders, so we need to
192 // delete tickets to recover from a corrupted PSK.
194 if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
195 c.config.ClientSessionCache.Put(cacheKey, nil)
201 if _, err := c.writeHandshakeRecord(hello, nil); err != nil {
205 // serverHelloMsg is not included in the transcript
206 msg, err := c.readHandshake(nil)
211 serverHello, ok := msg.(*serverHelloMsg)
213 c.sendAlert(alertUnexpectedMessage)
214 return unexpectedMessageError(serverHello, msg)
217 if err := c.pickTLSVersion(serverHello); err != nil {
221 // If we are negotiating a protocol version that's lower than what we
222 // support, check for the server downgrade canaries.
223 // See RFC 8446, Section 4.1.3.
224 maxVers := c.config.maxSupportedVersion(roleClient)
225 tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
226 tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
227 if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
228 maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
229 c.sendAlert(alertIllegalParameter)
230 return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
233 if c.vers == VersionTLS13 {
234 hs := &clientHandshakeStateTLS13{
237 serverHello: serverHello,
241 earlySecret: earlySecret,
242 binderKey: binderKey,
245 // In TLS 1.3, session tickets are delivered after the handshake.
246 return hs.handshake()
249 hs := &clientHandshakeState{
252 serverHello: serverHello,
257 if err := hs.handshake(); err != nil {
264 func (c *Conn) loadSession(hello *clientHelloMsg) (
265 session *SessionState, earlySecret, binderKey []byte, err error) {
266 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
267 return nil, nil, nil, nil
270 hello.ticketSupported = true
272 if hello.supportedVersions[0] == VersionTLS13 {
273 // Require DHE on resumption as it guarantees forward secrecy against
274 // compromise of the session ticket key. See RFC 8446, Section 4.2.9.
275 hello.pskModes = []uint8{pskModeDHE}
278 // Session resumption is not allowed if renegotiating because
279 // renegotiation is primarily used to allow a client to send a client
280 // certificate, which would be skipped if session resumption occurred.
281 if c.handshakes != 0 {
282 return nil, nil, nil, nil
285 // Try to resume a previously negotiated TLS session, if available.
286 cacheKey := c.clientSessionCacheKey()
288 return nil, nil, nil, nil
290 cs, ok := c.config.ClientSessionCache.Get(cacheKey)
291 if !ok || cs == nil {
292 return nil, nil, nil, nil
296 // Check that version used for the previous session is still valid.
298 for _, v := range hello.supportedVersions {
299 if v == session.version {
305 return nil, nil, nil, nil
308 // Check that the cached server certificate is not expired, and that it's
309 // valid for the ServerName. This should be ensured by the cache key, but
310 // protect the application from a faulty ClientSessionCache implementation.
311 if !c.config.InsecureSkipVerify {
312 if len(session.verifiedChains) == 0 {
313 // The original connection had InsecureSkipVerify, while this doesn't.
314 return nil, nil, nil, nil
316 serverCert := session.peerCertificates[0]
317 if c.config.time().After(serverCert.NotAfter) {
318 // Expired certificate, delete the entry.
319 c.config.ClientSessionCache.Put(cacheKey, nil)
320 return nil, nil, nil, nil
322 if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
323 return nil, nil, nil, nil
327 if session.version != VersionTLS13 {
328 // In TLS 1.2 the cipher suite must match the resumed session. Ensure we
329 // are still offering it.
330 if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
331 return nil, nil, nil, nil
334 hello.sessionTicket = cs.ticket
338 // Check that the session ticket is not expired.
339 if c.config.time().After(time.Unix(int64(session.useBy), 0)) {
340 c.config.ClientSessionCache.Put(cacheKey, nil)
341 return nil, nil, nil, nil
344 // In TLS 1.3 the KDF hash must match the resumed session. Ensure we
345 // offer at least one cipher suite with that hash.
346 cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
347 if cipherSuite == nil {
348 return nil, nil, nil, nil
350 cipherSuiteOk := false
351 for _, offeredID := range hello.cipherSuites {
352 offeredSuite := cipherSuiteTLS13ByID(offeredID)
353 if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
359 return nil, nil, nil, nil
362 // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
363 ticketAge := c.config.time().Sub(time.Unix(int64(session.createdAt), 0))
364 identity := pskIdentity{
366 obfuscatedTicketAge: uint32(ticketAge/time.Millisecond) + session.ageAdd,
368 hello.pskIdentities = []pskIdentity{identity}
369 hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
371 // Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
372 earlySecret = cipherSuite.extract(session.secret, nil)
373 binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
374 transcript := cipherSuite.hash.New()
375 helloBytes, err := hello.marshalWithoutBinders()
377 return nil, nil, nil, err
379 transcript.Write(helloBytes)
380 pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
381 if err := hello.updateBinders(pskBinders); err != nil {
382 return nil, nil, nil, err
388 func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
389 peerVersion := serverHello.vers
390 if serverHello.supportedVersion != 0 {
391 peerVersion = serverHello.supportedVersion
394 vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion})
396 c.sendAlert(alertProtocolVersion)
397 return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
408 // Does the handshake, either a full one or resumes old session. Requires hs.c,
409 // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
410 func (hs *clientHandshakeState) handshake() error {
413 isResume, err := hs.processServerHello()
418 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
420 // No signatures of the handshake are needed in a resumption.
421 // Otherwise, in a full handshake, if we don't have any certificates
422 // configured then we will never send a CertificateVerify message and
423 // thus no signatures are needed in that case either.
424 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
425 hs.finishedHash.discardHandshakeBuffer()
428 if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil {
431 if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil {
436 c.didResume = isResume
438 if err := hs.establishKeys(); err != nil {
441 if err := hs.readSessionTicket(); err != nil {
444 if err := hs.readFinished(c.serverFinished[:]); err != nil {
447 c.clientFinishedIsFirst = false
448 // Make sure the connection is still being verified whether or not this
449 // is a resumption. Resumptions currently don't reverify certificates so
450 // they don't call verifyServerCertificate. See Issue 31641.
451 if c.config.VerifyConnection != nil {
452 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
453 c.sendAlert(alertBadCertificate)
457 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
460 if _, err := c.flush(); err != nil {
464 if err := hs.doFullHandshake(); err != nil {
467 if err := hs.establishKeys(); err != nil {
470 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
473 if _, err := c.flush(); err != nil {
476 c.clientFinishedIsFirst = true
477 if err := hs.readSessionTicket(); err != nil {
480 if err := hs.readFinished(c.serverFinished[:]); err != nil {
484 if err := hs.saveSessionTicket(); err != nil {
488 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
489 c.isHandshakeComplete.Store(true)
494 func (hs *clientHandshakeState) pickCipherSuite() error {
495 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
496 hs.c.sendAlert(alertHandshakeFailure)
497 return errors.New("tls: server chose an unconfigured cipher suite")
500 hs.c.cipherSuite = hs.suite.id
504 func (hs *clientHandshakeState) doFullHandshake() error {
507 msg, err := c.readHandshake(&hs.finishedHash)
511 certMsg, ok := msg.(*certificateMsg)
512 if !ok || len(certMsg.certificates) == 0 {
513 c.sendAlert(alertUnexpectedMessage)
514 return unexpectedMessageError(certMsg, msg)
517 msg, err = c.readHandshake(&hs.finishedHash)
522 cs, ok := msg.(*certificateStatusMsg)
524 // RFC4366 on Certificate Status Request:
525 // The server MAY return a "certificate_status" message.
527 if !hs.serverHello.ocspStapling {
528 // If a server returns a "CertificateStatus" message, then the
529 // server MUST have included an extension of type "status_request"
530 // with empty "extension_data" in the extended server hello.
532 c.sendAlert(alertUnexpectedMessage)
533 return errors.New("tls: received unexpected CertificateStatus message")
536 c.ocspResponse = cs.response
538 msg, err = c.readHandshake(&hs.finishedHash)
544 if c.handshakes == 0 {
545 // If this is the first handshake on a connection, process and
546 // (optionally) verify the server's certificates.
547 if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
551 // This is a renegotiation handshake. We require that the
552 // server's identity (i.e. leaf certificate) is unchanged and
553 // thus any previous trust decision is still valid.
555 // See https://mitls.org/pages/attacks/3SHAKE for the
556 // motivation behind this requirement.
557 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
558 c.sendAlert(alertBadCertificate)
559 return errors.New("tls: server's identity changed during renegotiation")
563 keyAgreement := hs.suite.ka(c.vers)
565 skx, ok := msg.(*serverKeyExchangeMsg)
567 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
569 c.sendAlert(alertUnexpectedMessage)
573 msg, err = c.readHandshake(&hs.finishedHash)
579 var chainToSend *Certificate
580 var certRequested bool
581 certReq, ok := msg.(*certificateRequestMsg)
585 cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
586 if chainToSend, err = c.getClientCertificate(cri); err != nil {
587 c.sendAlert(alertInternalError)
591 msg, err = c.readHandshake(&hs.finishedHash)
597 shd, ok := msg.(*serverHelloDoneMsg)
599 c.sendAlert(alertUnexpectedMessage)
600 return unexpectedMessageError(shd, msg)
603 // If the server requested a certificate then we have to send a
604 // Certificate message, even if it's empty because we don't have a
605 // certificate to send.
607 certMsg = new(certificateMsg)
608 certMsg.certificates = chainToSend.Certificate
609 if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
614 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
616 c.sendAlert(alertInternalError)
620 if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
625 if chainToSend != nil && len(chainToSend.Certificate) > 0 {
626 certVerify := &certificateVerifyMsg{}
628 key, ok := chainToSend.PrivateKey.(crypto.Signer)
630 c.sendAlert(alertInternalError)
631 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
635 var sigHash crypto.Hash
636 if c.vers >= VersionTLS12 {
637 signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
639 c.sendAlert(alertIllegalParameter)
642 sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
644 return c.sendAlert(alertInternalError)
646 certVerify.hasSignatureAlgorithm = true
647 certVerify.signatureAlgorithm = signatureAlgorithm
649 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
651 c.sendAlert(alertIllegalParameter)
656 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
657 signOpts := crypto.SignerOpts(sigHash)
658 if sigType == signatureRSAPSS {
659 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
661 certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
663 c.sendAlert(alertInternalError)
667 if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
672 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
673 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
674 c.sendAlert(alertInternalError)
675 return errors.New("tls: failed to write to key log: " + err.Error())
678 hs.finishedHash.discardHandshakeBuffer()
683 func (hs *clientHandshakeState) establishKeys() error {
686 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
687 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
688 var clientCipher, serverCipher any
689 var clientHash, serverHash hash.Hash
690 if hs.suite.cipher != nil {
691 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
692 clientHash = hs.suite.mac(clientMAC)
693 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
694 serverHash = hs.suite.mac(serverMAC)
696 clientCipher = hs.suite.aead(clientKey, clientIV)
697 serverCipher = hs.suite.aead(serverKey, serverIV)
700 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
701 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
705 func (hs *clientHandshakeState) serverResumedSession() bool {
706 // If the server responded with the same sessionId then it means the
707 // sessionTicket is being used to resume a TLS session.
708 return hs.session != nil && hs.hello.sessionId != nil &&
709 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
712 func (hs *clientHandshakeState) processServerHello() (bool, error) {
715 if err := hs.pickCipherSuite(); err != nil {
719 if hs.serverHello.compressionMethod != compressionNone {
720 c.sendAlert(alertUnexpectedMessage)
721 return false, errors.New("tls: server selected unsupported compression format")
724 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
725 c.secureRenegotiation = true
726 if len(hs.serverHello.secureRenegotiation) != 0 {
727 c.sendAlert(alertHandshakeFailure)
728 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
732 if c.handshakes > 0 && c.secureRenegotiation {
733 var expectedSecureRenegotiation [24]byte
734 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
735 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
736 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
737 c.sendAlert(alertHandshakeFailure)
738 return false, errors.New("tls: incorrect renegotiation extension contents")
742 if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
743 c.sendAlert(alertUnsupportedExtension)
746 c.clientProtocol = hs.serverHello.alpnProtocol
748 c.scts = hs.serverHello.scts
750 if !hs.serverResumedSession() {
754 if hs.session.version != c.vers {
755 c.sendAlert(alertHandshakeFailure)
756 return false, errors.New("tls: server resumed a session with a different version")
759 if hs.session.cipherSuite != hs.suite.id {
760 c.sendAlert(alertHandshakeFailure)
761 return false, errors.New("tls: server resumed a session with a different cipher suite")
764 // Restore master secret and certificates from previous state
765 hs.masterSecret = hs.session.secret
766 c.peerCertificates = hs.session.peerCertificates
767 c.activeCertHandles = hs.c.activeCertHandles
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 if !hs.hello.ticketSupported {
842 c.sendAlert(alertIllegalParameter)
843 return errors.New("tls: server sent unrequested session ticket")
846 msg, err := c.readHandshake(&hs.finishedHash)
850 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
852 c.sendAlert(alertUnexpectedMessage)
853 return unexpectedMessageError(sessionTicketMsg, msg)
856 hs.ticket = sessionTicketMsg.ticket
860 func (hs *clientHandshakeState) saveSessionTicket() error {
861 if hs.ticket == nil {
866 cacheKey := c.clientSessionCacheKey()
871 session, err := c.sessionState()
875 session.secret = hs.masterSecret
877 cs := &ClientSessionState{ticket: hs.ticket, session: session}
878 c.config.ClientSessionCache.Put(cacheKey, cs)
882 func (hs *clientHandshakeState) sendFinished(out []byte) error {
885 if err := c.writeChangeCipherRecord(); err != nil {
889 finished := new(finishedMsg)
890 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
891 if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
894 copy(out, finished.verifyData)
898 // verifyServerCertificate parses and verifies the provided chain, setting
899 // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
900 func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
901 activeHandles := make([]*activeCert, len(certificates))
902 certs := make([]*x509.Certificate, len(certificates))
903 for i, asn1Data := range certificates {
904 cert, err := globalCertCache.newCert(asn1Data)
906 c.sendAlert(alertBadCertificate)
907 return errors.New("tls: failed to parse certificate from server: " + err.Error())
909 activeHandles[i] = cert
913 if !c.config.InsecureSkipVerify {
914 opts := x509.VerifyOptions{
915 Roots: c.config.RootCAs,
916 CurrentTime: c.config.time(),
917 DNSName: c.config.ServerName,
918 Intermediates: x509.NewCertPool(),
921 for _, cert := range certs[1:] {
922 opts.Intermediates.AddCert(cert)
925 c.verifiedChains, err = certs[0].Verify(opts)
927 c.sendAlert(alertBadCertificate)
928 return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
932 switch certs[0].PublicKey.(type) {
933 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
936 c.sendAlert(alertUnsupportedCertificate)
937 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
940 c.activeCertHandles = activeHandles
941 c.peerCertificates = certs
943 if c.config.VerifyPeerCertificate != nil {
944 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
945 c.sendAlert(alertBadCertificate)
950 if c.config.VerifyConnection != nil {
951 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
952 c.sendAlert(alertBadCertificate)
960 // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
961 // <= 1.2 CertificateRequest, making an effort to fill in missing information.
962 func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
963 cri := &CertificateRequestInfo{
964 AcceptableCAs: certReq.certificateAuthorities,
969 var rsaAvail, ecAvail bool
970 for _, certType := range certReq.certificateTypes {
972 case certTypeRSASign:
974 case certTypeECDSASign:
979 if !certReq.hasSignatureAlgorithm {
980 // Prior to TLS 1.2, signature schemes did not exist. In this case we
981 // make up a list based on the acceptable certificate types, to help
982 // GetClientCertificate and SupportsCertificate select the right certificate.
983 // The hash part of the SignatureScheme is a lie here, because
984 // TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
986 case rsaAvail && ecAvail:
987 cri.SignatureSchemes = []SignatureScheme{
988 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
989 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
992 cri.SignatureSchemes = []SignatureScheme{
993 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
996 cri.SignatureSchemes = []SignatureScheme{
997 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
1003 // Filter the signature schemes based on the certificate types.
1004 // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
1005 cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
1006 for _, sigScheme := range certReq.supportedSignatureAlgorithms {
1007 sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
1012 case signatureECDSA, signatureEd25519:
1014 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1016 case signatureRSAPSS, signaturePKCS1v15:
1018 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1026 func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
1027 if c.config.GetClientCertificate != nil {
1028 return c.config.GetClientCertificate(cri)
1031 for _, chain := range c.config.Certificates {
1032 if err := cri.SupportsCertificate(&chain); err != nil {
1038 // No acceptable certificate found. Don't send a certificate.
1039 return new(Certificate), nil
1042 // clientSessionCacheKey returns a key used to cache sessionTickets that could
1043 // be used to resume previously negotiated TLS sessions with a server.
1044 func (c *Conn) clientSessionCacheKey() string {
1045 if len(c.config.ServerName) > 0 {
1046 return c.config.ServerName
1049 return c.conn.RemoteAddr().String()
1054 // hostnameInSNI converts name into an appropriate hostname for SNI.
1055 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
1056 // See RFC 6066, Section 3.
1057 func hostnameInSNI(name string) string {
1059 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
1060 host = host[1 : len(host)-1]
1062 if i := strings.LastIndex(host, "%"); i > 0 {
1065 if net.ParseIP(host) != nil {
1068 for len(name) > 0 && name[len(name)-1] == '.' {
1069 name = name[:len(name)-1]