1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
34 // Deprecated: SSLv3 is cryptographically broken, and is no longer
35 // supported by this package. See golang.org/issue/32716.
40 maxPlaintext = 16384 // maximum plaintext payload length
41 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
42 maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3
43 recordHeaderLen = 5 // record header length
44 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
45 maxUselessRecords = 16 // maximum number of consecutive non-advancing records
52 recordTypeChangeCipherSpec recordType = 20
53 recordTypeAlert recordType = 21
54 recordTypeHandshake recordType = 22
55 recordTypeApplicationData recordType = 23
58 // TLS handshake message types.
60 typeHelloRequest uint8 = 0
61 typeClientHello uint8 = 1
62 typeServerHello uint8 = 2
63 typeNewSessionTicket uint8 = 4
64 typeEndOfEarlyData uint8 = 5
65 typeEncryptedExtensions uint8 = 8
66 typeCertificate uint8 = 11
67 typeServerKeyExchange uint8 = 12
68 typeCertificateRequest uint8 = 13
69 typeServerHelloDone uint8 = 14
70 typeCertificateVerify uint8 = 15
71 typeClientKeyExchange uint8 = 16
72 typeFinished uint8 = 20
73 typeCertificateStatus uint8 = 22
74 typeKeyUpdate uint8 = 24
75 typeNextProtocol uint8 = 67 // Not IANA assigned
76 typeMessageHash uint8 = 254 // synthetic message
79 // TLS compression types.
81 compressionNone uint8 = 0
84 // TLS extension numbers
86 extensionServerName uint16 = 0
87 extensionStatusRequest uint16 = 5
88 extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
89 extensionSupportedPoints uint16 = 11
90 extensionSignatureAlgorithms uint16 = 13
91 extensionALPN uint16 = 16
92 extensionSCT uint16 = 18
93 extensionSessionTicket uint16 = 35
94 extensionPreSharedKey uint16 = 41
95 extensionEarlyData uint16 = 42
96 extensionSupportedVersions uint16 = 43
97 extensionCookie uint16 = 44
98 extensionPSKModes uint16 = 45
99 extensionCertificateAuthorities uint16 = 47
100 extensionSignatureAlgorithmsCert uint16 = 50
101 extensionKeyShare uint16 = 51
102 extensionQUICTransportParameters uint16 = 57
103 extensionRenegotiationInfo uint16 = 0xff01
106 // TLS signaling cipher suite values
108 scsvRenegotiation uint16 = 0x00ff
111 // CurveID is the type of a TLS identifier for an elliptic curve. See
112 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
114 // In TLS 1.3, this type is called NamedGroup, but at this time this library
115 // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
119 CurveP256 CurveID = 23
120 CurveP384 CurveID = 24
121 CurveP521 CurveID = 25
125 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
126 type keyShare struct {
131 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
133 pskModePlain uint8 = 0
137 // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
138 // session. See RFC 8446, Section 4.2.11.
139 type pskIdentity struct {
141 obfuscatedTicketAge uint32
144 // TLS Elliptic Curve Point Formats
145 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
147 pointFormatUncompressed uint8 = 0
150 // TLS CertificateStatusType (RFC 3546)
152 statusTypeOCSP uint8 = 1
155 // Certificate types (for certificateRequestMsg)
158 certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
161 // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
162 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
164 signaturePKCS1v15 uint8 = iota + 225
170 // directSigning is a standard Hash value that signals that no pre-hashing
171 // should be performed, and that the input should be signed directly. It is the
172 // hash function associated with the Ed25519 signature scheme.
173 var directSigning crypto.Hash = 0
175 // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
176 // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
177 // CertificateRequest. The two fields are merged to match with TLS 1.3.
178 // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
179 var defaultSupportedSignatureAlgorithms = []SignatureScheme{
181 ECDSAWithP256AndSHA256,
188 ECDSAWithP384AndSHA384,
189 ECDSAWithP521AndSHA512,
194 // helloRetryRequestRandom is set as the Random value of a ServerHello
195 // to signal that the message is actually a HelloRetryRequest.
196 var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
197 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
198 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
199 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
200 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
204 // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
205 // random as a downgrade protection if the server would be capable of
206 // negotiating a higher version. See RFC 8446, Section 4.1.3.
207 downgradeCanaryTLS12 = "DOWNGRD\x01"
208 downgradeCanaryTLS11 = "DOWNGRD\x00"
211 // testingOnlyForceDowngradeCanary is set in tests to force the server side to
212 // include downgrade canaries even if it's using its highers supported version.
213 var testingOnlyForceDowngradeCanary bool
215 // ConnectionState records basic TLS details about the connection.
216 type ConnectionState struct {
217 // Version is the TLS version used by the connection (e.g. VersionTLS12).
220 // HandshakeComplete is true if the handshake has concluded.
221 HandshakeComplete bool
223 // DidResume is true if this connection was successfully resumed from a
224 // previous session with a session ticket or similar mechanism.
227 // CipherSuite is the cipher suite negotiated for the connection (e.g.
228 // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
231 // NegotiatedProtocol is the application protocol negotiated with ALPN.
232 NegotiatedProtocol string
234 // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
236 // Deprecated: this value is always true.
237 NegotiatedProtocolIsMutual bool
239 // ServerName is the value of the Server Name Indication extension sent by
240 // the client. It's available both on the server and on the client side.
243 // PeerCertificates are the parsed certificates sent by the peer, in the
244 // order in which they were sent. The first element is the leaf certificate
245 // that the connection is verified against.
247 // On the client side, it can't be empty. On the server side, it can be
248 // empty if Config.ClientAuth is not RequireAnyClientCert or
249 // RequireAndVerifyClientCert.
251 // PeerCertificates and its contents should not be modified.
252 PeerCertificates []*x509.Certificate
254 // VerifiedChains is a list of one or more chains where the first element is
255 // PeerCertificates[0] and the last element is from Config.RootCAs (on the
256 // client side) or Config.ClientCAs (on the server side).
258 // On the client side, it's set if Config.InsecureSkipVerify is false. On
259 // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
260 // (and the peer provided a certificate) or RequireAndVerifyClientCert.
262 // VerifiedChains and its contents should not be modified.
263 VerifiedChains [][]*x509.Certificate
265 // SignedCertificateTimestamps is a list of SCTs provided by the peer
266 // through the TLS handshake for the leaf certificate, if any.
267 SignedCertificateTimestamps [][]byte
269 // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
270 // response provided by the peer for the leaf certificate, if any.
273 // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
274 // Section 3). This value will be nil for TLS 1.3 connections and for all
275 // resumed connections.
277 // Deprecated: there are conditions in which this value might not be unique
278 // to a connection. See the Security Considerations sections of RFC 5705 and
279 // RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
282 // ekm is a closure exposed via ExportKeyingMaterial.
283 ekm func(label string, context []byte, length int) ([]byte, error)
286 // ExportKeyingMaterial returns length bytes of exported key material in a new
287 // slice as defined in RFC 5705. If context is nil, it is not used as part of
288 // the seed. If the connection was set to allow renegotiation via
289 // Config.Renegotiation, this function will return an error.
290 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
291 return cs.ekm(label, context, length)
294 // ClientAuthType declares the policy the server will follow for
295 // TLS Client Authentication.
296 type ClientAuthType int
299 // NoClientCert indicates that no client certificate should be requested
300 // during the handshake, and if any certificates are sent they will not
302 NoClientCert ClientAuthType = iota
303 // RequestClientCert indicates that a client certificate should be requested
304 // during the handshake, but does not require that the client send any
307 // RequireAnyClientCert indicates that a client certificate should be requested
308 // during the handshake, and that at least one certificate is required to be
309 // sent by the client, but that certificate is not required to be valid.
311 // VerifyClientCertIfGiven indicates that a client certificate should be requested
312 // during the handshake, but does not require that the client sends a
313 // certificate. If the client does send a certificate it is required to be
315 VerifyClientCertIfGiven
316 // RequireAndVerifyClientCert indicates that a client certificate should be requested
317 // during the handshake, and that at least one valid certificate is required
318 // to be sent by the client.
319 RequireAndVerifyClientCert
322 // requiresClientCert reports whether the ClientAuthType requires a client
323 // certificate to be provided.
324 func requiresClientCert(c ClientAuthType) bool {
326 case RequireAnyClientCert, RequireAndVerifyClientCert:
333 // ClientSessionCache is a cache of ClientSessionState objects that can be used
334 // by a client to resume a TLS session with a given server. ClientSessionCache
335 // implementations should expect to be called concurrently from different
336 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
337 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
338 // are supported via this interface.
339 type ClientSessionCache interface {
340 // Get searches for a ClientSessionState associated with the given key.
341 // On return, ok is true if one was found.
342 Get(sessionKey string) (session *ClientSessionState, ok bool)
344 // Put adds the ClientSessionState to the cache with the given key. It might
345 // get called multiple times in a connection if a TLS 1.3 server provides
346 // more than one session ticket. If called with a nil *ClientSessionState,
347 // it should remove the cache entry.
348 Put(sessionKey string, cs *ClientSessionState)
351 //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
353 // SignatureScheme identifies a signature algorithm supported by TLS. See
354 // RFC 8446, Section 4.2.3.
355 type SignatureScheme uint16
358 // RSASSA-PKCS1-v1_5 algorithms.
359 PKCS1WithSHA256 SignatureScheme = 0x0401
360 PKCS1WithSHA384 SignatureScheme = 0x0501
361 PKCS1WithSHA512 SignatureScheme = 0x0601
363 // RSASSA-PSS algorithms with public key OID rsaEncryption.
364 PSSWithSHA256 SignatureScheme = 0x0804
365 PSSWithSHA384 SignatureScheme = 0x0805
366 PSSWithSHA512 SignatureScheme = 0x0806
368 // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
369 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
370 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
371 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
374 Ed25519 SignatureScheme = 0x0807
376 // Legacy signature and hash algorithms for TLS 1.2.
377 PKCS1WithSHA1 SignatureScheme = 0x0201
378 ECDSAWithSHA1 SignatureScheme = 0x0203
381 // ClientHelloInfo contains information from a ClientHello message in order to
382 // guide application logic in the GetCertificate and GetConfigForClient callbacks.
383 type ClientHelloInfo struct {
384 // CipherSuites lists the CipherSuites supported by the client (e.g.
385 // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
386 CipherSuites []uint16
388 // ServerName indicates the name of the server requested by the client
389 // in order to support virtual hosting. ServerName is only set if the
390 // client is using SNI (see RFC 4366, Section 3.1).
393 // SupportedCurves lists the elliptic curves supported by the client.
394 // SupportedCurves is set only if the Supported Elliptic Curves
395 // Extension is being used (see RFC 4492, Section 5.1.1).
396 SupportedCurves []CurveID
398 // SupportedPoints lists the point formats supported by the client.
399 // SupportedPoints is set only if the Supported Point Formats Extension
400 // is being used (see RFC 4492, Section 5.1.2).
401 SupportedPoints []uint8
403 // SignatureSchemes lists the signature and hash schemes that the client
404 // is willing to verify. SignatureSchemes is set only if the Signature
405 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
406 SignatureSchemes []SignatureScheme
408 // SupportedProtos lists the application protocols supported by the client.
409 // SupportedProtos is set only if the Application-Layer Protocol
410 // Negotiation Extension is being used (see RFC 7301, Section 3.1).
412 // Servers can select a protocol by setting Config.NextProtos in a
413 // GetConfigForClient return value.
414 SupportedProtos []string
416 // SupportedVersions lists the TLS versions supported by the client.
417 // For TLS versions less than 1.3, this is extrapolated from the max
418 // version advertised by the client, so values other than the greatest
419 // might be rejected if used.
420 SupportedVersions []uint16
422 // Conn is the underlying net.Conn for the connection. Do not read
423 // from, or write to, this connection; that will cause the TLS
424 // connection to fail.
427 // config is embedded by the GetCertificate or GetConfigForClient caller,
428 // for use with SupportsCertificate.
431 // ctx is the context of the handshake that is in progress.
435 // Context returns the context of the handshake that is in progress.
436 // This context is a child of the context passed to HandshakeContext,
437 // if any, and is canceled when the handshake concludes.
438 func (c *ClientHelloInfo) Context() context.Context {
442 // CertificateRequestInfo contains information from a server's
443 // CertificateRequest message, which is used to demand a certificate and proof
444 // of control from a client.
445 type CertificateRequestInfo struct {
446 // AcceptableCAs contains zero or more, DER-encoded, X.501
447 // Distinguished Names. These are the names of root or intermediate CAs
448 // that the server wishes the returned certificate to be signed by. An
449 // empty slice indicates that the server has no preference.
450 AcceptableCAs [][]byte
452 // SignatureSchemes lists the signature schemes that the server is
453 // willing to verify.
454 SignatureSchemes []SignatureScheme
456 // Version is the TLS version that was negotiated for this connection.
459 // ctx is the context of the handshake that is in progress.
463 // Context returns the context of the handshake that is in progress.
464 // This context is a child of the context passed to HandshakeContext,
465 // if any, and is canceled when the handshake concludes.
466 func (c *CertificateRequestInfo) Context() context.Context {
470 // RenegotiationSupport enumerates the different levels of support for TLS
471 // renegotiation. TLS renegotiation is the act of performing subsequent
472 // handshakes on a connection after the first. This significantly complicates
473 // the state machine and has been the source of numerous, subtle security
474 // issues. Initiating a renegotiation is not supported, but support for
475 // accepting renegotiation requests may be enabled.
477 // Even when enabled, the server may not change its identity between handshakes
478 // (i.e. the leaf certificate must be the same). Additionally, concurrent
479 // handshake and application data flow is not permitted so renegotiation can
480 // only be used with protocols that synchronise with the renegotiation, such as
483 // Renegotiation is not defined in TLS 1.3.
484 type RenegotiationSupport int
487 // RenegotiateNever disables renegotiation.
488 RenegotiateNever RenegotiationSupport = iota
490 // RenegotiateOnceAsClient allows a remote server to request
491 // renegotiation once per connection.
492 RenegotiateOnceAsClient
494 // RenegotiateFreelyAsClient allows a remote server to repeatedly
495 // request renegotiation.
496 RenegotiateFreelyAsClient
499 // A Config structure is used to configure a TLS client or server.
500 // After one has been passed to a TLS function it must not be
501 // modified. A Config may be reused; the tls package will also not
504 // Rand provides the source of entropy for nonces and RSA blinding.
505 // If Rand is nil, TLS uses the cryptographic random reader in package
507 // The Reader must be safe for use by multiple goroutines.
510 // Time returns the current time as the number of seconds since the epoch.
511 // If Time is nil, TLS uses time.Now.
512 Time func() time.Time
514 // Certificates contains one or more certificate chains to present to the
515 // other side of the connection. The first certificate compatible with the
516 // peer's requirements is selected automatically.
518 // Server configurations must set one of Certificates, GetCertificate or
519 // GetConfigForClient. Clients doing client-authentication may set either
520 // Certificates or GetClientCertificate.
522 // Note: if there are multiple Certificates, and they don't have the
523 // optional field Leaf set, certificate selection will incur a significant
524 // per-handshake performance cost.
525 Certificates []Certificate
527 // NameToCertificate maps from a certificate name to an element of
528 // Certificates. Note that a certificate name can be of the form
529 // '*.example.com' and so doesn't have to be a domain name as such.
531 // Deprecated: NameToCertificate only allows associating a single
532 // certificate with a given name. Leave this field nil to let the library
533 // select the first compatible chain from Certificates.
534 NameToCertificate map[string]*Certificate
536 // GetCertificate returns a Certificate based on the given
537 // ClientHelloInfo. It will only be called if the client supplies SNI
538 // information or if Certificates is empty.
540 // If GetCertificate is nil or returns nil, then the certificate is
541 // retrieved from NameToCertificate. If NameToCertificate is nil, the
542 // best element of Certificates will be used.
544 // Once a Certificate is returned it should not be modified.
545 GetCertificate func(*ClientHelloInfo) (*Certificate, error)
547 // GetClientCertificate, if not nil, is called when a server requests a
548 // certificate from a client. If set, the contents of Certificates will
551 // If GetClientCertificate returns an error, the handshake will be
552 // aborted and that error will be returned. Otherwise
553 // GetClientCertificate must return a non-nil Certificate. If
554 // Certificate.Certificate is empty then no certificate will be sent to
555 // the server. If this is unacceptable to the server then it may abort
558 // GetClientCertificate may be called multiple times for the same
559 // connection if renegotiation occurs or if TLS 1.3 is in use.
561 // Once a Certificate is returned it should not be modified.
562 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
564 // GetConfigForClient, if not nil, is called after a ClientHello is
565 // received from a client. It may return a non-nil Config in order to
566 // change the Config that will be used to handle this connection. If
567 // the returned Config is nil, the original Config will be used. The
568 // Config returned by this callback may not be subsequently modified.
570 // If GetConfigForClient is nil, the Config passed to Server() will be
571 // used for all connections.
573 // If SessionTicketKey was explicitly set on the returned Config, or if
574 // SetSessionTicketKeys was called on the returned Config, those keys will
575 // be used. Otherwise, the original Config keys will be used (and possibly
576 // rotated if they are automatically managed).
577 GetConfigForClient func(*ClientHelloInfo) (*Config, error)
579 // VerifyPeerCertificate, if not nil, is called after normal
580 // certificate verification by either a TLS client or server. It
581 // receives the raw ASN.1 certificates provided by the peer and also
582 // any verified chains that normal processing found. If it returns a
583 // non-nil error, the handshake is aborted and that error results.
585 // If normal verification fails then the handshake will abort before
586 // considering this callback. If normal verification is disabled by
587 // setting InsecureSkipVerify, or (for a server) when ClientAuth is
588 // RequestClientCert or RequireAnyClientCert, then this callback will
589 // be considered but the verifiedChains argument will always be nil.
591 // verifiedChains and its contents should not be modified.
592 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
594 // VerifyConnection, if not nil, is called after normal certificate
595 // verification and after VerifyPeerCertificate by either a TLS client
596 // or server. If it returns a non-nil error, the handshake is aborted
597 // and that error results.
599 // If normal verification fails then the handshake will abort before
600 // considering this callback. This callback will run for all connections
601 // regardless of InsecureSkipVerify or ClientAuth settings.
602 VerifyConnection func(ConnectionState) error
604 // RootCAs defines the set of root certificate authorities
605 // that clients use when verifying server certificates.
606 // If RootCAs is nil, TLS uses the host's root CA set.
607 RootCAs *x509.CertPool
609 // NextProtos is a list of supported application level protocols, in
610 // order of preference. If both peers support ALPN, the selected
611 // protocol will be one from this list, and the connection will fail
612 // if there is no mutually supported protocol. If NextProtos is empty
613 // or the peer doesn't support ALPN, the connection will succeed and
614 // ConnectionState.NegotiatedProtocol will be empty.
617 // ServerName is used to verify the hostname on the returned
618 // certificates unless InsecureSkipVerify is given. It is also included
619 // in the client's handshake to support virtual hosting unless it is
623 // ClientAuth determines the server's policy for
624 // TLS Client Authentication. The default is NoClientCert.
625 ClientAuth ClientAuthType
627 // ClientCAs defines the set of root certificate authorities
628 // that servers use if required to verify a client certificate
629 // by the policy in ClientAuth.
630 ClientCAs *x509.CertPool
632 // InsecureSkipVerify controls whether a client verifies the server's
633 // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
634 // accepts any certificate presented by the server and any host name in that
635 // certificate. In this mode, TLS is susceptible to machine-in-the-middle
636 // attacks unless custom verification is used. This should be used only for
637 // testing or in combination with VerifyConnection or VerifyPeerCertificate.
638 InsecureSkipVerify bool
640 // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
641 // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
643 // If CipherSuites is nil, a safe default list is used. The default cipher
644 // suites might change over time.
645 CipherSuites []uint16
647 // PreferServerCipherSuites is a legacy field and has no effect.
649 // It used to control whether the server would follow the client's or the
650 // server's preference. Servers now select the best mutually supported
651 // cipher suite based on logic that takes into account inferred client
652 // hardware, server hardware, and security.
654 // Deprecated: PreferServerCipherSuites is ignored.
655 PreferServerCipherSuites bool
657 // SessionTicketsDisabled may be set to true to disable session ticket and
658 // PSK (resumption) support. Note that on clients, session ticket support is
659 // also disabled if ClientSessionCache is nil.
660 SessionTicketsDisabled bool
662 // SessionTicketKey is used by TLS servers to provide session resumption.
663 // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
664 // with random data before the first server handshake.
666 // Deprecated: if this field is left at zero, session ticket keys will be
667 // automatically rotated every day and dropped after seven days. For
668 // customizing the rotation schedule or synchronizing servers that are
669 // terminating connections for the same host, use SetSessionTicketKeys.
670 SessionTicketKey [32]byte
672 // ClientSessionCache is a cache of ClientSessionState entries for TLS
673 // session resumption. It is only used by clients.
674 ClientSessionCache ClientSessionCache
676 // UnwrapSession is called on the server to turn a ticket/identity
677 // previously produced by [WrapSession] into a usable session.
679 // UnwrapSession will usually either decrypt a session state in the ticket
680 // (for example with [Config.EncryptTicket]), or use the ticket as a handle
681 // to recover a previously stored state. It must use [ParseSessionState] to
682 // deserialize the session state.
684 // If UnwrapSession returns an error, the connection is terminated. If it
685 // returns (nil, nil), the session is ignored. crypto/tls may still choose
686 // not to resume the returned session.
687 UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
689 // WrapSession is called on the server to produce a session ticket/identity.
691 // WrapSession must serialize the session state with [SessionState.Bytes].
692 // It may then encrypt the serialized state (for example with
693 // [Config.DecryptTicket]) and use it as the ticket, or store the state and
694 // return a handle for it.
696 // If WrapSession returns an error, the connection is terminated.
698 // Warning: the return value will be exposed on the wire and to clients in
699 // plaintext. The application is in charge of encrypting and authenticating
700 // it (and rotating keys) or returning high-entropy identifiers. Failing to
701 // do so correctly can compromise current, previous, and future connections
702 // depending on the protocol version.
703 WrapSession func(ConnectionState, *SessionState) ([]byte, error)
705 // MinVersion contains the minimum TLS version that is acceptable.
707 // By default, TLS 1.2 is currently used as the minimum when acting as a
708 // client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
709 // supported by this package, both as a client and as a server.
711 // The client-side default can temporarily be reverted to TLS 1.0 by
712 // including the value "x509sha1=1" in the GODEBUG environment variable.
713 // Note that this option will be removed in Go 1.19 (but it will still be
714 // possible to set this field to VersionTLS10 explicitly).
717 // MaxVersion contains the maximum TLS version that is acceptable.
719 // By default, the maximum version supported by this package is used,
720 // which is currently TLS 1.3.
723 // CurvePreferences contains the elliptic curves that will be used in
724 // an ECDHE handshake, in preference order. If empty, the default will
725 // be used. The client will use the first preference as the type for
726 // its key share in TLS 1.3. This may change in the future.
727 CurvePreferences []CurveID
729 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
730 // When true, the largest possible TLS record size is always used. When
731 // false, the size of TLS records may be adjusted in an attempt to
733 DynamicRecordSizingDisabled bool
735 // Renegotiation controls what types of renegotiation are supported.
736 // The default, none, is correct for the vast majority of applications.
737 Renegotiation RenegotiationSupport
739 // KeyLogWriter optionally specifies a destination for TLS master secrets
740 // in NSS key log format that can be used to allow external programs
741 // such as Wireshark to decrypt TLS connections.
742 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
743 // Use of KeyLogWriter compromises security and should only be
744 // used for debugging.
745 KeyLogWriter io.Writer
747 // mutex protects sessionTicketKeys and autoSessionTicketKeys.
749 // sessionTicketKeys contains zero or more ticket keys. If set, it means
750 // the keys were set with SessionTicketKey or SetSessionTicketKeys. The
751 // first key is used for new tickets and any subsequent keys can be used to
752 // decrypt old tickets. The slice contents are not protected by the mutex
753 // and are immutable.
754 sessionTicketKeys []ticketKey
755 // autoSessionTicketKeys is like sessionTicketKeys but is owned by the
756 // auto-rotation logic. See Config.ticketKeys.
757 autoSessionTicketKeys []ticketKey
761 // ticketKeyLifetime is how long a ticket key remains valid and can be used to
762 // resume a client connection.
763 ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
765 // ticketKeyRotation is how often the server should rotate the session ticket key
766 // that is used for new tickets.
767 ticketKeyRotation = 24 * time.Hour
770 // ticketKey is the internal representation of a session ticket key.
771 type ticketKey struct {
774 // created is the time at which this ticket key was created. See Config.ticketKeys.
778 // ticketKeyFromBytes converts from the external representation of a session
779 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
780 // bytes and this function expands that into sufficient name and key material.
781 func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
782 hashed := sha512.Sum512(b[:])
783 // The first 16 bytes of the hash used to be exposed on the wire as a ticket
784 // prefix. They MUST NOT be used as a secret. In the future, it would make
785 // sense to use a proper KDF here, like HKDF with a fixed salt.
786 const legacyTicketKeyNameLen = 16
787 copy(key.aesKey[:], hashed[legacyTicketKeyNameLen:])
788 copy(key.hmacKey[:], hashed[legacyTicketKeyNameLen+len(key.aesKey):])
789 key.created = c.time()
793 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
794 // ticket, and the lifetime we set for all tickets we send.
795 const maxSessionTicketLifetime = 7 * 24 * time.Hour
797 // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
798 // being used concurrently by a TLS client or server.
799 func (c *Config) Clone() *Config {
804 defer c.mutex.RUnlock()
808 Certificates: c.Certificates,
809 NameToCertificate: c.NameToCertificate,
810 GetCertificate: c.GetCertificate,
811 GetClientCertificate: c.GetClientCertificate,
812 GetConfigForClient: c.GetConfigForClient,
813 VerifyPeerCertificate: c.VerifyPeerCertificate,
814 VerifyConnection: c.VerifyConnection,
816 NextProtos: c.NextProtos,
817 ServerName: c.ServerName,
818 ClientAuth: c.ClientAuth,
819 ClientCAs: c.ClientCAs,
820 InsecureSkipVerify: c.InsecureSkipVerify,
821 CipherSuites: c.CipherSuites,
822 PreferServerCipherSuites: c.PreferServerCipherSuites,
823 SessionTicketsDisabled: c.SessionTicketsDisabled,
824 SessionTicketKey: c.SessionTicketKey,
825 ClientSessionCache: c.ClientSessionCache,
826 UnwrapSession: c.UnwrapSession,
827 WrapSession: c.WrapSession,
828 MinVersion: c.MinVersion,
829 MaxVersion: c.MaxVersion,
830 CurvePreferences: c.CurvePreferences,
831 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
832 Renegotiation: c.Renegotiation,
833 KeyLogWriter: c.KeyLogWriter,
834 sessionTicketKeys: c.sessionTicketKeys,
835 autoSessionTicketKeys: c.autoSessionTicketKeys,
839 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
840 // randomized for backwards compatibility but is not in use.
841 var deprecatedSessionTicketKey = []byte("DEPRECATED")
843 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
844 // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
845 func (c *Config) initLegacySessionTicketKeyRLocked() {
846 // Don't write if SessionTicketKey is already defined as our deprecated string,
847 // or if it is defined by the user but sessionTicketKeys is already set.
848 if c.SessionTicketKey != [32]byte{} &&
849 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
853 // We need to write some data, so get an exclusive lock and re-check any conditions.
855 defer c.mutex.RLock()
857 defer c.mutex.Unlock()
858 if c.SessionTicketKey == [32]byte{} {
859 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
860 panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
862 // Write the deprecated prefix at the beginning so we know we created
863 // it. This key with the DEPRECATED prefix isn't used as an actual
864 // session ticket key, and is only randomized in case the application
865 // reuses it for some reason.
866 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
867 } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
868 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
873 // ticketKeys returns the ticketKeys for this connection.
874 // If configForClient has explicitly set keys, those will
875 // be returned. Otherwise, the keys on c will be used and
876 // may be rotated if auto-managed.
877 // During rotation, any expired session ticket keys are deleted from
878 // c.sessionTicketKeys. If the session ticket key that is currently
879 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
880 // is not fresh, then a new session ticket key will be
881 // created and prepended to c.sessionTicketKeys.
882 func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
883 // If the ConfigForClient callback returned a Config with explicitly set
884 // keys, use those, otherwise just use the original Config.
885 if configForClient != nil {
886 configForClient.mutex.RLock()
887 if configForClient.SessionTicketsDisabled {
890 configForClient.initLegacySessionTicketKeyRLocked()
891 if len(configForClient.sessionTicketKeys) != 0 {
892 ret := configForClient.sessionTicketKeys
893 configForClient.mutex.RUnlock()
896 configForClient.mutex.RUnlock()
900 defer c.mutex.RUnlock()
901 if c.SessionTicketsDisabled {
904 c.initLegacySessionTicketKeyRLocked()
905 if len(c.sessionTicketKeys) != 0 {
906 return c.sessionTicketKeys
908 // Fast path for the common case where the key is fresh enough.
909 if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
910 return c.autoSessionTicketKeys
913 // autoSessionTicketKeys are managed by auto-rotation.
915 defer c.mutex.RLock()
917 defer c.mutex.Unlock()
918 // Re-check the condition in case it changed since obtaining the new lock.
919 if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
921 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
922 panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
924 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
925 valid = append(valid, c.ticketKeyFromBytes(newKey))
926 for _, k := range c.autoSessionTicketKeys {
927 // While rotating the current key, also remove any expired ones.
928 if c.time().Sub(k.created) < ticketKeyLifetime {
929 valid = append(valid, k)
932 c.autoSessionTicketKeys = valid
934 return c.autoSessionTicketKeys
937 // SetSessionTicketKeys updates the session ticket keys for a server.
939 // The first key will be used when creating new tickets, while all keys can be
940 // used for decrypting tickets. It is safe to call this function while the
941 // server is running in order to rotate the session ticket keys. The function
942 // will panic if keys is empty.
944 // Calling this function will turn off automatic session ticket key rotation.
946 // If multiple servers are terminating connections for the same host they should
947 // all have the same session ticket keys. If the session ticket keys leaks,
948 // previously recorded and future TLS connections using those keys might be
950 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
952 panic("tls: keys must have at least one key")
955 newKeys := make([]ticketKey, len(keys))
956 for i, bytes := range keys {
957 newKeys[i] = c.ticketKeyFromBytes(bytes)
961 c.sessionTicketKeys = newKeys
965 func (c *Config) rand() io.Reader {
973 func (c *Config) time() time.Time {
981 func (c *Config) cipherSuites() []uint16 {
983 return fipsCipherSuites(c)
985 if c.CipherSuites != nil {
986 return c.CipherSuites
988 return defaultCipherSuites
991 var supportedVersions = []uint16{
998 // roleClient and roleServer are meant to call supportedVersions and parents
999 // with more readability at the callsite.
1000 const roleClient = true
1001 const roleServer = false
1003 func (c *Config) supportedVersions(isClient bool) []uint16 {
1004 versions := make([]uint16, 0, len(supportedVersions))
1005 for _, v := range supportedVersions {
1006 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
1009 if (c == nil || c.MinVersion == 0) &&
1010 isClient && v < VersionTLS12 {
1013 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
1016 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
1019 versions = append(versions, v)
1024 func (c *Config) maxSupportedVersion(isClient bool) uint16 {
1025 supportedVersions := c.supportedVersions(isClient)
1026 if len(supportedVersions) == 0 {
1029 return supportedVersions[0]
1032 // supportedVersionsFromMax returns a list of supported versions derived from a
1033 // legacy maximum version value. Note that only versions supported by this
1034 // library are returned. Any newer peer will use supportedVersions anyway.
1035 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
1036 versions := make([]uint16, 0, len(supportedVersions))
1037 for _, v := range supportedVersions {
1041 versions = append(versions, v)
1046 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
1048 func (c *Config) curvePreferences() []CurveID {
1050 return fipsCurvePreferences(c)
1052 if c == nil || len(c.CurvePreferences) == 0 {
1053 return defaultCurvePreferences
1055 return c.CurvePreferences
1058 func (c *Config) supportsCurve(curve CurveID) bool {
1059 for _, cc := range c.curvePreferences() {
1067 // mutualVersion returns the protocol version to use given the advertised
1068 // versions of the peer. Priority is given to the peer preference order.
1069 func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
1070 supportedVersions := c.supportedVersions(isClient)
1071 for _, peerVersion := range peerVersions {
1072 for _, v := range supportedVersions {
1073 if v == peerVersion {
1081 var errNoCertificates = errors.New("tls: no certificates configured")
1083 // getCertificate returns the best certificate for the given ClientHelloInfo,
1084 // defaulting to the first element of c.Certificates.
1085 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1086 if c.GetCertificate != nil &&
1087 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1088 cert, err := c.GetCertificate(clientHello)
1089 if cert != nil || err != nil {
1094 if len(c.Certificates) == 0 {
1095 return nil, errNoCertificates
1098 if len(c.Certificates) == 1 {
1099 // There's only one choice, so no point doing any work.
1100 return &c.Certificates[0], nil
1103 if c.NameToCertificate != nil {
1104 name := strings.ToLower(clientHello.ServerName)
1105 if cert, ok := c.NameToCertificate[name]; ok {
1109 labels := strings.Split(name, ".")
1111 wildcardName := strings.Join(labels, ".")
1112 if cert, ok := c.NameToCertificate[wildcardName]; ok {
1118 for _, cert := range c.Certificates {
1119 if err := clientHello.SupportsCertificate(&cert); err == nil {
1124 // If nothing matches, return the first certificate.
1125 return &c.Certificates[0], nil
1128 // SupportsCertificate returns nil if the provided certificate is supported by
1129 // the client that sent the ClientHello. Otherwise, it returns an error
1130 // describing the reason for the incompatibility.
1132 // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
1133 // callback, this method will take into account the associated Config. Note that
1134 // if GetConfigForClient returns a different Config, the change can't be
1135 // accounted for by this method.
1137 // This function will call x509.ParseCertificate unless c.Leaf is set, which can
1138 // incur a significant performance cost.
1139 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1140 // Note we don't currently support certificate_authorities nor
1141 // signature_algorithms_cert, and don't check the algorithms of the
1142 // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1143 // Section 4.4.2.2).
1145 config := chi.config
1149 vers, ok := config.mutualVersion(roleServer, chi.SupportedVersions)
1151 return errors.New("no mutually supported protocol versions")
1154 // If the client specified the name they are trying to connect to, the
1155 // certificate needs to be valid for it.
1156 if chi.ServerName != "" {
1157 x509Cert, err := c.leaf()
1159 return fmt.Errorf("failed to parse certificate: %w", err)
1161 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1162 return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1166 // supportsRSAFallback returns nil if the certificate and connection support
1167 // the static RSA key exchange, and unsupported otherwise. The logic for
1168 // supporting static RSA is completely disjoint from the logic for
1169 // supporting signed key exchanges, so we just check it as a fallback.
1170 supportsRSAFallback := func(unsupported error) error {
1171 // TLS 1.3 dropped support for the static RSA key exchange.
1172 if vers == VersionTLS13 {
1175 // The static RSA key exchange works by decrypting a challenge with the
1176 // RSA private key, not by signing, so check the PrivateKey implements
1177 // crypto.Decrypter, like *rsa.PrivateKey does.
1178 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1179 if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1185 // Finally, there needs to be a mutual cipher suite that uses the static
1186 // RSA key exchange instead of ECDHE.
1187 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1188 if c.flags&suiteECDHE != 0 {
1191 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1196 if rsaCipherSuite == nil {
1202 // If the client sent the signature_algorithms extension, ensure it supports
1203 // schemes we can use with this certificate and TLS version.
1204 if len(chi.SignatureSchemes) > 0 {
1205 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1206 return supportsRSAFallback(err)
1210 // In TLS 1.3 we are done because supported_groups is only relevant to the
1211 // ECDHE computation, point format negotiation is removed, cipher suites are
1212 // only relevant to the AEAD choice, and static RSA does not exist.
1213 if vers == VersionTLS13 {
1217 // The only signed key exchange we support is ECDHE.
1218 if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
1219 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1222 var ecdsaCipherSuite bool
1223 if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1224 switch pub := priv.Public().(type) {
1225 case *ecdsa.PublicKey:
1228 case elliptic.P256():
1230 case elliptic.P384():
1232 case elliptic.P521():
1235 return supportsRSAFallback(unsupportedCertificateError(c))
1238 for _, c := range chi.SupportedCurves {
1239 if c == curve && config.supportsCurve(c) {
1245 return errors.New("client doesn't support certificate curve")
1247 ecdsaCipherSuite = true
1248 case ed25519.PublicKey:
1249 if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1250 return errors.New("connection doesn't support Ed25519")
1252 ecdsaCipherSuite = true
1253 case *rsa.PublicKey:
1255 return supportsRSAFallback(unsupportedCertificateError(c))
1258 return supportsRSAFallback(unsupportedCertificateError(c))
1261 // Make sure that there is a mutually supported cipher suite that works with
1262 // this certificate. Cipher suite selection will then apply the logic in
1263 // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1264 cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1265 if c.flags&suiteECDHE == 0 {
1268 if c.flags&suiteECSign != 0 {
1269 if !ecdsaCipherSuite {
1273 if ecdsaCipherSuite {
1277 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1282 if cipherSuite == nil {
1283 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1289 // SupportsCertificate returns nil if the provided certificate is supported by
1290 // the server that sent the CertificateRequest. Otherwise, it returns an error
1291 // describing the reason for the incompatibility.
1292 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1293 if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1297 if len(cri.AcceptableCAs) == 0 {
1301 for j, cert := range c.Certificate {
1303 // Parse the certificate if this isn't the leaf node, or if
1304 // chain.Leaf was nil.
1305 if j != 0 || x509Cert == nil {
1307 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1308 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1312 for _, ca := range cri.AcceptableCAs {
1313 if bytes.Equal(x509Cert.RawIssuer, ca) {
1318 return errors.New("chain is not signed by an acceptable CA")
1321 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1322 // from the CommonName and SubjectAlternateName fields of each of the leaf
1325 // Deprecated: NameToCertificate only allows associating a single certificate
1326 // with a given name. Leave that field nil to let the library select the first
1327 // compatible chain from Certificates.
1328 func (c *Config) BuildNameToCertificate() {
1329 c.NameToCertificate = make(map[string]*Certificate)
1330 for i := range c.Certificates {
1331 cert := &c.Certificates[i]
1332 x509Cert, err := cert.leaf()
1336 // If SANs are *not* present, some clients will consider the certificate
1337 // valid for the name in the Common Name.
1338 if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
1339 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1341 for _, san := range x509Cert.DNSNames {
1342 c.NameToCertificate[san] = cert
1348 keyLogLabelTLS12 = "CLIENT_RANDOM"
1349 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1350 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1351 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
1352 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
1355 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1356 if c.KeyLogWriter == nil {
1360 logLine := fmt.Appendf(nil, "%s %x %x\n", label, clientRandom, secret)
1363 _, err := c.KeyLogWriter.Write(logLine)
1364 writerMutex.Unlock()
1369 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1370 // and is only for debugging, so a global mutex saves space.
1371 var writerMutex sync.Mutex
1373 // A Certificate is a chain of one or more certificates, leaf first.
1374 type Certificate struct {
1375 Certificate [][]byte
1376 // PrivateKey contains the private key corresponding to the public key in
1377 // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1378 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1379 // an RSA PublicKey.
1380 PrivateKey crypto.PrivateKey
1381 // SupportedSignatureAlgorithms is an optional list restricting what
1382 // signature algorithms the PrivateKey can be used for.
1383 SupportedSignatureAlgorithms []SignatureScheme
1384 // OCSPStaple contains an optional OCSP response which will be served
1385 // to clients that request it.
1387 // SignedCertificateTimestamps contains an optional list of Signed
1388 // Certificate Timestamps which will be served to clients that request it.
1389 SignedCertificateTimestamps [][]byte
1390 // Leaf is the parsed form of the leaf certificate, which may be initialized
1391 // using x509.ParseCertificate to reduce per-handshake processing. If nil,
1392 // the leaf certificate will be parsed as needed.
1393 Leaf *x509.Certificate
1396 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1397 // the corresponding c.Certificate[0].
1398 func (c *Certificate) leaf() (*x509.Certificate, error) {
1402 return x509.ParseCertificate(c.Certificate[0])
1405 type handshakeMessage interface {
1406 marshal() ([]byte, error)
1407 unmarshal([]byte) bool
1410 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1411 // caching strategy.
1412 type lruSessionCache struct {
1415 m map[string]*list.Element
1420 type lruSessionCacheEntry struct {
1422 state *ClientSessionState
1425 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1426 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1428 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1429 const defaultSessionCacheCapacity = 64
1432 capacity = defaultSessionCacheCapacity
1434 return &lruSessionCache{
1435 m: make(map[string]*list.Element),
1441 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1442 // corresponding to sessionKey is removed from the cache instead.
1443 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1447 if elem, ok := c.m[sessionKey]; ok {
1450 delete(c.m, sessionKey)
1452 entry := elem.Value.(*lruSessionCacheEntry)
1454 c.q.MoveToFront(elem)
1459 if c.q.Len() < c.capacity {
1460 entry := &lruSessionCacheEntry{sessionKey, cs}
1461 c.m[sessionKey] = c.q.PushFront(entry)
1466 entry := elem.Value.(*lruSessionCacheEntry)
1467 delete(c.m, entry.sessionKey)
1468 entry.sessionKey = sessionKey
1470 c.q.MoveToFront(elem)
1471 c.m[sessionKey] = elem
1474 // Get returns the ClientSessionState value associated with a given key. It
1475 // returns (nil, false) if no value is found.
1476 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1480 if elem, ok := c.m[sessionKey]; ok {
1481 c.q.MoveToFront(elem)
1482 return elem.Value.(*lruSessionCacheEntry).state, true
1487 var emptyConfig Config
1489 func defaultConfig() *Config {
1493 func unexpectedMessageError(wanted, got any) error {
1494 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1497 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1498 for _, s := range supportedSignatureAlgorithms {
1506 // CertificateVerificationError is returned when certificate verification fails during the handshake.
1507 type CertificateVerificationError struct {
1508 // UnverifiedCertificates and its contents should not be modified.
1509 UnverifiedCertificates []*x509.Certificate
1513 func (e *CertificateVerificationError) Error() string {
1514 return fmt.Sprintf("tls: failed to verify certificate: %s", e.Err)
1517 func (e *CertificateVerificationError) Unwrap() error {