From b030b9806222ecdc0df6fdc99d4c43fbb6dc41be Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 6 Mar 2026 19:42:56 -0500 Subject: [PATCH] attempt to fix vuln reported in PR --- backend/endpoints/collections.py | 18 ++ backend/endpoints/rom.py | 25 +++ backend/endpoints/saves.py | 37 +++- backend/endpoints/screenshots.py | 19 +- backend/endpoints/states.py | 37 +++- .../handler/filesystem/resources_handler.py | 36 ++++ backend/tests/utils/test_validation.py | 190 ++++++++++++++++++ backend/utils/validation.py | 99 +++++++++ 8 files changed, 446 insertions(+), 15 deletions(-) diff --git a/backend/endpoints/collections.py b/backend/endpoints/collections.py index 94a60cc3a..c698f9eb2 100644 --- a/backend/endpoints/collections.py +++ b/backend/endpoints/collections.py @@ -31,6 +31,7 @@ from models.collection import ( VirtualCollection, ) from utils.router import APIRouter +from utils.validation import ValidationError, validate_url_for_http_request router = APIRouter( prefix="/collections", @@ -68,6 +69,15 @@ async def add_collection( "is_favorite": is_favorite or False, "user_id": request.user.id, } + + # Validate URL if provided + if url_cover: + try: + validate_url_for_http_request(url_cover, "Cover URL") + except ValidationError as e: + log.error(f"Invalid cover URL in add_collection: {str(e)}") + raise ValueError(str(e)) + db_collection = db_collection_handler.get_collection_by_name( cleaned_data["name"], request.user.id ) @@ -438,6 +448,14 @@ async def update_collection( current_url_cover != collection.url_cover or not fs_resource_handler.cover_exists(collection, CoverSize.BIG) ): + # Validate URL if provided and changed + if current_url_cover: + try: + validate_url_for_http_request(current_url_cover, "Cover URL") + except ValidationError as e: + log.error(f"Invalid cover URL in update_collection: {str(e)}") + raise ValueError(str(e)) + path_cover_s, path_cover_l = await fs_resource_handler.get_cover( entity=collection, overwrite=True, diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index 28eda4e12..71f19e23e 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -73,6 +73,7 @@ from utils.filesystem import sanitize_filename from utils.hashing import crc32_to_hex from utils.nginx import FileRedirectResponse, ZipContentLine, ZipResponse from utils.router import APIRouter +from utils.validation import ValidationError, validate_url_for_http_request router = APIRouter( prefix="/roms", @@ -1290,6 +1291,14 @@ async def update_rom( cleaned_data.update({"igdb_id": None, "igdb_metadata": {}}) url_screenshots = cleaned_data.get("url_screenshots", []) + if url_screenshots: + for screenshot_url in url_screenshots: + try: + validate_url_for_http_request(str(screenshot_url), "Screenshot URL") + except ValidationError as e: + log.error(f"Invalid screenshot URL in update_rom: {str(e)}") + raise ValueError(str(e)) + screenshots_changed = pydash.xor(url_screenshots, rom.url_screenshots or []) if url_screenshots: path_screenshots = await fs_resource_handler.get_rom_screenshots( @@ -1345,6 +1354,14 @@ async def update_rom( url_cover = ( form_data.url_cover if "url_cover" in provided_fields else rom.url_cover ) + # Validate URL if provided and changed + if url_cover and url_cover != rom.url_cover: + try: + validate_url_for_http_request(url_cover, "Cover URL") + except ValidationError as e: + log.error(f"Invalid cover URL in update_rom: {str(e)}") + raise ValueError(str(e)) + path_cover_s, path_cover_l = await fs_resource_handler.get_cover( entity=rom, overwrite=url_cover != rom.url_cover, @@ -1361,6 +1378,14 @@ async def update_rom( url_manual = ( form_data.url_manual if "url_manual" in provided_fields else rom.url_manual ) + # Validate URL if provided and changed + if url_manual and url_manual != rom.url_manual: + try: + validate_url_for_http_request(url_manual, "Manual URL") + except ValidationError as e: + log.error(f"Invalid manual URL in update_rom: {str(e)}") + raise ValueError(str(e)) + path_manual = await fs_resource_handler.get_manual( rom=rom, overwrite=url_manual != rom.url_manual, diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index 959bffeac..06f4d4fad 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -27,6 +27,7 @@ from models.assets import Save from models.device import Device from models.device_save_sync import DeviceSaveSync from utils.datetime import to_utc +from utils.filesystem import sanitize_filename from utils.router import APIRouter @@ -257,20 +258,32 @@ async def add_save( log.warning(f"Could not delete old save file: {old_save.full_path}") if screenshotFile and screenshotFile.filename: + try: + sanitized_screenshot_filename = sanitize_filename(screenshotFile.filename) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Invalid screenshot filename: {str(exc)}", + ) from exc + screenshots_path = fs_asset_handler.build_screenshots_file_path( user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id ) - await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path) + await fs_asset_handler.write_file( + file=screenshotFile, + path=screenshots_path, + filename=sanitized_screenshot_filename, + ) scanned_screenshot = await scan_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id, ) db_screenshot = db_screenshot_handler.get_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, rom_id=rom.id, user_id=request.user.id, ) @@ -472,23 +485,35 @@ async def update_save( ) if screenshotFile and screenshotFile.filename: + try: + sanitized_screenshot_filename = sanitize_filename(screenshotFile.filename) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Invalid screenshot filename: {str(exc)}", + ) from exc + screenshots_path = fs_asset_handler.build_screenshots_file_path( user=request.user, platform_fs_slug=db_save.rom.platform_slug, rom_id=db_save.rom.id, ) - await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path) + await fs_asset_handler.write_file( + file=screenshotFile, + path=screenshots_path, + filename=sanitized_screenshot_filename, + ) # Scan or update screenshot scanned_screenshot = await scan_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, user=request.user, platform_fs_slug=db_save.rom.platform_slug, rom_id=db_save.rom.id, ) db_screenshot = db_screenshot_handler.get_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, rom_id=db_save.rom.id, user_id=request.user.id, ) diff --git a/backend/endpoints/screenshots.py b/backend/endpoints/screenshots.py index 22a65592b..6edbf3680 100644 --- a/backend/endpoints/screenshots.py +++ b/backend/endpoints/screenshots.py @@ -10,6 +10,7 @@ from handler.scan_handler import scan_screenshot from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log +from utils.filesystem import sanitize_filename from utils.router import APIRouter router = APIRouter( @@ -56,17 +57,29 @@ async def add_screenshot( status_code=status.HTTP_400_BAD_REQUEST, detail="Screenshot has no filename" ) - await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path) + try: + sanitized_screenshot_filename = sanitize_filename(screenshotFile.filename) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Invalid screenshot filename: {str(exc)}", + ) from exc + + await fs_asset_handler.write_file( + file=screenshotFile, + path=screenshots_path, + filename=sanitized_screenshot_filename, + ) # Scan or update screenshot scanned_screenshot = await scan_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id, ) db_screenshot = db_screenshot_handler.get_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, rom_id=rom.id, user_id=current_user.id, ) diff --git a/backend/endpoints/states.py b/backend/endpoints/states.py index 6798903b8..564627b5e 100644 --- a/backend/endpoints/states.py +++ b/backend/endpoints/states.py @@ -14,6 +14,7 @@ from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.assets import State +from utils.filesystem import sanitize_filename from utils.router import APIRouter router = APIRouter( @@ -102,21 +103,33 @@ async def add_state( db_state = db_state_handler.add_state(state=scanned_state) if screenshotFile and screenshotFile.filename: + try: + sanitized_screenshot_filename = sanitize_filename(screenshotFile.filename) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Invalid screenshot filename: {str(exc)}", + ) from exc + screenshots_path = fs_asset_handler.build_screenshots_file_path( user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id ) - await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path) + await fs_asset_handler.write_file( + file=screenshotFile, + path=screenshots_path, + filename=sanitized_screenshot_filename, + ) # Scan or update screenshot scanned_screenshot = await scan_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id, ) db_screenshot = db_screenshot_handler.get_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, rom_id=rom.id, user_id=request.user.id, ) @@ -210,23 +223,35 @@ async def update_state( db_state.id, {"file_size_bytes": stateFile.size} ) if screenshotFile and screenshotFile.filename: + try: + sanitized_screenshot_filename = sanitize_filename(screenshotFile.filename) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Invalid screenshot filename: {str(exc)}", + ) from exc + screenshots_path = fs_asset_handler.build_screenshots_file_path( user=request.user, platform_fs_slug=db_state.rom.platform_slug, rom_id=db_state.rom.id, ) - await fs_asset_handler.write_file(file=screenshotFile, path=screenshots_path) + await fs_asset_handler.write_file( + file=screenshotFile, + path=screenshots_path, + filename=sanitized_screenshot_filename, + ) # Scan or update screenshot scanned_screenshot = await scan_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, user=request.user, platform_fs_slug=db_state.rom.platform_slug, rom_id=db_state.rom.id, ) db_screenshot = db_screenshot_handler.get_screenshot( - file_name=screenshotFile.filename, + file_name=sanitized_screenshot_filename, rom_id=db_state.rom.id, user_id=request.user.id, ) diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index 3a8b016e3..e5d972e78 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -14,6 +14,7 @@ from models.collection import Collection from models.rom import Rom from tasks.scheduled.convert_images_to_webp import ImageConverter from utils.context import ctx_httpx_client +from utils.validation import ValidationError, validate_url_for_http_request from .base_handler import CoverSize, FSHandler @@ -92,6 +93,13 @@ class FSResourcesHandler(FSHandler): return None else: # Handle HTTP URLs + # Validate URL to prevent SSRF attacks + try: + validate_url_for_http_request(url_cover, "Cover URL") + except ValidationError as e: + log.error(f"URL validation failed for cover: {str(e)}") + return None + httpx_client = ctx_httpx_client.get() try: async with httpx_client.stream( @@ -256,6 +264,13 @@ class FSResourcesHandler(FSHandler): return None else: # Handle HTTP URLs + # Validate URL to prevent SSRF attacks + try: + validate_url_for_http_request(url_screenhot, "Screenshot URL") + except ValidationError as e: + log.error(f"URL validation failed for screenshot: {str(e)}") + return None + httpx_client = ctx_httpx_client.get() try: async with httpx_client.stream( @@ -367,6 +382,13 @@ class FSResourcesHandler(FSHandler): return None else: # Handle HTTP URL + # Validate URL to prevent SSRF attacks + try: + validate_url_for_http_request(url_manual, "Manual URL") + except ValidationError as e: + log.error(f"URL validation failed for manual: {str(e)}") + return None + httpx_client = ctx_httpx_client.get() try: async with httpx_client.stream( @@ -425,6 +447,13 @@ class FSResourcesHandler(FSHandler): # Retroachievements async def store_ra_badge(self, url: str, path: str) -> None: + # Validate URL to prevent SSRF attacks + try: + validate_url_for_http_request(url, "Badge URL") + except ValidationError as e: + log.error(f"URL validation failed for badge: {str(e)}") + return + httpx_client = ctx_httpx_client.get() directory, filename = os.path.split(path) @@ -488,6 +517,13 @@ class FSResourcesHandler(FSHandler): return None else: # Handle HTTP URLs + # Validate URL to prevent SSRF attacks + try: + validate_url_for_http_request(url, "Media URL") + except ValidationError as e: + log.error(f"URL validation failed for media file: {str(e)}") + return None + httpx_client = ctx_httpx_client.get() try: async with httpx_client.stream("GET", url, timeout=120) as response: diff --git a/backend/tests/utils/test_validation.py b/backend/tests/utils/test_validation.py index 73923cbd5..2e7a54802 100644 --- a/backend/tests/utils/test_validation.py +++ b/backend/tests/utils/test_validation.py @@ -7,6 +7,7 @@ from utils.validation import ( validate_ascii_only, validate_email, validate_password, + validate_url_for_http_request, validate_username, ) @@ -157,3 +158,192 @@ class TestValidateEmail: with pytest.raises(ValidationError) as exc_info: validate_email("résumé@example.com") assert "ASCII characters" in exc_info.value.message + + +class TestValidateUrlForHttpRequest: + """Test URL validation for HTTP requests to prevent SSRF attacks.""" + + def test_valid_http_urls(self): + """Test that valid HTTP/HTTPS URLs pass validation.""" + validate_url_for_http_request("http://example.com", "test_url") + validate_url_for_http_request("https://example.com", "test_url") + validate_url_for_http_request("http://example.com/path", "test_url") + validate_url_for_http_request("https://example.com/path?query=1", "test_url") + validate_url_for_http_request("http://subdomain.example.com", "test_url") + + def test_invalid_empty_url(self): + """Test that empty URLs fail validation.""" + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("", "test_url") + assert "cannot be empty" in exc_info.value.message + + def test_invalid_scheme(self): + """Test that non-HTTP/HTTPS schemes fail validation.""" + # FTP scheme + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("ftp://example.com", "test_url") + assert "only http and https schemes are allowed" in exc_info.value.message + + # File scheme + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("file:///etc/passwd", "test_url") + assert "only http and https schemes are allowed" in exc_info.value.message + + # Data scheme + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("data:text/html,

test

", "test_url") + assert "only http and https schemes are allowed" in exc_info.value.message + + # JavaScript scheme (XSS attack vector) + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("javascript:alert(1)", "test_url") + assert "only http and https schemes are allowed" in exc_info.value.message + + def test_invalid_localhost(self): + """Test that localhost and reserved hostnames fail validation.""" + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://localhost", "test_url") + assert ( + "localhost and reserved hostnames are not allowed" in exc_info.value.message + ) + + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://127.0.0.1", "test_url") + assert ( + "localhost and reserved hostnames are not allowed" in exc_info.value.message + ) + + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://[::1]", "test_url") + assert ( + "localhost and reserved hostnames are not allowed" in exc_info.value.message + ) + + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://0.0.0.0", "test_url") + assert ( + "localhost and reserved hostnames are not allowed" in exc_info.value.message + ) + + def test_invalid_private_ipv4_addresses(self): + """Test that private IPv4 addresses fail validation.""" + # 10.x.x.x range + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://10.0.0.1", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + # 192.168.x.x range + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://192.168.1.1", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + # 172.16.x.x - 172.31.x.x range + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://172.16.0.1", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://172.31.255.254", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + def test_invalid_cloud_metadata_service_ips(self): + """Test that cloud metadata service IPs fail validation.""" + # AWS/Azure metadata service: 169.254.169.254 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://169.254.169.254", "test_url") + assert ( + "cloud metadata service addresses are not allowed" in exc_info.value.message + ) + + # Link-local addresses (169.254.0.0/16) + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://169.254.1.1", "test_url") + assert ( + "cloud metadata service addresses are not allowed" in exc_info.value.message + ) + + def test_invalid_loopback_addresses(self): + """Test that loopback addresses fail validation.""" + # 127.x.x.x range + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://127.0.0.2", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://127.255.255.255", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + def test_invalid_private_ipv6_addresses(self): + """Test that private/link-local IPv6 addresses fail validation.""" + # Link-local IPv6: fe80::/10 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://[fe80::1]", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + # Unique local address: fc00::/7 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://[fc00::1]", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://[fd00::1]", "test_url") + assert ( + "private, internal, and reserved IP addresses are not allowed" + in exc_info.value.message + ) + + def test_invalid_multicast_addresses(self): + """Test that multicast addresses fail validation.""" + # IPv4 multicast: 224.0.0.0/4 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://224.0.0.1", "test_url") + assert "multicast addresses are not allowed" in exc_info.value.message + + # IPv6 multicast: ff00::/8 + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://[ff02::1]", "test_url") + assert "multicast addresses are not allowed" in exc_info.value.message + + def test_invalid_internal_tlds(self): + """Test that internal TLDs fail validation.""" + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://server.local", "test_url") + assert "internal domain names are not allowed" in exc_info.value.message + + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://server.internal", "test_url") + assert "internal domain names are not allowed" in exc_info.value.message + + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://server.localhost", "test_url") + assert "internal domain names are not allowed" in exc_info.value.message + + def test_invalid_missing_hostname(self): + """Test that URLs without hostnames fail validation.""" + with pytest.raises(ValidationError) as exc_info: + validate_url_for_http_request("http://", "test_url") + assert "missing hostname" in exc_info.value.message diff --git a/backend/utils/validation.py b/backend/utils/validation.py index 5e07a038b..e9c27a20a 100644 --- a/backend/utils/validation.py +++ b/backend/utils/validation.py @@ -1,4 +1,6 @@ +import ipaddress import re +from urllib.parse import urlparse from logger.logger import log from models.user import TEXT_FIELD_LENGTH @@ -115,3 +117,100 @@ def validate_email(email: str) -> None: msg = "Invalid email format" log.error(f"Validation failed: {msg} for email: {email}") raise ValidationError(msg, "Email") + + +def validate_url_for_http_request(url: str, field_name: str = "URL") -> None: + """Validate URL to prevent Server-Side Request Forgery (SSRF) attacks. + + This function validates that: + - The URL scheme is http or https only + - The host is not an internal/private IP address + - The host is not a reserved hostname (localhost, etc.) + - The host is not a cloud metadata service endpoint + + Args: + url (str): The URL to validate + field_name (str): The name of the field for error messages + + Raises: + ValidationError: If the URL is invalid or potentially dangerous + """ + if not url or not url.strip(): + msg = f"{field_name} cannot be empty" + log.error(msg) + raise ValidationError(msg, field_name) + + try: + parsed = urlparse(url) + except Exception as e: + msg = f"Invalid {field_name}: unable to parse URL" + log.error(f"{msg}: {str(e)}") + raise ValidationError(msg, field_name) + + # Validate scheme - only allow http and https + if parsed.scheme not in ["http", "https"]: + msg = f"Invalid {field_name}: only http and https schemes are allowed" + log.error(f"SSRF prevention: {msg} - got scheme '{parsed.scheme}'") + raise ValidationError(msg, field_name) + + # Extract hostname + hostname = parsed.hostname + if not hostname: + msg = f"Invalid {field_name}: missing hostname" + log.error(msg) + raise ValidationError(msg, field_name) + + # Check for localhost and reserved hostnames + reserved_hostnames = [ + "localhost", + "127.0.0.1", + "0.0.0.0", + "[::1]", + "::1", + "[::]", + "::", + ] + if hostname.lower() in reserved_hostnames: + msg = f"Invalid {field_name}: localhost and reserved hostnames are not allowed" + log.error(f"SSRF prevention: {msg} - hostname '{hostname}'") + raise ValidationError(msg, field_name) + + # Try to resolve hostname as IP address + try: + # Handle IPv6 addresses in brackets + ip_str = hostname.strip("[]") + ip = ipaddress.ip_address(ip_str) + + # Block private/internal IP addresses + if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved: + msg = f"Invalid {field_name}: private, internal, and reserved IP addresses are not allowed" + log.error(f"SSRF prevention: {msg} - IP '{ip}'") + raise ValidationError(msg, field_name) + + # Block multicast addresses + if ip.is_multicast: + msg = f"Invalid {field_name}: multicast addresses are not allowed" + log.error(f"SSRF prevention: {msg} - IP '{ip}'") + raise ValidationError(msg, field_name) + + # Block cloud metadata service IPs (AWS, GCP, Azure, etc.) + # AWS/Azure metadata service: 169.254.169.254 + # IPv6 link-local range: fe80::/10 (already covered by is_link_local) + if isinstance(ip, ipaddress.IPv4Address): + # Check for 169.254.0.0/16 (link-local) + if str(ip).startswith("169.254."): + msg = f"Invalid {field_name}: cloud metadata service addresses are not allowed" + log.error(f"SSRF prevention: {msg} - IP '{ip}'") + raise ValidationError(msg, field_name) + + except ValueError: + # Not a direct IP address, which is fine - it's a domain name + # Additional checks for suspicious domain patterns + hostname_lower = hostname.lower() + + # Block common internal TLDs + internal_tlds = [".local", ".internal", ".localhost"] + if any(hostname_lower.endswith(tld) for tld in internal_tlds): + msg = f"Invalid {field_name}: internal domain names are not allowed" + log.error(f"SSRF prevention: {msg} - hostname '{hostname}'") + raise ValidationError(msg, field_name)