Configure server through web onboarding and encrypt backups

This commit is contained in:
Ludwig Lehnert committed 2026-10-05 16:47:49 +00:00
1 parent 5cb3b5bedf
commit 88f803daf2
35 files changed
+4250 -981

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
"""BIP39 recovery phrases for versioned, reproducible backup archive keys."""
import hashlib
import secrets
import unicodedata
from pathlib import Path
WORDS = (Path(__file__).parent / 'vendor' / 'bip39' / 'english.txt').read_text().splitlines()
WORD_IDS = {word: index for index, word in enumerate(WORDS)}
if len(WORDS) != 2048 or len(WORD_IDS) != 2048:
raise RuntimeError('Invalid BIP39 wordlist')
def phrase_from_entropy(entropy):
if len(entropy) not in (16, 20, 24, 28, 32):
raise ValueError('Invalid entropy length')
checksum_bits = len(entropy) // 4
value = (int.from_bytes(entropy, 'big') << checksum_bits) | (hashlib.sha256(entropy).digest()[0] >> (8 - checksum_bits))
count = (len(entropy) * 8 + checksum_bits) // 11
return ' '.join(WORDS[(value >> (11 * index)) & 2047] for index in reversed(range(count)))
def normalize_phrase(phrase):
phrase = ' '.join(unicodedata.normalize('NFKD', phrase).lower().split())
words = phrase.split()
if len(words) not in (12, 15, 18, 21, 24) or any(word not in WORD_IDS for word in words):
raise ValueError('Ungültige Wiederherstellungsphrase')
value = 0
for word in words:
value = (value << 11) | WORD_IDS[word]
checksum_bits = len(words) // 3
entropy = (value >> checksum_bits).to_bytes((len(words) * 11 - checksum_bits) // 8, 'big')
if phrase_from_entropy(entropy) != phrase:
raise ValueError('Prüfsumme der Wiederherstellungsphrase stimmt nicht')
return phrase
def seed(phrase, passphrase=''):
phrase = normalize_phrase(phrase)
salt = unicodedata.normalize('NFKD', 'mnemonic' + passphrase)
return hashlib.pbkdf2_hmac('sha512', phrase.encode(), salt.encode(), 2048, dklen=64)
def archive_key(phrase):
# A domain-separated archive password, followed by 7z's own AES-256 KDF.
return hashlib.pbkdf2_hmac('sha512', seed(phrase), b'adfs-backup-archive-v1', 1, dklen=32).hex()
def generate():
phrase = phrase_from_entropy(secrets.token_bytes(32))
password = archive_key(phrase)
return {'phrase': phrase, 'password': password, 'keyId': hashlib.sha256(password.encode()).hexdigest()[:24],
'format': 'adfs-backup-archive-v1'}
+57 -10
View File
@@ -968,6 +968,7 @@ def prepare_state_snapshot(
database_relative,
f"{database_relative}-wal",
f"{database_relative}-shm",
'configuration.db', 'configuration.db-wal', 'configuration.db-shm',
}
def ignore_live_database(directory: str, names: List[str]) -> Set[str]:
@@ -1002,6 +1003,18 @@ def prepare_state_snapshot(
finally:
destination.close()
source.close()
configuration_path = os.path.join(state_root, 'configuration.db')
if os.path.isfile(configuration_path):
source = sqlite3.connect(f'file:{configuration_path}?mode=ro', uri=True, timeout=30)
destination = sqlite3.connect(os.path.join(staged_state, 'configuration.db'))
os.chmod(os.path.join(staged_state, 'configuration.db'), 0o600)
try:
source.backup(destination)
if destination.execute('PRAGMA quick_check').fetchone()[0] != 'ok':
raise RuntimeError('Configuration snapshot failed its integrity check')
finally:
destination.close()
source.close()
return temporary_root, staged_state
except Exception:
shutil.rmtree(temporary_root, ignore_errors=True)
@@ -1019,7 +1032,7 @@ def archive_password() -> str:
return password
def create_group_archive(source_path: str, archive_path: str, password: str) -> None:
def create_group_archive(source_path: str, archive_path: str, password: Optional[str]) -> None:
os.makedirs(os.path.dirname(archive_path), exist_ok=True)
source_parent = os.path.dirname(source_path)
source_name = os.path.basename(source_path)
@@ -1032,14 +1045,15 @@ def create_group_archive(source_path: str, archive_path: str, password: str) ->
"-mx=5",
"-mmt=on",
"-ms=off",
"-mhe=on",
"-p",
*(['-mhe=on', '-p'] if password else []),
'-snl',
'-xr!.trash',
"-y",
archive_path,
"--",
source_name,
],
input_text=f"{password}\n",
input_text=f"{password}\n" if password else None,
check=False,
env=os.environ.copy(),
cwd=source_parent,
@@ -1153,6 +1167,29 @@ def available_sources(
return sources
def prepare_encrypted_sources(sources, password, temporary_parent=None):
"""Encrypt every original/configuration source, including archive headers."""
root = tempfile.mkdtemp(prefix='backup-encrypted-', dir=temporary_parent or None)
staged = os.path.join(root, 'encrypted')
os.makedirs(staged)
try:
for source_path, destination_path in sources:
name = destination_path.replace('/', '-') + '.7z'
if BACKUP_STATUS is not None:
BACKUP_STATUS.write(state='running', currentSource=destination_path,
message=f'Encrypting {destination_path}', activeFiles=[])
create_group_archive(source_path, os.path.join(staged, name), password)
metadata = {'format': os.getenv('BACKUP_KEY_FORMAT', '7z-aes256'),
'keyId': os.getenv('BACKUP_KEY_ID', ''), 'encrypted': True,
'archives': [destination.replace('/', '-') + '.7z' for _, destination in sources]}
with open(os.path.join(staged, 'backup-format.json'), 'w') as handle:
json.dump(metadata, handle)
return root, [(staged, 'encrypted')]
except BaseException:
shutil.rmtree(root, ignore_errors=True)
raise
def format_host(hostname: str) -> str:
if ":" in hostname and not hostname.startswith("["):
return f"[{hostname}]"
@@ -1693,6 +1730,11 @@ def run_backup() -> int:
interactive_progress = should_show_progress_bar(progress_mode)
destination = parse_destination(destination_url)
namespace = os.getenv('BACKUP_NAMESPACE', '').strip('/')
if namespace:
if not re.fullmatch(r'keys/[a-f0-9]{24}|plain', namespace):
raise ValueError('Invalid backup key namespace')
destination.path = destination.path.rstrip('/') + '/' + namespace
BACKUP_STATUS = BackupStatus(
os.getenv("BACKUP_STATUS_FILE", DEFAULT_BACKUP_STATUS_FILE).strip()
)
@@ -1703,6 +1745,7 @@ def run_backup() -> int:
backend = None
state_snapshot_root = None
group_archive_root = None
encrypted_root = None
try:
state_snapshot = None
if os.path.isdir(STATE_ROOT):
@@ -1710,21 +1753,23 @@ def run_backup() -> int:
state_snapshot_root, state_snapshot = prepare_state_snapshot()
groups_snapshot = None
if os.path.isdir(GROUPS_SOURCE_PATH):
encrypted = os.getenv('BACKUP_ENCRYPTION_ENABLED', 'false').lower() == 'true'
if os.path.isdir(GROUPS_SOURCE_PATH) and not encrypted:
BACKUP_STATUS.write(
state="running",
currentSource="data/groups",
message="Creating encrypted group archives",
message="Creating group archives",
)
group_archive_root, groups_snapshot, archive_count = prepare_group_archives(
password=archive_password()
)
log(f"Created {archive_count} encrypted non-solid group archive(s)")
group_archive_root, groups_snapshot, archive_count = prepare_group_archives(password='' if os.getenv('BACKUP_KEY_ID') else os.getenv('BACKUP_ARCHIVE_PASSWORD', ''))
log(f"Created {archive_count} non-solid group archive(s)")
sources = available_sources(state_snapshot, groups_snapshot)
if not sources:
log("No backup sources are available, skipping backup")
return 0
if encrypted:
encrypted_root, sources = prepare_encrypted_sources(sources, archive_password(),
os.getenv('BACKUP_ARCHIVE_TEMP_DIR', DEFAULT_ARCHIVE_TEMP_DIR))
backend = build_backend(destination)
log(f"Starting backup to {redact_destination(destination.raw_url)}")
@@ -1784,6 +1829,8 @@ def run_backup() -> int:
shutil.rmtree(state_snapshot_root, ignore_errors=True)
if group_archive_root is not None:
shutil.rmtree(group_archive_root, ignore_errors=True)
if encrypted_root is not None:
shutil.rmtree(encrypted_root, ignore_errors=True)
def with_lock() -> int:
+456
View File
@@ -0,0 +1,456 @@
"""Persistent application settings. Environment input is imported only once."""
import argparse
import contextlib
import hashlib
import hmac
import ipaddress
import json
import os
from pathlib import Path
import re
import secrets
import shlex
import sqlite3
import ssl
import sys
import time
import urllib.parse
try:
from . import backup_keys
except ImportError:
import backup_keys
ROOT = Path('/state')
SID = re.compile(r'S-\d+(?:-\d+)+')
DNS = re.compile(r'(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?')
def field(section, label, default='', kind='text', minimum=None, maximum=None, **extra):
return dict(section=section, label=label, default=default, kind=kind, minimum=minimum, maximum=maximum, **extra)
FIELDS = {
'REALM': field('domain', 'Kerberos-Domäne', kind='dns', required=True),
'WORKGROUP': field('domain', 'NetBIOS-Domäne', kind='netbios', required=True),
'DOMAIN': field('domain', 'Domänencontroller / AD-DNS-Name', kind='dns', required=True),
'JOIN_USER': field('domain', 'Konto für Domänenbeitritt und LDAP'),
'JOIN_PASSWORD': field('domain', 'Passwort für Domänenbeitritt und LDAP', kind='secret'),
'LDAP_URI': field('domain', 'LDAP-Adresse (optional)', kind='ldap'),
'LDAP_BASE_DN': field('domain', 'LDAP-Basis-DN (optional)'),
'DOMAIN_USERS_SID': field('groups', 'Benutzergruppe', kind='group', required=True),
'DOMAIN_ADMINS_SID': field('groups', 'Administratorengruppe', kind='group', required=True),
'FSLOGIX_GROUP_SID': field('groups', 'FSLogix-Gruppe', kind='group', required=True),
'NETBIOS_NAME': field('network', 'Servername (NetBIOS)', 'ADSAMBAFSRV', 'netbios'),
'SAMBA_HOSTNAME': field('network', 'Servername (DNS)', 'adsambafsrv', 'dns'),
'AD_DNS_NAME': field('network', 'AD-DNS-Eintrag (optional)', kind='dns'),
'AD_DNS_IP': field('network', 'IP-Adresse für AD-DNS-Eintrag (optional)', kind='ip'),
'WEB_HOSTNAME': field('tls', 'HTTPS-Hostname', 'localhost', 'dns'),
'WEB_TLS_MODE': field('tls', 'HTTPS-Zertifikat', 'self-signed', 'choice', choices=['self-signed', 'acme', 'ca', 'files']),
'WEB_TLS_AUTORENEW': field('tls', 'Zertifikate automatisch erneuern', True, 'bool'),
'ACME_CA_SERVER': field('tls', 'ACME-Verzeichnisadresse', kind='https'),
'ACME_CA_CERTIFICATES_PEM': field('tls', 'CA-Vertrauenszertifikat (PEM)', kind='pem'),
'ACME_CA_CERTIFICATES_URL': field('tls', 'Adresse für CA-Vertrauenszertifikat (optional)', kind='https'),
'ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD': field('tls', 'CA-Download ohne Zertifikatsprüfung', False, 'bool'),
'ACME_RENEW_CHECK_SECONDS': field('tls', 'Erneuerung prüfen (Sekunden)', 900, 'int', 60, 86400),
'TLS_CA_URL': field('tls', 'CA-Adresse', kind='https'),
'TLS_CA_ROOT_PEM': field('tls', 'CA-Wurzelzertifikat (PEM)', kind='pem'),
'TLS_CA_FINGERPRINT': field('tls', 'CA-Fingerabdruck'),
'TLS_CA_PROVISIONER': field('tls', 'CA-Provisioner'),
'TLS_CA_TOKEN': field('tls', 'CA-Einrichtungstoken', kind='secret'),
'TLS_CA_PASSWORD': field('tls', 'CA-Provisioner-Passwort', kind='secret'),
'WEB_TLS_CERT_PEM': field('tls', 'HTTPS-Zertifikat (PEM)', kind='pem'),
'WEB_TLS_KEY_PEM': field('tls', 'Privater HTTPS-Schlüssel (PEM)', kind='secretpem'),
'WEB_TRUSTED_ORIGINS': field('web', 'Weitere HTTPS-Origins (kommagetrennt)', kind='origins'),
'WEB_JWT_TTL_SECONDS': field('web', 'Sitzungsdauer (Sekunden)', 28800, 'int', 300, 604800),
'WEB_AUTH_RECHECK_SECONDS': field('web', 'AD-Rechte erneut prüfen (Sekunden)', 60, 'int', 5, 300),
'WEB_LOGIN_ATTEMPTS_PER_5_MIN': field('web', 'Anmeldeversuche pro IP / 5 Minuten', 10, 'int', 3, 100),
'WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN': field('web', 'Anmeldeversuche pro Konto / 5 Minuten', 10, 'int', 3, 100),
'WEB_TLS_HANDSHAKE_TIMEOUT_SECONDS': field('web', 'TLS-Handshake-Zeitlimit (Sekunden)', 5, 'int', 1, 30),
'WEB_REQUEST_TIMEOUT_SECONDS': field('web', 'Anfrage-Zeitlimit (Sekunden)', 30, 'int', 1, 300),
'WEB_MAX_CONNECTIONS': field('web', 'Gleichzeitige Web-Verbindungen', 64, 'int', 4, 512),
'WEB_USAGE_SCAN_INTERVAL_SECONDS': field('web', 'Belegung erfassen (Sekunden)', 900, 'int', 10, 86400),
'WEB_DIRECTORY_CACHE_SECONDS': field('web', 'AD-Verzeichniszwischenspeicher (Sekunden)', 300, 'int', 5, 3600),
'PRIVATE_SKIP_USERS': field('files', 'Private Ordner: ausgeschlossene Benutzer (kommagetrennt)'),
'PRIVATE_SKIP_PREFIXES': field('files', 'Private Ordner: ausgeschlossene Präfixe (kommagetrennt)'),
'TRASH_RETENTION_DAYS': field('files', 'Papierkorb aufbewahren (Tage)', 7, 'int', 1, 365),
'AUDIT_SKIP_USER_SUFFIXES': field('files', 'Protokoll: ausgeschlossene Kontosuffixe', '_svc,_ServiceAcc'),
'AUDIT_QUERY_MAX_DAYS': field('files', 'Protokoll: größter Suchzeitraum (Tage)', 31, 'int', 1, 366),
'DOCUMENT_SCAN_SECONDS': field('documents', 'Dateien erneut erfassen (Sekunden)', 30, 'int', 5, 3600),
'DOCUMENT_OCR_LANGUAGE': field('documents', 'OCR-Sprachen', 'deu+eng', 'languages'),
'DOCUMENT_OCR_TIMEOUT_SECONDS': field('documents', 'OCR-Auftrag-Zeitlimit (Sekunden)', 600, 'int', 30, 3600),
'DOCUMENT_OCR_DPI': field('documents', 'OCR-Auflösung (DPI)', 300, 'int', 150, 400),
'DOCUMENT_OCR_MAX_DIMENSION': field('documents', 'OCR: größte Bildkante (Pixel)', 3500, 'int', 1500, 5000),
'DOCUMENT_OCR_PAGE_TIMEOUT_SECONDS': field('documents', 'OCR-Seiten-Zeitlimit (Sekunden)', 30, 'int', 5, 120),
'DOCUMENT_MAX_FILE_MB': field('documents', 'Größte Datei für Texterfassung (MiB)', 512, 'int', 1, 4096),
'DOCUMENT_MAX_PDF_PAGES': field('documents', 'Größte PDF-Seitenzahl', 500, 'int', 1, 5000),
'BACKUP_DESTINATION': field('backup', 'Sicherungsziel', kind='secreturl'),
'BACKUP_AUTO_ENABLED': field('backup', 'Automatische Sicherungen', False, 'bool'),
'BACKUP_START_HOUR': field('backup', 'Tägliche Startzeit (Stunde, UTC)', 2, 'int', 0, 23),
'BACKUP_RETENTION_DAILY': field('backup', 'Tägliche Sicherungen aufbewahren', 3, 'int', 0, 10000),
'BACKUP_RETENTION_WEEKLY': field('backup', 'Wöchentliche Sicherungen aufbewahren', 2, 'int', 0, 10000),
'BACKUP_RETENTION_MONTHLY': field('backup', 'Monatliche Sicherungen aufbewahren', 2, 'int', 0, 10000),
'BACKUP_RETENTION_YEARLY': field('backup', 'Jährliche Sicherungen aufbewahren', 1, 'int', 0, 10000),
'BACKUP_ENCRYPTION_ENABLED': field('backup', 'Alle Sicherungsdaten verschlüsseln', True, 'bool'),
'BACKUP_PROGRESS_INTERVAL_SECONDS': field('backup', 'Fortschritt erfassen (Sekunden)', 10, 'int', 1, 300),
}
PRIVATE_FIELDS = {'WEB_JWT_SECRET', 'BACKUP_ARCHIVE_PASSWORD', 'BACKUP_KEY_ID', 'BACKUP_KEY_FORMAT',
'BACKUP_NAMESPACE', 'STATE_DB_PATH', 'SHARE_DB_PATH', 'STATE_ROOT', 'GROUP_ROOT',
'GROUP_ARCHIVE_ROOT', 'PRIVATE_ROOT', 'FSLOGIX_ROOT', 'DOCUMENT_STATE_ROOT',
'RECONCILE_STATUS_FILE', 'RECONCILE_LOG_FILE', 'BACKUP_STATUS_FILE', 'BACKUP_LOG_FILE',
'BACKUP_ARCHIVE_TEMP_DIR', 'WEB_TLS_CERT_FILE', 'WEB_TLS_KEY_FILE', 'ACME_CA_CERTIFICATES',
'TLS_CA_ROOT', 'TLS_CA_PROVISIONER_PASSWORD', 'TLS_CA_PROVISIONER_PASSWORD_FILE', 'AUDIT_SOURCE_GLOB', 'AUDIT_ARCHIVE_DIR', 'AUDIT_POLL_SECONDS',
'TLS_CA_STATE_DIR', 'TLS_CA_REBOOTSTRAP', 'BACKUP_PROGRESS',
'WEB_HTTPS_PORT', 'WEB_BIND_PORT', 'WEB_BIND_ADDRESS', 'ACME_HTTP_LISTEN'}
SECTIONS = {'domain': 'Active Directory', 'groups': 'Gruppen für Anmeldung und Systemzugriff',
'network': 'Server und DNS', 'tls': 'HTTPS und Zertifikate', 'web': 'Web-Zugriff',
'files': 'Dateien und Protokolle', 'documents': 'Dokumentindex und OCR', 'backup': 'Sicherungen'}
def validate(name, value):
spec = FIELDS[name]
kind = spec['kind']
if kind == 'bool':
if value in (True, 'true', '1', 1):
return True
if value in (False, 'false', '0', 0):
return False
raise ValueError(spec['label'] + ': ungültiger Schalter')
if kind == 'int':
if isinstance(value, bool) or not re.fullmatch(r'\d+', str(value)):
raise ValueError(spec['label'] + ': ganze Zahl erforderlich')
value = int(value)
if not spec['minimum'] <= value <= spec['maximum']:
raise ValueError(spec['label'] + ': Wert außerhalb des zulässigen Bereichs')
return value
if not isinstance(value, str) or len(value) > (65536 if 'pem' in kind else 4096):
raise ValueError(spec['label'] + ': ungültiger Wert')
if '\0' in value or ('pem' not in kind and any(char in value for char in '\r\n')):
raise ValueError(spec['label'] + ': ungültige Steuerzeichen')
if kind not in ('secret', 'secretpem'):
value = value.strip()
if not value:
return value
if kind == 'dns' and not DNS.fullmatch(value):
raise ValueError(spec['label'] + ': ungültiger DNS-Name')
if kind == 'netbios' and not re.fullmatch(r'[A-Za-z0-9_-]{1,15}', value):
raise ValueError(spec['label'] + ': höchstens 15 Buchstaben/Ziffern, _ oder -')
if kind == 'group' and not SID.fullmatch(value):
raise ValueError(spec['label'] + ': ungültige Gruppen-SID')
if kind == 'ip':
ipaddress.ip_address(value)
if kind == 'languages' and not re.fullmatch(r'[a-z]{3}(?:\+[a-z]{3})*', value):
raise ValueError('Ungültige OCR-Sprachen')
if kind == 'choice' and value not in spec['choices']:
raise ValueError(spec['label'] + ': ungültige Auswahl')
if name in ('ACME_CA_CERTIFICATES_PEM', 'TLS_CA_ROOT_PEM'):
try:
ssl.create_default_context().load_verify_locations(cadata=value)
except ssl.SSLError as exc:
raise ValueError(spec['label'] + ': ungültiges PEM-Zertifikat') from exc
if kind in ('https', 'ldap', 'secreturl'):
parsed = urllib.parse.urlsplit(value)
allowed = {'https'} if kind == 'https' else {'ldap', 'ldaps'} if kind == 'ldap' else {'rsync', 'sftp', 'smb', 'cifs', 'davfs', 'dav', 'webdav', 'https', 'http'}
if parsed.scheme not in allowed or not parsed.hostname or parsed.query or parsed.fragment:
raise ValueError(spec['label'] + ': ungültige Adresse')
if kind == 'https' and (parsed.username is not None or parsed.password is not None):
raise ValueError(spec['label'] + ': Zugangsdaten in dieser Adresse sind nicht zulässig')
if parsed.port is not None and not 1 <= parsed.port <= 65535:
raise ValueError(spec['label'] + ': ungültiger Port')
if any(char in urllib.parse.unquote(value) for char in '\r\n\0'):
raise ValueError(spec['label'] + ': ungültige Steuerzeichen in der Adresse')
if kind == 'origins':
try:
from .web_security import origin
except ImportError:
from web_security import origin
for item in value.split(','):
origin(item.strip())
return value
class Conflict(ValueError):
pass
class Store:
def __init__(self, root=ROOT):
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
self.path = self.root / 'configuration.db'
fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o600)
os.close(fd)
os.chmod(self.path, 0o600)
with self.connect() as conn:
conn.execute('''CREATE TABLE IF NOT EXISTS configuration (
id INTEGER PRIMARY KEY CHECK(id=1), revision INTEGER NOT NULL, phase TEXT NOT NULL,
service_revision INTEGER NOT NULL, settings TEXT NOT NULL)''')
defaults = {name: spec['default'] for name, spec in FIELDS.items()}
defaults['WEB_JWT_SECRET'] = secrets.token_urlsafe(48)
conn.execute('INSERT OR IGNORE INTO configuration VALUES(1,0,?,0,?)', ('unconfigured', json.dumps(defaults)))
conn.execute('''CREATE TABLE IF NOT EXISTS pending_backup_keys (
nonce TEXT PRIMARY KEY, owner TEXT NOT NULL, expires REAL NOT NULL, revision INTEGER NOT NULL,
password TEXT NOT NULL, key_id TEXT NOT NULL, format TEXT NOT NULL)''')
conn.execute('CREATE TABLE IF NOT EXISTS scheduled_backups (slot TEXT PRIMARY KEY)')
@contextlib.contextmanager
def connect(self):
conn = sqlite3.connect(self.path, timeout=30)
conn.row_factory = sqlite3.Row
conn.execute('PRAGMA journal_mode=WAL')
try:
yield conn
conn.commit()
except BaseException:
conn.rollback()
raise
finally:
conn.close()
def snapshot(self):
with self.connect() as conn:
row = dict(conn.execute('SELECT * FROM configuration WHERE id=1').fetchone())
row['values'] = json.loads(row.pop('settings'))
return row
def public(self, section=None):
snap = self.snapshot()
result = {'revision': snap['revision'], 'phase': snap['phase'], 'sections': [],
'encryption': {'keyId': snap['values'].get('BACKUP_KEY_ID', ''),
'legacy': bool(snap['values'].get('BACKUP_ARCHIVE_PASSWORD') and not snap['values'].get('BACKUP_KEY_ID'))}}
for name, label in SECTIONS.items():
if section and section != name:
continue
fields = []
for key, spec in FIELDS.items():
if spec['section'] != name:
continue
value = snap['values'].get(key, spec['default'])
secret = spec['kind'] in ('secret', 'secretpem', 'secreturl')
fields.append(dict(spec, key=key, value='' if secret else value, configured=bool(value) if secret else False))
if spec['kind'] == 'secreturl' and value:
url = urllib.parse.urlsplit(value)
fields[-1]['summary'] = urllib.parse.urlunsplit((url.scheme, url.hostname + (':' + str(url.port) if url.port else ''), url.path, '', ''))
result['sections'].append({'id': name, 'label': label, 'fields': fields})
return result
def save(self, changes, revision, *, bootstrap=False):
if not isinstance(changes, dict) or any(name not in FIELDS for name in changes):
raise ValueError('Unbekannte Einstellung')
normalized = {name: validate(name, value) for name, value in changes.items()}
if not bootstrap and any(name in normalized for name in ('REALM', 'WORKGROUP')):
current = self.snapshot()['values']
if any(normalized[name] != current[name] for name in ('REALM', 'WORKGROUP') if name in normalized):
raise ValueError('Ein Wechsel der AD-Domäne erfordert einen erneuten Domänenbeitritt')
with self.connect() as conn:
conn.execute('BEGIN IMMEDIATE')
snap = dict(conn.execute('SELECT * FROM configuration WHERE id=1').fetchone())
if revision != snap['revision']:
raise Conflict('Einstellungen wurden inzwischen geändert; bitte erneut laden')
values = json.loads(snap['settings'])
values.update(normalized)
if values['WEB_TLS_MODE'] == 'files' and not (values.get('WEB_TLS_CERT_PEM') and values.get('WEB_TLS_KEY_PEM')) and not (values.get('WEB_TLS_CERT_FILE') and values.get('WEB_TLS_KEY_FILE')):
raise ValueError('Bitte HTTPS-Zertifikat und privaten Schlüssel gemeinsam hochladen')
if 'BACKUP_ENCRYPTION_ENABLED' in normalized and values.get('BACKUP_KEY_ID'):
values['BACKUP_NAMESPACE'] = 'keys/' + values['BACKUP_KEY_ID'] if values['BACKUP_ENCRYPTION_ENABLED'] else 'plain'
if values['BACKUP_DESTINATION'] and values['BACKUP_ENCRYPTION_ENABLED'] and not values.get('BACKUP_KEY_ID'):
raise ValueError('Bitte zuerst eine Wiederherstellungsphrase erzeugen und bestätigen')
if values['WEB_TLS_MODE'] == 'files' and (values.get('WEB_TLS_CERT_PEM') or values.get('WEB_TLS_KEY_PEM')):
try:
from .tls_configuration import validate_pair
except ImportError:
from tls_configuration import validate_pair
validate_pair(values['WEB_TLS_CERT_PEM'], values['WEB_TLS_KEY_PEM'])
previous = json.loads(snap['settings'])
if values == previous:
return self.public()
service_change = any(FIELDS[key]['section'] != 'backup' and (not bootstrap or FIELDS[key]['section'] != 'groups') and values[key] != previous.get(key) for key in normalized)
conn.execute('UPDATE configuration SET settings=?,revision=revision+1,service_revision=service_revision+? WHERE id=1',
(json.dumps(values), int(service_change)))
return self.public()
def phase(self, value):
with self.connect() as conn:
conn.execute('UPDATE configuration SET phase=?,revision=revision+1 WHERE id=1', (value,))
def bootstrap_code(self):
path = self.root / 'setup-code'
try:
return path.read_text().strip()
except FileNotFoundError:
code = secrets.token_urlsafe(32)
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
return path.read_text().strip()
with os.fdopen(fd, 'w') as handle:
handle.write(code)
return code
def accepts_bootstrap(self, supplied):
return self.snapshot()['phase'] != 'configured' and bool(supplied) and hmac.compare_digest(supplied.encode(), self.bootstrap_code().encode())
def finish(self, revision):
with self.connect() as conn:
conn.execute('BEGIN IMMEDIATE')
row = conn.execute('SELECT * FROM configuration WHERE id=1').fetchone()
if row['revision'] != revision:
raise Conflict('Einstellungen wurden inzwischen geändert')
values = json.loads(row['settings'])
required = ('REALM', 'WORKGROUP', 'DOMAIN', 'DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID', 'FSLOGIX_GROUP_SID')
if any(not values.get(key) for key in required):
raise ValueError('Domäne und Gruppen müssen vollständig eingerichtet sein')
conn.execute("UPDATE configuration SET phase='configured',revision=revision+1,service_revision=service_revision+1 WHERE id=1")
(self.root / 'setup-code').unlink(missing_ok=True)
def generate_key(self, owner):
result = backup_keys.generate()
nonce = secrets.token_urlsafe(32)
with self.connect() as conn:
conn.execute('DELETE FROM pending_backup_keys WHERE expires<?', (time.time(),))
revision = conn.execute('SELECT revision FROM configuration WHERE id=1').fetchone()[0]
conn.execute('INSERT INTO pending_backup_keys VALUES(?,?,?,?,?,?,?)',
(nonce, owner, time.time() + 900, revision, result['password'], result['keyId'], result['format']))
return {key: result[key] for key in ('phrase', 'keyId', 'format')} | {'nonce': nonce}
def activate_key(self, owner, nonce, written_down, acknowledge_old):
if written_down is not True:
raise ValueError('Bitte bestätigen, dass die Phrase sicher notiert wurde')
with self.connect() as conn:
conn.execute('BEGIN IMMEDIATE')
pending = conn.execute('SELECT * FROM pending_backup_keys WHERE nonce=? AND owner=? AND expires>?', (nonce, owner, time.time())).fetchone()
current = conn.execute('SELECT * FROM configuration WHERE id=1').fetchone()
if not pending or pending['revision'] != current['revision']:
raise Conflict('Schlüsselerzeugung ist abgelaufen oder Einstellungen wurden geändert')
values = json.loads(current['settings'])
if values.get('BACKUP_ARCHIVE_PASSWORD') and acknowledge_old is not True:
raise ValueError('Alte Sicherungen benötigen weiterhin ihre alte Phrase bzw. ihr altes Passwort; ohne diese sind deren Daten verloren')
values.update(BACKUP_ARCHIVE_PASSWORD=pending['password'], BACKUP_KEY_ID=pending['key_id'],
BACKUP_KEY_FORMAT=pending['format'], BACKUP_NAMESPACE='keys/' + pending['key_id'], BACKUP_ENCRYPTION_ENABLED=True)
conn.execute('UPDATE configuration SET settings=?,revision=revision+1 WHERE id=1', (json.dumps(values),))
conn.execute('DELETE FROM pending_backup_keys WHERE nonce=?', (nonce,))
return self.public('backup')
def import_legacy(self, values):
snap = self.snapshot()
if snap['phase'] == 'configured' or snap['revision'] != 0:
raise Conflict('Die Erstübernahme wurde bereits durchgeführt')
public = {key: validate(key, value) for key, value in values.items() if key in FIELDS}
private = {key: value for key, value in values.items() if key in PRIVATE_FIELDS}
if private.get('TLS_CA_PROVISIONER_PASSWORD'):
public['TLS_CA_PASSWORD'] = private.pop('TLS_CA_PROVISIONER_PASSWORD')
if private.get('TLS_CA_PROVISIONER_PASSWORD_FILE') and Path(private['TLS_CA_PROVISIONER_PASSWORD_FILE']).is_file():
public['TLS_CA_PASSWORD'] = Path(private.pop('TLS_CA_PROVISIONER_PASSWORD_FILE')).read_text().rstrip('\r\n')
if not public.get('WEB_TLS_MODE'):
public['WEB_TLS_MODE'] = 'acme' if public.get('ACME_CA_SERVER') else 'ca' if public.get('TLS_CA_URL') else 'files' if private.get('WEB_TLS_CERT_FILE') else 'self-signed'
if not all(public.get(key) for key in ('REALM', 'WORKGROUP', 'DOMAIN', 'DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID')):
return False
public.setdefault('FSLOGIX_GROUP_SID', public['DOMAIN_USERS_SID'])
# Keep the legacy format and password until encryption is deliberately
# enabled/renewed. Existing remote snapshots remain at their old path.
public['BACKUP_ENCRYPTION_ENABLED'] = False
public.setdefault('BACKUP_AUTO_ENABLED', True)
combined = snap['values'] | public | private
with self.connect() as conn:
conn.execute('BEGIN IMMEDIATE')
changed = conn.execute("UPDATE configuration SET settings=?,phase='configured',revision=1,service_revision=1 WHERE id=1 AND revision=0", (json.dumps(combined),)).rowcount
if not changed:
raise Conflict('Einstellungen wurden inzwischen geändert')
return True
def environment(self, materialize=True):
values = self.snapshot()['values']
result = {name: ('true' if value else 'false') if isinstance(value, bool) else str(value)
for name, value in values.items() if name in FIELDS or name in PRIVATE_FIELDS}
for name in ('LDAP_URI', 'LDAP_BASE_DN', 'AD_DNS_NAME'):
if not result.get(name):
result.pop(name, None)
if values.get('REALM') and not result.get('LDAP_BASE_DN'):
result['LDAP_BASE_DN'] = ','.join('DC=' + part for part in values['REALM'].lower().split('.'))
if values.get('REALM') and not result.get('AD_DNS_NAME'):
hostname = values.get('SAMBA_HOSTNAME', 'adsambafsrv').lower()
result['AD_DNS_NAME'] = hostname if '.' in hostname else hostname + '.' + values['REALM'].lower()
result.update(WEB_ENABLED='true', STATE_ROOT=str(self.root), STATE_DB_PATH=values.get('STATE_DB_PATH', str(self.root / 'shares.db')),
WEB_TLS_CERT_FILE=values.get('WEB_TLS_CERT_FILE', str(self.root / 'tls' / 'web.crt')),
WEB_TLS_KEY_FILE=values.get('WEB_TLS_KEY_FILE', str(self.root / 'tls' / 'web.key')),
WEB_BIND_PORT=values.get('WEB_BIND_PORT', '8443'), WEB_HTTPS_PORT=values.get('WEB_HTTPS_PORT', '443'),
ACME_HTTP_LISTEN='127.0.0.1:8080', ACME_CA_CERTIFICATES=values.get('ACME_CA_CERTIFICATES') or
(str(self.root / 'tls' / 'acme-ca-certificates.pem') if values.get('ACME_CA_CERTIFICATES_PEM') or values.get('ACME_CA_CERTIFICATES_URL') else '/etc/ssl/certs/ca-certificates.crt'))
for key, filename in (('ACME_CA_CERTIFICATES_PEM', 'acme-ca-certificates.pem'), ('TLS_CA_ROOT_PEM', 'ca-root.pem'),
('TLS_CA_PASSWORD', 'ca-password')):
if values.get(key):
directory = self.root / 'tls'
directory.mkdir(mode=0o700, exist_ok=True)
target = directory / filename
if materialize and (not target.exists() or target.read_text() != values[key]):
try:
from .tls_configuration import write_private
except ImportError:
from tls_configuration import write_private
write_private(target, values[key])
if key == 'TLS_CA_ROOT_PEM':
result['TLS_CA_ROOT'] = str(target)
if not result.get('TLS_CA_FINGERPRINT'):
result['TLS_CA_FINGERPRINT'] = hashlib.sha256(ssl.PEM_cert_to_DER_cert(values[key])).hexdigest()
if key == 'ACME_CA_CERTIFICATES_PEM':
result['ACME_CA_CERTIFICATES'] = str(target)
if key == 'TLS_CA_PASSWORD':
result['TLS_CA_PROVISIONER_PASSWORD_FILE'] = str(target)
elif key == 'TLS_CA_PASSWORD' and materialize:
(self.root / 'tls' / filename).unlink(missing_ok=True)
return result
def service_environment(self, inherited=None):
result = dict(os.environ if inherited is None else inherited)
for name in set(FIELDS) | PRIVATE_FIELDS:
result.pop(name, None)
result.update(self.environment())
return result
def parse_legacy(text):
result = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('export '):
line = line[7:]
key, sep, value = line.partition('=')
if not sep or key not in FIELDS and key not in PRIVATE_FIELDS:
continue
tokens = shlex.split(value, comments=True, posix=True)
result[key] = ' '.join(tokens)
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument('action', choices=['import-legacy', 'import-runtime', 'export-shell'])
args = parser.parse_args()
store = Store()
if args.action in ('import-legacy', 'import-runtime'):
payload = sys.stdin.read(1024 * 1024)
if store.snapshot()['revision'] != 0:
print('Persistent configuration already exists; legacy import skipped.')
return
if args.action == 'import-runtime':
items = json.loads(payload)
if not isinstance(items, list) or any(not isinstance(item, str) for item in items):
raise ValueError('Invalid container configuration')
values = dict(item.split('=', 1) for item in items if '=' in item)
else:
values = parse_legacy(payload)
if not store.import_legacy(values):
if args.action == 'import-runtime':
print('No legacy domain configuration found; continue web setup.')
return
raise ValueError('Unvollständige frühere Konfiguration')
print('Imported existing configuration without changing data or the domain join.')
else:
for key, value in store.environment().items():
print('export ' + key + '=' + shlex.quote(value))
if __name__ == '__main__':
main()
+133
View File
@@ -0,0 +1,133 @@
"""Keep setup HTTPS available while AD services join, start, or recover."""
import datetime as dt
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import configuration
import tls_configuration
import http_setup
APP = Path(__file__).parent
def stop(process):
if process is None:
return
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
return
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
process.wait()
def start(command, store, extra=None):
environment = store.service_environment()
environment.update(extra or {})
return subprocess.Popen(command, env=environment, start_new_session=True)
def write_status(store, **changes):
target = store.root / 'services-status.json'
temporary = target.with_suffix('.tmp')
temporary.write_text(json.dumps(changes))
os.chmod(temporary, 0o600)
os.replace(temporary, target)
def main():
store = configuration.Store()
if store.snapshot()['revision'] == 0:
store.import_legacy(dict(os.environ))
if store.snapshot()['phase'] != 'configured':
print('[setup] Open http://<server>/ for HTTPS only. HTTPS setup code: ' + http_setup.setup_code(store), flush=True)
print('[setup] Open https://<server>/ and enter setup code: ' + store.bootstrap_code(), flush=True)
tls_configuration.prepare(store)
ui = service = backup = certificate = None
http = start([sys.executable, str(APP / 'http_setup.py')], store)
revision = -1
running = True
next_retry = 0
next_tls_retry = 0
def terminate(*args):
nonlocal running
running = False
signal.signal(signal.SIGTERM, terminate)
signal.signal(signal.SIGINT, terminate)
try:
while running:
snap = store.snapshot()
if snap['service_revision'] != revision:
stop(service)
stop(certificate)
stop(ui)
service = ui = certificate = None
Path('/run/adfs-domain-ready').unlink(missing_ok=True)
Path('/run/adfs-services-ready').unlink(missing_ok=True)
revision = snap['service_revision']
next_retry = 0
next_tls_retry = 0
try:
tls_configuration.prepare(store)
except (OSError, ValueError, subprocess.SubprocessError):
write_status(store, state='failed', message='HTTPS-Zertifikat konnte nicht eingerichtet werden')
if ui is None or ui.poll() is not None:
ui = start([sys.executable, str(APP / 'run_service.py'), 'web_ui.py'], store)
if http.poll() is not None:
http = start([sys.executable, str(APP / 'http_setup.py')], store)
tls_marker = Path(store.environment()['WEB_TLS_CERT_FILE']).parent / 'bootstrap-certificate'
wants_acme = snap['values']['WEB_TLS_MODE'] == 'acme' and bool(snap['values']['ACME_CA_SERVER'])
if certificate is not None and certificate.poll() is not None:
succeeded = certificate.returncode == 0
stop(certificate)
certificate = None
tls_configuration.write_private(store.root / 'https-status.json', json.dumps({'state': 'ready' if succeeded else 'failed', 'message': 'HTTPS ist eingerichtet. Über HTTPS fortfahren.' if succeeded else 'ACME-Zertifikat konnte nicht angefordert werden. Hostname, CA und Erreichbarkeit von Port 80 prüfen.'}))
if wants_acme and tls_marker.exists() and certificate is None and time.monotonic() >= next_tls_retry:
tls_configuration.write_private(store.root / 'https-status.json', json.dumps({'state': 'working', 'message': 'ACME-Zertifikat wird angefordert'}))
certificate = start([str(APP / 'init.sh'), '--configure-tls'], store, {'ADFS_SUPERVISED': 'true'})
next_tls_retry = time.monotonic() + 60
desired = snap['phase'] in ('joining', 'groups', 'configured') and all(snap['values'].get(key) for key in ('REALM', 'WORKGROUP', 'DOMAIN'))
if wants_acme and (certificate is not None or tls_marker.exists()):
desired = False
if desired and (service is None or service.poll() is not None) and time.monotonic() >= next_retry:
mode = [] if snap['phase'] == 'configured' else ['--bootstrap-domain']
write_status(store, state='starting', message='AD-Dienste werden gestartet')
service = start([str(APP / 'init.sh'), *mode], store, {'ADFS_SUPERVISED': 'true'})
next_retry = time.monotonic() + 30
if service is not None and service.poll() is not None:
code = service.returncode
stop(service)
service = None
Path('/run/adfs-services-ready').unlink(missing_ok=True)
write_status(store, state='failed', message=f'AD-Dienste konnten nicht gestartet werden (Status {code}); Einstellungen prüfen')
elif service is not None and Path('/run/adfs-domain-ready').exists():
if snap['phase'] == 'joining':
store.phase('groups')
write_status(store, state='running', message='Domänenverbindung hergestellt')
if backup is not None and backup.poll() is not None:
backup = None
values = snap['values']
now = dt.datetime.now(dt.timezone.utc)
if snap['phase'] == 'configured' and backup is None and values['BACKUP_DESTINATION'] and values['BACKUP_AUTO_ENABLED'] and now.hour == values['BACKUP_START_HOUR']:
slot = now.strftime('%Y-%m-%dT%H')
with store.connect() as conn:
claimed = conn.execute('INSERT OR IGNORE INTO scheduled_backups VALUES(?)', (slot,)).rowcount
if claimed:
backup = start([sys.executable, str(APP / 'run_service.py'), 'backup_to_destination.py'], store, {'BACKUP_TRIGGER': 'automatic'})
time.sleep(1)
finally:
stop(service)
stop(ui)
stop(backup)
stop(certificate)
stop(http)
return 0
if __name__ == '__main__':
sys.exit(main())
+5
View File
@@ -0,0 +1,5 @@
import ssl
import urllib.request
response = urllib.request.urlopen('https://127.0.0.1:8443/healthz', context=ssl._create_unverified_context(), timeout=3)
raise SystemExit(0 if response.status == 200 else 1)
+166
View File
@@ -0,0 +1,166 @@
"""HTTP exposes public HTTPS setup only; credentials always require TLS."""
import hmac
import http.client
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import secrets
import ssl
import threading
import urllib.parse
try:
from . import configuration
from .tls_configuration import write_private
except ImportError:
import configuration
from tls_configuration import write_private
APP = Path(__file__).parent
TLS_FIELDS = {'WEB_HOSTNAME', 'ACME_CA_SERVER', 'ACME_CA_CERTIFICATES_PEM'}
def setup_code(store):
path = store.root / 'https-setup-code'
try:
return path.read_text().strip()
except FileNotFoundError:
code = secrets.token_urlsafe(32)
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
return path.read_text().strip()
with os.fdopen(fd, 'w') as handle:
handle.write(code)
return code
class Server(ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
capacity = threading.BoundedSemaphore(32)
def process_request(self, request, address):
if not self.capacity.acquire(blocking=False):
self.shutdown_request(request)
return
try:
super().process_request(request, address)
except BaseException:
self.capacity.release()
raise
def process_request_thread(self, request, address):
try:
request.settimeout(10)
super().process_request_thread(request, address)
finally:
self.capacity.release()
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass # Never log setup codes, URLs or request bodies.
def reply(self, status, value, content_type='application/json'):
payload = json.dumps(value).encode() if content_type == 'application/json' else value
self.send_response(status)
self.send_header('Content-Type', content_type)
self.send_header('Content-Length', str(len(payload)))
self.send_header('Cache-Control', 'no-store')
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('Referrer-Policy', 'no-referrer')
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
path = urllib.parse.urlsplit(self.path).path
if path.startswith('/.well-known/acme-challenge/'):
# The ACME standalone responder listens on loopback, never port 80.
proxy = http.client.HTTPConnection('127.0.0.1', 8080, timeout=5)
try:
proxy.request('GET', self.path, headers={'Host': self.headers.get('Host', '')})
response = proxy.getresponse()
payload = response.read(16385)
if len(payload) > 16384:
raise ValueError('Challenge too large')
self.reply(response.status, payload, 'text/plain')
except (OSError, ValueError, http.client.HTTPException):
self.reply(404, {'error': 'Keine aktive ACME-Challenge'})
finally:
proxy.close()
return
store = configuration.Store()
snap = store.snapshot()
port = str(snap['values'].get('WEB_HTTPS_PORT', '443'))
https_url = 'https://' + snap['values']['WEB_HOSTNAME'] + (':' + port if port != '443' else '') + '/'
if path == '/api/https/status':
try:
progress = json.loads((store.root / 'https-status.json').read_text())
except (OSError, ValueError):
progress = {'state': 'waiting'}
self.reply(200, {'state': progress.get('state'), 'message': progress.get('message', ''),
'hostname': snap['values']['WEB_HOSTNAME'], 'httpsUrl': https_url,
'configured': snap['phase'] == 'configured'})
return
if snap['phase'] == 'configured':
self.send_response(308)
self.send_header('Location', https_url)
self.send_header('Content-Length', '0')
self.end_headers()
return
files = {'/': ('https-setup.html', 'text/html; charset=utf-8'),
'/assets/https-setup.js': ('https-setup.js', 'text/javascript; charset=utf-8'),
'/assets/styles.css': ('styles.css', 'text/css; charset=utf-8')}
if path not in files:
self.reply(403, {'error': 'Über HTTP ist ausschließlich die HTTPS-Einrichtung verfügbar'})
return
filename, kind = files[path]
self.reply(200, (APP / 'web' / filename).read_bytes(), kind)
def do_POST(self):
store = configuration.Store()
if self.path != '/api/https/configure' or store.snapshot()['phase'] == 'configured':
self.reply(403, {'error': 'Über HTTP ist ausschließlich die HTTPS-Einrichtung verfügbar'})
return
if self.headers.get_content_type() != 'application/json' or self.headers.get('Sec-Fetch-Site') in {'same-site', 'cross-site'}:
self.reply(403, {'error': 'Anfrage muss vom selben Origin stammen'})
return
if self.headers.get('Origin') != 'http://' + self.headers.get('Host', ''):
self.reply(403, {'error': 'Ungültiger Origin'})
return
supplied = self.headers.get('X-HTTPS-Setup-Code', '')
if not supplied or not hmac.compare_digest(supplied.encode(), setup_code(store).encode()):
self.reply(403, {'error': 'Ungültiger HTTPS-Einrichtungscode'})
return
try:
length = int(self.headers.get('Content-Length', '0'))
if not 0 < length <= 131072:
raise ValueError('Ungültige Anfragelänge')
body = json.loads(self.rfile.read(length))
if not isinstance(body, dict) or set(body) - TLS_FIELDS:
raise ValueError('Nur HTTPS-Hostname, ACME-Adresse und CA-Zertifikat sind zulässig')
if not body.get('WEB_HOSTNAME') or not body.get('ACME_CA_SERVER'):
raise ValueError('HTTPS-Hostname und ACME-Adresse sind erforderlich')
url = urllib.parse.urlsplit(body['ACME_CA_SERVER'])
if url.username is not None or url.password is not None:
raise ValueError('Die HTTP-Einrichtung darf keine Zugangsdaten enthalten')
if body.get('ACME_CA_CERTIFICATES_PEM'):
try:
ssl.create_default_context().load_verify_locations(cadata=body['ACME_CA_CERTIFICATES_PEM'])
except (ssl.SSLError, TypeError) as exc:
raise ValueError('CA-Zertifikat ist kein gültiges PEM-Zertifikat') from exc
body['WEB_TLS_MODE'] = 'acme'
snap = store.snapshot()
store.save(body, snap['revision'], bootstrap=True)
# Force re-issuance on an explicit retry, including a changed root CA.
write_private(Path(store.environment()['WEB_TLS_CERT_FILE']).parent / 'bootstrap-certificate', '1')
write_private(store.root / 'https-status.json', json.dumps({'state': 'pending', 'message': 'ACME-Zertifikat wird angefordert'}))
self.reply(202, {'accepted': True})
except (ValueError, TypeError, OSError) as exc:
self.reply(400, {'error': str(exc)})
if __name__ == '__main__':
Server(('0.0.0.0', 80), Handler).serve_forever()
+41 -6
View File
@@ -355,7 +355,7 @@ selected_tls_mode() {
printf 'ca'
fi
;;
acme|ca|files) printf '%s' "$WEB_TLS_MODE" ;;
acme|ca|files|self-signed) printf '%s' "$WEB_TLS_MODE" ;;
*) return 1 ;;
esac
}
@@ -458,7 +458,7 @@ configure_web_tls() {
local provisioner_password_file=""
if ! tls_mode="$(selected_tls_mode)"; then
printf '[init] ERROR: WEB_TLS_MODE must be acme, ca, or files\n' >&2
printf '[init] ERROR: WEB_TLS_MODE must be self-signed, acme, ca, or files\n' >&2
return 1
fi
export ACTIVE_WEB_TLS_MODE="$tls_mode"
@@ -469,6 +469,10 @@ configure_web_tls() {
export STEPPATH="${TLS_CA_STATE_DIR:-/state/tls-client}"
mkdir -p "$(dirname "$WEB_TLS_CERT_FILE")" "$(dirname "$WEB_TLS_KEY_FILE")" "$STEPPATH"
if [[ "$tls_mode" == "self-signed" ]]; then
return
fi
if [[ "$tls_mode" == "files" ]]; then
if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" ]]; then
printf '[init] ERROR: WEB_TLS_MODE=files requires %s and %s\n' "$WEB_TLS_CERT_FILE" "$WEB_TLS_KEY_FILE" >&2
@@ -481,8 +485,9 @@ configure_web_tls() {
require_env ACME_CA_SERVER
require_env ACME_CA_CERTIFICATES
ensure_acme_ca_certificates
if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" ]]; then
if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" || -f "$(dirname "$WEB_TLS_CERT_FILE")/bootstrap-certificate" ]]; then
request_acme_certificate
rm -f "$(dirname "$WEB_TLS_CERT_FILE")/bootstrap-certificate"
fi
return
fi
@@ -495,7 +500,7 @@ configure_web_tls() {
step ca bootstrap --force --ca-url "$TLS_CA_URL" --fingerprint "$TLS_CA_FINGERPRINT"
fi
if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" ]]; then
if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" || -f "$(dirname "$WEB_TLS_CERT_FILE")/bootstrap-certificate" ]]; then
log "Requesting HTTPS certificate for ${WEB_HOSTNAME}"
if [[ -n "${TLS_CA_TOKEN:-}" ]]; then
step ca certificate "$WEB_HOSTNAME" "$WEB_TLS_CERT_FILE" "$WEB_TLS_KEY_FILE" --token "$TLS_CA_TOKEN" --force
@@ -522,6 +527,7 @@ configure_web_tls() {
fi
chmod 0600 "$WEB_TLS_KEY_FILE"
chmod 0644 "$WEB_TLS_CERT_FILE"
rm -f "$(dirname "$WEB_TLS_CERT_FILE")/bootstrap-certificate"
}
start_acme_renewal_daemon() {
@@ -546,7 +552,17 @@ start_observability_services() {
log 'Starting Samba audit collector'
python3 /app/audit_collector.py &
if web_should_start; then
if [[ "${ADFS_SUPERVISED:-false}" == "true" ]]; then
configure_web_tls
if env_is_true "${WEB_TLS_AUTORENEW:-true}"; then
case "$ACTIVE_WEB_TLS_MODE" in
acme) start_acme_renewal_daemon ;;
ca) step ca renew --daemon --force "$WEB_TLS_CERT_FILE" "$WEB_TLS_KEY_FILE" & ;;
esac
fi
log 'Starting document search and OCR worker'
python3 /app/document_index.py &
elif web_should_start; then
ensure_web_jwt_secret
configure_web_tls
unset TLS_CA_PROVISIONER_PASSWORD TLS_CA_TOKEN
@@ -582,7 +598,7 @@ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
17 * * * * root source /app/runtime.env && /usr/bin/python3 /app/trash.py --cleanup
EOF
if [[ -n "${BACKUP_DESTINATION:-}" ]] && env_is_true "${BACKUP_AUTO_ENABLED:-true}"; then
if [[ "${ADFS_SUPERVISED:-false}" != "true" ]] && [[ -n "${BACKUP_DESTINATION:-}" ]] && env_is_true "${BACKUP_AUTO_ENABLED:-true}"; then
cat >> /etc/cron.d/reconcile-shares <<EOF
0 ${BACKUP_START_HOUR} * * * root source /app/runtime.env && BACKUP_TRIGGER=automatic /usr/bin/python3 /app/backup_to_destination.py
EOF
@@ -591,6 +607,17 @@ EOF
chmod 0644 /etc/cron.d/reconcile-shares
}
if [[ "${ADFS_SUPERVISED:-false}" == "true" ]]; then
source <(python3 /app/configuration.py export-shell)
fi
if [[ "${1:-}" == "--configure-tls" ]]; then
configure_web_tls
exit 0
fi
if [[ "${1:-}" == "--bootstrap-domain" ]]; then
export DOMAIN_USERS_SID="${DOMAIN_USERS_SID:-S-1-5-32-545}"
export DOMAIN_ADMINS_SID="${DOMAIN_ADMINS_SID:-S-1-5-32-544}"
fi
require_env REALM
require_env WORKGROUP
require_env DOMAIN
@@ -624,8 +651,15 @@ ensure_machine_keytab
log 'Starting winbindd'
winbindd -F --no-process-group &
winbind_pid=$!
wait_for_winbind
touch /run/adfs-domain-ready
if [[ "${1:-}" == "--bootstrap-domain" ]]; then
log 'Domain joined; waiting for web setup to select groups.'
wait "$winbind_pid"
exit "$?"
fi
register_ad_dns_record
resolve_share_groups_from_sids
@@ -654,4 +688,5 @@ log 'Starting cron daemon'
cron -f &
log 'Starting smbd in foreground'
touch /run/adfs-services-ready
exec smbd -F --no-process-group
+31
View File
@@ -0,0 +1,31 @@
"""Offline recovery; never accept a recovery phrase through argv/environment."""
import argparse
import getpass
from pathlib import Path
import subprocess
try:
from .backup_keys import archive_key
except ImportError:
from backup_keys import archive_key
def main():
parser = argparse.ArgumentParser(description='Decrypt a backup archive into a new recovery directory; never overwrite live data.')
parser.add_argument('archive', type=Path)
parser.add_argument('output', type=Path)
args = parser.parse_args()
if args.output.exists():
parser.error('The recovery output must be a new directory')
if not args.archive.is_file():
parser.error('Archive does not exist')
password = archive_key(getpass.getpass('24-word recovery phrase: '))
args.output.mkdir(mode=0o700, parents=True)
result = subprocess.run(['7z', 'x', '-aos', '-o' + str(args.output.resolve()), '--', str(args.archive.resolve())],
input=(password + '\n').encode(), capture_output=True)
if result.returncode:
raise SystemExit('Recovery failed. Check the phrase, archive, and available disk space. No live data was changed.')
print('Recovered into ' + str(args.output) + '; inspect before copying to live storage.')
if __name__ == '__main__':
main()
+17
View File
@@ -0,0 +1,17 @@
"""Start a service from a single persisted configuration snapshot."""
import os
from pathlib import Path
import runpy
import sys
import configuration
if __name__ == '__main__':
environment = configuration.Store().service_environment()
os.environ.clear()
os.environ.update(environment)
allowed = {'web_ui.py', 'backup_to_destination.py', 'document_index.py', 'audit_collector.py', 'reconcile_shares.py', 'trash.py'}
if len(sys.argv) < 2 or sys.argv[1] not in allowed:
raise SystemExit('Unknown service')
target = Path(__file__).parent / sys.argv[1]
sys.argv = [str(target), *sys.argv[2:]]
runpy.run_path(str(target), run_name='__main__')
+80
View File
@@ -0,0 +1,80 @@
"""Provision persistent bootstrap TLS and validate uploaded certificate pairs."""
import os
import json
from pathlib import Path
import socket
import ssl
import subprocess
import tempfile
import time
def write_private(path, value):
path = Path(path)
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
fd, temp = tempfile.mkstemp(prefix='.tls-', dir=path.parent)
try:
os.fchmod(fd, 0o600)
with os.fdopen(fd, 'w') as handle:
handle.write(value)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp, path)
finally:
if os.path.exists(temp):
os.unlink(temp)
def validate_pair(cert, key):
with tempfile.TemporaryDirectory() as root:
cert_path, key_path = Path(root) / 'cert', Path(root) / 'key'
write_private(cert_path, cert)
write_private(key_path, key)
try:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert_path, key_path)
except (OSError, ssl.SSLError) as exc:
raise ValueError('Zertifikat und privater Schlüssel sind ungültig oder passen nicht zusammen') from exc
def prepare(store):
values = store.snapshot()['values']
environment = store.environment()
cert = Path(environment['WEB_TLS_CERT_FILE'])
key = Path(environment['WEB_TLS_KEY_FILE'])
mode = values['WEB_TLS_MODE']
marker = cert.parent / 'bootstrap-certificate'
identity_path = cert.parent / 'configuration.json'
identity = {'hostname': values['WEB_HOSTNAME'], 'mode': mode}
try:
previous = json.loads(identity_path.read_text())
except (OSError, ValueError):
previous = None
if mode == 'files' and values.get('WEB_TLS_CERT_PEM') and values.get('WEB_TLS_KEY_PEM'):
validate_pair(values['WEB_TLS_CERT_PEM'], values['WEB_TLS_KEY_PEM'])
if not cert.exists() or cert.read_text() != values['WEB_TLS_CERT_PEM'] or not key.exists() or key.read_text() != values['WEB_TLS_KEY_PEM']:
write_private(key, values['WEB_TLS_KEY_PEM'])
write_private(cert, values['WEB_TLS_CERT_PEM'])
marker.unlink(missing_ok=True)
write_private(identity_path, json.dumps(identity))
return
if cert.is_file() and key.is_file() and (previous is None or previous == identity):
valid = True
try:
validate_pair(cert.read_text(), key.read_text())
expired = ssl.cert_time_to_seconds(ssl._ssl._test_decode_cert(str(cert))['notAfter']) <= time.time() + 86400 * 7
except (OSError, ValueError, ssl.SSLError):
valid = False
expired = True
if valid and (not expired or mode != 'self-signed'):
write_private(identity_path, json.dumps(identity))
return
cert.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
hostname = values['WEB_HOSTNAME'] or 'localhost'
with tempfile.TemporaryDirectory(dir=cert.parent) as root:
generated_cert, generated_key = Path(root) / 'cert', Path(root) / 'key'
command = ['step', 'certificate', 'create', hostname, str(generated_cert), str(generated_key),
'--profile', 'self-signed', '--subtle', '--no-password', '--insecure', '--not-after', '8760h',
'--san', 'localhost', '--san', '127.0.0.1', '--san', hostname, '--san', socket.gethostname()]
subprocess.run(command, check=True, capture_output=True, timeout=30)
write_private(key, generated_key.read_text())
write_private(cert, generated_cert.read_text())
write_private(marker, '1')
write_private(identity_path, json.dumps(identity))
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2013-2016 Pavol Rusnak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+7
View File
@@ -0,0 +1,7 @@
The English BIP39 wordlist is vendored from Bitcoin BIPs:
https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt
The identical list is distributed by Trezor's python-mnemonic under the included MIT license:
https://github.com/trezor/python-mnemonic
SHA-256 of english.txt: 2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda
+2048
View File
File diff suppressed because it is too large. Load diff
+7 -1
View File
@@ -108,6 +108,7 @@ function empty(message) { return `<div class="empty">${esc(message)}</div>`; }
function badge(text, kind = "") { return `<span class="badge ${kind}">${esc(text)}</span>`; }
function routeFor(path) {
if (path.startsWith('/admin/settings') || path.startsWith('/settings')) return 'settings';
path = path.replace(/^\/admin(?=\/|$)/, "") || "/overview";
if (path.startsWith("/storage/data")) return "storage-data";
if (path.startsWith("/storage/users")) return "storage-users";
@@ -152,6 +153,10 @@ async function navigate(path, replace = false) {
if (route === "backup") await renderBackup();
if (route === "report") await renderReport();
if (route === "system") await renderSystem();
if (route === 'settings') {
content.innerHTML = pageHead('Einstellungen', 'Serverkonfiguration dauerhaft speichern.') + '<div id="configuration-settings"></div>';
await ConfigurationUI.mount(document.querySelector('#configuration-settings'), {api, notice, onDirty: dirty => { state.accessDirty = dirty; }});
}
content.focus();
} catch (error) {
content.innerHTML = pageHead("Seite konnte nicht geladen werden", error.message) + `<section class="panel">${empty("Dienststatus prüfen und erneut versuchen.")}</section>`;
@@ -563,7 +568,8 @@ async function renderBackup() {
"Sicherungen",
"Sicherungen manuell starten sowie Fortschritt und Ausgabe verfolgen.",
'<button id="start-backup" type="button">Sicherung jetzt starten</button>'
) + '<div id="backup-body"></div>';
) + '<details class="panel"><summary>Sicherungsziel, Zeitplan und Verschlüsselung</summary><div id="backup-settings" class="settings-advanced"></div></details><div id="backup-body"></div>';
void ConfigurationUI.mount(document.querySelector('#backup-settings'), {api, notice, section:'backup', onDirty: dirty => { state.accessDirty = dirty; }}).catch(error => notice(error.message));
const button = document.querySelector("#start-backup");
const body = document.querySelector("#backup-body");
let logLines = [];
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>HTTPS einrichten · Dateiserver</title><link rel="stylesheet" href="/assets/styles.css"></head><body><header class="portal-header"><strong>Dateiserver · HTTPS einrichten</strong></header><main class="setup-main"><h1>HTTPS zuerst einrichten</h1><p>Über HTTP können Sie ausschließlich das HTTPS-Zertifikat einrichten. Domänenbeitritt und alle Zugangsdaten werden anschließend über HTTPS konfiguriert.</p><section class="panel"><form id="https-form" class="stack"><label>HTTPS-Einrichtungscode<input name="code" type="password" autocomplete="off" required></label><small class="muted">Den Code finden Sie unter „HTTPS setup code“ in <code>docker compose logs samba</code>.</small><label>HTTPS-Hostname<input name="hostname" required placeholder="files.example.org"></label><label>ACME-Verzeichnisadresse<input name="acme" type="url" required placeholder="https://ca.example.org/acme/acme/directory"></label><label>Eigenes Root-CA-Zertifikat (optional, PEM)<input name="root" type="file" accept=".pem,.crt,.cer"></label><small class="muted">Ohne eigenen Upload werden die öffentlichen System-CAs verwendet.</small><p id="https-error" class="error" role="alert" hidden></p><button type="submit">HTTPS einrichten</button></form></section><p id="https-status" role="status"></p><a id="https-next" hidden>Über HTTPS mit der Einrichtung fortfahren</a></main><script src="/assets/https-setup.js" defer></script></body></html>
+21
View File
@@ -0,0 +1,21 @@
(() => {
const form = document.querySelector('#https-form'), status = document.querySelector('#https-status'), errorBox = document.querySelector('#https-error'), next = document.querySelector('#https-next');
form.elements.hostname.value = location.hostname;
form.onsubmit = async event => {
event.preventDefault(); errorBox.hidden = true; const button = form.querySelector('button'); button.disabled = true;
try {
const root = form.elements.root.files[0];
const response = await fetch('/api/https/configure', {method:'POST', headers:{'Content-Type':'application/json', 'X-HTTPS-Setup-Code':form.elements.code.value}, body:JSON.stringify({WEB_HOSTNAME:form.elements.hostname.value, ACME_CA_SERVER:form.elements.acme.value, ACME_CA_CERTIFICATES_PEM:root ? await root.text() : ''})});
const data = await response.json(); if (!response.ok) throw new Error(data.error);
form.elements.code.value = ''; status.textContent = 'ACME-Zertifikat wird angefordert …';
} catch (error) { errorBox.textContent = error.message; errorBox.hidden = false; }
finally { button.disabled = false; }
};
setInterval(async () => {
try {
const data = await (await fetch('/api/https/status')).json(); status.textContent = data.message || '';
next.hidden = !(data.state === 'ready' || data.configured);
if (!next.hidden) { next.href = data.httpsUrl; }
} catch { status.textContent = 'Dienst wird neu gestartet …'; }
}, 2000);
})();
+2
View File
@@ -37,6 +37,7 @@
<a href="/admin/backup" data-route="backup">Sicherungen</a>
<a href="/admin/report" data-route="report">PDF-Bericht</a>
<a href="/admin/system" data-route="system">System</a>
<a href="/admin/settings" data-route="settings">Einstellungen</a>
</nav>
<div class="sidebar-footer"><a href="/">Dateiansicht</a><span id="session-user"></span><button id="logout" class="link-button">Abmelden</button></div>
</aside>
@@ -44,6 +45,7 @@
<main id="content" class="content" tabindex="-1"></main>
</div>
<div id="toast" class="toast" role="status" hidden></div>
<script src="/assets/settings.js" defer></script>
<script src="/assets/app.js" defer></script>
</body>
</html>
+121
View File
@@ -0,0 +1,121 @@
/* Configuration controls share the application's existing form styles. */
(() => {
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'}[c]));
const labels = {'self-signed':'Selbstsigniert', acme:'ACME', ca:'Smallstep CA', files:'Zertifikat und Schlüssel hochladen'};
function fieldMarkup(field, groups = [], bootstrap = false) {
const {key, kind, label, value, configured} = field;
const id = 'setting-' + key;
let input;
if (kind === 'bool') return `<label class="settings-check"><input id="${id}" name="${key}" type="checkbox" ${value ? 'checked' : ''}>${esc(label)}</label>`;
if (kind === 'group') {
const options = [...groups];
if (value && !options.some(group => group.sid === value)) options.push({sid:value, name:value});
input = `<select id="${id}" name="${key}" required>${options.map(group => `<option value="${esc(group.sid)}" ${group.sid === value ? 'selected' : ''}>${esc(group.name)}</option>`).join('')}</select>`;
} else if (kind === 'choice') input = `<select id="${id}" name="${key}">${field.choices.map(option => `<option value="${esc(option)}" ${value === option ? 'selected' : ''}>${esc(labels[option] || option)}</option>`).join('')}</select>`;
else if (kind.includes('pem')) input = `<textarea id="${id}" name="${key}" rows="5" spellcheck="false" autocomplete="off" placeholder="${configured ? 'Gespeichert; leer lassen zum Beibehalten' : '-----BEGIN …-----'}">${esc(value)}</textarea>`;
else input = `<input id="${id}" name="${key}" type="${kind === 'int' ? 'number' : ['secret', 'secreturl'].includes(kind) ? 'password' : 'text'}" value="${esc(value)}" ${kind === 'int' ? `min="${field.minimum}" max="${field.maximum}" step="1"` : ''} ${!bootstrap && ['REALM','WORKGROUP'].includes(key) ? 'readonly' : ''} ${field.required ? 'required' : ''} autocomplete="${kind === 'secret' ? 'new-password' : 'off'}" placeholder="${configured ? 'Gespeichert; leer lassen zum Beibehalten' : key === 'BACKUP_DESTINATION' ? 'sftp://benutzer:passwort@server/pfad' : ''}">`;
const hint = field.summary ? `<small class="muted">Aktuelles Ziel: ${esc(field.summary)}</small>` : key === 'BACKUP_DESTINATION' ? '<small class="muted">Unterstützt rsync, SFTP, SMB und WebDAV. Zugangsdaten in der Adresse bitte URL-kodieren.</small>' : '';
input = input.replace(/^<(input|select|textarea)\b/, `<$1 aria-label="${esc(label)}"`);
const clear = configured && ['secret','secretpem'].includes(kind) ? `<label class="settings-check"><input name="clear-${key}" type="checkbox">Gespeicherten Wert löschen</label>` : '';
return `<div data-setting="${key}"><label>${esc(label)}${input}${hint}</label>${clear}</div>`;
}
function readValues(form, fields) {
const values = {};
for (const field of fields) {
const input = form.elements.namedItem(field.key);
if (!input || input.disabled) continue;
if (form.elements.namedItem('clear-' + field.key)?.checked) { values[field.key] = ''; continue; }
if (['secret','secreturl','secretpem'].includes(field.kind) && !input.value) continue;
values[field.key] = field.kind === 'bool' ? input.checked : field.kind === 'int' ? Number(input.value) : input.value;
}
return values;
}
function tlsVisibility(form) {
const mode = form.elements.namedItem('WEB_TLS_MODE');
if (!mode) return;
const update = () => form.querySelectorAll('[data-setting]').forEach(label => {
const key = label.dataset.setting;
const active = key.startsWith('ACME_') ? mode.value === 'acme' : key.startsWith('TLS_CA_') ? mode.value === 'ca' : ['WEB_TLS_CERT_PEM','WEB_TLS_KEY_PEM'].includes(key) ? mode.value === 'files' : true;
label.hidden = !active;
label.querySelectorAll('input,textarea,select').forEach(input => { input.disabled = !active; });
});
mode.addEventListener('change', update); update();
}
async function recoveryDialog(api, configuration, refreshed) {
const result = await api('/api/settings/backup-key/generate', {method:'POST', body:'{}'});
const oldKey = configuration.encryption.keyId || configuration.encryption.legacy;
const dialog = document.createElement('dialog');
dialog.className = 'access-dialog settings-key-dialog';
dialog.setAttribute('aria-labelledby', 'recovery-title');
dialog.innerHTML = `<h2 id="recovery-title">Wiederherstellungsphrase notieren</h2><p>Diese Phrase wird nur jetzt angezeigt. Sie entschlüsselt die vollständige Sicherung, einschließlich Zugangsdaten und Serverzustand. Bewahren Sie sie getrennt vom Server auf.</p><ol class="recovery-words">${result.phrase.split(' ').map(word => `<li>${esc(word)}</li>`).join('')}</ol><p class="muted">Schlüsselkennung: ${esc(result.keyId)}</p><form class="stack"><label class="settings-check"><input name="written" type="checkbox" required>Ich habe alle 24 Wörter in der richtigen Reihenfolge sicher notiert.</label>${oldKey ? '<p class="error">Alte Sicherungen bleiben erhalten und benötigen weiterhin ihre alte Phrase bzw. ihr altes Passwort. Geht diese Information verloren, sind die darin gespeicherten Daten nicht wiederherstellbar.</p><label class="settings-check"><input name="old" type="checkbox" required>Ich bewahre auch die bisherige Phrase bzw. das bisherige Passwort auf.</label>' : ''}<p class="error" role="alert" hidden></p><div class="access-dialog-actions"><button type="button" data-close>Abbrechen</button><button type="submit">Schlüssel aktivieren</button></div></form>`;
// The phrase stays in this dialog only; it is never stored in browser storage.
result.phrase = '';
document.body.append(dialog);
dialog.addEventListener('close', () => { dialog.replaceChildren(); dialog.remove(); }, {once:true});
dialog.querySelector('[data-close]').onclick = () => dialog.close();
dialog.querySelector('form').onsubmit = async event => {
event.preventDefault(); const form = event.currentTarget, button = form.querySelector('[type=submit]'); button.disabled = true;
try {
await api('/api/settings/backup-key/activate', {method:'POST', body:JSON.stringify({nonce:result.nonce, writtenDown:form.elements.written.checked, acknowledgeOldBackups:oldKey ? form.elements.old.checked : false})});
dialog.close(); await refreshed();
} catch (error) { const target = form.querySelector('[role=alert]'); target.textContent = error.message; target.hidden = false; button.disabled = false; }
};
dialog.showModal();
}
async function mount(host, {api, notice, section = '', initialSection = '', onDirty = () => {}}) {
const data = await api('/api/settings' + (section ? '?section=' + section : ''));
if (!host.isConnected) return;
let selected = section || initialSection || data.sections[0].id;
const render = async () => {
const current = data.sections.find(item => item.id === selected);
let groups = [];
if (selected === 'groups') groups = (await api('/api/settings/groups')).groups;
if (!host.isConnected) return;
host.innerHTML = `${!section ? `<div class="settings-tabs" role="group" aria-label="Einstellungen">${data.sections.map(item => `<button type="button" data-section="${item.id}" aria-pressed="${item.id === selected}">${esc(item.label)}</button>`).join('')}</div>` : ''}<section class="panel"><h2>${esc(current.label)}</h2><form class="stack settings-form">${current.fields.map(field => fieldMarkup(field, groups)).join('')}${selected === 'backup' ? `<div class="settings-encryption"><strong>Verschlüsselungsschlüssel</strong><p>${data.encryption.keyId ? 'Aktiver Schlüssel: ' + esc(data.encryption.keyId) : data.encryption.legacy ? 'Bisheriges Archivpasswort übernommen. Eine neue Phrase aktiviert die Verschlüsselung aller Sicherungsdaten.' : 'Noch kein Wiederherstellungsschlüssel eingerichtet.'}</p><button type="button" data-generate>${data.encryption.keyId || data.encryption.legacy ? 'Neue Wiederherstellungsphrase erzeugen' : 'Wiederherstellungsphrase erzeugen'}</button></div><label class="settings-check"><input type="checkbox" name="clearDestination">Sicherungsziel entfernen und Sicherungen deaktivieren</label>` : ''}<p class="error" role="alert" hidden></p><div class="toolbar"><button type="submit">Änderungen speichern</button><span class="muted" role="status"></span></div></form></section>`;
const form = host.querySelector('form'); tlsVisibility(form);
form.addEventListener('input', () => onDirty(true));
host.querySelectorAll('[data-section]').forEach(button => { button.onclick = async () => {
if (form.dataset.dirty === 'true' && !confirm('Ungespeicherte Änderungen verwerfen?')) return;
onDirty(false); selected = button.dataset.section; await render();
}; });
form.addEventListener('input', () => { form.dataset.dirty = 'true'; });
if (selected === 'backup') host.querySelector('[data-generate]').onclick = async () => {
try {
const draft = form.dataset.dirty === 'true' ? readValues(form, current.fields) : null;
const clearDestination = form.elements.clearDestination?.checked;
await recoveryDialog(api, data, async () => {
onDirty(false);
await mount(host, {api, notice, section, initialSection:selected, onDirty});
if (draft) {
draft.BACKUP_ENCRYPTION_ENABLED = true;
const next = host.querySelector('form');
for (const [key, value] of Object.entries(draft)) {
const input = next.elements.namedItem(key);
if (input) { if (input.type === 'checkbox') input.checked = value; else input.value = value; }
}
if (next.elements.clearDestination) next.elements.clearDestination.checked = clearDestination;
next.dataset.dirty = 'true'; onDirty(true);
}
notice('Verschlüsselungsschlüssel aktiviert.');
});
} catch (error) { notice(error.message); }
};
form.onsubmit = async event => {
event.preventDefault(); const button = form.querySelector('[type=submit]'); button.disabled = true;
const errorBox = form.querySelector('[role=alert]'); errorBox.hidden = true;
try {
const values = readValues(form, current.fields);
if (form.elements.clearDestination?.checked) { values.BACKUP_DESTINATION = ''; values.BACKUP_AUTO_ENABLED = false; }
const saved = await api('/api/settings', {method:'POST', body:JSON.stringify({revision:data.revision, values})});
onDirty(false); form.dataset.dirty = 'false';
Object.assign(data, saved);
form.querySelector('[role=status]').textContent = saved.restartRequired ? 'Gespeichert. Dienste starten neu; anschließend die Seite neu laden.' : 'Gespeichert.';
form.querySelectorAll('input[type=password],textarea[name=WEB_TLS_KEY_PEM]').forEach(input => { input.value = ''; });
} catch (error) { errorBox.textContent = error.message; errorBox.hidden = false; }
finally { button.disabled = false; }
};
};
await render();
}
window.ConfigurationUI = {mount, fieldMarkup, readValues, tlsVisibility};
})();
+7
View File
@@ -0,0 +1,7 @@
<!doctype html>
<html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Dateiserver einrichten</title><link rel="stylesheet" href="/assets/styles.css"></head><body>
<header class="portal-header"><strong>Dateiserver · Ersteinrichtung</strong></header>
<main class="setup-main"><h1>Dateiserver einrichten</h1><p id="setup-status" role="status"></p><p id="setup-error" class="error" role="alert" hidden></p>
<section id="setup-unlock" class="panel"><h2>Einrichtung entsperren</h2><p>Den einmaligen Einrichtungscode finden Sie im Containerprotokoll: <code>docker compose logs samba</code>.</p><form class="stack"><label>Einrichtungscode<input name="code" type="password" autocomplete="off" required autofocus></label><button type="submit">Weiter</button></form></section>
<div id="setup-content" hidden></div></main>
<script src="/assets/settings.js" defer></script><script src="/assets/setup.js" defer></script></body></html>
+62
View File
@@ -0,0 +1,62 @@
(() => {
let token = '', snapshot = null, polling = false;
const content = document.querySelector('#setup-content'), errorBox = document.querySelector('#setup-error'), status = document.querySelector('#setup-status');
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'}[c]));
const showError = error => { errorBox.textContent = error.message; errorBox.hidden = false; };
async function api(path, options = {}) {
const response = await fetch('/api/bootstrap/' + path, {...options, headers:{'Content-Type':'application/json', 'X-Setup-Token':token}, credentials:'same-origin'});
const result = await response.json();
if (!response.ok) throw new Error(result.error || 'Einrichtung konnte nicht geladen werden');
return result;
}
async function refresh() {
snapshot = await api('settings');
status.textContent = snapshot.services?.message || '';
if (snapshot.phase === 'groups' && !content.querySelector('#setup-groups')) await renderGroups();
}
async function renderGroups() {
const {groups} = await api('groups');
const fields = snapshot.sections.find(item => item.id === 'groups').fields.map(field => ({...field, value:field.value || groups.find(group => group.sid.endsWith(field.key === 'DOMAIN_ADMINS_SID' ? '-512' : '-513'))?.sid || groups[0]?.sid || ''}));
content.innerHTML = `<section class="panel"><h2>Gruppen auswählen</h2><p>Diese Gruppen steuern SMB-Anmeldung, Verwaltung und FSLogix. Dateizugriffe werden später individuell pro Benutzer zugeordnet.</p><form id="setup-groups" class="stack">${fields.map(field => ConfigurationUI.fieldMarkup(field, groups, true)).join('')}<label>Administratorkonto für die erste Anmeldung<input name="username" value="${esc(snapshot.sections.find(item => item.id === 'domain').fields.find(field => field.key === 'JOIN_USER').value)}" autocomplete="username" required></label><label>Passwort<input name="password" type="password" autocomplete="current-password" required></label><button type="submit">Einrichtung abschließen</button></form></section>`;
content.querySelector('form').onsubmit = async event => {
event.preventDefault(); const form = event.currentTarget, button = form.querySelector('button'); button.disabled = true; errorBox.hidden = true;
try {
await refresh();
await api('finish', {method:'POST', body:JSON.stringify({revision:snapshot.revision, values:ConfigurationUI.readValues(form, fields), username:form.elements.username.value, password:form.elements.password.value})});
form.elements.password.value = ''; token = ''; status.textContent = 'Einrichtung abgeschlossen. Dienste werden gestartet.';
content.innerHTML = '<section class="panel"><a href="/">Zur Anmeldung</a></section>';
polling = false;
} catch (error) { showError(error); button.disabled = false; }
};
}
function renderDomain() {
const essentials = new Set(['REALM','WORKGROUP','DOMAIN','JOIN_USER','JOIN_PASSWORD','NETBIOS_NAME','SAMBA_HOSTNAME','WEB_HOSTNAME','WEB_TLS_MODE','AD_DNS_IP','AD_DNS_NAME']);
const fields = snapshot.sections.filter(section => ['domain','network','tls'].includes(section.id)).flatMap(section => section.fields);
const hostname = fields.find(field => field.key === 'WEB_HOSTNAME');
if (hostname.value === 'localhost') hostname.value = location.hostname;
content.innerHTML = `<section class="panel"><h2>Domäne und Server</h2><form id="setup-domain" class="stack">${fields.filter(field => essentials.has(field.key)).map(field => ConfigurationUI.fieldMarkup(field, [], true)).join('')}<details><summary>LDAP- und Zertifikatseinstellungen</summary><div class="stack settings-advanced">${fields.filter(field => !essentials.has(field.key)).map(field => ConfigurationUI.fieldMarkup(field, [], true)).join('')}</div></details><button type="submit">Domäne beitreten</button></form></section><details class="panel"><summary>Bestehende Installation übernehmen</summary><p>Die bisherige .env-Datei einmalig importieren. Dateien, bestehender Domänenbeitritt, Rechte und Sicherungen bleiben erhalten.</p><form id="setup-import" class="stack"><label>Bisherige Konfigurationsdatei<input type="file" name="legacy" required></label><button type="submit">Konfiguration importieren</button></form></details>`;
const form = content.querySelector('#setup-domain'); ConfigurationUI.tlsVisibility(form);
form.onsubmit = async event => {
event.preventDefault(); errorBox.hidden = true; const button = form.querySelector('[type=submit]'); button.disabled = true;
try {
await refresh();
snapshot = await api('domain', {method:'POST', body:JSON.stringify({revision:snapshot.revision, values:ConfigurationUI.readValues(form, fields)})});
form.elements.JOIN_PASSWORD.value = ''; status.textContent = 'Domänenbeitritt läuft. Bei einem Fehler können Sie die Angaben korrigieren und erneut versuchen.';
polling = true;
} catch (error) { showError(error); }
finally { button.disabled = false; }
};
content.querySelector('#setup-import').onsubmit = async event => {
event.preventDefault(); errorBox.hidden = true;
try { const text = await event.currentTarget.elements.legacy.files[0].text(); await api('import', {method:'POST', body:JSON.stringify({text})}); token = ''; location.assign('/'); }
catch (error) { showError(error); }
};
}
document.querySelector('#setup-unlock form').onsubmit = async event => {
event.preventDefault(); const form = event.currentTarget; errorBox.hidden = true; token = form.elements.code.value;
try { await refresh(); form.elements.code.value = ''; document.querySelector('#setup-unlock').hidden = true; content.hidden = false; if (snapshot.phase !== 'groups') renderDomain(); polling = snapshot.phase !== 'unconfigured'; }
catch (error) { token = ''; showError(error); }
};
setInterval(async () => { if (polling && token) { try { await refresh(); } catch (error) { showError(error); } } }, 3000);
api('status').then(result => { if (result.configured) location.replace('/'); }).catch(showError);
})();
+16
View File
@@ -251,3 +251,19 @@ mark { background: #fff0a0; color: #111; }
.document-dialog-head { gap: .5rem; }
.document-dialog-head .row-actions { flex-wrap: nowrap; }
}
/* Setup and configuration use the existing typography, borders and controls. */
.setup-main { max-width: 780px; margin: 2rem auto; padding: 0 1rem 2rem; }
.settings-form { max-width: 700px; }
.settings-form textarea, .settings-advanced textarea { width: 100%; padding: .4rem; font: inherit; border: 1px solid #999; resize: vertical; }
.settings-check { display: flex; align-items: flex-start; gap: .5rem; }
.settings-check input { width: auto; flex-shrink: 0; margin-top: .25rem; }
.settings-tabs { display: flex; flex-wrap: wrap; gap: .4rem; margin-bottom: 1rem; }
.settings-tabs button[aria-pressed=true] { font-weight: bold; border-color: #111; background: #ddd; }
.settings-encryption { padding: .8rem 0; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; }
.settings-encryption p { margin: .4rem 0; overflow-wrap: anywhere; }
.settings-advanced { margin-top: .8rem; }
.recovery-words { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: .5rem 1.5rem; padding-left: 2rem; font-family: monospace; }
.settings-key-dialog { width: min(660px,calc(100vw - 2rem)); }
html:has(.settings-key-dialog[open]), body:has(.settings-key-dialog[open]) { overflow: hidden; }
@media (max-width: 480px) { .recovery-words { grid-template-columns: repeat(2,minmax(0,1fr)); } .settings-encryption button { white-space: normal; } }
+4
View File
@@ -67,6 +67,10 @@ class Sessions:
with self.connection() as conn, conn:
conn.execute('DELETE FROM web_sessions WHERE id=?', (self.key(jti),))
def recheck_all(self):
with self.connection() as conn, conn:
conn.execute('UPDATE web_sessions SET checked=0')
def close(self):
with self.lock:
if self.memory is not None:
+170 -6
View File
@@ -27,11 +27,11 @@ from typing import Dict, List, Optional, Tuple
try:
from app import reconcile_shares as directory
from app import trash, access_control, documents, web_security
from app import trash, access_control, documents, web_security, configuration
from app.account_policy import is_excluded_user
except ImportError: # Container execution uses /app as the import root.
import reconcile_shares as directory
import trash, access_control, documents, web_security
import trash, access_control, documents, web_security, configuration
from account_policy import is_excluded_user
try:
@@ -130,6 +130,8 @@ class ActionConflict(RuntimeError):
def launch_background(command: List[str], extra_env: Dict[str, str]) -> None:
environment = os.environ.copy()
environment.update(extra_env)
if CONFIG is not None:
environment.update(CONFIG.environment())
try:
process = subprocess.Popen(
command,
@@ -148,7 +150,7 @@ def launch_background(command: List[str], extra_env: Dict[str, str]) -> None:
def start_backup_action(username: str) -> Dict[str, object]:
if not os.getenv("BACKUP_DESTINATION", "").strip():
raise ActionConflict("Es ist kein Sicherungsziel eingerichtet")
if not os.getenv("BACKUP_ARCHIVE_PASSWORD", ""):
if env_bool('BACKUP_ENCRYPTION_ENABLED', False) and not os.getenv("BACKUP_ARCHIVE_PASSWORD", ""):
raise ActionConflict("BACKUP_ARCHIVE_PASSWORD ist nicht gesetzt")
with ACTION_LAUNCH_LOCK:
if lock_is_held(BACKUP_LOCK_FILE):
@@ -438,7 +440,7 @@ def authenticate_user(username: str, password: str) -> Optional[Dict[str, str]]:
return current_identity(user_sid_match.group(0))
def current_identity(sid: str):
def current_identity(sid: str, admin_sid=None):
try:
group_result = subprocess.run(["wbinfo", "--user-sids", sid], capture_output=True,
text=True, timeout=15, check=False)
@@ -446,7 +448,7 @@ def current_identity(sid: str):
return None
if group_result.returncode != 0:
return None
admin_sid = os.environ["DOMAIN_ADMINS_SID"].casefold()
admin_sid = (admin_sid or os.environ["DOMAIN_ADMINS_SID"]).casefold()
group_sids = {value.casefold() for value in SID_RE.findall(group_result.stdout)}
try:
resolved = subprocess.run(["wbinfo", "--sid-to-name", sid], capture_output=True, text=True, timeout=15, check=False)
@@ -863,6 +865,7 @@ class App:
APP: Optional[App] = None
CONFIG = None
class Handler(BaseHTTPRequestHandler):
@@ -871,6 +874,133 @@ class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt: str, *args) -> None:
log(f"{self.client_address[0]} {fmt % args}")
def reload_configuration(self):
if CONFIG is not None:
for name in ('LDAP_URI', 'LDAP_BASE_DN', 'AD_DNS_NAME'):
os.environ.pop(name, None)
os.environ.update(CONFIG.environment(materialize=False))
def domain_groups(self):
entries = directory.search_directory_entries('(objectClass=group)', access_control.ATTRS)
result = []
for entry in entries:
principal = directory.parse_principal_from_entry(entry)
if principal and directory.is_group_principal(principal):
sid = str(principal.get('objectSid') or '')
if SID_RE.fullmatch(sid):
result.append({'sid': sid, 'name': str(principal.get('samAccountName') or sid)})
return sorted(result, key=lambda row: row['name'].casefold())
def bootstrap(self, path, mutation=False):
if CONFIG is None:
self.send_error_json(HTTPStatus.NOT_FOUND, 'Nicht gefunden')
return
snap = CONFIG.snapshot()
if path == '/api/bootstrap/status' and not mutation:
self.send_json({'phase': snap['phase'], 'configured': snap['phase'] == 'configured'})
return
if not CONFIG.accepts_bootstrap(self.headers.get('X-Setup-Token', '')):
self.send_error_json(HTTPStatus.FORBIDDEN, 'Ungültiger Einrichtungscode oder Einrichtung abgeschlossen')
return
if mutation:
if self.headers.get_content_type() != 'application/json' or self.headers.get('Sec-Fetch-Site') in {'cross-site', 'same-site'}:
self.send_error_json(HTTPStatus.FORBIDDEN, 'Einrichtung erfordert JSON vom selben Origin')
return
origin = self.headers.get('Origin')
if origin:
try:
if web_security.origin(origin) != web_security.origin('https://' + self.headers.get('Host', '')):
raise ValueError()
except ValueError:
self.send_error_json(HTTPStatus.FORBIDDEN, 'Ungültiger Einrichtungs-Origin')
return
try:
if not mutation and path == '/api/bootstrap/settings':
value = CONFIG.public()
value['services'] = read_json(str(CONFIG.root / 'services-status.json'), {'state': 'waiting'})
self.send_json(value)
elif not mutation and path == '/api/bootstrap/groups':
if not os.path.exists('/run/adfs-domain-ready'):
raise ValueError('Domänenbeitritt ist noch nicht abgeschlossen')
self.send_json({'groups': self.domain_groups()})
elif mutation and path == '/api/bootstrap/domain':
body = self.read_json_body(262144)
changes = body.get('values', {})
if not isinstance(changes, dict) or any(key not in configuration.FIELDS or configuration.FIELDS[key]['section'] not in {'domain', 'network', 'tls'} for key in changes):
raise ValueError('Nur Domänen-, Server- und HTTPS-Einstellungen sind hier zulässig')
if not all(changes.get(key) or snap['values'].get(key) for key in ('REALM', 'WORKGROUP', 'DOMAIN', 'JOIN_USER', 'JOIN_PASSWORD')):
raise ValueError('Domäne und Zugangsdaten für den Beitritt sind erforderlich')
CONFIG.save(changes, body.get('revision'), bootstrap=True)
CONFIG.phase('joining')
self.reload_configuration()
self.send_json(CONFIG.public(), HTTPStatus.ACCEPTED)
elif mutation and path == '/api/bootstrap/finish':
if not os.path.exists('/run/adfs-domain-ready'):
raise ValueError('Domänenbeitritt ist noch nicht abgeschlossen')
body = self.read_json_body()
changes = body.get('values', {})
if not isinstance(changes, dict) or set(changes) != {'DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID', 'FSLOGIX_GROUP_SID'}:
raise ValueError('Benutzer-, Administratoren- und FSLogix-Gruppe auswählen')
groups = {row['sid'] for row in self.domain_groups()}
if any(sid not in groups for sid in changes.values()):
raise ValueError('Ausgewählte Gruppe ist nicht im aktuellen AD vorhanden')
identity = authenticate_user(body.get('username', snap['values']['JOIN_USER']), body.get('password', snap['values']['JOIN_PASSWORD']))
administrator = current_identity(identity['sid'], admin_sid=changes['DOMAIN_ADMINS_SID']) if identity else None
if not administrator or administrator['role'] != 'domain-admin':
raise ValueError('Das Einrichtungskonto muss zur ausgewählten Administratorengruppe gehören')
result = CONFIG.save(changes, body.get('revision'), bootstrap=True)
CONFIG.finish(result['revision'])
self.send_json({'configured': True, 'hostname': CONFIG.snapshot()['values']['WEB_HOSTNAME']})
elif mutation and path == '/api/bootstrap/import':
body = self.read_json_body(262144)
if not CONFIG.import_legacy(configuration.parse_legacy(body.get('text', ''))):
raise ValueError('Frühere Konfiguration ist unvollständig')
self.reload_configuration()
self.send_json({'configured': True})
else:
self.send_error_json(HTTPStatus.NOT_FOUND, 'Nicht gefunden')
except configuration.Conflict as exc:
self.send_error_json(HTTPStatus.CONFLICT, str(exc))
except (ValueError, TypeError, OSError, RuntimeError) as exc:
self.send_error_json(HTTPStatus.BAD_REQUEST, str(exc))
def settings_write(self, path, user):
if CONFIG is None:
self.send_error_json(HTTPStatus.SERVICE_UNAVAILABLE, 'Einstellungen nicht verfügbar')
return
try:
body = self.read_json_body(262144)
with ACTION_LAUNCH_LOCK:
if lock_is_held(BACKUP_LOCK_FILE):
raise configuration.Conflict('Während einer Sicherung können Einstellungen und Schlüssel nicht geändert werden')
if path == '/api/settings':
values = body.get('values', {})
if isinstance(values, dict) and any(key in values for key in ('DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID', 'FSLOGIX_GROUP_SID')):
groups = {row['sid'] for row in self.domain_groups()}
if any(values[key] not in groups for key in values if key in ('DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID', 'FSLOGIX_GROUP_SID')):
raise ValueError('Ausgewählte Gruppe ist nicht im aktuellen AD vorhanden')
if 'DOMAIN_ADMINS_SID' in values:
identity = current_identity(user['sid'], admin_sid=values['DOMAIN_ADMINS_SID'])
if not identity or identity['role'] != 'domain-admin':
raise ValueError('Sie müssen Mitglied der ausgewählten Administratorengruppe sein')
result = CONFIG.save(values, body.get('revision'))
if 'DOMAIN_ADMINS_SID' in values:
APP.tokens.sessions.recheck_all()
result['restartRequired'] = any(configuration.FIELDS[key]['section'] != 'backup' for key in values)
elif path == '/api/settings/backup-key/generate':
result = CONFIG.generate_key(str(user['jti']))
elif path == '/api/settings/backup-key/activate':
result = CONFIG.activate_key(str(user['jti']), body.get('nonce'), body.get('writtenDown'), body.get('acknowledgeOldBackups'))
else:
self.send_error_json(HTTPStatus.NOT_FOUND, 'Nicht gefunden')
return
self.reload_configuration()
self.send_json(result)
except configuration.Conflict as exc:
self.send_error_json(HTTPStatus.CONFLICT, str(exc))
except (ValueError, TypeError, OSError) as exc:
self.send_error_json(HTTPStatus.BAD_REQUEST, str(exc))
def security_headers(self, cache_control: str = "no-store", pdf_viewer: bool = False) -> None:
self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
self.send_header(
@@ -1019,6 +1149,13 @@ class Handler(BaseHTTPRequestHandler):
def do_POST(self) -> None: # pylint: disable=invalid-name
parsed = urllib.parse.urlparse(self.path)
self.reload_configuration()
if parsed.path.startswith('/api/bootstrap/'):
self.bootstrap(parsed.path, mutation=True)
return
if CONFIG is not None and CONFIG.snapshot()['phase'] != 'configured':
self.send_error_json(HTTPStatus.SERVICE_UNAVAILABLE, 'Ersteinrichtung erforderlich')
return
if not self.check_write_origin():
return
if parsed.path == "/api/login":
@@ -1076,6 +1213,9 @@ class Handler(BaseHTTPRequestHandler):
if administrator is None:
return
parsed = parsed._replace(path=parsed.path[len("/admin"):])
if parsed.path == '/api/settings' or parsed.path.startswith('/api/settings/'):
self.settings_write(parsed.path, administrator)
return
if parsed.path == "/api/documents/control":
conn = documents.connect()
try:
@@ -1186,10 +1326,23 @@ class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None: # pylint: disable=invalid-name,too-many-return-statements
parsed = urllib.parse.urlparse(self.path)
self.reload_configuration()
path = parsed.path
if path.startswith('/api/bootstrap/'):
self.bootstrap(path)
return
if path == "/healthz":
if CONFIG is not None and CONFIG.snapshot()['phase'] == 'configured' and not os.path.exists('/run/adfs-services-ready'):
self.send_json({'status': 'starting', 'message': 'Dateidienste werden gestartet'}, HTTPStatus.SERVICE_UNAVAILABLE)
return
self.send_json({"status": "ok"})
return
if CONFIG is not None and CONFIG.snapshot()['phase'] != 'configured' and not path.startswith('/assets/'):
if path.startswith('/api/') or path.startswith('/admin/api/'):
self.send_error_json(HTTPStatus.SERVICE_UNAVAILABLE, 'Ersteinrichtung erforderlich')
else:
self.serve_static('/setup')
return
if path.startswith("/api/"):
user = self.require_user()
if user is None:
@@ -1220,6 +1373,12 @@ class Handler(BaseHTTPRequestHandler):
conn.close()
elif path == "/api/overview":
self.send_json(APP.overview())
elif path == '/api/settings':
if CONFIG is None:
raise ValueError('Einstellungen nicht verfügbar')
self.send_json(CONFIG.public(params.get('section', [''])[0] or None))
elif path == '/api/settings/groups':
self.send_json({'groups': self.domain_groups()})
elif path == "/api/access":
conn = directory.open_db()
try:
@@ -1383,6 +1542,9 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(body)
return
files = {
'/setup': ('setup.html', 'text/html; charset=utf-8'),
'/assets/setup.js': ('setup.js', 'text/javascript; charset=utf-8'),
'/assets/settings.js': ('settings.js', 'text/javascript; charset=utf-8'),
"/assets/portal.js": ("portal.js", "text/javascript; charset=utf-8"),
"/assets/pdf-viewer.js": ("pdf-viewer.js", "text/javascript; charset=utf-8"),
"/assets/pdf-viewer.css": ("pdf-viewer.css", "text/css; charset=utf-8"),
@@ -1473,7 +1635,9 @@ def serve_https() -> None:
def main() -> int:
global APP
global APP, CONFIG
CONFIG = configuration.Store()
os.environ.update(CONFIG.environment())
if not os.path.isfile(TLS_CERT_FILE) or not os.path.isfile(TLS_KEY_FILE):
raise RuntimeError("TLS certificate or key is missing")
APP = App()