Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(security): block CGNAT/mesh ranges in SSRF guard; close QQ media redirect-to-internal

hobostay3ce2ee3ed138
diff --git a/agent/src/channels/qq.py b/agent/src/channels/qq.py
index c88796c13..94a70d7b9 100644
--- a/agent/src/channels/qq.py
+++ b/agent/src/channels/qq.py
@@ -409,7 +409,20 @@ class QQChannel(BaseChannel):
if not self._http:
self._http = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=120))
try:
- async with self._http.get(media_ref, allow_redirects=True) as resp:
+ # Do not auto-follow redirects: ``media_ref`` is agent-controlled
+ # (taken from ``msg.media``), and a public URL that 302s to an
+ # internal address (169.254.169.254, 100.64/10, …) would bypass the
+ # pre-flight ``validate_url_target`` check and exfiltrate internal
+ # content as a media attachment. Fail closed on 3xx instead — this
+ # mirrors napcat.py's inbound image download.
+ async with self._http.get(media_ref, allow_redirects=False) as resp:
+ if 300 <= resp.status < 400:
+ self.logger.warning(
+ "outbound media download redirect rejected url={} status={}",
+ media_ref,
+ resp.status,
+ )
+ return None, None
if resp.status >= 400:
self.logger.warning(
"outbound media download failed status={} url={}",
diff --git a/agent/src/channels/utils.py b/agent/src/channels/utils.py
index 222dac1eb..251bbe58a 100644
--- a/agent/src/channels/utils.py
+++ b/agent/src/channels/utils.py
@@ -146,11 +146,21 @@ def _is_allowed_loopback_target(
def _is_private(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
- """Check whether *addr* is private, link-local, or loopback."""
- if addr.is_loopback or addr.is_link_local or addr.is_private:
- return True
- # Also block well-known metadata endpoints
- if isinstance(addr, ipaddress.IPv4Address):
- return False
- # IPv6: block unspecified, multicast, unique-local
- return addr.is_multicast or addr.is_unspecified
+ """Check whether *addr* is non-globally-routable (private/internal/mesh).
+
+ ``addr.is_global`` is False for loopback, link-local, RFC 1918 private,
+ unspecified, reserved, and RFC 6598 shared address space
+ (``100.64.0.0/10`` — the default Tailscale/mesh range). The previous
+ explicit ``is_loopback | is_link_local | is_private`` checks missed the
+ 100.64/10 block (``is_private`` is False for it), letting CGNAT/mesh hosts
+ slip past ``validate_url_target`` and be fetched as channel media. Using
+ ``not addr.is_global`` blocks every non-globally-routable range uniformly.
+ Multicast is added explicitly because ``is_global`` is True for multicast
+ addresses (both ``224.0.0.0/4`` and ``ff00::/8``); the old code only caught
+ IPv6 multicast, so this also closes an IPv4-multicast gap and matches
+ ``web_reader_tool._url_allowed``.
+
+ Loopback is still permitted when ``validate_url_target(allow_loopback=True)``
+ is called — that allowance is evaluated before this function runs.
+ """
+ return not addr.is_global or addr.is_multicast
diff --git a/agent/tests/test_url_target_security.py b/agent/tests/test_url_target_security.py
new file mode 100644
index 000000000..592055d39
--- /dev/null
+++ b/agent/tests/test_url_target_security.py
@@ -0,0 +1,151 @@
+"""Regression tests for the SSRF URL guard and QQ outbound-media fetch.
+
+Covers two previously-untested gaps:
+
+- ``validate_url_target`` / ``_is_private`` must block non-globally-routable
+ ranges, including RFC 6598 ``100.64.0.0/10`` (CGNAT / the default Tailscale
+ mesh range). ``ipaddress.is_private`` is ``False`` for 100.64/10, so the old
+ ``is_loopback | is_link_local | is_private`` check let those hosts through.
+- QQ's outbound media download must reject HTTP redirects. ``media_ref`` is
+ agent-controlled (it comes from ``msg.media``), so a public URL that 302s to
+ an internal address would otherwise bypass the pre-flight
+ ``validate_url_target`` check and exfiltrate internal content as an
+ attachment. This mirrors napcat.py's inbound image download.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import ipaddress
+import logging
+
+import pytest
+
+from src.channels import qq as qq_module
+from src.channels.utils import _is_private, validate_url_target
+
+# ─── central SSRF guard ───
+
+
+ "ip",
+ [
+ # RFC 6598 shared address space — the default Tailscale/mesh range.
+ # is_private is False for these, so they slipped through before the fix.
+ "100.64.0.1",
+ "100.100.100.100",
+ "100.127.255.254",
+ # classic private / internal ranges must stay blocked too
+ "10.0.0.1",
+ "172.16.0.1",
+ "192.168.1.1",
+ "127.0.0.1",
+ "169.254.169.254", # cloud metadata
+ "0.0.0.0",
+ "224.0.0.1", # multicast
+ # IPv6 non-global
+ "::1",
+ "fe80::1",
+ "fc00::1",
+ ],
+)
+def test_is_private_blocks_non_global_ranges(ip: str) -> None:
+ assert _is_private(ipaddress.ip_address(ip)) is True
+
+
[email protected]("ip", ["8.8.8.8", "1.1.1.1", "2606:4700:4700::1111"])
+def test_is_private_allows_global_ranges(ip: str) -> None:
+ assert _is_private(ipaddress.ip_address(ip)) is False
+
+
[email protected]("ip", ["100.64.0.1", "100.100.100.100"])
+def test_validate_url_target_blocks_cgnat_ip_literal(ip: str) -> None:
+ # IP-literal host → getaddrinfo is a local parse, so this needs no network.
+ ok, err = validate_url_target(f"http://{ip}/x")
+ assert ok is False
+ assert "private" in err or "internal" in err
+
+
+def test_validate_url_target_allows_public_ip_literal() -> None:
+ ok, _err = validate_url_target("http://8.8.8.8/x")
+ assert ok is True
+
+
+def test_validate_url_target_loopback_only_with_opt_in() -> None:
+ # Default: loopback is blocked even though it is a literal IP.
+ assert validate_url_target("http://127.0.0.1/x")[0] is False
+ # The narrow opt-in still allows literal loopback.
+ assert validate_url_target("http://127.0.0.1/x", allow_loopback=True)[0] is True
+
+
+# ─── QQ outbound-media redirect rejection ───
+
+
+class _FakeResp:
+ def __init__(self, status: int) -> None:
+ self.status = status
+
+ async def __aenter__(self) -> "_FakeResp":
+ return self
+
+ async def __aexit__(self, *_exc: object) -> bool:
+ return False
+
+ async def read(self) -> bytes:
+ return b"internal-content"
+
+
+class _FakeHttp:
+ """Records the ``allow_redirects`` flag and returns a canned response."""
+
+ def __init__(self, status: int) -> None:
+ self.status = status
+ self.allow_redirects: object = "not-called"
+
+ def get(self, url: str, *, allow_redirects: bool = True) -> _FakeResp:
+ self.allow_redirects = allow_redirects
+ return _FakeResp(self.status)
+
+
+def _make_qq_channel(http: _FakeHttp) -> qq_module.QQChannel:
+ # Build a minimal instance without running __init__ (which validates config
+ # and creates a media dir on disk). _read_media_bytes only touches
+ # self._http and self.logger.
+ ch = object.__new__(qq_module.QQChannel)
+ ch._http = http # type: ignore[attr-defined]
+ # CRITICAL level keeps the (intentionally loguru-style) warning quiet under
+ # a stdlib logger without affecting return-value behavior.
+ log = logging.getLogger("qq-test")
+ log.setLevel(logging.CRITICAL)
+ ch.logger = log # type: ignore[attr-defined]
+ return ch
+
+
[email protected]("status", [301, 302, 303, 307, 308])
+def test_qq_outbound_media_rejects_redirects(status: int) -> None:
+ http = _FakeHttp(status=status)
+ ch = _make_qq_channel(http)
+ # Public IP-literal host → validate_url_target passes without a network call.
+ data, name = asyncio.run(ch._read_media_bytes("http://8.8.8.8/x.png"))
+ assert data is None
+ assert name is None
+ # The fix must not auto-follow redirects.
+ assert http.allow_redirects is False
+
+
+def test_qq_outbound_media_allows_2xx_and_does_not_follow_redirects() -> None:
+ http = _FakeHttp(status=200)
+ ch = _make_qq_channel(http)
+ data, name = asyncio.run(ch._read_media_bytes("http://8.8.8.8/x.png"))
+ assert data == b"internal-content"
+ assert name == "x.png"
+ assert http.allow_redirects is False
+
+
[email protected]("status", [400, 404, 500])
+def test_qq_outbound_media_rejects_error_status(status: int) -> None:
+ http = _FakeHttp(status=status)
+ ch = _make_qq_channel(http)
+ data, name = asyncio.run(ch._read_media_bytes("http://8.8.8.8/x.png"))
+ assert data is None
+ assert name is None