Documentation
¶
Overview ¶
Package ssrf provides URL validation and a hardened HTTP transport to prevent server-side request forgery (SSRF). Use this package to vet any URL before making an outbound HTTP request.
Trust model: DNS resolution is delegated to net.DefaultResolver (or a custom resolver via WithResolver). The transport resolves a hostname once and dials only the resolved literal IPs. Additionally, a net.Dialer Control hook validates the actually-connected IP at socket creation time, providing defense-in-depth against DNS rebinding/TOCTOU attacks even if the resolve-once layer is somehow bypassed.
Unsupported by design ¶
The following features are intentionally NOT implemented (docs/non-goals.md has the reasons):
- Custom allow/deny IP lists: WithAddressPolicy(func(netip.Addr) bool) already provides this.
- Hostname allowlist/denylist: Application-layer policy, not core SSRF defense.
- Happy Eyeballs (RFC 8305): Security library prioritizes correctness over speed.
- Response body size limit: Use io.LimitReader at the application layer.
- Blanket 2001::/23 block: Overly broad; we block specific non-routable sub-ranges.
- ISATAP embedded IPv4: Uses fe80::/64 (already blocked) or routable prefixes.
- DNS-over-HTTPS/TLS resolver: WithResolver enables plugging in any implementation.
Index ¶
- func IsPublicAddr(addr netip.Addr) bool
- func IsPublicHost(host string) bool
- func SafeRedirectPolicy(next func(req *http.Request, via []*http.Request) error) func(req *http.Request, via []*http.Request) error
- func SafeTransport(opts ...TransportOption) *http.Transport
- func ValidateURL(raw string) error
- type AddressPolicy
- type Error
- type ErrorKind
- type Resolver
- type TransportOption
- type URLPolicy
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsPublicAddr ¶
IsPublicAddr reports whether addr is a globally routable unicast address. Rejects loopback, private (RFC 1918/RFC 4193), link-local, multicast, unspecified, shared (RFC 6598 CGNAT), "this host" (0.0.0.0/8), former Class E (240.0.0.0/4), non-routable documentation/benchmarking ranges (RFC 5737, RFC 2544, RFC 6666, RFC 3849, RFC 9637, RFC 9602), and embedded IPv4 inside 6to4, NAT64, Teredo, or IPv4-compatible wrappers.
func IsPublicHost ¶
IsPublicHost reports whether host, as written, is a literal public address or a dotted name other than localhost. It returns false for localhost, bare hostnames, RFC 1918 and link-local literals, and RFC 6598 shared address space. It performs no DNS lookup, so a public name that resolves to a private address is reported public: pair it with SafeTransport, which checks every resolved and connected address.
Like ValidateURL it emits no log line: the whole validation path returns its verdict and lets the caller decide whether to record it.
func SafeRedirectPolicy ¶
func SafeRedirectPolicy( next func(req *http.Request, via []*http.Request) error, ) func(req *http.Request, via []*http.Request) error
SafeRedirectPolicy returns an http.Client CheckRedirect function that validates each redirect target URL against SSRF rules (HTTPS-only). For custom schemes, use URLPolicy.RedirectPolicy.
Example ¶
package main
import (
"net/http"
"github.com/cplieger/go/ssrf"
)
func main() {
client := &http.Client{
Transport: ssrf.SafeTransport(),
CheckRedirect: ssrf.SafeRedirectPolicy(nil),
}
_ = client // use client for outbound requests
}
Output:
func SafeTransport ¶
func SafeTransport(opts ...TransportOption) *http.Transport
SafeTransport returns an *http.Transport hardened against SSRF and DNS rebinding. Use WithAddressPolicy, WithDialer, WithResolver, WithAllowedPorts and WithLogger to customize.
Its HTTP2 PING window closes a silent connection 13 s after its last frame: only a request whose deadline is above 13 s fails with client connection lost before its header timeout, so a retry by the caller dials a new connection. Lowering ResponseHeaderTimeout means lowering HTTP2's timeouts.
Example ¶
package main
import (
"net/http"
"github.com/cplieger/go/ssrf"
)
func main() {
client := &http.Client{
Transport: ssrf.SafeTransport(),
}
_ = client // use client for outbound requests
}
Output:
func ValidateURL ¶
ValidateURL checks that a URL uses HTTPS and that its host, as written, is a literal public address or a dotted name other than localhost. It rejects HTTP (cleartext), non-HTTP schemes, loopback, private and link-local literals, and hostnames without dots ("localhost", "internal"). It performs no DNS lookup, so a public name that resolves to a private address passes: pair it with SafeTransport, which checks every resolved and connected address.
Example ¶
package main
import (
"fmt"
"github.com/cplieger/go/ssrf"
)
func main() {
err := ssrf.ValidateURL("https://example.com/data.json")
fmt.Println(err)
}
Output: <nil>
Types ¶
type AddressPolicy ¶
AddressPolicy controls whether a resolved IP address is allowed or denied. Return true to allow the connection, false to block it. The default policy (used when none is provided) is IsPublicAddr.
type Error ¶
type Error struct {
// Err is the underlying error, if any.
Err error
// Msg is a human-readable description.
Msg string
// Host is the hostname or IP that triggered the error (may be empty).
Host string
// Kind classifies the refusal; switch on it after errors.As.
Kind ErrorKind
// contains filtered or unexported fields
}
Error is a structured SSRF validation error with a machine-readable Kind.
type ErrorKind ¶
type ErrorKind int
ErrorKind classifies SSRF validation failures. Consumers can use errors.As(*Error) and switch on Kind for programmatic handling.
const ( // KindInvalidURL indicates the URL could not be parsed. KindInvalidURL ErrorKind = iota + 1 // KindBadScheme indicates the URL scheme is not allowed. KindBadScheme // KindEmptyHost indicates the URL has no host component. KindEmptyHost // KindLocalhost indicates the URL points to localhost. KindLocalhost // KindBareHostname indicates a hostname without dots (e.g. "internal"). KindBareHostname // KindNonPublicIP indicates the resolved IP is not globally routable. KindNonPublicIP // KindDNSFailed indicates DNS resolution failed. KindDNSFailed // KindPolicyDenied indicates the custom policy rejected the IP. KindPolicyDenied // KindBadPort indicates the port is not in the allowed set. KindBadPort // KindTooManyRedirects indicates a redirect chain exceeded the hop limit. KindTooManyRedirects // KindInvalidHost indicates the host is not a canonical host at all: it // carries a byte no DNS label may hold, or an IP literal carries a zone // identifier. Distinct from KindNonPublicIP, which means a well-formed host // that points somewhere private. KindInvalidHost )
func (ErrorKind) String ¶
String returns the Kind's snake_case reason label, or "blocked" for a value outside the constants. It is the "reason" the redirect policy and the address-policy refusals log for this Kind. The transport's structural refusals and its disallowed-port refusal log finer labels of their own ("port_not_allowed" for KindBadPort, and "disallowed_network" and "unparseable_ip" for KindNonPublicIP, among others), so a transport line's reason can be finer than String for the Kind the call returns.
type Resolver ¶
type Resolver interface {
// LookupNetIP resolves host to its addresses for network ("ip", "ip4" or
// "ip6"), as net.Resolver.LookupNetIP does.
LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
}
Resolver abstracts DNS resolution for testing and custom environments. The standard library's net.Resolver satisfies this interface.
type TransportOption ¶
type TransportOption func(*transportConfig)
TransportOption configures SafeTransport.
func WithAddressPolicy ¶
func WithAddressPolicy(p AddressPolicy) TransportOption
WithAddressPolicy sets a custom allow/deny policy for resolved IP addresses. The policy is called after unmapping IPv4-mapped IPv6 addresses. A nil policy is ignored (the default IsPublicAddr policy is retained).
func WithAllowedPorts ¶
func WithAllowedPorts(ports ...uint16) TransportOption
WithAllowedPorts sets the ports that outbound connections may target. By default only port 443 is allowed (matching the HTTPS-only posture). Passing no ports retains that default. Later calls replace the set, so this is last-wins with itself.
There is deliberately no way to switch the port check off. A caller whose peer lives on a port it cannot enumerate ahead of time should build its transport once the destination IS known and pass that one port — pinning the destination it already validated is a stronger check than any standing permissive policy, and it keeps the widest setting off this library's surface.
func WithDialer ¶
func WithDialer(d *net.Dialer) TransportOption
WithDialer sets a custom net.Dialer used for outbound connections. The dialer's DialContext is wrapped with SSRF-safe DNS resolution; callers can customize Timeout, KeepAlive, and other dialer fields. A nil dialer is ignored (the default dialer is retained).
The dialer's Control hook is always overwritten with the SSRF socket-time IP re-validation hook and cannot be supplied by the caller; this is the defense-in-depth layer against DNS rebinding and must not be bypassed. Its ControlContext is cleared on the transport's copy for the same reason, since a set ControlContext would run in place of Control.
func WithLogger ¶
func WithLogger(l *slog.Logger) TransportOption
WithLogger sets the logger the transport writes its dial and Control refusals to, so a caller running one transport per peer can attribute each line. A nil logger is ignored; with none, each line goes to slog.Default as it is written. The redirect policies take their logger from URLPolicy.WithLogger.
func WithResolver ¶
func WithResolver(r Resolver) TransportOption
WithResolver sets a custom DNS resolver for hostname resolution. Useful for testing or environments with custom resolvers (e.g., CoreDNS sidecar). A nil resolver is ignored (net.DefaultResolver is retained).
type URLPolicy ¶
type URLPolicy struct {
// contains filtered or unexported fields
}
URLPolicy validates URL schemes and hosts before requests or redirect hops. The zero value allows HTTPS only, so it is ready for use without a constructor. A URLPolicy performs no DNS lookup; pair it with SafeTransport when making requests so resolved and connected addresses are validated at the dial boundary.
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/cplieger/go/ssrf"
)
func main() {
// Allow plain HTTP alongside HTTPS (e.g. for legacy endpoints).
policy := ssrf.NewURLPolicy("https", "http")
client := &http.Client{
Transport: ssrf.SafeTransport(ssrf.WithAllowedPorts(443, 80)),
CheckRedirect: policy.RedirectPolicy(nil),
}
_ = client
fmt.Println(policy.Validate("https://example.com/data.json"))
}
Output: <nil>
func NewURLPolicy ¶
NewURLPolicy returns a URL policy allowing the given schemes. With no schemes it returns the HTTPS-only default. An empty scheme is skipped: a protocol-relative URL has an empty scheme, so allowing "" would let //8.8.8.8/ through; if no scheme remains, the HTTPS-only default applies.
Scheme matching is case-insensitive over ASCII and byte-exact outside it, which is the whole of RFC 3986's scheme grammar. Folding it over Unicode would mean a scheme the grammar excludes could match an allowed one: strings.ToLower maps U+212A KELVIN SIGN to "k", so "\u212Aafka" would satisfy an allowed "kafka".
func (URLPolicy) RedirectPolicy ¶
func (p URLPolicy) RedirectPolicy( next func(req *http.Request, via []*http.Request) error, ) func(req *http.Request, via []*http.Request) error
RedirectPolicy returns an http.Client CheckRedirect function that validates each redirect target URL against this policy's allowed schemes and the SSRF host rules. next, if non-nil, is called after validation passes, so callers can chain their own redirect logic.
func (URLPolicy) Validate ¶
Validate checks that raw uses an allowed scheme and that its host, as written, is a literal public address or a dotted name other than localhost. It performs no DNS lookup, so a public name that resolves to a private address passes: pair it with SafeTransport, which checks every resolved and connected address.
func (URLPolicy) WithLogger ¶
WithLogger returns a copy of p whose RedirectPolicy writes its refusals to l, so a caller running one client per peer can attribute each line. A nil l is ignored, as the transport's WithLogger ignores it, so the copy keeps p's logger; a policy that never had one writes to slog.Default at the time of each line.