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.py63
1 files changed, 45 insertions, 18 deletions
diff --git a/webmentions_ssg/url_security.py b/webmentions_ssg/url_security.py
index ade64d6..f943c7e 100644
--- a/webmentions_ssg/url_security.py
+++ b/webmentions_ssg/url_security.py
@@ -12,17 +12,51 @@ import dns.resolver
class AddressResolutionError(Exception):
- pass
+ """A hostname could not be resolved (potentially transient)."""
-def is_public_url(url: str) -> bool:
+class UnsafeAddressError(ValueError):
+ """A hostname or IP literal identifies a non-public network address."""
+
+
+def public_addresses(hostname: str, *, lifetime: float | None = None) -> tuple[str, ...]:
+ """Resolve *once* and return only checked, globally routable IP addresses.
+
+ A DNS name with a mixture of public and private answers is rejected in its
+ entirety. IP literals are handled without DNS, including IPv6 literals.
+ The returned strings must be used for the actual TCP connection; checking
+ them and then connecting to ``hostname`` reintroduces DNS rebinding.
"""
- Check whether a URL resolves exclusively to public IP addresses.
+ try:
+ literal = ipaddress.ip_address(hostname)
+ except ValueError:
+ literal = None
+
+ if literal is not None:
+ addresses = (literal,)
+ else:
+ try:
+ answers = dns.resolver.resolve_name(hostname, lifetime=lifetime)
+ addresses = tuple(ipaddress.ip_address(a) for a in answers.addresses())
+ except (dns.exception.DNSException, ValueError) as exc:
+ raise AddressResolutionError(
+ f"Could not resolve hostname {hostname!r}"
+ ) from exc
+
+ if not addresses:
+ raise AddressResolutionError(f"Could not resolve hostname {hostname!r}")
- :param url: URL whose hostname should be resolved.
- :return: Whether all resolved addresses are globally routable.
- :raises ValueError: If the URL does not contain a hostname.
- :raises AddressResolutionError: If the hostname cannot be resolved.
+ if any(not address.is_global for address in addresses):
+ raise UnsafeAddressError(f"Non-public network address for {hostname!r}")
+
+ return tuple(str(address) for address in addresses)
+
+
+def is_public_url(url: str) -> bool:
+ """Return whether the URL resolves entirely to public IP addresses.
+
+ This is useful for diagnostics, but **not** sufficient to authorize a
+ request: network connections must use the exact validated IP address.
"""
hostname = urlsplit(url).hostname
@@ -30,17 +64,10 @@ def is_public_url(url: str) -> bool:
raise ValueError("No hostname was specified")
try:
- answers = dns.resolver.resolve_name(hostname)
- except dns.exception.DNSException as exc:
- raise AddressResolutionError(
- f"Could not resolve hostname {hostname!r}"
- ) from exc
- else:
- for address in answers.addresses():
- if not ipaddress.ip_address(address).is_global:
- return False
-
- return True
+ public_addresses(hostname)
+ except UnsafeAddressError:
+ return False
+ return True
def is_http_url(url: str) -> bool: