64 lines
2.4 KiB
Python
64 lines
2.4 KiB
Python
"""Public-only egress checks for plugin proxy & outbound event webhook requests.
|
|
|
|
Mirrors ``sidecar/egress.py`` inside the backend container so non-owner plugins
|
|
can never hit loopback (127.0.0.1 / ::1), Docker internal networks, RFC1918 LAN
|
|
addresses, Tailscale (100.64.0.0/10), or link-local metadata endpoints.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import socket
|
|
from urllib.parse import urlsplit
|
|
|
|
_NAT64 = ipaddress.ip_network("64:ff9b::/96")
|
|
_CGNAT = ipaddress.ip_network("100.64.0.0/10") # Tailscale lives here
|
|
|
|
|
|
def is_public_ip(ip: str) -> bool:
|
|
"""True only when ``ip`` is globally routable on the public internet."""
|
|
try:
|
|
a = ipaddress.ip_address(ip.split("%")[0])
|
|
except ValueError:
|
|
return False
|
|
if a.version == 6:
|
|
if a.ipv4_mapped:
|
|
a = a.ipv4_mapped
|
|
elif a in _NAT64:
|
|
a = ipaddress.ip_address(int(a) & 0xFFFFFFFF)
|
|
if not a.is_global or a.is_multicast or a.is_unspecified or a.is_loopback or a.is_private:
|
|
return False
|
|
if a.version == 4 and a in _CGNAT:
|
|
return False
|
|
return True
|
|
|
|
|
|
def check_public_url(url: str) -> tuple[bool, str]:
|
|
"""Validate that ``url`` is plain http(s) and every resolved IP is public."""
|
|
if "\\" in url or "@" in url.split("://", 1)[-1].split("/", 1)[0]:
|
|
return False, "URL syntax not allowed"
|
|
try:
|
|
parts = urlsplit(url)
|
|
port = parts.port or (443 if parts.scheme == "https" else 80)
|
|
except ValueError:
|
|
return False, "invalid URL"
|
|
if parts.scheme not in ("http", "https") or not parts.hostname:
|
|
return False, "URL must be http(s) with a host"
|
|
host = parts.hostname.rstrip(".").lower()
|
|
if host in ("localhost",) or host.endswith((".local", ".internal", ".lab", ".lan")):
|
|
return False, f"internal host '{host}' refused"
|
|
# Direct IP literal check before DNS
|
|
try:
|
|
ipaddress.ip_address(host)
|
|
return (True, "") if is_public_ip(host) else (False, f"non-public IP '{host}' refused")
|
|
except ValueError:
|
|
pass
|
|
try:
|
|
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
|
except (OSError, UnicodeError):
|
|
return False, f"could not resolve host '{host}'"
|
|
addrs = [i[4][0] for i in infos]
|
|
if not addrs or not all(is_public_ip(a) for a in addrs):
|
|
return False, f"host '{host}' resolves to a non-public address"
|
|
return True, ""
|