ssrf

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

ssrf

Go Reference Go version

ssrf keeps your Go service's outbound requests off private networks and cloud metadata endpoints, by checking URLs before you fetch and every address at connect time.

It replaces the URL checks and custom dialer you would otherwise write around net/http, and it hands back a plain *http.Transport and CheckRedirect function. At run time it uses the standard library and two dependencies by the same author: textsafe, to clean untrusted text in its log lines, and urlform, for its ASCII-only case folding of schemes and hosts. It needs Go 1.27 or later and is licensed under Apache-2.0.

Why use it

ssrf is built for Go code that fetches URLs a user or an upstream response supplies, such as webhooks and link previews.

  • ValidateURL refuses a non-HTTPS URL, localhost, a name with no dot, and private, loopback, link-local, carrier-grade NAT and reserved addresses.
  • SafeTransport stops DNS rebinding, where a checked name later resolves to an internal address. It looks up each name once, refuses it when any address is not public, and connects only to a checked address. It checks the connected address again before the TCP handshake.
  • It also checks the IPv4 address inside a 6to4, NAT64 or Teredo IPv6 address.
  • The transport connects to port 443 only unless you list other ports.
  • Every refusal is an *ssrf.Error whose Kind you can switch on.

Consider Smokescreen if you want a separate egress proxy instead of a library. It authenticates clients over mTLS and applies a hostname allowlist per client.

Install

go get github.com/cplieger/go/ssrf@latest

Usage

Check a URL, then fetch it through a client that checks every address and every redirect:

import "github.com/cplieger/go/ssrf"

if err := ssrf.ValidateURL("https://example.com/data.json"); err != nil {
    return err
}

client := &http.Client{
    Timeout:       30 * time.Second,
    Transport:     ssrf.SafeTransport(),
    CheckRedirect: ssrf.SafeRedirectPolicy(nil),
}

To allow plain HTTP as well, set the schemes on a URLPolicy and the ports on the transport. The policy checks schemes on the first request and on every redirect, and the transport checks addresses and ports at dial time:

policy := ssrf.NewURLPolicy("https", "http")
client := &http.Client{
    Transport:     ssrf.SafeTransport(ssrf.WithAllowedPorts(443, 80)),
    CheckRedirect: policy.RedirectPolicy(nil),
}
if err := policy.Validate("http://example.com/data.json"); err != nil {
    return err
}

Check an address you already resolved:

if ssrf.IsPublicAddr(netip.MustParseAddr("8.8.8.8")) {
    // safe to connect
}

Error kinds shows how to switch on a refusal's Kind. The Example functions on pkg.go.dev are runnable, and go test keeps them true.

API

  • Validation: ValidateURL, IsPublicHost, IsPublicAddr, and URLPolicy with NewURLPolicy and its Validate and WithLogger methods.
  • Transport: SafeTransport with the options WithAllowedPorts, WithAddressPolicy, WithResolver, WithDialer and WithLogger, and the TransportOption, AddressPolicy and Resolver types.
  • Redirects: SafeRedirectPolicy and URLPolicy.RedirectPolicy, which check every hop and stop after 10.
  • Errors: Error, with its Kind, Host, Msg and Err fields, and the ErrorKind constants, whose String is the reason label the redirect and address-policy log lines carry. The transport's structural refusals and its disallowed-port refusal log finer labels of their own.

The full reference is on pkg.go.dev.

Validation reads the name, the transport checks the address

ValidateURL, IsPublicHost and URLPolicy.Validate do no DNS lookup. They judge the host as written, so a public-looking name that resolves to an internal address passes them. The host check accepts localhost.localdomain, a.localhost and metadata.google.internal, and all three resolve privately. Use the validation functions with SafeTransport, which checks the resolved address and the connected address.

The host check accepts two kinds of host and refuses every other string, most with KindInvalidHost. One is an IP address without a zone suffix such as %eth0, which names a network interface. The other is an ASCII DNS name with at least two labels, such as api.example.com.

ssrf refuses a non-ASCII host instead of converting it, so convert an internationalized name to its xn-- form first. The C library's resolver reads 0177.0.0.1, 0x7f.0.0.1 and 127.1 as 127.0.0.1, so the check refuses any name whose last label is a number, with KindNonPublicIP. Pass a bare host without brackets. ValidateURL already does this with url.Hostname().

Host validation has the full grammar and the reasons for it, and Blocked address ranges lists every refused range.

Ports, redirects and logging

SafeTransport connects to port 443 only, unless you list other ports with WithAllowedPorts. The list replaces the default, and a call with no ports keeps 443. No option allows every port. If you learn the port only at run time, validate the destination first, then build a transport that allows that one port.

The redirect policies refuse a hop with the hop's own Kind, such as KindBadScheme. The transport sets no proxy, so it ignores HTTP_PROXY and HTTPS_PROXY and connects to the destination itself.

The validation functions log nothing. Each transport or redirect refusal logs one Warn line, with a bounded reason attribute and its untrusted values sanitized. Transport lines go to the logger you pass with WithLogger, and redirect lines to the one you pass with URLPolicy.WithLogger, or each to slog's default logger. The transport covers the options, defaults and log lines.

Unsupported by design

ssrf has no IP allow or deny lists beyond WithAddressPolicy, no hostname allowlist, no Happy Eyeballs fast connect and no response size limit. It also has no blanket 2001::/23 block, no ISATAP unwrapping, no built-in DNS-over-HTTPS resolver and no allow-every-port option. Unsupported by design gives the reason for each and what to use instead.

Credits

The socket-time check uses a net.Dialer Control hook the way safedialer and safeurl do. safedialer adapts Andrew Ayer's 2019 post on preventing SSRF in Go. The typed error kinds and the port allowlist with no allow-all setting also follow safeurl.

Documentation

Contributing

See CONTRIBUTING.md.

Disclaimer

This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.

This project was built with AI-assisted tooling using Claude, GPT, and Kiro. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsPublicAddr

func IsPublicAddr(addr netip.Addr) bool

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

func IsPublicHost(host string) bool

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
}

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
}

func ValidateURL

func ValidateURL(raw string) error

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

type AddressPolicy func(addr netip.Addr) bool

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.

func (*Error) Error

func (e *Error) Error() string

Error renders Msg, followed by Err's text when Msg does not already say it.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns Err, so errors.Is and errors.As reach the underlying cause.

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

func (k ErrorKind) String() 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

func NewURLPolicy(schemes ...string) URLPolicy

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

func (p URLPolicy) Validate(raw string) error

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

func (p URLPolicy) WithLogger(l *slog.Logger) URLPolicy

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.

Jump to

Keyboard shortcuts

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