...
Run Format

Source file src/crypto/tls/common.go

Documentation: crypto/tls

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

View as plain text