From 1f8f884207beca7408057e94a001eafac05cde7d Mon Sep 17 00:00:00 2001 From: anor Date: Sat, 18 Jul 2026 20:35:34 +1000 Subject: [PATCH] =?UTF-8?q?fix(security):=20=D0=B1=D0=BB=D0=BE=D0=BA=20?= =?UTF-8?q?=E2=91=A4=20=E2=80=94=20=D0=BA=D1=80=D0=B8=D0=BF=D1=82=D0=B0=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=BE=D0=BB=D0=B5=D0=B9=20PBKDF2=20+=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B0=D0=BB=D1=8C=D0=BD=D0=B0=D1=8F=20=D0=B1=D0=BB?= =?UTF-8?q?=D0=BE=D0=BA=D0=B8=D1=80=D0=BE=D0=B2=D0=BA=D0=B0=20+=20rate-lim?= =?UTF-8?q?it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Пароли: одиночный SHA-256 → PBKDF2-HMAC-SHA256 (200k итераций). check_password поддерживает старый формат salt:sha256 → при успешном логине хэш прозрачно апгрейдится в БД (update_password_hash). Существующие юзеры не ломаются. - refresh_access_token теперь смотрит в БД: заблокированный/удалённый юзер больше не обновляет токен (была дыра — жил до 7 дней, кнопка «заблокировать» не работала). - verify-email: rate-limit 10 попыток/10мин на email (6-значный код без лимита брутился). - register: проверка существующего email ДО сжигания инвайта (была потеря приглашения на опечатке/повторе); + отвергаем email с '/'/'\\' (path-компонент). Тесты: pbkdf2+legacy, апгрейд при логине, blocked→refresh None, verify rate-limit, инвайт не сгорает. 304 passed. Co-Authored-By: Claude Opus 4.8 (1M context) --- auth.py | 66 ++++++++++++++++------ db.py | 9 +++ tests/test_auth_hardening.py | 104 +++++++++++++++++++++++++++++++++++ 3 files changed, 163 insertions(+), 16 deletions(-) create mode 100644 tests/test_auth_hardening.py diff --git a/auth.py b/auth.py index 7c2d838..39a5805 100644 --- a/auth.py +++ b/auth.py @@ -50,21 +50,34 @@ def _record_attempt(key: str): _login_attempts.setdefault(key, []).append(time.time()) +_PBKDF2_ITERS = 200_000 # OWASP-совместимо для pbkdf2-sha256; логин редкий → накладные ок + + def hash_password(password: str) -> str: - """Hash password with salt using SHA-256.""" + """Hash password with PBKDF2-HMAC-SHA256 (было: одиночный SHA-256 — брутился на GPU).""" salt = secrets.token_hex(16) - h = hashlib.sha256((salt + password).encode()).hexdigest() - return f"{salt}:{h}" + dk = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), _PBKDF2_ITERS) + return f"pbkdf2_sha256${_PBKDF2_ITERS}${salt}${dk.hex()}" def check_password(password: str, password_hash: str) -> bool: - """Verify password against stored hash.""" - if ":" not in password_hash: - return False - salt, h = password_hash.split(":", 1) - return hmac.compare_digest( - hashlib.sha256((salt + password).encode()).hexdigest(), h - ) + """Verify password. Поддерживает НОВЫЙ pbkdf2 и СТАРЫЙ salt:sha256 (для апгрейда).""" + if password_hash.startswith("pbkdf2_sha256$"): + try: + _, iters, salt, h = password_hash.split("$", 3) + dk = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), int(iters)) + return hmac.compare_digest(dk.hex(), h) + except (ValueError, TypeError): + return False + if ":" in password_hash: # legacy: salt:sha256hex (одиночный раунд) + salt, h = password_hash.split(":", 1) + return hmac.compare_digest(hashlib.sha256((salt + password).encode()).hexdigest(), h) + return False + + +def needs_rehash(password_hash: str) -> bool: + """Старый формат хэша → пересчитать на pbkdf2 при следующем успешном логине.""" + return not password_hash.startswith("pbkdf2_sha256$") def _make_token(username: str, role: str = "user") -> str: @@ -96,9 +109,18 @@ def refresh_access_token(refresh_token: str) -> str | None: payload = jwt.decode(refresh_token, SECRET, algorithms=[ALGORITHM]) if payload.get("type") != "refresh": return None - return _make_token(payload["sub"], payload.get("role", "user")) + sub = payload["sub"] + role = payload.get("role", "user") except Exception: return None + # Заблокированный/удалённый юзер НЕ должен обновлять токен (был жив до 7 дней — + # кнопка «заблокировать» фактически не работала). Legacy env-admin в БД нет — пропускаем. + if not (LEGACY_USER and sub == LEGACY_USER): + from db import get_user_by_email + u = get_user_by_email(sub) + if not u or u.get("blocked"): + return None + return _make_token(sub, role) def authenticate(username: str, password: str, client_ip: str = "") -> str | None: @@ -124,6 +146,12 @@ def authenticate(username: str, password: str, client_ip: str = "") -> str | Non from db import get_user_by_email user = get_user_by_email(username) # username = email if user and user["verified"] and not user.get("blocked") and check_password(password, user["password_hash"]): + if needs_rehash(user["password_hash"]): # прозрачный апгрейд sha256 → pbkdf2 + try: + from db import update_password_hash + update_password_hash(user["email"], hash_password(password)) + except Exception: # noqa: BLE001 — апгрейд не должен ломать вход + logger.exception("password rehash failed") return _make_token(user["email"], role=user["role"]) if ip_key: @@ -141,19 +169,19 @@ def register_user(email: str, password: str, invite_token: str) -> dict: from db import get_user_by_email, create_user, use_invite, set_verify_code email = email.lower().strip() - if not email or "@" not in email: + if not email or "@" not in email or "/" in email or "\\" in email: return {"ok": False, "error": "Некорректный email"} if len(password) < 6: return {"ok": False, "error": "Пароль минимум 6 символов"} + # Проверяем существование ДО сжигания инвайта (иначе опечатка/повтор жгла приглашение — Fable). + if get_user_by_email(email): + return {"ok": False, "error": "Пользователь с таким email уже существует"} + # Check invite if not use_invite(invite_token, email): return {"ok": False, "error": "Недействительная или использованная ссылка-приглашение"} - # Check existing user - if get_user_by_email(email): - return {"ok": False, "error": "Пользователь с таким email уже существует"} - # Create user pw_hash = hash_password(password) create_user(email, pw_hash) @@ -168,8 +196,14 @@ def register_user(email: str, password: str, invite_token: str) -> dict: def verify_email(email: str, code: str) -> dict: """Verify email with code. Returns {"ok": True} or {"ok": False, "error": ...}.""" from db import verify_user + email = (email or "").lower().strip() + # Rate-limit: 6-значный код (1M вариантов, TTL 10мин) без лимита брутился (Fable). + vkey = f"verify:{email}" + if _is_locked(vkey, max_attempts=10, window=600): + return {"ok": False, "error": "Слишком много попыток. Попробуйте позже."} if verify_user(email, code): return {"ok": True, "message": "Email подтверждён. Можете войти."} + _record_attempt(vkey) return {"ok": False, "error": "Неверный или просроченный код"} diff --git a/db.py b/db.py index 638d664..20ec038 100644 --- a/db.py +++ b/db.py @@ -192,6 +192,15 @@ def get_user_by_email(email: str) -> dict | None: return dict(row) if row else None +def update_password_hash(email: str, password_hash: str): + """Прозрачный апгрейд формата хэша при успешном логине (sha256 → pbkdf2).""" + with _conn() as conn: + conn.execute( + "UPDATE users SET password_hash = ? WHERE email = ?", + (password_hash, email.lower().strip()), + ) + + def set_verify_code(email: str, code: str, expires_in: int = 600): with _conn() as conn: conn.execute( diff --git a/tests/test_auth_hardening.py b/tests/test_auth_hardening.py new file mode 100644 index 0000000..5b1d390 --- /dev/null +++ b/tests/test_auth_hardening.py @@ -0,0 +1,104 @@ +"""Block ⑤ auth hardening (Fable audit 2026-07-18): +PBKDF2 + обратная совместимость, прозрачный апгрейд, блокировка при refresh, +rate-limit verify-email, инвайт не сгорает на существующем email. +""" +import hashlib +import importlib +import os +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + + +@pytest.fixture() +def a(monkeypatch, tmp_path): + monkeypatch.setenv("SESSION_SECRET", "test-secret") + monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db")) + monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "ext")) + import auth, db + importlib.reload(db) + importlib.reload(auth) + db.init_db() + auth._login_attempts.clear() + return auth, db + + +# ---- PBKDF2 + обратная совместимость ---- + +def test_new_hash_is_pbkdf2_and_verifies(a): + auth, _ = a + h = auth.hash_password("Secret123") + assert h.startswith("pbkdf2_sha256$") + assert auth.check_password("Secret123", h) + assert not auth.check_password("wrong", h) + assert not auth.needs_rehash(h) + + +def test_legacy_sha256_still_verifies_and_flags_rehash(a): + auth, _ = a + salt = "abcd1234" + legacy = f"{salt}:{hashlib.sha256((salt + 'Secret123').encode()).hexdigest()}" + assert auth.check_password("Secret123", legacy) # старый вход не сломан + assert not auth.check_password("wrong", legacy) + assert auth.needs_rehash(legacy) # помечен на апгрейд + + +def test_login_upgrades_legacy_hash_transparently(a): + auth, db = a + salt = "abcd1234" + legacy = f"{salt}:{hashlib.sha256((salt + 'Secret123').encode()).hexdigest()}" + db.create_user("u@x.com", legacy) + db.get_user_by_email("u@x.com") # ensure exists + with db._conn() as c: + c.execute("UPDATE users SET verified=1 WHERE email='u@x.com'") + tok = auth.authenticate("u@x.com", "Secret123", client_ip="1.2.3.4") + assert tok # вход прошёл + stored = db.get_user_by_email("u@x.com")["password_hash"] + assert stored.startswith("pbkdf2_sha256$") # хэш апгрейднут в БД + + +# ---- блокировка реально действует при refresh ---- + +def test_blocked_user_cannot_refresh(a): + auth, db = a + db.create_user("b@x.com", auth.hash_password("Secret123")) + with db._conn() as c: + c.execute("UPDATE users SET verified=1 WHERE email='b@x.com'") + rt = auth._make_refresh_token("b@x.com", "user") + assert auth.refresh_access_token(rt) # пока не заблокирован — ок + db.block_user("b@x.com", True) + assert auth.refresh_access_token(rt) is None # заблокирован → refresh мёртв + + +def test_deleted_user_cannot_refresh(a): + auth, db = a + rt = auth._make_refresh_token("ghost@x.com", "user") + assert auth.refresh_access_token(rt) is None # нет в БД → None + + +# ---- verify-email rate-limit ---- + +def test_verify_email_rate_limited(a): + auth, db = a + db.create_user("v@x.com", auth.hash_password("Secret123")) + db.set_verify_code("v@x.com", "111111") + for _ in range(10): + auth.verify_email("v@x.com", "000000") # неверные коды + r = auth.verify_email("v@x.com", "111111") # даже верный — залочен + assert not r["ok"] and "попыток" in r["error"] + + +# ---- инвайт не сгорает на существующем email ---- + +def test_invite_not_burned_on_existing_email(a, monkeypatch): + auth, db = a + calls = {"used": []} + monkeypatch.setattr("db.use_invite", lambda tok, email: calls["used"].append(tok) or True) + db.create_user("dup@x.com", auth.hash_password("Secret123")) + r = auth.register_user("dup@x.com", "Secret123", "invite-xyz") + assert not r["ok"] and "уже существует" in r["error"] + assert calls["used"] == [] # инвайт НЕ тронут