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 := config.maxSupportedVersion()
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()
153 c.serverName = hello.serverName
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 we are negotiating a protocol version that's lower than what we
190 // support, check for the server downgrade canaries.
191 // See RFC 8446, Section 4.1.3.
192 maxVers := c.config.maxSupportedVersion()
193 tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
194 tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
195 if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
196 maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
197 c.sendAlert(alertIllegalParameter)
198 return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
201 if c.vers == VersionTLS13 {
202 hs := &clientHandshakeStateTLS13{
204 serverHello: serverHello,
206 ecdheParams: ecdheParams,
208 earlySecret: earlySecret,
209 binderKey: binderKey,
212 // In TLS 1.3, session tickets are delivered after the handshake.
213 return hs.handshake()
216 hs := &clientHandshakeState{
218 serverHello: serverHello,
223 if err := hs.handshake(); err != nil {
227 // If we had a successful handshake and hs.session is different from
228 // the one already cached - cache a new one.
229 if cacheKey != "" && hs.session != nil && session != hs.session {
230 c.config.ClientSessionCache.Put(cacheKey, hs.session)
236 func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
237 session *ClientSessionState, earlySecret, binderKey []byte) {
238 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
239 return "", nil, nil, nil
242 hello.ticketSupported = true
244 if hello.supportedVersions[0] == VersionTLS13 {
245 // Require DHE on resumption as it guarantees forward secrecy against
246 // compromise of the session ticket key. See RFC 8446, Section 4.2.9.
247 hello.pskModes = []uint8{pskModeDHE}
250 // Session resumption is not allowed if renegotiating because
251 // renegotiation is primarily used to allow a client to send a client
252 // certificate, which would be skipped if session resumption occurred.
253 if c.handshakes != 0 {
254 return "", nil, nil, nil
257 // Try to resume a previously negotiated TLS session, if available.
258 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
259 session, ok := c.config.ClientSessionCache.Get(cacheKey)
260 if !ok || session == nil {
261 return cacheKey, nil, nil, nil
264 // Check that version used for the previous session is still valid.
266 for _, v := range hello.supportedVersions {
267 if v == session.vers {
273 return cacheKey, nil, nil, nil
276 // Check that the cached server certificate is not expired, and that it's
277 // valid for the ServerName. This should be ensured by the cache key, but
278 // protect the application from a faulty ClientSessionCache implementation.
279 if !c.config.InsecureSkipVerify {
280 if len(session.verifiedChains) == 0 {
281 // The original connection had InsecureSkipVerify, while this doesn't.
282 return cacheKey, nil, nil, nil
284 serverCert := session.serverCertificates[0]
285 if c.config.time().After(serverCert.NotAfter) {
286 // Expired certificate, delete the entry.
287 c.config.ClientSessionCache.Put(cacheKey, nil)
288 return cacheKey, nil, nil, nil
290 if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
291 return cacheKey, nil, nil, nil
295 if session.vers != VersionTLS13 {
296 // In TLS 1.2 the cipher suite must match the resumed session. Ensure we
297 // are still offering it.
298 if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
299 return cacheKey, nil, nil, nil
302 hello.sessionTicket = session.sessionTicket
306 // Check that the session ticket is not expired.
307 if c.config.time().After(session.useBy) {
308 c.config.ClientSessionCache.Put(cacheKey, nil)
309 return cacheKey, nil, nil, nil
312 // In TLS 1.3 the KDF hash must match the resumed session. Ensure we
313 // offer at least one cipher suite with that hash.
314 cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
315 if cipherSuite == nil {
316 return cacheKey, nil, nil, nil
318 cipherSuiteOk := false
319 for _, offeredID := range hello.cipherSuites {
320 offeredSuite := cipherSuiteTLS13ByID(offeredID)
321 if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
327 return cacheKey, nil, nil, nil
330 // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
331 ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
332 identity := pskIdentity{
333 label: session.sessionTicket,
334 obfuscatedTicketAge: ticketAge + session.ageAdd,
336 hello.pskIdentities = []pskIdentity{identity}
337 hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
339 // Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
340 psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
341 session.nonce, cipherSuite.hash.Size())
342 earlySecret = cipherSuite.extract(psk, nil)
343 binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
344 transcript := cipherSuite.hash.New()
345 transcript.Write(hello.marshalWithoutBinders())
346 pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
347 hello.updateBinders(pskBinders)
352 func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
353 peerVersion := serverHello.vers
354 if serverHello.supportedVersion != 0 {
355 peerVersion = serverHello.supportedVersion
358 vers, ok := c.config.mutualVersion([]uint16{peerVersion})
360 c.sendAlert(alertProtocolVersion)
361 return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
372 // Does the handshake, either a full one or resumes old session. Requires hs.c,
373 // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
374 func (hs *clientHandshakeState) handshake() error {
377 isResume, err := hs.processServerHello()
382 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
384 // No signatures of the handshake are needed in a resumption.
385 // Otherwise, in a full handshake, if we don't have any certificates
386 // configured then we will never send a CertificateVerify message and
387 // thus no signatures are needed in that case either.
388 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
389 hs.finishedHash.discardHandshakeBuffer()
392 hs.finishedHash.Write(hs.hello.marshal())
393 hs.finishedHash.Write(hs.serverHello.marshal())
396 c.didResume = isResume
398 if err := hs.establishKeys(); err != nil {
401 if err := hs.readSessionTicket(); err != nil {
404 if err := hs.readFinished(c.serverFinished[:]); err != nil {
407 c.clientFinishedIsFirst = false
408 // Make sure the connection is still being verified whether or not this
409 // is a resumption. Resumptions currently don't reverify certificates so
410 // they don't call verifyServerCertificate. See Issue 31641.
411 if c.config.VerifyConnection != nil {
412 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
413 c.sendAlert(alertBadCertificate)
417 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
420 if _, err := c.flush(); err != nil {
424 if err := hs.doFullHandshake(); err != nil {
427 if err := hs.establishKeys(); err != nil {
430 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
433 if _, err := c.flush(); err != nil {
436 c.clientFinishedIsFirst = true
437 if err := hs.readSessionTicket(); err != nil {
440 if err := hs.readFinished(c.serverFinished[:]); err != nil {
445 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
446 atomic.StoreUint32(&c.handshakeStatus, 1)
451 func (hs *clientHandshakeState) pickCipherSuite() error {
452 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
453 hs.c.sendAlert(alertHandshakeFailure)
454 return errors.New("tls: server chose an unconfigured cipher suite")
457 hs.c.cipherSuite = hs.suite.id
461 func (hs *clientHandshakeState) doFullHandshake() error {
464 msg, err := c.readHandshake()
468 certMsg, ok := msg.(*certificateMsg)
469 if !ok || len(certMsg.certificates) == 0 {
470 c.sendAlert(alertUnexpectedMessage)
471 return unexpectedMessageError(certMsg, msg)
473 hs.finishedHash.Write(certMsg.marshal())
475 msg, err = c.readHandshake()
480 cs, ok := msg.(*certificateStatusMsg)
482 // RFC4366 on Certificate Status Request:
483 // The server MAY return a "certificate_status" message.
485 if !hs.serverHello.ocspStapling {
486 // If a server returns a "CertificateStatus" message, then the
487 // server MUST have included an extension of type "status_request"
488 // with empty "extension_data" in the extended server hello.
490 c.sendAlert(alertUnexpectedMessage)
491 return errors.New("tls: received unexpected CertificateStatus message")
493 hs.finishedHash.Write(cs.marshal())
495 c.ocspResponse = cs.response
497 msg, err = c.readHandshake()
503 if c.handshakes == 0 {
504 // If this is the first handshake on a connection, process and
505 // (optionally) verify the server's certificates.
506 if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
510 // This is a renegotiation handshake. We require that the
511 // server's identity (i.e. leaf certificate) is unchanged and
512 // thus any previous trust decision is still valid.
514 // See https://mitls.org/pages/attacks/3SHAKE for the
515 // motivation behind this requirement.
516 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
517 c.sendAlert(alertBadCertificate)
518 return errors.New("tls: server's identity changed during renegotiation")
522 keyAgreement := hs.suite.ka(c.vers)
524 skx, ok := msg.(*serverKeyExchangeMsg)
526 hs.finishedHash.Write(skx.marshal())
527 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
529 c.sendAlert(alertUnexpectedMessage)
533 msg, err = c.readHandshake()
539 var chainToSend *Certificate
540 var certRequested bool
541 certReq, ok := msg.(*certificateRequestMsg)
544 hs.finishedHash.Write(certReq.marshal())
546 cri := certificateRequestInfoFromMsg(c.vers, certReq)
547 if chainToSend, err = c.getClientCertificate(cri); err != nil {
548 c.sendAlert(alertInternalError)
552 msg, err = c.readHandshake()
558 shd, ok := msg.(*serverHelloDoneMsg)
560 c.sendAlert(alertUnexpectedMessage)
561 return unexpectedMessageError(shd, msg)
563 hs.finishedHash.Write(shd.marshal())
565 // If the server requested a certificate then we have to send a
566 // Certificate message, even if it's empty because we don't have a
567 // certificate to send.
569 certMsg = new(certificateMsg)
570 certMsg.certificates = chainToSend.Certificate
571 hs.finishedHash.Write(certMsg.marshal())
572 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
577 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
579 c.sendAlert(alertInternalError)
583 hs.finishedHash.Write(ckx.marshal())
584 if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
589 if chainToSend != nil && len(chainToSend.Certificate) > 0 {
590 certVerify := &certificateVerifyMsg{}
592 key, ok := chainToSend.PrivateKey.(crypto.Signer)
594 c.sendAlert(alertInternalError)
595 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
599 var sigHash crypto.Hash
600 if c.vers >= VersionTLS12 {
601 signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
603 c.sendAlert(alertIllegalParameter)
606 sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
608 return c.sendAlert(alertInternalError)
610 certVerify.hasSignatureAlgorithm = true
611 certVerify.signatureAlgorithm = signatureAlgorithm
613 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
615 c.sendAlert(alertIllegalParameter)
620 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
621 signOpts := crypto.SignerOpts(sigHash)
622 if sigType == signatureRSAPSS {
623 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
625 certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
627 c.sendAlert(alertInternalError)
631 hs.finishedHash.Write(certVerify.marshal())
632 if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
637 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
638 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
639 c.sendAlert(alertInternalError)
640 return errors.New("tls: failed to write to key log: " + err.Error())
643 hs.finishedHash.discardHandshakeBuffer()
648 func (hs *clientHandshakeState) establishKeys() error {
651 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
652 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
653 var clientCipher, serverCipher interface{}
654 var clientHash, serverHash hash.Hash
655 if hs.suite.cipher != nil {
656 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
657 clientHash = hs.suite.mac(clientMAC)
658 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
659 serverHash = hs.suite.mac(serverMAC)
661 clientCipher = hs.suite.aead(clientKey, clientIV)
662 serverCipher = hs.suite.aead(serverKey, serverIV)
665 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
666 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
670 func (hs *clientHandshakeState) serverResumedSession() bool {
671 // If the server responded with the same sessionId then it means the
672 // sessionTicket is being used to resume a TLS session.
673 return hs.session != nil && hs.hello.sessionId != nil &&
674 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
677 func (hs *clientHandshakeState) processServerHello() (bool, error) {
680 if err := hs.pickCipherSuite(); err != nil {
684 if hs.serverHello.compressionMethod != compressionNone {
685 c.sendAlert(alertUnexpectedMessage)
686 return false, errors.New("tls: server selected unsupported compression format")
689 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
690 c.secureRenegotiation = true
691 if len(hs.serverHello.secureRenegotiation) != 0 {
692 c.sendAlert(alertHandshakeFailure)
693 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
697 if c.handshakes > 0 && c.secureRenegotiation {
698 var expectedSecureRenegotiation [24]byte
699 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
700 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
701 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
702 c.sendAlert(alertHandshakeFailure)
703 return false, errors.New("tls: incorrect renegotiation extension contents")
707 if hs.serverHello.alpnProtocol != "" {
708 if len(hs.hello.alpnProtocols) == 0 {
709 c.sendAlert(alertUnsupportedExtension)
710 return false, errors.New("tls: server advertised unrequested ALPN extension")
712 if mutualProtocol([]string{hs.serverHello.alpnProtocol}, hs.hello.alpnProtocols) == "" {
713 c.sendAlert(alertUnsupportedExtension)
714 return false, errors.New("tls: server selected unadvertised ALPN protocol")
716 c.clientProtocol = hs.serverHello.alpnProtocol
719 c.scts = hs.serverHello.scts
721 if !hs.serverResumedSession() {
725 if hs.session.vers != c.vers {
726 c.sendAlert(alertHandshakeFailure)
727 return false, errors.New("tls: server resumed a session with a different version")
730 if hs.session.cipherSuite != hs.suite.id {
731 c.sendAlert(alertHandshakeFailure)
732 return false, errors.New("tls: server resumed a session with a different cipher suite")
735 // Restore masterSecret, peerCerts, and ocspResponse from previous state
736 hs.masterSecret = hs.session.masterSecret
737 c.peerCertificates = hs.session.serverCertificates
738 c.verifiedChains = hs.session.verifiedChains
739 c.ocspResponse = hs.session.ocspResponse
740 // Let the ServerHello SCTs override the session SCTs from the original
741 // connection, if any are provided
742 if len(c.scts) == 0 && len(hs.session.scts) != 0 {
743 c.scts = hs.session.scts
749 func (hs *clientHandshakeState) readFinished(out []byte) error {
752 if err := c.readChangeCipherSpec(); err != nil {
756 msg, err := c.readHandshake()
760 serverFinished, ok := msg.(*finishedMsg)
762 c.sendAlert(alertUnexpectedMessage)
763 return unexpectedMessageError(serverFinished, msg)
766 verify := hs.finishedHash.serverSum(hs.masterSecret)
767 if len(verify) != len(serverFinished.verifyData) ||
768 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
769 c.sendAlert(alertHandshakeFailure)
770 return errors.New("tls: server's Finished message was incorrect")
772 hs.finishedHash.Write(serverFinished.marshal())
777 func (hs *clientHandshakeState) readSessionTicket() error {
778 if !hs.serverHello.ticketSupported {
783 msg, err := c.readHandshake()
787 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
789 c.sendAlert(alertUnexpectedMessage)
790 return unexpectedMessageError(sessionTicketMsg, msg)
792 hs.finishedHash.Write(sessionTicketMsg.marshal())
794 hs.session = &ClientSessionState{
795 sessionTicket: sessionTicketMsg.ticket,
797 cipherSuite: hs.suite.id,
798 masterSecret: hs.masterSecret,
799 serverCertificates: c.peerCertificates,
800 verifiedChains: c.verifiedChains,
801 receivedAt: c.config.time(),
802 ocspResponse: c.ocspResponse,
809 func (hs *clientHandshakeState) sendFinished(out []byte) error {
812 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
816 finished := new(finishedMsg)
817 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
818 hs.finishedHash.Write(finished.marshal())
819 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
822 copy(out, finished.verifyData)
826 // verifyServerCertificate parses and verifies the provided chain, setting
827 // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
828 func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
829 certs := make([]*x509.Certificate, len(certificates))
830 for i, asn1Data := range certificates {
831 cert, err := x509.ParseCertificate(asn1Data)
833 c.sendAlert(alertBadCertificate)
834 return errors.New("tls: failed to parse certificate from server: " + err.Error())
839 if !c.config.InsecureSkipVerify {
840 opts := x509.VerifyOptions{
841 IsBoring: isBoringCertificate,
843 Roots: c.config.RootCAs,
844 CurrentTime: c.config.time(),
845 DNSName: c.config.ServerName,
846 Intermediates: x509.NewCertPool(),
848 for _, cert := range certs[1:] {
849 opts.Intermediates.AddCert(cert)
852 c.verifiedChains, err = certs[0].Verify(opts)
854 c.sendAlert(alertBadCertificate)
859 switch certs[0].PublicKey.(type) {
860 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
863 c.sendAlert(alertUnsupportedCertificate)
864 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
867 c.peerCertificates = certs
869 if c.config.VerifyPeerCertificate != nil {
870 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
871 c.sendAlert(alertBadCertificate)
876 if c.config.VerifyConnection != nil {
877 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
878 c.sendAlert(alertBadCertificate)
886 // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
887 // <= 1.2 CertificateRequest, making an effort to fill in missing information.
888 func certificateRequestInfoFromMsg(vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
889 cri := &CertificateRequestInfo{
890 AcceptableCAs: certReq.certificateAuthorities,
894 var rsaAvail, ecAvail bool
895 for _, certType := range certReq.certificateTypes {
897 case certTypeRSASign:
899 case certTypeECDSASign:
904 if !certReq.hasSignatureAlgorithm {
905 // Prior to TLS 1.2, signature schemes did not exist. In this case we
906 // make up a list based on the acceptable certificate types, to help
907 // GetClientCertificate and SupportsCertificate select the right certificate.
908 // The hash part of the SignatureScheme is a lie here, because
909 // TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
911 case rsaAvail && ecAvail:
912 cri.SignatureSchemes = []SignatureScheme{
913 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
914 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
917 cri.SignatureSchemes = []SignatureScheme{
918 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
921 cri.SignatureSchemes = []SignatureScheme{
922 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
928 // Filter the signature schemes based on the certificate types.
929 // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
930 cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
931 for _, sigScheme := range certReq.supportedSignatureAlgorithms {
932 sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
937 case signatureECDSA, signatureEd25519:
939 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
941 case signatureRSAPSS, signaturePKCS1v15:
943 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
951 func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
952 if c.config.GetClientCertificate != nil {
953 return c.config.GetClientCertificate(cri)
956 for _, chain := range c.config.Certificates {
957 if err := cri.SupportsCertificate(&chain); err != nil {
963 // No acceptable certificate found. Don't send a certificate.
964 return new(Certificate), nil
967 // clientSessionCacheKey returns a key used to cache sessionTickets that could
968 // be used to resume previously negotiated TLS sessions with a server.
969 func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
970 if len(config.ServerName) > 0 {
971 return config.ServerName
973 return serverAddr.String()
976 // mutualProtocol finds the mutual ALPN protocol given list of possible
977 // protocols and a list of the preference order.
978 func mutualProtocol(protos, preferenceProtos []string) string {
979 for _, s := range preferenceProtos {
980 for _, c := range protos {
989 // hostnameInSNI converts name into an appropriate hostname for SNI.
990 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
991 // See RFC 6066, Section 3.
992 func hostnameInSNI(name string) string {
994 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
995 host = host[1 : len(host)-1]
997 if i := strings.LastIndex(host, "%"); i > 0 {
1000 if net.ParseIP(host) != nil {
1003 for len(name) > 0 && name[len(name)-1] == '.' {
1004 name = name[:len(name)-1]