feat: harden authentication (Argon2id by measurement, login limits, body limit)
Apply auth-hardening up to the bench_login label: Argon2id parameters from [auth] chosen by driver.py argon2-params (m=64 MiB, t=2, p=1), rehash on login, per-process KDF budget with 429, shared login failure limit in Valkey with a local fallback, X-Forwarded-For from HAProxy, 64 KiB body limit (400) in LB and middleware, bench login profile, tests, threat model and trust matrix rows. Hypotheses H1-H4 are committed here before the baseline label. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -55,7 +55,12 @@
|
||||
auth-storage только стенд с LB: сценарии sessions «Токена нет в
|
||||
хранилище» и users «Хэш в БД» — префиксы Argon2id и разные
|
||||
хэши одного пароля, token_hash = SHA-256 токена, ни токена,
|
||||
ни пароля в pg_dump; секреты не печатаются
|
||||
ни пароля в pg_dump; секреты не печатаются. С change
|
||||
auth-hardening — параметры строки хэша равны «Started API» и не
|
||||
ниже базовых, пересчёт хэша прежних параметров при входе (и его
|
||||
нет у неудачного), журнал API за время команды (регистрация,
|
||||
вход, 401, 429 предела, выход) без username, пароля, токена и
|
||||
значения Authorization; код 1 при нарушении
|
||||
s3-check стенд compose (make s3_check), без приложения: спек
|
||||
object-storage «Проверка приватности вне API» — bootstrap S3
|
||||
в режиме check (права ключа API, чужой bucket,
|
||||
@@ -1258,13 +1263,18 @@ def cmd_kill_inflight(
|
||||
f" LB error {status}: {json.dumps(error, ensure_ascii=False)}"
|
||||
f" request_id == X-Request-Id: {same_id}",
|
||||
)
|
||||
# с change auth-hardening бюджет хэшей процесса (1 место, 16 ждущих,
|
||||
# 2 с) может ответить 429 одновременным входам — допустимый исход,
|
||||
# отдельный счёт
|
||||
budget = sum(status == 429 for status, _, _, _ in results)
|
||||
print(f"429 of the hash budget (allowed): {budget}")
|
||||
print(f"replica {target} is left stopped; restore: make replicas")
|
||||
if hook.returncode != 0:
|
||||
return 1
|
||||
if not cut:
|
||||
print("no request was in flight on the killed replica: repeat")
|
||||
return 1
|
||||
unexpected = {status for status, _, _, _ in results} - {201, 502}
|
||||
unexpected = {status for status, _, _, _ in results} - {201, 429, 502}
|
||||
return 1 if unexpected else 0
|
||||
|
||||
|
||||
@@ -2006,6 +2016,7 @@ def cmd_auth_storage(port: int) -> int:
|
||||
до соли; дамп базы читается в память и никуда не пишется."""
|
||||
if no_lb(port):
|
||||
return 1
|
||||
started = time.time()
|
||||
password = f"Пароль:{secrets.token_urlsafe(18)}:ключ"
|
||||
# вход только первого: второй нужен лишь для второго хэша того же P
|
||||
first = synthetic_user(port, "auth", password)
|
||||
@@ -2072,13 +2083,199 @@ def cmd_auth_storage(port: int) -> int:
|
||||
problems.append(f"sessions rows {count}, token_hash {length} bytes")
|
||||
if token_text or token_hex or password_text:
|
||||
problems.append("T or P found in the dump")
|
||||
problems += auth_hardening_checks(port, hashes, started)
|
||||
if problems:
|
||||
print("FAIL: " + "; ".join(problems))
|
||||
return 1
|
||||
print("PASS: only Argon2id strings and SHA-256 of the token are stored")
|
||||
print(
|
||||
"PASS: only Argon2id strings of the configured parameters and SHA-256 "
|
||||
"of the token are stored; old hashes are rehashed on login; the API "
|
||||
"journal has no credentials",
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
# change auth-hardening (design, решения 1, 2, 9): базовая конфигурация
|
||||
# Argon2id рубрики и прежний профиль RFC 9106 low-memory
|
||||
ARGON2_BASE = {"m": 19456, "t": 2, "p": 1}
|
||||
ARGON2_OLD_PREFIX = "$argon2id$v=19$m=65536,t=3,p=4"
|
||||
OLD_HASH_PY = (
|
||||
"import sys\n"
|
||||
"from argon2 import PasswordHasher, profiles\n"
|
||||
"print(PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY)"
|
||||
".hash(sys.stdin.read()))\n"
|
||||
)
|
||||
|
||||
|
||||
def hash_params(prefix: str) -> dict[str, int]:
|
||||
"""`m`, `t`, `p` из префикса строки Argon2id."""
|
||||
parts = prefix.split("$")
|
||||
if len(parts) < 4:
|
||||
return {}
|
||||
return {
|
||||
key: int(value)
|
||||
for key, _, value in (
|
||||
item.partition("=") for item in parts[3].split(",")
|
||||
)
|
||||
if value.isdigit()
|
||||
}
|
||||
|
||||
|
||||
def stored_prefix(username: str) -> str:
|
||||
# username — синтетический [a-z0-9_]: безопасен в тексте SQL
|
||||
return stand_psql(
|
||||
"SELECT array_to_string((string_to_array(password_hash, '$'))[1:4], "
|
||||
f"'$') FROM users WHERE username = '{username}';\n",
|
||||
).strip()
|
||||
|
||||
|
||||
def set_old_hash(username: str, password: str) -> None:
|
||||
"""Хэш прежних параметров пользователю: считает Python образа API (пароль
|
||||
— stdin), записывает psql."""
|
||||
# реплика по ID: после make rolling_update номера контейнеров растут, и
|
||||
# `exec --index 1` не находит первую
|
||||
replica = compose("ps", "-q", "api").split()[0]
|
||||
old = subprocess.run(
|
||||
["docker", "exec", "-i", replica, "python", "-c", OLD_HASH_PY],
|
||||
input=password,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout.strip()
|
||||
if not old.startswith(ARGON2_OLD_PREFIX):
|
||||
raise RuntimeError("old hash was not computed")
|
||||
stand_psql(
|
||||
f"UPDATE users SET password_hash = '{old}' "
|
||||
f"WHERE username = '{username}';\n",
|
||||
)
|
||||
|
||||
|
||||
def started_auth() -> dict[str, object]:
|
||||
"""Поля `auth_*` записи «Started API» первой реплики."""
|
||||
for line in compose("logs", "--no-log-prefix", "api").splitlines():
|
||||
if '"Started API"' in line and line.startswith("{"):
|
||||
record = json.loads(line)
|
||||
return {k: v for k, v in record.items() if k.startswith("auth_")}
|
||||
return {}
|
||||
|
||||
|
||||
def auth_hardening_checks(
|
||||
port: int,
|
||||
hashes: list[list[str]],
|
||||
since: float,
|
||||
) -> list[str]:
|
||||
"""Параметры строки хэша, пересчёт при входе и журнал без credentials
|
||||
(change auth-hardening, задача 10.1)."""
|
||||
problems = []
|
||||
fields = started_auth()
|
||||
expected = {
|
||||
"m": fields.get("auth_argon2_memory_kib"),
|
||||
"t": fields.get("auth_argon2_time_cost"),
|
||||
"p": fields.get("auth_argon2_parallelism"),
|
||||
}
|
||||
print(
|
||||
"configured Argon2id (Started API): m={m} KiB, t={t}, p={p}".format(
|
||||
**expected,
|
||||
),
|
||||
)
|
||||
for prefix, _ in hashes:
|
||||
params = hash_params(prefix)
|
||||
if params != expected:
|
||||
problems.append(f"hash parameters {params} != configured")
|
||||
if any(params.get(k, 0) < v for k, v in ARGON2_BASE.items()):
|
||||
problems.append(f"hash parameters {params} below the base")
|
||||
# пересчёт: хэш прежних параметров, вход — новые; неудачный — прежний
|
||||
password = f"Rehash:{secrets.token_urlsafe(18)}"
|
||||
rehashed = register_user(port, "rehash", password)
|
||||
kept = register_user(port, "rehash", password)
|
||||
if rehashed is None or kept is None:
|
||||
return [*problems, "rehash users were not registered"]
|
||||
names = (str(rehashed["username"]), str(kept["username"]))
|
||||
for name in names:
|
||||
set_old_hash(name, password)
|
||||
old = [stored_prefix(name) for name in names]
|
||||
good = call(
|
||||
port,
|
||||
"POST",
|
||||
SESSIONS,
|
||||
authorization=basic(names[0], password),
|
||||
)
|
||||
bad = call(
|
||||
port,
|
||||
"POST",
|
||||
SESSIONS,
|
||||
authorization=basic(names[1], password + "-wrong"),
|
||||
)
|
||||
new = [stored_prefix(name) for name in names]
|
||||
print(
|
||||
f"rehash: user {short_name(names[0])} {old[0]} → login {good[0]} → "
|
||||
f"{new[0]}; user {short_name(names[1])} {old[1]} → wrong password "
|
||||
f"{bad[0]} → {new[1]}",
|
||||
)
|
||||
if good[0] != 201 or hash_params(new[0]) != expected:
|
||||
problems.append("old hash was not rehashed on login")
|
||||
if bad[0] != 401 or new[1] != ARGON2_OLD_PREFIX:
|
||||
problems.append("failed login changed the stored hash")
|
||||
# журнал API за время команды: регистрация, вход, 401, 429 предела и
|
||||
# выход — без username, пароля, токена и значения Authorization
|
||||
secret = f"Journal:{secrets.token_urlsafe(18)}"
|
||||
first = synthetic_user(port, "journal", secret)
|
||||
if first is None:
|
||||
return [*problems, "journal user was not registered"]
|
||||
user, token = first
|
||||
username = str(user["username"])
|
||||
statuses = []
|
||||
for _ in range(11):
|
||||
statuses.append(
|
||||
call(
|
||||
port,
|
||||
"POST",
|
||||
SESSIONS,
|
||||
authorization=basic(username, secret + "-wrong"),
|
||||
)[0],
|
||||
)
|
||||
call(port, "DELETE", f"{SESSIONS}/current", token=token)
|
||||
journal = compose(
|
||||
"logs",
|
||||
"--no-log-prefix",
|
||||
"--since",
|
||||
f"{since:.3f}",
|
||||
"api",
|
||||
)
|
||||
values = {
|
||||
"username": username,
|
||||
"password": secret,
|
||||
"token": token,
|
||||
"Authorization": basic(username, secret).split(" ", 1)[1],
|
||||
"wrong Authorization": basic(username, secret + "-wrong").split(
|
||||
" ",
|
||||
1,
|
||||
)[1],
|
||||
"rehash password": password,
|
||||
}
|
||||
found = [name for name, value in values.items() if value in journal]
|
||||
events = Counter(
|
||||
json.loads(line).get("event")
|
||||
for line in journal.splitlines()
|
||||
if line.startswith("{")
|
||||
)
|
||||
print(
|
||||
f"journal since the command: {sum(events.values())} records, "
|
||||
f"'Login failed' {events['Login failed']}, 'Login rate limited' "
|
||||
f"{events['Login rate limited']}, 'Rehashed password' "
|
||||
f"{events['Rehashed password']}; failed logins of one pair: "
|
||||
f"{Counter(statuses)}; credentials in the journal: "
|
||||
f"{', '.join(found) or 'none'}",
|
||||
)
|
||||
if statuses[-1] != 429 or 429 in statuses[:-1]:
|
||||
problems.append(f"pair limit statuses {statuses}")
|
||||
if found:
|
||||
problems.append(f"journal contains {', '.join(found)}")
|
||||
if not events["Rehashed password"]:
|
||||
problems.append("no 'Rehashed password' record")
|
||||
return problems
|
||||
|
||||
|
||||
# s3-check: проверочный объект режима check bootstrap S3
|
||||
S3_CHECK_KEY = ".s3-check/probe"
|
||||
# строки проверок bootstrap: «s3-bootstrap: check<TAB>имя<TAB>ожидаемо…»
|
||||
@@ -16204,7 +16401,12 @@ def cmd_argon2_params(*, image: str, kdf_concurrency: int) -> int:
|
||||
)
|
||||
return 2
|
||||
info = subprocess.run(
|
||||
["docker", "info", "-f", "{{.NCPU}} CPU, {{.MemTotal}} B, {{.OSType}}"],
|
||||
[
|
||||
"docker",
|
||||
"info",
|
||||
"-f",
|
||||
"{{.NCPU}} CPU, {{.MemTotal}} B, {{.OSType}}",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
|
||||
Reference in New Issue
Block a user