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 extensionExtendedMasterSecret uint16 = 23
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 extensionQUICTransportParameters uint16 = 57
104 extensionRenegotiationInfo uint16 = 0xff01
107 // TLS signaling cipher suite values
109 scsvRenegotiation uint16 = 0x00ff
112 // CurveID is the type of a TLS identifier for an elliptic curve. See
113 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
115 // In TLS 1.3, this type is called NamedGroup, but at this time this library
116 // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
120 CurveP256 CurveID = 23
121 CurveP384 CurveID = 24
122 CurveP521 CurveID = 25
126 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
127 type keyShare struct {
132 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
134 pskModePlain uint8 = 0
138 // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
139 // session. See RFC 8446, Section 4.2.11.
140 type pskIdentity struct {
142 obfuscatedTicketAge uint32
145 // TLS Elliptic Curve Point Formats
146 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
148 pointFormatUncompressed uint8 = 0
151 // TLS CertificateStatusType (RFC 3546)
153 statusTypeOCSP uint8 = 1
156 // Certificate types (for certificateRequestMsg)
159 certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
162 // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
163 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
165 signaturePKCS1v15 uint8 = iota + 225
171 // directSigning is a standard Hash value that signals that no pre-hashing
172 // should be performed, and that the input should be signed directly. It is the
173 // hash function associated with the Ed25519 signature scheme.
174 var directSigning crypto.Hash = 0
176 // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
177 // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
178 // CertificateRequest. The two fields are merged to match with TLS 1.3.
179 // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
180 var defaultSupportedSignatureAlgorithms = []SignatureScheme{
182 ECDSAWithP256AndSHA256,
189 ECDSAWithP384AndSHA384,
190 ECDSAWithP521AndSHA512,
195 // helloRetryRequestRandom is set as the Random value of a ServerHello
196 // to signal that the message is actually a HelloRetryRequest.
197 var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
198 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
199 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
200 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
201 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
205 // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
206 // random as a downgrade protection if the server would be capable of
207 // negotiating a higher version. See RFC 8446, Section 4.1.3.
208 downgradeCanaryTLS12 = "DOWNGRD\x01"
209 downgradeCanaryTLS11 = "DOWNGRD\x00"
212 // testingOnlyForceDowngradeCanary is set in tests to force the server side to
213 // include downgrade canaries even if it's using its highers supported version.
214 var testingOnlyForceDowngradeCanary bool
216 // ConnectionState records basic TLS details about the connection.
217 type ConnectionState struct {
218 // Version is the TLS version used by the connection (e.g. VersionTLS12).
221 // HandshakeComplete is true if the handshake has concluded.
222 HandshakeComplete bool
224 // DidResume is true if this connection was successfully resumed from a
225 // previous session with a session ticket or similar mechanism.
228 // CipherSuite is the cipher suite negotiated for the connection (e.g.
229 // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
232 // NegotiatedProtocol is the application protocol negotiated with ALPN.
233 NegotiatedProtocol string
235 // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
237 // Deprecated: this value is always true.
238 NegotiatedProtocolIsMutual bool
240 // ServerName is the value of the Server Name Indication extension sent by
241 // the client. It's available both on the server and on the client side.
244 // PeerCertificates are the parsed certificates sent by the peer, in the
245 // order in which they were sent. The first element is the leaf certificate
246 // that the connection is verified against.
248 // On the client side, it can't be empty. On the server side, it can be
249 // empty if Config.ClientAuth is not RequireAnyClientCert or
250 // RequireAndVerifyClientCert.
252 // PeerCertificates and its contents should not be modified.
253 PeerCertificates []*x509.Certificate
255 // VerifiedChains is a list of one or more chains where the first element is
256 // PeerCertificates[0] and the last element is from Config.RootCAs (on the
257 // client side) or Config.ClientCAs (on the server side).
259 // On the client side, it's set if Config.InsecureSkipVerify is false. On
260 // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
261 // (and the peer provided a certificate) or RequireAndVerifyClientCert.
263 // VerifiedChains and its contents should not be modified.
264 VerifiedChains [][]*x509.Certificate
266 // SignedCertificateTimestamps is a list of SCTs provided by the peer
267 // through the TLS handshake for the leaf certificate, if any.
268 SignedCertificateTimestamps [][]byte
270 // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
271 // response provided by the peer for the leaf certificate, if any.
274 // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
275 // Section 3). This value will be nil for TLS 1.3 connections and for
276 // resumed connections that don't support Extended Master Secret (RFC 7627).
279 // ekm is a closure exposed via ExportKeyingMaterial.
280 ekm func(label string, context []byte, length int) ([]byte, error)
283 // ExportKeyingMaterial returns length bytes of exported key material in a new
284 // slice as defined in RFC 5705. If context is nil, it is not used as part of
285 // the seed. If the connection was set to allow renegotiation via
286 // Config.Renegotiation, this function will return an error.
288 // There are conditions in which the returned values might not be unique to a
289 // connection. See the Security Considerations sections of RFC 5705 and RFC 7627,
290 // and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
291 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
292 return cs.ekm(label, context, length)
295 // ClientAuthType declares the policy the server will follow for
296 // TLS Client Authentication.
297 type ClientAuthType int
300 // NoClientCert indicates that no client certificate should be requested
301 // during the handshake, and if any certificates are sent they will not
303 NoClientCert ClientAuthType = iota
304 // RequestClientCert indicates that a client certificate should be requested
305 // during the handshake, but does not require that the client send any
308 // RequireAnyClientCert indicates that a client certificate should be requested
309 // during the handshake, and that at least one certificate is required to be
310 // sent by the client, but that certificate is not required to be valid.
312 // VerifyClientCertIfGiven indicates that a client certificate should be requested
313 // during the handshake, but does not require that the client sends a
314 // certificate. If the client does send a certificate it is required to be
316 VerifyClientCertIfGiven
317 // RequireAndVerifyClientCert indicates that a client certificate should be requested
318 // during the handshake, and that at least one valid certificate is required
319 // to be sent by the client.
320 RequireAndVerifyClientCert
323 // requiresClientCert reports whether the ClientAuthType requires a client
324 // certificate to be provided.
325 func requiresClientCert(c ClientAuthType) bool {
327 case RequireAnyClientCert, RequireAndVerifyClientCert:
334 // ClientSessionCache is a cache of ClientSessionState objects that can be used
335 // by a client to resume a TLS session with a given server. ClientSessionCache
336 // implementations should expect to be called concurrently from different
337 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
338 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
339 // are supported via this interface.
340 type ClientSessionCache interface {
341 // Get searches for a ClientSessionState associated with the given key.
342 // On return, ok is true if one was found.
343 Get(sessionKey string) (session *ClientSessionState, ok bool)
345 // Put adds the ClientSessionState to the cache with the given key. It might
346 // get called multiple times in a connection if a TLS 1.3 server provides
347 // more than one session ticket. If called with a nil *ClientSessionState,
348 // it should remove the cache entry.
349 Put(sessionKey string, cs *ClientSessionState)
352 //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
354 // SignatureScheme identifies a signature algorithm supported by TLS. See
355 // RFC 8446, Section 4.2.3.
356 type SignatureScheme uint16
359 // RSASSA-PKCS1-v1_5 algorithms.
360 PKCS1WithSHA256 SignatureScheme = 0x0401
361 PKCS1WithSHA384 SignatureScheme = 0x0501
362 PKCS1WithSHA512 SignatureScheme = 0x0601
364 // RSASSA-PSS algorithms with public key OID rsaEncryption.
365 PSSWithSHA256 SignatureScheme = 0x0804
366 PSSWithSHA384 SignatureScheme = 0x0805
367 PSSWithSHA512 SignatureScheme = 0x0806
369 // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
370 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
371 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
372 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
375 Ed25519 SignatureScheme = 0x0807
377 // Legacy signature and hash algorithms for TLS 1.2.
378 PKCS1WithSHA1 SignatureScheme = 0x0201
379 ECDSAWithSHA1 SignatureScheme = 0x0203
382 // ClientHelloInfo contains information from a ClientHello message in order to
383 // guide application logic in the GetCertificate and GetConfigForClient callbacks.
384 type ClientHelloInfo struct {
385 // CipherSuites lists the CipherSuites supported by the client (e.g.
386 // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
387 CipherSuites []uint16
389 // ServerName indicates the name of the server requested by the client
390 // in order to support virtual hosting. ServerName is only set if the
391 // client is using SNI (see RFC 4366, Section 3.1).
394 // SupportedCurves lists the elliptic curves supported by the client.
395 // SupportedCurves is set only if the Supported Elliptic Curves
396 // Extension is being used (see RFC 4492, Section 5.1.1).
397 SupportedCurves []CurveID
399 // SupportedPoints lists the point formats supported by the client.
400 // SupportedPoints is set only if the Supported Point Formats Extension
401 // is being used (see RFC 4492, Section 5.1.2).
402 SupportedPoints []uint8
404 // SignatureSchemes lists the signature and hash schemes that the client
405 // is willing to verify. SignatureSchemes is set only if the Signature
406 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
407 SignatureSchemes []SignatureScheme
409 // SupportedProtos lists the application protocols supported by the client.
410 // SupportedProtos is set only if the Application-Layer Protocol
411 // Negotiation Extension is being used (see RFC 7301, Section 3.1).
413 // Servers can select a protocol by setting Config.NextProtos in a
414 // GetConfigForClient return value.
415 SupportedProtos []string
417 // SupportedVersions lists the TLS versions supported by the client.
418 // For TLS versions less than 1.3, this is extrapolated from the max
419 // version advertised by the client, so values other than the greatest
420 // might be rejected if used.
421 SupportedVersions []uint16
423 // Conn is the underlying net.Conn for the connection. Do not read
424 // from, or write to, this connection; that will cause the TLS
425 // connection to fail.
428 // config is embedded by the GetCertificate or GetConfigForClient caller,
429 // for use with SupportsCertificate.
432 // ctx is the context of the handshake that is in progress.
436 // Context returns the context of the handshake that is in progress.
437 // This context is a child of the context passed to HandshakeContext,
438 // if any, and is canceled when the handshake concludes.
439 func (c *ClientHelloInfo) Context() context.Context {
443 // CertificateRequestInfo contains information from a server's
444 // CertificateRequest message, which is used to demand a certificate and proof
445 // of control from a client.
446 type CertificateRequestInfo struct {
447 // AcceptableCAs contains zero or more, DER-encoded, X.501
448 // Distinguished Names. These are the names of root or intermediate CAs
449 // that the server wishes the returned certificate to be signed by. An
450 // empty slice indicates that the server has no preference.
451 AcceptableCAs [][]byte
453 // SignatureSchemes lists the signature schemes that the server is
454 // willing to verify.
455 SignatureSchemes []SignatureScheme
457 // Version is the TLS version that was negotiated for this connection.
460 // ctx is the context of the handshake that is in progress.
464 // Context returns the context of the handshake that is in progress.
465 // This context is a child of the context passed to HandshakeContext,
466 // if any, and is canceled when the handshake concludes.
467 func (c *CertificateRequestInfo) Context() context.Context {
471 // RenegotiationSupport enumerates the different levels of support for TLS
472 // renegotiation. TLS renegotiation is the act of performing subsequent
473 // handshakes on a connection after the first. This significantly complicates
474 // the state machine and has been the source of numerous, subtle security
475 // issues. Initiating a renegotiation is not supported, but support for
476 // accepting renegotiation requests may be enabled.
478 // Even when enabled, the server may not change its identity between handshakes
479 // (i.e. the leaf certificate must be the same). Additionally, concurrent
480 // handshake and application data flow is not permitted so renegotiation can
481 // only be used with protocols that synchronise with the renegotiation, such as
484 // Renegotiation is not defined in TLS 1.3.
485 type RenegotiationSupport int
488 // RenegotiateNever disables renegotiation.
489 RenegotiateNever RenegotiationSupport = iota
491 // RenegotiateOnceAsClient allows a remote server to request
492 // renegotiation once per connection.
493 RenegotiateOnceAsClient
495 // RenegotiateFreelyAsClient allows a remote server to repeatedly
496 // request renegotiation.
497 RenegotiateFreelyAsClient
500 // A Config structure is used to configure a TLS client or server.
501 // After one has been passed to a TLS function it must not be
502 // modified. A Config may be reused; the tls package will also not
505 // Rand provides the source of entropy for nonces and RSA blinding.
506 // If Rand is nil, TLS uses the cryptographic random reader in package
508 // The Reader must be safe for use by multiple goroutines.
511 // Time returns the current time as the number of seconds since the epoch.
512 // If Time is nil, TLS uses time.Now.
513 Time func() time.Time
515 // Certificates contains one or more certificate chains to present to the
516 // other side of the connection. The first certificate compatible with the
517 // peer's requirements is selected automatically.
519 // Server configurations must set one of Certificates, GetCertificate or
520 // GetConfigForClient. Clients doing client-authentication may set either
521 // Certificates or GetClientCertificate.
523 // Note: if there are multiple Certificates, and they don't have the
524 // optional field Leaf set, certificate selection will incur a significant
525 // per-handshake performance cost.
526 Certificates []Certificate
528 // NameToCertificate maps from a certificate name to an element of
529 // Certificates. Note that a certificate name can be of the form
530 // '*.example.com' and so doesn't have to be a domain name as such.
532 // Deprecated: NameToCertificate only allows associating a single
533 // certificate with a given name. Leave this field nil to let the library
534 // select the first compatible chain from Certificates.
535 NameToCertificate map[string]*Certificate
537 // GetCertificate returns a Certificate based on the given
538 // ClientHelloInfo. It will only be called if the client supplies SNI
539 // information or if Certificates is empty.
541 // If GetCertificate is nil or returns nil, then the certificate is
542 // retrieved from NameToCertificate. If NameToCertificate is nil, the
543 // best element of Certificates will be used.
545 // Once a Certificate is returned it should not be modified.
546 GetCertificate func(*ClientHelloInfo) (*Certificate, error)
548 // GetClientCertificate, if not nil, is called when a server requests a
549 // certificate from a client. If set, the contents of Certificates will
552 // If GetClientCertificate returns an error, the handshake will be
553 // aborted and that error will be returned. Otherwise
554 // GetClientCertificate must return a non-nil Certificate. If
555 // Certificate.Certificate is empty then no certificate will be sent to
556 // the server. If this is unacceptable to the server then it may abort
559 // GetClientCertificate may be called multiple times for the same
560 // connection if renegotiation occurs or if TLS 1.3 is in use.
562 // Once a Certificate is returned it should not be modified.
563 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
565 // GetConfigForClient, if not nil, is called after a ClientHello is
566 // received from a client. It may return a non-nil Config in order to
567 // change the Config that will be used to handle this connection. If
568 // the returned Config is nil, the original Config will be used. The
569 // Config returned by this callback may not be subsequently modified.
571 // If GetConfigForClient is nil, the Config passed to Server() will be
572 // used for all connections.
574 // If SessionTicketKey was explicitly set on the returned Config, or if
575 // SetSessionTicketKeys was called on the returned Config, those keys will
576 // be used. Otherwise, the original Config keys will be used (and possibly
577 // rotated if they are automatically managed).
578 GetConfigForClient func(*ClientHelloInfo) (*Config, error)
580 // VerifyPeerCertificate, if not nil, is called after normal
581 // certificate verification by either a TLS client or server. It
582 // receives the raw ASN.1 certificates provided by the peer and also
583 // any verified chains that normal processing found. If it returns a
584 // non-nil error, the handshake is aborted and that error results.
586 // If normal verification fails then the handshake will abort before
587 // considering this callback. If normal verification is disabled by
588 // setting InsecureSkipVerify, or (for a server) when ClientAuth is
589 // RequestClientCert or RequireAnyClientCert, then this callback will
590 // be considered but the verifiedChains argument will always be nil.
592 // verifiedChains and its contents should not be modified.
593 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
595 // VerifyConnection, if not nil, is called after normal certificate
596 // verification and after VerifyPeerCertificate by either a TLS client
597 // or server. If it returns a non-nil error, the handshake is aborted
598 // and that error results.
600 // If normal verification fails then the handshake will abort before
601 // considering this callback. This callback will run for all connections
602 // regardless of InsecureSkipVerify or ClientAuth settings.
603 VerifyConnection func(ConnectionState) error
605 // RootCAs defines the set of root certificate authorities
606 // that clients use when verifying server certificates.
607 // If RootCAs is nil, TLS uses the host's root CA set.
608 RootCAs *x509.CertPool
610 // NextProtos is a list of supported application level protocols, in
611 // order of preference. If both peers support ALPN, the selected
612 // protocol will be one from this list, and the connection will fail
613 // if there is no mutually supported protocol. If NextProtos is empty
614 // or the peer doesn't support ALPN, the connection will succeed and
615 // ConnectionState.NegotiatedProtocol will be empty.
618 // ServerName is used to verify the hostname on the returned
619 // certificates unless InsecureSkipVerify is given. It is also included
620 // in the client's handshake to support virtual hosting unless it is
624 // ClientAuth determines the server's policy for
625 // TLS Client Authentication. The default is NoClientCert.
626 ClientAuth ClientAuthType
628 // ClientCAs defines the set of root certificate authorities
629 // that servers use if required to verify a client certificate
630 // by the policy in ClientAuth.
631 ClientCAs *x509.CertPool
633 // InsecureSkipVerify controls whether a client verifies the server's
634 // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
635 // accepts any certificate presented by the server and any host name in that
636 // certificate. In this mode, TLS is susceptible to machine-in-the-middle
637 // attacks unless custom verification is used. This should be used only for
638 // testing or in combination with VerifyConnection or VerifyPeerCertificate.
639 InsecureSkipVerify bool
641 // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
642 // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
644 // If CipherSuites is nil, a safe default list is used. The default cipher
645 // suites might change over time.
646 CipherSuites []uint16
648 // PreferServerCipherSuites is a legacy field and has no effect.
650 // It used to control whether the server would follow the client's or the
651 // server's preference. Servers now select the best mutually supported
652 // cipher suite based on logic that takes into account inferred client
653 // hardware, server hardware, and security.
655 // Deprecated: PreferServerCipherSuites is ignored.
656 PreferServerCipherSuites bool
658 // SessionTicketsDisabled may be set to true to disable session ticket and
659 // PSK (resumption) support. Note that on clients, session ticket support is
660 // also disabled if ClientSessionCache is nil.
661 SessionTicketsDisabled bool
663 // SessionTicketKey is used by TLS servers to provide session resumption.
664 // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
665 // with random data before the first server handshake.
667 // Deprecated: if this field is left at zero, session ticket keys will be
668 // automatically rotated every day and dropped after seven days. For
669 // customizing the rotation schedule or synchronizing servers that are
670 // terminating connections for the same host, use SetSessionTicketKeys.
671 SessionTicketKey [32]byte
673 // ClientSessionCache is a cache of ClientSessionState entries for TLS
674 // session resumption. It is only used by clients.
675 ClientSessionCache ClientSessionCache
677 // UnwrapSession is called on the server to turn a ticket/identity
678 // previously produced by [WrapSession] into a usable session.
680 // UnwrapSession will usually either decrypt a session state in the ticket
681 // (for example with [Config.EncryptTicket]), or use the ticket as a handle
682 // to recover a previously stored state. It must use [ParseSessionState] to
683 // deserialize the session state.
685 // If UnwrapSession returns an error, the connection is terminated. If it
686 // returns (nil, nil), the session is ignored. crypto/tls may still choose
687 // not to resume the returned session.
688 UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
690 // WrapSession is called on the server to produce a session ticket/identity.
692 // WrapSession must serialize the session state with [SessionState.Bytes].
693 // It may then encrypt the serialized state (for example with
694 // [Config.DecryptTicket]) and use it as the ticket, or store the state and
695 // return a handle for it.
697 // If WrapSession returns an error, the connection is terminated.
699 // Warning: the return value will be exposed on the wire and to clients in
700 // plaintext. The application is in charge of encrypting and authenticating
701 // it (and rotating keys) or returning high-entropy identifiers. Failing to
702 // do so correctly can compromise current, previous, and future connections
703 // depending on the protocol version.
704 WrapSession func(ConnectionState, *SessionState) ([]byte, error)
706 // MinVersion contains the minimum TLS version that is acceptable.
708 // By default, TLS 1.2 is currently used as the minimum when acting as a
709 // client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
710 // supported by this package, both as a client and as a server.
712 // The client-side default can temporarily be reverted to TLS 1.0 by
713 // including the value "x509sha1=1" in the GODEBUG environment variable.
714 // Note that this option will be removed in Go 1.19 (but it will still be
715 // possible to set this field to VersionTLS10 explicitly).
718 // MaxVersion contains the maximum TLS version that is acceptable.
720 // By default, the maximum version supported by this package is used,
721 // which is currently TLS 1.3.
724 // CurvePreferences contains the elliptic curves that will be used in
725 // an ECDHE handshake, in preference order. If empty, the default will
726 // be used. The client will use the first preference as the type for
727 // its key share in TLS 1.3. This may change in the future.
728 CurvePreferences []CurveID
730 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
731 // When true, the largest possible TLS record size is always used. When
732 // false, the size of TLS records may be adjusted in an attempt to
734 DynamicRecordSizingDisabled bool
736 // Renegotiation controls what types of renegotiation are supported.
737 // The default, none, is correct for the vast majority of applications.
738 Renegotiation RenegotiationSupport
740 // KeyLogWriter optionally specifies a destination for TLS master secrets
741 // in NSS key log format that can be used to allow external programs
742 // such as Wireshark to decrypt TLS connections.
743 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
744 // Use of KeyLogWriter compromises security and should only be
745 // used for debugging.
746 KeyLogWriter io.Writer
748 // mutex protects sessionTicketKeys and autoSessionTicketKeys.
750 // sessionTicketKeys contains zero or more ticket keys. If set, it means
751 // the keys were set with SessionTicketKey or SetSessionTicketKeys. The
752 // first key is used for new tickets and any subsequent keys can be used to
753 // decrypt old tickets. The slice contents are not protected by the mutex
754 // and are immutable.
755 sessionTicketKeys []ticketKey
756 // autoSessionTicketKeys is like sessionTicketKeys but is owned by the
757 // auto-rotation logic. See Config.ticketKeys.
758 autoSessionTicketKeys []ticketKey
762 // ticketKeyLifetime is how long a ticket key remains valid and can be used to
763 // resume a client connection.
764 ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
766 // ticketKeyRotation is how often the server should rotate the session ticket key
767 // that is used for new tickets.
768 ticketKeyRotation = 24 * time.Hour
771 // ticketKey is the internal representation of a session ticket key.
772 type ticketKey struct {
775 // created is the time at which this ticket key was created. See Config.ticketKeys.
779 // ticketKeyFromBytes converts from the external representation of a session
780 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
781 // bytes and this function expands that into sufficient name and key material.
782 func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
783 hashed := sha512.Sum512(b[:])
784 // The first 16 bytes of the hash used to be exposed on the wire as a ticket
785 // prefix. They MUST NOT be used as a secret. In the future, it would make
786 // sense to use a proper KDF here, like HKDF with a fixed salt.
787 const legacyTicketKeyNameLen = 16
788 copy(key.aesKey[:], hashed[legacyTicketKeyNameLen:])
789 copy(key.hmacKey[:], hashed[legacyTicketKeyNameLen+len(key.aesKey):])
790 key.created = c.time()
794 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
795 // ticket, and the lifetime we set for all tickets we send.
796 const maxSessionTicketLifetime = 7 * 24 * time.Hour
798 // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
799 // being used concurrently by a TLS client or server.
800 func (c *Config) Clone() *Config {
805 defer c.mutex.RUnlock()
809 Certificates: c.Certificates,
810 NameToCertificate: c.NameToCertificate,
811 GetCertificate: c.GetCertificate,
812 GetClientCertificate: c.GetClientCertificate,
813 GetConfigForClient: c.GetConfigForClient,
814 VerifyPeerCertificate: c.VerifyPeerCertificate,
815 VerifyConnection: c.VerifyConnection,
817 NextProtos: c.NextProtos,
818 ServerName: c.ServerName,
819 ClientAuth: c.ClientAuth,
820 ClientCAs: c.ClientCAs,
821 InsecureSkipVerify: c.InsecureSkipVerify,
822 CipherSuites: c.CipherSuites,
823 PreferServerCipherSuites: c.PreferServerCipherSuites,
824 SessionTicketsDisabled: c.SessionTicketsDisabled,
825 SessionTicketKey: c.SessionTicketKey,
826 ClientSessionCache: c.ClientSessionCache,
827 UnwrapSession: c.UnwrapSession,
828 WrapSession: c.WrapSession,
829 MinVersion: c.MinVersion,
830 MaxVersion: c.MaxVersion,
831 CurvePreferences: c.CurvePreferences,
832 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
833 Renegotiation: c.Renegotiation,
834 KeyLogWriter: c.KeyLogWriter,
835 sessionTicketKeys: c.sessionTicketKeys,
836 autoSessionTicketKeys: c.autoSessionTicketKeys,
840 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
841 // randomized for backwards compatibility but is not in use.
842 var deprecatedSessionTicketKey = []byte("DEPRECATED")
844 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
845 // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
846 func (c *Config) initLegacySessionTicketKeyRLocked() {
847 // Don't write if SessionTicketKey is already defined as our deprecated string,
848 // or if it is defined by the user but sessionTicketKeys is already set.
849 if c.SessionTicketKey != [32]byte{} &&
850 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
854 // We need to write some data, so get an exclusive lock and re-check any conditions.
856 defer c.mutex.RLock()
858 defer c.mutex.Unlock()
859 if c.SessionTicketKey == [32]byte{} {
860 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
861 panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
863 // Write the deprecated prefix at the beginning so we know we created
864 // it. This key with the DEPRECATED prefix isn't used as an actual
865 // session ticket key, and is only randomized in case the application
866 // reuses it for some reason.
867 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
868 } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
869 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
874 // ticketKeys returns the ticketKeys for this connection.
875 // If configForClient has explicitly set keys, those will
876 // be returned. Otherwise, the keys on c will be used and
877 // may be rotated if auto-managed.
878 // During rotation, any expired session ticket keys are deleted from
879 // c.sessionTicketKeys. If the session ticket key that is currently
880 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
881 // is not fresh, then a new session ticket key will be
882 // created and prepended to c.sessionTicketKeys.
883 func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
884 // If the ConfigForClient callback returned a Config with explicitly set
885 // keys, use those, otherwise just use the original Config.
886 if configForClient != nil {
887 configForClient.mutex.RLock()
888 if configForClient.SessionTicketsDisabled {
891 configForClient.initLegacySessionTicketKeyRLocked()
892 if len(configForClient.sessionTicketKeys) != 0 {
893 ret := configForClient.sessionTicketKeys
894 configForClient.mutex.RUnlock()
897 configForClient.mutex.RUnlock()
901 defer c.mutex.RUnlock()
902 if c.SessionTicketsDisabled {
905 c.initLegacySessionTicketKeyRLocked()
906 if len(c.sessionTicketKeys) != 0 {
907 return c.sessionTicketKeys
909 // Fast path for the common case where the key is fresh enough.
910 if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
911 return c.autoSessionTicketKeys
914 // autoSessionTicketKeys are managed by auto-rotation.
916 defer c.mutex.RLock()
918 defer c.mutex.Unlock()
919 // Re-check the condition in case it changed since obtaining the new lock.
920 if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
922 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
923 panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
925 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
926 valid = append(valid, c.ticketKeyFromBytes(newKey))
927 for _, k := range c.autoSessionTicketKeys {
928 // While rotating the current key, also remove any expired ones.
929 if c.time().Sub(k.created) < ticketKeyLifetime {
930 valid = append(valid, k)
933 c.autoSessionTicketKeys = valid
935 return c.autoSessionTicketKeys
938 // SetSessionTicketKeys updates the session ticket keys for a server.
940 // The first key will be used when creating new tickets, while all keys can be
941 // used for decrypting tickets. It is safe to call this function while the
942 // server is running in order to rotate the session ticket keys. The function
943 // will panic if keys is empty.
945 // Calling this function will turn off automatic session ticket key rotation.
947 // If multiple servers are terminating connections for the same host they should
948 // all have the same session ticket keys. If the session ticket keys leaks,
949 // previously recorded and future TLS connections using those keys might be
951 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
953 panic("tls: keys must have at least one key")
956 newKeys := make([]ticketKey, len(keys))
957 for i, bytes := range keys {
958 newKeys[i] = c.ticketKeyFromBytes(bytes)
962 c.sessionTicketKeys = newKeys
966 func (c *Config) rand() io.Reader {
974 func (c *Config) time() time.Time {
982 func (c *Config) cipherSuites() []uint16 {
984 return fipsCipherSuites(c)
986 if c.CipherSuites != nil {
987 return c.CipherSuites
989 return defaultCipherSuites
992 var supportedVersions = []uint16{
999 // roleClient and roleServer are meant to call supportedVersions and parents
1000 // with more readability at the callsite.
1001 const roleClient = true
1002 const roleServer = false
1004 func (c *Config) supportedVersions(isClient bool) []uint16 {
1005 versions := make([]uint16, 0, len(supportedVersions))
1006 for _, v := range supportedVersions {
1007 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
1010 if (c == nil || c.MinVersion == 0) &&
1011 isClient && v < VersionTLS12 {
1014 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
1017 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
1020 versions = append(versions, v)
1025 func (c *Config) maxSupportedVersion(isClient bool) uint16 {
1026 supportedVersions := c.supportedVersions(isClient)
1027 if len(supportedVersions) == 0 {
1030 return supportedVersions[0]
1033 // supportedVersionsFromMax returns a list of supported versions derived from a
1034 // legacy maximum version value. Note that only versions supported by this
1035 // library are returned. Any newer peer will use supportedVersions anyway.
1036 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
1037 versions := make([]uint16, 0, len(supportedVersions))
1038 for _, v := range supportedVersions {
1042 versions = append(versions, v)
1047 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
1049 func (c *Config) curvePreferences() []CurveID {
1051 return fipsCurvePreferences(c)
1053 if c == nil || len(c.CurvePreferences) == 0 {
1054 return defaultCurvePreferences
1056 return c.CurvePreferences
1059 func (c *Config) supportsCurve(curve CurveID) bool {
1060 for _, cc := range c.curvePreferences() {
1068 // mutualVersion returns the protocol version to use given the advertised
1069 // versions of the peer. Priority is given to the peer preference order.
1070 func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
1071 supportedVersions := c.supportedVersions(isClient)
1072 for _, peerVersion := range peerVersions {
1073 for _, v := range supportedVersions {
1074 if v == peerVersion {
1082 var errNoCertificates = errors.New("tls: no certificates configured")
1084 // getCertificate returns the best certificate for the given ClientHelloInfo,
1085 // defaulting to the first element of c.Certificates.
1086 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1087 if c.GetCertificate != nil &&
1088 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1089 cert, err := c.GetCertificate(clientHello)
1090 if cert != nil || err != nil {
1095 if len(c.Certificates) == 0 {
1096 return nil, errNoCertificates
1099 if len(c.Certificates) == 1 {
1100 // There's only one choice, so no point doing any work.
1101 return &c.Certificates[0], nil
1104 if c.NameToCertificate != nil {
1105 name := strings.ToLower(clientHello.ServerName)
1106 if cert, ok := c.NameToCertificate[name]; ok {
1110 labels := strings.Split(name, ".")
1112 wildcardName := strings.Join(labels, ".")
1113 if cert, ok := c.NameToCertificate[wildcardName]; ok {
1119 for _, cert := range c.Certificates {
1120 if err := clientHello.SupportsCertificate(&cert); err == nil {
1125 // If nothing matches, return the first certificate.
1126 return &c.Certificates[0], nil
1129 // SupportsCertificate returns nil if the provided certificate is supported by
1130 // the client that sent the ClientHello. Otherwise, it returns an error
1131 // describing the reason for the incompatibility.
1133 // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
1134 // callback, this method will take into account the associated Config. Note that
1135 // if GetConfigForClient returns a different Config, the change can't be
1136 // accounted for by this method.
1138 // This function will call x509.ParseCertificate unless c.Leaf is set, which can
1139 // incur a significant performance cost.
1140 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1141 // Note we don't currently support certificate_authorities nor
1142 // signature_algorithms_cert, and don't check the algorithms of the
1143 // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1144 // Section 4.4.2.2).
1146 config := chi.config
1150 vers, ok := config.mutualVersion(roleServer, chi.SupportedVersions)
1152 return errors.New("no mutually supported protocol versions")
1155 // If the client specified the name they are trying to connect to, the
1156 // certificate needs to be valid for it.
1157 if chi.ServerName != "" {
1158 x509Cert, err := c.leaf()
1160 return fmt.Errorf("failed to parse certificate: %w", err)
1162 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1163 return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1167 // supportsRSAFallback returns nil if the certificate and connection support
1168 // the static RSA key exchange, and unsupported otherwise. The logic for
1169 // supporting static RSA is completely disjoint from the logic for
1170 // supporting signed key exchanges, so we just check it as a fallback.
1171 supportsRSAFallback := func(unsupported error) error {
1172 // TLS 1.3 dropped support for the static RSA key exchange.
1173 if vers == VersionTLS13 {
1176 // The static RSA key exchange works by decrypting a challenge with the
1177 // RSA private key, not by signing, so check the PrivateKey implements
1178 // crypto.Decrypter, like *rsa.PrivateKey does.
1179 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1180 if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1186 // Finally, there needs to be a mutual cipher suite that uses the static
1187 // RSA key exchange instead of ECDHE.
1188 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1189 if c.flags&suiteECDHE != 0 {
1192 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1197 if rsaCipherSuite == nil {
1203 // If the client sent the signature_algorithms extension, ensure it supports
1204 // schemes we can use with this certificate and TLS version.
1205 if len(chi.SignatureSchemes) > 0 {
1206 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1207 return supportsRSAFallback(err)
1211 // In TLS 1.3 we are done because supported_groups is only relevant to the
1212 // ECDHE computation, point format negotiation is removed, cipher suites are
1213 // only relevant to the AEAD choice, and static RSA does not exist.
1214 if vers == VersionTLS13 {
1218 // The only signed key exchange we support is ECDHE.
1219 if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
1220 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1223 var ecdsaCipherSuite bool
1224 if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1225 switch pub := priv.Public().(type) {
1226 case *ecdsa.PublicKey:
1229 case elliptic.P256():
1231 case elliptic.P384():
1233 case elliptic.P521():
1236 return supportsRSAFallback(unsupportedCertificateError(c))
1239 for _, c := range chi.SupportedCurves {
1240 if c == curve && config.supportsCurve(c) {
1246 return errors.New("client doesn't support certificate curve")
1248 ecdsaCipherSuite = true
1249 case ed25519.PublicKey:
1250 if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1251 return errors.New("connection doesn't support Ed25519")
1253 ecdsaCipherSuite = true
1254 case *rsa.PublicKey:
1256 return supportsRSAFallback(unsupportedCertificateError(c))
1259 return supportsRSAFallback(unsupportedCertificateError(c))
1262 // Make sure that there is a mutually supported cipher suite that works with
1263 // this certificate. Cipher suite selection will then apply the logic in
1264 // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1265 cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1266 if c.flags&suiteECDHE == 0 {
1269 if c.flags&suiteECSign != 0 {
1270 if !ecdsaCipherSuite {
1274 if ecdsaCipherSuite {
1278 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1283 if cipherSuite == nil {
1284 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1290 // SupportsCertificate returns nil if the provided certificate is supported by
1291 // the server that sent the CertificateRequest. Otherwise, it returns an error
1292 // describing the reason for the incompatibility.
1293 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1294 if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1298 if len(cri.AcceptableCAs) == 0 {
1302 for j, cert := range c.Certificate {
1304 // Parse the certificate if this isn't the leaf node, or if
1305 // chain.Leaf was nil.
1306 if j != 0 || x509Cert == nil {
1308 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1309 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1313 for _, ca := range cri.AcceptableCAs {
1314 if bytes.Equal(x509Cert.RawIssuer, ca) {
1319 return errors.New("chain is not signed by an acceptable CA")
1322 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1323 // from the CommonName and SubjectAlternateName fields of each of the leaf
1326 // Deprecated: NameToCertificate only allows associating a single certificate
1327 // with a given name. Leave that field nil to let the library select the first
1328 // compatible chain from Certificates.
1329 func (c *Config) BuildNameToCertificate() {
1330 c.NameToCertificate = make(map[string]*Certificate)
1331 for i := range c.Certificates {
1332 cert := &c.Certificates[i]
1333 x509Cert, err := cert.leaf()
1337 // If SANs are *not* present, some clients will consider the certificate
1338 // valid for the name in the Common Name.
1339 if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
1340 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1342 for _, san := range x509Cert.DNSNames {
1343 c.NameToCertificate[san] = cert
1349 keyLogLabelTLS12 = "CLIENT_RANDOM"
1350 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1351 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1352 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
1353 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
1356 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1357 if c.KeyLogWriter == nil {
1361 logLine := fmt.Appendf(nil, "%s %x %x\n", label, clientRandom, secret)
1364 _, err := c.KeyLogWriter.Write(logLine)
1365 writerMutex.Unlock()
1370 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1371 // and is only for debugging, so a global mutex saves space.
1372 var writerMutex sync.Mutex
1374 // A Certificate is a chain of one or more certificates, leaf first.
1375 type Certificate struct {
1376 Certificate [][]byte
1377 // PrivateKey contains the private key corresponding to the public key in
1378 // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1379 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1380 // an RSA PublicKey.
1381 PrivateKey crypto.PrivateKey
1382 // SupportedSignatureAlgorithms is an optional list restricting what
1383 // signature algorithms the PrivateKey can be used for.
1384 SupportedSignatureAlgorithms []SignatureScheme
1385 // OCSPStaple contains an optional OCSP response which will be served
1386 // to clients that request it.
1388 // SignedCertificateTimestamps contains an optional list of Signed
1389 // Certificate Timestamps which will be served to clients that request it.
1390 SignedCertificateTimestamps [][]byte
1391 // Leaf is the parsed form of the leaf certificate, which may be initialized
1392 // using x509.ParseCertificate to reduce per-handshake processing. If nil,
1393 // the leaf certificate will be parsed as needed.
1394 Leaf *x509.Certificate
1397 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1398 // the corresponding c.Certificate[0].
1399 func (c *Certificate) leaf() (*x509.Certificate, error) {
1403 return x509.ParseCertificate(c.Certificate[0])
1406 type handshakeMessage interface {
1407 marshal() ([]byte, error)
1408 unmarshal([]byte) bool
1411 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1412 // caching strategy.
1413 type lruSessionCache struct {
1416 m map[string]*list.Element
1421 type lruSessionCacheEntry struct {
1423 state *ClientSessionState
1426 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1427 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1429 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1430 const defaultSessionCacheCapacity = 64
1433 capacity = defaultSessionCacheCapacity
1435 return &lruSessionCache{
1436 m: make(map[string]*list.Element),
1442 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1443 // corresponding to sessionKey is removed from the cache instead.
1444 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1448 if elem, ok := c.m[sessionKey]; ok {
1451 delete(c.m, sessionKey)
1453 entry := elem.Value.(*lruSessionCacheEntry)
1455 c.q.MoveToFront(elem)
1460 if c.q.Len() < c.capacity {
1461 entry := &lruSessionCacheEntry{sessionKey, cs}
1462 c.m[sessionKey] = c.q.PushFront(entry)
1467 entry := elem.Value.(*lruSessionCacheEntry)
1468 delete(c.m, entry.sessionKey)
1469 entry.sessionKey = sessionKey
1471 c.q.MoveToFront(elem)
1472 c.m[sessionKey] = elem
1475 // Get returns the ClientSessionState value associated with a given key. It
1476 // returns (nil, false) if no value is found.
1477 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1481 if elem, ok := c.m[sessionKey]; ok {
1482 c.q.MoveToFront(elem)
1483 return elem.Value.(*lruSessionCacheEntry).state, true
1488 var emptyConfig Config
1490 func defaultConfig() *Config {
1494 func unexpectedMessageError(wanted, got any) error {
1495 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1498 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1499 for _, s := range supportedSignatureAlgorithms {
1507 // CertificateVerificationError is returned when certificate verification fails during the handshake.
1508 type CertificateVerificationError struct {
1509 // UnverifiedCertificates and its contents should not be modified.
1510 UnverifiedCertificates []*x509.Certificate
1514 func (e *CertificateVerificationError) Error() string {
1515 return fmt.Sprintf("tls: failed to verify certificate: %s", e.Err)
1518 func (e *CertificateVerificationError) Unwrap() error {