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.
34 maxPlaintext = 16384 // maximum plaintext payload length
35 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
36 maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3
37 recordHeaderLen = 5 // record header length
38 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
39 maxUselessRecords = 16 // maximum number of consecutive non-advancing records
46 recordTypeChangeCipherSpec recordType = 20
47 recordTypeAlert recordType = 21
48 recordTypeHandshake recordType = 22
49 recordTypeApplicationData recordType = 23
52 // TLS handshake message types.
54 typeHelloRequest uint8 = 0
55 typeClientHello uint8 = 1
56 typeServerHello uint8 = 2
57 typeNewSessionTicket uint8 = 4
58 typeEndOfEarlyData uint8 = 5
59 typeEncryptedExtensions uint8 = 8
60 typeCertificate uint8 = 11
61 typeServerKeyExchange uint8 = 12
62 typeCertificateRequest uint8 = 13
63 typeServerHelloDone uint8 = 14
64 typeCertificateVerify uint8 = 15
65 typeClientKeyExchange uint8 = 16
66 typeFinished uint8 = 20
67 typeCertificateStatus uint8 = 22
68 typeKeyUpdate uint8 = 24
69 typeNextProtocol uint8 = 67 // Not IANA assigned
70 typeMessageHash uint8 = 254 // synthetic message
73 // TLS compression types.
75 compressionNone uint8 = 0
78 // TLS extension numbers
80 extensionServerName uint16 = 0
81 extensionStatusRequest uint16 = 5
82 extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
83 extensionSupportedPoints uint16 = 11
84 extensionSignatureAlgorithms uint16 = 13
85 extensionALPN uint16 = 16
86 extensionSCT uint16 = 18
87 extensionSessionTicket uint16 = 35
88 extensionPreSharedKey uint16 = 41
89 extensionEarlyData uint16 = 42
90 extensionSupportedVersions uint16 = 43
91 extensionCookie uint16 = 44
92 extensionPSKModes uint16 = 45
93 extensionCertificateAuthorities uint16 = 47
94 extensionSignatureAlgorithmsCert uint16 = 50
95 extensionKeyShare uint16 = 51
96 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
97 extensionRenegotiationInfo uint16 = 0xff01
100 // TLS signaling cipher suite values
102 scsvRenegotiation uint16 = 0x00ff
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.
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.
113 CurveP256 CurveID = 23
114 CurveP384 CurveID = 24
115 CurveP521 CurveID = 25
119 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
120 type keyShare struct {
125 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
127 pskModePlain uint8 = 0
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 {
135 obfuscatedTicketAge uint32
138 // TLS Elliptic Curve Point Formats
139 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
141 pointFormatUncompressed uint8 = 0
144 // TLS CertificateStatusType (RFC 3546)
146 statusTypeOCSP uint8 = 1
149 // Certificate types (for certificateRequestMsg)
152 certTypeECDSASign = 64 // RFC 4492, Section 5.5
155 // Signature algorithms (for internal signaling use). Starting at 16 to avoid overlap with
156 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
158 signaturePKCS1v15 uint8 = iota + 16
163 // supportedSignatureAlgorithms contains the signature and hash algorithms that
164 // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
165 // CertificateRequest. The two fields are merged to match with TLS 1.3.
166 // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
167 var supportedSignatureAlgorithms = []SignatureScheme{
172 ECDSAWithP256AndSHA256,
174 ECDSAWithP384AndSHA384,
176 ECDSAWithP521AndSHA512,
181 // RSA-PSS is disabled in TLS 1.2 for Go 1.12. See Issue 30055.
182 var supportedSignatureAlgorithmsTLS12 = supportedSignatureAlgorithms[3:]
184 // helloRetryRequestRandom is set as the Random value of a ServerHello
185 // to signal that the message is actually a HelloRetryRequest.
186 var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
187 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
188 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
189 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
190 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
194 // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
195 // random as a downgrade protection if the server would be capable of
196 // negotiating a higher version. See RFC 8446, Section 4.1.3.
197 downgradeCanaryTLS12 = "DOWNGRD\x01"
198 downgradeCanaryTLS11 = "DOWNGRD\x00"
201 // ConnectionState records basic TLS details about the connection.
202 type ConnectionState struct {
203 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
204 HandshakeComplete bool // TLS handshake is complete
205 DidResume bool // connection resumes a previous TLS connection
206 CipherSuite uint16 // cipher suite in use (TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, ...)
207 NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos)
208 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only)
209 ServerName string // server name requested by client, if any (server side only)
210 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
211 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
212 SignedCertificateTimestamps [][]byte // SCTs from the peer, if any
213 OCSPResponse []byte // stapled OCSP response from peer, if any
215 // ekm is a closure exposed via ExportKeyingMaterial.
216 ekm func(label string, context []byte, length int) ([]byte, error)
218 // TLSUnique contains the "tls-unique" channel binding value (see RFC
219 // 5929, section 3). For resumed sessions this value will be nil
220 // because resumption does not include enough context (see
221 // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
222 // change in future versions of Go once the TLS master-secret fix has
223 // been standardized and implemented. It is not defined in TLS 1.3.
227 // ExportKeyingMaterial returns length bytes of exported key material in a new
228 // slice as defined in RFC 5705. If context is nil, it is not used as part of
229 // the seed. If the connection was set to allow renegotiation via
230 // Config.Renegotiation, this function will return an error.
231 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
232 return cs.ekm(label, context, length)
235 // ClientAuthType declares the policy the server will follow for
236 // TLS Client Authentication.
237 type ClientAuthType int
240 NoClientCert ClientAuthType = iota
243 VerifyClientCertIfGiven
244 RequireAndVerifyClientCert
247 // requiresClientCert reports whether the ClientAuthType requires a client
248 // certificate to be provided.
249 func requiresClientCert(c ClientAuthType) bool {
251 case RequireAnyClientCert, RequireAndVerifyClientCert:
258 // ClientSessionState contains the state needed by clients to resume TLS
260 type ClientSessionState struct {
261 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
262 vers uint16 // SSL/TLS version negotiated for the session
263 cipherSuite uint16 // Ciphersuite negotiated for the session
264 masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
265 serverCertificates []*x509.Certificate // Certificate chain presented by the server
266 verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
267 receivedAt time.Time // When the session ticket was received from the server
270 nonce []byte // Ticket nonce sent by the server, to derive PSK
271 useBy time.Time // Expiration of the ticket lifetime as set by the server
272 ageAdd uint32 // Random obfuscation factor for sending the ticket age
275 // ClientSessionCache is a cache of ClientSessionState objects that can be used
276 // by a client to resume a TLS session with a given server. ClientSessionCache
277 // implementations should expect to be called concurrently from different
278 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
279 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
280 // are supported via this interface.
281 type ClientSessionCache interface {
282 // Get searches for a ClientSessionState associated with the given key.
283 // On return, ok is true if one was found.
284 Get(sessionKey string) (session *ClientSessionState, ok bool)
286 // Put adds the ClientSessionState to the cache with the given key. It might
287 // get called multiple times in a connection if a TLS 1.3 server provides
288 // more than one session ticket. If called with a nil *ClientSessionState,
289 // it should remove the cache entry.
290 Put(sessionKey string, cs *ClientSessionState)
293 // SignatureScheme identifies a signature algorithm supported by TLS. See
294 // RFC 8446, Section 4.2.3.
295 type SignatureScheme uint16
298 // RSASSA-PKCS1-v1_5 algorithms.
299 PKCS1WithSHA256 SignatureScheme = 0x0401
300 PKCS1WithSHA384 SignatureScheme = 0x0501
301 PKCS1WithSHA512 SignatureScheme = 0x0601
303 // RSASSA-PSS algorithms with public key OID rsaEncryption.
304 PSSWithSHA256 SignatureScheme = 0x0804
305 PSSWithSHA384 SignatureScheme = 0x0805
306 PSSWithSHA512 SignatureScheme = 0x0806
308 // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
309 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
310 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
311 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
313 // Legacy signature and hash algorithms for TLS 1.2.
314 PKCS1WithSHA1 SignatureScheme = 0x0201
315 ECDSAWithSHA1 SignatureScheme = 0x0203
318 // ClientHelloInfo contains information from a ClientHello message in order to
319 // guide certificate selection in the GetCertificate callback.
320 type ClientHelloInfo struct {
321 // CipherSuites lists the CipherSuites supported by the client (e.g.
322 // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
323 CipherSuites []uint16
325 // ServerName indicates the name of the server requested by the client
326 // in order to support virtual hosting. ServerName is only set if the
327 // client is using SNI (see RFC 4366, Section 3.1).
330 // SupportedCurves lists the elliptic curves supported by the client.
331 // SupportedCurves is set only if the Supported Elliptic Curves
332 // Extension is being used (see RFC 4492, Section 5.1.1).
333 SupportedCurves []CurveID
335 // SupportedPoints lists the point formats supported by the client.
336 // SupportedPoints is set only if the Supported Point Formats Extension
337 // is being used (see RFC 4492, Section 5.1.2).
338 SupportedPoints []uint8
340 // SignatureSchemes lists the signature and hash schemes that the client
341 // is willing to verify. SignatureSchemes is set only if the Signature
342 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
343 SignatureSchemes []SignatureScheme
345 // SupportedProtos lists the application protocols supported by the client.
346 // SupportedProtos is set only if the Application-Layer Protocol
347 // Negotiation Extension is being used (see RFC 7301, Section 3.1).
349 // Servers can select a protocol by setting Config.NextProtos in a
350 // GetConfigForClient return value.
351 SupportedProtos []string
353 // SupportedVersions lists the TLS versions supported by the client.
354 // For TLS versions less than 1.3, this is extrapolated from the max
355 // version advertised by the client, so values other than the greatest
356 // might be rejected if used.
357 SupportedVersions []uint16
359 // Conn is the underlying net.Conn for the connection. Do not read
360 // from, or write to, this connection; that will cause the TLS
361 // connection to fail.
365 // CertificateRequestInfo contains information from a server's
366 // CertificateRequest message, which is used to demand a certificate and proof
367 // of control from a client.
368 type CertificateRequestInfo struct {
369 // AcceptableCAs contains zero or more, DER-encoded, X.501
370 // Distinguished Names. These are the names of root or intermediate CAs
371 // that the server wishes the returned certificate to be signed by. An
372 // empty slice indicates that the server has no preference.
373 AcceptableCAs [][]byte
375 // SignatureSchemes lists the signature schemes that the server is
376 // willing to verify.
377 SignatureSchemes []SignatureScheme
380 // RenegotiationSupport enumerates the different levels of support for TLS
381 // renegotiation. TLS renegotiation is the act of performing subsequent
382 // handshakes on a connection after the first. This significantly complicates
383 // the state machine and has been the source of numerous, subtle security
384 // issues. Initiating a renegotiation is not supported, but support for
385 // accepting renegotiation requests may be enabled.
387 // Even when enabled, the server may not change its identity between handshakes
388 // (i.e. the leaf certificate must be the same). Additionally, concurrent
389 // handshake and application data flow is not permitted so renegotiation can
390 // only be used with protocols that synchronise with the renegotiation, such as
393 // Renegotiation is not defined in TLS 1.3.
394 type RenegotiationSupport int
397 // RenegotiateNever disables renegotiation.
398 RenegotiateNever RenegotiationSupport = iota
400 // RenegotiateOnceAsClient allows a remote server to request
401 // renegotiation once per connection.
402 RenegotiateOnceAsClient
404 // RenegotiateFreelyAsClient allows a remote server to repeatedly
405 // request renegotiation.
406 RenegotiateFreelyAsClient
409 // A Config structure is used to configure a TLS client or server.
410 // After one has been passed to a TLS function it must not be
411 // modified. A Config may be reused; the tls package will also not
414 // Rand provides the source of entropy for nonces and RSA blinding.
415 // If Rand is nil, TLS uses the cryptographic random reader in package
417 // The Reader must be safe for use by multiple goroutines.
420 // Time returns the current time as the number of seconds since the epoch.
421 // If Time is nil, TLS uses time.Now.
422 Time func() time.Time
424 // Certificates contains one or more certificate chains to present to
425 // the other side of the connection. Server configurations must include
426 // at least one certificate or else set GetCertificate. Clients doing
427 // client-authentication may set either Certificates or
428 // GetClientCertificate.
429 Certificates []Certificate
431 // NameToCertificate maps from a certificate name to an element of
432 // Certificates. Note that a certificate name can be of the form
433 // '*.example.com' and so doesn't have to be a domain name as such.
434 // See Config.BuildNameToCertificate
435 // The nil value causes the first element of Certificates to be used
436 // for all connections.
437 NameToCertificate map[string]*Certificate
439 // GetCertificate returns a Certificate based on the given
440 // ClientHelloInfo. It will only be called if the client supplies SNI
441 // information or if Certificates is empty.
443 // If GetCertificate is nil or returns nil, then the certificate is
444 // retrieved from NameToCertificate. If NameToCertificate is nil, the
445 // first element of Certificates will be used.
446 GetCertificate func(*ClientHelloInfo) (*Certificate, error)
448 // GetClientCertificate, if not nil, is called when a server requests a
449 // certificate from a client. If set, the contents of Certificates will
452 // If GetClientCertificate returns an error, the handshake will be
453 // aborted and that error will be returned. Otherwise
454 // GetClientCertificate must return a non-nil Certificate. If
455 // Certificate.Certificate is empty then no certificate will be sent to
456 // the server. If this is unacceptable to the server then it may abort
459 // GetClientCertificate may be called multiple times for the same
460 // connection if renegotiation occurs or if TLS 1.3 is in use.
461 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
463 // GetConfigForClient, if not nil, is called after a ClientHello is
464 // received from a client. It may return a non-nil Config in order to
465 // change the Config that will be used to handle this connection. If
466 // the returned Config is nil, the original Config will be used. The
467 // Config returned by this callback may not be subsequently modified.
469 // If GetConfigForClient is nil, the Config passed to Server() will be
470 // used for all connections.
472 // Uniquely for the fields in the returned Config, session ticket keys
473 // will be duplicated from the original Config if not set.
474 // Specifically, if SetSessionTicketKeys was called on the original
475 // config but not on the returned config then the ticket keys from the
476 // original config will be copied into the new config before use.
477 // Otherwise, if SessionTicketKey was set in the original config but
478 // not in the returned config then it will be copied into the returned
479 // config before use. If neither of those cases applies then the key
480 // material from the returned config will be used for session tickets.
481 GetConfigForClient func(*ClientHelloInfo) (*Config, error)
483 // VerifyPeerCertificate, if not nil, is called after normal
484 // certificate verification by either a TLS client or server. It
485 // receives the raw ASN.1 certificates provided by the peer and also
486 // any verified chains that normal processing found. If it returns a
487 // non-nil error, the handshake is aborted and that error results.
489 // If normal verification fails then the handshake will abort before
490 // considering this callback. If normal verification is disabled by
491 // setting InsecureSkipVerify, or (for a server) when ClientAuth is
492 // RequestClientCert or RequireAnyClientCert, then this callback will
493 // be considered but the verifiedChains argument will always be nil.
494 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
496 // RootCAs defines the set of root certificate authorities
497 // that clients use when verifying server certificates.
498 // If RootCAs is nil, TLS uses the host's root CA set.
499 RootCAs *x509.CertPool
501 // NextProtos is a list of supported application level protocols, in
502 // order of preference.
505 // ServerName is used to verify the hostname on the returned
506 // certificates unless InsecureSkipVerify is given. It is also included
507 // in the client's handshake to support virtual hosting unless it is
511 // ClientAuth determines the server's policy for
512 // TLS Client Authentication. The default is NoClientCert.
513 ClientAuth ClientAuthType
515 // ClientCAs defines the set of root certificate authorities
516 // that servers use if required to verify a client certificate
517 // by the policy in ClientAuth.
518 ClientCAs *x509.CertPool
520 // InsecureSkipVerify controls whether a client verifies the
521 // server's certificate chain and host name.
522 // If InsecureSkipVerify is true, TLS accepts any certificate
523 // presented by the server and any host name in that certificate.
524 // In this mode, TLS is susceptible to man-in-the-middle attacks.
525 // This should be used only for testing.
526 InsecureSkipVerify bool
528 // CipherSuites is a list of supported cipher suites for TLS versions up to
529 // TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites
530 // is used, with a preference order based on hardware performance. The
531 // default cipher suites might change over Go versions. Note that TLS 1.3
532 // ciphersuites are not configurable.
533 CipherSuites []uint16
535 // PreferServerCipherSuites controls whether the server selects the
536 // client's most preferred ciphersuite, or the server's most preferred
537 // ciphersuite. If true then the server's preference, as expressed in
538 // the order of elements in CipherSuites, is used.
539 PreferServerCipherSuites bool
541 // SessionTicketsDisabled may be set to true to disable session ticket and
542 // PSK (resumption) support. Note that on clients, session ticket support is
543 // also disabled if ClientSessionCache is nil.
544 SessionTicketsDisabled bool
546 // SessionTicketKey is used by TLS servers to provide session resumption.
547 // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
548 // with random data before the first server handshake.
550 // If multiple servers are terminating connections for the same host
551 // they should all have the same SessionTicketKey. If the
552 // SessionTicketKey leaks, previously recorded and future TLS
553 // connections using that key might be compromised.
554 SessionTicketKey [32]byte
556 // ClientSessionCache is a cache of ClientSessionState entries for TLS
557 // session resumption. It is only used by clients.
558 ClientSessionCache ClientSessionCache
560 // MinVersion contains the minimum SSL/TLS version that is acceptable.
561 // If zero, then TLS 1.0 is taken as the minimum.
564 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
565 // If zero, then the maximum version supported by this package is used,
566 // which is currently TLS 1.3.
569 // CurvePreferences contains the elliptic curves that will be used in
570 // an ECDHE handshake, in preference order. If empty, the default will
571 // be used. The client will use the first preference as the type for
572 // its key share in TLS 1.3. This may change in the future.
573 CurvePreferences []CurveID
575 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
576 // When true, the largest possible TLS record size is always used. When
577 // false, the size of TLS records may be adjusted in an attempt to
579 DynamicRecordSizingDisabled bool
581 // Renegotiation controls what types of renegotiation are supported.
582 // The default, none, is correct for the vast majority of applications.
583 Renegotiation RenegotiationSupport
585 // KeyLogWriter optionally specifies a destination for TLS master secrets
586 // in NSS key log format that can be used to allow external programs
587 // such as Wireshark to decrypt TLS connections.
588 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
589 // Use of KeyLogWriter compromises security and should only be
590 // used for debugging.
591 KeyLogWriter io.Writer
593 serverInitOnce sync.Once // guards calling (*Config).serverInit
595 // mutex protects sessionTicketKeys.
597 // sessionTicketKeys contains zero or more ticket keys. If the length
598 // is zero, SessionTicketsDisabled must be true. The first key is used
599 // for new tickets and any subsequent keys can be used to decrypt old
601 sessionTicketKeys []ticketKey
604 // ticketKeyNameLen is the number of bytes of identifier that is prepended to
605 // an encrypted session ticket in order to identify the key used to encrypt it.
606 const ticketKeyNameLen = 16
608 // ticketKey is the internal representation of a session ticket key.
609 type ticketKey struct {
610 // keyName is an opaque byte string that serves to identify the session
611 // ticket key. It's exposed as plaintext in every session ticket.
612 keyName [ticketKeyNameLen]byte
617 // ticketKeyFromBytes converts from the external representation of a session
618 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
619 // bytes and this function expands that into sufficient name and key material.
620 func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
621 hashed := sha512.Sum512(b[:])
622 copy(key.keyName[:], hashed[:ticketKeyNameLen])
623 copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
624 copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
628 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
629 // ticket, and the lifetime we set for tickets we send.
630 const maxSessionTicketLifetime = 7 * 24 * time.Hour
632 // Clone returns a shallow clone of c. It is safe to clone a Config that is
633 // being used concurrently by a TLS client or server.
634 func (c *Config) Clone() *Config {
635 // Running serverInit ensures that it's safe to read
636 // SessionTicketsDisabled.
637 c.serverInitOnce.Do(func() { c.serverInit(nil) })
639 var sessionTicketKeys []ticketKey
641 sessionTicketKeys = c.sessionTicketKeys
647 Certificates: c.Certificates,
648 NameToCertificate: c.NameToCertificate,
649 GetCertificate: c.GetCertificate,
650 GetClientCertificate: c.GetClientCertificate,
651 GetConfigForClient: c.GetConfigForClient,
652 VerifyPeerCertificate: c.VerifyPeerCertificate,
654 NextProtos: c.NextProtos,
655 ServerName: c.ServerName,
656 ClientAuth: c.ClientAuth,
657 ClientCAs: c.ClientCAs,
658 InsecureSkipVerify: c.InsecureSkipVerify,
659 CipherSuites: c.CipherSuites,
660 PreferServerCipherSuites: c.PreferServerCipherSuites,
661 SessionTicketsDisabled: c.SessionTicketsDisabled,
662 SessionTicketKey: c.SessionTicketKey,
663 ClientSessionCache: c.ClientSessionCache,
664 MinVersion: c.MinVersion,
665 MaxVersion: c.MaxVersion,
666 CurvePreferences: c.CurvePreferences,
667 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
668 Renegotiation: c.Renegotiation,
669 KeyLogWriter: c.KeyLogWriter,
670 sessionTicketKeys: sessionTicketKeys,
674 // serverInit is run under c.serverInitOnce to do initialization of c. If c was
675 // returned by a GetConfigForClient callback then the argument should be the
676 // Config that was passed to Server, otherwise it should be nil.
677 func (c *Config) serverInit(originalConfig *Config) {
678 if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
683 for _, b := range c.SessionTicketKey {
691 if originalConfig != nil {
692 copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
693 } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
694 c.SessionTicketsDisabled = true
699 if originalConfig != nil {
700 originalConfig.mutex.RLock()
701 c.sessionTicketKeys = originalConfig.sessionTicketKeys
702 originalConfig.mutex.RUnlock()
704 c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
708 func (c *Config) ticketKeys() []ticketKey {
710 // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
711 // will only update it by replacing it with a new value.
712 ret := c.sessionTicketKeys
717 // SetSessionTicketKeys updates the session ticket keys for a server. The first
718 // key will be used when creating new tickets, while all keys can be used for
719 // decrypting tickets. It is safe to call this function while the server is
720 // running in order to rotate the session ticket keys. The function will panic
722 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
724 panic("tls: keys must have at least one key")
727 newKeys := make([]ticketKey, len(keys))
728 for i, bytes := range keys {
729 newKeys[i] = ticketKeyFromBytes(bytes)
733 c.sessionTicketKeys = newKeys
737 func (c *Config) rand() io.Reader {
745 func (c *Config) time() time.Time {
753 func (c *Config) cipherSuites() []uint16 {
756 s = defaultCipherSuites()
761 var supportedVersions = []uint16{
769 func (c *Config) supportedVersions(isClient bool) []uint16 {
770 versions := make([]uint16, 0, len(supportedVersions))
771 for _, v := range supportedVersions {
772 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
775 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
778 // TLS 1.0 is the minimum version supported as a client.
779 if isClient && v < VersionTLS10 {
782 // TLS 1.3 is opt-in in Go 1.12.
783 if v == VersionTLS13 && !isTLS13Supported() {
786 versions = append(versions, v)
791 // tls13Support caches the result for isTLS13Supported.
792 var tls13Support struct {
797 // isTLS13Supported returns whether the program opted into TLS 1.3 via
798 // GODEBUG=tls13=1. It's cached after the first execution.
799 func isTLS13Supported() bool {
800 tls13Support.Do(func() {
801 tls13Support.cached = goDebugString("tls13") == "1"
803 return tls13Support.cached
806 // goDebugString returns the value of the named GODEBUG key.
807 // GODEBUG is of the form "key=val,key2=val2".
808 func goDebugString(key string) string {
809 s := os.Getenv("GODEBUG")
810 for i := 0; i < len(s)-len(key)-1; i++ {
811 if i > 0 && s[i-1] != ',' {
814 afterKey := s[i+len(key):]
815 if afterKey[0] != '=' || s[i:i+len(key)] != key {
819 for i, b := range val {
829 func (c *Config) maxSupportedVersion(isClient bool) uint16 {
830 supportedVersions := c.supportedVersions(isClient)
831 if len(supportedVersions) == 0 {
834 return supportedVersions[0]
837 // supportedVersionsFromMax returns a list of supported versions derived from a
838 // legacy maximum version value. Note that only versions supported by this
839 // library are returned. Any newer peer will use supportedVersions anyway.
840 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
841 versions := make([]uint16, 0, len(supportedVersions))
842 for _, v := range supportedVersions {
846 versions = append(versions, v)
851 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
853 func (c *Config) curvePreferences() []CurveID {
854 if c == nil || len(c.CurvePreferences) == 0 {
855 return defaultCurvePreferences
857 return c.CurvePreferences
860 // mutualVersion returns the protocol version to use given the advertised
861 // versions of the peer. Priority is given to the peer preference order.
862 func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
863 supportedVersions := c.supportedVersions(isClient)
864 for _, peerVersion := range peerVersions {
865 for _, v := range supportedVersions {
866 if v == peerVersion {
874 // getCertificate returns the best certificate for the given ClientHelloInfo,
875 // defaulting to the first element of c.Certificates.
876 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
877 if c.GetCertificate != nil &&
878 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
879 cert, err := c.GetCertificate(clientHello)
880 if cert != nil || err != nil {
885 if len(c.Certificates) == 0 {
886 return nil, errors.New("tls: no certificates configured")
889 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
890 // There's only one choice, so no point doing any work.
891 return &c.Certificates[0], nil
894 name := strings.ToLower(clientHello.ServerName)
895 for len(name) > 0 && name[len(name)-1] == '.' {
896 name = name[:len(name)-1]
899 if cert, ok := c.NameToCertificate[name]; ok {
903 // try replacing labels in the name with wildcards until we get a
905 labels := strings.Split(name, ".")
906 for i := range labels {
908 candidate := strings.Join(labels, ".")
909 if cert, ok := c.NameToCertificate[candidate]; ok {
914 // If nothing matches, return the first certificate.
915 return &c.Certificates[0], nil
918 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
919 // from the CommonName and SubjectAlternateName fields of each of the leaf
921 func (c *Config) BuildNameToCertificate() {
922 c.NameToCertificate = make(map[string]*Certificate)
923 for i := range c.Certificates {
924 cert := &c.Certificates[i]
925 x509Cert := cert.Leaf
928 x509Cert, err = x509.ParseCertificate(cert.Certificate[0])
933 if len(x509Cert.Subject.CommonName) > 0 {
934 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
936 for _, san := range x509Cert.DNSNames {
937 c.NameToCertificate[san] = cert
943 keyLogLabelTLS12 = "CLIENT_RANDOM"
944 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
945 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
946 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
947 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
950 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
951 if c.KeyLogWriter == nil {
955 logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
958 _, err := c.KeyLogWriter.Write(logLine)
964 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
965 // and is only for debugging, so a global mutex saves space.
966 var writerMutex sync.Mutex
968 // A Certificate is a chain of one or more certificates, leaf first.
969 type Certificate struct {
971 // PrivateKey contains the private key corresponding to the public key in
972 // Leaf. This must implement crypto.Signer with an RSA or ECDSA PublicKey.
973 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
975 PrivateKey crypto.PrivateKey
976 // OCSPStaple contains an optional OCSP response which will be served
977 // to clients that request it.
979 // SignedCertificateTimestamps contains an optional list of Signed
980 // Certificate Timestamps which will be served to clients that request it.
981 SignedCertificateTimestamps [][]byte
982 // Leaf is the parsed form of the leaf certificate, which may be
983 // initialized using x509.ParseCertificate to reduce per-handshake
984 // processing for TLS clients doing client authentication. If nil, the
985 // leaf certificate will be parsed as needed.
986 Leaf *x509.Certificate
989 type handshakeMessage interface {
991 unmarshal([]byte) bool
994 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
996 type lruSessionCache struct {
999 m map[string]*list.Element
1004 type lruSessionCacheEntry struct {
1006 state *ClientSessionState
1009 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1010 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1012 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1013 const defaultSessionCacheCapacity = 64
1016 capacity = defaultSessionCacheCapacity
1018 return &lruSessionCache{
1019 m: make(map[string]*list.Element),
1025 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1026 // corresponding to sessionKey is removed from the cache instead.
1027 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1031 if elem, ok := c.m[sessionKey]; ok {
1034 delete(c.m, sessionKey)
1036 entry := elem.Value.(*lruSessionCacheEntry)
1038 c.q.MoveToFront(elem)
1043 if c.q.Len() < c.capacity {
1044 entry := &lruSessionCacheEntry{sessionKey, cs}
1045 c.m[sessionKey] = c.q.PushFront(entry)
1050 entry := elem.Value.(*lruSessionCacheEntry)
1051 delete(c.m, entry.sessionKey)
1052 entry.sessionKey = sessionKey
1054 c.q.MoveToFront(elem)
1055 c.m[sessionKey] = elem
1058 // Get returns the ClientSessionState value associated with a given key. It
1059 // returns (nil, false) if no value is found.
1060 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1064 if elem, ok := c.m[sessionKey]; ok {
1065 c.q.MoveToFront(elem)
1066 return elem.Value.(*lruSessionCacheEntry).state, true
1071 // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1072 type dsaSignature struct {
1076 type ecdsaSignature dsaSignature
1078 var emptyConfig Config
1080 func defaultConfig() *Config {
1086 varDefaultCipherSuites []uint16
1087 varDefaultCipherSuitesTLS13 []uint16
1090 func defaultCipherSuites() []uint16 {
1091 once.Do(initDefaultCipherSuites)
1092 return varDefaultCipherSuites
1095 func defaultCipherSuitesTLS13() []uint16 {
1096 once.Do(initDefaultCipherSuites)
1097 return varDefaultCipherSuitesTLS13
1100 func initDefaultCipherSuites() {
1101 var topCipherSuites []uint16
1103 // Check the cpu flags for each platform that has optimized GCM implementations.
1104 // Worst case, these variables will just all be false.
1106 hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
1107 hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
1108 // Keep in sync with crypto/aes/cipher_s390x.go.
1109 hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
1111 hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
1115 // If AES-GCM hardware is provided then prioritise AES-GCM
1117 topCipherSuites = []uint16{
1118 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1119 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1120 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1121 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1122 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1123 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1125 varDefaultCipherSuitesTLS13 = []uint16{
1126 TLS_AES_128_GCM_SHA256,
1127 TLS_CHACHA20_POLY1305_SHA256,
1128 TLS_AES_256_GCM_SHA384,
1131 // Without AES-GCM hardware, we put the ChaCha20-Poly1305
1132 // cipher suites first.
1133 topCipherSuites = []uint16{
1134 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1135 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1136 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1137 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1138 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1139 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1141 varDefaultCipherSuitesTLS13 = []uint16{
1142 TLS_CHACHA20_POLY1305_SHA256,
1143 TLS_AES_128_GCM_SHA256,
1144 TLS_AES_256_GCM_SHA384,
1148 varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
1149 varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
1152 for _, suite := range cipherSuites {
1153 if suite.flags&suiteDefaultOff != 0 {
1156 for _, existing := range varDefaultCipherSuites {
1157 if existing == suite.id {
1158 continue NextCipherSuite
1161 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1165 func unexpectedMessageError(wanted, got interface{}) error {
1166 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1169 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1170 for _, s := range supportedSignatureAlgorithms {
1178 // signatureFromSignatureScheme maps a signature algorithm to the underlying
1179 // signature method (without hash function).
1180 func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
1181 switch signatureAlgorithm {
1182 case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
1183 return signaturePKCS1v15
1184 case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
1185 return signatureRSAPSS
1186 case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
1187 return signatureECDSA