Merge branch 'security/round4': SSRF + file-size hardening (S2/N4/S3/N5)

This commit is contained in:
sausheong committed 2026-06-13 12:06:50 +08:00
commit b85ffeac69
16 files changed
+396 -19

No files matched your search

+19
View File
@@ -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),
)...,
)
+44
View File
@@ -0,0 +1,44 @@
//go:build live
package browser
import (
"context"
"testing"
"time"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
"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()
taskCtx, ccancel, err := launchBrowser(ctx)
require.NoError(t, err)
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")
}
+11
View File
@@ -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())
+4
View File
@@ -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
+27
View File
@@ -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 ""
}
+21 -2
View File
@@ -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{
+60
View File
@@ -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")
}
+66
View File
@@ -0,0 +1,66 @@
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)
}
// 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 &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
},
}
}
+54
View File
@@ -0,0 +1,54 @@
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)
}
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
+4
View File
@@ -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
+27
View File
@@ -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)
}
}
+1 -13
View File
@@ -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 {
+16
View File
@@ -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")
}
+6 -1
View File
@@ -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
}
+7 -3
View File
@@ -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
}
+29
View File
@@ -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)
}