Return to Base
2025-12-07 Web Security, Theory, SSRF

Server-Side Request Forgery: The Theory & Mechanics (Part 1)

Server-Side Request Forgery: Understanding the Mechanics

Before we dive into the labs and exploitation scripts, we must understand the architectural flaws that make Server-Side Request Forgery (SSRF) possible. This vulnerability is not just about tricking a server into visiting a URL; it is about exploiting the implicit trust that internal networks place in the application server.


🔸 1. What is Server-Side Request Forgery (SSRF)?

Server-Side Request Forgery (SSRF) is a vulnerability that allows an attacker to induce the server-side application to make requests to an unintended location.

In a typical web request, the client (browser) sends data to the server. In an SSRF attack, the attacker modifies the data to force the server itself to create a new connection to a target of the attacker’s choosing.

Why do we need this functionality?

Applications often legitimately need to fetch data from external URLs. Common use cases include:

  1. Webhooks: Notifying external services of events.
  2. File Uploads from URL: Importing a profile picture from Instagram or a document from Dropbox.
  3. Link Previews: Fetching metadata (OpenGraph tags) to display a preview card for a shared link.
  4. Stock Checks: Querying a supplier’s API for inventory levels.

🧨 2. The Vulnerability: The Confused Deputy

The vulnerability arises when the application blindly trusts the destination URL provided by the user without proper validation.

The Core Assumption

Developers often operate under two dangerous assumptions:

  1. Implicit Trust: They assume users will only provide valid, harmless external URLs.
  2. Perimeter Security: They assume that even if the server makes a request, the internal network is safe because “it’s behind the firewall.”

The Reality: By forcing the server to make the request, the attacker bypasses the firewall. The request originates from the trusted internal IP of the web server, allowing access to systems that are blocked from the public internet.


🧠 3. The Million Dollar Question: How does it even work?

If I can’t access the internal admin panel from my browser, why can the server access it?

This relies on Network Architecture.

A. The “Wall” (Firewall/NAT)

  1. You (External Attacker): You are on the public internet. If you try to ping 192.168.0.1 (Internal Admin), the company firewall drops your packet. You have Zero Trust.

B. The “Deputy” (The Web Server)

  1. The Web Server: Sits inside the DMZ or the internal network. It has an interface on the public network (to talk to you) AND an interface on the private network (to talk to databases and internal services).
  2. The Privilege: Firewalls are often configured to allow Any-to-Any traffic within the internal network.

C. The Attack

You ask the Web Server: “Hey, can you fetch this URL for me?” The Web Server says: “Sure!” and connects to the Internal Admin panel. Because the request comes from the Web Server’s internal IP, the Admin panel says: “Welcome, trusted user.”


🧩 4. Root Causes: Why does it happen?

The vulnerability typically exists due to one of three failures:

A. Lack of Input Validation

The application accepts the user input (e.g., stockApi=...) and passes it directly to an HTTP client library (like curl, requests, or Guzzle) without checking if the domain is on a whitelist.

B. Flawed Parsing Logic

The application might try to validate the URL but fails to handle edge cases, such as:

  1. IP variations (e.g., using Octal or Hex representations of an IP).
  2. DNS rebinding.
  3. Redirects (The initial URL is valid, but it redirects to a malicious internal IP).

C. Cloud Misconfiguration

In cloud environments (AWS, GCP, Azure), servers have access to a Metadata Service (usually at 169.254.169.254). If an attacker can hit this IP via SSRF, they can steal temporary credentials and take over the cloud account.


📍 5. Where does it behave dangerously? (Attack Surface)

SSRF is dangerous when used in these specific contexts:

Component Dangerous Behavior Impact
Profile Import “Enter URL to upload image” Internal Port Scanning
PDF Generators Renders HTML/JS from a URL Local File Read (file://)
Webhooks Sends payload to user URL Blind SSRF / Intranet Mapping
Stock/API Checks Queries backend API via URL parameter Remote Code Execution (via Internal Admin)

Bug Bounty Tip: Look for parameters named url=, webhook=, api=, dest=, u=, or callback=.


🛠️ 6. Attack Mechanics: How we inject

We don’t just “type an IP.” We use specific techniques to evade detection and exploit the server.

1️⃣ Localhost Access

Accessing services running on the server itself (loopback interface).

stockApi=http://localhost/admin

stockApi=http://127.0.0.1/admin

Goal: Bypass IP-based authentication controls on admin panels.

2️⃣ Internal Network Scanning

Brute-forcing the last octet of the private IP range.

stockApi=http://192.168.0.X:8080/admin

Goal: Discover hidden internal services (databases, intranets) that are not exposed to the public.

3️⃣ Cloud Metadata Theft

Targeting the magic IP address used by cloud providers.

stockApi=http://169.254.169.254/latest/meta-data/

Goal: Retrieve IAM credentials or security tokens.

4️⃣ Filter Evasion (Obfuscation)

If 127.0.0.1 is blacklisted, we use alternative encodings.

  1. Short IP: http://127.1/
  2. Octal: http://0177.0.0.1/
  3. Double Encoding: http://127.1/%2561dmin (encodes ‘a’).

5️⃣ Protocol Smuggling

Changing the scheme to interact with the OS file system.

file:///etc/passwd

Goal: Read local files if the library supports it.


🛡️ 7. Remediation & Defense Strategies

Understanding the attack is only half the battle. Defense against SSRF requires a “Defense in Depth” approach.

1️⃣ Strict Whitelisting (The Golden Rule)

The most effective defense is to check the user-supplied URL against a strict list of permitted domains. Example: If your app only fetches images from Instagram, only allow *.instagram.com. Reject everything else.

2️⃣ Network Segmentation

Ensure the web server cannot talk to sensitive internal systems (like the metadata service or internal admin panels) at the network layer. Use firewall rules (iptables/Security Groups) to drop outbound traffic to 169.254.169.254 and 127.0.0.1 (except for necessary services).

3️⃣ Disable Redirects

HTTP client libraries often follow redirects by default. Attackers exploit this by providing a valid URL that redirects to a malicious internal IP. Secure Practice: explicitly disable HTTP redirection in your code (e.g., allow_redirects=False).

4️⃣ Use a Specialized Proxy

Route all user-initiated outbound requests through a dedicated DMZ proxy that has strict ACLs and no access to the internal network.


❓ 8. Interview Corner: Common FAQs (Pentest & AppSec)

If you are preparing for a role as a Penetration Tester or Cloud Security Engineer, expect to be grilled on SSRF.

Q1: What is the primary difference between SSRF and CSRF?

Answer:

  1. CSRF (Client-Side): The attacker tricks the victim’s browser into making a request to a vulnerable server. The request executes with the victim’s session/cookies.
  2. SSRF (Server-Side): The attacker tricks the server into making a request to another resource (internal or external). The request executes with the server’s machine privileges.

Q2: What is “Blind” SSRF and how do you detect it?

Answer: In Blind SSRF, the application makes the backend request but does not return the response to the frontend. Detection: You must use an out-of-band (OAST) technique like Burp Collaborator. You inject your collaborator URL and monitor for DNS queries or HTTP hits coming from the target server’s IP.

Q3: Why is 169.254.169.254 a critical target in SSRF?

Answer: This is the Instance Metadata Service (IMDS) IP address for AWS, Azure, and GCP. It requires no authentication. If an attacker can access it via SSRF, they can retrieve the temporary IAM credentials (Access Key and Secret Key) assigned to that server, potentially taking over the entire cloud infrastructure.

Q4: How would you bypass a blacklist filter blocking 127.0.0.1?

Answer: I would try alternative IP representations:

  1. Short IP: 127.1
  2. Octal Encoding: 0177.0.0.1
  3. Decimal Encoding: 2130706433
  4. DNS Pinning/Rebinding: Using a domain I control that resolves to 127.0.0.1.

Q5: Can SSRF lead to Remote Code Execution (RCE)?

Answer: Yes, indirectly.

  1. Accessing an internal admin panel (e.g., Jenkins, Apache Tomcat) that allows script execution without auth.
  2. Using the gopher:// protocol to smuggle commands to internal services like Redis or Memcached.

Q6: What is the “Open Redirect” bypass in SSRF?

Answer: If the SSRF protection uses a whitelist (e.g., “only allow requests to mysite.com”), but mysite.com has an Open Redirect vulnerability, the attacker can chain them. Payload: http://mysite.com/redirect?url=http://192.168.0.1 The validator sees mysite.com (Good), but the HTTP client follows the redirect to the internal IP (Bad).

Q7: How does DNS Rebinding help in SSRF exploitation?

Answer: It bypasses “Time of Check, Time of Use” (TOCTOU) checks.

  1. Check: The server resolves attacker.com -> 1.2.3.4 (Public IP). It passes the filter.
  2. Use: The server makes the actual request. The attacker’s DNS server changes the record to 127.0.0.1 with a very short TTL.
  3. Result: The connection goes to localhost, bypassing the initial check.

🧠 Advanced Interview Questions

Q8: You found a Blind SSRF. How do you exploit it to hack the internal network if you can’t see the responses?

Answer: I would focus on Time-Based analysis or Error-Based analysis.

  1. Time: Scanning internal ports. If a port is OPEN, the connection might be quick. If CLOSED/FILTERED, it might hang or timeout.
  2. Shellshock/Log4j: Attempt to inject RCE payloads into the blind request (e.g., in User-Agent headers) hoping an internal vulnerable system parses them.

Q9: What is the risk of having a PDF generator that accepts URLs?

Answer: PDF generators often use headless browsers or libraries like wkhtmltopdf. These are susceptible to:

  1. SSRF: Fetching internal content to render in the PDF.
  2. LFI: Using file:///etc/passwd to render local file contents onto the PDF.
  3. XSS: Executing JavaScript that reads internal DOM data.

Q10: How does gopher:// protocol change the severity of an SSRF?

Answer: gopher:// allows the attacker to construct arbitrary TCP streams, including newlines and null bytes. This allows interacting with non-HTTP services like Redis, SMTP, or FastCGI. You can use Gopher to send a multi-line Redis command to overwrite authorized keys (like authorized_keys) to gain RCE.

Q11: Explain the difference between IMDSv1 and IMDSv2 in AWS regarding SSRF.

Answer:

  1. IMDSv1: Simple Request/Response. Vulnerable to simple SSRF.
  2. IMDSv2: Requires a session token. The attacker must first send a PUT request to get a token, then use that token in the GET request. Impact: Simple SSRF usually only allows GET. Since v2 requires a PUT request with specific headers, it effectively neutralizes most standard SSRF attacks.

Q12: Why is “Input Validation” (Blacklisting) considered a weak fix for SSRF?

Answer: Because there are infinite ways to represent an IP address or domain. Maintaining a blacklist of “bad” chars and IPs is a cat-and-mouse game. Attackers will always find a bypass (e.g., ipv6 [::], Enclosed Alphanumerics, Redirects). Whitelisting is the only robust solution.

Q13: You have SSRF on a server, but it doesn’t return the response body. It does, however, show the HTTP Status Code (200, 404, 500). Is this useful?

Answer: Yes, this is Semi-Blind SSRF. I can use the status codes to map the internal network.

  1. 200 OK: A service exists and I hit a valid endpoint.
  2. 401/403: A service exists but is protected.
  3. Connection Refused: No service on this port. This allows me to fingerprint internal tech stacks (e.g., finding a Tomcat manager on port 8080).

Q14: How can an attacker use SSRF to pivot into the internal network?

Answer: The SSRF vulnerability effectively turns the web server into a proxy. If I can find an internal application susceptible to RCE (via the SSRF), I can compromise that internal box. From there, I have a shell inside the network and can launch further attacks (Lateral Movement) against the database or Active Directory.


🎭 9. Scenario-Based Questions

🎭 Scenario 1: The “Unfixable” Feature

Interviewer: “We have a ‘Webpage Screenshot’ tool that users use to capture any website. We must allow users to access any public URL. Whitelisting is impossible. How do we secure this?”

Gold Standard Answer: “If you must allow arbitrary public URLs, you need Network Isolation and DNS Validation.

  1. DNS Resolution: Before making the request, resolve the domain to an IP. Check if that IP falls into private ranges (RFC 1918) or 127.0.0.1. If it does, block it.
  2. Disable Redirects: Ensure the client does not follow redirects to bypass the check.
  3. Sandboxing: Ideally, run the screenshot worker in an isolated container or Lambda function with no network route to your internal VPC/Intranet.”

🎭 Scenario 2: The “Harmless” Image Fetch

Context: You find a profile picture upload feature: https://site.com/upload?url=.... You try 127.0.0.1 and get a generic “Image upload failed” error.

The Question: Is this safe? How would you dig deeper?

The “Hired” Answer: “It is not necessarily safe; it might just be Blind.

  1. Timing Attack: I would request url=http://127.0.0.1:80 vs url=http://127.0.0.1:12345 (random closed port). If the error message takes significantly longer to appear for one, I can deduce open ports.
  2. DNS Interaction: I would input a Burp Collaborator payload. If I see a DNS query, I know the server is attempting the connection.
  3. Impact: Even without seeing the image, I can use this to map the internal network via timing discrepancies.”

🎭 Scenario 3: The Cloud Breach

Context: You are auditing a financial app on AWS. You find an SSRF that returns the content of http://169.254.169.254/latest/meta-data/iam/security-credentials/admin-role.

The Question: What is your immediate next step, and how do you calculate the severity?

The “Hired” Answer: “Severity: Critical (P0). Immediate Action:

  1. Copy the AccessKeyId, SecretAccessKey, and Token.
  2. Configure the AWS CLI with these credentials.
  3. Run aws sts get-caller-identity to confirm the role.
  4. Do not perform destructive actions. Instead, check permissions (e.g., S3 access, EC2 control).
  5. Report immediately. This allows full takeover of the cloud resources assigned to that role.”

🎭 Scenario 4: The Webhook Integration

Context: A developer argues: “It’s a webhook. The whole point is to send data to the user’s URL. We can’t validate it.”

The Question: How can a webhook be abused if the server is only sending data (POST), not reading it?

The “Hired” Answer: “Webhooks can still be weaponized for Internal Port Scanning and Blind SSRF. If I set the webhook URL to http://internal-service:8080/admin/deleteUser, your server will send a POST request to that internal endpoint. If the internal service accepts POST requests without CSRF tokens (common in internal APIs), your webhook just deleted a user or shut down a service. Fix: The webhook worker should be on a segmented network with no inbound access to the internal production network.”


🎭 Scenario 5: The “PDF Report”

Context: An app generates invoices. It takes an HTML snippet from the user and converts it to PDF. User Input: <img src="http://169.254.169.254/..."> The PDF comes back blank.

The Question: The attack failed. Why? What would you try next?

The “Hired” Answer: “It failed likely because the PDF renderer timed out or the image was broken. I would try Side-Channel Data Exfiltration:

  1. Javascript: <script>x=new XMLHttpRequest;x.open("GET","http://169.254.169.254/...");x.send();...</script> - Attempt to read the data via JS and write it to the document body.
  2. Iframe: <iframe src="http://169.254.169.254/..." width="500" height="500"></iframe> - See if the metadata renders inside the frame in the final PDF.
  3. Local Files: Try <iframe src="file:///etc/passwd"> to see if I can read local server files instead of network requests.”

🛑 Summary of Part 1

  1. Concept: SSRF tricks the server into making requests on behalf of the attacker.
  2. Flaw: Implicit trust in user URLs and flat network architectures.
  3. Attack: We target localhost (Admin bypass), Internal Networks (Discovery), and Cloud Metadata (Credentials). ```

END OF LOG