ssrf

package
v1.0.548 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 10 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 ssrf is the SSRF (server-side request forgery) guard: the private/internal CIDR table, host resolution checks with a short-TTL DNS cache, and the connect-time dialer control that closes the DNS-rebinding TOCTOU window. Extracted from package main (proxy.go + security.go) per ADR-0002 so outbound-fetching leaves (blocklist feeds, threat feeds) can move without importing main. package main keeps thin wrappers (isPrivateIP / isPrivateHost / the swappable ssrfSafeDialContext var) so every existing call site — and the CodeQL inline-guard convention at those sites — is unchanged.

Index

Constants

This section is empty.

Variables

View Source
var ErrBlocked = errors.New("ssrf control: destination blocked")

ErrBlocked is the sentinel every SSRF REFUSAL wraps — the connect-time Control rejection and the pre-flight PrivateHostContext verdict alike — so a caller can errors.Is() a security block apart from a genuine failure to reach or resolve the destination.

Both layers matter because the guard has THREE outcomes, not two: allowed, refused-as-private, and could-not-determine (DNS failure, or the caller's deadline expiring mid-lookup). Only the middle one is an accusation. Without the sentinel a caller could tell them apart only by "the guard returned an error", which charges an SSRF refusal for every DNS outage — and a counter whose runbook says "this host resolved to a private address" must not move when the truth is "we never found out" (Codex review, PR #1369).

View Source
var ErrLookupBudget = errors.New("ssrf pre-flight: DNS lookup exceeded its budget")

ErrLookupBudget is the cancellation cause PrivateHostBudget attaches to its miss-path lookup, and is wrapped by the error it returns when that budget — rather than the caller's own context — is what ended the lookup. It is NOT ErrBlocked: a resolver that did not answer in time demonstrated nothing about the destination.

Functions

func AllowLoopbackForTest

func AllowLoopbackForTest() (restore func())

AllowLoopbackForTest removes the loopback ranges from the guard's CIDR table and returns a restore func. Test support for E2E fixtures that must CONNECT/dial to 127.0.0.1 through the real proxy path — never call from production code. The DNS verdict cache is reset on both swap and restore.

func CacheCleanup

func CacheCleanup()

CacheCleanup ages the cache by one generation (called periodically from the main tick loop, connlimit_startup.go). Constant time under the lock: the previous generation is dropped whole rather than swept entry by entry, and the current generation's still-live entries remain readable as the new previous generation. Expired entries are never served in the meantime.

func CacheDelete

func CacheDelete(host string)

CacheDelete removes a host's cached verdict (test support).

func CacheReset

func CacheReset()

CacheReset replaces the DNS verdict cache with an empty one (test support; pairs with AllowLoopbackForTest so stale verdicts don't leak across the guard-table swap).

func CacheStore

func CacheStore(host string, private bool)

CacheStore seeds a DNS verdict directly. Test support: lets tests mark loopback hosts public so local httptest servers pass the guard; pair with CacheDelete in cleanup.

func Control

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

Control rejects a connection when the resolved peer address falls into any private/internal range. Installed as net.Dialer.Control, it runs AFTER DNS resolution and IMMEDIATELY BEFORE connect(2), closing the TOCTOU window that a pre-flight LookupHost leaves open (DNS-rebinding: public IP on the pre-check, private IP on the real dial).

address is the resolved IP:port that the kernel is about to connect to (never a hostname at this layer), so net.ParseIP always succeeds for a well-formed stack. We still fail-closed on any parse anomaly.

func PrivateAddr added in v1.0.207

func PrivateAddr(addr netip.Addr) bool

PrivateAddr reports whether addr falls within any private/internal range.

It is the allocation-free classification entry point: callers holding a netip.Addr (netip.ParseAddr never heap-allocates, unlike net.ParseIP) reach the guard table without materialising a net.IP.

Two normalisations reproduce net.IPNet.Contains semantics exactly, and both are load-bearing for the guard:

  • Unmap: netip.Prefix.Contains returns false when an IPv4-mapped IPv6 address is tested against an IPv4 prefix, whereas net.IPNet.Contains called To4() first. Without the unmap, ::ffff:127.0.0.1 would be classified PUBLIC — the exact mapped-form bypass the table comment above warns about.
  • Zone strip: netip.Prefix.Contains returns false for ANY address carrying a zone, so fe80::1%eth0 would likewise read as public.

func PrivateHost

func PrivateHost(hostport string) error

PrivateHost resolves host (host or host:port) and returns an error if any resolved IP falls within a private/internal range. This prevents SSRF via proxy CONNECT to loopback, RFC 1918, link-local, or metadata endpoints. Results are cached in the package DNS cache (30s TTL) to avoid redundant DNS lookups.

The lookup on the miss path is UNBOUNDED — it runs under context.Background(), so a wedged resolver blocks the calling goroutine for the system resolver's full budget. Callers on a request goroutine should use PrivateHostContext and pass the deadline they are already working to.

func PrivateHostBudget added in v1.0.448

func PrivateHostBudget(ctx context.Context, hostport string, budget time.Duration) error

PrivateHostBudget is PrivateHostContext with the miss-path DNS lookup additionally capped at budget.

It exists for the data-plane tunnel paths (CONNECT bypass, CONNECT inspect, WebSocket, SOCKS5). Each of them bounds its upstream dial at 10 s, but ran this guard in front of that dial under context.Background(): the guard resolves the same name with no deadline and no link to the client, so a resolver that stops answering held every such request goroutine — with its client connection, descriptor and per-IP connection-limiter slot — for the OS resolver's full budget (timeout × attempts × nameservers, × search domains; 12 s measured against a two-nameserver resolv.conf, 30 s+ with glibc defaults and three), even after the client had hung up. The dial bound was unreachable because the unbounded step ran first.

The timer is created only on a cache MISS, so the per-request hot path — a cached verdict — pays nothing for the bound. Verdicts, caching (failures are still never cached) and fail-closed behaviour are identical to PrivateHostContext; only how long a lookup may take changes. budget <= 0 means no additional bound.

func PrivateHostContext added in v1.0.228

func PrivateHostContext(ctx context.Context, hostport string) error

PrivateHostContext is PrivateHost with the DNS lookup bounded by ctx.

Added by CHAOS-65: the OCSP responder URL is read from the peer's own certificate and guarded on a TLS handshake running on the request goroutine, so the guard itself must not become the unbounded call. Behaviour is otherwise identical, cache included; PrivateHost delegates here with a background context so every existing caller is byte-identical.

func PrivateIP

func PrivateIP(ip net.IP) bool

PrivateIP reports whether ip falls within any private/internal range. It is the net.IP-shaped façade over PrivateAddr, kept because the SSRF call sites (and the CodeQL inline-guard convention at those sites) pass net.IP.

func SafeDialContext

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

SafeDialContext is a net.Dialer.DialContext replacement that rejects connections to private/internal IPs. Use as the DialContext in an http.Transport to prevent SSRF at the network level, independent of URL validation. Safe against DNS rebinding because the check runs on the post-resolution address that will actually be connected.

func SetLookupHostForTest added in v1.0.448

func SetLookupHostForTest(fn func(ctx context.Context, host string) ([]string, error)) (restore func())

SetLookupHostForTest replaces the resolver the guard's miss path uses and returns a restore func. Test support — never call from production code. The DNS verdict cache is reset on both swap and restore so a verdict produced by one resolver is never served under the other.

Types

This section is empty.

Jump to

Keyboard shortcuts

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