github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/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  	"internal/cpu"
    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  	maxWarnAlertCount = 5            // maximum number of consecutive warning alerts
    37  
    38  	minVersion = VersionTLS10
    39  	maxVersion = VersionTLS12
    40  )
    41  
    42  // TLS record types.
    43  type recordType uint8
    44  
    45  const (
    46  	recordTypeChangeCipherSpec recordType = 20
    47  	recordTypeAlert            recordType = 21
    48  	recordTypeHandshake        recordType = 22
    49  	recordTypeApplicationData  recordType = 23
    50  )
    51  
    52  // TLS handshake message types.
    53  const (
    54  	typeHelloRequest       uint8 = 0
    55  	typeClientHello        uint8 = 1
    56  	typeServerHello        uint8 = 2
    57  	typeNewSessionTicket   uint8 = 4
    58  	typeCertificate        uint8 = 11
    59  	typeServerKeyExchange  uint8 = 12
    60  	typeCertificateRequest uint8 = 13
    61  	typeServerHelloDone    uint8 = 14
    62  	typeCertificateVerify  uint8 = 15
    63  	typeClientKeyExchange  uint8 = 16
    64  	typeFinished           uint8 = 20
    65  	typeCertificateStatus  uint8 = 22
    66  	typeNextProtocol       uint8 = 67 // Not IANA assigned
    67  )
    68  
    69  // TLS compression types.
    70  const (
    71  	compressionNone uint8 = 0
    72  )
    73  
    74  // TLS extension numbers
    75  const (
    76  	extensionServerName          uint16 = 0
    77  	extensionStatusRequest       uint16 = 5
    78  	extensionSupportedCurves     uint16 = 10
    79  	extensionSupportedPoints     uint16 = 11
    80  	extensionSignatureAlgorithms uint16 = 13
    81  	extensionALPN                uint16 = 16
    82  	extensionSCT                 uint16 = 18 // RFC 6962, Section 6
    83  	extensionSessionTicket       uint16 = 35
    84  	extensionNextProtoNeg        uint16 = 13172 // not IANA assigned
    85  	extensionRenegotiationInfo   uint16 = 0xff01
    86  )
    87  
    88  // TLS signaling cipher suite values
    89  const (
    90  	scsvRenegotiation uint16 = 0x00ff
    91  )
    92  
    93  // CurveID is the type of a TLS identifier for an elliptic curve. See
    94  // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
    95  type CurveID uint16
    96  
    97  const (
    98  	CurveP256 CurveID = 23
    99  	CurveP384 CurveID = 24
   100  	CurveP521 CurveID = 25
   101  	X25519    CurveID = 29
   102  )
   103  
   104  // TLS Elliptic Curve Point Formats
   105  // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
   106  const (
   107  	pointFormatUncompressed uint8 = 0
   108  )
   109  
   110  // TLS CertificateStatusType (RFC 3546)
   111  const (
   112  	statusTypeOCSP uint8 = 1
   113  )
   114  
   115  // Certificate types (for certificateRequestMsg)
   116  const (
   117  	certTypeRSASign    = 1 // A certificate containing an RSA key
   118  	certTypeDSSSign    = 2 // A certificate containing a DSA key
   119  	certTypeRSAFixedDH = 3 // A certificate containing a static DH key
   120  	certTypeDSSFixedDH = 4 // A certificate containing a static DH key
   121  
   122  	// See RFC 4492 sections 3 and 5.5.
   123  	certTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
   124  	certTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
   125  	certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
   126  
   127  	// Rest of these are reserved by the TLS spec
   128  )
   129  
   130  // Signature algorithms (for internal signaling use). Starting at 16 to avoid overlap with
   131  // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
   132  const (
   133  	signaturePKCS1v15 uint8 = iota + 16
   134  	signatureECDSA
   135  	signatureRSAPSS
   136  )
   137  
   138  // supportedSignatureAlgorithms contains the signature and hash algorithms that
   139  // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2
   140  // CertificateRequest. The two fields are merged to match with TLS 1.3.
   141  // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
   142  var supportedSignatureAlgorithms = []SignatureScheme{
   143  	PKCS1WithSHA256,
   144  	ECDSAWithP256AndSHA256,
   145  	PKCS1WithSHA384,
   146  	ECDSAWithP384AndSHA384,
   147  	PKCS1WithSHA512,
   148  	ECDSAWithP521AndSHA512,
   149  	PKCS1WithSHA1,
   150  	ECDSAWithSHA1,
   151  }
   152  
   153  // ConnectionState records basic TLS details about the connection.
   154  type ConnectionState struct {
   155  	Version                     uint16                // TLS version used by the connection (e.g. VersionTLS12)
   156  	HandshakeComplete           bool                  // TLS handshake is complete
   157  	DidResume                   bool                  // connection resumes a previous TLS connection
   158  	CipherSuite                 uint16                // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
   159  	NegotiatedProtocol          string                // negotiated next protocol (not guaranteed to be from Config.NextProtos)
   160  	NegotiatedProtocolIsMutual  bool                  // negotiated protocol was advertised by server (client side only)
   161  	ServerName                  string                // server name requested by client, if any (server side only)
   162  	PeerCertificates            []*x509.Certificate   // certificate chain presented by remote peer
   163  	VerifiedChains              [][]*x509.Certificate // verified chains built from PeerCertificates
   164  	SignedCertificateTimestamps [][]byte              // SCTs from the server, if any
   165  	OCSPResponse                []byte                // stapled OCSP response from server, if any
   166  
   167  	// ekm is a closure exposed via ExportKeyingMaterial.
   168  	ekm func(label string, context []byte, length int) ([]byte, error)
   169  
   170  	// TLSUnique contains the "tls-unique" channel binding value (see RFC
   171  	// 5929, section 3). For resumed sessions this value will be nil
   172  	// because resumption does not include enough context (see
   173  	// https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
   174  	// change in future versions of Go once the TLS master-secret fix has
   175  	// been standardized and implemented.
   176  	TLSUnique []byte
   177  }
   178  
   179  // ExportKeyingMaterial returns length bytes of exported key material in a new
   180  // slice as defined in RFC 5705. If context is nil, it is not used as part of
   181  // the seed. If the connection was set to allow renegotiation via
   182  // Config.Renegotiation, this function will return an error.
   183  func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
   184  	return cs.ekm(label, context, length)
   185  }
   186  
   187  // ClientAuthType declares the policy the server will follow for
   188  // TLS Client Authentication.
   189  type ClientAuthType int
   190  
   191  const (
   192  	NoClientCert ClientAuthType = iota
   193  	RequestClientCert
   194  	RequireAnyClientCert
   195  	VerifyClientCertIfGiven
   196  	RequireAndVerifyClientCert
   197  )
   198  
   199  // ClientSessionState contains the state needed by clients to resume TLS
   200  // sessions.
   201  type ClientSessionState struct {
   202  	sessionTicket      []uint8               // Encrypted ticket used for session resumption with server
   203  	vers               uint16                // SSL/TLS version negotiated for the session
   204  	cipherSuite        uint16                // Ciphersuite negotiated for the session
   205  	masterSecret       []byte                // MasterSecret generated by client on a full handshake
   206  	serverCertificates []*x509.Certificate   // Certificate chain presented by the server
   207  	verifiedChains     [][]*x509.Certificate // Certificate chains we built for verification
   208  }
   209  
   210  // ClientSessionCache is a cache of ClientSessionState objects that can be used
   211  // by a client to resume a TLS session with a given server. ClientSessionCache
   212  // implementations should expect to be called concurrently from different
   213  // goroutines. Only ticket-based resumption is supported, not SessionID-based
   214  // resumption.
   215  type ClientSessionCache interface {
   216  	// Get searches for a ClientSessionState associated with the given key.
   217  	// On return, ok is true if one was found.
   218  	Get(sessionKey string) (session *ClientSessionState, ok bool)
   219  
   220  	// Put adds the ClientSessionState to the cache with the given key.
   221  	Put(sessionKey string, cs *ClientSessionState)
   222  }
   223  
   224  // SignatureScheme identifies a signature algorithm supported by TLS. See
   225  // RFC 8446, Section 4.2.3.
   226  type SignatureScheme uint16
   227  
   228  const (
   229  	PKCS1WithSHA1   SignatureScheme = 0x0201
   230  	PKCS1WithSHA256 SignatureScheme = 0x0401
   231  	PKCS1WithSHA384 SignatureScheme = 0x0501
   232  	PKCS1WithSHA512 SignatureScheme = 0x0601
   233  
   234  	PSSWithSHA256 SignatureScheme = 0x0804
   235  	PSSWithSHA384 SignatureScheme = 0x0805
   236  	PSSWithSHA512 SignatureScheme = 0x0806
   237  
   238  	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
   239  	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
   240  	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
   241  
   242  	// Legacy signature and hash algorithms for TLS 1.2.
   243  	ECDSAWithSHA1 SignatureScheme = 0x0203
   244  )
   245  
   246  // ClientHelloInfo contains information from a ClientHello message in order to
   247  // guide certificate selection in the GetCertificate callback.
   248  type ClientHelloInfo struct {
   249  	// CipherSuites lists the CipherSuites supported by the client (e.g.
   250  	// TLS_RSA_WITH_RC4_128_SHA).
   251  	CipherSuites []uint16
   252  
   253  	// ServerName indicates the name of the server requested by the client
   254  	// in order to support virtual hosting. ServerName is only set if the
   255  	// client is using SNI (see RFC 4366, Section 3.1).
   256  	ServerName string
   257  
   258  	// SupportedCurves lists the elliptic curves supported by the client.
   259  	// SupportedCurves is set only if the Supported Elliptic Curves
   260  	// Extension is being used (see RFC 4492, Section 5.1.1).
   261  	SupportedCurves []CurveID
   262  
   263  	// SupportedPoints lists the point formats supported by the client.
   264  	// SupportedPoints is set only if the Supported Point Formats Extension
   265  	// is being used (see RFC 4492, Section 5.1.2).
   266  	SupportedPoints []uint8
   267  
   268  	// SignatureSchemes lists the signature and hash schemes that the client
   269  	// is willing to verify. SignatureSchemes is set only if the Signature
   270  	// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
   271  	SignatureSchemes []SignatureScheme
   272  
   273  	// SupportedProtos lists the application protocols supported by the client.
   274  	// SupportedProtos is set only if the Application-Layer Protocol
   275  	// Negotiation Extension is being used (see RFC 7301, Section 3.1).
   276  	//
   277  	// Servers can select a protocol by setting Config.NextProtos in a
   278  	// GetConfigForClient return value.
   279  	SupportedProtos []string
   280  
   281  	// SupportedVersions lists the TLS versions supported by the client.
   282  	// For TLS versions less than 1.3, this is extrapolated from the max
   283  	// version advertised by the client, so values other than the greatest
   284  	// might be rejected if used.
   285  	SupportedVersions []uint16
   286  
   287  	// Conn is the underlying net.Conn for the connection. Do not read
   288  	// from, or write to, this connection; that will cause the TLS
   289  	// connection to fail.
   290  	Conn net.Conn
   291  }
   292  
   293  // CertificateRequestInfo contains information from a server's
   294  // CertificateRequest message, which is used to demand a certificate and proof
   295  // of control from a client.
   296  type CertificateRequestInfo struct {
   297  	// AcceptableCAs contains zero or more, DER-encoded, X.501
   298  	// Distinguished Names. These are the names of root or intermediate CAs
   299  	// that the server wishes the returned certificate to be signed by. An
   300  	// empty slice indicates that the server has no preference.
   301  	AcceptableCAs [][]byte
   302  
   303  	// SignatureSchemes lists the signature schemes that the server is
   304  	// willing to verify.
   305  	SignatureSchemes []SignatureScheme
   306  }
   307  
   308  // RenegotiationSupport enumerates the different levels of support for TLS
   309  // renegotiation. TLS renegotiation is the act of performing subsequent
   310  // handshakes on a connection after the first. This significantly complicates
   311  // the state machine and has been the source of numerous, subtle security
   312  // issues. Initiating a renegotiation is not supported, but support for
   313  // accepting renegotiation requests may be enabled.
   314  //
   315  // Even when enabled, the server may not change its identity between handshakes
   316  // (i.e. the leaf certificate must be the same). Additionally, concurrent
   317  // handshake and application data flow is not permitted so renegotiation can
   318  // only be used with protocols that synchronise with the renegotiation, such as
   319  // HTTPS.
   320  type RenegotiationSupport int
   321  
   322  const (
   323  	// RenegotiateNever disables renegotiation.
   324  	RenegotiateNever RenegotiationSupport = iota
   325  
   326  	// RenegotiateOnceAsClient allows a remote server to request
   327  	// renegotiation once per connection.
   328  	RenegotiateOnceAsClient
   329  
   330  	// RenegotiateFreelyAsClient allows a remote server to repeatedly
   331  	// request renegotiation.
   332  	RenegotiateFreelyAsClient
   333  )
   334  
   335  // A Config structure is used to configure a TLS client or server.
   336  // After one has been passed to a TLS function it must not be
   337  // modified. A Config may be reused; the tls package will also not
   338  // modify it.
   339  type Config struct {
   340  	// Rand provides the source of entropy for nonces and RSA blinding.
   341  	// If Rand is nil, TLS uses the cryptographic random reader in package
   342  	// crypto/rand.
   343  	// The Reader must be safe for use by multiple goroutines.
   344  	Rand io.Reader
   345  
   346  	// Time returns the current time as the number of seconds since the epoch.
   347  	// If Time is nil, TLS uses time.Now.
   348  	Time func() time.Time
   349  
   350  	// Certificates contains one or more certificate chains to present to
   351  	// the other side of the connection. Server configurations must include
   352  	// at least one certificate or else set GetCertificate. Clients doing
   353  	// client-authentication may set either Certificates or
   354  	// GetClientCertificate.
   355  	Certificates []Certificate
   356  
   357  	// NameToCertificate maps from a certificate name to an element of
   358  	// Certificates. Note that a certificate name can be of the form
   359  	// '*.example.com' and so doesn't have to be a domain name as such.
   360  	// See Config.BuildNameToCertificate
   361  	// The nil value causes the first element of Certificates to be used
   362  	// for all connections.
   363  	NameToCertificate map[string]*Certificate
   364  
   365  	// GetCertificate returns a Certificate based on the given
   366  	// ClientHelloInfo. It will only be called if the client supplies SNI
   367  	// information or if Certificates is empty.
   368  	//
   369  	// If GetCertificate is nil or returns nil, then the certificate is
   370  	// retrieved from NameToCertificate. If NameToCertificate is nil, the
   371  	// first element of Certificates will be used.
   372  	GetCertificate func(*ClientHelloInfo) (*Certificate, error)
   373  
   374  	// GetClientCertificate, if not nil, is called when a server requests a
   375  	// certificate from a client. If set, the contents of Certificates will
   376  	// be ignored.
   377  	//
   378  	// If GetClientCertificate returns an error, the handshake will be
   379  	// aborted and that error will be returned. Otherwise
   380  	// GetClientCertificate must return a non-nil Certificate. If
   381  	// Certificate.Certificate is empty then no certificate will be sent to
   382  	// the server. If this is unacceptable to the server then it may abort
   383  	// the handshake.
   384  	//
   385  	// GetClientCertificate may be called multiple times for the same
   386  	// connection if renegotiation occurs or if TLS 1.3 is in use.
   387  	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
   388  
   389  	// GetConfigForClient, if not nil, is called after a ClientHello is
   390  	// received from a client. It may return a non-nil Config in order to
   391  	// change the Config that will be used to handle this connection. If
   392  	// the returned Config is nil, the original Config will be used. The
   393  	// Config returned by this callback may not be subsequently modified.
   394  	//
   395  	// If GetConfigForClient is nil, the Config passed to Server() will be
   396  	// used for all connections.
   397  	//
   398  	// Uniquely for the fields in the returned Config, session ticket keys
   399  	// will be duplicated from the original Config if not set.
   400  	// Specifically, if SetSessionTicketKeys was called on the original
   401  	// config but not on the returned config then the ticket keys from the
   402  	// original config will be copied into the new config before use.
   403  	// Otherwise, if SessionTicketKey was set in the original config but
   404  	// not in the returned config then it will be copied into the returned
   405  	// config before use. If neither of those cases applies then the key
   406  	// material from the returned config will be used for session tickets.
   407  	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
   408  
   409  	// VerifyPeerCertificate, if not nil, is called after normal
   410  	// certificate verification by either a TLS client or server. It
   411  	// receives the raw ASN.1 certificates provided by the peer and also
   412  	// any verified chains that normal processing found. If it returns a
   413  	// non-nil error, the handshake is aborted and that error results.
   414  	//
   415  	// If normal verification fails then the handshake will abort before
   416  	// considering this callback. If normal verification is disabled by
   417  	// setting InsecureSkipVerify, or (for a server) when ClientAuth is
   418  	// RequestClientCert or RequireAnyClientCert, then this callback will
   419  	// be considered but the verifiedChains argument will always be nil.
   420  	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
   421  
   422  	// RootCAs defines the set of root certificate authorities
   423  	// that clients use when verifying server certificates.
   424  	// If RootCAs is nil, TLS uses the host's root CA set.
   425  	RootCAs *x509.CertPool
   426  
   427  	// NextProtos is a list of supported, application level protocols.
   428  	NextProtos []string
   429  
   430  	// ServerName is used to verify the hostname on the returned
   431  	// certificates unless InsecureSkipVerify is given. It is also included
   432  	// in the client's handshake to support virtual hosting unless it is
   433  	// an IP address.
   434  	ServerName string
   435  
   436  	// ClientAuth determines the server's policy for
   437  	// TLS Client Authentication. The default is NoClientCert.
   438  	ClientAuth ClientAuthType
   439  
   440  	// ClientCAs defines the set of root certificate authorities
   441  	// that servers use if required to verify a client certificate
   442  	// by the policy in ClientAuth.
   443  	ClientCAs *x509.CertPool
   444  
   445  	// InsecureSkipVerify controls whether a client verifies the
   446  	// server's certificate chain and host name.
   447  	// If InsecureSkipVerify is true, TLS accepts any certificate
   448  	// presented by the server and any host name in that certificate.
   449  	// In this mode, TLS is susceptible to man-in-the-middle attacks.
   450  	// This should be used only for testing.
   451  	InsecureSkipVerify bool
   452  
   453  	// CipherSuites is a list of supported cipher suites. If CipherSuites
   454  	// is nil, TLS uses a list of suites supported by the implementation.
   455  	CipherSuites []uint16
   456  
   457  	// PreferServerCipherSuites controls whether the server selects the
   458  	// client's most preferred ciphersuite, or the server's most preferred
   459  	// ciphersuite. If true then the server's preference, as expressed in
   460  	// the order of elements in CipherSuites, is used.
   461  	PreferServerCipherSuites bool
   462  
   463  	// SessionTicketsDisabled may be set to true to disable session ticket
   464  	// (resumption) support. Note that on clients, session ticket support is
   465  	// also disabled if ClientSessionCache is nil.
   466  	SessionTicketsDisabled bool
   467  
   468  	// SessionTicketKey is used by TLS servers to provide session
   469  	// resumption. See RFC 5077. If zero, it will be filled with
   470  	// random data before the first server handshake.
   471  	//
   472  	// If multiple servers are terminating connections for the same host
   473  	// they should all have the same SessionTicketKey. If the
   474  	// SessionTicketKey leaks, previously recorded and future TLS
   475  	// connections using that key are compromised.
   476  	SessionTicketKey [32]byte
   477  
   478  	// ClientSessionCache is a cache of ClientSessionState entries for TLS
   479  	// session resumption. It is only used by clients.
   480  	ClientSessionCache ClientSessionCache
   481  
   482  	// MinVersion contains the minimum SSL/TLS version that is acceptable.
   483  	// If zero, then TLS 1.0 is taken as the minimum.
   484  	MinVersion uint16
   485  
   486  	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
   487  	// If zero, then the maximum version supported by this package is used,
   488  	// which is currently TLS 1.2.
   489  	MaxVersion uint16
   490  
   491  	// CurvePreferences contains the elliptic curves that will be used in
   492  	// an ECDHE handshake, in preference order. If empty, the default will
   493  	// be used.
   494  	CurvePreferences []CurveID
   495  
   496  	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
   497  	// When true, the largest possible TLS record size is always used. When
   498  	// false, the size of TLS records may be adjusted in an attempt to
   499  	// improve latency.
   500  	DynamicRecordSizingDisabled bool
   501  
   502  	// Renegotiation controls what types of renegotiation are supported.
   503  	// The default, none, is correct for the vast majority of applications.
   504  	Renegotiation RenegotiationSupport
   505  
   506  	// KeyLogWriter optionally specifies a destination for TLS master secrets
   507  	// in NSS key log format that can be used to allow external programs
   508  	// such as Wireshark to decrypt TLS connections.
   509  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   510  	// Use of KeyLogWriter compromises security and should only be
   511  	// used for debugging.
   512  	KeyLogWriter io.Writer
   513  
   514  	serverInitOnce sync.Once // guards calling (*Config).serverInit
   515  
   516  	// mutex protects sessionTicketKeys.
   517  	mutex sync.RWMutex
   518  	// sessionTicketKeys contains zero or more ticket keys. If the length
   519  	// is zero, SessionTicketsDisabled must be true. The first key is used
   520  	// for new tickets and any subsequent keys can be used to decrypt old
   521  	// tickets.
   522  	sessionTicketKeys []ticketKey
   523  }
   524  
   525  // ticketKeyNameLen is the number of bytes of identifier that is prepended to
   526  // an encrypted session ticket in order to identify the key used to encrypt it.
   527  const ticketKeyNameLen = 16
   528  
   529  // ticketKey is the internal representation of a session ticket key.
   530  type ticketKey struct {
   531  	// keyName is an opaque byte string that serves to identify the session
   532  	// ticket key. It's exposed as plaintext in every session ticket.
   533  	keyName [ticketKeyNameLen]byte
   534  	aesKey  [16]byte
   535  	hmacKey [16]byte
   536  }
   537  
   538  // ticketKeyFromBytes converts from the external representation of a session
   539  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   540  // bytes and this function expands that into sufficient name and key material.
   541  func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   542  	hashed := sha512.Sum512(b[:])
   543  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   544  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   545  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   546  	return key
   547  }
   548  
   549  // Clone returns a shallow clone of c. It is safe to clone a Config that is
   550  // being used concurrently by a TLS client or server.
   551  func (c *Config) Clone() *Config {
   552  	// Running serverInit ensures that it's safe to read
   553  	// SessionTicketsDisabled.
   554  	c.serverInitOnce.Do(func() { c.serverInit(nil) })
   555  
   556  	var sessionTicketKeys []ticketKey
   557  	c.mutex.RLock()
   558  	sessionTicketKeys = c.sessionTicketKeys
   559  	c.mutex.RUnlock()
   560  
   561  	return &Config{
   562  		Rand:                        c.Rand,
   563  		Time:                        c.Time,
   564  		Certificates:                c.Certificates,
   565  		NameToCertificate:           c.NameToCertificate,
   566  		GetCertificate:              c.GetCertificate,
   567  		GetClientCertificate:        c.GetClientCertificate,
   568  		GetConfigForClient:          c.GetConfigForClient,
   569  		VerifyPeerCertificate:       c.VerifyPeerCertificate,
   570  		RootCAs:                     c.RootCAs,
   571  		NextProtos:                  c.NextProtos,
   572  		ServerName:                  c.ServerName,
   573  		ClientAuth:                  c.ClientAuth,
   574  		ClientCAs:                   c.ClientCAs,
   575  		InsecureSkipVerify:          c.InsecureSkipVerify,
   576  		CipherSuites:                c.CipherSuites,
   577  		PreferServerCipherSuites:    c.PreferServerCipherSuites,
   578  		SessionTicketsDisabled:      c.SessionTicketsDisabled,
   579  		SessionTicketKey:            c.SessionTicketKey,
   580  		ClientSessionCache:          c.ClientSessionCache,
   581  		MinVersion:                  c.MinVersion,
   582  		MaxVersion:                  c.MaxVersion,
   583  		CurvePreferences:            c.CurvePreferences,
   584  		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   585  		Renegotiation:               c.Renegotiation,
   586  		KeyLogWriter:                c.KeyLogWriter,
   587  		sessionTicketKeys:           sessionTicketKeys,
   588  	}
   589  }
   590  
   591  // serverInit is run under c.serverInitOnce to do initialization of c. If c was
   592  // returned by a GetConfigForClient callback then the argument should be the
   593  // Config that was passed to Server, otherwise it should be nil.
   594  func (c *Config) serverInit(originalConfig *Config) {
   595  	if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
   596  		return
   597  	}
   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  	var topCipherSuites []uint16
   923  
   924  	// Check the cpu flags for each platform that has optimized GCM implementations.
   925  	// Worst case, these variables will just all be false
   926  	hasGCMAsmAMD64 := cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
   927  
   928  	hasGCMAsmARM64 := cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
   929  
   930  	// Keep in sync with crypto/aes/cipher_s390x.go.
   931  	hasGCMAsmS390X := cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
   932  
   933  	hasGCMAsm := hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
   934  
   935  	if hasGCMAsm {
   936  		// If AES-GCM hardware is provided then prioritise AES-GCM
   937  		// cipher suites.
   938  		topCipherSuites = []uint16{
   939  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   940  			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
   941  			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
   942  			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
   943  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
   944  			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
   945  		}
   946  	} else {
   947  		// Without AES-GCM hardware, we put the ChaCha20-Poly1305
   948  		// cipher suites first.
   949  		topCipherSuites = []uint16{
   950  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
   951  			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
   952  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   953  			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
   954  			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
   955  			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
   956  		}
   957  	}
   958  
   959  	varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
   960  	varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
   961  
   962  NextCipherSuite:
   963  	for _, suite := range cipherSuites {
   964  		if suite.flags&suiteDefaultOff != 0 {
   965  			continue
   966  		}
   967  		for _, existing := range varDefaultCipherSuites {
   968  			if existing == suite.id {
   969  				continue NextCipherSuite
   970  			}
   971  		}
   972  		varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
   973  	}
   974  }
   975  
   976  func unexpectedMessageError(wanted, got interface{}) error {
   977  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
   978  }
   979  
   980  func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
   981  	for _, s := range supportedSignatureAlgorithms {
   982  		if s == sigAlg {
   983  			return true
   984  		}
   985  	}
   986  	return false
   987  }
   988  
   989  // signatureFromSignatureScheme maps a signature algorithm to the underlying
   990  // signature method (without hash function).
   991  func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
   992  	switch signatureAlgorithm {
   993  	case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
   994  		return signaturePKCS1v15
   995  	case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
   996  		return signatureRSAPSS
   997  	case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
   998  		return signatureECDSA
   999  	default:
  1000  		return 0
  1001  	}
  1002  }