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.
10 "crypto/internal/boring"
35 maxPlaintext = 16384 // maximum plaintext payload length
36 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
37 maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3
38 recordHeaderLen = 5 // record header length
39 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
40 maxUselessRecords = 16 // maximum number of consecutive non-advancing records
47 recordTypeChangeCipherSpec recordType = 20
48 recordTypeAlert recordType = 21
49 recordTypeHandshake recordType = 22
50 recordTypeApplicationData recordType = 23
53 // TLS handshake message types.
55 typeHelloRequest uint8 = 0
56 typeClientHello uint8 = 1
57 typeServerHello uint8 = 2
58 typeNewSessionTicket uint8 = 4
59 typeEndOfEarlyData uint8 = 5
60 typeEncryptedExtensions uint8 = 8
61 typeCertificate uint8 = 11
62 typeServerKeyExchange uint8 = 12
63 typeCertificateRequest uint8 = 13
64 typeServerHelloDone uint8 = 14
65 typeCertificateVerify uint8 = 15
66 typeClientKeyExchange uint8 = 16
67 typeFinished uint8 = 20
68 typeCertificateStatus uint8 = 22
69 typeKeyUpdate uint8 = 24
70 typeNextProtocol uint8 = 67 // Not IANA assigned
71 typeMessageHash uint8 = 254 // synthetic message
74 // TLS compression types.
76 compressionNone uint8 = 0
79 // TLS extension numbers
81 extensionServerName uint16 = 0
82 extensionStatusRequest uint16 = 5
83 extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
84 extensionSupportedPoints uint16 = 11
85 extensionSignatureAlgorithms uint16 = 13
86 extensionALPN uint16 = 16
87 extensionSCT uint16 = 18
88 extensionSessionTicket uint16 = 35
89 extensionPreSharedKey uint16 = 41
90 extensionEarlyData uint16 = 42
91 extensionSupportedVersions uint16 = 43
92 extensionCookie uint16 = 44
93 extensionPSKModes uint16 = 45
94 extensionCertificateAuthorities uint16 = 47
95 extensionSignatureAlgorithmsCert uint16 = 50
96 extensionKeyShare uint16 = 51
97 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
98 extensionRenegotiationInfo uint16 = 0xff01
101 // TLS signaling cipher suite values
103 scsvRenegotiation uint16 = 0x00ff
106 // CurveID is the type of a TLS identifier for an elliptic curve. See
107 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
109 // In TLS 1.3, this type is called NamedGroup, but at this time this library
110 // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
114 CurveP256 CurveID = 23
115 CurveP384 CurveID = 24
116 CurveP521 CurveID = 25
120 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
121 type keyShare struct {
126 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
128 pskModePlain uint8 = 0
132 // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
133 // session. See RFC 8446, Section 4.2.11.
134 type pskIdentity struct {
136 obfuscatedTicketAge uint32
139 // TLS Elliptic Curve Point Formats
140 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
142 pointFormatUncompressed uint8 = 0
145 // TLS CertificateStatusType (RFC 3546)
147 statusTypeOCSP uint8 = 1
150 // Certificate types (for certificateRequestMsg)
153 certTypeECDSASign = 64 // RFC 4492, Section 5.5
156 // Signature algorithms (for internal signaling use). Starting at 16 to avoid overlap with
157 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
159 signaturePKCS1v15 uint8 = iota + 16
164 // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
165 // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
166 // CertificateRequest. The two fields are merged to match with TLS 1.3.
167 // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
168 var defaultSupportedSignatureAlgorithms = []SignatureScheme{
173 ECDSAWithP256AndSHA256,
175 ECDSAWithP384AndSHA384,
177 ECDSAWithP521AndSHA512,
182 // helloRetryRequestRandom is set as the Random value of a ServerHello
183 // to signal that the message is actually a HelloRetryRequest.
184 var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
185 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
186 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
187 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
188 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
192 // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
193 // random as a downgrade protection if the server would be capable of
194 // negotiating a higher version. See RFC 8446, Section 4.1.3.
195 downgradeCanaryTLS12 = "DOWNGRD\x01"
196 downgradeCanaryTLS11 = "DOWNGRD\x00"
199 // ConnectionState records basic TLS details about the connection.
200 type ConnectionState struct {
201 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
202 HandshakeComplete bool // TLS handshake is complete
203 DidResume bool // connection resumes a previous TLS connection
204 CipherSuite uint16 // cipher suite in use (TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, ...)
205 NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos)
206 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only)
207 ServerName string // server name requested by client, if any (server side only)
208 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
209 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
210 SignedCertificateTimestamps [][]byte // SCTs from the peer, if any
211 OCSPResponse []byte // stapled OCSP response from peer, if any
213 // ekm is a closure exposed via ExportKeyingMaterial.
214 ekm func(label string, context []byte, length int) ([]byte, error)
216 // TLSUnique contains the "tls-unique" channel binding value (see RFC
217 // 5929, section 3). For resumed sessions this value will be nil
218 // because resumption does not include enough context (see
219 // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
220 // change in future versions of Go once the TLS master-secret fix has
221 // been standardized and implemented. It is not defined in TLS 1.3.
225 // ExportKeyingMaterial returns length bytes of exported key material in a new
226 // slice as defined in RFC 5705. If context is nil, it is not used as part of
227 // the seed. If the connection was set to allow renegotiation via
228 // Config.Renegotiation, this function will return an error.
229 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
230 return cs.ekm(label, context, length)
233 // ClientAuthType declares the policy the server will follow for
234 // TLS Client Authentication.
235 type ClientAuthType int
238 NoClientCert ClientAuthType = iota
241 VerifyClientCertIfGiven
242 RequireAndVerifyClientCert
245 // requiresClientCert reports whether the ClientAuthType requires a client
246 // certificate to be provided.
247 func requiresClientCert(c ClientAuthType) bool {
249 case RequireAnyClientCert, RequireAndVerifyClientCert:
256 // ClientSessionState contains the state needed by clients to resume TLS
258 type ClientSessionState struct {
259 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
260 vers uint16 // SSL/TLS version negotiated for the session
261 cipherSuite uint16 // Ciphersuite negotiated for the session
262 masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
263 serverCertificates []*x509.Certificate // Certificate chain presented by the server
264 verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
265 receivedAt time.Time // When the session ticket was received from the server
268 nonce []byte // Ticket nonce sent by the server, to derive PSK
269 useBy time.Time // Expiration of the ticket lifetime as set by the server
270 ageAdd uint32 // Random obfuscation factor for sending the ticket age
273 // ClientSessionCache is a cache of ClientSessionState objects that can be used
274 // by a client to resume a TLS session with a given server. ClientSessionCache
275 // implementations should expect to be called concurrently from different
276 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
277 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
278 // are supported via this interface.
279 type ClientSessionCache interface {
280 // Get searches for a ClientSessionState associated with the given key.
281 // On return, ok is true if one was found.
282 Get(sessionKey string) (session *ClientSessionState, ok bool)
284 // Put adds the ClientSessionState to the cache with the given key. It might
285 // get called multiple times in a connection if a TLS 1.3 server provides
286 // more than one session ticket. If called with a nil *ClientSessionState,
287 // it should remove the cache entry.
288 Put(sessionKey string, cs *ClientSessionState)
291 // SignatureScheme identifies a signature algorithm supported by TLS. See
292 // RFC 8446, Section 4.2.3.
293 type SignatureScheme uint16
296 // RSASSA-PKCS1-v1_5 algorithms.
297 PKCS1WithSHA256 SignatureScheme = 0x0401
298 PKCS1WithSHA384 SignatureScheme = 0x0501
299 PKCS1WithSHA512 SignatureScheme = 0x0601
301 // RSASSA-PSS algorithms with public key OID rsaEncryption.
302 PSSWithSHA256 SignatureScheme = 0x0804
303 PSSWithSHA384 SignatureScheme = 0x0805
304 PSSWithSHA512 SignatureScheme = 0x0806
306 // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
307 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
308 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
309 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
311 // Legacy signature and hash algorithms for TLS 1.2.
312 PKCS1WithSHA1 SignatureScheme = 0x0201
313 ECDSAWithSHA1 SignatureScheme = 0x0203
316 // ClientHelloInfo contains information from a ClientHello message in order to
317 // guide certificate selection in the GetCertificate callback.
318 type ClientHelloInfo struct {
319 // CipherSuites lists the CipherSuites supported by the client (e.g.
320 // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
321 CipherSuites []uint16
323 // ServerName indicates the name of the server requested by the client
324 // in order to support virtual hosting. ServerName is only set if the
325 // client is using SNI (see RFC 4366, Section 3.1).
328 // SupportedCurves lists the elliptic curves supported by the client.
329 // SupportedCurves is set only if the Supported Elliptic Curves
330 // Extension is being used (see RFC 4492, Section 5.1.1).
331 SupportedCurves []CurveID
333 // SupportedPoints lists the point formats supported by the client.
334 // SupportedPoints is set only if the Supported Point Formats Extension
335 // is being used (see RFC 4492, Section 5.1.2).
336 SupportedPoints []uint8
338 // SignatureSchemes lists the signature and hash schemes that the client
339 // is willing to verify. SignatureSchemes is set only if the Signature
340 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
341 SignatureSchemes []SignatureScheme
343 // SupportedProtos lists the application protocols supported by the client.
344 // SupportedProtos is set only if the Application-Layer Protocol
345 // Negotiation Extension is being used (see RFC 7301, Section 3.1).
347 // Servers can select a protocol by setting Config.NextProtos in a
348 // GetConfigForClient return value.
349 SupportedProtos []string
351 // SupportedVersions lists the TLS versions supported by the client.
352 // For TLS versions less than 1.3, this is extrapolated from the max
353 // version advertised by the client, so values other than the greatest
354 // might be rejected if used.
355 SupportedVersions []uint16
357 // Conn is the underlying net.Conn for the connection. Do not read
358 // from, or write to, this connection; that will cause the TLS
359 // connection to fail.
363 // CertificateRequestInfo contains information from a server's
364 // CertificateRequest message, which is used to demand a certificate and proof
365 // of control from a client.
366 type CertificateRequestInfo struct {
367 // AcceptableCAs contains zero or more, DER-encoded, X.501
368 // Distinguished Names. These are the names of root or intermediate CAs
369 // that the server wishes the returned certificate to be signed by. An
370 // empty slice indicates that the server has no preference.
371 AcceptableCAs [][]byte
373 // SignatureSchemes lists the signature schemes that the server is
374 // willing to verify.
375 SignatureSchemes []SignatureScheme
378 // RenegotiationSupport enumerates the different levels of support for TLS
379 // renegotiation. TLS renegotiation is the act of performing subsequent
380 // handshakes on a connection after the first. This significantly complicates
381 // the state machine and has been the source of numerous, subtle security
382 // issues. Initiating a renegotiation is not supported, but support for
383 // accepting renegotiation requests may be enabled.
385 // Even when enabled, the server may not change its identity between handshakes
386 // (i.e. the leaf certificate must be the same). Additionally, concurrent
387 // handshake and application data flow is not permitted so renegotiation can
388 // only be used with protocols that synchronise with the renegotiation, such as
391 // Renegotiation is not defined in TLS 1.3.
392 type RenegotiationSupport int
395 // RenegotiateNever disables renegotiation.
396 RenegotiateNever RenegotiationSupport = iota
398 // RenegotiateOnceAsClient allows a remote server to request
399 // renegotiation once per connection.
400 RenegotiateOnceAsClient
402 // RenegotiateFreelyAsClient allows a remote server to repeatedly
403 // request renegotiation.
404 RenegotiateFreelyAsClient
407 // A Config structure is used to configure a TLS client or server.
408 // After one has been passed to a TLS function it must not be
409 // modified. A Config may be reused; the tls package will also not
412 // Rand provides the source of entropy for nonces and RSA blinding.
413 // If Rand is nil, TLS uses the cryptographic random reader in package
415 // The Reader must be safe for use by multiple goroutines.
418 // Time returns the current time as the number of seconds since the epoch.
419 // If Time is nil, TLS uses time.Now.
420 Time func() time.Time
422 // Certificates contains one or more certificate chains to present to
423 // the other side of the connection. Server configurations must include
424 // at least one certificate or else set GetCertificate. Clients doing
425 // client-authentication may set either Certificates or
426 // GetClientCertificate.
427 Certificates []Certificate
429 // NameToCertificate maps from a certificate name to an element of
430 // Certificates. Note that a certificate name can be of the form
431 // '*.example.com' and so doesn't have to be a domain name as such.
432 // See Config.BuildNameToCertificate
433 // The nil value causes the first element of Certificates to be used
434 // for all connections.
435 NameToCertificate map[string]*Certificate
437 // GetCertificate returns a Certificate based on the given
438 // ClientHelloInfo. It will only be called if the client supplies SNI
439 // information or if Certificates is empty.
441 // If GetCertificate is nil or returns nil, then the certificate is
442 // retrieved from NameToCertificate. If NameToCertificate is nil, the
443 // first element of Certificates will be used.
444 GetCertificate func(*ClientHelloInfo) (*Certificate, error)
446 // GetClientCertificate, if not nil, is called when a server requests a
447 // certificate from a client. If set, the contents of Certificates will
450 // If GetClientCertificate returns an error, the handshake will be
451 // aborted and that error will be returned. Otherwise
452 // GetClientCertificate must return a non-nil Certificate. If
453 // Certificate.Certificate is empty then no certificate will be sent to
454 // the server. If this is unacceptable to the server then it may abort
457 // GetClientCertificate may be called multiple times for the same
458 // connection if renegotiation occurs or if TLS 1.3 is in use.
459 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
461 // GetConfigForClient, if not nil, is called after a ClientHello is
462 // received from a client. It may return a non-nil Config in order to
463 // change the Config that will be used to handle this connection. If
464 // the returned Config is nil, the original Config will be used. The
465 // Config returned by this callback may not be subsequently modified.
467 // If GetConfigForClient is nil, the Config passed to Server() will be
468 // used for all connections.
470 // Uniquely for the fields in the returned Config, session ticket keys
471 // will be duplicated from the original Config if not set.
472 // Specifically, if SetSessionTicketKeys was called on the original
473 // config but not on the returned config then the ticket keys from the
474 // original config will be copied into the new config before use.
475 // Otherwise, if SessionTicketKey was set in the original config but
476 // not in the returned config then it will be copied into the returned
477 // config before use. If neither of those cases applies then the key
478 // material from the returned config will be used for session tickets.
479 GetConfigForClient func(*ClientHelloInfo) (*Config, error)
481 // VerifyPeerCertificate, if not nil, is called after normal
482 // certificate verification by either a TLS client or server. It
483 // receives the raw ASN.1 certificates provided by the peer and also
484 // any verified chains that normal processing found. If it returns a
485 // non-nil error, the handshake is aborted and that error results.
487 // If normal verification fails then the handshake will abort before
488 // considering this callback. If normal verification is disabled by
489 // setting InsecureSkipVerify, or (for a server) when ClientAuth is
490 // RequestClientCert or RequireAnyClientCert, then this callback will
491 // be considered but the verifiedChains argument will always be nil.
492 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
494 // RootCAs defines the set of root certificate authorities
495 // that clients use when verifying server certificates.
496 // If RootCAs is nil, TLS uses the host's root CA set.
497 RootCAs *x509.CertPool
499 // NextProtos is a list of supported application level protocols, in
500 // order of preference.
503 // ServerName is used to verify the hostname on the returned
504 // certificates unless InsecureSkipVerify is given. It is also included
505 // in the client's handshake to support virtual hosting unless it is
509 // ClientAuth determines the server's policy for
510 // TLS Client Authentication. The default is NoClientCert.
511 ClientAuth ClientAuthType
513 // ClientCAs defines the set of root certificate authorities
514 // that servers use if required to verify a client certificate
515 // by the policy in ClientAuth.
516 ClientCAs *x509.CertPool
518 // InsecureSkipVerify controls whether a client verifies the
519 // server's certificate chain and host name.
520 // If InsecureSkipVerify is true, TLS accepts any certificate
521 // presented by the server and any host name in that certificate.
522 // In this mode, TLS is susceptible to man-in-the-middle attacks.
523 // This should be used only for testing.
524 InsecureSkipVerify bool
526 // CipherSuites is a list of supported cipher suites for TLS versions up to
527 // TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites
528 // is used, with a preference order based on hardware performance. The
529 // default cipher suites might change over Go versions. Note that TLS 1.3
530 // ciphersuites are not configurable.
531 CipherSuites []uint16
533 // PreferServerCipherSuites controls whether the server selects the
534 // client's most preferred ciphersuite, or the server's most preferred
535 // ciphersuite. If true then the server's preference, as expressed in
536 // the order of elements in CipherSuites, is used.
537 PreferServerCipherSuites bool
539 // SessionTicketsDisabled may be set to true to disable session ticket and
540 // PSK (resumption) support. Note that on clients, session ticket support is
541 // also disabled if ClientSessionCache is nil.
542 SessionTicketsDisabled bool
544 // SessionTicketKey is used by TLS servers to provide session resumption.
545 // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
546 // with random data before the first server handshake.
548 // If multiple servers are terminating connections for the same host
549 // they should all have the same SessionTicketKey. If the
550 // SessionTicketKey leaks, previously recorded and future TLS
551 // connections using that key might be compromised.
552 SessionTicketKey [32]byte
554 // ClientSessionCache is a cache of ClientSessionState entries for TLS
555 // session resumption. It is only used by clients.
556 ClientSessionCache ClientSessionCache
558 // MinVersion contains the minimum SSL/TLS version that is acceptable.
559 // If zero, then TLS 1.0 is taken as the minimum.
562 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
563 // If zero, then the maximum version supported by this package is used,
564 // which is currently TLS 1.3.
567 // CurvePreferences contains the elliptic curves that will be used in
568 // an ECDHE handshake, in preference order. If empty, the default will
569 // be used. The client will use the first preference as the type for
570 // its key share in TLS 1.3. This may change in the future.
571 CurvePreferences []CurveID
573 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
574 // When true, the largest possible TLS record size is always used. When
575 // false, the size of TLS records may be adjusted in an attempt to
577 DynamicRecordSizingDisabled bool
579 // Renegotiation controls what types of renegotiation are supported.
580 // The default, none, is correct for the vast majority of applications.
581 Renegotiation RenegotiationSupport
583 // KeyLogWriter optionally specifies a destination for TLS master secrets
584 // in NSS key log format that can be used to allow external programs
585 // such as Wireshark to decrypt TLS connections.
586 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
587 // Use of KeyLogWriter compromises security and should only be
588 // used for debugging.
589 KeyLogWriter io.Writer
591 serverInitOnce sync.Once // guards calling (*Config).serverInit
593 // mutex protects sessionTicketKeys.
595 // sessionTicketKeys contains zero or more ticket keys. If the length
596 // is zero, SessionTicketsDisabled must be true. The first key is used
597 // for new tickets and any subsequent keys can be used to decrypt old
599 sessionTicketKeys []ticketKey
602 // ticketKeyNameLen is the number of bytes of identifier that is prepended to
603 // an encrypted session ticket in order to identify the key used to encrypt it.
604 const ticketKeyNameLen = 16
606 // ticketKey is the internal representation of a session ticket key.
607 type ticketKey struct {
608 // keyName is an opaque byte string that serves to identify the session
609 // ticket key. It's exposed as plaintext in every session ticket.
610 keyName [ticketKeyNameLen]byte
615 // ticketKeyFromBytes converts from the external representation of a session
616 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
617 // bytes and this function expands that into sufficient name and key material.
618 func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
619 hashed := sha512.Sum512(b[:])
620 copy(key.keyName[:], hashed[:ticketKeyNameLen])
621 copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
622 copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
626 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
627 // ticket, and the lifetime we set for tickets we send.
628 const maxSessionTicketLifetime = 7 * 24 * time.Hour
630 // Clone returns a shallow clone of c. It is safe to clone a Config that is
631 // being used concurrently by a TLS client or server.
632 func (c *Config) Clone() *Config {
633 // Running serverInit ensures that it's safe to read
634 // SessionTicketsDisabled.
635 c.serverInitOnce.Do(func() { c.serverInit(nil) })
637 var sessionTicketKeys []ticketKey
639 sessionTicketKeys = c.sessionTicketKeys
645 Certificates: c.Certificates,
646 NameToCertificate: c.NameToCertificate,
647 GetCertificate: c.GetCertificate,
648 GetClientCertificate: c.GetClientCertificate,
649 GetConfigForClient: c.GetConfigForClient,
650 VerifyPeerCertificate: c.VerifyPeerCertificate,
652 NextProtos: c.NextProtos,
653 ServerName: c.ServerName,
654 ClientAuth: c.ClientAuth,
655 ClientCAs: c.ClientCAs,
656 InsecureSkipVerify: c.InsecureSkipVerify,
657 CipherSuites: c.CipherSuites,
658 PreferServerCipherSuites: c.PreferServerCipherSuites,
659 SessionTicketsDisabled: c.SessionTicketsDisabled,
660 SessionTicketKey: c.SessionTicketKey,
661 ClientSessionCache: c.ClientSessionCache,
662 MinVersion: c.MinVersion,
663 MaxVersion: c.MaxVersion,
664 CurvePreferences: c.CurvePreferences,
665 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
666 Renegotiation: c.Renegotiation,
667 KeyLogWriter: c.KeyLogWriter,
668 sessionTicketKeys: sessionTicketKeys,
672 // serverInit is run under c.serverInitOnce to do initialization of c. If c was
673 // returned by a GetConfigForClient callback then the argument should be the
674 // Config that was passed to Server, otherwise it should be nil.
675 func (c *Config) serverInit(originalConfig *Config) {
676 if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
681 for _, b := range c.SessionTicketKey {
689 if originalConfig != nil {
690 copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
691 } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
692 c.SessionTicketsDisabled = true
697 if originalConfig != nil {
698 originalConfig.mutex.RLock()
699 c.sessionTicketKeys = originalConfig.sessionTicketKeys
700 originalConfig.mutex.RUnlock()
702 c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
706 func (c *Config) ticketKeys() []ticketKey {
708 // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
709 // will only update it by replacing it with a new value.
710 ret := c.sessionTicketKeys
715 // SetSessionTicketKeys updates the session ticket keys for a server. The first
716 // key will be used when creating new tickets, while all keys can be used for
717 // decrypting tickets. It is safe to call this function while the server is
718 // running in order to rotate the session ticket keys. The function will panic
720 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
722 panic("tls: keys must have at least one key")
725 newKeys := make([]ticketKey, len(keys))
726 for i, bytes := range keys {
727 newKeys[i] = ticketKeyFromBytes(bytes)
731 c.sessionTicketKeys = newKeys
735 func (c *Config) rand() io.Reader {
743 func (c *Config) time() time.Time {
751 func (c *Config) cipherSuites() []uint16 {
753 return fipsCipherSuites(c)
757 s = defaultCipherSuites()
762 var supportedVersions = []uint16{
770 func (c *Config) supportedVersions(isClient bool) []uint16 {
771 versions := make([]uint16, 0, len(supportedVersions))
772 for _, v := range supportedVersions {
773 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
776 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
779 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
782 // TLS 1.0 is the minimum version supported as a client.
783 if isClient && v < VersionTLS10 {
786 // TLS 1.3 is opt-in in Go 1.12.
787 if v == VersionTLS13 && !isTLS13Supported() {
790 versions = append(versions, v)
795 // tls13Support caches the result for isTLS13Supported.
796 var tls13Support struct {
801 // isTLS13Supported returns whether the program opted into TLS 1.3 via
802 // GODEBUG=tls13=1. It's cached after the first execution.
803 func isTLS13Supported() bool {
804 tls13Support.Do(func() {
805 tls13Support.cached = goDebugString("tls13") == "1"
807 return tls13Support.cached
810 // goDebugString returns the value of the named GODEBUG key.
811 // GODEBUG is of the form "key=val,key2=val2".
812 func goDebugString(key string) string {
813 s := os.Getenv("GODEBUG")
814 for i := 0; i < len(s)-len(key)-1; i++ {
815 if i > 0 && s[i-1] != ',' {
818 afterKey := s[i+len(key):]
819 if afterKey[0] != '=' || s[i:i+len(key)] != key {
823 for i, b := range val {
833 func (c *Config) maxSupportedVersion(isClient bool) uint16 {
834 supportedVersions := c.supportedVersions(isClient)
835 if len(supportedVersions) == 0 {
838 return supportedVersions[0]
841 // supportedVersionsFromMax returns a list of supported versions derived from a
842 // legacy maximum version value. Note that only versions supported by this
843 // library are returned. Any newer peer will use supportedVersions anyway.
844 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
845 versions := make([]uint16, 0, len(supportedVersions))
846 for _, v := range supportedVersions {
850 versions = append(versions, v)
855 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
857 func (c *Config) curvePreferences() []CurveID {
859 return fipsCurvePreferences(c)
861 if c == nil || len(c.CurvePreferences) == 0 {
862 return defaultCurvePreferences
864 return c.CurvePreferences
867 // mutualVersion returns the protocol version to use given the advertised
868 // versions of the peer. Priority is given to the peer preference order.
869 func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
870 supportedVersions := c.supportedVersions(isClient)
871 for _, peerVersion := range peerVersions {
872 for _, v := range supportedVersions {
873 if v == peerVersion {
881 // getCertificate returns the best certificate for the given ClientHelloInfo,
882 // defaulting to the first element of c.Certificates.
883 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
884 if c.GetCertificate != nil &&
885 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
886 cert, err := c.GetCertificate(clientHello)
887 if cert != nil || err != nil {
892 if len(c.Certificates) == 0 {
893 return nil, errors.New("tls: no certificates configured")
896 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
897 // There's only one choice, so no point doing any work.
898 return &c.Certificates[0], nil
901 name := strings.ToLower(clientHello.ServerName)
902 for len(name) > 0 && name[len(name)-1] == '.' {
903 name = name[:len(name)-1]
906 if cert, ok := c.NameToCertificate[name]; ok {
910 // try replacing labels in the name with wildcards until we get a
912 labels := strings.Split(name, ".")
913 for i := range labels {
915 candidate := strings.Join(labels, ".")
916 if cert, ok := c.NameToCertificate[candidate]; ok {
921 // If nothing matches, return the first certificate.
922 return &c.Certificates[0], nil
925 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
926 // from the CommonName and SubjectAlternateName fields of each of the leaf
928 func (c *Config) BuildNameToCertificate() {
929 c.NameToCertificate = make(map[string]*Certificate)
930 for i := range c.Certificates {
931 cert := &c.Certificates[i]
932 x509Cert := cert.Leaf
935 x509Cert, err = x509.ParseCertificate(cert.Certificate[0])
940 if len(x509Cert.Subject.CommonName) > 0 {
941 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
943 for _, san := range x509Cert.DNSNames {
944 c.NameToCertificate[san] = cert
950 keyLogLabelTLS12 = "CLIENT_RANDOM"
951 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
952 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
953 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
954 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
957 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
958 if c.KeyLogWriter == nil {
962 logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
965 _, err := c.KeyLogWriter.Write(logLine)
971 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
972 // and is only for debugging, so a global mutex saves space.
973 var writerMutex sync.Mutex
975 // A Certificate is a chain of one or more certificates, leaf first.
976 type Certificate struct {
978 // PrivateKey contains the private key corresponding to the public key in
979 // Leaf. This must implement crypto.Signer with an RSA or ECDSA PublicKey.
980 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
982 PrivateKey crypto.PrivateKey
983 // OCSPStaple contains an optional OCSP response which will be served
984 // to clients that request it.
986 // SignedCertificateTimestamps contains an optional list of Signed
987 // Certificate Timestamps which will be served to clients that request it.
988 SignedCertificateTimestamps [][]byte
989 // Leaf is the parsed form of the leaf certificate, which may be
990 // initialized using x509.ParseCertificate to reduce per-handshake
991 // processing for TLS clients doing client authentication. If nil, the
992 // leaf certificate will be parsed as needed.
993 Leaf *x509.Certificate
996 type handshakeMessage interface {
998 unmarshal([]byte) bool
1001 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1002 // caching strategy.
1003 type lruSessionCache struct {
1006 m map[string]*list.Element
1011 type lruSessionCacheEntry struct {
1013 state *ClientSessionState
1016 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1017 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1019 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1020 const defaultSessionCacheCapacity = 64
1023 capacity = defaultSessionCacheCapacity
1025 return &lruSessionCache{
1026 m: make(map[string]*list.Element),
1032 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1033 // corresponding to sessionKey is removed from the cache instead.
1034 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1038 if elem, ok := c.m[sessionKey]; ok {
1041 delete(c.m, sessionKey)
1043 entry := elem.Value.(*lruSessionCacheEntry)
1045 c.q.MoveToFront(elem)
1050 if c.q.Len() < c.capacity {
1051 entry := &lruSessionCacheEntry{sessionKey, cs}
1052 c.m[sessionKey] = c.q.PushFront(entry)
1057 entry := elem.Value.(*lruSessionCacheEntry)
1058 delete(c.m, entry.sessionKey)
1059 entry.sessionKey = sessionKey
1061 c.q.MoveToFront(elem)
1062 c.m[sessionKey] = elem
1065 // Get returns the ClientSessionState value associated with a given key. It
1066 // returns (nil, false) if no value is found.
1067 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1071 if elem, ok := c.m[sessionKey]; ok {
1072 c.q.MoveToFront(elem)
1073 return elem.Value.(*lruSessionCacheEntry).state, true
1078 // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1079 type dsaSignature struct {
1083 type ecdsaSignature dsaSignature
1085 var emptyConfig Config
1087 func defaultConfig() *Config {
1093 varDefaultCipherSuites []uint16
1094 varDefaultCipherSuitesTLS13 []uint16
1097 func defaultCipherSuites() []uint16 {
1098 once.Do(initDefaultCipherSuites)
1099 return varDefaultCipherSuites
1102 func defaultCipherSuitesTLS13() []uint16 {
1103 once.Do(initDefaultCipherSuites)
1104 return varDefaultCipherSuitesTLS13
1107 func initDefaultCipherSuites() {
1108 var topCipherSuites []uint16
1110 // Check the cpu flags for each platform that has optimized GCM implementations.
1111 // Worst case, these variables will just all be false.
1113 hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
1114 hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
1115 // Keep in sync with crypto/aes/cipher_s390x.go.
1116 hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
1118 hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
1121 if hasGCMAsm || boring.Enabled {
1122 // If BoringCrypto is enabled, always prioritize AES-GCM.
1123 // If AES-GCM hardware is provided then prioritise AES-GCM
1125 topCipherSuites = []uint16{
1126 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1127 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1128 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1129 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1130 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1131 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1133 varDefaultCipherSuitesTLS13 = []uint16{
1134 TLS_AES_128_GCM_SHA256,
1135 TLS_CHACHA20_POLY1305_SHA256,
1136 TLS_AES_256_GCM_SHA384,
1139 // Without AES-GCM hardware, we put the ChaCha20-Poly1305
1140 // cipher suites first.
1141 topCipherSuites = []uint16{
1142 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1143 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1144 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1145 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1146 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1147 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1149 varDefaultCipherSuitesTLS13 = []uint16{
1150 TLS_CHACHA20_POLY1305_SHA256,
1151 TLS_AES_128_GCM_SHA256,
1152 TLS_AES_256_GCM_SHA384,
1156 varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
1157 varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
1160 for _, suite := range cipherSuites {
1161 if suite.flags&suiteDefaultOff != 0 {
1164 for _, existing := range varDefaultCipherSuites {
1165 if existing == suite.id {
1166 continue NextCipherSuite
1169 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1173 func unexpectedMessageError(wanted, got interface{}) error {
1174 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1177 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1178 for _, s := range supportedSignatureAlgorithms {
1186 // signatureFromSignatureScheme maps a signature algorithm to the underlying
1187 // signature method (without hash function).
1188 func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
1189 switch signatureAlgorithm {
1190 case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
1191 return signaturePKCS1v15
1192 case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
1193 return signatureRSAPSS
1194 case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
1195 return signatureECDSA