SSRF HTTP Allowlist Security Boundaries

Guard outbound fetches against SSRF with an allowlist of hosts and schemes, blocking private networks and redirects to internal IPs.

GoSecurity Boundaries

Code

gosnippet
99 lines
// SSRF guard: validate every serverSide request target before dialing
package main

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var blockedZones = []string{
	"127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12",
	"192.168.0.0/16", "169.254.0.0/16", "::1/128", "fc00::/7",
}

var allowedHosts = map[string]bool{
	"api.partner.com": true, "cdn.partner.net": true, "hooks.vendor.io": true,
}

func validateTarget(raw string) (*url.URL, error) {
	parsed, err := url.Parse(raw)
	if err != nil {
		return nil, fmt.Errorf("parse url: %w", err)
	}

	if parsed.Scheme != "https" {
		return nil, fmt.Errorf("scheme %q not allowed", parsed.Scheme)
	}
	if !allowedHosts[parsed.Hostname()] {
		return nil, fmt.Errorf("host %q is not allowlisted", parsed.Hostname())
	}
	return parsed, nil
}

func dialGuard(ctx context.Context, network, addr string) (net.Conn, error) {
	host, port, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, err
	}

	ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
	if err != nil {
		return nil, err
	}
	for _, ip := range ips {
		if !isPublic(ip.IP) {
			return nil, fmt.Errorf("resolved %s to private address %s", host, ip.IP)
		}
	}

	dialer := &net.Dialer{Timeout: 5 * time.Second}
	return dialer.DialContext(ctx, network, net.JoinHostPort(ips[0].IP.String(), port))
}

func isPublic(ip net.IP) bool {
	for _, zone := range blockedZones {
		_, network, _ := net.ParseCIDR(zone)
		if network.Contains(ip) {
			return false
		}
	}
	return !ip.IsLoopback() && !ip.IsUnspecified() && !ip.IsLinkLocalUnicast()
}

func guardedClient() *http.Client {
	transport := &http.Transport{
		DialContext: dialGuard,
		// 重定向必须重走校验:禁止自动跟随
		DisableKeepAlives: true,
	}
	return &http.Client{
		Transport:     transport,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return validateSameHost(via[0], req.URL)
		},
		Timeout: 8 * time.Second,
	}
}

func validateSameHost(orig, next *url.URL) error {
	if strings.EqualFold(orig.Hostname(), next.Hostname()) {
		return nil
	}
	return fmt.Errorf("redirect to non-allowlisted host %q", next.Hostname())
}

func main() {
	client := guardedClient()
	if _, err := validateTarget("https://api.partner.com/v1/data"); err == nil {
		resp, err := client.Get("https://api.partner.com/v1/data")
		fmt.Println(resp, err)
	}

	_, err := validateTarget("http://169.254.169.254/latest/meta-data")
	fmt.Println("metadata endpoint blocked:", err)
}

How execution proceeds

One way to read it: the functions validateTarget, dialGuard, isPublic and guardedClient, doing all the work.

The cycling part of this snippet is for _, ip := range ips. Error handling is inline: 3 places test err != nil and branch immediately.

What to watch for

  • The function reports failure by returning error — callers branch on it before touching other results.

Applying it

Entry signature: func validateTarget(raw string) (*url.URL, error)

Running the file prints labeled results such as metadata endpoint blocked: — each operation’s effect is visible in the output.

The entry point wires guardedClient and validateTarget together — run it once and the whole demo flows.

Statements that matter

return nil, fmt.Errorf("parse url: %w", err)
return fmt.Errorf("redirect to non-allowlisted host %q", next.Hostname())
return nil, fmt.Errorf("resolved %s to private address %s", host, ip.IP)

Interactive Tools for This Topic

FAQ

How should callers handle failures?
No exceptions — `error` returns checked at 3 sites, and callers branch on `err` first.
What does SSRF HTTP Allowlist Security Boundaries print when run?
Invoke the file as-is — the `metadata endpoint blocked:` prefixes identify which step printed each line.