Bound the reverse DNS lookup on invalid auth requests (#182514)

This commit is contained in:
John Costa
2026-10-26 21:17:24 +00:00
committed by GitHub
parent aab4ab59e2
commit 070cdfe59e
2 changed files with 89 additions and 5 deletions
+10 -5
View File
@@ -1,5 +1,6 @@
"""Ban logic for HTTP component."""
import asyncio
from collections import defaultdict
from collections.abc import Awaitable, Callable, Coroutine
from contextlib import suppress
@@ -7,7 +8,7 @@ from datetime import datetime
from http import HTTPStatus
from ipaddress import IPv4Address, IPv6Address, ip_address
import logging
from socket import gethostbyaddr, herror
from socket import gethostbyaddr
from typing import Any, Concatenate, Final
from aiohttp.web import (
@@ -43,6 +44,8 @@ NOTIFICATION_ID_BAN: Final = "ip-ban"
NOTIFICATION_ID_LOGIN: Final = "http-login"
IP_BANS_FILE: Final = "ip_bans.yaml"
# Bound the reverse DNS lookup so a slow resolver cannot stall the response
REVERSE_DNS_TIMEOUT: Final = 1
ATTR_BANNED_AT: Final = "banned_at"
SCHEMA_IP_BAN_ENTRY: Final = probatio.Schema(
@@ -122,10 +125,12 @@ async def process_wrong_login(request: Request) -> None:
banned = await _async_count_wrong_login(request.app, hass, remote_addr)
remote_host = request.remote
with suppress(herror, UnicodeDecodeError):
remote_host, _, _ = await hass.async_add_executor_job(
gethostbyaddr, request.remote
)
# The hostname only feeds the log and notification below
with suppress(TimeoutError, OSError, UnicodeError):
async with asyncio.timeout(REVERSE_DNS_TIMEOUT):
remote_host, _, _ = await hass.async_add_executor_job(
gethostbyaddr, request.remote
)
base_msg = (
"Login attempt or request with invalid authentication from"
+79
View File
@@ -4,6 +4,8 @@ from http import HTTPStatus
from ipaddress import ip_address
import logging
import os
from socket import gaierror, herror
import threading
from typing import NoReturn
from unittest.mock import AsyncMock, Mock, mock_open, patch
@@ -463,6 +465,83 @@ async def test_failed_login_attempts_counter(
assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2
@pytest.mark.parametrize(
("lookup_error", "lookup_delay", "reverse_dns_timeout"),
[
pytest.param(None, 10, 0, id="slow_lookup"),
pytest.param(herror(1, "Unknown host"), 0, 1, id="herror"),
pytest.param(
gaierror(-3, "Temporary failure in name resolution"),
0,
1,
id="gaierror",
),
pytest.param(
UnicodeEncodeError("idna", "fe80::1%..", 9, 10, "label empty"),
0,
1,
id="unencodable_scope_id",
),
],
)
async def test_failed_login_reverse_dns_failure(
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
lookup_error: Exception | None,
lookup_delay: float,
reverse_dns_timeout: float,
) -> None:
"""Test that a slow or failing reverse DNS lookup still records the failed login."""
app = web.Application()
app[KEY_HASS] = hass
async def unauth_handler(request):
"""Return a mock web response."""
raise HTTPUnauthorized
app.router.add_get("/", unauth_handler)
setup_bans(hass, app, 5)
mock_real_ip(app)("200.201.202.204")
client = await aiohttp_client(app)
release_lookup = threading.Event()
lookup = Mock(side_effect=lookup_error, return_value=("example.com", [], []))
def fake_gethostbyaddr(ip: str) -> tuple[str, list[str], list[str]]:
"""Wait out the delay, then defer to the lookup mock."""
release_lookup.wait(lookup_delay)
return lookup(ip)
# Patch with a plain function so the test hass runs it in the executor
with (
patch(
"homeassistant.components.http.ban.gethostbyaddr",
fake_gethostbyaddr,
),
patch(
"homeassistant.components.http.ban.REVERSE_DNS_TIMEOUT",
reverse_dns_timeout,
),
):
resp = await client.get("/")
release_lookup.set()
assert resp.status == HTTPStatus.UNAUTHORIZED
assert app[KEY_FAILED_LOGIN_ATTEMPTS][ip_address("200.201.202.204")] == 1
assert (
"Login attempt or request with invalid authentication"
" from 200.201.202.204 (200.201.202.204)." in caplog.text
)
notifications = async_get_persistent_notifications(hass)
assert (
notifications["http-login"]["message"]
== "Login attempt or request with invalid authentication"
" from 200.201.202.204 (200.201.202.204)."
" See the log for details."
)
async def test_failed_login_attempts_counter_reverse_dns_unicode_decode_error(
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
) -> None: