GuardAPI Logo
GuardAPI

Fix SSRF (Server Side Request Forgery) in Pyramid

SSRF in Pyramid happens when you trust user-controlled input to fetch remote resources. An attacker can pivot from your app to scan internal metadata services (like 169.254.169.254), hit local databases, or bypass firewalls. To kill SSRF, you must enforce a strict allowlist of domains and validate that resolved IPs aren't pointing to your internal network.

The Vulnerable Pattern

from pyramid.view import view_config
import requests

@view_config(route_name=‘fetch_api’, renderer=‘json’) def fetch_api(request): # CRITICAL: User controls the full URL url = request.params.get(‘url’) response = requests.get(url, timeout=5) return {‘data’: response.text}

The Secure Implementation

The fix implements a defense-in-depth strategy. First, it enforces a strict scheme check (HTTP/S only) to prevent protocols like file:// or gopher://. Second, it uses an allowlist for netloc (domain). Third, it performs a DNS lookup and checks the resulting IP against private/reserved ranges to stop attackers from using 'localhost' or cloud metadata endpoints. Finally, it limits redirects to prevent an attacker from redirecting a 'safe' URL to an 'unsafe' internal one after the initial check.

from pyramid.view import view_config
from pyramid.httpexceptions import HTTPBadRequest
from urllib.parse import urlparse
import requests
import socket

ALLOWED_DOMAINS = [‘api.trusted-partner.com’]

def is_safe_url(url): try: parsed = urlparse(url) if parsed.scheme not in (‘http’, ‘https’): return False if parsed.netloc not in ALLOWED_DOMAINS: return False # Resolve DNS and block private IP ranges host_ip = socket.gethostbyname(parsed.hostname) private_ips = (‘127.’, ‘10.’, ‘172.16.’, ‘192.168.’, ‘169.254.’, ‘0.’) if any(host_ip.startswith(prefix) for prefix in private_ips): return False return True except Exception: return False

@view_config(route_name=‘fetch_api’, renderer=‘json’) def fetch_api(request): url = request.params.get(‘url’) if not url or not is_safe_url(url): return HTTPBadRequest(‘Invalid or forbidden URL’)

# Use a session with restricted redirects to prevent bypasses
with requests.Session() as session:
    session.max_redirects = 2
    response = session.get(url, timeout=5, allow_redirects=True)
    return {'data': response.text}</code></pre>
System Alert • ID: 4925
Target: Pyramid API
Potential Vulnerability

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

74% of Pyramid 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.