fix(email): guard user-supplied IMAP/SMTP hosts against SSRF (#6355)

* fix(email): guard user-supplied IMAP/SMTP hosts against SSRF

POST /api/email/accounts/test opened raw imaplib/smtplib connections to
whatever host:port the request body named, and POST/PUT /api/email/accounts
and PUT /api/email/config persisted arbitrary hosts for the background
pollers to contact. All of these sit behind require_user/require_owner with
no admin gate, so any authenticated user could make the server connect to
loopback, LAN and cloud-metadata targets (169.254.169.254) and read the
first 200 characters of the remote banner back out of the friendly error.
THREAT_MODEL.md lists email as admin-only; the tool layer honours that but
the HTTP routes did not.

Add check_outbound_host() to src/url_safety.py, a bare-host companion to
check_outbound_url() with the same classification (link-local, multicast,
reserved and unspecified always rejected; private/loopback only with
block_private) plus localhost-name handling and an explicit policy for names
that do not resolve. Wire it into the four email routes via
_check_mail_host(): non-admin owners (and everyone when
EMAIL_BLOCK_PRIVATE_IPS=true) also lose private/loopback targets, admins
keep the local-first LAN/Dovecot setups. Unresolvable names pass through
because the connect that follows fails with the same DNS error.

Regression tests cover the helper's policy table and each route: the test
route rejects before any socket opens, save routes reject before touching
the DB, admins keep loopback unless locked down, and an update that fails
validation leaves the stored row untouched.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TwcwfY2uQMxNRsK3y6xBAp

* fix(email): harden IMAP/SMTP SSRF protection against rebinding, TOCTOU, and unvetted hosts

- P0: Implement safe_create_connection() in src/url_safety.py to resolve hostnames once, validate every returned address against SSRF policy, and connect directly to the pinned IP. This eliminates DNS rebinding and TOCTOU while preserving TLS SNI and certificate hostname verification across IMAP, IMAPS, STARTTLS, SMTP, and SMTP_SSL.
- P1: Ensure unresolvable or deferred hostnames cannot become an unrestricted future connection capability by enforcing runtime SSRF validation fail-closed on every connection, while maintaining compatibility with offline configurations.
- P2: Extend SSRF enforcement to the core connection layer (_open_imap_connection, _send_smtp_message, _imap_connect) using ContextVar owner scoping, protecting pre-existing DB rows, restored configs, background pollers, and scheduled operations.
- P3: Allow admin and single-user access to IPv6 loopback (::1, [::1]) for local mail servers (e.g. Dovecot) by checking loopback before is_reserved, while keeping link-local, cloud metadata (169.254.169.254, 100.100.100.200), and non-admin restrictions strictly enforced.
- Add comprehensive regression and adversarial test coverage in tests/test_email_account_host_ssrf.py.

* fix(email): reject unresolved saved hosts without stdlib monkeypatches

Use the existing explicit policy IMAP/SMTP classes and canonical connect_outbound_tcp helper. Remove process-wide stdlib assignments, context-variable plumbing, redundant aliases and resolver-signature retries. Reject unsafe or unresolved hosts before account/config persistence, keep DNS work off the event loop, return fixed client errors, identify Alibaba metadata accurately and reject invalid TCP ports. Validation: 654 relevant email, URL-safety and CodeQL regression tests passed, 3 skipped. Three unrelated browser checks were excluded after environment failures (missing Playwright browser and Chromium timeout). Running-app checks verified rejected create/update/config requests leave stored data unchanged, administrator LAN configuration still works, and metadata/non-admin loopback are blocked.

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: PR #6029 Reviewer <reviewer@odysseus-review.local>
Co-authored-by: Afonso Junior <chatgpt@yack.com.br>
This commit is contained in:
Afonso Coutinho
2026-10-26 09:47:03 -06:00
committed by GitHub
co-authored by Claude Fable 5.1 PR #6029 Reviewer Afonso Junior
parent be9f575b59
commit 4d0610a1eb
3 changed files with 608 additions and 0 deletions
+27
View File
@@ -87,6 +87,17 @@ _SERVER_OWNED_OAUTH_FIELDS = {
_CACHE_HOOKS: dict = {"invalidate_list": None}
def _check_mail_host(host, owner: str, label: str) -> str | None:
"""Reject unsafe or unresolved mail hosts before saving or testing them."""
from src.url_safety import check_outbound_host
ok, reason = check_outbound_host(host, block_private=_mail_private_blocked(owner))
if ok:
return None
logger.warning("Rejected %s mail host for owner=%r: %s", label, owner, reason)
# Resolver and exception details belong in server logs, never the response.
return f"Rejected {label} host: server address is not allowed or does not resolve"
def _normalized_mail_host(value) -> str:
"""Normalize a mail hostname for exact provider-bound comparisons."""
return str(value or "").strip().lower().rstrip(".")
@@ -7139,6 +7150,12 @@ def setup_email_routes():
if account_id:
_assert_owns_account(account_id, owner)
for field, label in (("imap_host", "IMAP"), ("smtp_host", "SMTP")):
if data.get(field):
host_error = await run_in_threadpool(_check_mail_host, data[field], owner, label)
if host_error:
return {"ok": False, "error": host_error}
# Non-reply automation flags stay global. Away/auto-reply settings are
# account-scoped when an account_id is supplied by the Email Settings UI.
settings = _load_settings()
@@ -7279,6 +7296,11 @@ def setup_email_routes():
smtp_port, port_err = _coerce_port(data.get("smtp_port"), 465)
if port_err:
return {"ok": False, "error": port_err}
for field, label in (("imap_host", "IMAP"), ("smtp_host", "SMTP")):
if data.get(field):
host_error = await run_in_threadpool(_check_mail_host, data[field], owner, label)
if host_error:
return {"ok": False, "error": host_error}
db = SessionLocal()
try:
_lock_email_account_owner_mutation(db, owner)
@@ -7324,6 +7346,11 @@ def setup_email_routes():
"""Update an email account. Passwords only overwrite if non-empty."""
# Path param account_id — dep validated via Query, re-check the path-param value.
_assert_owns_account(account_id, owner)
for field, label in (("imap_host", "IMAP"), ("smtp_host", "SMTP")):
if data.get(field):
host_error = await run_in_threadpool(_check_mail_host, data[field], owner, label)
if host_error:
return {"ok": False, "error": host_error}
from core.database import SessionLocal, EmailAccount
db = SessionLocal()
try: