1.0.0
Wydanie WGTools-Extended / release (push) Failing after 16s

This commit is contained in:
asminme committed 2026-10-30 00:35:08 +01:00
1 parent f5bdd7e21c
commit affe28ad71
110 files changed
+52936 -14

No files matched your search

+529
View File
@@ -0,0 +1,529 @@
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import re
import secrets
import sqlite3
import struct
import time
from pathlib import Path
from typing import Any
from urllib.parse import quote, urlencode
from .mail_config import normalize_email
from .settings import DATABASE_PATH, SESSION_KEY_FILE
PBKDF2_ITERATIONS = 390_000
TOTP_DIGITS = 6
TOTP_PERIOD = 30
TOTP_WINDOW = 1
RECOVERY_CODE_COUNT = 10
RECOVERY_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
def _connect() -> sqlite3.Connection:
Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DATABASE_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA foreign_keys=ON")
return conn
def init_database() -> None:
with _connect() as conn:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL COLLATE NOCASE UNIQUE,
email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
iterations INTEGER NOT NULL,
session_version INTEGER NOT NULL DEFAULT 1,
mfa_enabled INTEGER NOT NULL DEFAULT 0,
mfa_secret TEXT NOT NULL DEFAULT '',
mfa_recovery_codes TEXT NOT NULL DEFAULT '[]',
mfa_confirmed_at INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
last_login INTEGER
);
"""
)
columns = {str(row[1]) for row in conn.execute("PRAGMA table_info(users)").fetchall()}
if "email" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN email TEXT NOT NULL DEFAULT ''")
if "session_version" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN session_version INTEGER NOT NULL DEFAULT 1")
if "mfa_enabled" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN mfa_enabled INTEGER NOT NULL DEFAULT 0")
if "mfa_secret" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN mfa_secret TEXT NOT NULL DEFAULT ''")
if "mfa_recovery_codes" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN mfa_recovery_codes TEXT NOT NULL DEFAULT '[]'")
if "mfa_confirmed_at" not in columns:
conn.execute("ALTER TABLE users ADD COLUMN mfa_confirmed_at INTEGER NOT NULL DEFAULT 0")
conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_unique ON users(lower(email)) WHERE email<>''"
)
conn.execute("CREATE TABLE IF NOT EXISTS user_access (user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, role TEXT NOT NULL, interfaces TEXT NOT NULL DEFAULT '[]')")
access_columns = {str(row[1]) for row in conn.execute("PRAGMA table_info(user_access)")}
if 'permissions' not in access_columns:
conn.execute("ALTER TABLE user_access ADD COLUMN permissions TEXT NOT NULL DEFAULT '{}'")
def get_user_access(user_id: int) -> dict[str, Any]:
init_database()
with _connect() as conn:
row = conn.execute("SELECT role,interfaces,permissions FROM user_access WHERE user_id=?", (int(user_id),)).fetchone()
if row is None:
return {"role": "admin", "interfaces": [], "permissions": {}} # Existing installations keep their access.
interfaces = json.loads(row["interfaces"])
permissions = json.loads(row["permissions"])
# Accounts configured before per-action permissions retain their access.
if not permissions:
permissions = {iface: ['add', 'edit', 'forward'] for iface in interfaces}
return {"role": row["role"], "interfaces": interfaces, "permissions": permissions}
def set_user_access(user_id: int, role: str, interfaces: list[str], permissions: dict[str, list[str]] | None = None) -> dict[str, Any]:
if role not in {"admin", "user"}:
raise ValueError("Nieprawidłowa rola")
if len(interfaces) > 100 or any(not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", i) or i.lower().startswith(("wgrly", "wgnode")) for i in interfaces):
raise ValueError("Nieprawidłowa nazwa interfejsu")
if permissions is None:
permissions = {iface: ['add', 'edit', 'forward'] for iface in interfaces}
if set(permissions) != set(interfaces) or any(not isinstance(actions, list) or any(action not in {'add', 'edit', 'forward'} for action in actions) for actions in permissions.values()):
raise ValueError("Nieprawidłowe uprawnienia sieci")
init_database()
with _connect() as conn:
if not conn.execute("SELECT 1 FROM users WHERE id=?", (user_id,)).fetchone():
raise ValueError("Użytkownik nie istnieje")
conn.execute("INSERT INTO user_access(user_id,role,interfaces,permissions) VALUES(?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET role=excluded.role,interfaces=excluded.interfaces,permissions=excluded.permissions", (user_id, role, json.dumps(sorted(set(interfaces))), json.dumps(permissions)))
return get_user_access(user_id)
def load_session_secret() -> str:
path = Path(SESSION_KEY_FILE)
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(secrets.token_hex(32), encoding="utf-8")
path.chmod(0o600)
value = path.read_text(encoding="utf-8").strip()
if len(value) < 32:
raise RuntimeError("WGTools session secret is invalid")
return value
def _normalize_username(username: str) -> str:
value = username.strip()
if not (3 <= len(value) <= 64):
raise ValueError("Username must contain 3 to 64 characters")
if any(ord(ch) < 32 for ch in value):
raise ValueError("Username contains invalid characters")
return value
def _derive_password(password: str, salt: bytes, iterations: int = PBKDF2_ITERATIONS) -> str:
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
return base64.b64encode(digest).decode("ascii")
def _hash_password(password: str, salt: bytes, iterations: int = PBKDF2_ITERATIONS) -> str:
if len(password) < 8:
raise ValueError("Password must contain at least 8 characters")
return _derive_password(password, salt, iterations)
def _public_user(row: sqlite3.Row | dict[str, Any]) -> dict[str, Any]:
source = dict(row)
recovery = _load_recovery_hashes(str(source.get("mfa_recovery_codes") or "[]"))
return {
"id": int(source["id"]),
"username": str(source["username"]),
"email": str(source.get("email") or ""),
"session_version": int(source.get("session_version") or 1),
"mfa_enabled": bool(int(source.get("mfa_enabled") or 0)),
"mfa_recovery_remaining": len(recovery),
"mfa_confirmed_at": int(source.get("mfa_confirmed_at") or 0),
"created_at": int(source.get("created_at") or 0),
"last_login": int(source.get("last_login") or 0) or None,
}
def user_count() -> int:
init_database()
with _connect() as conn:
row = conn.execute("SELECT COUNT(*) AS c FROM users").fetchone()
return int(row["c"])
def create_user(username: str, password: str, email: str = "") -> dict[str, Any]:
init_database()
username = _normalize_username(username)
email = normalize_email(email, allow_empty=True)
salt = secrets.token_bytes(18)
encoded_salt = base64.b64encode(salt).decode("ascii")
password_hash = _hash_password(password, salt)
now = int(time.time())
try:
with _connect() as conn:
cur = conn.execute(
"INSERT INTO users(username,email,password_hash,salt,iterations,session_version,created_at) VALUES(?,?,?,?,?,?,?)",
(username, email, password_hash, encoded_salt, PBKDF2_ITERATIONS, 1, now),
)
user_id = int(cur.lastrowid)
if conn.execute("SELECT COUNT(*) FROM users").fetchone()[0] > 1:
conn.execute("INSERT INTO user_access(user_id,role,interfaces) VALUES(?, 'user', '[]')", (user_id,))
except sqlite3.IntegrityError as exc:
text = str(exc).lower()
if "email" in text or "idx_users_email_unique" in text:
raise ValueError("A user with this email already exists") from exc
raise ValueError("A user with this name already exists") from exc
return get_user(user_id) or {
"id": user_id,
"username": username,
"email": email,
"created_at": now,
"last_login": None,
"session_version": 1,
"mfa_enabled": False,
"mfa_recovery_remaining": 0,
"mfa_confirmed_at": 0,
}
def get_user(user_id: int) -> dict[str, Any] | None:
init_database()
with _connect() as conn:
row = conn.execute(
"""
SELECT id,username,email,session_version,mfa_enabled,mfa_recovery_codes,mfa_confirmed_at,created_at,last_login
FROM users WHERE id=?
""",
(int(user_id),),
).fetchone()
return _public_user(row) if row else None
def list_users() -> list[dict[str, Any]]:
init_database()
with _connect() as conn:
rows = conn.execute(
"""
SELECT id,username,email,session_version,mfa_enabled,mfa_recovery_codes,mfa_confirmed_at,created_at,last_login
FROM users ORDER BY username COLLATE NOCASE
"""
).fetchall()
return [_public_user(row) for row in rows]
def authenticate(username: str, password: str, *, record_login: bool = True) -> dict[str, Any] | None:
init_database()
with _connect() as conn:
row = conn.execute(
"""
SELECT id,username,email,password_hash,salt,iterations,session_version,
mfa_enabled,mfa_recovery_codes,mfa_confirmed_at,created_at,last_login
FROM users WHERE username=? COLLATE NOCASE
""",
(username.strip(),),
).fetchone()
if not row:
# Keep the code path somewhat similar for unknown users.
hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), b"wgtools-invalid-user", PBKDF2_ITERATIONS)
return None
salt = base64.b64decode(row["salt"])
candidate = _derive_password(password, salt, int(row["iterations"]))
if not hmac.compare_digest(candidate, row["password_hash"]):
return None
user = _public_user(row)
if record_login:
now = int(time.time())
conn.execute("UPDATE users SET last_login=? WHERE id=?", (now, int(row["id"])))
user["last_login"] = now
return user
def record_login_success(user_id: int) -> dict[str, Any]:
init_database()
now = int(time.time())
with _connect() as conn:
cur = conn.execute("UPDATE users SET last_login=? WHERE id=?", (now, int(user_id)))
if cur.rowcount != 1:
raise ValueError("User not found")
user = get_user(user_id)
if not user:
raise ValueError("User not found")
user["last_login"] = now
return user
def verify_password(user_id: int, password: str) -> bool:
init_database()
with _connect() as conn:
row = conn.execute("SELECT password_hash,salt,iterations FROM users WHERE id=?", (int(user_id),)).fetchone()
if not row:
return False
salt = base64.b64decode(row["salt"])
candidate = _derive_password(password, salt, int(row["iterations"]))
return hmac.compare_digest(candidate, row["password_hash"])
def set_password(user_id: int, password: str) -> None:
init_database()
salt = secrets.token_bytes(18)
encoded_salt = base64.b64encode(salt).decode("ascii")
password_hash = _hash_password(password, salt)
with _connect() as conn:
cur = conn.execute(
"UPDATE users SET password_hash=?,salt=?,iterations=?,session_version=session_version+1 WHERE id=?",
(password_hash, encoded_salt, PBKDF2_ITERATIONS, int(user_id)),
)
if cur.rowcount != 1:
raise ValueError("User not found")
reset_table = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='password_reset_codes'").fetchone()
if reset_table:
conn.execute(
"UPDATE password_reset_codes SET consumed_at=? WHERE user_id=? AND consumed_at=0",
(int(time.time()), int(user_id)),
)
def find_user_by_identifier(identifier: str) -> dict[str, Any] | None:
init_database()
value = str(identifier or "").strip()
if not value:
return None
with _connect() as conn:
row = conn.execute(
"""
SELECT id,username,email,session_version,mfa_enabled,mfa_recovery_codes,mfa_confirmed_at,created_at,last_login
FROM users
WHERE username=? COLLATE NOCASE OR email=? COLLATE NOCASE
LIMIT 1
""",
(value, value),
).fetchone()
return _public_user(row) if row else None
def update_user_email(user_id: int, email: str) -> dict[str, Any]:
init_database()
normalized = normalize_email(email, allow_empty=True)
try:
with _connect() as conn:
cur = conn.execute("UPDATE users SET email=? WHERE id=?", (normalized, int(user_id)))
if cur.rowcount != 1:
raise ValueError("User not found")
reset_table = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='password_reset_codes'").fetchone()
if reset_table:
conn.execute(
"UPDATE password_reset_codes SET consumed_at=? WHERE user_id=? AND consumed_at=0",
(int(time.time()), int(user_id)),
)
except sqlite3.IntegrityError as exc:
raise ValueError("A user with this email already exists") from exc
user = get_user(user_id)
if not user:
raise ValueError("User not found")
return user
def _normalize_totp_code(code: str) -> str:
return "".join(ch for ch in str(code or "") if ch.isdigit())
def _decode_totp_secret(secret: str) -> bytes:
value = "".join(str(secret or "").split()).upper()
padding = "=" * ((8 - len(value) % 8) % 8)
return base64.b32decode(value + padding, casefold=True)
def _totp_at(secret: str, timestamp: int) -> str:
key = _decode_totp_secret(secret)
counter = int(timestamp) // TOTP_PERIOD
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
offset = digest[-1] & 0x0F
binary = struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF
return str(binary % (10 ** TOTP_DIGITS)).zfill(TOTP_DIGITS)
def verify_totp(secret: str, code: str, *, now: int | None = None, window: int = TOTP_WINDOW) -> bool:
normalized = _normalize_totp_code(code)
if len(normalized) != TOTP_DIGITS:
return False
current = int(now or time.time())
for offset in range(-abs(int(window)), abs(int(window)) + 1):
expected = _totp_at(secret, current + offset * TOTP_PERIOD)
if hmac.compare_digest(expected, normalized):
return True
return False
def generate_mfa_secret() -> str:
return base64.b32encode(secrets.token_bytes(20)).decode("ascii").rstrip("=")
def mfa_provisioning_uri(username: str, secret: str) -> str:
label = quote(f"WGTools:{username}", safe="")
query = urlencode(
{
"secret": secret,
"issuer": "WGTools",
"algorithm": "SHA1",
"digits": str(TOTP_DIGITS),
"period": str(TOTP_PERIOD),
}
)
return f"otpauth://totp/{label}?{query}"
def _new_recovery_codes() -> list[str]:
codes: list[str] = []
for _ in range(RECOVERY_CODE_COUNT):
raw = "".join(secrets.choice(RECOVERY_ALPHABET) for _ in range(12))
codes.append(f"{raw[:4]}-{raw[4:8]}-{raw[8:]}")
return codes
def _normalize_recovery_code(code: str) -> str:
return "".join(ch for ch in str(code or "").upper() if ch.isalnum())
def _recovery_hash(code: str) -> str:
return hashlib.sha256(_normalize_recovery_code(code).encode("ascii", errors="ignore")).hexdigest()
def _load_recovery_hashes(value: str) -> list[str]:
try:
data = json.loads(value or "[]")
except Exception:
return []
if not isinstance(data, list):
return []
return [str(item) for item in data if isinstance(item, str) and item]
def begin_mfa_setup(user_id: int) -> dict[str, Any]:
init_database()
secret = generate_mfa_secret()
with _connect() as conn:
row = conn.execute("SELECT username,mfa_enabled FROM users WHERE id=?", (int(user_id),)).fetchone()
if not row:
raise ValueError("User not found")
if bool(int(row["mfa_enabled"] or 0)):
raise ValueError("MFA is already enabled")
conn.execute(
"UPDATE users SET mfa_secret=?,mfa_recovery_codes='[]',mfa_confirmed_at=0 WHERE id=?",
(secret, int(user_id)),
)
username = str(row["username"])
return {"secret": secret, "uri": mfa_provisioning_uri(username, secret), "username": username}
def confirm_mfa_setup(user_id: int, code: str) -> dict[str, Any]:
init_database()
with _connect() as conn:
row = conn.execute("SELECT mfa_secret,mfa_enabled FROM users WHERE id=?", (int(user_id),)).fetchone()
if not row:
raise ValueError("User not found")
if bool(int(row["mfa_enabled"] or 0)):
raise ValueError("MFA is already enabled")
secret = str(row["mfa_secret"] or "")
if not secret:
raise ValueError("MFA setup has not been started")
if not verify_totp(secret, code):
raise ValueError("Invalid authentication code")
recovery_codes = _new_recovery_codes()
hashes = json.dumps([_recovery_hash(item) for item in recovery_codes], separators=(",", ":"))
now = int(time.time())
conn.execute(
"""
UPDATE users
SET mfa_enabled=1,mfa_recovery_codes=?,mfa_confirmed_at=?,session_version=session_version+1
WHERE id=?
""",
(hashes, now, int(user_id)),
)
version = int(conn.execute("SELECT session_version FROM users WHERE id=?", (int(user_id),)).fetchone()[0])
return {"recovery_codes": recovery_codes, "session_version": version}
def verify_user_mfa(user_id: int, code: str, *, consume_recovery: bool = True) -> dict[str, Any]:
init_database()
with _connect() as conn:
row = conn.execute(
"SELECT mfa_enabled,mfa_secret,mfa_recovery_codes FROM users WHERE id=?", (int(user_id),)
).fetchone()
if not row:
raise ValueError("User not found")
if not bool(int(row["mfa_enabled"] or 0)):
return {"ok": True, "method": "disabled", "recovery_remaining": 0}
secret = str(row["mfa_secret"] or "")
if secret and verify_totp(secret, code):
hashes = _load_recovery_hashes(str(row["mfa_recovery_codes"] or "[]"))
return {"ok": True, "method": "totp", "recovery_remaining": len(hashes)}
normalized = _normalize_recovery_code(code)
if not normalized:
return {"ok": False, "method": "", "recovery_remaining": 0}
candidate = _recovery_hash(normalized)
hashes = _load_recovery_hashes(str(row["mfa_recovery_codes"] or "[]"))
matched = next((item for item in hashes if hmac.compare_digest(item, candidate)), None)
if not matched:
return {"ok": False, "method": "", "recovery_remaining": len(hashes)}
if consume_recovery:
remaining = [item for item in hashes if not hmac.compare_digest(item, candidate)]
conn.execute(
"UPDATE users SET mfa_recovery_codes=? WHERE id=?",
(json.dumps(remaining, separators=(",", ":")), int(user_id)),
)
hashes = remaining
return {"ok": True, "method": "recovery", "recovery_remaining": len(hashes)}
def disable_mfa(user_id: int) -> dict[str, Any]:
init_database()
with _connect() as conn:
cur = conn.execute(
"""
UPDATE users
SET mfa_enabled=0,mfa_secret='',mfa_recovery_codes='[]',mfa_confirmed_at=0,
session_version=session_version+1
WHERE id=?
""",
(int(user_id),),
)
if cur.rowcount != 1:
raise ValueError("User not found")
version = int(conn.execute("SELECT session_version FROM users WHERE id=?", (int(user_id),)).fetchone()[0])
return {"session_version": version}
def regenerate_mfa_recovery_codes(user_id: int) -> dict[str, Any]:
init_database()
recovery_codes = _new_recovery_codes()
hashes = json.dumps([_recovery_hash(item) for item in recovery_codes], separators=(",", ":"))
with _connect() as conn:
row = conn.execute("SELECT mfa_enabled FROM users WHERE id=?", (int(user_id),)).fetchone()
if not row:
raise ValueError("User not found")
if not bool(int(row["mfa_enabled"] or 0)):
raise ValueError("MFA is not enabled")
conn.execute("UPDATE users SET mfa_recovery_codes=? WHERE id=?", (hashes, int(user_id)))
return {"recovery_codes": recovery_codes}
def delete_user(user_id: int) -> None:
init_database()
with _connect() as conn:
count = int(conn.execute("SELECT COUNT(*) FROM users").fetchone()[0])
if count <= 1:
raise ValueError("The last user cannot be deleted")
cur = conn.execute("DELETE FROM users WHERE id=?", (int(user_id),))
if cur.rowcount != 1:
raise ValueError("User not found")