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.
35 // Deprecated: SSLv3 is cryptographically broken, and is no longer
36 // supported by this package. See golang.org/issue/32716.
41 maxPlaintext = 16384 // maximum plaintext payload length
42 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
43 maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3
44 recordHeaderLen = 5 // record header length
45 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
46 maxUselessRecords = 16 // maximum number of consecutive non-advancing records
53 recordTypeChangeCipherSpec recordType = 20
54 recordTypeAlert recordType = 21
55 recordTypeHandshake recordType = 22
56 recordTypeApplicationData recordType = 23
59 // TLS handshake message types.
61 typeHelloRequest uint8 = 0
62 typeClientHello uint8 = 1
63 typeServerHello uint8 = 2
64 typeNewSessionTicket uint8 = 4
65 typeEndOfEarlyData uint8 = 5
66 typeEncryptedExtensions uint8 = 8
67 typeCertificate uint8 = 11
68 typeServerKeyExchange uint8 = 12
69 typeCertificateRequest uint8 = 13
70 typeServerHelloDone uint8 = 14
71 typeCertificateVerify uint8 = 15
72 typeClientKeyExchange uint8 = 16
73 typeFinished uint8 = 20
74 typeCertificateStatus uint8 = 22
75 typeKeyUpdate uint8 = 24
76 typeNextProtocol uint8 = 67 // Not IANA assigned
77 typeMessageHash uint8 = 254 // synthetic message
80 // TLS compression types.
82 compressionNone uint8 = 0
85 // TLS extension numbers
87 extensionServerName uint16 = 0
88 extensionStatusRequest uint16 = 5
89 extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
90 extensionSupportedPoints uint16 = 11
91 extensionSignatureAlgorithms uint16 = 13
92 extensionALPN uint16 = 16
93 extensionSCT uint16 = 18
94 extensionSessionTicket uint16 = 35
95 extensionPreSharedKey uint16 = 41
96 extensionEarlyData uint16 = 42
97 extensionSupportedVersions uint16 = 43
98 extensionCookie uint16 = 44
99 extensionPSKModes uint16 = 45
100 extensionCertificateAuthorities uint16 = 47
101 extensionSignatureAlgorithmsCert uint16 = 50
102 extensionKeyShare uint16 = 51
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 // supportedSignatureAlgorithms 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 supportedSignatureAlgorithms = []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.
250 PeerCertificates []*x509.Certificate
252 // VerifiedChains is a list of one or more chains where the first element is
253 // PeerCertificates[0] and the last element is from Config.RootCAs (on the
254 // client side) or Config.ClientCAs (on the server side).
256 // On the client side, it's set if Config.InsecureSkipVerify is false. On
257 // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
258 // (and the peer provided a certificate) or RequireAndVerifyClientCert.
259 VerifiedChains [][]*x509.Certificate
261 // SignedCertificateTimestamps is a list of SCTs provided by the peer
262 // through the TLS handshake for the leaf certificate, if any.
263 SignedCertificateTimestamps [][]byte
265 // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
266 // response provided by the peer for the leaf certificate, if any.
269 // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
270 // Section 3). This value will be nil for TLS 1.3 connections and for all
271 // resumed connections.
273 // Deprecated: there are conditions in which this value might not be unique
274 // to a connection. See the Security Considerations sections of RFC 5705 and
275 // RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
278 // ekm is a closure exposed via ExportKeyingMaterial.
279 ekm func(label string, context []byte, length int) ([]byte, error)
282 // ExportKeyingMaterial returns length bytes of exported key material in a new
283 // slice as defined in RFC 5705. If context is nil, it is not used as part of
284 // the seed. If the connection was set to allow renegotiation via
285 // Config.Renegotiation, this function will return an error.
286 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
287 return cs.ekm(label, context, length)
290 // ClientAuthType declares the policy the server will follow for
291 // TLS Client Authentication.
292 type ClientAuthType int
295 // NoClientCert indicates that no client certificate should be requested
296 // during the handshake, and if any certificates are sent they will not
298 NoClientCert ClientAuthType = iota
299 // RequestClientCert indicates that a client certificate should be requested
300 // during the handshake, but does not require that the client send any
303 // RequireAnyClientCert indicates that a client certificate should be requested
304 // during the handshake, and that at least one certificate is required to be
305 // sent by the client, but that certificate is not required to be valid.
307 // VerifyClientCertIfGiven indicates that a client certificate should be requested
308 // during the handshake, but does not require that the client sends a
309 // certificate. If the client does send a certificate it is required to be
311 VerifyClientCertIfGiven
312 // RequireAndVerifyClientCert indicates that a client certificate should be requested
313 // during the handshake, and that at least one valid certificate is required
314 // to be sent by the client.
315 RequireAndVerifyClientCert
318 // requiresClientCert reports whether the ClientAuthType requires a client
319 // certificate to be provided.
320 func requiresClientCert(c ClientAuthType) bool {
322 case RequireAnyClientCert, RequireAndVerifyClientCert:
329 // ClientSessionState contains the state needed by clients to resume TLS
331 type ClientSessionState struct {
332 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
333 vers uint16 // TLS version negotiated for the session
334 cipherSuite uint16 // Ciphersuite negotiated for the session
335 masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
336 serverCertificates []*x509.Certificate // Certificate chain presented by the server
337 verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
338 receivedAt time.Time // When the session ticket was received from the server
339 ocspResponse []byte // Stapled OCSP response presented by the server
340 scts [][]byte // SCTs presented by the server
343 nonce []byte // Ticket nonce sent by the server, to derive PSK
344 useBy time.Time // Expiration of the ticket lifetime as set by the server
345 ageAdd uint32 // Random obfuscation factor for sending the ticket age
348 // ClientSessionCache is a cache of ClientSessionState objects that can be used
349 // by a client to resume a TLS session with a given server. ClientSessionCache
350 // implementations should expect to be called concurrently from different
351 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
352 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
353 // are supported via this interface.
354 type ClientSessionCache interface {
355 // Get searches for a ClientSessionState associated with the given key.
356 // On return, ok is true if one was found.
357 Get(sessionKey string) (session *ClientSessionState, ok bool)
359 // Put adds the ClientSessionState to the cache with the given key. It might
360 // get called multiple times in a connection if a TLS 1.3 server provides
361 // more than one session ticket. If called with a nil *ClientSessionState,
362 // it should remove the cache entry.
363 Put(sessionKey string, cs *ClientSessionState)
366 //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
368 // SignatureScheme identifies a signature algorithm supported by TLS. See
369 // RFC 8446, Section 4.2.3.
370 type SignatureScheme uint16
373 // RSASSA-PKCS1-v1_5 algorithms.
374 PKCS1WithSHA256 SignatureScheme = 0x0401
375 PKCS1WithSHA384 SignatureScheme = 0x0501
376 PKCS1WithSHA512 SignatureScheme = 0x0601
378 // RSASSA-PSS algorithms with public key OID rsaEncryption.
379 PSSWithSHA256 SignatureScheme = 0x0804
380 PSSWithSHA384 SignatureScheme = 0x0805
381 PSSWithSHA512 SignatureScheme = 0x0806
383 // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
384 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
385 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
386 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
389 Ed25519 SignatureScheme = 0x0807
391 // Legacy signature and hash algorithms for TLS 1.2.
392 PKCS1WithSHA1 SignatureScheme = 0x0201
393 ECDSAWithSHA1 SignatureScheme = 0x0203
396 // ClientHelloInfo contains information from a ClientHello message in order to
397 // guide application logic in the GetCertificate and GetConfigForClient callbacks.
398 type ClientHelloInfo struct {
399 // CipherSuites lists the CipherSuites supported by the client (e.g.
400 // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
401 CipherSuites []uint16
403 // ServerName indicates the name of the server requested by the client
404 // in order to support virtual hosting. ServerName is only set if the
405 // client is using SNI (see RFC 4366, Section 3.1).
408 // SupportedCurves lists the elliptic curves supported by the client.
409 // SupportedCurves is set only if the Supported Elliptic Curves
410 // Extension is being used (see RFC 4492, Section 5.1.1).
411 SupportedCurves []CurveID
413 // SupportedPoints lists the point formats supported by the client.
414 // SupportedPoints is set only if the Supported Point Formats Extension
415 // is being used (see RFC 4492, Section 5.1.2).
416 SupportedPoints []uint8
418 // SignatureSchemes lists the signature and hash schemes that the client
419 // is willing to verify. SignatureSchemes is set only if the Signature
420 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
421 SignatureSchemes []SignatureScheme
423 // SupportedProtos lists the application protocols supported by the client.
424 // SupportedProtos is set only if the Application-Layer Protocol
425 // Negotiation Extension is being used (see RFC 7301, Section 3.1).
427 // Servers can select a protocol by setting Config.NextProtos in a
428 // GetConfigForClient return value.
429 SupportedProtos []string
431 // SupportedVersions lists the TLS versions supported by the client.
432 // For TLS versions less than 1.3, this is extrapolated from the max
433 // version advertised by the client, so values other than the greatest
434 // might be rejected if used.
435 SupportedVersions []uint16
437 // Conn is the underlying net.Conn for the connection. Do not read
438 // from, or write to, this connection; that will cause the TLS
439 // connection to fail.
442 // config is embedded by the GetCertificate or GetConfigForClient caller,
443 // for use with SupportsCertificate.
446 // ctx is the context of the handshake that is in progress.
450 // Context returns the context of the handshake that is in progress.
451 // This context is a child of the context passed to HandshakeContext,
452 // if any, and is canceled when the handshake concludes.
453 func (c *ClientHelloInfo) Context() context.Context {
457 // CertificateRequestInfo contains information from a server's
458 // CertificateRequest message, which is used to demand a certificate and proof
459 // of control from a client.
460 type CertificateRequestInfo struct {
461 // AcceptableCAs contains zero or more, DER-encoded, X.501
462 // Distinguished Names. These are the names of root or intermediate CAs
463 // that the server wishes the returned certificate to be signed by. An
464 // empty slice indicates that the server has no preference.
465 AcceptableCAs [][]byte
467 // SignatureSchemes lists the signature schemes that the server is
468 // willing to verify.
469 SignatureSchemes []SignatureScheme
471 // Version is the TLS version that was negotiated for this connection.
474 // ctx is the context of the handshake that is in progress.
478 // Context returns the context of the handshake that is in progress.
479 // This context is a child of the context passed to HandshakeContext,
480 // if any, and is canceled when the handshake concludes.
481 func (c *CertificateRequestInfo) Context() context.Context {
485 // RenegotiationSupport enumerates the different levels of support for TLS
486 // renegotiation. TLS renegotiation is the act of performing subsequent
487 // handshakes on a connection after the first. This significantly complicates
488 // the state machine and has been the source of numerous, subtle security
489 // issues. Initiating a renegotiation is not supported, but support for
490 // accepting renegotiation requests may be enabled.
492 // Even when enabled, the server may not change its identity between handshakes
493 // (i.e. the leaf certificate must be the same). Additionally, concurrent
494 // handshake and application data flow is not permitted so renegotiation can
495 // only be used with protocols that synchronise with the renegotiation, such as
498 // Renegotiation is not defined in TLS 1.3.
499 type RenegotiationSupport int
502 // RenegotiateNever disables renegotiation.
503 RenegotiateNever RenegotiationSupport = iota
505 // RenegotiateOnceAsClient allows a remote server to request
506 // renegotiation once per connection.
507 RenegotiateOnceAsClient
509 // RenegotiateFreelyAsClient allows a remote server to repeatedly
510 // request renegotiation.
511 RenegotiateFreelyAsClient
514 // A Config structure is used to configure a TLS client or server.
515 // After one has been passed to a TLS function it must not be
516 // modified. A Config may be reused; the tls package will also not
519 // Rand provides the source of entropy for nonces and RSA blinding.
520 // If Rand is nil, TLS uses the cryptographic random reader in package
522 // The Reader must be safe for use by multiple goroutines.
525 // Time returns the current time as the number of seconds since the epoch.
526 // If Time is nil, TLS uses time.Now.
527 Time func() time.Time
529 // Certificates contains one or more certificate chains to present to the
530 // other side of the connection. The first certificate compatible with the
531 // peer's requirements is selected automatically.
533 // Server configurations must set one of Certificates, GetCertificate or
534 // GetConfigForClient. Clients doing client-authentication may set either
535 // Certificates or GetClientCertificate.
537 // Note: if there are multiple Certificates, and they don't have the
538 // optional field Leaf set, certificate selection will incur a significant
539 // per-handshake performance cost.
540 Certificates []Certificate
542 // NameToCertificate maps from a certificate name to an element of
543 // Certificates. Note that a certificate name can be of the form
544 // '*.example.com' and so doesn't have to be a domain name as such.
546 // Deprecated: NameToCertificate only allows associating a single
547 // certificate with a given name. Leave this field nil to let the library
548 // select the first compatible chain from Certificates.
549 NameToCertificate map[string]*Certificate
551 // GetCertificate returns a Certificate based on the given
552 // ClientHelloInfo. It will only be called if the client supplies SNI
553 // information or if Certificates is empty.
555 // If GetCertificate is nil or returns nil, then the certificate is
556 // retrieved from NameToCertificate. If NameToCertificate is nil, the
557 // best element of Certificates will be used.
558 GetCertificate func(*ClientHelloInfo) (*Certificate, error)
560 // GetClientCertificate, if not nil, is called when a server requests a
561 // certificate from a client. If set, the contents of Certificates will
564 // If GetClientCertificate returns an error, the handshake will be
565 // aborted and that error will be returned. Otherwise
566 // GetClientCertificate must return a non-nil Certificate. If
567 // Certificate.Certificate is empty then no certificate will be sent to
568 // the server. If this is unacceptable to the server then it may abort
571 // GetClientCertificate may be called multiple times for the same
572 // connection if renegotiation occurs or if TLS 1.3 is in use.
573 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
575 // GetConfigForClient, if not nil, is called after a ClientHello is
576 // received from a client. It may return a non-nil Config in order to
577 // change the Config that will be used to handle this connection. If
578 // the returned Config is nil, the original Config will be used. The
579 // Config returned by this callback may not be subsequently modified.
581 // If GetConfigForClient is nil, the Config passed to Server() will be
582 // used for all connections.
584 // If SessionTicketKey was explicitly set on the returned Config, or if
585 // SetSessionTicketKeys was called on the returned Config, those keys will
586 // be used. Otherwise, the original Config keys will be used (and possibly
587 // rotated if they are automatically managed).
588 GetConfigForClient func(*ClientHelloInfo) (*Config, error)
590 // VerifyPeerCertificate, if not nil, is called after normal
591 // certificate verification by either a TLS client or server. It
592 // receives the raw ASN.1 certificates provided by the peer and also
593 // any verified chains that normal processing found. If it returns a
594 // non-nil error, the handshake is aborted and that error results.
596 // If normal verification fails then the handshake will abort before
597 // considering this callback. If normal verification is disabled by
598 // setting InsecureSkipVerify, or (for a server) when ClientAuth is
599 // RequestClientCert or RequireAnyClientCert, then this callback will
600 // be considered but the verifiedChains argument will always be nil.
601 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
603 // VerifyConnection, if not nil, is called after normal certificate
604 // verification and after VerifyPeerCertificate by either a TLS client
605 // or server. If it returns a non-nil error, the handshake is aborted
606 // and that error results.
608 // If normal verification fails then the handshake will abort before
609 // considering this callback. This callback will run for all connections
610 // regardless of InsecureSkipVerify or ClientAuth settings.
611 VerifyConnection func(ConnectionState) error
613 // RootCAs defines the set of root certificate authorities
614 // that clients use when verifying server certificates.
615 // If RootCAs is nil, TLS uses the host's root CA set.
616 RootCAs *x509.CertPool
618 // NextProtos is a list of supported application level protocols, in
619 // order of preference. If both peers support ALPN, the selected
620 // protocol will be one from this list, and the connection will fail
621 // if there is no mutually supported protocol. If NextProtos is empty
622 // or the peer doesn't support ALPN, the connection will succeed and
623 // ConnectionState.NegotiatedProtocol will be empty.
626 // ServerName is used to verify the hostname on the returned
627 // certificates unless InsecureSkipVerify is given. It is also included
628 // in the client's handshake to support virtual hosting unless it is
632 // ClientAuth determines the server's policy for
633 // TLS Client Authentication. The default is NoClientCert.
634 ClientAuth ClientAuthType
636 // ClientCAs defines the set of root certificate authorities
637 // that servers use if required to verify a client certificate
638 // by the policy in ClientAuth.
639 ClientCAs *x509.CertPool
641 // InsecureSkipVerify controls whether a client verifies the server's
642 // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
643 // accepts any certificate presented by the server and any host name in that
644 // certificate. In this mode, TLS is susceptible to machine-in-the-middle
645 // attacks unless custom verification is used. This should be used only for
646 // testing or in combination with VerifyConnection or VerifyPeerCertificate.
647 InsecureSkipVerify bool
649 // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
650 // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
652 // If CipherSuites is nil, a safe default list is used. The default cipher
653 // suites might change over time.
654 CipherSuites []uint16
656 // PreferServerCipherSuites is a legacy field and has no effect.
658 // It used to control whether the server would follow the client's or the
659 // server's preference. Servers now select the best mutually supported
660 // cipher suite based on logic that takes into account inferred client
661 // hardware, server hardware, and security.
663 // Deprecated: PreferServerCipherSuites is ignored.
664 PreferServerCipherSuites bool
666 // SessionTicketsDisabled may be set to true to disable session ticket and
667 // PSK (resumption) support. Note that on clients, session ticket support is
668 // also disabled if ClientSessionCache is nil.
669 SessionTicketsDisabled bool
671 // SessionTicketKey is used by TLS servers to provide session resumption.
672 // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
673 // with random data before the first server handshake.
675 // Deprecated: if this field is left at zero, session ticket keys will be
676 // automatically rotated every day and dropped after seven days. For
677 // customizing the rotation schedule or synchronizing servers that are
678 // terminating connections for the same host, use SetSessionTicketKeys.
679 SessionTicketKey [32]byte
681 // ClientSessionCache is a cache of ClientSessionState entries for TLS
682 // session resumption. It is only used by clients.
683 ClientSessionCache ClientSessionCache
685 // MinVersion contains the minimum TLS version that is acceptable.
687 // By default, TLS 1.2 is currently used as the minimum when acting as a
688 // client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
689 // supported by this package, both as a client and as a server.
691 // The client-side default can temporarily be reverted to TLS 1.0 by
692 // including the value "x509sha1=1" in the GODEBUG environment variable.
693 // Note that this option will be removed in Go 1.19 (but it will still be
694 // possible to set this field to VersionTLS10 explicitly).
697 // MaxVersion contains the maximum TLS version that is acceptable.
699 // By default, the maximum version supported by this package is used,
700 // which is currently TLS 1.3.
703 // CurvePreferences contains the elliptic curves that will be used in
704 // an ECDHE handshake, in preference order. If empty, the default will
705 // be used. The client will use the first preference as the type for
706 // its key share in TLS 1.3. This may change in the future.
707 CurvePreferences []CurveID
709 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
710 // When true, the largest possible TLS record size is always used. When
711 // false, the size of TLS records may be adjusted in an attempt to
713 DynamicRecordSizingDisabled bool
715 // Renegotiation controls what types of renegotiation are supported.
716 // The default, none, is correct for the vast majority of applications.
717 Renegotiation RenegotiationSupport
719 // KeyLogWriter optionally specifies a destination for TLS master secrets
720 // in NSS key log format that can be used to allow external programs
721 // such as Wireshark to decrypt TLS connections.
722 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
723 // Use of KeyLogWriter compromises security and should only be
724 // used for debugging.
725 KeyLogWriter io.Writer
727 // mutex protects sessionTicketKeys and autoSessionTicketKeys.
729 // sessionTicketKeys contains zero or more ticket keys. If set, it means the
730 // the keys were set with SessionTicketKey or SetSessionTicketKeys. The
731 // first key is used for new tickets and any subsequent keys can be used to
732 // decrypt old tickets. The slice contents are not protected by the mutex
733 // and are immutable.
734 sessionTicketKeys []ticketKey
735 // autoSessionTicketKeys is like sessionTicketKeys but is owned by the
736 // auto-rotation logic. See Config.ticketKeys.
737 autoSessionTicketKeys []ticketKey
741 // ticketKeyNameLen is the number of bytes of identifier that is prepended to
742 // an encrypted session ticket in order to identify the key used to encrypt it.
743 ticketKeyNameLen = 16
745 // ticketKeyLifetime is how long a ticket key remains valid and can be used to
746 // resume a client connection.
747 ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
749 // ticketKeyRotation is how often the server should rotate the session ticket key
750 // that is used for new tickets.
751 ticketKeyRotation = 24 * time.Hour
754 // ticketKey is the internal representation of a session ticket key.
755 type ticketKey struct {
756 // keyName is an opaque byte string that serves to identify the session
757 // ticket key. It's exposed as plaintext in every session ticket.
758 keyName [ticketKeyNameLen]byte
761 // created is the time at which this ticket key was created. See Config.ticketKeys.
765 // ticketKeyFromBytes converts from the external representation of a session
766 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
767 // bytes and this function expands that into sufficient name and key material.
768 func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
769 hashed := sha512.Sum512(b[:])
770 copy(key.keyName[:], hashed[:ticketKeyNameLen])
771 copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
772 copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
773 key.created = c.time()
777 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
778 // ticket, and the lifetime we set for tickets we send.
779 const maxSessionTicketLifetime = 7 * 24 * time.Hour
781 // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
782 // being used concurrently by a TLS client or server.
783 func (c *Config) Clone() *Config {
788 defer c.mutex.RUnlock()
792 Certificates: c.Certificates,
793 NameToCertificate: c.NameToCertificate,
794 GetCertificate: c.GetCertificate,
795 GetClientCertificate: c.GetClientCertificate,
796 GetConfigForClient: c.GetConfigForClient,
797 VerifyPeerCertificate: c.VerifyPeerCertificate,
798 VerifyConnection: c.VerifyConnection,
800 NextProtos: c.NextProtos,
801 ServerName: c.ServerName,
802 ClientAuth: c.ClientAuth,
803 ClientCAs: c.ClientCAs,
804 InsecureSkipVerify: c.InsecureSkipVerify,
805 CipherSuites: c.CipherSuites,
806 PreferServerCipherSuites: c.PreferServerCipherSuites,
807 SessionTicketsDisabled: c.SessionTicketsDisabled,
808 SessionTicketKey: c.SessionTicketKey,
809 ClientSessionCache: c.ClientSessionCache,
810 MinVersion: c.MinVersion,
811 MaxVersion: c.MaxVersion,
812 CurvePreferences: c.CurvePreferences,
813 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
814 Renegotiation: c.Renegotiation,
815 KeyLogWriter: c.KeyLogWriter,
816 sessionTicketKeys: c.sessionTicketKeys,
817 autoSessionTicketKeys: c.autoSessionTicketKeys,
821 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
822 // randomized for backwards compatibility but is not in use.
823 var deprecatedSessionTicketKey = []byte("DEPRECATED")
825 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
826 // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
827 func (c *Config) initLegacySessionTicketKeyRLocked() {
828 // Don't write if SessionTicketKey is already defined as our deprecated string,
829 // or if it is defined by the user but sessionTicketKeys is already set.
830 if c.SessionTicketKey != [32]byte{} &&
831 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
835 // We need to write some data, so get an exclusive lock and re-check any conditions.
837 defer c.mutex.RLock()
839 defer c.mutex.Unlock()
840 if c.SessionTicketKey == [32]byte{} {
841 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
842 panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
844 // Write the deprecated prefix at the beginning so we know we created
845 // it. This key with the DEPRECATED prefix isn't used as an actual
846 // session ticket key, and is only randomized in case the application
847 // reuses it for some reason.
848 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
849 } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
850 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
855 // ticketKeys returns the ticketKeys for this connection.
856 // If configForClient has explicitly set keys, those will
857 // be returned. Otherwise, the keys on c will be used and
858 // may be rotated if auto-managed.
859 // During rotation, any expired session ticket keys are deleted from
860 // c.sessionTicketKeys. If the session ticket key that is currently
861 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
862 // is not fresh, then a new session ticket key will be
863 // created and prepended to c.sessionTicketKeys.
864 func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
865 // If the ConfigForClient callback returned a Config with explicitly set
866 // keys, use those, otherwise just use the original Config.
867 if configForClient != nil {
868 configForClient.mutex.RLock()
869 if configForClient.SessionTicketsDisabled {
872 configForClient.initLegacySessionTicketKeyRLocked()
873 if len(configForClient.sessionTicketKeys) != 0 {
874 ret := configForClient.sessionTicketKeys
875 configForClient.mutex.RUnlock()
878 configForClient.mutex.RUnlock()
882 defer c.mutex.RUnlock()
883 if c.SessionTicketsDisabled {
886 c.initLegacySessionTicketKeyRLocked()
887 if len(c.sessionTicketKeys) != 0 {
888 return c.sessionTicketKeys
890 // Fast path for the common case where the key is fresh enough.
891 if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
892 return c.autoSessionTicketKeys
895 // autoSessionTicketKeys are managed by auto-rotation.
897 defer c.mutex.RLock()
899 defer c.mutex.Unlock()
900 // Re-check the condition in case it changed since obtaining the new lock.
901 if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
903 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
904 panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
906 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
907 valid = append(valid, c.ticketKeyFromBytes(newKey))
908 for _, k := range c.autoSessionTicketKeys {
909 // While rotating the current key, also remove any expired ones.
910 if c.time().Sub(k.created) < ticketKeyLifetime {
911 valid = append(valid, k)
914 c.autoSessionTicketKeys = valid
916 return c.autoSessionTicketKeys
919 // SetSessionTicketKeys updates the session ticket keys for a server.
921 // The first key will be used when creating new tickets, while all keys can be
922 // used for decrypting tickets. It is safe to call this function while the
923 // server is running in order to rotate the session ticket keys. The function
924 // will panic if keys is empty.
926 // Calling this function will turn off automatic session ticket key rotation.
928 // If multiple servers are terminating connections for the same host they should
929 // all have the same session ticket keys. If the session ticket keys leaks,
930 // previously recorded and future TLS connections using those keys might be
932 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
934 panic("tls: keys must have at least one key")
937 newKeys := make([]ticketKey, len(keys))
938 for i, bytes := range keys {
939 newKeys[i] = c.ticketKeyFromBytes(bytes)
943 c.sessionTicketKeys = newKeys
947 func (c *Config) rand() io.Reader {
955 func (c *Config) time() time.Time {
963 func (c *Config) cipherSuites() []uint16 {
964 if c.CipherSuites != nil {
965 return c.CipherSuites
967 return defaultCipherSuites
970 var supportedVersions = []uint16{
977 // debugEnableTLS10 enables TLS 1.0. See issue 45428.
978 var debugEnableTLS10 = godebug.Get("tls10default") == "1"
980 // roleClient and roleServer are meant to call supportedVersions and parents
981 // with more readability at the callsite.
982 const roleClient = true
983 const roleServer = false
985 func (c *Config) supportedVersions(isClient bool) []uint16 {
986 versions := make([]uint16, 0, len(supportedVersions))
987 for _, v := range supportedVersions {
988 if (c == nil || c.MinVersion == 0) && !debugEnableTLS10 &&
989 isClient && v < VersionTLS12 {
992 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
995 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
998 versions = append(versions, v)
1003 func (c *Config) maxSupportedVersion(isClient bool) uint16 {
1004 supportedVersions := c.supportedVersions(isClient)
1005 if len(supportedVersions) == 0 {
1008 return supportedVersions[0]
1011 // supportedVersionsFromMax returns a list of supported versions derived from a
1012 // legacy maximum version value. Note that only versions supported by this
1013 // library are returned. Any newer peer will use supportedVersions anyway.
1014 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
1015 versions := make([]uint16, 0, len(supportedVersions))
1016 for _, v := range supportedVersions {
1020 versions = append(versions, v)
1025 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
1027 func (c *Config) curvePreferences() []CurveID {
1028 if c == nil || len(c.CurvePreferences) == 0 {
1029 return defaultCurvePreferences
1031 return c.CurvePreferences
1034 func (c *Config) supportsCurve(curve CurveID) bool {
1035 for _, cc := range c.curvePreferences() {
1043 // mutualVersion returns the protocol version to use given the advertised
1044 // versions of the peer. Priority is given to the peer preference order.
1045 func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
1046 supportedVersions := c.supportedVersions(isClient)
1047 for _, peerVersion := range peerVersions {
1048 for _, v := range supportedVersions {
1049 if v == peerVersion {
1057 var errNoCertificates = errors.New("tls: no certificates configured")
1059 // getCertificate returns the best certificate for the given ClientHelloInfo,
1060 // defaulting to the first element of c.Certificates.
1061 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1062 if c.GetCertificate != nil &&
1063 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1064 cert, err := c.GetCertificate(clientHello)
1065 if cert != nil || err != nil {
1070 if len(c.Certificates) == 0 {
1071 return nil, errNoCertificates
1074 if len(c.Certificates) == 1 {
1075 // There's only one choice, so no point doing any work.
1076 return &c.Certificates[0], nil
1079 if c.NameToCertificate != nil {
1080 name := strings.ToLower(clientHello.ServerName)
1081 if cert, ok := c.NameToCertificate[name]; ok {
1085 labels := strings.Split(name, ".")
1087 wildcardName := strings.Join(labels, ".")
1088 if cert, ok := c.NameToCertificate[wildcardName]; ok {
1094 for _, cert := range c.Certificates {
1095 if err := clientHello.SupportsCertificate(&cert); err == nil {
1100 // If nothing matches, return the first certificate.
1101 return &c.Certificates[0], nil
1104 // SupportsCertificate returns nil if the provided certificate is supported by
1105 // the client that sent the ClientHello. Otherwise, it returns an error
1106 // describing the reason for the incompatibility.
1108 // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
1109 // callback, this method will take into account the associated Config. Note that
1110 // if GetConfigForClient returns a different Config, the change can't be
1111 // accounted for by this method.
1113 // This function will call x509.ParseCertificate unless c.Leaf is set, which can
1114 // incur a significant performance cost.
1115 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1116 // Note we don't currently support certificate_authorities nor
1117 // signature_algorithms_cert, and don't check the algorithms of the
1118 // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1119 // Section 4.4.2.2).
1121 config := chi.config
1125 vers, ok := config.mutualVersion(roleServer, chi.SupportedVersions)
1127 return errors.New("no mutually supported protocol versions")
1130 // If the client specified the name they are trying to connect to, the
1131 // certificate needs to be valid for it.
1132 if chi.ServerName != "" {
1133 x509Cert, err := c.leaf()
1135 return fmt.Errorf("failed to parse certificate: %w", err)
1137 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1138 return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1142 // supportsRSAFallback returns nil if the certificate and connection support
1143 // the static RSA key exchange, and unsupported otherwise. The logic for
1144 // supporting static RSA is completely disjoint from the logic for
1145 // supporting signed key exchanges, so we just check it as a fallback.
1146 supportsRSAFallback := func(unsupported error) error {
1147 // TLS 1.3 dropped support for the static RSA key exchange.
1148 if vers == VersionTLS13 {
1151 // The static RSA key exchange works by decrypting a challenge with the
1152 // RSA private key, not by signing, so check the PrivateKey implements
1153 // crypto.Decrypter, like *rsa.PrivateKey does.
1154 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1155 if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1161 // Finally, there needs to be a mutual cipher suite that uses the static
1162 // RSA key exchange instead of ECDHE.
1163 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1164 if c.flags&suiteECDHE != 0 {
1167 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1172 if rsaCipherSuite == nil {
1178 // If the client sent the signature_algorithms extension, ensure it supports
1179 // schemes we can use with this certificate and TLS version.
1180 if len(chi.SignatureSchemes) > 0 {
1181 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1182 return supportsRSAFallback(err)
1186 // In TLS 1.3 we are done because supported_groups is only relevant to the
1187 // ECDHE computation, point format negotiation is removed, cipher suites are
1188 // only relevant to the AEAD choice, and static RSA does not exist.
1189 if vers == VersionTLS13 {
1193 // The only signed key exchange we support is ECDHE.
1194 if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
1195 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1198 var ecdsaCipherSuite bool
1199 if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1200 switch pub := priv.Public().(type) {
1201 case *ecdsa.PublicKey:
1204 case elliptic.P256():
1206 case elliptic.P384():
1208 case elliptic.P521():
1211 return supportsRSAFallback(unsupportedCertificateError(c))
1214 for _, c := range chi.SupportedCurves {
1215 if c == curve && config.supportsCurve(c) {
1221 return errors.New("client doesn't support certificate curve")
1223 ecdsaCipherSuite = true
1224 case ed25519.PublicKey:
1225 if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1226 return errors.New("connection doesn't support Ed25519")
1228 ecdsaCipherSuite = true
1229 case *rsa.PublicKey:
1231 return supportsRSAFallback(unsupportedCertificateError(c))
1234 return supportsRSAFallback(unsupportedCertificateError(c))
1237 // Make sure that there is a mutually supported cipher suite that works with
1238 // this certificate. Cipher suite selection will then apply the logic in
1239 // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1240 cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1241 if c.flags&suiteECDHE == 0 {
1244 if c.flags&suiteECSign != 0 {
1245 if !ecdsaCipherSuite {
1249 if ecdsaCipherSuite {
1253 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1258 if cipherSuite == nil {
1259 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1265 // SupportsCertificate returns nil if the provided certificate is supported by
1266 // the server that sent the CertificateRequest. Otherwise, it returns an error
1267 // describing the reason for the incompatibility.
1268 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1269 if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1273 if len(cri.AcceptableCAs) == 0 {
1277 for j, cert := range c.Certificate {
1279 // Parse the certificate if this isn't the leaf node, or if
1280 // chain.Leaf was nil.
1281 if j != 0 || x509Cert == nil {
1283 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1284 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1288 for _, ca := range cri.AcceptableCAs {
1289 if bytes.Equal(x509Cert.RawIssuer, ca) {
1294 return errors.New("chain is not signed by an acceptable CA")
1297 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1298 // from the CommonName and SubjectAlternateName fields of each of the leaf
1301 // Deprecated: NameToCertificate only allows associating a single certificate
1302 // with a given name. Leave that field nil to let the library select the first
1303 // compatible chain from Certificates.
1304 func (c *Config) BuildNameToCertificate() {
1305 c.NameToCertificate = make(map[string]*Certificate)
1306 for i := range c.Certificates {
1307 cert := &c.Certificates[i]
1308 x509Cert, err := cert.leaf()
1312 // If SANs are *not* present, some clients will consider the certificate
1313 // valid for the name in the Common Name.
1314 if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
1315 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1317 for _, san := range x509Cert.DNSNames {
1318 c.NameToCertificate[san] = cert
1324 keyLogLabelTLS12 = "CLIENT_RANDOM"
1325 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1326 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1327 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
1328 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
1331 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1332 if c.KeyLogWriter == nil {
1336 logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
1339 _, err := c.KeyLogWriter.Write(logLine)
1340 writerMutex.Unlock()
1345 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1346 // and is only for debugging, so a global mutex saves space.
1347 var writerMutex sync.Mutex
1349 // A Certificate is a chain of one or more certificates, leaf first.
1350 type Certificate struct {
1351 Certificate [][]byte
1352 // PrivateKey contains the private key corresponding to the public key in
1353 // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1354 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1355 // an RSA PublicKey.
1356 PrivateKey crypto.PrivateKey
1357 // SupportedSignatureAlgorithms is an optional list restricting what
1358 // signature algorithms the PrivateKey can be used for.
1359 SupportedSignatureAlgorithms []SignatureScheme
1360 // OCSPStaple contains an optional OCSP response which will be served
1361 // to clients that request it.
1363 // SignedCertificateTimestamps contains an optional list of Signed
1364 // Certificate Timestamps which will be served to clients that request it.
1365 SignedCertificateTimestamps [][]byte
1366 // Leaf is the parsed form of the leaf certificate, which may be initialized
1367 // using x509.ParseCertificate to reduce per-handshake processing. If nil,
1368 // the leaf certificate will be parsed as needed.
1369 Leaf *x509.Certificate
1372 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1373 // the corresponding c.Certificate[0].
1374 func (c *Certificate) leaf() (*x509.Certificate, error) {
1378 return x509.ParseCertificate(c.Certificate[0])
1381 type handshakeMessage interface {
1383 unmarshal([]byte) bool
1386 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1387 // caching strategy.
1388 type lruSessionCache struct {
1391 m map[string]*list.Element
1396 type lruSessionCacheEntry struct {
1398 state *ClientSessionState
1401 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1402 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1404 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1405 const defaultSessionCacheCapacity = 64
1408 capacity = defaultSessionCacheCapacity
1410 return &lruSessionCache{
1411 m: make(map[string]*list.Element),
1417 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1418 // corresponding to sessionKey is removed from the cache instead.
1419 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1423 if elem, ok := c.m[sessionKey]; ok {
1426 delete(c.m, sessionKey)
1428 entry := elem.Value.(*lruSessionCacheEntry)
1430 c.q.MoveToFront(elem)
1435 if c.q.Len() < c.capacity {
1436 entry := &lruSessionCacheEntry{sessionKey, cs}
1437 c.m[sessionKey] = c.q.PushFront(entry)
1442 entry := elem.Value.(*lruSessionCacheEntry)
1443 delete(c.m, entry.sessionKey)
1444 entry.sessionKey = sessionKey
1446 c.q.MoveToFront(elem)
1447 c.m[sessionKey] = elem
1450 // Get returns the ClientSessionState value associated with a given key. It
1451 // returns (nil, false) if no value is found.
1452 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1456 if elem, ok := c.m[sessionKey]; ok {
1457 c.q.MoveToFront(elem)
1458 return elem.Value.(*lruSessionCacheEntry).state, true
1463 var emptyConfig Config
1465 func defaultConfig() *Config {
1469 func unexpectedMessageError(wanted, got interface{}) error {
1470 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1473 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1474 for _, s := range supportedSignatureAlgorithms {