sysproxy

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 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.

Documentation

Overview

Package sysproxy changes machine-wide routing for the attach degrees 6 and 7 (spec §19.9): the desktop or OS HTTPS proxy (--system-proxy, user scope) and a Linux nftables redirect for one user id (--transparent, needs privilege).

Every change is reversible. Before anything is written, the previous values are saved in a 0600 state file under the data directory; Stop restores them and re-reads them to verify. A value changed by another program since acd-ctx set it is left alone. A crashed run leaves its state file behind, and Leftovers and RestoreStale find it.

Nothing in this package runs a command by itself. Every command goes through a Runner that the caller injects; tests inject a fake. Only the CLI wires ExecRunner, the real os/exec runner.

Limitation: the proxy answers only the loopback listener of the current run. The per-run MITM token cannot be placed in system settings, so the listener authenticates the client by its peer process uid instead (see peer.go).

Index

Constants

View Source
const (
	ModeSystemProxy = "system-proxy"
	ModeTransparent = "transparent"
)

Mode names, as stored in state files and reported to the user.

View Source
const (
	FirewallNFT      = "nft"
	FirewallIptables = "iptables"
)

Redirect tools. nft is preferred; iptables is the fallback when nft is absent.

View Source
const NFTTable = "acd_ctx"

NFTTable is the nftables table acd-ctx creates. An underscore keeps the name a valid unquoted identifier. The owner tag OwnerTag is carried by the rule comments, and restore checks for it before it deletes anything.

View Source
const OwnerTag = "acd-ctx"

OwnerTag marks everything acd-ctx creates on the machine: the nft comment, the state files, and the owner field of each state.

View Source
const WatchdogArg = "__watchdog"

WatchdogArg is the hidden argument that makes the acd-ctx binary run the watchdog helper. The CLI checks for it before anything else runs.

Variables

View Source
var DefaultBypass = []string{"localhost", "127.0.0.0/8", "::1"}

DefaultBypass lists the hosts that never go through the proxy.

View Source
var ErrNoBackend = errors.New("no supported system proxy mechanism detected")

ErrNoBackend means no supported proxy mechanism was found on this machine.

View Source
var ErrNoFirewall = errors.New("transparent mode needs nft or iptables; neither was found")

ErrNoFirewall means neither nft nor iptables is installed.

View Source
var ErrUnsupported = errors.New("not supported on this platform")

ErrUnsupported means the degree is not available on this platform.

Functions

func CanApplyTransparent

func CanApplyTransparent(euid int, status string) bool

CanApplyTransparent reports whether the process may change firewall rules: it is root, or it holds CAP_NET_ADMIN (bit 12 of CapEff in /proc/self/status).

func ChooseFirewall

func ChooseFirewall(e Env) (string, error)

ChooseFirewall returns the redirect tool for this machine: nft when it is installed, otherwise iptables.

func Dial

func Dial(ctx context.Context, dst string) (net.Conn, error)

Dial connects to dst with a timeout. Both families are allowed: an IPv6 original destination is tunnelled as it was asked for.

func ExecSpawner

func ExecSpawner(statePath string, parentPID int, pipe *os.File) (func() error, error)

ExecSpawner starts the helper as this binary with WatchdogArg, in its own session, so a Ctrl-C or a closed terminal of the owner does not reach it. The pipe becomes descriptor 3 of the helper.

func FirewallLeftovers

func FirewallLeftovers(ctx context.Context, r Runner) []string

FirewallLeftovers reports the acd-ctx nft table and iptables/ip6tables chains that are present, with the command that removes each one. It only reads: each check is a list command. A tool that is not installed reports nothing, and an unprivileged user may not see a root-owned table (the probe then says nothing).

func LinuxPeerCheck

func LinuxPeerCheck(procRoot string, server netip.AddrPort, selfUID int) func(netip.AddrPort) error

LinuxPeerCheck refuses peers whose socket belongs to another uid. It is built from /proc under procRoot. A peer it cannot attribute is refused.

func OriginalDst

func OriginalDst(c net.Conn) (string, error)

OriginalDst returns the destination a redirected TCP connection had before the nat rule rewrote it. The family is the one of the local socket address.

func ParseSNI

func ParseSNI(rec []byte) (string, bool)

ParseSNI extracts the server_name from a handshake record payload that starts with a ClientHello. It is strict about lengths and returns false on anything it does not understand.

func PeerUID

func PeerUID(procRoot string, client, server netip.AddrPort) (int, error)

PeerUID returns the owner uid of the IPv4 TCP connection whose local end is client and whose remote end is server. The uid column of /proc/net/tcp is the socket owner's uid, so no process table walk is needed. That walk is slow with many connections, and it fails for same-uid processes that are not dumpable.

func ReadHello

func ReadHello(r io.Reader) (string, []byte, error)

ReadHello reads the first TLS record of c and returns its SNI. It returns the bytes it read even when the record is not a ClientHello, so the caller can replay them. A non-TLS first byte yields an empty SNI and no error.

func ResolveDestinations

func ResolveDestinations(ctx context.Context, e Env, hosts []string) (v4, v6 []netip.Addr, err error)

ResolveDestinations resolves hosts to unique IPv4 and IPv6 addresses. A host that fails is reported in the error, and the addresses of the others are still returned.

func ResolveIPv4

func ResolveIPv4(ctx context.Context, e Env, hosts []string) ([]netip.Addr, error)

ResolveIPv4 is ResolveDestinations for the IPv4 addresses only.

func RestoreContext

func RestoreContext() (context.Context, context.CancelFunc)

RestoreContext returns the context for restores: it is independent of the run's context, which an interrupt may already have canceled.

func RestoreStale

func RestoreStale(ctx context.Context, dir string, e Env) ([]string, error)

RestoreStale restores every state file whose owner is gone. Live owners are skipped. Each restore is verified, and its state file is removed only when the restore succeeded.

func RunWatchdog

func RunWatchdog(ctx context.Context, e Env, statePath string, parentPID int, in io.Reader) error

RunWatchdog is the helper's body. It holds the redirect's state until its owner ends:

  • the stand-down byte: the owner already restored the redirect; nothing runs;
  • EOF on the pipe (the owner died, or closed its end): the redirect is restored;
  • the owner's pid is gone or reused: the redirect is restored;
  • the helper's own context ends (a signal): the redirect is restored, because a leftover redirect would cut the client off.

The restore is the verified code that attach --restore uses. A state file that is already gone means nothing is left to do. A state file that does not belong to parentPID, or whose redirect names something other than acd-ctx's own table or chain, is refused before any command runs.

func Splice

func Splice(a, b net.Conn)

Splice copies bytes both ways between a and b until one side ends, then closes both.

func StateDir

func StateDir(dbPath string) string

StateDir is where the state files live: a "sysproxy" directory beside the database. --restore and doctor read the same directory.

func TransparentPreview

func TransparentPreview(fw string, p NFTPlan) (string, error)

TransparentPreview renders what StartTransparent would install with fw, for a dry run. Nothing is changed.

func WatchdogMain

func WatchdogMain(args []string, stderr io.Writer) int

WatchdogMain is the helper process's entry point. args are the arguments after WatchdogArg. Its pipe is descriptor 3, as set by ExecSpawner.

func WatchdogPIDs

func WatchdogPIDs(procRoot, statePath string) []int

WatchdogPIDs lists the helper processes that serve statePath, read from /proc under procRoot. It only reads.

Types

type Active

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

Active is a machine change that is in effect until Stop.

func StartSystemProxy

func StartSystemProxy(ctx context.Context, e Env, dir string, ep Endpoint) (*Active, error)

StartSystemProxy points the system HTTPS proxy at ep. It saves the previous values first. If any write or the verification fails, it rolls back and returns the error.

func StartTransparent

func StartTransparent(ctx context.Context, e Env, dir string, p NFTPlan, fw string) (*Active, error)

StartTransparent installs the redirect with fw (FirewallNFT or FirewallIptables). It refuses when the table or chain already exists, so a second run cannot take over the first one's rules, and it starts the watchdog before the first change.

func (*Active) SetDestinations

func (a *Active) SetDestinations(ctx context.Context, v4, v6 []netip.Addr) error

SetDestinations replaces the destination sets. An empty family keeps the addresses it had: a failed lookup must not empty the set. It is a no-op for the all-443 plan.

func (*Active) Stop

func (a *Active) Stop(ctx context.Context) ([]string, error)

Stop restores what this run changed, verifies it, and removes the state file. It is idempotent. Pass RestoreContext, because the run's own context may already be canceled.

type Backend

type Backend interface {
	// Name identifies the backend in state files ("gnome", "kde5", "kde6",
	// "darwin", "windows").
	Name() string
	// Plan returns the settings that route HTTPS through ep. Every returned
	// setting is Present.
	Plan(ctx context.Context, r Runner, ep Endpoint) ([]Setting, error)
	// Read returns the current value of one key.
	Read(ctx context.Context, r Runner, key string) (Setting, error)
	// Write returns the commands that make the key equal to s. Present=false
	// removes the setting when the backend supports it.
	Write(s Setting) ([]Command, error)
}

Backend is one desktop or OS mechanism for the system HTTPS proxy.

func Select

func Select(e Env) (Backend, error)

Select returns the backend for this machine. Linux uses XDG_CURRENT_DESKTOP (GNOME or KDE). KDE 6 is preferred when kwriteconfig6 is installed.

type Command

type Command struct {
	Name  string
	Args  []string
	Stdin string
}

Command is one external command: argv and optional stdin.

func (Command) String

func (c Command) String() string

String renders the command for messages. It is not a shell quoting.

type Endpoint

type Endpoint struct {
	Host   string
	Port   int
	Bypass []string
}

Endpoint is where the system proxy points: the loopback listener of this run.

func (Endpoint) Validate

func (ep Endpoint) Validate() error

Validate checks the endpoint before any value is written.

type Env

type Env struct {
	GOOS       string                                                       // "" means runtime.GOOS
	Getenv     func(string) string                                          // nil returns ""
	LookPath   func(string) bool                                            // nil reports nothing installed
	Geteuid    func() int                                                   // nil reports -1 (unprivileged)
	ProcStatus func() string                                                // nil returns "" (/proc/self/status)
	ProcRoot   string                                                       // "" means /proc
	Runner     Runner                                                       // required for any command
	Alive      func(pid int, start uint64) bool                             // nil uses the host check
	Resolve    func(ctx context.Context, host string) ([]netip.Addr, error) // nil uses DNS
	Now        func() time.Time                                             // nil means time.Now
	// Spawn starts the watchdog helper of a transparent run. Nil refuses the
	// transparent start: nothing would restore the redirect after a crash.
	// The CLI sets ExecSpawner; tests inject an in-process helper.
	Spawn Spawner
	// WatchdogPoll is the helper's liveness poll interval. Zero means one second.
	WatchdogPoll time.Duration
}

Env is everything the package reads from the machine. A zero Env is safe to build from, but a nil Runner makes every command-running operation fail.

func (Env) Euid

func (e Env) Euid() int

Euid returns the effective uid, or -1 when the Env does not know it.

func (Env) Privileged

func (e Env) Privileged() bool

Privileged reports whether this process may install transparent rules.

type ErrNeedPrivilege

type ErrNeedPrivilege struct {
	Commands []string
}

ErrNeedPrivilege means --transparent needs root or CAP_NET_ADMIN. Commands lists what the user can run as root.

func (*ErrNeedPrivilege) Error

func (e *ErrNeedPrivilege) Error() string

type ExecRunner

type ExecRunner struct{}

ExecRunner runs commands with os/exec. Only the CLI uses it.

func (ExecRunner) Run

func (ExecRunner) Run(ctx context.Context, c Command) (string, error)

Run implements Runner.

type ExitError

type ExitError struct {
	Command Command
	Code    int
	Output  string
}

ExitError is a command that ran and exited non-zero.

func (*ExitError) Error

func (e *ExitError) Error() string

type Leftover

type Leftover struct {
	Path    string
	Mode    string
	Backend string
	PID     int
	Alive   bool
}

Leftover is a state file found on disk, with its owner's liveness.

func Leftovers

func Leftovers(dir string, e Env) ([]Leftover, error)

Leftovers lists the state files in dir. A live owner is an active change; a dead one is a stale change from a crashed run. Unreadable files are reported with an error and are never restored.

type NFTPlan

type NFTPlan struct {
	TargetUID       int
	ProxyUID        int
	RedirectPort    int // 0 renders a placeholder in previews
	AllDestinations bool
	IPv4            []netip.Addr
	IPv6            []netip.Addr
	// RedirectIPv6 adds the IPv6 rules. The caller must have bound [::1] on
	// RedirectPort, or the redirected IPv6 connections would be refused.
	RedirectIPv6 bool
}

NFTPlan is the redirect of one user's TCP 443 traffic to the local listeners. Traffic of ProxyUID is accepted before any redirect, so the proxy's own upstream connections never loop back. The same plan renders the nft ruleset and the iptables/ip6tables chain.

func (NFTPlan) Ruleset

func (p NFTPlan) Ruleset() (string, error)

Ruleset renders the nft script that creates the table. It is applied with `nft -f -`, which is atomic. The first line is `create table`, which fails when the table already exists: a table that appeared after the check is refused, never merged into. The table is then flushed (a no-op on a new table) and filled.

func (NFTPlan) UpdateScript

func (p NFTPlan) UpdateScript() string

UpdateScript renders the nft script that replaces the destination sets with the plan's addresses. It returns "" when there are no sets.

func (NFTPlan) Validate

func (p NFTPlan) Validate() error

Validate checks the plan before rules are rendered or applied.

type PeerListener

type PeerListener struct {
	net.Listener
	// Check returns an error for a peer that must be refused. Nil accepts all.
	Check func(peer netip.AddrPort) error
}

PeerListener wraps a listener and closes every connection whose peer fails Check. The system proxy cannot carry the per-run token, so this is the check that stands in for it: only processes of the owner's uid may use the proxy.

func (PeerListener) Accept

func (l PeerListener) Accept() (net.Conn, error)

Accept returns the next connection whose peer passes Check.

type Router

type Router struct {
	// IsMITM reports whether host is intercepted.
	IsMITM func(host string) bool
	// MITM serves an intercepted connection; raw holds the bytes already read.
	MITM func(ctx context.Context, c net.Conn, host string, raw []byte) error
	// Blind tunnels an unintercepted connection to dst.
	Blind func(ctx context.Context, c net.Conn, dst string, raw []byte) error
	// OrigDst returns the original destination. Nil means OriginalDst.
	OrigDst func(c net.Conn) (string, error)
	// HelloTimeout bounds the wait for the ClientHello. Zero means 10s.
	HelloTimeout time.Duration
	// OnPanic receives a panic from a connection handler. The connection is
	// closed, and the caller decides how the run ends (transparent mode ends
	// the run, so its rules are restored).
	OnPanic func(v any)
}

Router handles the connections the redirect delivers. It reads the TLS ClientHello to learn the SNI and then either hands the connection to the MITM path (SNI in the allowlist) or blind-tunnels it to its original destination. Connections without an SNI are tunnelled too, never intercepted.

func (*Router) Serve

func (rt *Router) Serve(ctx context.Context, ln net.Listener) error

Serve accepts until ln is closed or ctx is done. Each connection is handled in its own goroutine; open tunnels outlive Serve and end when their peers close.

type Runner

type Runner interface {
	Run(ctx context.Context, c Command) (string, error)
}

Runner executes a command and returns its standard output. A non-zero exit status is returned as *ExitError.

type Setting

type Setting struct {
	Key     string `json:"key"`
	Value   string `json:"value"`
	Present bool   `json:"present"`
}

Setting is one machine setting that acd-ctx reads or writes. Key names it inside its backend. Value is the raw text the backend reads and writes back. Present=false means the setting does not exist.

type Spawner

type Spawner func(statePath string, parentPID int, pipe *os.File) (wait func() error, err error)

Spawner starts the helper for the state file at statePath, owned by parentPID. The helper reads from pipe. The spawner takes ownership of pipe and closes it once the helper has its own copy (or on failure). wait reports when the helper has exited.

type State

type State struct {
	Version  int    `json:"version"`
	Owner    string `json:"owner"`
	Mode     string `json:"mode"`
	Backend  string `json:"backend,omitempty"`
	NFTTable string `json:"nft_table,omitempty"`
	// Firewall is the transparent redirect tool: "nft" (or empty, for files
	// written before iptables support) or "iptables". Chain, UID and IPv6 hold
	// the iptables state: the chain name, the uid of its OUTPUT jump, and
	// whether the ip6tables chain was installed too.
	Firewall  string    `json:"firewall,omitempty"`
	Chain     string    `json:"chain,omitempty"`
	UID       int       `json:"uid,omitempty"`
	IPv6      bool      `json:"ipv6,omitempty"`
	PID       int       `json:"pid"`
	StartTime uint64    `json:"start_time,omitempty"`
	Created   time.Time `json:"created"`
	// Applied holds the values this run set. Previous holds the values found
	// before, in the same order and with the same keys.
	Applied  []Setting `json:"applied,omitempty"`
	Previous []Setting `json:"previous,omitempty"`
}

State is what one run changed and what it found before. It is written before the first change and removed only after the restore is verified.

Jump to

Keyboard shortcuts

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