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.
4
5package tls
6
7import (
8	"bytes"
9	"container/list"
10	"context"
11	"crypto"
12	"crypto/ecdsa"
13	"crypto/ed25519"
14	"crypto/elliptic"
15	"crypto/rand"
16	"crypto/rsa"
17	"crypto/sha512"
18	"crypto/x509"
19	"errors"
20	"fmt"
21	"internal/godebug"
22	"io"
23	"net"
24	"slices"
25	"strings"
26	"sync"
27	"time"
28	_ "unsafe" // for linkname
29)
30
31const (
32	VersionTLS10 = 0x0301
33	VersionTLS11 = 0x0302
34	VersionTLS12 = 0x0303
35	VersionTLS13 = 0x0304
36
37	// Deprecated: SSLv3 is cryptographically broken, and is no longer
38	// supported by this package. See golang.org/issue/32716.
39	VersionSSL30 = 0x0300
40)
41
42// VersionName returns the name for the provided TLS version number
43// (e.g. "TLS 1.3"), or a fallback representation of the value if the
44// version is not implemented by this package.
45func VersionName(version uint16) string {
46	switch version {
47	case VersionSSL30:
48		return "SSLv3"
49	case VersionTLS10:
50		return "TLS 1.0"
51	case VersionTLS11:
52		return "TLS 1.1"
53	case VersionTLS12:
54		return "TLS 1.2"
55	case VersionTLS13:
56		return "TLS 1.3"
57	default:
58		return fmt.Sprintf("0x%04X", version)
59	}
60}
61
62const (
63	maxPlaintext               = 16384        // maximum plaintext payload length
64	maxCiphertext              = 16384 + 2048 // maximum ciphertext payload length
65	maxCiphertextTLS13         = 16384 + 256  // maximum ciphertext length in TLS 1.3
66	recordHeaderLen            = 5            // record header length
67	maxHandshake               = 65536        // maximum handshake we support (protocol max is 16 MB)
68	maxHandshakeCertificateMsg = 262144       // maximum certificate message size (256 KiB)
69	maxUselessRecords          = 16           // maximum number of consecutive non-advancing records
70)
71
72// TLS record types.
73type recordType uint8
74
75const (
76	recordTypeChangeCipherSpec recordType = 20
77	recordTypeAlert            recordType = 21
78	recordTypeHandshake        recordType = 22
79	recordTypeApplicationData  recordType = 23
80)
81
82// TLS handshake message types.
83const (
84	typeHelloRequest        uint8 = 0
85	typeClientHello         uint8 = 1
86	typeServerHello         uint8 = 2
87	typeNewSessionTicket    uint8 = 4
88	typeEndOfEarlyData      uint8 = 5
89	typeEncryptedExtensions uint8 = 8
90	typeCertificate         uint8 = 11
91	typeServerKeyExchange   uint8 = 12
92	typeCertificateRequest  uint8 = 13
93	typeServerHelloDone     uint8 = 14
94	typeCertificateVerify   uint8 = 15
95	typeClientKeyExchange   uint8 = 16
96	typeFinished            uint8 = 20
97	typeCertificateStatus   uint8 = 22
98	typeKeyUpdate           uint8 = 24
99	typeMessageHash         uint8 = 254 // synthetic message
100)
101
102// TLS compression types.
103const (
104	compressionNone uint8 = 0
105)
106
107// TLS extension numbers
108const (
109	extensionServerName              uint16 = 0
110	extensionStatusRequest           uint16 = 5
111	extensionSupportedCurves         uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
112	extensionSupportedPoints         uint16 = 11
113	extensionSignatureAlgorithms     uint16 = 13
114	extensionALPN                    uint16 = 16
115	extensionSCT                     uint16 = 18
116	extensionExtendedMasterSecret    uint16 = 23
117	extensionSessionTicket           uint16 = 35
118	extensionPreSharedKey            uint16 = 41
119	extensionEarlyData               uint16 = 42
120	extensionSupportedVersions       uint16 = 43
121	extensionCookie                  uint16 = 44
122	extensionPSKModes                uint16 = 45
123	extensionCertificateAuthorities  uint16 = 47
124	extensionSignatureAlgorithmsCert uint16 = 50
125	extensionKeyShare                uint16 = 51
126	extensionQUICTransportParameters uint16 = 57
127	extensionRenegotiationInfo       uint16 = 0xff01
128	extensionECHOuterExtensions      uint16 = 0xfd00
129	extensionEncryptedClientHello    uint16 = 0xfe0d
130)
131
132// TLS signaling cipher suite values
133const (
134	scsvRenegotiation uint16 = 0x00ff
135)
136
137// CurveID is the type of a TLS identifier for a key exchange mechanism. See
138// https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
139//
140// In TLS 1.2, this registry used to support only elliptic curves. In TLS 1.3,
141// it was extended to other groups and renamed NamedGroup. See RFC 8446, Section
142// 4.2.7. It was then also extended to other mechanisms, such as hybrid
143// post-quantum KEMs.
144type CurveID uint16
145
146const (
147	CurveP256 CurveID = 23
148	CurveP384 CurveID = 24
149	CurveP521 CurveID = 25
150	X25519    CurveID = 29
151
152	// Experimental codepoint for X25519Kyber768Draft00, specified in
153	// draft-tls-westerbaan-xyber768d00-03. Not exported, as support might be
154	// removed in the future.
155	x25519Kyber768Draft00 CurveID = 0x6399 // X25519Kyber768Draft00
156)
157
158// TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
159type keyShare struct {
160	group CurveID
161	data  []byte
162}
163
164// TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
165const (
166	pskModePlain uint8 = 0
167	pskModeDHE   uint8 = 1
168)
169
170// TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
171// session. See RFC 8446, Section 4.2.11.
172type pskIdentity struct {
173	label               []byte
174	obfuscatedTicketAge uint32
175}
176
177// TLS Elliptic Curve Point Formats
178// https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
179const (
180	pointFormatUncompressed uint8 = 0
181)
182
183// TLS CertificateStatusType (RFC 3546)
184const (
185	statusTypeOCSP uint8 = 1
186)
187
188// Certificate types (for certificateRequestMsg)
189const (
190	certTypeRSASign   = 1
191	certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
192)
193
194// Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
195// TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
196const (
197	signaturePKCS1v15 uint8 = iota + 225
198	signatureRSAPSS
199	signatureECDSA
200	signatureEd25519
201)
202
203// directSigning is a standard Hash value that signals that no pre-hashing
204// should be performed, and that the input should be signed directly. It is the
205// hash function associated with the Ed25519 signature scheme.
206var directSigning crypto.Hash = 0
207
208// helloRetryRequestRandom is set as the Random value of a ServerHello
209// to signal that the message is actually a HelloRetryRequest.
210var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
211	0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
212	0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
213	0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
214	0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
215}
216
217const (
218	// downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
219	// random as a downgrade protection if the server would be capable of
220	// negotiating a higher version. See RFC 8446, Section 4.1.3.
221	downgradeCanaryTLS12 = "DOWNGRD\x01"
222	downgradeCanaryTLS11 = "DOWNGRD\x00"
223)
224
225// testingOnlyForceDowngradeCanary is set in tests to force the server side to
226// include downgrade canaries even if it's using its highers supported version.
227var testingOnlyForceDowngradeCanary bool
228
229// ConnectionState records basic TLS details about the connection.
230type ConnectionState struct {
231	// Version is the TLS version used by the connection (e.g. VersionTLS12).
232	Version uint16
233
234	// HandshakeComplete is true if the handshake has concluded.
235	HandshakeComplete bool
236
237	// DidResume is true if this connection was successfully resumed from a
238	// previous session with a session ticket or similar mechanism.
239	DidResume bool
240
241	// CipherSuite is the cipher suite negotiated for the connection (e.g.
242	// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
243	CipherSuite uint16
244
245	// NegotiatedProtocol is the application protocol negotiated with ALPN.
246	NegotiatedProtocol string
247
248	// NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
249	//
250	// Deprecated: this value is always true.
251	NegotiatedProtocolIsMutual bool
252
253	// ServerName is the value of the Server Name Indication extension sent by
254	// the client. It's available both on the server and on the client side.
255	ServerName string
256
257	// PeerCertificates are the parsed certificates sent by the peer, in the
258	// order in which they were sent. The first element is the leaf certificate
259	// that the connection is verified against.
260	//
261	// On the client side, it can't be empty. On the server side, it can be
262	// empty if Config.ClientAuth is not RequireAnyClientCert or
263	// RequireAndVerifyClientCert.
264	//
265	// PeerCertificates and its contents should not be modified.
266	PeerCertificates []*x509.Certificate
267
268	// VerifiedChains is a list of one or more chains where the first element is
269	// PeerCertificates[0] and the last element is from Config.RootCAs (on the
270	// client side) or Config.ClientCAs (on the server side).
271	//
272	// On the client side, it's set if Config.InsecureSkipVerify is false. On
273	// the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
274	// (and the peer provided a certificate) or RequireAndVerifyClientCert.
275	//
276	// VerifiedChains and its contents should not be modified.
277	VerifiedChains [][]*x509.Certificate
278
279	// SignedCertificateTimestamps is a list of SCTs provided by the peer
280	// through the TLS handshake for the leaf certificate, if any.
281	SignedCertificateTimestamps [][]byte
282
283	// OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
284	// response provided by the peer for the leaf certificate, if any.
285	OCSPResponse []byte
286
287	// TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
288	// Section 3). This value will be nil for TLS 1.3 connections and for
289	// resumed connections that don't support Extended Master Secret (RFC 7627).
290	TLSUnique []byte
291
292	// ECHAccepted indicates if Encrypted Client Hello was offered by the client
293	// and accepted by the server. Currently, ECH is supported only on the
294	// client side.
295	ECHAccepted bool
296
297	// ekm is a closure exposed via ExportKeyingMaterial.
298	ekm func(label string, context []byte, length int) ([]byte, error)
299
300	// testingOnlyDidHRR is true if a HelloRetryRequest was sent/received.
301	testingOnlyDidHRR bool
302
303	// testingOnlyCurveID is the selected CurveID, or zero if an RSA exchanges
304	// is performed.
305	testingOnlyCurveID CurveID
306}
307
308// ExportKeyingMaterial returns length bytes of exported key material in a new
309// slice as defined in RFC 5705. If context is nil, it is not used as part of
310// the seed. If the connection was set to allow renegotiation via
311// Config.Renegotiation, or if the connections supports neither TLS 1.3 nor
312// Extended Master Secret, this function will return an error.
313//
314// Exporting key material without Extended Master Secret or TLS 1.3 was disabled
315// in Go 1.22 due to security issues (see the Security Considerations sections
316// of RFC 5705 and RFC 7627), but can be re-enabled with the GODEBUG setting
317// tlsunsafeekm=1.
318func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
319	return cs.ekm(label, context, length)
320}
321
322// ClientAuthType declares the policy the server will follow for
323// TLS Client Authentication.
324type ClientAuthType int
325
326const (
327	// NoClientCert indicates that no client certificate should be requested
328	// during the handshake, and if any certificates are sent they will not
329	// be verified.
330	NoClientCert ClientAuthType = iota
331	// RequestClientCert indicates that a client certificate should be requested
332	// during the handshake, but does not require that the client send any
333	// certificates.
334	RequestClientCert
335	// RequireAnyClientCert indicates that a client certificate should be requested
336	// during the handshake, and that at least one certificate is required to be
337	// sent by the client, but that certificate is not required to be valid.
338	RequireAnyClientCert
339	// VerifyClientCertIfGiven indicates that a client certificate should be requested
340	// during the handshake, but does not require that the client sends a
341	// certificate. If the client does send a certificate it is required to be
342	// valid.
343	VerifyClientCertIfGiven
344	// RequireAndVerifyClientCert indicates that a client certificate should be requested
345	// during the handshake, and that at least one valid certificate is required
346	// to be sent by the client.
347	RequireAndVerifyClientCert
348)
349
350// requiresClientCert reports whether the ClientAuthType requires a client
351// certificate to be provided.
352func requiresClientCert(c ClientAuthType) bool {
353	switch c {
354	case RequireAnyClientCert, RequireAndVerifyClientCert:
355		return true
356	default:
357		return false
358	}
359}
360
361// ClientSessionCache is a cache of ClientSessionState objects that can be used
362// by a client to resume a TLS session with a given server. ClientSessionCache
363// implementations should expect to be called concurrently from different
364// goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
365// SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
366// are supported via this interface.
367type ClientSessionCache interface {
368	// Get searches for a ClientSessionState associated with the given key.
369	// On return, ok is true if one was found.
370	Get(sessionKey string) (session *ClientSessionState, ok bool)
371
372	// Put adds the ClientSessionState to the cache with the given key. It might
373	// get called multiple times in a connection if a TLS 1.3 server provides
374	// more than one session ticket. If called with a nil *ClientSessionState,
375	// it should remove the cache entry.
376	Put(sessionKey string, cs *ClientSessionState)
377}
378
379//go:generate stringer -linecomment -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
380
381// SignatureScheme identifies a signature algorithm supported by TLS. See
382// RFC 8446, Section 4.2.3.
383type SignatureScheme uint16
384
385const (
386	// RSASSA-PKCS1-v1_5 algorithms.
387	PKCS1WithSHA256 SignatureScheme = 0x0401
388	PKCS1WithSHA384 SignatureScheme = 0x0501
389	PKCS1WithSHA512 SignatureScheme = 0x0601
390
391	// RSASSA-PSS algorithms with public key OID rsaEncryption.
392	PSSWithSHA256 SignatureScheme = 0x0804
393	PSSWithSHA384 SignatureScheme = 0x0805
394	PSSWithSHA512 SignatureScheme = 0x0806
395
396	// ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
397	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
398	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
399	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
400
401	// EdDSA algorithms.
402	Ed25519 SignatureScheme = 0x0807
403
404	// Legacy signature and hash algorithms for TLS 1.2.
405	PKCS1WithSHA1 SignatureScheme = 0x0201
406	ECDSAWithSHA1 SignatureScheme = 0x0203
407)
408
409// ClientHelloInfo contains information from a ClientHello message in order to
410// guide application logic in the GetCertificate and GetConfigForClient callbacks.
411type ClientHelloInfo struct {
412	// CipherSuites lists the CipherSuites supported by the client (e.g.
413	// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
414	CipherSuites []uint16
415
416	// ServerName indicates the name of the server requested by the client
417	// in order to support virtual hosting. ServerName is only set if the
418	// client is using SNI (see RFC 4366, Section 3.1).
419	ServerName string
420
421	// SupportedCurves lists the elliptic curves supported by the client.
422	// SupportedCurves is set only if the Supported Elliptic Curves
423	// Extension is being used (see RFC 4492, Section 5.1.1).
424	SupportedCurves []CurveID
425
426	// SupportedPoints lists the point formats supported by the client.
427	// SupportedPoints is set only if the Supported Point Formats Extension
428	// is being used (see RFC 4492, Section 5.1.2).
429	SupportedPoints []uint8
430
431	// SignatureSchemes lists the signature and hash schemes that the client
432	// is willing to verify. SignatureSchemes is set only if the Signature
433	// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
434	SignatureSchemes []SignatureScheme
435
436	// SupportedProtos lists the application protocols supported by the client.
437	// SupportedProtos is set only if the Application-Layer Protocol
438	// Negotiation Extension is being used (see RFC 7301, Section 3.1).
439	//
440	// Servers can select a protocol by setting Config.NextProtos in a
441	// GetConfigForClient return value.
442	SupportedProtos []string
443
444	// SupportedVersions lists the TLS versions supported by the client.
445	// For TLS versions less than 1.3, this is extrapolated from the max
446	// version advertised by the client, so values other than the greatest
447	// might be rejected if used.
448	SupportedVersions []uint16
449
450	// Conn is the underlying net.Conn for the connection. Do not read
451	// from, or write to, this connection; that will cause the TLS
452	// connection to fail.
453	Conn net.Conn
454
455	// config is embedded by the GetCertificate or GetConfigForClient caller,
456	// for use with SupportsCertificate.
457	config *Config
458
459	// ctx is the context of the handshake that is in progress.
460	ctx context.Context
461}
462
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.
466func (c *ClientHelloInfo) Context() context.Context {
467	return c.ctx
468}
469
470// CertificateRequestInfo contains information from a server's
471// CertificateRequest message, which is used to demand a certificate and proof
472// of control from a client.
473type CertificateRequestInfo struct {
474	// AcceptableCAs contains zero or more, DER-encoded, X.501
475	// Distinguished Names. These are the names of root or intermediate CAs
476	// that the server wishes the returned certificate to be signed by. An
477	// empty slice indicates that the server has no preference.
478	AcceptableCAs [][]byte
479
480	// SignatureSchemes lists the signature schemes that the server is
481	// willing to verify.
482	SignatureSchemes []SignatureScheme
483
484	// Version is the TLS version that was negotiated for this connection.
485	Version uint16
486
487	// ctx is the context of the handshake that is in progress.
488	ctx context.Context
489}
490
491// Context returns the context of the handshake that is in progress.
492// This context is a child of the context passed to HandshakeContext,
493// if any, and is canceled when the handshake concludes.
494func (c *CertificateRequestInfo) Context() context.Context {
495	return c.ctx
496}
497
498// RenegotiationSupport enumerates the different levels of support for TLS
499// renegotiation. TLS renegotiation is the act of performing subsequent
500// handshakes on a connection after the first. This significantly complicates
501// the state machine and has been the source of numerous, subtle security
502// issues. Initiating a renegotiation is not supported, but support for
503// accepting renegotiation requests may be enabled.
504//
505// Even when enabled, the server may not change its identity between handshakes
506// (i.e. the leaf certificate must be the same). Additionally, concurrent
507// handshake and application data flow is not permitted so renegotiation can
508// only be used with protocols that synchronise with the renegotiation, such as
509// HTTPS.
510//
511// Renegotiation is not defined in TLS 1.3.
512type RenegotiationSupport int
513
514const (
515	// RenegotiateNever disables renegotiation.
516	RenegotiateNever RenegotiationSupport = iota
517
518	// RenegotiateOnceAsClient allows a remote server to request
519	// renegotiation once per connection.
520	RenegotiateOnceAsClient
521
522	// RenegotiateFreelyAsClient allows a remote server to repeatedly
523	// request renegotiation.
524	RenegotiateFreelyAsClient
525)
526
527// A Config structure is used to configure a TLS client or server.
528// After one has been passed to a TLS function it must not be
529// modified. A Config may be reused; the tls package will also not
530// modify it.
531type Config struct {
532	// Rand provides the source of entropy for nonces and RSA blinding.
533	// If Rand is nil, TLS uses the cryptographic random reader in package
534	// crypto/rand.
535	// The Reader must be safe for use by multiple goroutines.
536	Rand io.Reader
537
538	// Time returns the current time as the number of seconds since the epoch.
539	// If Time is nil, TLS uses time.Now.
540	Time func() time.Time
541
542	// Certificates contains one or more certificate chains to present to the
543	// other side of the connection. The first certificate compatible with the
544	// peer's requirements is selected automatically.
545	//
546	// Server configurations must set one of Certificates, GetCertificate or
547	// GetConfigForClient. Clients doing client-authentication may set either
548	// Certificates or GetClientCertificate.
549	//
550	// Note: if there are multiple Certificates, and they don't have the
551	// optional field Leaf set, certificate selection will incur a significant
552	// per-handshake performance cost.
553	Certificates []Certificate
554
555	// NameToCertificate maps from a certificate name to an element of
556	// Certificates. Note that a certificate name can be of the form
557	// '*.example.com' and so doesn't have to be a domain name as such.
558	//
559	// Deprecated: NameToCertificate only allows associating a single
560	// certificate with a given name. Leave this field nil to let the library
561	// select the first compatible chain from Certificates.
562	NameToCertificate map[string]*Certificate
563
564	// GetCertificate returns a Certificate based on the given
565	// ClientHelloInfo. It will only be called if the client supplies SNI
566	// information or if Certificates is empty.
567	//
568	// If GetCertificate is nil or returns nil, then the certificate is
569	// retrieved from NameToCertificate. If NameToCertificate is nil, the
570	// best element of Certificates will be used.
571	//
572	// Once a Certificate is returned it should not be modified.
573	GetCertificate func(*ClientHelloInfo) (*Certificate, error)
574
575	// GetClientCertificate, if not nil, is called when a server requests a
576	// certificate from a client. If set, the contents of Certificates will
577	// be ignored.
578	//
579	// If GetClientCertificate returns an error, the handshake will be
580	// aborted and that error will be returned. Otherwise
581	// GetClientCertificate must return a non-nil Certificate. If
582	// Certificate.Certificate is empty then no certificate will be sent to
583	// the server. If this is unacceptable to the server then it may abort
584	// the handshake.
585	//
586	// GetClientCertificate may be called multiple times for the same
587	// connection if renegotiation occurs or if TLS 1.3 is in use.
588	//
589	// Once a Certificate is returned it should not be modified.
590	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
591
592	// GetConfigForClient, if not nil, is called after a ClientHello is
593	// received from a client. It may return a non-nil Config in order to
594	// change the Config that will be used to handle this connection. If
595	// the returned Config is nil, the original Config will be used. The
596	// Config returned by this callback may not be subsequently modified.
597	//
598	// If GetConfigForClient is nil, the Config passed to Server() will be
599	// used for all connections.
600	//
601	// If SessionTicketKey was explicitly set on the returned Config, or if
602	// SetSessionTicketKeys was called on the returned Config, those keys will
603	// be used. Otherwise, the original Config keys will be used (and possibly
604	// rotated if they are automatically managed).
605	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
606
607	// VerifyPeerCertificate, if not nil, is called after normal
608	// certificate verification by either a TLS client or server. It
609	// receives the raw ASN.1 certificates provided by the peer and also
610	// any verified chains that normal processing found. If it returns a
611	// non-nil error, the handshake is aborted and that error results.
612	//
613	// If normal verification fails then the handshake will abort before
614	// considering this callback. If normal verification is disabled (on the
615	// client when InsecureSkipVerify is set, or on a server when ClientAuth is
616	// RequestClientCert or RequireAnyClientCert), then this callback will be
617	// considered but the verifiedChains argument will always be nil. When
618	// ClientAuth is NoClientCert, this callback is not called on the server.
619	// rawCerts may be empty on the server if ClientAuth is RequestClientCert or
620	// VerifyClientCertIfGiven.
621	//
622	// This callback is not invoked on resumed connections, as certificates are
623	// not re-verified on resumption.
624	//
625	// verifiedChains and its contents should not be modified.
626	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
627
628	// VerifyConnection, if not nil, is called after normal certificate
629	// verification and after VerifyPeerCertificate by either a TLS client
630	// or server. If it returns a non-nil error, the handshake is aborted
631	// and that error results.
632	//
633	// If normal verification fails then the handshake will abort before
634	// considering this callback. This callback will run for all connections,
635	// including resumptions, regardless of InsecureSkipVerify or ClientAuth
636	// settings.
637	VerifyConnection func(ConnectionState) error
638
639	// RootCAs defines the set of root certificate authorities
640	// that clients use when verifying server certificates.
641	// If RootCAs is nil, TLS uses the host's root CA set.
642	RootCAs *x509.CertPool
643
644	// NextProtos is a list of supported application level protocols, in
645	// order of preference. If both peers support ALPN, the selected
646	// protocol will be one from this list, and the connection will fail
647	// if there is no mutually supported protocol. If NextProtos is empty
648	// or the peer doesn't support ALPN, the connection will succeed and
649	// ConnectionState.NegotiatedProtocol will be empty.
650	NextProtos []string
651
652	// ServerName is used to verify the hostname on the returned
653	// certificates unless InsecureSkipVerify is given. It is also included
654	// in the client's handshake to support virtual hosting unless it is
655	// an IP address.
656	ServerName string
657
658	// ClientAuth determines the server's policy for
659	// TLS Client Authentication. The default is NoClientCert.
660	ClientAuth ClientAuthType
661
662	// ClientCAs defines the set of root certificate authorities
663	// that servers use if required to verify a client certificate
664	// by the policy in ClientAuth.
665	ClientCAs *x509.CertPool
666
667	// InsecureSkipVerify controls whether a client verifies the server's
668	// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
669	// accepts any certificate presented by the server and any host name in that
670	// certificate. In this mode, TLS is susceptible to machine-in-the-middle
671	// attacks unless custom verification is used. This should be used only for
672	// testing or in combination with VerifyConnection or VerifyPeerCertificate.
673	InsecureSkipVerify bool
674
675	// CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
676	// the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
677	//
678	// If CipherSuites is nil, a safe default list is used. The default cipher
679	// suites might change over time. In Go 1.22 RSA key exchange based cipher
680	// suites were removed from the default list, but can be re-added with the
681	// GODEBUG setting tlsrsakex=1. In Go 1.23 3DES cipher suites were removed
682	// from the default list, but can be re-added with the GODEBUG setting
683	// tls3des=1.
684	CipherSuites []uint16
685
686	// PreferServerCipherSuites is a legacy field and has no effect.
687	//
688	// It used to control whether the server would follow the client's or the
689	// server's preference. Servers now select the best mutually supported
690	// cipher suite based on logic that takes into account inferred client
691	// hardware, server hardware, and security.
692	//
693	// Deprecated: PreferServerCipherSuites is ignored.
694	PreferServerCipherSuites bool
695
696	// SessionTicketsDisabled may be set to true to disable session ticket and
697	// PSK (resumption) support. Note that on clients, session ticket support is
698	// also disabled if ClientSessionCache is nil.
699	SessionTicketsDisabled bool
700
701	// SessionTicketKey is used by TLS servers to provide session resumption.
702	// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
703	// with random data before the first server handshake.
704	//
705	// Deprecated: if this field is left at zero, session ticket keys will be
706	// automatically rotated every day and dropped after seven days. For
707	// customizing the rotation schedule or synchronizing servers that are
708	// terminating connections for the same host, use SetSessionTicketKeys.
709	SessionTicketKey [32]byte
710
711	// ClientSessionCache is a cache of ClientSessionState entries for TLS
712	// session resumption. It is only used by clients.
713	ClientSessionCache ClientSessionCache
714
715	// UnwrapSession is called on the server to turn a ticket/identity
716	// previously produced by [WrapSession] into a usable session.
717	//
718	// UnwrapSession will usually either decrypt a session state in the ticket
719	// (for example with [Config.EncryptTicket]), or use the ticket as a handle
720	// to recover a previously stored state. It must use [ParseSessionState] to
721	// deserialize the session state.
722	//
723	// If UnwrapSession returns an error, the connection is terminated. If it
724	// returns (nil, nil), the session is ignored. crypto/tls may still choose
725	// not to resume the returned session.
726	UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
727
728	// WrapSession is called on the server to produce a session ticket/identity.
729	//
730	// WrapSession must serialize the session state with [SessionState.Bytes].
731	// It may then encrypt the serialized state (for example with
732	// [Config.DecryptTicket]) and use it as the ticket, or store the state and
733	// return a handle for it.
734	//
735	// If WrapSession returns an error, the connection is terminated.
736	//
737	// Warning: the return value will be exposed on the wire and to clients in
738	// plaintext. The application is in charge of encrypting and authenticating
739	// it (and rotating keys) or returning high-entropy identifiers. Failing to
740	// do so correctly can compromise current, previous, and future connections
741	// depending on the protocol version.
742	WrapSession func(ConnectionState, *SessionState) ([]byte, error)
743
744	// MinVersion contains the minimum TLS version that is acceptable.
745	//
746	// By default, TLS 1.2 is currently used as the minimum. TLS 1.0 is the
747	// minimum supported by this package.
748	//
749	// The server-side default can be reverted to TLS 1.0 by including the value
750	// "tls10server=1" in the GODEBUG environment variable.
751	MinVersion uint16
752
753	// MaxVersion contains the maximum TLS version that is acceptable.
754	//
755	// By default, the maximum version supported by this package is used,
756	// which is currently TLS 1.3.
757	MaxVersion uint16
758
759	// CurvePreferences contains the elliptic curves that will be used in
760	// an ECDHE handshake, in preference order. If empty, the default will
761	// be used. The client will use the first preference as the type for
762	// its key share in TLS 1.3. This may change in the future.
763	//
764	// From Go 1.23, the default includes the X25519Kyber768Draft00 hybrid
765	// post-quantum key exchange. To disable it, set CurvePreferences explicitly
766	// or use the GODEBUG=tlskyber=0 environment variable.
767	CurvePreferences []CurveID
768
769	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
770	// When true, the largest possible TLS record size is always used. When
771	// false, the size of TLS records may be adjusted in an attempt to
772	// improve latency.
773	DynamicRecordSizingDisabled bool
774
775	// Renegotiation controls what types of renegotiation are supported.
776	// The default, none, is correct for the vast majority of applications.
777	Renegotiation RenegotiationSupport
778
779	// KeyLogWriter optionally specifies a destination for TLS master secrets
780	// in NSS key log format that can be used to allow external programs
781	// such as Wireshark to decrypt TLS connections.
782	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
783	// Use of KeyLogWriter compromises security and should only be
784	// used for debugging.
785	KeyLogWriter io.Writer
786
787	// EncryptedClientHelloConfigList is a serialized ECHConfigList. If
788	// provided, clients will attempt to connect to servers using Encrypted
789	// Client Hello (ECH) using one of the provided ECHConfigs. Servers
790	// currently ignore this field.
791	//
792	// If the list contains no valid ECH configs, the handshake will fail
793	// and return an error.
794	//
795	// If EncryptedClientHelloConfigList is set, MinVersion, if set, must
796	// be VersionTLS13.
797	//
798	// When EncryptedClientHelloConfigList is set, the handshake will only
799	// succeed if ECH is sucessfully negotiated. If the server rejects ECH,
800	// an ECHRejectionError error will be returned, which may contain a new
801	// ECHConfigList that the server suggests using.
802	//
803	// How this field is parsed may change in future Go versions, if the
804	// encoding described in the final Encrypted Client Hello RFC changes.
805	EncryptedClientHelloConfigList []byte
806
807	// EncryptedClientHelloRejectionVerify, if not nil, is called when ECH is
808	// rejected, in order to verify the ECH provider certificate in the outer
809	// Client Hello. If it returns a non-nil error, the handshake is aborted and
810	// that error results.
811	//
812	// Unlike VerifyPeerCertificate and VerifyConnection, normal certificate
813	// verification will not be performed before calling
814	// EncryptedClientHelloRejectionVerify.
815	//
816	// If EncryptedClientHelloRejectionVerify is nil and ECH is rejected, the
817	// roots in RootCAs will be used to verify the ECH providers public
818	// certificate. VerifyPeerCertificate and VerifyConnection are not called
819	// when ECH is rejected, even if set, and InsecureSkipVerify is ignored.
820	EncryptedClientHelloRejectionVerify func(ConnectionState) error
821
822	// mutex protects sessionTicketKeys and autoSessionTicketKeys.
823	mutex sync.RWMutex
824	// sessionTicketKeys contains zero or more ticket keys. If set, it means
825	// the keys were set with SessionTicketKey or SetSessionTicketKeys. The
826	// first key is used for new tickets and any subsequent keys can be used to
827	// decrypt old tickets. The slice contents are not protected by the mutex
828	// and are immutable.
829	sessionTicketKeys []ticketKey
830	// autoSessionTicketKeys is like sessionTicketKeys but is owned by the
831	// auto-rotation logic. See Config.ticketKeys.
832	autoSessionTicketKeys []ticketKey
833}
834
835const (
836	// ticketKeyLifetime is how long a ticket key remains valid and can be used to
837	// resume a client connection.
838	ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
839
840	// ticketKeyRotation is how often the server should rotate the session ticket key
841	// that is used for new tickets.
842	ticketKeyRotation = 24 * time.Hour
843)
844
845// ticketKey is the internal representation of a session ticket key.
846type ticketKey struct {
847	aesKey  [16]byte
848	hmacKey [16]byte
849	// created is the time at which this ticket key was created. See Config.ticketKeys.
850	created time.Time
851}
852
853// ticketKeyFromBytes converts from the external representation of a session
854// ticket key to a ticketKey. Externally, session ticket keys are 32 random
855// bytes and this function expands that into sufficient name and key material.
856func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
857	hashed := sha512.Sum512(b[:])
858	// The first 16 bytes of the hash used to be exposed on the wire as a ticket
859	// prefix. They MUST NOT be used as a secret. In the future, it would make
860	// sense to use a proper KDF here, like HKDF with a fixed salt.
861	const legacyTicketKeyNameLen = 16
862	copy(key.aesKey[:], hashed[legacyTicketKeyNameLen:])
863	copy(key.hmacKey[:], hashed[legacyTicketKeyNameLen+len(key.aesKey):])
864	key.created = c.time()
865	return key
866}
867
868// maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
869// ticket, and the lifetime we set for all tickets we send.
870const maxSessionTicketLifetime = 7 * 24 * time.Hour
871
872// Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a [Config] that is
873// being used concurrently by a TLS client or server.
874func (c *Config) Clone() *Config {
875	if c == nil {
876		return nil
877	}
878	c.mutex.RLock()
879	defer c.mutex.RUnlock()
880	return &Config{
881		Rand:                                c.Rand,
882		Time:                                c.Time,
883		Certificates:                        c.Certificates,
884		NameToCertificate:                   c.NameToCertificate,
885		GetCertificate:                      c.GetCertificate,
886		GetClientCertificate:                c.GetClientCertificate,
887		GetConfigForClient:                  c.GetConfigForClient,
888		VerifyPeerCertificate:               c.VerifyPeerCertificate,
889		VerifyConnection:                    c.VerifyConnection,
890		RootCAs:                             c.RootCAs,
891		NextProtos:                          c.NextProtos,
892		ServerName:                          c.ServerName,
893		ClientAuth:                          c.ClientAuth,
894		ClientCAs:                           c.ClientCAs,
895		InsecureSkipVerify:                  c.InsecureSkipVerify,
896		CipherSuites:                        c.CipherSuites,
897		PreferServerCipherSuites:            c.PreferServerCipherSuites,
898		SessionTicketsDisabled:              c.SessionTicketsDisabled,
899		SessionTicketKey:                    c.SessionTicketKey,
900		ClientSessionCache:                  c.ClientSessionCache,
901		UnwrapSession:                       c.UnwrapSession,
902		WrapSession:                         c.WrapSession,
903		MinVersion:                          c.MinVersion,
904		MaxVersion:                          c.MaxVersion,
905		CurvePreferences:                    c.CurvePreferences,
906		DynamicRecordSizingDisabled:         c.DynamicRecordSizingDisabled,
907		Renegotiation:                       c.Renegotiation,
908		KeyLogWriter:                        c.KeyLogWriter,
909		EncryptedClientHelloConfigList:      c.EncryptedClientHelloConfigList,
910		EncryptedClientHelloRejectionVerify: c.EncryptedClientHelloRejectionVerify,
911		sessionTicketKeys:                   c.sessionTicketKeys,
912		autoSessionTicketKeys:               c.autoSessionTicketKeys,
913	}
914}
915
916// deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
917// randomized for backwards compatibility but is not in use.
918var deprecatedSessionTicketKey = []byte("DEPRECATED")
919
920// initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
921// randomized if empty, and that sessionTicketKeys is populated from it otherwise.
922func (c *Config) initLegacySessionTicketKeyRLocked() {
923	// Don't write if SessionTicketKey is already defined as our deprecated string,
924	// or if it is defined by the user but sessionTicketKeys is already set.
925	if c.SessionTicketKey != [32]byte{} &&
926		(bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
927		return
928	}
929
930	// We need to write some data, so get an exclusive lock and re-check any conditions.
931	c.mutex.RUnlock()
932	defer c.mutex.RLock()
933	c.mutex.Lock()
934	defer c.mutex.Unlock()
935	if c.SessionTicketKey == [32]byte{} {
936		if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
937			panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
938		}
939		// Write the deprecated prefix at the beginning so we know we created
940		// it. This key with the DEPRECATED prefix isn't used as an actual
941		// session ticket key, and is only randomized in case the application
942		// reuses it for some reason.
943		copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
944	} else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
945		c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
946	}
947
948}
949
950// ticketKeys returns the ticketKeys for this connection.
951// If configForClient has explicitly set keys, those will
952// be returned. Otherwise, the keys on c will be used and
953// may be rotated if auto-managed.
954// During rotation, any expired session ticket keys are deleted from
955// c.sessionTicketKeys. If the session ticket key that is currently
956// encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
957// is not fresh, then a new session ticket key will be
958// created and prepended to c.sessionTicketKeys.
959func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
960	// If the ConfigForClient callback returned a Config with explicitly set
961	// keys, use those, otherwise just use the original Config.
962	if configForClient != nil {
963		configForClient.mutex.RLock()
964		if configForClient.SessionTicketsDisabled {
965			return nil
966		}
967		configForClient.initLegacySessionTicketKeyRLocked()
968		if len(configForClient.sessionTicketKeys) != 0 {
969			ret := configForClient.sessionTicketKeys
970			configForClient.mutex.RUnlock()
971			return ret
972		}
973		configForClient.mutex.RUnlock()
974	}
975
976	c.mutex.RLock()
977	defer c.mutex.RUnlock()
978	if c.SessionTicketsDisabled {
979		return nil
980	}
981	c.initLegacySessionTicketKeyRLocked()
982	if len(c.sessionTicketKeys) != 0 {
983		return c.sessionTicketKeys
984	}
985	// Fast path for the common case where the key is fresh enough.
986	if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
987		return c.autoSessionTicketKeys
988	}
989
990	// autoSessionTicketKeys are managed by auto-rotation.
991	c.mutex.RUnlock()
992	defer c.mutex.RLock()
993	c.mutex.Lock()
994	defer c.mutex.Unlock()
995	// Re-check the condition in case it changed since obtaining the new lock.
996	if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
997		var newKey [32]byte
998		if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
999			panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
1000		}
1001		valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
1002		valid = append(valid, c.ticketKeyFromBytes(newKey))
1003		for _, k := range c.autoSessionTicketKeys {
1004			// While rotating the current key, also remove any expired ones.
1005			if c.time().Sub(k.created) < ticketKeyLifetime {
1006				valid = append(valid, k)
1007			}
1008		}
1009		c.autoSessionTicketKeys = valid
1010	}
1011	return c.autoSessionTicketKeys
1012}
1013
1014// SetSessionTicketKeys updates the session ticket keys for a server.
1015//
1016// The first key will be used when creating new tickets, while all keys can be
1017// used for decrypting tickets. It is safe to call this function while the
1018// server is running in order to rotate the session ticket keys. The function
1019// will panic if keys is empty.
1020//
1021// Calling this function will turn off automatic session ticket key rotation.
1022//
1023// If multiple servers are terminating connections for the same host they should
1024// all have the same session ticket keys. If the session ticket keys leaks,
1025// previously recorded and future TLS connections using those keys might be
1026// compromised.
1027func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
1028	if len(keys) == 0 {
1029		panic("tls: keys must have at least one key")
1030	}
1031
1032	newKeys := make([]ticketKey, len(keys))
1033	for i, bytes := range keys {
1034		newKeys[i] = c.ticketKeyFromBytes(bytes)
1035	}
1036
1037	c.mutex.Lock()
1038	c.sessionTicketKeys = newKeys
1039	c.mutex.Unlock()
1040}
1041
1042func (c *Config) rand() io.Reader {
1043	r := c.Rand
1044	if r == nil {
1045		return rand.Reader
1046	}
1047	return r
1048}
1049
1050func (c *Config) time() time.Time {
1051	t := c.Time
1052	if t == nil {
1053		t = time.Now
1054	}
1055	return t()
1056}
1057
1058func (c *Config) cipherSuites() []uint16 {
1059	if c.CipherSuites == nil {
1060		if needFIPS() {
1061			return defaultCipherSuitesFIPS
1062		}
1063		return defaultCipherSuites()
1064	}
1065	if needFIPS() {
1066		cipherSuites := slices.Clone(c.CipherSuites)
1067		return slices.DeleteFunc(cipherSuites, func(id uint16) bool {
1068			return !slices.Contains(defaultCipherSuitesFIPS, id)
1069		})
1070	}
1071	return c.CipherSuites
1072}
1073
1074var supportedVersions = []uint16{
1075	VersionTLS13,
1076	VersionTLS12,
1077	VersionTLS11,
1078	VersionTLS10,
1079}
1080
1081// roleClient and roleServer are meant to call supportedVersions and parents
1082// with more readability at the callsite.
1083const roleClient = true
1084const roleServer = false
1085
1086var tls10server = godebug.New("tls10server")
1087
1088func (c *Config) supportedVersions(isClient bool) []uint16 {
1089	versions := make([]uint16, 0, len(supportedVersions))
1090	for _, v := range supportedVersions {
1091		if needFIPS() && !slices.Contains(defaultSupportedVersionsFIPS, v) {
1092			continue
1093		}
1094		if (c == nil || c.MinVersion == 0) && v < VersionTLS12 {
1095			if isClient || tls10server.Value() != "1" {
1096				continue
1097			}
1098		}
1099		if isClient && c.EncryptedClientHelloConfigList != nil && v < VersionTLS13 {
1100			continue
1101		}
1102		if c != nil && c.MinVersion != 0 && v < c.MinVersion {
1103			continue
1104		}
1105		if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
1106			continue
1107		}
1108		versions = append(versions, v)
1109	}
1110	return versions
1111}
1112
1113func (c *Config) maxSupportedVersion(isClient bool) uint16 {
1114	supportedVersions := c.supportedVersions(isClient)
1115	if len(supportedVersions) == 0 {
1116		return 0
1117	}
1118	return supportedVersions[0]
1119}
1120
1121// supportedVersionsFromMax returns a list of supported versions derived from a
1122// legacy maximum version value. Note that only versions supported by this
1123// library are returned. Any newer peer will use supportedVersions anyway.
1124func supportedVersionsFromMax(maxVersion uint16) []uint16 {
1125	versions := make([]uint16, 0, len(supportedVersions))
1126	for _, v := range supportedVersions {
1127		if v > maxVersion {
1128			continue
1129		}
1130		versions = append(versions, v)
1131	}
1132	return versions
1133}
1134
1135func (c *Config) curvePreferences(version uint16) []CurveID {
1136	var curvePreferences []CurveID
1137	if c != nil && len(c.CurvePreferences) != 0 {
1138		curvePreferences = slices.Clone(c.CurvePreferences)
1139		if needFIPS() {
1140			return slices.DeleteFunc(curvePreferences, func(c CurveID) bool {
1141				return !slices.Contains(defaultCurvePreferencesFIPS, c)
1142			})
1143		}
1144	} else if needFIPS() {
1145		curvePreferences = slices.Clone(defaultCurvePreferencesFIPS)
1146	} else {
1147		curvePreferences = defaultCurvePreferences()
1148	}
1149	if version < VersionTLS13 {
1150		return slices.DeleteFunc(curvePreferences, func(c CurveID) bool {
1151			return c == x25519Kyber768Draft00
1152		})
1153	}
1154	return curvePreferences
1155}
1156
1157func (c *Config) supportsCurve(version uint16, curve CurveID) bool {
1158	for _, cc := range c.curvePreferences(version) {
1159		if cc == curve {
1160			return true
1161		}
1162	}
1163	return false
1164}
1165
1166// mutualVersion returns the protocol version to use given the advertised
1167// versions of the peer. Priority is given to the peer preference order.
1168func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
1169	supportedVersions := c.supportedVersions(isClient)
1170	for _, peerVersion := range peerVersions {
1171		for _, v := range supportedVersions {
1172			if v == peerVersion {
1173				return v, true
1174			}
1175		}
1176	}
1177	return 0, false
1178}
1179
1180// errNoCertificates should be an internal detail,
1181// but widely used packages access it using linkname.
1182// Notable members of the hall of shame include:
1183//   - github.com/xtls/xray-core
1184//
1185// Do not remove or change the type signature.
1186// See go.dev/issue/67401.
1187//
1188//go:linkname errNoCertificates
1189var errNoCertificates = errors.New("tls: no certificates configured")
1190
1191// getCertificate returns the best certificate for the given ClientHelloInfo,
1192// defaulting to the first element of c.Certificates.
1193func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1194	if c.GetCertificate != nil &&
1195		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1196		cert, err := c.GetCertificate(clientHello)
1197		if cert != nil || err != nil {
1198			return cert, err
1199		}
1200	}
1201
1202	if len(c.Certificates) == 0 {
1203		return nil, errNoCertificates
1204	}
1205
1206	if len(c.Certificates) == 1 {
1207		// There's only one choice, so no point doing any work.
1208		return &c.Certificates[0], nil
1209	}
1210
1211	if c.NameToCertificate != nil {
1212		name := strings.ToLower(clientHello.ServerName)
1213		if cert, ok := c.NameToCertificate[name]; ok {
1214			return cert, nil
1215		}
1216		if len(name) > 0 {
1217			labels := strings.Split(name, ".")
1218			labels[0] = "*"
1219			wildcardName := strings.Join(labels, ".")
1220			if cert, ok := c.NameToCertificate[wildcardName]; ok {
1221				return cert, nil
1222			}
1223		}
1224	}
1225
1226	for _, cert := range c.Certificates {
1227		if err := clientHello.SupportsCertificate(&cert); err == nil {
1228			return &cert, nil
1229		}
1230	}
1231
1232	// If nothing matches, return the first certificate.
1233	return &c.Certificates[0], nil
1234}
1235
1236// SupportsCertificate returns nil if the provided certificate is supported by
1237// the client that sent the ClientHello. Otherwise, it returns an error
1238// describing the reason for the incompatibility.
1239//
1240// If this [ClientHelloInfo] was passed to a GetConfigForClient or GetCertificate
1241// callback, this method will take into account the associated [Config]. Note that
1242// if GetConfigForClient returns a different [Config], the change can't be
1243// accounted for by this method.
1244//
1245// This function will call x509.ParseCertificate unless c.Leaf is set, which can
1246// incur a significant performance cost.
1247func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1248	// Note we don't currently support certificate_authorities nor
1249	// signature_algorithms_cert, and don't check the algorithms of the
1250	// signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1251	// Section 4.4.2.2).
1252
1253	config := chi.config
1254	if config == nil {
1255		config = &Config{}
1256	}
1257	vers, ok := config.mutualVersion(roleServer, chi.SupportedVersions)
1258	if !ok {
1259		return errors.New("no mutually supported protocol versions")
1260	}
1261
1262	// If the client specified the name they are trying to connect to, the
1263	// certificate needs to be valid for it.
1264	if chi.ServerName != "" {
1265		x509Cert, err := c.leaf()
1266		if err != nil {
1267			return fmt.Errorf("failed to parse certificate: %w", err)
1268		}
1269		if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1270			return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1271		}
1272	}
1273
1274	// supportsRSAFallback returns nil if the certificate and connection support
1275	// the static RSA key exchange, and unsupported otherwise. The logic for
1276	// supporting static RSA is completely disjoint from the logic for
1277	// supporting signed key exchanges, so we just check it as a fallback.
1278	supportsRSAFallback := func(unsupported error) error {
1279		// TLS 1.3 dropped support for the static RSA key exchange.
1280		if vers == VersionTLS13 {
1281			return unsupported
1282		}
1283		// The static RSA key exchange works by decrypting a challenge with the
1284		// RSA private key, not by signing, so check the PrivateKey implements
1285		// crypto.Decrypter, like *rsa.PrivateKey does.
1286		if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1287			if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1288				return unsupported
1289			}
1290		} else {
1291			return unsupported
1292		}
1293		// Finally, there needs to be a mutual cipher suite that uses the static
1294		// RSA key exchange instead of ECDHE.
1295		rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1296			if c.flags&suiteECDHE != 0 {
1297				return false
1298			}
1299			if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1300				return false
1301			}
1302			return true
1303		})
1304		if rsaCipherSuite == nil {
1305			return unsupported
1306		}
1307		return nil
1308	}
1309
1310	// If the client sent the signature_algorithms extension, ensure it supports
1311	// schemes we can use with this certificate and TLS version.
1312	if len(chi.SignatureSchemes) > 0 {
1313		if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1314			return supportsRSAFallback(err)
1315		}
1316	}
1317
1318	// In TLS 1.3 we are done because supported_groups is only relevant to the
1319	// ECDHE computation, point format negotiation is removed, cipher suites are
1320	// only relevant to the AEAD choice, and static RSA does not exist.
1321	if vers == VersionTLS13 {
1322		return nil
1323	}
1324
1325	// The only signed key exchange we support is ECDHE.
1326	if !supportsECDHE(config, vers, chi.SupportedCurves, chi.SupportedPoints) {
1327		return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1328	}
1329
1330	var ecdsaCipherSuite bool
1331	if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1332		switch pub := priv.Public().(type) {
1333		case *ecdsa.PublicKey:
1334			var curve CurveID
1335			switch pub.Curve {
1336			case elliptic.P256():
1337				curve = CurveP256
1338			case elliptic.P384():
1339				curve = CurveP384
1340			case elliptic.P521():
1341				curve = CurveP521
1342			default:
1343				return supportsRSAFallback(unsupportedCertificateError(c))
1344			}
1345			var curveOk bool
1346			for _, c := range chi.SupportedCurves {
1347				if c == curve && config.supportsCurve(vers, c) {
1348					curveOk = true
1349					break
1350				}
1351			}
1352			if !curveOk {
1353				return errors.New("client doesn't support certificate curve")
1354			}
1355			ecdsaCipherSuite = true
1356		case ed25519.PublicKey:
1357			if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1358				return errors.New("connection doesn't support Ed25519")
1359			}
1360			ecdsaCipherSuite = true
1361		case *rsa.PublicKey:
1362		default:
1363			return supportsRSAFallback(unsupportedCertificateError(c))
1364		}
1365	} else {
1366		return supportsRSAFallback(unsupportedCertificateError(c))
1367	}
1368
1369	// Make sure that there is a mutually supported cipher suite that works with
1370	// this certificate. Cipher suite selection will then apply the logic in
1371	// reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1372	cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1373		if c.flags&suiteECDHE == 0 {
1374			return false
1375		}
1376		if c.flags&suiteECSign != 0 {
1377			if !ecdsaCipherSuite {
1378				return false
1379			}
1380		} else {
1381			if ecdsaCipherSuite {
1382				return false
1383			}
1384		}
1385		if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1386			return false
1387		}
1388		return true
1389	})
1390	if cipherSuite == nil {
1391		return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1392	}
1393
1394	return nil
1395}
1396
1397// SupportsCertificate returns nil if the provided certificate is supported by
1398// the server that sent the CertificateRequest. Otherwise, it returns an error
1399// describing the reason for the incompatibility.
1400func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1401	if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1402		return err
1403	}
1404
1405	if len(cri.AcceptableCAs) == 0 {
1406		return nil
1407	}
1408
1409	for j, cert := range c.Certificate {
1410		x509Cert := c.Leaf
1411		// Parse the certificate if this isn't the leaf node, or if
1412		// chain.Leaf was nil.
1413		if j != 0 || x509Cert == nil {
1414			var err error
1415			if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1416				return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1417			}
1418		}
1419
1420		for _, ca := range cri.AcceptableCAs {
1421			if bytes.Equal(x509Cert.RawIssuer, ca) {
1422				return nil
1423			}
1424		}
1425	}
1426	return errors.New("chain is not signed by an acceptable CA")
1427}
1428
1429// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1430// from the CommonName and SubjectAlternateName fields of each of the leaf
1431// certificates.
1432//
1433// Deprecated: NameToCertificate only allows associating a single certificate
1434// with a given name. Leave that field nil to let the library select the first
1435// compatible chain from Certificates.
1436func (c *Config) BuildNameToCertificate() {
1437	c.NameToCertificate = make(map[string]*Certificate)
1438	for i := range c.Certificates {
1439		cert := &c.Certificates[i]
1440		x509Cert, err := cert.leaf()
1441		if err != nil {
1442			continue
1443		}
1444		// If SANs are *not* present, some clients will consider the certificate
1445		// valid for the name in the Common Name.
1446		if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
1447			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1448		}
1449		for _, san := range x509Cert.DNSNames {
1450			c.NameToCertificate[san] = cert
1451		}
1452	}
1453}
1454
1455const (
1456	keyLogLabelTLS12           = "CLIENT_RANDOM"
1457	keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1458	keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1459	keyLogLabelClientTraffic   = "CLIENT_TRAFFIC_SECRET_0"
1460	keyLogLabelServerTraffic   = "SERVER_TRAFFIC_SECRET_0"
1461)
1462
1463func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1464	if c.KeyLogWriter == nil {
1465		return nil
1466	}
1467
1468	logLine := fmt.Appendf(nil, "%s %x %x\n", label, clientRandom, secret)
1469
1470	writerMutex.Lock()
1471	_, err := c.KeyLogWriter.Write(logLine)
1472	writerMutex.Unlock()
1473
1474	return err
1475}
1476
1477// writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1478// and is only for debugging, so a global mutex saves space.
1479var writerMutex sync.Mutex
1480
1481// A Certificate is a chain of one or more certificates, leaf first.
1482type Certificate struct {
1483	Certificate [][]byte
1484	// PrivateKey contains the private key corresponding to the public key in
1485	// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1486	// For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1487	// an RSA PublicKey.
1488	PrivateKey crypto.PrivateKey
1489	// SupportedSignatureAlgorithms is an optional list restricting what
1490	// signature algorithms the PrivateKey can be used for.
1491	SupportedSignatureAlgorithms []SignatureScheme
1492	// OCSPStaple contains an optional OCSP response which will be served
1493	// to clients that request it.
1494	OCSPStaple []byte
1495	// SignedCertificateTimestamps contains an optional list of Signed
1496	// Certificate Timestamps which will be served to clients that request it.
1497	SignedCertificateTimestamps [][]byte
1498	// Leaf is the parsed form of the leaf certificate, which may be initialized
1499	// using x509.ParseCertificate to reduce per-handshake processing. If nil,
1500	// the leaf certificate will be parsed as needed.
1501	Leaf *x509.Certificate
1502}
1503
1504// leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1505// the corresponding c.Certificate[0].
1506func (c *Certificate) leaf() (*x509.Certificate, error) {
1507	if c.Leaf != nil {
1508		return c.Leaf, nil
1509	}
1510	return x509.ParseCertificate(c.Certificate[0])
1511}
1512
1513type handshakeMessage interface {
1514	marshal() ([]byte, error)
1515	unmarshal([]byte) bool
1516}
1517
1518type handshakeMessageWithOriginalBytes interface {
1519	handshakeMessage
1520
1521	// originalBytes should return the original bytes that were passed to
1522	// unmarshal to create the message. If the message was not produced by
1523	// unmarshal, it should return nil.
1524	originalBytes() []byte
1525}
1526
1527// lruSessionCache is a ClientSessionCache implementation that uses an LRU
1528// caching strategy.
1529type lruSessionCache struct {
1530	sync.Mutex
1531
1532	m        map[string]*list.Element
1533	q        *list.List
1534	capacity int
1535}
1536
1537type lruSessionCacheEntry struct {
1538	sessionKey string
1539	state      *ClientSessionState
1540}
1541
1542// NewLRUClientSessionCache returns a [ClientSessionCache] with the given
1543// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1544// is used instead.
1545func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1546	const defaultSessionCacheCapacity = 64
1547
1548	if capacity < 1 {
1549		capacity = defaultSessionCacheCapacity
1550	}
1551	return &lruSessionCache{
1552		m:        make(map[string]*list.Element),
1553		q:        list.New(),
1554		capacity: capacity,
1555	}
1556}
1557
1558// Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1559// corresponding to sessionKey is removed from the cache instead.
1560func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1561	c.Lock()
1562	defer c.Unlock()
1563
1564	if elem, ok := c.m[sessionKey]; ok {
1565		if cs == nil {
1566			c.q.Remove(elem)
1567			delete(c.m, sessionKey)
1568		} else {
1569			entry := elem.Value.(*lruSessionCacheEntry)
1570			entry.state = cs
1571			c.q.MoveToFront(elem)
1572		}
1573		return
1574	}
1575
1576	if c.q.Len() < c.capacity {
1577		entry := &lruSessionCacheEntry{sessionKey, cs}
1578		c.m[sessionKey] = c.q.PushFront(entry)
1579		return
1580	}
1581
1582	elem := c.q.Back()
1583	entry := elem.Value.(*lruSessionCacheEntry)
1584	delete(c.m, entry.sessionKey)
1585	entry.sessionKey = sessionKey
1586	entry.state = cs
1587	c.q.MoveToFront(elem)
1588	c.m[sessionKey] = elem
1589}
1590
1591// Get returns the [ClientSessionState] value associated with a given key. It
1592// returns (nil, false) if no value is found.
1593func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1594	c.Lock()
1595	defer c.Unlock()
1596
1597	if elem, ok := c.m[sessionKey]; ok {
1598		c.q.MoveToFront(elem)
1599		return elem.Value.(*lruSessionCacheEntry).state, true
1600	}
1601	return nil, false
1602}
1603
1604var emptyConfig Config
1605
1606func defaultConfig() *Config {
1607	return &emptyConfig
1608}
1609
1610func unexpectedMessageError(wanted, got any) error {
1611	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1612}
1613
1614// supportedSignatureAlgorithms returns the supported signature algorithms.
1615func supportedSignatureAlgorithms() []SignatureScheme {
1616	if !needFIPS() {
1617		return defaultSupportedSignatureAlgorithms
1618	}
1619	return defaultSupportedSignatureAlgorithmsFIPS
1620}
1621
1622func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1623	for _, s := range supportedSignatureAlgorithms {
1624		if s == sigAlg {
1625			return true
1626		}
1627	}
1628	return false
1629}
1630
1631// CertificateVerificationError is returned when certificate verification fails during the handshake.
1632type CertificateVerificationError struct {
1633	// UnverifiedCertificates and its contents should not be modified.
1634	UnverifiedCertificates []*x509.Certificate
1635	Err                    error
1636}
1637
1638func (e *CertificateVerificationError) Error() string {
1639	return fmt.Sprintf("tls: failed to verify certificate: %s", e.Err)
1640}
1641
1642func (e *CertificateVerificationError) Unwrap() error {
1643	return e.Err
1644}
1645