chrometls

package module
v0.0.0-...-f0875bf Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

chrometls

chrometls provides Chrome-compatible TLS handshakes for Go while keeping the application data plane under your control.

It exposes a net.Dialer / crypto/tls style API:

  • chrometls.Dial and chrometls.DialWithDialer
  • chrometls.Dialer with Dial, DialContext, Client, and Close
  • Standard Go net.Conn, net/http, and HTTP/2 integration
  • No CGO required

The native TLS library is embedded in the Go module and loaded automatically. Supported platforms are:

  • Linux amd64 / arm64 / arm (GOARM=7)
  • macOS amd64 / arm64
  • Windows amd64 / arm64

For Linux ARM builds, set GOOS=linux GOARCH=arm GOARM=7.

Install

go get github.com/phuslu/chrometls

Quick Start

package main

import (
	"fmt"
	"io"
	"log"

	"github.com/phuslu/chrometls"
)

func main() {
	conn, err := chrometls.Dial("tcp", "example.com:443", &chrometls.Config{
		NextProtos: []string{"http/1.1"},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	_, _ = conn.Write([]byte(
		"GET / HTTP/1.1\r\n" +
			"Host: example.com\r\n" +
			"Connection: close\r\n\r\n",
	))

	body, err := io.ReadAll(conn)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(body))
}

Using Dialer

Dialer is constructed directly as a struct value. It can be reused for multiple connections.

dialer := chrometls.Dialer{
	NetDialer: &net.Dialer{
		Timeout: 10 * time.Second,
	},
	Config: &chrometls.Config{
		ServerName:         "example.com",
		NextProtos:         []string{"http/1.1"},
		ClientSessionCache: chrometls.NewLRUClientSessionCache(64),
	},
}
defer dialer.Close()

conn, err := dialer.DialContext(ctx, "tcp", "example.com:443")

Call Close when the dialer is no longer needed. Existing connections remain valid after the dialer is closed.

Standard net/http

For HTTP/1.1, use DialContext as http.Transport.DialTLSContext:

dialer := chrometls.Dialer{
	Config: &chrometls.Config{
		NextProtos: []string{"http/1.1"},
	},
}
defer dialer.Close()

client := &http.Client{
	Transport: &http.Transport{
		DialTLSContext: dialer.DialContext,
	},
}

resp, err := client.Get("https://example.com/")

Go's standard HTTP transport only auto-enables HTTP/2 for *crypto/tls.Conn. Set NextProtos to HTTP/1.1 when using the standard transport with chrometls.

HTTP/2

Use golang.org/x/net/http2.Transport for HTTP/2:

import (
	"crypto/tls"
	"net"
	"net/http"

	"github.com/phuslu/chrometls"
	"golang.org/x/net/http2"
)

dialer := chrometls.Dialer{
	Config: &chrometls.Config{
		NextProtos: []string{"h2"},
	},
}
defer dialer.Close()

client := &http.Client{
	Transport: &http2.Transport{
		DialTLSContext: func(ctx context.Context, network, addr string, _ *tls.Config) (net.Conn, error) {
			return dialer.DialContext(ctx, network, addr)
		},
	},
}

resp, err := client.Get("https://www.google.com/")

HTTP/2 framing is handled by Go's HTTP/2 implementation.

Wrapping an Existing Connection

Dialer.Client wraps an existing net.Conn, which is useful with SOCKS5, HTTP proxies, or custom transports.

dialer := chrometls.Dialer{
	Config: &chrometls.Config{
		ServerName: "example.com",
	},
}
defer dialer.Close()

tlsConn, err := dialer.Client(rawConn, nil)
if err != nil {
	return err
}
if err := tlsConn.HandshakeContext(ctx); err != nil {
	return err
}

Configuration

Common Config fields:

  • ServerName sets SNI and certificate hostname verification.
  • NextProtos configures ALPN.
  • RootCAs overrides the system root certificate pool.
  • InsecureSkipVerify disables certificate verification and should be used only for controlled testing.
  • VerifyPeerCertificate adds custom certificate verification.
  • ClientSessionCache enables TLS session resumption.

Chrome-specific options include post-quantum key exchange, ALPS, ECH GREASE, extension permutation, trust anchor IDs, and TLS 1.3-only mode.

Native Library

The matching native library is selected automatically for the current OS and architecture. On Linux it is loaded from a sealed memfd through /proc/self/fd, avoiding an executable file in the cache or tmpfs. If memfd loading is unavailable, it falls back to a file in the user's cache directory that is verified by SHA-256.

For custom deployments, override the library with Config.LibraryPath or CHROMETLS_LIB_PATH. CHROMETLS_CACHE_DIR changes the fallback cache location.

License

MIT License. See LICENSE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// ServerName is used for SNI and certificate hostname verification.
	// When Dial/DialContext is called with a host:port, ServerName defaults to the host.
	ServerName string

	// NextProtos specifies the ALPN protocols to advertise.
	// If nil, defaults to []string{"h2", "http/1.1"} to match Chrome.
	// Set to an empty non-nil slice ([]string{}) to omit ALPN.
	NextProtos []string

	// RootCAs defines the root certificate authorities used to verify server certificates.
	// If nil, Go's system root CAs are used.
	RootCAs *x509.CertPool

	// InsecureSkipVerify disables certificate chain and hostname verification.
	// BoringSSL still verifies the TLS handshake CertificateVerify signature.
	InsecureSkipVerify bool

	// VerifyPeerCertificate, if non-nil, is called during certificate verification
	// before Client Finished is sent (similar to crypto/tls.Config.VerifyPeerCertificate).
	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error

	// NoPostQuantum disables the X25519MLKEM768 hybrid post-quantum key exchange group.
	NoPostQuantum bool

	// DisableALPS disables TLS ALPS (Application-Layer Protocol Settings) for "h2".
	DisableALPS bool

	// UseOldALPSCodepoint switches ALPS from the new codepoint (17613) to the legacy one (17513).
	UseOldALPSCodepoint bool

	// DisableECHGrease disables GREASE Encrypted Client Hello (ECH) extension.
	DisableECHGrease bool

	// DisableExtensionPermutation disables Chrome's TLS ClientHello extension permutation.
	DisableExtensionPermutation bool

	// ECHConfigList optionally sets a real ECHConfigList (overrides ECH GREASE).
	ECHConfigList []byte

	// TrustAnchorIDs optionally sets TLS Requested Trust Anchor IDs wire bytes.
	TrustAnchorIDs []byte

	// TLS13Only restricts the minimum TLS version to TLS 1.3 (default minimum is TLS 1.2).
	TLS13Only bool

	// ClientSessionCache enables TLS session resumption across connections.
	ClientSessionCache SessionCache

	// LibraryPath explicitly specifies the path to libchrometls.so/.dylib/.dll.
	// If empty, auto-discovery checks CHROMETLS_LIB_PATH, executable dir,
	// ./internal/bssl/lib, the platform-specific embedded library, and OS paths.
	LibraryPath string
}

Config configures Chrome-like TLS handshakes performed via BoringSSL. All network I/O and application data framing remain fully controlled in Go.

func (*Config) Clone

func (c *Config) Clone() *Config

Clone returns a shallow copy of Config.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn represents a TLS connection whose handshake and record crypto are backed by Chrome's BoringSSL (via purego memory BIO) while all network I/O runs natively on the underlying Go net.Conn.

func Dial

func Dial(network, addr string, config *Config) (*Conn, error)

Dial connects to the given network address and performs a Chrome TLS handshake.

func DialWithDialer

func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)

DialWithDialer connects using dialer and performs a Chrome TLS handshake. A nil dialer is equivalent to the zero-value net.Dialer.

func (*Conn) Close

func (c *Conn) Close() error

Close sends a best-effort TLS close_notify alert, closes the underlying net.Conn, and releases native BoringSSL resources.

func (*Conn) ConnectionState

func (c *Conn) ConnectionState() ConnectionState

ConnectionState returns TLS connection details after the handshake completes.

func (*Conn) Handshake

func (c *Conn) Handshake() error

Handshake runs the Chrome TLS handshake if it has not yet run.

func (*Conn) HandshakeContext

func (c *Conn) HandshakeContext(ctx context.Context) error

HandshakeContext runs the Chrome TLS handshake, honoring ctx cancellation/deadline.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

func (*Conn) NetConn

func (c *Conn) NetConn() net.Conn

NetConn returns the underlying network connection.

func (*Conn) Read

func (c *Conn) Read(p []byte) (int, error)

Read reads decrypted application data from the TLS connection.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

func (*Conn) Write

func (c *Conn) Write(p []byte) (int, error)

Write encrypts and writes application data to the underlying net.Conn.

type ConnectionState

type ConnectionState struct {
	Version            uint16
	CipherSuite        uint16
	NegotiatedProtocol string
	DidResume          bool
	ServerName         string
	PeerCertificates   []*x509.Certificate
	VerifiedChains     [][]*x509.Certificate
}

ConnectionState records basic TLS details about an established Conn.

type Dialer

type Dialer struct {
	// NetDialer is the optional dialer used for underlying TCP connections.
	// If nil, a zero-value net.Dialer is used.
	NetDialer *net.Dialer

	// Config specifies the Chrome TLS parameters. If nil, default Chrome 154
	// parameters are used.
	Config *Config
	// contains filtered or unexported fields
}

Dialer dials network connections and establishes a Chrome-fingerprinted TLS session using BoringSSL (via purego) while keeping all network I/O in Go. Its shape matches crypto/tls.Dialer. The zero value is ready to use.

func (*Dialer) Client

func (d *Dialer) Client(rawConn net.Conn, cfg *Config) (*Conn, error)

Client wraps an existing net.Conn as a Chrome-fingerprinted TLS client connection without immediately running the handshake (matching crypto/tls.Client).

func (*Dialer) Close

func (d *Dialer) Close() error

Close releases the shared native SSL_CTX and prevents further use of the Dialer. Existing *Conn instances remain valid because BoringSSL reference-counts SSL_CTX.

func (*Dialer) Dial

func (d *Dialer) Dial(network, addr string) (net.Conn, error)

Dial connects to the given network address and performs a Chrome TLS handshake.

func (*Dialer) DialContext

func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)

DialContext connects to the given network address using ctx and performs a Chrome TLS handshake.

type SessionCache

type SessionCache interface {
	Get(sessionKey string) (session []byte, ok bool)
	Put(sessionKey string, session []byte)
}

SessionCache stores serialized BoringSSL TLS sessions keyed by host/session key to enable authentic Chrome TLS 1.3 PSK session resumption.

func NewLRUClientSessionCache

func NewLRUClientSessionCache(capacity int) SessionCache

NewLRUClientSessionCache returns an in-memory LRU SessionCache. If capacity <= 0, a sensible default (64) is used.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL