github.com/3andne/restls-client-go@v0.1.6/u_common.go (about)

     1  // Copyright 2017 Google Inc. 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  	"crypto/hmac"
     9  	"crypto/sha512"
    10  	"encoding/json"
    11  	"errors"
    12  	"fmt"
    13  	"hash"
    14  	"log"
    15  
    16  	"github.com/3andne/restls-client-go/internal/helper"
    17  	"golang.org/x/crypto/cryptobyte"
    18  )
    19  
    20  // Naming convention:
    21  // Unsupported things are prefixed with "Fake"
    22  // Things, supported by utls, but not crypto/tls' are prefixed with "utls"
    23  // Supported things, that have changed their ID are prefixed with "Old"
    24  // Supported but disabled things are prefixed with "Disabled". We will _enable_ them.
    25  
    26  // TLS handshake message types.
    27  const (
    28  	utlsTypeEncryptedExtensions uint8 = 8 // implemention incomplete by crypto/tls
    29  	// https://datatracker.ietf.org/doc/html/rfc8879#section-7.2
    30  	utlsTypeCompressedCertificate uint8 = 25
    31  )
    32  
    33  // TLS
    34  const (
    35  	extensionNextProtoNeg uint16 = 13172 // not IANA assigned. Removed by crypto/tls since Nov 2019
    36  
    37  	utlsExtensionPadding             uint16 = 21
    38  	utlsExtensionCompressCertificate uint16 = 27    // https://datatracker.ietf.org/doc/html/rfc8879#section-7.1
    39  	utlsExtensionApplicationSettings uint16 = 17513 // not IANA assigned
    40  	utlsFakeExtensionCustom          uint16 = 1234  // not IANA assigned, for ALPS
    41  
    42  	// extensions with 'fake' prefix break connection, if server echoes them back
    43  	fakeExtensionEncryptThenMAC       uint16 = 22
    44  	fakeExtensionTokenBinding         uint16 = 24
    45  	fakeExtensionDelegatedCredentials uint16 = 34
    46  	fakeExtensionPreSharedKey         uint16 = 41
    47  	fakeOldExtensionChannelID         uint16 = 30031 // not IANA assigned
    48  	fakeExtensionChannelID            uint16 = 30032 // not IANA assigned
    49  )
    50  
    51  const (
    52  	OLD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   = uint16(0xcc13)
    53  	OLD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = uint16(0xcc14)
    54  
    55  	DISABLED_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = uint16(0xc024)
    56  	DISABLED_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   = uint16(0xc028)
    57  	DISABLED_TLS_RSA_WITH_AES_256_CBC_SHA256         = uint16(0x003d)
    58  
    59  	FAKE_OLD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = uint16(0xcc15) // we can try to craft these ciphersuites
    60  	FAKE_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256           = uint16(0x009e) // from existing pieces, if needed
    61  
    62  	FAKE_TLS_DHE_RSA_WITH_AES_128_CBC_SHA    = uint16(0x0033)
    63  	FAKE_TLS_DHE_RSA_WITH_AES_256_CBC_SHA    = uint16(0x0039)
    64  	FAKE_TLS_RSA_WITH_RC4_128_MD5            = uint16(0x0004)
    65  	FAKE_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = uint16(0x009f)
    66  	FAKE_TLS_DHE_DSS_WITH_AES_128_CBC_SHA    = uint16(0x0032)
    67  	FAKE_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = uint16(0x006b)
    68  	FAKE_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = uint16(0x0067)
    69  	FAKE_TLS_EMPTY_RENEGOTIATION_INFO_SCSV   = uint16(0x00ff)
    70  
    71  	// https://docs.microsoft.com/en-us/dotnet/api/system.net.security.tlsciphersuite?view=netcore-3.1
    72  	FAKE_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = uint16(0xc008)
    73  )
    74  
    75  const (
    76  	CurveSECP256R1 CurveID = 0x0017
    77  	CurveSECP384R1 CurveID = 0x0018
    78  	CurveSECP521R1 CurveID = 0x0019
    79  	CurveX25519    CurveID = 0x001d
    80  
    81  	FakeCurveFFDHE2048 CurveID = 0x0100
    82  	FakeCurveFFDHE3072 CurveID = 0x0101
    83  	FakeCurveFFDHE4096 CurveID = 0x0102
    84  	FakeCurveFFDHE6144 CurveID = 0x0103
    85  	FakeCurveFFDHE8192 CurveID = 0x0104
    86  )
    87  
    88  // Other things
    89  const (
    90  	fakeRecordSizeLimit uint16 = 0x001c
    91  )
    92  
    93  // newest signatures
    94  var (
    95  	FakePKCS1WithSHA224 SignatureScheme = 0x0301
    96  	FakeECDSAWithSHA224 SignatureScheme = 0x0303
    97  
    98  	FakeSHA1WithDSA   SignatureScheme = 0x0202
    99  	FakeSHA256WithDSA SignatureScheme = 0x0402
   100  
   101  	// fakeEd25519 = SignatureAndHash{0x08, 0x07}
   102  	// fakeEd448 = SignatureAndHash{0x08, 0x08}
   103  )
   104  
   105  // fake curves(groups)
   106  var (
   107  	FakeFFDHE2048 = uint16(0x0100)
   108  	FakeFFDHE3072 = uint16(0x0101)
   109  )
   110  
   111  // https://tools.ietf.org/html/draft-ietf-tls-certificate-compression-04
   112  type CertCompressionAlgo uint16
   113  
   114  const (
   115  	CertCompressionZlib   CertCompressionAlgo = 0x0001
   116  	CertCompressionBrotli CertCompressionAlgo = 0x0002
   117  	CertCompressionZstd   CertCompressionAlgo = 0x0003
   118  )
   119  
   120  const (
   121  	PskModePlain uint8 = pskModePlain
   122  	PskModeDHE   uint8 = pskModeDHE
   123  )
   124  
   125  type ClientHelloID struct {
   126  	Client string
   127  
   128  	// Version specifies version of a mimicked clients (e.g. browsers).
   129  	// Not used in randomized, custom handshake, and default Go.
   130  	Version string
   131  
   132  	// Seed is only used for randomized fingerprints to seed PRNG.
   133  	// Must not be modified once set.
   134  	Seed *PRNGSeed
   135  
   136  	// Weights are only used for randomized fingerprints in func
   137  	// generateRandomizedSpec(). Must not be modified once set.
   138  	Weights *Weights
   139  }
   140  
   141  func (p *ClientHelloID) Str() string {
   142  	return fmt.Sprintf("%s-%s", p.Client, p.Version)
   143  }
   144  
   145  func (p *ClientHelloID) IsSet() bool {
   146  	return (p.Client == "") && (p.Version == "")
   147  }
   148  
   149  const (
   150  	// clients
   151  	helloGolang           = "Golang"
   152  	helloRandomized       = "Randomized"
   153  	helloRandomizedALPN   = "Randomized-ALPN"
   154  	helloRandomizedNoALPN = "Randomized-NoALPN"
   155  	helloCustom           = "Custom"
   156  	helloFirefox          = "Firefox"
   157  	helloChrome           = "Chrome"
   158  	helloIOS              = "iOS"
   159  	helloAndroid          = "Android"
   160  	helloEdge             = "Edge"
   161  	helloSafari           = "Safari"
   162  	hello360              = "360Browser"
   163  	helloQQ               = "QQBrowser"
   164  
   165  	// versions
   166  	helloAutoVers = "0"
   167  )
   168  
   169  type ClientHelloSpec struct {
   170  	CipherSuites       []uint16       // nil => default
   171  	CompressionMethods []uint8        // nil => no compression
   172  	Extensions         []TLSExtension // nil => no extensions
   173  
   174  	TLSVersMin uint16 // [1.0-1.3] default: parse from .Extensions, if SupportedVersions ext is not present => 1.0
   175  	TLSVersMax uint16 // [1.2-1.3] default: parse from .Extensions, if SupportedVersions ext is not present => 1.2
   176  
   177  	// GreaseStyle: currently only random
   178  	// sessionID may or may not depend on ticket; nil => random
   179  	GetSessionID func(ticket []byte) [32]byte
   180  
   181  	// TLSFingerprintLink string // ?? link to tlsfingerprint.io for informational purposes
   182  }
   183  
   184  // ReadCipherSuites is a helper function to construct a list of cipher suites from
   185  // a []byte into []uint16.
   186  //
   187  // example: []byte{0x13, 0x01, 0x13, 0x02, 0x13, 0x03} => []uint16{0x1301, 0x1302, 0x1303}
   188  func (chs *ClientHelloSpec) ReadCipherSuites(b []byte) error {
   189  	cipherSuites := []uint16{}
   190  	s := cryptobyte.String(b)
   191  	for !s.Empty() {
   192  		var suite uint16
   193  		if !s.ReadUint16(&suite) {
   194  			return errors.New("unable to read ciphersuite")
   195  		}
   196  		cipherSuites = append(cipherSuites, unGREASEUint16(suite))
   197  	}
   198  	chs.CipherSuites = cipherSuites
   199  	return nil
   200  }
   201  
   202  // ReadCompressionMethods is a helper function to construct a list of compression
   203  // methods from a []byte into []uint8.
   204  func (chs *ClientHelloSpec) ReadCompressionMethods(compressionMethods []byte) error {
   205  	chs.CompressionMethods = compressionMethods
   206  	return nil
   207  }
   208  
   209  // ReadTLSExtensions is a helper function to construct a list of TLS extensions from
   210  // a byte slice into []TLSExtension.
   211  //
   212  // If keepPSK is not set, the PSK extension will cause an error.
   213  func (chs *ClientHelloSpec) ReadTLSExtensions(b []byte, allowBluntMimicry bool) error {
   214  	extensions := cryptobyte.String(b)
   215  	for !extensions.Empty() {
   216  		var extension uint16
   217  		var extData cryptobyte.String
   218  		if !extensions.ReadUint16(&extension) {
   219  			return fmt.Errorf("unable to read extension ID")
   220  		}
   221  		if !extensions.ReadUint16LengthPrefixed(&extData) {
   222  			return fmt.Errorf("unable to read data for extension %x", extension)
   223  		}
   224  
   225  		ext := ExtensionFromID(extension)
   226  		extWriter, ok := ext.(TLSExtensionWriter)
   227  		if ext != nil && ok { // known extension and implements TLSExtensionWriter properly
   228  			if extension == extensionSupportedVersions {
   229  				chs.TLSVersMin = 0
   230  				chs.TLSVersMax = 0
   231  			}
   232  			if _, err := extWriter.Write(extData); err != nil {
   233  				return err
   234  			}
   235  
   236  			chs.Extensions = append(chs.Extensions, extWriter)
   237  		} else {
   238  			if allowBluntMimicry {
   239  				chs.Extensions = append(chs.Extensions, &GenericExtension{extension, extData})
   240  			} else {
   241  				return fmt.Errorf("unsupported extension %d", extension)
   242  			}
   243  		}
   244  	}
   245  	return nil
   246  }
   247  
   248  func (chs *ClientHelloSpec) AlwaysAddPadding() {
   249  	alreadyHasPadding := false
   250  	for _, ext := range chs.Extensions {
   251  		if _, ok := ext.(*UtlsPaddingExtension); ok {
   252  			alreadyHasPadding = true
   253  			break
   254  		}
   255  		if _, ok := ext.(*FakePreSharedKeyExtension); ok {
   256  			alreadyHasPadding = true // PSK must be last, so we don't need to add padding
   257  			break
   258  		}
   259  	}
   260  	if !alreadyHasPadding {
   261  		chs.Extensions = append(chs.Extensions, &UtlsPaddingExtension{GetPaddingLen: BoringPaddingStyle})
   262  	}
   263  }
   264  
   265  // Import TLS ClientHello data from client.tlsfingerprint.io:8443
   266  //
   267  // data is a map of []byte with following keys:
   268  // - cipher_suites: [10, 10, 19, 1, 19, 2, 19, 3, 192, 43, 192, 47, 192, 44, 192, 48, 204, 169, 204, 168, 192, 19, 192, 20, 0, 156, 0, 157, 0, 47, 0, 53]
   269  // - compression_methods: [0] => null
   270  // - extensions: [10, 10, 255, 1, 0, 45, 0, 35, 0, 16, 68, 105, 0, 11, 0, 43, 0, 18, 0, 13, 0, 0, 0, 10, 0, 27, 0, 5, 0, 51, 0, 23, 10, 10, 0, 21]
   271  // - pt_fmts (ec_point_formats): [1, 0] => len: 1, content: 0x00
   272  // - sig_algs (signature_algorithms): [0, 16, 4, 3, 8, 4, 4, 1, 5, 3, 8, 5, 5, 1, 8, 6, 6, 1] => len: 16, content: 0x0403, 0x0804, 0x0401, 0x0503, 0x0805, 0x0501, 0x0806, 0x0601
   273  // - supported_versions: [10, 10, 3, 4, 3, 3] => 0x0a0a, 0x0304, 0x0303 (GREASE, TLS 1.3, TLS 1.2)
   274  // - curves (named_groups, supported_groups): [0, 8, 10, 10, 0, 29, 0, 23, 0, 24] => len: 8, content: GREASE, 0x001d, 0x0017, 0x0018
   275  // - alpn: [0, 12, 2, 104, 50, 8, 104, 116, 116, 112, 47, 49, 46, 49] => len: 12, content: h2, http/1.1
   276  // - key_share: [10, 10, 0, 1, 0, 29, 0, 32] => {group: 0x0a0a, len:1}, {group: 0x001d, len:32}
   277  // - psk_key_exchange_modes: [1] => psk_dhe_ke(0x01)
   278  // - cert_compression_algs: [2, 0, 2] => brotli (0x0002)
   279  // - record_size_limit: [0, 255] => 255
   280  //
   281  // TLSVersMin/TLSVersMax are set to 0 if supported_versions is present.
   282  // To prevent conflict, they should be set manually if needed BEFORE calling this function.
   283  func (chs *ClientHelloSpec) ImportTLSClientHello(data map[string][]byte) error {
   284  	var tlsExtensionTypes []uint16
   285  	var err error
   286  
   287  	if data["cipher_suites"] == nil {
   288  		return errors.New("cipher_suites is required")
   289  	}
   290  	chs.CipherSuites, err = helper.Uint8to16(data["cipher_suites"])
   291  	if err != nil {
   292  		return err
   293  	}
   294  
   295  	if data["compression_methods"] == nil {
   296  		return errors.New("compression_methods is required")
   297  	}
   298  	chs.CompressionMethods = data["compression_methods"]
   299  
   300  	if data["extensions"] == nil {
   301  		return errors.New("extensions is required")
   302  	}
   303  	tlsExtensionTypes, err = helper.Uint8to16(data["extensions"])
   304  	if err != nil {
   305  		return err
   306  	}
   307  
   308  	for _, extType := range tlsExtensionTypes {
   309  		extension := ExtensionFromID(extType)
   310  		extWriter, ok := extension.(TLSExtensionWriter)
   311  		if !ok {
   312  			return fmt.Errorf("unsupported extension %d", extType)
   313  		}
   314  		if extension == nil || !ok {
   315  			log.Printf("[Warning] Unsupported extension %d added as a &GenericExtension without Data", extType)
   316  			chs.Extensions = append(chs.Extensions, &GenericExtension{extType, []byte{}})
   317  		} else {
   318  			switch extType {
   319  			case extensionSupportedPoints:
   320  				if data["pt_fmts"] == nil {
   321  					return errors.New("pt_fmts is required")
   322  				}
   323  				_, err = extWriter.Write(data["pt_fmts"])
   324  				if err != nil {
   325  					return err
   326  				}
   327  			case extensionSignatureAlgorithms:
   328  				if data["sig_algs"] == nil {
   329  					return errors.New("sig_algs is required")
   330  				}
   331  				_, err = extWriter.Write(data["sig_algs"])
   332  				if err != nil {
   333  					return err
   334  				}
   335  			case extensionSupportedVersions:
   336  				chs.TLSVersMin = 0
   337  				chs.TLSVersMax = 0
   338  
   339  				if data["supported_versions"] == nil {
   340  					return errors.New("supported_versions is required")
   341  				}
   342  
   343  				// need to add uint8 length prefix
   344  				fixedData := make([]byte, len(data["supported_versions"])+1)
   345  				fixedData[0] = uint8(len(data["supported_versions"]) & 0xff)
   346  				copy(fixedData[1:], data["supported_versions"])
   347  				_, err = extWriter.Write(fixedData)
   348  				if err != nil {
   349  					return err
   350  				}
   351  			case extensionSupportedCurves:
   352  				if data["curves"] == nil {
   353  					return errors.New("curves is required")
   354  				}
   355  
   356  				_, err = extWriter.Write(data["curves"])
   357  				if err != nil {
   358  					return err
   359  				}
   360  			case extensionALPN:
   361  				if data["alpn"] == nil {
   362  					return errors.New("alpn is required")
   363  				}
   364  
   365  				_, err = extWriter.Write(data["alpn"])
   366  				if err != nil {
   367  					return err
   368  				}
   369  			case extensionKeyShare:
   370  				if data["key_share"] == nil {
   371  					return errors.New("key_share is required")
   372  				}
   373  
   374  				// need to add (zero) data per each key share, [10, 10, 0, 1] => [10, 10, 0, 1, 0]
   375  				fixedData := make([]byte, 0)
   376  				for i := 0; i < len(data["key_share"]); i += 4 {
   377  					fixedData = append(fixedData, data["key_share"][i:i+4]...)
   378  					for j := 0; j < int(data["key_share"][i+3]); j++ {
   379  						fixedData = append(fixedData, 0)
   380  					}
   381  				}
   382  				// add uint16 length prefix
   383  				fixedData = append([]byte{uint8(len(fixedData) >> 8), uint8(len(fixedData) & 0xff)}, fixedData...)
   384  
   385  				_, err = extWriter.Write(fixedData)
   386  				if err != nil {
   387  					return err
   388  				}
   389  			case extensionPSKModes:
   390  				if data["psk_key_exchange_modes"] == nil {
   391  					return errors.New("psk_key_exchange_modes is required")
   392  				}
   393  
   394  				// need to add uint8 length prefix
   395  				fixedData := make([]byte, len(data["psk_key_exchange_modes"])+1)
   396  				fixedData[0] = uint8(len(data["psk_key_exchange_modes"]) & 0xff)
   397  				copy(fixedData[1:], data["psk_key_exchange_modes"])
   398  				_, err = extWriter.Write(fixedData)
   399  				if err != nil {
   400  					return err
   401  				}
   402  			case utlsExtensionCompressCertificate:
   403  				if data["cert_compression_algs"] == nil {
   404  					return errors.New("cert_compression_algs is required")
   405  				}
   406  
   407  				// need to add uint8 length prefix
   408  				fixedData := make([]byte, len(data["cert_compression_algs"])+1)
   409  				fixedData[0] = uint8(len(data["cert_compression_algs"]) & 0xff)
   410  				copy(fixedData[1:], data["cert_compression_algs"])
   411  				_, err = extWriter.Write(fixedData)
   412  				if err != nil {
   413  					return err
   414  				}
   415  			case fakeRecordSizeLimit:
   416  				if data["record_size_limit"] == nil {
   417  					return errors.New("record_size_limit is required")
   418  				}
   419  
   420  				_, err = extWriter.Write(data["record_size_limit"]) // uint16 as []byte
   421  				if err != nil {
   422  					return err
   423  				}
   424  			case utlsExtensionApplicationSettings:
   425  				// TODO: tlsfingerprint.io should record/provide application settings data
   426  				extWriter.(*ApplicationSettingsExtension).SupportedProtocols = []string{"h2"}
   427  			case extensionPreSharedKey:
   428  				log.Printf("[Warning] PSK extension added without data")
   429  			default:
   430  				if !isGREASEUint16(extType) {
   431  					log.Printf("[Warning] extension %d added without data", extType)
   432  				} /*else {
   433  					log.Printf("[Warning] GREASE extension added but ID/Data discarded. They will be automatically re-GREASEd on ApplyPreset() call.")
   434  				}*/
   435  			}
   436  			chs.Extensions = append(chs.Extensions, extWriter)
   437  		}
   438  	}
   439  	return nil
   440  }
   441  
   442  // ImportTLSClientHelloFromJSON imports ClientHelloSpec from JSON data from client.tlsfingerprint.io format
   443  //
   444  // It calls ImportTLSClientHello internally after unmarshaling JSON data into map[string][]byte
   445  func (chs *ClientHelloSpec) ImportTLSClientHelloFromJSON(jsonB []byte) error {
   446  	var data map[string][]byte
   447  	err := json.Unmarshal(jsonB, &data)
   448  	if err != nil {
   449  		return err
   450  	}
   451  	return chs.ImportTLSClientHello(data)
   452  }
   453  
   454  // FromRaw converts a ClientHello message in the form of raw bytes into a ClientHelloSpec.
   455  func (chs *ClientHelloSpec) FromRaw(raw []byte, allowBluntMimicry ...bool) error {
   456  	if chs == nil {
   457  		return errors.New("cannot unmarshal into nil ClientHelloSpec")
   458  	}
   459  
   460  	var bluntMimicry = false
   461  	if len(allowBluntMimicry) == 1 {
   462  		bluntMimicry = allowBluntMimicry[0]
   463  	}
   464  
   465  	*chs = ClientHelloSpec{} // reset
   466  	s := cryptobyte.String(raw)
   467  
   468  	var contentType uint8
   469  	var recordVersion uint16
   470  	if !s.ReadUint8(&contentType) || // record type
   471  		!s.ReadUint16(&recordVersion) || !s.Skip(2) { // record version and length
   472  		return errors.New("unable to read record type, version, and length")
   473  	}
   474  
   475  	if recordType(contentType) != recordTypeHandshake {
   476  		return errors.New("record is not a handshake")
   477  	}
   478  
   479  	var handshakeVersion uint16
   480  	var handshakeType uint8
   481  
   482  	if !s.ReadUint8(&handshakeType) || !s.Skip(3) || // message type and 3 byte length
   483  		!s.ReadUint16(&handshakeVersion) || !s.Skip(32) { // 32 byte random
   484  		return errors.New("unable to read handshake message type, length, and random")
   485  	}
   486  
   487  	if handshakeType != typeClientHello {
   488  		return errors.New("handshake message is not a ClientHello")
   489  	}
   490  
   491  	chs.TLSVersMin = recordVersion
   492  	chs.TLSVersMax = handshakeVersion
   493  
   494  	var ignoredSessionID cryptobyte.String
   495  	if !s.ReadUint8LengthPrefixed(&ignoredSessionID) {
   496  		return errors.New("unable to read session id")
   497  	}
   498  
   499  	// CipherSuites
   500  	var cipherSuitesBytes cryptobyte.String
   501  	if !s.ReadUint16LengthPrefixed(&cipherSuitesBytes) {
   502  		return errors.New("unable to read ciphersuites")
   503  	}
   504  
   505  	if err := chs.ReadCipherSuites(cipherSuitesBytes); err != nil {
   506  		return err
   507  	}
   508  
   509  	// CompressionMethods
   510  	var compressionMethods cryptobyte.String
   511  	if !s.ReadUint8LengthPrefixed(&compressionMethods) {
   512  		return errors.New("unable to read compression methods")
   513  	}
   514  
   515  	if err := chs.ReadCompressionMethods(compressionMethods); err != nil {
   516  		return err
   517  	}
   518  
   519  	if s.Empty() {
   520  		// Extensions are optional
   521  		return nil
   522  	}
   523  
   524  	var extensions cryptobyte.String
   525  	if !s.ReadUint16LengthPrefixed(&extensions) {
   526  		return errors.New("unable to read extensions data")
   527  	}
   528  
   529  	if err := chs.ReadTLSExtensions(extensions, bluntMimicry); err != nil {
   530  		return err
   531  	}
   532  
   533  	return nil
   534  }
   535  
   536  // UnmarshalJSON unmarshals a ClientHello message in the form of JSON into a ClientHelloSpec.
   537  func (chs *ClientHelloSpec) UnmarshalJSON(jsonB []byte) error {
   538  	var chsju ClientHelloSpecJSONUnmarshaler
   539  	if err := json.Unmarshal(jsonB, &chsju); err != nil {
   540  		return err
   541  	}
   542  
   543  	*chs = chsju.ClientHelloSpec()
   544  	return nil
   545  }
   546  
   547  var (
   548  	// HelloGolang will use default "crypto/tls" handshake marshaling codepath, which WILL
   549  	// overwrite your changes to Hello(Config, Session are fine).
   550  	// You might want to call BuildHandshakeState() before applying any changes.
   551  	// UConn.Extensions will be completely ignored.
   552  	HelloGolang = ClientHelloID{helloGolang, helloAutoVers, nil, nil}
   553  
   554  	// HelloCustom will prepare ClientHello with empty uconn.Extensions so you can fill it with
   555  	// TLSExtensions manually or use ApplyPreset function
   556  	HelloCustom = ClientHelloID{helloCustom, helloAutoVers, nil, nil}
   557  
   558  	// HelloRandomized* randomly adds/reorders extensions, ciphersuites, etc.
   559  	HelloRandomized       = ClientHelloID{helloRandomized, helloAutoVers, nil, nil}
   560  	HelloRandomizedALPN   = ClientHelloID{helloRandomizedALPN, helloAutoVers, nil, nil}
   561  	HelloRandomizedNoALPN = ClientHelloID{helloRandomizedNoALPN, helloAutoVers, nil, nil}
   562  
   563  	// The rest will will parrot given browser.
   564  	HelloFirefox_Auto = HelloFirefox_105
   565  	HelloFirefox_55   = ClientHelloID{helloFirefox, "55", nil, nil}
   566  	HelloFirefox_56   = ClientHelloID{helloFirefox, "56", nil, nil}
   567  	HelloFirefox_63   = ClientHelloID{helloFirefox, "63", nil, nil}
   568  	HelloFirefox_65   = ClientHelloID{helloFirefox, "65", nil, nil}
   569  	HelloFirefox_99   = ClientHelloID{helloFirefox, "99", nil, nil}
   570  	HelloFirefox_102  = ClientHelloID{helloFirefox, "102", nil, nil}
   571  	HelloFirefox_105  = ClientHelloID{helloFirefox, "105", nil, nil}
   572  
   573  	HelloChrome_Auto        = HelloChrome_106_Shuffle
   574  	HelloChrome_58          = ClientHelloID{helloChrome, "58", nil, nil}
   575  	HelloChrome_62          = ClientHelloID{helloChrome, "62", nil, nil}
   576  	HelloChrome_70          = ClientHelloID{helloChrome, "70", nil, nil}
   577  	HelloChrome_72          = ClientHelloID{helloChrome, "72", nil, nil}
   578  	HelloChrome_83          = ClientHelloID{helloChrome, "83", nil, nil}
   579  	HelloChrome_87          = ClientHelloID{helloChrome, "87", nil, nil}
   580  	HelloChrome_96          = ClientHelloID{helloChrome, "96", nil, nil}
   581  	HelloChrome_100         = ClientHelloID{helloChrome, "100", nil, nil}
   582  	HelloChrome_102         = ClientHelloID{helloChrome, "102", nil, nil}
   583  	HelloChrome_106_Shuffle = ClientHelloID{helloChrome, "106", nil, nil} // beta: shuffler enabled starting from 106
   584  
   585  	// Chrome with PSK: Chrome start sending this ClientHello after doing TLS 1.3 handshake with the same server.
   586  	HelloChrome_100_PSK      = ClientHelloID{helloChrome, "100_PSK", nil, nil} // beta: PSK extension added. uTLS doesn't fully support PSK. Use at your own risk.
   587  	HelloChrome_112_PSK_Shuf = ClientHelloID{helloChrome, "112_PSK", nil, nil} // beta: PSK extension added. uTLS doesn't fully support PSK. Use at your own risk.
   588  
   589  	HelloIOS_Auto = HelloIOS_14
   590  	HelloIOS_11_1 = ClientHelloID{helloIOS, "111", nil, nil} // legacy "111" means 11.1
   591  	HelloIOS_12_1 = ClientHelloID{helloIOS, "12.1", nil, nil}
   592  	HelloIOS_13   = ClientHelloID{helloIOS, "13", nil, nil}
   593  	HelloIOS_14   = ClientHelloID{helloIOS, "14", nil, nil}
   594  
   595  	HelloAndroid_11_OkHttp = ClientHelloID{helloAndroid, "11", nil, nil}
   596  
   597  	HelloEdge_Auto = HelloEdge_85 // HelloEdge_106 seems to be incompatible with this library
   598  	HelloEdge_85   = ClientHelloID{helloEdge, "85", nil, nil}
   599  	HelloEdge_106  = ClientHelloID{helloEdge, "106", nil, nil}
   600  
   601  	HelloSafari_Auto = HelloSafari_16_0
   602  	HelloSafari_16_0 = ClientHelloID{helloSafari, "16.0", nil, nil}
   603  
   604  	Hello360_Auto = Hello360_7_5 // Hello360_11_0 seems to be incompatible with this library
   605  	Hello360_7_5  = ClientHelloID{hello360, "7.5", nil, nil}
   606  	Hello360_11_0 = ClientHelloID{hello360, "11.0", nil, nil}
   607  
   608  	HelloQQ_Auto = HelloQQ_11_1
   609  	HelloQQ_11_1 = ClientHelloID{helloQQ, "11.1", nil, nil}
   610  )
   611  
   612  type Weights struct {
   613  	Extensions_Append_ALPN                             float64
   614  	TLSVersMax_Set_VersionTLS13                        float64
   615  	CipherSuites_Remove_RandomCiphers                  float64
   616  	SigAndHashAlgos_Append_ECDSAWithSHA1               float64
   617  	SigAndHashAlgos_Append_ECDSAWithP521AndSHA512      float64
   618  	SigAndHashAlgos_Append_PSSWithSHA256               float64
   619  	SigAndHashAlgos_Append_PSSWithSHA384_PSSWithSHA512 float64
   620  	CurveIDs_Append_X25519                             float64
   621  	CurveIDs_Append_CurveP521                          float64
   622  	Extensions_Append_Padding                          float64
   623  	Extensions_Append_Status                           float64
   624  	Extensions_Append_SCT                              float64
   625  	Extensions_Append_Reneg                            float64
   626  	Extensions_Append_EMS                              float64
   627  	FirstKeyShare_Set_CurveP256                        float64
   628  	Extensions_Append_ALPS                             float64
   629  }
   630  
   631  // Do not modify them directly as they may being used. If you
   632  // want to use your custom weights, please make a copy first.
   633  var DefaultWeights = Weights{
   634  	Extensions_Append_ALPN:                             0.7,
   635  	TLSVersMax_Set_VersionTLS13:                        0.4,
   636  	CipherSuites_Remove_RandomCiphers:                  0.4,
   637  	SigAndHashAlgos_Append_ECDSAWithSHA1:               0.63,
   638  	SigAndHashAlgos_Append_ECDSAWithP521AndSHA512:      0.59,
   639  	SigAndHashAlgos_Append_PSSWithSHA256:               0.51,
   640  	SigAndHashAlgos_Append_PSSWithSHA384_PSSWithSHA512: 0.9,
   641  	CurveIDs_Append_X25519:                             0.71,
   642  	CurveIDs_Append_CurveP521:                          0.46,
   643  	Extensions_Append_Padding:                          0.62,
   644  	Extensions_Append_Status:                           0.74,
   645  	Extensions_Append_SCT:                              0.46,
   646  	Extensions_Append_Reneg:                            0.75,
   647  	Extensions_Append_EMS:                              0.77,
   648  	FirstKeyShare_Set_CurveP256:                        0.25,
   649  	Extensions_Append_ALPS:                             0.33,
   650  }
   651  
   652  // based on spec's GreaseStyle, GREASE_PLACEHOLDER may be replaced by another GREASE value
   653  // https://tools.ietf.org/html/draft-ietf-tls-grease-01
   654  const GREASE_PLACEHOLDER = 0x0a0a
   655  
   656  func isGREASEUint16(v uint16) bool {
   657  	// First byte is same as second byte
   658  	// and lowest nibble is 0xa
   659  	return ((v >> 8) == v&0xff) && v&0xf == 0xa
   660  }
   661  
   662  func unGREASEUint16(v uint16) uint16 {
   663  	if isGREASEUint16(v) {
   664  		return GREASE_PLACEHOLDER
   665  	} else {
   666  		return v
   667  	}
   668  }
   669  
   670  // utlsMacSHA384 returns a SHA-384 based MAC. These are only supported in TLS 1.2
   671  // so the given version is ignored.
   672  func utlsMacSHA384(key []byte) hash.Hash {
   673  	return hmac.New(sha512.New384, key)
   674  }
   675  
   676  var utlsSupportedCipherSuites []*cipherSuite
   677  
   678  func init() {
   679  	utlsSupportedCipherSuites = append(cipherSuites, []*cipherSuite{
   680  		{OLD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 32, 0, 12, ecdheRSAKA,
   681  			suiteECDHE | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
   682  		{OLD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 32, 0, 12, ecdheECDSAKA,
   683  			suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadChaCha20Poly1305},
   684  	}...)
   685  }
   686  
   687  // EnableWeakCiphers allows utls connections to continue in some cases, when weak cipher was chosen.
   688  // This provides better compatibility with servers on the web, but weakens security. Feel free
   689  // to use this option if you establish additional secure connection inside of utls connection.
   690  // This option does not change the shape of parrots (i.e. same ciphers will be offered either way).
   691  // Must be called before establishing any connections.
   692  func EnableWeakCiphers() {
   693  	utlsSupportedCipherSuites = append(cipherSuites, []*cipherSuite{
   694  		{DISABLED_TLS_RSA_WITH_AES_256_CBC_SHA256, 32, 32, 16, rsaKA,
   695  			suiteTLS12, cipherAES, macSHA256, nil},
   696  
   697  		{DISABLED_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 32, 48, 16, ecdheECDSAKA,
   698  			suiteECDHE | suiteECSign | suiteTLS12 | suiteSHA384, cipherAES, utlsMacSHA384, nil},
   699  		{DISABLED_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, 32, 48, 16, ecdheRSAKA,
   700  			suiteECDHE | suiteTLS12 | suiteSHA384, cipherAES, utlsMacSHA384, nil},
   701  	}...)
   702  }