]> 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         "container/list"
9         "crypto"
10         "crypto/internal/boring"
11         "crypto/rand"
12         "crypto/sha512"
13         "crypto/x509"
14         "errors"
15         "fmt"
16         "internal/cpu"
17         "io"
18         "math/big"
19         "net"
20         "os"
21         "strings"
22         "sync"
23         "time"
24 )
25
26 const (
27         VersionSSL30 = 0x0300
28         VersionTLS10 = 0x0301
29         VersionTLS11 = 0x0302
30         VersionTLS12 = 0x0303
31         VersionTLS13 = 0x0304
32 )
33
34 const (
35         maxPlaintext       = 16384        // maximum plaintext payload length
36         maxCiphertext      = 16384 + 2048 // maximum ciphertext payload length
37         maxCiphertextTLS13 = 16384 + 256  // maximum ciphertext length in TLS 1.3
38         recordHeaderLen    = 5            // record header length
39         maxHandshake       = 65536        // maximum handshake we support (protocol max is 16 MB)
40         maxUselessRecords  = 16           // maximum number of consecutive non-advancing records
41 )
42
43 // TLS record types.
44 type recordType uint8
45
46 const (
47         recordTypeChangeCipherSpec recordType = 20
48         recordTypeAlert            recordType = 21
49         recordTypeHandshake        recordType = 22
50         recordTypeApplicationData  recordType = 23
51 )
52
53 // TLS handshake message types.
54 const (
55         typeHelloRequest        uint8 = 0
56         typeClientHello         uint8 = 1
57         typeServerHello         uint8 = 2
58         typeNewSessionTicket    uint8 = 4
59         typeEndOfEarlyData      uint8 = 5
60         typeEncryptedExtensions uint8 = 8
61         typeCertificate         uint8 = 11
62         typeServerKeyExchange   uint8 = 12
63         typeCertificateRequest  uint8 = 13
64         typeServerHelloDone     uint8 = 14
65         typeCertificateVerify   uint8 = 15
66         typeClientKeyExchange   uint8 = 16
67         typeFinished            uint8 = 20
68         typeCertificateStatus   uint8 = 22
69         typeKeyUpdate           uint8 = 24
70         typeNextProtocol        uint8 = 67  // Not IANA assigned
71         typeMessageHash         uint8 = 254 // synthetic message
72 )
73
74 // TLS compression types.
75 const (
76         compressionNone uint8 = 0
77 )
78
79 // TLS extension numbers
80 const (
81         extensionServerName              uint16 = 0
82         extensionStatusRequest           uint16 = 5
83         extensionSupportedCurves         uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
84         extensionSupportedPoints         uint16 = 11
85         extensionSignatureAlgorithms     uint16 = 13
86         extensionALPN                    uint16 = 16
87         extensionSCT                     uint16 = 18
88         extensionSessionTicket           uint16 = 35
89         extensionPreSharedKey            uint16 = 41
90         extensionEarlyData               uint16 = 42
91         extensionSupportedVersions       uint16 = 43
92         extensionCookie                  uint16 = 44
93         extensionPSKModes                uint16 = 45
94         extensionCertificateAuthorities  uint16 = 47
95         extensionSignatureAlgorithmsCert uint16 = 50
96         extensionKeyShare                uint16 = 51
97         extensionNextProtoNeg            uint16 = 13172 // not IANA assigned
98         extensionRenegotiationInfo       uint16 = 0xff01
99 )
100
101 // TLS signaling cipher suite values
102 const (
103         scsvRenegotiation uint16 = 0x00ff
104 )
105
106 // CurveID is the type of a TLS identifier for an elliptic curve. See
107 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
108 //
109 // In TLS 1.3, this type is called NamedGroup, but at this time this library
110 // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
111 type CurveID uint16
112
113 const (
114         CurveP256 CurveID = 23
115         CurveP384 CurveID = 24
116         CurveP521 CurveID = 25
117         X25519    CurveID = 29
118 )
119
120 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
121 type keyShare struct {
122         group CurveID
123         data  []byte
124 }
125
126 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
127 const (
128         pskModePlain uint8 = 0
129         pskModeDHE   uint8 = 1
130 )
131
132 // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
133 // session. See RFC 8446, Section 4.2.11.
134 type pskIdentity struct {
135         label               []byte
136         obfuscatedTicketAge uint32
137 }
138
139 // TLS Elliptic Curve Point Formats
140 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
141 const (
142         pointFormatUncompressed uint8 = 0
143 )
144
145 // TLS CertificateStatusType (RFC 3546)
146 const (
147         statusTypeOCSP uint8 = 1
148 )
149
150 // Certificate types (for certificateRequestMsg)
151 const (
152         certTypeRSASign   = 1
153         certTypeECDSASign = 64 // RFC 4492, Section 5.5
154 )
155
156 // Signature algorithms (for internal signaling use). Starting at 16 to avoid overlap with
157 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
158 const (
159         signaturePKCS1v15 uint8 = iota + 16
160         signatureECDSA
161         signatureRSAPSS
162 )
163
164 // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
165 // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
166 // CertificateRequest. The two fields are merged to match with TLS 1.3.
167 // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
168 var defaultSupportedSignatureAlgorithms = []SignatureScheme{
169         PSSWithSHA256,
170         PSSWithSHA384,
171         PSSWithSHA512,
172         PKCS1WithSHA256,
173         ECDSAWithP256AndSHA256,
174         PKCS1WithSHA384,
175         ECDSAWithP384AndSHA384,
176         PKCS1WithSHA512,
177         ECDSAWithP521AndSHA512,
178         PKCS1WithSHA1,
179         ECDSAWithSHA1,
180 }
181
182 // helloRetryRequestRandom is set as the Random value of a ServerHello
183 // to signal that the message is actually a HelloRetryRequest.
184 var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
185         0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
186         0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
187         0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
188         0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
189 }
190
191 const (
192         // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
193         // random as a downgrade protection if the server would be capable of
194         // negotiating a higher version. See RFC 8446, Section 4.1.3.
195         downgradeCanaryTLS12 = "DOWNGRD\x01"
196         downgradeCanaryTLS11 = "DOWNGRD\x00"
197 )
198
199 // ConnectionState records basic TLS details about the connection.
200 type ConnectionState struct {
201         Version                     uint16                // TLS version used by the connection (e.g. VersionTLS12)
202         HandshakeComplete           bool                  // TLS handshake is complete
203         DidResume                   bool                  // connection resumes a previous TLS connection
204         CipherSuite                 uint16                // cipher suite in use (TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, ...)
205         NegotiatedProtocol          string                // negotiated next protocol (not guaranteed to be from Config.NextProtos)
206         NegotiatedProtocolIsMutual  bool                  // negotiated protocol was advertised by server (client side only)
207         ServerName                  string                // server name requested by client, if any (server side only)
208         PeerCertificates            []*x509.Certificate   // certificate chain presented by remote peer
209         VerifiedChains              [][]*x509.Certificate // verified chains built from PeerCertificates
210         SignedCertificateTimestamps [][]byte              // SCTs from the peer, if any
211         OCSPResponse                []byte                // stapled OCSP response from peer, if any
212
213         // ekm is a closure exposed via ExportKeyingMaterial.
214         ekm func(label string, context []byte, length int) ([]byte, error)
215
216         // TLSUnique contains the "tls-unique" channel binding value (see RFC
217         // 5929, section 3). For resumed sessions this value will be nil
218         // because resumption does not include enough context (see
219         // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
220         // change in future versions of Go once the TLS master-secret fix has
221         // been standardized and implemented. It is not defined in TLS 1.3.
222         TLSUnique []byte
223 }
224
225 // ExportKeyingMaterial returns length bytes of exported key material in a new
226 // slice as defined in RFC 5705. If context is nil, it is not used as part of
227 // the seed. If the connection was set to allow renegotiation via
228 // Config.Renegotiation, this function will return an error.
229 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
230         return cs.ekm(label, context, length)
231 }
232
233 // ClientAuthType declares the policy the server will follow for
234 // TLS Client Authentication.
235 type ClientAuthType int
236
237 const (
238         NoClientCert ClientAuthType = iota
239         RequestClientCert
240         RequireAnyClientCert
241         VerifyClientCertIfGiven
242         RequireAndVerifyClientCert
243 )
244
245 // requiresClientCert reports whether the ClientAuthType requires a client
246 // certificate to be provided.
247 func requiresClientCert(c ClientAuthType) bool {
248         switch c {
249         case RequireAnyClientCert, RequireAndVerifyClientCert:
250                 return true
251         default:
252                 return false
253         }
254 }
255
256 // ClientSessionState contains the state needed by clients to resume TLS
257 // sessions.
258 type ClientSessionState struct {
259         sessionTicket      []uint8               // Encrypted ticket used for session resumption with server
260         vers               uint16                // SSL/TLS version negotiated for the session
261         cipherSuite        uint16                // Ciphersuite negotiated for the session
262         masterSecret       []byte                // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
263         serverCertificates []*x509.Certificate   // Certificate chain presented by the server
264         verifiedChains     [][]*x509.Certificate // Certificate chains we built for verification
265         receivedAt         time.Time             // When the session ticket was received from the server
266
267         // TLS 1.3 fields.
268         nonce  []byte    // Ticket nonce sent by the server, to derive PSK
269         useBy  time.Time // Expiration of the ticket lifetime as set by the server
270         ageAdd uint32    // Random obfuscation factor for sending the ticket age
271 }
272
273 // ClientSessionCache is a cache of ClientSessionState objects that can be used
274 // by a client to resume a TLS session with a given server. ClientSessionCache
275 // implementations should expect to be called concurrently from different
276 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
277 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
278 // are supported via this interface.
279 type ClientSessionCache interface {
280         // Get searches for a ClientSessionState associated with the given key.
281         // On return, ok is true if one was found.
282         Get(sessionKey string) (session *ClientSessionState, ok bool)
283
284         // Put adds the ClientSessionState to the cache with the given key. It might
285         // get called multiple times in a connection if a TLS 1.3 server provides
286         // more than one session ticket. If called with a nil *ClientSessionState,
287         // it should remove the cache entry.
288         Put(sessionKey string, cs *ClientSessionState)
289 }
290
291 // SignatureScheme identifies a signature algorithm supported by TLS. See
292 // RFC 8446, Section 4.2.3.
293 type SignatureScheme uint16
294
295 const (
296         // RSASSA-PKCS1-v1_5 algorithms.
297         PKCS1WithSHA256 SignatureScheme = 0x0401
298         PKCS1WithSHA384 SignatureScheme = 0x0501
299         PKCS1WithSHA512 SignatureScheme = 0x0601
300
301         // RSASSA-PSS algorithms with public key OID rsaEncryption.
302         PSSWithSHA256 SignatureScheme = 0x0804
303         PSSWithSHA384 SignatureScheme = 0x0805
304         PSSWithSHA512 SignatureScheme = 0x0806
305
306         // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
307         ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
308         ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
309         ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
310
311         // Legacy signature and hash algorithms for TLS 1.2.
312         PKCS1WithSHA1 SignatureScheme = 0x0201
313         ECDSAWithSHA1 SignatureScheme = 0x0203
314 )
315
316 // ClientHelloInfo contains information from a ClientHello message in order to
317 // guide certificate selection in the GetCertificate callback.
318 type ClientHelloInfo struct {
319         // CipherSuites lists the CipherSuites supported by the client (e.g.
320         // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
321         CipherSuites []uint16
322
323         // ServerName indicates the name of the server requested by the client
324         // in order to support virtual hosting. ServerName is only set if the
325         // client is using SNI (see RFC 4366, Section 3.1).
326         ServerName string
327
328         // SupportedCurves lists the elliptic curves supported by the client.
329         // SupportedCurves is set only if the Supported Elliptic Curves
330         // Extension is being used (see RFC 4492, Section 5.1.1).
331         SupportedCurves []CurveID
332
333         // SupportedPoints lists the point formats supported by the client.
334         // SupportedPoints is set only if the Supported Point Formats Extension
335         // is being used (see RFC 4492, Section 5.1.2).
336         SupportedPoints []uint8
337
338         // SignatureSchemes lists the signature and hash schemes that the client
339         // is willing to verify. SignatureSchemes is set only if the Signature
340         // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
341         SignatureSchemes []SignatureScheme
342
343         // SupportedProtos lists the application protocols supported by the client.
344         // SupportedProtos is set only if the Application-Layer Protocol
345         // Negotiation Extension is being used (see RFC 7301, Section 3.1).
346         //
347         // Servers can select a protocol by setting Config.NextProtos in a
348         // GetConfigForClient return value.
349         SupportedProtos []string
350
351         // SupportedVersions lists the TLS versions supported by the client.
352         // For TLS versions less than 1.3, this is extrapolated from the max
353         // version advertised by the client, so values other than the greatest
354         // might be rejected if used.
355         SupportedVersions []uint16
356
357         // Conn is the underlying net.Conn for the connection. Do not read
358         // from, or write to, this connection; that will cause the TLS
359         // connection to fail.
360         Conn net.Conn
361 }
362
363 // CertificateRequestInfo contains information from a server's
364 // CertificateRequest message, which is used to demand a certificate and proof
365 // of control from a client.
366 type CertificateRequestInfo struct {
367         // AcceptableCAs contains zero or more, DER-encoded, X.501
368         // Distinguished Names. These are the names of root or intermediate CAs
369         // that the server wishes the returned certificate to be signed by. An
370         // empty slice indicates that the server has no preference.
371         AcceptableCAs [][]byte
372
373         // SignatureSchemes lists the signature schemes that the server is
374         // willing to verify.
375         SignatureSchemes []SignatureScheme
376 }
377
378 // RenegotiationSupport enumerates the different levels of support for TLS
379 // renegotiation. TLS renegotiation is the act of performing subsequent
380 // handshakes on a connection after the first. This significantly complicates
381 // the state machine and has been the source of numerous, subtle security
382 // issues. Initiating a renegotiation is not supported, but support for
383 // accepting renegotiation requests may be enabled.
384 //
385 // Even when enabled, the server may not change its identity between handshakes
386 // (i.e. the leaf certificate must be the same). Additionally, concurrent
387 // handshake and application data flow is not permitted so renegotiation can
388 // only be used with protocols that synchronise with the renegotiation, such as
389 // HTTPS.
390 //
391 // Renegotiation is not defined in TLS 1.3.
392 type RenegotiationSupport int
393
394 const (
395         // RenegotiateNever disables renegotiation.
396         RenegotiateNever RenegotiationSupport = iota
397
398         // RenegotiateOnceAsClient allows a remote server to request
399         // renegotiation once per connection.
400         RenegotiateOnceAsClient
401
402         // RenegotiateFreelyAsClient allows a remote server to repeatedly
403         // request renegotiation.
404         RenegotiateFreelyAsClient
405 )
406
407 // A Config structure is used to configure a TLS client or server.
408 // After one has been passed to a TLS function it must not be
409 // modified. A Config may be reused; the tls package will also not
410 // modify it.
411 type Config struct {
412         // Rand provides the source of entropy for nonces and RSA blinding.
413         // If Rand is nil, TLS uses the cryptographic random reader in package
414         // crypto/rand.
415         // The Reader must be safe for use by multiple goroutines.
416         Rand io.Reader
417
418         // Time returns the current time as the number of seconds since the epoch.
419         // If Time is nil, TLS uses time.Now.
420         Time func() time.Time
421
422         // Certificates contains one or more certificate chains to present to
423         // the other side of the connection. Server configurations must include
424         // at least one certificate or else set GetCertificate. Clients doing
425         // client-authentication may set either Certificates or
426         // GetClientCertificate.
427         Certificates []Certificate
428
429         // NameToCertificate maps from a certificate name to an element of
430         // Certificates. Note that a certificate name can be of the form
431         // '*.example.com' and so doesn't have to be a domain name as such.
432         // See Config.BuildNameToCertificate
433         // The nil value causes the first element of Certificates to be used
434         // for all connections.
435         NameToCertificate map[string]*Certificate
436
437         // GetCertificate returns a Certificate based on the given
438         // ClientHelloInfo. It will only be called if the client supplies SNI
439         // information or if Certificates is empty.
440         //
441         // If GetCertificate is nil or returns nil, then the certificate is
442         // retrieved from NameToCertificate. If NameToCertificate is nil, the
443         // first element of Certificates will be used.
444         GetCertificate func(*ClientHelloInfo) (*Certificate, error)
445
446         // GetClientCertificate, if not nil, is called when a server requests a
447         // certificate from a client. If set, the contents of Certificates will
448         // be ignored.
449         //
450         // If GetClientCertificate returns an error, the handshake will be
451         // aborted and that error will be returned. Otherwise
452         // GetClientCertificate must return a non-nil Certificate. If
453         // Certificate.Certificate is empty then no certificate will be sent to
454         // the server. If this is unacceptable to the server then it may abort
455         // the handshake.
456         //
457         // GetClientCertificate may be called multiple times for the same
458         // connection if renegotiation occurs or if TLS 1.3 is in use.
459         GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
460
461         // GetConfigForClient, if not nil, is called after a ClientHello is
462         // received from a client. It may return a non-nil Config in order to
463         // change the Config that will be used to handle this connection. If
464         // the returned Config is nil, the original Config will be used. The
465         // Config returned by this callback may not be subsequently modified.
466         //
467         // If GetConfigForClient is nil, the Config passed to Server() will be
468         // used for all connections.
469         //
470         // Uniquely for the fields in the returned Config, session ticket keys
471         // will be duplicated from the original Config if not set.
472         // Specifically, if SetSessionTicketKeys was called on the original
473         // config but not on the returned config then the ticket keys from the
474         // original config will be copied into the new config before use.
475         // Otherwise, if SessionTicketKey was set in the original config but
476         // not in the returned config then it will be copied into the returned
477         // config before use. If neither of those cases applies then the key
478         // material from the returned config will be used for session tickets.
479         GetConfigForClient func(*ClientHelloInfo) (*Config, error)
480
481         // VerifyPeerCertificate, if not nil, is called after normal
482         // certificate verification by either a TLS client or server. It
483         // receives the raw ASN.1 certificates provided by the peer and also
484         // any verified chains that normal processing found. If it returns a
485         // non-nil error, the handshake is aborted and that error results.
486         //
487         // If normal verification fails then the handshake will abort before
488         // considering this callback. If normal verification is disabled by
489         // setting InsecureSkipVerify, or (for a server) when ClientAuth is
490         // RequestClientCert or RequireAnyClientCert, then this callback will
491         // be considered but the verifiedChains argument will always be nil.
492         VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
493
494         // RootCAs defines the set of root certificate authorities
495         // that clients use when verifying server certificates.
496         // If RootCAs is nil, TLS uses the host's root CA set.
497         RootCAs *x509.CertPool
498
499         // NextProtos is a list of supported application level protocols, in
500         // order of preference.
501         NextProtos []string
502
503         // ServerName is used to verify the hostname on the returned
504         // certificates unless InsecureSkipVerify is given. It is also included
505         // in the client's handshake to support virtual hosting unless it is
506         // an IP address.
507         ServerName string
508
509         // ClientAuth determines the server's policy for
510         // TLS Client Authentication. The default is NoClientCert.
511         ClientAuth ClientAuthType
512
513         // ClientCAs defines the set of root certificate authorities
514         // that servers use if required to verify a client certificate
515         // by the policy in ClientAuth.
516         ClientCAs *x509.CertPool
517
518         // InsecureSkipVerify controls whether a client verifies the
519         // server's certificate chain and host name.
520         // If InsecureSkipVerify is true, TLS accepts any certificate
521         // presented by the server and any host name in that certificate.
522         // In this mode, TLS is susceptible to man-in-the-middle attacks.
523         // This should be used only for testing.
524         InsecureSkipVerify bool
525
526         // CipherSuites is a list of supported cipher suites for TLS versions up to
527         // TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites
528         // is used, with a preference order based on hardware performance. The
529         // default cipher suites might change over Go versions. Note that TLS 1.3
530         // ciphersuites are not configurable.
531         CipherSuites []uint16
532
533         // PreferServerCipherSuites controls whether the server selects the
534         // client's most preferred ciphersuite, or the server's most preferred
535         // ciphersuite. If true then the server's preference, as expressed in
536         // the order of elements in CipherSuites, is used.
537         PreferServerCipherSuites bool
538
539         // SessionTicketsDisabled may be set to true to disable session ticket and
540         // PSK (resumption) support. Note that on clients, session ticket support is
541         // also disabled if ClientSessionCache is nil.
542         SessionTicketsDisabled bool
543
544         // SessionTicketKey is used by TLS servers to provide session resumption.
545         // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
546         // with random data before the first server handshake.
547         //
548         // If multiple servers are terminating connections for the same host
549         // they should all have the same SessionTicketKey. If the
550         // SessionTicketKey leaks, previously recorded and future TLS
551         // connections using that key might be compromised.
552         SessionTicketKey [32]byte
553
554         // ClientSessionCache is a cache of ClientSessionState entries for TLS
555         // session resumption. It is only used by clients.
556         ClientSessionCache ClientSessionCache
557
558         // MinVersion contains the minimum SSL/TLS version that is acceptable.
559         // If zero, then TLS 1.0 is taken as the minimum.
560         MinVersion uint16
561
562         // MaxVersion contains the maximum SSL/TLS version that is acceptable.
563         // If zero, then the maximum version supported by this package is used,
564         // which is currently TLS 1.3.
565         MaxVersion uint16
566
567         // CurvePreferences contains the elliptic curves that will be used in
568         // an ECDHE handshake, in preference order. If empty, the default will
569         // be used. The client will use the first preference as the type for
570         // its key share in TLS 1.3. This may change in the future.
571         CurvePreferences []CurveID
572
573         // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
574         // When true, the largest possible TLS record size is always used. When
575         // false, the size of TLS records may be adjusted in an attempt to
576         // improve latency.
577         DynamicRecordSizingDisabled bool
578
579         // Renegotiation controls what types of renegotiation are supported.
580         // The default, none, is correct for the vast majority of applications.
581         Renegotiation RenegotiationSupport
582
583         // KeyLogWriter optionally specifies a destination for TLS master secrets
584         // in NSS key log format that can be used to allow external programs
585         // such as Wireshark to decrypt TLS connections.
586         // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
587         // Use of KeyLogWriter compromises security and should only be
588         // used for debugging.
589         KeyLogWriter io.Writer
590
591         serverInitOnce sync.Once // guards calling (*Config).serverInit
592
593         // mutex protects sessionTicketKeys.
594         mutex sync.RWMutex
595         // sessionTicketKeys contains zero or more ticket keys. If the length
596         // is zero, SessionTicketsDisabled must be true. The first key is used
597         // for new tickets and any subsequent keys can be used to decrypt old
598         // tickets.
599         sessionTicketKeys []ticketKey
600 }
601
602 // ticketKeyNameLen is the number of bytes of identifier that is prepended to
603 // an encrypted session ticket in order to identify the key used to encrypt it.
604 const ticketKeyNameLen = 16
605
606 // ticketKey is the internal representation of a session ticket key.
607 type ticketKey struct {
608         // keyName is an opaque byte string that serves to identify the session
609         // ticket key. It's exposed as plaintext in every session ticket.
610         keyName [ticketKeyNameLen]byte
611         aesKey  [16]byte
612         hmacKey [16]byte
613 }
614
615 // ticketKeyFromBytes converts from the external representation of a session
616 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
617 // bytes and this function expands that into sufficient name and key material.
618 func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
619         hashed := sha512.Sum512(b[:])
620         copy(key.keyName[:], hashed[:ticketKeyNameLen])
621         copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
622         copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
623         return key
624 }
625
626 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
627 // ticket, and the lifetime we set for tickets we send.
628 const maxSessionTicketLifetime = 7 * 24 * time.Hour
629
630 // Clone returns a shallow clone of c. It is safe to clone a Config that is
631 // being used concurrently by a TLS client or server.
632 func (c *Config) Clone() *Config {
633         // Running serverInit ensures that it's safe to read
634         // SessionTicketsDisabled.
635         c.serverInitOnce.Do(func() { c.serverInit(nil) })
636
637         var sessionTicketKeys []ticketKey
638         c.mutex.RLock()
639         sessionTicketKeys = c.sessionTicketKeys
640         c.mutex.RUnlock()
641
642         return &Config{
643                 Rand:                        c.Rand,
644                 Time:                        c.Time,
645                 Certificates:                c.Certificates,
646                 NameToCertificate:           c.NameToCertificate,
647                 GetCertificate:              c.GetCertificate,
648                 GetClientCertificate:        c.GetClientCertificate,
649                 GetConfigForClient:          c.GetConfigForClient,
650                 VerifyPeerCertificate:       c.VerifyPeerCertificate,
651                 RootCAs:                     c.RootCAs,
652                 NextProtos:                  c.NextProtos,
653                 ServerName:                  c.ServerName,
654                 ClientAuth:                  c.ClientAuth,
655                 ClientCAs:                   c.ClientCAs,
656                 InsecureSkipVerify:          c.InsecureSkipVerify,
657                 CipherSuites:                c.CipherSuites,
658                 PreferServerCipherSuites:    c.PreferServerCipherSuites,
659                 SessionTicketsDisabled:      c.SessionTicketsDisabled,
660                 SessionTicketKey:            c.SessionTicketKey,
661                 ClientSessionCache:          c.ClientSessionCache,
662                 MinVersion:                  c.MinVersion,
663                 MaxVersion:                  c.MaxVersion,
664                 CurvePreferences:            c.CurvePreferences,
665                 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
666                 Renegotiation:               c.Renegotiation,
667                 KeyLogWriter:                c.KeyLogWriter,
668                 sessionTicketKeys:           sessionTicketKeys,
669         }
670 }
671
672 // serverInit is run under c.serverInitOnce to do initialization of c. If c was
673 // returned by a GetConfigForClient callback then the argument should be the
674 // Config that was passed to Server, otherwise it should be nil.
675 func (c *Config) serverInit(originalConfig *Config) {
676         if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
677                 return
678         }
679
680         alreadySet := false
681         for _, b := range c.SessionTicketKey {
682                 if b != 0 {
683                         alreadySet = true
684                         break
685                 }
686         }
687
688         if !alreadySet {
689                 if originalConfig != nil {
690                         copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
691                 } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
692                         c.SessionTicketsDisabled = true
693                         return
694                 }
695         }
696
697         if originalConfig != nil {
698                 originalConfig.mutex.RLock()
699                 c.sessionTicketKeys = originalConfig.sessionTicketKeys
700                 originalConfig.mutex.RUnlock()
701         } else {
702                 c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
703         }
704 }
705
706 func (c *Config) ticketKeys() []ticketKey {
707         c.mutex.RLock()
708         // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
709         // will only update it by replacing it with a new value.
710         ret := c.sessionTicketKeys
711         c.mutex.RUnlock()
712         return ret
713 }
714
715 // SetSessionTicketKeys updates the session ticket keys for a server. The first
716 // key will be used when creating new tickets, while all keys can be used for
717 // decrypting tickets. It is safe to call this function while the server is
718 // running in order to rotate the session ticket keys. The function will panic
719 // if keys is empty.
720 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
721         if len(keys) == 0 {
722                 panic("tls: keys must have at least one key")
723         }
724
725         newKeys := make([]ticketKey, len(keys))
726         for i, bytes := range keys {
727                 newKeys[i] = ticketKeyFromBytes(bytes)
728         }
729
730         c.mutex.Lock()
731         c.sessionTicketKeys = newKeys
732         c.mutex.Unlock()
733 }
734
735 func (c *Config) rand() io.Reader {
736         r := c.Rand
737         if r == nil {
738                 return rand.Reader
739         }
740         return r
741 }
742
743 func (c *Config) time() time.Time {
744         t := c.Time
745         if t == nil {
746                 t = time.Now
747         }
748         return t()
749 }
750
751 func (c *Config) cipherSuites() []uint16 {
752         if needFIPS() {
753                 return fipsCipherSuites(c)
754         }
755         s := c.CipherSuites
756         if s == nil {
757                 s = defaultCipherSuites()
758         }
759         return s
760 }
761
762 var supportedVersions = []uint16{
763         VersionTLS13,
764         VersionTLS12,
765         VersionTLS11,
766         VersionTLS10,
767         VersionSSL30,
768 }
769
770 func (c *Config) supportedVersions(isClient bool) []uint16 {
771         versions := make([]uint16, 0, len(supportedVersions))
772         for _, v := range supportedVersions {
773                 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
774                         continue
775                 }
776                 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
777                         continue
778                 }
779                 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
780                         continue
781                 }
782                 // TLS 1.0 is the minimum version supported as a client.
783                 if isClient && v < VersionTLS10 {
784                         continue
785                 }
786                 // TLS 1.3 is opt-in in Go 1.12.
787                 if v == VersionTLS13 && !isTLS13Supported() {
788                         continue
789                 }
790                 versions = append(versions, v)
791         }
792         return versions
793 }
794
795 // tls13Support caches the result for isTLS13Supported.
796 var tls13Support struct {
797         sync.Once
798         cached bool
799 }
800
801 // isTLS13Supported returns whether the program opted into TLS 1.3 via
802 // GODEBUG=tls13=1. It's cached after the first execution.
803 func isTLS13Supported() bool {
804         tls13Support.Do(func() {
805                 tls13Support.cached = goDebugString("tls13") == "1"
806         })
807         return tls13Support.cached
808 }
809
810 // goDebugString returns the value of the named GODEBUG key.
811 // GODEBUG is of the form "key=val,key2=val2".
812 func goDebugString(key string) string {
813         s := os.Getenv("GODEBUG")
814         for i := 0; i < len(s)-len(key)-1; i++ {
815                 if i > 0 && s[i-1] != ',' {
816                         continue
817                 }
818                 afterKey := s[i+len(key):]
819                 if afterKey[0] != '=' || s[i:i+len(key)] != key {
820                         continue
821                 }
822                 val := afterKey[1:]
823                 for i, b := range val {
824                         if b == ',' {
825                                 return val[:i]
826                         }
827                 }
828                 return val
829         }
830         return ""
831 }
832
833 func (c *Config) maxSupportedVersion(isClient bool) uint16 {
834         supportedVersions := c.supportedVersions(isClient)
835         if len(supportedVersions) == 0 {
836                 return 0
837         }
838         return supportedVersions[0]
839 }
840
841 // supportedVersionsFromMax returns a list of supported versions derived from a
842 // legacy maximum version value. Note that only versions supported by this
843 // library are returned. Any newer peer will use supportedVersions anyway.
844 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
845         versions := make([]uint16, 0, len(supportedVersions))
846         for _, v := range supportedVersions {
847                 if v > maxVersion {
848                         continue
849                 }
850                 versions = append(versions, v)
851         }
852         return versions
853 }
854
855 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
856
857 func (c *Config) curvePreferences() []CurveID {
858         if needFIPS() {
859                 return fipsCurvePreferences(c)
860         }
861         if c == nil || len(c.CurvePreferences) == 0 {
862                 return defaultCurvePreferences
863         }
864         return c.CurvePreferences
865 }
866
867 // mutualVersion returns the protocol version to use given the advertised
868 // versions of the peer. Priority is given to the peer preference order.
869 func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
870         supportedVersions := c.supportedVersions(isClient)
871         for _, peerVersion := range peerVersions {
872                 for _, v := range supportedVersions {
873                         if v == peerVersion {
874                                 return v, true
875                         }
876                 }
877         }
878         return 0, false
879 }
880
881 // getCertificate returns the best certificate for the given ClientHelloInfo,
882 // defaulting to the first element of c.Certificates.
883 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
884         if c.GetCertificate != nil &&
885                 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
886                 cert, err := c.GetCertificate(clientHello)
887                 if cert != nil || err != nil {
888                         return cert, err
889                 }
890         }
891
892         if len(c.Certificates) == 0 {
893                 return nil, errors.New("tls: no certificates configured")
894         }
895
896         if len(c.Certificates) == 1 || c.NameToCertificate == nil {
897                 // There's only one choice, so no point doing any work.
898                 return &c.Certificates[0], nil
899         }
900
901         name := strings.ToLower(clientHello.ServerName)
902         for len(name) > 0 && name[len(name)-1] == '.' {
903                 name = name[:len(name)-1]
904         }
905
906         if cert, ok := c.NameToCertificate[name]; ok {
907                 return cert, nil
908         }
909
910         // try replacing labels in the name with wildcards until we get a
911         // match.
912         labels := strings.Split(name, ".")
913         for i := range labels {
914                 labels[i] = "*"
915                 candidate := strings.Join(labels, ".")
916                 if cert, ok := c.NameToCertificate[candidate]; ok {
917                         return cert, nil
918                 }
919         }
920
921         // If nothing matches, return the first certificate.
922         return &c.Certificates[0], nil
923 }
924
925 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
926 // from the CommonName and SubjectAlternateName fields of each of the leaf
927 // certificates.
928 func (c *Config) BuildNameToCertificate() {
929         c.NameToCertificate = make(map[string]*Certificate)
930         for i := range c.Certificates {
931                 cert := &c.Certificates[i]
932                 x509Cert := cert.Leaf
933                 if x509Cert == nil {
934                         var err error
935                         x509Cert, err = x509.ParseCertificate(cert.Certificate[0])
936                         if err != nil {
937                                 continue
938                         }
939                 }
940                 if len(x509Cert.Subject.CommonName) > 0 {
941                         c.NameToCertificate[x509Cert.Subject.CommonName] = cert
942                 }
943                 for _, san := range x509Cert.DNSNames {
944                         c.NameToCertificate[san] = cert
945                 }
946         }
947 }
948
949 const (
950         keyLogLabelTLS12           = "CLIENT_RANDOM"
951         keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
952         keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
953         keyLogLabelClientTraffic   = "CLIENT_TRAFFIC_SECRET_0"
954         keyLogLabelServerTraffic   = "SERVER_TRAFFIC_SECRET_0"
955 )
956
957 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
958         if c.KeyLogWriter == nil {
959                 return nil
960         }
961
962         logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
963
964         writerMutex.Lock()
965         _, err := c.KeyLogWriter.Write(logLine)
966         writerMutex.Unlock()
967
968         return err
969 }
970
971 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
972 // and is only for debugging, so a global mutex saves space.
973 var writerMutex sync.Mutex
974
975 // A Certificate is a chain of one or more certificates, leaf first.
976 type Certificate struct {
977         Certificate [][]byte
978         // PrivateKey contains the private key corresponding to the public key in
979         // Leaf. This must implement crypto.Signer with an RSA or ECDSA PublicKey.
980         // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
981         // an RSA PublicKey.
982         PrivateKey crypto.PrivateKey
983         // OCSPStaple contains an optional OCSP response which will be served
984         // to clients that request it.
985         OCSPStaple []byte
986         // SignedCertificateTimestamps contains an optional list of Signed
987         // Certificate Timestamps which will be served to clients that request it.
988         SignedCertificateTimestamps [][]byte
989         // Leaf is the parsed form of the leaf certificate, which may be
990         // initialized using x509.ParseCertificate to reduce per-handshake
991         // processing for TLS clients doing client authentication. If nil, the
992         // leaf certificate will be parsed as needed.
993         Leaf *x509.Certificate
994 }
995
996 type handshakeMessage interface {
997         marshal() []byte
998         unmarshal([]byte) bool
999 }
1000
1001 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1002 // caching strategy.
1003 type lruSessionCache struct {
1004         sync.Mutex
1005
1006         m        map[string]*list.Element
1007         q        *list.List
1008         capacity int
1009 }
1010
1011 type lruSessionCacheEntry struct {
1012         sessionKey string
1013         state      *ClientSessionState
1014 }
1015
1016 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1017 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1018 // is used instead.
1019 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1020         const defaultSessionCacheCapacity = 64
1021
1022         if capacity < 1 {
1023                 capacity = defaultSessionCacheCapacity
1024         }
1025         return &lruSessionCache{
1026                 m:        make(map[string]*list.Element),
1027                 q:        list.New(),
1028                 capacity: capacity,
1029         }
1030 }
1031
1032 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1033 // corresponding to sessionKey is removed from the cache instead.
1034 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1035         c.Lock()
1036         defer c.Unlock()
1037
1038         if elem, ok := c.m[sessionKey]; ok {
1039                 if cs == nil {
1040                         c.q.Remove(elem)
1041                         delete(c.m, sessionKey)
1042                 } else {
1043                         entry := elem.Value.(*lruSessionCacheEntry)
1044                         entry.state = cs
1045                         c.q.MoveToFront(elem)
1046                 }
1047                 return
1048         }
1049
1050         if c.q.Len() < c.capacity {
1051                 entry := &lruSessionCacheEntry{sessionKey, cs}
1052                 c.m[sessionKey] = c.q.PushFront(entry)
1053                 return
1054         }
1055
1056         elem := c.q.Back()
1057         entry := elem.Value.(*lruSessionCacheEntry)
1058         delete(c.m, entry.sessionKey)
1059         entry.sessionKey = sessionKey
1060         entry.state = cs
1061         c.q.MoveToFront(elem)
1062         c.m[sessionKey] = elem
1063 }
1064
1065 // Get returns the ClientSessionState value associated with a given key. It
1066 // returns (nil, false) if no value is found.
1067 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1068         c.Lock()
1069         defer c.Unlock()
1070
1071         if elem, ok := c.m[sessionKey]; ok {
1072                 c.q.MoveToFront(elem)
1073                 return elem.Value.(*lruSessionCacheEntry).state, true
1074         }
1075         return nil, false
1076 }
1077
1078 // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1079 type dsaSignature struct {
1080         R, S *big.Int
1081 }
1082
1083 type ecdsaSignature dsaSignature
1084
1085 var emptyConfig Config
1086
1087 func defaultConfig() *Config {
1088         return &emptyConfig
1089 }
1090
1091 var (
1092         once                        sync.Once
1093         varDefaultCipherSuites      []uint16
1094         varDefaultCipherSuitesTLS13 []uint16
1095 )
1096
1097 func defaultCipherSuites() []uint16 {
1098         once.Do(initDefaultCipherSuites)
1099         return varDefaultCipherSuites
1100 }
1101
1102 func defaultCipherSuitesTLS13() []uint16 {
1103         once.Do(initDefaultCipherSuites)
1104         return varDefaultCipherSuitesTLS13
1105 }
1106
1107 func initDefaultCipherSuites() {
1108         var topCipherSuites []uint16
1109
1110         // Check the cpu flags for each platform that has optimized GCM implementations.
1111         // Worst case, these variables will just all be false.
1112         var (
1113                 hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
1114                 hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
1115                 // Keep in sync with crypto/aes/cipher_s390x.go.
1116                 hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
1117
1118                 hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
1119         )
1120
1121         if hasGCMAsm || boring.Enabled {
1122                 // If BoringCrypto is enabled, always prioritize AES-GCM.
1123                 // If AES-GCM hardware is provided then prioritise AES-GCM
1124                 // cipher suites.
1125                 topCipherSuites = []uint16{
1126                         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1127                         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1128                         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1129                         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1130                         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1131                         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1132                 }
1133                 varDefaultCipherSuitesTLS13 = []uint16{
1134                         TLS_AES_128_GCM_SHA256,
1135                         TLS_CHACHA20_POLY1305_SHA256,
1136                         TLS_AES_256_GCM_SHA384,
1137                 }
1138         } else {
1139                 // Without AES-GCM hardware, we put the ChaCha20-Poly1305
1140                 // cipher suites first.
1141                 topCipherSuites = []uint16{
1142                         TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1143                         TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1144                         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1145                         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1146                         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1147                         TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1148                 }
1149                 varDefaultCipherSuitesTLS13 = []uint16{
1150                         TLS_CHACHA20_POLY1305_SHA256,
1151                         TLS_AES_128_GCM_SHA256,
1152                         TLS_AES_256_GCM_SHA384,
1153                 }
1154         }
1155
1156         varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
1157         varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
1158
1159 NextCipherSuite:
1160         for _, suite := range cipherSuites {
1161                 if suite.flags&suiteDefaultOff != 0 {
1162                         continue
1163                 }
1164                 for _, existing := range varDefaultCipherSuites {
1165                         if existing == suite.id {
1166                                 continue NextCipherSuite
1167                         }
1168                 }
1169                 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1170         }
1171 }
1172
1173 func unexpectedMessageError(wanted, got interface{}) error {
1174         return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1175 }
1176
1177 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1178         for _, s := range supportedSignatureAlgorithms {
1179                 if s == sigAlg {
1180                         return true
1181                 }
1182         }
1183         return false
1184 }
1185
1186 // signatureFromSignatureScheme maps a signature algorithm to the underlying
1187 // signature method (without hash function).
1188 func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
1189         switch signatureAlgorithm {
1190         case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
1191                 return signaturePKCS1v15
1192         case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
1193                 return signatureRSAPSS
1194         case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
1195                 return signatureECDSA
1196         default:
1197                 return 0
1198         }
1199 }