Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/channels/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import httpx

from app.channels.base import SendResult
from app.core.security import is_ssrf_safe_url


class WebhookAdapter:
Expand All @@ -30,6 +31,8 @@ async def send(
target = str(config.get("url", ""))
if not target:
return SendResult(ok=False, detail="missing url")
if not is_ssrf_safe_url(target, allow_http=True):
return SendResult(ok=False, detail="blocked: unsafe url")
payload = self.build_payload(config, user_id, message)
try:
if client is None:
Expand Down
37 changes: 30 additions & 7 deletions app/core/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import hashlib
import hmac
import secrets
import socket
from ipaddress import IPv4Address, IPv6Address, ip_address, ip_network
from urllib.parse import urlparse

Expand Down Expand Up @@ -48,23 +49,45 @@ def generate_registration_token() -> str:
def is_private_ip(host: str) -> bool:
"""True when *host* is an IP literal in a private/restricted range.

Plain hostnames (not IP literals) return ``False``; DNS-rebinding
protections are documented — outbound sends never follow redirects.
Hostnames (not IP literals) are resolved before checking; unresolvable
hosts fail closed (treated as unsafe).
"""
try:
addr: IPv4Address | IPv6Address = ip_address(host)
except ValueError:
return False
return _hostname_resolves_private(host)
return any(addr in net for net in _TRUSTED)


def _hostname_resolves_private(host: str) -> bool:
"""Resolve *host* via DNS and report whether any address is private."""
try:
infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
except (socket.gaierror, OSError):
return True # fail closed on unresolvable hosts
for info in infos:
sockaddr = info[4]
if isinstance(sockaddr, (tuple, list)):
ip_raw = sockaddr[0]
elif isinstance(sockaddr, (bytes, bytearray)):
ip_raw = bytes(sockaddr)
else:
ip_raw = sockaddr
try:
addr = ip_address(ip_raw)
except (ValueError, TypeError):
return True # fail closed on unparseable addresses
if is_private_ip(str(addr)):
return True
return False


def is_ssrf_safe_url(url: str, allow_http: bool = False) -> bool:
"""Validate an outbound webhook URL: scheme and host IP.
"""Validate an outbound webhook URL: scheme and resolved host address.

- scheme must be ``https`` (or ``http`` when *allow_http* is True)
- a host that is an IP literal must not be private/restricted
- hostname hosts are permitted; redirection is disabled in senders so a
user-supplied URL cannot be redirected into an internal address
- the host must not resolve to a private/restricted IP range
(IP literals and hostnames alike; unresolvable hosts fail closed)
"""
parsed = urlparse(url)
allowed_schemes = ("https",) if not allow_http else ("http", "https")
Expand Down
8 changes: 8 additions & 0 deletions tests/test_core_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ def test_ssrf_blocks_private_ip_literal_hosts() -> None:
assert is_ssrf_safe_url("https://0.0.0.0/hook") is False


def test_ssrf_blocks_localhost_hostname_and_fails_closed_on_unresolvable() -> None:
# Hostname that resolves to loopback must be blocked now that hostnames
# are resolved (e.g. 127.0.0.1.nip.io style bypasses are closed by DNS check).
assert is_ssrf_safe_url("https://localhost/hook") is False
assert is_ssrf_safe_url("http://localhost:9000/hook", allow_http=True) is False
assert is_ssrf_safe_url("https://this-host-does-not-resolve.invalid/hook") is False


def test_ssrf_allows_public_https_and_blocks_other_schemes() -> None:
assert is_ssrf_safe_url("https://hooks.slack.com/services/a/b/c") is True
assert is_ssrf_safe_url("https://8.8.8.8/hook") is True
Expand Down
Loading