github.com/euank/go@v0.0.0-20160829210321-495514729181/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  	// KeyLogWriter optionally specifies a destination for TLS master secrets
   391  	// in NSS key log format that can be used to allow external programs
   392  	// such as Wireshark to decrypt TLS connections.
   393  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   394  	// Use of KeyLogWriter compromises security and should only be
   395  	// used for debugging.
   396  	KeyLogWriter io.Writer
   397  
   398  	serverInitOnce sync.Once // guards calling (*Config).serverInit
   399  
   400  	// mutex protects sessionTicketKeys
   401  	mutex sync.RWMutex
   402  	// sessionTicketKeys contains zero or more ticket keys. If the length
   403  	// is zero, SessionTicketsDisabled must be true. The first key is used
   404  	// for new tickets and any subsequent keys can be used to decrypt old
   405  	// tickets.
   406  	sessionTicketKeys []ticketKey
   407  }
   408  
   409  // ticketKeyNameLen is the number of bytes of identifier that is prepended to
   410  // an encrypted session ticket in order to identify the key used to encrypt it.
   411  const ticketKeyNameLen = 16
   412  
   413  // ticketKey is the internal representation of a session ticket key.
   414  type ticketKey struct {
   415  	// keyName is an opaque byte string that serves to identify the session
   416  	// ticket key. It's exposed as plaintext in every session ticket.
   417  	keyName [ticketKeyNameLen]byte
   418  	aesKey  [16]byte
   419  	hmacKey [16]byte
   420  }
   421  
   422  // ticketKeyFromBytes converts from the external representation of a session
   423  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   424  // bytes and this function expands that into sufficient name and key material.
   425  func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   426  	hashed := sha512.Sum512(b[:])
   427  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   428  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   429  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   430  	return key
   431  }
   432  
   433  // clone returns a copy of c. Only the exported fields are copied.
   434  func (c *Config) clone() *Config {
   435  	return &Config{
   436  		Rand:                        c.Rand,
   437  		Time:                        c.Time,
   438  		Certificates:                c.Certificates,
   439  		NameToCertificate:           c.NameToCertificate,
   440  		GetCertificate:              c.GetCertificate,
   441  		RootCAs:                     c.RootCAs,
   442  		NextProtos:                  c.NextProtos,
   443  		ServerName:                  c.ServerName,
   444  		ClientAuth:                  c.ClientAuth,
   445  		ClientCAs:                   c.ClientCAs,
   446  		InsecureSkipVerify:          c.InsecureSkipVerify,
   447  		CipherSuites:                c.CipherSuites,
   448  		PreferServerCipherSuites:    c.PreferServerCipherSuites,
   449  		SessionTicketsDisabled:      c.SessionTicketsDisabled,
   450  		SessionTicketKey:            c.SessionTicketKey,
   451  		ClientSessionCache:          c.ClientSessionCache,
   452  		MinVersion:                  c.MinVersion,
   453  		MaxVersion:                  c.MaxVersion,
   454  		CurvePreferences:            c.CurvePreferences,
   455  		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   456  		Renegotiation:               c.Renegotiation,
   457  		KeyLogWriter:                c.KeyLogWriter,
   458  	}
   459  }
   460  
   461  func (c *Config) serverInit() {
   462  	if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
   463  		return
   464  	}
   465  
   466  	alreadySet := false
   467  	for _, b := range c.SessionTicketKey {
   468  		if b != 0 {
   469  			alreadySet = true
   470  			break
   471  		}
   472  	}
   473  
   474  	if !alreadySet {
   475  		if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   476  			c.SessionTicketsDisabled = true
   477  			return
   478  		}
   479  	}
   480  
   481  	c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
   482  }
   483  
   484  func (c *Config) ticketKeys() []ticketKey {
   485  	c.mutex.RLock()
   486  	// c.sessionTicketKeys is constant once created. SetSessionTicketKeys
   487  	// will only update it by replacing it with a new value.
   488  	ret := c.sessionTicketKeys
   489  	c.mutex.RUnlock()
   490  	return ret
   491  }
   492  
   493  // SetSessionTicketKeys updates the session ticket keys for a server. The first
   494  // key will be used when creating new tickets, while all keys can be used for
   495  // decrypting tickets. It is safe to call this function while the server is
   496  // running in order to rotate the session ticket keys. The function will panic
   497  // if keys is empty.
   498  func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
   499  	if len(keys) == 0 {
   500  		panic("tls: keys must have at least one key")
   501  	}
   502  
   503  	newKeys := make([]ticketKey, len(keys))
   504  	for i, bytes := range keys {
   505  		newKeys[i] = ticketKeyFromBytes(bytes)
   506  	}
   507  
   508  	c.mutex.Lock()
   509  	c.sessionTicketKeys = newKeys
   510  	c.mutex.Unlock()
   511  }
   512  
   513  func (c *Config) rand() io.Reader {
   514  	r := c.Rand
   515  	if r == nil {
   516  		return rand.Reader
   517  	}
   518  	return r
   519  }
   520  
   521  func (c *Config) time() time.Time {
   522  	t := c.Time
   523  	if t == nil {
   524  		t = time.Now
   525  	}
   526  	return t()
   527  }
   528  
   529  func (c *Config) cipherSuites() []uint16 {
   530  	s := c.CipherSuites
   531  	if s == nil {
   532  		s = defaultCipherSuites()
   533  	}
   534  	return s
   535  }
   536  
   537  func (c *Config) minVersion() uint16 {
   538  	if c == nil || c.MinVersion == 0 {
   539  		return minVersion
   540  	}
   541  	return c.MinVersion
   542  }
   543  
   544  func (c *Config) maxVersion() uint16 {
   545  	if c == nil || c.MaxVersion == 0 {
   546  		return maxVersion
   547  	}
   548  	return c.MaxVersion
   549  }
   550  
   551  var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
   552  
   553  func (c *Config) curvePreferences() []CurveID {
   554  	if c == nil || len(c.CurvePreferences) == 0 {
   555  		return defaultCurvePreferences
   556  	}
   557  	return c.CurvePreferences
   558  }
   559  
   560  // mutualVersion returns the protocol version to use given the advertised
   561  // version of the peer.
   562  func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
   563  	minVersion := c.minVersion()
   564  	maxVersion := c.maxVersion()
   565  
   566  	if vers < minVersion {
   567  		return 0, false
   568  	}
   569  	if vers > maxVersion {
   570  		vers = maxVersion
   571  	}
   572  	return vers, true
   573  }
   574  
   575  // getCertificate returns the best certificate for the given ClientHelloInfo,
   576  // defaulting to the first element of c.Certificates.
   577  func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
   578  	if c.GetCertificate != nil &&
   579  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
   580  		cert, err := c.GetCertificate(clientHello)
   581  		if cert != nil || err != nil {
   582  			return cert, err
   583  		}
   584  	}
   585  
   586  	if len(c.Certificates) == 0 {
   587  		return nil, errors.New("tls: no certificates configured")
   588  	}
   589  
   590  	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
   591  		// There's only one choice, so no point doing any work.
   592  		return &c.Certificates[0], nil
   593  	}
   594  
   595  	name := strings.ToLower(clientHello.ServerName)
   596  	for len(name) > 0 && name[len(name)-1] == '.' {
   597  		name = name[:len(name)-1]
   598  	}
   599  
   600  	if cert, ok := c.NameToCertificate[name]; ok {
   601  		return cert, nil
   602  	}
   603  
   604  	// try replacing labels in the name with wildcards until we get a
   605  	// match.
   606  	labels := strings.Split(name, ".")
   607  	for i := range labels {
   608  		labels[i] = "*"
   609  		candidate := strings.Join(labels, ".")
   610  		if cert, ok := c.NameToCertificate[candidate]; ok {
   611  			return cert, nil
   612  		}
   613  	}
   614  
   615  	// If nothing matches, return the first certificate.
   616  	return &c.Certificates[0], nil
   617  }
   618  
   619  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
   620  // from the CommonName and SubjectAlternateName fields of each of the leaf
   621  // certificates.
   622  func (c *Config) BuildNameToCertificate() {
   623  	c.NameToCertificate = make(map[string]*Certificate)
   624  	for i := range c.Certificates {
   625  		cert := &c.Certificates[i]
   626  		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
   627  		if err != nil {
   628  			continue
   629  		}
   630  		if len(x509Cert.Subject.CommonName) > 0 {
   631  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
   632  		}
   633  		for _, san := range x509Cert.DNSNames {
   634  			c.NameToCertificate[san] = cert
   635  		}
   636  	}
   637  }
   638  
   639  // writeKeyLog logs client random and master secret if logging enabled
   640  // by setting KeyLogWriter.
   641  func (c *Config) writeKeyLog(clientRandom, masterSecret []byte) error {
   642  	if c.KeyLogWriter == nil {
   643  		return nil
   644  	}
   645  	_, err := fmt.Fprintf(c.KeyLogWriter, "CLIENT_RANDOM %x %x\n", clientRandom, masterSecret)
   646  	return err
   647  }
   648  
   649  // A Certificate is a chain of one or more certificates, leaf first.
   650  type Certificate struct {
   651  	Certificate [][]byte
   652  	// PrivateKey contains the private key corresponding to the public key
   653  	// in Leaf. For a server, this must implement crypto.Signer and/or
   654  	// crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
   655  	// (performing client authentication), this must be a crypto.Signer
   656  	// with an RSA or ECDSA PublicKey.
   657  	PrivateKey crypto.PrivateKey
   658  	// OCSPStaple contains an optional OCSP response which will be served
   659  	// to clients that request it.
   660  	OCSPStaple []byte
   661  	// SignedCertificateTimestamps contains an optional list of Signed
   662  	// Certificate Timestamps which will be served to clients that request it.
   663  	SignedCertificateTimestamps [][]byte
   664  	// Leaf is the parsed form of the leaf certificate, which may be
   665  	// initialized using x509.ParseCertificate to reduce per-handshake
   666  	// processing for TLS clients doing client authentication. If nil, the
   667  	// leaf certificate will be parsed as needed.
   668  	Leaf *x509.Certificate
   669  }
   670  
   671  type handshakeMessage interface {
   672  	marshal() []byte
   673  	unmarshal([]byte) bool
   674  }
   675  
   676  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
   677  // caching strategy.
   678  type lruSessionCache struct {
   679  	sync.Mutex
   680  
   681  	m        map[string]*list.Element
   682  	q        *list.List
   683  	capacity int
   684  }
   685  
   686  type lruSessionCacheEntry struct {
   687  	sessionKey string
   688  	state      *ClientSessionState
   689  }
   690  
   691  // NewLRUClientSessionCache returns a ClientSessionCache with the given
   692  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
   693  // is used instead.
   694  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
   695  	const defaultSessionCacheCapacity = 64
   696  
   697  	if capacity < 1 {
   698  		capacity = defaultSessionCacheCapacity
   699  	}
   700  	return &lruSessionCache{
   701  		m:        make(map[string]*list.Element),
   702  		q:        list.New(),
   703  		capacity: capacity,
   704  	}
   705  }
   706  
   707  // Put adds the provided (sessionKey, cs) pair to the cache.
   708  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
   709  	c.Lock()
   710  	defer c.Unlock()
   711  
   712  	if elem, ok := c.m[sessionKey]; ok {
   713  		entry := elem.Value.(*lruSessionCacheEntry)
   714  		entry.state = cs
   715  		c.q.MoveToFront(elem)
   716  		return
   717  	}
   718  
   719  	if c.q.Len() < c.capacity {
   720  		entry := &lruSessionCacheEntry{sessionKey, cs}
   721  		c.m[sessionKey] = c.q.PushFront(entry)
   722  		return
   723  	}
   724  
   725  	elem := c.q.Back()
   726  	entry := elem.Value.(*lruSessionCacheEntry)
   727  	delete(c.m, entry.sessionKey)
   728  	entry.sessionKey = sessionKey
   729  	entry.state = cs
   730  	c.q.MoveToFront(elem)
   731  	c.m[sessionKey] = elem
   732  }
   733  
   734  // Get returns the ClientSessionState value associated with a given key. It
   735  // returns (nil, false) if no value is found.
   736  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
   737  	c.Lock()
   738  	defer c.Unlock()
   739  
   740  	if elem, ok := c.m[sessionKey]; ok {
   741  		c.q.MoveToFront(elem)
   742  		return elem.Value.(*lruSessionCacheEntry).state, true
   743  	}
   744  	return nil, false
   745  }
   746  
   747  // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
   748  type dsaSignature struct {
   749  	R, S *big.Int
   750  }
   751  
   752  type ecdsaSignature dsaSignature
   753  
   754  var emptyConfig Config
   755  
   756  func defaultConfig() *Config {
   757  	return &emptyConfig
   758  }
   759  
   760  var (
   761  	once                   sync.Once
   762  	varDefaultCipherSuites []uint16
   763  )
   764  
   765  func defaultCipherSuites() []uint16 {
   766  	once.Do(initDefaultCipherSuites)
   767  	return varDefaultCipherSuites
   768  }
   769  
   770  func initDefaultCipherSuites() {
   771  	varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
   772  	for _, suite := range cipherSuites {
   773  		if suite.flags&suiteDefaultOff != 0 {
   774  			continue
   775  		}
   776  		varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
   777  	}
   778  }
   779  
   780  func unexpectedMessageError(wanted, got interface{}) error {
   781  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
   782  }
   783  
   784  func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
   785  	for _, s := range sigHashes {
   786  		if s == sigHash {
   787  			return true
   788  		}
   789  	}
   790  	return false
   791  }