GuardAPI Logo
GuardAPI

Fix SSRF (Server Side Request Forgery) in Flask

SSRF (Server-Side Request Forgery) is a critical vulnerability that allows an attacker to force the server to execute unintended requests. In Flask, this typically happens when user-controlled input is passed directly to HTTP libraries like 'requests'. This can lead to internal port scanning, access to cloud metadata services (like AWS IMDS), or pivoting into the internal network.

The Vulnerable Pattern

from flask import Flask, request
import requests

app = Flask(name)

@app.route(‘/fetch’) def fetch_url(): # DANGER: User controls the URL directly url = request.args.get(‘url’) resp = requests.get(url) return resp.text

The Secure Implementation

The vulnerable code blindly trusts the 'url' parameter, allowing attackers to request 'http://169.254.169.254/latest/meta-data/' or 'file:///etc/passwd'. The secure implementation mitigates this by: 1. Validating the URI scheme to prevent non-HTTP protocols. 2. Implementing a strict domain whitelist (netloc) to prevent internal network pivoting. 3. Disabling redirects to prevent 'Open Redirect' to SSRF bypasses. 4. Setting a timeout to prevent the server from hanging on malicious endpoints. For production, consider also resolving the IP and checking against a blacklist of private CIDR ranges to prevent DNS rebinding.

from flask import Flask, request, abort
from urllib.parse import urlparse
import requests

app = Flask(name)

ALLOWED_DOMAINS = [‘api.trusted.com’, ‘cdn.example.com’]

@app.route(‘/fetch’) def fetch_url(): url = request.args.get(‘url’) if not url: abort(400)

parsed = urlparse(url)

# 1. Enforce HTTPS only
if parsed.scheme != 'https':
    abort(400, description='Invalid protocol')

# 2. Strict Whitelisting of domains
if parsed.netloc not in ALLOWED_DOMAINS:
    abort(403, description='Domain not authorized')

try:
    # 3. Use timeouts to prevent DoS
    resp = requests.get(url, timeout=5, allow_redirects=False)
    return resp.text
except requests.exceptions.RequestException:
    abort(500)</code></pre>
System Alert • ID: 3108
Target: Flask API
Potential Vulnerability

Your Flask API might be exposed to SSRF (Server Side Request Forgery)

74% of Flask apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.