netguard

package
v2.3.1 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: AGPL-3.0 Imports: 15 Imported by: 2 modules, 1 package

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 provides SSRF safeguards for outbound requests whose destination is derived from stored configuration (LLM upstream endpoints, OCI registries). Internal-range blocking is on by default (since 2.3): LLM_UPSTREAM_BLOCK_INTERNAL=false turns it off, and LLM_UPSTREAM_ALLOWED_INTERNAL_HOSTS exempts named hosts, for deployments proxying to internal LLMs. The setting is parsed once, at startup (Configure).

Internal-range blocking is enforced at dial time, on the exact IP address being connected (via net.Dialer.Control). This closes the DNS-rebinding TOCTOU window: there is no separate validate-then-resolve step for an attacker-controlled DNS server to exploit — the address that is checked is the address that is dialed.

Index

Constants

View Source
const (
	// EnvBlockInternal ("LLM_UPSTREAM_BLOCK_INTERNAL") controls blocking of
	// connections to internal/reserved IP ranges at dial time. Unset or empty
	// means true; "false" turns blocking off; any other value is a
	// configuration error (Configure).
	EnvBlockInternal = "LLM_UPSTREAM_BLOCK_INTERNAL"

	// EnvAllowedHosts ("LLM_UPSTREAM_ALLOWED_HOSTS") is a comma-separated
	// allowlist of upstream hostnames. Entries starting with '.' match the
	// apex domain and any subdomain on a label boundary (".anthropic.com"
	// matches "anthropic.com" and "api.anthropic.com", never
	// "evil-anthropic.com"). When set, upstream hosts not on the list are
	// refused.
	EnvAllowedHosts = "LLM_UPSTREAM_ALLOWED_HOSTS"

	// EnvAllowInternal is the existing development flag that disables
	// internal-network restrictions platform-wide.
	EnvAllowInternal = "ALLOW_INTERNAL_NETWORK_ACCESS"

	// EnvAllowedInternalHosts ("LLM_UPSTREAM_ALLOWED_INTERNAL_HOSTS") names
	// upstream hosts that are exempt from internal-range blocking, using the
	// same matching as EnvAllowedHosts (".svc.cluster.local" matches every
	// in-cluster Service). It exists because the two existing controls cannot
	// express "reach this in-cluster model server, keep blocking everything
	// else internal": EnvAllowInternal disables the policy platform-wide, and
	// EnvAllowedHosts is a global allowlist, so using it to permit a cluster
	// host silently restricts every external provider not also listed.
	//
	// This is an additive exemption. It is consulted before EnvAllowedHosts and
	// widens the policy only for the hosts named, so an operator can run an
	// InferencePool-backed upstream alongside SaaS providers with egress
	// blocking left on. It also exempts the hosts named from the plugin host
	// rule (PluginHostExempt), for an internal registry or gRPC plugin.
	EnvAllowedInternalHosts = "LLM_UPSTREAM_ALLOWED_INTERNAL_HOSTS"
)

Variables

View Source
var ErrInternalPluginHost = errors.New("plugin host is an internal address")

ErrInternalPluginHost matches every InternalPluginHostError (errors.Is).

View Source
var ErrPolicyDial = errors.New("destination resolved to a blocked internal address")

ErrPolicyDial is returned from a policy-built HTTP client when the address a hostname resolved to is blocked. It is permanent: retrying will not change the answer.

View Source
var ErrURLPolicy = errors.New("url is not allowed by the outbound URL policy")

ErrURLPolicy is the default sentinel wrapped by every URLPolicy error. Features that need their own sentinel set PolicyOptions.Err.

View Source
var LookupIP = net.LookupIP

LookupIP resolves hostnames for the plugin host checks. A variable so tests in any package can stub DNS (the plugin security services resolve through it too).

Functions

func CheckPluginHost added in v2.3.0

func CheckPluginHost(host string) error

CheckPluginHost applies the plugin host rule to host (an IP literal or a hostname, without a port). No DNS lookup is made when internal hosts are allowed or the host is exempt.

func CheckPluginHostWith added in v2.3.0

func CheckPluginHostWith(exempt Exemption, host string) error

CheckPluginHostWith is CheckPluginHost with a plugin's own "Allow internal host" exemption (CommandExemption): its hosts pass too.

func CommandTargetsInternalHost added in v2.3.0

func CommandTargetsInternalHost(command string) bool

CommandTargetsInternalHost reports whether a plugin command names an internal address: a loopback, private, link-local, unique-local, shared (CGNAT, 100.64.0.0/10) or unspecified IP (IPv4-mapped IPv6 included), or localhost. It looks at the host of every URL in the command (grpc://10.0.0.1:50051), at host:port tokens, and at bare IP literals. Flag values (--upstream=grpc://10.0.0.1), quoted values and comma-separated lists are unpacked first.

URL hosts are what a plugin dials, so there the legacy IPv4 spellings that inet_aton and many dialers accept are decoded too: decimal (2130706433), hex (0x7f000001), octal (0177.0.0.1) and short forms (127.1). Elsewhere only canonical IP literals count, so a version ("10.2"), a ratio ("1:2") or a path (/opt/plugins/v10.2/run) is not mistaken for an address.

It does no DNS resolution: a hostname that resolves to an internal address is not detected here (the plugin security service resolves and checks URL hosts when the API validates the command). Translated IPv6 forms (NAT64, IPv4-compatible, 6to4) are not decoded.

func Configure added in v2.3.0

func Configure(getenv func(string) string) error

Configure reads LLM_UPSTREAM_BLOCK_INTERNAL through getenv and stores it for every later check. Call it once at startup and refuse to start on an error; netguard is consulted lazily from many places, so the environment is not read again per request.

func DialControl

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

DialControl is a net.Dialer Control hook that rejects connections to internal IP ranges when blocking is enabled. It runs after DNS resolution, once per connection attempt, on the exact address being dialed — so a DNS answer that changes between validation and connection cannot bypass it.

func DisabledWarning added in v2.3.0

func DisabledWarning() string

DisabledWarning is the warning to log at startup when internal-range blocking is off, naming the setting that turned it off; "" when it is on.

func HTTPTransport

func HTTPTransport() *http.Transport

HTTPTransport returns an *http.Transport (based on http.DefaultTransport) whose dials are guarded by DialControl. Use it for any HTTP client whose destination comes from stored configuration.

The exemption is applied here rather than in DialControl because Control runs after DNS resolution and sees only an IP, whereas the transport hands DialContext the hostname it set out to reach — the same name ValidateUpstreamURL checked. Keying the exemption on that name is what makes a host allowlist expressible at all, and it does not reopen the DNS-rebinding window the Control hook closes: an exempted name is one the operator has declared may resolve internally, not one an attacker chose.

func HostIsInternal added in v2.3.0

func HostIsInternal(host string, lookup func(string) ([]net.IP, error)) bool

HostIsInternal reports whether host (an IP literal or a hostname) is an internal address: localhost or *.localhost, an IP in internalCIDRs, or a hostname that lookup resolves to any such IP. A hostname that does not resolve counts as internal, so a name that resolves differently for the dialer cannot slip past. lookup is net.LookupIP outside tests.

func HostMatches

func HostMatches(host, pattern string) bool

HostMatches compares a lower-cased host with a pattern: ".example.com" matches example.com and any subdomain; anything else is an exact match.

func IsInternalHost added in v2.3.0

func IsInternalHost(host string) bool

IsInternalHost reports whether a host literal (no DNS lookup) is localhost or an internal IP address, including IPv4-mapped IPv6 forms, a trailing dot, and the legacy IPv4 spellings described on CommandTargetsInternalHost.

func IsInternalHostname

func IsInternalHostname(host string) bool

IsInternalHostname reports whether a hostname names a local or cluster-internal destination by convention.

func IsInternalIP

func IsInternalIP(ip net.IP) bool

IsInternalIP reports whether ip belongs to a private, loopback, shared (CGNAT), link-local, unique-local, "this network" or unspecified range.

func IsUnresolvedPluginHost added in v2.3.0

func IsUnresolvedPluginHost(err error) bool

IsUnresolvedPluginHost reports whether err refuses a plugin host only because its name did not resolve (as opposed to resolving internally).

func NewDialer

func NewDialer() *net.Dialer

NewDialer returns a net.Dialer whose connections are guarded by DialControl.

func ParseBlockInternal added in v2.3.0

func ParseBlockInternal(v string) (bool, error)

ParseBlockInternal parses a LLM_UPSTREAM_BLOCK_INTERNAL value: unset or empty is true, otherwise strconv.ParseBool after trimming spaces. Any other value is an error, never a silent default, since it is a security setting.

func PluginDialControl added in v2.3.0

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

PluginDialControl is a net.Dialer Control hook applying the plugin host rule to the exact address being dialled, after DNS resolution, so a DNS answer that changes after CheckPluginHost cannot reach an internal address.

func PluginHTTPTransport added in v2.3.0

func PluginHTTPTransport() http.RoundTripper

PluginHTTPTransport returns the transport for OCI client requests (registry, signature and token-server connections): the upstream URL policy (scheme, LLM_UPSTREAM_ALLOWED_HOSTS) on every request, and every dial guarded by PluginDialControl whatever LLM_UPSTREAM_BLOCK_INTERNAL says. A host named in LLM_UPSTREAM_ALLOWED_INTERNAL_HOSTS is dialled unguarded, as HTTPTransport does, keyed on the name the request set out to reach. When internal plugin hosts are allowed, ALLOW_INTERNAL_NETWORK_ACCESS also lifts LLM_UPSTREAM_BLOCK_INTERNAL, so PluginDialControl is the only internal-range guard needed.

Behind a proxy (HTTPS_PROXY / HTTP_PROXY, NO_PROXY honoured) the dial goes to the proxy, which is operator configuration, not a plugin host: the proxy endpoint is dialled unguarded, and the request's target is checked by name (CheckPluginHost) before it is handed to the proxy. Connect-time rebinding protection does not apply to the target then; the proxy is responsible for egress. A target that bypasses the proxy (NO_PROXY) is dial-guarded.

func PluginHTTPTransportFor added in v2.3.0

func PluginHTTPTransportFor(exempt Exemption) http.RoundTripper

PluginHTTPTransportFor is PluginHTTPTransport with a plugin's own "Allow internal host" exemption (CommandExemption): its registry and signature hosts are dialled unguarded too. Use one per exemption, so connections are never shared across plugins with different switches.

func PluginHostExempt added in v2.3.0

func PluginHostExempt(host string) bool

PluginHostExempt reports whether host is named in LLM_UPSTREAM_ALLOWED_INTERNAL_HOSTS (exact, or a ".suffix" entry), which exempts it from the plugin host rule.

func PluginInternalHostsAllowed added in v2.3.0

func PluginInternalHostsAllowed() bool

PluginInternalHostsAllowed reports whether ALLOW_INTERNAL_NETWORK_ACCESS lifts the plugin host rule.

func PooledByExemption added in v2.3.0

func PooledByExemption(build func(Exemption) http.RoundTripper) http.RoundTripper

PooledByExemption returns a RoundTripper for a client shared by many assets: each request goes through a transport of its own for the exemption its context carries (Exemption.WithContext), built by build and kept for reuse. Connections are pooled per exemption, so one dialled under an asset's exemption is never reused for a request without it, which a single pool would allow (the dial-time check runs once per connection).

func Refusal added in v2.3.0

func Refusal(err error) (string, bool)

Refusal returns the policy's reason when err is, or wraps, a RefusalError: from ValidateUpstreamURL and the Exemption checks, or from a dial that DialControl refused.

func SetBlockInternal added in v2.3.0

func SetBlockInternal(b bool) (previous bool)

SetBlockInternal sets the stored setting directly and returns the previous one. For tests (netguardtest.AllowInternal) and hosts that configure netguard themselves.

func ValidateUpstreamURL

func ValidateUpstreamURL(u *url.URL) error

ValidateUpstreamURL validates an outbound upstream URL against the configured policy:

  1. Scheme must be http or https.
  2. If LLM_UPSTREAM_ALLOWED_INTERNAL_HOSTS names the host, it is permitted outright — this is the in-cluster exemption and it short-circuits the rules below.
  3. If LLM_UPSTREAM_ALLOWED_HOSTS is set, the hostname must match an entry (exact, case-insensitive; ".suffix" entries match the apex and subdomains on a label boundary).
  4. If internal blocking is enabled and the host is an IP literal, it must not be an internal address (an early, clear error; hostnames are enforced at dial time by DialControl/HTTPTransport, which also covers DNS-rebinding).

This function performs no DNS resolution, so it is cheap on the request path and cannot be raced against a later lookup.

func ValidatingHTTPTransport

func ValidatingHTTPTransport() http.RoundTripper

ValidatingHTTPTransport returns a RoundTripper that applies the full URL policy (scheme + host allowlist) to every request — including redirects and any request issued by wrapping clients — on top of HTTPTransport's dial-time internal-IP guard. Use it for clients where per-request URL validation cannot be guaranteed at the call sites.

Types

type Exemption added in v2.3.0

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

Exemption is one managed asset's "Allow internal host" switch (an LLM, an embedder, a tool, a datasource, a guardrail, a plugin): with it on, the asset's own hosts may be internal addresses while blocking stays on for everything else, including another asset on the same host. It lifts only the internal-address check: LLM_UPSTREAM_ALLOWED_HOSTS still applies, and the environment settings (LLM_UPSTREAM_BLOCK_INTERNAL, LLM_UPSTREAM_ALLOWED_INTERNAL_HOSTS, ALLOW_INTERNAL_NETWORK_ACCESS) stay global overrides. The zero value exempts nothing.

Every client an asset uses goes through one of its methods, so the rule is the same wherever the asset is called from, Studio or an edge.

func CommandExemption added in v2.3.0

func CommandExemption(allow bool, command string) Exemption

CommandExemption is a plugin's "Allow internal host" exemption: the hosts of the URLs in its command (oci:// registry, grpc:// host), when allow.

func ExemptionFor added in v2.3.0

func ExemptionFor(allow bool, targets ...string) Exemption

ExemptionFor is the exemption of an asset whose switch is allow, for the hosts of its own targets: URLs ("https://ollama:11434/v1"), "host:port" or bare hosts. A target without a host adds nothing. allow false, or no targets, is the zero Exemption.

func ExemptionFromContext added in v2.3.0

func ExemptionFromContext(ctx context.Context) Exemption

ExemptionFromContext is the exemption WithContext stored in ctx, or the zero Exemption.

func (Exemption) DialContext added in v2.3.0

func (e Exemption) DialContext(ctx context.Context, network, address string) (net.Conn, error)

DialContext dials address with the dial-time check, except for the exemption's hosts and LLM_UPSTREAM_ALLOWED_INTERNAL_HOSTS. For clients that are not HTTP (a pgx pool, a Redis client).

func (Exemption) HTTPClient added in v2.3.0

func (e Exemption) HTTPClient(timeout time.Duration) *http.Client

HTTPClient is an *http.Client on HTTPTransport.

func (Exemption) HTTPTransport added in v2.3.0

func (e Exemption) HTTPTransport() http.RoundTripper

HTTPTransport is ValidatingHTTPTransport with the exemption: the URL policy on every request (redirects included) and the dial-time check on the resolved address, except for the exemption's hosts. The zero Exemption shares one transport.

func (Exemption) Has added in v2.3.0

func (e Exemption) Has(host string) bool

Has reports whether host is one of the exemption's hosts.

func (Exemption) Hosts added in v2.3.0

func (e Exemption) Hosts() []string

Hosts returns the exempted hosts.

func (Exemption) Transport added in v2.3.0

func (e Exemption) Transport() *http.Transport

Transport is HTTPTransport without the URL check: the dial-time check with the exemption, as an *http.Transport whose pool settings a caller may tune.

func (Exemption) ValidateURL added in v2.3.0

func (e Exemption) ValidateURL(u *url.URL) error

ValidateURL is ValidateUpstreamURL with the exemption.

func (Exemption) WithContext added in v2.3.0

func (e Exemption) WithContext(ctx context.Context) context.Context

WithContext returns ctx carrying the exemption, for a client that serves many assets through one RoundTripper (the gateway's upstream pool): only PooledByExemption reads it, so a connection dialled under one asset's exemption is never reused for another asset's request.

type InternalPluginHostError added in v2.3.0

type InternalPluginHostError struct {
	Host string
	// Unresolved is set when Host is a name whose lookup failed, rather
	// than one that resolved to an internal address.
	Unresolved bool
}

InternalPluginHostError names the refused host and the setting that allows it, so an operator can act on the log line or API error alone.

func (*InternalPluginHostError) Error added in v2.3.0

func (e *InternalPluginHostError) Error() string

func (*InternalPluginHostError) Is added in v2.3.0

func (e *InternalPluginHostError) Is(target error) bool

Is makes errors.Is(err, ErrInternalPluginHost) true.

type PolicyOptions

type PolicyOptions struct {
	// AllowInternal permits loopback, RFC1918, link-local and other internal
	// destinations for every URL the policy checks.
	AllowInternal bool
	// AllowedHosts, when non-empty, restricts destinations to these hosts
	// (exact, or ".suffix" for a domain and its subdomains). A host named
	// exactly here may also be internal.
	AllowedHosts []string
	// DeniedHosts always rejects and wins over AllowedHosts.
	DeniedHosts []string
	// ExemptHosts are exact hosts permitted to be internal without opening
	// the policy for anything else (a per-object exemption, e.g. one
	// administrator-approved Dashboard on a private address).
	ExemptHosts []string
	// Err is the sentinel wrapped in every validation error. Defaults to
	// ErrURLPolicy.
	Err error
	// InternalHint is appended to "internal address" rejections so the
	// message names the switch that would allow it.
	InternalHint string
}

PolicyOptions configures a URLPolicy.

type RefusalError added in v2.3.0

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

RefusalError is a refusal by the upstream policy: a host outside LLM_UPSTREAM_ALLOWED_HOSTS or an internal address with blocking on. Its message names the setting, which is what tells an operator how to fix it, so a caller that hides other upstream errors behind a generic message still passes this one on (see Refusal).

func (*RefusalError) Error added in v2.3.0

func (e *RefusalError) Error() string

type URLPolicy

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

URLPolicy decides where an outbound request derived from stored configuration may go. It is always on, independent of the LLM_UPSTREAM_* environment gating in this package, because the URLs it guards are typed in by users and are an exfiltration vector.

Two layers: Validate checks the URL as written (scheme, userinfo, host, IP literals, allow/deny lists) whenever a URL is stored and again before every use; the client built by NewHTTPClient re-checks the resolved IP at connect time so a hostname that resolves to an internal address (or is re-pointed there later) is still blocked.

func NewURLPolicy

func NewURLPolicy(o PolicyOptions) *URLPolicy

NewURLPolicy builds a policy from options.

func (*URLPolicy) ExplicitlyAllowed

func (p *URLPolicy) ExplicitlyAllowed(host string) bool

ExplicitlyAllowed reports whether the operator named this exact host in the allow list or the exemptions; such hosts may be internal.

func (*URLPolicy) HostAllowed

func (p *URLPolicy) HostAllowed(host string) error

HostAllowed applies the deny list, then the allow list.

func (*URLPolicy) NewHTTPClient

func (p *URLPolicy) NewHTTPClient(timeout time.Duration) *http.Client

NewHTTPClient returns a client whose dialer rejects internal addresses at connect time (unless permitted), which never uses a proxy (a proxy would bypass the dial guard) and never follows redirects: a 3xx would send the request somewhere the administrator did not approve.

func (*URLPolicy) NewPinnedHTTPClient added in v2.3.0

func (p *URLPolicy) NewPinnedHTTPClient(timeout time.Duration, ip net.IP) *http.Client

NewPinnedHTTPClient is NewHTTPClient for one of several servers behind a hostname that resolves to more than one address: every connection goes to ip, while the URL, the Host header and the TLS server name keep the hostname. Whether an internal ip may be dialled is decided for the hostname, exactly as for an unpinned dial of it.

Like NewHTTPClient it is a constructor: each call builds a new transport with its own connection pool. Callers keep the client for as long as they talk to that address (the Tyk Gateway connections pool one per node) rather than building one per request.

func (*URLPolicy) Validate

func (p *URLPolicy) Validate(raw string) (*url.URL, error)

Validate parses and checks a URL. The returned URL is normalised.

func (*URLPolicy) WithExemptHosts

func (p *URLPolicy) WithExemptHosts(hosts ...string) *URLPolicy

WithExemptHosts returns a copy of the policy that additionally permits the named hosts to be internal.

Directories

Path Synopsis
Package netguardtest stubs the DNS lookups of the plugin host checks (netguard.LookupIP), so tests that name registries or plugin hosts stay hermetic.
Package netguardtest stubs the DNS lookups of the plugin host checks (netguard.LookupIP), so tests that name registries or plugin hosts stay hermetic.

Jump to

Keyboard shortcuts

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