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

snippet
// 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)
}