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.
34 // Deprecated: SSLv3 is cryptographically broken, and is no longer
35 // supported by this package. See golang.org/issue/32716.
40 maxPlaintext = 16384 // maximum plaintext payload length
41 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
42 maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3
43 recordHeaderLen = 5 // record header length
44 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
45 maxUselessRecords = 16 // maximum number of consecutive non-advancing records
52 recordTypeChangeCipherSpec recordType = 20
53 recordTypeAlert recordType = 21
54 recordTypeHandshake recordType = 22
55 recordTypeApplicationData recordType = 23
58 // TLS handshake message types.
60 typeHelloRequest uint8 = 0
61 typeClientHello uint8 = 1
62 typeServerHello uint8 = 2
63 typeNewSessionTicket uint8 = 4
64 typeEndOfEarlyData uint8 = 5
65 typeEncryptedExtensions uint8 = 8
66 typeCertificate uint8 = 11
67 typeServerKeyExchange uint8 = 12
68 typeCertificateRequest uint8 = 13
69 typeServerHelloDone uint8 = 14
70 typeCertificateVerify uint8 = 15
71 typeClientKeyExchange uint8 = 16
72 typeFinished uint8 = 20
73 typeCertificateStatus uint8 = 22
74 typeKeyUpdate uint8 = 24
75 typeNextProtocol uint8 = 67 // Not IANA assigned
76 typeMessageHash uint8 = 254 // synthetic message
79 // TLS compression types.
81 compressionNone uint8 = 0
84 // TLS extension numbers
86 extensionServerName uint16 = 0
87 extensionStatusRequest uint16 = 5
88 extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
89 extensionSupportedPoints uint16 = 11
90 extensionSignatureAlgorithms uint16 = 13
91 extensionALPN uint16 = 16
92 extensionSCT uint16 = 18
93 extensionSessionTicket uint16 = 35
94 extensionPreSharedKey uint16 = 41
95 extensionEarlyData uint16 = 42
96 extensionSupportedVersions uint16 = 43
97 extensionCookie uint16 = 44
98 extensionPSKModes uint16 = 45
99 extensionCertificateAuthorities uint16 = 47
100 extensionSignatureAlgorithmsCert uint16 = 50
101 extensionKeyShare uint16 = 51
102 extensionQUICTransportParameters uint16 = 57
103 extensionRenegotiationInfo uint16 = 0xff01
106 // TLS signaling cipher suite values
108 scsvRenegotiation uint16 = 0x00ff
111 // CurveID is the type of a TLS identifier for an elliptic curve. See
112 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
114 // In TLS 1.3, this type is called NamedGroup, but at this time this library
115 // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
119 CurveP256 CurveID = 23
120 CurveP384 CurveID = 24
121 CurveP521 CurveID = 25
125 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
126 type keyShare struct {
131 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
133 pskModePlain uint8 = 0
137 // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
138 // session. See RFC 8446, Section 4.2.11.
139 type pskIdentity struct {
141 obfuscatedTicketAge uint32
144 // TLS Elliptic Curve Point Formats
145 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
147 pointFormatUncompressed uint8 = 0
150 // TLS CertificateStatusType (RFC 3546)
152 statusTypeOCSP uint8 = 1
155 // Certificate types (for certificateRequestMsg)
158 certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
161 // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
162 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
164 signaturePKCS1v15 uint8 = iota + 225
170 // directSigning is a standard Hash value that signals that no pre-hashing
171 // should be performed, and that the input should be signed directly. It is the
172 // hash function associated with the Ed25519 signature scheme.
173 var directSigning crypto.Hash = 0
175 // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
176 // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
177 // CertificateRequest. The two fields are merged to match with TLS 1.3.
178 // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
179 var defaultSupportedSignatureAlgorithms = []SignatureScheme{
181 ECDSAWithP256AndSHA256,
188 ECDSAWithP384AndSHA384,
189 ECDSAWithP521AndSHA512,
194 // helloRetryRequestRandom is set as the Random value of a ServerHello
195 // to signal that the message is actually a HelloRetryRequest.
196 var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
197 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
198 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
199 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
200 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
204 // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
205 // random as a downgrade protection if the server would be capable of
206 // negotiating a higher version. See RFC 8446, Section 4.1.3.
207 downgradeCanaryTLS12 = "DOWNGRD\x01"
208 downgradeCanaryTLS11 = "DOWNGRD\x00"
211 // testingOnlyForceDowngradeCanary is set in tests to force the server side to
212 // include downgrade canaries even if it's using its highers supported version.
213 var testingOnlyForceDowngradeCanary bool
215 // ConnectionState records basic TLS details about the connection.
216 type ConnectionState struct {
217 // Version is the TLS version used by the connection (e.g. VersionTLS12).
220 // HandshakeComplete is true if the handshake has concluded.
221 HandshakeComplete bool
223 // DidResume is true if this connection was successfully resumed from a
224 // previous session with a session ticket or similar mechanism.
227 // CipherSuite is the cipher suite negotiated for the connection (e.g.
228 // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
231 // NegotiatedProtocol is the application protocol negotiated with ALPN.
232 NegotiatedProtocol string
234 // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
236 // Deprecated: this value is always true.
237 NegotiatedProtocolIsMutual bool
239 // ServerName is the value of the Server Name Indication extension sent by
240 // the client. It's available both on the server and on the client side.
243 // PeerCertificates are the parsed certificates sent by the peer, in the
244 // order in which they were sent. The first element is the leaf certificate
245 // that the connection is verified against.
247 // On the client side, it can't be empty. On the server side, it can be
248 // empty if Config.ClientAuth is not RequireAnyClientCert or
249 // RequireAndVerifyClientCert.
251 // PeerCertificates and its contents should not be modified.
252 PeerCertificates []*x509.Certificate
254 // VerifiedChains is a list of one or more chains where the first element is
255 // PeerCertificates[0] and the last element is from Config.RootCAs (on the
256 // client side) or Config.ClientCAs (on the server side).
258 // On the client side, it's set if Config.InsecureSkipVerify is false. On
259 // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
260 // (and the peer provided a certificate) or RequireAndVerifyClientCert.
262 // VerifiedChains and its contents should not be modified.
263 VerifiedChains [][]*x509.Certificate
265 // SignedCertificateTimestamps is a list of SCTs provided by the peer
266 // through the TLS handshake for the leaf certificate, if any.
267 SignedCertificateTimestamps [][]byte
269 // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
270 // response provided by the peer for the leaf certificate, if any.
273 // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
274 // Section 3). This value will be nil for TLS 1.3 connections and for all
275 // resumed connections.
277 // Deprecated: there are conditions in which this value might not be unique
278 // to a connection. See the Security Considerations sections of RFC 5705 and
279 // RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
282 // ekm is a closure exposed via ExportKeyingMaterial.
283 ekm func(label string, context []byte, length int) ([]byte, error)
286 // ExportKeyingMaterial returns length bytes of exported key material in a new
287 // slice as defined in RFC 5705. If context is nil, it is not used as part of
288 // the seed. If the connection was set to allow renegotiation via
289 // Config.Renegotiation, this function will return an error.
290 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
291 return cs.ekm(label, context, length)
294 // ClientAuthType declares the policy the server will follow for
295 // TLS Client Authentication.
296 type ClientAuthType int
299 // NoClientCert indicates that no client certificate should be requested
300 // during the handshake, and if any certificates are sent they will not
302 NoClientCert ClientAuthType = iota
303 // RequestClientCert indicates that a client certificate should be requested
304 // during the handshake, but does not require that the client send any
307 // RequireAnyClientCert indicates that a client certificate should be requested
308 // during the handshake, and that at least one certificate is required to be
309 // sent by the client, but that certificate is not required to be valid.
311 // VerifyClientCertIfGiven indicates that a client certificate should be requested
312 // during the handshake, but does not require that the client sends a
313 // certificate. If the client does send a certificate it is required to be
315 VerifyClientCertIfGiven
316 // RequireAndVerifyClientCert indicates that a client certificate should be requested
317 // during the handshake, and that at least one valid certificate is required
318 // to be sent by the client.
319 RequireAndVerifyClientCert
322 // requiresClientCert reports whether the ClientAuthType requires a client
323 // certificate to be provided.
324 func requiresClientCert(c ClientAuthType) bool {
326 case RequireAnyClientCert, RequireAndVerifyClientCert:
333 // ClientSessionState contains the state needed by clients to resume TLS
335 type ClientSessionState struct {
336 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
337 vers uint16 // TLS version negotiated for the session
338 cipherSuite uint16 // Ciphersuite negotiated for the session
339 masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
340 serverCertificates []*x509.Certificate // Certificate chain presented by the server
341 verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
342 receivedAt time.Time // When the session ticket was received from the server
343 ocspResponse []byte // Stapled OCSP response presented by the server
344 scts [][]byte // SCTs presented by the server
347 nonce []byte // Ticket nonce sent by the server, to derive PSK
348 useBy time.Time // Expiration of the ticket lifetime as set by the server
349 ageAdd uint32 // Random obfuscation factor for sending the ticket age
352 // ClientSessionCache is a cache of ClientSessionState objects that can be used
353 // by a client to resume a TLS session with a given server. ClientSessionCache
354 // implementations should expect to be called concurrently from different
355 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
356 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
357 // are supported via this interface.
358 type ClientSessionCache interface {
359 // Get searches for a ClientSessionState associated with the given key.
360 // On return, ok is true if one was found.
361 Get(sessionKey string) (session *ClientSessionState, ok bool)
363 // Put adds the ClientSessionState to the cache with the given key. It might
364 // get called multiple times in a connection if a TLS 1.3 server provides
365 // more than one session ticket. If called with a nil *ClientSessionState,
366 // it should remove the cache entry.
367 Put(sessionKey string, cs *ClientSessionState)
370 //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
372 // SignatureScheme identifies a signature algorithm supported by TLS. See
373 // RFC 8446, Section 4.2.3.
374 type SignatureScheme uint16
377 // RSASSA-PKCS1-v1_5 algorithms.
378 PKCS1WithSHA256 SignatureScheme = 0x0401
379 PKCS1WithSHA384 SignatureScheme = 0x0501
380 PKCS1WithSHA512 SignatureScheme = 0x0601
382 // RSASSA-PSS algorithms with public key OID rsaEncryption.
383 PSSWithSHA256 SignatureScheme = 0x0804
384 PSSWithSHA384 SignatureScheme = 0x0805
385 PSSWithSHA512 SignatureScheme = 0x0806
387 // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
388 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
389 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
390 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
393 Ed25519 SignatureScheme = 0x0807
395 // Legacy signature and hash algorithms for TLS 1.2.
396 PKCS1WithSHA1 SignatureScheme = 0x0201
397 ECDSAWithSHA1 SignatureScheme = 0x0203
400 // ClientHelloInfo contains information from a ClientHello message in order to
401 // guide application logic in the GetCertificate and GetConfigForClient callbacks.
402 type ClientHelloInfo struct {
403 // CipherSuites lists the CipherSuites supported by the client (e.g.
404 // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
405 CipherSuites []uint16
407 // ServerName indicates the name of the server requested by the client
408 // in order to support virtual hosting. ServerName is only set if the
409 // client is using SNI (see RFC 4366, Section 3.1).
412 // SupportedCurves lists the elliptic curves supported by the client.
413 // SupportedCurves is set only if the Supported Elliptic Curves
414 // Extension is being used (see RFC 4492, Section 5.1.1).
415 SupportedCurves []CurveID
417 // SupportedPoints lists the point formats supported by the client.
418 // SupportedPoints is set only if the Supported Point Formats Extension
419 // is being used (see RFC 4492, Section 5.1.2).
420 SupportedPoints []uint8
422 // SignatureSchemes lists the signature and hash schemes that the client
423 // is willing to verify. SignatureSchemes is set only if the Signature
424 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
425 SignatureSchemes []SignatureScheme
427 // SupportedProtos lists the application protocols supported by the client.
428 // SupportedProtos is set only if the Application-Layer Protocol
429 // Negotiation Extension is being used (see RFC 7301, Section 3.1).
431 // Servers can select a protocol by setting Config.NextProtos in a
432 // GetConfigForClient return value.
433 SupportedProtos []string
435 // SupportedVersions lists the TLS versions supported by the client.
436 // For TLS versions less than 1.3, this is extrapolated from the max
437 // version advertised by the client, so values other than the greatest
438 // might be rejected if used.
439 SupportedVersions []uint16
441 // Conn is the underlying net.Conn for the connection. Do not read
442 // from, or write to, this connection; that will cause the TLS
443 // connection to fail.
446 // config is embedded by the GetCertificate or GetConfigForClient caller,
447 // for use with SupportsCertificate.
450 // ctx is the context of the handshake that is in progress.
454 // Context returns the context of the handshake that is in progress.
455 // This context is a child of the context passed to HandshakeContext,
456 // if any, and is canceled when the handshake concludes.
457 func (c *ClientHelloInfo) Context() context.Context {
461 // CertificateRequestInfo contains information from a server's
462 // CertificateRequest message, which is used to demand a certificate and proof
463 // of control from a client.
464 type CertificateRequestInfo struct {
465 // AcceptableCAs contains zero or more, DER-encoded, X.501
466 // Distinguished Names. These are the names of root or intermediate CAs
467 // that the server wishes the returned certificate to be signed by. An
468 // empty slice indicates that the server has no preference.
469 AcceptableCAs [][]byte
471 // SignatureSchemes lists the signature schemes that the server is
472 // willing to verify.
473 SignatureSchemes []SignatureScheme
475 // Version is the TLS version that was negotiated for this connection.
478 // ctx is the context of the handshake that is in progress.
482 // Context returns the context of the handshake that is in progress.
483 // This context is a child of the context passed to HandshakeContext,
484 // if any, and is canceled when the handshake concludes.
485 func (c *CertificateRequestInfo) Context() context.Context {
489 // RenegotiationSupport enumerates the different levels of support for TLS
490 // renegotiation. TLS renegotiation is the act of performing subsequent
491 // handshakes on a connection after the first. This significantly complicates
492 // the state machine and has been the source of numerous, subtle security
493 // issues. Initiating a renegotiation is not supported, but support for
494 // accepting renegotiation requests may be enabled.
496 // Even when enabled, the server may not change its identity between handshakes
497 // (i.e. the leaf certificate must be the same). Additionally, concurrent
498 // handshake and application data flow is not permitted so renegotiation can
499 // only be used with protocols that synchronise with the renegotiation, such as
502 // Renegotiation is not defined in TLS 1.3.
503 type RenegotiationSupport int
506 // RenegotiateNever disables renegotiation.
507 RenegotiateNever RenegotiationSupport = iota
509 // RenegotiateOnceAsClient allows a remote server to request
510 // renegotiation once per connection.
511 RenegotiateOnceAsClient
513 // RenegotiateFreelyAsClient allows a remote server to repeatedly
514 // request renegotiation.
515 RenegotiateFreelyAsClient
518 // A Config structure is used to configure a TLS client or server.
519 // After one has been passed to a TLS function it must not be
520 // modified. A Config may be reused; the tls package will also not
523 // Rand provides the source of entropy for nonces and RSA blinding.
524 // If Rand is nil, TLS uses the cryptographic random reader in package
526 // The Reader must be safe for use by multiple goroutines.
529 // Time returns the current time as the number of seconds since the epoch.
530 // If Time is nil, TLS uses time.Now.
531 Time func() time.Time
533 // Certificates contains one or more certificate chains to present to the
534 // other side of the connection. The first certificate compatible with the
535 // peer's requirements is selected automatically.
537 // Server configurations must set one of Certificates, GetCertificate or
538 // GetConfigForClient. Clients doing client-authentication may set either
539 // Certificates or GetClientCertificate.
541 // Note: if there are multiple Certificates, and they don't have the
542 // optional field Leaf set, certificate selection will incur a significant
543 // per-handshake performance cost.
544 Certificates []Certificate
546 // NameToCertificate maps from a certificate name to an element of
547 // Certificates. Note that a certificate name can be of the form
548 // '*.example.com' and so doesn't have to be a domain name as such.
550 // Deprecated: NameToCertificate only allows associating a single
551 // certificate with a given name. Leave this field nil to let the library
552 // select the first compatible chain from Certificates.
553 NameToCertificate map[string]*Certificate
555 // GetCertificate returns a Certificate based on the given
556 // ClientHelloInfo. It will only be called if the client supplies SNI
557 // information or if Certificates is empty.
559 // If GetCertificate is nil or returns nil, then the certificate is
560 // retrieved from NameToCertificate. If NameToCertificate is nil, the
561 // best element of Certificates will be used.
563 // Once a Certificate is returned it should not be modified.
564 GetCertificate func(*ClientHelloInfo) (*Certificate, error)
566 // GetClientCertificate, if not nil, is called when a server requests a
567 // certificate from a client. If set, the contents of Certificates will
570 // If GetClientCertificate returns an error, the handshake will be
571 // aborted and that error will be returned. Otherwise
572 // GetClientCertificate must return a non-nil Certificate. If
573 // Certificate.Certificate is empty then no certificate will be sent to
574 // the server. If this is unacceptable to the server then it may abort
577 // GetClientCertificate may be called multiple times for the same
578 // connection if renegotiation occurs or if TLS 1.3 is in use.
580 // Once a Certificate is returned it should not be modified.
581 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
583 // GetConfigForClient, if not nil, is called after a ClientHello is
584 // received from a client. It may return a non-nil Config in order to
585 // change the Config that will be used to handle this connection. If
586 // the returned Config is nil, the original Config will be used. The
587 // Config returned by this callback may not be subsequently modified.
589 // If GetConfigForClient is nil, the Config passed to Server() will be
590 // used for all connections.
592 // If SessionTicketKey was explicitly set on the returned Config, or if
593 // SetSessionTicketKeys was called on the returned Config, those keys will
594 // be used. Otherwise, the original Config keys will be used (and possibly
595 // rotated if they are automatically managed).
596 GetConfigForClient func(*ClientHelloInfo) (*Config, error)
598 // VerifyPeerCertificate, if not nil, is called after normal
599 // certificate verification by either a TLS client or server. It
600 // receives the raw ASN.1 certificates provided by the peer and also
601 // any verified chains that normal processing found. If it returns a
602 // non-nil error, the handshake is aborted and that error results.
604 // If normal verification fails then the handshake will abort before
605 // considering this callback. If normal verification is disabled by
606 // setting InsecureSkipVerify, or (for a server) when ClientAuth is
607 // RequestClientCert or RequireAnyClientCert, then this callback will
608 // be considered but the verifiedChains argument will always be nil.
610 // verifiedChains and its contents should not be modified.
611 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
613 // VerifyConnection, if not nil, is called after normal certificate
614 // verification and after VerifyPeerCertificate by either a TLS client
615 // or server. If it returns a non-nil error, the handshake is aborted
616 // and that error results.
618 // If normal verification fails then the handshake will abort before
619 // considering this callback. This callback will run for all connections
620 // regardless of InsecureSkipVerify or ClientAuth settings.
621 VerifyConnection func(ConnectionState) error
623 // RootCAs defines the set of root certificate authorities
624 // that clients use when verifying server certificates.
625 // If RootCAs is nil, TLS uses the host's root CA set.
626 RootCAs *x509.CertPool
628 // NextProtos is a list of supported application level protocols, in
629 // order of preference. If both peers support ALPN, the selected
630 // protocol will be one from this list, and the connection will fail
631 // if there is no mutually supported protocol. If NextProtos is empty
632 // or the peer doesn't support ALPN, the connection will succeed and
633 // ConnectionState.NegotiatedProtocol will be empty.
636 // ServerName is used to verify the hostname on the returned
637 // certificates unless InsecureSkipVerify is given. It is also included
638 // in the client's handshake to support virtual hosting unless it is
642 // ClientAuth determines the server's policy for
643 // TLS Client Authentication. The default is NoClientCert.
644 ClientAuth ClientAuthType
646 // ClientCAs defines the set of root certificate authorities
647 // that servers use if required to verify a client certificate
648 // by the policy in ClientAuth.
649 ClientCAs *x509.CertPool
651 // InsecureSkipVerify controls whether a client verifies the server's
652 // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
653 // accepts any certificate presented by the server and any host name in that
654 // certificate. In this mode, TLS is susceptible to machine-in-the-middle
655 // attacks unless custom verification is used. This should be used only for
656 // testing or in combination with VerifyConnection or VerifyPeerCertificate.
657 InsecureSkipVerify bool
659 // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
660 // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
662 // If CipherSuites is nil, a safe default list is used. The default cipher
663 // suites might change over time.
664 CipherSuites []uint16
666 // PreferServerCipherSuites is a legacy field and has no effect.
668 // It used to control whether the server would follow the client's or the
669 // server's preference. Servers now select the best mutually supported
670 // cipher suite based on logic that takes into account inferred client
671 // hardware, server hardware, and security.
673 // Deprecated: PreferServerCipherSuites is ignored.
674 PreferServerCipherSuites bool
676 // SessionTicketsDisabled may be set to true to disable session ticket and
677 // PSK (resumption) support. Note that on clients, session ticket support is
678 // also disabled if ClientSessionCache is nil.
679 SessionTicketsDisabled bool
681 // SessionTicketKey is used by TLS servers to provide session resumption.
682 // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
683 // with random data before the first server handshake.
685 // Deprecated: if this field is left at zero, session ticket keys will be
686 // automatically rotated every day and dropped after seven days. For
687 // customizing the rotation schedule or synchronizing servers that are
688 // terminating connections for the same host, use SetSessionTicketKeys.
689 SessionTicketKey [32]byte
691 // ClientSessionCache is a cache of ClientSessionState entries for TLS
692 // session resumption. It is only used by clients.
693 ClientSessionCache ClientSessionCache
695 // MinVersion contains the minimum TLS version that is acceptable.
697 // By default, TLS 1.2 is currently used as the minimum when acting as a
698 // client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
699 // supported by this package, both as a client and as a server.
701 // The client-side default can temporarily be reverted to TLS 1.0 by
702 // including the value "x509sha1=1" in the GODEBUG environment variable.
703 // Note that this option will be removed in Go 1.19 (but it will still be
704 // possible to set this field to VersionTLS10 explicitly).
707 // MaxVersion contains the maximum TLS version that is acceptable.
709 // By default, the maximum version supported by this package is used,
710 // which is currently TLS 1.3.
713 // CurvePreferences contains the elliptic curves that will be used in
714 // an ECDHE handshake, in preference order. If empty, the default will
715 // be used. The client will use the first preference as the type for
716 // its key share in TLS 1.3. This may change in the future.
717 CurvePreferences []CurveID
719 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
720 // When true, the largest possible TLS record size is always used. When
721 // false, the size of TLS records may be adjusted in an attempt to
723 DynamicRecordSizingDisabled bool
725 // Renegotiation controls what types of renegotiation are supported.
726 // The default, none, is correct for the vast majority of applications.
727 Renegotiation RenegotiationSupport
729 // KeyLogWriter optionally specifies a destination for TLS master secrets
730 // in NSS key log format that can be used to allow external programs
731 // such as Wireshark to decrypt TLS connections.
732 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
733 // Use of KeyLogWriter compromises security and should only be
734 // used for debugging.
735 KeyLogWriter io.Writer
737 // mutex protects sessionTicketKeys and autoSessionTicketKeys.
739 // sessionTicketKeys contains zero or more ticket keys. If set, it means
740 // the keys were set with SessionTicketKey or SetSessionTicketKeys. The
741 // first key is used for new tickets and any subsequent keys can be used to
742 // decrypt old tickets. The slice contents are not protected by the mutex
743 // and are immutable.
744 sessionTicketKeys []ticketKey
745 // autoSessionTicketKeys is like sessionTicketKeys but is owned by the
746 // auto-rotation logic. See Config.ticketKeys.
747 autoSessionTicketKeys []ticketKey
751 // ticketKeyNameLen is the number of bytes of identifier that is prepended to
752 // an encrypted session ticket in order to identify the key used to encrypt it.
753 ticketKeyNameLen = 16
755 // ticketKeyLifetime is how long a ticket key remains valid and can be used to
756 // resume a client connection.
757 ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
759 // ticketKeyRotation is how often the server should rotate the session ticket key
760 // that is used for new tickets.
761 ticketKeyRotation = 24 * time.Hour
764 // ticketKey is the internal representation of a session ticket key.
765 type ticketKey struct {
766 // keyName is an opaque byte string that serves to identify the session
767 // ticket key. It's exposed as plaintext in every session ticket.
768 keyName [ticketKeyNameLen]byte
771 // created is the time at which this ticket key was created. See Config.ticketKeys.
775 // ticketKeyFromBytes converts from the external representation of a session
776 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
777 // bytes and this function expands that into sufficient name and key material.
778 func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
779 hashed := sha512.Sum512(b[:])
780 copy(key.keyName[:], hashed[:ticketKeyNameLen])
781 copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
782 copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
783 key.created = c.time()
787 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
788 // ticket, and the lifetime we set for tickets we send.
789 const maxSessionTicketLifetime = 7 * 24 * time.Hour
791 // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
792 // being used concurrently by a TLS client or server.
793 func (c *Config) Clone() *Config {
798 defer c.mutex.RUnlock()
802 Certificates: c.Certificates,
803 NameToCertificate: c.NameToCertificate,
804 GetCertificate: c.GetCertificate,
805 GetClientCertificate: c.GetClientCertificate,
806 GetConfigForClient: c.GetConfigForClient,
807 VerifyPeerCertificate: c.VerifyPeerCertificate,
808 VerifyConnection: c.VerifyConnection,
810 NextProtos: c.NextProtos,
811 ServerName: c.ServerName,
812 ClientAuth: c.ClientAuth,
813 ClientCAs: c.ClientCAs,
814 InsecureSkipVerify: c.InsecureSkipVerify,
815 CipherSuites: c.CipherSuites,
816 PreferServerCipherSuites: c.PreferServerCipherSuites,
817 SessionTicketsDisabled: c.SessionTicketsDisabled,
818 SessionTicketKey: c.SessionTicketKey,
819 ClientSessionCache: c.ClientSessionCache,
820 MinVersion: c.MinVersion,
821 MaxVersion: c.MaxVersion,
822 CurvePreferences: c.CurvePreferences,
823 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
824 Renegotiation: c.Renegotiation,
825 KeyLogWriter: c.KeyLogWriter,
826 sessionTicketKeys: c.sessionTicketKeys,
827 autoSessionTicketKeys: c.autoSessionTicketKeys,
831 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
832 // randomized for backwards compatibility but is not in use.
833 var deprecatedSessionTicketKey = []byte("DEPRECATED")
835 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
836 // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
837 func (c *Config) initLegacySessionTicketKeyRLocked() {
838 // Don't write if SessionTicketKey is already defined as our deprecated string,
839 // or if it is defined by the user but sessionTicketKeys is already set.
840 if c.SessionTicketKey != [32]byte{} &&
841 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
845 // We need to write some data, so get an exclusive lock and re-check any conditions.
847 defer c.mutex.RLock()
849 defer c.mutex.Unlock()
850 if c.SessionTicketKey == [32]byte{} {
851 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
852 panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
854 // Write the deprecated prefix at the beginning so we know we created
855 // it. This key with the DEPRECATED prefix isn't used as an actual
856 // session ticket key, and is only randomized in case the application
857 // reuses it for some reason.
858 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
859 } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
860 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
865 // ticketKeys returns the ticketKeys for this connection.
866 // If configForClient has explicitly set keys, those will
867 // be returned. Otherwise, the keys on c will be used and
868 // may be rotated if auto-managed.
869 // During rotation, any expired session ticket keys are deleted from
870 // c.sessionTicketKeys. If the session ticket key that is currently
871 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
872 // is not fresh, then a new session ticket key will be
873 // created and prepended to c.sessionTicketKeys.
874 func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
875 // If the ConfigForClient callback returned a Config with explicitly set
876 // keys, use those, otherwise just use the original Config.
877 if configForClient != nil {
878 configForClient.mutex.RLock()
879 if configForClient.SessionTicketsDisabled {
882 configForClient.initLegacySessionTicketKeyRLocked()
883 if len(configForClient.sessionTicketKeys) != 0 {
884 ret := configForClient.sessionTicketKeys
885 configForClient.mutex.RUnlock()
888 configForClient.mutex.RUnlock()
892 defer c.mutex.RUnlock()
893 if c.SessionTicketsDisabled {
896 c.initLegacySessionTicketKeyRLocked()
897 if len(c.sessionTicketKeys) != 0 {
898 return c.sessionTicketKeys
900 // Fast path for the common case where the key is fresh enough.
901 if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
902 return c.autoSessionTicketKeys
905 // autoSessionTicketKeys are managed by auto-rotation.
907 defer c.mutex.RLock()
909 defer c.mutex.Unlock()
910 // Re-check the condition in case it changed since obtaining the new lock.
911 if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
913 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
914 panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
916 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
917 valid = append(valid, c.ticketKeyFromBytes(newKey))
918 for _, k := range c.autoSessionTicketKeys {
919 // While rotating the current key, also remove any expired ones.
920 if c.time().Sub(k.created) < ticketKeyLifetime {
921 valid = append(valid, k)
924 c.autoSessionTicketKeys = valid
926 return c.autoSessionTicketKeys
929 // SetSessionTicketKeys updates the session ticket keys for a server.
931 // The first key will be used when creating new tickets, while all keys can be
932 // used for decrypting tickets. It is safe to call this function while the
933 // server is running in order to rotate the session ticket keys. The function
934 // will panic if keys is empty.
936 // Calling this function will turn off automatic session ticket key rotation.
938 // If multiple servers are terminating connections for the same host they should
939 // all have the same session ticket keys. If the session ticket keys leaks,
940 // previously recorded and future TLS connections using those keys might be
942 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
944 panic("tls: keys must have at least one key")
947 newKeys := make([]ticketKey, len(keys))
948 for i, bytes := range keys {
949 newKeys[i] = c.ticketKeyFromBytes(bytes)
953 c.sessionTicketKeys = newKeys
957 func (c *Config) rand() io.Reader {
965 func (c *Config) time() time.Time {
973 func (c *Config) cipherSuites() []uint16 {
975 return fipsCipherSuites(c)
977 if c.CipherSuites != nil {
978 return c.CipherSuites
980 return defaultCipherSuites
983 var supportedVersions = []uint16{
990 // roleClient and roleServer are meant to call supportedVersions and parents
991 // with more readability at the callsite.
992 const roleClient = true
993 const roleServer = false
995 func (c *Config) supportedVersions(isClient bool) []uint16 {
996 versions := make([]uint16, 0, len(supportedVersions))
997 for _, v := range supportedVersions {
998 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
1001 if (c == nil || c.MinVersion == 0) &&
1002 isClient && v < VersionTLS12 {
1005 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
1008 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
1011 versions = append(versions, v)
1016 func (c *Config) maxSupportedVersion(isClient bool) uint16 {
1017 supportedVersions := c.supportedVersions(isClient)
1018 if len(supportedVersions) == 0 {
1021 return supportedVersions[0]
1024 // supportedVersionsFromMax returns a list of supported versions derived from a
1025 // legacy maximum version value. Note that only versions supported by this
1026 // library are returned. Any newer peer will use supportedVersions anyway.
1027 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
1028 versions := make([]uint16, 0, len(supportedVersions))
1029 for _, v := range supportedVersions {
1033 versions = append(versions, v)
1038 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
1040 func (c *Config) curvePreferences() []CurveID {
1042 return fipsCurvePreferences(c)
1044 if c == nil || len(c.CurvePreferences) == 0 {
1045 return defaultCurvePreferences
1047 return c.CurvePreferences
1050 func (c *Config) supportsCurve(curve CurveID) bool {
1051 for _, cc := range c.curvePreferences() {
1059 // mutualVersion returns the protocol version to use given the advertised
1060 // versions of the peer. Priority is given to the peer preference order.
1061 func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
1062 supportedVersions := c.supportedVersions(isClient)
1063 for _, peerVersion := range peerVersions {
1064 for _, v := range supportedVersions {
1065 if v == peerVersion {
1073 var errNoCertificates = errors.New("tls: no certificates configured")
1075 // getCertificate returns the best certificate for the given ClientHelloInfo,
1076 // defaulting to the first element of c.Certificates.
1077 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1078 if c.GetCertificate != nil &&
1079 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1080 cert, err := c.GetCertificate(clientHello)
1081 if cert != nil || err != nil {
1086 if len(c.Certificates) == 0 {
1087 return nil, errNoCertificates
1090 if len(c.Certificates) == 1 {
1091 // There's only one choice, so no point doing any work.
1092 return &c.Certificates[0], nil
1095 if c.NameToCertificate != nil {
1096 name := strings.ToLower(clientHello.ServerName)
1097 if cert, ok := c.NameToCertificate[name]; ok {
1101 labels := strings.Split(name, ".")
1103 wildcardName := strings.Join(labels, ".")
1104 if cert, ok := c.NameToCertificate[wildcardName]; ok {
1110 for _, cert := range c.Certificates {
1111 if err := clientHello.SupportsCertificate(&cert); err == nil {
1116 // If nothing matches, return the first certificate.
1117 return &c.Certificates[0], nil
1120 // SupportsCertificate returns nil if the provided certificate is supported by
1121 // the client that sent the ClientHello. Otherwise, it returns an error
1122 // describing the reason for the incompatibility.
1124 // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
1125 // callback, this method will take into account the associated Config. Note that
1126 // if GetConfigForClient returns a different Config, the change can't be
1127 // accounted for by this method.
1129 // This function will call x509.ParseCertificate unless c.Leaf is set, which can
1130 // incur a significant performance cost.
1131 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1132 // Note we don't currently support certificate_authorities nor
1133 // signature_algorithms_cert, and don't check the algorithms of the
1134 // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1135 // Section 4.4.2.2).
1137 config := chi.config
1141 vers, ok := config.mutualVersion(roleServer, chi.SupportedVersions)
1143 return errors.New("no mutually supported protocol versions")
1146 // If the client specified the name they are trying to connect to, the
1147 // certificate needs to be valid for it.
1148 if chi.ServerName != "" {
1149 x509Cert, err := c.leaf()
1151 return fmt.Errorf("failed to parse certificate: %w", err)
1153 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1154 return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1158 // supportsRSAFallback returns nil if the certificate and connection support
1159 // the static RSA key exchange, and unsupported otherwise. The logic for
1160 // supporting static RSA is completely disjoint from the logic for
1161 // supporting signed key exchanges, so we just check it as a fallback.
1162 supportsRSAFallback := func(unsupported error) error {
1163 // TLS 1.3 dropped support for the static RSA key exchange.
1164 if vers == VersionTLS13 {
1167 // The static RSA key exchange works by decrypting a challenge with the
1168 // RSA private key, not by signing, so check the PrivateKey implements
1169 // crypto.Decrypter, like *rsa.PrivateKey does.
1170 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1171 if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1177 // Finally, there needs to be a mutual cipher suite that uses the static
1178 // RSA key exchange instead of ECDHE.
1179 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1180 if c.flags&suiteECDHE != 0 {
1183 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1188 if rsaCipherSuite == nil {
1194 // If the client sent the signature_algorithms extension, ensure it supports
1195 // schemes we can use with this certificate and TLS version.
1196 if len(chi.SignatureSchemes) > 0 {
1197 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1198 return supportsRSAFallback(err)
1202 // In TLS 1.3 we are done because supported_groups is only relevant to the
1203 // ECDHE computation, point format negotiation is removed, cipher suites are
1204 // only relevant to the AEAD choice, and static RSA does not exist.
1205 if vers == VersionTLS13 {
1209 // The only signed key exchange we support is ECDHE.
1210 if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
1211 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1214 var ecdsaCipherSuite bool
1215 if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1216 switch pub := priv.Public().(type) {
1217 case *ecdsa.PublicKey:
1220 case elliptic.P256():
1222 case elliptic.P384():
1224 case elliptic.P521():
1227 return supportsRSAFallback(unsupportedCertificateError(c))
1230 for _, c := range chi.SupportedCurves {
1231 if c == curve && config.supportsCurve(c) {
1237 return errors.New("client doesn't support certificate curve")
1239 ecdsaCipherSuite = true
1240 case ed25519.PublicKey:
1241 if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1242 return errors.New("connection doesn't support Ed25519")
1244 ecdsaCipherSuite = true
1245 case *rsa.PublicKey:
1247 return supportsRSAFallback(unsupportedCertificateError(c))
1250 return supportsRSAFallback(unsupportedCertificateError(c))
1253 // Make sure that there is a mutually supported cipher suite that works with
1254 // this certificate. Cipher suite selection will then apply the logic in
1255 // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1256 cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1257 if c.flags&suiteECDHE == 0 {
1260 if c.flags&suiteECSign != 0 {
1261 if !ecdsaCipherSuite {
1265 if ecdsaCipherSuite {
1269 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1274 if cipherSuite == nil {
1275 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1281 // SupportsCertificate returns nil if the provided certificate is supported by
1282 // the server that sent the CertificateRequest. Otherwise, it returns an error
1283 // describing the reason for the incompatibility.
1284 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1285 if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1289 if len(cri.AcceptableCAs) == 0 {
1293 for j, cert := range c.Certificate {
1295 // Parse the certificate if this isn't the leaf node, or if
1296 // chain.Leaf was nil.
1297 if j != 0 || x509Cert == nil {
1299 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1300 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1304 for _, ca := range cri.AcceptableCAs {
1305 if bytes.Equal(x509Cert.RawIssuer, ca) {
1310 return errors.New("chain is not signed by an acceptable CA")
1313 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1314 // from the CommonName and SubjectAlternateName fields of each of the leaf
1317 // Deprecated: NameToCertificate only allows associating a single certificate
1318 // with a given name. Leave that field nil to let the library select the first
1319 // compatible chain from Certificates.
1320 func (c *Config) BuildNameToCertificate() {
1321 c.NameToCertificate = make(map[string]*Certificate)
1322 for i := range c.Certificates {
1323 cert := &c.Certificates[i]
1324 x509Cert, err := cert.leaf()
1328 // If SANs are *not* present, some clients will consider the certificate
1329 // valid for the name in the Common Name.
1330 if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
1331 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1333 for _, san := range x509Cert.DNSNames {
1334 c.NameToCertificate[san] = cert
1340 keyLogLabelTLS12 = "CLIENT_RANDOM"
1341 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1342 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1343 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
1344 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
1347 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1348 if c.KeyLogWriter == nil {
1352 logLine := fmt.Appendf(nil, "%s %x %x\n", label, clientRandom, secret)
1355 _, err := c.KeyLogWriter.Write(logLine)
1356 writerMutex.Unlock()
1361 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1362 // and is only for debugging, so a global mutex saves space.
1363 var writerMutex sync.Mutex
1365 // A Certificate is a chain of one or more certificates, leaf first.
1366 type Certificate struct {
1367 Certificate [][]byte
1368 // PrivateKey contains the private key corresponding to the public key in
1369 // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1370 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1371 // an RSA PublicKey.
1372 PrivateKey crypto.PrivateKey
1373 // SupportedSignatureAlgorithms is an optional list restricting what
1374 // signature algorithms the PrivateKey can be used for.
1375 SupportedSignatureAlgorithms []SignatureScheme
1376 // OCSPStaple contains an optional OCSP response which will be served
1377 // to clients that request it.
1379 // SignedCertificateTimestamps contains an optional list of Signed
1380 // Certificate Timestamps which will be served to clients that request it.
1381 SignedCertificateTimestamps [][]byte
1382 // Leaf is the parsed form of the leaf certificate, which may be initialized
1383 // using x509.ParseCertificate to reduce per-handshake processing. If nil,
1384 // the leaf certificate will be parsed as needed.
1385 Leaf *x509.Certificate
1388 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1389 // the corresponding c.Certificate[0].
1390 func (c *Certificate) leaf() (*x509.Certificate, error) {
1394 return x509.ParseCertificate(c.Certificate[0])
1397 type handshakeMessage interface {
1398 marshal() ([]byte, error)
1399 unmarshal([]byte) bool
1402 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1403 // caching strategy.
1404 type lruSessionCache struct {
1407 m map[string]*list.Element
1412 type lruSessionCacheEntry struct {
1414 state *ClientSessionState
1417 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1418 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1420 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1421 const defaultSessionCacheCapacity = 64
1424 capacity = defaultSessionCacheCapacity
1426 return &lruSessionCache{
1427 m: make(map[string]*list.Element),
1433 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1434 // corresponding to sessionKey is removed from the cache instead.
1435 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1439 if elem, ok := c.m[sessionKey]; ok {
1442 delete(c.m, sessionKey)
1444 entry := elem.Value.(*lruSessionCacheEntry)
1446 c.q.MoveToFront(elem)
1451 if c.q.Len() < c.capacity {
1452 entry := &lruSessionCacheEntry{sessionKey, cs}
1453 c.m[sessionKey] = c.q.PushFront(entry)
1458 entry := elem.Value.(*lruSessionCacheEntry)
1459 delete(c.m, entry.sessionKey)
1460 entry.sessionKey = sessionKey
1462 c.q.MoveToFront(elem)
1463 c.m[sessionKey] = elem
1466 // Get returns the ClientSessionState value associated with a given key. It
1467 // returns (nil, false) if no value is found.
1468 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1472 if elem, ok := c.m[sessionKey]; ok {
1473 c.q.MoveToFront(elem)
1474 return elem.Value.(*lruSessionCacheEntry).state, true
1479 var emptyConfig Config
1481 func defaultConfig() *Config {
1485 func unexpectedMessageError(wanted, got any) error {
1486 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1489 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1490 for _, s := range supportedSignatureAlgorithms {
1498 // CertificateVerificationError is returned when certificate verification fails during the handshake.
1499 type CertificateVerificationError struct {
1500 // UnverifiedCertificates and its contents should not be modified.
1501 UnverifiedCertificates []*x509.Certificate
1505 func (e *CertificateVerificationError) Error() string {
1506 return fmt.Sprintf("tls: failed to verify certificate: %s", e.Err)
1509 func (e *CertificateVerificationError) Unwrap() error {