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