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