]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/common.go
[dev.boringcrypto] crypto/hmac: merge up to 2a206c7 and skip test
[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 server's
604         // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
605         // accepts any certificate presented by the server and any host name in that
606         // certificate. In this mode, TLS is susceptible to machine-in-the-middle
607         // attacks unless custom verification is used. This should be used only for
608         // testing or in combination with VerifyConnection or VerifyPeerCertificate.
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 or nil if c is nil. 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         if c == nil {
734                 return nil
735         }
736         c.mutex.RLock()
737         defer c.mutex.RUnlock()
738         return &Config{
739                 Rand:                        c.Rand,
740                 Time:                        c.Time,
741                 Certificates:                c.Certificates,
742                 NameToCertificate:           c.NameToCertificate,
743                 GetCertificate:              c.GetCertificate,
744                 GetClientCertificate:        c.GetClientCertificate,
745                 GetConfigForClient:          c.GetConfigForClient,
746                 VerifyPeerCertificate:       c.VerifyPeerCertificate,
747                 VerifyConnection:            c.VerifyConnection,
748                 RootCAs:                     c.RootCAs,
749                 NextProtos:                  c.NextProtos,
750                 ServerName:                  c.ServerName,
751                 ClientAuth:                  c.ClientAuth,
752                 ClientCAs:                   c.ClientCAs,
753                 InsecureSkipVerify:          c.InsecureSkipVerify,
754                 CipherSuites:                c.CipherSuites,
755                 PreferServerCipherSuites:    c.PreferServerCipherSuites,
756                 SessionTicketsDisabled:      c.SessionTicketsDisabled,
757                 SessionTicketKey:            c.SessionTicketKey,
758                 ClientSessionCache:          c.ClientSessionCache,
759                 MinVersion:                  c.MinVersion,
760                 MaxVersion:                  c.MaxVersion,
761                 CurvePreferences:            c.CurvePreferences,
762                 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
763                 Renegotiation:               c.Renegotiation,
764                 KeyLogWriter:                c.KeyLogWriter,
765                 sessionTicketKeys:           c.sessionTicketKeys,
766                 autoSessionTicketKeys:       c.autoSessionTicketKeys,
767         }
768 }
769
770 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
771 // randomized for backwards compatibility but is not in use.
772 var deprecatedSessionTicketKey = []byte("DEPRECATED")
773
774 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
775 // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
776 func (c *Config) initLegacySessionTicketKeyRLocked() {
777         // Don't write if SessionTicketKey is already defined as our deprecated string,
778         // or if it is defined by the user but sessionTicketKeys is already set.
779         if c.SessionTicketKey != [32]byte{} &&
780                 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
781                 return
782         }
783
784         // We need to write some data, so get an exclusive lock and re-check any conditions.
785         c.mutex.RUnlock()
786         defer c.mutex.RLock()
787         c.mutex.Lock()
788         defer c.mutex.Unlock()
789         if c.SessionTicketKey == [32]byte{} {
790                 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
791                         panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
792                 }
793                 // Write the deprecated prefix at the beginning so we know we created
794                 // it. This key with the DEPRECATED prefix isn't used as an actual
795                 // session ticket key, and is only randomized in case the application
796                 // reuses it for some reason.
797                 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
798         } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
799                 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
800         }
801
802 }
803
804 // ticketKeys returns the ticketKeys for this connection.
805 // If configForClient has explicitly set keys, those will
806 // be returned. Otherwise, the keys on c will be used and
807 // may be rotated if auto-managed.
808 // During rotation, any expired session ticket keys are deleted from
809 // c.sessionTicketKeys. If the session ticket key that is currently
810 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
811 // is not fresh, then a new session ticket key will be
812 // created and prepended to c.sessionTicketKeys.
813 func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
814         // If the ConfigForClient callback returned a Config with explicitly set
815         // keys, use those, otherwise just use the original Config.
816         if configForClient != nil {
817                 configForClient.mutex.RLock()
818                 if configForClient.SessionTicketsDisabled {
819                         return nil
820                 }
821                 configForClient.initLegacySessionTicketKeyRLocked()
822                 if len(configForClient.sessionTicketKeys) != 0 {
823                         ret := configForClient.sessionTicketKeys
824                         configForClient.mutex.RUnlock()
825                         return ret
826                 }
827                 configForClient.mutex.RUnlock()
828         }
829
830         c.mutex.RLock()
831         defer c.mutex.RUnlock()
832         if c.SessionTicketsDisabled {
833                 return nil
834         }
835         c.initLegacySessionTicketKeyRLocked()
836         if len(c.sessionTicketKeys) != 0 {
837                 return c.sessionTicketKeys
838         }
839         // Fast path for the common case where the key is fresh enough.
840         if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
841                 return c.autoSessionTicketKeys
842         }
843
844         // autoSessionTicketKeys are managed by auto-rotation.
845         c.mutex.RUnlock()
846         defer c.mutex.RLock()
847         c.mutex.Lock()
848         defer c.mutex.Unlock()
849         // Re-check the condition in case it changed since obtaining the new lock.
850         if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
851                 var newKey [32]byte
852                 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
853                         panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
854                 }
855                 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
856                 valid = append(valid, c.ticketKeyFromBytes(newKey))
857                 for _, k := range c.autoSessionTicketKeys {
858                         // While rotating the current key, also remove any expired ones.
859                         if c.time().Sub(k.created) < ticketKeyLifetime {
860                                 valid = append(valid, k)
861                         }
862                 }
863                 c.autoSessionTicketKeys = valid
864         }
865         return c.autoSessionTicketKeys
866 }
867
868 // SetSessionTicketKeys updates the session ticket keys for a server.
869 //
870 // The first key will be used when creating new tickets, while all keys can be
871 // used for decrypting tickets. It is safe to call this function while the
872 // server is running in order to rotate the session ticket keys. The function
873 // will panic if keys is empty.
874 //
875 // Calling this function will turn off automatic session ticket key rotation.
876 //
877 // If multiple servers are terminating connections for the same host they should
878 // all have the same session ticket keys. If the session ticket keys leaks,
879 // previously recorded and future TLS connections using those keys might be
880 // compromised.
881 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
882         if len(keys) == 0 {
883                 panic("tls: keys must have at least one key")
884         }
885
886         newKeys := make([]ticketKey, len(keys))
887         for i, bytes := range keys {
888                 newKeys[i] = c.ticketKeyFromBytes(bytes)
889         }
890
891         c.mutex.Lock()
892         c.sessionTicketKeys = newKeys
893         c.mutex.Unlock()
894 }
895
896 func (c *Config) rand() io.Reader {
897         r := c.Rand
898         if r == nil {
899                 return rand.Reader
900         }
901         return r
902 }
903
904 func (c *Config) time() time.Time {
905         t := c.Time
906         if t == nil {
907                 t = time.Now
908         }
909         return t()
910 }
911
912 func (c *Config) cipherSuites() []uint16 {
913         if needFIPS() {
914                 return fipsCipherSuites(c)
915         }
916         s := c.CipherSuites
917         if s == nil {
918                 s = defaultCipherSuites()
919         }
920         return s
921 }
922
923 var supportedVersions = []uint16{
924         VersionTLS13,
925         VersionTLS12,
926         VersionTLS11,
927         VersionTLS10,
928 }
929
930 func (c *Config) supportedVersions() []uint16 {
931         versions := make([]uint16, 0, len(supportedVersions))
932         for _, v := range supportedVersions {
933                 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
934                         continue
935                 }
936                 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
937                         continue
938                 }
939                 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
940                         continue
941                 }
942                 versions = append(versions, v)
943         }
944         return versions
945 }
946
947 func (c *Config) maxSupportedVersion() uint16 {
948         supportedVersions := c.supportedVersions()
949         if len(supportedVersions) == 0 {
950                 return 0
951         }
952         return supportedVersions[0]
953 }
954
955 // supportedVersionsFromMax returns a list of supported versions derived from a
956 // legacy maximum version value. Note that only versions supported by this
957 // library are returned. Any newer peer will use supportedVersions anyway.
958 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
959         versions := make([]uint16, 0, len(supportedVersions))
960         for _, v := range supportedVersions {
961                 if v > maxVersion {
962                         continue
963                 }
964                 versions = append(versions, v)
965         }
966         return versions
967 }
968
969 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
970
971 func (c *Config) curvePreferences() []CurveID {
972         if needFIPS() {
973                 return fipsCurvePreferences(c)
974         }
975         if c == nil || len(c.CurvePreferences) == 0 {
976                 return defaultCurvePreferences
977         }
978         return c.CurvePreferences
979 }
980
981 func (c *Config) supportsCurve(curve CurveID) bool {
982         for _, cc := range c.curvePreferences() {
983                 if cc == curve {
984                         return true
985                 }
986         }
987         return false
988 }
989
990 // mutualVersion returns the protocol version to use given the advertised
991 // versions of the peer. Priority is given to the peer preference order.
992 func (c *Config) mutualVersion(peerVersions []uint16) (uint16, bool) {
993         supportedVersions := c.supportedVersions()
994         for _, peerVersion := range peerVersions {
995                 for _, v := range supportedVersions {
996                         if v == peerVersion {
997                                 return v, true
998                         }
999                 }
1000         }
1001         return 0, false
1002 }
1003
1004 var errNoCertificates = errors.New("tls: no certificates configured")
1005
1006 // getCertificate returns the best certificate for the given ClientHelloInfo,
1007 // defaulting to the first element of c.Certificates.
1008 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1009         if c.GetCertificate != nil &&
1010                 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1011                 cert, err := c.GetCertificate(clientHello)
1012                 if cert != nil || err != nil {
1013                         return cert, err
1014                 }
1015         }
1016
1017         if len(c.Certificates) == 0 {
1018                 return nil, errNoCertificates
1019         }
1020
1021         if len(c.Certificates) == 1 {
1022                 // There's only one choice, so no point doing any work.
1023                 return &c.Certificates[0], nil
1024         }
1025
1026         if c.NameToCertificate != nil {
1027                 name := strings.ToLower(clientHello.ServerName)
1028                 if cert, ok := c.NameToCertificate[name]; ok {
1029                         return cert, nil
1030                 }
1031                 if len(name) > 0 {
1032                         labels := strings.Split(name, ".")
1033                         labels[0] = "*"
1034                         wildcardName := strings.Join(labels, ".")
1035                         if cert, ok := c.NameToCertificate[wildcardName]; ok {
1036                                 return cert, nil
1037                         }
1038                 }
1039         }
1040
1041         for _, cert := range c.Certificates {
1042                 if err := clientHello.SupportsCertificate(&cert); err == nil {
1043                         return &cert, nil
1044                 }
1045         }
1046
1047         // If nothing matches, return the first certificate.
1048         return &c.Certificates[0], nil
1049 }
1050
1051 // SupportsCertificate returns nil if the provided certificate is supported by
1052 // the client that sent the ClientHello. Otherwise, it returns an error
1053 // describing the reason for the incompatibility.
1054 //
1055 // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
1056 // callback, this method will take into account the associated Config. Note that
1057 // if GetConfigForClient returns a different Config, the change can't be
1058 // accounted for by this method.
1059 //
1060 // This function will call x509.ParseCertificate unless c.Leaf is set, which can
1061 // incur a significant performance cost.
1062 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1063         // Note we don't currently support certificate_authorities nor
1064         // signature_algorithms_cert, and don't check the algorithms of the
1065         // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1066         // Section 4.4.2.2).
1067
1068         config := chi.config
1069         if config == nil {
1070                 config = &Config{}
1071         }
1072         vers, ok := config.mutualVersion(chi.SupportedVersions)
1073         if !ok {
1074                 return errors.New("no mutually supported protocol versions")
1075         }
1076
1077         // If the client specified the name they are trying to connect to, the
1078         // certificate needs to be valid for it.
1079         if chi.ServerName != "" {
1080                 x509Cert, err := c.leaf()
1081                 if err != nil {
1082                         return fmt.Errorf("failed to parse certificate: %w", err)
1083                 }
1084                 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1085                         return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1086                 }
1087         }
1088
1089         // supportsRSAFallback returns nil if the certificate and connection support
1090         // the static RSA key exchange, and unsupported otherwise. The logic for
1091         // supporting static RSA is completely disjoint from the logic for
1092         // supporting signed key exchanges, so we just check it as a fallback.
1093         supportsRSAFallback := func(unsupported error) error {
1094                 // TLS 1.3 dropped support for the static RSA key exchange.
1095                 if vers == VersionTLS13 {
1096                         return unsupported
1097                 }
1098                 // The static RSA key exchange works by decrypting a challenge with the
1099                 // RSA private key, not by signing, so check the PrivateKey implements
1100                 // crypto.Decrypter, like *rsa.PrivateKey does.
1101                 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1102                         if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1103                                 return unsupported
1104                         }
1105                 } else {
1106                         return unsupported
1107                 }
1108                 // Finally, there needs to be a mutual cipher suite that uses the static
1109                 // RSA key exchange instead of ECDHE.
1110                 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1111                         if c.flags&suiteECDHE != 0 {
1112                                 return false
1113                         }
1114                         if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1115                                 return false
1116                         }
1117                         return true
1118                 })
1119                 if rsaCipherSuite == nil {
1120                         return unsupported
1121                 }
1122                 return nil
1123         }
1124
1125         // If the client sent the signature_algorithms extension, ensure it supports
1126         // schemes we can use with this certificate and TLS version.
1127         if len(chi.SignatureSchemes) > 0 {
1128                 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1129                         return supportsRSAFallback(err)
1130                 }
1131         }
1132
1133         // In TLS 1.3 we are done because supported_groups is only relevant to the
1134         // ECDHE computation, point format negotiation is removed, cipher suites are
1135         // only relevant to the AEAD choice, and static RSA does not exist.
1136         if vers == VersionTLS13 {
1137                 return nil
1138         }
1139
1140         // The only signed key exchange we support is ECDHE.
1141         if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
1142                 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1143         }
1144
1145         var ecdsaCipherSuite bool
1146         if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1147                 switch pub := priv.Public().(type) {
1148                 case *ecdsa.PublicKey:
1149                         var curve CurveID
1150                         switch pub.Curve {
1151                         case elliptic.P256():
1152                                 curve = CurveP256
1153                         case elliptic.P384():
1154                                 curve = CurveP384
1155                         case elliptic.P521():
1156                                 curve = CurveP521
1157                         default:
1158                                 return supportsRSAFallback(unsupportedCertificateError(c))
1159                         }
1160                         var curveOk bool
1161                         for _, c := range chi.SupportedCurves {
1162                                 if c == curve && config.supportsCurve(c) {
1163                                         curveOk = true
1164                                         break
1165                                 }
1166                         }
1167                         if !curveOk {
1168                                 return errors.New("client doesn't support certificate curve")
1169                         }
1170                         ecdsaCipherSuite = true
1171                 case ed25519.PublicKey:
1172                         if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1173                                 return errors.New("connection doesn't support Ed25519")
1174                         }
1175                         ecdsaCipherSuite = true
1176                 case *rsa.PublicKey:
1177                 default:
1178                         return supportsRSAFallback(unsupportedCertificateError(c))
1179                 }
1180         } else {
1181                 return supportsRSAFallback(unsupportedCertificateError(c))
1182         }
1183
1184         // Make sure that there is a mutually supported cipher suite that works with
1185         // this certificate. Cipher suite selection will then apply the logic in
1186         // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1187         cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1188                 if c.flags&suiteECDHE == 0 {
1189                         return false
1190                 }
1191                 if c.flags&suiteECSign != 0 {
1192                         if !ecdsaCipherSuite {
1193                                 return false
1194                         }
1195                 } else {
1196                         if ecdsaCipherSuite {
1197                                 return false
1198                         }
1199                 }
1200                 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1201                         return false
1202                 }
1203                 return true
1204         })
1205         if cipherSuite == nil {
1206                 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1207         }
1208
1209         return nil
1210 }
1211
1212 // SupportsCertificate returns nil if the provided certificate is supported by
1213 // the server that sent the CertificateRequest. Otherwise, it returns an error
1214 // describing the reason for the incompatibility.
1215 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1216         if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1217                 return err
1218         }
1219
1220         if len(cri.AcceptableCAs) == 0 {
1221                 return nil
1222         }
1223
1224         for j, cert := range c.Certificate {
1225                 x509Cert := c.Leaf
1226                 // Parse the certificate if this isn't the leaf node, or if
1227                 // chain.Leaf was nil.
1228                 if j != 0 || x509Cert == nil {
1229                         var err error
1230                         if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1231                                 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1232                         }
1233                 }
1234
1235                 for _, ca := range cri.AcceptableCAs {
1236                         if bytes.Equal(x509Cert.RawIssuer, ca) {
1237                                 return nil
1238                         }
1239                 }
1240         }
1241         return errors.New("chain is not signed by an acceptable CA")
1242 }
1243
1244 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1245 // from the CommonName and SubjectAlternateName fields of each of the leaf
1246 // certificates.
1247 //
1248 // Deprecated: NameToCertificate only allows associating a single certificate
1249 // with a given name. Leave that field nil to let the library select the first
1250 // compatible chain from Certificates.
1251 func (c *Config) BuildNameToCertificate() {
1252         c.NameToCertificate = make(map[string]*Certificate)
1253         for i := range c.Certificates {
1254                 cert := &c.Certificates[i]
1255                 x509Cert, err := cert.leaf()
1256                 if err != nil {
1257                         continue
1258                 }
1259                 if len(x509Cert.Subject.CommonName) > 0 {
1260                         c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1261                 }
1262                 for _, san := range x509Cert.DNSNames {
1263                         c.NameToCertificate[san] = cert
1264                 }
1265         }
1266 }
1267
1268 const (
1269         keyLogLabelTLS12           = "CLIENT_RANDOM"
1270         keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1271         keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1272         keyLogLabelClientTraffic   = "CLIENT_TRAFFIC_SECRET_0"
1273         keyLogLabelServerTraffic   = "SERVER_TRAFFIC_SECRET_0"
1274 )
1275
1276 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1277         if c.KeyLogWriter == nil {
1278                 return nil
1279         }
1280
1281         logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
1282
1283         writerMutex.Lock()
1284         _, err := c.KeyLogWriter.Write(logLine)
1285         writerMutex.Unlock()
1286
1287         return err
1288 }
1289
1290 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1291 // and is only for debugging, so a global mutex saves space.
1292 var writerMutex sync.Mutex
1293
1294 // A Certificate is a chain of one or more certificates, leaf first.
1295 type Certificate struct {
1296         Certificate [][]byte
1297         // PrivateKey contains the private key corresponding to the public key in
1298         // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1299         // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1300         // an RSA PublicKey.
1301         PrivateKey crypto.PrivateKey
1302         // SupportedSignatureAlgorithms is an optional list restricting what
1303         // signature algorithms the PrivateKey can be used for.
1304         SupportedSignatureAlgorithms []SignatureScheme
1305         // OCSPStaple contains an optional OCSP response which will be served
1306         // to clients that request it.
1307         OCSPStaple []byte
1308         // SignedCertificateTimestamps contains an optional list of Signed
1309         // Certificate Timestamps which will be served to clients that request it.
1310         SignedCertificateTimestamps [][]byte
1311         // Leaf is the parsed form of the leaf certificate, which may be initialized
1312         // using x509.ParseCertificate to reduce per-handshake processing. If nil,
1313         // the leaf certificate will be parsed as needed.
1314         Leaf *x509.Certificate
1315 }
1316
1317 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1318 // the corresponding c.Certificate[0].
1319 func (c *Certificate) leaf() (*x509.Certificate, error) {
1320         if c.Leaf != nil {
1321                 return c.Leaf, nil
1322         }
1323         return x509.ParseCertificate(c.Certificate[0])
1324 }
1325
1326 type handshakeMessage interface {
1327         marshal() []byte
1328         unmarshal([]byte) bool
1329 }
1330
1331 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1332 // caching strategy.
1333 type lruSessionCache struct {
1334         sync.Mutex
1335
1336         m        map[string]*list.Element
1337         q        *list.List
1338         capacity int
1339 }
1340
1341 type lruSessionCacheEntry struct {
1342         sessionKey string
1343         state      *ClientSessionState
1344 }
1345
1346 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1347 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1348 // is used instead.
1349 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1350         const defaultSessionCacheCapacity = 64
1351
1352         if capacity < 1 {
1353                 capacity = defaultSessionCacheCapacity
1354         }
1355         return &lruSessionCache{
1356                 m:        make(map[string]*list.Element),
1357                 q:        list.New(),
1358                 capacity: capacity,
1359         }
1360 }
1361
1362 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1363 // corresponding to sessionKey is removed from the cache instead.
1364 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1365         c.Lock()
1366         defer c.Unlock()
1367
1368         if elem, ok := c.m[sessionKey]; ok {
1369                 if cs == nil {
1370                         c.q.Remove(elem)
1371                         delete(c.m, sessionKey)
1372                 } else {
1373                         entry := elem.Value.(*lruSessionCacheEntry)
1374                         entry.state = cs
1375                         c.q.MoveToFront(elem)
1376                 }
1377                 return
1378         }
1379
1380         if c.q.Len() < c.capacity {
1381                 entry := &lruSessionCacheEntry{sessionKey, cs}
1382                 c.m[sessionKey] = c.q.PushFront(entry)
1383                 return
1384         }
1385
1386         elem := c.q.Back()
1387         entry := elem.Value.(*lruSessionCacheEntry)
1388         delete(c.m, entry.sessionKey)
1389         entry.sessionKey = sessionKey
1390         entry.state = cs
1391         c.q.MoveToFront(elem)
1392         c.m[sessionKey] = elem
1393 }
1394
1395 // Get returns the ClientSessionState value associated with a given key. It
1396 // returns (nil, false) if no value is found.
1397 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1398         c.Lock()
1399         defer c.Unlock()
1400
1401         if elem, ok := c.m[sessionKey]; ok {
1402                 c.q.MoveToFront(elem)
1403                 return elem.Value.(*lruSessionCacheEntry).state, true
1404         }
1405         return nil, false
1406 }
1407
1408 var emptyConfig Config
1409
1410 func defaultConfig() *Config {
1411         return &emptyConfig
1412 }
1413
1414 var (
1415         once                        sync.Once
1416         varDefaultCipherSuites      []uint16
1417         varDefaultCipherSuitesTLS13 []uint16
1418 )
1419
1420 func defaultCipherSuites() []uint16 {
1421         once.Do(initDefaultCipherSuites)
1422         return varDefaultCipherSuites
1423 }
1424
1425 func defaultCipherSuitesTLS13() []uint16 {
1426         once.Do(initDefaultCipherSuites)
1427         return varDefaultCipherSuitesTLS13
1428 }
1429
1430 func initDefaultCipherSuites() {
1431         var topCipherSuites []uint16
1432
1433         // Check the cpu flags for each platform that has optimized GCM implementations.
1434         // Worst case, these variables will just all be false.
1435         var (
1436                 hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
1437                 hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
1438                 // Keep in sync with crypto/aes/cipher_s390x.go.
1439                 hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
1440
1441                 hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
1442         )
1443
1444         if hasGCMAsm || boringEnabled {
1445                 // If BoringCrypto is enabled, always prioritize AES-GCM.
1446                 // If AES-GCM hardware is provided then prioritise AES-GCM
1447                 // cipher suites.
1448                 topCipherSuites = []uint16{
1449                         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1450                         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1451                         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1452                         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1453                         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1454                         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1455                 }
1456                 varDefaultCipherSuitesTLS13 = []uint16{
1457                         TLS_AES_128_GCM_SHA256,
1458                         TLS_CHACHA20_POLY1305_SHA256,
1459                         TLS_AES_256_GCM_SHA384,
1460                 }
1461         } else {
1462                 // Without AES-GCM hardware, we put the ChaCha20-Poly1305
1463                 // cipher suites first.
1464                 topCipherSuites = []uint16{
1465                         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1466                         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1467                         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1468                         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1469                         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1470                         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1471                 }
1472                 varDefaultCipherSuitesTLS13 = []uint16{
1473                         TLS_CHACHA20_POLY1305_SHA256,
1474                         TLS_AES_128_GCM_SHA256,
1475                         TLS_AES_256_GCM_SHA384,
1476                 }
1477         }
1478
1479         varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
1480         varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
1481
1482 NextCipherSuite:
1483         for _, suite := range cipherSuites {
1484                 if suite.flags&suiteDefaultOff != 0 {
1485                         continue
1486                 }
1487                 for _, existing := range varDefaultCipherSuites {
1488                         if existing == suite.id {
1489                                 continue NextCipherSuite
1490                         }
1491                 }
1492                 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1493         }
1494 }
1495
1496 func unexpectedMessageError(wanted, got interface{}) error {
1497         return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1498 }
1499
1500 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1501         for _, s := range supportedSignatureAlgorithms {
1502                 if s == sigAlg {
1503                         return true
1504                 }
1505         }
1506         return false
1507 }