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