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