SSRF prevention requires controlling the destination your server actually connects to, including DNS results and redirect targets. For SaaS features that fetch user-supplied URLs, combine strict parsing, destination restrictions, connection-time enforcement, and outbound network controls.
A link preview or URL import gives users indirect access to your server’s network position. The safest design applies destination checks at every hop, then limits what each request can consume. Start by defining which destinations your feature genuinely needs.
Key Takeaways
- Restrict URL inputs, schemes, hosts, and ports to the feature’s needs.
- Validate IPv4 and IPv6 destinations, then bind the connection to an approved address.
- Treat redirects as new requests, isolate outbound workers, and cap request duration and response size.
How SaaS URL Fetching Becomes SSRF
Server-side request forgery happens when an attacker makes your backend request an unintended destination. The backend might reach services that the attacker can’t access directly.
Common entry points include link previews, image proxies, remote document imports, and webhook delivery settings. An attacker submits an internal address, or supplies a public hostname that redirects or later resolves internally.
The consequences extend beyond returned content. A request can trigger an internal action, expose cloud credentials, or reveal reachable services through timing differences. Even a fetcher that never displays its response can remain vulnerable.
OWASP’s SSRF guidance recommends application and network defenses because input filtering alone leaves gaps.
For multi-tenant SaaS, authorize the caller before scheduling a fetch. Carry trusted tenant context into the job, and reauthorize user-delegated work when it runs.
Constrain URLs Before Making Requests
Parse once and restrict schemes
Use a maintained URL parser compatible with your HTTP client. Reject malformed URLs, embedded username/password fields, unexpected ports, and ambiguous input. Don’t use a regular expression as the entire validator.
Prefer HTTPS. Allow HTTP only when the feature requires it, and reject schemes such as file, gopher, and ftp. Limit ports to approved services rather than accepting every numeric value.
Pass the validated, parsed destination through the request pipeline. Repeated decoding or reparsing by different components can produce conflicting interpretations.
Users also shouldn’t control the Host header, proxy configuration, or arbitrary authentication headers.
Prefer exact hostname allowlists
For a fixed integration, accept a provider identifier or resource ID and build the URL server-side. This avoids accepting an unrestricted destination.
When URLs are necessary, normalize hostname case, internationalized names, and trailing dots consistently before matching approved hosts. Avoid substring matching: an approved name appearing somewhere inside a hostname proves nothing.
OWASP’s prevention cheat sheet distinguishes constrained destinations from features requiring arbitrary external access.
A hostname allowlist narrows exposure, but DNS and connection checks remain necessary. Approved names can still resolve to prohibited addresses.
Validate DNS and the Actual Connection
Classify every IPv4 and IPv6 address
Resolve both A and AAAA records. Reject the request if any returned address violates the destination policy, and fail closed when resolution fails.
For public-only fetching, block IPv4 loopback 127.0.0.0/8, private ranges 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16, plus link-local 169.254.0.0/16.
IPv6 needs equivalent protection: loopback ::1, unique-local fc00::/7, and link-local fe80::/10. Also reject unspecified, multicast, and other prohibited special-purpose destinations. These examples aren’t an exhaustive address policy.
Use maintained IP-classification logic. Normalize IPv4-mapped IPv6 addresses before classification so embedded private IPv4 addresses can’t bypass checks. Handle NAT64 and other translation mechanisms explicitly, or reject unsupported forms.
Block provider-specific metadata destinations too. AWS documents its instance metadata addresses as 169.254.169.254 and, where enabled, fd00:ec2::254.
Bind validation to connection establishment
DNS rebinding exploits a gap between validation and use. A hostname can return a public address during validation, then return an internal address when the HTTP client resolves it again.
Resolve through controlled infrastructure and connect to a validated address without an unchecked second lookup. Preserve the original hostname for HTTP routing, TLS SNI, and certificate verification. Don’t disable certificate checks.
A DNS lookup protects the fetch only when its approved result governs the connection the client actually opens.
Apply this rule to retries and fallback addresses. If an outbound proxy performs DNS resolution, that proxy must enforce the destination policy.
Revalidate Redirects and Isolate Outbound Traffic
Treat each redirect as a fresh destination
Disable automatic redirects by default. If the feature needs them, handle each hop explicitly with a bounded chain.
Resolve relative redirect targets against the current URL. Then repeat parsing, scheme, port, hostname, DNS, and IP checks before connecting. A safe first destination doesn’t authorize the next one.
OWASP’s Node.js prevention guidance describes this per-hop validation approach.
Don’t forward cookies, authorization headers, or endpoint-specific webhook credentials to a different origin. For webhook delivery, disabling redirects often provides the clearest security and delivery behavior.
Make network controls an independent barrier
Run URL-fetching workers separately from application services. Block their access to databases, Redis, internal administration endpoints, private service networks, and metadata services.
Use an egress firewall or policy-enforcing proxy with deny-by-default rules and narrowly scoped allowances. Apply equivalent restrictions to IPv4 and IPv6, including the network’s actual routing and translation paths.
Workers should have minimal cloud permissions and no unnecessary application credentials. Network isolation reduces damage when application validation has a defect.
Keep tenant identity attached to queued work and stored results. If you cache responses, include tenant and access-policy scope wherever content isn’t deliberately public.
Bound Request Time and Response Size
SSRF prevention also needs resource controls. A publicly reachable endpoint can hold connections open or return enough data to exhaust workers.
Set separate limits for DNS resolution, connection establishment, TLS negotiation, response headers, and body reads. Also enforce an overall deadline. A peer sending occasional bytes can evade an idle timeout without completing useful work.
Stream responses with a hard byte cap. Don’t trust Content-Length, because it can be absent or inaccurate. Limit decompressed output too, since compressed responses can expand substantially.
Apply per-tenant concurrency limits, queue quotas, and bounded retries. Cancel underlying requests when jobs expire.
Treat downloaded content as untrusted. Imports should enter private quarantine before validation and release. Preview generation needs isolated processing, and browser previews shouldn’t inherit application cookies.
A Secure Fetch Flow for Link Previews
A link-preview worker can use this ordered flow:
- Authenticate the caller, authorize the workspace operation, and create an immutable job containing trusted tenant context.
- Parse the submitted URL. Enforce the scheme, port, hostname, and input rules before DNS resolution.
- Resolve IPv4 and IPv6 addresses through the controlled resolver. Reject prohibited results and DNS failures.
- Open a TLS-verified connection to an approved address while retaining the original hostname. Use the restricted egress path.
- Process each permitted redirect through the same validation sequence. Never let the client follow redirects automatically.
- Stream the response within time and byte limits. Process preview metadata in isolation, then store the result under the authorized tenant.
Return safe error categories rather than internal response bodies or detailed network diagnostics. In logs, record correlation IDs, destination classifications, and rejection reasons. Redact signed URL parameters, credentials, and sensitive payloads.
Match Restrictions to the Feature
Different features need different destination policies.
| Feature | Practical default | Main trade-off |
|---|---|---|
| Webhooks | HTTPS endpoints, restricted ports, no redirects | Some customer endpoints need explicit exceptions. |
| Link previews | Public destinations with validated redirects | Private intranet links won’t generate previews. |
| URL imports | Approved providers where feasible, isolated downloads | Broad compatibility adds content-processing risk. |
A fixed-provider import can use a hostname allowlist. General link previews usually require public-internet access, so connection enforcement and egress isolation carry more responsibility.
If customers need private webhook destinations, provide a separately authenticated agent or connector with explicit resource permissions. Don’t open private ranges in the shared public fetcher.
For authenticated imports, bind credentials to a stored integration and approved destination. Never attach a tenant’s API key merely because the submitted URL requests authentication.
Testing Checklist Before Release
Test through the deployed worker and egress path. Unit tests can’t reveal every proxy, resolver, or routing behavior.
- Submit malformed URLs, user-info fields, unsupported schemes, alternate IP representations, misleading hostname suffixes, and unapproved ports. Each should fail before any prohibited connection.
- Exercise loopback, private, link-local, metadata, mapped IPv6, and mixed public/private DNS answers. Include destinations available only through IPv6.
- Use controlled DNS infrastructure to change answers between validation and connection. Confirm the worker uses only approved addresses during retries and fallback.
- Test redirects into prohibited networks, relative targets, redirect loops, and cross-origin credential forwarding.
- Serve oversized, compressed, slow, and never-ending responses. Assert cancellation, bounded memory use, and correct tenant quotas.
- Attempt cross-tenant job access and cached-result retrieval. Pair denials with successful authorized previews, imports, and webhook deliveries.
Assert side effects as well as HTTP responses. A rejected request mustn’t contact the forbidden destination, leak a credential, or publish unvalidated content.
Frequently Asked Questions
Does CORS prevent SSRF?
No. CORS governs browser access to cross-origin responses. SSRF originates from your server, so browser origin rules don’t restrict the backend’s network access. Configure outbound destination controls independently of your API’s CORS policy.
Are signed import URLs safe to fetch?
A signature can authorize access to an object, but it doesn’t establish that the destination is safe for your server. Apply normal destination checks. Also treat the signed URL as a bearer credential and exclude its sensitive parameters from logs and analytics.
Build Around the Connection You Permit
Reliable SSRF prevention ties destination policy to the connection actually made. Parsing, DNS inspection, and redirect validation must remain connected throughout the request.
Back those checks with isolated workers, restricted egress, and bounded processing. Keep tenant authorization attached to every job and result.
Before releasing a URL-fetching feature, test prohibited destinations through its real production network path. A rejected input is useful only when the unwanted connection never happens.