blob: ade64d6343380abab6bfe1d63306306d1e3d2504 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Validate URL schemes and publicly routable network destinations."""
import ipaddress
from urllib.parse import urlsplit
import dns.exception
import dns.resolver
class AddressResolutionError(Exception):
pass
def is_public_url(url: str) -> bool:
"""
Check whether a URL resolves exclusively to public IP addresses.
: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.
"""
hostname = urlsplit(url).hostname
if hostname is None:
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
def is_http_url(url: str) -> bool:
"""
Check whether a URL is an absolute HTTP or HTTPS URL.
:param url: URL to validate.
:return: Whether the URL uses HTTP or HTTPS and contains a hostname.
"""
try:
parsed = urlsplit(url)
except ValueError:
return False
return parsed.scheme.lower() in {"http", "https"} and parsed.hostname is not None
def is_safe_next_url(next_url: str) -> bool:
"""Allow redirects only to paths on this site."""
# Check the original string too: urlsplit("///evil.example").path is
# "/evil.example", even though browsers can treat the original as external.
if "\\" in next_url or not next_url.startswith("/") or next_url.startswith("//"):
return False
try:
target = urlsplit(next_url)
except ValueError:
return False
return (
not target.scheme
and not target.netloc
and target.path.startswith("/")
and not target.path.startswith("//")
)
|