TL;DR
- A customer-controlled webhook URL is an outbound network capability. Treat its destination as untrusted even when the URL looks like a normal HTTPS endpoint.
- Parse URLs with a real URL library, allow only the required scheme and port, reject credentials and ambiguous syntax, and resolve every A and AAAA record.
- Reject non-global destinations and bind the actual connection to a validated address. A DNS pre-check followed by an ordinary hostname lookup is still vulnerable to DNS rebinding.
- Disable redirects, enforce network-level egress restrictions, cap response bytes and time, and make retry, signing, and secret handling explicit.
Why webhook delivery creates an SSRF boundary
A webhook product asks a customer to provide a destination URL, then asks your server to connect to it. That makes your service a network client under partial attacker control. An attacker can register a destination that resolves to an internal service, a loopback listener, a cloud metadata endpoint, or a public relay that redirects to one of those destinations. The request originates from your infrastructure, so network controls and credentials available to that infrastructure can be exposed.
Server-Side Request Forgery (SSRF) is not solved by checking that a string begins with https:// or does not contain the word localhost. URL parsers, DNS answers, redirects, IPv6 forms, and proxy environment variables can all change where the request goes. OWASP recommends positive destination validation, disabling redirects, and binding the connection to a validated address because a separate DNS check does not prevent rebinding. OWASP SSRF Prevention Cheat Sheet
This guide focuses on an outbound webhook dispatcher that sends events to customer-configured endpoints. The same controls apply to URL previews, importers, callback validators, and other server-side fetch features, but a webhook system has additional requirements around retries, event signatures, and endpoint ownership.
Prefer a customer domain allowlist when the product can support one. If arbitrary public destinations are a business requirement, use multiple independent controls. The goal is to ensure the destination that is checked is the destination that receives the TCP connection, and that the process has no path to sensitive internal networks even if application validation fails.
Build a destination policy before sending requests
Accept only the URL forms the product needs
Parse the URL using a well-maintained URL parser. Require https unless an explicit product need justifies HTTP. Reject user information such as user:password@host, fragments, missing hostnames, control characters, unsupported schemes, and nonstandard ports. Normalize the hostname with the parser’s IDNA handling and compare allowlisted hostnames on label boundaries. A suffix string check can incorrectly allow trusted.example.attacker.invalid or similarly confusing names.
Do not accept a raw IP literal by default. If the product must support them, run the literal through the same address policy as DNS results. Reject IPv4 shorthand, scoped IPv6 addresses, IPv4-mapped IPv6 that embed a blocked address, and any parser disagreement between the validation layer and the HTTP client. Test the canonicalized URL produced by the exact libraries in use.
Restrict methods, headers, and request bodies. A delivery endpoint generally needs a fixed method and a small set of generated headers. Do not let a tenant choose arbitrary headers like Host, Authorization, Cookie, Proxy-Authorization, or hop-by-hop connection headers. Create a fresh request from allowlisted values instead of forwarding a user-controlled HTTP request.
Resolve every address family and reject unsafe answers
Resolve the hostname and inspect every address returned for both IPv4 and IPv6. Reject the hostname if any answer is not globally routable under your policy. This conservative rule avoids allowing a hostname whose address selection can vary between public and private results. Also consider blocking internal DNS suffixes, private split-horizon zones, and organization-specific ranges that Python’s generic address classifier cannot know.
Python’s ipaddress module exposes is_global, but its registry interpretation has changed across Python versions. In particular, shared address space has special behavior, and documentation notes corrections in version 3.13. Pin your runtime, define your own explicit denied CIDRs for the deployment, and test a curated set of special addresses during upgrades. Python ipaddress reference
from ipaddress import ip_address
from socket import getaddrinfo, SOCK_STREAM
DENIED = (
# Add organization and provider-specific ranges to these policy inputs.
# Keep this list versioned and reviewed with network engineering.
)
def resolve_public_destination(host: str, port: int) -> list[str]:
answers = getaddrinfo(host, port, type=SOCK_STREAM)
addresses = {ip_address(item[4][0]) for item in answers}
if not addresses:
raise ValueError("hostname has no usable address")
for address in addresses:
if not address.is_global:
raise ValueError("destination is not globally routable")
if any(address in network for network in DENIED):
raise ValueError("destination is blocked by egress policy")
return sorted(str(address) for address in addresses)
The snippet is a policy illustration, not a complete SSRF-safe HTTP client. It does not pin the subsequent socket connection. It also assumes the runtime’s resolver and parser behave as expected. Treat DNS lookup as an input to a trusted egress layer rather than as proof that a later independent HTTP lookup is safe.
Defeat DNS rebinding at the connection boundary
A classic time-of-check/time-of-use failure occurs when the application resolves a hostname, validates a public IP, and then calls an HTTP client with the original hostname. The HTTP library may perform a second DNS lookup when opening the socket. If that answer changes to a private or metadata address, the check and the connection disagree. This is DNS rebinding. OWASP explicitly warns that checking DNS answers separately is insufficient and says the connection must be bound to a validated address. OWASP guidance on DNS rebinding and redirects
There are two practical patterns:
- Use a dedicated egress proxy. The application sends a normalized destination to a proxy that performs resolution, address policy, connection pinning, TLS verification, and redirect blocking as one operation. The worker network can connect only to this proxy. This concentrates the difficult socket behavior in a component designed to enforce it.
- Use a transport that connects to the vetted IP. A custom transport can dial a validated address while preserving the original hostname for the HTTP
Hostheader, TLS Server Name Indication, and certificate validation. The exact mechanism depends on the HTTP library and version. It must not disable TLS verification or rewrite the hostname to an IP in a way that changes certificate checking.
Do not improvise this with a preflight DNS lookup followed by httpx.post(url). HTTPX supports custom transports and a trust_env option, but a secure pinning transport still needs careful implementation and review. HTTPX transport API · HTTPX environment configuration
When using a proxy, ensure that user-controlled proxy environment variables cannot redirect requests through an unexpected intermediary. HTTPX clients can disable ambient proxy environment configuration with trust_env=False. In production, configure the intended proxy explicitly and constrain workers so they cannot connect directly to arbitrary destinations.
Do not follow redirects by default
Suppose a customer endpoint returns a redirect from a public address to http://169.254.169.254/. A client that follows redirects can reach the forbidden target even if the initial hostname was safe. Redirects also allow a trusted-looking endpoint to bounce through several domains and obscure which system received the webhook.
Disable automatic redirects. If a product requirement needs them, treat each redirect as a new destination: parse the Location header, reapply scheme, port, hostname, DNS, and address checks, and pin the next connection. Enforce a small redirect count and reject redirect loops. In most webhook systems, the simpler policy is to treat a redirect response as a delivery failure and ask the endpoint owner to configure the final URL directly.
Put network-level controls around the worker
Application checks can regress. Place the webhook worker in a network segment that cannot route to databases, control planes, internal admin panels, or cloud metadata endpoints. Use a deny-by-default firewall or network policy, then permit only the egress proxy or a tightly defined destination set. This reduces impact if an application parser or transport has a vulnerability. OWASP also recommends network segmentation and deny-by-default egress policies as part of SSRF mitigation.
Cloud metadata services need provider-specific treatment. Block the link-local metadata addresses and use the provider’s hardened metadata mode where available. Do not assume a single IPv4 block is enough for every cloud, runtime, or IPv6 configuration. The worker should have no instance role credentials unless the delivery operation truly requires them. If credentials are required, scope them to the minimum action and resource.
Separate delivery workers from application servers. The dispatch service should not share ambient credentials, mounted sockets, or service-account permissions with a privileged control plane. Apply per-tenant rate limits and a global concurrency ceiling. A webhook endpoint that accepts connections but never responds can otherwise consume worker slots, file descriptors, memory, and retry capacity.
Bound time, bytes, and retry work
Set a total delivery deadline and separate connect, write, and read timeouts. A connect timeout bounds network establishment. A read timeout bounds waiting between response bytes, but a peer that trickles data can still hold a worker unless a total deadline also exists. Limit response bytes and do not parse arbitrary response bodies. Usually the dispatcher needs only a status code and a small diagnostic excerpt after redaction.
Use a retry schedule with exponential backoff and jitter, a maximum age, and a terminal state. Retry connection failures and selected transient status codes. Do not retry a permanent validation failure forever. Keep per-tenant and global budgets so a misconfigured endpoint cannot monopolize the fleet. Record the last attempt time, next attempt time, attempt number, and sanitized failure class.
A receiving server may accept an event and then time out before your dispatcher sees its response. It may receive the retry twice. Include a stable event ID, and document that webhook consumers should deduplicate. This is the same uncertainty described in our guide to idempotent payment operations. A signed event authenticates content; it does not make delivery exactly once.
Sign events without leaking reusable credentials
Sign the raw event bytes, not a JSON object that might be serialized differently by the sender and verifier. Include a timestamp and stable event ID in the signed input. The receiver should compare the signature in constant time and enforce a reasonable timestamp window, while still using event IDs for durable deduplication. Rotate endpoint secrets without making both old and new keys valid forever.
Use a separate secret for each endpoint or tenant, keep it in a secret store, and never put it in the URL. Do not include credentials from the user’s original URL in outbound requests. Redact authorization headers, URL userinfo, query tokens, and sensitive response bodies from logs and traces. Provide a secret rotation workflow that can overlap keys briefly and records which key version signed each attempt.
Validate a destination when it is created and again immediately before every delivery. A saved URL can become unsafe later because DNS records, redirects, ownership, or network policy changed. Re-run the full address policy for each attempt and do not trust a prior validation result as permanent.
Test the full request path, not only a URL helper
Unit tests can cover URL parsing and IP classification, but they cannot prove which address the socket reaches. Add an integration test with a controlled DNS resolver and a test egress proxy. Exercise public A records, public AAAA records, mixed public and private answers, CNAME chains, rebinding between validation and connect, IPv4-mapped IPv6, unusual numeric host forms, and DNS failures.
Test redirects to a private address, redirect chains, unusual ports, userinfo, embedded credentials, proxy environment variables, slow headers, slow body trickles, large responses, TLS certificate mismatch, and connection reset after the server accepts the event. For each blocked attempt, assert that the destination server did not receive a connection. Include cloud metadata addresses and your organization’s own internal CIDRs in the test corpus.
Finally test operational behavior: retry exhaustion, per-tenant concurrency, secret rotation, sanitized logs, duplicate delivery, and a worker crash during an attempt. The service should make failed deliveries visible without exposing the data that caused the failure.
Frequently asked questions
Is checking DNS and rejecting private IPs enough to prevent SSRF?
No. The HTTP client can resolve the hostname again after the check, so DNS rebinding can change the address used for the connection. Bind the socket to a validated address or use an egress proxy that resolves, checks, and connects as one operation. Also disable redirects and apply network-level egress controls.
Should webhook senders follow customer endpoint redirects?
Usually not. A redirect can point to a private address or a different host and bypass the original destination check. Treat redirects as delivery failures. If following them is required, validate and pin every new target, restrict schemes and ports, and cap the redirect chain.
Can Python ipaddress.is_global define my whole SSRF policy?
It is a useful classifier, not a complete deployment policy. Its behavior follows address registries and has changed across Python versions. Add explicit organization and provider-specific denied ranges, pin supported runtime versions, and test special IPv4 and IPv6 cases during upgrades.
Does an HMAC signature make webhook delivery safe to retry?
No. A signature lets a receiver verify event authenticity and integrity. It does not prevent duplicate delivery or make the receiver’s side effect idempotent. Include a stable event ID and tell consumers to store processed IDs or otherwise make their business operation safe to repeat.
Make outbound access an explicit capability
Webhook delivery should have a narrow network identity, a destination policy, and a recoverable retry model. Validate URLs with a parser, inspect all DNS answers, pin the actual connection, disable redirects, constrain egress, and cap time and bytes. Treat every attempt as untrusted input even after the endpoint has been saved.
If your product lets customers configure callbacks or integrations, review the entire path from URL validation through the socket and retry worker. Talk with our security engineers about isolating outbound delivery, testing rebinding cases, and setting a policy that matches your product’s destination requirements.
