github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/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  	"crypto"
     9  	"crypto/rand"
    10  	"crypto/x509"
    11  	"io"
    12  	"math/big"
    13  	"strings"
    14  	"sync"
    15  	"time"
    16  )
    17  
    18  const (
    19  	VersionSSL30 = 0x0300
    20  	VersionTLS10 = 0x0301
    21  	VersionTLS11 = 0x0302
    22  	VersionTLS12 = 0x0303
    23  )
    24  
    25  const (
    26  	maxPlaintext    = 16384        // maximum plaintext payload length
    27  	maxCiphertext   = 16384 + 2048 // maximum ciphertext payload length
    28  	recordHeaderLen = 5            // record header length
    29  	maxHandshake    = 65536        // maximum handshake we support (protocol max is 16 MB)
    30  
    31  	minVersion = VersionSSL30
    32  	maxVersion = VersionTLS12
    33  )
    34  
    35  // TLS record types.
    36  type recordType uint8
    37  
    38  const (
    39  	recordTypeChangeCipherSpec recordType = 20
    40  	recordTypeAlert            recordType = 21
    41  	recordTypeHandshake        recordType = 22
    42  	recordTypeApplicationData  recordType = 23
    43  )
    44  
    45  // TLS handshake message types.
    46  const (
    47  	typeClientHello        uint8 = 1
    48  	typeServerHello        uint8 = 2
    49  	typeNewSessionTicket   uint8 = 4
    50  	typeCertificate        uint8 = 11
    51  	typeServerKeyExchange  uint8 = 12
    52  	typeCertificateRequest uint8 = 13
    53  	typeServerHelloDone    uint8 = 14
    54  	typeCertificateVerify  uint8 = 15
    55  	typeClientKeyExchange  uint8 = 16
    56  	typeFinished           uint8 = 20
    57  	typeCertificateStatus  uint8 = 22
    58  	typeNextProtocol       uint8 = 67 // Not IANA assigned
    59  )
    60  
    61  // TLS compression types.
    62  const (
    63  	compressionNone uint8 = 0
    64  )
    65  
    66  // TLS extension numbers
    67  var (
    68  	extensionServerName          uint16 = 0
    69  	extensionStatusRequest       uint16 = 5
    70  	extensionSupportedCurves     uint16 = 10
    71  	extensionSupportedPoints     uint16 = 11
    72  	extensionSignatureAlgorithms uint16 = 13
    73  	extensionSessionTicket       uint16 = 35
    74  	extensionNextProtoNeg        uint16 = 13172 // not IANA assigned
    75  )
    76  
    77  // TLS Elliptic Curves
    78  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
    79  var (
    80  	curveP256 uint16 = 23
    81  	curveP384 uint16 = 24
    82  	curveP521 uint16 = 25
    83  )
    84  
    85  // TLS Elliptic Curve Point Formats
    86  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
    87  var (
    88  	pointFormatUncompressed uint8 = 0
    89  )
    90  
    91  // TLS CertificateStatusType (RFC 3546)
    92  const (
    93  	statusTypeOCSP uint8 = 1
    94  )
    95  
    96  // Certificate types (for certificateRequestMsg)
    97  const (
    98  	certTypeRSASign    = 1 // A certificate containing an RSA key
    99  	certTypeDSSSign    = 2 // A certificate containing a DSA key
   100  	certTypeRSAFixedDH = 3 // A certificate containing a static DH key
   101  	certTypeDSSFixedDH = 4 // A certificate containing a static DH key
   102  
   103  	// See RFC4492 sections 3 and 5.5.
   104  	certTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
   105  	certTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
   106  	certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
   107  
   108  	// Rest of these are reserved by the TLS spec
   109  )
   110  
   111  // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
   112  const (
   113  	hashSHA1   uint8 = 2
   114  	hashSHA256 uint8 = 4
   115  )
   116  
   117  // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
   118  const (
   119  	signatureRSA   uint8 = 1
   120  	signatureECDSA uint8 = 3
   121  )
   122  
   123  // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
   124  // RFC 5246, section A.4.1.
   125  type signatureAndHash struct {
   126  	hash, signature uint8
   127  }
   128  
   129  // supportedSignatureAlgorithms contains the signature and hash algorithms that
   130  // the code can advertise as supported both in a TLS 1.2 ClientHello and
   131  // CertificateRequest.
   132  var supportedSignatureAlgorithms = []signatureAndHash{
   133  	{hashSHA256, signatureRSA},
   134  	{hashSHA256, signatureECDSA},
   135  }
   136  
   137  // ConnectionState records basic TLS details about the connection.
   138  type ConnectionState struct {
   139  	HandshakeComplete          bool
   140  	DidResume                  bool
   141  	CipherSuite                uint16
   142  	NegotiatedProtocol         string
   143  	NegotiatedProtocolIsMutual bool
   144  
   145  	// ServerName contains the server name indicated by the client, if any.
   146  	// (Only valid for server connections.)
   147  	ServerName string
   148  
   149  	// the certificate chain that was presented by the other side
   150  	PeerCertificates []*x509.Certificate
   151  	// the verified certificate chains built from PeerCertificates.
   152  	VerifiedChains [][]*x509.Certificate
   153  }
   154  
   155  // ClientAuthType declares the policy the server will follow for
   156  // TLS Client Authentication.
   157  type ClientAuthType int
   158  
   159  const (
   160  	NoClientCert ClientAuthType = iota
   161  	RequestClientCert
   162  	RequireAnyClientCert
   163  	VerifyClientCertIfGiven
   164  	RequireAndVerifyClientCert
   165  )
   166  
   167  // A Config structure is used to configure a TLS client or server. After one
   168  // has been passed to a TLS function it must not be modified.
   169  type Config struct {
   170  	// Rand provides the source of entropy for nonces and RSA blinding.
   171  	// If Rand is nil, TLS uses the cryptographic random reader in package
   172  	// crypto/rand.
   173  	Rand io.Reader
   174  
   175  	// Time returns the current time as the number of seconds since the epoch.
   176  	// If Time is nil, TLS uses time.Now.
   177  	Time func() time.Time
   178  
   179  	// Certificates contains one or more certificate chains
   180  	// to present to the other side of the connection.
   181  	// Server configurations must include at least one certificate.
   182  	Certificates []Certificate
   183  
   184  	// NameToCertificate maps from a certificate name to an element of
   185  	// Certificates. Note that a certificate name can be of the form
   186  	// '*.example.com' and so doesn't have to be a domain name as such.
   187  	// See Config.BuildNameToCertificate
   188  	// The nil value causes the first element of Certificates to be used
   189  	// for all connections.
   190  	NameToCertificate map[string]*Certificate
   191  
   192  	// RootCAs defines the set of root certificate authorities
   193  	// that clients use when verifying server certificates.
   194  	// If RootCAs is nil, TLS uses the host's root CA set.
   195  	RootCAs *x509.CertPool
   196  
   197  	// NextProtos is a list of supported, application level protocols.
   198  	NextProtos []string
   199  
   200  	// ServerName is included in the client's handshake to support virtual
   201  	// hosting.
   202  	ServerName string
   203  
   204  	// ClientAuth determines the server's policy for
   205  	// TLS Client Authentication. The default is NoClientCert.
   206  	ClientAuth ClientAuthType
   207  
   208  	// ClientCAs defines the set of root certificate authorities
   209  	// that servers use if required to verify a client certificate
   210  	// by the policy in ClientAuth.
   211  	ClientCAs *x509.CertPool
   212  
   213  	// InsecureSkipVerify controls whether a client verifies the
   214  	// server's certificate chain and host name.
   215  	// If InsecureSkipVerify is true, TLS accepts any certificate
   216  	// presented by the server and any host name in that certificate.
   217  	// In this mode, TLS is susceptible to man-in-the-middle attacks.
   218  	// This should be used only for testing.
   219  	InsecureSkipVerify bool
   220  
   221  	// CipherSuites is a list of supported cipher suites. If CipherSuites
   222  	// is nil, TLS uses a list of suites supported by the implementation.
   223  	CipherSuites []uint16
   224  
   225  	// PreferServerCipherSuites controls whether the server selects the
   226  	// client's most preferred ciphersuite, or the server's most preferred
   227  	// ciphersuite. If true then the server's preference, as expressed in
   228  	// the order of elements in CipherSuites, is used.
   229  	PreferServerCipherSuites bool
   230  
   231  	// SessionTicketsDisabled may be set to true to disable session ticket
   232  	// (resumption) support.
   233  	SessionTicketsDisabled bool
   234  
   235  	// SessionTicketKey is used by TLS servers to provide session
   236  	// resumption. See RFC 5077. If zero, it will be filled with
   237  	// random data before the first server handshake.
   238  	//
   239  	// If multiple servers are terminating connections for the same host
   240  	// they should all have the same SessionTicketKey. If the
   241  	// SessionTicketKey leaks, previously recorded and future TLS
   242  	// connections using that key are compromised.
   243  	SessionTicketKey [32]byte
   244  
   245  	// MinVersion contains the minimum SSL/TLS version that is acceptable.
   246  	// If zero, then SSLv3 is taken as the minimum.
   247  	MinVersion uint16
   248  
   249  	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
   250  	// If zero, then the maximum version supported by this package is used,
   251  	// which is currently TLS 1.1.
   252  	MaxVersion uint16
   253  
   254  	serverInitOnce sync.Once // guards calling (*Config).serverInit
   255  }
   256  
   257  func (c *Config) serverInit() {
   258  	if c.SessionTicketsDisabled {
   259  		return
   260  	}
   261  
   262  	// If the key has already been set then we have nothing to do.
   263  	for _, b := range c.SessionTicketKey {
   264  		if b != 0 {
   265  			return
   266  		}
   267  	}
   268  
   269  	if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   270  		c.SessionTicketsDisabled = true
   271  	}
   272  }
   273  
   274  func (c *Config) rand() io.Reader {
   275  	r := c.Rand
   276  	if r == nil {
   277  		return rand.Reader
   278  	}
   279  	return r
   280  }
   281  
   282  func (c *Config) time() time.Time {
   283  	t := c.Time
   284  	if t == nil {
   285  		t = time.Now
   286  	}
   287  	return t()
   288  }
   289  
   290  func (c *Config) cipherSuites() []uint16 {
   291  	s := c.CipherSuites
   292  	if s == nil {
   293  		s = defaultCipherSuites()
   294  	}
   295  	return s
   296  }
   297  
   298  func (c *Config) minVersion() uint16 {
   299  	if c == nil || c.MinVersion == 0 {
   300  		return minVersion
   301  	}
   302  	return c.MinVersion
   303  }
   304  
   305  func (c *Config) maxVersion() uint16 {
   306  	if c == nil || c.MaxVersion == 0 {
   307  		return maxVersion
   308  	}
   309  	return c.MaxVersion
   310  }
   311  
   312  // mutualVersion returns the protocol version to use given the advertised
   313  // version of the peer.
   314  func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
   315  	minVersion := c.minVersion()
   316  	maxVersion := c.maxVersion()
   317  
   318  	if vers < minVersion {
   319  		return 0, false
   320  	}
   321  	if vers > maxVersion {
   322  		vers = maxVersion
   323  	}
   324  	return vers, true
   325  }
   326  
   327  // getCertificateForName returns the best certificate for the given name,
   328  // defaulting to the first element of c.Certificates if there are no good
   329  // options.
   330  func (c *Config) getCertificateForName(name string) *Certificate {
   331  	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
   332  		// There's only one choice, so no point doing any work.
   333  		return &c.Certificates[0]
   334  	}
   335  
   336  	name = strings.ToLower(name)
   337  	for len(name) > 0 && name[len(name)-1] == '.' {
   338  		name = name[:len(name)-1]
   339  	}
   340  
   341  	if cert, ok := c.NameToCertificate[name]; ok {
   342  		return cert
   343  	}
   344  
   345  	// try replacing labels in the name with wildcards until we get a
   346  	// match.
   347  	labels := strings.Split(name, ".")
   348  	for i := range labels {
   349  		labels[i] = "*"
   350  		candidate := strings.Join(labels, ".")
   351  		if cert, ok := c.NameToCertificate[candidate]; ok {
   352  			return cert
   353  		}
   354  	}
   355  
   356  	// If nothing matches, return the first certificate.
   357  	return &c.Certificates[0]
   358  }
   359  
   360  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
   361  // from the CommonName and SubjectAlternateName fields of each of the leaf
   362  // certificates.
   363  func (c *Config) BuildNameToCertificate() {
   364  	c.NameToCertificate = make(map[string]*Certificate)
   365  	for i := range c.Certificates {
   366  		cert := &c.Certificates[i]
   367  		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
   368  		if err != nil {
   369  			continue
   370  		}
   371  		if len(x509Cert.Subject.CommonName) > 0 {
   372  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
   373  		}
   374  		for _, san := range x509Cert.DNSNames {
   375  			c.NameToCertificate[san] = cert
   376  		}
   377  	}
   378  }
   379  
   380  // A Certificate is a chain of one or more certificates, leaf first.
   381  type Certificate struct {
   382  	Certificate [][]byte
   383  	PrivateKey  crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
   384  	// OCSPStaple contains an optional OCSP response which will be served
   385  	// to clients that request it.
   386  	OCSPStaple []byte
   387  	// Leaf is the parsed form of the leaf certificate, which may be
   388  	// initialized using x509.ParseCertificate to reduce per-handshake
   389  	// processing for TLS clients doing client authentication. If nil, the
   390  	// leaf certificate will be parsed as needed.
   391  	Leaf *x509.Certificate
   392  }
   393  
   394  // A TLS record.
   395  type record struct {
   396  	contentType  recordType
   397  	major, minor uint8
   398  	payload      []byte
   399  }
   400  
   401  type handshakeMessage interface {
   402  	marshal() []byte
   403  	unmarshal([]byte) bool
   404  }
   405  
   406  // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
   407  type dsaSignature struct {
   408  	R, S *big.Int
   409  }
   410  
   411  type ecdsaSignature dsaSignature
   412  
   413  var emptyConfig Config
   414  
   415  func defaultConfig() *Config {
   416  	return &emptyConfig
   417  }
   418  
   419  var (
   420  	once                   sync.Once
   421  	varDefaultCipherSuites []uint16
   422  )
   423  
   424  func defaultCipherSuites() []uint16 {
   425  	once.Do(initDefaultCipherSuites)
   426  	return varDefaultCipherSuites
   427  }
   428  
   429  func initDefaultCipherSuites() {
   430  	varDefaultCipherSuites = make([]uint16, len(cipherSuites))
   431  	for i, suite := range cipherSuites {
   432  		varDefaultCipherSuites[i] = suite.id
   433  	}
   434  }