src/pkg/crypto/tls/common.go - The Go Programming Language

Golang

Source file src/pkg/crypto/tls/common.go

     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		"strings"
    13		"sync"
    14		"time"
    15	)
    16	
    17	const (
    18		maxPlaintext    = 16384        // maximum plaintext payload length
    19		maxCiphertext   = 16384 + 2048 // maximum ciphertext payload length
    20		recordHeaderLen = 5            // record header length
    21		maxHandshake    = 65536        // maximum handshake we support (protocol max is 16 MB)
    22	
    23		versionSSL30 = 0x0300
    24		versionTLS10 = 0x0301
    25	
    26		minVersion = versionSSL30
    27		maxVersion = versionTLS10
    28	)
    29	
    30	// TLS record types.
    31	type recordType uint8
    32	
    33	const (
    34		recordTypeChangeCipherSpec recordType = 20
    35		recordTypeAlert            recordType = 21
    36		recordTypeHandshake        recordType = 22
    37		recordTypeApplicationData  recordType = 23
    38	)
    39	
    40	// TLS handshake message types.
    41	const (
    42		typeClientHello        uint8 = 1
    43		typeServerHello        uint8 = 2
    44		typeCertificate        uint8 = 11
    45		typeServerKeyExchange  uint8 = 12
    46		typeCertificateRequest uint8 = 13
    47		typeServerHelloDone    uint8 = 14
    48		typeCertificateVerify  uint8 = 15
    49		typeClientKeyExchange  uint8 = 16
    50		typeFinished           uint8 = 20
    51		typeCertificateStatus  uint8 = 22
    52		typeNextProtocol       uint8 = 67 // Not IANA assigned
    53	)
    54	
    55	// TLS compression types.
    56	const (
    57		compressionNone uint8 = 0
    58	)
    59	
    60	// TLS extension numbers
    61	var (
    62		extensionServerName      uint16 = 0
    63		extensionStatusRequest   uint16 = 5
    64		extensionSupportedCurves uint16 = 10
    65		extensionSupportedPoints uint16 = 11
    66		extensionNextProtoNeg    uint16 = 13172 // not IANA assigned
    67	)
    68	
    69	// TLS Elliptic Curves
    70	// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
    71	var (
    72		curveP256 uint16 = 23
    73		curveP384 uint16 = 24
    74		curveP521 uint16 = 25
    75	)
    76	
    77	// TLS Elliptic Curve Point Formats
    78	// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
    79	var (
    80		pointFormatUncompressed uint8 = 0
    81	)
    82	
    83	// TLS CertificateStatusType (RFC 3546)
    84	const (
    85		statusTypeOCSP uint8 = 1
    86	)
    87	
    88	// Certificate types (for certificateRequestMsg)
    89	const (
    90		certTypeRSASign    = 1 // A certificate containing an RSA key
    91		certTypeDSSSign    = 2 // A certificate containing a DSA key
    92		certTypeRSAFixedDH = 3 // A certificate containing a static DH key
    93		certTypeDSSFixedDH = 4 // A certificate containing a static DH key
    94		// Rest of these are reserved by the TLS spec
    95	)
    96	
    97	// ConnectionState records basic TLS details about the connection.
    98	type ConnectionState struct {
    99		HandshakeComplete          bool
   100		CipherSuite                uint16
   101		NegotiatedProtocol         string
   102		NegotiatedProtocolIsMutual bool
   103	
   104		// ServerName contains the server name indicated by the client, if any.
   105		// (Only valid for server connections.)
   106		ServerName string
   107	
   108		// the certificate chain that was presented by the other side
   109		PeerCertificates []*x509.Certificate
   110		// the verified certificate chains built from PeerCertificates.
   111		VerifiedChains [][]*x509.Certificate
   112	}
   113	
   114	// ClientAuthType declares the policy the server will follow for
   115	// TLS Client Authentication.
   116	type ClientAuthType int
   117	
   118	const (
   119		NoClientCert ClientAuthType = iota
   120		RequestClientCert
   121		RequireAnyClientCert
   122		VerifyClientCertIfGiven
   123		RequireAndVerifyClientCert
   124	)
   125	
   126	// A Config structure is used to configure a TLS client or server. After one
   127	// has been passed to a TLS function it must not be modified.
   128	type Config struct {
   129		// Rand provides the source of entropy for nonces and RSA blinding.
   130		// If Rand is nil, TLS uses the cryptographic random reader in package
   131		// crypto/rand.
   132		Rand io.Reader
   133	
   134		// Time returns the current time as the number of seconds since the epoch.
   135		// If Time is nil, TLS uses time.Now.
   136		Time func() time.Time
   137	
   138		// Certificates contains one or more certificate chains
   139		// to present to the other side of the connection.
   140		// Server configurations must include at least one certificate.
   141		Certificates []Certificate
   142	
   143		// NameToCertificate maps from a certificate name to an element of
   144		// Certificates. Note that a certificate name can be of the form
   145		// '*.example.com' and so doesn't have to be a domain name as such.
   146		// See Config.BuildNameToCertificate
   147		// The nil value causes the first element of Certificates to be used
   148		// for all connections.
   149		NameToCertificate map[string]*Certificate
   150	
   151		// RootCAs defines the set of root certificate authorities
   152		// that clients use when verifying server certificates.
   153		// If RootCAs is nil, TLS uses the host's root CA set.
   154		RootCAs *x509.CertPool
   155	
   156		// NextProtos is a list of supported, application level protocols.
   157		NextProtos []string
   158	
   159		// ServerName is included in the client's handshake to support virtual
   160		// hosting.
   161		ServerName string
   162	
   163		// ClientAuth determines the server's policy for
   164		// TLS Client Authentication. The default is NoClientCert.
   165		ClientAuth ClientAuthType
   166	
   167		// ClientCAs defines the set of root certificate authorities
   168		// that servers use if required to verify a client certificate
   169		// by the policy in ClientAuth.
   170		ClientCAs *x509.CertPool
   171	
   172		// InsecureSkipVerify controls whether a client verifies the
   173		// server's certificate chain and host name.
   174		// If InsecureSkipVerify is true, TLS accepts any certificate
   175		// presented by the server and any host name in that certificate.
   176		// In this mode, TLS is susceptible to man-in-the-middle attacks.
   177		// This should be used only for testing.
   178		InsecureSkipVerify bool
   179	
   180		// CipherSuites is a list of supported cipher suites. If CipherSuites
   181		// is nil, TLS uses a list of suites supported by the implementation.
   182		CipherSuites []uint16
   183	}
   184	
   185	func (c *Config) rand() io.Reader {
   186		r := c.Rand
   187		if r == nil {
   188			return rand.Reader
   189		}
   190		return r
   191	}
   192	
   193	func (c *Config) time() time.Time {
   194		t := c.Time
   195		if t == nil {
   196			t = time.Now
   197		}
   198		return t()
   199	}
   200	
   201	func (c *Config) cipherSuites() []uint16 {
   202		s := c.CipherSuites
   203		if s == nil {
   204			s = defaultCipherSuites()
   205		}
   206		return s
   207	}
   208	
   209	// getCertificateForName returns the best certificate for the given name,
   210	// defaulting to the first element of c.Certificates if there are no good
   211	// options.
   212	func (c *Config) getCertificateForName(name string) *Certificate {
   213		if len(c.Certificates) == 1 || c.NameToCertificate == nil {
   214			// There's only one choice, so no point doing any work.
   215			return &c.Certificates[0]
   216		}
   217	
   218		name = strings.ToLower(name)
   219		for len(name) > 0 && name[len(name)-1] == '.' {
   220			name = name[:len(name)-1]
   221		}
   222	
   223		if cert, ok := c.NameToCertificate[name]; ok {
   224			return cert
   225		}
   226	
   227		// try replacing labels in the name with wildcards until we get a
   228		// match.
   229		labels := strings.Split(name, ".")
   230		for i := range labels {
   231			labels[i] = "*"
   232			candidate := strings.Join(labels, ".")
   233			if cert, ok := c.NameToCertificate[candidate]; ok {
   234				return cert
   235			}
   236		}
   237	
   238		// If nothing matches, return the first certificate.
   239		return &c.Certificates[0]
   240	}
   241	
   242	// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
   243	// from the CommonName and SubjectAlternateName fields of each of the leaf
   244	// certificates.
   245	func (c *Config) BuildNameToCertificate() {
   246		c.NameToCertificate = make(map[string]*Certificate)
   247		for i := range c.Certificates {
   248			cert := &c.Certificates[i]
   249			x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
   250			if err != nil {
   251				continue
   252			}
   253			if len(x509Cert.Subject.CommonName) > 0 {
   254				c.NameToCertificate[x509Cert.Subject.CommonName] = cert
   255			}
   256			for _, san := range x509Cert.DNSNames {
   257				c.NameToCertificate[san] = cert
   258			}
   259		}
   260	}
   261	
   262	// A Certificate is a chain of one or more certificates, leaf first.
   263	type Certificate struct {
   264		Certificate [][]byte
   265		PrivateKey  crypto.PrivateKey // supported types: *rsa.PrivateKey
   266		// OCSPStaple contains an optional OCSP response which will be served
   267		// to clients that request it.
   268		OCSPStaple []byte
   269		// Leaf is the parsed form of the leaf certificate, which may be
   270		// initialized using x509.ParseCertificate to reduce per-handshake
   271		// processing for TLS clients doing client authentication. If nil, the
   272		// leaf certificate will be parsed as needed.
   273		Leaf *x509.Certificate
   274	}
   275	
   276	// A TLS record.
   277	type record struct {
   278		contentType  recordType
   279		major, minor uint8
   280		payload      []byte
   281	}
   282	
   283	type handshakeMessage interface {
   284		marshal() []byte
   285		unmarshal([]byte) bool
   286	}
   287	
   288	// mutualVersion returns the protocol version to use given the advertised
   289	// version of the peer.
   290	func mutualVersion(vers uint16) (uint16, bool) {
   291		if vers < minVersion {
   292			return 0, false
   293		}
   294		if vers > maxVersion {
   295			vers = maxVersion
   296		}
   297		return vers, true
   298	}
   299	
   300	var emptyConfig Config
   301	
   302	func defaultConfig() *Config {
   303		return &emptyConfig
   304	}
   305	
   306	var (
   307		once                   sync.Once
   308		varDefaultCipherSuites []uint16
   309	)
   310	
   311	func defaultCipherSuites() []uint16 {
   312		once.Do(initDefaultCipherSuites)
   313		return varDefaultCipherSuites
   314	}
   315	
   316	func initDefaultCipherSuites() {
   317		varDefaultCipherSuites = make([]uint16, len(cipherSuites))
   318		for i, suite := range cipherSuites {
   319			varDefaultCipherSuites[i] = suite.id
   320		}
   321	}