Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(net): parse IP literals the same on every platform and interpreter (#1550) (#1562)

qwist1233-cpu0626ea8307a4
diff --git a/changelog.d/0.75.1/1562.fixed.md b/changelog.d/0.75.1/1562.fixed.md
new file mode 100644
index 00000000..8ea5d5be
--- /dev/null
+++ b/changelog.d/0.75.1/1562.fixed.md
@@ -0,0 +1 @@
+- **IP-literal parsing depended on the platform and the interpreter (#1550 by @qwist1233-cpu in #1562).** On Windows the C library refused `0xffffffff`, `4294967295` and `0377.0377.0377.0377`, so those spellings of `255.255.255.255` passed the outbound guard; 6to4, NAT64 and Teredo literals were classified only by the interpreter's `ipaddress` tables. `net_guard` now parses IPv4 spellings in pure Python, unwraps the embedded IPv4 address and classifies it too, and `refuse_private_ip_literal` parses once.
diff --git a/src/soup_cli/utils/net_guard.py b/src/soup_cli/utils/net_guard.py
index dbcf5df3..437f770e 100644
--- a/src/soup_cli/utils/net_guard.py
+++ b/src/soup_cli/utils/net_guard.py
@@ -82,10 +82,12 @@ def parse_ip_literal(host: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address
Handles canonical IPv4/IPv6 via :func:`ipaddress.ip_address` **and**
abbreviated / decimal / hex / octal IPv4 forms (e.g. ``127.1``,
- ``2130706433``, ``0x7f000001``, ``0177.0.0.1``) via the platform C
- library :func:`socket.inet_aton`. The latter is a pure in-process
- string parser — no DNS lookup is performed. A hostname (``"localhost"``,
- ``"evil.example.com"``) returns ``None`` rather than being resolved.
+ ``2130706433``, ``0x7f000001``, ``0177.0.0.1``) via :func:`inet_aton`, a
+ pure-Python port of the BSD parser, so the answer is the same on Linux,
+ macOS and Windows (the C library's differs: Windows refuses every spelling
+ of ``255.255.255.255`` except the dotted quad, #1550). No DNS lookup is
+ performed. A hostname (``"localhost"``, ``"evil.example.com"``) returns
+ ``None`` rather than being resolved.
A non-ASCII host is also read in the ASCII forms a client would connect to
(see :func:`_ascii_spellings`), and the first form that is an IP literal is
@@ -102,20 +104,120 @@ def parse_ip_literal(host: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address
def _parse_ascii_ip_literal(
host: str,
) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
- import socket # noqa: PLC0415 — lazy import (stdlib, negligible cost)
-
clean_host = host.rstrip(".")
try:
return ipaddress.ip_address(clean_host)
except ValueError:
pass
- # Fallback: C-level inet_aton accepts abbreviated/integer/hex/octal
+ # Fallback: the BSD inet_aton grammar accepts abbreviated/integer/hex/octal
# IPv4 representations that Python's ipaddress module rejects.
- try:
- canonical = socket.inet_ntoa(socket.inet_aton(clean_host))
- return ipaddress.ip_address(canonical)
- except (OSError, ValueError):
+ packed = inet_aton(clean_host)
+ if packed is None:
+ return None
+ return ipaddress.IPv4Address(packed)
+
+
+# Upper bound of the last part of a 1-, 2-, 3- or 4-part BSD inet_aton
+# spelling: that part fills every byte the earlier parts did not.
+_INET_ATON_LAST_PART_MAX = {1: 0xFFFFFFFF, 2: 0xFFFFFF, 3: 0xFFFF, 4: 0xFF}
+
+# What C's ``isspace()`` calls whitespace in the C locale: the C parsers stop
+# there and read only the text before it.
+_C_SPACE = frozenset(" \t\n\v\f\r")
+
+
+# The digits each base accepts. ``int(digits, base)`` is not a substitute: it
+# also takes its own radix prefix, so ``int("0xa", 16)`` would let a second
+# prefix through, and it takes "_" separators and surrounding space.
+_INET_ATON_DIGITS = {
+ 10: frozenset("0123456789"),
+ 8: frozenset("01234567"),
+ 16: frozenset("0123456789abcdefABCDEF"),
+}
+
+
+def _inet_aton_part(part: str) -> int | None:
+ """One dot-separated part, read like C ``strtoul(part, &end, 0)`` would."""
+ if not part or not part[0].isdigit() or not part.isascii():
+ return None
+ base = 10
+ digits = part
+ if part[0] == "0" and len(part) > 1:
+ if part[1] in "xX":
+ base, digits = 16, part[2:]
+ else:
+ base, digits = 8, part[1:]
+ if not digits or not set(digits) <= _INET_ATON_DIGITS[base]:
+ return None # includes a bare "0x", which needs at least one hex digit
+ return int(digits, base)
+
+
+def inet_aton(text: str) -> int | None:
+ """Parse ``text`` with the BSD ``inet_aton`` grammar, in pure Python.
+
+ Returns the address as an int, or ``None`` if ``text`` is not an IPv4
+ spelling. Accepts one to four ``.``-separated parts; each part is a C
+ number (``0x`` hex, leading-``0`` octal, else decimal, no sign); the last
+ part fills every byte the earlier parts left (``127.1`` is ``127.0.0.1``,
+ ``1.65535`` is ``1.0.255.255``, ``2130706433`` is ``127.0.0.1``). Unlike
+ the C library's, the result does not depend on the platform: Windows
+ refuses ``0xffffffff``, ``4294967295`` and ``0377.0377.0377.0377`` where
+ glibc reads ``255.255.255.255`` (#1550).
+
+ Like the C parsers, the text ends at the first ASCII whitespace and only
+ what precedes it is read, so ``"10.0.0.1 x"`` is ``10.0.0.1`` while
+ ``"10.0.0.1x"`` is not an address at all.
+ """
+ for i, ch in enumerate(text):
+ if ch in _C_SPACE:
+ text = text[:i]
+ break
+ parts = text.split(".")
+ if not 1 <= len(parts) <= 4:
return None
+ values = []
+ for part in parts:
+ value = _inet_aton_part(part)
+ if value is None:
+ return None
+ values.append(value)
+ *head, last = values
+ if any(v > 0xFF for v in head) or last > _INET_ATON_LAST_PART_MAX[len(values)]:
+ return None
+ packed = 0
+ for v in head:
+ packed = (packed << 8) | v
+ return (packed << (8 * (5 - len(values)))) | last
+
+
+# IPv6 prefixes that carry an IPv4 address inside them. The inner address is
+# what the packet reaches, so it is classified too, whatever the interpreter's
+# ``ipaddress`` tables say about the outer prefix (6to4 counts as private only
+# from 3.10.15 / 3.11.10 / 3.12.4, #1550).
+_SIXTOFOUR = ipaddress.IPv6Network("2002::/16")
+_TEREDO = ipaddress.IPv6Network("2001::/32")
+_NAT64 = ipaddress.IPv6Network("64:ff9b::/96")
+
+
+def embedded_ipv4(addr: ipaddress.IPv6Address) -> ipaddress.IPv4Address | None:
+ """The IPv4 address an IPv6 transition address embeds, or ``None``.
+
+ IPv4-mapped ``::ffff:a.b.c.d`` (low 32 bits), 6to4 ``2002::/16`` (bits
+ 16-47), NAT64 ``64:ff9b::/96`` (low 32 bits) and Teredo ``2001::/32``
+ (low 32 bits, inverted). Unwrapped here by hand rather than through
+ ``IPv6Address.sixtofour`` / ``.teredo`` so the set does not depend on the
+ interpreter either.
+ """
+ bits = int(addr)
+ if addr.ipv4_mapped is not None:
+ return addr.ipv4_mapped
+ if addr in _SIXTOFOUR:
+ return ipaddress.IPv4Address((bits >> 80) & 0xFFFFFFFF)
+ if addr in _NAT64:
+ return ipaddress.IPv4Address(bits & 0xFFFFFFFF)
+ if addr in _TEREDO:
+ return ipaddress.IPv4Address((~bits) & 0xFFFFFFFF)
+ return None
def is_private_or_link_local(host: str) -> bool:
@@ -137,6 +239,19 @@ def is_private_or_link_local(host: str) -> bool:
# back to "treat as public". A malicious DNS record pointing to
# a private IP is out of scope for this local-tool threat model.
return False
+ return is_non_public_address(addr)
+
+
+def is_non_public_address(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
+ """:func:`is_private_or_link_local` for an already-parsed address.
+
+ An IPv6 address that embeds an IPv4 address (see :func:`embedded_ipv4`)
+ is non-public when either the outer or the inner address is.
+ """
+ if isinstance(addr, ipaddress.IPv6Address):
+ inner = embedded_ipv4(addr)
+ if inner is not None and is_non_public_address(inner):
+ return True
return (
addr.is_private
or addr.is_link_local
@@ -173,7 +288,7 @@ def refuse_private_ip_literal(host: str | None, *, label: str) -> None:
mapped = getattr(addr, "ipv4_mapped", None)
if (mapped if mapped is not None else addr).is_loopback:
return
- if is_private_or_link_local(clean):
+ if is_non_public_address(addr):
raise ValueError(
f"{label}: private/link-local/reserved IP hosts are not allowed (SSRF protection); "
"address the server by its hostname"
diff --git a/tests/test_issue1550_ip_literal_portable.py b/tests/test_issue1550_ip_literal_portable.py
new file mode 100644
index 00000000..c1d25845
--- /dev/null
+++ b/tests/test_issue1550_ip_literal_portable.py
@@ -0,0 +1,233 @@
+"""#1550: IP-literal parsing does not depend on the platform or the interpreter.
+
+``parse_ip_literal`` fell back to the C library's ``inet_aton``, which differs
+by platform: Windows refuses ``0xffffffff``, ``4294967295`` and
+``0377.0377.0377.0377`` (every spelling of ``255.255.255.255`` except the
+dotted quad) that glibc reads, so those spellings passed the guard there. And
+IPv6 forms that embed an IPv4 address were classified only through the
+interpreter's ``ipaddress`` tables: 6to4 ``2002::/16`` counts as private only
+from 3.10.15 / 3.11.10 / 3.12.4.
+
+The parser is now pure Python, the embedded IPv4 address is unwrapped and
+classified by hand, and ``refuse_private_ip_literal`` parses once.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+
+import pytest
+
+from soup_cli.utils.net_guard import (
+ is_private_or_link_local,
+ parse_ip_literal,
+ refuse_private_ip_literal,
+)
+
+# ``inet_aton`` and ``embedded_ipv4`` are new in this change; they are imported
+# inside the tests that need them so the file still collects on an older tree
+# and the other tests measure what that tree gets wrong.
+
+# (spelling, dotted quad) -- the same answer is expected on Linux, macOS and
+# Windows, which is what the CI matrix checks.
+INET_ATON_TABLE = [
+ ("255.255.255.255", "255.255.255.255"),
+ ("0xffffffff", "255.255.255.255"), # Windows C library: refused
+ ("0XFFFFFFFF", "255.255.255.255"),
+ ("4294967295", "255.255.255.255"), # Windows C library: refused
+ ("0377.0377.0377.0377", "255.255.255.255"), # Windows C library: refused
+ ("037777777777", "255.255.255.255"),
+ ("127.1", "127.0.0.1"),
+ ("127.0.1", "127.0.0.1"),
+ ("2130706433", "127.0.0.1"),
+ ("0x7f000001", "127.0.0.1"),
+ ("0x7f.1", "127.0.0.1"),
+ ("0177.0.0.1", "127.0.0.1"),
+ ("0177.1", "127.0.0.1"),
+ ("1.2.3", "1.2.0.3"),
+ ("1.65535", "1.0.255.255"),
+ ("1.256", "1.0.1.0"),
+ ("1.0x10000", "1.1.0.0"),
+ ("10.0x0.1", "10.0.0.1"),
+ ("0", "0.0.0.0"),
+ ("00", "0.0.0.0"),
+ ("167772161", "10.0.0.1"),
+ ("0xa000001", "10.0.0.1"),
+ ("012.0.0.1", "10.0.0.1"),
+ ("0xC0.0xA8.0x1.0x1", "192.168.1.1"),
+ # The text ends at the first ASCII whitespace; the prefix is the address.
+ ("10.0.0.1 x", "10.0.0.1"),
+ ("10.1 x", "10.0.0.1"),
+ ("167772161 x", "10.0.0.1"),
+ ("10.0.0.1\x0bx", "10.0.0.1"), # vertical tab
+ ("10.0.0.1 ", "10.0.0.1"),
+ ("127.0.0.1 x", "127.0.0.1"), # still loopback
+ ("1 ", "0.0.0.1"),
+]
+
+NOT_INET_ATON = [
+ "",
+ ".1",
+ "1..2",
+ "1.2.3.4.5",
+ "4294967296", # one past the top of the address space
+ "1.2.3.256",
+ "1.2.65536",
+ "256.1",
+ "08.1.1.1", # 8 is not an octal digit
+ "0x1g",
+ "+1",
+ "-1",
+ " 1", # leading space is not skipped: the prefix is empty
+ " ",
+ "1_0", # int() would take the separator; C does not
+ "0_x",
+ "١", # ARABIC-INDIC DIGIT ONE: int() would take it; C does not
+ "localhost",
+ "evil.example.com",
+ "1.2.3.4a",
+ "10.0.0.1x", # no whitespace to end the text: the whole string is read
+ # A radix prefix is written once. int(digits, base) would take a second
+ # one, and a bare "0x" needs at least one hex digit after it.
+ "0x",
+ "0x.1",
+ "0x0xa.1", # int("0xa", 16)
+ "00o12.0.0.1", # int("0o12", 8)
+ "0X0X1",
+]
+
+
[email protected](("spelling", "dotted"), INET_ATON_TABLE)
+def test_inet_aton_reads_every_spelling_the_same_everywhere(spelling: str, dotted: str) -> None:
+ """The pure-Python parser gives one answer on every OS."""
+ from soup_cli.utils.net_guard import inet_aton
+
+ packed = inet_aton(spelling)
+ assert packed is not None, spelling
+ assert str(ipaddress.IPv4Address(packed)) == dotted
+
+
[email protected]("spelling", NOT_INET_ATON)
+def test_inet_aton_refuses_what_is_not_an_address(spelling: str) -> None:
+ """Nothing outside the BSD grammar is read as an address."""
+ from soup_cli.utils.net_guard import inet_aton
+
+ assert inet_aton(spelling) is None
+
+
[email protected](("spelling", "dotted"), INET_ATON_TABLE)
+def test_parse_ip_literal_uses_the_portable_parser(spelling: str, dotted: str) -> None:
+ """``parse_ip_literal`` reaches the same dotted quad through the fallback."""
+ assert parse_ip_literal(spelling) == ipaddress.IPv4Address(dotted)
+
+
+ "spelling",
+ ["0xffffffff", "4294967295", "0377.0377.0377.0377", "037777777777"],
+)
+def test_broadcast_spellings_are_refused_on_every_platform(spelling: str) -> None:
+ """The spellings Windows' C library let through are refused like the dotted quad."""
+ assert is_private_or_link_local(spelling)
+ with pytest.raises(ValueError, match="SSRF"):
+ refuse_private_ip_literal(spelling, label="x")
+
+
+def test_parse_ip_literal_does_not_use_the_c_library(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The platform ``socket.inet_aton`` is not consulted at all."""
+ import socket
+
+ def boom(_text: str) -> bytes:
+ raise AssertionError("socket.inet_aton must not be called")
+
+ monkeypatch.setattr(socket, "inet_aton", boom)
+ assert parse_ip_literal("0xffffffff") == ipaddress.IPv4Address("255.255.255.255")
+ assert parse_ip_literal("127.1") == ipaddress.IPv4Address("127.0.0.1")
+ assert parse_ip_literal("example.com") is None
+
+
+# --- IPv6 forms that embed an IPv4 address ---------------------------------
+
+EMBEDDED = [
+ pytest.param("2002:0a00:0001::", "10.0.0.1", id="6to4"),
+ pytest.param("64:ff9b::a00:1", "10.0.0.1", id="nat64"),
+ # Teredo: the client IPv4 address is the inverted low 32 bits
+ # (10.0.0.1 -> f5ff:fffe).
+ pytest.param("2001:0:4136:e378:8000:63bf:f5ff:fffe", "10.0.0.1", id="teredo"),
+ pytest.param("::ffff:10.0.0.1", "10.0.0.1", id="v4-mapped"),
+]
+
+
[email protected](("literal", "inner"), EMBEDDED)
+def test_embedded_ipv4_is_unwrapped_by_hand(literal: str, inner: str) -> None:
+ """The inner address comes out of the right bits of each prefix."""
+ from soup_cli.utils.net_guard import embedded_ipv4
+
+ assert embedded_ipv4(ipaddress.IPv6Address(literal)) == ipaddress.IPv4Address(inner)
+
+
[email protected]("literal", ["2606:4700::1111", "2001:db8::1", "fd00::1", "::1"])
+def test_other_ipv6_embeds_nothing(literal: str) -> None:
+ """Prefixes outside the four transition forms carry no inner address."""
+ from soup_cli.utils.net_guard import embedded_ipv4
+
+ assert embedded_ipv4(ipaddress.IPv6Address(literal)) is None
+
+
+def old_ipaddress_tables(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Make IPv6 look the way an interpreter with the pre-2024 tables saw it.
+
+ Every outer-prefix classification says "public", so only the unwrapped
+ inner address can refuse the literal (as the mapped-loopback test in
+ ``test_outbound_endpoint_ip_literals.py`` does for ``is_loopback``).
+ """
+ v6 = ipaddress.IPv6Address
+ for name in ("is_private", "is_reserved", "is_link_local", "is_multicast", "is_site_local"):
+ monkeypatch.setattr(v6, name, property(lambda self: False))
+ monkeypatch.setattr(v6, "is_global", property(lambda self: True))
+
+
[email protected]("old_ipaddress_tables")
[email protected](("literal", "inner"), EMBEDDED)
+def test_embedded_private_ipv4_is_refused_on_every_interpreter(literal: str, inner: str) -> None:
+ """6to4, NAT64 and Teredo around 10.0.0.1 are refused even with old tables."""
+ assert is_private_or_link_local(literal)
+ with pytest.raises(ValueError, match="SSRF"):
+ refuse_private_ip_literal(literal, label="x")
+ with pytest.raises(ValueError, match="SSRF"):
+ refuse_private_ip_literal(f"[{literal}]", label="x")
+
+
[email protected]("old_ipaddress_tables")
+def test_old_tables_fixture_really_lets_the_outer_prefix_through() -> None:
+ """Guard on the fixture: with the tables patched, the outer prefix alone says public."""
+ addr = ipaddress.IPv6Address("2002:0a00:0001::")
+ assert not addr.is_private and addr.is_global
+
+
+def test_embedded_public_ipv4_does_not_refuse_by_itself(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Unwrapping only adds an inner address: NAT64 around 8.8.8.8 follows the outer prefix."""
+ v6 = ipaddress.IPv6Address
+ for name in ("is_private", "is_reserved", "is_link_local", "is_multicast", "is_site_local"):
+ monkeypatch.setattr(v6, name, property(lambda self: False))
+ monkeypatch.setattr(v6, "is_global", property(lambda self: True))
+ assert not is_private_or_link_local("64:ff9b::808:808")
+
+
+def test_refuse_parses_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ """``refuse_private_ip_literal`` parses the host a single time."""
+ from soup_cli.utils import net_guard
+
+ calls: list[str] = []
+ real = net_guard.parse_ip_literal
+
+ def counting(host: str):
+ calls.append(host)
+ return real(host)
+
+ monkeypatch.setattr(net_guard, "parse_ip_literal", counting)
+ with pytest.raises(ValueError):
+ net_guard.refuse_private_ip_literal("10.0.0.1", label="x")
+ assert calls == ["10.0.0.1"]