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