fix(security): reject malformed hostnames before DNS resolution (#6716)

Reject control characters before parsing and whitespace in the parsed hostname before resolving the destination.

Co-authored-by: Mark Zhang <122280878+atlasmarkz@users.noreply.github.com>
This commit is contained in:
chengyongruandMark Zhang authored and GitHub committed 2026-11-19 16:12:35 +08:00
1 parent 094bac0dc3
commit 085521823e
2 files changed
+18

No files matched your search

+7
View File
@@ -26,6 +26,7 @@ _BLOCKED_NETWORKS = [
]
_URL_RE = re.compile(r"https?://[^\s\"'`;|<>]+", re.IGNORECASE)
_URL_CONTROL_RE = re.compile(r"[\x00-\x1f\x7f-\x9f]")
_allowed_networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network] = []
@@ -95,6 +96,10 @@ def resolve_url_target(
resolved_ips contains the public IPs that were validated for this URL, or
is empty when an unresolved hostname is delegated to a trusted proxy.
"""
# urlparse silently strips some control characters.
if _URL_CONTROL_RE.search(url):
return False, "Invalid URL: control characters are not allowed", ()
try:
p = urlparse(url)
except Exception as e:
@@ -108,6 +113,8 @@ def resolve_url_target(
hostname = p.hostname
if not hostname:
return False, "Missing hostname", ()
if any(char.isspace() for char in hostname):
return False, "Invalid hostname: whitespace is not allowed", ()
try:
infos = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
+11
View File
@@ -179,6 +179,17 @@ def test_resolve_url_target_returns_validated_public_ips():
assert resolved_ips == ("93.184.216.34",)
@pytest.mark.parametrize("character", ["\x00", "\t", " ", "\x7f"], ids=["nul", "tab", "space", "del"])
def test_resolve_url_target_rejects_invalid_hostname_before_dns(character: str) -> None:
with patch("nanobot.security.network.socket.getaddrinfo") as getaddrinfo:
ok, error, resolved_ips = resolve_url_target(f"https://mail{character}host.invalid/")
assert not ok
assert error.startswith(("Invalid URL:", "Invalid hostname:"))
assert resolved_ips == ()
getaddrinfo.assert_not_called()
@pytest.mark.parametrize(
("trust_remote_dns", "expected_ok"),
[(False, False), (True, True)],