diff --git a/nanobot/security/network.py b/nanobot/security/network.py index d676ddbe2..50e712af4 100644 --- a/nanobot/security/network.py +++ b/nanobot/security/network.py @@ -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) diff --git a/tests/security/test_security_network.py b/tests/security/test_security_network.py index 703a07537..09d3a5ac3 100644 --- a/tests/security/test_security_network.py +++ b/tests/security/test_security_network.py @@ -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)],