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