// Package safehttp fetches remote resources on behalf of API clients while // refusing to connect to internal network addresses, which guards against // server-side request forgery (SSRF). // // Addresses are checked at dial time, after DNS resolution, so a hostname that // resolves (or re-resolves) to a private address is refused too. package safehttp import ( "context" "errors" "fmt" "io" "net" "net/http" "net/netip" "net/url" "strings" "syscall" "time" ) // maxRedirects bounds redirect chains. const maxRedirects = 5 var ( // ErrBlockedAddress is returned when a destination resolves to an address // that is not allowed. ErrBlockedAddress = errors.New("safehttp: destination address is not allowed") // ErrHostNotAllowed is returned when an allowlist is configured and the // host is not on it. ErrHostNotAllowed = errors.New("safehttp: host is not on the allowlist") // ErrScheme is returned for URLs that are not http or https. ErrScheme = errors.New("safehttp: only http and https URLs are allowed") // ErrTooLarge is returned when a response body exceeds the size limit. ErrTooLarge = errors.New("safehttp: response exceeds size limit") ) // Options configures a Client. type Options struct { // Timeout bounds a whole fetch, including redirects and reading the body. Timeout time.Duration // MaxBytes is the largest response body accepted. MaxBytes int64 // AllowPrivate permits loopback, private, link-local and other // non-public destinations. AllowPrivate bool // AllowedHosts, when non-empty, restricts fetches to these hostnames. // Listed hosts may resolve to private addresses. AllowedHosts []string } // Client fetches URLs with SSRF protection. It is safe for concurrent use. type Client struct { http *http.Client maxBytes int64 allowPrivate bool allowed map[string]struct{} } // New returns a Client configured by o. func New(o Options) *Client { c := &Client{ maxBytes: o.MaxBytes, allowPrivate: o.AllowPrivate, allowed: make(map[string]struct{}, len(o.AllowedHosts)), } for _, host := range o.AllowedHosts { c.allowed[strings.ToLower(host)] = struct{}{} } guarded := &net.Dialer{Timeout: o.Timeout, Control: c.checkDialAddress} plain := &net.Dialer{Timeout: o.Timeout} transport := &http.Transport{ // No proxy: a proxy would make the dial-time address check useless. Proxy: nil, DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { host, _, err := net.SplitHostPort(addr) if err != nil { return nil, err } if c.allowlisted(host) { return plain.DialContext(ctx, network, addr) } return guarded.DialContext(ctx, network, addr) }, ForceAttemptHTTP2: true, MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, TLSHandshakeTimeout: o.Timeout, ResponseHeaderTimeout: o.Timeout, } c.http = &http.Client{ Transport: transport, Timeout: o.Timeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { if len(via) >= maxRedirects { return fmt.Errorf("safehttp: stopped after %d redirects", maxRedirects) } return c.checkURL(req.URL) }, } return c } // Fetch GETs rawURL and returns the response body. func (c *Client) Fetch(ctx context.Context, rawURL string) ([]byte, error) { u, err := url.Parse(rawURL) if err != nil { return nil, fmt.Errorf("parsing URL: %w", err) } if err := c.checkURL(u); err != nil { return nil, err } req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { return nil, fmt.Errorf("building request: %w", err) } req.Header.Set("User-Agent", "uberbringer") resp, err := c.http.Do(req) if err != nil { return nil, fmt.Errorf("fetching %s: %w", u.Redacted(), err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("fetching %s: unexpected status %s", u.Redacted(), resp.Status) } if resp.ContentLength > c.maxBytes { return nil, fmt.Errorf("%w: %d bytes, limit is %d", ErrTooLarge, resp.ContentLength, c.maxBytes) } body, err := io.ReadAll(io.LimitReader(resp.Body, c.maxBytes+1)) if err != nil { return nil, fmt.Errorf("reading %s: %w", u.Redacted(), err) } if int64(len(body)) > c.maxBytes { return nil, fmt.Errorf("%w: limit is %d bytes", ErrTooLarge, c.maxBytes) } return body, nil } // checkURL validates the scheme and, when an allowlist is set, the host. func (c *Client) checkURL(u *url.URL) error { if u.Scheme != "http" && u.Scheme != "https" { return fmt.Errorf("%w: %q", ErrScheme, u.Scheme) } if u.Hostname() == "" { return fmt.Errorf("safehttp: URL has no host") } if len(c.allowed) > 0 && !c.allowlisted(u.Hostname()) { return fmt.Errorf("%w: %s", ErrHostNotAllowed, u.Hostname()) } return nil } func (c *Client) allowlisted(host string) bool { _, ok := c.allowed[strings.ToLower(host)] return ok } // checkDialAddress runs after DNS resolution with the concrete IP the dialer // is about to connect to. func (c *Client) checkDialAddress(_, address string, _ syscall.RawConn) error { if c.allowPrivate { return nil } addrPort, err := netip.ParseAddrPort(address) if err != nil { return fmt.Errorf("%w: %s", ErrBlockedAddress, address) } if !IsPublic(addrPort.Addr()) { return fmt.Errorf("%w: %s", ErrBlockedAddress, addrPort.Addr()) } return nil } // nonPublic lists ranges that are not reachable on the public internet and // are not already covered by the netip.Addr predicates in IsPublic. It is // effectively constant and must not be modified. var nonPublic = []netip.Prefix{ netip.MustParsePrefix("0.0.0.0/8"), // "this" network netip.MustParsePrefix("100.64.0.0/10"), // carrier-grade NAT netip.MustParsePrefix("192.0.0.0/24"), // IETF protocol assignments netip.MustParsePrefix("192.0.2.0/24"), // TEST-NET-1 netip.MustParsePrefix("198.18.0.0/15"), // benchmarking netip.MustParsePrefix("198.51.100.0/24"), // TEST-NET-2 netip.MustParsePrefix("203.0.113.0/24"), // TEST-NET-3 netip.MustParsePrefix("240.0.0.0/4"), // reserved, includes broadcast netip.MustParsePrefix("2001:db8::/32"), // documentation netip.MustParsePrefix("64:ff9b:1::/48"), // local-use NAT64 } // IsPublic reports whether addr is a globally routable unicast address. // Loopback, private (RFC 1918 and IPv6 ULA), link-local (which includes cloud // metadata endpoints), multicast and reserved ranges are not public. func IsPublic(addr netip.Addr) bool { addr = addr.Unmap() if !addr.IsValid() || addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() || addr.IsInterfaceLocalMulticast() || addr.IsMulticast() { return false } for _, prefix := range nonPublic { if prefix.Contains(addr) { return false } } return true }