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