github.com/zmap/zcrypto@v0.0.0-20240512203510-0fef58d9a9db/tls/common.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls
     6  
     7  import (
     8  	"container/list"
     9  	"crypto"
    10  	"crypto/rand"
    11  	"crypto/rsa"
    12  	"crypto/sha512"
    13  	"encoding/hex"
    14  	"encoding/json"
    15  	"errors"
    16  	"fmt"
    17  	"io"
    18  	"math/big"
    19  	"net"
    20  	"strings"
    21  	"sync"
    22  	"time"
    23  
    24  	"github.com/zmap/zcrypto/x509"
    25  )
    26  
    27  const (
    28  	VersionSSL30 = 0x0300
    29  	VersionTLS10 = 0x0301
    30  	VersionTLS11 = 0x0302
    31  	VersionTLS12 = 0x0303
    32  )
    33  
    34  const (
    35  	maxPlaintext        = 16384        // maximum plaintext payload length
    36  	maxCiphertext       = 16384 + 2048 // maximum ciphertext payload length
    37  	tlsRecordHeaderLen  = 5            // record header length
    38  	dtlsRecordHeaderLen = 13
    39  	maxHandshake        = 65536 // maximum handshake we support (protocol max is 16 MB)
    40  
    41  	minVersion = VersionSSL30
    42  	maxVersion = VersionTLS12
    43  )
    44  
    45  // TLS record types.
    46  type recordType uint8
    47  
    48  const (
    49  	recordTypeChangeCipherSpec recordType = 20
    50  	recordTypeAlert            recordType = 21
    51  	recordTypeHandshake        recordType = 22
    52  	recordTypeApplicationData  recordType = 23
    53  )
    54  
    55  // TLS handshake message types.
    56  const (
    57  	typeHelloRequest        uint8 = 0
    58  	typeClientHello         uint8 = 1
    59  	typeServerHello         uint8 = 2
    60  	typeHelloVerifyRequest  uint8 = 3
    61  	typeNewSessionTicket    uint8 = 4
    62  	typeCertificate         uint8 = 11
    63  	typeServerKeyExchange   uint8 = 12
    64  	typeCertificateRequest  uint8 = 13
    65  	typeServerHelloDone     uint8 = 14
    66  	typeCertificateVerify   uint8 = 15
    67  	typeClientKeyExchange   uint8 = 16
    68  	typeFinished            uint8 = 20
    69  	typeCertificateStatus   uint8 = 22
    70  	typeNextProtocol        uint8 = 67  // Not IANA assigned
    71  	typeEncryptedExtensions uint8 = 203 // Not IANA assigned
    72  )
    73  
    74  // TLS compression types.
    75  const (
    76  	compressionNone uint8 = 0
    77  )
    78  
    79  // TLS extension numbers
    80  const (
    81  	extensionServerName           uint16 = 0
    82  	extensionStatusRequest        uint16 = 5
    83  	extensionSupportedCurves      uint16 = 10
    84  	extensionSupportedPoints      uint16 = 11
    85  	extensionSignatureAlgorithms  uint16 = 13
    86  	extensionALPN                 uint16 = 16
    87  	extensionExtendedMasterSecret uint16 = 23
    88  	extensionSessionTicket        uint16 = 35
    89  	extensionNextProtoNeg         uint16 = 13172 // not IANA assigned
    90  	extensionRenegotiationInfo    uint16 = 0xff01
    91  	extensionExtendedRandom       uint16 = 0x0028 // not IANA assigned
    92  	extensionSCT                  uint16 = 18
    93  )
    94  
    95  // TLS signaling cipher suite values
    96  const (
    97  	scsvRenegotiation uint16 = 0x00ff
    98  )
    99  
   100  // CurveID is the type of a TLS identifier for an elliptic curve. See
   101  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
   102  type CurveID uint16
   103  
   104  const (
   105  	CurveP256 CurveID = 23
   106  	CurveP384 CurveID = 24
   107  	CurveP521 CurveID = 25
   108  )
   109  
   110  func (curveID *CurveID) MarshalJSON() ([]byte, error) {
   111  	buf := make([]byte, 2)
   112  	buf[0] = byte(*curveID >> 8)
   113  	buf[1] = byte(*curveID)
   114  	enc := strings.ToUpper(hex.EncodeToString(buf))
   115  	aux := struct {
   116  		Hex   string `json:"hex"`
   117  		Name  string `json:"name"`
   118  		Value uint16 `json:"value"`
   119  	}{
   120  		Hex:   fmt.Sprintf("0x%s", enc),
   121  		Name:  curveID.String(),
   122  		Value: uint16(*curveID),
   123  	}
   124  
   125  	return json.Marshal(aux)
   126  }
   127  
   128  func (curveID *CurveID) UnmarshalJSON(b []byte) error {
   129  	aux := struct {
   130  		Hex   string `json:"hex"`
   131  		Name  string `json:"name"`
   132  		Value uint16 `json:"value"`
   133  	}{}
   134  	if err := json.Unmarshal(b, &aux); err != nil {
   135  		return err
   136  	}
   137  	if expectedName := nameForCurve(aux.Value); expectedName != aux.Name {
   138  		return fmt.Errorf("mismatched curve and name, curve: %d, name: %s, expected name: %s", aux.Value, aux.Name, expectedName)
   139  	}
   140  	*curveID = CurveID(aux.Value)
   141  	return nil
   142  }
   143  
   144  type PointFormat uint8
   145  
   146  // TLS Elliptic Curve Point Formats
   147  // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
   148  const (
   149  	pointFormatUncompressed uint8 = 0
   150  )
   151  
   152  func (pFormat *PointFormat) MarshalJSON() ([]byte, error) {
   153  	buf := make([]byte, 1)
   154  	buf[0] = byte(*pFormat)
   155  	enc := strings.ToUpper(hex.EncodeToString(buf))
   156  	aux := struct {
   157  		Hex   string `json:"hex"`
   158  		Name  string `json:"name"`
   159  		Value uint8  `json:"value"`
   160  	}{
   161  		Hex:   fmt.Sprintf("0x%s", enc),
   162  		Name:  pFormat.String(),
   163  		Value: uint8(*pFormat),
   164  	}
   165  
   166  	return json.Marshal(aux)
   167  }
   168  
   169  func (pFormat *PointFormat) UnmarshalJSON(b []byte) error {
   170  	aux := struct {
   171  		Hex   string `json:"hex"`
   172  		Name  string `json:"name"`
   173  		Value uint8  `json:"value"`
   174  	}{}
   175  	if err := json.Unmarshal(b, &aux); err != nil {
   176  		return err
   177  	}
   178  	if expectedName := nameForPointFormat(aux.Value); expectedName != aux.Name {
   179  		return fmt.Errorf("mismatched point format and name, point format: %d, name: %s, expected name: %s", aux.Value, aux.Name, expectedName)
   180  	}
   181  	*pFormat = PointFormat(aux.Value)
   182  	return nil
   183  }
   184  
   185  // TLS CertificateStatusType (RFC 3546)
   186  const (
   187  	statusTypeOCSP uint8 = 1
   188  )
   189  
   190  // Certificate types (for certificateRequestMsg)
   191  const (
   192  	certTypeRSASign    = 1 // A certificate containing an RSA key
   193  	certTypeDSSSign    = 2 // A certificate containing a DSA key
   194  	certTypeRSAFixedDH = 3 // A certificate containing a static DH key
   195  	certTypeDSSFixedDH = 4 // A certificate containing a static DH key
   196  
   197  	// See RFC4492 sections 3 and 5.5.
   198  	certTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
   199  	certTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
   200  	certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
   201  
   202  	// Rest of these are reserved by the TLS spec
   203  )
   204  
   205  // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
   206  const (
   207  	hashMD5    uint8 = 1
   208  	hashSHA1   uint8 = 2
   209  	hashSHA224 uint8 = 3
   210  	hashSHA256 uint8 = 4
   211  	hashSHA384 uint8 = 5
   212  	hashSHA512 uint8 = 6
   213  )
   214  
   215  // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
   216  const (
   217  	signatureRSA   uint8 = 1
   218  	signatureDSA   uint8 = 2
   219  	signatureECDSA uint8 = 3
   220  )
   221  
   222  // SigAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
   223  // RFC 5246, section A.4.1.
   224  type SigAndHash struct {
   225  	Signature, Hash uint8
   226  }
   227  
   228  // supportedSKXSignatureAlgorithms contains the signature and hash algorithms
   229  // that the code advertises as supported in a TLS 1.2 ClientHello.
   230  var supportedSKXSignatureAlgorithms = []SigAndHash{
   231  	{signatureRSA, hashSHA512},
   232  	{signatureECDSA, hashSHA512},
   233  	{signatureDSA, hashSHA512},
   234  	{signatureRSA, hashSHA384},
   235  	{signatureECDSA, hashSHA384},
   236  	{signatureDSA, hashSHA384},
   237  	{signatureRSA, hashSHA256},
   238  	{signatureECDSA, hashSHA256},
   239  	{signatureDSA, hashSHA256},
   240  	{signatureRSA, hashSHA224},
   241  	{signatureECDSA, hashSHA224},
   242  	{signatureDSA, hashSHA224},
   243  	{signatureRSA, hashSHA1},
   244  	{signatureECDSA, hashSHA1},
   245  	{signatureDSA, hashSHA1},
   246  	{signatureRSA, hashMD5},
   247  	{signatureECDSA, hashMD5},
   248  	{signatureDSA, hashMD5},
   249  }
   250  
   251  var defaultSKXSignatureAlgorithms = []SigAndHash{
   252  	{signatureRSA, hashSHA256},
   253  	{signatureECDSA, hashSHA256},
   254  	{signatureRSA, hashSHA1},
   255  	{signatureECDSA, hashSHA1},
   256  	{signatureRSA, hashSHA256},
   257  	{signatureRSA, hashSHA384},
   258  	{signatureRSA, hashSHA512},
   259  }
   260  
   261  // supportedClientCertSignatureAlgorithms contains the signature and hash
   262  // algorithms that the code advertises as supported in a TLS 1.2
   263  // CertificateRequest.
   264  var supportedClientCertSignatureAlgorithms = []SigAndHash{
   265  	{signatureRSA, hashSHA256},
   266  	{signatureECDSA, hashSHA256},
   267  }
   268  
   269  // ConnectionState records basic TLS details about the connection.
   270  type ConnectionState struct {
   271  	Version                    uint16                  // TLS version used by the connection (e.g. VersionTLS12)
   272  	HandshakeComplete          bool                    // TLS handshake is complete
   273  	DidResume                  bool                    // connection resumes a previous TLS connection
   274  	CipherSuite                uint16                  // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
   275  	NegotiatedProtocol         string                  // negotiated next protocol (from Config.NextProtos)
   276  	NegotiatedProtocolIsMutual bool                    // negotiated protocol was advertised by server
   277  	ServerName                 string                  // server name requested by client, if any (server side only)
   278  	PeerCertificates           []*x509.Certificate     // certificate chain presented by remote peer
   279  	VerifiedChains             []x509.CertificateChain // verified chains built from PeerCertificates
   280  }
   281  
   282  // ClientAuthType declares the policy the server will follow for
   283  // TLS Client Authentication.
   284  type ClientAuthType int
   285  
   286  const (
   287  	// Values have no meaning (were previously 'iota')
   288  	// Values added IOT allow dereference to name for JSON
   289  	NoClientCert               ClientAuthType = 0
   290  	RequestClientCert          ClientAuthType = 1
   291  	RequireAnyClientCert       ClientAuthType = 2
   292  	VerifyClientCertIfGiven    ClientAuthType = 3
   293  	RequireAndVerifyClientCert ClientAuthType = 4
   294  )
   295  
   296  func (authType *ClientAuthType) String() string {
   297  	if name, ok := clientAuthTypeNames[int(*authType)]; ok {
   298  		return name
   299  	}
   300  
   301  	return "unknown"
   302  }
   303  
   304  func (authType *ClientAuthType) MarshalJSON() ([]byte, error) {
   305  	return []byte(`"` + authType.String() + `"`), nil
   306  }
   307  
   308  func (authType *ClientAuthType) UnmarshalJSON(b []byte) error {
   309  	panic("unimplemented")
   310  }
   311  
   312  // ClientSessionState contains the state needed by clients to resume TLS
   313  // sessions.
   314  type ClientSessionState struct {
   315  	sessionTicket        []uint8             // Encrypted ticket used for session resumption with server
   316  	lifetimeHint         uint32              // Hint from server about how long the session ticket should be stored
   317  	vers                 uint16              // SSL/TLS version negotiated for the session
   318  	cipherSuite          uint16              // Ciphersuite negotiated for the session
   319  	masterSecret         []byte              // MasterSecret generated by client on a full handshake
   320  	serverCertificates   []*x509.Certificate // Certificate chain presented by the server
   321  	extendedMasterSecret bool                // Whether an extended master secret was used to generate the session
   322  }
   323  
   324  // ClientSessionCache is a cache of ClientSessionState objects that can be used
   325  // by a client to resume a TLS session with a given server. ClientSessionCache
   326  // implementations should expect to be called concurrently from different
   327  // goroutines.
   328  type ClientSessionCache interface {
   329  	// Get searches for a ClientSessionState associated with the given key.
   330  	// On return, ok is true if one was found.
   331  	Get(sessionKey string) (session *ClientSessionState, ok bool)
   332  
   333  	// Put adds the ClientSessionState to the cache with the given key.
   334  	Put(sessionKey string, cs *ClientSessionState)
   335  }
   336  
   337  // A Config structure is used to configure a TLS client or server.
   338  // After one has been passed to a TLS function it must not be
   339  // modified. A Config may be reused; the tls package will also not
   340  // modify it.
   341  type Config struct {
   342  	// Rand provides the source of entropy for nonces and RSA blinding.
   343  	// If Rand is nil, TLS uses the cryptographic random reader in package
   344  	// crypto/rand.
   345  	// The Reader must be safe for use by multiple goroutines.
   346  	Rand io.Reader
   347  
   348  	// Time returns the current time as the number of seconds since the epoch.
   349  	// If Time is nil, TLS uses time.Now.
   350  	Time func() time.Time
   351  
   352  	// Certificates contains one or more certificate chains
   353  	// to present to the other side of the connection.
   354  	// Server configurations must include at least one certificate.
   355  	Certificates []Certificate
   356  
   357  	// NameToCertificate maps from a certificate name to an element of
   358  	// Certificates. Note that a certificate name can be of the form
   359  	// '*.example.com' and so doesn't have to be a domain name as such.
   360  	// See Config.BuildNameToCertificate
   361  	// The nil value causes the first element of Certificates to be used
   362  	// for all connections.
   363  	NameToCertificate map[string]*Certificate
   364  
   365  	// RootCAs defines the set of root certificate authorities
   366  	// that clients use when verifying server certificates.
   367  	// If RootCAs is nil, TLS uses the host's root CA set.
   368  	RootCAs *x509.CertPool
   369  
   370  	// NextProtos is a list of supported, application level protocols.
   371  	NextProtos []string
   372  
   373  	// ServerName is used to verify the hostname on the returned
   374  	// certificates unless InsecureSkipVerify is given. It is also included
   375  	// in the client's handshake to support virtual hosting.
   376  	ServerName string
   377  
   378  	// ClientAuth determines the server's policy for
   379  	// TLS Client Authentication. The default is NoClientCert.
   380  	ClientAuth ClientAuthType
   381  
   382  	// ClientCAs defines the set of root certificate authorities
   383  	// that servers use if required to verify a client certificate
   384  	// by the policy in ClientAuth.
   385  	ClientCAs *x509.CertPool
   386  
   387  	// InsecureSkipVerify controls whether a client verifies the
   388  	// server's certificate chain and host name.
   389  	// If InsecureSkipVerify is true, TLS accepts any certificate
   390  	// presented by the server and any host name in that certificate.
   391  	// In this mode, TLS is susceptible to man-in-the-middle attacks.
   392  	// This should be used only for testing.
   393  	InsecureSkipVerify bool
   394  
   395  	// CipherSuites is a list of supported cipher suites. If CipherSuites
   396  	// is nil, TLS uses a list of suites supported by the implementation.
   397  	CipherSuites []uint16
   398  
   399  	// PreferServerCipherSuites controls whether the server selects the
   400  	// client's most preferred ciphersuite, or the server's most preferred
   401  	// ciphersuite. If true then the server's preference, as expressed in
   402  	// the order of elements in CipherSuites, is used.
   403  	PreferServerCipherSuites bool
   404  
   405  	// SessionTicketsDisabled may be set to true to disable session ticket
   406  	// (resumption) support.
   407  	SessionTicketsDisabled bool
   408  
   409  	// SessionTicketKey is used by TLS servers to provide session
   410  	// resumption. See RFC 5077. If zero, it will be filled with
   411  	// random data before the first server handshake.
   412  	//
   413  	// If multiple servers are terminating connections for the same host
   414  	// they should all have the same SessionTicketKey. If the
   415  	// SessionTicketKey leaks, previously recorded and future TLS
   416  	// connections using that key are compromised.
   417  	SessionTicketKey [32]byte
   418  
   419  	// SessionCache is a cache of ClientSessionState entries for TLS session
   420  	// resumption.
   421  	ClientSessionCache ClientSessionCache
   422  
   423  	// MinVersion contains the minimum SSL/TLS version that is acceptable.
   424  	// If zero, then SSLv3 is taken as the minimum.
   425  	MinVersion uint16
   426  
   427  	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
   428  	// If zero, then the maximum version supported by this package is used,
   429  	// which is currently TLS 1.2.
   430  	MaxVersion uint16
   431  
   432  	// CurvePreferences contains the elliptic curves that will be used in
   433  	// an ECDHE handshake, in preference order. If empty, the default will
   434  	// be used.
   435  	CurvePreferences []CurveID
   436  
   437  	// If enabled, empty CurvePreferences indicates that there are no curves
   438  	// supported for ECDHE key exchanges
   439  	ExplicitCurvePreferences bool
   440  
   441  	// EC Point Formats. Specifies what compressed points the client supports
   442  	SupportedPoints []uint8
   443  
   444  	// Online Certificate Status Protocol (OCSP) stapling,
   445  	// formally knows as TLS Certificate Status Request.
   446  	// If this option enabled, the certificate status won't be checked
   447  	NoOcspStapling bool
   448  
   449  	// Specifies what compression methods the client supports
   450  	CompressionMethods []uint8
   451  
   452  	// If enabled, specifies the signature and hash algorithms to be accepted by
   453  	// a server, or sent by a client
   454  	SignatureAndHashes []SigAndHash
   455  
   456  	serverInitOnce sync.Once // guards calling (*Config).serverInit
   457  
   458  	// Add all ciphers in CipherSuites to Client Hello even if unimplemented
   459  	// Client-side Only
   460  	ForceSuites bool
   461  
   462  	// Export RSA Key
   463  	ExportRSAKey *rsa.PrivateKey
   464  
   465  	// HeartbeatEnabled sets whether the heartbeat extension is sent
   466  	HeartbeatEnabled bool
   467  
   468  	// ClientDSAEnabled sets whether a TLS client will accept server DSA keys
   469  	// and DSS signatures
   470  	ClientDSAEnabled bool
   471  
   472  	// Use extended random
   473  	ExtendedRandom bool
   474  
   475  	// Force Client Hello to send TLS Session Ticket extension
   476  	ForceSessionTicketExt bool
   477  
   478  	// Enable use of the Extended Master Secret extension
   479  	ExtendedMasterSecret bool
   480  
   481  	SignedCertificateTimestampExt bool
   482  
   483  	// Explicitly set Client random
   484  	ClientRandom []byte
   485  
   486  	// Explicitly set Server random
   487  	ServerRandom []byte
   488  
   489  	// Explicitly set ClientHello with raw data
   490  	ExternalClientHello []byte
   491  
   492  	// If non-null specifies the contents of the client-hello
   493  	// WARNING: Setting this may invalidate other fields in the Config object
   494  	ClientFingerprintConfiguration *ClientFingerprintConfiguration
   495  
   496  	// GetConfigForClient, if not nil, is called after a ClientHello is
   497  	// received from a client. It may return a non-nil Config in order to
   498  	// change the Config that will be used to handle this connection. If
   499  	// the returned Config is nil, the original Config will be used. The
   500  	// Config returned by this callback may not be subsequently modified.
   501  	//
   502  	// If GetConfigForClient is nil, the Config passed to Server() will be
   503  	// used for all connections.
   504  	//
   505  	// Uniquely for the fields in the returned Config, session ticket keys
   506  	// will be duplicated from the original Config if not set.
   507  	// Specifically, if SetSessionTicketKeys was called on the original
   508  	// config but not on the returned config then the ticket keys from the
   509  	// original config will be copied into the new config before use.
   510  	// Otherwise, if SessionTicketKey was set in the original config but
   511  	// not in the returned config then it will be copied into the returned
   512  	// config before use. If neither of those cases applies then the key
   513  	// material from the returned config will be used for session tickets.
   514  	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
   515  
   516  	// CertsOnly is used to cause a client to close the TLS connection
   517  	// as soon as the server's certificates have been received
   518  	CertsOnly bool
   519  
   520  	// DontBufferHandshakes causes Handshake() to act like older versions of the go crypto library, where each TLS packet is sent in a separate Write.
   521  	DontBufferHandshakes bool
   522  
   523  	// mutex protects sessionTicketKeys and originalConfig.
   524  	mutex sync.RWMutex
   525  	// sessionTicketKeys contains zero or more ticket keys. If the length
   526  	// is zero, SessionTicketsDisabled must be true. The first key is used
   527  	// for new tickets and any subsequent keys can be used to decrypt old
   528  	// tickets.
   529  	sessionTicketKeys []ticketKey
   530  	// originalConfig is set to the Config that was passed to Server if
   531  	// this Config is returned by a GetConfigForClient callback. It's used
   532  	// by serverInit in order to copy session ticket keys if needed.
   533  	originalConfig *Config
   534  }
   535  
   536  // ticketKeyNameLen is the number of bytes of identifier that is prepended to
   537  // an encrypted session ticket in order to identify the key used to encrypt it.
   538  const ticketKeyNameLen = 16
   539  
   540  // ticketKey is the internal representation of a session ticket key.
   541  type ticketKey struct {
   542  	// keyName is an opaque byte string that serves to identify the session
   543  	// ticket key. It's exposed as plaintext in every session ticket.
   544  	keyName [ticketKeyNameLen]byte
   545  	aesKey  [16]byte
   546  	hmacKey [16]byte
   547  }
   548  
   549  // ticketKeyFromBytes converts from the external representation of a session
   550  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   551  // bytes and this function expands that into sufficient name and key material.
   552  func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   553  	hashed := sha512.Sum512(b[:])
   554  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   555  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   556  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   557  	return key
   558  }
   559  
   560  // Clone returns a shallow clone of c. It is safe to clone a Config that is
   561  // being used concurrently by a TLS client or server.
   562  func (c *Config) Clone() *Config {
   563  	// Running serverInit ensures that it's safe to read
   564  	// SessionTicketsDisabled.
   565  	c.serverInitOnce.Do(c.serverInit)
   566  
   567  	var sessionTicketKeys []ticketKey
   568  	c.mutex.RLock()
   569  	sessionTicketKeys = c.sessionTicketKeys
   570  	c.mutex.RUnlock()
   571  
   572  	return &Config{
   573  		Rand:                           c.Rand,
   574  		Time:                           c.Time,
   575  		Certificates:                   c.Certificates,
   576  		NameToCertificate:              c.NameToCertificate,
   577  		GetConfigForClient:             c.GetConfigForClient,
   578  		RootCAs:                        c.RootCAs,
   579  		NextProtos:                     c.NextProtos,
   580  		ServerName:                     c.ServerName,
   581  		ClientAuth:                     c.ClientAuth,
   582  		ClientCAs:                      c.ClientCAs,
   583  		InsecureSkipVerify:             c.InsecureSkipVerify,
   584  		CipherSuites:                   c.CipherSuites,
   585  		PreferServerCipherSuites:       c.PreferServerCipherSuites,
   586  		SessionTicketsDisabled:         c.SessionTicketsDisabled,
   587  		SessionTicketKey:               c.SessionTicketKey,
   588  		ClientSessionCache:             c.ClientSessionCache,
   589  		MinVersion:                     c.MinVersion,
   590  		MaxVersion:                     c.MaxVersion,
   591  		CurvePreferences:               c.CurvePreferences,
   592  		ExplicitCurvePreferences:       c.ExplicitCurvePreferences,
   593  		sessionTicketKeys:              sessionTicketKeys,
   594  		ClientFingerprintConfiguration: c.ClientFingerprintConfiguration,
   595  		CertsOnly:                      c.CertsOnly,
   596  		// originalConfig is deliberately not duplicated.
   597  
   598  		// Not merged from upstream:
   599  		// GetCertificate: c.GetCertificate,
   600  		// DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   601  		// VerifyPeerCertificate:    c.VerifyPeerCertificate,
   602  		// KeyLogWriter:             c.KeyLogWriter,
   603  		// Renegotiation:            c.Renegotiation,
   604  	}
   605  }
   606  
   607  func (c *Config) serverInit() {
   608  	if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
   609  		return
   610  	}
   611  
   612  	var originalConfig *Config
   613  	c.mutex.Lock()
   614  	originalConfig, c.originalConfig = c.originalConfig, nil
   615  	c.mutex.Unlock()
   616  
   617  	alreadySet := false
   618  	for _, b := range c.SessionTicketKey {
   619  		if b != 0 {
   620  			alreadySet = true
   621  			break
   622  		}
   623  	}
   624  
   625  	if !alreadySet {
   626  		if originalConfig != nil {
   627  			copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
   628  		} else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   629  			c.SessionTicketsDisabled = true
   630  			return
   631  		}
   632  	}
   633  
   634  	if originalConfig != nil {
   635  		originalConfig.mutex.RLock()
   636  		c.sessionTicketKeys = originalConfig.sessionTicketKeys
   637  		originalConfig.mutex.RUnlock()
   638  	} else {
   639  		c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
   640  	}
   641  }
   642  
   643  func (c *Config) ticketKeys() []ticketKey {
   644  	c.mutex.RLock()
   645  	// c.sessionTicketKeys is constant once created. SetSessionTicketKeys
   646  	// will only update it by replacing it with a new value.
   647  	ret := c.sessionTicketKeys
   648  	c.mutex.RUnlock()
   649  	return ret
   650  }
   651  
   652  func (c *Config) rand() io.Reader {
   653  	r := c.Rand
   654  	if r == nil {
   655  		return rand.Reader
   656  	}
   657  	return r
   658  }
   659  
   660  func (c *Config) time() time.Time {
   661  	t := c.Time
   662  	if t == nil {
   663  		t = time.Now
   664  	}
   665  	return t()
   666  }
   667  
   668  func (c *Config) cipherSuites() []uint16 {
   669  	s := c.CipherSuites
   670  	if s == nil {
   671  		s = defaultCipherSuites()
   672  	}
   673  	return s
   674  }
   675  
   676  func (c *Config) minVersion() uint16 {
   677  	if c == nil || c.MinVersion == 0 {
   678  		return minVersion
   679  	}
   680  	return c.MinVersion
   681  }
   682  
   683  func (c *Config) maxVersion() uint16 {
   684  	if c == nil || c.MaxVersion == 0 {
   685  		return maxVersion
   686  	}
   687  	return c.MaxVersion
   688  }
   689  
   690  var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
   691  
   692  func (c *Config) curvePreferences() []CurveID {
   693  	if c.ExplicitCurvePreferences {
   694  		return c.CurvePreferences
   695  	}
   696  	if c == nil || len(c.CurvePreferences) == 0 {
   697  		return defaultCurvePreferences
   698  	}
   699  	return c.CurvePreferences
   700  }
   701  
   702  // mutualVersion returns the protocol version to use given the advertised
   703  // version of the peer.
   704  func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
   705  	minVersion := c.minVersion()
   706  	maxVersion := c.maxVersion()
   707  
   708  	if vers < minVersion {
   709  		return 0, false
   710  	}
   711  	if vers > maxVersion {
   712  		vers = maxVersion
   713  	}
   714  	return vers, true
   715  }
   716  
   717  // SetSessionTicketKeys updates the session ticket keys for a server. The first
   718  // key will be used when creating new tickets, while all keys can be used for
   719  // decrypting tickets. It is safe to call this function while the server is
   720  // running in order to rotate the session ticket keys. The function will panic
   721  // if keys is empty.
   722  func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
   723  	if len(keys) == 0 {
   724  		panic("tls: keys must have at least one key")
   725  	}
   726  
   727  	newKeys := make([]ticketKey, len(keys))
   728  	for i, bytes := range keys {
   729  		newKeys[i] = ticketKeyFromBytes(bytes)
   730  	}
   731  
   732  	c.mutex.Lock()
   733  	c.sessionTicketKeys = newKeys
   734  	c.mutex.Unlock()
   735  }
   736  
   737  // getCertificateForName returns the best certificate for the given name,
   738  // defaulting to the first element of c.Certificates if there are no good
   739  // options.
   740  func (c *Config) getCertificateForName(name string) *Certificate {
   741  	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
   742  		// There's only one choice, so no point doing any work.
   743  		return &c.Certificates[0]
   744  	}
   745  
   746  	name = strings.ToLower(name)
   747  	for len(name) > 0 && name[len(name)-1] == '.' {
   748  		name = name[:len(name)-1]
   749  	}
   750  
   751  	if cert, ok := c.NameToCertificate[name]; ok {
   752  		return cert
   753  	}
   754  
   755  	// try replacing labels in the name with wildcards until we get a
   756  	// match.
   757  	labels := strings.Split(name, ".")
   758  	for i := range labels {
   759  		labels[i] = "*"
   760  		candidate := strings.Join(labels, ".")
   761  		if cert, ok := c.NameToCertificate[candidate]; ok {
   762  			return cert
   763  		}
   764  	}
   765  
   766  	// If nothing matches, return the first certificate.
   767  	return &c.Certificates[0]
   768  }
   769  
   770  func (c *Config) signatureAndHashesForServer() []SigAndHash {
   771  	if c != nil && c.SignatureAndHashes != nil {
   772  		return c.SignatureAndHashes
   773  	}
   774  	return supportedClientCertSignatureAlgorithms
   775  }
   776  
   777  func (c *Config) signatureAndHashesForClient() []SigAndHash {
   778  	if c != nil && c.SignatureAndHashes != nil {
   779  		return c.SignatureAndHashes
   780  	}
   781  	if c.ClientDSAEnabled {
   782  		return supportedSKXSignatureAlgorithms
   783  	}
   784  	return defaultSKXSignatureAlgorithms
   785  }
   786  
   787  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
   788  // from the CommonName and SubjectAlternateName fields of each of the leaf
   789  // certificates.
   790  func (c *Config) BuildNameToCertificate() {
   791  	c.NameToCertificate = make(map[string]*Certificate)
   792  	for i := range c.Certificates {
   793  		cert := &c.Certificates[i]
   794  		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
   795  		if err != nil {
   796  			continue
   797  		}
   798  		if len(x509Cert.Subject.CommonName) > 0 {
   799  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
   800  		}
   801  		for _, san := range x509Cert.DNSNames {
   802  			c.NameToCertificate[san] = cert
   803  		}
   804  	}
   805  }
   806  
   807  // A Certificate is a chain of one or more certificates, leaf first.
   808  type Certificate struct {
   809  	Certificate [][]byte `json:"certificate_chain,omitempty"`
   810  
   811  	// supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
   812  	// OCSPStaple contains an optional OCSP response which will be served
   813  	// to clients that request it.
   814  	// Don't expose the private key by default (can be marshalled manually)
   815  	PrivateKey crypto.PrivateKey `json:"-"`
   816  
   817  	OCSPStaple []byte `json:"ocsp_staple,omitempty"`
   818  
   819  	// Leaf is the parsed form of the leaf certificate, which may be
   820  	// initialized using x509.ParseCertificate to reduce per-handshake
   821  	// processing for TLS clients doing client authentication. If nil, the
   822  	// leaf certificate will be parsed as needed.
   823  	Leaf *x509.Certificate `json:"leaf,omitempty"`
   824  }
   825  
   826  // A TLS record.
   827  type record struct {
   828  	contentType  recordType
   829  	major, minor uint8
   830  	payload      []byte
   831  }
   832  
   833  type handshakeMessage interface {
   834  	marshal() []byte
   835  	unmarshal([]byte) bool
   836  }
   837  
   838  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
   839  // caching strategy.
   840  type lruSessionCache struct {
   841  	sync.Mutex
   842  
   843  	m        map[string]*list.Element
   844  	q        *list.List
   845  	capacity int
   846  }
   847  
   848  type lruSessionCacheEntry struct {
   849  	sessionKey string
   850  	state      *ClientSessionState
   851  }
   852  
   853  // NewLRUClientSessionCache returns a ClientSessionCache with the given
   854  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
   855  // is used instead.
   856  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
   857  	const defaultSessionCacheCapacity = 64
   858  
   859  	if capacity < 1 {
   860  		capacity = defaultSessionCacheCapacity
   861  	}
   862  	return &lruSessionCache{
   863  		m:        make(map[string]*list.Element),
   864  		q:        list.New(),
   865  		capacity: capacity,
   866  	}
   867  }
   868  
   869  // Put adds the provided (sessionKey, cs) pair to the cache.
   870  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
   871  	c.Lock()
   872  	defer c.Unlock()
   873  
   874  	if elem, ok := c.m[sessionKey]; ok {
   875  		entry := elem.Value.(*lruSessionCacheEntry)
   876  		entry.state = cs
   877  		c.q.MoveToFront(elem)
   878  		return
   879  	}
   880  
   881  	if c.q.Len() < c.capacity {
   882  		entry := &lruSessionCacheEntry{sessionKey, cs}
   883  		c.m[sessionKey] = c.q.PushFront(entry)
   884  		return
   885  	}
   886  
   887  	elem := c.q.Back()
   888  	entry := elem.Value.(*lruSessionCacheEntry)
   889  	delete(c.m, entry.sessionKey)
   890  	entry.sessionKey = sessionKey
   891  	entry.state = cs
   892  	c.q.MoveToFront(elem)
   893  	c.m[sessionKey] = elem
   894  }
   895  
   896  // Get returns the ClientSessionState value associated with a given key. It
   897  // returns (nil, false) if no value is found.
   898  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
   899  	c.Lock()
   900  	defer c.Unlock()
   901  
   902  	if elem, ok := c.m[sessionKey]; ok {
   903  		c.q.MoveToFront(elem)
   904  		return elem.Value.(*lruSessionCacheEntry).state, true
   905  	}
   906  	return nil, false
   907  }
   908  
   909  // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
   910  type dsaSignature struct {
   911  	R, S *big.Int
   912  }
   913  
   914  type ecdsaSignature dsaSignature
   915  
   916  var emptyConfig Config = Config{InsecureSkipVerify: true}
   917  
   918  func defaultConfig() *Config {
   919  	return &emptyConfig
   920  }
   921  
   922  var (
   923  	once                   sync.Once
   924  	varDefaultCipherSuites []uint16
   925  )
   926  
   927  func defaultCipherSuites() []uint16 {
   928  	once.Do(initDefaultCipherSuites)
   929  	return varDefaultCipherSuites
   930  }
   931  
   932  func initDefaultCipherSuites() {
   933  	varDefaultCipherSuites = make([]uint16, len(stdlibCipherSuites))
   934  	for i, suite := range stdlibCipherSuites {
   935  		varDefaultCipherSuites[i] = suite.id
   936  	}
   937  }
   938  
   939  func unexpectedMessageError(wanted, got interface{}) error {
   940  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
   941  }
   942  
   943  func isSupportedSignatureAndHash(sigHash SigAndHash, sigHashes []SigAndHash) bool {
   944  	for _, s := range sigHashes {
   945  		if s == sigHash {
   946  			return true
   947  		}
   948  	}
   949  	return false
   950  }
   951  
   952  // SignatureScheme identifies a signature algorithm supported by TLS. See
   953  // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3.
   954  type SignatureScheme uint16
   955  
   956  const (
   957  	PKCS1WithSHA1   SignatureScheme = 0x0201
   958  	PKCS1WithSHA256 SignatureScheme = 0x0401
   959  	PKCS1WithSHA384 SignatureScheme = 0x0501
   960  	PKCS1WithSHA512 SignatureScheme = 0x0601
   961  
   962  	PSSWithSHA256 SignatureScheme = 0x0804
   963  	PSSWithSHA384 SignatureScheme = 0x0805
   964  	PSSWithSHA512 SignatureScheme = 0x0806
   965  
   966  	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
   967  	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
   968  	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
   969  
   970  	EdDSAWithEd25519 SignatureScheme = 0x0807
   971  	EdDSAWithEd448   SignatureScheme = 0x0808
   972  )
   973  
   974  func (sigScheme *SignatureScheme) MarshalJSON() ([]byte, error) {
   975  	buf := sigScheme.Bytes()
   976  	enc := strings.ToUpper(hex.EncodeToString(buf))
   977  	aux := struct {
   978  		Hex   string `json:"hex"`
   979  		Name  string `json:"name"`
   980  		Value uint16 `json:"value"`
   981  	}{
   982  		Hex:   fmt.Sprintf("0x%s", enc),
   983  		Name:  sigScheme.String(),
   984  		Value: uint16(*sigScheme),
   985  	}
   986  
   987  	return json.Marshal(aux)
   988  }
   989  
   990  func (sigScheme *SignatureScheme) UnmarshalJSON(b []byte) error {
   991  	aux := struct {
   992  		Hex   string `json:"hex"`
   993  		Name  string `json:"name"`
   994  		Value uint16 `json:"value"`
   995  	}{}
   996  	if err := json.Unmarshal(b, &aux); err != nil {
   997  		return err
   998  	}
   999  	if expectedName := nameForSignatureScheme(aux.Value); expectedName != aux.Name {
  1000  		return fmt.Errorf("mismatched signature scheme and name, signature scheme: %d, name: %s, expected name: %s", aux.Value, aux.Name, expectedName)
  1001  	}
  1002  	*sigScheme = SignatureScheme(aux.Value)
  1003  	return nil
  1004  }
  1005  
  1006  // ClientHelloInfo contains information from a ClientHello message in order to
  1007  // guide certificate selection in the GetCertificate callback.
  1008  type ClientHelloInfo struct {
  1009  	// CipherSuites lists the CipherSuites supported by the client (e.g.
  1010  	// TLS_RSA_WITH_RC4_128_SHA).
  1011  	CipherSuites []uint16
  1012  
  1013  	// ServerName indicates the name of the server requested by the client
  1014  	// in order to support virtual hosting. ServerName is only set if the
  1015  	// client is using SNI (see
  1016  	// http://tools.ietf.org/html/rfc4366#section-3.1).
  1017  	ServerName string
  1018  
  1019  	// SupportedCurves lists the elliptic curves supported by the client.
  1020  	// SupportedCurves is set only if the Supported Elliptic Curves
  1021  	// Extension is being used (see
  1022  	// http://tools.ietf.org/html/rfc4492#section-5.1.1).
  1023  	SupportedCurves []CurveID
  1024  
  1025  	// SupportedPoints lists the point formats supported by the client.
  1026  	// SupportedPoints is set only if the Supported Point Formats Extension
  1027  	// is being used (see
  1028  	// http://tools.ietf.org/html/rfc4492#section-5.1.2).
  1029  	SupportedPoints []uint8
  1030  
  1031  	// SignatureSchemes lists the signature and hash schemes that the client
  1032  	// is willing to verify. SignatureSchemes is set only if the Signature
  1033  	// Algorithms Extension is being used (see
  1034  	// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1).
  1035  	SignatureSchemes []SignatureScheme
  1036  
  1037  	// SupportedProtos lists the application protocols supported by the client.
  1038  	// SupportedProtos is set only if the Application-Layer Protocol
  1039  	// Negotiation Extension is being used (see
  1040  	// https://tools.ietf.org/html/rfc7301#section-3.1).
  1041  	//
  1042  	// Servers can select a protocol by setting Config.NextProtos in a
  1043  	// GetConfigForClient return value.
  1044  	SupportedProtos []string
  1045  
  1046  	// SupportedVersions lists the TLS versions supported by the client.
  1047  	// For TLS versions less than 1.3, this is extrapolated from the max
  1048  	// version advertised by the client, so values other than the greatest
  1049  	// might be rejected if used.
  1050  	SupportedVersions []uint16
  1051  
  1052  	// Conn is the underlying net.Conn for the connection. Do not read
  1053  	// from, or write to, this connection; that will cause the TLS
  1054  	// connection to fail.
  1055  	Conn net.Conn
  1056  
  1057  	// Add a pointer to the entire tls handshake structure so that it can
  1058  	// be retrieved without hijacking the connection from higher-level
  1059  	// packages
  1060  	HandshakeLog *ServerHandshake
  1061  }
  1062  
  1063  func (info *ClientHelloInfo) MarshalJSON() ([]byte, error) {
  1064  	aux := struct {
  1065  		CipherSuites      []CipherSuite     `json:"cipher_suites"`
  1066  		ServerName        string            `json:"server_name,omitempty"`
  1067  		SupportedCurves   []CurveID         `json:"supported_curves,omitempty"`
  1068  		SupportedPoints   []PointFormat     `json:"supported_point_formats,omitempty"`
  1069  		SignatureSchemes  []SignatureScheme `json:"signature_schemes,omitempty"`
  1070  		SupportedProtos   []string          `json:"supported_protocols,omitempty"`
  1071  		SupportedVersions []TLSVersion      `json:"supported_versions,omitempty"`
  1072  		LocalAddr         string            `json:"local_address,omitempty"`
  1073  		RemoteAddr        string            `json:"remote_address,omitempty"`
  1074  	}{
  1075  		ServerName:       info.ServerName,
  1076  		SupportedCurves:  info.SupportedCurves,
  1077  		SignatureSchemes: info.SignatureSchemes,
  1078  		SupportedProtos:  info.SupportedProtos,
  1079  		// Do not marshal HandshakeLog IOT avoid duplication of data
  1080  		// HandshakeLog can be marshalled manually from
  1081  		// ClientHelloInfo.HandshakeLog or Conn.GetHandshakeLog()
  1082  	}
  1083  
  1084  	aux.CipherSuites = make([]CipherSuite, len(info.CipherSuites))
  1085  	for i, cipher := range info.CipherSuites {
  1086  		aux.CipherSuites[i] = CipherSuite(cipher)
  1087  	}
  1088  
  1089  	aux.SupportedPoints = make([]PointFormat, len(info.SupportedPoints))
  1090  	for i, format := range info.SupportedPoints {
  1091  		aux.SupportedPoints[i] = PointFormat(format)
  1092  	}
  1093  
  1094  	aux.SupportedVersions = make([]TLSVersion, len(info.SupportedVersions))
  1095  	for i, version := range info.SupportedVersions {
  1096  		aux.SupportedVersions[i] = TLSVersion(version)
  1097  	}
  1098  
  1099  	aux.LocalAddr = fmt.Sprintf("%s+%s", info.Conn.LocalAddr().String(), info.Conn.LocalAddr().Network())
  1100  	aux.RemoteAddr = fmt.Sprintf("%s+%s", info.Conn.RemoteAddr().String(), info.Conn.RemoteAddr().Network())
  1101  
  1102  	return json.Marshal(aux)
  1103  }
  1104  
  1105  func (info *ClientHelloInfo) UnmarshalJSON(b []byte) error {
  1106  	aux := struct {
  1107  		CipherSuites      []CipherSuite     `json:"cipher_suites"`
  1108  		ServerName        string            `json:"server_name,omitempty"`
  1109  		SupportedCurves   []CurveID         `json:"supported_curves,omitempty"`
  1110  		SupportedPoints   []PointFormat     `json:"supported_point_formats,omitempty"`
  1111  		SignatureSchemes  []SignatureScheme `json:"signature_schemes,omitempty"`
  1112  		SupportedProtos   []string          `json:"supported_protocols,omitempty"`
  1113  		SupportedVersions []TLSVersion      `json:"supported_versions,omitempty"`
  1114  		LocalAddr         string            `json:"local_address,omitempty"`
  1115  		RemoteAddr        string            `json:"remote_address,omitempty"`
  1116  	}{}
  1117  
  1118  	err := json.Unmarshal(b, &aux)
  1119  	if err != nil {
  1120  		return err
  1121  	}
  1122  
  1123  	splitLocalAddr := strings.Split(aux.LocalAddr, "+")
  1124  	if len(splitLocalAddr) != 2 {
  1125  		return errors.New("local_address is not unmarshalable")
  1126  	}
  1127  	splitRemoteAddr := strings.Split(aux.RemoteAddr, "+")
  1128  	if len(splitRemoteAddr) != 2 {
  1129  		return errors.New("remote_address is not unmarshalable")
  1130  	}
  1131  
  1132  	info.Conn = FakeConn{
  1133  		localAddr: FakeAddr{
  1134  			stringStr:  splitLocalAddr[0],
  1135  			networkStr: splitLocalAddr[1],
  1136  		},
  1137  		remoteAddr: FakeAddr{
  1138  			stringStr:  splitRemoteAddr[0],
  1139  			networkStr: splitLocalAddr[1],
  1140  		},
  1141  	}
  1142  
  1143  	info.ServerName = aux.ServerName
  1144  	info.SupportedCurves = aux.SupportedCurves
  1145  	info.SignatureSchemes = aux.SignatureSchemes
  1146  	info.SupportedProtos = aux.SupportedProtos
  1147  
  1148  	info.CipherSuites = make([]uint16, len(aux.CipherSuites))
  1149  	for i, cipher := range aux.CipherSuites {
  1150  		info.CipherSuites[i] = uint16(cipher)
  1151  	}
  1152  
  1153  	info.SupportedPoints = make([]uint8, len(aux.SupportedPoints))
  1154  	for i, format := range aux.SupportedPoints {
  1155  		info.SupportedPoints[i] = uint8(format)
  1156  	}
  1157  
  1158  	info.SupportedVersions = make([]uint16, len(aux.SupportedVersions))
  1159  	for i, version := range aux.SupportedVersions {
  1160  		info.SupportedVersions[i] = uint16(version)
  1161  	}
  1162  
  1163  	return nil
  1164  }
  1165  
  1166  // FakeConn and FakeAddr are to allow unmarshaling of tls objects that contain
  1167  // net.Conn objects
  1168  // With the exeption of recovering the net.Addr strings contained in the JSON,
  1169  // any attempt to use these objects will result in a runtime panic()
  1170  type FakeConn struct {
  1171  	localAddr  FakeAddr
  1172  	remoteAddr FakeAddr
  1173  }
  1174  
  1175  func (fConn FakeConn) Read(b []byte) (int, error) {
  1176  	panic("Read() on FakeConn")
  1177  }
  1178  
  1179  func (fConn FakeConn) Write(b []byte) (int, error) {
  1180  	panic("Write() on FakeConn")
  1181  }
  1182  
  1183  func (fConn FakeConn) Close() error {
  1184  	panic("Close() on FakeConn")
  1185  }
  1186  
  1187  func (fConn FakeConn) LocalAddr() net.Addr {
  1188  	return fConn.localAddr
  1189  }
  1190  
  1191  func (fConn FakeConn) RemoteAddr() net.Addr {
  1192  	return fConn.remoteAddr
  1193  }
  1194  
  1195  func (fConn FakeConn) SetDeadline(t time.Time) error {
  1196  	panic("SetDeadline() on FakeConn")
  1197  }
  1198  
  1199  func (fConn FakeConn) SetReadDeadline(t time.Time) error {
  1200  	panic("SetReadDeadline() on FakeConn")
  1201  }
  1202  
  1203  func (fConn FakeConn) SetWriteDeadline(t time.Time) error {
  1204  	panic("SetWriteDeadline() on FakeConn")
  1205  }
  1206  
  1207  type FakeAddr struct {
  1208  	networkStr string
  1209  	stringStr  string
  1210  }
  1211  
  1212  func (fAddr FakeAddr) String() string {
  1213  	return fAddr.stringStr
  1214  }
  1215  
  1216  func (fAddr FakeAddr) Network() string {
  1217  	return fAddr.networkStr
  1218  }
  1219  
  1220  type ConfigJSON struct {
  1221  	Certificates                   []Certificate                   `json:"certificates,omitempty"`
  1222  	RootCAs                        *x509.CertPool                  `json:"root_cas,omitempty"`
  1223  	NextProtos                     []string                        `json:"next_protocols,omitempty"`
  1224  	ServerName                     string                          `json:"server_name,omitempty"`
  1225  	ClientAuth                     ClientAuthType                  `json:"client_auth_type"`
  1226  	ClientCAs                      *x509.CertPool                  `json:"client_cas,omitempty"`
  1227  	InsecureSkipVerify             bool                            `json:"skip_verify"`
  1228  	CipherSuites                   []CipherSuite                   `json:"cipher_suites,omitempty"`
  1229  	PreferServerCipherSuites       bool                            `json:"prefer_server_cipher_suites"`
  1230  	SessionTicketsDisabled         bool                            `json:"session_tickets_disabled"`
  1231  	SessionTicketKey               []byte                          `json:"session_ticket_key,omitempty"`
  1232  	ClientSessionCache             ClientSessionCache              `json:"client_session_cache,omitempty"`
  1233  	MinVersion                     TLSVersion                      `json:"min_tls_version,omitempty"`
  1234  	MaxVersion                     TLSVersion                      `json:"max_tls_version,omitempty"`
  1235  	CurvePreferences               []CurveID                       `json:"curve_preferences,omitempty"`
  1236  	ExplicitCurvePreferences       bool                            `json:"explicit_curve_preferences"`
  1237  	ForceSuites                    bool                            `json:"force_cipher_suites"`
  1238  	ExportRSAKey                   *rsa.PrivateKey                 `json:"export_rsa_key,omitempty"`
  1239  	HeartbeatEnabled               bool                            `json:"heartbeat_enabled"`
  1240  	ClientDSAEnabled               bool                            `json:"client_dsa_enabled"`
  1241  	ExtendedRandom                 bool                            `json:"extended_random_enabled"`
  1242  	ForceSessionTicketExt          bool                            `json:"session_ticket_ext_enabled"`
  1243  	ExtendedMasterSecret           bool                            `json:"extended_master_secret_enabled"`
  1244  	SignedCertificateTimestampExt  bool                            `json:"sct_ext_enabled"`
  1245  	ClientRandom                   []byte                          `json:"client_random,omitempty"`
  1246  	ExternalClientHello            []byte                          `json:"external_client_hello,omitempty"`
  1247  	ClientFingerprintConfiguration *ClientFingerprintConfiguration `json:"client_fingerprint_config,omitempty"`
  1248  	DontBufferHandshakes           bool                            `json:"dont_buffer_handshakes"`
  1249  }
  1250  
  1251  func (config *Config) MarshalJSON() ([]byte, error) {
  1252  	aux := new(ConfigJSON)
  1253  
  1254  	aux.Certificates = config.Certificates
  1255  	aux.RootCAs = config.RootCAs
  1256  	aux.NextProtos = config.NextProtos
  1257  	aux.ServerName = config.ServerName
  1258  	aux.ClientAuth = config.ClientAuth
  1259  	aux.ClientCAs = config.ClientCAs
  1260  	aux.InsecureSkipVerify = config.InsecureSkipVerify
  1261  
  1262  	ciphers := config.cipherSuites()
  1263  	aux.CipherSuites = make([]CipherSuite, len(ciphers))
  1264  	for i, aCipher := range ciphers {
  1265  		aux.CipherSuites[i] = CipherSuite(aCipher)
  1266  	}
  1267  
  1268  	aux.PreferServerCipherSuites = config.PreferServerCipherSuites
  1269  	aux.SessionTicketsDisabled = config.SessionTicketsDisabled
  1270  	aux.SessionTicketKey = config.SessionTicketKey[:]
  1271  	aux.ClientSessionCache = config.ClientSessionCache
  1272  	aux.MinVersion = TLSVersion(config.minVersion())
  1273  	aux.MaxVersion = TLSVersion(config.maxVersion())
  1274  	aux.CurvePreferences = config.curvePreferences()
  1275  	aux.ExplicitCurvePreferences = config.ExplicitCurvePreferences
  1276  	aux.ForceSuites = config.ForceSuites
  1277  	aux.ExportRSAKey = config.ExportRSAKey
  1278  	aux.HeartbeatEnabled = config.HeartbeatEnabled
  1279  	aux.ClientDSAEnabled = config.ClientDSAEnabled
  1280  	aux.ExtendedRandom = config.ExtendedRandom
  1281  	aux.ForceSessionTicketExt = config.ForceSessionTicketExt
  1282  	aux.ExtendedMasterSecret = config.ExtendedMasterSecret
  1283  	aux.SignedCertificateTimestampExt = config.SignedCertificateTimestampExt
  1284  	aux.ClientRandom = config.ClientRandom
  1285  	aux.ExternalClientHello = config.ExternalClientHello
  1286  	aux.ClientFingerprintConfiguration = config.ClientFingerprintConfiguration
  1287  	aux.DontBufferHandshakes = config.DontBufferHandshakes
  1288  
  1289  	return json.Marshal(aux)
  1290  }
  1291  
  1292  func (config *Config) UnmarshalJSON(b []byte) error {
  1293  	panic("unimplemented")
  1294  }
  1295  
  1296  // Error type raised by doFullHandshake() when the CertsOnly option is
  1297  // in use
  1298  var ErrCertsOnly = errors.New("handshake abandoned per CertsOnly option")