Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions core/network/ssrf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package network

import (
"context"
"fmt"
"net"
"net/netip"
"time"
)

// cgnat is the RFC 6598 Carrier-Grade NAT shared address space (100.64.0.0/10).
// It is reserved for provider-internal networks and is used for pod IPs on some
// Kubernetes platforms (e.g. EKS), so it must not be reachable. netip's
// IsPrivate() does not cover it.
var cgnat = netip.MustParsePrefix("100.64.0.0/10")

// IsPublicIP reports whether ip is safe to dial from server-side code that
// fetches user-controlled URLs: not loopback, private, CGNAT, link-local,
// unique-local, site-local, multicast, broadcast, or unspecified. IPv6 forms
// that embed an IPv4 address (IPv4-mapped, 6to4, NAT64) are reduced to that
// IPv4 and re-checked, so an internal IPv4 such as the 169.254.169.254
// metadata endpoint cannot be reached by wrapping it in an IPv6 transition
// representation.
//
// This is stricter than the complement of IsPrivateIP: IsPrivateIP is a
// coarse range check for save-time URL validation (where private targets may
// be deliberately allowed), while IsPublicIP is the dial-time gate.
func IsPublicIP(ip net.IP) bool {
addr, ok := netip.AddrFromSlice(ip)
if !ok {
return false
}
addr = addr.Unmap()

// If the address embeds an IPv4 via a transition mechanism (6to4 / NAT64),
// classify the embedded IPv4 — otherwise an internal target like
// 169.254.169.254 can be reached as 2002:a9fe:a9fe:: or 64:ff9b::a9fe:a9fe,
// neither of which Unmap() collapses.
if embedded, ok := embeddedIPv4(addr); ok {
addr = embedded
}

if addr.IsLoopback() || addr.IsPrivate() || cgnat.Contains(addr) ||
addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() ||
addr.IsMulticast() || addr.IsUnspecified() || addr.IsInterfaceLocalMulticast() ||
addr == netip.AddrFrom4([4]byte{255, 255, 255, 255}) {
return false
}

// Deprecated IPv6 site-local fec0::/10 (RFC 3879) isn't matched by any
// helper above; reject it explicitly.
if addr.Is6() {
b := addr.As16()
if b[0] == 0xfe && (b[1]&0xc0) == 0xc0 {
return false
}
}

return true
}

// embeddedIPv4 extracts the IPv4 address carried inside an IPv6 transition
// address: 6to4 (2002::/16) or NAT64 (RFC 6052 well-known 64:ff9b::/96 and
// RFC 8215 local-use 64:ff9b:1::/48). Returns false for anything else.
//
// Limitation: NAT64 with an operator-chosen Network-Specific Prefix (any other
// /32../96) is indistinguishable from a normal global address and is not
// unwrapped — only the two standard prefixes are covered.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
func embeddedIPv4(addr netip.Addr) (netip.Addr, bool) {
if !addr.Is6() {
return netip.Addr{}, false
}
b := addr.As16()
switch {
case b[0] == 0x20 && b[1] == 0x02: // 6to4 2002::/16 -> bytes 2..5
return netip.AddrFrom4([4]byte{b[2], b[3], b[4], b[5]}), true
case b[0] == 0x00 && b[1] == 0x64 && b[2] == 0xff && b[3] == 0x9b:
// NAT64 well-known 64:ff9b::/96 -> IPv4 in the low 32 bits (bytes 12..15).
if b[4] == 0x00 && b[5] == 0x00 {
return netip.AddrFrom4([4]byte{b[12], b[13], b[14], b[15]}), true
}
// NAT64 local-use 64:ff9b:1::/48 -> per RFC 6052 the IPv4 occupies
// bytes 6,7,9,10 (byte 8 is the reserved u-octet, skipped).
if b[4] == 0x00 && b[5] == 0x01 {
return netip.AddrFrom4([4]byte{b[6], b[7], b[9], b[10]}), true
}
}
return netip.Addr{}, false
}

// ipLookuper resolves a hostname to IPs. *net.Resolver satisfies it; tests
// substitute a fake to exercise the dial path without real DNS.
type ipLookuper interface {
LookupIP(ctx context.Context, network, host string) ([]net.IP, error)
}

// SSRFSafeDialContext returns a DialContext for outbound requests to
// user-controlled URLs. On every dial it resolves the host, rejects the
// connection if any resolved address fails IsPublicIP, and then dials the
// first validated IP directly — so a second DNS resolution cannot swap in a
// private address after validation (DNS rebinding TOCTOU). Because the check
// runs per dial, it also holds across redirects and connection-pool re-dials.
func SSRFSafeDialContext(dialTimeout time.Duration) func(ctx context.Context, netw, addr string) (net.Conn, error) {
dialer := &net.Dialer{Timeout: dialTimeout}
return ssrfSafeDialContext(net.DefaultResolver, dialer.DialContext)
}

// ssrfSafeDialContext is the seam behind SSRFSafeDialContext with injectable
// resolver and dial for tests.
func ssrfSafeDialContext(resolver ipLookuper, dial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, netw, addr string) (net.Conn, error) {
return func(ctx context.Context, netw, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("invalid dial address %q: %w", addr, err)
}
ips, err := resolver.LookupIP(ctx, "ip", host)
if err != nil {
return nil, fmt.Errorf("DNS lookup failed for %s: %w", host, err)
}
if len(ips) == 0 {
return nil, fmt.Errorf("DNS lookup for %s returned no addresses", host)
}
for _, ip := range ips {
if !IsPublicIP(ip) {
return nil, fmt.Errorf("blocked connection to non-public address %s (host %s)", ip, host)
}
}
return dial(ctx, netw, net.JoinHostPort(ips[0].String(), port))
}
}
172 changes: 172 additions & 0 deletions core/network/ssrf_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
package network

import (
"context"
"errors"
"net"
"strings"
"testing"
"time"
)

// TestIsPublicIP guards the SSRF denylist used for dial-time validation. It
// locks in both the long-standing blocks (loopback / RFC 1918 / link-local /
// ULA) and the hardened cases: CGNAT, IPv6-transition-wrapped internal IPv4
// (6to4 / NAT64), and deprecated IPv6 site-local.
func TestIsPublicIP(t *testing.T) {
tests := []struct {
name string
ip string
want bool
}{
// Legitimate public targets must still be dialable.
{"public v4 google dns", "8.8.8.8", true},
{"public v4 cloudflare", "1.1.1.1", true},
{"public v6", "2606:4700:4700::1111", true},
// 6to4 wrapping a *public* IPv4 is legitimately public.
{"6to4 public 8.8.8.8", "2002:0808:0808::", true},

// Baseline blocks — regression guard.
{"loopback v4", "127.0.0.1", false},
{"private 10/8", "10.0.0.1", false},
{"private 172.16/12", "172.16.5.4", false},
{"private 192.168/16", "192.168.1.1", false},
{"link-local / IMDS", "169.254.169.254", false},
{"loopback v6", "::1", false},
{"ula v6", "fc00::1", false},
{"link-local v6", "fe80::1", false},
{"unspecified v4", "0.0.0.0", false},
{"unspecified v6", "::", false},
{"multicast v4", "224.0.0.1", false},
{"broadcast v4", "255.255.255.255", false},
{"interface-local multicast v6", "ff01::1", false},
{"ipv4-mapped loopback", "::ffff:127.0.0.1", false},

// CGNAT (RFC 6598).
{"cgnat low", "100.64.0.1", false},
{"cgnat high", "100.127.255.255", false},
{"cgnat boundary just outside (public)", "100.128.0.1", true},

// IPv4 metadata endpoint smuggled inside IPv6 transition forms.
{"6to4-wrapped IMDS", "2002:a9fe:a9fe::", false},
{"nat64 well-known-wrapped IMDS", "64:ff9b::a9fe:a9fe", false},
{"nat64 local-use-wrapped IMDS", "64:ff9b:1:a9fe:a9:fe00::", false},

// Deprecated IPv6 site-local (RFC 3879).
{"site-local fec0::/10", "fec0::1", false},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ip := net.ParseIP(tt.ip)
if ip == nil {
t.Fatalf("could not parse IP %q", tt.ip)
}
if got := IsPublicIP(ip); got != tt.want {
t.Errorf("IsPublicIP(%s) = %v, want %v", tt.ip, got, tt.want)
}
})
}
}

// fakeResolver returns a fixed IP set (or error) and counts lookups so tests
// can assert that every dial triggers a fresh resolution.
type fakeResolver struct {
ips []net.IP
err error
lookups int
}

func (f *fakeResolver) LookupIP(_ context.Context, _, _ string) ([]net.IP, error) {
f.lookups++
return f.ips, f.err
}

func TestSSRFSafeDialContextBlocksNonPublicResolution(t *testing.T) {
// One public and one private A record: the private one must block the dial
// entirely (an attacker controlling DNS can mix records).
resolver := &fakeResolver{ips: []net.IP{net.ParseIP("93.184.216.34"), net.ParseIP("10.0.0.5")}}
dial := ssrfSafeDialContext(resolver, func(_ context.Context, _, _ string) (net.Conn, error) {
t.Fatal("dial must not be reached when a resolved IP is non-public")
return nil, nil
})

_, err := dial(context.Background(), "tcp", "evil.example:443")
if err == nil || !strings.Contains(err.Error(), "blocked connection to non-public address") {
t.Fatalf("expected blocked-connection error, got %v", err)
}
}

func TestSSRFSafeDialContextDialsValidatedIPDirectly(t *testing.T) {
// The connection must go to the IP that passed validation, not through a
// second hostname resolution — that closes the DNS-rebinding TOCTOU.
resolver := &fakeResolver{ips: []net.IP{net.ParseIP("93.184.216.34"), net.ParseIP("93.184.216.35")}}
var dialed string
dialErr := errors.New("stop before real network")
dial := ssrfSafeDialContext(resolver, func(_ context.Context, _, addr string) (net.Conn, error) {
dialed = addr
return nil, dialErr
})

_, err := dial(context.Background(), "tcp", "example.com:443")
if !errors.Is(err, dialErr) {
t.Fatalf("expected sentinel dial error, got %v", err)
}
if dialed != "93.184.216.34:443" {
t.Fatalf("dialed %q, want first validated IP %q", dialed, "93.184.216.34:443")
}
}

func TestSSRFSafeDialContextReResolvesPerDial(t *testing.T) {
// Validation must run on every dial (redirects, pooled-connection re-dials),
// so a record that turns private between attempts is caught.
resolver := &fakeResolver{ips: []net.IP{net.ParseIP("127.0.0.1")}}
dial := ssrfSafeDialContext(resolver, func(_ context.Context, _, _ string) (net.Conn, error) {
t.Fatal("dial must not be reached")
return nil, nil
})

for i := 0; i < 2; i++ {
if _, err := dial(context.Background(), "tcp", "rebind.example:80"); err == nil {
t.Fatal("expected blocked-connection error")
}
}
if resolver.lookups != 2 {
t.Fatalf("resolver invoked %d times, want one lookup per dial (2)", resolver.lookups)
}
}

func TestSSRFSafeDialContextErrorPaths(t *testing.T) {
t.Run("resolver error propagates", func(t *testing.T) {
resolver := &fakeResolver{err: errors.New("nxdomain")}
dial := ssrfSafeDialContext(resolver, nil)
if _, err := dial(context.Background(), "tcp", "gone.example:443"); err == nil || !strings.Contains(err.Error(), "DNS lookup failed") {
t.Fatalf("expected DNS lookup error, got %v", err)
}
})

t.Run("empty resolution rejected", func(t *testing.T) {
resolver := &fakeResolver{}
dial := ssrfSafeDialContext(resolver, nil)
if _, err := dial(context.Background(), "tcp", "empty.example:443"); err == nil || !strings.Contains(err.Error(), "no addresses") {
t.Fatalf("expected no-addresses error, got %v", err)
}
})

t.Run("address without port rejected", func(t *testing.T) {
resolver := &fakeResolver{ips: []net.IP{net.ParseIP("93.184.216.34")}}
dial := ssrfSafeDialContext(resolver, nil)
if _, err := dial(context.Background(), "tcp", "no-port.example"); err == nil || !strings.Contains(err.Error(), "invalid dial address") {
t.Fatalf("expected invalid-address error, got %v", err)
}
})
}

func TestSSRFSafeDialContextBlocksLoopbackLiteral(t *testing.T) {
// End-to-end through the exported constructor with the real resolver: an IP
// literal resolves to itself and must be blocked before any connection.
dial := SSRFSafeDialContext(time.Second)
if _, err := dial(context.Background(), "tcp", "127.0.0.1:80"); err == nil || !strings.Contains(err.Error(), "blocked connection to non-public address") {
t.Fatalf("expected blocked-connection error, got %v", err)
}
}
Loading
Loading