tunnel

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Unlicense Imports: 39 Imported by: 0

README

tunnel

Put your local web service on an HTTPS URL—through a server you control.

Your application machine connects outward over QUIC, so it needs no inbound port forwarding. The public server routes connections by hostname while HTTPS terminates on your application machine: its certificate private keys stay with you.

Publish an existing service with tunnelproxy, or give your Go application a tunnel-backed net.Listener. Leave a site public or protect it with Basic authentication, a browser sign-in page, or client certificates.

Browser ── HTTPS ──▶ public server ── QUIC tunnel ──▶ application machine
                    tunneld                          tunnelproxy → local service
                                                     or your Go application

You'll need a public server and a domain you control. Building from source requires Go 1.27.1 or newer.

Meet the tools

tunneld — your public entry point

Runs on the public server, accepts outbound tunnels, and routes public connections to approved clients by hostname. You control who may publish which names; application HTTPS keys never need to reach the daemon.

Server setup and deployment →

tunnelctl — access administration

Inspect access requests, approve or reject clients, manage hostname grants, and revoke access through the daemon's local admin socket.

Administration guide →

tunnelproxy — publish an existing service

Expose a loopback web service without modifying the application. Choose local HTTPS termination or TLS passthrough, and optionally restrict visitors with passwords, cookie-based sign-in, or client certificates.

Proxy setup, serving modes, and authentication →

hello — a working Go example

A small HTTP application served directly through the tunnel API. Use it to try the connection and approval flow or as a starting point for your own application.

Run the example →

The tunnel package — integrate directly

Use github.com/fasmide/tunnel to obtain a net.Listener for your Go server, with persistent credentials, approval workflows, local TLS, reconnection, and graceful draining.

Go package guide →

Each command-line tool supports --help; subcommands have their own help too.

Where things happen

Serving modes configure the application side. In every mode, tunneld authenticates tunnel clients, enforces approved hostname grants, and forwards traffic over encrypted QUIC. This transport security is separate from the browser's HTTPS connection.

For public TLS, the daemon reads the hostname from SNI and relays the TLS bytes without decrypting application traffic:

Mode What tunneld does Where public TLS terminates HTTPS certificate source
acme (default) Reads SNI and relays TLS bytes, including ACME validation traffic tunnelproxy ACME CA; obtained and cached on the application machine
private Reads SNI and relays TLS bytes; also signs authorized certificate requests tunnelproxy Daemon's generated constrained CA
byo Reads SNI and relays TLS bytes tunnelproxy Operator-supplied certificate and key
raw Reads SNI and relays TLS bytes Local target service Managed by the target service
http Parses HTTP and routes by Host No public TLS None

With the Go package, your application takes the place of tunnelproxy and chooses the corresponding listener API.

Certificates and trust
  • ACME happens locally: the application-side client obtains and renews certificates. The daemon forwards TLS-ALPN-01 validation connections; it does not manage the ACME account or hold application HTTPS keys.
  • Private mode adds a signing role: the application generates its key locally and submits a CSR. The daemon checks hostname ownership and signs it. This requires the daemon's generated CA, which browsers must separately trust. The CA is a trust authority for these sites: its holder can issue other certificates for the same names even though application keys remain local.
  • BYO and raw need no daemon certificate management: BYO loads keys in the proxy; raw leaves all TLS handling to the target. Public HTTPS certificates are distinct from the daemon's QUIC transport certificate.
Authentication and plain HTTP

Daemon approval controls who may publish a hostname, not who may visit it. Optional Basic, cookie, and public client-certificate authentication run locally in tunnelproxy, never in tunneld. In raw mode, configure visitor authentication on the target instead.

HTTP mode is the exception to encrypted public traffic: the browser-to-daemon leg is plaintext, so the daemon can see requests, responses, and credentials. It forwards one HTTP/1.x request/response exchange per connection, without CONNECT or upgrades such as WebSockets. If no eligible HTTP listener exists, the daemon returns a 308 redirect to HTTPS.

The daemon records the advertised mode but groups acme, private, byo, and raw into the same TLS forwarding class; http uses a separate HTTP class. The mode changes where certificates and application protocols are handled—not whether the tunnel itself is encrypted.

Downloads and releases

Download prebuilt archives from GitHub Releases. Linux and macOS archives contain tunneld, tunnelctl, and tunnelproxy; Windows archives contain only tunnelproxy. All three platforms have amd64 and arm64 builds. Releases include a checksums.txt file with SHA-256 checksums.

Binaries are built without cgo. ACME mode still requires a system CA trust bundle; install ca-certificates in minimal Linux containers.

Every tool supports <tool> version (including the hello example). GoReleaser builds report the Git tag, full source revision, and UTC compile date:

tunnelproxy
tag: v0.1.0
srcrev: <full Git commit hash>
compile date: <RFC3339 UTC timestamp>

Plain go build defaults to dev / unknown / unknown. Custom builds can populate github.com/fasmide/tunnel/internal/cli.Tag, .SourceRevision, and .BuildDate using go build -ldflags with -X assignments.

Publishing a release

GitHub Actions runs static checks and race-enabled tests on branch pushes and pull requests, and builds downloadable GoReleaser snapshot archives. Pushing a semantic-version tag runs the checks again and publishes a GitHub Release with archives, checksums, and generated release notes:

git tag -a v0.1.0 -m "Release v0.1.0"
git push origin v0.1.0

Use a tag such as v0.1.0-rc.1 for a prerelease. No additional token secret is required: the release workflow uses GitHub's built-in GITHUB_TOKEN with release-job-only write permission.

To validate or build locally with GoReleaser v2:

goreleaser check
goreleaser release --snapshot --clean

Output is written to dist/. The hello command remains a source example and is not included in release archives.

Development

Run make test for race-enabled tests or make vet for static checks. Tests require curl and OpenSSL 3+ for the client-certificate interoperability test.

How does it compare?

All of these can make a private service publicly reachable. Key differences are who operates the public endpoint, where TLS terminates, and which protocols they support.

Tool Good fit Trade-off
tunnel Self-hosted SNI routing for web services, HTTPS termination on the application machine, or Go net.Listener integration. You manage the public server, DNS, firewall, and access approvals. Supports SNI-routed TLS and opt-in plain HTTP, not arbitrary public TCP/UDP forwarding.
ngrok A managed public endpoint with minimal setup and traffic-management features. The usual hosted workflow depends on ngrok's service; features and limits vary by plan.
Cloudflare Tunnel (cloudflared) Publishing applications through Cloudflare, with optional Cloudflare Access policies. The standard public-hostname workflow uses Cloudflare's DNS and edge; public HTTPS terminates there.
frp Self-hosted forwarding across a broader range of protocols, including TCP and UDP. You operate the server and configure forwarding; its model is broader than this project's web-service and Go-listener focus.

Choose tunnel if you want to own the public endpoint and keep application TLS termination on your machine. Choose a managed service if you'd rather avoid operating that endpoint, or a general-purpose forwarder if you need other protocols. TLS behavior depends on the product and mode—ngrok, for example, also supports TLS passthrough.

Documentation

Overview

Package tunnel provides QUIC-backed raw net.Listeners for Go servers.

Dial requires an existing identity approved by the server. ListenRaw returns unmodified public bytes; the application owns TLS. Storage and persisted Ed25519 credentials and signed RequestJoin bootstrap are included. Listen performs local ACME TLS; ListenTLS uses application-provided certificates. ListenHTTP opts into one-shot plain HTTP. EnsureJoined and EnsureJoinedAndListen support a join-then-wait workflow for administrator approval, with optional event callbacks. Clients reconnect automatically without replaying in-flight requests. CloseGracefully unadvertises and drains allocated streams within a caller-supplied context.

Index

Constants

This section is empty.

Variables

View Source
var ErrIdentityNotApproved = errors.New("identity is not approved for forwarding")
View Source
var ErrIdentityRevoked = errors.New("identity revoked")
View Source
var ErrJoinExpired = fmt.Errorf("join request expired: %w", ErrIdentityNotApproved)

ErrJoinExpired means the pending request expired; call EnsureJoined again to submit a new request. It also matches ErrIdentityNotApproved.

Functions

func FormatJoinEvent

func FormatJoinEvent(event JoinEvent) string

func LoadTransportTLS

func LoadTransportTLS(storage Storage, addr, serverName string) (*tls.Config, error)

LoadTransportTLS loads saved endpoint-local trust for JoinRequest.TLSConfig or WithTLSConfig. It does not fall back to system roots when a saved CA is used. For IP endpoints pass the certified DNS name as serverName.

Types

type Client

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

func Dial

func Dial(ctx context.Context, addr string, options ...Option) (*Client, error)

Dial retries transient connection failures until ctx expires. ctx bounds setup; the returned Client reconnects independently until explicitly closed/denied.

func EnsureJoinedAndListen

func EnsureJoinedAndListen(ctx context.Context, addr string, options JoinWaitOptions, listen ListenFunc, dialOptions ...Option) (net.Listener, *Client, error)

EnsureJoinedAndListen combines EnsureJoined, Dial, and listener creation. The listen callback selects the desired listener mode, for example:

listener, client, err := tunnel.EnsureJoinedAndListen(ctx, addr, opts,
	func(ctx context.Context, c *tunnel.Client) (net.Listener, error) { return c.Listen(ctx, name) })

func (*Client) Close

func (c *Client) Close() error

func (*Client) CloseGracefully

func (c *Client) CloseGracefully(ctx context.Context) error

CloseGracefully removes all pool members, allows allocated streams to be accepted and finish, then closes the transport. Deadline/cancellation aborts the remainder. No reconnect or new listeners are started during draining.

func (*Client) Listen

func (c *Client) Listen(ctx context.Context, name string) (net.Listener, error)

Listen terminates TLS locally using on-demand ACME certificates. It accepts the configured CA's terms of service. By default the CA is Let's Encrypt and only TLS-ALPN-01 is used; DNS must resolve to the daemon on public TCP 443. Credential storage also stores the ACME account and cached certificates.

func (*Client) ListenHTTP

func (c *Client) ListenHTTP(ctx context.Context, name string) (net.Listener, error)

ListenHTTP opts into one-shot plaintext HTTP, independently of TLS listeners.

func (*Client) ListenPrivate

func (c *Client) ListenPrivate(ctx context.Context, name string) (net.Listener, error)

ListenPrivate terminates public TLS locally using certificates issued by the daemon's constrained CA. Browsers must separately trust that CA. Local keys never leave credential storage. Each authorized descendant is issued an exact name certificate on demand; renewal happens at subsequent handshakes with less than 24 hours remaining. No wildcard certificates or ACME are used.

func (*Client) ListenPrivateWithClientAuth

func (c *Client) ListenPrivateWithClientAuth(ctx context.Context, name string, auth *ClientAuthConfig) (net.Listener, error)

ListenPrivateWithClientAuth is ListenPrivate with public client authentication.

func (*Client) ListenRaw

func (c *Client) ListenRaw(ctx context.Context, name string) (net.Listener, error)

func (*Client) ListenTLS

func (c *Client) ListenTLS(ctx context.Context, name string, config *tls.Config) (net.Listener, error)

ListenTLS terminates public TLS locally with an application-provided config. Accepted connections have completed TLS handshakes. The daemon never sees this configuration or its certificate private keys.

func (*Client) ListenWithClientAuth

func (c *Client) ListenWithClientAuth(ctx context.Context, name string, auth *ClientAuthConfig) (net.Listener, error)

ListenWithClientAuth is Listen with public client authentication. ACME TLS-ALPN-01 challenge connections are exempt and never reach Accept.

func (*Client) Listening

func (c *Client) Listening() []string

func (*Client) Routes

func (c *Client) Routes() []string

func (*Client) Status

func (c *Client) Status() string

type ClientAuthConfig

type ClientAuthConfig struct {
	ClientAuth       tls.ClientAuthType
	ClientCAs        *x509.CertPool
	VerifyConnection func(tls.ConnectionState) error
}

ClientAuthConfig configures public client-certificate authentication, separate from tunnel transport credentials. VerifyConnection also runs on resumption.

type Credentials

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

Credentials holds an Ed25519 identity, not proof of route approval. Its private key is intentionally unexported; it never goes to the daemon. Credentials must not be logged or serialized. A zero value is invalid.

func EnsureJoined

func EnsureJoined(ctx context.Context, addr string, options JoinWaitOptions) (Credentials, error)

EnsureJoined makes sure a local identity has a submitted join request and then waits until an administrator approves it. The wait is canceled by ctx.

If credential storage already contains an approved identity, no new join is submitted. If an identity exists but is not approved, EnsureJoined submits a fresh join request before waiting.

func LoadCredentials

func LoadCredentials(storage Storage) (Credentials, error)

LoadCredentials loads an existing identity without creating a new one. Missing keys return an error wrapping fs.ErrNotExist. Malformed keys return an ordinary error and are never silently replaced. Keys are persisted as PKCS#8 DER, unencrypted; storage access controls protect the private key.

func RequestJoin

func RequestJoin(ctx context.Context, addr string, request JoinRequest) (Credentials, error)

RequestJoin returns persisted credentials after durable pending submission, not after human approval. A new Dial is required once an admin approves it.

func (Credentials) GoString

func (c Credentials) GoString() string

func (Credentials) Identity

func (c Credentials) Identity() string

Identity returns the full lowercase SHA-256 public-key identifier, or an empty string for invalid credentials.

func (Credentials) PublicKey

func (c Credentials) PublicKey() ed25519.PublicKey

PublicKey returns a copy of the identity's public key, or nil for invalid credentials. Renewing a transport certificate does not change this identity.

func (Credentials) String

func (c Credentials) String() string

String and GoString redact private material in ordinary formatted output.

type JoinEvent

type JoinEvent struct {
	Time     time.Time
	Type     JoinEventType
	Message  string
	Identity string
	InviteID string
	Routes   []string
	Err      error
}

type JoinEventType

type JoinEventType string
const (
	JoinEventLoadedIdentity JoinEventType = "loaded_identity"
	JoinEventJoinSubmitted  JoinEventType = "join_submitted"
	JoinEventWaiting        JoinEventType = "waiting"
	JoinEventApproved       JoinEventType = "approved"
	JoinEventCheckFailed    JoinEventType = "check_failed"
	JoinEventRevoked        JoinEventType = "revoked"
)

type JoinRequest

type JoinRequest struct {
	Routes   []string
	Storage  Storage
	Metadata map[string]string
	// TLSConfig optionally supplies private roots/ServerName for tunnel TLS.
	// Public CA trust is used by default; verification cannot be disabled.
	TLSConfig *tls.Config
}

type JoinWaitOptions

type JoinWaitOptions struct {
	JoinRequest  JoinRequest
	PollInterval time.Duration
	OnEvent      func(JoinEvent)
}

type ListenFunc

type ListenFunc func(context.Context, *Client) (net.Listener, error)

type Option

type Option func(*dialOptions) error

func WithACMEClient

func WithACMEClient(client *acme.Client) Option

WithACMEClient selects an alternate ACME directory/HTTP transport (e.g. a staging CA). The client is copied; a nil account Key uses persisted storage. Supply this before Dial. Only TLS-ALPN-01 is enabled, regardless of CA offers.

func WithACMEEmail

func WithACMEEmail(email string) Option

func WithACMEErrorHandler

func WithACMEErrorHandler(handler func(host string, err error)) Option

WithACMEErrorHandler reports certificate acquisition errors that otherwise only fail the incoming TLS handshake. The handler may be called concurrently and should return promptly. A nil handler disables reporting.

func WithCredentials

func WithCredentials(c Credentials) Option

func WithTLSConfig

func WithTLSConfig(config *tls.Config) Option

WithTLSConfig supplies server trust roots/ServerName. Verification is required.

type Storage

type Storage interface {
	Get(key string) ([]byte, error)
	Put(key string, value []byte) error
	Delete(key string) error
}

Storage stores private credentials and ACME state. Get must return an error wrapping fs.ErrNotExist for absent keys. Delete is idempotent. Put replaces a value atomically. Implementations must support concurrent callers and must not retain or expose mutable aliases to the supplied/returned byte slices. There is no compare-and-swap: initialize an identity before sharing its store between processes. Treat all stored data as secret.

func FileStorage

func FileStorage(dir string) Storage

FileStorage returns a store rooted at dir. Initialization errors are reported by the first operation, preserving the brief's FileStorage(dir) Storage API. New directories use 0700 and value files use 0600. Existing directory modes are not changed; callers must choose a private, trusted directory. Writes sync a temporary file, rename it atomically, then sync its parent directory. A sync failure can occur after a replacement has already become visible. Symlink traversal cannot escape the root (os.Root); untrusted users must not be permitted to modify the root itself. Stores under /tmp are not durable.

func MemoryStorage

func MemoryStorage() Storage

MemoryStorage returns an independent, concurrency-safe, non-durable store.

type TransportTrust

type TransportTrust struct {
	CA                  []byte
	Fingerprint, Domain string
	FirstUse            bool
}

TransportTrust describes the saved CA without exposing any private material.

func BootstrapTrust

func BootstrapTrust(ctx context.Context, addr string, request TrustRequest) (TransportTrust, error)

BootstrapTrust downloads the constrained CA from the QUIC TLS certificate chain, verifies a supplied fingerprint or explicitly accepts TOFU, verifies hostname/chain, then persists the CA. It sends no Join or forwarding request. Existing trust is never overwritten, including when TOFU is selected again.

func FetchTransportTrust

func FetchTransportTrust(ctx context.Context, addr, serverName string) (TransportTrust, error)

FetchTransportTrust downloads the constrained transport CA from the QUIC TLS chain and returns its public metadata without persisting it.

type TrustRequest

type TrustRequest struct {
	Storage     Storage
	ServerName  string
	Fingerprint string // lowercase SHA-256 hex of CA DER, printed by tunneld
	TOFU        bool   // explicit acceptance of interception risk on first contact
}

TrustRequest explicitly selects fingerprint verification or first-use trust. ServerName is required when addr is an IP but the certificate is DNS-only. Storage must be durable in real deployments. Do not bootstrap a shared store concurrently across processes: Storage does not support compare-and-swap.

Directories

Path Synopsis
cmd
hello command
hello is a minimal HTTP application exposed using the tunnel Go API.
hello is a minimal HTTP application exposed using the tunnel Go API.
tunnelctl command
tunneld command
tunnelproxy command
tunnelproxy exposes a loopback TCP service through an approved tunnel identity.
tunnelproxy exposes a loopback TCP service through an approved tunnel identity.
internal
cli
Package cli provides shared command-line helpers for the tunnel tools.
Package cli provides shared command-line helpers for the tunnel tools.
names
Package names contains shared DNS-label validation and subtree matching.
Package names contains shared DNS-label validation and subtree matching.
server
Package server implements the daemon's tunnel-facing control plane.
Package server implements the daemon's tunnel-facing control plane.
streamconn
Package streamconn adapts QUIC bidirectional streams to net.Conn.
Package streamconn adapts QUIC bidirectional streams to net.Conn.
transportpki
Package transportpki manages the daemon's private transport PKI, not public TLS.
Package transportpki manages the daemon's private transport PKI, not public TLS.
wire
Package wire implements the bounded JSON frames in PROTOCOL.md.
Package wire implements the bounded JSON frames in PROTOCOL.md.

Jump to

Keyboard shortcuts

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