...

Source file src/github.com/tjfoc/gmsm/gmtls/common.go

Documentation: github.com/tjfoc/gmsm/gmtls

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

View as plain text