github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/crypto/tls/common.go (about)

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