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