diff --git a/ai-station-portal-admin b/ai-station-portal-admin index d4940df..8fdf4c4 100755 --- a/ai-station-portal-admin +++ b/ai-station-portal-admin @@ -292,6 +292,35 @@ def network_read(iface): })) return 0 + +def password_change(username): + if username != 'theroot': + return 2 + + password = sys.stdin.readline(258) + if not password.endswith('\n'): + return 2 + + password = password[:-1] + + if ( + len(password) < 8 + or len(password) > 256 + or any(ord(char) < 32 or ord(char) == 127 for char in password) + or ':' in password + ): + return 2 + + subprocess.run( + ['/usr/sbin/chpasswd'], + input=f'{username}:{password}\n', + text=True, + check=True, + capture_output=True, + timeout=15, + ) + return 0 + def main(): if len(sys.argv) != 3: return 2 action, value = sys.argv[1:] @@ -304,6 +333,7 @@ def main(): if action == 'ntp': if value not in {'yes', 'no'}: return 2 run('/usr/bin/timedatectl', 'set-ntp', 'true' if value == 'yes' else 'false'); return 0 + if action == 'password-change': return password_change(value) if action == 'network-read': return network_read(value) if action == 'network-status': return network_status() if action == 'network-apply': return network_apply(value) diff --git a/app.py b/app.py index 0883ebc..e0e21f3 100644 --- a/app.py +++ b/app.py @@ -15,6 +15,7 @@ import subprocess import time import ipaddress import logging +import hmac from datetime import datetime, timezone from zoneinfo import available_timezones from pathlib import Path @@ -169,6 +170,29 @@ def run_helper(*args: str) -> tuple[bool, str]: return result.returncode == 0, output +def run_helper_input(input_text: str, *args: str) -> tuple[bool, str]: + try: + result = subprocess.run( + ["sudo", "-n", ADMIN_HELPER, *args], + input=input_text, + capture_output=True, + text=True, + timeout=15, + check=False, + ) + except subprocess.TimeoutExpired: + return False, "helper timeout" + except OSError: + return False, "helper execution error" + + output = "\\n".join( + part.strip() + for part in (result.stdout, result.stderr) + if part and part.strip() + ) + return result.returncode == 0, output + + def timedatectl_value(property_name: str) -> str | None: """Read the live system value from systemd-timedated, not cached config files.""" try: @@ -266,6 +290,11 @@ async def admin_page(request: Request): network_state = json.loads(status_output) except json.JSONDecodeError: pass + csrf_token = request.session.get("password_csrf") + if not csrf_token: + csrf_token = secrets.token_urlsafe(32) + request.session["password_csrf"] = csrf_token + network = read_network_settings() network_url = "" if network.get("address"): @@ -287,10 +316,63 @@ async def admin_page(request: Request): "network": network, "network_url": network_url, "network_state": network_state, + "password_csrf": csrf_token, }, ) +@app.post("/admin/settings/password") +async def update_admin_password( + request: Request, + current_password: str = Form(...), + new_password: str = Form(...), + confirm_password: str = Form(...), + csrf_token: str = Form(...), +): + if not admin_session_valid(request): + return RedirectResponse("/admin/login", status_code=303) + + session_token = request.session.get("password_csrf", "") + if not session_token or not hmac.compare_digest(csrf_token, session_token): + return RedirectResponse("/admin?error=password-csrf", status_code=303) + + if ADMIN_USER != "theroot": + return RedirectResponse("/admin?error=password-helper", status_code=303) + + authenticated = False + try: + authenticated = pam.pam().authenticate( + ADMIN_USER, current_password, service="login" + ) + except Exception: + authenticated = False + + if not authenticated: + return RedirectResponse("/admin?error=password-current", status_code=303) + + if new_password != confirm_password: + return RedirectResponse("/admin?error=password-mismatch", status_code=303) + + if ( + len(new_password) < 8 + or len(new_password) > 256 + or any(ord(char) < 32 or ord(char) == 127 for char in new_password) + or ":" in new_password + ): + return RedirectResponse("/admin?error=password-policy", status_code=303) + + ok, _ = run_helper_input( + new_password + "\n", + "password-change", + ADMIN_USER, + ) + if not ok: + return RedirectResponse("/admin?error=password-helper", status_code=303) + + request.session.clear() + return RedirectResponse("/admin/login?result=password-changed", status_code=303) + + @app.post("/admin/settings/network") async def update_network( request: Request, diff --git a/templates/admin.html b/templates/admin.html index 786b1f1..c51d637 100644 --- a/templates/admin.html +++ b/templates/admin.html @@ -197,11 +197,17 @@ })(); {% elif request.query_params.get('result') == 'network-confirmed' %}
Изменение системного пароля пользователя {{ admin_user }}.
+ +Интерфейс {{ network.interface }} · MAC {{ network.mac }} · управление Netplan / systemd-networkd