github.com/Hyperledger-TWGC/tjfoc-gm@v1.4.0/gmtls/common.go (about)

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