github.com/FenixAra/go@v0.0.0-20170127160404-96ea0918e670/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/internal/cipherhw"
    11  	"crypto/rand"
    12  	"crypto/sha512"
    13  	"crypto/x509"
    14  	"errors"
    15  	"fmt"
    16  	"io"
    17  	"math/big"
    18  	"net"
    19  	"strings"
    20  	"sync"
    21  	"time"
    22  )
    23  
    24  const (
    25  	VersionSSL30 = 0x0300
    26  	VersionTLS10 = 0x0301
    27  	VersionTLS11 = 0x0302
    28  	VersionTLS12 = 0x0303
    29  )
    30  
    31  const (
    32  	maxPlaintext    = 16384        // maximum plaintext payload length
    33  	maxCiphertext   = 16384 + 2048 // maximum ciphertext payload length
    34  	recordHeaderLen = 5            // record header length
    35  	maxHandshake    = 65536        // maximum handshake we support (protocol max is 16 MB)
    36  
    37  	minVersion = VersionTLS10
    38  	maxVersion = VersionTLS12
    39  )
    40  
    41  // TLS record types.
    42  type recordType uint8
    43  
    44  const (
    45  	recordTypeChangeCipherSpec recordType = 20
    46  	recordTypeAlert            recordType = 21
    47  	recordTypeHandshake        recordType = 22
    48  	recordTypeApplicationData  recordType = 23
    49  )
    50  
    51  // TLS handshake message types.
    52  const (
    53  	typeHelloRequest       uint8 = 0
    54  	typeClientHello        uint8 = 1
    55  	typeServerHello        uint8 = 2
    56  	typeNewSessionTicket   uint8 = 4
    57  	typeCertificate        uint8 = 11
    58  	typeServerKeyExchange  uint8 = 12
    59  	typeCertificateRequest uint8 = 13
    60  	typeServerHelloDone    uint8 = 14
    61  	typeCertificateVerify  uint8 = 15
    62  	typeClientKeyExchange  uint8 = 16
    63  	typeFinished           uint8 = 20
    64  	typeCertificateStatus  uint8 = 22
    65  	typeNextProtocol       uint8 = 67 // Not IANA assigned
    66  )
    67  
    68  // TLS compression types.
    69  const (
    70  	compressionNone uint8 = 0
    71  )
    72  
    73  // TLS extension numbers
    74  const (
    75  	extensionServerName          uint16 = 0
    76  	extensionStatusRequest       uint16 = 5
    77  	extensionSupportedCurves     uint16 = 10
    78  	extensionSupportedPoints     uint16 = 11
    79  	extensionSignatureAlgorithms uint16 = 13
    80  	extensionALPN                uint16 = 16
    81  	extensionSCT                 uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6
    82  	extensionSessionTicket       uint16 = 35
    83  	extensionNextProtoNeg        uint16 = 13172 // not IANA assigned
    84  	extensionRenegotiationInfo   uint16 = 0xff01
    85  )
    86  
    87  // TLS signaling cipher suite values
    88  const (
    89  	scsvRenegotiation uint16 = 0x00ff
    90  )
    91  
    92  // CurveID is the type of a TLS identifier for an elliptic curve. See
    93  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
    94  type CurveID uint16
    95  
    96  const (
    97  	CurveP256 CurveID = 23
    98  	CurveP384 CurveID = 24
    99  	CurveP521 CurveID = 25
   100  	X25519    CurveID = 29
   101  )
   102  
   103  // TLS Elliptic Curve Point Formats
   104  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
   105  const (
   106  	pointFormatUncompressed uint8 = 0
   107  )
   108  
   109  // TLS CertificateStatusType (RFC 3546)
   110  const (
   111  	statusTypeOCSP uint8 = 1
   112  )
   113  
   114  // Certificate types (for certificateRequestMsg)
   115  const (
   116  	certTypeRSASign    = 1 // A certificate containing an RSA key
   117  	certTypeDSSSign    = 2 // A certificate containing a DSA key
   118  	certTypeRSAFixedDH = 3 // A certificate containing a static DH key
   119  	certTypeDSSFixedDH = 4 // A certificate containing a static DH key
   120  
   121  	// See RFC 4492 sections 3 and 5.5.
   122  	certTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
   123  	certTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
   124  	certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
   125  
   126  	// Rest of these are reserved by the TLS spec
   127  )
   128  
   129  // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
   130  const (
   131  	hashSHA1   uint8 = 2
   132  	hashSHA256 uint8 = 4
   133  	hashSHA384 uint8 = 5
   134  )
   135  
   136  // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
   137  const (
   138  	signatureRSA   uint8 = 1
   139  	signatureECDSA uint8 = 3
   140  )
   141  
   142  // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
   143  // RFC 5246, section A.4.1.
   144  type signatureAndHash struct {
   145  	hash, signature uint8
   146  }
   147  
   148  // supportedSignatureAlgorithms contains the signature and hash algorithms that
   149  // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2
   150  // CertificateRequest.
   151  var supportedSignatureAlgorithms = []signatureAndHash{
   152  	{hashSHA256, signatureRSA},
   153  	{hashSHA256, signatureECDSA},
   154  	{hashSHA384, signatureRSA},
   155  	{hashSHA384, signatureECDSA},
   156  	{hashSHA1, signatureRSA},
   157  	{hashSHA1, signatureECDSA},
   158  }
   159  
   160  // ConnectionState records basic TLS details about the connection.
   161  type ConnectionState struct {
   162  	Version                     uint16                // TLS version used by the connection (e.g. VersionTLS12)
   163  	HandshakeComplete           bool                  // TLS handshake is complete
   164  	DidResume                   bool                  // connection resumes a previous TLS connection
   165  	CipherSuite                 uint16                // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
   166  	NegotiatedProtocol          string                // negotiated next protocol (from Config.NextProtos)
   167  	NegotiatedProtocolIsMutual  bool                  // negotiated protocol was advertised by server
   168  	ServerName                  string                // server name requested by client, if any (server side only)
   169  	PeerCertificates            []*x509.Certificate   // certificate chain presented by remote peer
   170  	VerifiedChains              [][]*x509.Certificate // verified chains built from PeerCertificates
   171  	SignedCertificateTimestamps [][]byte              // SCTs from the server, if any
   172  	OCSPResponse                []byte                // stapled OCSP response from server, if any
   173  
   174  	// TLSUnique contains the "tls-unique" channel binding value (see RFC
   175  	// 5929, section 3). For resumed sessions this value will be nil
   176  	// because resumption does not include enough context (see
   177  	// https://secure-resumption.com/#channelbindings). This will change in
   178  	// future versions of Go once the TLS master-secret fix has been
   179  	// standardized and implemented.
   180  	TLSUnique []byte
   181  }
   182  
   183  // ClientAuthType declares the policy the server will follow for
   184  // TLS Client Authentication.
   185  type ClientAuthType int
   186  
   187  const (
   188  	NoClientCert ClientAuthType = iota
   189  	RequestClientCert
   190  	RequireAnyClientCert
   191  	VerifyClientCertIfGiven
   192  	RequireAndVerifyClientCert
   193  )
   194  
   195  // ClientSessionState contains the state needed by clients to resume TLS
   196  // sessions.
   197  type ClientSessionState struct {
   198  	sessionTicket      []uint8               // Encrypted ticket used for session resumption with server
   199  	vers               uint16                // SSL/TLS version negotiated for the session
   200  	cipherSuite        uint16                // Ciphersuite negotiated for the session
   201  	masterSecret       []byte                // MasterSecret generated by client on a full handshake
   202  	serverCertificates []*x509.Certificate   // Certificate chain presented by the server
   203  	verifiedChains     [][]*x509.Certificate // Certificate chains we built for verification
   204  }
   205  
   206  // ClientSessionCache is a cache of ClientSessionState objects that can be used
   207  // by a client to resume a TLS session with a given server. ClientSessionCache
   208  // implementations should expect to be called concurrently from different
   209  // goroutines.
   210  type ClientSessionCache interface {
   211  	// Get searches for a ClientSessionState associated with the given key.
   212  	// On return, ok is true if one was found.
   213  	Get(sessionKey string) (session *ClientSessionState, ok bool)
   214  
   215  	// Put adds the ClientSessionState to the cache with the given key.
   216  	Put(sessionKey string, cs *ClientSessionState)
   217  }
   218  
   219  // SignatureScheme identifies a signature algorithm supported by TLS. See
   220  // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3.
   221  type SignatureScheme uint16
   222  
   223  const (
   224  	PKCS1WithSHA1   SignatureScheme = 0x0201
   225  	PKCS1WithSHA256 SignatureScheme = 0x0401
   226  	PKCS1WithSHA384 SignatureScheme = 0x0501
   227  	PKCS1WithSHA512 SignatureScheme = 0x0601
   228  
   229  	PSSWithSHA256 SignatureScheme = 0x0804
   230  	PSSWithSHA384 SignatureScheme = 0x0805
   231  	PSSWithSHA512 SignatureScheme = 0x0806
   232  
   233  	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
   234  	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
   235  	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
   236  )
   237  
   238  // ClientHelloInfo contains information from a ClientHello message in order to
   239  // guide certificate selection in the GetCertificate callback.
   240  type ClientHelloInfo struct {
   241  	// CipherSuites lists the CipherSuites supported by the client (e.g.
   242  	// TLS_RSA_WITH_RC4_128_SHA).
   243  	CipherSuites []uint16
   244  
   245  	// ServerName indicates the name of the server requested by the client
   246  	// in order to support virtual hosting. ServerName is only set if the
   247  	// client is using SNI (see
   248  	// http://tools.ietf.org/html/rfc4366#section-3.1).
   249  	ServerName string
   250  
   251  	// SupportedCurves lists the elliptic curves supported by the client.
   252  	// SupportedCurves is set only if the Supported Elliptic Curves
   253  	// Extension is being used (see
   254  	// http://tools.ietf.org/html/rfc4492#section-5.1.1).
   255  	SupportedCurves []CurveID
   256  
   257  	// SupportedPoints lists the point formats supported by the client.
   258  	// SupportedPoints is set only if the Supported Point Formats Extension
   259  	// is being used (see
   260  	// http://tools.ietf.org/html/rfc4492#section-5.1.2).
   261  	SupportedPoints []uint8
   262  
   263  	// SignatureSchemes lists the signature and hash schemes that the client
   264  	// is willing to verify. SignatureSchemes is set only if the Signature
   265  	// Algorithms Extension is being used (see
   266  	// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1).
   267  	SignatureSchemes []SignatureScheme
   268  
   269  	// SupportedProtos lists the application protocols supported by the client.
   270  	// SupportedProtos is set only if the Application-Layer Protocol
   271  	// Negotiation Extension is being used (see
   272  	// https://tools.ietf.org/html/rfc7301#section-3.1).
   273  	//
   274  	// Servers can select a protocol by setting Config.NextProtos in a
   275  	// GetConfigForClient return value.
   276  	SupportedProtos []string
   277  
   278  	// SupportedVersions lists the TLS versions supported by the client.
   279  	// For TLS versions less than 1.3, this is extrapolated from the max
   280  	// version advertised by the client, so values other than the greatest
   281  	// might be rejected if used.
   282  	SupportedVersions []uint16
   283  
   284  	// Conn is the underlying net.Conn for the connection. Do not read
   285  	// from, or write to, this connection; that will cause the TLS
   286  	// connection to fail.
   287  	Conn net.Conn
   288  }
   289  
   290  // CertificateRequestInfo contains information from a server's
   291  // CertificateRequest message, which is used to demand a certificate and proof
   292  // of control from a client.
   293  type CertificateRequestInfo struct {
   294  	// AcceptableCAs contains zero or more, DER-encoded, X.501
   295  	// Distinguished Names. These are the names of root or intermediate CAs
   296  	// that the server wishes the returned certificate to be signed by. An
   297  	// empty slice indicates that the server has no preference.
   298  	AcceptableCAs [][]byte
   299  
   300  	// SignatureSchemes lists the signature schemes that the server is
   301  	// willing to verify.
   302  	SignatureSchemes []SignatureScheme
   303  }
   304  
   305  // RenegotiationSupport enumerates the different levels of support for TLS
   306  // renegotiation. TLS renegotiation is the act of performing subsequent
   307  // handshakes on a connection after the first. This significantly complicates
   308  // the state machine and has been the source of numerous, subtle security
   309  // issues. Initiating a renegotiation is not supported, but support for
   310  // accepting renegotiation requests may be enabled.
   311  //
   312  // Even when enabled, the server may not change its identity between handshakes
   313  // (i.e. the leaf certificate must be the same). Additionally, concurrent
   314  // handshake and application data flow is not permitted so renegotiation can
   315  // only be used with protocols that synchronise with the renegotiation, such as
   316  // HTTPS.
   317  type RenegotiationSupport int
   318  
   319  const (
   320  	// RenegotiateNever disables renegotiation.
   321  	RenegotiateNever RenegotiationSupport = iota
   322  
   323  	// RenegotiateOnceAsClient allows a remote server to request
   324  	// renegotiation once per connection.
   325  	RenegotiateOnceAsClient
   326  
   327  	// RenegotiateFreelyAsClient allows a remote server to repeatedly
   328  	// request renegotiation.
   329  	RenegotiateFreelyAsClient
   330  )
   331  
   332  // A Config structure is used to configure a TLS client or server.
   333  // After one has been passed to a TLS function it must not be
   334  // modified. A Config may be reused; the tls package will also not
   335  // modify it.
   336  type Config struct {
   337  	// Rand provides the source of entropy for nonces and RSA blinding.
   338  	// If Rand is nil, TLS uses the cryptographic random reader in package
   339  	// crypto/rand.
   340  	// The Reader must be safe for use by multiple goroutines.
   341  	Rand io.Reader
   342  
   343  	// Time returns the current time as the number of seconds since the epoch.
   344  	// If Time is nil, TLS uses time.Now.
   345  	Time func() time.Time
   346  
   347  	// Certificates contains one or more certificate chains to present to
   348  	// the other side of the connection. Server configurations must include
   349  	// at least one certificate or else set GetCertificate. Clients doing
   350  	// client-authentication may set either Certificates or
   351  	// GetClientCertificate.
   352  	Certificates []Certificate
   353  
   354  	// NameToCertificate maps from a certificate name to an element of
   355  	// Certificates. Note that a certificate name can be of the form
   356  	// '*.example.com' and so doesn't have to be a domain name as such.
   357  	// See Config.BuildNameToCertificate
   358  	// The nil value causes the first element of Certificates to be used
   359  	// for all connections.
   360  	NameToCertificate map[string]*Certificate
   361  
   362  	// GetCertificate returns a Certificate based on the given
   363  	// ClientHelloInfo. It will only be called if the client supplies SNI
   364  	// information or if Certificates is empty.
   365  	//
   366  	// If GetCertificate is nil or returns nil, then the certificate is
   367  	// retrieved from NameToCertificate. If NameToCertificate is nil, the
   368  	// first element of Certificates will be used.
   369  	GetCertificate func(*ClientHelloInfo) (*Certificate, error)
   370  
   371  	// GetClientCertificate, if not nil, is called when a server requests a
   372  	// certificate from a client. If set, the contents of Certificates will
   373  	// be ignored.
   374  	//
   375  	// If GetClientCertificate returns an error, the handshake will be
   376  	// aborted and that error will be returned. Otherwise
   377  	// GetClientCertificate must return a non-nil Certificate. If
   378  	// Certificate.Certificate is empty then no certificate will be sent to
   379  	// the server. If this is unacceptable to the server then it may abort
   380  	// the handshake.
   381  	//
   382  	// GetClientCertificate may be called multiple times for the same
   383  	// connection if renegotiation occurs or if TLS 1.3 is in use.
   384  	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
   385  
   386  	// GetConfigForClient, if not nil, is called after a ClientHello is
   387  	// received from a client. It may return a non-nil Config in order to
   388  	// change the Config that will be used to handle this connection. If
   389  	// the returned Config is nil, the original Config will be used. The
   390  	// Config returned by this callback may not be subsequently modified.
   391  	//
   392  	// If GetConfigForClient is nil, the Config passed to Server() will be
   393  	// used for all connections.
   394  	//
   395  	// Uniquely for the fields in the returned Config, session ticket keys
   396  	// will be duplicated from the original Config if not set.
   397  	// Specifically, if SetSessionTicketKeys was called on the original
   398  	// config but not on the returned config then the ticket keys from the
   399  	// original config will be copied into the new config before use.
   400  	// Otherwise, if SessionTicketKey was set in the original config but
   401  	// not in the returned config then it will be copied into the returned
   402  	// config before use. If neither of those cases applies then the key
   403  	// material from the returned config will be used for session tickets.
   404  	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
   405  
   406  	// VerifyPeerCertificate, if not nil, is called after normal
   407  	// certificate verification by either a TLS client or server. It
   408  	// receives the raw ASN.1 certificates provided by the peer and also
   409  	// any verified chains that normal processing found. If it returns a
   410  	// non-nil error, the handshake is aborted and that error results.
   411  	//
   412  	// If normal verification fails then the handshake will abort before
   413  	// considering this callback. If normal verification is disabled by
   414  	// setting InsecureSkipVerify then this callback will be considered but
   415  	// the verifiedChains argument will always be nil.
   416  	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
   417  
   418  	// RootCAs defines the set of root certificate authorities
   419  	// that clients use when verifying server certificates.
   420  	// If RootCAs is nil, TLS uses the host's root CA set.
   421  	RootCAs *x509.CertPool
   422  
   423  	// NextProtos is a list of supported, application level protocols.
   424  	NextProtos []string
   425  
   426  	// ServerName is used to verify the hostname on the returned
   427  	// certificates unless InsecureSkipVerify is given. It is also included
   428  	// in the client's handshake to support virtual hosting unless it is
   429  	// an IP address.
   430  	ServerName string
   431  
   432  	// ClientAuth determines the server's policy for
   433  	// TLS Client Authentication. The default is NoClientCert.
   434  	ClientAuth ClientAuthType
   435  
   436  	// ClientCAs defines the set of root certificate authorities
   437  	// that servers use if required to verify a client certificate
   438  	// by the policy in ClientAuth.
   439  	ClientCAs *x509.CertPool
   440  
   441  	// InsecureSkipVerify controls whether a client verifies the
   442  	// server's certificate chain and host name.
   443  	// If InsecureSkipVerify is true, TLS accepts any certificate
   444  	// presented by the server and any host name in that certificate.
   445  	// In this mode, TLS is susceptible to man-in-the-middle attacks.
   446  	// This should be used only for testing.
   447  	InsecureSkipVerify bool
   448  
   449  	// CipherSuites is a list of supported cipher suites. If CipherSuites
   450  	// is nil, TLS uses a list of suites supported by the implementation.
   451  	CipherSuites []uint16
   452  
   453  	// PreferServerCipherSuites controls whether the server selects the
   454  	// client's most preferred ciphersuite, or the server's most preferred
   455  	// ciphersuite. If true then the server's preference, as expressed in
   456  	// the order of elements in CipherSuites, is used.
   457  	PreferServerCipherSuites bool
   458  
   459  	// SessionTicketsDisabled may be set to true to disable session ticket
   460  	// (resumption) support.
   461  	SessionTicketsDisabled bool
   462  
   463  	// SessionTicketKey is used by TLS servers to provide session
   464  	// resumption. See RFC 5077. If zero, it will be filled with
   465  	// random data before the first server handshake.
   466  	//
   467  	// If multiple servers are terminating connections for the same host
   468  	// they should all have the same SessionTicketKey. If the
   469  	// SessionTicketKey leaks, previously recorded and future TLS
   470  	// connections using that key are compromised.
   471  	SessionTicketKey [32]byte
   472  
   473  	// SessionCache is a cache of ClientSessionState entries for TLS session
   474  	// resumption.
   475  	ClientSessionCache ClientSessionCache
   476  
   477  	// MinVersion contains the minimum SSL/TLS version that is acceptable.
   478  	// If zero, then TLS 1.0 is taken as the minimum.
   479  	MinVersion uint16
   480  
   481  	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
   482  	// If zero, then the maximum version supported by this package is used,
   483  	// which is currently TLS 1.2.
   484  	MaxVersion uint16
   485  
   486  	// CurvePreferences contains the elliptic curves that will be used in
   487  	// an ECDHE handshake, in preference order. If empty, the default will
   488  	// be used.
   489  	CurvePreferences []CurveID
   490  
   491  	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
   492  	// When true, the largest possible TLS record size is always used. When
   493  	// false, the size of TLS records may be adjusted in an attempt to
   494  	// improve latency.
   495  	DynamicRecordSizingDisabled bool
   496  
   497  	// Renegotiation controls what types of renegotiation are supported.
   498  	// The default, none, is correct for the vast majority of applications.
   499  	Renegotiation RenegotiationSupport
   500  
   501  	// KeyLogWriter optionally specifies a destination for TLS master secrets
   502  	// in NSS key log format that can be used to allow external programs
   503  	// such as Wireshark to decrypt TLS connections.
   504  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   505  	// Use of KeyLogWriter compromises security and should only be
   506  	// used for debugging.
   507  	KeyLogWriter io.Writer
   508  
   509  	serverInitOnce sync.Once // guards calling (*Config).serverInit
   510  
   511  	// mutex protects sessionTicketKeys and originalConfig.
   512  	mutex sync.RWMutex
   513  	// sessionTicketKeys contains zero or more ticket keys. If the length
   514  	// is zero, SessionTicketsDisabled must be true. The first key is used
   515  	// for new tickets and any subsequent keys can be used to decrypt old
   516  	// tickets.
   517  	sessionTicketKeys []ticketKey
   518  	// originalConfig is set to the Config that was passed to Server if
   519  	// this Config is returned by a GetConfigForClient callback. It's used
   520  	// by serverInit in order to copy session ticket keys if needed.
   521  	originalConfig *Config
   522  }
   523  
   524  // ticketKeyNameLen is the number of bytes of identifier that is prepended to
   525  // an encrypted session ticket in order to identify the key used to encrypt it.
   526  const ticketKeyNameLen = 16
   527  
   528  // ticketKey is the internal representation of a session ticket key.
   529  type ticketKey struct {
   530  	// keyName is an opaque byte string that serves to identify the session
   531  	// ticket key. It's exposed as plaintext in every session ticket.
   532  	keyName [ticketKeyNameLen]byte
   533  	aesKey  [16]byte
   534  	hmacKey [16]byte
   535  }
   536  
   537  // ticketKeyFromBytes converts from the external representation of a session
   538  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   539  // bytes and this function expands that into sufficient name and key material.
   540  func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   541  	hashed := sha512.Sum512(b[:])
   542  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   543  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   544  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   545  	return key
   546  }
   547  
   548  // Clone returns a shallow clone of c. It is safe to clone a Config that is
   549  // being used concurrently by a TLS client or server.
   550  func (c *Config) Clone() *Config {
   551  	// Running serverInit ensures that it's safe to read
   552  	// SessionTicketsDisabled.
   553  	c.serverInitOnce.Do(c.serverInit)
   554  
   555  	var sessionTicketKeys []ticketKey
   556  	c.mutex.RLock()
   557  	sessionTicketKeys = c.sessionTicketKeys
   558  	c.mutex.RUnlock()
   559  
   560  	return &Config{
   561  		Rand:                        c.Rand,
   562  		Time:                        c.Time,
   563  		Certificates:                c.Certificates,
   564  		NameToCertificate:           c.NameToCertificate,
   565  		GetCertificate:              c.GetCertificate,
   566  		GetConfigForClient:          c.GetConfigForClient,
   567  		VerifyPeerCertificate:       c.VerifyPeerCertificate,
   568  		RootCAs:                     c.RootCAs,
   569  		NextProtos:                  c.NextProtos,
   570  		ServerName:                  c.ServerName,
   571  		ClientAuth:                  c.ClientAuth,
   572  		ClientCAs:                   c.ClientCAs,
   573  		InsecureSkipVerify:          c.InsecureSkipVerify,
   574  		CipherSuites:                c.CipherSuites,
   575  		PreferServerCipherSuites:    c.PreferServerCipherSuites,
   576  		SessionTicketsDisabled:      c.SessionTicketsDisabled,
   577  		SessionTicketKey:            c.SessionTicketKey,
   578  		ClientSessionCache:          c.ClientSessionCache,
   579  		MinVersion:                  c.MinVersion,
   580  		MaxVersion:                  c.MaxVersion,
   581  		CurvePreferences:            c.CurvePreferences,
   582  		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   583  		Renegotiation:               c.Renegotiation,
   584  		KeyLogWriter:                c.KeyLogWriter,
   585  		sessionTicketKeys:           sessionTicketKeys,
   586  		// originalConfig is deliberately not duplicated.
   587  	}
   588  }
   589  
   590  func (c *Config) serverInit() {
   591  	if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
   592  		return
   593  	}
   594  
   595  	var originalConfig *Config
   596  	c.mutex.Lock()
   597  	originalConfig, c.originalConfig = c.originalConfig, nil
   598  	c.mutex.Unlock()
   599  
   600  	alreadySet := false
   601  	for _, b := range c.SessionTicketKey {
   602  		if b != 0 {
   603  			alreadySet = true
   604  			break
   605  		}
   606  	}
   607  
   608  	if !alreadySet {
   609  		if originalConfig != nil {
   610  			copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
   611  		} else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   612  			c.SessionTicketsDisabled = true
   613  			return
   614  		}
   615  	}
   616  
   617  	if originalConfig != nil {
   618  		originalConfig.mutex.RLock()
   619  		c.sessionTicketKeys = originalConfig.sessionTicketKeys
   620  		originalConfig.mutex.RUnlock()
   621  	} else {
   622  		c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
   623  	}
   624  }
   625  
   626  func (c *Config) ticketKeys() []ticketKey {
   627  	c.mutex.RLock()
   628  	// c.sessionTicketKeys is constant once created. SetSessionTicketKeys
   629  	// will only update it by replacing it with a new value.
   630  	ret := c.sessionTicketKeys
   631  	c.mutex.RUnlock()
   632  	return ret
   633  }
   634  
   635  // SetSessionTicketKeys updates the session ticket keys for a server. The first
   636  // key will be used when creating new tickets, while all keys can be used for
   637  // decrypting tickets. It is safe to call this function while the server is
   638  // running in order to rotate the session ticket keys. The function will panic
   639  // if keys is empty.
   640  func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
   641  	if len(keys) == 0 {
   642  		panic("tls: keys must have at least one key")
   643  	}
   644  
   645  	newKeys := make([]ticketKey, len(keys))
   646  	for i, bytes := range keys {
   647  		newKeys[i] = ticketKeyFromBytes(bytes)
   648  	}
   649  
   650  	c.mutex.Lock()
   651  	c.sessionTicketKeys = newKeys
   652  	c.mutex.Unlock()
   653  }
   654  
   655  func (c *Config) rand() io.Reader {
   656  	r := c.Rand
   657  	if r == nil {
   658  		return rand.Reader
   659  	}
   660  	return r
   661  }
   662  
   663  func (c *Config) time() time.Time {
   664  	t := c.Time
   665  	if t == nil {
   666  		t = time.Now
   667  	}
   668  	return t()
   669  }
   670  
   671  func (c *Config) cipherSuites() []uint16 {
   672  	s := c.CipherSuites
   673  	if s == nil {
   674  		s = defaultCipherSuites()
   675  	}
   676  	return s
   677  }
   678  
   679  func (c *Config) minVersion() uint16 {
   680  	if c == nil || c.MinVersion == 0 {
   681  		return minVersion
   682  	}
   683  	return c.MinVersion
   684  }
   685  
   686  func (c *Config) maxVersion() uint16 {
   687  	if c == nil || c.MaxVersion == 0 {
   688  		return maxVersion
   689  	}
   690  	return c.MaxVersion
   691  }
   692  
   693  var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
   694  
   695  func (c *Config) curvePreferences() []CurveID {
   696  	if c == nil || len(c.CurvePreferences) == 0 {
   697  		return defaultCurvePreferences
   698  	}
   699  	return c.CurvePreferences
   700  }
   701  
   702  // mutualVersion returns the protocol version to use given the advertised
   703  // version of the peer.
   704  func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
   705  	minVersion := c.minVersion()
   706  	maxVersion := c.maxVersion()
   707  
   708  	if vers < minVersion {
   709  		return 0, false
   710  	}
   711  	if vers > maxVersion {
   712  		vers = maxVersion
   713  	}
   714  	return vers, true
   715  }
   716  
   717  // getCertificate returns the best certificate for the given ClientHelloInfo,
   718  // defaulting to the first element of c.Certificates.
   719  func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
   720  	if c.GetCertificate != nil &&
   721  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
   722  		cert, err := c.GetCertificate(clientHello)
   723  		if cert != nil || err != nil {
   724  			return cert, err
   725  		}
   726  	}
   727  
   728  	if len(c.Certificates) == 0 {
   729  		return nil, errors.New("tls: no certificates configured")
   730  	}
   731  
   732  	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
   733  		// There's only one choice, so no point doing any work.
   734  		return &c.Certificates[0], nil
   735  	}
   736  
   737  	name := strings.ToLower(clientHello.ServerName)
   738  	for len(name) > 0 && name[len(name)-1] == '.' {
   739  		name = name[:len(name)-1]
   740  	}
   741  
   742  	if cert, ok := c.NameToCertificate[name]; ok {
   743  		return cert, nil
   744  	}
   745  
   746  	// try replacing labels in the name with wildcards until we get a
   747  	// match.
   748  	labels := strings.Split(name, ".")
   749  	for i := range labels {
   750  		labels[i] = "*"
   751  		candidate := strings.Join(labels, ".")
   752  		if cert, ok := c.NameToCertificate[candidate]; ok {
   753  			return cert, nil
   754  		}
   755  	}
   756  
   757  	// If nothing matches, return the first certificate.
   758  	return &c.Certificates[0], nil
   759  }
   760  
   761  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
   762  // from the CommonName and SubjectAlternateName fields of each of the leaf
   763  // certificates.
   764  func (c *Config) BuildNameToCertificate() {
   765  	c.NameToCertificate = make(map[string]*Certificate)
   766  	for i := range c.Certificates {
   767  		cert := &c.Certificates[i]
   768  		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
   769  		if err != nil {
   770  			continue
   771  		}
   772  		if len(x509Cert.Subject.CommonName) > 0 {
   773  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
   774  		}
   775  		for _, san := range x509Cert.DNSNames {
   776  			c.NameToCertificate[san] = cert
   777  		}
   778  	}
   779  }
   780  
   781  // writeKeyLog logs client random and master secret if logging was enabled by
   782  // setting c.KeyLogWriter.
   783  func (c *Config) writeKeyLog(clientRandom, masterSecret []byte) error {
   784  	if c.KeyLogWriter == nil {
   785  		return nil
   786  	}
   787  
   788  	logLine := []byte(fmt.Sprintf("CLIENT_RANDOM %x %x\n", clientRandom, masterSecret))
   789  
   790  	writerMutex.Lock()
   791  	_, err := c.KeyLogWriter.Write(logLine)
   792  	writerMutex.Unlock()
   793  
   794  	return err
   795  }
   796  
   797  // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
   798  // and is only for debugging, so a global mutex saves space.
   799  var writerMutex sync.Mutex
   800  
   801  // A Certificate is a chain of one or more certificates, leaf first.
   802  type Certificate struct {
   803  	Certificate [][]byte
   804  	// PrivateKey contains the private key corresponding to the public key
   805  	// in Leaf. For a server, this must implement crypto.Signer and/or
   806  	// crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
   807  	// (performing client authentication), this must be a crypto.Signer
   808  	// with an RSA or ECDSA PublicKey.
   809  	PrivateKey crypto.PrivateKey
   810  	// OCSPStaple contains an optional OCSP response which will be served
   811  	// to clients that request it.
   812  	OCSPStaple []byte
   813  	// SignedCertificateTimestamps contains an optional list of Signed
   814  	// Certificate Timestamps which will be served to clients that request it.
   815  	SignedCertificateTimestamps [][]byte
   816  	// Leaf is the parsed form of the leaf certificate, which may be
   817  	// initialized using x509.ParseCertificate to reduce per-handshake
   818  	// processing for TLS clients doing client authentication. If nil, the
   819  	// leaf certificate will be parsed as needed.
   820  	Leaf *x509.Certificate
   821  }
   822  
   823  type handshakeMessage interface {
   824  	marshal() []byte
   825  	unmarshal([]byte) bool
   826  }
   827  
   828  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
   829  // caching strategy.
   830  type lruSessionCache struct {
   831  	sync.Mutex
   832  
   833  	m        map[string]*list.Element
   834  	q        *list.List
   835  	capacity int
   836  }
   837  
   838  type lruSessionCacheEntry struct {
   839  	sessionKey string
   840  	state      *ClientSessionState
   841  }
   842  
   843  // NewLRUClientSessionCache returns a ClientSessionCache with the given
   844  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
   845  // is used instead.
   846  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
   847  	const defaultSessionCacheCapacity = 64
   848  
   849  	if capacity < 1 {
   850  		capacity = defaultSessionCacheCapacity
   851  	}
   852  	return &lruSessionCache{
   853  		m:        make(map[string]*list.Element),
   854  		q:        list.New(),
   855  		capacity: capacity,
   856  	}
   857  }
   858  
   859  // Put adds the provided (sessionKey, cs) pair to the cache.
   860  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
   861  	c.Lock()
   862  	defer c.Unlock()
   863  
   864  	if elem, ok := c.m[sessionKey]; ok {
   865  		entry := elem.Value.(*lruSessionCacheEntry)
   866  		entry.state = cs
   867  		c.q.MoveToFront(elem)
   868  		return
   869  	}
   870  
   871  	if c.q.Len() < c.capacity {
   872  		entry := &lruSessionCacheEntry{sessionKey, cs}
   873  		c.m[sessionKey] = c.q.PushFront(entry)
   874  		return
   875  	}
   876  
   877  	elem := c.q.Back()
   878  	entry := elem.Value.(*lruSessionCacheEntry)
   879  	delete(c.m, entry.sessionKey)
   880  	entry.sessionKey = sessionKey
   881  	entry.state = cs
   882  	c.q.MoveToFront(elem)
   883  	c.m[sessionKey] = elem
   884  }
   885  
   886  // Get returns the ClientSessionState value associated with a given key. It
   887  // returns (nil, false) if no value is found.
   888  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
   889  	c.Lock()
   890  	defer c.Unlock()
   891  
   892  	if elem, ok := c.m[sessionKey]; ok {
   893  		c.q.MoveToFront(elem)
   894  		return elem.Value.(*lruSessionCacheEntry).state, true
   895  	}
   896  	return nil, false
   897  }
   898  
   899  // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
   900  type dsaSignature struct {
   901  	R, S *big.Int
   902  }
   903  
   904  type ecdsaSignature dsaSignature
   905  
   906  var emptyConfig Config
   907  
   908  func defaultConfig() *Config {
   909  	return &emptyConfig
   910  }
   911  
   912  var (
   913  	once                   sync.Once
   914  	varDefaultCipherSuites []uint16
   915  )
   916  
   917  func defaultCipherSuites() []uint16 {
   918  	once.Do(initDefaultCipherSuites)
   919  	return varDefaultCipherSuites
   920  }
   921  
   922  func initDefaultCipherSuites() {
   923  	var topCipherSuites []uint16
   924  	if cipherhw.AESGCMSupport() {
   925  		// If AES-GCM hardware is provided then prioritise AES-GCM
   926  		// cipher suites.
   927  		topCipherSuites = []uint16{
   928  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   929  			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
   930  			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
   931  			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
   932  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
   933  			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
   934  		}
   935  	} else {
   936  		// Without AES-GCM hardware, we put the ChaCha20-Poly1305
   937  		// cipher suites first.
   938  		topCipherSuites = []uint16{
   939  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
   940  			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
   941  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   942  			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
   943  			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
   944  			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
   945  		}
   946  	}
   947  
   948  	varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
   949  	for _, topCipher := range topCipherSuites {
   950  		varDefaultCipherSuites = append(varDefaultCipherSuites, topCipher)
   951  	}
   952  
   953  NextCipherSuite:
   954  	for _, suite := range cipherSuites {
   955  		if suite.flags&suiteDefaultOff != 0 {
   956  			continue
   957  		}
   958  		for _, existing := range varDefaultCipherSuites {
   959  			if existing == suite.id {
   960  				continue NextCipherSuite
   961  			}
   962  		}
   963  		varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
   964  	}
   965  }
   966  
   967  func unexpectedMessageError(wanted, got interface{}) error {
   968  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
   969  }
   970  
   971  func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
   972  	for _, s := range sigHashes {
   973  		if s == sigHash {
   974  			return true
   975  		}
   976  	}
   977  	return false
   978  }