DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
FREEDOM251

Freedom251 › Blog › API security

How to Build an API SSRF Defense That Pins Safe Connections

By Freedom251 Team · · 11 min read

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Validate the destination IP immediately before the connection, not just the URL text. An API that accepts a user-controlled URL can be tricked into connecting to localhost, private network services, IPv6 local addresses, or cloud metadata even when the hostname appears on an allowlist. DNS chooses the address used by the socket, and that answer can be malicious from the start or change between validation and connection.

A defensible server-side fetcher parses the input strictly, permits only required schemes and ports, resolves every A and AAAA answer, rejects prohibited address ranges, pins the approved address to the actual connection, and revalidates every redirect. Network egress restrictions, segmentation, and metadata-service defenses limit damage if application checks fail, but a hostname check alone is not an SSRF defense.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What is API SSRF, and why does the resolved IP matter?

Server-Side Request Forgery (SSRF) occurs when a server retrieves a user-influenced URL without proving that the connection reaches the intended destination. The attacker supplies a URL to an API, image importer, webhook tester, document previewer, or similar feature; the server then makes the outbound request from a more trusted network position.

MITRE CWE-918 describes the consequences: an attacker may reach unexpected hosts or ports, bypass network access controls, read application data, scan internal networks, or invoke non-HTTP protocols such as file:// and gopher://. The risk is not determined by how respectable the hostname looks. It is determined by the address and protocol the server actually uses.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

DNS separates those two facts. A URL contains a hostname, while DNS returns one or more addresses. The HTTP client opens a socket to an address, potentially after its own resolver, connection pool, proxy, retry logic, or address-family fallback makes additional decisions. If policy is applied only to the original string, the policy is checking an identifier rather than the destination.

Why can a hostname allowlist still reach localhost or cloud metadata?

A hostname can be approved textually while resolving to a prohibited address. An attacker can control a domain that resembles an approved name, obtain control of a permitted DNS record, or exploit a DNS rebinding service that answers with a public address during validation and a local address during use. OWASP states the core limitation plainly: “Domain allowlisting alone does not prevent DNS rebinding.”

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The failure also appears when the validator and the HTTP client perform separate lookups. GitLab characterizes this as a time-of-check/time-of-use race: the name resolves to a safe address when checked, then changes before the request is sent. Even a validator that correctly classifies an address is ineffective if the approved address is discarded and the client resolves the name again.

Multiple DNS answers create another bypass. A name may return several A or AAAA records, with only one pointing to an internal range. Accepting the first textual answer, checking IPv4 but not IPv6, or allowing a resolver to select a different address later leaves an exploitable path. IPv4-mapped IPv6 forms and alternate textual representations must be normalized before classification.

Should a fetcher validate the URL, hostname, or resolved IP?

It must validate all three at different stages, with the resolved address as the final destination decision. URL parsing prevents syntax tricks; hostname policy limits which resources may be named; IP policy determines whether the socket can safely connect.

Validation target What it catches Why it is insufficient alone
URL string and parsed components Malformed input, ambiguous parser interpretations, embedded credentials, unexpected backslashes, unsupported schemes, and unusual ports A syntactically valid hostname can still resolve to an internal address.
Hostname or resource identifier Whether the requested service is on an explicit business allowlist DNS can map an approved name to a prohibited address or change the answer after checking.
Resolved IPv4 and IPv6 addresses Loopback, private, link-local, unique-local, multicast, broadcast, metadata, and other prohibited ranges The approved address must still be bound to the socket; a later lookup can substitute another one.
Connection-time enforcement Whether the actual socket uses the address that passed policy It does not replace parsing, scheme restrictions, redirect checks, or network egress controls.

For many APIs, the safest interface is not a complete user URL. Accept a resource identifier or hostname, then construct the URL yourself with a fixed HTTPS scheme, port, and controlled path. This removes parser edge cases and prevents callers from selecting a protocol or destination port the feature never needs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I build an SSRF-resistant server-side fetcher?

Use a staged pipeline in which every later operation receives the decision made by the earlier one. The following sequence keeps parsing, policy, DNS, and connection behavior aligned.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
  1. Parse with one standards-compliant URL parser

    Reject malformed input rather than trying to repair it. Reject ambiguous interpretations, embedded user information such as user:password@host, unexpected backslashes, control characters, and unsupported schemes. Do not pass the raw string to a second library that may parse it differently. Store the normalized scheme, hostname, port, path, and query as separate fields.

  2. Allow only the scheme and port the feature needs

    For an ordinary web callback, that normally means HTTPS and a fixed port or the protocol’s standard port. Explicitly reject file:, gopher:, ftp:, dict:, data:, and every unused scheme. A scheme check must happen before any network operation, including proxy negotiation.

  3. Apply hostname or resource policy

    Match the normalized host against an explicit allowlist, or map an approved resource identifier to a server-controlled hostname. Avoid suffix checks that turn approved.example into permission for approved.example.attacker.test. If wildcard names are required, define their boundaries precisely and keep the list as small as the business function allows.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  4. Resolve immediately before connecting

    Resolve the hostname at the point where the request will be made. Examine every returned A and AAAA record, not only the first result. Normalize IPv4-mapped IPv6 and alternate textual forms before applying policy. If any returned address is prohibited, fail closed rather than allowing a resolver or client to choose a different answer.

  5. Classify each address against the network policy

    Unless the feature explicitly requires internal destinations, reject loopback, RFC1918 private IPv4 space, link-local addresses, IPv6 unique-local space, multicast, broadcast, cloud-metadata ranges, and other reserved or administratively prohibited ranges. Keep the classification rules current for both address families. A public-looking address is not automatically safe if the request can be redirected or proxied into a restricted network.

  6. Pin the approved address to the socket

    Pass the exact validated address to the connection routine so it cannot perform a second DNS lookup. Keep the original hostname separately for the HTTP Host header, TLS Server Name Indication (SNI), and certificate verification. Routing to the approved IP while presenting the hostname preserves virtual hosting and certificate checks without surrendering destination control.

  7. Constrain the request and response

    Set strict connection and read timeouts, bound the response size, and limit retries. Normalize the response before returning anything to an untrusted caller. Do not expose raw upstream headers, detailed socket errors, or unrestricted response bodies that could disclose internal topology or credentials.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    Rank #3
    Sale
    Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
    • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
    • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
    • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
    • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
    • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
  8. Record the decision

    Log the normalized host, resolved addresses, selected address, scheme, port, redirect count, and the reason for any rejection. Avoid logging credentials or sensitive response data. These records help distinguish an ordinary configuration error from repeated probing of internal ranges.

How do I prevent DNS rebinding and time-of-check/time-of-use races?

Validation and use must share the same address object. Resolve once, classify that result, and open the socket to that exact address. Do not validate a name with one resolver call and then hand the name to a separate HTTP client that resolves it again.

Connection pools and retries need the same treatment. A pooled connection should be associated with the policy decision that permitted it; a new connection created after expiry or failure must repeat resolution and classification. Retries must not silently fall back from IPv6 to IPv4, or from one address to another, without applying the policy to the replacement.

If the platform’s HTTP library cannot pin an address while retaining the original hostname for SNI and certificate verification, place a controlled connector beneath it or use a client feature that explicitly separates the route address from the logical host. Disabling certificate verification is not an acceptable workaround: it removes identity validation while leaving SSRF unresolved.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What should happen when the target returns a redirect?

The simplest safe behavior is to disable automatic redirects. If redirects are a required feature, treat every Location value as a new untrusted input and repeat the complete process for each hop.

  1. Parse and normalize the new URL with the same parser.
  2. Reject credentials, backslashes, unsupported schemes, and disallowed ports.
  3. Apply hostname or resource policy to the new destination.
  4. Resolve all A and AAAA answers and classify every address.
  5. Pin the selected approved address for that hop while preserving the new hostname for Host, SNI, and certificate checks.
  6. Enforce a small maximum hop count and stop on loops or repeated destinations.

Never assume that a redirect remains on the original host, preserves HTTPS, or points to a public address. A permitted public endpoint can redirect to localhost, a private service, or a metadata endpoint unless each hop is independently checked.

Which addresses and protocols should an API block?

Block categories that the feature does not explicitly need, across both IPv4 and IPv6. The exact set depends on your architecture, but the following baseline prevents common internal-targeting paths.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Category Examples of why it is dangerous Default treatment
Loopback Reaches services bound only to the server itself. Reject.
RFC1918 private IPv4 Reaches databases, control panels, and internal APIs on private networks. Reject unless explicitly required and separately authorized.
Link-local May expose host-local services and cloud control endpoints. Reject.
IPv6 unique-local Provides private IPv6 routing comparable to private IPv4. Reject by default.
Multicast and broadcast Can create unintended fan-out or network discovery behavior. Reject.
Cloud metadata ranges May return instance identity documents, credentials, or configuration. Reject unless the application has a documented, tightly controlled need.
Unused schemes file, gopher, ftp, dict, and data can access local resources or non-HTTP services. Reject explicitly.

Do not treat a proxy as a security boundary by itself. A proxy can resolve names on the server’s behalf, follow redirects, or choose a different address family. Its behavior must be constrained by the same destination policy, and direct egress should be denied when the architecture requires all outbound traffic to pass through the controlled path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which controls belong in the application, and which belong in the network?

Application validation decides whether a particular request is legitimate; network controls limit what happens when validation is bypassed or a new code path appears. Use both layers rather than substituting one for the other.

Layer Useful controls Limit
Application Strict parsing, scheme and port allowlists, hostname policy, full A/AAAA classification, address pinning, redirect revalidation, bounded responses, and logging Can be bypassed by an implementation bug, a dependency, or an overlooked code path.
Network Deny-by-default outbound rules, segmentation, restricted routes, proxy enforcement, and monitoring Cannot prove that an allowed public destination is the intended business service.
Cloud and identity Least-privilege instance identities, metadata-service hardening, and separation of sensitive workloads Reduces impact but does not stop arbitrary internal requests.

Apply egress rules to every execution environment that can make the request, including workers and background jobs. Monitor rejected destinations, unusual redirect chains, repeated DNS changes, and bursts of requests to reserved ranges. These signals are valuable for incident response even when the request is blocked.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How can I review an implementation for SSRF gaps?

Use this checklist during design review and code review:

  • Is policy evaluated on the resolved address rather than only the original hostname string?
  • Are all A and AAAA answers checked, including IPv4-mapped IPv6 and alternate textual IP forms?
  • Does the connection use the exact address that passed validation?
  • Is the original hostname retained only for Host, SNI, and certificate verification?
  • Are redirects rejected or revalidated hop by hop?
  • Are file:, gopher:, ftp:, dict:, data:, and other unused schemes rejected?
  • Do retries, connection pools, proxies, and fallback address families enforce the same policy?
  • Are loopback, private, link-local, unique-local, multicast, broadcast, and cloud metadata ranges blocked where unnecessary?
  • Are outbound routes restricted and monitored at the network layer?
  • Are responses normalized and constrained before being exposed to callers?

A design that answers “no” to address pinning or redirect revalidation still has a destination-substitution path, even if every hostname appears on an allowlist.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What are common failed fixes, and how should they be corrected?

Checking only for a forbidden hostname

String checks such as searching for “localhost” miss numeric loopback forms, IPv6 notation, DNS aliases, and rebinding. Parse the URL and classify the resolved address instead.

Resolving once, then letting the client resolve again

This creates the exact race the validation was meant to prevent. Pass the approved address into the connector and preserve the hostname only for protocol identity.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Checking only IPv4

An attacker can supply an IPv6 address or obtain an AAAA record while IPv4 checks pass. Evaluate both families and normalize mapped forms.

Following redirects automatically

The initial destination may be harmless while a later hop is internal. Disable redirects or run the full policy for every hop.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Relying solely on a firewall

Egress filtering limits impact but cannot identify whether an allowed address is the intended service. Keep application-level destination checks and use the firewall as defense in depth.

What is the practical decision rule?

Consider the request safe only when the parsed input uses an allowed scheme and port, names an allowed resource, resolves to addresses permitted by policy, and connects to one of those exact addresses. Every redirect, retry, proxy route, and new pooled connection must satisfy the same rule. If any stage cannot provide that guarantee, reject the request or redesign the feature to accept a server-controlled resource identifier instead of an arbitrary URL.

Frequently Asked Questions

Can DNS TTL values make an SSRF allowlist safe by themselves?

No. A low or high TTL describes caching behavior, not whether an address is trustworthy. The fetcher still has to resolve at connection time, classify every answer, and use the validated address directly.

How should an API handle a hostname with both public and private DNS answers?

Treat the set of answers as the policy input, not just the address selected by the resolver. If any answer falls into a prohibited range and the feature does not explicitly support that network, fail closed rather than allowing nondeterministic selection.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I permit HTTP instead of HTTPS for an internal integration?

Only when that internal route is an explicit, narrowly scoped requirement with its own authorization and network controls. A general-purpose fetcher should normally require HTTPS, because permitting cleartext expands protocol and interception risks in addition to SSRF risk.

What information should a blocked-request log contain?

Record the normalized hostname, scheme, port, resolved addresses, policy category that caused rejection, redirect hop, and calling feature or identity. Exclude credentials, authorization headers, and sensitive upstream response content.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

API securityDNS rebindingNetwork SecuritySSRFURL Validation

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.