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