Ssrf Server Side with Bearer Tokens
How SSRF Manifests in Bearer Token Authentication
Server-Side Request Forgery (SSRF) attacks exploit the ability of a server to make requests to internal resources on behalf of a user. When Bearer tokens are involved, SSRF vulnerabilities create particularly dangerous attack vectors because they can expose sensitive internal services and allow attackers to abuse the server's trusted position.
The most common Bearer token SSRF scenario occurs when an API endpoint accepts a URL parameter and makes an internal request using the server's credentials. Consider this vulnerable pattern:
app.post('/proxy', async (req, res) => {
const targetUrl = req.body.url;
const response = await fetch(targetUrl, {
headers: {
Authorization: req.headers.authorization // Server uses its own token
}
});
res.json(await response.json());
});An attacker can craft requests to internal services like http://internal-api/metadata or http://localhost:8080/admin, causing the server to make requests using its own Bearer token. This is especially dangerous when the server has elevated privileges or access to internal services that the client shouldn't reach.
Cloud metadata services are frequent SSRF targets. Many cloud providers expose metadata APIs at predictable internal URLs:
# AWS metadata service
http://169.254.169.254/latest/meta-data/
# Azure instance metadata
http://169.254.169.254/metadata/instance?api-version=2021-02-01
# Google Cloud metadata
http://metadata.google.internal/computeMetadata/v1/Attackers can use these endpoints to extract cloud credentials, SSH keys, or configuration data that the server's Bearer token can access. A successful SSRF attack might reveal AWS IAM role credentials that can be used to access other cloud resources.
Another Bearer token-specific SSRF pattern involves OAuth2 token introspection endpoints. Many OAuth2 implementations provide introspection endpoints at internal URLs like /introspect that validate Bearer tokens. An SSRF vulnerability could allow an attacker to bypass token validation entirely by directly querying the introspection service.
SSRF attacks can also target internal microservices that use service-to-service authentication with long-lived Bearer tokens. If a compromised API can make requests to internal services like http://payment-service:8080/transactions, it might trigger unauthorized financial operations using the server's trusted credentials.
Bearer Token-Specific Detection Methods
Detecting SSRF vulnerabilities in Bearer token implementations requires both static analysis and dynamic testing. Here are specific detection approaches:
Static Code Analysis should look for patterns where user input is used to construct URLs for server-side requests. Search for these red flags in your Bearer token authentication code:
# Look for dangerous patterns
fetch(url, { headers: { Authorization: token } })
axios.get(userProvidedUrl, { headers: { Authorization: req.headers.authorization } })
http.get(req.body.url, { headers: { 'Authorization': process.env.SERVER_TOKEN } })Tools like ESLint with security plugins can flag these patterns automatically. Pay special attention to any code that uses process.env variables for Bearer tokens in combination with user-controlled URLs.
Dynamic Testing involves actively probing your API with SSRF test payloads. Use tools like Burp Suite or custom scripts to test:
# Test for SSRF vulnerabilities
curl -X POST http://api.example.com/proxy \
-H 'Authorization: Bearer valid-token' \
-H 'Content-Type: application/json' \
-d '{"url": "http://169.254.169.254/latest/meta-data/"}'Look for responses that contain internal IP addresses, timing differences, or error messages that reveal internal infrastructure. A truly vulnerable endpoint might return AWS metadata or expose internal service details.
middleBrick Scanning provides automated SSRF detection for Bearer token APIs without requiring credentials. The scanner tests 12 security categories including SSRF by attempting to access internal resources and cloud metadata services. It analyzes your API's behavior when presented with various URL inputs and identifies if the server makes unauthorized internal requests.
middleBrick's approach is particularly effective because it simulates real attack scenarios without needing access to your internal network. It tests common SSRF targets like:
- Cloud metadata services (AWS, Azure, GCP)
- Localhost and RFC 1918 private IP ranges
- Common internal ports (8080, 3306, 5432, 6379)
- Common admin interfaces and management endpoints
The scanner provides specific findings about which endpoints are vulnerable and what internal resources were successfully accessed, along with severity ratings and remediation guidance.
Bearer Token-Specific Remediation Techniques
Fixing SSRF vulnerabilities in Bearer token implementations requires a defense-in-depth approach. Here are specific remediation techniques:
Input Validation and URL Sanitization is the first line of defense. Implement strict validation of any URL parameters:
function validateUrl(url) {
try {
const parsed = new URL(url);
// Block private IP ranges and localhost
const privateRanges = [
/^127\./,
/^10\./,
/^172\.(1[6-9]|2[0-9]|3[0-1])\./,
/^192\.168\./,
/^169\.254\./,
/^0\.0\.0\.0/,
/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ // Reject bare IPs
];
if (privateRanges.some(regex => regex.test(parsed.hostname))) {
throw new Error('Private IP address not allowed');
}
// Only allow specific protocols
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error('Only HTTP/HTTPS allowed');
}
// Whitelist allowed domains if applicable
const allowedDomains = ['api.example.com', 'cdn.example.net'];
if (allowedDomains.length > 0 && !allowedDomains.includes(parsed.hostname)) {
throw new Error('Domain not allowed');
}
return parsed;
} catch (err) {
throw new Error(`Invalid URL: ${err.message}`);
}
}
// Usage in your API
app.post('/proxy', async (req, res) => {
try {
const targetUrl = validateUrl(req.body.url);
const response = await fetch(targetUrl.href, {
headers: {
Authorization: req.headers.authorization
}
});
res.json(await response.json());
} catch (err) {
res.status(400).json({ error: err.message });
}
});Network-Level Controls provide an additional security layer. Configure your firewall or cloud security groups to block outbound requests to internal networks and cloud metadata services:
# AWS Security Group example
# Block outbound to metadata service
aws ec2 revoke-security-group-egress \
--group-id sg-xxxxxxx \
--ip-permissions IPRange={
CidrIp=169.254.169.254/32,
FromPort=80,
ToPort=80,
IpProtocol=tcp
}Service Mesh and Proxy Controls can enforce request policies at the network layer. If using Istio or similar:
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: strict-transport
spec:
mtls:
mode: STRICT
---
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: outbound-traffic-policy
spec:
hosts:
- "*"
http:
- match:
- uri:
prefix: "/"
route:
- destination:
host: authorized-services
- match:
- uri:
prefix: "/"
directResponse:
status: 403Least Privilege for Bearer Tokens limits the blast radius if SSRF is exploited. Use short-lived tokens with minimal scopes:
// Instead of using the same token for all requests
const scopedToken = jwt.sign({
sub: userId,
scope: ['read:profile', 'write:posts'],
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 300 // 5-minute expiry
}, process.env.JWT_SECRET);Runtime Monitoring helps detect SSRF attempts in production. Log and alert on suspicious URL patterns:
const suspiciousPatterns = [
/169\.254\./,
/\.internal\//,
/localhost/,
/metadata/,
/admin/,
/_debug/,
/_internal/
];
function logSuspiciousRequest(url, userId) {
if (suspiciousPatterns.some(pattern => pattern.test(url))) {
console.warn(`Suspicious URL detected: ${url} by user ${userId}`);
// Send to monitoring service
monitoring.alert({
type: 'SSRF_ATTEMPT',
url,
userId,
timestamp: new Date().toISOString()
});
}
}Implementing these remediation techniques significantly reduces the risk of SSRF attacks in Bearer token implementations. Remember that SSRF is a complex vulnerability that often requires multiple layers of defense to mitigate effectively.