gitee.com/lh-her-team/common@v1.5.1/crypto/tls/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  	"crypto"
    11  	"crypto/ecdsa"
    12  	"crypto/ed25519"
    13  	"crypto/elliptic"
    14  	"crypto/rand"
    15  	"crypto/rsa"
    16  	"crypto/sha512"
    17  	"crypto/x509"
    18  	"errors"
    19  	"fmt"
    20  	"io"
    21  	"math/big"
    22  	"net"
    23  	"strings"
    24  	"sync"
    25  	"time"
    26  
    27  	cmx509 "gitee.com/lh-her-team/common/crypto/x509"
    28  	"github.com/tjfoc/gmsm/sm2"
    29  	"golang.org/x/sys/cpu"
    30  )
    31  
    32  const (
    33  	VersionTLS10 = 0x0301
    34  	VersionTLS11 = 0x0302
    35  	VersionTLS12 = 0x0303
    36  	VersionTLS13 = 0x0304
    37  
    38  	// Deprecated: SSLv3 is cryptographically broken, and is no longer
    39  	// supported by this package. See golang.org/issue/32716.
    40  	VersionSSL30 = 0x0300
    41  )
    42  
    43  const (
    44  	maxPlaintext       = 16384        // maximum plaintext payload length
    45  	maxCiphertext      = 16384 + 2048 // maximum ciphertext payload length
    46  	maxCiphertextTLS13 = 16384 + 256  // maximum ciphertext length in TLS 1.3
    47  	recordHeaderLen    = 5            // record header length
    48  	maxHandshake       = 65536        // maximum handshake we support (protocol max is 16 MB)
    49  	maxUselessRecords  = 16           // maximum number of consecutive non-advancing records
    50  
    51  	minVersion = VersionGMSSL
    52  	maxVersion = VersionTLS13
    53  )
    54  
    55  // TLS record types.
    56  type recordType uint8
    57  
    58  const (
    59  	recordTypeChangeCipherSpec recordType = 20
    60  	recordTypeAlert            recordType = 21
    61  	recordTypeHandshake        recordType = 22
    62  	recordTypeApplicationData  recordType = 23
    63  )
    64  
    65  // TLS handshake message types.
    66  const (
    67  	typeHelloRequest        uint8 = 0
    68  	typeClientHello         uint8 = 1
    69  	typeServerHello         uint8 = 2
    70  	typeNewSessionTicket    uint8 = 4
    71  	typeEndOfEarlyData      uint8 = 5
    72  	typeEncryptedExtensions uint8 = 8
    73  	typeCertificate         uint8 = 11
    74  	typeServerKeyExchange   uint8 = 12
    75  	typeCertificateRequest  uint8 = 13
    76  	typeServerHelloDone     uint8 = 14
    77  	typeCertificateVerify   uint8 = 15
    78  	typeClientKeyExchange   uint8 = 16
    79  	typeFinished            uint8 = 20
    80  	typeCertificateStatus   uint8 = 22
    81  	typeKeyUpdate           uint8 = 24
    82  	typeNextProtocol        uint8 = 67  // Not IANA assigned
    83  	typeMessageHash         uint8 = 254 // synthetic message
    84  )
    85  
    86  // TLS compression types.
    87  const (
    88  	compressionNone uint8 = 0
    89  )
    90  
    91  // TLS extension numbers
    92  const (
    93  	extensionServerName              uint16 = 0
    94  	extensionStatusRequest           uint16 = 5
    95  	extensionSupportedCurves         uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
    96  	extensionSupportedPoints         uint16 = 11
    97  	extensionSignatureAlgorithms     uint16 = 13
    98  	extensionALPN                    uint16 = 16
    99  	extensionSCT                     uint16 = 18
   100  	extensionSessionTicket           uint16 = 35
   101  	extensionPreSharedKey            uint16 = 41
   102  	extensionEarlyData               uint16 = 42
   103  	extensionSupportedVersions       uint16 = 43
   104  	extensionCookie                  uint16 = 44
   105  	extensionPSKModes                uint16 = 45
   106  	extensionCertificateAuthorities  uint16 = 47
   107  	extensionSignatureAlgorithmsCert uint16 = 50
   108  	extensionKeyShare                uint16 = 51
   109  	extensionRenegotiationInfo       uint16 = 0xff01
   110  )
   111  
   112  // TLS signaling cipher suite values
   113  const (
   114  	scsvRenegotiation uint16 = 0x00ff
   115  )
   116  
   117  // CurveID is the type of a TLS identifier for an elliptic curve. See
   118  // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
   119  //
   120  // In TLS 1.3, this type is called NamedGroup, but at this time this library
   121  // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
   122  type CurveID uint16
   123  
   124  const (
   125  	CurveP256 CurveID = 23
   126  	CurveP384 CurveID = 24
   127  	CurveP521 CurveID = 25
   128  	X25519    CurveID = 29
   129  	SM2P256V1 CurveID = 41
   130  )
   131  
   132  // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
   133  type keyShare struct {
   134  	group CurveID
   135  	data  []byte
   136  }
   137  
   138  // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
   139  const (
   140  	pskModePlain uint8 = 0
   141  	pskModeDHE   uint8 = 1
   142  )
   143  
   144  // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
   145  // session. See RFC 8446, Section 4.2.11.
   146  type pskIdentity struct {
   147  	label               []byte
   148  	obfuscatedTicketAge uint32
   149  }
   150  
   151  // TLS Elliptic Curve Point Formats
   152  // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
   153  const (
   154  	pointFormatUncompressed uint8 = 0
   155  )
   156  
   157  // TLS CertificateStatusType (RFC 3546)
   158  const (
   159  	statusTypeOCSP uint8 = 1
   160  )
   161  
   162  // Certificate types (for certificateRequestMsg)
   163  const (
   164  	certTypeRSASign   = 1
   165  	certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
   166  )
   167  
   168  // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
   169  // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
   170  const (
   171  	signaturePKCS1v15 uint8 = iota + 225
   172  	signatureRSAPSS
   173  	signatureECDSA
   174  	signatureEd25519
   175  	signatureSM2
   176  )
   177  
   178  // directSigning is a standard Hash value that signals that no pre-hashing
   179  // should be performed, and that the input should be signed directly. It is the
   180  // hash function associated with the Ed25519 signature scheme.
   181  var directSigning crypto.Hash = 0
   182  
   183  // supportedSignatureAlgorithms contains the signature and hash algorithms that
   184  // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
   185  // CertificateRequest. The two fields are merged to match with TLS 1.3.
   186  // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
   187  var supportedSignatureAlgorithms = []SignatureScheme{
   188  	PSSWithSHA256,
   189  	ECDSAWithP256AndSHA256,
   190  	Ed25519,
   191  	PSSWithSHA384,
   192  	PSSWithSHA512,
   193  	PKCS1WithSHA256,
   194  	PKCS1WithSHA384,
   195  	PKCS1WithSHA512,
   196  	ECDSAWithP384AndSHA384,
   197  	ECDSAWithP521AndSHA512,
   198  	PKCS1WithSHA1,
   199  	ECDSAWithSHA1,
   200  	SM2WithSM3,
   201  }
   202  
   203  // helloRetryRequestRandom is set as the Random value of a ServerHello
   204  // to signal that the message is actually a HelloRetryRequest.
   205  var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
   206  	0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
   207  	0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
   208  	0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
   209  	0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
   210  }
   211  
   212  const (
   213  	// downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
   214  	// random as a downgrade protection if the server would be capable of
   215  	// negotiating a higher version. See RFC 8446, Section 4.1.3.
   216  	downgradeCanaryTLS12 = "DOWNGRD\x01"
   217  	downgradeCanaryTLS11 = "DOWNGRD\x00"
   218  )
   219  
   220  // ConnectionState records basic TLS details about the connection.
   221  type ConnectionState struct {
   222  	Version                     uint16                  // TLS version used by the connection (e.g. VersionTLS12)
   223  	HandshakeComplete           bool                    // TLS handshake is complete
   224  	DidResume                   bool                    // connection resumes a previous TLS connection
   225  	CipherSuite                 uint16                  // cipher suite in use (TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, ...)
   226  	NegotiatedProtocol          string                  // negotiated next protocol (not guaranteed to be from Config.NextProtos)
   227  	NegotiatedProtocolIsMutual  bool                    // negotiated protocol was advertised by server (client side only)
   228  	ServerName                  string                  // server name requested by client, if any (server side only)
   229  	PeerCertificates            []*cmx509.Certificate   // certificate chain presented by remote peer
   230  	VerifiedChains              [][]*cmx509.Certificate // verified chains built from PeerCertificates
   231  	SignedCertificateTimestamps [][]byte                // SCTs from the peer, if any
   232  	OCSPResponse                []byte                  // stapled OCSP response from peer, if any
   233  
   234  	// ekm is a closure exposed via ExportKeyingMaterial.
   235  	ekm func(label string, context []byte, length int) ([]byte, error)
   236  
   237  	// TLSUnique contains the "tls-unique" channel binding value (see RFC
   238  	// 5929, section 3). For resumed sessions this value will be nil
   239  	// because resumption does not include enough context (see
   240  	// https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
   241  	// change in future versions of Go once the TLS master-secret fix has
   242  	// been standardized and implemented. It is not defined in TLS 1.3.
   243  	TLSUnique []byte
   244  }
   245  
   246  // ExportKeyingMaterial returns length bytes of exported key material in a new
   247  // slice as defined in RFC 5705. If context is nil, it is not used as part of
   248  // the seed. If the connection was set to allow renegotiation via
   249  // Config.Renegotiation, this function will return an error.
   250  func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
   251  	return cs.ekm(label, context, length)
   252  }
   253  
   254  // ClientAuthType declares the policy the server will follow for
   255  // TLS Client Authentication.
   256  type ClientAuthType int
   257  
   258  const (
   259  	NoClientCert ClientAuthType = iota
   260  	RequestClientCert
   261  	RequireAnyClientCert
   262  	VerifyClientCertIfGiven
   263  	RequireAndVerifyClientCert
   264  )
   265  
   266  // requiresClientCert reports whether the ClientAuthType requires a client
   267  // certificate to be provided.
   268  func requiresClientCert(c ClientAuthType) bool {
   269  	switch c {
   270  	case RequireAnyClientCert, RequireAndVerifyClientCert:
   271  		return true
   272  	default:
   273  		return false
   274  	}
   275  }
   276  
   277  // ClientSessionState contains the state needed by clients to resume TLS
   278  // sessions.
   279  type ClientSessionState struct {
   280  	sessionTicket      []uint8                 // Encrypted ticket used for session resumption with server
   281  	vers               uint16                  // TLS version negotiated for the session
   282  	cipherSuite        uint16                  // Ciphersuite negotiated for the session
   283  	masterSecret       []byte                  // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
   284  	serverCertificates []*cmx509.Certificate   // Certificate chain presented by the server
   285  	verifiedChains     [][]*cmx509.Certificate // Certificate chains we built for verification
   286  	receivedAt         time.Time               // When the session ticket was received from the server
   287  
   288  	// TLS 1.3 fields.
   289  	nonce  []byte    // Ticket nonce sent by the server, to derive PSK
   290  	useBy  time.Time // Expiration of the ticket lifetime as set by the server
   291  	ageAdd uint32    // Random obfuscation factor for sending the ticket age
   292  }
   293  
   294  // ClientSessionCache is a cache of ClientSessionState objects that can be used
   295  // by a client to resume a TLS session with a given server. ClientSessionCache
   296  // implementations should expect to be called concurrently from different
   297  // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
   298  // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
   299  // are supported via this interface.
   300  type ClientSessionCache interface {
   301  	// Get searches for a ClientSessionState associated with the given key.
   302  	// On return, ok is true if one was found.
   303  	Get(sessionKey string) (session *ClientSessionState, ok bool)
   304  	// Put adds the ClientSessionState to the cache with the given key. It might
   305  	// get called multiple times in a connection if a TLS 1.3 server provides
   306  	// more than one session ticket. If called with a nil *ClientSessionState,
   307  	// it should remove the cache entry.
   308  	Put(sessionKey string, cs *ClientSessionState)
   309  }
   310  
   311  // SignatureScheme identifies a signature algorithm supported by TLS. See
   312  // RFC 8446, Section 4.2.3.
   313  type SignatureScheme uint16
   314  
   315  const (
   316  	// RSASSA-PKCS1-v1_5 algorithms.
   317  	PKCS1WithSHA256 SignatureScheme = 0x0401
   318  	PKCS1WithSHA384 SignatureScheme = 0x0501
   319  	PKCS1WithSHA512 SignatureScheme = 0x0601
   320  
   321  	// RSASSA-PSS algorithms with public key OID rsaEncryption.
   322  	PSSWithSHA256 SignatureScheme = 0x0804
   323  	PSSWithSHA384 SignatureScheme = 0x0805
   324  	PSSWithSHA512 SignatureScheme = 0x0806
   325  
   326  	// ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
   327  	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
   328  	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
   329  	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
   330  
   331  	// EdDSA algorithms.
   332  	Ed25519 SignatureScheme = 0x0807
   333  
   334  	// Legacy signature and hash algorithms for TLS 1.2.
   335  	PKCS1WithSHA1 SignatureScheme = 0x0201
   336  	ECDSAWithSHA1 SignatureScheme = 0x0203
   337  
   338  	SM2WithSM3 SignatureScheme = 0x0708
   339  )
   340  
   341  // ClientHelloInfo contains information from a ClientHello message in order to
   342  // guide application logic in the GetCertificate and GetConfigForClient callbacks.
   343  type ClientHelloInfo struct {
   344  	// CipherSuites lists the CipherSuites supported by the client (e.g.
   345  	// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
   346  	CipherSuites []uint16
   347  	// ServerName indicates the name of the server requested by the client
   348  	// in order to support virtual hosting. ServerName is only set if the
   349  	// client is using SNI (see RFC 4366, Section 3.1).
   350  	ServerName string
   351  	// SupportedCurves lists the elliptic curves supported by the client.
   352  	// SupportedCurves is set only if the Supported Elliptic Curves
   353  	// Extension is being used (see RFC 4492, Section 5.1.1).
   354  	SupportedCurves []CurveID
   355  	// SupportedPoints lists the point formats supported by the client.
   356  	// SupportedPoints is set only if the Supported Point Formats Extension
   357  	// is being used (see RFC 4492, Section 5.1.2).
   358  	SupportedPoints []uint8
   359  	// SignatureSchemes lists the signature and hash schemes that the client
   360  	// is willing to verify. SignatureSchemes is set only if the Signature
   361  	// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
   362  	SignatureSchemes []SignatureScheme
   363  	// SupportedProtos lists the application protocols supported by the client.
   364  	// SupportedProtos is set only if the Application-Layer Protocol
   365  	// Negotiation Extension is being used (see RFC 7301, Section 3.1).
   366  	//
   367  	// Servers can select a protocol by setting Config.NextProtos in a
   368  	// GetConfigForClient return value.
   369  	SupportedProtos []string
   370  	// SupportedVersions lists the TLS versions supported by the client.
   371  	// For TLS versions less than 1.3, this is extrapolated from the max
   372  	// version advertised by the client, so values other than the greatest
   373  	// might be rejected if used.
   374  	SupportedVersions []uint16
   375  	// Conn is the underlying net.Conn for the connection. Do not read
   376  	// from, or write to, this connection; that will cause the TLS
   377  	// connection to fail.
   378  	Conn net.Conn
   379  	// config is embedded by the GetCertificate or GetConfigForClient caller,
   380  	// for use with SupportsCertificate.
   381  	config *Config
   382  }
   383  
   384  // CertificateRequestInfo contains information from a server's
   385  // CertificateRequest message, which is used to demand a certificate and proof
   386  // of control from a client.
   387  type CertificateRequestInfo struct {
   388  	// AcceptableCAs contains zero or more, DER-encoded, X.501
   389  	// Distinguished Names. These are the names of root or intermediate CAs
   390  	// that the server wishes the returned certificate to be signed by. An
   391  	// empty slice indicates that the server has no preference.
   392  	AcceptableCAs [][]byte
   393  	// SignatureSchemes lists the signature schemes that the server is
   394  	// willing to verify.
   395  	SignatureSchemes []SignatureScheme
   396  	// Version is the TLS version that was negotiated for this connection.
   397  	Version uint16
   398  }
   399  
   400  // RenegotiationSupport enumerates the different levels of support for TLS
   401  // renegotiation. TLS renegotiation is the act of performing subsequent
   402  // handshakes on a connection after the first. This significantly complicates
   403  // the state machine and has been the source of numerous, subtle security
   404  // issues. Initiating a renegotiation is not supported, but support for
   405  // accepting renegotiation requests may be enabled.
   406  //
   407  // Even when enabled, the server may not change its identity between handshakes
   408  // (i.e. the leaf certificate must be the same). Additionally, concurrent
   409  // handshake and application data flow is not permitted so renegotiation can
   410  // only be used with protocols that synchronise with the renegotiation, such as
   411  // HTTPS.
   412  //
   413  // Renegotiation is not defined in TLS 1.3.
   414  type RenegotiationSupport int
   415  
   416  const (
   417  	// RenegotiateNever disables renegotiation.
   418  	RenegotiateNever RenegotiationSupport = iota
   419  	// RenegotiateOnceAsClient allows a remote server to request
   420  	// renegotiation once per connection.
   421  	RenegotiateOnceAsClient
   422  	// RenegotiateFreelyAsClient allows a remote server to repeatedly
   423  	// request renegotiation.
   424  	RenegotiateFreelyAsClient
   425  )
   426  
   427  // A Config structure is used to configure a TLS client or server.
   428  // After one has been passed to a TLS function it must not be
   429  // modified. A Config may be reused; the tls package will also not
   430  // modify it.
   431  type Config struct {
   432  	//if not nil, will support GMT0024
   433  	GMSupport *GMSupport
   434  	// Rand provides the source of entropy for nonces and RSA blinding.
   435  	// If Rand is nil, TLS uses the cryptographic random reader in package
   436  	// crypto/rand.
   437  	// The Reader must be safe for use by multiple goroutines.
   438  	Rand io.Reader
   439  	// Time returns the current time as the number of seconds since the epoch.
   440  	// If Time is nil, TLS uses time.Now.
   441  	Time func() time.Time
   442  	// Certificates contains one or more certificate chains to present to the
   443  	// other side of the connection. The first certificate compatible with the
   444  	// peer's requirements is selected automatically.
   445  	//
   446  	// Server configurations must set one of Certificates, GetCertificate or
   447  	// GetConfigForClient. Clients doing client-authentication may set either
   448  	// Certificates or GetClientCertificate.
   449  	//
   450  	// Note: if there are multiple Certificates, and they don't have the
   451  	// optional field Leaf set, certificate selection will incur a significant
   452  	// per-handshake performance cost.
   453  	Certificates []Certificate
   454  	// NameToCertificate maps from a certificate name to an element of
   455  	// Certificates. Note that a certificate name can be of the form
   456  	// '*.example.com' and so doesn't have to be a domain name as such.
   457  	//
   458  	// Deprecated: NameToCertificate only allows associating a single
   459  	// certificate with a given name. Leave this field nil to let the library
   460  	// select the first compatible chain from Certificates.
   461  	NameToCertificate map[string]*Certificate
   462  	// GetCertificate returns a Certificate based on the given
   463  	// ClientHelloInfo. It will only be called if the client supplies SNI
   464  	// information or if Certificates is empty.
   465  	//
   466  	// If GetCertificate is nil or returns nil, then the certificate is
   467  	// retrieved from NameToCertificate. If NameToCertificate is nil, the
   468  	// best element of Certificates will be used.
   469  	GetCertificate func(*ClientHelloInfo) (*Certificate, error)
   470  	// GetKECertificate 获取密钥交换证书(加密证书)
   471  	// 这个方法只有在使用Config中Certificates为空或长度小于2时,才会被调用。
   472  	// 如果该方法为空,则默认从证书列表中 Certificates 取出第二个位置的证书,也就是加密证书。
   473  	// 该方法只有GMSSL流程中才会调用。
   474  	GetKECertificate func(*ClientHelloInfo) (*Certificate, error)
   475  	// GetClientCertificate, if not nil, is called when a server requests a
   476  	// certificate from a client. If set, the contents of Certificates will
   477  	// be ignored.
   478  	//
   479  	// If GetClientCertificate returns an error, the handshake will be
   480  	// aborted and that error will be returned. Otherwise
   481  	// GetClientCertificate must return a non-nil Certificate. If
   482  	// Certificate.Certificate is empty then no certificate will be sent to
   483  	// the server. If this is unacceptable to the server then it may abort
   484  	// the handshake.
   485  	//
   486  	// GetClientCertificate may be called multiple times for the same
   487  	// connection if renegotiation occurs or if TLS 1.3 is in use.
   488  	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
   489  	// GetConfigForClient, if not nil, is called after a ClientHello is
   490  	// received from a client. It may return a non-nil Config in order to
   491  	// change the Config that will be used to handle this connection. If
   492  	// the returned Config is nil, the original Config will be used. The
   493  	// Config returned by this callback may not be subsequently modified.
   494  	//
   495  	// If GetConfigForClient is nil, the Config passed to Server() will be
   496  	// used for all connections.
   497  	//
   498  	// Uniquely for the fields in the returned Config, session ticket keys
   499  	// will be duplicated from the original Config if not set.
   500  	// Specifically, if SetSessionTicketKeys was called on the original
   501  	// config but not on the returned config then the ticket keys from the
   502  	// original config will be copied into the new config before use.
   503  	// Otherwise, if SessionTicketKey was set in the original config but
   504  	// not in the returned config then it will be copied into the returned
   505  	// config before use. If neither of those cases applies then the key
   506  	// material from the returned config will be used for session tickets.
   507  	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
   508  	// VerifyPeerCertificate, if not nil, is called after normal
   509  	// certificate verification by either a TLS client or server. It
   510  	// receives the raw ASN.1 certificates provided by the peer and also
   511  	// any verified chains that normal processing found. If it returns a
   512  	// non-nil error, the handshake is aborted and that error results.
   513  	//
   514  	// If normal verification fails then the handshake will abort before
   515  	// considering this callback. If normal verification is disabled by
   516  	// setting InsecureSkipVerify, or (for a server) when ClientAuth is
   517  	// RequestClientCert or RequireAnyClientCert, then this callback will
   518  	// be considered but the verifiedChains argument will always be nil.
   519  	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*cmx509.Certificate) error
   520  	// RootCAs defines the set of root certificate authorities
   521  	// that clients use when verifying server certificates.
   522  	// If RootCAs is nil, TLS uses the host's root CA set.
   523  	RootCAs *cmx509.CertPool
   524  	// NextProtos is a list of supported application level protocols, in
   525  	// order of preference.
   526  	NextProtos []string
   527  	// ServerName is used to verify the hostname on the returned
   528  	// certificates unless InsecureSkipVerify is given. It is also included
   529  	// in the client's handshake to support virtual hosting unless it is
   530  	// an IP address.
   531  	ServerName string
   532  	// ClientAuth determines the server's policy for
   533  	// TLS Client Authentication. The default is NoClientCert.
   534  	ClientAuth ClientAuthType
   535  	// ClientCAs defines the set of root certificate authorities
   536  	// that servers use if required to verify a client certificate
   537  	// by the policy in ClientAuth.
   538  	ClientCAs *cmx509.CertPool
   539  	// InsecureSkipVerify controls whether a client verifies the
   540  	// server's certificate chain and host name.
   541  	// If InsecureSkipVerify is true, TLS accepts any certificate
   542  	// presented by the server and any host name in that certificate.
   543  	// In this mode, TLS is susceptible to man-in-the-middle attacks.
   544  	// This should be used only for testing.
   545  	InsecureSkipVerify bool
   546  	// CipherSuites is a list of supported cipher suites for TLS versions up to
   547  	// TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites
   548  	// is used, with a preference order based on hardware performance. The
   549  	// default cipher suites might change over Go versions. Note that TLS 1.3
   550  	// ciphersuites are not configurable.
   551  	CipherSuites []uint16
   552  	// PreferServerCipherSuites controls whether the server selects the
   553  	// client's most preferred ciphersuite, or the server's most preferred
   554  	// ciphersuite. If true then the server's preference, as expressed in
   555  	// the order of elements in CipherSuites, is used.
   556  	PreferServerCipherSuites bool
   557  	// SessionTicketsDisabled may be set to true to disable session ticket and
   558  	// PSK (resumption) support. Note that on clients, session ticket support is
   559  	// also disabled if ClientSessionCache is nil.
   560  	SessionTicketsDisabled bool
   561  	// SessionTicketKey is used by TLS servers to provide session resumption.
   562  	// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
   563  	// with random data before the first server handshake.
   564  	//
   565  	// If multiple servers are terminating connections for the same host
   566  	// they should all have the same SessionTicketKey. If the
   567  	// SessionTicketKey leaks, previously recorded and future TLS
   568  	// connections using that key might be compromised.
   569  	SessionTicketKey [32]byte
   570  	// ClientSessionCache is a cache of ClientSessionState entries for TLS
   571  	// session resumption. It is only used by clients.
   572  	ClientSessionCache ClientSessionCache
   573  	// MinVersion contains the minimum TLS version that is acceptable.
   574  	// If zero, TLS 1.0 is currently taken as the minimum.
   575  	MinVersion uint16
   576  	// MaxVersion contains the maximum TLS version that is acceptable.
   577  	// If zero, the maximum version supported by this package is used,
   578  	// which is currently TLS 1.3.
   579  	MaxVersion uint16
   580  	// CurvePreferences contains the elliptic curves that will be used in
   581  	// an ECDHE handshake, in preference order. If empty, the default will
   582  	// be used. The client will use the first preference as the type for
   583  	// its key share in TLS 1.3. This may change in the future.
   584  	CurvePreferences []CurveID
   585  	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
   586  	// When true, the largest possible TLS record size is always used. When
   587  	// false, the size of TLS records may be adjusted in an attempt to
   588  	// improve latency.
   589  	DynamicRecordSizingDisabled bool
   590  	// Renegotiation controls what types of renegotiation are supported.
   591  	// The default, none, is correct for the vast majority of applications.
   592  	Renegotiation RenegotiationSupport
   593  	// KeyLogWriter optionally specifies a destination for TLS master secrets
   594  	// in NSS key log format that can be used to allow external programs
   595  	// such as Wireshark to decrypt TLS connections.
   596  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   597  	// Use of KeyLogWriter compromises security and should only be
   598  	// used for debugging.
   599  	KeyLogWriter   io.Writer
   600  	serverInitOnce sync.Once // guards calling (*Config).serverInit
   601  	// mutex protects sessionTicketKeys.
   602  	mutex sync.RWMutex
   603  	// sessionTicketKeys contains zero or more ticket keys. If the length
   604  	// is zero, SessionTicketsDisabled must be true. The first key is used
   605  	// for new tickets and any subsequent keys can be used to decrypt old
   606  	// tickets.
   607  	sessionTicketKeys []ticketKey
   608  }
   609  
   610  // ticketKeyNameLen is the number of bytes of identifier that is prepended to
   611  // an encrypted session ticket in order to identify the key used to encrypt it.
   612  const ticketKeyNameLen = 16
   613  
   614  // ticketKey is the internal representation of a session ticket key.
   615  type ticketKey struct {
   616  	// keyName is an opaque byte string that serves to identify the session
   617  	// ticket key. It's exposed as plaintext in every session ticket.
   618  	keyName [ticketKeyNameLen]byte
   619  	aesKey  [16]byte
   620  	hmacKey [16]byte
   621  }
   622  
   623  // ticketKeyFromBytes converts from the external representation of a session
   624  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   625  // bytes and this function expands that into sufficient name and key material.
   626  func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   627  	hashed := sha512.Sum512(b[:])
   628  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   629  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   630  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   631  	return key
   632  }
   633  
   634  // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
   635  // ticket, and the lifetime we set for tickets we send.
   636  const maxSessionTicketLifetime = 7 * 24 * time.Hour
   637  
   638  // Clone returns a shallow clone of c. It is safe to clone a Config that is
   639  // being used concurrently by a TLS client or server.
   640  func (c *Config) Clone() *Config {
   641  	// Running serverInit ensures that it's safe to read
   642  	// SessionTicketsDisabled.
   643  	c.serverInitOnce.Do(func() { c.serverInit(nil) })
   644  	var sessionTicketKeys []ticketKey
   645  	c.mutex.RLock()
   646  	sessionTicketKeys = c.sessionTicketKeys
   647  	c.mutex.RUnlock()
   648  	return &Config{
   649  		GMSupport:                   c.GMSupport,
   650  		Rand:                        c.Rand,
   651  		Time:                        c.Time,
   652  		Certificates:                c.Certificates,
   653  		NameToCertificate:           c.NameToCertificate,
   654  		GetCertificate:              c.GetCertificate,
   655  		GetKECertificate:            c.GetKECertificate,
   656  		GetClientCertificate:        c.GetClientCertificate,
   657  		GetConfigForClient:          c.GetConfigForClient,
   658  		VerifyPeerCertificate:       c.VerifyPeerCertificate,
   659  		RootCAs:                     c.RootCAs,
   660  		NextProtos:                  c.NextProtos,
   661  		ServerName:                  c.ServerName,
   662  		ClientAuth:                  c.ClientAuth,
   663  		ClientCAs:                   c.ClientCAs,
   664  		InsecureSkipVerify:          c.InsecureSkipVerify,
   665  		CipherSuites:                c.CipherSuites,
   666  		PreferServerCipherSuites:    c.PreferServerCipherSuites,
   667  		SessionTicketsDisabled:      c.SessionTicketsDisabled,
   668  		SessionTicketKey:            c.SessionTicketKey,
   669  		ClientSessionCache:          c.ClientSessionCache,
   670  		MinVersion:                  c.MinVersion,
   671  		MaxVersion:                  c.MaxVersion,
   672  		CurvePreferences:            c.CurvePreferences,
   673  		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   674  		Renegotiation:               c.Renegotiation,
   675  		KeyLogWriter:                c.KeyLogWriter,
   676  		sessionTicketKeys:           sessionTicketKeys,
   677  	}
   678  }
   679  
   680  // serverInit is run under c.serverInitOnce to do initialization of c. If c was
   681  // returned by a GetConfigForClient callback then the argument should be the
   682  // Config that was passed to Server, otherwise it should be nil.
   683  func (c *Config) serverInit(originalConfig *Config) {
   684  	if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
   685  		return
   686  	}
   687  	alreadySet := false
   688  	for _, b := range c.SessionTicketKey {
   689  		if b != 0 {
   690  			alreadySet = true
   691  			break
   692  		}
   693  	}
   694  	if !alreadySet {
   695  		if originalConfig != nil {
   696  			copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
   697  		} else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   698  			c.SessionTicketsDisabled = true
   699  			return
   700  		}
   701  	}
   702  	if originalConfig != nil {
   703  		originalConfig.mutex.RLock()
   704  		c.sessionTicketKeys = originalConfig.sessionTicketKeys
   705  		originalConfig.mutex.RUnlock()
   706  	} else {
   707  		c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
   708  	}
   709  }
   710  
   711  func (c *Config) ticketKeys() []ticketKey {
   712  	c.mutex.RLock()
   713  	// c.sessionTicketKeys is constant once created. SetSessionTicketKeys
   714  	// will only update it by replacing it with a new value.
   715  	ret := c.sessionTicketKeys
   716  	c.mutex.RUnlock()
   717  	return ret
   718  }
   719  
   720  // SetSessionTicketKeys updates the session ticket keys for a server. The first
   721  // key will be used when creating new tickets, while all keys can be used for
   722  // decrypting tickets. It is safe to call this function while the server is
   723  // running in order to rotate the session ticket keys. The function will panic
   724  // if keys is empty.
   725  func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
   726  	if len(keys) == 0 {
   727  		panic("tls: keys must have at least one key")
   728  	}
   729  	newKeys := make([]ticketKey, len(keys))
   730  	for i, bytes := range keys {
   731  		newKeys[i] = ticketKeyFromBytes(bytes)
   732  	}
   733  	c.mutex.Lock()
   734  	c.sessionTicketKeys = newKeys
   735  	c.mutex.Unlock()
   736  }
   737  
   738  func (c *Config) rand() io.Reader {
   739  	r := c.Rand
   740  	if r == nil {
   741  		return rand.Reader
   742  	}
   743  	return r
   744  }
   745  
   746  func (c *Config) time() time.Time {
   747  	t := c.Time
   748  	if t == nil {
   749  		t = time.Now
   750  	}
   751  	return t()
   752  }
   753  
   754  func (c *Config) cipherSuites() []uint16 {
   755  	s := c.CipherSuites
   756  	if s == nil {
   757  		s = defaultCipherSuites()
   758  	}
   759  	return s
   760  }
   761  
   762  var supportedVersions = []uint16{
   763  	VersionTLS13,
   764  	VersionTLS12,
   765  	VersionTLS11,
   766  	VersionTLS10,
   767  	VersionGMSSL,
   768  }
   769  
   770  func (c *Config) supportedVersions() []uint16 {
   771  	versions := make([]uint16, 0, len(supportedVersions))
   772  	for _, v := range supportedVersions {
   773  		if c != nil && c.MinVersion != 0 && v < c.MinVersion {
   774  			continue
   775  		}
   776  		if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
   777  			continue
   778  		}
   779  		versions = append(versions, v)
   780  	}
   781  	return versions
   782  }
   783  
   784  func (c *Config) maxSupportedVersion() uint16 {
   785  	supportedVersions := c.supportedVersions()
   786  	if len(supportedVersions) == 0 {
   787  		return 0
   788  	}
   789  	return supportedVersions[0]
   790  }
   791  
   792  func (c *Config) minVersion() uint16 {
   793  	if c == nil || c.MinVersion == 0 {
   794  		return minVersion
   795  	}
   796  	return c.MinVersion
   797  }
   798  
   799  func (c *Config) maxVersion() uint16 {
   800  	if c == nil || c.MaxVersion == 0 {
   801  		return maxVersion
   802  	}
   803  	return c.MaxVersion
   804  }
   805  
   806  // supportedVersionsFromMax returns a list of supported versions derived from a
   807  // legacy maximum version value. Note that only versions supported by this
   808  // library are returned. Any newer peer will use supportedVersions anyway.
   809  func supportedVersionsFromMax(maxVersion uint16) []uint16 {
   810  	versions := make([]uint16, 0, len(supportedVersions))
   811  	for _, v := range supportedVersions {
   812  		if v > maxVersion {
   813  			continue
   814  		}
   815  		versions = append(versions, v)
   816  	}
   817  	return versions
   818  }
   819  
   820  var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521, SM2P256V1}
   821  
   822  func (c *Config) curvePreferences() []CurveID {
   823  	if c == nil || len(c.CurvePreferences) == 0 {
   824  		return defaultCurvePreferences
   825  	}
   826  	return c.CurvePreferences
   827  }
   828  
   829  func (c *Config) supportsCurve(curve CurveID) bool {
   830  	for _, cc := range c.curvePreferences() {
   831  		if cc == curve {
   832  			return true
   833  		}
   834  	}
   835  	return false
   836  }
   837  
   838  // mutualVersion returns the protocol version to use given the advertised
   839  // versions of the peer. Priority is given to the peer preference order.
   840  func (c *Config) mutualVersion(peerVersions []uint16) (uint16, bool) {
   841  	supportedVersions := c.supportedVersions()
   842  	for _, peerVersion := range peerVersions {
   843  		for _, v := range supportedVersions {
   844  			if v == peerVersion {
   845  				return v, true
   846  			}
   847  		}
   848  	}
   849  	return 0, false
   850  }
   851  
   852  var errNoCertificates = errors.New("tls: no certificates configured")
   853  
   854  // getCertificate 返回密钥交换使用的证书及密钥
   855  // 该方法只有GMSSL会调用
   856  // 如果 Certificates 长度大于等于2时,默认返回第2个证书密钥
   857  // 如果 Certificates 为空或不足2时,调用 GetEKCertificate 方法获取。
   858  func (c *Config) getEKCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
   859  	if c.GetKECertificate != nil && (len(c.Certificates) < 2) {
   860  		cert, err := c.GetKECertificate(clientHello)
   861  		if cert != nil || err != nil {
   862  			return cert, err
   863  		}
   864  	}
   865  	if len(c.Certificates) >= 2 {
   866  		return &c.Certificates[1], nil
   867  	}
   868  	return nil, errors.New("tls: no key exchange (encrypt) certificate configured")
   869  }
   870  
   871  // getCertificate returns the best certificate for the given ClientHelloInfo,
   872  // defaulting to the first element of c.Certificates.
   873  func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
   874  	if c.GetCertificate != nil &&
   875  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
   876  		cert, err := c.GetCertificate(clientHello)
   877  		if cert != nil || err != nil {
   878  			return cert, err
   879  		}
   880  	}
   881  	if len(c.Certificates) == 0 {
   882  		return nil, errNoCertificates
   883  	}
   884  	if len(c.Certificates) == 1 {
   885  		// There's only one choice, so no point doing any work.
   886  		return &c.Certificates[0], nil
   887  	}
   888  	if c.NameToCertificate != nil {
   889  		name := strings.ToLower(clientHello.ServerName)
   890  		if cert, ok := c.NameToCertificate[name]; ok {
   891  			return cert, nil
   892  		}
   893  		if len(name) > 0 {
   894  			labels := strings.Split(name, ".")
   895  			labels[0] = "*"
   896  			wildcardName := strings.Join(labels, ".")
   897  			if cert, ok := c.NameToCertificate[wildcardName]; ok {
   898  				return cert, nil
   899  			}
   900  		}
   901  	}
   902  	for _, cert := range c.Certificates {
   903  		if err := clientHello.SupportsCertificate(&cert); err == nil {
   904  			return &cert, nil
   905  		}
   906  	}
   907  	// If nothing matches, return the first certificate.
   908  	return &c.Certificates[0], nil
   909  }
   910  
   911  // SupportsCertificate returns nil if the provided certificate is supported by
   912  // the client that sent the ClientHello. Otherwise, it returns an error
   913  // describing the reason for the incompatibility.
   914  //
   915  // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
   916  // callback, this method will take into account the associated Config. Note that
   917  // if GetConfigForClient returns a different Config, the change can't be
   918  // accounted for by this method.
   919  //
   920  // This function will call x509.ParseCertificate unless c.Leaf is set, which can
   921  // incur a significant performance cost.
   922  func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
   923  	// Note we don't currently support certificate_authorities nor
   924  	// signature_algorithms_cert, and don't check the algorithms of the
   925  	// signatures on the chain (which anyway are a SHOULD, see RFC 8446,
   926  	// Section 4.4.2.2).
   927  	config := chi.config
   928  	if config == nil {
   929  		config = &Config{}
   930  	}
   931  	vers, ok := config.mutualVersion(chi.SupportedVersions)
   932  	if !ok {
   933  		return errors.New("no mutually supported protocol versions")
   934  	}
   935  	// If the client specified the name they are trying to connect to, the
   936  	// certificate needs to be valid for it.
   937  	if chi.ServerName != "" {
   938  		x509Cert, err := c.leaf()
   939  		if err != nil {
   940  			return fmt.Errorf("failed to parse certificate: %w", err)
   941  		}
   942  		if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
   943  			return fmt.Errorf("certificate is not valid for requested server name: %w", err)
   944  		}
   945  	}
   946  	// supportsRSAFallback returns nil if the certificate and connection support
   947  	// the static RSA key exchange, and unsupported otherwise. The logic for
   948  	// supporting static RSA is completely disjoint from the logic for
   949  	// supporting signed key exchanges, so we just check it as a fallback.
   950  	supportsRSAFallback := func(unsupported error) error {
   951  		// TLS 1.3 dropped support for the static RSA key exchange.
   952  		if vers == VersionTLS13 {
   953  			return unsupported
   954  		}
   955  		// The static RSA key exchange works by decrypting a challenge with the
   956  		// RSA private key, not by signing, so check the PrivateKey implements
   957  		// crypto.Decrypter, like *rsa.PrivateKey does.
   958  		if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
   959  			if _, ok := priv.Public().(*rsa.PublicKey); !ok {
   960  				return unsupported
   961  			}
   962  		} else {
   963  			return unsupported
   964  		}
   965  		// Finally, there needs to be a mutual cipher suite that uses the static
   966  		// RSA key exchange instead of ECDHE.
   967  		rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
   968  			if c.flags&suiteECDHE != 0 {
   969  				return false
   970  			}
   971  			if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
   972  				return false
   973  			}
   974  			return true
   975  		})
   976  		if rsaCipherSuite == nil {
   977  			return unsupported
   978  		}
   979  		return nil
   980  	}
   981  	// If the client sent the signature_algorithms extension, ensure it supports
   982  	// schemes we can use with this certificate and TLS version.
   983  	if len(chi.SignatureSchemes) > 0 {
   984  		if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
   985  			return supportsRSAFallback(err)
   986  		}
   987  	}
   988  	// In TLS 1.3 we are done because supported_groups is only relevant to the
   989  	// ECDHE computation, point format negotiation is removed, cipher suites are
   990  	// only relevant to the AEAD choice, and static RSA does not exist.
   991  	if vers == VersionTLS13 {
   992  		return nil
   993  	}
   994  	// The only signed key exchange we support is ECDHE.
   995  	if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
   996  		return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
   997  	}
   998  	var ecdsaCipherSuite bool
   999  	if priv, ok := c.PrivateKey.(crypto.Signer); ok {
  1000  		switch pub := priv.Public().(type) {
  1001  		case *ecdsa.PublicKey:
  1002  			var curve CurveID
  1003  			switch pub.Curve {
  1004  			case elliptic.P256():
  1005  				curve = CurveP256
  1006  			case elliptic.P384():
  1007  				curve = CurveP384
  1008  			case elliptic.P521():
  1009  				curve = CurveP521
  1010  			default:
  1011  				return supportsRSAFallback(unsupportedCertificateError(c))
  1012  			}
  1013  			var curveOk bool
  1014  			for _, c := range chi.SupportedCurves {
  1015  				if c == curve && config.supportsCurve(c) {
  1016  					curveOk = true
  1017  					break
  1018  				}
  1019  			}
  1020  			if !curveOk {
  1021  				return errors.New("client doesn't support certificate curve")
  1022  			}
  1023  			ecdsaCipherSuite = true
  1024  		case *sm2.PublicKey:
  1025  			var curveOk bool
  1026  			for _, c := range chi.SupportedCurves {
  1027  				if c == SM2P256V1 && config.supportsCurve(c) {
  1028  					curveOk = true
  1029  					break
  1030  				}
  1031  			}
  1032  			if !curveOk {
  1033  				return errors.New("client doesn't support certificate curve")
  1034  			}
  1035  		case ed25519.PublicKey:
  1036  			if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
  1037  				return errors.New("connection doesn't support Ed25519")
  1038  			}
  1039  			ecdsaCipherSuite = true
  1040  		case *rsa.PublicKey:
  1041  		default:
  1042  			return supportsRSAFallback(unsupportedCertificateError(c))
  1043  		}
  1044  	} else {
  1045  		return supportsRSAFallback(unsupportedCertificateError(c))
  1046  	}
  1047  	// Make sure that there is a mutually supported cipher suite that works with
  1048  	// this certificate. Cipher suite selection will then apply the logic in
  1049  	// reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
  1050  	cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
  1051  		if c.flags&suiteECDHE == 0 {
  1052  			return false
  1053  		}
  1054  		if c.flags&suiteECSign != 0 {
  1055  			if !ecdsaCipherSuite {
  1056  				return false
  1057  			}
  1058  		} else {
  1059  			if ecdsaCipherSuite {
  1060  				return false
  1061  			}
  1062  		}
  1063  		if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1064  			return false
  1065  		}
  1066  		return true
  1067  	})
  1068  	if cipherSuite == nil {
  1069  		return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
  1070  	}
  1071  	return nil
  1072  }
  1073  
  1074  // SupportsCertificate returns nil if the provided certificate is supported by
  1075  // the server that sent the CertificateRequest. Otherwise, it returns an error
  1076  // describing the reason for the incompatibility.
  1077  func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
  1078  	if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
  1079  		return err
  1080  	}
  1081  	if len(cri.AcceptableCAs) == 0 {
  1082  		return nil
  1083  	}
  1084  	for j, cert := range c.Certificate {
  1085  		x509Cert := c.Leaf
  1086  		// Parse the certificate if this isn't the leaf node, or if
  1087  		// chain.Leaf was nil.
  1088  		if j != 0 || x509Cert == nil {
  1089  			var err error
  1090  			cmx509Cert, err := cmx509.ParseCertificate(cert)
  1091  			if err != nil {
  1092  				return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
  1093  			} else {
  1094  				x509Cert, _ = cmx509.HerbtCertToX509Cert(cmx509Cert)
  1095  			}
  1096  		}
  1097  		for _, ca := range cri.AcceptableCAs {
  1098  			if bytes.Equal(x509Cert.RawIssuer, ca) {
  1099  				return nil
  1100  			}
  1101  		}
  1102  	}
  1103  	return errors.New("chain is not signed by an acceptable CA")
  1104  }
  1105  
  1106  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  1107  // from the CommonName and SubjectAlternateName fields of each of the leaf
  1108  // certificates.
  1109  //
  1110  // Deprecated: NameToCertificate only allows associating a single certificate
  1111  // with a given name. Leave that field nil to let the library select the first
  1112  // compatible chain from Certificates.
  1113  func (c *Config) BuildNameToCertificate() {
  1114  	c.NameToCertificate = make(map[string]*Certificate)
  1115  	for i := range c.Certificates {
  1116  		cert := &c.Certificates[i]
  1117  		x509Cert, err := cert.leaf()
  1118  		if err != nil {
  1119  			continue
  1120  		}
  1121  		if len(x509Cert.Subject.CommonName) > 0 {
  1122  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  1123  		}
  1124  		for _, san := range x509Cert.DNSNames {
  1125  			c.NameToCertificate[san] = cert
  1126  		}
  1127  	}
  1128  }
  1129  
  1130  const (
  1131  	keyLogLabelTLS12           = "CLIENT_RANDOM"
  1132  	keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  1133  	keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  1134  	keyLogLabelClientTraffic   = "CLIENT_TRAFFIC_SECRET_0"
  1135  	keyLogLabelServerTraffic   = "SERVER_TRAFFIC_SECRET_0"
  1136  )
  1137  
  1138  func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
  1139  	if c.KeyLogWriter == nil {
  1140  		return nil
  1141  	}
  1142  	logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
  1143  	writerMutex.Lock()
  1144  	_, err := c.KeyLogWriter.Write(logLine)
  1145  	writerMutex.Unlock()
  1146  	return err
  1147  }
  1148  
  1149  // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  1150  // and is only for debugging, so a global mutex saves space.
  1151  var writerMutex sync.Mutex
  1152  
  1153  // A Certificate is a chain of one or more certificates, leaf first.
  1154  type Certificate struct {
  1155  	Certificate [][]byte
  1156  	// PrivateKey contains the private key corresponding to the public key in
  1157  	// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
  1158  	// For a server up to TLS 1.2, it can also implement crypto.Decrypter with
  1159  	// an RSA PublicKey.
  1160  	PrivateKey crypto.PrivateKey
  1161  	// SupportedSignatureAlgorithms is an optional list restricting what
  1162  	// signature algorithms the PrivateKey can be used for.
  1163  	SupportedSignatureAlgorithms []SignatureScheme
  1164  	// OCSPStaple contains an optional OCSP response which will be served
  1165  	// to clients that request it.
  1166  	OCSPStaple []byte
  1167  	// SignedCertificateTimestamps contains an optional list of Signed
  1168  	// Certificate Timestamps which will be served to clients that request it.
  1169  	SignedCertificateTimestamps [][]byte
  1170  	// Leaf is the parsed form of the leaf certificate, which may be initialized
  1171  	// using x509.ParseCertificate to reduce per-handshake processing. If nil,
  1172  	// the leaf certificate will be parsed as needed.
  1173  	Leaf *x509.Certificate
  1174  }
  1175  
  1176  // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
  1177  // the corresponding c.Certificate[0].
  1178  func (c *Certificate) leaf() (*x509.Certificate, error) {
  1179  	if c.Leaf != nil {
  1180  		return c.Leaf, nil
  1181  	}
  1182  	return x509.ParseCertificate(c.Certificate[0])
  1183  }
  1184  
  1185  type handshakeMessage interface {
  1186  	marshal() []byte
  1187  	unmarshal([]byte) bool
  1188  }
  1189  
  1190  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  1191  // caching strategy.
  1192  type lruSessionCache struct {
  1193  	sync.Mutex
  1194  	m        map[string]*list.Element
  1195  	q        *list.List
  1196  	capacity int
  1197  }
  1198  
  1199  type lruSessionCacheEntry struct {
  1200  	sessionKey string
  1201  	state      *ClientSessionState
  1202  }
  1203  
  1204  // NewLRUClientSessionCache returns a ClientSessionCache with the given
  1205  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  1206  // is used instead.
  1207  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  1208  	const defaultSessionCacheCapacity = 64
  1209  	if capacity < 1 {
  1210  		capacity = defaultSessionCacheCapacity
  1211  	}
  1212  	return &lruSessionCache{
  1213  		m:        make(map[string]*list.Element),
  1214  		q:        list.New(),
  1215  		capacity: capacity,
  1216  	}
  1217  }
  1218  
  1219  // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
  1220  // corresponding to sessionKey is removed from the cache instead.
  1221  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  1222  	c.Lock()
  1223  	defer c.Unlock()
  1224  	if elem, ok := c.m[sessionKey]; ok {
  1225  		if cs == nil {
  1226  			c.q.Remove(elem)
  1227  			delete(c.m, sessionKey)
  1228  		} else {
  1229  			entry := elem.Value.(*lruSessionCacheEntry)
  1230  			entry.state = cs
  1231  			c.q.MoveToFront(elem)
  1232  		}
  1233  		return
  1234  	}
  1235  	if c.q.Len() < c.capacity {
  1236  		entry := &lruSessionCacheEntry{sessionKey, cs}
  1237  		c.m[sessionKey] = c.q.PushFront(entry)
  1238  		return
  1239  	}
  1240  	elem := c.q.Back()
  1241  	entry := elem.Value.(*lruSessionCacheEntry)
  1242  	delete(c.m, entry.sessionKey)
  1243  	entry.sessionKey = sessionKey
  1244  	entry.state = cs
  1245  	c.q.MoveToFront(elem)
  1246  	c.m[sessionKey] = elem
  1247  }
  1248  
  1249  // Get returns the ClientSessionState value associated with a given key. It
  1250  // returns (nil, false) if no value is found.
  1251  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  1252  	c.Lock()
  1253  	defer c.Unlock()
  1254  	if elem, ok := c.m[sessionKey]; ok {
  1255  		c.q.MoveToFront(elem)
  1256  		return elem.Value.(*lruSessionCacheEntry).state, true
  1257  	}
  1258  	return nil, false
  1259  }
  1260  
  1261  // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  1262  type dsaSignature struct {
  1263  	R, S *big.Int
  1264  }
  1265  
  1266  type ecdsaSignature dsaSignature
  1267  
  1268  var emptyConfig Config
  1269  
  1270  func defaultConfig() *Config {
  1271  	return &emptyConfig
  1272  }
  1273  
  1274  var (
  1275  	once                        sync.Once
  1276  	varDefaultCipherSuites      []uint16
  1277  	varDefaultCipherSuitesTLS13 []uint16
  1278  )
  1279  
  1280  func defaultCipherSuites() []uint16 {
  1281  	once.Do(initDefaultCipherSuites)
  1282  	return varDefaultCipherSuites
  1283  }
  1284  
  1285  func defaultCipherSuitesTLS13() []uint16 {
  1286  	once.Do(initDefaultCipherSuites)
  1287  	return varDefaultCipherSuitesTLS13
  1288  }
  1289  
  1290  func initDefaultCipherSuites() {
  1291  	var topCipherSuites []uint16
  1292  	// Check the cpu flags for each platform that has optimized GCM implementations.
  1293  	// Worst case, these variables will just all be false.
  1294  	var (
  1295  		hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
  1296  		hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
  1297  		// Keep in sync with crypto/aes/cipher_s390x.go.
  1298  		hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
  1299  		hasGCMAsm      = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
  1300  	)
  1301  
  1302  	if hasGCMAsm {
  1303  		// If AES-GCM hardware is provided then prioritise AES-GCM
  1304  		// cipher suites.
  1305  		topCipherSuites = []uint16{
  1306  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1307  			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1308  			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1309  			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1310  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1311  			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1312  		}
  1313  		varDefaultCipherSuitesTLS13 = []uint16{
  1314  			TLS_AES_128_GCM_SHA256,
  1315  			TLS_CHACHA20_POLY1305_SHA256,
  1316  			TLS_AES_256_GCM_SHA384,
  1317  		}
  1318  	} else {
  1319  		// Without AES-GCM hardware, we put the ChaCha20-Poly1305
  1320  		// cipher suites first.
  1321  		topCipherSuites = []uint16{
  1322  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1323  			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1324  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1325  			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1326  			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1327  			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1328  		}
  1329  		varDefaultCipherSuitesTLS13 = []uint16{
  1330  			TLS_CHACHA20_POLY1305_SHA256,
  1331  			TLS_AES_128_GCM_SHA256,
  1332  			TLS_AES_256_GCM_SHA384,
  1333  		}
  1334  	}
  1335  	varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  1336  	varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
  1337  
  1338  NextCipherSuite:
  1339  	for _, suite := range cipherSuites {
  1340  		if suite.flags&suiteDefaultOff != 0 {
  1341  			continue
  1342  		}
  1343  		for _, existing := range varDefaultCipherSuites {
  1344  			if existing == suite.id {
  1345  				continue NextCipherSuite
  1346  			}
  1347  		}
  1348  		varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  1349  	}
  1350  }
  1351  
  1352  func unexpectedMessageError(wanted, got interface{}) error {
  1353  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1354  }
  1355  
  1356  func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1357  	for _, s := range supportedSignatureAlgorithms {
  1358  		if s == sigAlg {
  1359  			return true
  1360  		}
  1361  	}
  1362  	return false
  1363  }