github.com/hellobchain/newcryptosm@v0.0.0-20221019060107-edb949a317e9/tls/common.go (about)

     1  /*
     2  Copyright Suzhou Tongji Fintech Research Institute 2017 All Rights Reserved.
     3  Licensed under the Apache License, Version 2.0 (the "License");
     4  you may not use this file except in compliance with the License.
     5  You may obtain a copy of the License at
     6  
     7  	http://www.apache.org/licenses/LICENSE-2.0
     8  
     9  Unless required by applicable law or agreed to in writing, software
    10  distributed under the License is distributed on an "AS IS" BASIS,
    11  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  See the License for the specific language governing permissions and
    13  limitations under the License.
    14  */
    15  
    16  package tls
    17  
    18  import (
    19  	"container/list"
    20  	"crypto"
    21  	"crypto/rand"
    22  	"crypto/sha512"
    23  	"errors"
    24  	"fmt"
    25  	x5092 "github.com/hellobchain/newcryptosm/x509"
    26  	"io"
    27  	"math/big"
    28  	"net"
    29  	"strings"
    30  	"sync"
    31  	"time"
    32  )
    33  
    34  const (
    35  	VersionSSL30 = 0x0300
    36  	VersionTLS10 = 0x0301
    37  	VersionTLS11 = 0x0302
    38  	VersionTLS12 = 0x0303
    39  	VersionTLS13 = 0x0304
    40  )
    41  
    42  const (
    43  	maxPlaintext    = 16384        // maximum plaintext payload length
    44  	maxCiphertext   = 16384 + 2048 // maximum ciphertext payload length
    45  	recordHeaderLen = 5            // record header length
    46  	maxHandshake    = 65536        // maximum handshake we support (protocol max is 16 MB)
    47  
    48  	minVersion = VersionTLS10
    49  	maxVersion = VersionTLS12
    50  )
    51  
    52  // TLS record types.
    53  type recordType uint8
    54  
    55  const (
    56  	recordTypeChangeCipherSpec recordType = 20
    57  	recordTypeAlert            recordType = 21
    58  	recordTypeHandshake        recordType = 22
    59  	recordTypeApplicationData  recordType = 23
    60  )
    61  
    62  // TLS handshake message types.
    63  const (
    64  	typeHelloRequest       uint8 = 0
    65  	typeClientHello        uint8 = 1
    66  	typeServerHello        uint8 = 2
    67  	typeNewSessionTicket   uint8 = 4
    68  	typeCertificate        uint8 = 11
    69  	typeServerKeyExchange  uint8 = 12
    70  	typeCertificateRequest uint8 = 13
    71  	typeServerHelloDone    uint8 = 14
    72  	typeCertificateVerify  uint8 = 15
    73  	typeClientKeyExchange  uint8 = 16
    74  	typeFinished           uint8 = 20
    75  	typeCertificateStatus  uint8 = 22
    76  	typeNextProtocol       uint8 = 67 // Not IANA assigned
    77  )
    78  
    79  // TLS compression types.
    80  const (
    81  	compressionNone uint8 = 0
    82  )
    83  
    84  // TLS extension numbers
    85  const (
    86  	extensionServerName          uint16 = 0
    87  	extensionStatusRequest       uint16 = 5
    88  	extensionSupportedCurves     uint16 = 10
    89  	extensionSupportedPoints     uint16 = 11
    90  	extensionSignatureAlgorithms uint16 = 13
    91  	extensionALPN                uint16 = 16
    92  	extensionSCT                 uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6
    93  	extensionSessionTicket       uint16 = 35
    94  	extensionNextProtoNeg        uint16 = 13172 // not IANA assigned
    95  	extensionRenegotiationInfo   uint16 = 0xff01
    96  )
    97  
    98  // TLS signaling cipher suite values
    99  const (
   100  	scsvRenegotiation uint16 = 0x00ff
   101  )
   102  
   103  // CurveID is the type of a TLS identifier for an elliptic curve. See
   104  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
   105  type CurveID uint16
   106  
   107  const (
   108  	CurveP256   CurveID = 23
   109  	CurveP384   CurveID = 24
   110  	CurveP521   CurveID = 25
   111  	X25519      CurveID = 29
   112  	CureP256SM2 CurveID = 41
   113  )
   114  
   115  // TLS Elliptic Curve Point Formats
   116  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
   117  const (
   118  	pointFormatUncompressed uint8 = 0
   119  )
   120  
   121  // TLS CertificateStatusType (RFC 3546)
   122  const (
   123  	statusTypeOCSP uint8 = 1
   124  )
   125  
   126  // Certificate types (for certificateRequestMsg)
   127  const (
   128  	certTypeRSASign    = 1 // A certificate containing an RSA key
   129  	certTypeDSSSign    = 2 // A certificate containing a DSA key
   130  	certTypeRSAFixedDH = 3 // A certificate containing a static DH key
   131  	certTypeDSSFixedDH = 4 // A certificate containing a static DH key
   132  
   133  	// See RFC 4492 sections 3 and 5.5.
   134  	certTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
   135  	certTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
   136  	certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
   137  	certTypeSM2Sign        = 41 // wsw add
   138  	// Rest of these are reserved by the TLS spec
   139  )
   140  
   141  // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
   142  const (
   143  	hashSHA1   uint8 = 2
   144  	hashSHA256 uint8 = 4
   145  	hashSHA384 uint8 = 5
   146  	hashSM3    uint8 = 7 // wsw add
   147  )
   148  
   149  // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
   150  const (
   151  	signatureRSA   uint8 = 1
   152  	signatureECDSA uint8 = 3
   153  	signatureSM2   uint8 = 8 //wsw add
   154  )
   155  
   156  // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
   157  // RFC 5246, section A.4.1.
   158  type signatureAndHash struct {
   159  	hash, signature uint8
   160  }
   161  
   162  // supportedSignatureAlgorithms contains the signature and hash algorithms that
   163  // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2
   164  // CertificateRequest.
   165  var supportedSignatureAlgorithms = []signatureAndHash{
   166  	{hashSHA256, signatureECDSA},
   167  	{hashSM3, signatureSM2}, // wsw add
   168  }
   169  
   170  // ConnectionState records basic TLS details about the connection.
   171  type ConnectionState struct {
   172  	Version                     uint16                 // TLS version used by the connection (e.g. VersionTLS12)
   173  	HandshakeComplete           bool                   // TLS handshake is complete
   174  	DidResume                   bool                   // connection resumes a previous TLS connection
   175  	CipherSuite                 uint16                 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
   176  	NegotiatedProtocol          string                 // negotiated next protocol (from Config.NextProtos)
   177  	NegotiatedProtocolIsMutual  bool                   // negotiated protocol was advertised by server
   178  	ServerName                  string                 // server name requested by client, if any (server side only)
   179  	PeerCertificates            []*x5092.Certificate   // certificate chain presented by remote peer
   180  	VerifiedChains              [][]*x5092.Certificate // verified chains built from PeerCertificates
   181  	SignedCertificateTimestamps [][]byte               // SCTs from the server, if any
   182  	OCSPResponse                []byte                 // stapled OCSP response from server, if any
   183  
   184  	// TLSUnique contains the "tls-unique" channel binding value (see RFC
   185  	// 5929, section 3). For resumed sessions this value will be nil
   186  	// because resumption does not include enough context (see
   187  	// https://secure-resumption.com/#channelbindings). This will change in
   188  	// future versions of Go once the TLS master-secret fix has been
   189  	// standardized and implemented.
   190  	TLSUnique []byte
   191  }
   192  
   193  // ClientAuthType declares the policy the server will follow for
   194  // TLS Client Authentication.
   195  type ClientAuthType int
   196  
   197  const (
   198  	NoClientCert ClientAuthType = iota
   199  	RequestClientCert
   200  	RequireAnyClientCert
   201  	VerifyClientCertIfGiven
   202  	RequireAndVerifyClientCert
   203  )
   204  
   205  // ClientSessionState contains the state needed by clients to resume TLS
   206  // sessions.
   207  type ClientSessionState struct {
   208  	sessionTicket      []uint8                // Encrypted ticket used for session resumption with server
   209  	vers               uint16                 // SSL/TLS version negotiated for the session
   210  	cipherSuite        uint16                 // Ciphersuite negotiated for the session
   211  	masterSecret       []byte                 // MasterSecret generated by client on a full handshake
   212  	serverCertificates []*x5092.Certificate   // Certificate chain presented by the server
   213  	verifiedChains     [][]*x5092.Certificate // Certificate chains we built for verification
   214  }
   215  
   216  // ClientSessionCache is a cache of ClientSessionState objects that can be used
   217  // by a client to resume a TLS session with a given server. ClientSessionCache
   218  // implementations should expect to be called concurrently from different
   219  // goroutines.
   220  type ClientSessionCache interface {
   221  	// Get searches for a ClientSessionState associated with the given key.
   222  	// On return, ok is true if one was found.
   223  	Get(sessionKey string) (session *ClientSessionState, ok bool)
   224  
   225  	// Put adds the ClientSessionState to the cache with the given key.
   226  	Put(sessionKey string, cs *ClientSessionState)
   227  }
   228  
   229  // SignatureScheme identifies a signature algorithm supported by TLS. See
   230  // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3.
   231  type SignatureScheme uint16
   232  
   233  const (
   234  	PKCS1WithSHA1   SignatureScheme = 0x0201
   235  	PKCS1WithSHA256 SignatureScheme = 0x0401
   236  	PKCS1WithSHA384 SignatureScheme = 0x0501
   237  	PKCS1WithSHA512 SignatureScheme = 0x0601
   238  
   239  	PSSWithSHA256 SignatureScheme = 0x0804
   240  	PSSWithSHA384 SignatureScheme = 0x0805
   241  	PSSWithSHA512 SignatureScheme = 0x0806
   242  
   243  	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
   244  	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
   245  	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
   246  	SM2WithP256AndSM3      SignatureScheme = 0x0708 // wsw add
   247  
   248  )
   249  
   250  // ClientHelloInfo contains information from a ClientHello message in order to
   251  // guide certificate selection in the GetCertificate callback.
   252  type ClientHelloInfo struct {
   253  	// CipherSuites lists the CipherSuites supported by the client (e.g.
   254  	// TLS_RSA_WITH_RC4_128_SHA).
   255  	CipherSuites []uint16
   256  
   257  	// ServerName indicates the name of the server requested by the client
   258  	// in order to support virtual hosting. ServerName is only set if the
   259  	// client is using SNI (see
   260  	// http://tools.ietf.org/html/rfc4366#section-3.1).
   261  	ServerName string
   262  
   263  	// SupportedCurves lists the elliptic curves supported by the client.
   264  	// SupportedCurves is set only if the Supported Elliptic Curves
   265  	// Extension is being used (see
   266  	// http://tools.ietf.org/html/rfc4492#section-5.1.1).
   267  	SupportedCurves []CurveID
   268  
   269  	// SupportedPoints lists the point formats supported by the client.
   270  	// SupportedPoints is set only if the Supported Point Formats Extension
   271  	// is being used (see
   272  	// http://tools.ietf.org/html/rfc4492#section-5.1.2).
   273  	SupportedPoints []uint8
   274  
   275  	// SignatureSchemes lists the signature and hash schemes that the client
   276  	// is willing to verify. SignatureSchemes is set only if the Signature
   277  	// Algorithms Extension is being used (see
   278  	// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1).
   279  	SignatureSchemes []SignatureScheme
   280  
   281  	// SupportedProtos lists the application protocols supported by the client.
   282  	// SupportedProtos is set only if the Application-Layer Protocol
   283  	// Negotiation Extension is being used (see
   284  	// https://tools.ietf.org/html/rfc7301#section-3.1).
   285  	//
   286  	// Servers can select a protocol by setting Config.NextProtos in a
   287  	// GetConfigForClient return value.
   288  	SupportedProtos []string
   289  
   290  	// SupportedVersions lists the TLS versions supported by the client.
   291  	// For TLS versions less than 1.3, this is extrapolated from the max
   292  	// version advertised by the client, so values other than the greatest
   293  	// might be rejected if used.
   294  	SupportedVersions []uint16
   295  
   296  	// Conn is the underlying net.Conn for the connection. Do not read
   297  	// from, or write to, this connection; that will cause the TLS
   298  	// connection to fail.
   299  	Conn net.Conn
   300  }
   301  
   302  // CertificateRequestInfo contains information from a server's
   303  // CertificateRequest message, which is used to demand a certificate and proof
   304  // of control from a client.
   305  type CertificateRequestInfo struct {
   306  	// AcceptableCAs contains zero or more, DER-encoded, X.501
   307  	// Distinguished Names. These are the names of root or intermediate CAs
   308  	// that the server wishes the returned certificate to be signed by. An
   309  	// empty slice indicates that the server has no preference.
   310  	AcceptableCAs [][]byte
   311  
   312  	// SignatureSchemes lists the signature schemes that the server is
   313  	// willing to verify.
   314  	SignatureSchemes []SignatureScheme
   315  }
   316  
   317  // RenegotiationSupport enumerates the different levels of support for TLS
   318  // renegotiation. TLS renegotiation is the act of performing subsequent
   319  // handshakes on a connection after the first. This significantly complicates
   320  // the state machine and has been the source of numerous, subtle security
   321  // issues. Initiating a renegotiation is not supported, but support for
   322  // accepting renegotiation requests may be enabled.
   323  //
   324  // Even when enabled, the server may not change its identity between handshakes
   325  // (i.e. the leaf certificate must be the same). Additionally, concurrent
   326  // handshake and application data flow is not permitted so renegotiation can
   327  // only be used with protocols that synchronise with the renegotiation, such as
   328  // HTTPS.
   329  type RenegotiationSupport int
   330  
   331  const (
   332  	// RenegotiateNever disables renegotiation.
   333  	RenegotiateNever RenegotiationSupport = iota
   334  
   335  	// RenegotiateOnceAsClient allows a remote server to request
   336  	// renegotiation once per connection.
   337  	RenegotiateOnceAsClient
   338  
   339  	// RenegotiateFreelyAsClient allows a remote server to repeatedly
   340  	// request renegotiation.
   341  	RenegotiateFreelyAsClient
   342  )
   343  
   344  // A Config structure is used to configure a TLS client or server.
   345  // After one has been passed to a TLS function it must not be
   346  // modified. A Config may be reused; the tls package will also not
   347  // modify it.
   348  type Config struct {
   349  	// Rand provides the source of entropy for nonces and RSA blinding.
   350  	// If Rand is nil, TLS uses the cryptographic random reader in package
   351  	// crypto/rand.
   352  	// The Reader must be safe for use by multiple goroutines.
   353  	Rand io.Reader
   354  
   355  	// Time returns the current time as the number of seconds since the epoch.
   356  	// If Time is nil, TLS uses time.Now.
   357  	Time func() time.Time
   358  
   359  	// Certificates contains one or more certificate chains to present to
   360  	// the other side of the connection. Server configurations must include
   361  	// at least one certificate or else set GetCertificate. Clients doing
   362  	// client-authentication may set either Certificates or
   363  	// GetClientCertificate.
   364  	Certificates []Certificate
   365  
   366  	// NameToCertificate maps from a certificate name to an element of
   367  	// Certificates. Note that a certificate name can be of the form
   368  	// '*.example.com' and so doesn't have to be a domain name as such.
   369  	// See Config.BuildNameToCertificate
   370  	// The nil value causes the first element of Certificates to be used
   371  	// for all connections.
   372  	NameToCertificate map[string]*Certificate
   373  
   374  	// GetCertificate returns a Certificate based on the given
   375  	// ClientHelloInfo. It will only be called if the client supplies SNI
   376  	// information or if Certificates is empty.
   377  	//
   378  	// If GetCertificate is nil or returns nil, then the certificate is
   379  	// retrieved from NameToCertificate. If NameToCertificate is nil, the
   380  	// first element of Certificates will be used.
   381  	GetCertificate func(*ClientHelloInfo) (*Certificate, error)
   382  
   383  	// GetClientCertificate, if not nil, is called when a server requests a
   384  	// certificate from a client. If set, the contents of Certificates will
   385  	// be ignored.
   386  	//
   387  	// If GetClientCertificate returns an error, the handshake will be
   388  	// aborted and that error will be returned. Otherwise
   389  	// GetClientCertificate must return a non-nil Certificate. If
   390  	// Certificate.Certificate is empty then no certificate will be sent to
   391  	// the server. If this is unacceptable to the server then it may abort
   392  	// the handshake.
   393  	//
   394  	// GetClientCertificate may be called multiple times for the same
   395  	// connection if renegotiation occurs or if TLS 1.3 is in use.
   396  	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
   397  
   398  	// GetConfigForClient, if not nil, is called after a ClientHello is
   399  	// received from a client. It may return a non-nil Config in order to
   400  	// change the Config that will be used to handle this connection. If
   401  	// the returned Config is nil, the original Config will be used. The
   402  	// Config returned by this callback may not be subsequently modified.
   403  	//
   404  	// If GetConfigForClient is nil, the Config passed to Server() will be
   405  	// used for all connections.
   406  	//
   407  	// Uniquely for the fields in the returned Config, session ticket keys
   408  	// will be duplicated from the original Config if not set.
   409  	// Specifically, if SetSessionTicketKeys was called on the original
   410  	// config but not on the returned config then the ticket keys from the
   411  	// original config will be copied into the new config before use.
   412  	// Otherwise, if SessionTicketKey was set in the original config but
   413  	// not in the returned config then it will be copied into the returned
   414  	// config before use. If neither of those cases applies then the key
   415  	// material from the returned config will be used for session tickets.
   416  	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
   417  
   418  	// VerifyPeerCertificate, if not nil, is called after normal
   419  	// certificate verification by either a TLS client or server. It
   420  	// receives the raw ASN.1 certificates provided by the peer and also
   421  	// any verified chains that normal processing found. If it returns a
   422  	// non-nil error, the handshake is aborted and that error results.
   423  	//
   424  	// If normal verification fails then the handshake will abort before
   425  	// considering this callback. If normal verification is disabled by
   426  	// setting InsecureSkipVerify then this callback will be considered but
   427  	// the verifiedChains argument will always be nil.
   428  	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x5092.Certificate) error
   429  
   430  	// RootCAs defines the set of root certificate authorities
   431  	// that clients use when verifying server certificates.
   432  	// If RootCAs is nil, TLS uses the host's root CA set.
   433  	RootCAs *x5092.CertPool
   434  
   435  	// NextProtos is a list of supported, application level protocols.
   436  	NextProtos []string
   437  
   438  	// ServerName is used to verify the hostname on the returned
   439  	// certificates unless InsecureSkipVerify is given. It is also included
   440  	// in the client's handshake to support virtual hosting unless it is
   441  	// an IP address.
   442  	ServerName string
   443  
   444  	// ClientAuth determines the server's policy for
   445  	// TLS Client Authentication. The default is NoClientCert.
   446  	ClientAuth ClientAuthType
   447  
   448  	// ClientCAs defines the set of root certificate authorities
   449  	// that servers use if required to verify a client certificate
   450  	// by the policy in ClientAuth.
   451  	ClientCAs *x5092.CertPool
   452  
   453  	// InsecureSkipVerify controls whether a client verifies the
   454  	// server's certificate chain and host name.
   455  	// If InsecureSkipVerify is true, TLS accepts any certificate
   456  	// presented by the server and any host name in that certificate.
   457  	// In this mode, TLS is susceptible to man-in-the-middle attacks.
   458  	// This should be used only for testing.
   459  	InsecureSkipVerify bool
   460  
   461  	// CipherSuites is a list of supported cipher suites. If CipherSuites
   462  	// is nil, TLS uses a list of suites supported by the implementation.
   463  	CipherSuites []uint16
   464  
   465  	// PreferServerCipherSuites controls whether the server selects the
   466  	// client's most preferred ciphersuite, or the server's most preferred
   467  	// ciphersuite. If true then the server's preference, as expressed in
   468  	// the order of elements in CipherSuites, is used.
   469  	PreferServerCipherSuites bool
   470  
   471  	// SessionTicketsDisabled may be set to true to disable session ticket
   472  	// (resumption) support.
   473  	SessionTicketsDisabled bool
   474  
   475  	// SessionTicketKey is used by TLS servers to provide session
   476  	// resumption. See RFC 5077. If zero, it will be filled with
   477  	// random data before the first server handshake.
   478  	//
   479  	// If multiple servers are terminating connections for the same host
   480  	// they should all have the same SessionTicketKey. If the
   481  	// SessionTicketKey leaks, previously recorded and future TLS
   482  	// connections using that key are compromised.
   483  	SessionTicketKey [32]byte
   484  
   485  	// SessionCache is a cache of ClientSessionState entries for TLS session
   486  	// resumption.
   487  	ClientSessionCache ClientSessionCache
   488  
   489  	// MinVersion contains the minimum SSL/TLS version that is acceptable.
   490  	// If zero, then TLS 1.0 is taken as the minimum.
   491  	MinVersion uint16
   492  
   493  	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
   494  	// If zero, then the maximum version supported by this package is used,
   495  	// which is currently TLS 1.2.
   496  	MaxVersion uint16
   497  
   498  	// CurvePreferences contains the elliptic curves that will be used in
   499  	// an ECDHE handshake, in preference order. If empty, the default will
   500  	// be used.
   501  	CurvePreferences []CurveID
   502  
   503  	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
   504  	// When true, the largest possible TLS record size is always used. When
   505  	// false, the size of TLS records may be adjusted in an attempt to
   506  	// improve latency.
   507  	DynamicRecordSizingDisabled bool
   508  
   509  	// Renegotiation controls what types of renegotiation are supported.
   510  	// The default, none, is correct for the vast majority of applications.
   511  	Renegotiation RenegotiationSupport
   512  
   513  	// KeyLogWriter optionally specifies a destination for TLS master secrets
   514  	// in NSS key log format that can be used to allow external programs
   515  	// such as Wireshark to decrypt TLS connections.
   516  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   517  	// Use of KeyLogWriter compromises security and should only be
   518  	// used for debugging.
   519  	KeyLogWriter io.Writer
   520  
   521  	serverInitOnce sync.Once // guards calling (*Config).serverInit
   522  
   523  	// mutex protects sessionTicketKeys and originalConfig.
   524  	mutex sync.RWMutex
   525  	// sessionTicketKeys contains zero or more ticket keys. If the length
   526  	// is zero, SessionTicketsDisabled must be true. The first key is used
   527  	// for new tickets and any subsequent keys can be used to decrypt old
   528  	// tickets.
   529  	sessionTicketKeys []ticketKey
   530  	// originalConfig is set to the Config that was passed to Server if
   531  	// this Config is returned by a GetConfigForClient callback. It's used
   532  	// by serverInit in order to copy session ticket keys if needed.
   533  	originalConfig *Config
   534  }
   535  
   536  // ticketKeyNameLen is the number of bytes of identifier that is prepended to
   537  // an encrypted session ticket in order to identify the key used to encrypt it.
   538  const ticketKeyNameLen = 16
   539  
   540  // ticketKey is the internal representation of a session ticket key.
   541  type ticketKey struct {
   542  	// keyName is an opaque byte string that serves to identify the session
   543  	// ticket key. It's exposed as plaintext in every session ticket.
   544  	keyName [ticketKeyNameLen]byte
   545  	aesKey  [16]byte
   546  	hmacKey [16]byte
   547  }
   548  
   549  // ticketKeyFromBytes converts from the external representation of a session
   550  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   551  // bytes and this function expands that into sufficient name and key material.
   552  func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   553  	hashed := sha512.Sum512(b[:])
   554  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   555  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   556  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   557  	return key
   558  }
   559  
   560  // Clone returns a shallow clone of c. It is safe to clone a Config that is
   561  // being used concurrently by a TLS client or server.
   562  func (c *Config) Clone() *Config {
   563  	// Running serverInit ensures that it's safe to read
   564  	// SessionTicketsDisabled.
   565  	c.serverInitOnce.Do(c.serverInit)
   566  
   567  	var sessionTicketKeys []ticketKey
   568  	c.mutex.RLock()
   569  	sessionTicketKeys = c.sessionTicketKeys
   570  	c.mutex.RUnlock()
   571  
   572  	return &Config{
   573  		Rand:                        c.Rand,
   574  		Time:                        c.Time,
   575  		Certificates:                c.Certificates,
   576  		NameToCertificate:           c.NameToCertificate,
   577  		GetCertificate:              c.GetCertificate,
   578  		GetConfigForClient:          c.GetConfigForClient,
   579  		VerifyPeerCertificate:       c.VerifyPeerCertificate,
   580  		RootCAs:                     c.RootCAs,
   581  		NextProtos:                  c.NextProtos,
   582  		ServerName:                  c.ServerName,
   583  		ClientAuth:                  c.ClientAuth,
   584  		ClientCAs:                   c.ClientCAs,
   585  		InsecureSkipVerify:          c.InsecureSkipVerify,
   586  		CipherSuites:                c.CipherSuites,
   587  		PreferServerCipherSuites:    c.PreferServerCipherSuites,
   588  		SessionTicketsDisabled:      c.SessionTicketsDisabled,
   589  		SessionTicketKey:            c.SessionTicketKey,
   590  		ClientSessionCache:          c.ClientSessionCache,
   591  		MinVersion:                  c.MinVersion,
   592  		MaxVersion:                  c.MaxVersion,
   593  		CurvePreferences:            c.CurvePreferences,
   594  		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   595  		Renegotiation:               c.Renegotiation,
   596  		KeyLogWriter:                c.KeyLogWriter,
   597  		sessionTicketKeys:           sessionTicketKeys,
   598  		// originalConfig is deliberately not duplicated.
   599  	}
   600  }
   601  
   602  func (c *Config) serverInit() {
   603  	if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
   604  		return
   605  	}
   606  
   607  	var originalConfig *Config
   608  	c.mutex.Lock()
   609  	originalConfig, c.originalConfig = c.originalConfig, nil
   610  	c.mutex.Unlock()
   611  
   612  	alreadySet := false
   613  	for _, b := range c.SessionTicketKey {
   614  		if b != 0 {
   615  			alreadySet = true
   616  			break
   617  		}
   618  	}
   619  
   620  	if !alreadySet {
   621  		if originalConfig != nil {
   622  			copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
   623  		} else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   624  			c.SessionTicketsDisabled = true
   625  			return
   626  		}
   627  	}
   628  
   629  	if originalConfig != nil {
   630  		originalConfig.mutex.RLock()
   631  		c.sessionTicketKeys = originalConfig.sessionTicketKeys
   632  		originalConfig.mutex.RUnlock()
   633  	} else {
   634  		c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
   635  	}
   636  }
   637  
   638  func (c *Config) ticketKeys() []ticketKey {
   639  	c.mutex.RLock()
   640  	// c.sessionTicketKeys is constant once created. SetSessionTicketKeys
   641  	// will only update it by replacing it with a new value.
   642  	ret := c.sessionTicketKeys
   643  	c.mutex.RUnlock()
   644  	return ret
   645  }
   646  
   647  // SetSessionTicketKeys updates the session ticket keys for a server. The first
   648  // key will be used when creating new tickets, while all keys can be used for
   649  // decrypting tickets. It is safe to call this function while the server is
   650  // running in order to rotate the session ticket keys. The function will panic
   651  // if keys is empty.
   652  func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
   653  	if len(keys) == 0 {
   654  		panic("tls: keys must have at least one key")
   655  	}
   656  
   657  	newKeys := make([]ticketKey, len(keys))
   658  	for i, bytes := range keys {
   659  		newKeys[i] = ticketKeyFromBytes(bytes)
   660  	}
   661  
   662  	c.mutex.Lock()
   663  	c.sessionTicketKeys = newKeys
   664  	c.mutex.Unlock()
   665  }
   666  
   667  func (c *Config) rand() io.Reader {
   668  	r := c.Rand
   669  	if r == nil {
   670  		return rand.Reader
   671  	}
   672  	return r
   673  }
   674  
   675  func (c *Config) time() time.Time {
   676  	t := c.Time
   677  	if t == nil {
   678  		t = time.Now
   679  	}
   680  	return t()
   681  }
   682  
   683  func (c *Config) cipherSuites() []uint16 {
   684  	s := c.CipherSuites
   685  	if s == nil {
   686  		s = defaultCipherSuites()
   687  	}
   688  	return s
   689  }
   690  
   691  func (c *Config) minVersion() uint16 {
   692  	if c == nil || c.MinVersion == 0 {
   693  		return minVersion
   694  	}
   695  	return c.MinVersion
   696  }
   697  
   698  func (c *Config) maxVersion() uint16 {
   699  	if c == nil || c.MaxVersion == 0 {
   700  		return maxVersion
   701  	}
   702  	return c.MaxVersion
   703  }
   704  
   705  var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521, CureP256SM2}
   706  
   707  func (c *Config) curvePreferences() []CurveID {
   708  	if c == nil || len(c.CurvePreferences) == 0 {
   709  		return defaultCurvePreferences
   710  	}
   711  	return c.CurvePreferences
   712  }
   713  
   714  // mutualVersion returns the protocol version to use given the advertised
   715  // version of the peer.
   716  func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
   717  	minVersion := c.minVersion()
   718  	maxVersion := c.maxVersion()
   719  
   720  	if vers < minVersion {
   721  		return 0, false
   722  	}
   723  	if vers > maxVersion {
   724  		vers = maxVersion
   725  	}
   726  	return vers, true
   727  }
   728  
   729  // getCertificate returns the best certificate for the given ClientHelloInfo,
   730  // defaulting to the first element of c.Certificates.
   731  func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
   732  	if c.GetCertificate != nil &&
   733  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
   734  		cert, err := c.GetCertificate(clientHello)
   735  		if cert != nil || err != nil {
   736  			return cert, err
   737  		}
   738  	}
   739  
   740  	if len(c.Certificates) == 0 {
   741  		return nil, errors.New("tls: no certificates configured")
   742  	}
   743  
   744  	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
   745  		// There's only one choice, so no point doing any work.
   746  		return &c.Certificates[0], nil
   747  	}
   748  
   749  	name := strings.ToLower(clientHello.ServerName)
   750  	for len(name) > 0 && name[len(name)-1] == '.' {
   751  		name = name[:len(name)-1]
   752  	}
   753  
   754  	if cert, ok := c.NameToCertificate[name]; ok {
   755  		return cert, nil
   756  	}
   757  
   758  	// try replacing labels in the name with wildcards until we get a
   759  	// match.
   760  	labels := strings.Split(name, ".")
   761  	for i := range labels {
   762  		labels[i] = "*"
   763  		candidate := strings.Join(labels, ".")
   764  		if cert, ok := c.NameToCertificate[candidate]; ok {
   765  			return cert, nil
   766  		}
   767  	}
   768  
   769  	// If nothing matches, return the first certificate.
   770  	return &c.Certificates[0], nil
   771  }
   772  
   773  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
   774  // from the CommonName and SubjectAlternateName fields of each of the leaf
   775  // certificates.
   776  func (c *Config) BuildNameToCertificate() {
   777  	c.NameToCertificate = make(map[string]*Certificate)
   778  	for i := range c.Certificates {
   779  		cert := &c.Certificates[i]
   780  		x509Cert, err := x5092.ParseCertificate(cert.Certificate[0])
   781  		if err != nil {
   782  			continue
   783  		}
   784  		if len(x509Cert.Subject.CommonName) > 0 {
   785  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
   786  		}
   787  		for _, san := range x509Cert.DNSNames {
   788  			c.NameToCertificate[san] = cert
   789  		}
   790  	}
   791  }
   792  
   793  // writeKeyLog logs client random and master secret if logging was enabled by
   794  // setting c.KeyLogWriter.
   795  func (c *Config) writeKeyLog(clientRandom, masterSecret []byte) error {
   796  	if c.KeyLogWriter == nil {
   797  		return nil
   798  	}
   799  
   800  	logLine := []byte(fmt.Sprintf("CLIENT_RANDOM %x %x\n", clientRandom, masterSecret))
   801  
   802  	writerMutex.Lock()
   803  	_, err := c.KeyLogWriter.Write(logLine)
   804  	writerMutex.Unlock()
   805  
   806  	return err
   807  }
   808  
   809  // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
   810  // and is only for debugging, so a global mutex saves space.
   811  var writerMutex sync.Mutex
   812  
   813  // A Certificate is a chain of one or more certificates, leaf first.
   814  type Certificate struct {
   815  	Certificate [][]byte
   816  	// PrivateKey contains the private key corresponding to the public key
   817  	// in Leaf. For a server, this must implement crypto.Signer and/or
   818  	// crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
   819  	// (performing client authentication), this must be a crypto.Signer
   820  	// with an RSA or ECDSA PublicKey.
   821  	PrivateKey crypto.PrivateKey
   822  	// OCSPStaple contains an optional OCSP response which will be served
   823  	// to clients that request it.
   824  	OCSPStaple []byte
   825  	// SignedCertificateTimestamps contains an optional list of Signed
   826  	// Certificate Timestamps which will be served to clients that request it.
   827  	SignedCertificateTimestamps [][]byte
   828  	// Leaf is the parsed form of the leaf certificate, which may be
   829  	// initialized using x509.ParseCertificate to reduce per-handshake
   830  	// processing for TLS clients doing client authentication. If nil, the
   831  	// leaf certificate will be parsed as needed.
   832  	Leaf *x5092.Certificate
   833  }
   834  
   835  type handshakeMessage interface {
   836  	marshal() []byte
   837  	unmarshal([]byte) bool
   838  }
   839  
   840  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
   841  // caching strategy.
   842  type lruSessionCache struct {
   843  	sync.Mutex
   844  
   845  	m        map[string]*list.Element
   846  	q        *list.List
   847  	capacity int
   848  }
   849  
   850  type lruSessionCacheEntry struct {
   851  	sessionKey string
   852  	state      *ClientSessionState
   853  }
   854  
   855  // NewLRUClientSessionCache returns a ClientSessionCache with the given
   856  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
   857  // is used instead.
   858  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
   859  	const defaultSessionCacheCapacity = 64
   860  
   861  	if capacity < 1 {
   862  		capacity = defaultSessionCacheCapacity
   863  	}
   864  	return &lruSessionCache{
   865  		m:        make(map[string]*list.Element),
   866  		q:        list.New(),
   867  		capacity: capacity,
   868  	}
   869  }
   870  
   871  // Put adds the provided (sessionKey, cs) pair to the cache.
   872  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
   873  	c.Lock()
   874  	defer c.Unlock()
   875  
   876  	if elem, ok := c.m[sessionKey]; ok {
   877  		entry := elem.Value.(*lruSessionCacheEntry)
   878  		entry.state = cs
   879  		c.q.MoveToFront(elem)
   880  		return
   881  	}
   882  
   883  	if c.q.Len() < c.capacity {
   884  		entry := &lruSessionCacheEntry{sessionKey, cs}
   885  		c.m[sessionKey] = c.q.PushFront(entry)
   886  		return
   887  	}
   888  
   889  	elem := c.q.Back()
   890  	entry := elem.Value.(*lruSessionCacheEntry)
   891  	delete(c.m, entry.sessionKey)
   892  	entry.sessionKey = sessionKey
   893  	entry.state = cs
   894  	c.q.MoveToFront(elem)
   895  	c.m[sessionKey] = elem
   896  }
   897  
   898  // Get returns the ClientSessionState value associated with a given key. It
   899  // returns (nil, false) if no value is found.
   900  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
   901  	c.Lock()
   902  	defer c.Unlock()
   903  
   904  	if elem, ok := c.m[sessionKey]; ok {
   905  		c.q.MoveToFront(elem)
   906  		return elem.Value.(*lruSessionCacheEntry).state, true
   907  	}
   908  	return nil, false
   909  }
   910  
   911  // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
   912  type dsaSignature struct {
   913  	R, S *big.Int
   914  }
   915  
   916  type ecdsaSignature dsaSignature
   917  
   918  type sm2Signature dsaSignature
   919  
   920  var emptyConfig Config
   921  
   922  func defaultConfig() *Config {
   923  	return &emptyConfig
   924  }
   925  
   926  var (
   927  	once                   sync.Once
   928  	varDefaultCipherSuites []uint16
   929  )
   930  
   931  func defaultCipherSuites() []uint16 {
   932  	once.Do(initDefaultCipherSuites)
   933  	return varDefaultCipherSuites
   934  }
   935  
   936  func initDefaultCipherSuites() {
   937  	var topCipherSuites []uint16
   938  	topCipherSuites = []uint16{
   939  		TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   940  		TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
   941  		TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
   942  		TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
   943  		TLS_RSA_WITH_AES_128_GCM_SHA256,
   944  		TLS_RSA_WITH_AES_256_GCM_SHA384,
   945  		TLS_SM2_WITH_SM4_SM3,
   946  		TLS_SM4_GCM_SM3,
   947  		TLS_ECDHE_SM2_WITH_SM4_SM3,
   948  		TLS_SM4_CCM_SM3,
   949  	}
   950  
   951  	varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
   952  	for _, topCipher := range topCipherSuites {
   953  		varDefaultCipherSuites = append(varDefaultCipherSuites, topCipher)
   954  	}
   955  
   956  NextCipherSuite:
   957  	for _, suite := range cipherSuites {
   958  		if suite.flags&suiteDefaultOff != 0 {
   959  			continue
   960  		}
   961  		for _, existing := range varDefaultCipherSuites {
   962  			if existing == suite.id {
   963  				continue NextCipherSuite
   964  			}
   965  		}
   966  		varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
   967  	}
   968  }
   969  
   970  func unexpectedMessageError(wanted, got interface{}) error {
   971  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
   972  }
   973  
   974  func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
   975  	for _, s := range sigHashes {
   976  		if s == sigHash {
   977  			return true
   978  		}
   979  	}
   980  	return false
   981  }