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