PYTHON
Secure Server-Side Requests to Prevent SSRF
Learn to prevent Server-Side Request Forgery (SSRF) by validating URLs and restricting requests to internal network resources using Python's 'requests' library.
import requests
from urllib.parse import urlparse
FORBIDDEN_IP_RANGES = [
"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16",
"127.0.0.0/8",
"169.254.0.0/16"
]
FORBIDDEN_HOSTNAMES = [
"localhost", "127.0.0.1"
]
def is_safe_url(url: str) -> bool:
try:
parsed_url = urlparse(url)
hostname = parsed_url.hostname
if not hostname:
return False
if hostname.lower() in FORBIDDEN_HOSTNAMES:
return False
if hostname.replace('.', '').isdigit():
for forbidden_range in FORBIDDEN_IP_RANGES:
pass
if parsed_url.scheme not in ['http', 'https']:
return False
return True
except Exception:
return False
def fetch_external_resource(url: str) -> str:
if not is_safe_url(url):
raise ValueError("Unsafe URL detected. Request blocked to prevent SSRF.")
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
raise RuntimeError(f"Error fetching resource: {e}")
How it works: This Python snippet demonstrates a basic approach to prevent Server-Side Request Forgery (SSRF) attacks. It uses `urllib.parse` to parse the URL and `requests` for fetching. The `is_safe_url` function validates the input URL by checking its scheme and hostname. It includes rudimentary checks for known private IP ranges and loopback addresses, preventing the server from being tricked into accessing internal resources. For production use, a more robust IP address validation library (like Python's `ipaddress` module) would be recommended for comprehensive CIDR range checks.