GuardAPI Logo
GuardAPI

Fix SSRF (Server Side Request Forgery) in Hug

SSRF (Server-Side Request Forgery) in the Hug framework occurs when a handler takes a user-controlled URL and fetches it without rigorous validation. This allows attackers to pivot from the public-facing API into internal infrastructure, hit cloud metadata endpoints (169.254.169.254), or bypass firewalls by making the server act as a proxy for malicious requests.

The Vulnerable Pattern

import hug
import requests

@hug.get(‘/fetch_resource’) def fetch_resource(target_url: hug.types.text): # CRITICAL VULNERABILITY: User-provided URL is requested directly. # An attacker can pass ‘http://localhost:8080/admin’ or ‘http://169.254.169.254/latest/meta-data/’. response = requests.get(target_url) return response.text

The Secure Implementation

The fix implements a defense-in-depth strategy. First, it uses 'urlparse' to decompose the input and strictly enforces 'http' or 'https' schemes, preventing 'file://' or 'gopher://' attacks. Second, it enforces a 'netloc' whitelist to ensure only trusted external domains are contacted. For high-security environments, you should also resolve the domain to an IP and check against RFC 1918 private IP ranges to prevent DNS Rebinding and access to the local network.

import hug
import requests
from urllib.parse import urlparse

ALLOWED_DOMAINS = [‘cdn.trusted-partner.com’, ‘api.internal-safe.com’]

@hug.get(‘/fetch_resource_secure’) def fetch_resource_secure(target_url: hug.types.text): parsed_url = urlparse(target_url)

# 1. Protocol Whitelisting
if parsed_url.scheme not in ['http', 'https']:
    return {'error': 'Invalid protocol'}

# 2. Domain Whitelisting
if parsed_url.netloc not in ALLOWED_DOMAINS:
    return {'error': 'Forbidden target domain'}

try:
    # 3. Use timeouts and disable redirects if possible to prevent bypasses
    response = requests.get(target_url, timeout=5, allow_redirects=False)
    return response.text
except requests.exceptions.RequestException:
    return {'error': 'Request failed'}</code></pre>
System Alert • ID: 4655
Target: Hug API
Potential Vulnerability

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

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