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