Ssrf Server Side with Api Keys
How SSRF Server-Side Manifests with API Keys
Server-Side Request Forgery (SSRF) is a critical vulnerability where an attacker abuses server functionality to access internal resources or external systems. When API keys are present—whether in headers, query parameters, or request bodies—SSRF attacks become significantly more dangerous. The API key often acts as a trusted credential, allowing the attacker to pivot from a simple SSRF into a full compromise of internal services, cloud metadata endpoints, or third-party APIs.
The most common manifestation occurs when an application accepts a user-supplied URL (e.g., for webhooks, import functions, or proxy-like features) and includes API keys in the outgoing request. An attacker can supply a URL pointing to an internal service (e.g., http://169.254.169.254/latest/meta-data/ on AWS) that returns sensitive data. Because the request carries a valid API key (e.g., for a payment gateway or internal microservice), the internal service may process it as an authenticated request, leaking credentials or data. For example:
POST /import-data HTTP/1.1
Host: vulnerable-api.com
Authorization: Bearer sk_live_abc123
Content-Type: application/json
{
"target_url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/admin-role"
}Here, the backend fetches target_url using the attacker-supplied URL, attaching the API key. The AWS metadata endpoint returns temporary IAM credentials, which the attacker can then use to access the AWS account. This pattern is documented in real incidents like the Capital One breach (CVE-2019-0053) where SSRF led to credential exposure.
API keys also amplify SSRF when they are used to access cloud provider APIs (e.g., AWS STS, Google Cloud IAM). An attacker who can trigger SSRF to http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token may obtain OAuth tokens that grant broader access than the original API key. Similarly, SSRF can be chained with BOLA/IDOR if the internal service uses the API key to access user-specific data, allowing horizontal privilege escalation.
Another subtle manifestation is via "SSRF through API key validation endpoints." Some APIs expose an endpoint like /validate-key?key= that internally calls a third-party service to check key validity. If the key parameter is used to construct a URL (e.g., https://validator.example.com/check?key=USER_KEY), an attacker can supply a URL as the key value, turning the validation endpoint into an SSRF proxy with the API's outbound network access.
Finally, in LLM/AI contexts, API keys for model providers (e.g., OpenAI, Anthropic) are high-value targets. An SSRF that reaches http://internal-llm-gateway:8080/v1/completions with the API key can cause the server to make unauthorized calls to the LLM provider, leading to cost exploitation (CWE-400) or data exfiltration via model outputs.
API Keys-Specific Detection
Detecting SSRF vulnerabilities that involve API keys requires testing both the SSRF vector and the impact of the leaked credential. Black-box scanners like middleBrick automate this by:
- Probing common metadata endpoints: Sending requests to
http://169.254.169.254/(AWS),http://metadata.google.internal/(GCP),http://169.254.169.254/metadata/instance?api-version=2021-02-01(Azure) and checking for responses that indicate successful access to cloud credentials. - Testing internal service access: Attempting to reach
http://localhost:8080/admin,http://internal-api:5000/health, or other common internal endpoints, observing whether responses differ when an API key is present versus absent. - Analyzing API key propagation: Identifying if user-supplied URLs are fetched by the server with the API key attached (e.g., via differences in error messages, timing, or status codes when the SSRF target is reachable vs. unreachable).
- Checking for API key leakage in SSRF responses: Scanning responses from SSRF targets for patterns matching API keys (e.g.,
sk_live_[a-zA-Z0-9]+,Bearer [a-zA-Z0-9_\-]+) or cloud credential JSON structures.
With middleBrick, you can scan an API endpoint in seconds:
middlebrick scan https://api.example.com/v1/importThe scan tests for SSRF by sending crafted payloads to parameters that accept URLs, then analyzes the response for signs of internal service access or credential leakage. The report includes a per-category SSRF score (0–100) and specific findings, such as: "SSRF via target_url parameter allows access to AWS metadata endpoint with API key propagation." The CLI output (JSON) can be integrated into CI/CD pipelines to fail builds if SSRF risk exceeds a threshold.
For LLM-specific API keys, middleBrick's unique LLM security checks include active prompt injection probes that attempt to make the LLM server issue an SSRF request to a controlled endpoint (e.g., http://attacker.com/log?key=), then verify if the API key appears in the logs. This detects "SSRF via LLM tool calls" where the model's function-calling feature is abused.
API Keys-Specific Remediation
Remediation focuses on preventing SSRF and limiting the blast radius of leaked API keys. Implement these controls at the application and infrastructure levels:
1. Validate and Sanitize User-Supplied URLs
Never trust user input for network requests. Use an allowlist of permitted domains and protocols. For example, in Node.js with the url module:
const allowedDomains = ['trusted-api.com', 'cdn.trusted.com'];
function safeUrl(userInput) {
const url = new URL(userInput);
if (!['http:', 'https:'].includes(url.protocol)) {
throw new Error('Invalid protocol');
}
if (!allowedDomains.includes(url.hostname)) {
throw new Error('Domain not allowed');
}
return url.toString();
}
// Use in route handler
app.post('/import', (req, res) => {
const targetUrl = safeUrl(req.body.target_url);
// Proceed with fetch...
});For Python (Django/Flask), use libraries like urllib.parse and hostname allowlisting. Also, disable HTTP redirects (allow_redirects=False) to prevent open redirect chains that could lead to SSRF.
2. Restrict API Key Scope and Network Access
Configure API keys (e.g., in AWS, GCP, Stripe) with the principle of least privilege:
- Restrict by HTTP referrer or IP: In cloud consoles, set API key restrictions to only accept requests from your server's IP range or specific domains. For example, Google Cloud API keys can be restricted to specific API services and HTTP referrers.
- Use short-lived tokens: Replace long-lived API keys with OAuth 2.0 access tokens that expire quickly (e.g., 1 hour). If SSRF leaks a token, its validity window is minimized.
- Separate keys for internal vs. external use: Use different API keys for server-side calls (stored in environment variables) versus client-side calls. The server-side key should never be exposed to user input.
3. Network-Level Isolation
Deploy your API in a VPC or private subnet with no direct internet access. Use NAT gateways for outbound traffic, but block access to metadata endpoints (169.254.169.254/32) via security groups or iptables. For example, in AWS, add a VPC endpoint policy that denies ec2:DescribeInstances from your API's role unless the source is a trusted IP.
4. Scan Regularly
Integrate middleBrick into your CI/CD pipeline to catch SSRF regressions:
# .github/workflows/api-security.yml
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: middlebrick/github-action@v1
with:
api-url: ${{ secrets.API_ENDPOINT }}
fail-below: 'B' # Fail if score drops below BPro and Enterprise tiers include continuous monitoring, alerting on new SSRF findings as your API evolves.
For LLM endpoints, disable unnecessary tool-calling features or sandbox them. Ensure the LLM server's API key is stored in a secret manager and never passed through user-controllable parameters. Apply input validation on all function-call arguments.
By combining strict input validation, API key scoping, and network segmentation, you can mitigate SSRF risks even when API keys are in use. Remember: the goal is to ensure that even if an SSRF occurs, the attacker cannot leverage API keys to escalate privileges.