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 extensionRenegotiationInfo uint16 = 0xff01
105 // TLS signaling cipher suite values
107 scsvRenegotiation uint16 = 0x00ff
110 // CurveID is the type of a TLS identifier for an elliptic curve. See
111 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
113 // In TLS 1.3, this type is called NamedGroup, but at this time this library
114 // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
118 CurveP256 CurveID = 23
119 CurveP384 CurveID = 24
120 CurveP521 CurveID = 25
124 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
125 type keyShare struct {
130 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
132 pskModePlain uint8 = 0
136 // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
137 // session. See RFC 8446, Section 4.2.11.
138 type pskIdentity struct {
140 obfuscatedTicketAge uint32
143 // TLS Elliptic Curve Point Formats
144 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
146 pointFormatUncompressed uint8 = 0
149 // TLS CertificateStatusType (RFC 3546)
151 statusTypeOCSP uint8 = 1
154 // Certificate types (for certificateRequestMsg)
157 certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
160 // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
161 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
163 signaturePKCS1v15 uint8 = iota + 225
169 // directSigning is a standard Hash value that signals that no pre-hashing
170 // should be performed, and that the input should be signed directly. It is the
171 // hash function associated with the Ed25519 signature scheme.
172 var directSigning crypto.Hash = 0
174 // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
175 // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
176 // CertificateRequest. The two fields are merged to match with TLS 1.3.
177 // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
178 var defaultSupportedSignatureAlgorithms = []SignatureScheme{
180 ECDSAWithP256AndSHA256,
187 ECDSAWithP384AndSHA384,
188 ECDSAWithP521AndSHA512,
193 // helloRetryRequestRandom is set as the Random value of a ServerHello
194 // to signal that the message is actually a HelloRetryRequest.
195 var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
196 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
197 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
198 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
199 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
203 // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
204 // random as a downgrade protection if the server would be capable of
205 // negotiating a higher version. See RFC 8446, Section 4.1.3.
206 downgradeCanaryTLS12 = "DOWNGRD\x01"
207 downgradeCanaryTLS11 = "DOWNGRD\x00"
210 // testingOnlyForceDowngradeCanary is set in tests to force the server side to
211 // include downgrade canaries even if it's using its highers supported version.
212 var testingOnlyForceDowngradeCanary bool
214 // ConnectionState records basic TLS details about the connection.
215 type ConnectionState struct {
216 // Version is the TLS version used by the connection (e.g. VersionTLS12).
219 // HandshakeComplete is true if the handshake has concluded.
220 HandshakeComplete bool
222 // DidResume is true if this connection was successfully resumed from a
223 // previous session with a session ticket or similar mechanism.
226 // CipherSuite is the cipher suite negotiated for the connection (e.g.
227 // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
230 // NegotiatedProtocol is the application protocol negotiated with ALPN.
231 NegotiatedProtocol string
233 // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
235 // Deprecated: this value is always true.
236 NegotiatedProtocolIsMutual bool
238 // ServerName is the value of the Server Name Indication extension sent by
239 // the client. It's available both on the server and on the client side.
242 // PeerCertificates are the parsed certificates sent by the peer, in the
243 // order in which they were sent. The first element is the leaf certificate
244 // that the connection is verified against.
246 // On the client side, it can't be empty. On the server side, it can be
247 // empty if Config.ClientAuth is not RequireAnyClientCert or
248 // RequireAndVerifyClientCert.
249 PeerCertificates []*x509.Certificate
251 // VerifiedChains is a list of one or more chains where the first element is
252 // PeerCertificates[0] and the last element is from Config.RootCAs (on the
253 // client side) or Config.ClientCAs (on the server side).
255 // On the client side, it's set if Config.InsecureSkipVerify is false. On
256 // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
257 // (and the peer provided a certificate) or RequireAndVerifyClientCert.
258 VerifiedChains [][]*x509.Certificate
260 // SignedCertificateTimestamps is a list of SCTs provided by the peer
261 // through the TLS handshake for the leaf certificate, if any.
262 SignedCertificateTimestamps [][]byte
264 // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
265 // response provided by the peer for the leaf certificate, if any.
268 // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
269 // Section 3). This value will be nil for TLS 1.3 connections and for all
270 // resumed connections.
272 // Deprecated: there are conditions in which this value might not be unique
273 // to a connection. See the Security Considerations sections of RFC 5705 and
274 // RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
277 // ekm is a closure exposed via ExportKeyingMaterial.
278 ekm func(label string, context []byte, length int) ([]byte, error)
281 // ExportKeyingMaterial returns length bytes of exported key material in a new
282 // slice as defined in RFC 5705. If context is nil, it is not used as part of
283 // the seed. If the connection was set to allow renegotiation via
284 // Config.Renegotiation, this function will return an error.
285 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
286 return cs.ekm(label, context, length)
289 // ClientAuthType declares the policy the server will follow for
290 // TLS Client Authentication.
291 type ClientAuthType int
294 // NoClientCert indicates that no client certificate should be requested
295 // during the handshake, and if any certificates are sent they will not
297 NoClientCert ClientAuthType = iota
298 // RequestClientCert indicates that a client certificate should be requested
299 // during the handshake, but does not require that the client send any
302 // RequireAnyClientCert indicates that a client certificate should be requested
303 // during the handshake, and that at least one certificate is required to be
304 // sent by the client, but that certificate is not required to be valid.
306 // VerifyClientCertIfGiven indicates that a client certificate should be requested
307 // during the handshake, but does not require that the client sends a
308 // certificate. If the client does send a certificate it is required to be
310 VerifyClientCertIfGiven
311 // RequireAndVerifyClientCert indicates that a client certificate should be requested
312 // during the handshake, and that at least one valid certificate is required
313 // to be sent by the client.
314 RequireAndVerifyClientCert
317 // requiresClientCert reports whether the ClientAuthType requires a client
318 // certificate to be provided.
319 func requiresClientCert(c ClientAuthType) bool {
321 case RequireAnyClientCert, RequireAndVerifyClientCert:
328 // ClientSessionState contains the state needed by clients to resume TLS
330 type ClientSessionState struct {
331 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
332 vers uint16 // TLS version negotiated for the session
333 cipherSuite uint16 // Ciphersuite negotiated for the session
334 masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
335 serverCertificates []*x509.Certificate // Certificate chain presented by the server
336 verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
337 receivedAt time.Time // When the session ticket was received from the server
338 ocspResponse []byte // Stapled OCSP response presented by the server
339 scts [][]byte // SCTs presented by the server
342 nonce []byte // Ticket nonce sent by the server, to derive PSK
343 useBy time.Time // Expiration of the ticket lifetime as set by the server
344 ageAdd uint32 // Random obfuscation factor for sending the ticket age
347 // ClientSessionCache is a cache of ClientSessionState objects that can be used
348 // by a client to resume a TLS session with a given server. ClientSessionCache
349 // implementations should expect to be called concurrently from different
350 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
351 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
352 // are supported via this interface.
353 type ClientSessionCache interface {
354 // Get searches for a ClientSessionState associated with the given key.
355 // On return, ok is true if one was found.
356 Get(sessionKey string) (session *ClientSessionState, ok bool)
358 // Put adds the ClientSessionState to the cache with the given key. It might
359 // get called multiple times in a connection if a TLS 1.3 server provides
360 // more than one session ticket. If called with a nil *ClientSessionState,
361 // it should remove the cache entry.
362 Put(sessionKey string, cs *ClientSessionState)
365 //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
367 // SignatureScheme identifies a signature algorithm supported by TLS. See
368 // RFC 8446, Section 4.2.3.
369 type SignatureScheme uint16
372 // RSASSA-PKCS1-v1_5 algorithms.
373 PKCS1WithSHA256 SignatureScheme = 0x0401
374 PKCS1WithSHA384 SignatureScheme = 0x0501
375 PKCS1WithSHA512 SignatureScheme = 0x0601
377 // RSASSA-PSS algorithms with public key OID rsaEncryption.
378 PSSWithSHA256 SignatureScheme = 0x0804
379 PSSWithSHA384 SignatureScheme = 0x0805
380 PSSWithSHA512 SignatureScheme = 0x0806
382 // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
383 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
384 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
385 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
388 Ed25519 SignatureScheme = 0x0807
390 // Legacy signature and hash algorithms for TLS 1.2.
391 PKCS1WithSHA1 SignatureScheme = 0x0201
392 ECDSAWithSHA1 SignatureScheme = 0x0203
395 // ClientHelloInfo contains information from a ClientHello message in order to
396 // guide application logic in the GetCertificate and GetConfigForClient callbacks.
397 type ClientHelloInfo struct {
398 // CipherSuites lists the CipherSuites supported by the client (e.g.
399 // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
400 CipherSuites []uint16
402 // ServerName indicates the name of the server requested by the client
403 // in order to support virtual hosting. ServerName is only set if the
404 // client is using SNI (see RFC 4366, Section 3.1).
407 // SupportedCurves lists the elliptic curves supported by the client.
408 // SupportedCurves is set only if the Supported Elliptic Curves
409 // Extension is being used (see RFC 4492, Section 5.1.1).
410 SupportedCurves []CurveID
412 // SupportedPoints lists the point formats supported by the client.
413 // SupportedPoints is set only if the Supported Point Formats Extension
414 // is being used (see RFC 4492, Section 5.1.2).
415 SupportedPoints []uint8
417 // SignatureSchemes lists the signature and hash schemes that the client
418 // is willing to verify. SignatureSchemes is set only if the Signature
419 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
420 SignatureSchemes []SignatureScheme
422 // SupportedProtos lists the application protocols supported by the client.
423 // SupportedProtos is set only if the Application-Layer Protocol
424 // Negotiation Extension is being used (see RFC 7301, Section 3.1).
426 // Servers can select a protocol by setting Config.NextProtos in a
427 // GetConfigForClient return value.
428 SupportedProtos []string
430 // SupportedVersions lists the TLS versions supported by the client.
431 // For TLS versions less than 1.3, this is extrapolated from the max
432 // version advertised by the client, so values other than the greatest
433 // might be rejected if used.
434 SupportedVersions []uint16
436 // Conn is the underlying net.Conn for the connection. Do not read
437 // from, or write to, this connection; that will cause the TLS
438 // connection to fail.
441 // config is embedded by the GetCertificate or GetConfigForClient caller,
442 // for use with SupportsCertificate.
445 // ctx is the context of the handshake that is in progress.
449 // Context returns the context of the handshake that is in progress.
450 // This context is a child of the context passed to HandshakeContext,
451 // if any, and is canceled when the handshake concludes.
452 func (c *ClientHelloInfo) Context() context.Context {
456 // CertificateRequestInfo contains information from a server's
457 // CertificateRequest message, which is used to demand a certificate and proof
458 // of control from a client.
459 type CertificateRequestInfo struct {
460 // AcceptableCAs contains zero or more, DER-encoded, X.501
461 // Distinguished Names. These are the names of root or intermediate CAs
462 // that the server wishes the returned certificate to be signed by. An
463 // empty slice indicates that the server has no preference.
464 AcceptableCAs [][]byte
466 // SignatureSchemes lists the signature schemes that the server is
467 // willing to verify.
468 SignatureSchemes []SignatureScheme
470 // Version is the TLS version that was negotiated for this connection.
473 // ctx is the context of the handshake that is in progress.
477 // Context returns the context of the handshake that is in progress.
478 // This context is a child of the context passed to HandshakeContext,
479 // if any, and is canceled when the handshake concludes.
480 func (c *CertificateRequestInfo) Context() context.Context {
484 // RenegotiationSupport enumerates the different levels of support for TLS
485 // renegotiation. TLS renegotiation is the act of performing subsequent
486 // handshakes on a connection after the first. This significantly complicates
487 // the state machine and has been the source of numerous, subtle security
488 // issues. Initiating a renegotiation is not supported, but support for
489 // accepting renegotiation requests may be enabled.
491 // Even when enabled, the server may not change its identity between handshakes
492 // (i.e. the leaf certificate must be the same). Additionally, concurrent
493 // handshake and application data flow is not permitted so renegotiation can
494 // only be used with protocols that synchronise with the renegotiation, such as
497 // Renegotiation is not defined in TLS 1.3.
498 type RenegotiationSupport int
501 // RenegotiateNever disables renegotiation.
502 RenegotiateNever RenegotiationSupport = iota
504 // RenegotiateOnceAsClient allows a remote server to request
505 // renegotiation once per connection.
506 RenegotiateOnceAsClient
508 // RenegotiateFreelyAsClient allows a remote server to repeatedly
509 // request renegotiation.
510 RenegotiateFreelyAsClient
513 // A Config structure is used to configure a TLS client or server.
514 // After one has been passed to a TLS function it must not be
515 // modified. A Config may be reused; the tls package will also not
518 // Rand provides the source of entropy for nonces and RSA blinding.
519 // If Rand is nil, TLS uses the cryptographic random reader in package
521 // The Reader must be safe for use by multiple goroutines.
524 // Time returns the current time as the number of seconds since the epoch.
525 // If Time is nil, TLS uses time.Now.
526 Time func() time.Time
528 // Certificates contains one or more certificate chains to present to the
529 // other side of the connection. The first certificate compatible with the
530 // peer's requirements is selected automatically.
532 // Server configurations must set one of Certificates, GetCertificate or
533 // GetConfigForClient. Clients doing client-authentication may set either
534 // Certificates or GetClientCertificate.
536 // Note: if there are multiple Certificates, and they don't have the
537 // optional field Leaf set, certificate selection will incur a significant
538 // per-handshake performance cost.
539 Certificates []Certificate
541 // NameToCertificate maps from a certificate name to an element of
542 // Certificates. Note that a certificate name can be of the form
543 // '*.example.com' and so doesn't have to be a domain name as such.
545 // Deprecated: NameToCertificate only allows associating a single
546 // certificate with a given name. Leave this field nil to let the library
547 // select the first compatible chain from Certificates.
548 NameToCertificate map[string]*Certificate
550 // GetCertificate returns a Certificate based on the given
551 // ClientHelloInfo. It will only be called if the client supplies SNI
552 // information or if Certificates is empty.
554 // If GetCertificate is nil or returns nil, then the certificate is
555 // retrieved from NameToCertificate. If NameToCertificate is nil, the
556 // best element of Certificates will be used.
557 GetCertificate func(*ClientHelloInfo) (*Certificate, error)
559 // GetClientCertificate, if not nil, is called when a server requests a
560 // certificate from a client. If set, the contents of Certificates will
563 // If GetClientCertificate returns an error, the handshake will be
564 // aborted and that error will be returned. Otherwise
565 // GetClientCertificate must return a non-nil Certificate. If
566 // Certificate.Certificate is empty then no certificate will be sent to
567 // the server. If this is unacceptable to the server then it may abort
570 // GetClientCertificate may be called multiple times for the same
571 // connection if renegotiation occurs or if TLS 1.3 is in use.
572 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
574 // GetConfigForClient, if not nil, is called after a ClientHello is
575 // received from a client. It may return a non-nil Config in order to
576 // change the Config that will be used to handle this connection. If
577 // the returned Config is nil, the original Config will be used. The
578 // Config returned by this callback may not be subsequently modified.
580 // If GetConfigForClient is nil, the Config passed to Server() will be
581 // used for all connections.
583 // If SessionTicketKey was explicitly set on the returned Config, or if
584 // SetSessionTicketKeys was called on the returned Config, those keys will
585 // be used. Otherwise, the original Config keys will be used (and possibly
586 // rotated if they are automatically managed).
587 GetConfigForClient func(*ClientHelloInfo) (*Config, error)
589 // VerifyPeerCertificate, if not nil, is called after normal
590 // certificate verification by either a TLS client or server. It
591 // receives the raw ASN.1 certificates provided by the peer and also
592 // any verified chains that normal processing found. If it returns a
593 // non-nil error, the handshake is aborted and that error results.
595 // If normal verification fails then the handshake will abort before
596 // considering this callback. If normal verification is disabled by
597 // setting InsecureSkipVerify, or (for a server) when ClientAuth is
598 // RequestClientCert or RequireAnyClientCert, then this callback will
599 // be considered but the verifiedChains argument will always be nil.
600 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
602 // VerifyConnection, if not nil, is called after normal certificate
603 // verification and after VerifyPeerCertificate by either a TLS client
604 // or server. If it returns a non-nil error, the handshake is aborted
605 // and that error results.
607 // If normal verification fails then the handshake will abort before
608 // considering this callback. This callback will run for all connections
609 // regardless of InsecureSkipVerify or ClientAuth settings.
610 VerifyConnection func(ConnectionState) error
612 // RootCAs defines the set of root certificate authorities
613 // that clients use when verifying server certificates.
614 // If RootCAs is nil, TLS uses the host's root CA set.
615 RootCAs *x509.CertPool
617 // NextProtos is a list of supported application level protocols, in
618 // order of preference. If both peers support ALPN, the selected
619 // protocol will be one from this list, and the connection will fail
620 // if there is no mutually supported protocol. If NextProtos is empty
621 // or the peer doesn't support ALPN, the connection will succeed and
622 // ConnectionState.NegotiatedProtocol will be empty."
625 // ServerName is used to verify the hostname on the returned
626 // certificates unless InsecureSkipVerify is given. It is also included
627 // in the client's handshake to support virtual hosting unless it is
631 // ClientAuth determines the server's policy for
632 // TLS Client Authentication. The default is NoClientCert.
633 ClientAuth ClientAuthType
635 // ClientCAs defines the set of root certificate authorities
636 // that servers use if required to verify a client certificate
637 // by the policy in ClientAuth.
638 ClientCAs *x509.CertPool
640 // InsecureSkipVerify controls whether a client verifies the server's
641 // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
642 // accepts any certificate presented by the server and any host name in that
643 // certificate. In this mode, TLS is susceptible to machine-in-the-middle
644 // attacks unless custom verification is used. This should be used only for
645 // testing or in combination with VerifyConnection or VerifyPeerCertificate.
646 InsecureSkipVerify bool
648 // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
649 // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
651 // If CipherSuites is nil, a safe default list is used. The default cipher
652 // suites might change over time.
653 CipherSuites []uint16
655 // PreferServerCipherSuites is a legacy field and has no effect.
657 // It used to control whether the server would follow the client's or the
658 // server's preference. Servers now select the best mutually supported
659 // cipher suite based on logic that takes into account inferred client
660 // hardware, server hardware, and security.
662 // Deprected: PreferServerCipherSuites is ignored.
663 PreferServerCipherSuites bool
665 // SessionTicketsDisabled may be set to true to disable session ticket and
666 // PSK (resumption) support. Note that on clients, session ticket support is
667 // also disabled if ClientSessionCache is nil.
668 SessionTicketsDisabled bool
670 // SessionTicketKey is used by TLS servers to provide session resumption.
671 // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
672 // with random data before the first server handshake.
674 // Deprecated: if this field is left at zero, session ticket keys will be
675 // automatically rotated every day and dropped after seven days. For
676 // customizing the rotation schedule or synchronizing servers that are
677 // terminating connections for the same host, use SetSessionTicketKeys.
678 SessionTicketKey [32]byte
680 // ClientSessionCache is a cache of ClientSessionState entries for TLS
681 // session resumption. It is only used by clients.
682 ClientSessionCache ClientSessionCache
684 // MinVersion contains the minimum TLS version that is acceptable.
685 // If zero, TLS 1.0 is currently taken as the minimum.
688 // MaxVersion contains the maximum TLS version that is acceptable.
689 // If zero, the maximum version supported by this package is used,
690 // which is currently TLS 1.3.
693 // CurvePreferences contains the elliptic curves that will be used in
694 // an ECDHE handshake, in preference order. If empty, the default will
695 // be used. The client will use the first preference as the type for
696 // its key share in TLS 1.3. This may change in the future.
697 CurvePreferences []CurveID
699 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
700 // When true, the largest possible TLS record size is always used. When
701 // false, the size of TLS records may be adjusted in an attempt to
703 DynamicRecordSizingDisabled bool
705 // Renegotiation controls what types of renegotiation are supported.
706 // The default, none, is correct for the vast majority of applications.
707 Renegotiation RenegotiationSupport
709 // KeyLogWriter optionally specifies a destination for TLS master secrets
710 // in NSS key log format that can be used to allow external programs
711 // such as Wireshark to decrypt TLS connections.
712 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
713 // Use of KeyLogWriter compromises security and should only be
714 // used for debugging.
715 KeyLogWriter io.Writer
717 // mutex protects sessionTicketKeys and autoSessionTicketKeys.
719 // sessionTicketKeys contains zero or more ticket keys. If set, it means the
720 // the keys were set with SessionTicketKey or SetSessionTicketKeys. The
721 // first key is used for new tickets and any subsequent keys can be used to
722 // decrypt old tickets. The slice contents are not protected by the mutex
723 // and are immutable.
724 sessionTicketKeys []ticketKey
725 // autoSessionTicketKeys is like sessionTicketKeys but is owned by the
726 // auto-rotation logic. See Config.ticketKeys.
727 autoSessionTicketKeys []ticketKey
731 // ticketKeyNameLen is the number of bytes of identifier that is prepended to
732 // an encrypted session ticket in order to identify the key used to encrypt it.
733 ticketKeyNameLen = 16
735 // ticketKeyLifetime is how long a ticket key remains valid and can be used to
736 // resume a client connection.
737 ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
739 // ticketKeyRotation is how often the server should rotate the session ticket key
740 // that is used for new tickets.
741 ticketKeyRotation = 24 * time.Hour
744 // ticketKey is the internal representation of a session ticket key.
745 type ticketKey struct {
746 // keyName is an opaque byte string that serves to identify the session
747 // ticket key. It's exposed as plaintext in every session ticket.
748 keyName [ticketKeyNameLen]byte
751 // created is the time at which this ticket key was created. See Config.ticketKeys.
755 // ticketKeyFromBytes converts from the external representation of a session
756 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
757 // bytes and this function expands that into sufficient name and key material.
758 func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
759 hashed := sha512.Sum512(b[:])
760 copy(key.keyName[:], hashed[:ticketKeyNameLen])
761 copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
762 copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
763 key.created = c.time()
767 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
768 // ticket, and the lifetime we set for tickets we send.
769 const maxSessionTicketLifetime = 7 * 24 * time.Hour
771 // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
772 // being used concurrently by a TLS client or server.
773 func (c *Config) Clone() *Config {
778 defer c.mutex.RUnlock()
782 Certificates: c.Certificates,
783 NameToCertificate: c.NameToCertificate,
784 GetCertificate: c.GetCertificate,
785 GetClientCertificate: c.GetClientCertificate,
786 GetConfigForClient: c.GetConfigForClient,
787 VerifyPeerCertificate: c.VerifyPeerCertificate,
788 VerifyConnection: c.VerifyConnection,
790 NextProtos: c.NextProtos,
791 ServerName: c.ServerName,
792 ClientAuth: c.ClientAuth,
793 ClientCAs: c.ClientCAs,
794 InsecureSkipVerify: c.InsecureSkipVerify,
795 CipherSuites: c.CipherSuites,
796 PreferServerCipherSuites: c.PreferServerCipherSuites,
797 SessionTicketsDisabled: c.SessionTicketsDisabled,
798 SessionTicketKey: c.SessionTicketKey,
799 ClientSessionCache: c.ClientSessionCache,
800 MinVersion: c.MinVersion,
801 MaxVersion: c.MaxVersion,
802 CurvePreferences: c.CurvePreferences,
803 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
804 Renegotiation: c.Renegotiation,
805 KeyLogWriter: c.KeyLogWriter,
806 sessionTicketKeys: c.sessionTicketKeys,
807 autoSessionTicketKeys: c.autoSessionTicketKeys,
811 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
812 // randomized for backwards compatibility but is not in use.
813 var deprecatedSessionTicketKey = []byte("DEPRECATED")
815 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
816 // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
817 func (c *Config) initLegacySessionTicketKeyRLocked() {
818 // Don't write if SessionTicketKey is already defined as our deprecated string,
819 // or if it is defined by the user but sessionTicketKeys is already set.
820 if c.SessionTicketKey != [32]byte{} &&
821 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
825 // We need to write some data, so get an exclusive lock and re-check any conditions.
827 defer c.mutex.RLock()
829 defer c.mutex.Unlock()
830 if c.SessionTicketKey == [32]byte{} {
831 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
832 panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
834 // Write the deprecated prefix at the beginning so we know we created
835 // it. This key with the DEPRECATED prefix isn't used as an actual
836 // session ticket key, and is only randomized in case the application
837 // reuses it for some reason.
838 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
839 } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
840 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
845 // ticketKeys returns the ticketKeys for this connection.
846 // If configForClient has explicitly set keys, those will
847 // be returned. Otherwise, the keys on c will be used and
848 // may be rotated if auto-managed.
849 // During rotation, any expired session ticket keys are deleted from
850 // c.sessionTicketKeys. If the session ticket key that is currently
851 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
852 // is not fresh, then a new session ticket key will be
853 // created and prepended to c.sessionTicketKeys.
854 func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
855 // If the ConfigForClient callback returned a Config with explicitly set
856 // keys, use those, otherwise just use the original Config.
857 if configForClient != nil {
858 configForClient.mutex.RLock()
859 if configForClient.SessionTicketsDisabled {
862 configForClient.initLegacySessionTicketKeyRLocked()
863 if len(configForClient.sessionTicketKeys) != 0 {
864 ret := configForClient.sessionTicketKeys
865 configForClient.mutex.RUnlock()
868 configForClient.mutex.RUnlock()
872 defer c.mutex.RUnlock()
873 if c.SessionTicketsDisabled {
876 c.initLegacySessionTicketKeyRLocked()
877 if len(c.sessionTicketKeys) != 0 {
878 return c.sessionTicketKeys
880 // Fast path for the common case where the key is fresh enough.
881 if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
882 return c.autoSessionTicketKeys
885 // autoSessionTicketKeys are managed by auto-rotation.
887 defer c.mutex.RLock()
889 defer c.mutex.Unlock()
890 // Re-check the condition in case it changed since obtaining the new lock.
891 if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
893 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
894 panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
896 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
897 valid = append(valid, c.ticketKeyFromBytes(newKey))
898 for _, k := range c.autoSessionTicketKeys {
899 // While rotating the current key, also remove any expired ones.
900 if c.time().Sub(k.created) < ticketKeyLifetime {
901 valid = append(valid, k)
904 c.autoSessionTicketKeys = valid
906 return c.autoSessionTicketKeys
909 // SetSessionTicketKeys updates the session ticket keys for a server.
911 // The first key will be used when creating new tickets, while all keys can be
912 // used for decrypting tickets. It is safe to call this function while the
913 // server is running in order to rotate the session ticket keys. The function
914 // will panic if keys is empty.
916 // Calling this function will turn off automatic session ticket key rotation.
918 // If multiple servers are terminating connections for the same host they should
919 // all have the same session ticket keys. If the session ticket keys leaks,
920 // previously recorded and future TLS connections using those keys might be
922 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
924 panic("tls: keys must have at least one key")
927 newKeys := make([]ticketKey, len(keys))
928 for i, bytes := range keys {
929 newKeys[i] = c.ticketKeyFromBytes(bytes)
933 c.sessionTicketKeys = newKeys
937 func (c *Config) rand() io.Reader {
945 func (c *Config) time() time.Time {
953 func (c *Config) cipherSuites() []uint16 {
955 return fipsCipherSuites(c)
957 if c.CipherSuites != nil {
958 return c.CipherSuites
960 return defaultCipherSuites
963 var supportedVersions = []uint16{
970 func (c *Config) supportedVersions() []uint16 {
971 versions := make([]uint16, 0, len(supportedVersions))
972 for _, v := range supportedVersions {
973 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
976 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
979 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
982 versions = append(versions, v)
987 func (c *Config) maxSupportedVersion() uint16 {
988 supportedVersions := c.supportedVersions()
989 if len(supportedVersions) == 0 {
992 return supportedVersions[0]
995 // supportedVersionsFromMax returns a list of supported versions derived from a
996 // legacy maximum version value. Note that only versions supported by this
997 // library are returned. Any newer peer will use supportedVersions anyway.
998 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
999 versions := make([]uint16, 0, len(supportedVersions))
1000 for _, v := range supportedVersions {
1004 versions = append(versions, v)
1009 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
1011 func (c *Config) curvePreferences() []CurveID {
1013 return fipsCurvePreferences(c)
1015 if c == nil || len(c.CurvePreferences) == 0 {
1016 return defaultCurvePreferences
1018 return c.CurvePreferences
1021 func (c *Config) supportsCurve(curve CurveID) bool {
1022 for _, cc := range c.curvePreferences() {
1030 // mutualVersion returns the protocol version to use given the advertised
1031 // versions of the peer. Priority is given to the peer preference order.
1032 func (c *Config) mutualVersion(peerVersions []uint16) (uint16, bool) {
1033 supportedVersions := c.supportedVersions()
1034 for _, peerVersion := range peerVersions {
1035 for _, v := range supportedVersions {
1036 if v == peerVersion {
1044 var errNoCertificates = errors.New("tls: no certificates configured")
1046 // getCertificate returns the best certificate for the given ClientHelloInfo,
1047 // defaulting to the first element of c.Certificates.
1048 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1049 if c.GetCertificate != nil &&
1050 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1051 cert, err := c.GetCertificate(clientHello)
1052 if cert != nil || err != nil {
1057 if len(c.Certificates) == 0 {
1058 return nil, errNoCertificates
1061 if len(c.Certificates) == 1 {
1062 // There's only one choice, so no point doing any work.
1063 return &c.Certificates[0], nil
1066 if c.NameToCertificate != nil {
1067 name := strings.ToLower(clientHello.ServerName)
1068 if cert, ok := c.NameToCertificate[name]; ok {
1072 labels := strings.Split(name, ".")
1074 wildcardName := strings.Join(labels, ".")
1075 if cert, ok := c.NameToCertificate[wildcardName]; ok {
1081 for _, cert := range c.Certificates {
1082 if err := clientHello.SupportsCertificate(&cert); err == nil {
1087 // If nothing matches, return the first certificate.
1088 return &c.Certificates[0], nil
1091 // SupportsCertificate returns nil if the provided certificate is supported by
1092 // the client that sent the ClientHello. Otherwise, it returns an error
1093 // describing the reason for the incompatibility.
1095 // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
1096 // callback, this method will take into account the associated Config. Note that
1097 // if GetConfigForClient returns a different Config, the change can't be
1098 // accounted for by this method.
1100 // This function will call x509.ParseCertificate unless c.Leaf is set, which can
1101 // incur a significant performance cost.
1102 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1103 // Note we don't currently support certificate_authorities nor
1104 // signature_algorithms_cert, and don't check the algorithms of the
1105 // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1106 // Section 4.4.2.2).
1108 config := chi.config
1112 vers, ok := config.mutualVersion(chi.SupportedVersions)
1114 return errors.New("no mutually supported protocol versions")
1117 // If the client specified the name they are trying to connect to, the
1118 // certificate needs to be valid for it.
1119 if chi.ServerName != "" {
1120 x509Cert, err := c.leaf()
1122 return fmt.Errorf("failed to parse certificate: %w", err)
1124 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1125 return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1129 // supportsRSAFallback returns nil if the certificate and connection support
1130 // the static RSA key exchange, and unsupported otherwise. The logic for
1131 // supporting static RSA is completely disjoint from the logic for
1132 // supporting signed key exchanges, so we just check it as a fallback.
1133 supportsRSAFallback := func(unsupported error) error {
1134 // TLS 1.3 dropped support for the static RSA key exchange.
1135 if vers == VersionTLS13 {
1138 // The static RSA key exchange works by decrypting a challenge with the
1139 // RSA private key, not by signing, so check the PrivateKey implements
1140 // crypto.Decrypter, like *rsa.PrivateKey does.
1141 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1142 if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1148 // Finally, there needs to be a mutual cipher suite that uses the static
1149 // RSA key exchange instead of ECDHE.
1150 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1151 if c.flags&suiteECDHE != 0 {
1154 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1159 if rsaCipherSuite == nil {
1165 // If the client sent the signature_algorithms extension, ensure it supports
1166 // schemes we can use with this certificate and TLS version.
1167 if len(chi.SignatureSchemes) > 0 {
1168 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1169 return supportsRSAFallback(err)
1173 // In TLS 1.3 we are done because supported_groups is only relevant to the
1174 // ECDHE computation, point format negotiation is removed, cipher suites are
1175 // only relevant to the AEAD choice, and static RSA does not exist.
1176 if vers == VersionTLS13 {
1180 // The only signed key exchange we support is ECDHE.
1181 if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
1182 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1185 var ecdsaCipherSuite bool
1186 if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1187 switch pub := priv.Public().(type) {
1188 case *ecdsa.PublicKey:
1191 case elliptic.P256():
1193 case elliptic.P384():
1195 case elliptic.P521():
1198 return supportsRSAFallback(unsupportedCertificateError(c))
1201 for _, c := range chi.SupportedCurves {
1202 if c == curve && config.supportsCurve(c) {
1208 return errors.New("client doesn't support certificate curve")
1210 ecdsaCipherSuite = true
1211 case ed25519.PublicKey:
1212 if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1213 return errors.New("connection doesn't support Ed25519")
1215 ecdsaCipherSuite = true
1216 case *rsa.PublicKey:
1218 return supportsRSAFallback(unsupportedCertificateError(c))
1221 return supportsRSAFallback(unsupportedCertificateError(c))
1224 // Make sure that there is a mutually supported cipher suite that works with
1225 // this certificate. Cipher suite selection will then apply the logic in
1226 // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1227 cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1228 if c.flags&suiteECDHE == 0 {
1231 if c.flags&suiteECSign != 0 {
1232 if !ecdsaCipherSuite {
1236 if ecdsaCipherSuite {
1240 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1245 if cipherSuite == nil {
1246 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1252 // SupportsCertificate returns nil if the provided certificate is supported by
1253 // the server that sent the CertificateRequest. Otherwise, it returns an error
1254 // describing the reason for the incompatibility.
1255 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1256 if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1260 if len(cri.AcceptableCAs) == 0 {
1264 for j, cert := range c.Certificate {
1266 // Parse the certificate if this isn't the leaf node, or if
1267 // chain.Leaf was nil.
1268 if j != 0 || x509Cert == nil {
1270 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1271 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1275 for _, ca := range cri.AcceptableCAs {
1276 if bytes.Equal(x509Cert.RawIssuer, ca) {
1281 return errors.New("chain is not signed by an acceptable CA")
1284 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1285 // from the CommonName and SubjectAlternateName fields of each of the leaf
1288 // Deprecated: NameToCertificate only allows associating a single certificate
1289 // with a given name. Leave that field nil to let the library select the first
1290 // compatible chain from Certificates.
1291 func (c *Config) BuildNameToCertificate() {
1292 c.NameToCertificate = make(map[string]*Certificate)
1293 for i := range c.Certificates {
1294 cert := &c.Certificates[i]
1295 x509Cert, err := cert.leaf()
1299 // If SANs are *not* present, some clients will consider the certificate
1300 // valid for the name in the Common Name.
1301 if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
1302 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1304 for _, san := range x509Cert.DNSNames {
1305 c.NameToCertificate[san] = cert
1311 keyLogLabelTLS12 = "CLIENT_RANDOM"
1312 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1313 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1314 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
1315 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
1318 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1319 if c.KeyLogWriter == nil {
1323 logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
1326 _, err := c.KeyLogWriter.Write(logLine)
1327 writerMutex.Unlock()
1332 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1333 // and is only for debugging, so a global mutex saves space.
1334 var writerMutex sync.Mutex
1336 // A Certificate is a chain of one or more certificates, leaf first.
1337 type Certificate struct {
1338 Certificate [][]byte
1339 // PrivateKey contains the private key corresponding to the public key in
1340 // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1341 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1342 // an RSA PublicKey.
1343 PrivateKey crypto.PrivateKey
1344 // SupportedSignatureAlgorithms is an optional list restricting what
1345 // signature algorithms the PrivateKey can be used for.
1346 SupportedSignatureAlgorithms []SignatureScheme
1347 // OCSPStaple contains an optional OCSP response which will be served
1348 // to clients that request it.
1350 // SignedCertificateTimestamps contains an optional list of Signed
1351 // Certificate Timestamps which will be served to clients that request it.
1352 SignedCertificateTimestamps [][]byte
1353 // Leaf is the parsed form of the leaf certificate, which may be initialized
1354 // using x509.ParseCertificate to reduce per-handshake processing. If nil,
1355 // the leaf certificate will be parsed as needed.
1356 Leaf *x509.Certificate
1359 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1360 // the corresponding c.Certificate[0].
1361 func (c *Certificate) leaf() (*x509.Certificate, error) {
1365 return x509.ParseCertificate(c.Certificate[0])
1368 type handshakeMessage interface {
1370 unmarshal([]byte) bool
1373 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1374 // caching strategy.
1375 type lruSessionCache struct {
1378 m map[string]*list.Element
1383 type lruSessionCacheEntry struct {
1385 state *ClientSessionState
1388 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1389 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1391 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1392 const defaultSessionCacheCapacity = 64
1395 capacity = defaultSessionCacheCapacity
1397 return &lruSessionCache{
1398 m: make(map[string]*list.Element),
1404 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1405 // corresponding to sessionKey is removed from the cache instead.
1406 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1410 if elem, ok := c.m[sessionKey]; ok {
1413 delete(c.m, sessionKey)
1415 entry := elem.Value.(*lruSessionCacheEntry)
1417 c.q.MoveToFront(elem)
1422 if c.q.Len() < c.capacity {
1423 entry := &lruSessionCacheEntry{sessionKey, cs}
1424 c.m[sessionKey] = c.q.PushFront(entry)
1429 entry := elem.Value.(*lruSessionCacheEntry)
1430 delete(c.m, entry.sessionKey)
1431 entry.sessionKey = sessionKey
1433 c.q.MoveToFront(elem)
1434 c.m[sessionKey] = elem
1437 // Get returns the ClientSessionState value associated with a given key. It
1438 // returns (nil, false) if no value is found.
1439 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1443 if elem, ok := c.m[sessionKey]; ok {
1444 c.q.MoveToFront(elem)
1445 return elem.Value.(*lruSessionCacheEntry).state, true
1450 var emptyConfig Config
1452 func defaultConfig() *Config {
1456 func unexpectedMessageError(wanted, got interface{}) error {
1457 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1460 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1461 for _, s := range supportedSignatureAlgorithms {