""" SSRF protection utilities for webmention processing Per ADR-063 Decision 9 and background-worker.md: - Block private IP address ranges - Resolve hostname before making requests - DEV_MODE exception for localhost testing - Applied to all outgoing HTTP requests References: - ADR-063: Webmention Implementation - Background Worker Design: /docs/design/v1.6.0/background-worker.md """ import ipaddress import socket from flask import current_app class SSRFBlockedError(Exception): """Raised when SSRF protection blocks a request""" pass # Private IP ranges per RFC 1918 and link-local ranges BLOCKED_NETWORKS = [ ipaddress.ip_network('10.0.0.0/8'), # RFC 1918 private ipaddress.ip_network('172.16.0.0/12'), # RFC 1918 private ipaddress.ip_network('192.168.0.0/16'), # RFC 1918 private ipaddress.ip_network('127.0.0.0/8'), # Localhost ipaddress.ip_network('169.254.0.0/16'), # Link-local ipaddress.ip_network('::1/128'), # IPv6 localhost ipaddress.ip_network('fc00::/7'), # IPv6 unique local ipaddress.ip_network('fe80::/10'), # IPv6 link-local ] def is_private_ip(ip: str) -> bool: """ Check if IP address is in a private/blocked range. Args: ip: IP address string (IPv4 or IPv6) Returns: True if IP is private/blocked, False otherwise """ try: addr = ipaddress.ip_address(ip) return any(addr in network for network in BLOCKED_NETWORKS) except ValueError: # Invalid IP format, treat as blocked return True def safe_resolve(hostname: str) -> str: """ Resolve hostname and validate IP is not private. Per background-worker.md: DEV_MODE exception for localhost testing. Args: hostname: Hostname to resolve Returns: Resolved IP address if safe Raises: SSRFBlockedError: If hostname resolves to private IP socket.gaierror: If hostname cannot be resolved """ # DEV_MODE exception for localhost if current_app.config.get('DEV_MODE') and hostname in ('localhost', '127.0.0.1', '::1'): return '127.0.0.1' # Resolve hostname ip = socket.gethostbyname(hostname) # Check if resolved IP is private if is_private_ip(ip): raise SSRFBlockedError(f"Blocked request to private IP: {ip}") return ip def validate_url_for_fetch(url: str) -> None: """ Validate URL is safe to fetch (not private IP). Args: url: URL to validate Raises: SSRFBlockedError: If URL points to private IP ValueError: If URL is malformed """ from urllib.parse import urlparse parsed = urlparse(url) if not parsed.scheme in ('http', 'https'): raise ValueError(f"Unsupported URL scheme: {parsed.scheme}") if not parsed.netloc: raise ValueError("URL must include a hostname") # Extract hostname (remove port if present) hostname = parsed.hostname if not hostname: raise ValueError("Could not extract hostname from URL") # Validate hostname resolves to public IP safe_resolve(hostname)