netguard

package
v0.209.1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 17 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 netguard holds the shared loopback listen-address guard.

Extracted 2026-07-17 from cmd/local-agent (validateListenAddr) for fleet-serve; behavior identical. Both HTTP servers (local-agent's OpenAI shim, which is unauthenticated, and fleet-serve, which needs the fleet bearer on every lane) refuse to bind beyond loopback unless the operator explicitly opts into a trusted network.

publicnet.go is this package's PUBLIC-WEB outbound guard — the third sibling of the listen guard (netguard.go) and the tailnet guard (tailnet.go).

tailnet.go keeps a seat endpoint pointed INSIDE the tailnet; this file keeps the research lane pointed OUTSIDE it. Both face the same attack: a hostname the caller supplies resolves one way when it is VALIDATED and another way when it is DIALED (DNS rebinding — a TOCTOU window with an attacker-chosen TTL on the far side). The answer is identical in both: resolve once, judge every answer, and hand the dialer the vetted IP LITERAL so nothing between the check and connect(2) can re-resolve.

Everything a caller needs lives here:

  • LookupIP the ONE resolution seam in the tree (tests pin it)
  • PublicIP / CheckPublicIP the ONE public-address predicate in the tree
  • PublicDialControl a net.Dialer.Control hook (after DNS, before connect)
  • PublicDialContext resolve-and-pin around any DialFunc
  • PublicTransport an http.RoundTripper whose every dial rides both

The predicate was the agent lane's (internal/agent's isDisallowedIP/blockedNets, 2026-08) and the research lane had its own weaker copy that missed 0.0.0.0/8, 240/4, the TEST-NETs, 192.0.0.0/24, 192.88.99.0/24, NAT64 and 6to4. Two predicates meant two answers to one question; there is now one.

tailnet.go is this package's OUTBOUND guard — the listen guard's mirror image. netguard.Validate keeps unauthenticated servers from binding beyond loopback; TailnetURL + SafeTransport keep a remote model seat (config seat_endpoints, the delegation lanes) from ever POINTING beyond loopback or the operator's tailnet. The threat is a config edit — fat-fingered or hostile — that aims a "local" seat at the public internet, which would break the never-cloud rule (ADR 0001) silently: the completion still succeeds, just against a server the operator never chose.

The guard is TWO layers, because URL-shape checks and DNS answers fail independently:

  1. TailnetURL (config-load time): pure shape check, no DNS. Only loopback, 100.64.0.0/10 literals, dotless MagicDNS short names, and hostnames under a configured tailnet zone (the operator's own, and the zone of any other tailnet that shared a node in) pass.
  2. SafeTransport / SafeDialContext (dial time, EVERY dial): a hostname that passed the shape check is resolved here, any answer outside loopback/CGNAT is refused, and the connection goes to the vetted IP LITERAL — never back through the name. ingress.go bans hostnames outright to avoid resolve-then-redial rebinding; seat endpoints exist to name MagicDNS hosts, so this guard resolves-and-PINS instead of banning. The check runs per dial, so a DNS answer that drifts to a public address after validation (classic rebinding) dies at the socket, not in a comment.

Index

Constants

This section is empty.

Variables

View Source
var LookupIP = func(ctx context.Context, host string) ([]netip.Addr, error) {
	return net.DefaultResolver.LookupNetIP(ctx, "ip", host)
}

LookupIP resolves a hostname to addresses. It is a package var because it is the SINGLE resolution seam every guard in this package shares: the tailnet dial gate, the public dial gate, and the research lane's URL validation all call it, so one test hook pins DNS for all three (and a rebinding test can answer differently per call, which is the whole attack). Production always rides the default resolver.

Functions

func AllInterfaces added in v0.206.0

func AllInterfaces(addr string) bool

AllInterfaces reports whether a "host:port" listen address binds every interface: an empty host (":18811" — Go's net.Listen binds all interfaces for it) or an unspecified IP (0.0.0.0, ::, and their spellings). A malformed address reports false; Validate refuses it on its own.

func CheckPublicIP added in v0.206.0

func CheckPublicIP(ip net.IP) error

CheckPublicIP is the ONE public-address predicate in this tree. It blocks any address an SSRF attacker would pivot to: loopback, RFC1918 private, link-local (including the 169.254.169.254 cloud-metadata address, which IsPrivate does NOT cover), multicast, unspecified, and every reserved range above. IPv4-mapped IPv6 (::ffff:127.0.0.1) is normalized to its IPv4 form first, so it cannot slip through disguised as "IPv6". Returns nil iff ip is a routable public address; the error names the reason, which callers surface verbatim.

func HostAllowed added in v0.206.0

func HostAllowed(hostport string) (ok bool, why string)

HostAllowed reports whether a request's Host header (host or host:port) names this listener in a way only the operator's own clients would: the TailnetURL rules applied to a bare host. why says what failed when ok is false.

The name test is TailnetURL's own (tailnetNameAllowedIn), so the two cannot disagree about a name; the port test is url.Parse's (digits only, no range). The one place this is stricter is a name made only of dots, which TailnetURL reads as an empty, dotless name and admits.

func InTailnetZone added in v0.206.0

func InTailnetZone(host string) bool

InTailnetZone reports whether host is a configured zone or sits under one of them. It is the NAME test for the callers that must treat the tailnet as a class — the research lane refuses to read it as web — and judges every installed zone, not only the primary one. host is matched the way TailnetURL matches: case-insensitive, with any trailing root dot ignored.

func IngressGuard added in v0.206.0

func IngressGuard(o IngressOptions, next http.Handler) http.Handler

IngressGuard wraps next with the SF-16 checks.

func LoopbackAddr added in v0.206.0

func LoopbackAddr(addr string) bool

LoopbackAddr reports whether a "host:port" listen address is bound to loopback — the same notion Validate enforces, exported as a FACT for callers that need the answer rather than the refusal (fleet-serve's lane auth gate: a node with no fleet_auth_token is acceptable only on a loopback listener). Malformed/unprovable addresses report false — a listener we cannot prove loopback must be treated as exposed, so the caller fails closed.

func ParseZone added in v0.206.0

func ParseZone(label, s string) (string, error)

ParseZone normalizes one tailnet DNS zone the way TailnetURL normalizes a host — lowercased, trailing root dot and a leading dot removed — so "…ts.net.", ".…ts.net" and "…TS.NET" all behave identically instead of silently never matching. "" (or only whitespace and dots) is an unset slot and returns "" with no error. A value that is not a plausible DNS zone is REFUSED, naming label (the config key and index it came from), because a typo here fails open in the reader's mind ("I set it, so my host is allowed") while failing closed in the gate.

A zone is dot-separated labels of [a-z0-9-] only: a wildcard ("*.x.ts.net"), a stray query or backslash ("x.ts.net?", "x.ts.net\") or an empty label is not a zone, and a value that is merely not matched by anything is exactly the typo this refuses. The bare "ts.net" is refused by name: as a zone it is every tailnet's, Funnel-published public hostnames included, which is the generic rule the comment on houseTailnetZones rules out.

func PublicDialControl added in v0.206.0

func PublicDialControl(network, address string, _ syscall.RawConn) error

PublicDialControl is the net.Dialer.Control hook. It fires AFTER the dialer's own DNS resolution and BEFORE connect(2), with address = the exact resolved IP the kernel will dial — so validate-time IS connect-time and every candidate address (multi-A / Happy Eyeballs) is vetted individually. It is the belt to PublicDialContext's braces: the latter pins the address, this one catches any resolution that still happened below us.

func PublicIP added in v0.206.0

func PublicIP(ip net.IP) bool

PublicIP is CheckPublicIP's boolean face, for call sites that only branch.

func PublicTransport added in v0.206.0

func PublicTransport(fallback http.RoundTripper) http.RoundTripper

PublicTransport returns a transport that carries fallback's settings with every dial path routed through PublicDialContext (and, where we build the dialer, PublicDialControl). fallback is cloned, never mutated; nil — or any non-*http.Transport RoundTripper, whose dial path we cannot reach — starts from http.DefaultTransport's defaults instead, because the dial gate is the one part that cannot be optional. Proxy is stripped for the same reason SafeTransport strips it: an env-configured proxy would be handed the request and dial anywhere on our behalf, outside the gate.

DialTLSContext is wrapped too when set. A custom TLS dialer receives the vetted IP literal rather than the hostname, so a caller that sets one must carry its own TLSClientConfig.ServerName — the alternative (leaving it unwrapped) is a dial path that silently escapes the guard.

func RedactBase added in v0.206.0

func RedactBase(raw string) string

RedactBase is a configured base URL as it may be PRINTED: unchanged unless it carries what a URL can carry that is a secret (userinfo, a query string, a fragment), in which case those are dropped and the scheme, host, port and path remain. A value that does not parse is shown as it is (a typo has to be shown to be fixed), except that whatever sits before the last "@" of its authority is masked and anything from a "?" or "#" on is cut, so a mistyped base carrying credentials is not echoed whole. An ordinary base prints byte-identically, so no message about it changes.

It lives here, below internal/config, because the tailnet guard's own refusal quotes the value it refused: a roster entry is a base URL, but nothing stops one being pasted with a token in its query string or a user:password in front of its host, and every message that names an entry must be safe to paste into a chat. internal/config.RedactBase is this function.

func SafeTransport added in v0.206.0

func SafeTransport(fallback http.RoundTripper) http.RoundTripper

SafeTransport returns a transport that carries fallback's settings with its DialContext wrapped by SafeDialContext. fallback is cloned, never mutated; nil (or any non-*http.Transport RoundTripper, whose dial path we cannot reach) starts from http.DefaultTransport's defaults instead — the dial gate is the one part that cannot be optional. Proxy is stripped for the same reason ingress.go's client strips it: an env-configured proxy would be handed the request and dial anywhere on our behalf, outside the gate.

func SetTailnetSuffix added in v0.206.0

func SetTailnetSuffix(s string) error

SetTailnetSuffix installs ONE tailnet DNS zone, replacing whatever was installed. Empty clears it (back to fail-closed). It is SetTailnetSuffixes for the original single key, kept so every caller of the one-zone form is unchanged.

func SetTailnetSuffixes added in v0.206.0

func SetTailnetSuffixes(zones []string) error

SetTailnetSuffixes installs the operator's tailnet zones, in the order given (the first is the primary one TailnetSuffix reports). Each entry is normalized by ParseZone; blank entries are unset slots and duplicates collapse. The list is installed all-or-nothing: one malformed entry refuses the call and leaves the previous list in force. nil or an empty list clears it (fail-closed).

func TailnetSuffix added in v0.206.0

func TailnetSuffix() string

TailnetSuffix reports the primary configured zone (normalized, "" when unset): the first one installed. A caller that must consider EVERY zone uses TailnetSuffixes, InTailnetZone or TailnetURL; this exists for the places that name one.

func TailnetSuffixes added in v0.206.0

func TailnetSuffixes() []string

TailnetSuffixes reports every configured zone (normalized, nil when unset). The slice is the caller's own copy.

func TailnetURL added in v0.206.0

func TailnetURL(raw string) error

TailnetURL vets a remote seat endpoint's base URL at CONFIG time, no DNS touched. Allowed: http(s) with a loopback or 100.64.0.0/10 IP-literal host, a dotless hostname (a MagicDNS short name — its resolution is enforced at dial time by SafeDialContext, which this check alone cannot do), or a hostname under one of the installed tailnet zones. Everything else — public FQDNs, public or LAN IP literals, generic .ts.net hosts, non-http schemes — fails with an error the config loader can attribute to its key.

func TailnetURLIn added in v0.206.0

func TailnetURLIn(zones []string, raw string) error

TailnetURLIn is TailnetURL judged against the zones it is GIVEN rather than the installed ones. It exists for a caller that must reach the same verdict a loaded config will reach without depending on which config this process loaded last (the doctor's roster finding), and it is the one body TailnetURL runs, so the two can never disagree about a shape. zones are expected normalized (ParseZone).

func Validate

func Validate(addr string, allowNonLocal bool) error

Validate refuses any listen host that is not loopback. The local agent's server using it is UNAUTHENTICATED by design, so binding beyond loopback exposes an RCE-class surface to the local network — a footgun for anyone publishing this repo; a fleet node behind it requires the fleet bearer on every lane, and refuses to start beyond loopback without one.

Empty-host forms ("", ":18800") are treated as non-loopback: Go's net.Listen binds ALL interfaces when the host is empty, so they are exactly as exposed as "0.0.0.0" and must be refused too. Bracketed IPv6 ("[::1]") is handled by net.SplitHostPort, which strips the brackets; we also accept a bare "[::1]" host defensively in case brackets survive.

allowNonLocal (from --listen-trusted-network) permits ONE specific non-loopback address — the tailnet address — and nothing wider: an all-interfaces address (an empty host such as ":18811", 0.0.0.0, ::) is refused even with the override, and so is an address that does not parse. Until 0.144.1 the override returned before any check, so a unit whose `--listen "$(tailscale ip -4)":18811` ran before tailscaled had an address expanded to ":18811" and served the unauthenticated endpoints on every interface instead of failing — and the unit's Restart=on-failure, written for exactly that boot race, never fired because nothing failed. The loud warning is the caller's responsibility, not the validator's — this stays a pure, side-effect-free function so it is trivial to test.

Types

type DialFunc added in v0.206.0

type DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)

DialFunc matches net.Dialer.DialContext's shape.

func PublicDialContext added in v0.206.0

func PublicDialContext(next DialFunc) DialFunc

PublicDialContext wraps next with the public-web dial gate, the mirror image of SafeDialContext. IP-literal addresses are judged directly and passed through unchanged; hostnames are resolved HERE and next receives the vetted IP LITERAL — never the hostname, so nothing between the check and the connect can re-resolve it. Refusals cost zero network activity.

A set containing ANY non-public answer is refused whole, rather than dialing the good members: that matches what the research lane's URL validation already does with a mixed answer, and on the public web a mixed answer is an attack, not the redundancy it is on a tailnet (where SafeDialContext skips the poisoned record instead, so one injected record cannot DoS a real seat).

func SafeDialContext added in v0.206.0

func SafeDialContext(next DialFunc) DialFunc

SafeDialContext wraps next with the tailnet dial gate. IP-literal addresses are judged directly and passed through unchanged; hostnames are resolved HERE, every off-tailnet answer is discarded, and next receives the vetted IP literal — never the hostname, so nothing between check and connect can re-resolve to somewhere else. Refusals cost zero network activity.

type IngressOptions added in v0.206.0

type IngressOptions struct {
	// Mode is off, warn or enforce; anything else is treated as enforce.
	Mode string
	// RequireJSONPost refuses (enforce) or logs (warn) a POST whose Content-Type is not
	// application/json.
	RequireJSONPost bool
	// AllowSameOrigin admits an Origin whose host is the request's own Host: a browser UI the
	// listener serves itself (fleet-ui). The fleet node and local-agent leave it false: the node
	// serves generated media (an SVG can carry script) from its own origin.
	AllowSameOrigin bool
	// Key is the config key a refusal names, so the operator knows what relaxes it.
	Key string
	// Logf receives the warn and enforce lines; nil discards them.
	Logf func(format string, args ...any)
}

IngressOptions configures IngressGuard.

Jump to

Keyboard shortcuts

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