Initial commit
This commit is contained in:
186
app/auth.py
Normal file
186
app/auth.py
Normal file
@@ -0,0 +1,186 @@
|
||||
"""HTTP Basic authentication, with a throttle on failed attempts.
|
||||
|
||||
Basic is the only scheme every OPDS reader UI can drive: the reader prompts for a
|
||||
user name and password, and the server answers an unauthenticated request with
|
||||
``401`` and a ``WWW-Authenticate`` header. That header is also the whole reason
|
||||
this service must sit behind TLS -- the credentials travel base64-encoded, which
|
||||
is encoding, not encryption.
|
||||
|
||||
Two things this module is careful about:
|
||||
|
||||
*The comparison is constant time.* Passwords are stored as sha256 digests
|
||||
(``make hash-password``) and compared with :func:`hmac.compare_digest`, and an
|
||||
unknown user name is compared against a dummy digest so that a missing account and
|
||||
a wrong password take the same time. Otherwise the response time tells an
|
||||
attacker which half of the guess was right.
|
||||
|
||||
*Failures are throttled.* Basic auth can be guessed at line speed, so an address
|
||||
that fails repeatedly is refused for a cooling-off period before its credentials
|
||||
are even examined.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from app import config as app_config
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# Compared against when the user name is unknown, so that the work done -- and
|
||||
# therefore the time taken -- does not depend on whether the account exists.
|
||||
_DUMMY_DIGEST = hashlib.sha256(b"no such user").hexdigest()
|
||||
|
||||
|
||||
class UnauthorizedError(Exception):
|
||||
"""Credentials were missing, malformed, or wrong. Answered with 401."""
|
||||
|
||||
def __init__(self, message: str = "authentication required") -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class RateLimitedError(Exception):
|
||||
"""Too many failed attempts from this address. Answered with 429."""
|
||||
|
||||
def __init__(self, retry_after: int) -> None:
|
||||
super().__init__("too many failed authentication attempts")
|
||||
self.retry_after = max(1, int(retry_after))
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Attempts:
|
||||
"""Failed-attempt bookkeeping for one client address."""
|
||||
|
||||
timestamps: list[float] = field(default_factory=list)
|
||||
|
||||
def within_window(self, now: float, window: float) -> int:
|
||||
return sum(1 for moment in self.timestamps if now - moment < window)
|
||||
|
||||
|
||||
class Authenticator:
|
||||
"""Checks Basic credentials and throttles repeated failures."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: app_config.AuthConfig,
|
||||
*,
|
||||
clock=time.monotonic,
|
||||
) -> None:
|
||||
self._config = config
|
||||
self._clock = clock
|
||||
# Digest lookups avoid a linear scan that would leak user names by timing.
|
||||
self._users = {user.username: user.password_sha256 for user in config.users}
|
||||
self._lock = threading.Lock()
|
||||
self._attempts: dict[str, _Attempts] = {}
|
||||
|
||||
@property
|
||||
def challenge(self) -> str:
|
||||
"""The ``WWW-Authenticate`` value that makes a reader prompt."""
|
||||
realm = self._config.realm.replace('"', "")
|
||||
return f'Basic realm="{realm}", charset="UTF-8"'
|
||||
|
||||
def authenticate(self, authorization: str | None, client: str) -> str:
|
||||
"""Return the authenticated user name, or raise.
|
||||
|
||||
``client`` identifies the address for throttling; only failed attempts are
|
||||
counted, and a success clears the record.
|
||||
"""
|
||||
self._check_throttle(client)
|
||||
username, password = _parse_basic(authorization)
|
||||
if username is None or not self._matches(username, password):
|
||||
self._record_failure(client)
|
||||
# The source address is what matters for spotting a brute-force run, so
|
||||
# that is the warning. The attempted name is attacker-supplied and
|
||||
# close to an identifier, so it is kept for debugging only, and the
|
||||
# password is never logged at any level.
|
||||
LOGGER.warning("rejected authentication attempt from %s", client)
|
||||
LOGGER.debug("rejected credentials for user %r from %s", username, client)
|
||||
raise UnauthorizedError
|
||||
self._clear_failures(client)
|
||||
return username
|
||||
|
||||
def _matches(self, username: str, password: str | None) -> bool:
|
||||
if password is None:
|
||||
return False
|
||||
expected = self._users.get(username, _DUMMY_DIGEST)
|
||||
offered = hashlib.sha256(password.encode("utf-8")).hexdigest()
|
||||
return hmac.compare_digest(expected, offered)
|
||||
|
||||
# -- throttling ------------------------------------------------------
|
||||
|
||||
def _check_throttle(self, client: str) -> None:
|
||||
window = self._config.throttle_seconds
|
||||
with self._lock:
|
||||
record = self._attempts.get(client)
|
||||
if record is None:
|
||||
return
|
||||
now = self._clock()
|
||||
recent = record.within_window(now, window)
|
||||
if recent < self._config.max_failures_per_minute:
|
||||
return
|
||||
oldest = min(record.timestamps)
|
||||
retry_after = max(1, int(window - (now - oldest)) + 1)
|
||||
raise RateLimitedError(retry_after)
|
||||
|
||||
def _record_failure(self, client: str) -> None:
|
||||
now = self._clock()
|
||||
window = self._config.throttle_seconds
|
||||
with self._lock:
|
||||
record = self._attempts.setdefault(client, _Attempts())
|
||||
record.timestamps.append(now)
|
||||
# Trim anything that has aged out, and drop the record entirely when
|
||||
# it is empty, so a long uptime cannot accumulate addresses.
|
||||
record.timestamps = [moment for moment in record.timestamps if now - moment < window]
|
||||
if not record.timestamps:
|
||||
del self._attempts[client]
|
||||
elif len(self._attempts) > 4096:
|
||||
self._evict_oldest(now, window)
|
||||
|
||||
def _clear_failures(self, client: str) -> None:
|
||||
with self._lock:
|
||||
self._attempts.pop(client, None)
|
||||
|
||||
def _evict_oldest(self, now: float, window: float) -> None:
|
||||
"""Bound the table: a flood of addresses must not become a memory leak."""
|
||||
stale = [
|
||||
address
|
||||
for address, record in self._attempts.items()
|
||||
if not record.within_window(now, window)
|
||||
]
|
||||
for address in stale:
|
||||
del self._attempts[address]
|
||||
while len(self._attempts) > 4096:
|
||||
oldest = min(
|
||||
self._attempts,
|
||||
key=lambda address: min(self._attempts[address].timestamps),
|
||||
)
|
||||
del self._attempts[oldest]
|
||||
|
||||
|
||||
def _parse_basic(authorization: str | None) -> tuple[str | None, str | None]:
|
||||
"""Split a Basic header into its credentials.
|
||||
|
||||
Returns ``(None, None)`` for anything that is not a well-formed Basic header,
|
||||
which the caller treats exactly like a wrong password.
|
||||
"""
|
||||
if not authorization:
|
||||
return None, None
|
||||
scheme, _, payload = authorization.partition(" ")
|
||||
if scheme.lower() != "basic" or not payload:
|
||||
return None, None
|
||||
try:
|
||||
decoded = base64.b64decode(payload.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
return None, None
|
||||
# Only the first colon separates: a password may contain colons.
|
||||
username, separator, password = decoded.partition(":")
|
||||
if not separator or not username:
|
||||
return None, None
|
||||
return username, password
|
||||
Reference in New Issue
Block a user