ssrf-detection
БесплатноБез исполняемых скриптовНе проверенFinds server-side request forgery (SSRF) risk in code that fetches a user-supplied URL, and fixes it with a tested URL-validation guard (scheme allowlist, DNS…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
SSRF Detection
Overview
Server-side request forgery happens when a server fetches a URL that an attacker controls, and the server can reach destinations the attacker cannot reach directly: localhost, an internal admin API, a database port, or a cloud instance-metadata endpoint. Any feature that takes a URL and fetches it on the backend is a candidate: webhook registration, link unfurling, "import image from URL", PDF/document generation from a remote resource, RSS/feed readers, and server-side OAuth or SSO callbacks.
This skill is for finding and fixing that risk in your own application. It does not cover attacking systems you do not own; SSRF testing against infrastructure you do not control is unauthorized access in most jurisdictions.
Instructions
1. Find the vectors
Search the codebase for server-side HTTP calls built from request input:
grep -rnE "(axios|fetch|requests\.(get|post)|urllib|http\.client)\(.*req\.(query|body|params)" src/
grep -rniE "(url|uri|endpoint|webhook|callback|src|target).*=.*req\." src/
For each hit, check whether the destination is ever resolved and connected to without going through a validator like the one below. Pay special attention to:
- Redirect handling — an allowed URL can redirect to a blocked one; validate again at each hop, or disable redirects and handle the first one yourself.
- Any parser (image, PDF, XML, markdown) that can itself fetch a remote resource (e.g. an XML external entity, an SVG
<image>, a markdown image tag) — these are SSRF vectors even if your own code never callsfetch.
2. Validate before connecting, and connect to what you validated
The common bug is to validate a URL, then let the HTTP client re-resolve the hostname itself — the second lookup can return a different (private) address (DNS rebinding) because nothing pins it. The guard below resolves once, checks the result, and hands the caller the already-checked IP.
"""Defensive SSRF guard: validate a user-supplied URL, then connect to the IP that was checked."""
import ipaddress, socket, ssl, http.client
from urllib.parse import urlparse
class BlockedURL(ValueError):
pass
def is_blocked(ip) -> bool:
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped:
ip = ip.ipv4_mapped
return not ip.is_global or ip in ipaddress.ip_network("100.64.0.0/10")
def resolve_safe(hostname, port):
try:
infos = socket.getaddrinfo(hostname, port, proto=socket.IPPROTO_TCP)
except socket.gaierror as exc:
raise BlockedURL(f"cannot resolve {hostname}") from exc
for _, _, _, _, sockaddr in infos:
ip = ipaddress.ip_address(sockaddr[0])
if is_blocked(ip):
raise BlockedURL(f"{hostname} resolves to non-public address {ip}")
return infos[0][4][0]
def validate_url(url, allowed_schemes=("http", "https")):
parsed = urlparse(url)
if parsed.scheme not in allowed_schemes:
raise BlockedURL(f"blocked scheme {parsed.scheme!r}")
if not parsed.hostname:
raise BlockedURL("no hostname")
if parsed.username or parsed.password:
raise BlockedURL("credentials in URL are not allowed")
try:
port = parsed.port or (443 if parsed.scheme == "https" else 80)
except ValueError:
raise BlockedURL("invalid port")
return parsed.hostname, resolve_safe(parsed.hostname, port)
class PinnedHTTPConnection(http.client.HTTPConnection):
def __init__(self, host, safe_ip, **kw):
super().__init__(host, **kw)
self.safe_ip = safe_ip
def connect(self):
self.sock = socket.create_connection((self.safe_ip, self.port), self.timeout)
class PinnedHTTPSConnection(http.client.HTTPSConnection):
def __init__(self, host, safe_ip, **kw):
super().__init__(host, **kw)
self.safe_ip = safe_ip
def connect(self):
sock = socket.create_connection((self.safe_ip, self.port), self.timeout)
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
MAX_BYTES = 5 * 1024 * 1024
def fetch_preview(url):
hostname, safe_ip = validate_url(url)
parsed = urlparse(url)
cls = PinnedHTTPSConnection if parsed.scheme == "https" else PinnedHTTPConnection
conn = cls(hostname, safe_ip, port=parsed.port, timeout=5)
try:
conn.request("GET", (parsed.path or "/") + (f"?{parsed.query}" if parsed.query else ""))
resp = conn.getresponse()
if 300 <= resp.status < 400:
raise BlockedURL("redirects are not followed")
body = resp.read(MAX_BYTES + 1)
if len(body) > MAX_BYTES:
raise BlockedURL("response exceeds size limit")
return body
finally:
conn.close()
fetch_preview connects to safe_ip itself, so the hostname is never resolved a second time (TLS still verifies the certificate against hostname). It does not follow redirects: to support them, call validate_url on each Location and repeat, with a hop limit. `ip.i
Установить ssrf-detection в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл ssrf-detection?
Finds server-side request forgery (SSRF) risk in code that fetches a user-supplied URL, and fixes it with a tested URL-validation guard (scheme allowlist, DNS resolution against private/link-local ranges, connect-to-resolved-IP to close the DNS-rebinding gap). Use when reviewing a webhook, link-preview, image-import, PDF-generator or any feature that fetches an external URL server-side, or when hardening cloud metadata access (IMDSv2).
Как установить скилл ssrf-detection?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ssrf-detection запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic