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