124 lines
4.7 KiB
Python
124 lines
4.7 KiB
Python
"""
|
|
hyperstitionstud_io.security — Centralized Architectural Security Boundaries:
|
|
1. `safe_urlopen()` (`CWE-918` / Bandit `B310` SSRF-safe scheme allowlist, `TLSv1.2+`, & bounded `max_bytes` reads),
|
|
2. `safe_tar_members()` (`PEP 706` `tarfile.data_filter` semantics & per-member byte quota).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ssl
|
|
import tarfile
|
|
import urllib.parse
|
|
import urllib.request
|
|
from typing import Any
|
|
|
|
DEFAULT_MAX_NETWORK_BYTES = 15 * 1024 * 1024 # 15 MB
|
|
DEFAULT_MAX_TAR_MEMBER_BYTES = 24 * 1024 * 1024 # 24 MB
|
|
|
|
|
|
class SecurityBoundaryError(ValueError):
|
|
"""Raised when an untrusted URL scheme, host, or tar member violates security boundaries."""
|
|
|
|
|
|
class _BoundedResponseWrapper:
|
|
def __init__(self, resp: Any, max_bytes: int) -> None:
|
|
self._resp = resp
|
|
self._max_bytes = int(max_bytes)
|
|
self.status = getattr(resp, "status", 200)
|
|
|
|
def read(self, amt: int | None = None) -> bytes:
|
|
limit = self._max_bytes if amt is None else min(int(amt), self._max_bytes)
|
|
data = self._resp.read(limit + 1)
|
|
if len(data) > self._max_bytes:
|
|
raise SecurityBoundaryError(
|
|
f"Response payload exceeded max_bytes quota ({self._max_bytes} bytes)"
|
|
)
|
|
return data
|
|
|
|
def __enter__(self) -> _BoundedResponseWrapper:
|
|
return self
|
|
|
|
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
try:
|
|
self._resp.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def validate_safe_url(url: str, *, allow_http_localhost: bool = False) -> str:
|
|
"""
|
|
Validate `url` against SSRF / scheme injection (`CWE-918` / Bandit `B310`):
|
|
- Allows `https://` to non-metadata hosts (`169.254.169.254` blocked).
|
|
- Allows `http://` strictly to `127.0.0.1` or `localhost` when `allow_http_localhost=True`.
|
|
- Rejects `file://`, `ftp://`, `gopher://`, `data:`, and all other schemes.
|
|
"""
|
|
parsed = urllib.parse.urlsplit(str(url).strip())
|
|
scheme = (parsed.scheme or "").lower()
|
|
host = (parsed.hostname or "").lower()
|
|
|
|
if not scheme or not host:
|
|
raise SecurityBoundaryError(f"Blocked URL with missing scheme or host: {url!r}")
|
|
if host in ("169.254.169.254", "metadata.google.internal"):
|
|
raise SecurityBoundaryError(f"Blocked cloud metadata SSRF target host: {host!r}")
|
|
if scheme == "https":
|
|
return str(url)
|
|
if scheme == "http" and allow_http_localhost and host in ("127.0.0.1", "localhost", "::1"):
|
|
return str(url)
|
|
raise SecurityBoundaryError(
|
|
f"Blocked disallowed URL scheme/host ({scheme}://{host}) in {url!r}"
|
|
)
|
|
|
|
|
|
def safe_urlopen(
|
|
req_or_url: str | urllib.request.Request,
|
|
*,
|
|
timeout: float = 15.0,
|
|
max_bytes: int = DEFAULT_MAX_NETWORK_BYTES,
|
|
allow_http_localhost: bool = False,
|
|
) -> _BoundedResponseWrapper:
|
|
"""
|
|
Open an HTTP/HTTPS request after enforcing `validate_safe_url()`, `TLSv1.2+` verification,
|
|
and a hard `max_bytes` response read cap.
|
|
"""
|
|
raw_url = req_or_url.full_url if isinstance(req_or_url, urllib.request.Request) else str(req_or_url)
|
|
validate_safe_url(raw_url, allow_http_localhost=allow_http_localhost)
|
|
scheme = urllib.parse.urlsplit(raw_url).scheme.lower()
|
|
ctx = None
|
|
if scheme == "https":
|
|
ctx = ssl.create_default_context()
|
|
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
resp = urllib.request.urlopen(req_or_url, timeout=timeout, context=ctx) # nosec B310
|
|
return _BoundedResponseWrapper(resp, max_bytes=max_bytes)
|
|
|
|
|
|
def safe_tar_members(
|
|
tf: tarfile.TarFile,
|
|
*,
|
|
max_member_bytes: int = DEFAULT_MAX_TAR_MEMBER_BYTES,
|
|
) -> list[tarfile.TarInfo]:
|
|
"""
|
|
Return validated regular-file `TarInfo` members from `tf` enforcing `PEP 706` (`tarfile.data_filter`)
|
|
semantics: rejects absolute paths, `..` traversal, symlinks/hardlinks/devices/FIFOs, and members
|
|
exceeding `max_member_bytes`.
|
|
"""
|
|
safe_list: list[tarfile.TarInfo] = []
|
|
data_filter = getattr(tarfile, "data_filter", None)
|
|
for m in tf.getmembers():
|
|
name = m.name or ""
|
|
if not name or name.startswith("/") or ".." in name.split("/"):
|
|
raise SecurityBoundaryError(f"Blocked unsafe tar member path: {name!r}")
|
|
if m.issym() or m.islnk() or m.isdev() or m.isfifo() or m.ischr() or m.isblk():
|
|
raise SecurityBoundaryError(f"Blocked non-regular tar member: {name!r}")
|
|
if not m.isfile():
|
|
continue
|
|
if m.size < 0 or m.size > max_member_bytes:
|
|
raise SecurityBoundaryError(
|
|
f"Blocked tar member {name!r} exceeding max_member_bytes ({m.size} > {max_member_bytes})"
|
|
)
|
|
if callable(data_filter):
|
|
m = data_filter(m, "/tmp")
|
|
if m is None:
|
|
continue
|
|
safe_list.append(m)
|
|
return safe_list
|