github.com/peggyl/go@v0.0.0-20151008231540-ae315999c2d5/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  	// or else set GetCertificate.
   260  	Certificates []Certificate
   261  
   262  	// NameToCertificate maps from a certificate name to an element of
   263  	// Certificates. Note that a certificate name can be of the form
   264  	// '*.example.com' and so doesn't have to be a domain name as such.
   265  	// See Config.BuildNameToCertificate
   266  	// The nil value causes the first element of Certificates to be used
   267  	// for all connections.
   268  	NameToCertificate map[string]*Certificate
   269  
   270  	// GetCertificate returns a Certificate based on the given
   271  	// ClientHelloInfo. It will only be called if the client supplies SNI
   272  	// information or if Certificates is empty.
   273  	//
   274  	// If GetCertificate is nil or returns nil, then the certificate is
   275  	// retrieved from NameToCertificate. If NameToCertificate is nil, the
   276  	// first element of Certificates will be used.
   277  	GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error)
   278  
   279  	// RootCAs defines the set of root certificate authorities
   280  	// that clients use when verifying server certificates.
   281  	// If RootCAs is nil, TLS uses the host's root CA set.
   282  	RootCAs *x509.CertPool
   283  
   284  	// NextProtos is a list of supported, application level protocols.
   285  	NextProtos []string
   286  
   287  	// ServerName is used to verify the hostname on the returned
   288  	// certificates unless InsecureSkipVerify is given. It is also included
   289  	// in the client's handshake to support virtual hosting.
   290  	ServerName string
   291  
   292  	// ClientAuth determines the server's policy for
   293  	// TLS Client Authentication. The default is NoClientCert.
   294  	ClientAuth ClientAuthType
   295  
   296  	// ClientCAs defines the set of root certificate authorities
   297  	// that servers use if required to verify a client certificate
   298  	// by the policy in ClientAuth.
   299  	ClientCAs *x509.CertPool
   300  
   301  	// InsecureSkipVerify controls whether a client verifies the
   302  	// server's certificate chain and host name.
   303  	// If InsecureSkipVerify is true, TLS accepts any certificate
   304  	// presented by the server and any host name in that certificate.
   305  	// In this mode, TLS is susceptible to man-in-the-middle attacks.
   306  	// This should be used only for testing.
   307  	InsecureSkipVerify bool
   308  
   309  	// CipherSuites is a list of supported cipher suites. If CipherSuites
   310  	// is nil, TLS uses a list of suites supported by the implementation.
   311  	CipherSuites []uint16
   312  
   313  	// PreferServerCipherSuites controls whether the server selects the
   314  	// client's most preferred ciphersuite, or the server's most preferred
   315  	// ciphersuite. If true then the server's preference, as expressed in
   316  	// the order of elements in CipherSuites, is used.
   317  	PreferServerCipherSuites bool
   318  
   319  	// SessionTicketsDisabled may be set to true to disable session ticket
   320  	// (resumption) support.
   321  	SessionTicketsDisabled bool
   322  
   323  	// SessionTicketKey is used by TLS servers to provide session
   324  	// resumption. See RFC 5077. If zero, it will be filled with
   325  	// random data before the first server handshake.
   326  	//
   327  	// If multiple servers are terminating connections for the same host
   328  	// they should all have the same SessionTicketKey. If the
   329  	// SessionTicketKey leaks, previously recorded and future TLS
   330  	// connections using that key are compromised.
   331  	SessionTicketKey [32]byte
   332  
   333  	// SessionCache is a cache of ClientSessionState entries for TLS session
   334  	// resumption.
   335  	ClientSessionCache ClientSessionCache
   336  
   337  	// MinVersion contains the minimum SSL/TLS version that is acceptable.
   338  	// If zero, then TLS 1.0 is taken as the minimum.
   339  	MinVersion uint16
   340  
   341  	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
   342  	// If zero, then the maximum version supported by this package is used,
   343  	// which is currently TLS 1.2.
   344  	MaxVersion uint16
   345  
   346  	// CurvePreferences contains the elliptic curves that will be used in
   347  	// an ECDHE handshake, in preference order. If empty, the default will
   348  	// be used.
   349  	CurvePreferences []CurveID
   350  
   351  	serverInitOnce sync.Once // guards calling (*Config).serverInit
   352  
   353  	// mutex protects sessionTicketKeys
   354  	mutex sync.RWMutex
   355  	// sessionTicketKeys contains zero or more ticket keys. If the length
   356  	// is zero, SessionTicketsDisabled must be true. The first key is used
   357  	// for new tickets and any subsequent keys can be used to decrypt old
   358  	// tickets.
   359  	sessionTicketKeys []ticketKey
   360  }
   361  
   362  // ticketKeyNameLen is the number of bytes of identifier that is prepended to
   363  // an encrypted session ticket in order to identify the key used to encrypt it.
   364  const ticketKeyNameLen = 16
   365  
   366  // ticketKey is the internal representation of a session ticket key.
   367  type ticketKey struct {
   368  	// keyName is an opaque byte string that serves to identify the session
   369  	// ticket key. It's exposed as plaintext in every session ticket.
   370  	keyName [ticketKeyNameLen]byte
   371  	aesKey  [16]byte
   372  	hmacKey [16]byte
   373  }
   374  
   375  // ticketKeyFromBytes converts from the external representation of a session
   376  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   377  // bytes and this function expands that into sufficient name and key material.
   378  func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   379  	hashed := sha512.Sum512(b[:])
   380  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   381  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   382  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   383  	return key
   384  }
   385  
   386  func (c *Config) serverInit() {
   387  	if c.SessionTicketsDisabled {
   388  		return
   389  	}
   390  
   391  	alreadySet := false
   392  	for _, b := range c.SessionTicketKey {
   393  		if b != 0 {
   394  			alreadySet = true
   395  			break
   396  		}
   397  	}
   398  
   399  	if !alreadySet {
   400  		if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   401  			c.SessionTicketsDisabled = true
   402  			return
   403  		}
   404  	}
   405  
   406  	c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
   407  }
   408  
   409  func (c *Config) ticketKeys() []ticketKey {
   410  	c.mutex.RLock()
   411  	// c.sessionTicketKeys is constant once created. SetSessionTicketKeys
   412  	// will only update it by replacing it with a new value.
   413  	ret := c.sessionTicketKeys
   414  	c.mutex.RUnlock()
   415  	return ret
   416  }
   417  
   418  // SetSessionTicketKeys updates the session ticket keys for a server. The first
   419  // key will be used when creating new tickets, while all keys can be used for
   420  // decrypting tickets. It is safe to call this function while the server is
   421  // running in order to rotate the session ticket keys. The function will panic
   422  // if keys is empty.
   423  func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
   424  	if len(keys) == 0 {
   425  		panic("tls: keys must have at least one key")
   426  	}
   427  
   428  	newKeys := make([]ticketKey, len(keys))
   429  	for i, bytes := range keys {
   430  		newKeys[i] = ticketKeyFromBytes(bytes)
   431  	}
   432  
   433  	c.mutex.Lock()
   434  	c.sessionTicketKeys = newKeys
   435  	c.mutex.Unlock()
   436  }
   437  
   438  func (c *Config) rand() io.Reader {
   439  	r := c.Rand
   440  	if r == nil {
   441  		return rand.Reader
   442  	}
   443  	return r
   444  }
   445  
   446  func (c *Config) time() time.Time {
   447  	t := c.Time
   448  	if t == nil {
   449  		t = time.Now
   450  	}
   451  	return t()
   452  }
   453  
   454  func (c *Config) cipherSuites() []uint16 {
   455  	s := c.CipherSuites
   456  	if s == nil {
   457  		s = defaultCipherSuites()
   458  	}
   459  	return s
   460  }
   461  
   462  func (c *Config) minVersion() uint16 {
   463  	if c == nil || c.MinVersion == 0 {
   464  		return minVersion
   465  	}
   466  	return c.MinVersion
   467  }
   468  
   469  func (c *Config) maxVersion() uint16 {
   470  	if c == nil || c.MaxVersion == 0 {
   471  		return maxVersion
   472  	}
   473  	return c.MaxVersion
   474  }
   475  
   476  var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
   477  
   478  func (c *Config) curvePreferences() []CurveID {
   479  	if c == nil || len(c.CurvePreferences) == 0 {
   480  		return defaultCurvePreferences
   481  	}
   482  	return c.CurvePreferences
   483  }
   484  
   485  // mutualVersion returns the protocol version to use given the advertised
   486  // version of the peer.
   487  func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
   488  	minVersion := c.minVersion()
   489  	maxVersion := c.maxVersion()
   490  
   491  	if vers < minVersion {
   492  		return 0, false
   493  	}
   494  	if vers > maxVersion {
   495  		vers = maxVersion
   496  	}
   497  	return vers, true
   498  }
   499  
   500  // getCertificate returns the best certificate for the given ClientHelloInfo,
   501  // defaulting to the first element of c.Certificates.
   502  func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
   503  	if c.GetCertificate != nil &&
   504  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
   505  		cert, err := c.GetCertificate(clientHello)
   506  		if cert != nil || err != nil {
   507  			return cert, err
   508  		}
   509  	}
   510  
   511  	if len(c.Certificates) == 0 {
   512  		return nil, errors.New("crypto/tls: no certificates configured")
   513  	}
   514  
   515  	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
   516  		// There's only one choice, so no point doing any work.
   517  		return &c.Certificates[0], nil
   518  	}
   519  
   520  	name := strings.ToLower(clientHello.ServerName)
   521  	for len(name) > 0 && name[len(name)-1] == '.' {
   522  		name = name[:len(name)-1]
   523  	}
   524  
   525  	if cert, ok := c.NameToCertificate[name]; ok {
   526  		return cert, nil
   527  	}
   528  
   529  	// try replacing labels in the name with wildcards until we get a
   530  	// match.
   531  	labels := strings.Split(name, ".")
   532  	for i := range labels {
   533  		labels[i] = "*"
   534  		candidate := strings.Join(labels, ".")
   535  		if cert, ok := c.NameToCertificate[candidate]; ok {
   536  			return cert, nil
   537  		}
   538  	}
   539  
   540  	// If nothing matches, return the first certificate.
   541  	return &c.Certificates[0], nil
   542  }
   543  
   544  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
   545  // from the CommonName and SubjectAlternateName fields of each of the leaf
   546  // certificates.
   547  func (c *Config) BuildNameToCertificate() {
   548  	c.NameToCertificate = make(map[string]*Certificate)
   549  	for i := range c.Certificates {
   550  		cert := &c.Certificates[i]
   551  		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
   552  		if err != nil {
   553  			continue
   554  		}
   555  		if len(x509Cert.Subject.CommonName) > 0 {
   556  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
   557  		}
   558  		for _, san := range x509Cert.DNSNames {
   559  			c.NameToCertificate[san] = cert
   560  		}
   561  	}
   562  }
   563  
   564  // A Certificate is a chain of one or more certificates, leaf first.
   565  type Certificate struct {
   566  	Certificate [][]byte
   567  	// PrivateKey contains the private key corresponding to the public key
   568  	// in Leaf. For a server, this must implement crypto.Signer and/or
   569  	// crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
   570  	// (performing client authentication), this must be a crypto.Signer
   571  	// with an RSA or ECDSA PublicKey.
   572  	PrivateKey crypto.PrivateKey
   573  	// OCSPStaple contains an optional OCSP response which will be served
   574  	// to clients that request it.
   575  	OCSPStaple []byte
   576  	// SignedCertificateTimestamps contains an optional list of Signed
   577  	// Certificate Timestamps which will be served to clients that request it.
   578  	SignedCertificateTimestamps [][]byte
   579  	// Leaf is the parsed form of the leaf certificate, which may be
   580  	// initialized using x509.ParseCertificate to reduce per-handshake
   581  	// processing for TLS clients doing client authentication. If nil, the
   582  	// leaf certificate will be parsed as needed.
   583  	Leaf *x509.Certificate
   584  }
   585  
   586  // A TLS record.
   587  type record struct {
   588  	contentType  recordType
   589  	major, minor uint8
   590  	payload      []byte
   591  }
   592  
   593  type handshakeMessage interface {
   594  	marshal() []byte
   595  	unmarshal([]byte) bool
   596  }
   597  
   598  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
   599  // caching strategy.
   600  type lruSessionCache struct {
   601  	sync.Mutex
   602  
   603  	m        map[string]*list.Element
   604  	q        *list.List
   605  	capacity int
   606  }
   607  
   608  type lruSessionCacheEntry struct {
   609  	sessionKey string
   610  	state      *ClientSessionState
   611  }
   612  
   613  // NewLRUClientSessionCache returns a ClientSessionCache with the given
   614  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
   615  // is used instead.
   616  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
   617  	const defaultSessionCacheCapacity = 64
   618  
   619  	if capacity < 1 {
   620  		capacity = defaultSessionCacheCapacity
   621  	}
   622  	return &lruSessionCache{
   623  		m:        make(map[string]*list.Element),
   624  		q:        list.New(),
   625  		capacity: capacity,
   626  	}
   627  }
   628  
   629  // Put adds the provided (sessionKey, cs) pair to the cache.
   630  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
   631  	c.Lock()
   632  	defer c.Unlock()
   633  
   634  	if elem, ok := c.m[sessionKey]; ok {
   635  		entry := elem.Value.(*lruSessionCacheEntry)
   636  		entry.state = cs
   637  		c.q.MoveToFront(elem)
   638  		return
   639  	}
   640  
   641  	if c.q.Len() < c.capacity {
   642  		entry := &lruSessionCacheEntry{sessionKey, cs}
   643  		c.m[sessionKey] = c.q.PushFront(entry)
   644  		return
   645  	}
   646  
   647  	elem := c.q.Back()
   648  	entry := elem.Value.(*lruSessionCacheEntry)
   649  	delete(c.m, entry.sessionKey)
   650  	entry.sessionKey = sessionKey
   651  	entry.state = cs
   652  	c.q.MoveToFront(elem)
   653  	c.m[sessionKey] = elem
   654  }
   655  
   656  // Get returns the ClientSessionState value associated with a given key. It
   657  // returns (nil, false) if no value is found.
   658  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
   659  	c.Lock()
   660  	defer c.Unlock()
   661  
   662  	if elem, ok := c.m[sessionKey]; ok {
   663  		c.q.MoveToFront(elem)
   664  		return elem.Value.(*lruSessionCacheEntry).state, true
   665  	}
   666  	return nil, false
   667  }
   668  
   669  // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
   670  type dsaSignature struct {
   671  	R, S *big.Int
   672  }
   673  
   674  type ecdsaSignature dsaSignature
   675  
   676  var emptyConfig Config
   677  
   678  func defaultConfig() *Config {
   679  	return &emptyConfig
   680  }
   681  
   682  var (
   683  	once                   sync.Once
   684  	varDefaultCipherSuites []uint16
   685  )
   686  
   687  func defaultCipherSuites() []uint16 {
   688  	once.Do(initDefaultCipherSuites)
   689  	return varDefaultCipherSuites
   690  }
   691  
   692  func initDefaultCipherSuites() {
   693  	varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
   694  	for _, suite := range cipherSuites {
   695  		if suite.flags&suiteDefaultOff != 0 {
   696  			continue
   697  		}
   698  		varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
   699  	}
   700  }
   701  
   702  func unexpectedMessageError(wanted, got interface{}) error {
   703  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
   704  }
   705  
   706  func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
   707  	for _, s := range sigHashes {
   708  		if s == sigHash {
   709  			return true
   710  		}
   711  	}
   712  	return false
   713  }