Fix SSRF (Server Side Request Forgery) in TurboGears
SSRF in TurboGears occurs when a controller takes a user-supplied URL and uses the server's identity to fetch resources. This allows attackers to scan internal ports, hit metadata endpoints (like 169.254.169.254), or bypass firewalls. If your @expose() methods are using 'requests' or 'urllib' on raw input, you are vulnerable.
The Vulnerable Pattern
import requests from tg import expose, BaseController
class RootController(BaseController): @expose() def proxy_fetch(self, target_url): # VULNERABLE: Direct sink of user input into requests.get # Attacker can pass ‘http://localhost:8080/admin’ or ‘file:///etc/passwd’ response = requests.get(target_url) return response.text
The Secure Implementation
The secure implementation applies three critical layers of defense. First, it uses urlparse to validate the scheme, killing protocol smuggling (e.g., gopher://, file://). Second, it implements a strict domain allowlist to ensure the server only talks to known-good peers. Third, it disables 'allow_redirects' to prevent an attacker from bypassing the domain check by redirecting a trusted URL to an internal one (e.g., 127.0.0.1). Finally, a short timeout is enforced to mitigate resource exhaustion attacks.
import requests
from tg import expose, abort, BaseController
from urllib.parse import urlparse
ALLOWED_DOMAINS = [‘api.trusted-service.com’]
class RootController(BaseController):
@expose()
def proxy_fetch(self, target_url):
try:
parsed = urlparse(target_url)
# 1. Enforce Scheme
if parsed.scheme not in [‘http’, ‘https’]:
abort(400, ‘Invalid protocol’)
# 2. Domain Allowlisting
if parsed.netloc not in ALLOWED_DOMAINS:
abort(403, 'Unauthorized target domain')
# 3. Prevent Redirect Smuggling and set Timeouts
response = requests.get(
target_url,
allow_redirects=False,
timeout=3.0
)
return response.text
except Exception:
abort(500, 'Request failed')</code></pre>
Your TurboGears API
might be exposed to SSRF (Server Side Request Forgery)
74% of TurboGears apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
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.