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.
22 // serverHandshakeState contains details of a server handshake in progress.
23 // It's discarded once the handshake has completed.
24 type serverHandshakeState struct {
27 clientHello *clientHelloMsg
34 sessionState *SessionState
35 finishedHash finishedHash
40 // serverHandshake performs a TLS handshake as a server.
41 func (c *Conn) serverHandshake(ctx context.Context) error {
42 clientHello, err := c.readClientHello(ctx)
47 if c.vers == VersionTLS13 {
48 hs := serverHandshakeStateTLS13{
51 clientHello: clientHello,
56 hs := serverHandshakeState{
59 clientHello: clientHello,
64 func (hs *serverHandshakeState) handshake() error {
67 if err := hs.processClientHello(); err != nil {
71 // For an overview of TLS handshaking, see RFC 5246, Section 7.3.
73 if err := hs.checkForResumption(); err != nil {
76 if hs.sessionState != nil {
77 // The client has included a session ticket and so we do an abbreviated handshake.
78 if err := hs.doResumeHandshake(); err != nil {
81 if err := hs.establishKeys(); err != nil {
84 if err := hs.sendSessionTicket(); err != nil {
87 if err := hs.sendFinished(c.serverFinished[:]); err != nil {
90 if _, err := c.flush(); err != nil {
93 c.clientFinishedIsFirst = false
94 if err := hs.readFinished(nil); err != nil {
98 // The client didn't include a session ticket, or it wasn't
99 // valid so we do a full handshake.
100 if err := hs.pickCipherSuite(); err != nil {
103 if err := hs.doFullHandshake(); err != nil {
106 if err := hs.establishKeys(); err != nil {
109 if err := hs.readFinished(c.clientFinished[:]); err != nil {
112 c.clientFinishedIsFirst = true
114 if err := hs.sendSessionTicket(); err != nil {
117 if err := hs.sendFinished(nil); err != nil {
120 if _, err := c.flush(); err != nil {
125 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
126 c.isHandshakeComplete.Store(true)
131 // readClientHello reads a ClientHello message and selects the protocol version.
132 func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) {
133 // clientHelloMsg is included in the transcript, but we haven't initialized
134 // it yet. The respective handshake functions will record it themselves.
135 msg, err := c.readHandshake(nil)
139 clientHello, ok := msg.(*clientHelloMsg)
141 c.sendAlert(alertUnexpectedMessage)
142 return nil, unexpectedMessageError(clientHello, msg)
145 var configForClient *Config
146 originalConfig := c.config
147 if c.config.GetConfigForClient != nil {
148 chi := clientHelloInfo(ctx, c, clientHello)
149 if configForClient, err = c.config.GetConfigForClient(chi); err != nil {
150 c.sendAlert(alertInternalError)
152 } else if configForClient != nil {
153 c.config = configForClient
156 c.ticketKeys = originalConfig.ticketKeys(configForClient)
158 clientVersions := clientHello.supportedVersions
159 if len(clientHello.supportedVersions) == 0 {
160 clientVersions = supportedVersionsFromMax(clientHello.vers)
162 c.vers, ok = c.config.mutualVersion(roleServer, clientVersions)
164 c.sendAlert(alertProtocolVersion)
165 return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
168 c.in.version = c.vers
169 c.out.version = c.vers
171 return clientHello, nil
174 func (hs *serverHandshakeState) processClientHello() error {
177 hs.hello = new(serverHelloMsg)
178 hs.hello.vers = c.vers
180 foundCompression := false
181 // We only support null compression, so check that the client offered it.
182 for _, compression := range hs.clientHello.compressionMethods {
183 if compression == compressionNone {
184 foundCompression = true
189 if !foundCompression {
190 c.sendAlert(alertHandshakeFailure)
191 return errors.New("tls: client does not support uncompressed connections")
194 hs.hello.random = make([]byte, 32)
195 serverRandom := hs.hello.random
196 // Downgrade protection canaries. See RFC 8446, Section 4.1.3.
197 maxVers := c.config.maxSupportedVersion(roleServer)
198 if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary {
199 if c.vers == VersionTLS12 {
200 copy(serverRandom[24:], downgradeCanaryTLS12)
202 copy(serverRandom[24:], downgradeCanaryTLS11)
204 serverRandom = serverRandom[:24]
206 _, err := io.ReadFull(c.config.rand(), serverRandom)
208 c.sendAlert(alertInternalError)
212 if len(hs.clientHello.secureRenegotiation) != 0 {
213 c.sendAlert(alertHandshakeFailure)
214 return errors.New("tls: initial handshake had non-empty renegotiation extension")
217 hs.hello.extendedMasterSecret = hs.clientHello.extendedMasterSecret
218 hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
219 hs.hello.compressionMethod = compressionNone
220 if len(hs.clientHello.serverName) > 0 {
221 c.serverName = hs.clientHello.serverName
224 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, false)
226 c.sendAlert(alertNoApplicationProtocol)
229 hs.hello.alpnProtocol = selectedProto
230 c.clientProtocol = selectedProto
232 hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
234 if err == errNoCertificates {
235 c.sendAlert(alertUnrecognizedName)
237 c.sendAlert(alertInternalError)
241 if hs.clientHello.scts {
242 hs.hello.scts = hs.cert.SignedCertificateTimestamps
245 hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
247 if hs.ecdheOk && len(hs.clientHello.supportedPoints) > 0 {
248 // Although omitting the ec_point_formats extension is permitted, some
249 // old OpenSSL version will refuse to handshake if not present.
251 // Per RFC 4492, section 5.1.2, implementations MUST support the
252 // uncompressed point format. See golang.org/issue/31943.
253 hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
256 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
257 switch priv.Public().(type) {
258 case *ecdsa.PublicKey:
260 case ed25519.PublicKey:
265 c.sendAlert(alertInternalError)
266 return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
269 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
270 switch priv.Public().(type) {
272 hs.rsaDecryptOk = true
274 c.sendAlert(alertInternalError)
275 return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
282 // negotiateALPN picks a shared ALPN protocol that both sides support in server
283 // preference order. If ALPN is not configured or the peer doesn't support it,
284 // it returns "" and no error.
285 func negotiateALPN(serverProtos, clientProtos []string, quic bool) (string, error) {
286 if len(serverProtos) == 0 || len(clientProtos) == 0 {
287 if quic && len(serverProtos) != 0 {
288 // RFC 9001, Section 8.1
289 return "", fmt.Errorf("tls: client did not request an application protocol")
293 var http11fallback bool
294 for _, s := range serverProtos {
295 for _, c := range clientProtos {
299 if s == "h2" && c == "http/1.1" {
300 http11fallback = true
304 // As a special case, let http/1.1 clients connect to h2 servers as if they
305 // didn't support ALPN. We used not to enforce protocol overlap, so over
306 // time a number of HTTP servers were configured with only "h2", but
307 // expected to accept connections from "http/1.1" clients. See Issue 46310.
311 return "", fmt.Errorf("tls: client requested unsupported application protocols (%s)", clientProtos)
314 // supportsECDHE returns whether ECDHE key exchanges can be used with this
315 // pre-TLS 1.3 client.
316 func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool {
317 supportsCurve := false
318 for _, curve := range supportedCurves {
319 if c.supportsCurve(curve) {
325 supportsPointFormat := false
326 for _, pointFormat := range supportedPoints {
327 if pointFormat == pointFormatUncompressed {
328 supportsPointFormat = true
332 // Per RFC 8422, Section 5.1.2, if the Supported Point Formats extension is
333 // missing, uncompressed points are supported. If supportedPoints is empty,
334 // the extension must be missing, as an empty extension body is rejected by
335 // the parser. See https://go.dev/issue/49126.
336 if len(supportedPoints) == 0 {
337 supportsPointFormat = true
340 return supportsCurve && supportsPointFormat
343 func (hs *serverHandshakeState) pickCipherSuite() error {
346 preferenceOrder := cipherSuitesPreferenceOrder
347 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
348 preferenceOrder = cipherSuitesPreferenceOrderNoAES
351 configCipherSuites := c.config.cipherSuites()
352 preferenceList := make([]uint16, 0, len(configCipherSuites))
353 for _, suiteID := range preferenceOrder {
354 for _, id := range configCipherSuites {
356 preferenceList = append(preferenceList, id)
362 hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk)
364 c.sendAlert(alertHandshakeFailure)
365 return errors.New("tls: no cipher suite supported by both client and server")
367 c.cipherSuite = hs.suite.id
369 for _, id := range hs.clientHello.cipherSuites {
370 if id == TLS_FALLBACK_SCSV {
371 // The client is doing a fallback connection. See RFC 7507.
372 if hs.clientHello.vers < c.config.maxSupportedVersion(roleServer) {
373 c.sendAlert(alertInappropriateFallback)
374 return errors.New("tls: client using inappropriate protocol fallback")
383 func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
384 if c.flags&suiteECDHE != 0 {
388 if c.flags&suiteECSign != 0 {
392 } else if !hs.rsaSignOk {
395 } else if !hs.rsaDecryptOk {
398 if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
404 // checkForResumption reports whether we should perform resumption on this connection.
405 func (hs *serverHandshakeState) checkForResumption() error {
408 if c.config.SessionTicketsDisabled {
412 var sessionState *SessionState
413 if c.config.UnwrapSession != nil {
414 ss, err := c.config.UnwrapSession(hs.clientHello.sessionTicket, c.connectionStateLocked())
423 plaintext := c.config.decryptTicket(hs.clientHello.sessionTicket, c.ticketKeys)
424 if plaintext == nil {
427 ss, err := ParseSessionState(plaintext)
434 // TLS 1.2 tickets don't natively have a lifetime, but we want to avoid
435 // re-wrapping the same master secret in different tickets over and over for
436 // too long, weakening forward secrecy.
437 createdAt := time.Unix(int64(sessionState.createdAt), 0)
438 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
442 // Never resume a session for a different TLS version.
443 if c.vers != sessionState.version {
447 cipherSuiteOk := false
448 // Check that the client is still offering the ciphersuite in the session.
449 for _, id := range hs.clientHello.cipherSuites {
450 if id == sessionState.cipherSuite {
459 // Check that we also support the ciphersuite from the session.
460 suite := selectCipherSuite([]uint16{sessionState.cipherSuite},
461 c.config.cipherSuites(), hs.cipherSuiteOk)
466 sessionHasClientCerts := len(sessionState.peerCertificates) != 0
467 needClientCerts := requiresClientCert(c.config.ClientAuth)
468 if needClientCerts && !sessionHasClientCerts {
471 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
475 // RFC 7627, Section 5.3
476 if !sessionState.extMasterSecret && hs.clientHello.extendedMasterSecret {
479 if sessionState.extMasterSecret && !hs.clientHello.extendedMasterSecret {
480 // Aborting is somewhat harsh, but it's a MUST and it would indicate a
481 // weird downgrade in client capabilities.
482 return errors.New("tls: session supported extended_master_secret but client does not")
485 c.extMasterSecret = sessionState.extMasterSecret
486 hs.sessionState = sessionState
492 func (hs *serverHandshakeState) doResumeHandshake() error {
495 hs.hello.cipherSuite = hs.suite.id
496 c.cipherSuite = hs.suite.id
497 // We echo the client's session ID in the ServerHello to let it know
498 // that we're doing a resumption.
499 hs.hello.sessionId = hs.clientHello.sessionId
500 // We always send a new session ticket, even if it wraps the same master
501 // secret and it's potentially encrypted with the same key, to help the
502 // client avoid cross-connection tracking from a network observer.
503 hs.hello.ticketSupported = true
504 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
505 hs.finishedHash.discardHandshakeBuffer()
506 if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
509 if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
513 if err := c.processCertsFromClient(hs.sessionState.certificate()); err != nil {
517 if c.config.VerifyConnection != nil {
518 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
519 c.sendAlert(alertBadCertificate)
524 hs.masterSecret = hs.sessionState.secret
529 func (hs *serverHandshakeState) doFullHandshake() error {
532 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
533 hs.hello.ocspStapling = true
536 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
537 hs.hello.cipherSuite = hs.suite.id
539 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
540 if c.config.ClientAuth == NoClientCert {
541 // No need to keep a full record of the handshake if client
542 // certificates won't be used.
543 hs.finishedHash.discardHandshakeBuffer()
545 if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
548 if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
552 certMsg := new(certificateMsg)
553 certMsg.certificates = hs.cert.Certificate
554 if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
558 if hs.hello.ocspStapling {
559 certStatus := new(certificateStatusMsg)
560 certStatus.response = hs.cert.OCSPStaple
561 if _, err := hs.c.writeHandshakeRecord(certStatus, &hs.finishedHash); err != nil {
566 keyAgreement := hs.suite.ka(c.vers)
567 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
569 c.sendAlert(alertHandshakeFailure)
573 if _, err := hs.c.writeHandshakeRecord(skx, &hs.finishedHash); err != nil {
578 var certReq *certificateRequestMsg
579 if c.config.ClientAuth >= RequestClientCert {
580 // Request a client certificate
581 certReq = new(certificateRequestMsg)
582 certReq.certificateTypes = []byte{
583 byte(certTypeRSASign),
584 byte(certTypeECDSASign),
586 if c.vers >= VersionTLS12 {
587 certReq.hasSignatureAlgorithm = true
588 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
591 // An empty list of certificateAuthorities signals to
592 // the client that it may send any certificate in response
593 // to our request. When we know the CAs we trust, then
594 // we can send them down, so that the client can choose
595 // an appropriate certificate to give to us.
596 if c.config.ClientCAs != nil {
597 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
599 if _, err := hs.c.writeHandshakeRecord(certReq, &hs.finishedHash); err != nil {
604 helloDone := new(serverHelloDoneMsg)
605 if _, err := hs.c.writeHandshakeRecord(helloDone, &hs.finishedHash); err != nil {
609 if _, err := c.flush(); err != nil {
613 var pub crypto.PublicKey // public key for client auth, if any
615 msg, err := c.readHandshake(&hs.finishedHash)
620 // If we requested a client certificate, then the client must send a
621 // certificate message, even if it's empty.
622 if c.config.ClientAuth >= RequestClientCert {
623 certMsg, ok := msg.(*certificateMsg)
625 c.sendAlert(alertUnexpectedMessage)
626 return unexpectedMessageError(certMsg, msg)
629 if err := c.processCertsFromClient(Certificate{
630 Certificate: certMsg.certificates,
634 if len(certMsg.certificates) != 0 {
635 pub = c.peerCertificates[0].PublicKey
638 msg, err = c.readHandshake(&hs.finishedHash)
643 if c.config.VerifyConnection != nil {
644 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
645 c.sendAlert(alertBadCertificate)
650 // Get client key exchange
651 ckx, ok := msg.(*clientKeyExchangeMsg)
653 c.sendAlert(alertUnexpectedMessage)
654 return unexpectedMessageError(ckx, msg)
657 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
659 c.sendAlert(alertHandshakeFailure)
662 if hs.hello.extendedMasterSecret {
663 c.extMasterSecret = true
664 hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
665 hs.finishedHash.Sum())
667 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
668 hs.clientHello.random, hs.hello.random)
670 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
671 c.sendAlert(alertInternalError)
675 // If we received a client cert in response to our certificate request message,
676 // the client will send us a certificateVerifyMsg immediately after the
677 // clientKeyExchangeMsg. This message is a digest of all preceding
678 // handshake-layer messages that is signed using the private key corresponding
679 // to the client's certificate. This allows us to verify that the client is in
680 // possession of the private key of the certificate.
681 if len(c.peerCertificates) > 0 {
682 // certificateVerifyMsg is included in the transcript, but not until
683 // after we verify the handshake signature, since the state before
684 // this message was sent is used.
685 msg, err = c.readHandshake(nil)
689 certVerify, ok := msg.(*certificateVerifyMsg)
691 c.sendAlert(alertUnexpectedMessage)
692 return unexpectedMessageError(certVerify, msg)
696 var sigHash crypto.Hash
697 if c.vers >= VersionTLS12 {
698 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
699 c.sendAlert(alertIllegalParameter)
700 return errors.New("tls: client certificate used with invalid signature algorithm")
702 sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
704 return c.sendAlert(alertInternalError)
707 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
709 c.sendAlert(alertIllegalParameter)
714 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
715 if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
716 c.sendAlert(alertDecryptError)
717 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
720 if err := transcriptMsg(certVerify, &hs.finishedHash); err != nil {
725 hs.finishedHash.discardHandshakeBuffer()
730 func (hs *serverHandshakeState) establishKeys() error {
733 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
734 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
736 var clientCipher, serverCipher any
737 var clientHash, serverHash hash.Hash
739 if hs.suite.aead == nil {
740 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
741 clientHash = hs.suite.mac(clientMAC)
742 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
743 serverHash = hs.suite.mac(serverMAC)
745 clientCipher = hs.suite.aead(clientKey, clientIV)
746 serverCipher = hs.suite.aead(serverKey, serverIV)
749 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
750 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
755 func (hs *serverHandshakeState) readFinished(out []byte) error {
758 if err := c.readChangeCipherSpec(); err != nil {
762 // finishedMsg is included in the transcript, but not until after we
763 // check the client version, since the state before this message was
764 // sent is used during verification.
765 msg, err := c.readHandshake(nil)
769 clientFinished, ok := msg.(*finishedMsg)
771 c.sendAlert(alertUnexpectedMessage)
772 return unexpectedMessageError(clientFinished, msg)
775 verify := hs.finishedHash.clientSum(hs.masterSecret)
776 if len(verify) != len(clientFinished.verifyData) ||
777 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
778 c.sendAlert(alertHandshakeFailure)
779 return errors.New("tls: client's Finished message is incorrect")
782 if err := transcriptMsg(clientFinished, &hs.finishedHash); err != nil {
790 func (hs *serverHandshakeState) sendSessionTicket() error {
791 if !hs.hello.ticketSupported {
796 m := new(newSessionTicketMsg)
798 state, err := c.sessionState()
802 state.secret = hs.masterSecret
803 if hs.sessionState != nil {
804 // If this is re-wrapping an old key, then keep
805 // the original time it was created.
806 state.createdAt = hs.sessionState.createdAt
808 if c.config.WrapSession != nil {
809 m.ticket, err = c.config.WrapSession(c.connectionStateLocked(), state)
814 stateBytes, err := state.Bytes()
818 m.ticket, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
824 if _, err := hs.c.writeHandshakeRecord(m, &hs.finishedHash); err != nil {
831 func (hs *serverHandshakeState) sendFinished(out []byte) error {
834 if err := c.writeChangeCipherRecord(); err != nil {
838 finished := new(finishedMsg)
839 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
840 if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
844 copy(out, finished.verifyData)
849 // processCertsFromClient takes a chain of client certificates either from a
850 // Certificates message or from a sessionState and verifies them. It returns
851 // the public key of the leaf certificate.
852 func (c *Conn) processCertsFromClient(certificate Certificate) error {
853 certificates := certificate.Certificate
854 certs := make([]*x509.Certificate, len(certificates))
856 for i, asn1Data := range certificates {
857 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
858 c.sendAlert(alertBadCertificate)
859 return errors.New("tls: failed to parse client certificate: " + err.Error())
863 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
864 if c.vers == VersionTLS13 {
865 c.sendAlert(alertCertificateRequired)
867 c.sendAlert(alertBadCertificate)
869 return errors.New("tls: client didn't provide a certificate")
872 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
873 opts := x509.VerifyOptions{
874 Roots: c.config.ClientCAs,
875 CurrentTime: c.config.time(),
876 Intermediates: x509.NewCertPool(),
877 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
880 for _, cert := range certs[1:] {
881 opts.Intermediates.AddCert(cert)
884 chains, err := certs[0].Verify(opts)
886 var errCertificateInvalid x509.CertificateInvalidError
887 if errors.As(err, &x509.UnknownAuthorityError{}) {
888 c.sendAlert(alertUnknownCA)
889 } else if errors.As(err, &errCertificateInvalid) && errCertificateInvalid.Reason == x509.Expired {
890 c.sendAlert(alertCertificateExpired)
892 c.sendAlert(alertBadCertificate)
894 return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
897 c.verifiedChains = chains
900 c.peerCertificates = certs
901 c.ocspResponse = certificate.OCSPStaple
902 c.scts = certificate.SignedCertificateTimestamps
905 switch certs[0].PublicKey.(type) {
906 case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
908 c.sendAlert(alertUnsupportedCertificate)
909 return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
913 if c.config.VerifyPeerCertificate != nil {
914 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
915 c.sendAlert(alertBadCertificate)
923 func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
924 supportedVersions := clientHello.supportedVersions
925 if len(clientHello.supportedVersions) == 0 {
926 supportedVersions = supportedVersionsFromMax(clientHello.vers)
929 return &ClientHelloInfo{
930 CipherSuites: clientHello.cipherSuites,
931 ServerName: clientHello.serverName,
932 SupportedCurves: clientHello.supportedCurves,
933 SupportedPoints: clientHello.supportedPoints,
934 SignatureSchemes: clientHello.supportedSignatureAlgorithms,
935 SupportedProtos: clientHello.alpnProtocols,
936 SupportedVersions: supportedVersions,