github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/crypto/tls/common.go (about)

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