Categorygithub.com/12end/tls
modulepackage
0.0.0-20230329031950-bbfc948c6240
Repository: https://github.com/12end/tls.git
Documentation: pkg.go.dev

# README

uTLS uTLS

Build Status godoc

uTLS is a fork of "crypto/tls", which provides ClientHello fingerprinting resistance, low-level access to handshake, fake session tickets and some other features. Handshake is still performed by "crypto/tls", this library merely changes ClientHello part of it and provides low-level access.
Golang 1.19+ is required.

If you have any questions, bug reports or contributions, you are welcome to publish those on GitHub. If you want to do so in private, you can contact one of developers personally via [email protected].

Documentation below may not keep up with all the changes and new features at all times, so you are encouraged to use godoc.

Note: Information provided below in this README.md could be obsolete.

Features

Low-level access to handshake

  • Read/write access to all bits of client hello message.
  • Read access to fields of ClientHandshakeState, which, among other things, includes ServerHello and MasterSecret.
  • Read keystream. Can be used, for example, to "write" something in ciphertext.

ClientHello fingerprinting resistance

Golang's ClientHello has a very unique fingerprint, which especially sticks out on mobile clients, where Golang is not too popular yet. Some members of anti-censorship community are concerned that their tools could be trivially blocked based on ClientHello with relatively small collateral damage. There are multiple solutions to this issue.

It is highly recommended to use multiple fingeprints, including randomized ones to avoid relying on a single fingerprint. utls.Roller does this automatically.

Randomized Fingerprint

Randomized Fingerprints are supposedly good at defeating blacklists, since those fingerprints have random ciphersuites and extensions in random order. Note that all used ciphersuites and extensions are fully supported by uTLS, which provides a solid moving target without any compatibility or parrot-is-dead attack risks.

But note that there's a small chance that generated fingerprint won't work, so you may want to keep generating until a working one is found, and then keep reusing the working fingerprint to avoid suspicious behavior of constantly changing fingerprints. utls.Roller reuses working fingerprint automatically.

Generating randomized fingerprints

To generate a randomized fingerprint, simply do:

uTlsConn := tls.UClient(tcpConn, &config, tls.HelloRandomized)

you can use helloRandomizedALPN or helloRandomizedNoALPN to ensure presence or absence of ALPN(Application-Layer Protocol Negotiation) extension. It is recommended, but certainly not required to include ALPN (or use helloRandomized which may or may not include ALPN). If you do use ALPN, you will want to correctly handle potential application layer protocols (likely h2 or http/1.1).

Reusing randomized fingerprint

// oldConn is an old connection that worked before, so we want to reuse it
// newConn is a new connection we'd like to establish
newConn := tls.UClient(tcpConn, &config, oldConn.ClientHelloID)

Parroting

This package can be used to parrot ClientHello of popular browsers. There are some caveats to this parroting:

  • We are forced to offer ciphersuites and tls extensions that are not supported by crypto/tls. This is not a problem, if you fully control the server and turn unsupported things off on server side.
  • Parroting could be imperfect, and there is no parroting beyond ClientHello.

Compatibility risks of available parrots

ParrotCiphers*Signature*Unsupported extensionsTLS Fingerprint ID
Chrome 62nonoChannelID0a4a74aeebd1bb66
Chrome 70nonoChannelID, Encrypted Certsbc4c7e42f4961cd7
Chrome 72nonoChannelID, Encrypted Certsbbf04e5f1881f506
Chrome 83nonoChannelID, Encrypted Certs9c673fd64a32c8dc
Firefox 56very lownoNonec884bad7f40bee56
Firefox 65very lownoMaxRecordSize6bfedc5d5c740d58
iOS 11.1low**noNone71a81bafd58e1301
iOS 12.1low**noNoneec55e5b4136c7949

* Denotes very rough guesstimate of likelihood that unsupported things will get echoed back by the server in the wild, visibly breaking the connection.
** No risk, if utls.EnableWeakCiphers() is called prior to using it.

Parrots FAQ

Does it really look like, say, Google Chrome with all the GREASE and stuff?

It LGTM, but please open up Wireshark and check. If you see something — say something.

Aren't there side channels? Everybody knows that the bird is a wordparrot is dead

There sure are. If you found one that approaches practicality at line speed — please tell us.

However, there is a difference between this sort of parroting and techniques like SkypeMorth. Namely, TLS is highly standardized protocol, therefore simply not that many subtle things in TLS protocol could be different and/or suddenly change in one of mimicked implementation(potentially undermining the mimicry). It is possible that we have a distinguisher right now, but amount of those potential distinguishers is limited.

Custom Handshake

It is possible to create custom handshake by

  1. Use HelloCustom as an argument for UClient() to get empty config
  2. Fill tls header fields: UConn.Hello.{Random, CipherSuites, CompressionMethods}, if needed, or stick to defaults.
  3. Configure and add various TLS Extensions to UConn.Extensions: they will be marshaled in order.
  4. Set Session and SessionCache, as needed.

If you need to manually control all the bytes on the wire(certainly not recommended!), you can set UConn.HandshakeStateBuilt = true, and marshal clientHello into UConn.HandshakeState.Hello.raw yourself. In this case you will be responsible for modifying other parts of Config and ClientHelloMsg to reflect your setup and not confuse "crypto/tls", which will be processing response from server.

Fingerprinting Captured Client Hello

You can use a captured client hello to generate new ones that mimic/have the same properties as the original. The generated client hellos should look like they were generated from the same client software as the original fingerprinted bytes. In order to do this:

  1. Create a ClientHelloSpec from the raw bytes of the original client hello
  2. Use HelloCustom as an argument for UClient() to get empty config
  3. Use ApplyPreset with the generated ClientHelloSpec to set the appropriate connection properties
uConn := UClient(&net.TCPConn{}, nil, HelloCustom)
fingerprinter := &Fingerprinter{}
generatedSpec, err := fingerprinter.FingerprintClientHello(rawCapturedClientHelloBytes)
if err != nil {
  panic("fingerprinting failed: %v", err)
}
if err := uConn.ApplyPreset(generatedSpec); err != nil {
  panic("applying generated spec failed: %v", err)
}

The rawCapturedClientHelloBytes should be the full tls record, including the record type/version/length header.

Roller

A simple wrapper, that allows to easily use multiple latest(auto-updated) fingerprints.

// NewRoller creates Roller object with default range of HelloIDs to cycle
// through until a working/unblocked one is found.
func NewRoller() (*Roller, error)
// Dial attempts to connect to given address using different HelloIDs.
// If a working HelloID is found, it is used again for subsequent Dials.
// If tcp connection fails or all HelloIDs are tried, returns with last error.
//
// Usage examples:
//
// Dial("tcp4", "google.com:443", "google.com")
// Dial("tcp", "10.23.144.22:443", "mywebserver.org")
func (c *Roller) Dial(network, addr, serverName string) (*UConn, error)

Fake Session Tickets

Fake session tickets is a very nifty trick that allows power users to hide parts of handshake, which may have some very fingerprintable features of handshake, and saves 1 RTT. Currently, there is a simple function to set session ticket to any desired state:

// If you want you session tickets to be reused - use same cache on following connections
func (uconn *UConn) SetSessionState(session *ClientSessionState)

Note that session tickets (fake ones or otherwise) are not reused.
To reuse tickets, create a shared cache and set it on current and further configs:

// If you want you session tickets to be reused - use same cache on following connections
func (uconn *UConn) SetSessionCache(cache ClientSessionCache)

Custom TLS extensions

If you want to add your own fake (placeholder, without added functionality) extension for mimicry purposes, you can embed *tls.GenericExtension into your own struct and override Len() and Read() methods. For example, DelegatedCredentials extension can be implemented as follows:

const FakeDelegatedCredentials uint16 = 0x0022

type FakeDelegatedCredentialsExtension struct {
	*tls.GenericExtension
	SignatureAlgorithms []tls.SignatureScheme
}

func (e *FakeDelegatedCredentialsExtension) Len() int {
	return 6 + 2*len(e.SignatureAlgorithms)
}

func (e *FakeDelegatedCredentialsExtension) Read(b []byte) (n int, err error) {
	if len(b) < e.Len() {
		return 0, io.ErrShortBuffer
	}
	offset := 0
	appendUint16 := func(val uint16) {
		b[offset] = byte(val >> 8)
		b[offset+1] = byte(val & 0xff)
		offset += 2
	}

	// Extension type
	appendUint16(FakeDelegatedCredentials)

	algosLength := 2 * len(e.SignatureAlgorithms)

	// Extension data length
	appendUint16(uint16(algosLength) + 2)

	// Algorithms list length
	appendUint16(uint16(algosLength))

	// Algorithms list
	for _, a := range e.SignatureAlgorithms {
		appendUint16(uint16(a))
	}
	return e.Len(), io.EOF
}

Then it can be used just like normal extension:

&tls.ClientHelloSpec{
	//...
	Extensions: []tls.TLSExtension{
		//...
		&FakeDelegatedCredentialsExtension{
			SignatureAlgorithms: []tls.SignatureScheme{
				tls.ECDSAWithP256AndSHA256,
				tls.ECDSAWithP384AndSHA384,
				tls.ECDSAWithP521AndSHA512,
				tls.ECDSAWithSHA1,
			},
		},
		//...
	}
	//...
}

Client Hello IDs

See full list of clientHelloID values here.
There are different behaviors you can get, depending on your clientHelloID:

  1. utls.HelloRandomized adds/reorders extensions, ciphersuites, etc. randomly.
    HelloRandomized adds ALPN in a percentage of cases, you may want to use HelloRandomizedALPN or HelloRandomizedNoALPN to choose specific behavior explicitly, as ALPN might affect application layer.
  2. utls.HelloGolang HelloGolang will use default "crypto/tls" handshake marshaling codepath, which WILL overwrite your changes to Hello(Config, Session are fine). You might want to call BuildHandshakeState() before applying any changes. UConn.Extensions will be completely ignored.
  3. utls.HelloCustom will prepare ClientHello with empty uconn.Extensions so you can fill it with TLSExtension's manually.
  4. The rest will will parrot given browser. Such parrots include, for example:
    • utls.HelloChrome_Auto- parrots recommended(usually latest) Google Chrome version
    • utls.HelloChrome_58 - parrots Google Chrome 58
    • utls.HelloFirefox_Auto - parrots recommended(usually latest) Firefox version
    • utls.HelloFirefox_55 - parrots Firefox 55

Usage

Examples

Find basic examples here.
Here's a more advanced example showing how to generate randomized ClientHello, modify generated ciphersuites a bit, and proceed with the handshake.

Migrating from "crypto/tls"

Here's how default "crypto/tls" is typically used:

    dialConn, err := net.Dial("tcp", "172.217.11.46:443")
    if err != nil {
        fmt.Printf("net.Dial() failed: %+v\n", err)
        return
    }

    config := tls.Config{ServerName: "www.google.com"}
    tlsConn := tls.Client(dialConn, &config)
    n, err = tlsConn.Write("Hello, World!")
    //...

To start using using uTLS:

  1. Import this library (e.g. import tls "github.com/refraction-networking/utls")
  2. Pick the Client Hello ID
  3. Simply substitute tlsConn := tls.Client(dialConn, &config) with tlsConn := tls.UClient(dialConn, &config, tls.clientHelloID)

Customizing handshake

Some customizations(such as setting session ticket/clientHello) have easy-to-use functions for them. The idea is to make common manipulations easy:

    cRandom := []byte{100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
        110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
        120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
        130, 131}
    tlsConn.SetClientRandom(cRandom)
    masterSecret := make([]byte, 48)
    copy(masterSecret, []byte("masterSecret is NOT sent over the wire")) // you may use it for real security

    // Create a session ticket that wasn't actually issued by the server.
    sessionState := utls.MakeClientSessionState(sessionTicket, uint16(tls.VersionTLS12),
        tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
        masterSecret,
        nil, nil)
    tlsConn.SetSessionState(sessionState)

For other customizations there are following functions

// you can use this to build the state manually and change it
// for example use Randomized ClientHello, and add more extensions
func (uconn *UConn) BuildHandshakeState() error
// Then apply the changes and marshal final bytes, which will be sent
func (uconn *UConn) MarshalClientHello() error

Contributors' guide

Please refer to this document if you're interested in internals

Credits

The initial development of uTLS was completed during an internship at Google Jigsaw. This is not an official Google product.

# Packages

Package cpu implements processor feature detection used by the Go standard library.
No description provided by the author
Package testenv provides information about what functionality is available in different testing environments run by the Go team.

# Functions

https://github.com/google/boringssl/blob/7d7554b6b3c79e707e25521e61e066ce2b996e4c/ssl/t1_lib.c#L2803.
CipherSuiteName returns the standard name for the passed cipher suite ID (e.g.
CipherSuites returns a list of cipher suites currently implemented by this package, excluding those with security issues, which are returned by InsecureCipherSuites.
Client returns a new TLS client side connection using conn as the underlying transport.
DecryptTicketWith decrypts an encrypted session ticket using a TicketKeys (ie []TicketKey) struct usedOldKey will be true if the key used for decryption is not the first in the []TicketKey slice [uTLS] changed to be made public and take a TicketKeys and use a fake conn receiver.
Dial connects to the given network address using net.Dial and then initiates a TLS handshake, returning the resulting TLS connection.
DialWithDialer connects to the given network address using dialer.Dial and then initiates a TLS handshake, returning the resulting TLS connection.
EnableWeakCiphers allows utls connections to continue in some cases, when weak cipher was chosen.
ExtensionIDToExtension returns a TLSExtension for the given extension ID.
will panic if ssl_grease_last_index[index] is out of bounds.
InsecureCipherSuites returns a list of cipher suites currently implemented by this package and which have security issues.
Listen creates a TLS listener accepting connections on the given network address using net.Listen.
LoadX509KeyPair reads and parses a public/private key pair from a pair of files.
ClientSessionState contains the state needed by clients to resume TLS sessions.
MakeConnWithCompleteHandshake allows to forge both server and client side TLS connections.
NewListener creates a Listener which accepts connections from an inner Listener and wraps each connection with Server.
NewLRUClientSessionCache returns a ClientSessionCache with the given capacity that uses an LRU strategy.
NewPRNGSeed creates a new PRNG seed using crypto/rand.Read.
NewRoller creates Roller object with default range of HelloIDs to cycle through until a working/unblocked one is found.
Server returns a new TLS server side connection using conn as the underlying transport.
No description provided by the author
UClient returns a new uTLS client, with behavior depending on clientHelloID.
UnmarshalClientHello allows external code to parse raw client hellos.
UTLSIdToSpec converts a ClientHelloID to a corresponding ClientHelloSpec.
X509KeyPair parses a public/private key pair from a pair of PEM encoded data.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
ECDSA algorithms.
No description provided by the author
No description provided by the author
No description provided by the author
EdDSA algorithms.
we can try to craft these ciphersuites.
No description provided by the author
No description provided by the author
No description provided by the author
from existing pieces, if needed.
No description provided by the author
No description provided by the author
No description provided by the author
https://docs.microsoft.com/en-us/dotnet/api/system.net.security.tlsciphersuite?view=netcore-3.1.
No description provided by the author
No description provided by the author
based on spec's GreaseStyle, GREASE_PLACEHOLDER may be replaced by another GREASE value https://tools.ietf.org/html/draft-ietf-tls-grease-01.
NoClientCert indicates that no client certificate should be requested during the handshake, and if any certificates are sent they will not be verified.
No description provided by the author
No description provided by the author
Legacy signature and hash algorithms for TLS 1.2.
RSASSA-PKCS1-v1_5 algorithms.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
RSASSA-PSS algorithms with public key OID rsaEncryption.
No description provided by the author
No description provided by the author
RenegotiateFreelyAsClient allows a remote server to repeatedly request renegotiation.
RenegotiateNever disables renegotiation.
RenegotiateOnceAsClient allows a remote server to request renegotiation once per connection.
RequestClientCert indicates that a client certificate should be requested during the handshake, but does not require that the client send any certificates.
RequireAndVerifyClientCert indicates that a client certificate should be requested during the handshake, and that at least one valid certificate is required to be sent by the client.
RequireAnyClientCert indicates that a client certificate should be requested during the handshake, and that at least one certificate is required to be sent by the client, but that certificate is not required to be valid.
TLS 1.3 cipher suites.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
Legacy names for the corresponding cipher suites with the correct _SHA256 suffix, retained for backward compatibility.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator that the client is doing version fallback.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
A list of cipher suite IDs that are, or have been, implemented by this package.
TLS 1.0 - 1.2 cipher suites.
VerifyClientCertIfGiven indicates that a client certificate should be requested during the handshake, but does not require that the client sends a certificate.
Deprecated: SSLv3 is cryptographically broken, and is no longer supported by this package.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Variables

Do not modify them directly as they may being used.
newest signatures.
fake curves(groups).
fake curves(groups).
newest signatures.
newest signatures.
newest signatures.
No description provided by the author
No description provided by the author
Hello360_11_0 seems to be incompatible with this library.
No description provided by the author
No description provided by the author
No description provided by the author
beta: shuffler enabled starting from 106.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
HelloCustom will prepare ClientHello with empty uconn.Extensions so you can fill it with TLSExtensions manually or use ApplyPreset function.
No description provided by the author
No description provided by the author
HelloEdge_106 seems to be incompatible with this library.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
The rest will will parrot given browser.
HelloGolang will use default "crypto/tls" handshake marshaling codepath, which WILL overwrite your changes to Hello(Config, Session are fine).
legacy "111" means 11.1.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
HelloRandomized* randomly adds/reorders extensions, ciphersuites, etc.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Structs

No description provided by the author
ApplicationSettingsExtension represents the TLS ALPS extension.
[uTLS] Boring struct is only to be used to record static env variables in boring package.
A Certificate is a chain of one or more certificates, leaf first.
CertificateRequestInfo contains information from a server's CertificateRequest message, which is used to demand a certificate and proof of control from a client.
No description provided by the author
CipherSuite is a TLS cipher suite.
No description provided by the author
ClientHelloInfo contains information from a ClientHello message in order to guide application logic in the GetCertificate and GetConfigForClient callbacks.
No description provided by the author
ClientSessionState contains the state needed by clients to resume TLS sessions.
A Config structure is used to configure a TLS client or server.
A Conn represents a secured connection.
ConnectionState records basic TLS details about the connection.
MUST NOT be part of initial ClientHello.
No description provided by the author
Dialer dials TLS connections given a configuration and a Dialer for the underlying connection.
No description provided by the author
No description provided by the author
FakePreSharedKeyExtension is an extension used to set the PSK extension in the ClientHello.
No description provided by the author
https://tools.ietf.org/html/rfc8472#section-2.
Fingerprinter is a struct largely for holding options for the FingerprintClientHello func.
A FinishedHash calculates the hash of a set of handshake messages suitable for including in a Finished message.
GenericExtension allows to include in ClientHello arbitrary unsupported extensions.
TLS 1.3 Key Share.
TLS 1.3 */.
No description provided by the author
TLS 1.3 PSK Identity.
No description provided by the author
A CipherSuite is a specific combination of key agreement, cipher and MAC function.
No description provided by the author
ClientHandshakeState includes both TLS 1.3-only and TLS 1.2-only states, only one of them will be used, depending on negotiated version.
No description provided by the author
No description provided by the author
RecordHeaderError is returned when a TLS record header is invalid.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
TicketKey is the internal representation of a session ticket key.
TLS 1.2 and before only.
TLS 1.3 only.
No description provided by the author
UtlsCompressCertExtension is only implemented client-side, for server certificates.
No description provided by the author
it is responsibility of user not to generate multiple grease extensions with same value.
No description provided by the author
No description provided by the author

# Interfaces

ClientSessionCache is a cache of ClientSessionState objects that can be used by a client to resume a TLS session with a given server.
No description provided by the author
No description provided by the author
TLSExtensionWriter is an interface allowing a TLS extension to be auto-constucted/recovered by reading in a byte stream.

# Type aliases

https://tools.ietf.org/html/draft-ietf-tls-certificate-compression-04.
ClientAuthType declares the policy the server will follow for TLS Client Authentication.
CurveID is the type of a TLS identifier for an elliptic curve.
No description provided by the author
[uTLS SECTION START].
PRNGSeed is a PRNG seed.
No description provided by the author
RenegotiationSupport enumerates the different levels of support for TLS renegotiation.
SignatureScheme identifies a signature algorithm supported by TLS.
No description provided by the author