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 // Deprecated: SSLv3 is cryptographically broken, and is no longer
35 // supported by this package. See golang.org/issue/32716.
40 maxPlaintext = 16384 // maximum plaintext payload length
41 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
42 maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3
43 recordHeaderLen = 5 // record header length
44 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
45 maxUselessRecords = 16 // maximum number of consecutive non-advancing records
52 recordTypeChangeCipherSpec recordType = 20
53 recordTypeAlert recordType = 21
54 recordTypeHandshake recordType = 22
55 recordTypeApplicationData recordType = 23
58 // TLS handshake message types.
60 typeHelloRequest uint8 = 0
61 typeClientHello uint8 = 1
62 typeServerHello uint8 = 2
63 typeNewSessionTicket uint8 = 4
64 typeEndOfEarlyData uint8 = 5
65 typeEncryptedExtensions uint8 = 8
66 typeCertificate uint8 = 11
67 typeServerKeyExchange uint8 = 12
68 typeCertificateRequest uint8 = 13
69 typeServerHelloDone uint8 = 14
70 typeCertificateVerify uint8 = 15
71 typeClientKeyExchange uint8 = 16
72 typeFinished uint8 = 20
73 typeCertificateStatus uint8 = 22
74 typeKeyUpdate uint8 = 24
75 typeNextProtocol uint8 = 67 // Not IANA assigned
76 typeMessageHash uint8 = 254 // synthetic message
79 // TLS compression types.
81 compressionNone uint8 = 0
84 // TLS extension numbers
86 extensionServerName uint16 = 0
87 extensionStatusRequest uint16 = 5
88 extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
89 extensionSupportedPoints uint16 = 11
90 extensionSignatureAlgorithms uint16 = 13
91 extensionALPN uint16 = 16
92 extensionSCT uint16 = 18
93 extensionSessionTicket uint16 = 35
94 extensionPreSharedKey uint16 = 41
95 extensionEarlyData uint16 = 42
96 extensionSupportedVersions uint16 = 43
97 extensionCookie uint16 = 44
98 extensionPSKModes uint16 = 45
99 extensionCertificateAuthorities uint16 = 47
100 extensionSignatureAlgorithmsCert uint16 = 50
101 extensionKeyShare uint16 = 51
102 extensionRenegotiationInfo uint16 = 0xff01
105 // TLS signaling cipher suite values
107 scsvRenegotiation uint16 = 0x00ff
110 // CurveID is the type of a TLS identifier for an elliptic curve. See
111 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
113 // In TLS 1.3, this type is called NamedGroup, but at this time this library
114 // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
118 CurveP256 CurveID = 23
119 CurveP384 CurveID = 24
120 CurveP521 CurveID = 25
124 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
125 type keyShare struct {
130 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
132 pskModePlain uint8 = 0
136 // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
137 // session. See RFC 8446, Section 4.2.11.
138 type pskIdentity struct {
140 obfuscatedTicketAge uint32
143 // TLS Elliptic Curve Point Formats
144 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
146 pointFormatUncompressed uint8 = 0
149 // TLS CertificateStatusType (RFC 3546)
151 statusTypeOCSP uint8 = 1
154 // Certificate types (for certificateRequestMsg)
157 certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
160 // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
161 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
163 signaturePKCS1v15 uint8 = iota + 225
169 // directSigning is a standard Hash value that signals that no pre-hashing
170 // should be performed, and that the input should be signed directly. It is the
171 // hash function associated with the Ed25519 signature scheme.
172 var directSigning crypto.Hash = 0
174 // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
175 // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
176 // CertificateRequest. The two fields are merged to match with TLS 1.3.
177 // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
178 var defaultSupportedSignatureAlgorithms = []SignatureScheme{
180 ECDSAWithP256AndSHA256,
187 ECDSAWithP384AndSHA384,
188 ECDSAWithP521AndSHA512,
193 // helloRetryRequestRandom is set as the Random value of a ServerHello
194 // to signal that the message is actually a HelloRetryRequest.
195 var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
196 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
197 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
198 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
199 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
203 // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
204 // random as a downgrade protection if the server would be capable of
205 // negotiating a higher version. See RFC 8446, Section 4.1.3.
206 downgradeCanaryTLS12 = "DOWNGRD\x01"
207 downgradeCanaryTLS11 = "DOWNGRD\x00"
210 // testingOnlyForceDowngradeCanary is set in tests to force the server side to
211 // include downgrade canaries even if it's using its highers supported version.
212 var testingOnlyForceDowngradeCanary bool
214 // ConnectionState records basic TLS details about the connection.
215 type ConnectionState struct {
216 // Version is the TLS version used by the connection (e.g. VersionTLS12).
219 // HandshakeComplete is true if the handshake has concluded.
220 HandshakeComplete bool
222 // DidResume is true if this connection was successfully resumed from a
223 // previous session with a session ticket or similar mechanism.
226 // CipherSuite is the cipher suite negotiated for the connection (e.g.
227 // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
230 // NegotiatedProtocol is the application protocol negotiated with ALPN.
232 // Note that on the client side, this is currently not guaranteed to be from
233 // Config.NextProtos.
234 NegotiatedProtocol string
236 // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
238 // Deprecated: this value is always true.
239 NegotiatedProtocolIsMutual bool
241 // ServerName is the value of the Server Name Indication extension sent by
242 // the client. It's available both on the server and on the client side.
245 // PeerCertificates are the parsed certificates sent by the peer, in the
246 // order in which they were sent. The first element is the leaf certificate
247 // that the connection is verified against.
249 // On the client side, it can't be empty. On the server side, it can be
250 // empty if Config.ClientAuth is not RequireAnyClientCert or
251 // RequireAndVerifyClientCert.
252 PeerCertificates []*x509.Certificate
254 // VerifiedChains is a list of one or more chains where the first element is
255 // PeerCertificates[0] and the last element is from Config.RootCAs (on the
256 // client side) or Config.ClientCAs (on the server side).
258 // On the client side, it's set if Config.InsecureSkipVerify is false. On
259 // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
260 // (and the peer provided a certificate) or RequireAndVerifyClientCert.
261 VerifiedChains [][]*x509.Certificate
263 // SignedCertificateTimestamps is a list of SCTs provided by the peer
264 // through the TLS handshake for the leaf certificate, if any.
265 SignedCertificateTimestamps [][]byte
267 // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
268 // response provided by the peer for the leaf certificate, if any.
271 // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
272 // Section 3). This value will be nil for TLS 1.3 connections and for all
273 // resumed connections.
275 // Deprecated: there are conditions in which this value might not be unique
276 // to a connection. See the Security Considerations sections of RFC 5705 and
277 // RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
280 // ekm is a closure exposed via ExportKeyingMaterial.
281 ekm func(label string, context []byte, length int) ([]byte, error)
284 // ExportKeyingMaterial returns length bytes of exported key material in a new
285 // slice as defined in RFC 5705. If context is nil, it is not used as part of
286 // the seed. If the connection was set to allow renegotiation via
287 // Config.Renegotiation, this function will return an error.
288 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
289 return cs.ekm(label, context, length)
292 // ClientAuthType declares the policy the server will follow for
293 // TLS Client Authentication.
294 type ClientAuthType int
297 NoClientCert ClientAuthType = iota
300 VerifyClientCertIfGiven
301 RequireAndVerifyClientCert
304 // requiresClientCert reports whether the ClientAuthType requires a client
305 // certificate to be provided.
306 func requiresClientCert(c ClientAuthType) bool {
308 case RequireAnyClientCert, RequireAndVerifyClientCert:
315 // ClientSessionState contains the state needed by clients to resume TLS
317 type ClientSessionState struct {
318 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
319 vers uint16 // TLS version negotiated for the session
320 cipherSuite uint16 // Ciphersuite negotiated for the session
321 masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
322 serverCertificates []*x509.Certificate // Certificate chain presented by the server
323 verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
324 receivedAt time.Time // When the session ticket was received from the server
325 ocspResponse []byte // Stapled OCSP response presented by the server
326 scts [][]byte // SCTs presented by the server
329 nonce []byte // Ticket nonce sent by the server, to derive PSK
330 useBy time.Time // Expiration of the ticket lifetime as set by the server
331 ageAdd uint32 // Random obfuscation factor for sending the ticket age
334 // ClientSessionCache is a cache of ClientSessionState objects that can be used
335 // by a client to resume a TLS session with a given server. ClientSessionCache
336 // implementations should expect to be called concurrently from different
337 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
338 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
339 // are supported via this interface.
340 type ClientSessionCache interface {
341 // Get searches for a ClientSessionState associated with the given key.
342 // On return, ok is true if one was found.
343 Get(sessionKey string) (session *ClientSessionState, ok bool)
345 // Put adds the ClientSessionState to the cache with the given key. It might
346 // get called multiple times in a connection if a TLS 1.3 server provides
347 // more than one session ticket. If called with a nil *ClientSessionState,
348 // it should remove the cache entry.
349 Put(sessionKey string, cs *ClientSessionState)
352 //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
354 // SignatureScheme identifies a signature algorithm supported by TLS. See
355 // RFC 8446, Section 4.2.3.
356 type SignatureScheme uint16
359 // RSASSA-PKCS1-v1_5 algorithms.
360 PKCS1WithSHA256 SignatureScheme = 0x0401
361 PKCS1WithSHA384 SignatureScheme = 0x0501
362 PKCS1WithSHA512 SignatureScheme = 0x0601
364 // RSASSA-PSS algorithms with public key OID rsaEncryption.
365 PSSWithSHA256 SignatureScheme = 0x0804
366 PSSWithSHA384 SignatureScheme = 0x0805
367 PSSWithSHA512 SignatureScheme = 0x0806
369 // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
370 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
371 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
372 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
375 Ed25519 SignatureScheme = 0x0807
377 // Legacy signature and hash algorithms for TLS 1.2.
378 PKCS1WithSHA1 SignatureScheme = 0x0201
379 ECDSAWithSHA1 SignatureScheme = 0x0203
382 // ClientHelloInfo contains information from a ClientHello message in order to
383 // guide application logic in the GetCertificate and GetConfigForClient callbacks.
384 type ClientHelloInfo struct {
385 // CipherSuites lists the CipherSuites supported by the client (e.g.
386 // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
387 CipherSuites []uint16
389 // ServerName indicates the name of the server requested by the client
390 // in order to support virtual hosting. ServerName is only set if the
391 // client is using SNI (see RFC 4366, Section 3.1).
394 // SupportedCurves lists the elliptic curves supported by the client.
395 // SupportedCurves is set only if the Supported Elliptic Curves
396 // Extension is being used (see RFC 4492, Section 5.1.1).
397 SupportedCurves []CurveID
399 // SupportedPoints lists the point formats supported by the client.
400 // SupportedPoints is set only if the Supported Point Formats Extension
401 // is being used (see RFC 4492, Section 5.1.2).
402 SupportedPoints []uint8
404 // SignatureSchemes lists the signature and hash schemes that the client
405 // is willing to verify. SignatureSchemes is set only if the Signature
406 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
407 SignatureSchemes []SignatureScheme
409 // SupportedProtos lists the application protocols supported by the client.
410 // SupportedProtos is set only if the Application-Layer Protocol
411 // Negotiation Extension is being used (see RFC 7301, Section 3.1).
413 // Servers can select a protocol by setting Config.NextProtos in a
414 // GetConfigForClient return value.
415 SupportedProtos []string
417 // SupportedVersions lists the TLS versions supported by the client.
418 // For TLS versions less than 1.3, this is extrapolated from the max
419 // version advertised by the client, so values other than the greatest
420 // might be rejected if used.
421 SupportedVersions []uint16
423 // Conn is the underlying net.Conn for the connection. Do not read
424 // from, or write to, this connection; that will cause the TLS
425 // connection to fail.
428 // config is embedded by the GetCertificate or GetConfigForClient caller,
429 // for use with SupportsCertificate.
433 // CertificateRequestInfo contains information from a server's
434 // CertificateRequest message, which is used to demand a certificate and proof
435 // of control from a client.
436 type CertificateRequestInfo struct {
437 // AcceptableCAs contains zero or more, DER-encoded, X.501
438 // Distinguished Names. These are the names of root or intermediate CAs
439 // that the server wishes the returned certificate to be signed by. An
440 // empty slice indicates that the server has no preference.
441 AcceptableCAs [][]byte
443 // SignatureSchemes lists the signature schemes that the server is
444 // willing to verify.
445 SignatureSchemes []SignatureScheme
447 // Version is the TLS version that was negotiated for this connection.
451 // RenegotiationSupport enumerates the different levels of support for TLS
452 // renegotiation. TLS renegotiation is the act of performing subsequent
453 // handshakes on a connection after the first. This significantly complicates
454 // the state machine and has been the source of numerous, subtle security
455 // issues. Initiating a renegotiation is not supported, but support for
456 // accepting renegotiation requests may be enabled.
458 // Even when enabled, the server may not change its identity between handshakes
459 // (i.e. the leaf certificate must be the same). Additionally, concurrent
460 // handshake and application data flow is not permitted so renegotiation can
461 // only be used with protocols that synchronise with the renegotiation, such as
464 // Renegotiation is not defined in TLS 1.3.
465 type RenegotiationSupport int
468 // RenegotiateNever disables renegotiation.
469 RenegotiateNever RenegotiationSupport = iota
471 // RenegotiateOnceAsClient allows a remote server to request
472 // renegotiation once per connection.
473 RenegotiateOnceAsClient
475 // RenegotiateFreelyAsClient allows a remote server to repeatedly
476 // request renegotiation.
477 RenegotiateFreelyAsClient
480 // A Config structure is used to configure a TLS client or server.
481 // After one has been passed to a TLS function it must not be
482 // modified. A Config may be reused; the tls package will also not
485 // Rand provides the source of entropy for nonces and RSA blinding.
486 // If Rand is nil, TLS uses the cryptographic random reader in package
488 // The Reader must be safe for use by multiple goroutines.
491 // Time returns the current time as the number of seconds since the epoch.
492 // If Time is nil, TLS uses time.Now.
493 Time func() time.Time
495 // Certificates contains one or more certificate chains to present to the
496 // other side of the connection. The first certificate compatible with the
497 // peer's requirements is selected automatically.
499 // Server configurations must set one of Certificates, GetCertificate or
500 // GetConfigForClient. Clients doing client-authentication may set either
501 // Certificates or GetClientCertificate.
503 // Note: if there are multiple Certificates, and they don't have the
504 // optional field Leaf set, certificate selection will incur a significant
505 // per-handshake performance cost.
506 Certificates []Certificate
508 // NameToCertificate maps from a certificate name to an element of
509 // Certificates. Note that a certificate name can be of the form
510 // '*.example.com' and so doesn't have to be a domain name as such.
512 // Deprecated: NameToCertificate only allows associating a single
513 // certificate with a given name. Leave this field nil to let the library
514 // select the first compatible chain from Certificates.
515 NameToCertificate map[string]*Certificate
517 // GetCertificate returns a Certificate based on the given
518 // ClientHelloInfo. It will only be called if the client supplies SNI
519 // information or if Certificates is empty.
521 // If GetCertificate is nil or returns nil, then the certificate is
522 // retrieved from NameToCertificate. If NameToCertificate is nil, the
523 // best element of Certificates will be used.
524 GetCertificate func(*ClientHelloInfo) (*Certificate, error)
526 // GetClientCertificate, if not nil, is called when a server requests a
527 // certificate from a client. If set, the contents of Certificates will
530 // If GetClientCertificate returns an error, the handshake will be
531 // aborted and that error will be returned. Otherwise
532 // GetClientCertificate must return a non-nil Certificate. If
533 // Certificate.Certificate is empty then no certificate will be sent to
534 // the server. If this is unacceptable to the server then it may abort
537 // GetClientCertificate may be called multiple times for the same
538 // connection if renegotiation occurs or if TLS 1.3 is in use.
539 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
541 // GetConfigForClient, if not nil, is called after a ClientHello is
542 // received from a client. It may return a non-nil Config in order to
543 // change the Config that will be used to handle this connection. If
544 // the returned Config is nil, the original Config will be used. The
545 // Config returned by this callback may not be subsequently modified.
547 // If GetConfigForClient is nil, the Config passed to Server() will be
548 // used for all connections.
550 // If SessionTicketKey was explicitly set on the returned Config, or if
551 // SetSessionTicketKeys was called on the returned Config, those keys will
552 // be used. Otherwise, the original Config keys will be used (and possibly
553 // rotated if they are automatically managed).
554 GetConfigForClient func(*ClientHelloInfo) (*Config, error)
556 // VerifyPeerCertificate, if not nil, is called after normal
557 // certificate verification by either a TLS client or server. It
558 // receives the raw ASN.1 certificates provided by the peer and also
559 // any verified chains that normal processing found. If it returns a
560 // non-nil error, the handshake is aborted and that error results.
562 // If normal verification fails then the handshake will abort before
563 // considering this callback. If normal verification is disabled by
564 // setting InsecureSkipVerify, or (for a server) when ClientAuth is
565 // RequestClientCert or RequireAnyClientCert, then this callback will
566 // be considered but the verifiedChains argument will always be nil.
567 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
569 // VerifyConnection, if not nil, is called after normal certificate
570 // verification and after VerifyPeerCertificate by either a TLS client
571 // or server. If it returns a non-nil error, the handshake is aborted
572 // and that error results.
574 // If normal verification fails then the handshake will abort before
575 // considering this callback. This callback will run for all connections
576 // regardless of InsecureSkipVerify or ClientAuth settings.
577 VerifyConnection func(ConnectionState) error
579 // RootCAs defines the set of root certificate authorities
580 // that clients use when verifying server certificates.
581 // If RootCAs is nil, TLS uses the host's root CA set.
582 RootCAs *x509.CertPool
584 // NextProtos is a list of supported application level protocols, in
585 // order of preference.
588 // ServerName is used to verify the hostname on the returned
589 // certificates unless InsecureSkipVerify is given. It is also included
590 // in the client's handshake to support virtual hosting unless it is
594 // ClientAuth determines the server's policy for
595 // TLS Client Authentication. The default is NoClientCert.
596 ClientAuth ClientAuthType
598 // ClientCAs defines the set of root certificate authorities
599 // that servers use if required to verify a client certificate
600 // by the policy in ClientAuth.
601 ClientCAs *x509.CertPool
603 // InsecureSkipVerify controls whether a client verifies the server's
604 // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
605 // accepts any certificate presented by the server and any host name in that
606 // certificate. In this mode, TLS is susceptible to machine-in-the-middle
607 // attacks unless custom verification is used. This should be used only for
608 // testing or in combination with VerifyConnection or VerifyPeerCertificate.
609 InsecureSkipVerify bool
611 // CipherSuites is a list of supported cipher suites for TLS versions up to
612 // TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites
613 // is used, with a preference order based on hardware performance. The
614 // default cipher suites might change over Go versions. Note that TLS 1.3
615 // ciphersuites are not configurable.
616 CipherSuites []uint16
618 // PreferServerCipherSuites controls whether the server selects the
619 // client's most preferred ciphersuite, or the server's most preferred
620 // ciphersuite. If true then the server's preference, as expressed in
621 // the order of elements in CipherSuites, is used.
622 PreferServerCipherSuites bool
624 // SessionTicketsDisabled may be set to true to disable session ticket and
625 // PSK (resumption) support. Note that on clients, session ticket support is
626 // also disabled if ClientSessionCache is nil.
627 SessionTicketsDisabled bool
629 // SessionTicketKey is used by TLS servers to provide session resumption.
630 // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
631 // with random data before the first server handshake.
633 // Deprecated: if this field is left at zero, session ticket keys will be
634 // automatically rotated every day and dropped after seven days. For
635 // customizing the rotation schedule or synchronizing servers that are
636 // terminating connections for the same host, use SetSessionTicketKeys.
637 SessionTicketKey [32]byte
639 // ClientSessionCache is a cache of ClientSessionState entries for TLS
640 // session resumption. It is only used by clients.
641 ClientSessionCache ClientSessionCache
643 // MinVersion contains the minimum TLS version that is acceptable.
644 // If zero, TLS 1.0 is currently taken as the minimum.
647 // MaxVersion contains the maximum TLS version that is acceptable.
648 // If zero, the maximum version supported by this package is used,
649 // which is currently TLS 1.3.
652 // CurvePreferences contains the elliptic curves that will be used in
653 // an ECDHE handshake, in preference order. If empty, the default will
654 // be used. The client will use the first preference as the type for
655 // its key share in TLS 1.3. This may change in the future.
656 CurvePreferences []CurveID
658 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
659 // When true, the largest possible TLS record size is always used. When
660 // false, the size of TLS records may be adjusted in an attempt to
662 DynamicRecordSizingDisabled bool
664 // Renegotiation controls what types of renegotiation are supported.
665 // The default, none, is correct for the vast majority of applications.
666 Renegotiation RenegotiationSupport
668 // KeyLogWriter optionally specifies a destination for TLS master secrets
669 // in NSS key log format that can be used to allow external programs
670 // such as Wireshark to decrypt TLS connections.
671 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
672 // Use of KeyLogWriter compromises security and should only be
673 // used for debugging.
674 KeyLogWriter io.Writer
676 // mutex protects sessionTicketKeys and autoSessionTicketKeys.
678 // sessionTicketKeys contains zero or more ticket keys. If set, it means the
679 // the keys were set with SessionTicketKey or SetSessionTicketKeys. The
680 // first key is used for new tickets and any subsequent keys can be used to
681 // decrypt old tickets. The slice contents are not protected by the mutex
682 // and are immutable.
683 sessionTicketKeys []ticketKey
684 // autoSessionTicketKeys is like sessionTicketKeys but is owned by the
685 // auto-rotation logic. See Config.ticketKeys.
686 autoSessionTicketKeys []ticketKey
690 // ticketKeyNameLen is the number of bytes of identifier that is prepended to
691 // an encrypted session ticket in order to identify the key used to encrypt it.
692 ticketKeyNameLen = 16
694 // ticketKeyLifetime is how long a ticket key remains valid and can be used to
695 // resume a client connection.
696 ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
698 // ticketKeyRotation is how often the server should rotate the session ticket key
699 // that is used for new tickets.
700 ticketKeyRotation = 24 * time.Hour
703 // ticketKey is the internal representation of a session ticket key.
704 type ticketKey struct {
705 // keyName is an opaque byte string that serves to identify the session
706 // ticket key. It's exposed as plaintext in every session ticket.
707 keyName [ticketKeyNameLen]byte
710 // created is the time at which this ticket key was created. See Config.ticketKeys.
714 // ticketKeyFromBytes converts from the external representation of a session
715 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
716 // bytes and this function expands that into sufficient name and key material.
717 func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
718 hashed := sha512.Sum512(b[:])
719 copy(key.keyName[:], hashed[:ticketKeyNameLen])
720 copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
721 copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
722 key.created = c.time()
726 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
727 // ticket, and the lifetime we set for tickets we send.
728 const maxSessionTicketLifetime = 7 * 24 * time.Hour
730 // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
731 // being used concurrently by a TLS client or server.
732 func (c *Config) Clone() *Config {
737 defer c.mutex.RUnlock()
741 Certificates: c.Certificates,
742 NameToCertificate: c.NameToCertificate,
743 GetCertificate: c.GetCertificate,
744 GetClientCertificate: c.GetClientCertificate,
745 GetConfigForClient: c.GetConfigForClient,
746 VerifyPeerCertificate: c.VerifyPeerCertificate,
747 VerifyConnection: c.VerifyConnection,
749 NextProtos: c.NextProtos,
750 ServerName: c.ServerName,
751 ClientAuth: c.ClientAuth,
752 ClientCAs: c.ClientCAs,
753 InsecureSkipVerify: c.InsecureSkipVerify,
754 CipherSuites: c.CipherSuites,
755 PreferServerCipherSuites: c.PreferServerCipherSuites,
756 SessionTicketsDisabled: c.SessionTicketsDisabled,
757 SessionTicketKey: c.SessionTicketKey,
758 ClientSessionCache: c.ClientSessionCache,
759 MinVersion: c.MinVersion,
760 MaxVersion: c.MaxVersion,
761 CurvePreferences: c.CurvePreferences,
762 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
763 Renegotiation: c.Renegotiation,
764 KeyLogWriter: c.KeyLogWriter,
765 sessionTicketKeys: c.sessionTicketKeys,
766 autoSessionTicketKeys: c.autoSessionTicketKeys,
770 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
771 // randomized for backwards compatibility but is not in use.
772 var deprecatedSessionTicketKey = []byte("DEPRECATED")
774 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
775 // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
776 func (c *Config) initLegacySessionTicketKeyRLocked() {
777 // Don't write if SessionTicketKey is already defined as our deprecated string,
778 // or if it is defined by the user but sessionTicketKeys is already set.
779 if c.SessionTicketKey != [32]byte{} &&
780 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
784 // We need to write some data, so get an exclusive lock and re-check any conditions.
786 defer c.mutex.RLock()
788 defer c.mutex.Unlock()
789 if c.SessionTicketKey == [32]byte{} {
790 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
791 panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
793 // Write the deprecated prefix at the beginning so we know we created
794 // it. This key with the DEPRECATED prefix isn't used as an actual
795 // session ticket key, and is only randomized in case the application
796 // reuses it for some reason.
797 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
798 } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
799 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
804 // ticketKeys returns the ticketKeys for this connection.
805 // If configForClient has explicitly set keys, those will
806 // be returned. Otherwise, the keys on c will be used and
807 // may be rotated if auto-managed.
808 // During rotation, any expired session ticket keys are deleted from
809 // c.sessionTicketKeys. If the session ticket key that is currently
810 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
811 // is not fresh, then a new session ticket key will be
812 // created and prepended to c.sessionTicketKeys.
813 func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
814 // If the ConfigForClient callback returned a Config with explicitly set
815 // keys, use those, otherwise just use the original Config.
816 if configForClient != nil {
817 configForClient.mutex.RLock()
818 if configForClient.SessionTicketsDisabled {
821 configForClient.initLegacySessionTicketKeyRLocked()
822 if len(configForClient.sessionTicketKeys) != 0 {
823 ret := configForClient.sessionTicketKeys
824 configForClient.mutex.RUnlock()
827 configForClient.mutex.RUnlock()
831 defer c.mutex.RUnlock()
832 if c.SessionTicketsDisabled {
835 c.initLegacySessionTicketKeyRLocked()
836 if len(c.sessionTicketKeys) != 0 {
837 return c.sessionTicketKeys
839 // Fast path for the common case where the key is fresh enough.
840 if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
841 return c.autoSessionTicketKeys
844 // autoSessionTicketKeys are managed by auto-rotation.
846 defer c.mutex.RLock()
848 defer c.mutex.Unlock()
849 // Re-check the condition in case it changed since obtaining the new lock.
850 if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
852 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
853 panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
855 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
856 valid = append(valid, c.ticketKeyFromBytes(newKey))
857 for _, k := range c.autoSessionTicketKeys {
858 // While rotating the current key, also remove any expired ones.
859 if c.time().Sub(k.created) < ticketKeyLifetime {
860 valid = append(valid, k)
863 c.autoSessionTicketKeys = valid
865 return c.autoSessionTicketKeys
868 // SetSessionTicketKeys updates the session ticket keys for a server.
870 // The first key will be used when creating new tickets, while all keys can be
871 // used for decrypting tickets. It is safe to call this function while the
872 // server is running in order to rotate the session ticket keys. The function
873 // will panic if keys is empty.
875 // Calling this function will turn off automatic session ticket key rotation.
877 // If multiple servers are terminating connections for the same host they should
878 // all have the same session ticket keys. If the session ticket keys leaks,
879 // previously recorded and future TLS connections using those keys might be
881 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
883 panic("tls: keys must have at least one key")
886 newKeys := make([]ticketKey, len(keys))
887 for i, bytes := range keys {
888 newKeys[i] = c.ticketKeyFromBytes(bytes)
892 c.sessionTicketKeys = newKeys
896 func (c *Config) rand() io.Reader {
904 func (c *Config) time() time.Time {
912 func (c *Config) cipherSuites() []uint16 {
914 return fipsCipherSuites(c)
918 s = defaultCipherSuites()
923 var supportedVersions = []uint16{
930 func (c *Config) supportedVersions() []uint16 {
931 versions := make([]uint16, 0, len(supportedVersions))
932 for _, v := range supportedVersions {
933 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
936 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
939 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
942 versions = append(versions, v)
947 func (c *Config) maxSupportedVersion() uint16 {
948 supportedVersions := c.supportedVersions()
949 if len(supportedVersions) == 0 {
952 return supportedVersions[0]
955 // supportedVersionsFromMax returns a list of supported versions derived from a
956 // legacy maximum version value. Note that only versions supported by this
957 // library are returned. Any newer peer will use supportedVersions anyway.
958 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
959 versions := make([]uint16, 0, len(supportedVersions))
960 for _, v := range supportedVersions {
964 versions = append(versions, v)
969 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
971 func (c *Config) curvePreferences() []CurveID {
973 return fipsCurvePreferences(c)
975 if c == nil || len(c.CurvePreferences) == 0 {
976 return defaultCurvePreferences
978 return c.CurvePreferences
981 func (c *Config) supportsCurve(curve CurveID) bool {
982 for _, cc := range c.curvePreferences() {
990 // mutualVersion returns the protocol version to use given the advertised
991 // versions of the peer. Priority is given to the peer preference order.
992 func (c *Config) mutualVersion(peerVersions []uint16) (uint16, bool) {
993 supportedVersions := c.supportedVersions()
994 for _, peerVersion := range peerVersions {
995 for _, v := range supportedVersions {
996 if v == peerVersion {
1004 var errNoCertificates = errors.New("tls: no certificates configured")
1006 // getCertificate returns the best certificate for the given ClientHelloInfo,
1007 // defaulting to the first element of c.Certificates.
1008 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1009 if c.GetCertificate != nil &&
1010 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1011 cert, err := c.GetCertificate(clientHello)
1012 if cert != nil || err != nil {
1017 if len(c.Certificates) == 0 {
1018 return nil, errNoCertificates
1021 if len(c.Certificates) == 1 {
1022 // There's only one choice, so no point doing any work.
1023 return &c.Certificates[0], nil
1026 if c.NameToCertificate != nil {
1027 name := strings.ToLower(clientHello.ServerName)
1028 if cert, ok := c.NameToCertificate[name]; ok {
1032 labels := strings.Split(name, ".")
1034 wildcardName := strings.Join(labels, ".")
1035 if cert, ok := c.NameToCertificate[wildcardName]; ok {
1041 for _, cert := range c.Certificates {
1042 if err := clientHello.SupportsCertificate(&cert); err == nil {
1047 // If nothing matches, return the first certificate.
1048 return &c.Certificates[0], nil
1051 // SupportsCertificate returns nil if the provided certificate is supported by
1052 // the client that sent the ClientHello. Otherwise, it returns an error
1053 // describing the reason for the incompatibility.
1055 // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
1056 // callback, this method will take into account the associated Config. Note that
1057 // if GetConfigForClient returns a different Config, the change can't be
1058 // accounted for by this method.
1060 // This function will call x509.ParseCertificate unless c.Leaf is set, which can
1061 // incur a significant performance cost.
1062 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1063 // Note we don't currently support certificate_authorities nor
1064 // signature_algorithms_cert, and don't check the algorithms of the
1065 // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1066 // Section 4.4.2.2).
1068 config := chi.config
1072 vers, ok := config.mutualVersion(chi.SupportedVersions)
1074 return errors.New("no mutually supported protocol versions")
1077 // If the client specified the name they are trying to connect to, the
1078 // certificate needs to be valid for it.
1079 if chi.ServerName != "" {
1080 x509Cert, err := c.leaf()
1082 return fmt.Errorf("failed to parse certificate: %w", err)
1084 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1085 return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1089 // supportsRSAFallback returns nil if the certificate and connection support
1090 // the static RSA key exchange, and unsupported otherwise. The logic for
1091 // supporting static RSA is completely disjoint from the logic for
1092 // supporting signed key exchanges, so we just check it as a fallback.
1093 supportsRSAFallback := func(unsupported error) error {
1094 // TLS 1.3 dropped support for the static RSA key exchange.
1095 if vers == VersionTLS13 {
1098 // The static RSA key exchange works by decrypting a challenge with the
1099 // RSA private key, not by signing, so check the PrivateKey implements
1100 // crypto.Decrypter, like *rsa.PrivateKey does.
1101 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1102 if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1108 // Finally, there needs to be a mutual cipher suite that uses the static
1109 // RSA key exchange instead of ECDHE.
1110 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1111 if c.flags&suiteECDHE != 0 {
1114 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1119 if rsaCipherSuite == nil {
1125 // If the client sent the signature_algorithms extension, ensure it supports
1126 // schemes we can use with this certificate and TLS version.
1127 if len(chi.SignatureSchemes) > 0 {
1128 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1129 return supportsRSAFallback(err)
1133 // In TLS 1.3 we are done because supported_groups is only relevant to the
1134 // ECDHE computation, point format negotiation is removed, cipher suites are
1135 // only relevant to the AEAD choice, and static RSA does not exist.
1136 if vers == VersionTLS13 {
1140 // The only signed key exchange we support is ECDHE.
1141 if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
1142 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1145 var ecdsaCipherSuite bool
1146 if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1147 switch pub := priv.Public().(type) {
1148 case *ecdsa.PublicKey:
1151 case elliptic.P256():
1153 case elliptic.P384():
1155 case elliptic.P521():
1158 return supportsRSAFallback(unsupportedCertificateError(c))
1161 for _, c := range chi.SupportedCurves {
1162 if c == curve && config.supportsCurve(c) {
1168 return errors.New("client doesn't support certificate curve")
1170 ecdsaCipherSuite = true
1171 case ed25519.PublicKey:
1172 if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1173 return errors.New("connection doesn't support Ed25519")
1175 ecdsaCipherSuite = true
1176 case *rsa.PublicKey:
1178 return supportsRSAFallback(unsupportedCertificateError(c))
1181 return supportsRSAFallback(unsupportedCertificateError(c))
1184 // Make sure that there is a mutually supported cipher suite that works with
1185 // this certificate. Cipher suite selection will then apply the logic in
1186 // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1187 cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1188 if c.flags&suiteECDHE == 0 {
1191 if c.flags&suiteECSign != 0 {
1192 if !ecdsaCipherSuite {
1196 if ecdsaCipherSuite {
1200 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1205 if cipherSuite == nil {
1206 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1212 // SupportsCertificate returns nil if the provided certificate is supported by
1213 // the server that sent the CertificateRequest. Otherwise, it returns an error
1214 // describing the reason for the incompatibility.
1215 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1216 if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1220 if len(cri.AcceptableCAs) == 0 {
1224 for j, cert := range c.Certificate {
1226 // Parse the certificate if this isn't the leaf node, or if
1227 // chain.Leaf was nil.
1228 if j != 0 || x509Cert == nil {
1230 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1231 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1235 for _, ca := range cri.AcceptableCAs {
1236 if bytes.Equal(x509Cert.RawIssuer, ca) {
1241 return errors.New("chain is not signed by an acceptable CA")
1244 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1245 // from the CommonName and SubjectAlternateName fields of each of the leaf
1248 // Deprecated: NameToCertificate only allows associating a single certificate
1249 // with a given name. Leave that field nil to let the library select the first
1250 // compatible chain from Certificates.
1251 func (c *Config) BuildNameToCertificate() {
1252 c.NameToCertificate = make(map[string]*Certificate)
1253 for i := range c.Certificates {
1254 cert := &c.Certificates[i]
1255 x509Cert, err := cert.leaf()
1259 if len(x509Cert.Subject.CommonName) > 0 {
1260 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1262 for _, san := range x509Cert.DNSNames {
1263 c.NameToCertificate[san] = cert
1269 keyLogLabelTLS12 = "CLIENT_RANDOM"
1270 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1271 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1272 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
1273 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
1276 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1277 if c.KeyLogWriter == nil {
1281 logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
1284 _, err := c.KeyLogWriter.Write(logLine)
1285 writerMutex.Unlock()
1290 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1291 // and is only for debugging, so a global mutex saves space.
1292 var writerMutex sync.Mutex
1294 // A Certificate is a chain of one or more certificates, leaf first.
1295 type Certificate struct {
1296 Certificate [][]byte
1297 // PrivateKey contains the private key corresponding to the public key in
1298 // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1299 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1300 // an RSA PublicKey.
1301 PrivateKey crypto.PrivateKey
1302 // SupportedSignatureAlgorithms is an optional list restricting what
1303 // signature algorithms the PrivateKey can be used for.
1304 SupportedSignatureAlgorithms []SignatureScheme
1305 // OCSPStaple contains an optional OCSP response which will be served
1306 // to clients that request it.
1308 // SignedCertificateTimestamps contains an optional list of Signed
1309 // Certificate Timestamps which will be served to clients that request it.
1310 SignedCertificateTimestamps [][]byte
1311 // Leaf is the parsed form of the leaf certificate, which may be initialized
1312 // using x509.ParseCertificate to reduce per-handshake processing. If nil,
1313 // the leaf certificate will be parsed as needed.
1314 Leaf *x509.Certificate
1317 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1318 // the corresponding c.Certificate[0].
1319 func (c *Certificate) leaf() (*x509.Certificate, error) {
1323 return x509.ParseCertificate(c.Certificate[0])
1326 type handshakeMessage interface {
1328 unmarshal([]byte) bool
1331 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1332 // caching strategy.
1333 type lruSessionCache struct {
1336 m map[string]*list.Element
1341 type lruSessionCacheEntry struct {
1343 state *ClientSessionState
1346 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1347 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1349 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1350 const defaultSessionCacheCapacity = 64
1353 capacity = defaultSessionCacheCapacity
1355 return &lruSessionCache{
1356 m: make(map[string]*list.Element),
1362 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1363 // corresponding to sessionKey is removed from the cache instead.
1364 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1368 if elem, ok := c.m[sessionKey]; ok {
1371 delete(c.m, sessionKey)
1373 entry := elem.Value.(*lruSessionCacheEntry)
1375 c.q.MoveToFront(elem)
1380 if c.q.Len() < c.capacity {
1381 entry := &lruSessionCacheEntry{sessionKey, cs}
1382 c.m[sessionKey] = c.q.PushFront(entry)
1387 entry := elem.Value.(*lruSessionCacheEntry)
1388 delete(c.m, entry.sessionKey)
1389 entry.sessionKey = sessionKey
1391 c.q.MoveToFront(elem)
1392 c.m[sessionKey] = elem
1395 // Get returns the ClientSessionState value associated with a given key. It
1396 // returns (nil, false) if no value is found.
1397 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1401 if elem, ok := c.m[sessionKey]; ok {
1402 c.q.MoveToFront(elem)
1403 return elem.Value.(*lruSessionCacheEntry).state, true
1408 var emptyConfig Config
1410 func defaultConfig() *Config {
1416 varDefaultCipherSuites []uint16
1417 varDefaultCipherSuitesTLS13 []uint16
1420 func defaultCipherSuites() []uint16 {
1421 once.Do(initDefaultCipherSuites)
1422 return varDefaultCipherSuites
1425 func defaultCipherSuitesTLS13() []uint16 {
1426 once.Do(initDefaultCipherSuites)
1427 return varDefaultCipherSuitesTLS13
1430 func initDefaultCipherSuites() {
1431 var topCipherSuites []uint16
1433 // Check the cpu flags for each platform that has optimized GCM implementations.
1434 // Worst case, these variables will just all be false.
1436 hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
1437 hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
1438 // Keep in sync with crypto/aes/cipher_s390x.go.
1439 hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
1441 hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
1444 if hasGCMAsm || boringEnabled {
1445 // If BoringCrypto is enabled, always prioritize AES-GCM.
1446 // If AES-GCM hardware is provided then prioritise AES-GCM
1448 topCipherSuites = []uint16{
1449 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1450 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1451 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1452 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1453 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1454 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1456 varDefaultCipherSuitesTLS13 = []uint16{
1457 TLS_AES_128_GCM_SHA256,
1458 TLS_CHACHA20_POLY1305_SHA256,
1459 TLS_AES_256_GCM_SHA384,
1462 // Without AES-GCM hardware, we put the ChaCha20-Poly1305
1463 // cipher suites first.
1464 topCipherSuites = []uint16{
1465 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1466 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1467 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1468 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1469 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1470 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1472 varDefaultCipherSuitesTLS13 = []uint16{
1473 TLS_CHACHA20_POLY1305_SHA256,
1474 TLS_AES_128_GCM_SHA256,
1475 TLS_AES_256_GCM_SHA384,
1479 varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
1480 varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
1483 for _, suite := range cipherSuites {
1484 if suite.flags&suiteDefaultOff != 0 {
1487 for _, existing := range varDefaultCipherSuites {
1488 if existing == suite.id {
1489 continue NextCipherSuite
1492 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1496 func unexpectedMessageError(wanted, got interface{}) error {
1497 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1500 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1501 for _, s := range supportedSignatureAlgorithms {