]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/common.go
crypto/tls: support QUIC as a transport
[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 // ClientSessionState contains the state needed by clients to resume TLS
334 // sessions.
335 type ClientSessionState struct {
336         sessionTicket      []uint8               // Encrypted ticket used for session resumption with server
337         vers               uint16                // TLS version negotiated for the session
338         cipherSuite        uint16                // Ciphersuite negotiated for the session
339         masterSecret       []byte                // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
340         serverCertificates []*x509.Certificate   // Certificate chain presented by the server
341         verifiedChains     [][]*x509.Certificate // Certificate chains we built for verification
342         receivedAt         time.Time             // When the session ticket was received from the server
343         ocspResponse       []byte                // Stapled OCSP response presented by the server
344         scts               [][]byte              // SCTs presented by the server
345
346         // TLS 1.3 fields.
347         nonce  []byte    // Ticket nonce sent by the server, to derive PSK
348         useBy  time.Time // Expiration of the ticket lifetime as set by the server
349         ageAdd uint32    // Random obfuscation factor for sending the ticket age
350 }
351
352 // ClientSessionCache is a cache of ClientSessionState objects that can be used
353 // by a client to resume a TLS session with a given server. ClientSessionCache
354 // implementations should expect to be called concurrently from different
355 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
356 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
357 // are supported via this interface.
358 type ClientSessionCache interface {
359         // Get searches for a ClientSessionState associated with the given key.
360         // On return, ok is true if one was found.
361         Get(sessionKey string) (session *ClientSessionState, ok bool)
362
363         // Put adds the ClientSessionState to the cache with the given key. It might
364         // get called multiple times in a connection if a TLS 1.3 server provides
365         // more than one session ticket. If called with a nil *ClientSessionState,
366         // it should remove the cache entry.
367         Put(sessionKey string, cs *ClientSessionState)
368 }
369
370 //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
371
372 // SignatureScheme identifies a signature algorithm supported by TLS. See
373 // RFC 8446, Section 4.2.3.
374 type SignatureScheme uint16
375
376 const (
377         // RSASSA-PKCS1-v1_5 algorithms.
378         PKCS1WithSHA256 SignatureScheme = 0x0401
379         PKCS1WithSHA384 SignatureScheme = 0x0501
380         PKCS1WithSHA512 SignatureScheme = 0x0601
381
382         // RSASSA-PSS algorithms with public key OID rsaEncryption.
383         PSSWithSHA256 SignatureScheme = 0x0804
384         PSSWithSHA384 SignatureScheme = 0x0805
385         PSSWithSHA512 SignatureScheme = 0x0806
386
387         // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
388         ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
389         ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
390         ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
391
392         // EdDSA algorithms.
393         Ed25519 SignatureScheme = 0x0807
394
395         // Legacy signature and hash algorithms for TLS 1.2.
396         PKCS1WithSHA1 SignatureScheme = 0x0201
397         ECDSAWithSHA1 SignatureScheme = 0x0203
398 )
399
400 // ClientHelloInfo contains information from a ClientHello message in order to
401 // guide application logic in the GetCertificate and GetConfigForClient callbacks.
402 type ClientHelloInfo struct {
403         // CipherSuites lists the CipherSuites supported by the client (e.g.
404         // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
405         CipherSuites []uint16
406
407         // ServerName indicates the name of the server requested by the client
408         // in order to support virtual hosting. ServerName is only set if the
409         // client is using SNI (see RFC 4366, Section 3.1).
410         ServerName string
411
412         // SupportedCurves lists the elliptic curves supported by the client.
413         // SupportedCurves is set only if the Supported Elliptic Curves
414         // Extension is being used (see RFC 4492, Section 5.1.1).
415         SupportedCurves []CurveID
416
417         // SupportedPoints lists the point formats supported by the client.
418         // SupportedPoints is set only if the Supported Point Formats Extension
419         // is being used (see RFC 4492, Section 5.1.2).
420         SupportedPoints []uint8
421
422         // SignatureSchemes lists the signature and hash schemes that the client
423         // is willing to verify. SignatureSchemes is set only if the Signature
424         // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
425         SignatureSchemes []SignatureScheme
426
427         // SupportedProtos lists the application protocols supported by the client.
428         // SupportedProtos is set only if the Application-Layer Protocol
429         // Negotiation Extension is being used (see RFC 7301, Section 3.1).
430         //
431         // Servers can select a protocol by setting Config.NextProtos in a
432         // GetConfigForClient return value.
433         SupportedProtos []string
434
435         // SupportedVersions lists the TLS versions supported by the client.
436         // For TLS versions less than 1.3, this is extrapolated from the max
437         // version advertised by the client, so values other than the greatest
438         // might be rejected if used.
439         SupportedVersions []uint16
440
441         // Conn is the underlying net.Conn for the connection. Do not read
442         // from, or write to, this connection; that will cause the TLS
443         // connection to fail.
444         Conn net.Conn
445
446         // config is embedded by the GetCertificate or GetConfigForClient caller,
447         // for use with SupportsCertificate.
448         config *Config
449
450         // ctx is the context of the handshake that is in progress.
451         ctx context.Context
452 }
453
454 // Context returns the context of the handshake that is in progress.
455 // This context is a child of the context passed to HandshakeContext,
456 // if any, and is canceled when the handshake concludes.
457 func (c *ClientHelloInfo) Context() context.Context {
458         return c.ctx
459 }
460
461 // CertificateRequestInfo contains information from a server's
462 // CertificateRequest message, which is used to demand a certificate and proof
463 // of control from a client.
464 type CertificateRequestInfo struct {
465         // AcceptableCAs contains zero or more, DER-encoded, X.501
466         // Distinguished Names. These are the names of root or intermediate CAs
467         // that the server wishes the returned certificate to be signed by. An
468         // empty slice indicates that the server has no preference.
469         AcceptableCAs [][]byte
470
471         // SignatureSchemes lists the signature schemes that the server is
472         // willing to verify.
473         SignatureSchemes []SignatureScheme
474
475         // Version is the TLS version that was negotiated for this connection.
476         Version uint16
477
478         // ctx is the context of the handshake that is in progress.
479         ctx context.Context
480 }
481
482 // Context returns the context of the handshake that is in progress.
483 // This context is a child of the context passed to HandshakeContext,
484 // if any, and is canceled when the handshake concludes.
485 func (c *CertificateRequestInfo) Context() context.Context {
486         return c.ctx
487 }
488
489 // RenegotiationSupport enumerates the different levels of support for TLS
490 // renegotiation. TLS renegotiation is the act of performing subsequent
491 // handshakes on a connection after the first. This significantly complicates
492 // the state machine and has been the source of numerous, subtle security
493 // issues. Initiating a renegotiation is not supported, but support for
494 // accepting renegotiation requests may be enabled.
495 //
496 // Even when enabled, the server may not change its identity between handshakes
497 // (i.e. the leaf certificate must be the same). Additionally, concurrent
498 // handshake and application data flow is not permitted so renegotiation can
499 // only be used with protocols that synchronise with the renegotiation, such as
500 // HTTPS.
501 //
502 // Renegotiation is not defined in TLS 1.3.
503 type RenegotiationSupport int
504
505 const (
506         // RenegotiateNever disables renegotiation.
507         RenegotiateNever RenegotiationSupport = iota
508
509         // RenegotiateOnceAsClient allows a remote server to request
510         // renegotiation once per connection.
511         RenegotiateOnceAsClient
512
513         // RenegotiateFreelyAsClient allows a remote server to repeatedly
514         // request renegotiation.
515         RenegotiateFreelyAsClient
516 )
517
518 // A Config structure is used to configure a TLS client or server.
519 // After one has been passed to a TLS function it must not be
520 // modified. A Config may be reused; the tls package will also not
521 // modify it.
522 type Config struct {
523         // Rand provides the source of entropy for nonces and RSA blinding.
524         // If Rand is nil, TLS uses the cryptographic random reader in package
525         // crypto/rand.
526         // The Reader must be safe for use by multiple goroutines.
527         Rand io.Reader
528
529         // Time returns the current time as the number of seconds since the epoch.
530         // If Time is nil, TLS uses time.Now.
531         Time func() time.Time
532
533         // Certificates contains one or more certificate chains to present to the
534         // other side of the connection. The first certificate compatible with the
535         // peer's requirements is selected automatically.
536         //
537         // Server configurations must set one of Certificates, GetCertificate or
538         // GetConfigForClient. Clients doing client-authentication may set either
539         // Certificates or GetClientCertificate.
540         //
541         // Note: if there are multiple Certificates, and they don't have the
542         // optional field Leaf set, certificate selection will incur a significant
543         // per-handshake performance cost.
544         Certificates []Certificate
545
546         // NameToCertificate maps from a certificate name to an element of
547         // Certificates. Note that a certificate name can be of the form
548         // '*.example.com' and so doesn't have to be a domain name as such.
549         //
550         // Deprecated: NameToCertificate only allows associating a single
551         // certificate with a given name. Leave this field nil to let the library
552         // select the first compatible chain from Certificates.
553         NameToCertificate map[string]*Certificate
554
555         // GetCertificate returns a Certificate based on the given
556         // ClientHelloInfo. It will only be called if the client supplies SNI
557         // information or if Certificates is empty.
558         //
559         // If GetCertificate is nil or returns nil, then the certificate is
560         // retrieved from NameToCertificate. If NameToCertificate is nil, the
561         // best element of Certificates will be used.
562         //
563         // Once a Certificate is returned it should not be modified.
564         GetCertificate func(*ClientHelloInfo) (*Certificate, error)
565
566         // GetClientCertificate, if not nil, is called when a server requests a
567         // certificate from a client. If set, the contents of Certificates will
568         // be ignored.
569         //
570         // If GetClientCertificate returns an error, the handshake will be
571         // aborted and that error will be returned. Otherwise
572         // GetClientCertificate must return a non-nil Certificate. If
573         // Certificate.Certificate is empty then no certificate will be sent to
574         // the server. If this is unacceptable to the server then it may abort
575         // the handshake.
576         //
577         // GetClientCertificate may be called multiple times for the same
578         // connection if renegotiation occurs or if TLS 1.3 is in use.
579         //
580         // Once a Certificate is returned it should not be modified.
581         GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
582
583         // GetConfigForClient, if not nil, is called after a ClientHello is
584         // received from a client. It may return a non-nil Config in order to
585         // change the Config that will be used to handle this connection. If
586         // the returned Config is nil, the original Config will be used. The
587         // Config returned by this callback may not be subsequently modified.
588         //
589         // If GetConfigForClient is nil, the Config passed to Server() will be
590         // used for all connections.
591         //
592         // If SessionTicketKey was explicitly set on the returned Config, or if
593         // SetSessionTicketKeys was called on the returned Config, those keys will
594         // be used. Otherwise, the original Config keys will be used (and possibly
595         // rotated if they are automatically managed).
596         GetConfigForClient func(*ClientHelloInfo) (*Config, error)
597
598         // VerifyPeerCertificate, if not nil, is called after normal
599         // certificate verification by either a TLS client or server. It
600         // receives the raw ASN.1 certificates provided by the peer and also
601         // any verified chains that normal processing found. If it returns a
602         // non-nil error, the handshake is aborted and that error results.
603         //
604         // If normal verification fails then the handshake will abort before
605         // considering this callback. If normal verification is disabled by
606         // setting InsecureSkipVerify, or (for a server) when ClientAuth is
607         // RequestClientCert or RequireAnyClientCert, then this callback will
608         // be considered but the verifiedChains argument will always be nil.
609         //
610         // verifiedChains and its contents should not be modified.
611         VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
612
613         // VerifyConnection, if not nil, is called after normal certificate
614         // verification and after VerifyPeerCertificate by either a TLS client
615         // or server. If it returns a non-nil error, the handshake is aborted
616         // and that error results.
617         //
618         // If normal verification fails then the handshake will abort before
619         // considering this callback. This callback will run for all connections
620         // regardless of InsecureSkipVerify or ClientAuth settings.
621         VerifyConnection func(ConnectionState) error
622
623         // RootCAs defines the set of root certificate authorities
624         // that clients use when verifying server certificates.
625         // If RootCAs is nil, TLS uses the host's root CA set.
626         RootCAs *x509.CertPool
627
628         // NextProtos is a list of supported application level protocols, in
629         // order of preference. If both peers support ALPN, the selected
630         // protocol will be one from this list, and the connection will fail
631         // if there is no mutually supported protocol. If NextProtos is empty
632         // or the peer doesn't support ALPN, the connection will succeed and
633         // ConnectionState.NegotiatedProtocol will be empty.
634         NextProtos []string
635
636         // ServerName is used to verify the hostname on the returned
637         // certificates unless InsecureSkipVerify is given. It is also included
638         // in the client's handshake to support virtual hosting unless it is
639         // an IP address.
640         ServerName string
641
642         // ClientAuth determines the server's policy for
643         // TLS Client Authentication. The default is NoClientCert.
644         ClientAuth ClientAuthType
645
646         // ClientCAs defines the set of root certificate authorities
647         // that servers use if required to verify a client certificate
648         // by the policy in ClientAuth.
649         ClientCAs *x509.CertPool
650
651         // InsecureSkipVerify controls whether a client verifies the server's
652         // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
653         // accepts any certificate presented by the server and any host name in that
654         // certificate. In this mode, TLS is susceptible to machine-in-the-middle
655         // attacks unless custom verification is used. This should be used only for
656         // testing or in combination with VerifyConnection or VerifyPeerCertificate.
657         InsecureSkipVerify bool
658
659         // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
660         // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
661         //
662         // If CipherSuites is nil, a safe default list is used. The default cipher
663         // suites might change over time.
664         CipherSuites []uint16
665
666         // PreferServerCipherSuites is a legacy field and has no effect.
667         //
668         // It used to control whether the server would follow the client's or the
669         // server's preference. Servers now select the best mutually supported
670         // cipher suite based on logic that takes into account inferred client
671         // hardware, server hardware, and security.
672         //
673         // Deprecated: PreferServerCipherSuites is ignored.
674         PreferServerCipherSuites bool
675
676         // SessionTicketsDisabled may be set to true to disable session ticket and
677         // PSK (resumption) support. Note that on clients, session ticket support is
678         // also disabled if ClientSessionCache is nil.
679         SessionTicketsDisabled bool
680
681         // SessionTicketKey is used by TLS servers to provide session resumption.
682         // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
683         // with random data before the first server handshake.
684         //
685         // Deprecated: if this field is left at zero, session ticket keys will be
686         // automatically rotated every day and dropped after seven days. For
687         // customizing the rotation schedule or synchronizing servers that are
688         // terminating connections for the same host, use SetSessionTicketKeys.
689         SessionTicketKey [32]byte
690
691         // ClientSessionCache is a cache of ClientSessionState entries for TLS
692         // session resumption. It is only used by clients.
693         ClientSessionCache ClientSessionCache
694
695         // MinVersion contains the minimum TLS version that is acceptable.
696         //
697         // By default, TLS 1.2 is currently used as the minimum when acting as a
698         // client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
699         // supported by this package, both as a client and as a server.
700         //
701         // The client-side default can temporarily be reverted to TLS 1.0 by
702         // including the value "x509sha1=1" in the GODEBUG environment variable.
703         // Note that this option will be removed in Go 1.19 (but it will still be
704         // possible to set this field to VersionTLS10 explicitly).
705         MinVersion uint16
706
707         // MaxVersion contains the maximum TLS version that is acceptable.
708         //
709         // By default, the maximum version supported by this package is used,
710         // which is currently TLS 1.3.
711         MaxVersion uint16
712
713         // CurvePreferences contains the elliptic curves that will be used in
714         // an ECDHE handshake, in preference order. If empty, the default will
715         // be used. The client will use the first preference as the type for
716         // its key share in TLS 1.3. This may change in the future.
717         CurvePreferences []CurveID
718
719         // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
720         // When true, the largest possible TLS record size is always used. When
721         // false, the size of TLS records may be adjusted in an attempt to
722         // improve latency.
723         DynamicRecordSizingDisabled bool
724
725         // Renegotiation controls what types of renegotiation are supported.
726         // The default, none, is correct for the vast majority of applications.
727         Renegotiation RenegotiationSupport
728
729         // KeyLogWriter optionally specifies a destination for TLS master secrets
730         // in NSS key log format that can be used to allow external programs
731         // such as Wireshark to decrypt TLS connections.
732         // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
733         // Use of KeyLogWriter compromises security and should only be
734         // used for debugging.
735         KeyLogWriter io.Writer
736
737         // mutex protects sessionTicketKeys and autoSessionTicketKeys.
738         mutex sync.RWMutex
739         // sessionTicketKeys contains zero or more ticket keys. If set, it means
740         // the keys were set with SessionTicketKey or SetSessionTicketKeys. The
741         // first key is used for new tickets and any subsequent keys can be used to
742         // decrypt old tickets. The slice contents are not protected by the mutex
743         // and are immutable.
744         sessionTicketKeys []ticketKey
745         // autoSessionTicketKeys is like sessionTicketKeys but is owned by the
746         // auto-rotation logic. See Config.ticketKeys.
747         autoSessionTicketKeys []ticketKey
748 }
749
750 const (
751         // ticketKeyNameLen is the number of bytes of identifier that is prepended to
752         // an encrypted session ticket in order to identify the key used to encrypt it.
753         ticketKeyNameLen = 16
754
755         // ticketKeyLifetime is how long a ticket key remains valid and can be used to
756         // resume a client connection.
757         ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
758
759         // ticketKeyRotation is how often the server should rotate the session ticket key
760         // that is used for new tickets.
761         ticketKeyRotation = 24 * time.Hour
762 )
763
764 // ticketKey is the internal representation of a session ticket key.
765 type ticketKey struct {
766         // keyName is an opaque byte string that serves to identify the session
767         // ticket key. It's exposed as plaintext in every session ticket.
768         keyName [ticketKeyNameLen]byte
769         aesKey  [16]byte
770         hmacKey [16]byte
771         // created is the time at which this ticket key was created. See Config.ticketKeys.
772         created time.Time
773 }
774
775 // ticketKeyFromBytes converts from the external representation of a session
776 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
777 // bytes and this function expands that into sufficient name and key material.
778 func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
779         hashed := sha512.Sum512(b[:])
780         copy(key.keyName[:], hashed[:ticketKeyNameLen])
781         copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
782         copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
783         key.created = c.time()
784         return key
785 }
786
787 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
788 // ticket, and the lifetime we set for tickets we send.
789 const maxSessionTicketLifetime = 7 * 24 * time.Hour
790
791 // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
792 // being used concurrently by a TLS client or server.
793 func (c *Config) Clone() *Config {
794         if c == nil {
795                 return nil
796         }
797         c.mutex.RLock()
798         defer c.mutex.RUnlock()
799         return &Config{
800                 Rand:                        c.Rand,
801                 Time:                        c.Time,
802                 Certificates:                c.Certificates,
803                 NameToCertificate:           c.NameToCertificate,
804                 GetCertificate:              c.GetCertificate,
805                 GetClientCertificate:        c.GetClientCertificate,
806                 GetConfigForClient:          c.GetConfigForClient,
807                 VerifyPeerCertificate:       c.VerifyPeerCertificate,
808                 VerifyConnection:            c.VerifyConnection,
809                 RootCAs:                     c.RootCAs,
810                 NextProtos:                  c.NextProtos,
811                 ServerName:                  c.ServerName,
812                 ClientAuth:                  c.ClientAuth,
813                 ClientCAs:                   c.ClientCAs,
814                 InsecureSkipVerify:          c.InsecureSkipVerify,
815                 CipherSuites:                c.CipherSuites,
816                 PreferServerCipherSuites:    c.PreferServerCipherSuites,
817                 SessionTicketsDisabled:      c.SessionTicketsDisabled,
818                 SessionTicketKey:            c.SessionTicketKey,
819                 ClientSessionCache:          c.ClientSessionCache,
820                 MinVersion:                  c.MinVersion,
821                 MaxVersion:                  c.MaxVersion,
822                 CurvePreferences:            c.CurvePreferences,
823                 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
824                 Renegotiation:               c.Renegotiation,
825                 KeyLogWriter:                c.KeyLogWriter,
826                 sessionTicketKeys:           c.sessionTicketKeys,
827                 autoSessionTicketKeys:       c.autoSessionTicketKeys,
828         }
829 }
830
831 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
832 // randomized for backwards compatibility but is not in use.
833 var deprecatedSessionTicketKey = []byte("DEPRECATED")
834
835 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
836 // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
837 func (c *Config) initLegacySessionTicketKeyRLocked() {
838         // Don't write if SessionTicketKey is already defined as our deprecated string,
839         // or if it is defined by the user but sessionTicketKeys is already set.
840         if c.SessionTicketKey != [32]byte{} &&
841                 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
842                 return
843         }
844
845         // We need to write some data, so get an exclusive lock and re-check any conditions.
846         c.mutex.RUnlock()
847         defer c.mutex.RLock()
848         c.mutex.Lock()
849         defer c.mutex.Unlock()
850         if c.SessionTicketKey == [32]byte{} {
851                 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
852                         panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
853                 }
854                 // Write the deprecated prefix at the beginning so we know we created
855                 // it. This key with the DEPRECATED prefix isn't used as an actual
856                 // session ticket key, and is only randomized in case the application
857                 // reuses it for some reason.
858                 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
859         } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
860                 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
861         }
862
863 }
864
865 // ticketKeys returns the ticketKeys for this connection.
866 // If configForClient has explicitly set keys, those will
867 // be returned. Otherwise, the keys on c will be used and
868 // may be rotated if auto-managed.
869 // During rotation, any expired session ticket keys are deleted from
870 // c.sessionTicketKeys. If the session ticket key that is currently
871 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
872 // is not fresh, then a new session ticket key will be
873 // created and prepended to c.sessionTicketKeys.
874 func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
875         // If the ConfigForClient callback returned a Config with explicitly set
876         // keys, use those, otherwise just use the original Config.
877         if configForClient != nil {
878                 configForClient.mutex.RLock()
879                 if configForClient.SessionTicketsDisabled {
880                         return nil
881                 }
882                 configForClient.initLegacySessionTicketKeyRLocked()
883                 if len(configForClient.sessionTicketKeys) != 0 {
884                         ret := configForClient.sessionTicketKeys
885                         configForClient.mutex.RUnlock()
886                         return ret
887                 }
888                 configForClient.mutex.RUnlock()
889         }
890
891         c.mutex.RLock()
892         defer c.mutex.RUnlock()
893         if c.SessionTicketsDisabled {
894                 return nil
895         }
896         c.initLegacySessionTicketKeyRLocked()
897         if len(c.sessionTicketKeys) != 0 {
898                 return c.sessionTicketKeys
899         }
900         // Fast path for the common case where the key is fresh enough.
901         if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
902                 return c.autoSessionTicketKeys
903         }
904
905         // autoSessionTicketKeys are managed by auto-rotation.
906         c.mutex.RUnlock()
907         defer c.mutex.RLock()
908         c.mutex.Lock()
909         defer c.mutex.Unlock()
910         // Re-check the condition in case it changed since obtaining the new lock.
911         if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
912                 var newKey [32]byte
913                 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
914                         panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
915                 }
916                 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
917                 valid = append(valid, c.ticketKeyFromBytes(newKey))
918                 for _, k := range c.autoSessionTicketKeys {
919                         // While rotating the current key, also remove any expired ones.
920                         if c.time().Sub(k.created) < ticketKeyLifetime {
921                                 valid = append(valid, k)
922                         }
923                 }
924                 c.autoSessionTicketKeys = valid
925         }
926         return c.autoSessionTicketKeys
927 }
928
929 // SetSessionTicketKeys updates the session ticket keys for a server.
930 //
931 // The first key will be used when creating new tickets, while all keys can be
932 // used for decrypting tickets. It is safe to call this function while the
933 // server is running in order to rotate the session ticket keys. The function
934 // will panic if keys is empty.
935 //
936 // Calling this function will turn off automatic session ticket key rotation.
937 //
938 // If multiple servers are terminating connections for the same host they should
939 // all have the same session ticket keys. If the session ticket keys leaks,
940 // previously recorded and future TLS connections using those keys might be
941 // compromised.
942 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
943         if len(keys) == 0 {
944                 panic("tls: keys must have at least one key")
945         }
946
947         newKeys := make([]ticketKey, len(keys))
948         for i, bytes := range keys {
949                 newKeys[i] = c.ticketKeyFromBytes(bytes)
950         }
951
952         c.mutex.Lock()
953         c.sessionTicketKeys = newKeys
954         c.mutex.Unlock()
955 }
956
957 func (c *Config) rand() io.Reader {
958         r := c.Rand
959         if r == nil {
960                 return rand.Reader
961         }
962         return r
963 }
964
965 func (c *Config) time() time.Time {
966         t := c.Time
967         if t == nil {
968                 t = time.Now
969         }
970         return t()
971 }
972
973 func (c *Config) cipherSuites() []uint16 {
974         if needFIPS() {
975                 return fipsCipherSuites(c)
976         }
977         if c.CipherSuites != nil {
978                 return c.CipherSuites
979         }
980         return defaultCipherSuites
981 }
982
983 var supportedVersions = []uint16{
984         VersionTLS13,
985         VersionTLS12,
986         VersionTLS11,
987         VersionTLS10,
988 }
989
990 // roleClient and roleServer are meant to call supportedVersions and parents
991 // with more readability at the callsite.
992 const roleClient = true
993 const roleServer = false
994
995 func (c *Config) supportedVersions(isClient bool) []uint16 {
996         versions := make([]uint16, 0, len(supportedVersions))
997         for _, v := range supportedVersions {
998                 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
999                         continue
1000                 }
1001                 if (c == nil || c.MinVersion == 0) &&
1002                         isClient && v < VersionTLS12 {
1003                         continue
1004                 }
1005                 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
1006                         continue
1007                 }
1008                 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
1009                         continue
1010                 }
1011                 versions = append(versions, v)
1012         }
1013         return versions
1014 }
1015
1016 func (c *Config) maxSupportedVersion(isClient bool) uint16 {
1017         supportedVersions := c.supportedVersions(isClient)
1018         if len(supportedVersions) == 0 {
1019                 return 0
1020         }
1021         return supportedVersions[0]
1022 }
1023
1024 // supportedVersionsFromMax returns a list of supported versions derived from a
1025 // legacy maximum version value. Note that only versions supported by this
1026 // library are returned. Any newer peer will use supportedVersions anyway.
1027 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
1028         versions := make([]uint16, 0, len(supportedVersions))
1029         for _, v := range supportedVersions {
1030                 if v > maxVersion {
1031                         continue
1032                 }
1033                 versions = append(versions, v)
1034         }
1035         return versions
1036 }
1037
1038 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
1039
1040 func (c *Config) curvePreferences() []CurveID {
1041         if needFIPS() {
1042                 return fipsCurvePreferences(c)
1043         }
1044         if c == nil || len(c.CurvePreferences) == 0 {
1045                 return defaultCurvePreferences
1046         }
1047         return c.CurvePreferences
1048 }
1049
1050 func (c *Config) supportsCurve(curve CurveID) bool {
1051         for _, cc := range c.curvePreferences() {
1052                 if cc == curve {
1053                         return true
1054                 }
1055         }
1056         return false
1057 }
1058
1059 // mutualVersion returns the protocol version to use given the advertised
1060 // versions of the peer. Priority is given to the peer preference order.
1061 func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
1062         supportedVersions := c.supportedVersions(isClient)
1063         for _, peerVersion := range peerVersions {
1064                 for _, v := range supportedVersions {
1065                         if v == peerVersion {
1066                                 return v, true
1067                         }
1068                 }
1069         }
1070         return 0, false
1071 }
1072
1073 var errNoCertificates = errors.New("tls: no certificates configured")
1074
1075 // getCertificate returns the best certificate for the given ClientHelloInfo,
1076 // defaulting to the first element of c.Certificates.
1077 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1078         if c.GetCertificate != nil &&
1079                 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1080                 cert, err := c.GetCertificate(clientHello)
1081                 if cert != nil || err != nil {
1082                         return cert, err
1083                 }
1084         }
1085
1086         if len(c.Certificates) == 0 {
1087                 return nil, errNoCertificates
1088         }
1089
1090         if len(c.Certificates) == 1 {
1091                 // There's only one choice, so no point doing any work.
1092                 return &c.Certificates[0], nil
1093         }
1094
1095         if c.NameToCertificate != nil {
1096                 name := strings.ToLower(clientHello.ServerName)
1097                 if cert, ok := c.NameToCertificate[name]; ok {
1098                         return cert, nil
1099                 }
1100                 if len(name) > 0 {
1101                         labels := strings.Split(name, ".")
1102                         labels[0] = "*"
1103                         wildcardName := strings.Join(labels, ".")
1104                         if cert, ok := c.NameToCertificate[wildcardName]; ok {
1105                                 return cert, nil
1106                         }
1107                 }
1108         }
1109
1110         for _, cert := range c.Certificates {
1111                 if err := clientHello.SupportsCertificate(&cert); err == nil {
1112                         return &cert, nil
1113                 }
1114         }
1115
1116         // If nothing matches, return the first certificate.
1117         return &c.Certificates[0], nil
1118 }
1119
1120 // SupportsCertificate returns nil if the provided certificate is supported by
1121 // the client that sent the ClientHello. Otherwise, it returns an error
1122 // describing the reason for the incompatibility.
1123 //
1124 // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
1125 // callback, this method will take into account the associated Config. Note that
1126 // if GetConfigForClient returns a different Config, the change can't be
1127 // accounted for by this method.
1128 //
1129 // This function will call x509.ParseCertificate unless c.Leaf is set, which can
1130 // incur a significant performance cost.
1131 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1132         // Note we don't currently support certificate_authorities nor
1133         // signature_algorithms_cert, and don't check the algorithms of the
1134         // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1135         // Section 4.4.2.2).
1136
1137         config := chi.config
1138         if config == nil {
1139                 config = &Config{}
1140         }
1141         vers, ok := config.mutualVersion(roleServer, chi.SupportedVersions)
1142         if !ok {
1143                 return errors.New("no mutually supported protocol versions")
1144         }
1145
1146         // If the client specified the name they are trying to connect to, the
1147         // certificate needs to be valid for it.
1148         if chi.ServerName != "" {
1149                 x509Cert, err := c.leaf()
1150                 if err != nil {
1151                         return fmt.Errorf("failed to parse certificate: %w", err)
1152                 }
1153                 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1154                         return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1155                 }
1156         }
1157
1158         // supportsRSAFallback returns nil if the certificate and connection support
1159         // the static RSA key exchange, and unsupported otherwise. The logic for
1160         // supporting static RSA is completely disjoint from the logic for
1161         // supporting signed key exchanges, so we just check it as a fallback.
1162         supportsRSAFallback := func(unsupported error) error {
1163                 // TLS 1.3 dropped support for the static RSA key exchange.
1164                 if vers == VersionTLS13 {
1165                         return unsupported
1166                 }
1167                 // The static RSA key exchange works by decrypting a challenge with the
1168                 // RSA private key, not by signing, so check the PrivateKey implements
1169                 // crypto.Decrypter, like *rsa.PrivateKey does.
1170                 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1171                         if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1172                                 return unsupported
1173                         }
1174                 } else {
1175                         return unsupported
1176                 }
1177                 // Finally, there needs to be a mutual cipher suite that uses the static
1178                 // RSA key exchange instead of ECDHE.
1179                 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1180                         if c.flags&suiteECDHE != 0 {
1181                                 return false
1182                         }
1183                         if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1184                                 return false
1185                         }
1186                         return true
1187                 })
1188                 if rsaCipherSuite == nil {
1189                         return unsupported
1190                 }
1191                 return nil
1192         }
1193
1194         // If the client sent the signature_algorithms extension, ensure it supports
1195         // schemes we can use with this certificate and TLS version.
1196         if len(chi.SignatureSchemes) > 0 {
1197                 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1198                         return supportsRSAFallback(err)
1199                 }
1200         }
1201
1202         // In TLS 1.3 we are done because supported_groups is only relevant to the
1203         // ECDHE computation, point format negotiation is removed, cipher suites are
1204         // only relevant to the AEAD choice, and static RSA does not exist.
1205         if vers == VersionTLS13 {
1206                 return nil
1207         }
1208
1209         // The only signed key exchange we support is ECDHE.
1210         if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
1211                 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1212         }
1213
1214         var ecdsaCipherSuite bool
1215         if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1216                 switch pub := priv.Public().(type) {
1217                 case *ecdsa.PublicKey:
1218                         var curve CurveID
1219                         switch pub.Curve {
1220                         case elliptic.P256():
1221                                 curve = CurveP256
1222                         case elliptic.P384():
1223                                 curve = CurveP384
1224                         case elliptic.P521():
1225                                 curve = CurveP521
1226                         default:
1227                                 return supportsRSAFallback(unsupportedCertificateError(c))
1228                         }
1229                         var curveOk bool
1230                         for _, c := range chi.SupportedCurves {
1231                                 if c == curve && config.supportsCurve(c) {
1232                                         curveOk = true
1233                                         break
1234                                 }
1235                         }
1236                         if !curveOk {
1237                                 return errors.New("client doesn't support certificate curve")
1238                         }
1239                         ecdsaCipherSuite = true
1240                 case ed25519.PublicKey:
1241                         if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1242                                 return errors.New("connection doesn't support Ed25519")
1243                         }
1244                         ecdsaCipherSuite = true
1245                 case *rsa.PublicKey:
1246                 default:
1247                         return supportsRSAFallback(unsupportedCertificateError(c))
1248                 }
1249         } else {
1250                 return supportsRSAFallback(unsupportedCertificateError(c))
1251         }
1252
1253         // Make sure that there is a mutually supported cipher suite that works with
1254         // this certificate. Cipher suite selection will then apply the logic in
1255         // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1256         cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1257                 if c.flags&suiteECDHE == 0 {
1258                         return false
1259                 }
1260                 if c.flags&suiteECSign != 0 {
1261                         if !ecdsaCipherSuite {
1262                                 return false
1263                         }
1264                 } else {
1265                         if ecdsaCipherSuite {
1266                                 return false
1267                         }
1268                 }
1269                 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1270                         return false
1271                 }
1272                 return true
1273         })
1274         if cipherSuite == nil {
1275                 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1276         }
1277
1278         return nil
1279 }
1280
1281 // SupportsCertificate returns nil if the provided certificate is supported by
1282 // the server that sent the CertificateRequest. Otherwise, it returns an error
1283 // describing the reason for the incompatibility.
1284 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1285         if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1286                 return err
1287         }
1288
1289         if len(cri.AcceptableCAs) == 0 {
1290                 return nil
1291         }
1292
1293         for j, cert := range c.Certificate {
1294                 x509Cert := c.Leaf
1295                 // Parse the certificate if this isn't the leaf node, or if
1296                 // chain.Leaf was nil.
1297                 if j != 0 || x509Cert == nil {
1298                         var err error
1299                         if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1300                                 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1301                         }
1302                 }
1303
1304                 for _, ca := range cri.AcceptableCAs {
1305                         if bytes.Equal(x509Cert.RawIssuer, ca) {
1306                                 return nil
1307                         }
1308                 }
1309         }
1310         return errors.New("chain is not signed by an acceptable CA")
1311 }
1312
1313 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1314 // from the CommonName and SubjectAlternateName fields of each of the leaf
1315 // certificates.
1316 //
1317 // Deprecated: NameToCertificate only allows associating a single certificate
1318 // with a given name. Leave that field nil to let the library select the first
1319 // compatible chain from Certificates.
1320 func (c *Config) BuildNameToCertificate() {
1321         c.NameToCertificate = make(map[string]*Certificate)
1322         for i := range c.Certificates {
1323                 cert := &c.Certificates[i]
1324                 x509Cert, err := cert.leaf()
1325                 if err != nil {
1326                         continue
1327                 }
1328                 // If SANs are *not* present, some clients will consider the certificate
1329                 // valid for the name in the Common Name.
1330                 if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
1331                         c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1332                 }
1333                 for _, san := range x509Cert.DNSNames {
1334                         c.NameToCertificate[san] = cert
1335                 }
1336         }
1337 }
1338
1339 const (
1340         keyLogLabelTLS12           = "CLIENT_RANDOM"
1341         keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1342         keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1343         keyLogLabelClientTraffic   = "CLIENT_TRAFFIC_SECRET_0"
1344         keyLogLabelServerTraffic   = "SERVER_TRAFFIC_SECRET_0"
1345 )
1346
1347 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1348         if c.KeyLogWriter == nil {
1349                 return nil
1350         }
1351
1352         logLine := fmt.Appendf(nil, "%s %x %x\n", label, clientRandom, secret)
1353
1354         writerMutex.Lock()
1355         _, err := c.KeyLogWriter.Write(logLine)
1356         writerMutex.Unlock()
1357
1358         return err
1359 }
1360
1361 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1362 // and is only for debugging, so a global mutex saves space.
1363 var writerMutex sync.Mutex
1364
1365 // A Certificate is a chain of one or more certificates, leaf first.
1366 type Certificate struct {
1367         Certificate [][]byte
1368         // PrivateKey contains the private key corresponding to the public key in
1369         // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1370         // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1371         // an RSA PublicKey.
1372         PrivateKey crypto.PrivateKey
1373         // SupportedSignatureAlgorithms is an optional list restricting what
1374         // signature algorithms the PrivateKey can be used for.
1375         SupportedSignatureAlgorithms []SignatureScheme
1376         // OCSPStaple contains an optional OCSP response which will be served
1377         // to clients that request it.
1378         OCSPStaple []byte
1379         // SignedCertificateTimestamps contains an optional list of Signed
1380         // Certificate Timestamps which will be served to clients that request it.
1381         SignedCertificateTimestamps [][]byte
1382         // Leaf is the parsed form of the leaf certificate, which may be initialized
1383         // using x509.ParseCertificate to reduce per-handshake processing. If nil,
1384         // the leaf certificate will be parsed as needed.
1385         Leaf *x509.Certificate
1386 }
1387
1388 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1389 // the corresponding c.Certificate[0].
1390 func (c *Certificate) leaf() (*x509.Certificate, error) {
1391         if c.Leaf != nil {
1392                 return c.Leaf, nil
1393         }
1394         return x509.ParseCertificate(c.Certificate[0])
1395 }
1396
1397 type handshakeMessage interface {
1398         marshal() ([]byte, error)
1399         unmarshal([]byte) bool
1400 }
1401
1402 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1403 // caching strategy.
1404 type lruSessionCache struct {
1405         sync.Mutex
1406
1407         m        map[string]*list.Element
1408         q        *list.List
1409         capacity int
1410 }
1411
1412 type lruSessionCacheEntry struct {
1413         sessionKey string
1414         state      *ClientSessionState
1415 }
1416
1417 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1418 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1419 // is used instead.
1420 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1421         const defaultSessionCacheCapacity = 64
1422
1423         if capacity < 1 {
1424                 capacity = defaultSessionCacheCapacity
1425         }
1426         return &lruSessionCache{
1427                 m:        make(map[string]*list.Element),
1428                 q:        list.New(),
1429                 capacity: capacity,
1430         }
1431 }
1432
1433 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1434 // corresponding to sessionKey is removed from the cache instead.
1435 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1436         c.Lock()
1437         defer c.Unlock()
1438
1439         if elem, ok := c.m[sessionKey]; ok {
1440                 if cs == nil {
1441                         c.q.Remove(elem)
1442                         delete(c.m, sessionKey)
1443                 } else {
1444                         entry := elem.Value.(*lruSessionCacheEntry)
1445                         entry.state = cs
1446                         c.q.MoveToFront(elem)
1447                 }
1448                 return
1449         }
1450
1451         if c.q.Len() < c.capacity {
1452                 entry := &lruSessionCacheEntry{sessionKey, cs}
1453                 c.m[sessionKey] = c.q.PushFront(entry)
1454                 return
1455         }
1456
1457         elem := c.q.Back()
1458         entry := elem.Value.(*lruSessionCacheEntry)
1459         delete(c.m, entry.sessionKey)
1460         entry.sessionKey = sessionKey
1461         entry.state = cs
1462         c.q.MoveToFront(elem)
1463         c.m[sessionKey] = elem
1464 }
1465
1466 // Get returns the ClientSessionState value associated with a given key. It
1467 // returns (nil, false) if no value is found.
1468 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1469         c.Lock()
1470         defer c.Unlock()
1471
1472         if elem, ok := c.m[sessionKey]; ok {
1473                 c.q.MoveToFront(elem)
1474                 return elem.Value.(*lruSessionCacheEntry).state, true
1475         }
1476         return nil, false
1477 }
1478
1479 var emptyConfig Config
1480
1481 func defaultConfig() *Config {
1482         return &emptyConfig
1483 }
1484
1485 func unexpectedMessageError(wanted, got any) error {
1486         return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1487 }
1488
1489 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1490         for _, s := range supportedSignatureAlgorithms {
1491                 if s == sigAlg {
1492                         return true
1493                 }
1494         }
1495         return false
1496 }
1497
1498 // CertificateVerificationError is returned when certificate verification fails during the handshake.
1499 type CertificateVerificationError struct {
1500         // UnverifiedCertificates and its contents should not be modified.
1501         UnverifiedCertificates []*x509.Certificate
1502         Err                    error
1503 }
1504
1505 func (e *CertificateVerificationError) Error() string {
1506         return fmt.Sprintf("tls: failed to verify certificate: %s", e.Err)
1507 }
1508
1509 func (e *CertificateVerificationError) Unwrap() error {
1510         return e.Err
1511 }