github.com/3andne/restls-client-go@v0.1.6/common.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls
     6  
     7  import (
     8  	"bytes"
     9  	"container/list"
    10  	"context"
    11  	"crypto"
    12  	"crypto/ecdsa"
    13  	"crypto/ed25519"
    14  	"crypto/elliptic"
    15  	"crypto/rand"
    16  	"crypto/rsa"
    17  	"crypto/sha512"
    18  	"crypto/x509"
    19  	"errors"
    20  	"fmt"
    21  	"io"
    22  	"net"
    23  	"strings"
    24  	"sync"
    25  	"sync/atomic"
    26  	"time"
    27  )
    28  
    29  const (
    30  	VersionTLS10 = 0x0301
    31  	VersionTLS11 = 0x0302
    32  	VersionTLS12 = 0x0303
    33  	VersionTLS13 = 0x0304
    34  
    35  	// Deprecated: SSLv3 is cryptographically broken, and is no longer
    36  	// supported by this package. See golang.org/issue/32716.
    37  	VersionSSL30 = 0x0300
    38  )
    39  
    40  // VersionName returns the name for the provided TLS version number
    41  // (e.g. "TLS 1.3"), or a fallback representation of the value if the
    42  // version is not implemented by this package.
    43  func VersionName(version uint16) string {
    44  	switch version {
    45  	case VersionSSL30:
    46  		return "SSLv3"
    47  	case VersionTLS10:
    48  		return "TLS 1.0"
    49  	case VersionTLS11:
    50  		return "TLS 1.1"
    51  	case VersionTLS12:
    52  		return "TLS 1.2"
    53  	case VersionTLS13:
    54  		return "TLS 1.3"
    55  	default:
    56  		return fmt.Sprintf("0x%04X", version)
    57  	}
    58  }
    59  
    60  const (
    61  	maxPlaintext       = 16384        // maximum plaintext payload length
    62  	maxCiphertext      = 16384 + 2048 // maximum ciphertext payload length
    63  	maxCiphertextTLS13 = 16384 + 256  // maximum ciphertext length in TLS 1.3
    64  	recordHeaderLen    = 5            // record header length
    65  	maxHandshake       = 65536        // maximum handshake we support (protocol max is 16 MB)
    66  	maxUselessRecords  = 32           // maximum number of consecutive non-advancing records
    67  )
    68  
    69  // TLS record types.
    70  type recordType uint8
    71  
    72  const (
    73  	recordTypeChangeCipherSpec recordType = 20
    74  	recordTypeAlert            recordType = 21
    75  	recordTypeHandshake        recordType = 22
    76  	recordTypeApplicationData  recordType = 23
    77  )
    78  
    79  // TLS handshake message types.
    80  const (
    81  	typeHelloRequest        uint8 = 0
    82  	typeClientHello         uint8 = 1
    83  	typeServerHello         uint8 = 2
    84  	typeNewSessionTicket    uint8 = 4
    85  	typeEndOfEarlyData      uint8 = 5
    86  	typeEncryptedExtensions uint8 = 8
    87  	typeCertificate         uint8 = 11
    88  	typeServerKeyExchange   uint8 = 12
    89  	typeCertificateRequest  uint8 = 13
    90  	typeServerHelloDone     uint8 = 14
    91  	typeCertificateVerify   uint8 = 15
    92  	typeClientKeyExchange   uint8 = 16
    93  	typeFinished            uint8 = 20
    94  	typeCertificateStatus   uint8 = 22
    95  	typeKeyUpdate           uint8 = 24
    96  	typeNextProtocol        uint8 = 67  // Not IANA assigned
    97  	typeMessageHash         uint8 = 254 // synthetic message
    98  )
    99  
   100  // TLS compression types.
   101  const (
   102  	compressionNone uint8 = 0
   103  )
   104  
   105  // TLS extension numbers
   106  const (
   107  	extensionServerName              uint16 = 0
   108  	extensionStatusRequest           uint16 = 5
   109  	extensionSupportedCurves         uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
   110  	extensionSupportedPoints         uint16 = 11
   111  	extensionSignatureAlgorithms     uint16 = 13
   112  	extensionALPN                    uint16 = 16
   113  	extensionStatusRequestV2         uint16 = 17
   114  	extensionSCT                     uint16 = 18
   115  	extensionExtendedMasterSecret    uint16 = 23
   116  	extensionDelegatedCredentials    uint16 = 34
   117  	extensionSessionTicket           uint16 = 35
   118  	extensionPreSharedKey            uint16 = 41
   119  	extensionEarlyData               uint16 = 42
   120  	extensionSupportedVersions       uint16 = 43
   121  	extensionCookie                  uint16 = 44
   122  	extensionPSKModes                uint16 = 45
   123  	extensionCertificateAuthorities  uint16 = 47
   124  	extensionSignatureAlgorithmsCert uint16 = 50
   125  	extensionKeyShare                uint16 = 51
   126  	extensionQUICTransportParameters uint16 = 57
   127  	extensionRenegotiationInfo       uint16 = 0xff01
   128  )
   129  
   130  // TLS signaling cipher suite values
   131  const (
   132  	scsvRenegotiation uint16 = 0x00ff
   133  )
   134  
   135  // CurveID is the type of a TLS identifier for an elliptic curve. See
   136  // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
   137  //
   138  // In TLS 1.3, this type is called NamedGroup, but at this time this library
   139  // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
   140  type CurveID uint16
   141  
   142  const (
   143  	CurveP256 CurveID = 23
   144  	CurveP384 CurveID = 24
   145  	CurveP521 CurveID = 25
   146  	X25519    CurveID = 29
   147  )
   148  
   149  // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
   150  type keyShare struct {
   151  	group CurveID
   152  	data  []byte
   153  }
   154  
   155  // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
   156  const (
   157  	pskModePlain uint8 = 0
   158  	pskModeDHE   uint8 = 1
   159  )
   160  
   161  // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
   162  // session. See RFC 8446, Section 4.2.11.
   163  type pskIdentity struct {
   164  	label               []byte
   165  	obfuscatedTicketAge uint32
   166  }
   167  
   168  // TLS Elliptic Curve Point Formats
   169  // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
   170  const (
   171  	pointFormatUncompressed uint8 = 0
   172  )
   173  
   174  // TLS CertificateStatusType (RFC 3546)
   175  const (
   176  	statusTypeOCSP   uint8 = 1
   177  	statusV2TypeOCSP uint8 = 2
   178  )
   179  
   180  // Certificate types (for certificateRequestMsg)
   181  const (
   182  	certTypeRSASign   = 1
   183  	certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
   184  )
   185  
   186  // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
   187  // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
   188  const (
   189  	signaturePKCS1v15 uint8 = iota + 225
   190  	signatureRSAPSS
   191  	signatureECDSA
   192  	signatureEd25519
   193  )
   194  
   195  // directSigning is a standard Hash value that signals that no pre-hashing
   196  // should be performed, and that the input should be signed directly. It is the
   197  // hash function associated with the Ed25519 signature scheme.
   198  var directSigning crypto.Hash = 0
   199  
   200  // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
   201  // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
   202  // CertificateRequest. The two fields are merged to match with TLS 1.3.
   203  // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
   204  var defaultSupportedSignatureAlgorithms = []SignatureScheme{
   205  	PSSWithSHA256,
   206  	ECDSAWithP256AndSHA256,
   207  	Ed25519,
   208  	PSSWithSHA384,
   209  	PSSWithSHA512,
   210  	PKCS1WithSHA256,
   211  	PKCS1WithSHA384,
   212  	PKCS1WithSHA512,
   213  	ECDSAWithP384AndSHA384,
   214  	ECDSAWithP521AndSHA512,
   215  	PKCS1WithSHA1,
   216  	ECDSAWithSHA1,
   217  }
   218  
   219  // helloRetryRequestRandom is set as the Random value of a ServerHello
   220  // to signal that the message is actually a HelloRetryRequest.
   221  var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
   222  	0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
   223  	0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
   224  	0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
   225  	0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
   226  }
   227  
   228  const (
   229  	// downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
   230  	// random as a downgrade protection if the server would be capable of
   231  	// negotiating a higher version. See RFC 8446, Section 4.1.3.
   232  	downgradeCanaryTLS12 = "DOWNGRD\x01"
   233  	downgradeCanaryTLS11 = "DOWNGRD\x00"
   234  )
   235  
   236  // testingOnlyForceDowngradeCanary is set in tests to force the server side to
   237  // include downgrade canaries even if it's using its highers supported version.
   238  var testingOnlyForceDowngradeCanary bool
   239  
   240  // ConnectionState records basic TLS details about the connection.
   241  type ConnectionState struct {
   242  	// Version is the TLS version used by the connection (e.g. VersionTLS12).
   243  	Version uint16
   244  
   245  	// HandshakeComplete is true if the handshake has concluded.
   246  	HandshakeComplete bool
   247  
   248  	// DidResume is true if this connection was successfully resumed from a
   249  	// previous session with a session ticket or similar mechanism.
   250  	DidResume bool
   251  
   252  	// CipherSuite is the cipher suite negotiated for the connection (e.g.
   253  	// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
   254  	CipherSuite uint16
   255  
   256  	// NegotiatedProtocol is the application protocol negotiated with ALPN.
   257  	NegotiatedProtocol string
   258  
   259  	// NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
   260  	//
   261  	// Deprecated: this value is always true.
   262  	NegotiatedProtocolIsMutual bool
   263  
   264  	// PeerApplicationSettings is the Application-Layer Protocol Settings (ALPS)
   265  	// provided by peer.
   266  	PeerApplicationSettings []byte // [uTLS]
   267  
   268  	// ServerName is the value of the Server Name Indication extension sent by
   269  	// the client. It's available both on the server and on the client side.
   270  	ServerName string
   271  
   272  	// PeerCertificates are the parsed certificates sent by the peer, in the
   273  	// order in which they were sent. The first element is the leaf certificate
   274  	// that the connection is verified against.
   275  	//
   276  	// On the client side, it can't be empty. On the server side, it can be
   277  	// empty if Config.ClientAuth is not RequireAnyClientCert or
   278  	// RequireAndVerifyClientCert.
   279  	//
   280  	// PeerCertificates and its contents should not be modified.
   281  	PeerCertificates []*x509.Certificate
   282  
   283  	// VerifiedChains is a list of one or more chains where the first element is
   284  	// PeerCertificates[0] and the last element is from Config.RootCAs (on the
   285  	// client side) or Config.ClientCAs (on the server side).
   286  	//
   287  	// On the client side, it's set if Config.InsecureSkipVerify is false. On
   288  	// the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
   289  	// (and the peer provided a certificate) or RequireAndVerifyClientCert.
   290  	//
   291  	// VerifiedChains and its contents should not be modified.
   292  	VerifiedChains [][]*x509.Certificate
   293  
   294  	// SignedCertificateTimestamps is a list of SCTs provided by the peer
   295  	// through the TLS handshake for the leaf certificate, if any.
   296  	SignedCertificateTimestamps [][]byte
   297  
   298  	// OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
   299  	// response provided by the peer for the leaf certificate, if any.
   300  	OCSPResponse []byte
   301  
   302  	// TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
   303  	// Section 3). This value will be nil for TLS 1.3 connections and for
   304  	// resumed connections that don't support Extended Master Secret (RFC 7627).
   305  	TLSUnique []byte
   306  
   307  	// ekm is a closure exposed via ExportKeyingMaterial.
   308  	ekm func(label string, context []byte, length int) ([]byte, error)
   309  }
   310  
   311  // ExportKeyingMaterial returns length bytes of exported key material in a new
   312  // slice as defined in RFC 5705. If context is nil, it is not used as part of
   313  // the seed. If the connection was set to allow renegotiation via
   314  // Config.Renegotiation, this function will return an error.
   315  //
   316  // There are conditions in which the returned values might not be unique to a
   317  // connection. See the Security Considerations sections of RFC 5705 and RFC 7627,
   318  // and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
   319  func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
   320  	return cs.ekm(label, context, length)
   321  }
   322  
   323  // ClientAuthType declares the policy the server will follow for
   324  // TLS Client Authentication.
   325  type ClientAuthType int
   326  
   327  const (
   328  	// NoClientCert indicates that no client certificate should be requested
   329  	// during the handshake, and if any certificates are sent they will not
   330  	// be verified.
   331  	NoClientCert ClientAuthType = iota
   332  	// RequestClientCert indicates that a client certificate should be requested
   333  	// during the handshake, but does not require that the client send any
   334  	// certificates.
   335  	RequestClientCert
   336  	// RequireAnyClientCert indicates that a client certificate should be requested
   337  	// during the handshake, and that at least one certificate is required to be
   338  	// sent by the client, but that certificate is not required to be valid.
   339  	RequireAnyClientCert
   340  	// VerifyClientCertIfGiven indicates that a client certificate should be requested
   341  	// during the handshake, but does not require that the client sends a
   342  	// certificate. If the client does send a certificate it is required to be
   343  	// valid.
   344  	VerifyClientCertIfGiven
   345  	// RequireAndVerifyClientCert indicates that a client certificate should be requested
   346  	// during the handshake, and that at least one valid certificate is required
   347  	// to be sent by the client.
   348  	RequireAndVerifyClientCert
   349  )
   350  
   351  // requiresClientCert reports whether the ClientAuthType requires a client
   352  // certificate to be provided.
   353  func requiresClientCert(c ClientAuthType) bool {
   354  	switch c {
   355  	case RequireAnyClientCert, RequireAndVerifyClientCert:
   356  		return true
   357  	default:
   358  		return false
   359  	}
   360  }
   361  
   362  // ClientSessionCache is a cache of ClientSessionState objects that can be used
   363  // by a client to resume a TLS session with a given server. ClientSessionCache
   364  // implementations should expect to be called concurrently from different
   365  // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
   366  // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
   367  // are supported via this interface.
   368  type ClientSessionCache interface {
   369  	// Get searches for a ClientSessionState associated with the given key.
   370  	// On return, ok is true if one was found.
   371  	Get(sessionKey string) (session *ClientSessionState, ok bool)
   372  
   373  	// Put adds the ClientSessionState to the cache with the given key. It might
   374  	// get called multiple times in a connection if a TLS 1.3 server provides
   375  	// more than one session ticket. If called with a nil *ClientSessionState,
   376  	// it should remove the cache entry.
   377  	Put(sessionKey string, cs *ClientSessionState)
   378  }
   379  
   380  //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
   381  
   382  // SignatureScheme identifies a signature algorithm supported by TLS. See
   383  // RFC 8446, Section 4.2.3.
   384  type SignatureScheme uint16
   385  
   386  const (
   387  	// RSASSA-PKCS1-v1_5 algorithms.
   388  	PKCS1WithSHA256 SignatureScheme = 0x0401
   389  	PKCS1WithSHA384 SignatureScheme = 0x0501
   390  	PKCS1WithSHA512 SignatureScheme = 0x0601
   391  
   392  	// RSASSA-PSS algorithms with public key OID rsaEncryption.
   393  	PSSWithSHA256 SignatureScheme = 0x0804
   394  	PSSWithSHA384 SignatureScheme = 0x0805
   395  	PSSWithSHA512 SignatureScheme = 0x0806
   396  
   397  	// ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
   398  	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
   399  	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
   400  	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
   401  
   402  	// EdDSA algorithms.
   403  	Ed25519 SignatureScheme = 0x0807
   404  
   405  	// Legacy signature and hash algorithms for TLS 1.2.
   406  	PKCS1WithSHA1 SignatureScheme = 0x0201
   407  	ECDSAWithSHA1 SignatureScheme = 0x0203
   408  )
   409  
   410  // ClientHelloInfo contains information from a ClientHello message in order to
   411  // guide application logic in the GetCertificate and GetConfigForClient callbacks.
   412  type ClientHelloInfo struct {
   413  	// CipherSuites lists the CipherSuites supported by the client (e.g.
   414  	// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
   415  	CipherSuites []uint16
   416  
   417  	// ServerName indicates the name of the server requested by the client
   418  	// in order to support virtual hosting. ServerName is only set if the
   419  	// client is using SNI (see RFC 4366, Section 3.1).
   420  	ServerName string
   421  
   422  	// SupportedCurves lists the elliptic curves supported by the client.
   423  	// SupportedCurves is set only if the Supported Elliptic Curves
   424  	// Extension is being used (see RFC 4492, Section 5.1.1).
   425  	SupportedCurves []CurveID
   426  
   427  	// SupportedPoints lists the point formats supported by the client.
   428  	// SupportedPoints is set only if the Supported Point Formats Extension
   429  	// is being used (see RFC 4492, Section 5.1.2).
   430  	SupportedPoints []uint8
   431  
   432  	// SignatureSchemes lists the signature and hash schemes that the client
   433  	// is willing to verify. SignatureSchemes is set only if the Signature
   434  	// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
   435  	SignatureSchemes []SignatureScheme
   436  
   437  	// SupportedProtos lists the application protocols supported by the client.
   438  	// SupportedProtos is set only if the Application-Layer Protocol
   439  	// Negotiation Extension is being used (see RFC 7301, Section 3.1).
   440  	//
   441  	// Servers can select a protocol by setting Config.NextProtos in a
   442  	// GetConfigForClient return value.
   443  	SupportedProtos []string
   444  
   445  	// SupportedVersions lists the TLS versions supported by the client.
   446  	// For TLS versions less than 1.3, this is extrapolated from the max
   447  	// version advertised by the client, so values other than the greatest
   448  	// might be rejected if used.
   449  	SupportedVersions []uint16
   450  
   451  	// Conn is the underlying net.Conn for the connection. Do not read
   452  	// from, or write to, this connection; that will cause the TLS
   453  	// connection to fail.
   454  	Conn net.Conn
   455  
   456  	// config is embedded by the GetCertificate or GetConfigForClient caller,
   457  	// for use with SupportsCertificate.
   458  	config *Config
   459  
   460  	// ctx is the context of the handshake that is in progress.
   461  	ctx context.Context
   462  }
   463  
   464  // Context returns the context of the handshake that is in progress.
   465  // This context is a child of the context passed to HandshakeContext,
   466  // if any, and is canceled when the handshake concludes.
   467  func (c *ClientHelloInfo) Context() context.Context {
   468  	return c.ctx
   469  }
   470  
   471  // CertificateRequestInfo contains information from a server's
   472  // CertificateRequest message, which is used to demand a certificate and proof
   473  // of control from a client.
   474  type CertificateRequestInfo struct {
   475  	// AcceptableCAs contains zero or more, DER-encoded, X.501
   476  	// Distinguished Names. These are the names of root or intermediate CAs
   477  	// that the server wishes the returned certificate to be signed by. An
   478  	// empty slice indicates that the server has no preference.
   479  	AcceptableCAs [][]byte
   480  
   481  	// SignatureSchemes lists the signature schemes that the server is
   482  	// willing to verify.
   483  	SignatureSchemes []SignatureScheme
   484  
   485  	// Version is the TLS version that was negotiated for this connection.
   486  	Version uint16
   487  
   488  	// ctx is the context of the handshake that is in progress.
   489  	ctx context.Context
   490  }
   491  
   492  // Context returns the context of the handshake that is in progress.
   493  // This context is a child of the context passed to HandshakeContext,
   494  // if any, and is canceled when the handshake concludes.
   495  func (c *CertificateRequestInfo) Context() context.Context {
   496  	return c.ctx
   497  }
   498  
   499  // RenegotiationSupport enumerates the different levels of support for TLS
   500  // renegotiation. TLS renegotiation is the act of performing subsequent
   501  // handshakes on a connection after the first. This significantly complicates
   502  // the state machine and has been the source of numerous, subtle security
   503  // issues. Initiating a renegotiation is not supported, but support for
   504  // accepting renegotiation requests may be enabled.
   505  //
   506  // Even when enabled, the server may not change its identity between handshakes
   507  // (i.e. the leaf certificate must be the same). Additionally, concurrent
   508  // handshake and application data flow is not permitted so renegotiation can
   509  // only be used with protocols that synchronise with the renegotiation, such as
   510  // HTTPS.
   511  //
   512  // Renegotiation is not defined in TLS 1.3.
   513  type RenegotiationSupport int
   514  
   515  const (
   516  	// RenegotiateNever disables renegotiation.
   517  	RenegotiateNever RenegotiationSupport = iota
   518  
   519  	// RenegotiateOnceAsClient allows a remote server to request
   520  	// renegotiation once per connection.
   521  	RenegotiateOnceAsClient
   522  
   523  	// RenegotiateFreelyAsClient allows a remote server to repeatedly
   524  	// request renegotiation.
   525  	RenegotiateFreelyAsClient
   526  )
   527  
   528  // A Config structure is used to configure a TLS client or server.
   529  // After one has been passed to a TLS function it must not be
   530  // modified. A Config may be reused; the tls package will also not
   531  // modify it.
   532  type Config struct {
   533  	// Rand provides the source of entropy for nonces and RSA blinding.
   534  	// If Rand is nil, TLS uses the cryptographic random reader in package
   535  	// crypto/rand.
   536  	// The Reader must be safe for use by multiple goroutines.
   537  	Rand io.Reader
   538  
   539  	// Time returns the current time as the number of seconds since the epoch.
   540  	// If Time is nil, TLS uses time.Now.
   541  	Time func() time.Time
   542  
   543  	// Certificates contains one or more certificate chains to present to the
   544  	// other side of the connection. The first certificate compatible with the
   545  	// peer's requirements is selected automatically.
   546  	//
   547  	// Server configurations must set one of Certificates, GetCertificate or
   548  	// GetConfigForClient. Clients doing client-authentication may set either
   549  	// Certificates or GetClientCertificate.
   550  	//
   551  	// Note: if there are multiple Certificates, and they don't have the
   552  	// optional field Leaf set, certificate selection will incur a significant
   553  	// per-handshake performance cost.
   554  	Certificates []Certificate
   555  
   556  	// NameToCertificate maps from a certificate name to an element of
   557  	// Certificates. Note that a certificate name can be of the form
   558  	// '*.example.com' and so doesn't have to be a domain name as such.
   559  	//
   560  	// Deprecated: NameToCertificate only allows associating a single
   561  	// certificate with a given name. Leave this field nil to let the library
   562  	// select the first compatible chain from Certificates.
   563  	NameToCertificate map[string]*Certificate
   564  
   565  	// GetCertificate returns a Certificate based on the given
   566  	// ClientHelloInfo. It will only be called if the client supplies SNI
   567  	// information or if Certificates is empty.
   568  	//
   569  	// If GetCertificate is nil or returns nil, then the certificate is
   570  	// retrieved from NameToCertificate. If NameToCertificate is nil, the
   571  	// best element of Certificates will be used.
   572  	//
   573  	// Once a Certificate is returned it should not be modified.
   574  	GetCertificate func(*ClientHelloInfo) (*Certificate, error)
   575  
   576  	// GetClientCertificate, if not nil, is called when a server requests a
   577  	// certificate from a client. If set, the contents of Certificates will
   578  	// be ignored.
   579  	//
   580  	// If GetClientCertificate returns an error, the handshake will be
   581  	// aborted and that error will be returned. Otherwise
   582  	// GetClientCertificate must return a non-nil Certificate. If
   583  	// Certificate.Certificate is empty then no certificate will be sent to
   584  	// the server. If this is unacceptable to the server then it may abort
   585  	// the handshake.
   586  	//
   587  	// GetClientCertificate may be called multiple times for the same
   588  	// connection if renegotiation occurs or if TLS 1.3 is in use.
   589  	//
   590  	// Once a Certificate is returned it should not be modified.
   591  	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
   592  
   593  	// GetConfigForClient, if not nil, is called after a ClientHello is
   594  	// received from a client. It may return a non-nil Config in order to
   595  	// change the Config that will be used to handle this connection. If
   596  	// the returned Config is nil, the original Config will be used. The
   597  	// Config returned by this callback may not be subsequently modified.
   598  	//
   599  	// If GetConfigForClient is nil, the Config passed to Server() will be
   600  	// used for all connections.
   601  	//
   602  	// If SessionTicketKey was explicitly set on the returned Config, or if
   603  	// SetSessionTicketKeys was called on the returned Config, those keys will
   604  	// be used. Otherwise, the original Config keys will be used (and possibly
   605  	// rotated if they are automatically managed).
   606  	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
   607  
   608  	// VerifyPeerCertificate, if not nil, is called after normal
   609  	// certificate verification by either a TLS client or server. It
   610  	// receives the raw ASN.1 certificates provided by the peer and also
   611  	// any verified chains that normal processing found. If it returns a
   612  	// non-nil error, the handshake is aborted and that error results.
   613  	//
   614  	// If normal verification fails then the handshake will abort before
   615  	// considering this callback. If normal verification is disabled (on the
   616  	// client when InsecureSkipVerify is set, or on a server when ClientAuth is
   617  	// RequestClientCert or RequireAnyClientCert), then this callback will be
   618  	// considered but the verifiedChains argument will always be nil. When
   619  	// ClientAuth is NoClientCert, this callback is not called on the server.
   620  	// rawCerts may be empty on the server if ClientAuth is RequestClientCert or
   621  	// VerifyClientCertIfGiven.
   622  	//
   623  	// This callback is not invoked on resumed connections, as certificates are
   624  	// not re-verified on resumption.
   625  	//
   626  	// verifiedChains and its contents should not be modified.
   627  	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
   628  
   629  	// VerifyConnection, if not nil, is called after normal certificate
   630  	// verification and after VerifyPeerCertificate by either a TLS client
   631  	// or server. If it returns a non-nil error, the handshake is aborted
   632  	// and that error results.
   633  	//
   634  	// If normal verification fails then the handshake will abort before
   635  	// considering this callback. This callback will run for all connections,
   636  	// including resumptions, regardless of InsecureSkipVerify or ClientAuth
   637  	// settings.
   638  	VerifyConnection func(ConnectionState) error
   639  
   640  	// RootCAs defines the set of root certificate authorities
   641  	// that clients use when verifying server certificates.
   642  	// If RootCAs is nil, TLS uses the host's root CA set.
   643  	RootCAs *x509.CertPool
   644  
   645  	// NextProtos is a list of supported application level protocols, in
   646  	// order of preference. If both peers support ALPN, the selected
   647  	// protocol will be one from this list, and the connection will fail
   648  	// if there is no mutually supported protocol. If NextProtos is empty
   649  	// or the peer doesn't support ALPN, the connection will succeed and
   650  	// ConnectionState.NegotiatedProtocol will be empty.
   651  	NextProtos []string
   652  
   653  	// ApplicationSettings is a set of application settings (ALPS) to use
   654  	// with each application protocol (ALPN).
   655  	ApplicationSettings map[string][]byte // [uTLS]
   656  
   657  	// ServerName is used to verify the hostname on the returned
   658  	// certificates unless InsecureSkipVerify is given. It is also included
   659  	// in the client's handshake to support virtual hosting unless it is
   660  	// an IP address.
   661  	ServerName string
   662  
   663  	// ClientAuth determines the server's policy for
   664  	// TLS Client Authentication. The default is NoClientCert.
   665  	ClientAuth ClientAuthType
   666  
   667  	// ClientCAs defines the set of root certificate authorities
   668  	// that servers use if required to verify a client certificate
   669  	// by the policy in ClientAuth.
   670  	ClientCAs *x509.CertPool
   671  
   672  	// InsecureSkipVerify controls whether a client verifies the server's
   673  	// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
   674  	// accepts any certificate presented by the server and any host name in that
   675  	// certificate. In this mode, TLS is susceptible to machine-in-the-middle
   676  	// attacks unless custom verification is used. This should be used only for
   677  	// testing or in combination with VerifyConnection or VerifyPeerCertificate.
   678  	InsecureSkipVerify bool
   679  
   680  	// InsecureSkipTimeVerify controls whether a client verifies the server's
   681  	// certificate chain against time. If InsecureSkipTimeVerify is true,
   682  	// crypto/tls accepts the certificate even when it is expired.
   683  	//
   684  	// This field is ignored when InsecureSkipVerify is true.
   685  	InsecureSkipTimeVerify bool // [uTLS]
   686  
   687  	// InsecureServerNameToVerify is used to verify the hostname on the returned
   688  	// certificates. It is intended to use with spoofed ServerName.
   689  	// If InsecureServerNameToVerify is "*", crypto/tls will do normal
   690  	// certificate validation but ignore certifacate's DNSName.
   691  	//
   692  	// This field is ignored when InsecureSkipVerify is true.
   693  	InsecureServerNameToVerify string // [uTLS]
   694  
   695  	// CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
   696  	// the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
   697  	//
   698  	// If CipherSuites is nil, a safe default list is used. The default cipher
   699  	// suites might change over time.
   700  	CipherSuites []uint16
   701  
   702  	// PreferServerCipherSuites is a legacy field and has no effect.
   703  	//
   704  	// It used to control whether the server would follow the client's or the
   705  	// server's preference. Servers now select the best mutually supported
   706  	// cipher suite based on logic that takes into account inferred client
   707  	// hardware, server hardware, and security.
   708  	//
   709  	// Deprecated: PreferServerCipherSuites is ignored.
   710  	PreferServerCipherSuites bool
   711  
   712  	// SessionTicketsDisabled may be set to true to disable session ticket and
   713  	// PSK (resumption) support. Note that on clients, session ticket support is
   714  	// also disabled if ClientSessionCache is nil.
   715  	SessionTicketsDisabled bool
   716  
   717  	// SessionTicketKey is used by TLS servers to provide session resumption.
   718  	// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
   719  	// with random data before the first server handshake.
   720  	//
   721  	// Deprecated: if this field is left at zero, session ticket keys will be
   722  	// automatically rotated every day and dropped after seven days. For
   723  	// customizing the rotation schedule or synchronizing servers that are
   724  	// terminating connections for the same host, use SetSessionTicketKeys.
   725  	SessionTicketKey [32]byte
   726  
   727  	// ClientSessionCache is a cache of ClientSessionState entries for TLS
   728  	// session resumption. It is only used by clients.
   729  	ClientSessionCache ClientSessionCache
   730  
   731  	// UnwrapSession is called on the server to turn a ticket/identity
   732  	// previously produced by [WrapSession] into a usable session.
   733  	//
   734  	// UnwrapSession will usually either decrypt a session state in the ticket
   735  	// (for example with [Config.EncryptTicket]), or use the ticket as a handle
   736  	// to recover a previously stored state. It must use [ParseSessionState] to
   737  	// deserialize the session state.
   738  	//
   739  	// If UnwrapSession returns an error, the connection is terminated. If it
   740  	// returns (nil, nil), the session is ignored. crypto/tls may still choose
   741  	// not to resume the returned session.
   742  	UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
   743  
   744  	// WrapSession is called on the server to produce a session ticket/identity.
   745  	//
   746  	// WrapSession must serialize the session state with [SessionState.Bytes].
   747  	// It may then encrypt the serialized state (for example with
   748  	// [Config.DecryptTicket]) and use it as the ticket, or store the state and
   749  	// return a handle for it.
   750  	//
   751  	// If WrapSession returns an error, the connection is terminated.
   752  	//
   753  	// Warning: the return value will be exposed on the wire and to clients in
   754  	// plaintext. The application is in charge of encrypting and authenticating
   755  	// it (and rotating keys) or returning high-entropy identifiers. Failing to
   756  	// do so correctly can compromise current, previous, and future connections
   757  	// depending on the protocol version.
   758  	WrapSession func(ConnectionState, *SessionState) ([]byte, error)
   759  
   760  	// MinVersion contains the minimum TLS version that is acceptable.
   761  	//
   762  	// By default, TLS 1.2 is currently used as the minimum when acting as a
   763  	// client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
   764  	// supported by this package, both as a client and as a server.
   765  	//
   766  	// The client-side default can temporarily be reverted to TLS 1.0 by
   767  	// including the value "x509sha1=1" in the GODEBUG environment variable.
   768  	// Note that this option will be removed in Go 1.19 (but it will still be
   769  	// possible to set this field to VersionTLS10 explicitly).
   770  	MinVersion uint16
   771  
   772  	// MaxVersion contains the maximum TLS version that is acceptable.
   773  	//
   774  	// By default, the maximum version supported by this package is used,
   775  	// which is currently TLS 1.3.
   776  	MaxVersion uint16
   777  
   778  	// CurvePreferences contains the elliptic curves that will be used in
   779  	// an ECDHE handshake, in preference order. If empty, the default will
   780  	// be used. The client will use the first preference as the type for
   781  	// its key share in TLS 1.3. This may change in the future.
   782  	CurvePreferences []CurveID
   783  
   784  	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
   785  	// When true, the largest possible TLS record size is always used. When
   786  	// false, the size of TLS records may be adjusted in an attempt to
   787  	// improve latency.
   788  	DynamicRecordSizingDisabled bool
   789  
   790  	// Renegotiation controls what types of renegotiation are supported.
   791  	// The default, none, is correct for the vast majority of applications.
   792  	Renegotiation RenegotiationSupport
   793  
   794  	// KeyLogWriter optionally specifies a destination for TLS master secrets
   795  	// in NSS key log format that can be used to allow external programs
   796  	// such as Wireshark to decrypt TLS connections.
   797  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   798  	// Use of KeyLogWriter compromises security and should only be
   799  	// used for debugging.
   800  	KeyLogWriter io.Writer
   801  
   802  	// mutex protects sessionTicketKeys and autoSessionTicketKeys.
   803  	mutex sync.RWMutex
   804  	// sessionTicketKeys contains zero or more ticket keys. If set, it means
   805  	// the keys were set with SessionTicketKey or SetSessionTicketKeys. The
   806  	// first key is used for new tickets and any subsequent keys can be used to
   807  	// decrypt old tickets. The slice contents are not protected by the mutex
   808  	// and are immutable.
   809  	sessionTicketKeys []ticketKey
   810  	// autoSessionTicketKeys is like sessionTicketKeys but is owned by the
   811  	// auto-rotation logic. See Config.ticketKeys.
   812  	autoSessionTicketKeys []ticketKey
   813  
   814  	RestlsSecret []byte                         // #RESTLS#
   815  	VersionHint  versionHint                    // #RESTLS#
   816  	RestlsScript []Line                         // #RESTLS#
   817  	ClientID     *atomic.Pointer[ClientHelloID] // #RESTLS#
   818  }
   819  
   820  const (
   821  	// ticketKeyLifetime is how long a ticket key remains valid and can be used to
   822  	// resume a client connection.
   823  	ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
   824  
   825  	// ticketKeyRotation is how often the server should rotate the session ticket key
   826  	// that is used for new tickets.
   827  	ticketKeyRotation = 24 * time.Hour
   828  )
   829  
   830  // ticketKey is the internal representation of a session ticket key.
   831  type ticketKey struct {
   832  	aesKey  [16]byte
   833  	hmacKey [16]byte
   834  	// created is the time at which this ticket key was created. See Config.ticketKeys.
   835  	created time.Time
   836  }
   837  
   838  // ticketKeyFromBytes converts from the external representation of a session
   839  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   840  // bytes and this function expands that into sufficient name and key material.
   841  func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   842  	hashed := sha512.Sum512(b[:])
   843  	// The first 16 bytes of the hash used to be exposed on the wire as a ticket
   844  	// prefix. They MUST NOT be used as a secret. In the future, it would make
   845  	// sense to use a proper KDF here, like HKDF with a fixed salt.
   846  	const legacyTicketKeyNameLen = 16
   847  	copy(key.aesKey[:], hashed[legacyTicketKeyNameLen:])
   848  	copy(key.hmacKey[:], hashed[legacyTicketKeyNameLen+len(key.aesKey):])
   849  	key.created = c.time()
   850  	return key
   851  }
   852  
   853  // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
   854  // ticket, and the lifetime we set for all tickets we send.
   855  const maxSessionTicketLifetime = 7 * 24 * time.Hour
   856  
   857  // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
   858  // being used concurrently by a TLS client or server.
   859  func (c *Config) Clone() *Config {
   860  	if c == nil {
   861  		return nil
   862  	}
   863  	c.mutex.RLock()
   864  	defer c.mutex.RUnlock()
   865  	return &Config{
   866  		Rand:                        c.Rand,
   867  		Time:                        c.Time,
   868  		Certificates:                c.Certificates,
   869  		NameToCertificate:           c.NameToCertificate,
   870  		GetCertificate:              c.GetCertificate,
   871  		GetClientCertificate:        c.GetClientCertificate,
   872  		GetConfigForClient:          c.GetConfigForClient,
   873  		VerifyPeerCertificate:       c.VerifyPeerCertificate,
   874  		VerifyConnection:            c.VerifyConnection,
   875  		RootCAs:                     c.RootCAs,
   876  		NextProtos:                  c.NextProtos,
   877  		ApplicationSettings:         c.ApplicationSettings,
   878  		ServerName:                  c.ServerName,
   879  		ClientAuth:                  c.ClientAuth,
   880  		ClientCAs:                   c.ClientCAs,
   881  		InsecureSkipVerify:          c.InsecureSkipVerify,
   882  		InsecureSkipTimeVerify:      c.InsecureSkipTimeVerify,
   883  		InsecureServerNameToVerify:  c.InsecureServerNameToVerify,
   884  		CipherSuites:                c.CipherSuites,
   885  		PreferServerCipherSuites:    c.PreferServerCipherSuites,
   886  		SessionTicketsDisabled:      c.SessionTicketsDisabled,
   887  		SessionTicketKey:            c.SessionTicketKey,
   888  		ClientSessionCache:          c.ClientSessionCache,
   889  		UnwrapSession:               c.UnwrapSession,
   890  		WrapSession:                 c.WrapSession,
   891  		MinVersion:                  c.MinVersion,
   892  		MaxVersion:                  c.MaxVersion,
   893  		CurvePreferences:            c.CurvePreferences,
   894  		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   895  		Renegotiation:               c.Renegotiation,
   896  		KeyLogWriter:                c.KeyLogWriter,
   897  		sessionTicketKeys:           c.sessionTicketKeys,
   898  		autoSessionTicketKeys:       c.autoSessionTicketKeys,
   899  		VersionHint:                 c.VersionHint,  // #RESTLS#
   900  		RestlsSecret:                c.RestlsSecret, // #RESTLS#
   901  		RestlsScript:                c.RestlsScript, // #RESTLS#
   902  		ClientID:                    c.ClientID,     // #RESTLS#
   903  	}
   904  }
   905  
   906  // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
   907  // randomized for backwards compatibility but is not in use.
   908  var deprecatedSessionTicketKey = []byte("DEPRECATED")
   909  
   910  // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
   911  // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
   912  func (c *Config) initLegacySessionTicketKeyRLocked() {
   913  	// Don't write if SessionTicketKey is already defined as our deprecated string,
   914  	// or if it is defined by the user but sessionTicketKeys is already set.
   915  	if c.SessionTicketKey != [32]byte{} &&
   916  		(bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
   917  		return
   918  	}
   919  
   920  	// We need to write some data, so get an exclusive lock and re-check any conditions.
   921  	c.mutex.RUnlock()
   922  	defer c.mutex.RLock()
   923  	c.mutex.Lock()
   924  	defer c.mutex.Unlock()
   925  	if c.SessionTicketKey == [32]byte{} {
   926  		if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   927  			panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
   928  		}
   929  		// Write the deprecated prefix at the beginning so we know we created
   930  		// it. This key with the DEPRECATED prefix isn't used as an actual
   931  		// session ticket key, and is only randomized in case the application
   932  		// reuses it for some reason.
   933  		copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
   934  	} else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
   935  		c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
   936  	}
   937  
   938  }
   939  
   940  // ticketKeys returns the ticketKeys for this connection.
   941  // If configForClient has explicitly set keys, those will
   942  // be returned. Otherwise, the keys on c will be used and
   943  // may be rotated if auto-managed.
   944  // During rotation, any expired session ticket keys are deleted from
   945  // c.sessionTicketKeys. If the session ticket key that is currently
   946  // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
   947  // is not fresh, then a new session ticket key will be
   948  // created and prepended to c.sessionTicketKeys.
   949  func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
   950  	// If the ConfigForClient callback returned a Config with explicitly set
   951  	// keys, use those, otherwise just use the original Config.
   952  	if configForClient != nil {
   953  		configForClient.mutex.RLock()
   954  		if configForClient.SessionTicketsDisabled {
   955  			return nil
   956  		}
   957  		configForClient.initLegacySessionTicketKeyRLocked()
   958  		if len(configForClient.sessionTicketKeys) != 0 {
   959  			ret := configForClient.sessionTicketKeys
   960  			configForClient.mutex.RUnlock()
   961  			return ret
   962  		}
   963  		configForClient.mutex.RUnlock()
   964  	}
   965  
   966  	c.mutex.RLock()
   967  	defer c.mutex.RUnlock()
   968  	if c.SessionTicketsDisabled {
   969  		return nil
   970  	}
   971  	c.initLegacySessionTicketKeyRLocked()
   972  	if len(c.sessionTicketKeys) != 0 {
   973  		return c.sessionTicketKeys
   974  	}
   975  	// Fast path for the common case where the key is fresh enough.
   976  	if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
   977  		return c.autoSessionTicketKeys
   978  	}
   979  
   980  	// autoSessionTicketKeys are managed by auto-rotation.
   981  	c.mutex.RUnlock()
   982  	defer c.mutex.RLock()
   983  	c.mutex.Lock()
   984  	defer c.mutex.Unlock()
   985  	// Re-check the condition in case it changed since obtaining the new lock.
   986  	if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
   987  		var newKey [32]byte
   988  		if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
   989  			panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
   990  		}
   991  		valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
   992  		valid = append(valid, c.ticketKeyFromBytes(newKey))
   993  		for _, k := range c.autoSessionTicketKeys {
   994  			// While rotating the current key, also remove any expired ones.
   995  			if c.time().Sub(k.created) < ticketKeyLifetime {
   996  				valid = append(valid, k)
   997  			}
   998  		}
   999  		c.autoSessionTicketKeys = valid
  1000  	}
  1001  	return c.autoSessionTicketKeys
  1002  }
  1003  
  1004  // SetSessionTicketKeys updates the session ticket keys for a server.
  1005  //
  1006  // The first key will be used when creating new tickets, while all keys can be
  1007  // used for decrypting tickets. It is safe to call this function while the
  1008  // server is running in order to rotate the session ticket keys. The function
  1009  // will panic if keys is empty.
  1010  //
  1011  // Calling this function will turn off automatic session ticket key rotation.
  1012  //
  1013  // If multiple servers are terminating connections for the same host they should
  1014  // all have the same session ticket keys. If the session ticket keys leaks,
  1015  // previously recorded and future TLS connections using those keys might be
  1016  // compromised.
  1017  func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  1018  	if len(keys) == 0 {
  1019  		panic("tls: keys must have at least one key")
  1020  	}
  1021  
  1022  	newKeys := make([]ticketKey, len(keys))
  1023  	for i, bytes := range keys {
  1024  		newKeys[i] = c.ticketKeyFromBytes(bytes)
  1025  	}
  1026  
  1027  	c.mutex.Lock()
  1028  	c.sessionTicketKeys = newKeys
  1029  	c.mutex.Unlock()
  1030  }
  1031  
  1032  func (c *Config) rand() io.Reader {
  1033  	r := c.Rand
  1034  	if r == nil {
  1035  		return rand.Reader
  1036  	}
  1037  	return r
  1038  }
  1039  
  1040  func (c *Config) time() time.Time {
  1041  	t := c.Time
  1042  	if t == nil {
  1043  		t = time.Now
  1044  	}
  1045  	return t()
  1046  }
  1047  
  1048  func (c *Config) cipherSuites() []uint16 {
  1049  	if needFIPS() {
  1050  		return fipsCipherSuites(c)
  1051  	}
  1052  	if c.CipherSuites != nil {
  1053  		return c.CipherSuites
  1054  	}
  1055  	return defaultCipherSuites
  1056  }
  1057  
  1058  var supportedVersions = []uint16{
  1059  	VersionTLS13,
  1060  	VersionTLS12,
  1061  	VersionTLS11,
  1062  	VersionTLS10,
  1063  }
  1064  
  1065  // roleClient and roleServer are meant to call supportedVersions and parents
  1066  // with more readability at the callsite.
  1067  const roleClient = true
  1068  const roleServer = false
  1069  
  1070  func (c *Config) supportedVersions(isClient bool) []uint16 {
  1071  	versions := make([]uint16, 0, len(supportedVersions))
  1072  	for _, v := range supportedVersions {
  1073  		if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
  1074  			continue
  1075  		}
  1076  		if (c == nil || c.MinVersion == 0) &&
  1077  			isClient && v < VersionTLS12 {
  1078  			continue
  1079  		}
  1080  		if c != nil && c.MinVersion != 0 && v < c.MinVersion {
  1081  			continue
  1082  		}
  1083  		if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
  1084  			continue
  1085  		}
  1086  		versions = append(versions, v)
  1087  	}
  1088  	return versions
  1089  }
  1090  
  1091  func (c *Config) maxSupportedVersion(isClient bool) uint16 {
  1092  	supportedVersions := c.supportedVersions(isClient)
  1093  	if len(supportedVersions) == 0 {
  1094  		return 0
  1095  	}
  1096  	return supportedVersions[0]
  1097  }
  1098  
  1099  // supportedVersionsFromMax returns a list of supported versions derived from a
  1100  // legacy maximum version value. Note that only versions supported by this
  1101  // library are returned. Any newer peer will use supportedVersions anyway.
  1102  func supportedVersionsFromMax(maxVersion uint16) []uint16 {
  1103  	versions := make([]uint16, 0, len(supportedVersions))
  1104  	for _, v := range supportedVersions {
  1105  		if v > maxVersion {
  1106  			continue
  1107  		}
  1108  		versions = append(versions, v)
  1109  	}
  1110  	return versions
  1111  }
  1112  
  1113  var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  1114  
  1115  func (c *Config) curvePreferences() []CurveID {
  1116  	if needFIPS() {
  1117  		return fipsCurvePreferences(c)
  1118  	}
  1119  	if c == nil || len(c.CurvePreferences) == 0 {
  1120  		return defaultCurvePreferences
  1121  	}
  1122  	return c.CurvePreferences
  1123  }
  1124  
  1125  func (c *Config) supportsCurve(curve CurveID) bool {
  1126  	for _, cc := range c.curvePreferences() {
  1127  		if cc == curve {
  1128  			return true
  1129  		}
  1130  	}
  1131  	return false
  1132  }
  1133  
  1134  // mutualVersion returns the protocol version to use given the advertised
  1135  // versions of the peer. Priority is given to the peer preference order.
  1136  func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
  1137  	supportedVersions := c.supportedVersions(isClient)
  1138  	for _, peerVersion := range peerVersions {
  1139  		for _, v := range supportedVersions {
  1140  			if v == peerVersion {
  1141  				return v, true
  1142  			}
  1143  		}
  1144  	}
  1145  	return 0, false
  1146  }
  1147  
  1148  var errNoCertificates = errors.New("tls: no certificates configured")
  1149  
  1150  // getCertificate returns the best certificate for the given ClientHelloInfo,
  1151  // defaulting to the first element of c.Certificates.
  1152  func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  1153  	if c.GetCertificate != nil &&
  1154  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  1155  		cert, err := c.GetCertificate(clientHello)
  1156  		if cert != nil || err != nil {
  1157  			return cert, err
  1158  		}
  1159  	}
  1160  
  1161  	if len(c.Certificates) == 0 {
  1162  		return nil, errNoCertificates
  1163  	}
  1164  
  1165  	if len(c.Certificates) == 1 {
  1166  		// There's only one choice, so no point doing any work.
  1167  		return &c.Certificates[0], nil
  1168  	}
  1169  
  1170  	if c.NameToCertificate != nil {
  1171  		name := strings.ToLower(clientHello.ServerName)
  1172  		if cert, ok := c.NameToCertificate[name]; ok {
  1173  			return cert, nil
  1174  		}
  1175  		if len(name) > 0 {
  1176  			labels := strings.Split(name, ".")
  1177  			labels[0] = "*"
  1178  			wildcardName := strings.Join(labels, ".")
  1179  			if cert, ok := c.NameToCertificate[wildcardName]; ok {
  1180  				return cert, nil
  1181  			}
  1182  		}
  1183  	}
  1184  
  1185  	for _, cert := range c.Certificates {
  1186  		if err := clientHello.SupportsCertificate(&cert); err == nil {
  1187  			return &cert, nil
  1188  		}
  1189  	}
  1190  
  1191  	// If nothing matches, return the first certificate.
  1192  	return &c.Certificates[0], nil
  1193  }
  1194  
  1195  // SupportsCertificate returns nil if the provided certificate is supported by
  1196  // the client that sent the ClientHello. Otherwise, it returns an error
  1197  // describing the reason for the incompatibility.
  1198  //
  1199  // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
  1200  // callback, this method will take into account the associated Config. Note that
  1201  // if GetConfigForClient returns a different Config, the change can't be
  1202  // accounted for by this method.
  1203  //
  1204  // This function will call x509.ParseCertificate unless c.Leaf is set, which can
  1205  // incur a significant performance cost.
  1206  func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
  1207  	// Note we don't currently support certificate_authorities nor
  1208  	// signature_algorithms_cert, and don't check the algorithms of the
  1209  	// signatures on the chain (which anyway are a SHOULD, see RFC 8446,
  1210  	// Section 4.4.2.2).
  1211  
  1212  	config := chi.config
  1213  	if config == nil {
  1214  		config = &Config{}
  1215  	}
  1216  	vers, ok := config.mutualVersion(roleServer, chi.SupportedVersions)
  1217  	if !ok {
  1218  		return errors.New("no mutually supported protocol versions")
  1219  	}
  1220  
  1221  	// If the client specified the name they are trying to connect to, the
  1222  	// certificate needs to be valid for it.
  1223  	if chi.ServerName != "" {
  1224  		x509Cert, err := c.leaf()
  1225  		if err != nil {
  1226  			return fmt.Errorf("failed to parse certificate: %w", err)
  1227  		}
  1228  		if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
  1229  			return fmt.Errorf("certificate is not valid for requested server name: %w", err)
  1230  		}
  1231  	}
  1232  
  1233  	// supportsRSAFallback returns nil if the certificate and connection support
  1234  	// the static RSA key exchange, and unsupported otherwise. The logic for
  1235  	// supporting static RSA is completely disjoint from the logic for
  1236  	// supporting signed key exchanges, so we just check it as a fallback.
  1237  	supportsRSAFallback := func(unsupported error) error {
  1238  		// TLS 1.3 dropped support for the static RSA key exchange.
  1239  		if vers == VersionTLS13 {
  1240  			return unsupported
  1241  		}
  1242  		// The static RSA key exchange works by decrypting a challenge with the
  1243  		// RSA private key, not by signing, so check the PrivateKey implements
  1244  		// crypto.Decrypter, like *rsa.PrivateKey does.
  1245  		if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
  1246  			if _, ok := priv.Public().(*rsa.PublicKey); !ok {
  1247  				return unsupported
  1248  			}
  1249  		} else {
  1250  			return unsupported
  1251  		}
  1252  		// Finally, there needs to be a mutual cipher suite that uses the static
  1253  		// RSA key exchange instead of ECDHE.
  1254  		rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
  1255  			if c.flags&suiteECDHE != 0 {
  1256  				return false
  1257  			}
  1258  			if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1259  				return false
  1260  			}
  1261  			return true
  1262  		})
  1263  		if rsaCipherSuite == nil {
  1264  			return unsupported
  1265  		}
  1266  		return nil
  1267  	}
  1268  
  1269  	// If the client sent the signature_algorithms extension, ensure it supports
  1270  	// schemes we can use with this certificate and TLS version.
  1271  	if len(chi.SignatureSchemes) > 0 {
  1272  		if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
  1273  			return supportsRSAFallback(err)
  1274  		}
  1275  	}
  1276  
  1277  	// In TLS 1.3 we are done because supported_groups is only relevant to the
  1278  	// ECDHE computation, point format negotiation is removed, cipher suites are
  1279  	// only relevant to the AEAD choice, and static RSA does not exist.
  1280  	if vers == VersionTLS13 {
  1281  		return nil
  1282  	}
  1283  
  1284  	// The only signed key exchange we support is ECDHE.
  1285  	if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
  1286  		return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
  1287  	}
  1288  
  1289  	var ecdsaCipherSuite bool
  1290  	if priv, ok := c.PrivateKey.(crypto.Signer); ok {
  1291  		switch pub := priv.Public().(type) {
  1292  		case *ecdsa.PublicKey:
  1293  			var curve CurveID
  1294  			switch pub.Curve {
  1295  			case elliptic.P256():
  1296  				curve = CurveP256
  1297  			case elliptic.P384():
  1298  				curve = CurveP384
  1299  			case elliptic.P521():
  1300  				curve = CurveP521
  1301  			default:
  1302  				return supportsRSAFallback(unsupportedCertificateError(c))
  1303  			}
  1304  			var curveOk bool
  1305  			for _, c := range chi.SupportedCurves {
  1306  				if c == curve && config.supportsCurve(c) {
  1307  					curveOk = true
  1308  					break
  1309  				}
  1310  			}
  1311  			if !curveOk {
  1312  				return errors.New("client doesn't support certificate curve")
  1313  			}
  1314  			ecdsaCipherSuite = true
  1315  		case ed25519.PublicKey:
  1316  			if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
  1317  				return errors.New("connection doesn't support Ed25519")
  1318  			}
  1319  			ecdsaCipherSuite = true
  1320  		case *rsa.PublicKey:
  1321  		default:
  1322  			return supportsRSAFallback(unsupportedCertificateError(c))
  1323  		}
  1324  	} else {
  1325  		return supportsRSAFallback(unsupportedCertificateError(c))
  1326  	}
  1327  
  1328  	// Make sure that there is a mutually supported cipher suite that works with
  1329  	// this certificate. Cipher suite selection will then apply the logic in
  1330  	// reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
  1331  	cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
  1332  		if c.flags&suiteECDHE == 0 {
  1333  			return false
  1334  		}
  1335  		if c.flags&suiteECSign != 0 {
  1336  			if !ecdsaCipherSuite {
  1337  				return false
  1338  			}
  1339  		} else {
  1340  			if ecdsaCipherSuite {
  1341  				return false
  1342  			}
  1343  		}
  1344  		if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1345  			return false
  1346  		}
  1347  		return true
  1348  	})
  1349  	if cipherSuite == nil {
  1350  		return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
  1351  	}
  1352  
  1353  	return nil
  1354  }
  1355  
  1356  // SupportsCertificate returns nil if the provided certificate is supported by
  1357  // the server that sent the CertificateRequest. Otherwise, it returns an error
  1358  // describing the reason for the incompatibility.
  1359  func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
  1360  	if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
  1361  		return err
  1362  	}
  1363  
  1364  	if len(cri.AcceptableCAs) == 0 {
  1365  		return nil
  1366  	}
  1367  
  1368  	for j, cert := range c.Certificate {
  1369  		x509Cert := c.Leaf
  1370  		// Parse the certificate if this isn't the leaf node, or if
  1371  		// chain.Leaf was nil.
  1372  		if j != 0 || x509Cert == nil {
  1373  			var err error
  1374  			if x509Cert, err = x509.ParseCertificate(cert); err != nil {
  1375  				return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
  1376  			}
  1377  		}
  1378  
  1379  		for _, ca := range cri.AcceptableCAs {
  1380  			if bytes.Equal(x509Cert.RawIssuer, ca) {
  1381  				return nil
  1382  			}
  1383  		}
  1384  	}
  1385  	return errors.New("chain is not signed by an acceptable CA")
  1386  }
  1387  
  1388  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  1389  // from the CommonName and SubjectAlternateName fields of each of the leaf
  1390  // certificates.
  1391  //
  1392  // Deprecated: NameToCertificate only allows associating a single certificate
  1393  // with a given name. Leave that field nil to let the library select the first
  1394  // compatible chain from Certificates.
  1395  func (c *Config) BuildNameToCertificate() {
  1396  	c.NameToCertificate = make(map[string]*Certificate)
  1397  	for i := range c.Certificates {
  1398  		cert := &c.Certificates[i]
  1399  		x509Cert, err := cert.leaf()
  1400  		if err != nil {
  1401  			continue
  1402  		}
  1403  		// If SANs are *not* present, some clients will consider the certificate
  1404  		// valid for the name in the Common Name.
  1405  		if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
  1406  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  1407  		}
  1408  		for _, san := range x509Cert.DNSNames {
  1409  			c.NameToCertificate[san] = cert
  1410  		}
  1411  	}
  1412  }
  1413  
  1414  const (
  1415  	keyLogLabelTLS12           = "CLIENT_RANDOM"
  1416  	keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  1417  	keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  1418  	keyLogLabelClientTraffic   = "CLIENT_TRAFFIC_SECRET_0"
  1419  	keyLogLabelServerTraffic   = "SERVER_TRAFFIC_SECRET_0"
  1420  )
  1421  
  1422  func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
  1423  	if c.KeyLogWriter == nil {
  1424  		return nil
  1425  	}
  1426  
  1427  	logLine := fmt.Appendf(nil, "%s %x %x\n", label, clientRandom, secret)
  1428  
  1429  	writerMutex.Lock()
  1430  	_, err := c.KeyLogWriter.Write(logLine)
  1431  	writerMutex.Unlock()
  1432  
  1433  	return err
  1434  }
  1435  
  1436  // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  1437  // and is only for debugging, so a global mutex saves space.
  1438  var writerMutex sync.Mutex
  1439  
  1440  // A Certificate is a chain of one or more certificates, leaf first.
  1441  type Certificate struct {
  1442  	Certificate [][]byte
  1443  	// PrivateKey contains the private key corresponding to the public key in
  1444  	// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
  1445  	// For a server up to TLS 1.2, it can also implement crypto.Decrypter with
  1446  	// an RSA PublicKey.
  1447  	PrivateKey crypto.PrivateKey
  1448  	// SupportedSignatureAlgorithms is an optional list restricting what
  1449  	// signature algorithms the PrivateKey can be used for.
  1450  	SupportedSignatureAlgorithms []SignatureScheme
  1451  	// OCSPStaple contains an optional OCSP response which will be served
  1452  	// to clients that request it.
  1453  	OCSPStaple []byte
  1454  	// SignedCertificateTimestamps contains an optional list of Signed
  1455  	// Certificate Timestamps which will be served to clients that request it.
  1456  	SignedCertificateTimestamps [][]byte
  1457  	// Leaf is the parsed form of the leaf certificate, which may be initialized
  1458  	// using x509.ParseCertificate to reduce per-handshake processing. If nil,
  1459  	// the leaf certificate will be parsed as needed.
  1460  	Leaf *x509.Certificate
  1461  }
  1462  
  1463  // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
  1464  // the corresponding c.Certificate[0].
  1465  func (c *Certificate) leaf() (*x509.Certificate, error) {
  1466  	if c.Leaf != nil {
  1467  		return c.Leaf, nil
  1468  	}
  1469  	return x509.ParseCertificate(c.Certificate[0])
  1470  }
  1471  
  1472  type handshakeMessage interface {
  1473  	marshal() ([]byte, error)
  1474  	unmarshal([]byte) bool
  1475  }
  1476  
  1477  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  1478  // caching strategy.
  1479  type lruSessionCache struct {
  1480  	sync.Mutex
  1481  
  1482  	m        map[string]*list.Element
  1483  	q        *list.List
  1484  	capacity int
  1485  }
  1486  
  1487  type lruSessionCacheEntry struct {
  1488  	sessionKey string
  1489  	state      *ClientSessionState
  1490  }
  1491  
  1492  // NewLRUClientSessionCache returns a ClientSessionCache with the given
  1493  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  1494  // is used instead.
  1495  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  1496  	const defaultSessionCacheCapacity = 64
  1497  
  1498  	if capacity < 1 {
  1499  		capacity = defaultSessionCacheCapacity
  1500  	}
  1501  	return &lruSessionCache{
  1502  		m:        make(map[string]*list.Element),
  1503  		q:        list.New(),
  1504  		capacity: capacity,
  1505  	}
  1506  }
  1507  
  1508  // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
  1509  // corresponding to sessionKey is removed from the cache instead.
  1510  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  1511  	c.Lock()
  1512  	defer c.Unlock()
  1513  
  1514  	if elem, ok := c.m[sessionKey]; ok {
  1515  		if cs == nil {
  1516  			c.q.Remove(elem)
  1517  			delete(c.m, sessionKey)
  1518  		} else {
  1519  			entry := elem.Value.(*lruSessionCacheEntry)
  1520  			entry.state = cs
  1521  			c.q.MoveToFront(elem)
  1522  		}
  1523  		return
  1524  	}
  1525  
  1526  	if c.q.Len() < c.capacity {
  1527  		entry := &lruSessionCacheEntry{sessionKey, cs}
  1528  		c.m[sessionKey] = c.q.PushFront(entry)
  1529  		return
  1530  	}
  1531  
  1532  	elem := c.q.Back()
  1533  	entry := elem.Value.(*lruSessionCacheEntry)
  1534  	delete(c.m, entry.sessionKey)
  1535  	entry.sessionKey = sessionKey
  1536  	entry.state = cs
  1537  	c.q.MoveToFront(elem)
  1538  	c.m[sessionKey] = elem
  1539  }
  1540  
  1541  // Get returns the ClientSessionState value associated with a given key. It
  1542  // returns (nil, false) if no value is found.
  1543  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  1544  	c.Lock()
  1545  	defer c.Unlock()
  1546  
  1547  	if elem, ok := c.m[sessionKey]; ok {
  1548  		c.q.MoveToFront(elem)
  1549  		return elem.Value.(*lruSessionCacheEntry).state, true
  1550  	}
  1551  	return nil, false
  1552  }
  1553  
  1554  var emptyConfig Config
  1555  
  1556  func defaultConfig() *Config {
  1557  	return &emptyConfig
  1558  }
  1559  
  1560  func unexpectedMessageError(wanted, got any) error {
  1561  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1562  }
  1563  
  1564  func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1565  	for _, s := range supportedSignatureAlgorithms {
  1566  		if s == sigAlg {
  1567  			return true
  1568  		}
  1569  	}
  1570  	return false
  1571  }
  1572  
  1573  // #RESTLS#
  1574  type versionHint uint8
  1575  
  1576  // #RESTLS#
  1577  const (
  1578  	TLS12Hint versionHint = 12
  1579  	TLS13Hint versionHint = 13
  1580  )
  1581  
  1582  // #RESTLS#
  1583  const (
  1584  	restlsHandshakeMACLength      int = 16
  1585  	restlsAppDataMACLength        int = 8
  1586  	restlsCmdLength               int = 2
  1587  	restlsMaskLength              int = restlsCmdLength + 2
  1588  	restlsAppDataAuthHeaderLength int = restlsAppDataMACLength +
  1589  		restlsMaskLength
  1590  	restlsAppDataOffset    int = restlsAppDataAuthHeaderLength
  1591  	restlsAppDataLenOffset int = restlsAppDataMACLength
  1592  )
  1593  
  1594  // #RESTLS#
  1595  var restlsRandomResponseMagic []byte = []byte("restls-random-response")
  1596  var restls12ClientAuthLayout3 []int = []int{0, 11, 22, 32}
  1597  var restls12ClientAuthLayout4 []int = []int{0, 8, 16, 24, 32}
  1598  
  1599  // CertificateVerificationError is returned when certificate verification fails during the handshake.
  1600  type CertificateVerificationError struct {
  1601  	// UnverifiedCertificates and its contents should not be modified.
  1602  	UnverifiedCertificates []*x509.Certificate
  1603  	Err                    error
  1604  }
  1605  
  1606  func (e *CertificateVerificationError) Error() string {
  1607  	return fmt.Sprintf("tls: failed to verify certificate: %s", e.Err)
  1608  }
  1609  
  1610  func (e *CertificateVerificationError) Unwrap() error {
  1611  	return e.Err
  1612  }