hostctl

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: AGPL-3.0 Imports: 23 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 hostctl is the agent's view of the machine it runs on: host facts for Hello, host metrics for StatsBatch, and the only host state the agent owns: its own nftables table for port-hop redirects and the SSH brute-force guard, the fail-open torrent queue, exact UDP inbound rules in an active UFW firewall, the fq + bbr sysctl baseline and the journald size cap. The real implementation is Linux-only behind a build tag; other OSes get a no-op stub so the whole repo still builds and vets.

Index

Constants

View Source
const (
	// MinHopPort and MaxHopSpan bound every port-hop range the node will redirect (F12): a hop range is a
	// DNAT of every incoming packet of that range, so an unbounded one (a typo, a hostile panel) would
	// swallow DNS, NTP, WireGuard or sshd on the same host.
	MinHopPort = 1024
	MaxHopSpan = 20000 // number of ports in the range
)
View Source
const (
	SysctlFilePath   = "/etc/sysctl.d/90-mistgate.conf"
	JournaldFilePath = "/etc/systemd/journald.conf.d/90-mistgate.conf"
	SysctlFileBody   = sysctlFileBody
	JournaldFileBody = journaldFileBody
	// JournalCapMB is SystemMaxUse in journaldFileBody and the target of VacuumJournal.
	JournalCapMB = 200
)

Exported so the doctor's net_baseline check compares against exactly what ApplyBaseline writes.

View Source
const (
	// ResolverModeResolved configures systemd-resolved through a drop-in; ResolverModeResolvConf rewrites
	// /etc/resolv.conf (backup kept).
	ResolverModeResolved   = "resolved"
	ResolverModeResolvConf = "resolv_conf"
)
View Source
const (
	// NftTunnelTable is the table of the tunnel rules. The doctor treats it as ours.
	NftTunnelTable = "mistgate_awg"
	// NftWarpTable is the table of the WARP manager (internal/node/warp.NftTable, a test in cmd/mistgate-node keeps
	// the two equal); the doctor treats it as ours too, and the two tables are the only ones besides NftTable.
	NftWarpTable = "mistgate_warp"
	// TunnelIfacePrefix is the name prefix of every interface the AWG engine creates (awg.IfaceName, a test in
	// internal/node/awg keeps the two equal). Cleanup deletes links that carry it.
	TunnelIfacePrefix = "mgawg"
	// WarpIface is the WARP tunnel device (warp.DefaultIface, same test).
	WarpIface = "mgwarp"
)
View Source
const (
	// NftTable is the agent's own table; the agent never touches any other.
	NftTable = "mistgate_node"
)
View Source
const (
	// NftTorrentTable is Mistgate's independent, fail-open NFQUEUE ruleset.
	NftTorrentTable = "mistgate_torrentguard"
)

Variables

View Source
var ErrUnsupported = errors.New("hostctl: not supported on this OS")

ErrUnsupported is returned by the non-Linux stub.

Functions

func CleanupTunnels

func CleanupTunnels(ctx context.Context) error

CleanupTunnels is the stateless form for the unit's ExecStopPost (a crashed agent leaves its interfaces and its table behind): it deletes the tunnel table and every link named mgawg* or mgwarp. The WARP routing rules and routes are removed by internal/node/warp.CleanupHost, which the same subcommand calls.

func NeedsV6

func NeedsV6(ts []Tunnel) bool

NeedsV6 reports whether any tunnel has an IPv6 subnet (IPv6 forwarding is wanted).

func RenderHops

func RenderHops(hops []Hop) (string, error)

RenderHops renders the agent's table with only the port-hop redirects (no SSH guard).

func RenderRuleset

func RenderRuleset(hops []Hop, sshPorts []uint16) (string, error)

RenderRuleset returns the nft script that atomically replaces the agent's table with one redirect rule per hop and, when sshPorts is not empty, the SSH brute-force guard (ssh.go). `add` + `delete` first makes the script work whether or not the table exists, and nft applies a whole -f file as one transaction. No hops and no ssh ports renders the delete only (= cleanup). Every hop goes through ValidateHop, with the ssh ports reserved.

`redirect` (DNAT to the local address of the incoming interface) works for IPv4 and IPv6 in the inet family (kernel >= 5.2) and needs no knowledge of the node's address.

func RenderTorrentGuard added in v0.1.5

func RenderTorrentGuard(ifaces []string) (string, error)

RenderTorrentGuard returns an atomic replacement for Mistgate's own nft table. Queue rules match the exact active AWG interface set in either direction, exclude traffic that enters and leaves through AWG interfaces, and use queue bypass so traffic continues when no userspace listener exists.

func RenderTunnels

func RenderTunnels(ts []Tunnel) (string, error)

RenderTunnels returns the nft script that atomically replaces the tunnel table. `add` + `delete` first makes it work whether or not the table exists; nft applies a whole -f file as one transaction. No tunnels renders the delete only.

func TorrentGuardSupported added in v0.1.5

func TorrentGuardSupported() bool

TorrentGuardSupported reports that this build includes the Linux NFQUEUE runtime.

func TunnelIface

func TunnelIface(port uint16) string

TunnelIface is the interface name of a tunnel inbound on a UDP port.

func TunnelsEqual

func TunnelsEqual(a, b []Tunnel) bool

TunnelsEqual reports whether two tunnel sets install the same rules (order does not matter).

func ValidateHop

func ValidateHop(h Hop, reserved []uint16) error

ValidateHop is the one place that says whether a hop may be installed. reserved are ports a range must never cover (the sshd ports, other inbounds' ports): the caller knows them, this package cannot. The inbound's own Port may lie inside its range.

func ValidateTunnel

func ValidateTunnel(t Tunnel) error

ValidateTunnel checks one tunnel before it reaches nft. The strings that get into the script are interface names and address literals rendered by the netip package; the name is additionally restricted.

Types

type Facts

type Facts struct {
	Hostname  string
	OS        string
	Kernel    string
	Arch      string
	CPUCount  int
	RAMTotal  uint64
	DiskTotal uint64
	Virt      string // systemd-detect-virt style: "kvm", "openvz", "lxc", "none", "unknown"
	HasIPv6   bool
	Boot      time.Time
}

type Fixer

type Fixer interface {
	// VacuumJournal runs journalctl --vacuum-size=200M --vacuum-time=7d.
	VacuumJournal(ctx context.Context) error
	// ResolverPlan says what SetResolver would do, changing nothing.
	ResolverPlan(ctx context.Context, servers []string) (ResolverPlan, error)
	// SetResolver points the host resolver at servers (IPs, optionally host:port where the mode allows it).
	// The previous configuration is kept so Cleanup can restore it.
	SetResolver(ctx context.Context, servers []string) error
}

Fixer is the part of the host the doctor's safe fixes need beyond Host. The Linux host implements it, the stub returns ErrUnsupported; a caller type-asserts (`fx, ok := host.(Fixer)`). Cleanup undoes SetResolver.

type Hop

type Hop struct {
	InboundID string
	Network   string // "udp" | "tcp"
	From, To  uint16
	Port      uint16
}

Hop is one port-hopping range: packets to Network/From-To are redirected to the inbound's real Port.

type Host

type Host interface {
	// Facts are read once per connection (Hello).
	Facts(ctx context.Context) Facts
	// Metrics is sampled once per stats interval; rates are averaged since the previous call.
	Metrics() Metrics
	// ApplyBaseline installs the sysctl and journald baseline and the SSH brute-force guard. Idempotent; a
	// failure is returned but is never fatal for the agent (OpenVZ/LXC cannot set qdisc/congestion control).
	ApplyBaseline(ctx context.Context) error
	// SetPortHops makes the hop part of the agent's nft table match hops exactly. Atomic; the SSH guard
	// (installed by ApplyBaseline) stays. Every hop must pass ValidateHop.
	SetPortHops(ctx context.Context, hops []Hop) error
	// SyncInboundUDPPorts reconciles exact Mistgate UDP listener ports and hop ranges in a supported,
	// already-active host firewall. It never enables a firewall or edits provider-level rules.
	SyncInboundUDPPorts(ctx context.Context, ports []UDPInboundPort) error
	// SSHPorts are the sshd ports found by the last ApplyBaseline (22 when detection found nothing):
	// the SSH guard rate-limits them and no port-hop range may cover them.
	SSHPorts() []uint16
	// Cleanup removes everything the agent installed (nft tables with hops, SSH guard and torrent queue, tagged UFW UDP rules, sysctl and journald drop-ins,
	// and the resolver fix of the doctor: resolved drop-in, resolv.conf restored from its backup; the tunnel table
	// "mistgate_awg" and every link named mgawg* or mgwarp). The WARP routing rules and routes are the WARP
	// manager's (warp.Cleanup).
	// Live sysctl values are not reverted (the previous values are not recorded).
	Cleanup(ctx context.Context) error
}

Host is implemented by the Linux host owner and by the stub.

func New

func New(log *slog.Logger) Host

New returns the real Linux host owner.

nftables is driven through the `nft` binary, not github.com/google/nftables: the ruleset is one short text script applied with `nft -f -` (a single atomic transaction, replace-or-create, easy to read in an incident and to assert in a test by rendering it), while the library would add a netlink dependency and a hand-built expression tree for the same three lines. The price is that `nft` must be installed (it is on Debian 12 and Ubuntu 22.04+); SetPortHops reports a clear error if it is not.

type Metrics

type Metrics struct {
	CPUPct     float64
	SoftirqPct float64 // part of CPUPct spent in softirq
	Load1      float64
	RAMUsed    uint64
	RAMTotal   uint64
	DiskUsed   uint64
	DiskTotal  uint64
	NetRxBps   uint64
	NetTxBps   uint64
	UptimeS    uint64
}

type ResolverPlan

type ResolverPlan struct {
	Mode   string   // "resolved" (systemd-resolved drop-in) or "resolv_conf" (/etc/resolv.conf rewritten)
	Before []string // nameservers in effect now
	After  []string // nameservers that will be configured (validated, deduplicated)
}

ResolverPlan is the dry run of SetResolver.

type TorrentDetection added in v0.1.5

type TorrentDetection struct {
	SourceIP        netip.Addr
	SourcePort      uint16
	DestinationIP   netip.Addr
	DestinationPort uint16
	L4Protocol      string
	Signature       torrentguard.Protocol
	TunnelIface     string
	TunnelIP        netip.Addr
}

TorrentDetection describes one positively identified BitTorrent flow. Source and destination retain the direction of the packet that matched the signature; TunnelIP identifies the address on the AWG side of that packet.

type TorrentGuardHost added in v0.1.5

type TorrentGuardHost interface {
	// SetTorrentGuard inspects forwarded TCP/UDP traffic crossing exactly the
	// supplied active AWG interfaces. Passing no interfaces removes Mistgate's
	// queue table and stops its runtime. Queue failures are fail-open.
	SetTorrentGuard(ctx context.Context, ifaces []string, onAttempt func(TorrentDetection)) error
}

TorrentGuardHost owns the optional Linux userspace flow inspector.

type Tunnel

type Tunnel struct {
	Iface            string // mgawg<port>
	Subnet4, Subnet6 netip.Prefix
	Addr4, Addr6     netip.Addr // the node's own addresses inside the subnets (.1)
	UDPPort          uint16
	// ViaWarp: the egress of this tunnel is WARP. No masquerade here, the WARP table does it.
	ViaWarp bool
}

Tunnel is one tunnel interface as the firewall sees it.

type TunnelHost

type TunnelHost interface {
	// SetTunnels atomically replaces the tunnel table with the rules of ts (no tunnels = the table is deleted) and
	// turns forwarding on: net.ipv4.ip_forward, and IPv6 forwarding when a tunnel has an IPv6 subnet. A call with the
	// set that is already installed does nothing (the counters keep counting).
	SetTunnels(ctx context.Context, ts []Tunnel) error
	// TunnelCounters returns, per UDP port of an installed tunnel, the datagrams received since the tunnel was first
	// installed by this process (a replacement of the table does not reset them).
	TunnelCounters(ctx context.Context) (map[uint16]uint64, error)
}

TunnelHost is the part of the host that the L3 protocols need beyond Host. The Linux host implements it, the stub accepts and does nothing; a caller type-asserts (`th, ok := host.(TunnelHost)`).

type UDPInboundPort added in v0.1.1

type UDPInboundPort struct {
	Port     uint16
	From, To uint16
}

UDPInboundPort describes one exact UDP port or one exact Hysteria2 hop range. Set Port for a single listener; set From and To for a range.

Jump to

Keyboard shortcuts

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