diff --git a/tools/browser/browser.go b/tools/browser/browser.go index 642172b..d57767a 100644 --- a/tools/browser/browser.go +++ b/tools/browser/browser.go @@ -36,24 +36,6 @@ const ( janitorInterval = 1 * time.Minute ) -// hostResolverRules forces Chrome to fail DNS resolution for private/internal -// IP ranges and localhost, so in-page fetch() and evaluate()'d JS cannot reach -// cloud-metadata endpoints or localhost services — the Go-side -// ValidateURLNotInternal check only sees the top-level URL, so this covers -// sub-resource and script-initiated requests. (S3) -// -// Residual gap: name-based rules do not stop a page that dials a *literal* -// private IP URL in some Chrome builds; the complete fix is an allowlisting -// proxy (deferred). See the security-deeper spec's limitations section. -const hostResolverRules = "MAP localhost ~NOTFOUND," + - "MAP *.localhost ~NOTFOUND," + - "MAP 127.0.0.0/8 ~NOTFOUND," + - "MAP 10.0.0.0/8 ~NOTFOUND," + - "MAP 172.16.0.0/12 ~NOTFOUND," + - "MAP 169.254.0.0/16 ~NOTFOUND," + - "MAP 192.168.0.0/16 ~NOTFOUND," + - "MAP [::1] ~NOTFOUND" - // stealthScript runs before any page script on every new document. It hides the // most common headless/automation tells that JS-heavy sites use to refuse to // render content (Cloudflare, Akamai, anti-bot scripts, "please enable JS" @@ -482,6 +464,17 @@ func (t *BrowserTool) reapIdleSessions() { // reaper watchdog. If the parent dies hard before cleanup runs, the // watchdog SIGKILLs any process whose argv contains that path and rm -rfs // the dir. +// +// SSRF containment: Chrome is pointed at an in-process web.EgressProxy +// (--proxy-server, with <-loopback> so localhost is not exempt). The proxy +// resolves each destination, refuses it if any address is private/internal +// (loopback, RFC 1918, link-local/metadata, CGNAT, ULA), and dials the +// validated IP directly, so nip.io-style names and DNS rebinding are caught +// too. This covers redirects, sub-resources, in-page fetch/XHR and +// WebSockets. WebRTC is restricted to proxied UDP. Chrome's +// --host-resolver-rules is deliberately not used: it only glob-matches host +// strings, so CIDR entries never match. The proxy lives and dies with the +// returned cleanup func. func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, error) { udd, err := os.MkdirTemp("", "harness-browser-") if err != nil { @@ -489,6 +482,16 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, } trackDirForReaping(udd) + // All Chrome traffic (top-level, sub-resource, in-page fetch, WebSocket) + // is forced through an in-process proxy that refuses private/internal + // destinations at dial time. See web.EgressProxy. + proxy, err := web.StartEgressProxy() + if err != nil { + untrackDirForReaping(udd) + _ = os.RemoveAll(udd) + return nil, nil, fmt.Errorf("start egress proxy: %w", err) + } + allocCtx, allocCancel := chromedp.NewExecAllocator(parent, append(chromedp.DefaultExecAllocatorOptions[:], chromedp.NoSandbox, @@ -496,7 +499,13 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, chromedp.UserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"), chromedp.Flag("disable-blink-features", "AutomationControlled"), chromedp.Flag("lang", "en-US"), - chromedp.Flag("host-resolver-rules", hostResolverRules), + chromedp.ProxyServer(proxy.URL()), + // Drop Chrome's implicit loopback bypass so localhost and + // 127.0.0.0/8 also go through (and are refused by) the proxy. + chromedp.Flag("proxy-bypass-list", "<-loopback>"), + // Keep WebRTC from sending UDP around the proxy. + chromedp.Flag("force-webrtc-ip-handling-policy", "disable_non_proxied_udp"), + chromedp.Flag("webrtc-ip-handling-policy", "disable_non_proxied_udp"), chromedp.UserDataDir(udd), )..., ) @@ -511,6 +520,7 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, ); err != nil { taskCancel() allocCancel() + _ = proxy.Close() untrackDirForReaping(udd) _ = os.RemoveAll(udd) return nil, nil, err @@ -518,6 +528,7 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, cleanup := func() { taskCancel() allocCancel() + _ = proxy.Close() untrackDirForReaping(udd) _ = os.RemoveAll(udd) } diff --git a/tools/browser/browser_ssrf_live_test.go b/tools/browser/browser_ssrf_live_test.go index 396d436..03a7cbf 100644 --- a/tools/browser/browser_ssrf_live_test.go +++ b/tools/browser/browser_ssrf_live_test.go @@ -4,6 +4,11 @@ package browser import ( "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" "testing" "time" @@ -12,33 +17,71 @@ import ( "github.com/stretchr/testify/require" ) -// TestInPageFetchPrivateIPBlocked_Live verifies host-resolver-rules stops an -// in-page fetch to a metadata IP. Requires a real Chrome. Run: -// go test -tags live ./tools/browser/ -run TestInPageFetchPrivateIPBlocked_Live +// TestInPageFetchPrivateIPBlocked_Live verifies the egress proxy stops +// in-page fetches and navigations to loopback, private-resolving names and the +// metadata IP, without any request reaching a local server. Requires a real +// Chrome and network access. Run: +// +// go test -tags live ./tools/browser/ -run TestInPageFetchPrivateIPBlocked_Live func TestInPageFetchPrivateIPBlocked_Live(t *testing.T) { - tool := NewBrowserTool() - defer tool.Shutdown() - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + var hits atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Header().Set("Access-Control-Allow-Origin", "*") + fmt.Fprint(w, "secret") + })) + defer srv.Close() + port := srv.Listener.Addr().(interface{ String() string }).String() + port = port[strings.LastIndex(port, ":")+1:] + + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) defer cancel() taskCtx, ccancel, err := launchBrowser(ctx) require.NoError(t, err) defer ccancel() - require.NoError(t, chromedp.Run(taskCtx, chromedp.Navigate("https://example.com"))) + // Positive control: public sites work through the proxy. + var title string + require.NoError(t, chromedp.Run(taskCtx, chromedp.Navigate("https://example.com"), chromedp.Title(&title))) + require.Contains(t, title, "Example") - var result string - script := `(async () => { - try { - await fetch('http://169.254.169.254/latest/meta-data/', {mode:'no-cors'}); - return 'REACHED'; - } catch (e) { - return 'BLOCKED'; - } - })()` - err = chromedp.Run(taskCtx, chromedp.Evaluate(script, &result, func(p *runtime.EvaluateParams) *runtime.EvaluateParams { - return p.WithAwaitPromise(true) - })) - require.NoError(t, err) - require.Equal(t, "BLOCKED", result, "in-page fetch to metadata IP must be blocked by host-resolver-rules") + targets := []string{ + "http://127.0.0.1:" + port, + "http://localhost:" + port, + "http://127.0.0.1.nip.io:" + port, + "http://169.254.169.254/latest/meta-data/", + } + for _, target := range targets { + var result string + script := fmt.Sprintf(`(async () => { + const ac = new AbortController(); + const timer = setTimeout(() => ac.abort(), 10000); + try { + await fetch(%q, {signal: ac.signal}); + return 'REACHED'; + } catch (e) { + return 'BLOCKED'; + } finally { clearTimeout(timer); } + })()`, target) + start := time.Now() + err = chromedp.Run(taskCtx, chromedp.Evaluate(script, &result, func(p *runtime.EvaluateParams) *runtime.EvaluateParams { + return p.WithAwaitPromise(true) + })) + require.NoError(t, err, target) + require.Equal(t, "BLOCKED", result, "in-page fetch to %s must be blocked", target) + require.Less(t, time.Since(start), 8*time.Second, "%s should be refused quickly, not time out", target) + } + + navCtx, navCancel := context.WithTimeout(taskCtx, 20*time.Second) + defer navCancel() + // The proxy answers 403, which Chrome renders as an ordinary page, so + // accept either a navigation error or the proxy's refusal text. + var body string + err = chromedp.Run(navCtx, chromedp.Navigate("http://127.0.0.1.nip.io:"+port), chromedp.Text("body", &body, chromedp.ByQuery)) + if err == nil { + require.Contains(t, body, "blocked by egress policy", "direct navigation to a private-resolving name must be refused") + } + + require.EqualValues(t, 0, hits.Load(), "local server must never be reached") } diff --git a/tools/browser/browser_test.go b/tools/browser/browser_test.go index 7a78fd3..e36548c 100644 --- a/tools/browser/browser_test.go +++ b/tools/browser/browser_test.go @@ -4,23 +4,12 @@ import ( "context" "encoding/json" "fmt" - "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestHostResolverRules_BlocksPrivateRanges(t *testing.T) { - require.Contains(t, hostResolverRules, "127.0.0.0/8") - require.Contains(t, hostResolverRules, "169.254.0.0/16") - require.Contains(t, hostResolverRules, "10.0.0.0/8") - require.Contains(t, hostResolverRules, "192.168.0.0/16") - require.Contains(t, hostResolverRules, "172.16.0.0/12") - require.Contains(t, hostResolverRules, "localhost") - require.True(t, strings.Contains(hostResolverRules, "~NOTFOUND")) -} - func TestBrowserToolName(t *testing.T) { tool := &BrowserTool{} assert.Equal(t, "browser", tool.Name()) diff --git a/tools/stagehand/stagehand.go b/tools/stagehand/stagehand.go index 849f753..9a7b238 100644 --- a/tools/stagehand/stagehand.go +++ b/tools/stagehand/stagehand.go @@ -13,6 +13,7 @@ import ( "encoding/json" "errors" "fmt" + "net" "strings" "sync" "time" @@ -42,20 +43,6 @@ const ( janitorInterval = 1 * time.Minute ) -// hostResolverRules mirrors tools/browser: it makes a *local* Chrome fail DNS -// for localhost and private ranges so in-page fetch()/XHR can't reach -// cloud-metadata endpoints or local services. The Go-side -// ValidateURLNotInternal check only covers the top-level URL. Browserbase -// browsers run remotely and can't reach this machine's network anyway. -const hostResolverRules = "MAP localhost ~NOTFOUND," + - "MAP *.localhost ~NOTFOUND," + - "MAP 127.0.0.0/8 ~NOTFOUND," + - "MAP 10.0.0.0/8 ~NOTFOUND," + - "MAP 172.16.0.0/12 ~NOTFOUND," + - "MAP 169.254.0.0/16 ~NOTFOUND," + - "MAP 192.168.0.0/16 ~NOTFOUND," + - "MAP [::1] ~NOTFOUND" - // Config configures a StagehandTool. type Config struct { // Provider and Model serve Stagehand's internal inference. Required. @@ -82,6 +69,9 @@ type session struct { browser *sh.Browser client *sh.Stagehand lastUsed time.Time + // proxy is the egress proxy a local Chrome is forced through; nil for + // Browserbase and in tests. + proxy *web.EgressProxy } // StagehandTool is an AI-driven browser tool. @@ -393,6 +383,18 @@ func (t *StagehandTool) acquire(ctx context.Context, name string) (*session, fun // launchSession starts a browser on the configured backend and attaches a // Stagehand client whose inference runs through the harness provider. +// +// A local Chrome is forced through an in-process web.EgressProxy that refuses +// private/internal destinations at dial time (loopback, RFC 1918, link-local/ +// metadata, names resolving to them, DNS rebinding), covering sub-resource and +// script-initiated requests that the Go-side ValidateURLNotInternal check +// never sees. Chrome's --host-resolver-rules is not used: it only glob-matches +// host strings, so CIDR entries never match. Browserbase browsers run remotely +// and can't reach this machine's network anyway. +// +// The implicit loopback bypass is removed (<-loopback), so localhost and +// 127.0.0.1 are refused too; the one exception is Chrome's own debugging port, +// which Stagehand's extension needs (a page could still reach that port). func (t *StagehandTool) launchSession(ctx context.Context) (*session, error) { // The browser outlives this call for persistent sessions, so detach it // from the caller's cancellation and bound only the launch itself. @@ -400,18 +402,45 @@ func (t *StagehandTool) launchSession(ctx context.Context) (*session, error) { defer cancel() var browser *sh.Browser + var proxy *web.EgressProxy var err error if t.cfg.BrowserbaseAPIKey != "" { browser, err = sh.LaunchBrowserbase(launchCtx, sh.BrowserbaseLaunchOptions{APIKey: t.cfg.BrowserbaseAPIKey}) } else { + proxy, err = web.StartEgressProxy() + if err != nil { + return nil, fmt.Errorf("start egress proxy: %w", err) + } + // Stagehand's in-browser extension connects to Chrome's own debugging + // port over loopback, so pick that port up front and let exactly it + // through the proxy. + var debugPort int + debugPort, err = freeLoopbackPort() + if err != nil { + _ = proxy.Close() + return nil, fmt.Errorf("pick debugging port: %w", err) + } + proxy.AllowLoopbackPort(debugPort) browser, err = sh.LaunchLocalBrowser(launchCtx, &sh.LocalBrowserLaunchOptions{ Headless: !t.cfg.Headful, ExecutablePath: t.cfg.ChromePath, - Args: []string{"--host-resolver-rules=" + hostResolverRules}, - Viewport: &sh.LocalViewport{Width: defaultViewportW, Height: defaultViewportH}, + Port: debugPort, + Args: []string{ + "--proxy-server=" + proxy.URL(), + // Drop Chrome's implicit loopback/link-local bypass so those + // destinations hit the proxy (and are refused). + "--proxy-bypass-list=<-loopback>", + // Keep WebRTC from sending UDP around the proxy. + "--force-webrtc-ip-handling-policy=disable_non_proxied_udp", + "--webrtc-ip-handling-policy=disable_non_proxied_udp", + }, + Viewport: &sh.LocalViewport{Width: defaultViewportW, Height: defaultViewportH}, }) } if err != nil { + if proxy != nil { + _ = proxy.Close() + } return nil, fmt.Errorf("launch browser: %w", err) } @@ -423,9 +452,13 @@ func (t *StagehandTool) launchSession(ctx context.Context) (*session, error) { if err != nil { closeCtx, cancelClose := context.WithTimeout(context.Background(), closeTimeout) defer cancelClose() - return nil, errors.Join(fmt.Errorf("start stagehand: %w", err), browser.Close(closeCtx)) + cerr := browser.Close(closeCtx) + if proxy != nil { + _ = proxy.Close() + } + return nil, errors.Join(fmt.Errorf("start stagehand: %w", err), cerr) } - return &session{browser: browser, client: client, lastUsed: time.Now()}, nil + return &session{browser: browser, client: client, lastUsed: time.Now(), proxy: proxy}, nil } // close tears down the client then the browser. Safe on a partially @@ -439,6 +472,9 @@ func (s *session) close() { if s.browser != nil { _ = s.browser.Close(ctx) } + if s.proxy != nil { + _ = s.proxy.Close() + } } func (t *StagehandTool) closeSession(name string) bool { @@ -533,3 +569,13 @@ func truncate(s string) string { } return s[:maxTextOutput] + fmt.Sprintf("\n\n[truncated: %d of %d bytes shown]", maxTextOutput, len(s)) } + +// freeLoopbackPort returns a currently unused 127.0.0.1 TCP port. +func freeLoopbackPort() (int, error) { + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + return 0, err + } + defer ln.Close() + return ln.Addr().(*net.TCPAddr).Port, nil +} diff --git a/tools/web/client.go b/tools/web/client.go index 735b33c..2262c86 100644 --- a/tools/web/client.go +++ b/tools/web/client.go @@ -5,6 +5,7 @@ import ( "fmt" "net" "net/http" + "strings" "time" ) @@ -17,37 +18,7 @@ func SafeHTTPClient(timeout time.Duration) *http.Client { transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: func(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.LookupIP(ctx, "ip", host) - if err != nil { - return nil, fmt.Errorf("cannot resolve %q — blocking to prevent SSRF", host) - } - // Fail closed: if ANY resolved IP is private, refuse — this defeats - // DNS-rebinding where one A record is public and another is private. - for _, ip := range ips { - if isPrivateIP(ip) { - return nil, fmt.Errorf("access to internal address %s (%s) is blocked", host, ip) - } - } - if len(ips) == 0 { - return nil, fmt.Errorf("no usable address for %q", host) - } - // Try each validated public IP in order, falling back on dial - // failure so dual-stack hosts still connect on IPv4-only or - // IPv6-broken networks (stock happy-eyeballs is bypassed because we - // dial literal IPs to pin the validated address). - var lastErr error - for _, ip := range ips { - conn, derr := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port)) - if derr == nil { - return conn, nil - } - lastErr = derr - } - return nil, lastErr + return safeDialContext(ctx, dialer, isPrivateIP, network, addr) }, } return &http.Client{ @@ -64,3 +35,139 @@ func SafeHTTPClient(timeout time.Duration) *http.Client { }, } } + +// blockedError marks a destination refused by the SSRF policy (as opposed to +// an ordinary resolve/dial failure), so callers can tell policy from outage. +type blockedError struct{ msg string } + +func (e *blockedError) Error() string { return e.msg } + +// safeDialContext is the single SSRF-safe dial path shared by SafeHTTPClient +// and the browser egress proxy. It resolves addr's host, fails closed if +// blockIP reports ANY resolved IP (or the host is a known metadata name), then +// dials the exact validated IPs so nothing is re-resolved after validation. +func safeDialContext(ctx context.Context, dialer *net.Dialer, blockIP func(net.IP) bool, network, addr string) (net.Conn, error) { + host, port, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + lower := strings.ToLower(strings.TrimSuffix(host, ".")) + if lower == "metadata.google.internal" || lower == "metadata" { + return nil, &blockedError{"access to internal metadata endpoint is blocked"} + } + ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host) + if err != nil { + return nil, fmt.Errorf("cannot resolve %q — blocking to prevent SSRF", host) + } + // Fail closed: if ANY resolved IP is private, refuse — this defeats + // DNS-rebinding where one A record is public and another is private. + for _, ip := range ips { + if blockIP(ip) { + return nil, &blockedError{fmt.Sprintf("access to internal address %s (%s) is blocked", host, ip)} + } + } + if len(ips) == 0 { + return nil, fmt.Errorf("no usable address for %q", host) + } + return dialValidated(ctx, dialer, network, interleaveFamilies(ips), port) +} + +// happyEyeballsDelay is how long dialValidated waits on one address before +// also starting the next (RFC 8305 uses 250ms). +const happyEyeballsDelay = 300 * time.Millisecond + +// interleaveFamilies reorders ips to alternate address families, starting with +// the resolver's first, so a dead family can't stall the other. +func interleaveFamilies(ips []net.IP) []net.IP { + var v4, v6 []net.IP + for _, ip := range ips { + if ip.To4() != nil { + v4 = append(v4, ip) + } else { + v6 = append(v6, ip) + } + } + first, second := v4, v6 + if len(ips) > 0 && ips[0].To4() == nil { + first, second = v6, v4 + } + out := make([]net.IP, 0, len(ips)) + for i := 0; i < len(first) || i < len(second); i++ { + if i < len(first) { + out = append(out, first[i]) + } + if i < len(second) { + out = append(out, second[i]) + } + } + return out +} + +// dialValidated dials the already-validated literal IPs RFC 8305 style: +// attempts start staggered (or immediately after a failure) and the first to +// connect wins, so dual-stack hosts work on IPv4-only or IPv6-broken networks +// without waiting out a full dial timeout. Stock happy-eyeballs is bypassed +// because we dial literal IPs to pin the validated address. +func dialValidated(ctx context.Context, dialer *net.Dialer, network string, ips []net.IP, port string) (net.Conn, error) { + if len(ips) == 1 { + return dialer.DialContext(ctx, network, net.JoinHostPort(ips[0].String(), port)) + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + type result struct { + conn net.Conn + err error + } + ch := make(chan result, len(ips)) // buffered: attempts never block on send + launched, pending := 0, 0 + launch := func() { + addr := net.JoinHostPort(ips[launched].String(), port) + launched++ + pending++ + go func() { + c, err := dialer.DialContext(ctx, network, addr) + ch <- result{c, err} + }() + } + // Close any connections that complete after we've returned. + drain := func() { + n := pending + go func() { + for ; n > 0; n-- { + if r := <-ch; r.conn != nil { + _ = r.conn.Close() + } + } + }() + } + timer := time.NewTimer(0) + defer timer.Stop() + var lastErr error + for { + select { + case <-timer.C: + if launched < len(ips) { + launch() + if launched < len(ips) { + timer.Reset(happyEyeballsDelay) + } + } + case r := <-ch: + pending-- + if r.err == nil { + drain() + return r.conn, nil + } + lastErr = r.err + if launched == len(ips) && pending == 0 { + return nil, lastErr + } + if launched < len(ips) { + timer.Reset(0) // failed fast: start the next address now + } + case <-ctx.Done(): + drain() + return nil, ctx.Err() + } + } +} diff --git a/tools/web/client_test.go b/tools/web/client_test.go index 78a6502..5496990 100644 --- a/tools/web/client_test.go +++ b/tools/web/client_test.go @@ -1,6 +1,7 @@ package web import ( + "context" "net" "net/http" "net/http/httptest" @@ -52,3 +53,22 @@ func TestSafeHTTPClient_PublicUnreachableReturnsDialError(t *testing.T) { var _ = isPrivateIP(net.IPv4(127, 0, 0, 1)) var _ = strings.TrimSpace + +func TestDialValidated_FallsBackPastDeadAddress(t *testing.T) { + ln, err := net.Listen("tcp4", "127.0.0.1:0") + require.NoError(t, err) + defer ln.Close() + go func() { + if c, err := ln.Accept(); err == nil { + _ = c.Close() + } + }() + _, port, _ := net.SplitHostPort(ln.Addr().String()) + // First address is a black hole (TEST-NET-1); the second is live. + ips := []net.IP{net.ParseIP("192.0.2.1"), net.ParseIP("127.0.0.1")} + start := time.Now() + c, err := dialValidated(context.Background(), &net.Dialer{Timeout: 30 * time.Second}, "tcp", ips, port) + require.NoError(t, err) + _ = c.Close() + require.Less(t, time.Since(start), 5*time.Second) +} diff --git a/tools/web/egress_proxy.go b/tools/web/egress_proxy.go new file mode 100644 index 0000000..4e57f51 --- /dev/null +++ b/tools/web/egress_proxy.go @@ -0,0 +1,279 @@ +package web + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httputil" + "strconv" + "strings" + "sync" + "time" +) + +const ( + egressDialTimeout = 30 * time.Second + halfCloseGrace = 60 * time.Second +) + +// EgressProxy is a loopback HTTP proxy that only forwards to public +// destinations. Point a browser at it (--proxy-server) so every request it +// makes — top-level, sub-resource, in-page fetch, WebSocket — is validated at +// dial time against the same private-range policy as SafeHTTPClient. Names +// that resolve to private IPs (nip.io, DNS rebinding) are caught because the +// check runs on the resolved address, which is then dialed directly. +// +// It speaks CONNECT (https/wss) and absolute-URI HTTP (http/ws). It does not +// follow redirects or honor HTTP_PROXY: a 3xx goes back to the browser, whose +// next request re-enters the proxy and is validated again. +type EgressProxy struct { + ln net.Listener + srv *http.Server + tr *http.Transport + dialer *net.Dialer + // blockIP reports whether a resolved IP must be refused. Defaults to + // isPrivateIP; tests override it to reach loopback httptest servers. + blockIP func(net.IP) bool + + mu sync.Mutex + allow map[string]struct{} // loopback ports reachable despite blockIP + conns map[net.Conn]struct{} + closed bool + wg sync.WaitGroup + once sync.Once +} + +// StartEgressProxy starts a proxy on 127.0.0.1 with an ephemeral port. +func StartEgressProxy() (*EgressProxy, error) { + return startEgressProxy(isPrivateIP) +} + +func startEgressProxy(blockIP func(net.IP) bool) (*EgressProxy, error) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return nil, fmt.Errorf("egress proxy listen: %w", err) + } + p := &EgressProxy{ + ln: ln, + dialer: &net.Dialer{Timeout: egressDialTimeout}, + blockIP: blockIP, + conns: make(map[net.Conn]struct{}), + } + p.tr = &http.Transport{ + Proxy: nil, // never chain through HTTP_PROXY + DialContext: p.dial, + DisableCompression: true, // pass bytes through untouched + MaxIdleConns: 32, + IdleConnTimeout: 90 * time.Second, + } + rp := &httputil.ReverseProxy{ + Rewrite: func(r *httputil.ProxyRequest) { r.Out.Header.Del("Proxy-Connection") }, + Transport: p.tr, + ErrorHandler: p.proxyError, + } + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodConnect: + p.handleConnect(w, r) + case r.URL.IsAbs() && r.URL.Host != "" && r.URL.Scheme == "http": + rp.ServeHTTP(w, r) + default: + http.Error(w, "egress proxy: absolute http URL or CONNECT required", http.StatusBadRequest) + } + }) + p.srv = &http.Server{Handler: handler, ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second} + p.wg.Add(1) + go func() { + defer p.wg.Done() + _ = p.srv.Serve(ln) + }() + return p, nil +} + +// AllowLoopbackPort lets the browser reach 127.0.0.1:port (and localhost:port) +// through the proxy despite the private-range policy, for a port the caller +// itself owns (e.g. the browser's own debugging port). Nothing else on +// loopback is opened. +func (p *EgressProxy) AllowLoopbackPort(port int) { + p.mu.Lock() + defer p.mu.Unlock() + if p.allow == nil { + p.allow = make(map[string]struct{}) + } + p.allow[strconv.Itoa(port)] = struct{}{} +} + +// allowedLoopback reports whether addr is an exact allowlisted loopback port. +func (p *EgressProxy) allowedLoopback(addr string) bool { + host, port, err := net.SplitHostPort(addr) + if err != nil { + return false + } + if host != "127.0.0.1" && !strings.EqualFold(strings.TrimSuffix(host, "."), "localhost") { + return false + } + p.mu.Lock() + defer p.mu.Unlock() + _, ok := p.allow[port] + return ok +} + +// Addr returns the listen address as host:port. +func (p *EgressProxy) Addr() string { return p.ln.Addr().String() } + +// URL returns the proxy URL suitable for --proxy-server. +func (p *EgressProxy) URL() string { return "http://" + p.Addr() } + +// Close stops the listener and tears down every in-flight tunnel and upstream +// connection. Idempotent. +func (p *EgressProxy) Close() error { + var err error + p.once.Do(func() { + p.mu.Lock() + p.closed = true + for c := range p.conns { + _ = c.Close() + } + p.mu.Unlock() + err = p.srv.Close() + p.tr.CloseIdleConnections() + p.wg.Wait() + }) + return err +} + +// track registers c so Close can sever it. Returns false (and closes c) if +// the proxy is already closed. +func (p *EgressProxy) track(c net.Conn) bool { + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + _ = c.Close() + return false + } + p.conns[c] = struct{}{} + return true +} + +func (p *EgressProxy) untrack(c net.Conn) { + p.mu.Lock() + delete(p.conns, c) + p.mu.Unlock() +} + +type proxyConn struct { + net.Conn + p *EgressProxy +} + +func (c *proxyConn) Close() error { + c.p.untrack(c.Conn) + return c.Conn.Close() +} + +// dial is the only way the proxy reaches upstream: validated, pinned, tracked. +func (p *EgressProxy) dial(ctx context.Context, network, addr string) (net.Conn, error) { + var conn net.Conn + var err error + if p.allowedLoopback(addr) { + _, port, _ := net.SplitHostPort(addr) + conn, err = p.dialer.DialContext(ctx, network, net.JoinHostPort("127.0.0.1", port)) + } else { + conn, err = safeDialContext(ctx, p.dialer, p.blockIP, network, addr) + } + if err != nil { + return nil, err + } + if !p.track(conn) { + return nil, errors.New("egress proxy closed") + } + return &proxyConn{Conn: conn, p: p}, nil +} + +func (p *EgressProxy) proxyError(w http.ResponseWriter, r *http.Request, err error) { + writeDialError(w, err) +} + +func writeDialError(w http.ResponseWriter, err error) { + var be *blockedError + if errors.As(err, &be) { + http.Error(w, "blocked by egress policy: "+be.msg, http.StatusForbidden) + return + } + http.Error(w, "upstream unavailable", http.StatusBadGateway) +} + +func (p *EgressProxy) handleConnect(w http.ResponseWriter, r *http.Request) { + target := r.Host + if h, port, err := net.SplitHostPort(target); err != nil || h == "" || port == "" { + http.Error(w, "egress proxy: CONNECT target must be host:port", http.StatusBadRequest) + return + } + // Validate and dial before hijacking so a refusal is a clean 403. + up, err := p.dial(r.Context(), "tcp", target) + if err != nil { + writeDialError(w, err) + return + } + hj, ok := w.(http.Hijacker) + if !ok { + _ = up.Close() + http.Error(w, "hijack unsupported", http.StatusInternalServerError) + return + } + client, buf, err := hj.Hijack() + if err != nil { + _ = up.Close() + return + } + if !p.track(client) { + _ = up.Close() + return + } + defer func() { + p.untrack(client) + _ = client.Close() + _ = up.Close() + }() + if _, err := client.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")); err != nil { + return + } + done := make(chan struct{}, 2) + // Bytes the server already buffered from the client belong upstream. + go func() { + _, _ = io.Copy(up, buf) + _, _ = io.Copy(up, client) + closeWrite(up) // propagate the client's FIN, keep reading the reply + done <- struct{}{} + }() + go func() { + _, _ = io.Copy(client, up) + closeWrite(client) + done <- struct{}{} + }() + // Wait for both directions (half-close is legal), but once one side has + // finished give the other a bounded grace so a peer that vanished without + // closing can't pin the tunnel. Close() also severs the conns. + <-done + grace := time.AfterFunc(halfCloseGrace, func() { + _ = client.Close() + _ = up.Close() + }) + <-done + grace.Stop() +} + +// closeWrite half-closes c's write side when it supports it, else fully closes. +func closeWrite(c net.Conn) { + if pc, ok := c.(*proxyConn); ok { + c = pc.Conn + } + if cw, ok := c.(interface{ CloseWrite() error }); ok { + _ = cw.CloseWrite() + return + } + _ = c.Close() +} diff --git a/tools/web/egress_proxy_test.go b/tools/web/egress_proxy_test.go new file mode 100644 index 0000000..33c6558 --- /dev/null +++ b/tools/web/egress_proxy_test.go @@ -0,0 +1,219 @@ +package web + +import ( + "bufio" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// allowLoopback lets tests reach httptest servers while still blocking every +// other private range, so the block path stays exercised. +func allowLoopback(ip net.IP) bool { + if ip.IsLoopback() { + return false + } + return isPrivateIP(ip) +} + +func newTestProxy(t *testing.T, block func(net.IP) bool) *EgressProxy { + t.Helper() + p, err := startEgressProxy(block) + require.NoError(t, err) + t.Cleanup(func() { _ = p.Close() }) + return p +} + +// connect sends a CONNECT and returns the status code plus the live conn. +func connect(t *testing.T, p *EgressProxy, target string) (int, net.Conn, *bufio.Reader) { + t.Helper() + c, err := net.Dial("tcp", p.Addr()) + require.NoError(t, err) + t.Cleanup(func() { _ = c.Close() }) + fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", target, target) + br := bufio.NewReader(c) + resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodConnect}) + require.NoError(t, err) + return resp.StatusCode, c, br +} + +func countingServer(t *testing.T) (*httptest.Server, *atomic.Int64) { + var hits atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + fmt.Fprint(w, "secret") + })) + t.Cleanup(srv.Close) + return srv, &hits +} + +func proxyClient(p *EgressProxy) *http.Client { + u, _ := url.Parse(p.URL()) + return &http.Client{ + Timeout: 10 * time.Second, + Transport: &http.Transport{Proxy: http.ProxyURL(u)}, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } +} + +func TestEgressProxy_ConnectBlocksPrivateTargets(t *testing.T) { + srv, hits := countingServer(t) + p := newTestProxy(t, isPrivateIP) + _, port, _ := net.SplitHostPort(srv.Listener.Addr().String()) + for _, target := range []string{ + "127.0.0.1:" + port, + "localhost:" + port, + "[::1]:" + port, + "[::ffff:127.0.0.1]:" + port, + "169.254.169.254:80", + "10.0.0.1:443", + "metadata.google.internal:80", + "metadata:80", + } { + code, _, _ := connect(t, p, target) + require.Equal(t, http.StatusForbidden, code, target) + } + require.EqualValues(t, 0, hits.Load()) +} + +func TestEgressProxy_PlainHTTPBlocksPrivate(t *testing.T) { + srv, hits := countingServer(t) + p := newTestProxy(t, isPrivateIP) + resp, err := proxyClient(p).Get(srv.URL) + require.NoError(t, err) + defer resp.Body.Close() + require.Equal(t, http.StatusForbidden, resp.StatusCode) + require.EqualValues(t, 0, hits.Load()) +} + +func TestEgressProxy_PlainHTTPForwards(t *testing.T) { + srv, hits := countingServer(t) + p := newTestProxy(t, allowLoopback) + resp, err := proxyClient(p).Get(srv.URL) + require.NoError(t, err) + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + require.Equal(t, http.StatusOK, resp.StatusCode) + require.Equal(t, "secret", string(body)) + require.EqualValues(t, 1, hits.Load()) +} + +func TestEgressProxy_RedirectNotFollowed(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "http://169.254.169.254/", http.StatusFound) + })) + defer srv.Close() + p := newTestProxy(t, allowLoopback) + resp, err := proxyClient(p).Get(srv.URL) + require.NoError(t, err) + defer resp.Body.Close() + require.Equal(t, http.StatusFound, resp.StatusCode) +} + +func TestEgressProxy_ConnectTunnelForwards(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + defer ln.Close() + go func() { + c, err := ln.Accept() + if err != nil { + return + } + defer c.Close() + _, _ = io.Copy(c, c) // echo + }() + p := newTestProxy(t, allowLoopback) + code, c, br := connect(t, p, ln.Addr().String()) + require.Equal(t, http.StatusOK, code) + _, err = c.Write([]byte("ping\n")) + require.NoError(t, err) + line, err := br.ReadString('\n') + require.NoError(t, err) + require.Equal(t, "ping\n", line) +} + +func TestEgressProxy_OriginFormRejected(t *testing.T) { + p := newTestProxy(t, isPrivateIP) + c, err := net.Dial("tcp", p.Addr()) + require.NoError(t, err) + defer c.Close() + fmt.Fprint(c, "GET /foo HTTP/1.1\r\nHost: example.com\r\n\r\n") + resp, err := http.ReadResponse(bufio.NewReader(c), nil) + require.NoError(t, err) + require.Equal(t, http.StatusBadRequest, resp.StatusCode) +} + +func TestEgressProxy_CloseTearsDownTunnel(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + defer ln.Close() + go func() { + c, err := ln.Accept() + if err != nil { + return + } + defer c.Close() + _, _ = io.Copy(io.Discard, c) + }() + p := newTestProxy(t, allowLoopback) + code, c, _ := connect(t, p, ln.Addr().String()) + require.Equal(t, http.StatusOK, code) + require.NoError(t, p.Close()) + require.NoError(t, p.Close(), "Close must be idempotent") + _ = c.SetReadDeadline(time.Now().Add(5 * time.Second)) + _, err = c.Read(make([]byte, 1)) + require.Equal(t, io.EOF, err, "tunnel must be closed, not timed out") +} + +func TestEgressProxy_HalfClose(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + defer ln.Close() + go func() { + c, err := ln.Accept() + if err != nil { + return + } + defer c.Close() + _, _ = io.Copy(io.Discard, c) // read to client EOF + time.Sleep(100 * time.Millisecond) + _, _ = c.Write([]byte("REPLY")) + }() + p := newTestProxy(t, allowLoopback) + status, c, br := connect(t, p, ln.Addr().String()) + require.Equal(t, 200, status) + _, _ = c.Write([]byte("hi")) + require.NoError(t, c.(*net.TCPConn).CloseWrite()) + _ = c.SetReadDeadline(time.Now().Add(5 * time.Second)) + got, _ := io.ReadAll(br) + require.Equal(t, "REPLY", string(got)) +} + +func TestEgressProxy_AllowLoopbackPortIsExact(t *testing.T) { + srv, hits := countingServer(t) + other, otherHits := countingServer(t) + p := newTestProxy(t, isPrivateIP) // default policy: loopback blocked + _, port, _ := net.SplitHostPort(srv.Listener.Addr().String()) + var n int + _, _ = fmt.Sscan(port, &n) + p.AllowLoopbackPort(n) + + resp, err := proxyClient(p).Get(srv.URL) + require.NoError(t, err) + _ = resp.Body.Close() + require.Equal(t, int64(1), hits.Load()) + + resp, err = proxyClient(p).Get(other.URL) + require.NoError(t, err) + _ = resp.Body.Close() + require.Equal(t, 403, resp.StatusCode) + require.Zero(t, otherHits.Load()) +} diff --git a/tools/web/ssrf.go b/tools/web/ssrf.go index 65373f2..99bd06c 100644 --- a/tools/web/ssrf.go +++ b/tools/web/ssrf.go @@ -21,6 +21,32 @@ var privateNetworks = []string{ "fc00::/7", // IPv6 unique local "fe80::/10", // IPv6 link-local "::/128", // IPv6 unspecified + "198.18.0.0/15", // benchmarking (RFC 2544) + "224.0.0.0/4", // IPv4 multicast + "240.0.0.0/4", // reserved, incl. 255.255.255.255 broadcast + "ff00::/8", // IPv6 multicast + "2001::/32", // Teredo (embeds an obfuscated IPv4) + "64:ff9b:1::/48", // local-use NAT64 (RFC 8215) +} + +// embeddedV4Nets are IPv6 prefixes that carry an IPv4 address translators may +// route to: the embedded address is re-checked so e.g. 64:ff9b::7f00:1 (NAT64 +// for 127.0.0.1) is blocked while a public embedded address stays allowed. +var embeddedV4Nets = []struct { + net *net.IPNet + offset int // byte offset of the embedded IPv4 address +}{ + {mustCIDR("64:ff9b::/96"), 12}, // NAT64 well-known prefix + {mustCIDR("2002::/16"), 2}, // 6to4 + {mustCIDR("::/96"), 12}, // IPv4-compatible (deprecated) +} + +func mustCIDR(s string) *net.IPNet { + _, n, err := net.ParseCIDR(s) + if err != nil { + panic(err) + } + return n } var parsedPrivateNets []*net.IPNet @@ -41,6 +67,15 @@ func isPrivateIP(ip net.IP) bool { return true } } + if ip.To4() == nil { + if ip16 := ip.To16(); ip16 != nil { + for _, e := range embeddedV4Nets { + if e.net.Contains(ip16) { + return isPrivateIP(net.IP(ip16[e.offset : e.offset+4])) + } + } + } + } return false } diff --git a/tools/web/ssrf_test.go b/tools/web/ssrf_test.go index b5f9d9b..849e46f 100644 --- a/tools/web/ssrf_test.go +++ b/tools/web/ssrf_test.go @@ -17,7 +17,7 @@ func TestValidateURLNotInternal_BlocksLoopback(t *testing.T) { "http://10.0.0.1/", "http://172.16.0.1/", "http://192.168.1.1/", - "http://169.254.169.254/", // AWS/GCP/Azure metadata IP + "http://169.254.169.254/", // AWS/GCP/Azure metadata IP "http://metadata.google.internal/", // GCP metadata host } for _, u := range cases { @@ -72,3 +72,24 @@ func TestIsPrivateIP_AllowsPublic(t *testing.T) { require.False(t, isPrivateIP(ip), "%s must be allowed (public)", s) } } + +func TestIsPrivateIP_EmbeddedAndReserved(t *testing.T) { + blocked := []string{ + "64:ff9b::7f00:1", // NAT64 -> 127.0.0.1 + "64:ff9b::a9fe:a9fe", // NAT64 -> 169.254.169.254 + "2002:7f00:1::", // 6to4 -> 127.0.0.1 + "::127.0.0.1", // IPv4-compatible + "224.0.0.1", "ff02::1", // multicast + "198.18.0.1", // benchmarking + "240.0.0.1", "255.255.255.255", + "2001:0:4136:e378:8000:63bf:3fff:fdd2", // Teredo + } + for _, s := range blocked { + ip := net.ParseIP(s) + require.NotNil(t, ip, "parse %s", s) + require.True(t, isPrivateIP(ip), "%s must be blocked", s) + } + for _, s := range []string{"64:ff9b::808:808", "2002:808:808::"} { // embed 8.8.8.8 + require.False(t, isPrivateIP(net.ParseIP(s)), "%s embeds a public address", s) + } +}