Documentation
¶
Overview ¶
Package agent is the node agent core: it enrolls with the panel, keeps ONE agent session open (mTLS Connect by default, or the signed WebSocket link when the agent has a link URL and the panel advertises it; a link that fails to establish falls back to mTLS and is retried after a hold period; reconnecting with backoff), applies desired state to engines, reports traffic reliably (seq + ack), executes commands and serves its own log. The wire protocol is specified in the comment block of proto/mistgate/agent/v1/agent.proto; this package implements it, nothing more.
Concurrency model: one worker goroutine owns every mutation of engine and host state (desired-state apply, kick, restart, retire, credential-expiry sweep), so the engines see one caller for Apply/Remove/ Kick as their contract demands. Each stream has a reader (the session goroutine) and one writer; the statistics collector, certificate renewal and the expiry timer run for the agent's whole life, across reconnects.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotEnrolled is returned by New when the state directory holds no identity. ErrNotEnrolled = errors.New("agent is not enrolled (run `mistgate-node enroll` first)") // ErrRetired is returned by Run after the panel retired the node; the caller should exit 0. ErrRetired = errors.New("node retired by the panel") )
var BindIP net.IP
BindIP is nil in production (all interfaces). Tests bind the fronts to loopback.
Functions ¶
func IsEnrolled ¶
IsEnrolled reports whether dir holds an identity (enroll writes identity.pem last).
Types ¶
type AWGKernelDebugEngine ¶
type AWGKernelDebugEngine interface {
KernelDebugInfo() (bool, []awg.KernelDebugInterface)
WatchKernelUnknownPeers(func(string)) (bool, func())
}
AWGKernelDebugEngine is what the kernel-log capture asks the awg engine: whether it runs on the kernel module and its interfaces, and the unknown-peer events. The node's awg engine is a wrapper (cmd/mistgate-node), which must forward both: without them a capture on a real node silently reads no AWG lines.
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent is the node agent. Build it with New and run it with Run.
func New ¶
New loads the identity from cfg.StateDir and builds the engines. The panel is not contacted. Returns ErrNotEnrolled when `enroll` has not been run.
func (*Agent) AwgBackend ¶
AwgBackend returns NodeSettings.awg_backend ("" = auto). The awg engine factory asks for it when it builds its backend, like the engines ask for DNS.
func (*Agent) AwgPeers ¶
AwgPeers counts the AmneziaWG devices of the enabled awg inbounds: the userspace fallback's memory ceiling asks for it when it builds the engine (awg.Options.Peers).
func (*Agent) ClientIPv6Disabled ¶ added in v0.1.22
ClientIPv6Disabled returns NodeSettings.client_ipv6_disabled: "IPv6 for clients" is off. The direct egress of the protocol engines asks for it on every dial, like the engines ask for DNS.
func (*Agent) DNS ¶
DNS returns the resolvers from NodeSettings (empty = engine default). Engines call it per use.
type AwgModuleReprober ¶
AwgModuleReprober is what the awg engine offers the doctor fix awg_module_repair (cmd/mistgate-node's wrapper does): when the engine runs on the userspace fallback and the kernel backend is usable now, drop the engine and say so.
type Config ¶
type Config struct {
// StateDir holds the identity and the persisted desired state (created by Enroll).
StateDir string
// LinkURL is the full wss://host/<secret-prefix> base for the optional signed WebSocket transport.
LinkURL string
// Version is reported in Hello; defaults to buildinfo.Version.
Version string
// Built is the Unix time of the source commit (Hello.built); 0 = buildinfo.BuiltUnix().
Built int64
// Updater is the self-update machinery (internal/node/update). Nil = this agent never lists an update capability and
// refuses UpdateAgent and RollbackAgent.
Updater *update.Updater
// Log receives the agent's records; every record also goes to the in-memory ring that LogRequest reads.
// Nil = slog.Default().
Log *slog.Logger
// Level is the LevelVar behind Log's handler. A debug capture raises it for its duration and puts it back; nil = the agent keeps
// a private one and the capture only gates what reaches its own buffer.
Level *slog.LevelVar
// Host-side services handed to the engines (engine.Env). Nil Certs means engines get no certificates,
// nil Egress means only a "no egress configured" error. Nil Masquerade uses the persisted node decoy site.
Certs engine.CertSource
Egress func(name string) (engine.Egress, error)
Masquerade func(inboundID string) http.Handler
// DoctorEnv adjusts the doctor's view of the machine before the doctor is built (tests point it at a fake
// root directory and fake commands). Nil = the real host.
DoctorEnv func(doctor.Env) doctor.Env
// Warp is the node-level WARP manager (internal/node/warp.Manager). Nil = this build has no WARP: the agent does not
// list "warp/1", and an inbound whose egress is WARP is not started. The manager is also what Egress("warp") returns.
Warp WarpManager
// UnitGen is the generation of the systemd unit the agent runs from (MISTGATE_UNIT_GEN); 3 is listed as "unit/3".
UnitGen int
// UnitUnderSystemd detects the service manager environment even if this build cannot launch unit refresh.
UnitUnderSystemd bool
// UnitSkipReason is "other_unit" when the process belongs to systemd but not mistgate-node.service.
UnitSkipReason string
// UnitRefreshLauncher is available only in Linux systemd services; nil disables refresh_unit and its capability.
UnitRefreshBusy func(context.Context) error
UnitRefreshReserve func(context.Context) (release func(started bool), err error)
UnitRefreshLauncher func(context.Context, func()) error
// SecurityUpdatesLauncher starts the bounded apt configuration job in its own transient root systemd unit.
// Nil disables the fix on builds or hosts that cannot launch it.
SecurityUpdatesLauncher func(context.Context) error
// NftInstallLauncher starts the job that installs the nftables package, the same way. Nil disables install_nftables.
NftInstallLauncher func(context.Context) error
// OSUpdateReader replaces the read-only operating-system snapshot source in tests.
OSUpdateReader *osupdate.Reader
// OSUpdateCapability replaces host detection in tests; nil uses Linux/root/systemd detection.
OSUpdateCapability func() bool
// OSUpdate runs OS jobs on request (internal/node/osupdate). Nil = this agent does not list "os-update/1".
OSUpdate *osupdate.Controller
// AwgPrepare builds the AmneziaWG kernel module on request (internal/node/awgprep). Nil = this agent does not list
// "awg-prepare/1", and the admin UI keeps showing the manual command.
AwgPrepare *awgprep.Controller
// AwgKmod follows the apt-hook and agent-start module sync. Nil disables automatic sync.
AwgKmod *awgprep.KmodController
// AwgKmodRepair launches the doctor repair as a transient root unit.
AwgKmodRepair func(context.Context) error
// SpeedTest runs one bandwidth measurement (MeasureBandwidth). Nil = the real one against the public test servers; tests
// give a fake, since they have no internet.
SpeedTest func(ctx context.Context) (speedtest.Result, error)
// MaxPending and MaxPendingBytes bound the queue of unacked reliable messages (defaults 2160 = 6 h of
// 10 s batches, and 32 MiB).
MaxPending int
MaxPendingBytes int
// contains filtered or unexported fields
}
Config is what the caller (cmd/mistgate-node, or a test) provides.
type EnrollConfig ¶
type EnrollConfig struct {
StateDir string
Panel string // host:port
SNI string
CASHA256 string // hex fingerprint of the panel CA certificate (colons and case ignored)
Token string
Version string // defaults to buildinfo.Version
Force bool // overwrite an existing identity
ResumePendingKey bool // persist and reuse the CSR key if enrollment is interrupted
Timeout time.Duration
// LinkURL (wss://host/<secret-prefix>/) enrols over the panel's public link route instead of the pinned mTLS
// endpoint: system-root TLS carries the token (a proven "mg2_" token only as a signature over the CSR), the CA pin
// then vouches for the panel. Exclusive with Panel and SNI.
LinkURL string
// contains filtered or unexported fields
}
EnrollConfig is the input of the `enroll` command.
type Meta ¶
type Meta struct {
Panel string `json:"panel"` // host:port
SNI string `json:"sni"` // secret agent SNI
NodeID string `json:"node_id"` // informational; the certificate is authoritative
// Link is the wss://host/<secret-prefix>/ the agent enrolled through. Set = link-only: the agent never dials mTLS
// (Panel and SNI are empty), renews over its link session and lists no self-update.
Link string `json:"link,omitempty"`
}
Meta is what enrollment leaves next to the key material.
type SettingsAware ¶
type SettingsAware interface {
NodeSettings(ctx context.Context, st *pb.NodeSettings) (reset bool)
}
SettingsAware is implemented by an engine whose configuration comes from NodeSettings (awg: the backend). The worker calls NodeSettings before every reconcile with the settings the agent holds; an engine that dropped its inbounds because of a change returns reset=true and every inbound of its protocol is applied again in the same reconcile.
type WarpManager ¶
type WarpManager interface {
// Apply makes the node match the spec: nil removes WARP, Enabled=false pauses it. Idempotent and cheap for a
// spec it already runs (it only re-asserts the routing).
Apply(ctx context.Context, spec *plugin.WarpSpec) error
// Reconnect rebuilds a down tunnel without changing its account or routed subnets. False means it recovered already.
Reconnect(ctx context.Context) (bool, error)
// CheckNow retries one current failed check and reports whether WARP is down at its failure threshold.
CheckNow(ctx context.Context) (checked, thresholdDown bool, err error)
// SetRoutedSubnets sets the client subnets of the awg inbounds with egress "warp".
SetRoutedSubnets(ctx context.Context, subnets []netip.Prefix) error
// Configured says whether the node has a WARP configuration (paused included).
Configured() bool
// Health is the last measured state; ok=false when the node has no WARP.
Health() (warp.Health, bool)
// Preflight lists clashes with the host (routing table, rule preferences, a FORWARD drop policy); the doctor shows them.
Preflight(ctx context.Context) []warp.Finding
// Run drives the health checks until ctx ends.
Run(ctx context.Context)
// Cleanup removes everything the manager installed on the host.
Cleanup(ctx context.Context) error
// Reach fetches the sites through the tunnel and says which show a block page (agent.proto "WARP REACH").
Reach(ctx context.Context, domains []string) (warp.ReachReport, error)
}
WarpManager is what the agent needs of internal/node/warp.Manager (the real one implements it; tests use a fake). The manager is handed to the engines through Config.Egress; the agent owns its lifecycle and feeds it the spec.
Source Files
¶
- agent.go
- apply.go
- awg_kmod.go
- awgprep.go
- bandwidth.go
- bridge.go
- bridge_state.go
- convert_l3.go
- countryprobe.go
- debugcap.go
- decoy.go
- doctor.go
- front.go
- identity.go
- ipv6addr.go
- journal.go
- kernel_debug.go
- kernel_debug_linux.go
- l3.go
- lastexit.go
- lastexit_linux.go
- link.go
- logring.go
- logs.go
- networks.go
- nft.go
- os_status.go
- osupdate.go
- outbox.go
- pathtrace.go
- ranged_http.go
- relay.go
- speed.go
- speed_channel.go
- started.go
- state.go
- stats.go
- tcpcheck.go
- torrent.go
- udpcheck.go
- update.go
- update_sources.go
- warpreach.go