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
604 // server's certificate chain and host name.
605 // If InsecureSkipVerify is true, TLS accepts any certificate
606 // presented by the server and any host name in that certificate.
607 // In this mode, TLS is susceptible to machine-in-the-middle attacks.
608 // This should be used only for testing.
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. 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 {
734 defer c.mutex.RUnlock()
738 Certificates: c.Certificates,
739 NameToCertificate: c.NameToCertificate,
740 GetCertificate: c.GetCertificate,
741 GetClientCertificate: c.GetClientCertificate,
742 GetConfigForClient: c.GetConfigForClient,
743 VerifyPeerCertificate: c.VerifyPeerCertificate,
744 VerifyConnection: c.VerifyConnection,
746 NextProtos: c.NextProtos,
747 ServerName: c.ServerName,
748 ClientAuth: c.ClientAuth,
749 ClientCAs: c.ClientCAs,
750 InsecureSkipVerify: c.InsecureSkipVerify,
751 CipherSuites: c.CipherSuites,
752 PreferServerCipherSuites: c.PreferServerCipherSuites,
753 SessionTicketsDisabled: c.SessionTicketsDisabled,
754 SessionTicketKey: c.SessionTicketKey,
755 ClientSessionCache: c.ClientSessionCache,
756 MinVersion: c.MinVersion,
757 MaxVersion: c.MaxVersion,
758 CurvePreferences: c.CurvePreferences,
759 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
760 Renegotiation: c.Renegotiation,
761 KeyLogWriter: c.KeyLogWriter,
762 sessionTicketKeys: c.sessionTicketKeys,
763 autoSessionTicketKeys: c.autoSessionTicketKeys,
767 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
768 // randomized for backwards compatibility but is not in use.
769 var deprecatedSessionTicketKey = []byte("DEPRECATED")
771 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
772 // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
773 func (c *Config) initLegacySessionTicketKeyRLocked() {
774 // Don't write if SessionTicketKey is already defined as our deprecated string,
775 // or if it is defined by the user but sessionTicketKeys is already set.
776 if c.SessionTicketKey != [32]byte{} &&
777 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
781 // We need to write some data, so get an exclusive lock and re-check any conditions.
783 defer c.mutex.RLock()
785 defer c.mutex.Unlock()
786 if c.SessionTicketKey == [32]byte{} {
787 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
788 panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
790 // Write the deprecated prefix at the beginning so we know we created
791 // it. This key with the DEPRECATED prefix isn't used as an actual
792 // session ticket key, and is only randomized in case the application
793 // reuses it for some reason.
794 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
795 } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
796 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
801 // ticketKeys returns the ticketKeys for this connection.
802 // If configForClient has explicitly set keys, those will
803 // be returned. Otherwise, the keys on c will be used and
804 // may be rotated if auto-managed.
805 // During rotation, any expired session ticket keys are deleted from
806 // c.sessionTicketKeys. If the session ticket key that is currently
807 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
808 // is not fresh, then a new session ticket key will be
809 // created and prepended to c.sessionTicketKeys.
810 func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
811 // If the ConfigForClient callback returned a Config with explicitly set
812 // keys, use those, otherwise just use the original Config.
813 if configForClient != nil {
814 configForClient.mutex.RLock()
815 if configForClient.SessionTicketsDisabled {
818 configForClient.initLegacySessionTicketKeyRLocked()
819 if len(configForClient.sessionTicketKeys) != 0 {
820 ret := configForClient.sessionTicketKeys
821 configForClient.mutex.RUnlock()
824 configForClient.mutex.RUnlock()
828 defer c.mutex.RUnlock()
829 if c.SessionTicketsDisabled {
832 c.initLegacySessionTicketKeyRLocked()
833 if len(c.sessionTicketKeys) != 0 {
834 return c.sessionTicketKeys
836 // Fast path for the common case where the key is fresh enough.
837 if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
838 return c.autoSessionTicketKeys
841 // autoSessionTicketKeys are managed by auto-rotation.
843 defer c.mutex.RLock()
845 defer c.mutex.Unlock()
846 // Re-check the condition in case it changed since obtaining the new lock.
847 if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
849 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
850 panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
852 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
853 valid = append(valid, c.ticketKeyFromBytes(newKey))
854 for _, k := range c.autoSessionTicketKeys {
855 // While rotating the current key, also remove any expired ones.
856 if c.time().Sub(k.created) < ticketKeyLifetime {
857 valid = append(valid, k)
860 c.autoSessionTicketKeys = valid
862 return c.autoSessionTicketKeys
865 // SetSessionTicketKeys updates the session ticket keys for a server.
867 // The first key will be used when creating new tickets, while all keys can be
868 // used for decrypting tickets. It is safe to call this function while the
869 // server is running in order to rotate the session ticket keys. The function
870 // will panic if keys is empty.
872 // Calling this function will turn off automatic session ticket key rotation.
874 // If multiple servers are terminating connections for the same host they should
875 // all have the same session ticket keys. If the session ticket keys leaks,
876 // previously recorded and future TLS connections using those keys might be
878 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
880 panic("tls: keys must have at least one key")
883 newKeys := make([]ticketKey, len(keys))
884 for i, bytes := range keys {
885 newKeys[i] = c.ticketKeyFromBytes(bytes)
889 c.sessionTicketKeys = newKeys
893 func (c *Config) rand() io.Reader {
901 func (c *Config) time() time.Time {
909 func (c *Config) cipherSuites() []uint16 {
911 return fipsCipherSuites(c)
915 s = defaultCipherSuites()
920 var supportedVersions = []uint16{
927 func (c *Config) supportedVersions() []uint16 {
928 versions := make([]uint16, 0, len(supportedVersions))
929 for _, v := range supportedVersions {
930 if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
933 if c != nil && c.MinVersion != 0 && v < c.MinVersion {
936 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
939 versions = append(versions, v)
944 func (c *Config) maxSupportedVersion() uint16 {
945 supportedVersions := c.supportedVersions()
946 if len(supportedVersions) == 0 {
949 return supportedVersions[0]
952 // supportedVersionsFromMax returns a list of supported versions derived from a
953 // legacy maximum version value. Note that only versions supported by this
954 // library are returned. Any newer peer will use supportedVersions anyway.
955 func supportedVersionsFromMax(maxVersion uint16) []uint16 {
956 versions := make([]uint16, 0, len(supportedVersions))
957 for _, v := range supportedVersions {
961 versions = append(versions, v)
966 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
968 func (c *Config) curvePreferences() []CurveID {
970 return fipsCurvePreferences(c)
972 if c == nil || len(c.CurvePreferences) == 0 {
973 return defaultCurvePreferences
975 return c.CurvePreferences
978 func (c *Config) supportsCurve(curve CurveID) bool {
979 for _, cc := range c.curvePreferences() {
987 // mutualVersion returns the protocol version to use given the advertised
988 // versions of the peer. Priority is given to the peer preference order.
989 func (c *Config) mutualVersion(peerVersions []uint16) (uint16, bool) {
990 supportedVersions := c.supportedVersions()
991 for _, peerVersion := range peerVersions {
992 for _, v := range supportedVersions {
993 if v == peerVersion {
1001 var errNoCertificates = errors.New("tls: no certificates configured")
1003 // getCertificate returns the best certificate for the given ClientHelloInfo,
1004 // defaulting to the first element of c.Certificates.
1005 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
1006 if c.GetCertificate != nil &&
1007 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
1008 cert, err := c.GetCertificate(clientHello)
1009 if cert != nil || err != nil {
1014 if len(c.Certificates) == 0 {
1015 return nil, errNoCertificates
1018 if len(c.Certificates) == 1 {
1019 // There's only one choice, so no point doing any work.
1020 return &c.Certificates[0], nil
1023 if c.NameToCertificate != nil {
1024 name := strings.ToLower(clientHello.ServerName)
1025 if cert, ok := c.NameToCertificate[name]; ok {
1029 labels := strings.Split(name, ".")
1031 wildcardName := strings.Join(labels, ".")
1032 if cert, ok := c.NameToCertificate[wildcardName]; ok {
1038 for _, cert := range c.Certificates {
1039 if err := clientHello.SupportsCertificate(&cert); err == nil {
1044 // If nothing matches, return the first certificate.
1045 return &c.Certificates[0], nil
1048 // SupportsCertificate returns nil if the provided certificate is supported by
1049 // the client that sent the ClientHello. Otherwise, it returns an error
1050 // describing the reason for the incompatibility.
1052 // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
1053 // callback, this method will take into account the associated Config. Note that
1054 // if GetConfigForClient returns a different Config, the change can't be
1055 // accounted for by this method.
1057 // This function will call x509.ParseCertificate unless c.Leaf is set, which can
1058 // incur a significant performance cost.
1059 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
1060 // Note we don't currently support certificate_authorities nor
1061 // signature_algorithms_cert, and don't check the algorithms of the
1062 // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
1063 // Section 4.4.2.2).
1065 config := chi.config
1069 vers, ok := config.mutualVersion(chi.SupportedVersions)
1071 return errors.New("no mutually supported protocol versions")
1074 // If the client specified the name they are trying to connect to, the
1075 // certificate needs to be valid for it.
1076 if chi.ServerName != "" {
1077 x509Cert, err := c.leaf()
1079 return fmt.Errorf("failed to parse certificate: %w", err)
1081 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
1082 return fmt.Errorf("certificate is not valid for requested server name: %w", err)
1086 // supportsRSAFallback returns nil if the certificate and connection support
1087 // the static RSA key exchange, and unsupported otherwise. The logic for
1088 // supporting static RSA is completely disjoint from the logic for
1089 // supporting signed key exchanges, so we just check it as a fallback.
1090 supportsRSAFallback := func(unsupported error) error {
1091 // TLS 1.3 dropped support for the static RSA key exchange.
1092 if vers == VersionTLS13 {
1095 // The static RSA key exchange works by decrypting a challenge with the
1096 // RSA private key, not by signing, so check the PrivateKey implements
1097 // crypto.Decrypter, like *rsa.PrivateKey does.
1098 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
1099 if _, ok := priv.Public().(*rsa.PublicKey); !ok {
1105 // Finally, there needs to be a mutual cipher suite that uses the static
1106 // RSA key exchange instead of ECDHE.
1107 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1108 if c.flags&suiteECDHE != 0 {
1111 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1116 if rsaCipherSuite == nil {
1122 // If the client sent the signature_algorithms extension, ensure it supports
1123 // schemes we can use with this certificate and TLS version.
1124 if len(chi.SignatureSchemes) > 0 {
1125 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
1126 return supportsRSAFallback(err)
1130 // In TLS 1.3 we are done because supported_groups is only relevant to the
1131 // ECDHE computation, point format negotiation is removed, cipher suites are
1132 // only relevant to the AEAD choice, and static RSA does not exist.
1133 if vers == VersionTLS13 {
1137 // The only signed key exchange we support is ECDHE.
1138 if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
1139 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
1142 var ecdsaCipherSuite bool
1143 if priv, ok := c.PrivateKey.(crypto.Signer); ok {
1144 switch pub := priv.Public().(type) {
1145 case *ecdsa.PublicKey:
1148 case elliptic.P256():
1150 case elliptic.P384():
1152 case elliptic.P521():
1155 return supportsRSAFallback(unsupportedCertificateError(c))
1158 for _, c := range chi.SupportedCurves {
1159 if c == curve && config.supportsCurve(c) {
1165 return errors.New("client doesn't support certificate curve")
1167 ecdsaCipherSuite = true
1168 case ed25519.PublicKey:
1169 if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
1170 return errors.New("connection doesn't support Ed25519")
1172 ecdsaCipherSuite = true
1173 case *rsa.PublicKey:
1175 return supportsRSAFallback(unsupportedCertificateError(c))
1178 return supportsRSAFallback(unsupportedCertificateError(c))
1181 // Make sure that there is a mutually supported cipher suite that works with
1182 // this certificate. Cipher suite selection will then apply the logic in
1183 // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
1184 cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
1185 if c.flags&suiteECDHE == 0 {
1188 if c.flags&suiteECSign != 0 {
1189 if !ecdsaCipherSuite {
1193 if ecdsaCipherSuite {
1197 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
1202 if cipherSuite == nil {
1203 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
1209 // SupportsCertificate returns nil if the provided certificate is supported by
1210 // the server that sent the CertificateRequest. Otherwise, it returns an error
1211 // describing the reason for the incompatibility.
1212 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
1213 if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
1217 if len(cri.AcceptableCAs) == 0 {
1221 for j, cert := range c.Certificate {
1223 // Parse the certificate if this isn't the leaf node, or if
1224 // chain.Leaf was nil.
1225 if j != 0 || x509Cert == nil {
1227 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1228 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
1232 for _, ca := range cri.AcceptableCAs {
1233 if bytes.Equal(x509Cert.RawIssuer, ca) {
1238 return errors.New("chain is not signed by an acceptable CA")
1241 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1242 // from the CommonName and SubjectAlternateName fields of each of the leaf
1245 // Deprecated: NameToCertificate only allows associating a single certificate
1246 // with a given name. Leave that field nil to let the library select the first
1247 // compatible chain from Certificates.
1248 func (c *Config) BuildNameToCertificate() {
1249 c.NameToCertificate = make(map[string]*Certificate)
1250 for i := range c.Certificates {
1251 cert := &c.Certificates[i]
1252 x509Cert, err := cert.leaf()
1256 if len(x509Cert.Subject.CommonName) > 0 {
1257 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1259 for _, san := range x509Cert.DNSNames {
1260 c.NameToCertificate[san] = cert
1266 keyLogLabelTLS12 = "CLIENT_RANDOM"
1267 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
1268 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
1269 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
1270 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
1273 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
1274 if c.KeyLogWriter == nil {
1278 logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
1281 _, err := c.KeyLogWriter.Write(logLine)
1282 writerMutex.Unlock()
1287 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
1288 // and is only for debugging, so a global mutex saves space.
1289 var writerMutex sync.Mutex
1291 // A Certificate is a chain of one or more certificates, leaf first.
1292 type Certificate struct {
1293 Certificate [][]byte
1294 // PrivateKey contains the private key corresponding to the public key in
1295 // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
1296 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
1297 // an RSA PublicKey.
1298 PrivateKey crypto.PrivateKey
1299 // SupportedSignatureAlgorithms is an optional list restricting what
1300 // signature algorithms the PrivateKey can be used for.
1301 SupportedSignatureAlgorithms []SignatureScheme
1302 // OCSPStaple contains an optional OCSP response which will be served
1303 // to clients that request it.
1305 // SignedCertificateTimestamps contains an optional list of Signed
1306 // Certificate Timestamps which will be served to clients that request it.
1307 SignedCertificateTimestamps [][]byte
1308 // Leaf is the parsed form of the leaf certificate, which may be initialized
1309 // using x509.ParseCertificate to reduce per-handshake processing. If nil,
1310 // the leaf certificate will be parsed as needed.
1311 Leaf *x509.Certificate
1314 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
1315 // the corresponding c.Certificate[0].
1316 func (c *Certificate) leaf() (*x509.Certificate, error) {
1320 return x509.ParseCertificate(c.Certificate[0])
1323 type handshakeMessage interface {
1325 unmarshal([]byte) bool
1328 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
1329 // caching strategy.
1330 type lruSessionCache struct {
1333 m map[string]*list.Element
1338 type lruSessionCacheEntry struct {
1340 state *ClientSessionState
1343 // NewLRUClientSessionCache returns a ClientSessionCache with the given
1344 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1346 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1347 const defaultSessionCacheCapacity = 64
1350 capacity = defaultSessionCacheCapacity
1352 return &lruSessionCache{
1353 m: make(map[string]*list.Element),
1359 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
1360 // corresponding to sessionKey is removed from the cache instead.
1361 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1365 if elem, ok := c.m[sessionKey]; ok {
1368 delete(c.m, sessionKey)
1370 entry := elem.Value.(*lruSessionCacheEntry)
1372 c.q.MoveToFront(elem)
1377 if c.q.Len() < c.capacity {
1378 entry := &lruSessionCacheEntry{sessionKey, cs}
1379 c.m[sessionKey] = c.q.PushFront(entry)
1384 entry := elem.Value.(*lruSessionCacheEntry)
1385 delete(c.m, entry.sessionKey)
1386 entry.sessionKey = sessionKey
1388 c.q.MoveToFront(elem)
1389 c.m[sessionKey] = elem
1392 // Get returns the ClientSessionState value associated with a given key. It
1393 // returns (nil, false) if no value is found.
1394 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1398 if elem, ok := c.m[sessionKey]; ok {
1399 c.q.MoveToFront(elem)
1400 return elem.Value.(*lruSessionCacheEntry).state, true
1405 var emptyConfig Config
1407 func defaultConfig() *Config {
1413 varDefaultCipherSuites []uint16
1414 varDefaultCipherSuitesTLS13 []uint16
1417 func defaultCipherSuites() []uint16 {
1418 once.Do(initDefaultCipherSuites)
1419 return varDefaultCipherSuites
1422 func defaultCipherSuitesTLS13() []uint16 {
1423 once.Do(initDefaultCipherSuites)
1424 return varDefaultCipherSuitesTLS13
1427 func initDefaultCipherSuites() {
1428 var topCipherSuites []uint16
1430 // Check the cpu flags for each platform that has optimized GCM implementations.
1431 // Worst case, these variables will just all be false.
1433 hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
1434 hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
1435 // Keep in sync with crypto/aes/cipher_s390x.go.
1436 hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
1438 hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
1441 if hasGCMAsm || boringEnabled {
1442 // If BoringCrypto is enabled, always prioritize AES-GCM.
1443 // If AES-GCM hardware is provided then prioritise AES-GCM
1445 topCipherSuites = []uint16{
1446 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1447 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1448 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1449 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1450 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1451 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1453 varDefaultCipherSuitesTLS13 = []uint16{
1454 TLS_AES_128_GCM_SHA256,
1455 TLS_CHACHA20_POLY1305_SHA256,
1456 TLS_AES_256_GCM_SHA384,
1459 // Without AES-GCM hardware, we put the ChaCha20-Poly1305
1460 // cipher suites first.
1461 topCipherSuites = []uint16{
1462 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1463 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1464 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1465 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1466 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1467 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1469 varDefaultCipherSuitesTLS13 = []uint16{
1470 TLS_CHACHA20_POLY1305_SHA256,
1471 TLS_AES_128_GCM_SHA256,
1472 TLS_AES_256_GCM_SHA384,
1476 varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
1477 varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
1480 for _, suite := range cipherSuites {
1481 if suite.flags&suiteDefaultOff != 0 {
1484 for _, existing := range varDefaultCipherSuites {
1485 if existing == suite.id {
1486 continue NextCipherSuite
1489 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1493 func unexpectedMessageError(wanted, got interface{}) error {
1494 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1497 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1498 for _, s := range supportedSignatureAlgorithms {