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:
1 parent
559954b222
commit
a29862860d
4 files changed
+282
-16
No files matched your search
@@ -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):
|
||||
|
||||
@@ -22,6 +22,8 @@ async function loadUsers() {
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<button class="btn btn-sm me-1" style="border:1px solid var(--border); color:var(--muted)"
|
||||
onclick="openRenameModal(${nameJson})">Rename</button>
|
||||
<button class="btn btn-sm me-1" style="border:1px solid var(--border); color:var(--muted)"
|
||||
onclick="openPwModal(${nameJson})">Password</button>
|
||||
<button class="btn btn-sm btn-danger"
|
||||
@@ -95,6 +97,61 @@ async function submitPassword() {
|
||||
showToast(`Password updated for "${name}".`);
|
||||
}
|
||||
|
||||
function openRenameModal(name) {
|
||||
document.getElementById('renameOldName').value = name;
|
||||
document.getElementById('renameNewName').value = name;
|
||||
new bootstrap.Modal(document.getElementById('renameModal')).show();
|
||||
}
|
||||
|
||||
async function submitRename() {
|
||||
const oldName = document.getElementById('renameOldName').value;
|
||||
const newName = document.getElementById('renameNewName').value.trim();
|
||||
if (!newName) return showToast('New username is required.', 'danger');
|
||||
|
||||
const res = await apiFetch(`/api/users/${encodeURIComponent(oldName)}`, {
|
||||
method: 'PATCH', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({name: newName}),
|
||||
});
|
||||
if (!res) return;
|
||||
const data = await res.json();
|
||||
bootstrap.Modal.getInstance(document.getElementById('renameModal')).hide();
|
||||
if (!res.ok) return showToast('Error: ' + (data.error || res.status), 'danger');
|
||||
if (data.warning) showToast(data.warning, 'warning');
|
||||
else showToast(`Renamed to "${newName}".`);
|
||||
loadUsers();
|
||||
loadGroups();
|
||||
}
|
||||
|
||||
function openAdminSettings() {
|
||||
document.getElementById('adminCurrentPw').value = '';
|
||||
document.getElementById('adminNewUser').value = '';
|
||||
document.getElementById('adminNewPw').value = '';
|
||||
document.getElementById('adminNewPwConfirm').value = '';
|
||||
new bootstrap.Modal(document.getElementById('adminModal')).show();
|
||||
}
|
||||
|
||||
async function submitAdminSettings() {
|
||||
const currentPw = document.getElementById('adminCurrentPw').value;
|
||||
const newUser = document.getElementById('adminNewUser').value.trim();
|
||||
const newPw = document.getElementById('adminNewPw').value;
|
||||
const newPwConf = document.getElementById('adminNewPwConfirm').value;
|
||||
|
||||
if (!currentPw) return showToast('Current password is required.', 'danger');
|
||||
if (newPw && newPw !== newPwConf) return showToast('New passwords do not match.', 'danger');
|
||||
if (newPw && newPw.length < 8) return showToast('Password must be at least 8 characters.', 'danger');
|
||||
|
||||
const res = await apiFetch('/api/admin/credentials', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({currentPassword: currentPw, username: newUser, password: newPw}),
|
||||
});
|
||||
if (!res) return;
|
||||
const data = await res.json();
|
||||
if (!res.ok) return showToast('Error: ' + (data.error || res.status), 'danger');
|
||||
bootstrap.Modal.getInstance(document.getElementById('adminModal')).hide();
|
||||
showToast('Credentials updated — please log in again.');
|
||||
setTimeout(() => { window.location.href = '/login'; }, 1500);
|
||||
}
|
||||
|
||||
// ===== GROUPS =====
|
||||
|
||||
async function loadGroups() {
|
||||
|
||||
+60
-1
@@ -67,11 +67,70 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Admin settings modal -->
|
||||
<div class="modal fade" id="adminModal" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Admin Credentials</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" style="color:var(--muted); font-size:.85rem">Current Password</label>
|
||||
<input type="password" id="adminCurrentPw" class="form-control" placeholder="Required to confirm changes">
|
||||
</div>
|
||||
<hr style="border-color:var(--border)">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" style="color:var(--muted); font-size:.85rem">New Username <span style="font-weight:400">(leave blank to keep current)</span></label>
|
||||
<input type="text" id="adminNewUser" class="form-control" placeholder="admin">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" style="color:var(--muted); font-size:.85rem">New Password <span style="font-weight:400">(leave blank to keep current)</span></label>
|
||||
<input type="password" id="adminNewPw" class="form-control" placeholder="min 8 characters">
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label class="form-label" style="color:var(--muted); font-size:.85rem">Confirm New Password</label>
|
||||
<input type="password" id="adminNewPwConfirm" class="form-control">
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="button" class="btn btn-primary" onclick="submitAdminSettings()">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Rename user modal -->
|
||||
<div class="modal fade" id="renameModal" tabindex="-1">
|
||||
<div class="modal-dialog modal-sm">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Rename User</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<input type="hidden" id="renameOldName">
|
||||
<label class="form-label" style="color:var(--muted); font-size:.85rem">New Username</label>
|
||||
<input type="text" id="renameNewName" class="form-control mb-2">
|
||||
<div class="small" style="color:var(--yellow)">SMB and WebDAV password must be reset after rename.</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="button" class="btn btn-primary btn-sm" onclick="submitRename()">Rename</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Header -->
|
||||
<div class="topbar d-flex justify-content-between align-items-center">
|
||||
<span class="fw-semibold fs-5">MicroNAS</span>
|
||||
<div class="d-flex align-items-center gap-3">
|
||||
<span id="lastRefresh" class="small" style="color:var(--muted)"></span>
|
||||
<button type="button" class="btn btn-sm" style="border:1px solid var(--border); color:var(--muted)"
|
||||
onclick="openAdminSettings()">⚙ Settings</button>
|
||||
<a href="/logout" class="btn btn-sm" style="border:1px solid var(--border); color:var(--muted)">Sign out</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -261,7 +320,7 @@
|
||||
<div class="fw-semibold mb-2">Users</div>
|
||||
<div class="table-responsive mb-5">
|
||||
<table class="table table-striped mb-0">
|
||||
<thead><tr><th>Username</th><th>UID</th><th>SMB Account</th><th>Actions</th></tr></thead>
|
||||
<thead><tr><th>Username</th><th>UID</th><th>SMB</th><th>Actions</th></tr></thead>
|
||||
<tbody id="usersTableBody">
|
||||
<tr><td colspan="4" style="color:var(--muted)">Loading…</td></tr>
|
||||
</tbody>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>MicroNAS — Setup</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/app.css') }}">
|
||||
<style>
|
||||
body { display: flex; align-items: center; justify-content: center; min-height: 100vh; }
|
||||
.setup-card { width: 100%; max-width: 400px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="setup-card">
|
||||
<div class="text-center mb-4">
|
||||
<div class="fw-bold fs-4" style="color:var(--text)">MicroNAS</div>
|
||||
<div class="small" style="color:var(--muted)">First-time setup — create your admin account</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-body p-4">
|
||||
{% if error %}
|
||||
<div class="alert mb-3 py-2 px-3" style="background:#2d1515; border:1px solid var(--red); color:var(--red); border-radius:6px; font-size:.9rem;">
|
||||
{{ error }}
|
||||
</div>
|
||||
{% endif %}
|
||||
<form method="POST">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" style="color:var(--muted); font-size:.85rem">Admin Username</label>
|
||||
<input type="text" name="username" class="form-control" value="{{ username or 'admin' }}" autofocus autocomplete="username">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" style="color:var(--muted); font-size:.85rem">Password</label>
|
||||
<input type="password" name="password" class="form-control" autocomplete="new-password">
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" style="color:var(--muted); font-size:.85rem">Confirm Password</label>
|
||||
<input type="password" name="confirm" class="form-control" autocomplete="new-password">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary w-100">Create Account</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-center mt-3" style="font-size:.8rem; color:var(--muted)">
|
||||
Credentials are saved hashed to <code>/etc/micronas.env</code>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user