Phase 5: secure credentials, first-login setup, user rename, admin settings

Security:
- PBKDF2-HMAC-SHA256 password hashing (260k iterations, random salt per password)
- Legacy MICRONAS_PASS plaintext still works for existing installs
- MICRONAS_PASS_HASH replaces plaintext in env file after first setup/change
- Timing-safe comparison via hmac.compare_digest

First-login setup:
- /setup route: shown when no credentials configured (fresh install)
- Replaces editing /etc/micronas.env manually
- setup.html dark-themed form matching login.html

Admin credential change:
- POST /api/admin/credentials (requires current password to confirm)
- Settings button in topbar opens modal for username + password change
- Session cleared after change → redirected to login

User management:
- PATCH /api/users/<name>: rename Linux user (usermod -l)
  SMB + WebDAV entries removed, password reset required after rename
- Rename button in users table, modal with yellow warning

WebDAV:
- Options Indexes: directories now browsable in a regular web browser

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
marcandClaude Sonnet 4.6 committed 2026-06-20 16:45:16 +02:00
1 parent 559954b222
commit a29862860d
4 files changed
+282 -16

No files matched your search

+117 -15
View File
@@ -2,6 +2,7 @@ import os
import re
import pwd
import grp
import hmac
import shutil
import hashlib
import subprocess
@@ -16,28 +17,61 @@ VALID_NAME = re.compile(r'^[A-Za-z0-9_-]+$')
VALID_NFS_CLIENT = re.compile(r'^[A-Za-z0-9.*:/\-]+$')
ALLOWED_PATH_BASE = Path('/srv').resolve()
_AUTH_USER = os.environ.get('MICRONAS_USER', 'admin')
_AUTH_PASS = os.environ.get('MICRONAS_PASS', '')
_ENV_FILE = '/etc/micronas.env'
# Derive secret key from the password so sessions survive restarts
# but are automatically invalidated if the password changes.
# Mutable credential store — updated by setup/change without restart (single gunicorn worker).
_creds = {
'user': os.environ.get('MICRONAS_USER', ''),
'hash': os.environ.get('MICRONAS_PASS_HASH', ''), # PBKDF2: "salt$hex"
'plain': os.environ.get('MICRONAS_PASS', ''), # legacy plaintext
}
def _is_configured():
return bool(_creds['user'] and (_creds['hash'] or _creds['plain']))
def _hash_password(password):
salt = os.urandom(16).hex()
h = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 260_000).hex()
return f'{salt}${h}'
def _verify_password(password):
if _creds['hash']:
try:
salt, h = _creds['hash'].split('$', 1)
computed = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 260_000).hex()
return hmac.compare_digest(computed, h)
except Exception:
return False
if _creds['plain']:
return hmac.compare_digest(password, _creds['plain'])
return False
def _save_credentials(user, password):
h = _hash_password(password)
Path(_ENV_FILE).write_text(f'MICRONAS_USER={user}\nMICRONAS_PASS_HASH={h}\n')
os.chmod(_ENV_FILE, 0o600)
_creds['user'] = user
_creds['hash'] = h
_creds['plain'] = ''
app.secret_key = hashlib.sha256(h.encode()).hexdigest()
# Derive initial secret key
_secret_src = _creds['hash'] or _creds['plain'] or 'insecure-dev-key'
app.secret_key = os.environ.get('MICRONAS_SECRET') or \
hashlib.sha256((_AUTH_PASS or 'insecure-dev-key').encode()).hexdigest()
hashlib.sha256(_secret_src.encode()).hexdigest()
if not _AUTH_PASS:
if not _is_configured():
import warnings
warnings.warn(
'MICRONAS_PASS is not set — all routes are unprotected! '
'Set it via the environment or /etc/micronas.env.',
stacklevel=1,
)
warnings.warn('No credentials configured — first-time setup required at /setup', stacklevel=1)
def require_auth(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
if not _AUTH_PASS:
return f(*args, **kwargs)
if not _is_configured():
if request.path.startswith('/api/'):
return Response('Setup required', 403)
return redirect(url_for('setup'))
if not session.get('logged_in'):
if request.path.startswith('/api/'):
return Response('Unauthorized', 401)
@@ -299,7 +333,7 @@ def _write_webdav_conf(shares):
' AuthName "MicroNAS WebDAV"\n',
f' AuthUserFile {WEBDAV_PASSWD}\n',
f' {require}\n',
' Options None\n',
' Options Indexes\n',
' AllowOverride None\n',
'</Directory>\n',
f'# END {_WEBDAV_MARK} {s["name"]}\n\n',
@@ -399,15 +433,39 @@ def delete_webdav(name):
# ===== AUTH ROUTES =====
@app.route('/setup', methods=['GET', 'POST'])
def setup():
if _is_configured():
return redirect(url_for('index'))
error = None
username = 'admin'
if request.method == 'POST':
username = request.form.get('username', '').strip()
password = request.form.get('password', '')
confirm = request.form.get('confirm', '')
if not username or not VALID_NAME.match(username):
error = 'Invalid username (letters, digits, _ - only).'
elif len(password) < 8:
error = 'Password must be at least 8 characters.'
elif password != confirm:
error = 'Passwords do not match.'
else:
_save_credentials(username, password)
return redirect(url_for('login'))
return render_template('setup.html', error=error, username=username)
@app.route('/login', methods=['GET', 'POST'])
def login():
if not _is_configured():
return redirect(url_for('setup'))
if session.get('logged_in'):
return redirect(url_for('index'))
error = None
if request.method == 'POST':
username = request.form.get('username', '')
password = request.form.get('password', '')
if not _AUTH_PASS or (username == _AUTH_USER and password == _AUTH_PASS):
if username == _creds['user'] and _verify_password(password):
session['logged_in'] = True
return redirect(url_for('index'))
error = 'Invalid username or password.'
@@ -846,6 +904,50 @@ def delete_user(name):
return jsonify({'status': 'deleted'})
@app.route('/api/admin/credentials', methods=['POST'])
@require_auth
def change_admin_credentials():
data = request.json or {}
current_pw = data.get('currentPassword', '')
new_user = data.get('username', '').strip()
new_pw = data.get('password', '')
if not _verify_password(current_pw):
return jsonify({'error': 'Current password is incorrect.'}), 403
if new_user and not VALID_NAME.match(new_user):
return jsonify({'error': 'Invalid username.'}), 400
if new_pw and len(new_pw) < 8:
return jsonify({'error': 'Password must be at least 8 characters.'}), 400
user = new_user or _creds['user']
pw = new_pw or current_pw
_save_credentials(user, pw)
session.clear()
return jsonify({'status': 'updated'})
@app.route('/api/users/<name>', methods=['PATCH'])
@require_auth
def rename_user(name):
if not VALID_NAME.match(name):
return jsonify({'error': 'invalid username'}), 400
new_name = (request.json or {}).get('name', '').strip()
if not new_name or not VALID_NAME.match(new_name):
return jsonify({'error': 'invalid new username'}), 400
if new_name == name:
return jsonify({'status': 'no change'}), 200
r = subprocess.run(['usermod', '-l', new_name, name], capture_output=True, text=True)
if r.returncode != 0:
return jsonify({'error': r.stderr.strip() or 'usermod failed'}), 500
# Remove SMB and WebDAV entries — password must be reset after rename
subprocess.run(['smbpasswd', '-x', name], capture_output=True)
_remove_webdav_user(name)
return jsonify({'status': 'renamed',
'warning': 'SMB and WebDAV password must be reset for the renamed user.'})
@app.route('/api/users/<name>/password', methods=['POST'])
@require_auth
def change_password(name):