github.com/huandu/go@v0.0.0-20151114150818-04e615e41150/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/rand"
    11  	"crypto/sha512"
    12  	"crypto/x509"
    13  	"errors"
    14  	"fmt"
    15  	"io"
    16  	"math/big"
    17  	"strings"
    18  	"sync"
    19  	"time"
    20  )
    21  
    22  const (
    23  	VersionSSL30 = 0x0300
    24  	VersionTLS10 = 0x0301
    25  	VersionTLS11 = 0x0302
    26  	VersionTLS12 = 0x0303
    27  )
    28  
    29  const (
    30  	maxPlaintext    = 16384        // maximum plaintext payload length
    31  	maxCiphertext   = 16384 + 2048 // maximum ciphertext payload length
    32  	recordHeaderLen = 5            // record header length
    33  	maxHandshake    = 65536        // maximum handshake we support (protocol max is 16 MB)
    34  
    35  	minVersion = VersionTLS10
    36  	maxVersion = VersionTLS12
    37  )
    38  
    39  // TLS record types.
    40  type recordType uint8
    41  
    42  const (
    43  	recordTypeChangeCipherSpec recordType = 20
    44  	recordTypeAlert            recordType = 21
    45  	recordTypeHandshake        recordType = 22
    46  	recordTypeApplicationData  recordType = 23
    47  )
    48  
    49  // TLS handshake message types.
    50  const (
    51  	typeClientHello        uint8 = 1
    52  	typeServerHello        uint8 = 2
    53  	typeNewSessionTicket   uint8 = 4
    54  	typeCertificate        uint8 = 11
    55  	typeServerKeyExchange  uint8 = 12
    56  	typeCertificateRequest uint8 = 13
    57  	typeServerHelloDone    uint8 = 14
    58  	typeCertificateVerify  uint8 = 15
    59  	typeClientKeyExchange  uint8 = 16
    60  	typeFinished           uint8 = 20
    61  	typeCertificateStatus  uint8 = 22
    62  	typeNextProtocol       uint8 = 67 // Not IANA assigned
    63  )
    64  
    65  // TLS compression types.
    66  const (
    67  	compressionNone uint8 = 0
    68  )
    69  
    70  // TLS extension numbers
    71  const (
    72  	extensionServerName          uint16 = 0
    73  	extensionStatusRequest       uint16 = 5
    74  	extensionSupportedCurves     uint16 = 10
    75  	extensionSupportedPoints     uint16 = 11
    76  	extensionSignatureAlgorithms uint16 = 13
    77  	extensionALPN                uint16 = 16
    78  	extensionSCT                 uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6
    79  	extensionSessionTicket       uint16 = 35
    80  	extensionNextProtoNeg        uint16 = 13172 // not IANA assigned
    81  	extensionRenegotiationInfo   uint16 = 0xff01
    82  )
    83  
    84  // TLS signaling cipher suite values
    85  const (
    86  	scsvRenegotiation uint16 = 0x00ff
    87  )
    88  
    89  // CurveID is the type of a TLS identifier for an elliptic curve. See
    90  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
    91  type CurveID uint16
    92  
    93  const (
    94  	CurveP256 CurveID = 23
    95  	CurveP384 CurveID = 24
    96  	CurveP521 CurveID = 25
    97  )
    98  
    99  // TLS Elliptic Curve Point Formats
   100  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
   101  const (
   102  	pointFormatUncompressed uint8 = 0
   103  )
   104  
   105  // TLS CertificateStatusType (RFC 3546)
   106  const (
   107  	statusTypeOCSP uint8 = 1
   108  )
   109  
   110  // Certificate types (for certificateRequestMsg)
   111  const (
   112  	certTypeRSASign    = 1 // A certificate containing an RSA key
   113  	certTypeDSSSign    = 2 // A certificate containing a DSA key
   114  	certTypeRSAFixedDH = 3 // A certificate containing a static DH key
   115  	certTypeDSSFixedDH = 4 // A certificate containing a static DH key
   116  
   117  	// See RFC4492 sections 3 and 5.5.
   118  	certTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
   119  	certTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
   120  	certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
   121  
   122  	// Rest of these are reserved by the TLS spec
   123  )
   124  
   125  // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
   126  const (
   127  	hashSHA1   uint8 = 2
   128  	hashSHA256 uint8 = 4
   129  	hashSHA384 uint8 = 5
   130  )
   131  
   132  // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
   133  const (
   134  	signatureRSA   uint8 = 1
   135  	signatureECDSA uint8 = 3
   136  )
   137  
   138  // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
   139  // RFC 5246, section A.4.1.
   140  type signatureAndHash struct {
   141  	hash, signature uint8
   142  }
   143  
   144  // supportedSignatureAlgorithms contains the signature and hash algorithms that
   145  // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2
   146  // CertificateRequest.
   147  var supportedSignatureAlgorithms = []signatureAndHash{
   148  	{hashSHA256, signatureRSA},
   149  	{hashSHA256, signatureECDSA},
   150  	{hashSHA384, signatureRSA},
   151  	{hashSHA384, signatureECDSA},
   152  	{hashSHA1, signatureRSA},
   153  	{hashSHA1, signatureECDSA},
   154  }
   155  
   156  // ConnectionState records basic TLS details about the connection.
   157  type ConnectionState struct {
   158  	Version                     uint16                // TLS version used by the connection (e.g. VersionTLS12)
   159  	HandshakeComplete           bool                  // TLS handshake is complete
   160  	DidResume                   bool                  // connection resumes a previous TLS connection
   161  	CipherSuite                 uint16                // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
   162  	NegotiatedProtocol          string                // negotiated next protocol (from Config.NextProtos)
   163  	NegotiatedProtocolIsMutual  bool                  // negotiated protocol was advertised by server
   164  	ServerName                  string                // server name requested by client, if any (server side only)
   165  	PeerCertificates            []*x509.Certificate   // certificate chain presented by remote peer
   166  	VerifiedChains              [][]*x509.Certificate // verified chains built from PeerCertificates
   167  	SignedCertificateTimestamps [][]byte              // SCTs from the server, if any
   168  	OCSPResponse                []byte                // stapled OCSP response from server, if any
   169  
   170  	// TLSUnique contains the "tls-unique" channel binding value (see RFC
   171  	// 5929, section 3). For resumed sessions this value will be nil
   172  	// because resumption does not include enough context (see
   173  	// https://secure-resumption.com/#channelbindings). This will change in
   174  	// future versions of Go once the TLS master-secret fix has been
   175  	// standardized and implemented.
   176  	TLSUnique []byte
   177  }
   178  
   179  // ClientAuthType declares the policy the server will follow for
   180  // TLS Client Authentication.
   181  type ClientAuthType int
   182  
   183  const (
   184  	NoClientCert ClientAuthType = iota
   185  	RequestClientCert
   186  	RequireAnyClientCert
   187  	VerifyClientCertIfGiven
   188  	RequireAndVerifyClientCert
   189  )
   190  
   191  // ClientSessionState contains the state needed by clients to resume TLS
   192  // sessions.
   193  type ClientSessionState struct {
   194  	sessionTicket      []uint8               // Encrypted ticket used for session resumption with server
   195  	vers               uint16                // SSL/TLS version negotiated for the session
   196  	cipherSuite        uint16                // Ciphersuite negotiated for the session
   197  	masterSecret       []byte                // MasterSecret generated by client on a full handshake
   198  	serverCertificates []*x509.Certificate   // Certificate chain presented by the server
   199  	verifiedChains     [][]*x509.Certificate // Certificate chains we built for verification
   200  }
   201  
   202  // ClientSessionCache is a cache of ClientSessionState objects that can be used
   203  // by a client to resume a TLS session with a given server. ClientSessionCache
   204  // implementations should expect to be called concurrently from different
   205  // goroutines.
   206  type ClientSessionCache interface {
   207  	// Get searches for a ClientSessionState associated with the given key.
   208  	// On return, ok is true if one was found.
   209  	Get(sessionKey string) (session *ClientSessionState, ok bool)
   210  
   211  	// Put adds the ClientSessionState to the cache with the given key.
   212  	Put(sessionKey string, cs *ClientSessionState)
   213  }
   214  
   215  // ClientHelloInfo contains information from a ClientHello message in order to
   216  // guide certificate selection in the GetCertificate callback.
   217  type ClientHelloInfo struct {
   218  	// CipherSuites lists the CipherSuites supported by the client (e.g.
   219  	// TLS_RSA_WITH_RC4_128_SHA).
   220  	CipherSuites []uint16
   221  
   222  	// ServerName indicates the name of the server requested by the client
   223  	// in order to support virtual hosting. ServerName is only set if the
   224  	// client is using SNI (see
   225  	// http://tools.ietf.org/html/rfc4366#section-3.1).
   226  	ServerName string
   227  
   228  	// SupportedCurves lists the elliptic curves supported by the client.
   229  	// SupportedCurves is set only if the Supported Elliptic Curves
   230  	// Extension is being used (see
   231  	// http://tools.ietf.org/html/rfc4492#section-5.1.1).
   232  	SupportedCurves []CurveID
   233  
   234  	// SupportedPoints lists the point formats supported by the client.
   235  	// SupportedPoints is set only if the Supported Point Formats Extension
   236  	// is being used (see
   237  	// http://tools.ietf.org/html/rfc4492#section-5.1.2).
   238  	SupportedPoints []uint8
   239  }
   240  
   241  // A Config structure is used to configure a TLS client or server.
   242  // After one has been passed to a TLS function it must not be
   243  // modified. A Config may be reused; the tls package will also not
   244  // modify it.
   245  type Config struct {
   246  	// Rand provides the source of entropy for nonces and RSA blinding.
   247  	// If Rand is nil, TLS uses the cryptographic random reader in package
   248  	// crypto/rand.
   249  	// The Reader must be safe for use by multiple goroutines.
   250  	Rand io.Reader
   251  
   252  	// Time returns the current time as the number of seconds since the epoch.
   253  	// If Time is nil, TLS uses time.Now.
   254  	Time func() time.Time
   255  
   256  	// Certificates contains one or more certificate chains
   257  	// to present to the other side of the connection.
   258  	// Server configurations must include at least one certificate.
   259  	Certificates []Certificate
   260  
   261  	// NameToCertificate maps from a certificate name to an element of
   262  	// Certificates. Note that a certificate name can be of the form
   263  	// '*.example.com' and so doesn't have to be a domain name as such.
   264  	// See Config.BuildNameToCertificate
   265  	// The nil value causes the first element of Certificates to be used
   266  	// for all connections.
   267  	NameToCertificate map[string]*Certificate
   268  
   269  	// GetCertificate returns a Certificate based on the given
   270  	// ClientHelloInfo. It will only be called if the client supplies SNI
   271  	// information or if Certificates is empty.
   272  	//
   273  	// If GetCertificate is nil or returns nil, then the certificate is
   274  	// retrieved from NameToCertificate. If NameToCertificate is nil, the
   275  	// first element of Certificates will be used.
   276  	GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error)
   277  
   278  	// RootCAs defines the set of root certificate authorities
   279  	// that clients use when verifying server certificates.
   280  	// If RootCAs is nil, TLS uses the host's root CA set.
   281  	RootCAs *x509.CertPool
   282  
   283  	// NextProtos is a list of supported, application level protocols.
   284  	NextProtos []string
   285  
   286  	// ServerName is used to verify the hostname on the returned
   287  	// certificates unless InsecureSkipVerify is given. It is also included
   288  	// in the client's handshake to support virtual hosting.
   289  	ServerName string
   290  
   291  	// ClientAuth determines the server's policy for
   292  	// TLS Client Authentication. The default is NoClientCert.
   293  	ClientAuth ClientAuthType
   294  
   295  	// ClientCAs defines the set of root certificate authorities
   296  	// that servers use if required to verify a client certificate
   297  	// by the policy in ClientAuth.
   298  	ClientCAs *x509.CertPool
   299  
   300  	// InsecureSkipVerify controls whether a client verifies the
   301  	// server's certificate chain and host name.
   302  	// If InsecureSkipVerify is true, TLS accepts any certificate
   303  	// presented by the server and any host name in that certificate.
   304  	// In this mode, TLS is susceptible to man-in-the-middle attacks.
   305  	// This should be used only for testing.
   306  	InsecureSkipVerify bool
   307  
   308  	// CipherSuites is a list of supported cipher suites. If CipherSuites
   309  	// is nil, TLS uses a list of suites supported by the implementation.
   310  	CipherSuites []uint16
   311  
   312  	// PreferServerCipherSuites controls whether the server selects the
   313  	// client's most preferred ciphersuite, or the server's most preferred
   314  	// ciphersuite. If true then the server's preference, as expressed in
   315  	// the order of elements in CipherSuites, is used.
   316  	PreferServerCipherSuites bool
   317  
   318  	// SessionTicketsDisabled may be set to true to disable session ticket
   319  	// (resumption) support.
   320  	SessionTicketsDisabled bool
   321  
   322  	// SessionTicketKey is used by TLS servers to provide session
   323  	// resumption. See RFC 5077. If zero, it will be filled with
   324  	// random data before the first server handshake.
   325  	//
   326  	// If multiple servers are terminating connections for the same host
   327  	// they should all have the same SessionTicketKey. If the
   328  	// SessionTicketKey leaks, previously recorded and future TLS
   329  	// connections using that key are compromised.
   330  	SessionTicketKey [32]byte
   331  
   332  	// SessionCache is a cache of ClientSessionState entries for TLS session
   333  	// resumption.
   334  	ClientSessionCache ClientSessionCache
   335  
   336  	// MinVersion contains the minimum SSL/TLS version that is acceptable.
   337  	// If zero, then TLS 1.0 is taken as the minimum.
   338  	MinVersion uint16
   339  
   340  	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
   341  	// If zero, then the maximum version supported by this package is used,
   342  	// which is currently TLS 1.2.
   343  	MaxVersion uint16
   344  
   345  	// CurvePreferences contains the elliptic curves that will be used in
   346  	// an ECDHE handshake, in preference order. If empty, the default will
   347  	// be used.
   348  	CurvePreferences []CurveID
   349  
   350  	serverInitOnce sync.Once // guards calling (*Config).serverInit
   351  
   352  	// mutex protects sessionTicketKeys
   353  	mutex sync.RWMutex
   354  	// sessionTicketKeys contains zero or more ticket keys. If the length
   355  	// is zero, SessionTicketsDisabled must be true. The first key is used
   356  	// for new tickets and any subsequent keys can be used to decrypt old
   357  	// tickets.
   358  	sessionTicketKeys []ticketKey
   359  }
   360  
   361  // ticketKeyNameLen is the number of bytes of identifier that is prepended to
   362  // an encrypted session ticket in order to identify the key used to encrypt it.
   363  const ticketKeyNameLen = 16
   364  
   365  // ticketKey is the internal representation of a session ticket key.
   366  type ticketKey struct {
   367  	// keyName is an opaque byte string that serves to identify the session
   368  	// ticket key. It's exposed as plaintext in every session ticket.
   369  	keyName [ticketKeyNameLen]byte
   370  	aesKey  [16]byte
   371  	hmacKey [16]byte
   372  }
   373  
   374  // ticketKeyFromBytes converts from the external representation of a session
   375  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   376  // bytes and this function expands that into sufficient name and key material.
   377  func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   378  	hashed := sha512.Sum512(b[:])
   379  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   380  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   381  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   382  	return key
   383  }
   384  
   385  func (c *Config) serverInit() {
   386  	if c.SessionTicketsDisabled {
   387  		return
   388  	}
   389  
   390  	alreadySet := false
   391  	for _, b := range c.SessionTicketKey {
   392  		if b != 0 {
   393  			alreadySet = true
   394  			break
   395  		}
   396  	}
   397  
   398  	if !alreadySet {
   399  		if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   400  			c.SessionTicketsDisabled = true
   401  			return
   402  		}
   403  	}
   404  
   405  	c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
   406  }
   407  
   408  func (c *Config) ticketKeys() []ticketKey {
   409  	c.mutex.RLock()
   410  	// c.sessionTicketKeys is constant once created. SetSessionTicketKeys
   411  	// will only update it by replacing it with a new value.
   412  	ret := c.sessionTicketKeys
   413  	c.mutex.RUnlock()
   414  	return ret
   415  }
   416  
   417  // SetSessionTicketKeys updates the session ticket keys for a server. The first
   418  // key will be used when creating new tickets, while all keys can be used for
   419  // decrypting tickets. It is safe to call this function while the server is
   420  // running in order to rotate the session ticket keys. The function will panic
   421  // if keys is empty.
   422  func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
   423  	if len(keys) == 0 {
   424  		panic("tls: keys must have at least one key")
   425  	}
   426  
   427  	newKeys := make([]ticketKey, len(keys))
   428  	for i, bytes := range keys {
   429  		newKeys[i] = ticketKeyFromBytes(bytes)
   430  	}
   431  
   432  	c.mutex.Lock()
   433  	c.sessionTicketKeys = newKeys
   434  	c.mutex.Unlock()
   435  }
   436  
   437  func (c *Config) rand() io.Reader {
   438  	r := c.Rand
   439  	if r == nil {
   440  		return rand.Reader
   441  	}
   442  	return r
   443  }
   444  
   445  func (c *Config) time() time.Time {
   446  	t := c.Time
   447  	if t == nil {
   448  		t = time.Now
   449  	}
   450  	return t()
   451  }
   452  
   453  func (c *Config) cipherSuites() []uint16 {
   454  	s := c.CipherSuites
   455  	if s == nil {
   456  		s = defaultCipherSuites()
   457  	}
   458  	return s
   459  }
   460  
   461  func (c *Config) minVersion() uint16 {
   462  	if c == nil || c.MinVersion == 0 {
   463  		return minVersion
   464  	}
   465  	return c.MinVersion
   466  }
   467  
   468  func (c *Config) maxVersion() uint16 {
   469  	if c == nil || c.MaxVersion == 0 {
   470  		return maxVersion
   471  	}
   472  	return c.MaxVersion
   473  }
   474  
   475  var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
   476  
   477  func (c *Config) curvePreferences() []CurveID {
   478  	if c == nil || len(c.CurvePreferences) == 0 {
   479  		return defaultCurvePreferences
   480  	}
   481  	return c.CurvePreferences
   482  }
   483  
   484  // mutualVersion returns the protocol version to use given the advertised
   485  // version of the peer.
   486  func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
   487  	minVersion := c.minVersion()
   488  	maxVersion := c.maxVersion()
   489  
   490  	if vers < minVersion {
   491  		return 0, false
   492  	}
   493  	if vers > maxVersion {
   494  		vers = maxVersion
   495  	}
   496  	return vers, true
   497  }
   498  
   499  // getCertificate returns the best certificate for the given ClientHelloInfo,
   500  // defaulting to the first element of c.Certificates.
   501  func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
   502  	if c.GetCertificate != nil &&
   503  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
   504  		cert, err := c.GetCertificate(clientHello)
   505  		if cert != nil || err != nil {
   506  			return cert, err
   507  		}
   508  	}
   509  
   510  	if len(c.Certificates) == 0 {
   511  		return nil, errors.New("crypto/tls: no certificates configured")
   512  	}
   513  
   514  	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
   515  		// There's only one choice, so no point doing any work.
   516  		return &c.Certificates[0], nil
   517  	}
   518  
   519  	name := strings.ToLower(clientHello.ServerName)
   520  	for len(name) > 0 && name[len(name)-1] == '.' {
   521  		name = name[:len(name)-1]
   522  	}
   523  
   524  	if cert, ok := c.NameToCertificate[name]; ok {
   525  		return cert, nil
   526  	}
   527  
   528  	// try replacing labels in the name with wildcards until we get a
   529  	// match.
   530  	labels := strings.Split(name, ".")
   531  	for i := range labels {
   532  		labels[i] = "*"
   533  		candidate := strings.Join(labels, ".")
   534  		if cert, ok := c.NameToCertificate[candidate]; ok {
   535  			return cert, nil
   536  		}
   537  	}
   538  
   539  	// If nothing matches, return the first certificate.
   540  	return &c.Certificates[0], nil
   541  }
   542  
   543  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
   544  // from the CommonName and SubjectAlternateName fields of each of the leaf
   545  // certificates.
   546  func (c *Config) BuildNameToCertificate() {
   547  	c.NameToCertificate = make(map[string]*Certificate)
   548  	for i := range c.Certificates {
   549  		cert := &c.Certificates[i]
   550  		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
   551  		if err != nil {
   552  			continue
   553  		}
   554  		if len(x509Cert.Subject.CommonName) > 0 {
   555  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
   556  		}
   557  		for _, san := range x509Cert.DNSNames {
   558  			c.NameToCertificate[san] = cert
   559  		}
   560  	}
   561  }
   562  
   563  // A Certificate is a chain of one or more certificates, leaf first.
   564  type Certificate struct {
   565  	Certificate [][]byte
   566  	// PrivateKey contains the private key corresponding to the public key
   567  	// in Leaf. For a server, this must implement crypto.Signer and/or
   568  	// crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
   569  	// (performing client authentication), this must be a crypto.Signer
   570  	// with an RSA or ECDSA PublicKey.
   571  	PrivateKey crypto.PrivateKey
   572  	// OCSPStaple contains an optional OCSP response which will be served
   573  	// to clients that request it.
   574  	OCSPStaple []byte
   575  	// SignedCertificateTimestamps contains an optional list of Signed
   576  	// Certificate Timestamps which will be served to clients that request it.
   577  	SignedCertificateTimestamps [][]byte
   578  	// Leaf is the parsed form of the leaf certificate, which may be
   579  	// initialized using x509.ParseCertificate to reduce per-handshake
   580  	// processing for TLS clients doing client authentication. If nil, the
   581  	// leaf certificate will be parsed as needed.
   582  	Leaf *x509.Certificate
   583  }
   584  
   585  // A TLS record.
   586  type record struct {
   587  	contentType  recordType
   588  	major, minor uint8
   589  	payload      []byte
   590  }
   591  
   592  type handshakeMessage interface {
   593  	marshal() []byte
   594  	unmarshal([]byte) bool
   595  }
   596  
   597  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
   598  // caching strategy.
   599  type lruSessionCache struct {
   600  	sync.Mutex
   601  
   602  	m        map[string]*list.Element
   603  	q        *list.List
   604  	capacity int
   605  }
   606  
   607  type lruSessionCacheEntry struct {
   608  	sessionKey string
   609  	state      *ClientSessionState
   610  }
   611  
   612  // NewLRUClientSessionCache returns a ClientSessionCache with the given
   613  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
   614  // is used instead.
   615  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
   616  	const defaultSessionCacheCapacity = 64
   617  
   618  	if capacity < 1 {
   619  		capacity = defaultSessionCacheCapacity
   620  	}
   621  	return &lruSessionCache{
   622  		m:        make(map[string]*list.Element),
   623  		q:        list.New(),
   624  		capacity: capacity,
   625  	}
   626  }
   627  
   628  // Put adds the provided (sessionKey, cs) pair to the cache.
   629  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
   630  	c.Lock()
   631  	defer c.Unlock()
   632  
   633  	if elem, ok := c.m[sessionKey]; ok {
   634  		entry := elem.Value.(*lruSessionCacheEntry)
   635  		entry.state = cs
   636  		c.q.MoveToFront(elem)
   637  		return
   638  	}
   639  
   640  	if c.q.Len() < c.capacity {
   641  		entry := &lruSessionCacheEntry{sessionKey, cs}
   642  		c.m[sessionKey] = c.q.PushFront(entry)
   643  		return
   644  	}
   645  
   646  	elem := c.q.Back()
   647  	entry := elem.Value.(*lruSessionCacheEntry)
   648  	delete(c.m, entry.sessionKey)
   649  	entry.sessionKey = sessionKey
   650  	entry.state = cs
   651  	c.q.MoveToFront(elem)
   652  	c.m[sessionKey] = elem
   653  }
   654  
   655  // Get returns the ClientSessionState value associated with a given key. It
   656  // returns (nil, false) if no value is found.
   657  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
   658  	c.Lock()
   659  	defer c.Unlock()
   660  
   661  	if elem, ok := c.m[sessionKey]; ok {
   662  		c.q.MoveToFront(elem)
   663  		return elem.Value.(*lruSessionCacheEntry).state, true
   664  	}
   665  	return nil, false
   666  }
   667  
   668  // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
   669  type dsaSignature struct {
   670  	R, S *big.Int
   671  }
   672  
   673  type ecdsaSignature dsaSignature
   674  
   675  var emptyConfig Config
   676  
   677  func defaultConfig() *Config {
   678  	return &emptyConfig
   679  }
   680  
   681  var (
   682  	once                   sync.Once
   683  	varDefaultCipherSuites []uint16
   684  )
   685  
   686  func defaultCipherSuites() []uint16 {
   687  	once.Do(initDefaultCipherSuites)
   688  	return varDefaultCipherSuites
   689  }
   690  
   691  func initDefaultCipherSuites() {
   692  	varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
   693  	for _, suite := range cipherSuites {
   694  		if suite.flags&suiteDefaultOff != 0 {
   695  			continue
   696  		}
   697  		varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
   698  	}
   699  }
   700  
   701  func unexpectedMessageError(wanted, got interface{}) error {
   702  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
   703  }
   704  
   705  func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
   706  	for _, s := range sigHashes {
   707  		if s == sigHash {
   708  			return true
   709  		}
   710  	}
   711  	return false
   712  }