Repository navigation
net: SSRF guard for web_fetch (IPv4 blocklist + redirect re-check) - #85
Conversation
picoclaw documents "SSRF protection via DNS re-resolution and private IP blocking" on their WebFetchTool; PasClaw shipped web_fetch without it. Closing that gap before someone runs the gateway exposed — without this, an agent on (e.g.) an EC2 instance can be tricked into fetching http://169.254.169.254/latest/meta-data/iam/security- credentials/<role> and leaking the instance's IAM credentials. PasClaw.Net.SSRF (new unit) HostIsLocal(host): bool — parses host as IPv4 literal (no DNS) or resolves via Indy GStack, checks each result against an 11-entry CIDR blocklist: 0.0.0.0/8 unspecified / kernel localhost on some BSDs 10.0.0.0/8 RFC1918 corporate LAN 100.64.0.0/10 RFC6598 carrier-grade NAT 127.0.0.0/8 loopback 169.254.0.0/16 link-local — INCLUDES 169.254.169.254 cloud metadata endpoint 172.16.0.0/12 RFC1918 corporate LAN 192.0.0.0/24 IETF Protocol Assignments 192.168.0.0/16 RFC1918 home LAN 198.18.0.0/15 RFC2544 benchmark 224.0.0.0/4 IPv4 multicast 240.0.0.0/4 reserved Symbolic-name short-circuit: 'localhost', 'localhost.localdomain', and IPv6 '::1' refuse without DNS so systems with no resolver still fail closed. URLIsLocal(url): bool — strips scheme + userinfo + bracketed IPv6 + port out of the URL and calls HostIsLocal on the host. Failed URL parsing returns True (fail closed); failed DNS resolution returns False (let the connect attempt fail with a clearer network error). Initialization block IncUsages Indy's GStack so the first resolution doesn't pay the setup cost. TSandboxPolicy.BlockPrivateNetworks (new field, default True) Adds the toggle to sandbox/config.json so the operator can turn the guard off when they actually need the model to reach private addresses (local dev mode, intranet scraping) and have weighed the credential-leak risk. Serialised as sandbox.block_private_networks. TConfig defaults to True, so existing configs that don't mention the field get the guard on by default — opt-out, not opt-in. PasClaw.Tools.Sandbox.NetworkBlockingActive (new accessor) Reads GPolicy.BlockPrivateNetworks. Mirrors the existing RestrictionActive helper so web_fetch can ask the sandbox policy without re-loading TConfig from disk. PasClaw.Tools.WebFetch wiring Two-layer check: 1. Pre-check on the URL the model handed us — refused requests return a clear "web_fetch: SSRF: <url> refused (<reason>; flip sandbox.block_private_networks=false in config.json to allow)" so the model knows it's a policy refusal, not a transient network error. 2. TWebFetchRedirectGuard.OnRedirect runs URLIsLocal on every 3xx target. A public->private redirect (the canonical bypass attempt) raises from inside the callback and is caught by the existing try/except around HTTP.Get, yielding the same surface as a direct hit. Both layers must pass for the request to land. Build: Makefile UNIT_DIRS gains src/pkg/net; dproj DCC_UnitSearchPath grows ..\pkg\net plus DCCReference for PasClaw.Net.SSRF.pas. README sandbox-config table picks up block_private_networks; repo-layout net/ row added. Verified locally: make builds clean under FPC 3.2.2. Standalone smoke (33 assertions): - 17 IP literals — every blocked range edge + samples just OUTSIDE the range (172.32, 192.0.1, 100.128) confirming mask math is right - 3 symbolic localhost variants - 9 URLs (loopback, port, AWS metadata, userinfo stripped, localhost name, IPv6 ::1, two public IPs allowed, malformed) - 4 public passthroughs All pass. Known gaps (documented in the unit's docstring): - IPv6 blocklist beyond ::1 (fc00::/7, fe80::/10, IPv4-mapped ::ffff:0:0/96). Most attack vectors surface on IPv4 (metadata, RFC1918 LAN, localhost). Add when reported. - DNS rebinding: the guard re-resolves at request and redirect time, not per TCP packet. Closing this requires pinning the connection to the validated IP, which Indy doesn't make easy. Same residual risk picoclaw ships with; documented. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cbfaac2b12
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| HostEnd := Pos('@', S); | ||
| if HostEnd > 0 then S := Copy(S, HostEnd + 1, MaxInt); |
There was a problem hiding this comment.
Parse userinfo only inside the URL authority
When a blocked URL contains an @ in its path, query, or fragment, this strips everything through that character and validates the following text as the host. For example, http://169.254.169.254/latest/meta-data/@example.com is checked as example.com, but Indy's HTTP parser still connects to 169.254.169.254 because the @ occurs after the authority delimiter. This bypasses the new default SSRF protection for the cloud-metadata endpoint; delimit the authority before processing userinfo.
Useful? React with 👍 / 👎.
| if URLIsLocal(Dest, Reason) then | ||
| raise Exception.CreateFmt('SSRF: redirect to %s refused (%s; ' + |
There was a problem hiding this comment.
When a public server returns a common relative redirect such as Location: /login, Indy's TIdHTTP passes that raw Location value to OnRedirect. Calling URLIsLocal('/login', ...) fails to find ://, treats the destination as malformed, and raises an SSRF error. As a result, web_fetch can no longer follow relative redirects on otherwise safe public sites. Resolve relative redirect targets against the current URL before applying the host check, or explicitly permit them because they retain the already-validated origin.
Useful? React with 👍 / 👎.
…redirects Two Codex reviews against the SSRF guard, both legit and material. PR #85 P1 — userinfo-in-path bypass (cloud-metadata SSRF): ExtractHost ran Pos('@', S) against the entire post-scheme string, so an @ anywhere — in the path, query, or fragment — was treated as a userinfo delimiter. That meant http://169.254.169.254/latest/meta-data/@example.com parsed as host=example.com (validated, allowed), while Indy's HTTP client connected to 169.254.169.254 because the @ falls after the authority boundary. Complete bypass of the default cloud-metadata SSRF protection. Fix: slice the URL authority first — everything from the end of "://" to the first '/', '?', or '#' — and parse userinfo and port ONLY within that authority slice. Bytes past the boundary can no longer masquerade as the delimiter. Port trim now keys on ':' alone (authority slice already terminated on the path/ query/fragment delimiters). PR #85 P2 — relative redirects rejected as malformed: Indy passes whatever the server's Location header said into OnRedirect. A common public-server pattern is a path-relative redirect like "/login". The guard called URLIsLocal("/login") which found no "://", returned True (fail closed), raised, and broke web_fetch for the vast majority of public sites that use relative Location. Fix: classify each redirect target before invoking URLIsLocal: - Absolute http(s)://… — full SSRF check applies. - Protocol-relative //… — synthesise an http: prefix and run URLIsLocal on the result so the host check still fires (the host CAN change relative to the original request). - Path-relative /next or next.html — same origin as the request that already passed; let Indy follow it. Helper IsAbsoluteHttpURL handles the dispatch with a single case-insensitive scheme test. Regression coverage (16 standalone assertions, all pass): PR #85 P1 — bypass attempts: @ inside path on metadata host → blocked @ inside query string on metadata host → blocked @ inside fragment on metadata host → blocked @ inside path on loopback host → blocked real userinfo before loopback → still blocked real userinfo before public host → still allowed @ inside path on public host → still allowed userinfo + port + @ in path → loopback blocked authority terminated by ? → blocked authority terminated by # → blocked port still trimmed → loopback → blocked port still trimmed → public → allowed PR #85 P2 — relative-redirect handling (via URLIsLocal contract): bare path "/login" → True (fail closed — web_fetch shortcuts before this call) bare relative "next.html" → True (same) "http:" + "//127.0.0.1/x" synthesise → blocked "http:" + "//8.8.8.8/x" synthesise → allowed https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
picoclaw documents "SSRF protection via DNS re-resolution and private IP blocking" on their
WebFetchTool; PasClaw shippedweb_fetchwithout it. Closing the gap before someone runs the gateway exposed — without this, an agent on (e.g.) an EC2 instance can be tricked into fetchinghttp://169.254.169.254/latest/meta-data/iam/security-credentials/<role>and leaking the instance's IAM credentials.PasClaw.Net.SSRF(new unit)HostIsLocal(host) → bool: parses host as IPv4 literal (no DNS) or resolves via Indy'sGStack, checks each result against an 11-entry CIDR blocklist:0.0.0.0/810.0.0.0/8100.64.0.0/10127.0.0.0/8169.254.0.0/16169.254.169.254cloud metadata172.16.0.0/12192.0.0.0/24192.168.0.0/16198.18.0.0/15224.0.0.0/4240.0.0.0/4Symbolic-name short-circuit:
localhost,localhost.localdomain, and IPv6::1refuse without DNS so systems with no resolver still fail closed.URLIsLocal(url) → bool: strips scheme + userinfo + bracketed IPv6 + port and callsHostIsLocal. Failed URL parsing returns True (fail closed); failed DNS resolution returns False (let connect fail with a clearer network error).sandbox.block_private_networks(new, defaulttrue)Toggle on
TSandboxPolicy. Existing configs that don't mention the field get the guard on — opt-out, not opt-in.web_fetchtwo-layer wiringweb_fetch: SSRF: <url> refused (<reason>; flip sandbox.block_private_networks=false in config.json to allow)so the model knows it's a policy refusal, not a transient network error.TWebFetchRedirectGuard.OnRedirectrunsURLIsLocalon every 3xx target. A public→private redirect raises from inside the callback, gets caught by the existingtry/exceptaroundHTTP.Get, surfaces as the same SSRF error. Both layers must pass for the request to land.Verification
makebuilds clean under FPC 3.2.2. Standalone smoke — 33 assertions, all pass:172.32,192.0.1,100.128) confirming the mask math is right.localhost,LOCALHOST,localhost.localdomain).::1, two public IPs allowed, malformed).8.8.8.8,1.1.1.1, public-IP URLs).Known gaps (intentional, documented in the unit's docstring)
::1(fc00::/7,fe80::/10,::ffff:0:0/96IPv4-mapped)https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code