From 083122a81fe58f16988b02d0d24fc276f0f23299 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 11:15:26 +0800 Subject: [PATCH 1/7] feat(web): add SafeHTTPClient with IP-pinning transport (S2) --- tools/web/client.go | 56 ++++++++++++++++++++++++++++++++++++++++ tools/web/client_test.go | 43 ++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 tools/web/client.go create mode 100644 tools/web/client_test.go diff --git a/tools/web/client.go b/tools/web/client.go new file mode 100644 index 0000000..4e134a5 --- /dev/null +++ b/tools/web/client.go @@ -0,0 +1,56 @@ +package web + +import ( + "context" + "fmt" + "net" + "net/http" + "time" +) + +// SafeHTTPClient returns an *http.Client whose transport resolves and validates +// the destination host, then dials the exact validated IP — closing the +// TOCTOU/DNS-rebinding window where a stock http.Client would re-resolve the +// hostname independently of ValidateURLNotInternal. Redirects are re-validated. +func SafeHTTPClient(timeout time.Duration) *http.Client { + dialer := &net.Dialer{Timeout: timeout} + 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) + } + var dialIP net.IP + for _, ip := range ips { + if isPrivateIP(ip) { + return nil, fmt.Errorf("access to internal address %s (%s) is blocked", host, ip) + } + if dialIP == nil { + dialIP = ip + } + } + if dialIP == nil { + return nil, fmt.Errorf("no usable address for %q", host) + } + return dialer.DialContext(ctx, network, net.JoinHostPort(dialIP.String(), port)) + }, + } + return &http.Client{ + Timeout: timeout, + Transport: transport, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return fmt.Errorf("too many redirects (max 10)") + } + if err := ValidateURLNotInternal(req.URL.String()); err != nil { + return fmt.Errorf("redirect blocked: %w", err) + } + return nil + }, + } +} diff --git a/tools/web/client_test.go b/tools/web/client_test.go new file mode 100644 index 0000000..ec8e263 --- /dev/null +++ b/tools/web/client_test.go @@ -0,0 +1,43 @@ +package web + +import ( + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestSafeHTTPClient_BlocksPrivateAtDial(t *testing.T) { + client := SafeHTTPClient(5 * time.Second) + // 127.0.0.1 is itself private, so dialing it directly must be refused. + _, err := client.Get("http://127.0.0.1:9/") + require.Error(t, err) + require.Contains(t, err.Error(), "internal address") +} + +func TestSafeHTTPClient_AllowsPublic(t *testing.T) { + client := SafeHTTPClient(5 * time.Second) + tr, ok := client.Transport.(*http.Transport) + require.True(t, ok) + require.NotNil(t, tr.DialContext) + require.NotNil(t, client.CheckRedirect) + require.Equal(t, 5*time.Second, client.Timeout) +} + +func TestSafeHTTPClient_RedirectToPrivateBlocked(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound) + })) + defer srv.Close() + client := SafeHTTPClient(5 * time.Second) + // The httptest server binds loopback (private), so the FIRST dial is already blocked. + _, err := client.Get(srv.URL) + require.Error(t, err) +} + +var _ = isPrivateIP(net.IPv4(127, 0, 0, 1)) +var _ = strings.TrimSpace From 1e00916a828b5258d47743b79bd90f93788ff8c1 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 11:19:03 +0800 Subject: [PATCH 2/7] fix(web): block 0.0.0.0/8, CGNAT, and reserved ranges in isPrivateIP (S2 hardening) --- tools/web/ssrf.go | 4 ++++ tools/web/ssrf_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/tools/web/ssrf.go b/tools/web/ssrf.go index eea493e..65373f2 100644 --- a/tools/web/ssrf.go +++ b/tools/web/ssrf.go @@ -14,9 +14,13 @@ var privateNetworks = []string{ "172.16.0.0/12", // RFC 1918 "192.168.0.0/16", // RFC 1918 "169.254.0.0/16", // link-local + "0.0.0.0/8", // "this" network / unspecified; routes to loopback on Linux + "100.64.0.0/10", // CGNAT (RFC 6598) + "192.0.0.0/24", // IETF protocol assignments (RFC 6890) "::1/128", // IPv6 loopback "fc00::/7", // IPv6 unique local "fe80::/10", // IPv6 link-local + "::/128", // IPv6 unspecified } var parsedPrivateNets []*net.IPNet diff --git a/tools/web/ssrf_test.go b/tools/web/ssrf_test.go index af00388..b5f9d9b 100644 --- a/tools/web/ssrf_test.go +++ b/tools/web/ssrf_test.go @@ -1,10 +1,12 @@ package web import ( + "net" "strings" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValidateURLNotInternal_BlocksLoopback(t *testing.T) { @@ -45,3 +47,28 @@ func TestValidateURLNotInternal_RejectsBadScheme(t *testing.T) { assert.Error(t, err, "non-http schemes must be rejected") _ = strings.TrimSpace(err.Error()) } + +func TestIsPrivateIP_BlocksReservedRanges(t *testing.T) { + blocked := []string{ + "0.0.0.0", // unspecified / routes to loopback on Linux + "0.0.0.1", // 0.0.0.0/8 + "100.64.0.0", // CGNAT 100.64.0.0/10 + "100.127.255.255", // CGNAT upper + "192.0.0.1", // 192.0.0.0/24 IETF protocol assignments + "::", // IPv6 unspecified ::/128 + } + for _, s := range blocked { + ip := net.ParseIP(s) + require.NotNil(t, ip, "parse %s", s) + require.True(t, isPrivateIP(ip), "%s must be treated as private/blocked", s) + } +} + +func TestIsPrivateIP_AllowsPublic(t *testing.T) { + pub := []string{"8.8.8.8", "1.1.1.1", "93.184.216.34", "2606:2800:220:1:248:1893:25c8:1946"} + for _, s := range pub { + ip := net.ParseIP(s) + require.NotNil(t, ip, "parse %s", s) + require.False(t, isPrivateIP(ip), "%s must be allowed (public)", s) + } +} From d7777f7c89aa53eddef50e4b9b7579a03adf75ba Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 11:20:12 +0800 Subject: [PATCH 3/7] =?UTF-8?q?fix(web):=20web=5Ffetch=20uses=20SafeHTTPCl?= =?UTF-8?q?ient=20=E2=80=94=20pins=20validated=20IP=20(S2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/web/webfetch.go | 14 +------------- tools/web/webfetch_test.go | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 13 deletions(-) create mode 100644 tools/web/webfetch_test.go diff --git a/tools/web/webfetch.go b/tools/web/webfetch.go index b5fbde1..71f70b6 100644 --- a/tools/web/webfetch.go +++ b/tools/web/webfetch.go @@ -85,19 +85,7 @@ func (t *WebFetchTool) Execute(ctx context.Context, input json.RawMessage) (tool req.Header.Set(k, v) } - client := &http.Client{ - Timeout: fetchTimeout, - CheckRedirect: func(req *http.Request, via []*http.Request) error { - if len(via) >= 10 { - return fmt.Errorf("too many redirects (max 10)") - } - // Re-validate each redirect destination against SSRF blocklist - if err := ValidateURLNotInternal(req.URL.String()); err != nil { - return fmt.Errorf("redirect blocked: %w", err) - } - return nil - }, - } + client := SafeHTTPClient(fetchTimeout) resp, err := client.Do(req) if err != nil { diff --git a/tools/web/webfetch_test.go b/tools/web/webfetch_test.go new file mode 100644 index 0000000..9eb7b91 --- /dev/null +++ b/tools/web/webfetch_test.go @@ -0,0 +1,16 @@ +package web + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestWebFetch_BlocksPrivateHost(t *testing.T) { + tool := &WebFetchTool{} + res, err := tool.Execute(context.Background(), + []byte(`{"url":"http://169.254.169.254/latest/meta-data/"}`)) + require.NoError(t, err) + require.NotEmpty(t, res.Error, "private metadata IP must be rejected") +} From 7d8507450981b1380ebe1a59103c8ab779ef5174 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 11:22:15 +0800 Subject: [PATCH 4/7] fix(web): all web_search backends use SafeHTTPClient (N4) --- tools/web/websearch.go | 7 ++++++- tools/web/websearch_backends.go | 10 +++++++--- tools/web/websearch_test.go | 29 +++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 tools/web/websearch_test.go diff --git a/tools/web/websearch.go b/tools/web/websearch.go index 4be3342..f08dee6 100644 --- a/tools/web/websearch.go +++ b/tools/web/websearch.go @@ -14,6 +14,11 @@ import ( const searchTimeout = 15 * time.Second +// searchClient is the shared SSRF-safe HTTP client for all web_search +// backends. It pins the validated IP and re-validates redirects, bringing +// web_search to parity with web_fetch. (N4) +var searchClient = SafeHTTPClient(searchTimeout) + // WebSearchTool searches the web and returns results via a configurable // backend. The default backend (when Backend is nil) scrapes DuckDuckGo's // HTML interface — no API key required, but fragile to upstream HTML @@ -131,7 +136,7 @@ func duckDuckGoSearch(ctx context.Context, query string, maxResults int) ([]sear } req.Header.Set("User-Agent", "harness/1.0 (Go agent framework)") - resp, err := http.DefaultClient.Do(req) + resp, err := searchClient.Do(req) if err != nil { return nil, err } diff --git a/tools/web/websearch_backends.go b/tools/web/websearch_backends.go index 08ba613..e6a6343 100644 --- a/tools/web/websearch_backends.go +++ b/tools/web/websearch_backends.go @@ -17,6 +17,10 @@ import ( // are constructed with their config (API key, base URL, etc.) at // registration time and remain immutable thereafter. This keeps the tool // dispatch path zero-allocation in the hot loop. +// +// Implementations that make outbound HTTP calls MUST use the package +// searchClient (SafeHTTPClient) so a configured/typo'd internal base URL +// cannot be used for SSRF. (N4) type WebSearchBackend interface { Name() string Search(ctx context.Context, query string, maxResults int) ([]searchResult, error) @@ -58,7 +62,7 @@ func (b *braveBackend) Search(ctx context.Context, q string, n int) ([]searchRes } req.Header.Set("Accept", "application/json") req.Header.Set("X-Subscription-Token", b.apiKey) - resp, err := http.DefaultClient.Do(req) + resp, err := searchClient.Do(req) if err != nil { return nil, err } @@ -119,7 +123,7 @@ func (b *tavilyBackend) Search(ctx context.Context, q string, n int) ([]searchRe return nil, err } req.Header.Set("Content-Type", "application/json") - resp, err := http.DefaultClient.Do(req) + resp, err := searchClient.Do(req) if err != nil { return nil, err } @@ -169,7 +173,7 @@ func (b *searxngBackend) Search(ctx context.Context, q string, n int) ([]searchR if err != nil { return nil, err } - resp, err := http.DefaultClient.Do(req) + resp, err := searchClient.Do(req) if err != nil { return nil, err } diff --git a/tools/web/websearch_test.go b/tools/web/websearch_test.go new file mode 100644 index 0000000..5f34ee1 --- /dev/null +++ b/tools/web/websearch_test.go @@ -0,0 +1,29 @@ +package web + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func testCtx(t *testing.T) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + return ctx +} + +func TestSearchClient_IsSafe(t *testing.T) { + require.NotNil(t, searchClient) + require.NotNil(t, searchClient.Transport) + require.NotNil(t, searchClient.CheckRedirect) + require.Equal(t, searchTimeout, searchClient.Timeout) +} + +func TestSearxng_BlocksPrivateBaseURL(t *testing.T) { + b := newSearxngBackend("http://127.0.0.1:8080") + _, err := b.Search(testCtx(t), "hello", 3) + require.Error(t, err) +} From 01b55a144636c1a5dd115295c51d16d9d9d5342d Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 11:25:22 +0800 Subject: [PATCH 5/7] fix(browser): block private-IP resolution via host-resolver-rules (S3) --- tools/browser/browser.go | 19 +++++++++++++++++++ tools/browser/browser_ssrf_live_test.go | 24 ++++++++++++++++++++++++ tools/browser/browser_test.go | 11 +++++++++++ 3 files changed, 54 insertions(+) create mode 100644 tools/browser/browser_ssrf_live_test.go diff --git a/tools/browser/browser.go b/tools/browser/browser.go index 7db7101..9cddf95 100644 --- a/tools/browser/browser.go +++ b/tools/browser/browser.go @@ -36,6 +36,24 @@ 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" @@ -474,6 +492,7 @@ 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.UserDataDir(udd), )..., ) diff --git a/tools/browser/browser_ssrf_live_test.go b/tools/browser/browser_ssrf_live_test.go new file mode 100644 index 0000000..1c06c8d --- /dev/null +++ b/tools/browser/browser_ssrf_live_test.go @@ -0,0 +1,24 @@ +//go:build live + +package browser + +import ( + "context" + "testing" + "time" + + "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 +func TestInPageFetchPrivateIPBlocked_Live(t *testing.T) { + tool := NewBrowserTool() + defer tool.Shutdown() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + res, err := tool.Execute(ctx, []byte(`{"action":"evaluate","url":"https://example.com","session":"ssrf","script":"fetch('http://169.254.169.254/').then(()=>'REACHED').catch(e=>'BLOCKED:'+e)"}`)) + require.NoError(t, err) + require.NotContains(t, res.Output, "REACHED") +} diff --git a/tools/browser/browser_test.go b/tools/browser/browser_test.go index e36548c..7a78fd3 100644 --- a/tools/browser/browser_test.go +++ b/tools/browser/browser_test.go @@ -4,12 +4,23 @@ 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()) From fb5103fb87c09278b03984ff0d2818480f943fce Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 11:27:34 +0800 Subject: [PATCH 6/7] feat(file): cap read_file/edit_file size to prevent OOM (N5) --- tools/file/editfile.go | 4 +++ tools/file/limits.go | 27 +++++++++++++++++ tools/file/readfile.go | 23 ++++++++++++-- tools/file/readfile_test.go | 60 +++++++++++++++++++++++++++++++++++++ 4 files changed, 112 insertions(+), 2 deletions(-) create mode 100644 tools/file/limits.go create mode 100644 tools/file/readfile_test.go diff --git a/tools/file/editfile.go b/tools/file/editfile.go index 2bad1bb..54e43e1 100644 --- a/tools/file/editfile.go +++ b/tools/file/editfile.go @@ -74,6 +74,10 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T } } + if msg := checkFileSize(in.Path, int64(maxTextFileSize), "text"); msg != "" { + return tool.ToolResult{Error: msg}, nil + } + data, err := os.ReadFile(in.Path) if err != nil { return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil diff --git a/tools/file/limits.go b/tools/file/limits.go new file mode 100644 index 0000000..d1903a5 --- /dev/null +++ b/tools/file/limits.go @@ -0,0 +1,27 @@ +package file + +import ( + "fmt" + "os" +) + +const ( + maxTextFileSize = 10 * 1024 * 1024 // 10 MB + maxImageFileSize = 5 * 1024 * 1024 // 5 MB +) + +// checkFileSize stats path and returns a non-empty error string if the file +// exceeds limit. kind is "text" or "image" for the message. Empty return means +// within bounds (or stat failed, in which case the caller's read surfaces the +// real error). +func checkFileSize(path string, limit int64, kind string) string { + fi, err := os.Stat(path) + if err != nil { + return "" + } + if fi.Size() > limit { + return fmt.Sprintf("file too large: %d bytes exceeds the %d byte limit for %s files; read a specific range or use a different tool", + fi.Size(), limit, kind) + } + return "" +} diff --git a/tools/file/readfile.go b/tools/file/readfile.go index 8a6c793..703c1b1 100644 --- a/tools/file/readfile.go +++ b/tools/file/readfile.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "io" "os" "path/filepath" "strings" @@ -93,13 +94,31 @@ func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T } } - data, err := os.ReadFile(in.Path) + ext := strings.ToLower(filepath.Ext(in.Path)) + limit := int64(maxTextFileSize) + kind := "text" + if _, isImg := imageExtMap[ext]; isImg { + limit = int64(maxImageFileSize) + kind = "image" + } + if msg := checkFileSize(in.Path, limit, kind); msg != "" { + return tool.ToolResult{Error: msg}, nil + } + + f, err := os.Open(in.Path) if err != nil { return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, limit+1)) + if err != nil { + return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil + } + if int64(len(data)) > limit { + return tool.ToolResult{Error: fmt.Sprintf("file too large: exceeds the %d byte limit for %s files; read a specific range or use a different tool", limit, kind)}, nil + } // Check if this is an image file - ext := strings.ToLower(filepath.Ext(in.Path)) if mimeType, ok := imageExtMap[ext]; ok { mimeType = detectImageMIMEFromBytes(data, mimeType) return tool.ToolResult{ diff --git a/tools/file/readfile_test.go b/tools/file/readfile_test.go new file mode 100644 index 0000000..744123a --- /dev/null +++ b/tools/file/readfile_test.go @@ -0,0 +1,60 @@ +package file + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func writeSized(t *testing.T, dir, name string, n int) string { + t.Helper() + p := filepath.Join(dir, name) + require.NoError(t, os.WriteFile(p, make([]byte, n), 0o600)) + return p +} + +func TestReadFile_RejectsOversizedText(t *testing.T) { + dir := t.TempDir() + p := writeSized(t, dir, "big.txt", maxTextFileSize+1) + tool := &ReadFileTool{} + in, _ := json.Marshal(map[string]string{"path": p}) + res, err := tool.Execute(context.Background(), in) + require.NoError(t, err) + require.Contains(t, res.Error, "too large") +} + +func TestReadFile_AllowsNormalText(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "ok.txt") + require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600)) + tool := &ReadFileTool{} + in, _ := json.Marshal(map[string]string{"path": p}) + res, err := tool.Execute(context.Background(), in) + require.NoError(t, err) + require.Empty(t, res.Error) + require.Equal(t, "hello", res.Output) +} + +func TestReadFile_RejectsOversizedImage(t *testing.T) { + dir := t.TempDir() + p := writeSized(t, dir, "big.png", maxImageFileSize+1) + tool := &ReadFileTool{} + in, _ := json.Marshal(map[string]string{"path": p}) + res, err := tool.Execute(context.Background(), in) + require.NoError(t, err) + require.Contains(t, res.Error, "too large") +} + +func TestEditFile_RejectsOversized(t *testing.T) { + dir := t.TempDir() + p := writeSized(t, dir, "big.txt", maxTextFileSize+1) + tool := &EditFileTool{} + in, _ := json.Marshal(map[string]string{"path": p, "old_string": "a", "new_string": "b"}) + res, err := tool.Execute(context.Background(), in) + require.NoError(t, err) + require.Contains(t, res.Error, "too large") +} From d6db565d7c756aeea996f60f0022d2579d324204 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 11:56:30 +0800 Subject: [PATCH 7/7] fix(web): dial all validated IPs for dual-stack fallback (I1); fix live SSRF test to await fetch (M1) --- tools/browser/browser_ssrf_live_test.go | 24 ++++++++++++++++++++++-- tools/web/client.go | 22 ++++++++++++++++------ tools/web/client_test.go | 11 +++++++++++ 3 files changed, 49 insertions(+), 8 deletions(-) diff --git a/tools/browser/browser_ssrf_live_test.go b/tools/browser/browser_ssrf_live_test.go index 1c06c8d..396d436 100644 --- a/tools/browser/browser_ssrf_live_test.go +++ b/tools/browser/browser_ssrf_live_test.go @@ -7,6 +7,8 @@ import ( "testing" "time" + "github.com/chromedp/cdproto/runtime" + "github.com/chromedp/chromedp" "github.com/stretchr/testify/require" ) @@ -18,7 +20,25 @@ func TestInPageFetchPrivateIPBlocked_Live(t *testing.T) { defer tool.Shutdown() ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() - res, err := tool.Execute(ctx, []byte(`{"action":"evaluate","url":"https://example.com","session":"ssrf","script":"fetch('http://169.254.169.254/').then(()=>'REACHED').catch(e=>'BLOCKED:'+e)"}`)) + + taskCtx, ccancel, err := launchBrowser(ctx) require.NoError(t, err) - require.NotContains(t, res.Output, "REACHED") + defer ccancel() + + require.NoError(t, chromedp.Run(taskCtx, chromedp.Navigate("https://example.com"))) + + 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") } diff --git a/tools/web/client.go b/tools/web/client.go index 4e134a5..735b33c 100644 --- a/tools/web/client.go +++ b/tools/web/client.go @@ -25,19 +25,29 @@ func SafeHTTPClient(timeout time.Duration) *http.Client { if err != nil { return nil, fmt.Errorf("cannot resolve %q — blocking to prevent SSRF", host) } - var dialIP net.IP + // 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 dialIP == nil { - dialIP = ip - } } - if dialIP == nil { + if len(ips) == 0 { return nil, fmt.Errorf("no usable address for %q", host) } - return dialer.DialContext(ctx, network, net.JoinHostPort(dialIP.String(), port)) + // 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 &http.Client{ diff --git a/tools/web/client_test.go b/tools/web/client_test.go index ec8e263..78a6502 100644 --- a/tools/web/client_test.go +++ b/tools/web/client_test.go @@ -39,5 +39,16 @@ func TestSafeHTTPClient_RedirectToPrivateBlocked(t *testing.T) { require.Error(t, err) } +func TestSafeHTTPClient_PublicUnreachableReturnsDialError(t *testing.T) { + // 192.0.2.1 is RFC5737 TEST-NET-1 (public, unrouteable). It is NOT in the + // private blocklist, so validation passes and we should get a DIAL error + // (timeout/unreachable), not a "blocked" validation error — proving the + // path dials rather than rejecting. + client := SafeHTTPClient(2 * time.Second) + _, err := client.Get("http://192.0.2.1/") + require.Error(t, err) + require.NotContains(t, err.Error(), "internal address") +} + var _ = isPrivateIP(net.IPv4(127, 0, 0, 1)) var _ = strings.TrimSpace