aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/url_security.py
diff options
context:
space:
mode:
Diffstat (limited to 'webmentions_ssg/url_security.py')
-rw-r--r--webmentions_ssg/url_security.py28
1 files changed, 27 insertions, 1 deletions
diff --git a/webmentions_ssg/url_security.py b/webmentions_ssg/url_security.py
index 4e7940b..c4324e0 100644
--- a/webmentions_ssg/url_security.py
+++ b/webmentions_ssg/url_security.py
@@ -19,6 +19,32 @@ class UnsafeAddressError(ValueError):
"""A hostname or IP literal identifies a non-public network address."""
+_NAT64_PREFIX = ipaddress.IPv6Network("64:ff9b::/96")
+_IPV4_COMPATIBLE_PREFIX = ipaddress.IPv6Network("::/96")
+
+
+def is_public_address(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
+ """Reject non-public addresses, including IPv4 hidden in IPv6 forms.
+
+ ``is_global`` alone does not reliably exclude IPv6 transition addresses
+ across Python versions or networks with NAT64/6to4 routing.
+ """
+ if isinstance(address, ipaddress.IPv6Address):
+ # The well-known NAT64 prefix can translate an otherwise global IPv6
+ # address into a private IPv4 destination. IPv4-compatible addresses
+ # similarly embed IPv4 in ::/96, even without ipv4_mapped metadata.
+ if address in _NAT64_PREFIX or address in _IPV4_COMPATIBLE_PREFIX:
+ return False
+
+ # 6to4 and IPv4-mapped IPv6 addresses expose their embedded IPv4
+ # destination through ipaddress; validate that destination as well.
+ for embedded in (address.sixtofour, address.ipv4_mapped):
+ if embedded is not None and not embedded.is_global:
+ return False
+
+ return address.is_global
+
+
def public_addresses(
hostname: str, *, lifetime: float | None = None
) -> tuple[str, ...]:
@@ -48,7 +74,7 @@ def public_addresses(
if not addresses:
raise AddressResolutionError(f"Could not resolve hostname {hostname!r}")
- if any(not address.is_global for address in addresses):
+ if any(not is_public_address(address) for address in addresses):
raise UnsafeAddressError(f"Non-public network address for {hostname!r}")
return tuple(str(address) for address in addresses)