324 lines
16 KiB
Python
324 lines
16 KiB
Python
#!/usr/bin/env python3
|
|
"""Interactive configuration for PVE-IDM; Python standard library only."""
|
|
import argparse
|
|
import getpass
|
|
import ipaddress
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from urllib.parse import urlsplit
|
|
|
|
ROOT = Path(__file__).resolve().parent
|
|
ROLES = ['Administrator', 'PVEAdmin', 'PVEAuditor', 'PVEDatastoreAdmin',
|
|
'PVEDatastoreUser', 'PVEMappingAdmin', 'PVEMappingUser', 'PVEPoolAdmin',
|
|
'PVEPoolUser', 'PVESDNAdmin', 'PVESDNUser', 'PVESysAdmin',
|
|
'PVETemplateUser', 'PVEUserAdmin', 'PVEVMAdmin', 'PVEVMUser']
|
|
|
|
|
|
def ask(label, default='', validate=None):
|
|
while True:
|
|
value = input(f'{label}' + (f' [{default}]' if default != '' else '') + ': ').strip()
|
|
value = value or str(default)
|
|
try:
|
|
if validate:
|
|
validate(value)
|
|
return value
|
|
except ValueError as exc:
|
|
print(f'Bitte korrigieren: {exc}')
|
|
|
|
|
|
def required(value):
|
|
if not value or any(c in value for c in '\r\n\x00'):
|
|
raise ValueError('Ein gültiger Wert ist erforderlich.')
|
|
|
|
|
|
def identifier(value):
|
|
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]*', value):
|
|
raise ValueError('Nur Buchstaben, Ziffern, Punkt, Unterstrich und Bindestrich.')
|
|
|
|
|
|
def address(value):
|
|
required(value)
|
|
try:
|
|
ipaddress.ip_address(value)
|
|
return
|
|
except ValueError:
|
|
pass
|
|
if not re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?', value):
|
|
raise ValueError('IP-Adresse oder DNS-Hostname ohne Port/Protokoll eingeben.')
|
|
if re.fullmatch(r'[0-9.]+', value):
|
|
raise ValueError('Ungültige IP-Adresse.')
|
|
|
|
|
|
def integer(value, maximum=2147483647):
|
|
if not value.isdigit() or not 1 <= int(value) <= maximum:
|
|
raise ValueError(f'Ganze Zahl zwischen 1 und {maximum}.')
|
|
|
|
|
|
def https_url(value, root=False):
|
|
parsed = urlsplit(value)
|
|
try:
|
|
port = parsed.port
|
|
except ValueError as exc:
|
|
raise ValueError('Ungültiger Port.') from exc
|
|
if (parsed.scheme != 'https' or not parsed.hostname or parsed.username or
|
|
parsed.password or parsed.query or parsed.fragment or '*' in value or
|
|
any(c.isspace() for c in value)):
|
|
raise ValueError('Exakte HTTPS-Adresse ohne Zugangsdaten, Wildcard oder Query erforderlich.')
|
|
if port is not None and not 1 <= port <= 65535:
|
|
raise ValueError('Ungültiger Port.')
|
|
if root and parsed.path != '/':
|
|
raise ValueError('PVE-Browser-Adresse muss mit / enden und darf keinen Unterpfad enthalten.')
|
|
if not root and parsed.path:
|
|
raise ValueError('Keycloak-Basisadresse ohne Unterpfad und ohne abschließenden /.')
|
|
|
|
|
|
def absolute_path(value):
|
|
if not value.startswith('/') or '\x00' in value:
|
|
raise ValueError('Absoluten Pfad eingeben.')
|
|
|
|
|
|
def local_file(value):
|
|
if not Path(value).expanduser().is_file():
|
|
raise ValueError('Datei auf diesem Mac/Controller nicht gefunden.')
|
|
|
|
|
|
def yes(label, default=False):
|
|
return ask(label + ' (j/n)', 'j' if default else 'n',
|
|
lambda v: None if v.lower() in ('j', 'n') else invalid('j oder n eingeben.')).lower() == 'j'
|
|
|
|
|
|
def invalid(message):
|
|
raise ValueError(message)
|
|
|
|
|
|
def secret(label, minimum=1, maximum=4096):
|
|
while True:
|
|
value = getpass.getpass(label + ': ')
|
|
if not minimum <= len(value) <= maximum or '\n' in value or '\r' in value:
|
|
print(f'Bitte {minimum} bis {maximum} Zeichen ohne Zeilenumbruch eingeben.')
|
|
continue
|
|
if getpass.getpass('Zur Bestätigung erneut eingeben: ') != value:
|
|
print('Die Eingaben stimmen nicht überein.')
|
|
continue
|
|
return value
|
|
|
|
|
|
def host(kind, alias, target, user):
|
|
print(f'\n{kind}: SSH-Verbindung (unabhängig von der HTTPS-Browser-Adresse)')
|
|
alias = ask('Inventory-Name', alias, identifier)
|
|
data = {
|
|
'ansible_host': ask('IP-Adresse oder DNS-Hostname', target, address),
|
|
'ansible_port': int(ask('SSH-Port', '22', lambda v: integer(v, 65535))),
|
|
'ansible_user': ask('SSH-Benutzer', user, identifier),
|
|
'ansible_become': True,
|
|
'ansible_become_user': ask('Zielbenutzer für sudo/become', 'root', identifier),
|
|
}
|
|
key = ask('SSH-Key auf diesem Mac (leer = SSH-Agent/Standard-Key)', '',
|
|
lambda v: local_file(v) if v else None)
|
|
if key:
|
|
data['ansible_ssh_private_key_file'] = str(Path(key).expanduser().resolve())
|
|
return alias, data
|
|
|
|
|
|
def encrypt_vault(payload, password, executable):
|
|
# Anonymous pipe: no plaintext password file and no secret command arguments.
|
|
read_fd, write_fd = os.pipe()
|
|
try:
|
|
os.write(write_fd, (password + '\n').encode())
|
|
os.close(write_fd)
|
|
write_fd = None
|
|
result = subprocess.run(
|
|
[executable, 'encrypt', '--vault-password-file', f'/dev/fd/{read_fd}', '--output', '-'],
|
|
input=json.dumps(payload).encode(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
pass_fds=(read_fd,), check=False)
|
|
if result.returncode or not result.stdout.startswith(b'$ANSIBLE_VAULT;'):
|
|
raise RuntimeError('Vault-Verschlüsselung fehlgeschlagen; keine Konfiguration gespeichert.')
|
|
return result.stdout
|
|
finally:
|
|
os.close(read_fd)
|
|
if write_fd is not None:
|
|
os.close(write_fd)
|
|
|
|
|
|
def atomic_write(path, content):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
fd, temporary = tempfile.mkstemp(prefix='.pve-idm-', dir=path.parent)
|
|
try:
|
|
with os.fdopen(fd, 'wb') as stream:
|
|
stream.write(content)
|
|
os.replace(temporary, path)
|
|
finally:
|
|
if os.path.exists(temporary):
|
|
os.unlink(temporary)
|
|
|
|
|
|
def rollback_logout():
|
|
"""Remove the remote patch and disable reinstallation in local configuration."""
|
|
os.chdir(ROOT)
|
|
executable = shutil.which('ansible-playbook')
|
|
if not executable:
|
|
raise RuntimeError('Ansible fehlt. Bitte zuerst die Ansible-Python-Umgebung aktivieren.')
|
|
config_path = ROOT / 'group_vars/all.yml'
|
|
if not config_path.is_file():
|
|
raise RuntimeError('group_vars/all.yml fehlt. Für eine manuelle Installation den Rückbau-Befehl aus der README direkt auf PVE verwenden.')
|
|
try:
|
|
import yaml
|
|
config = yaml.safe_load(config_path.read_text())
|
|
except (ImportError, ValueError) as exc:
|
|
raise RuntimeError('Konfiguration kann nicht gelesen werden. Bitte die Ansible-Python-Umgebung verwenden.') from exc
|
|
if not isinstance(config, dict):
|
|
raise RuntimeError('group_vars/all.yml muss eine YAML-Zuordnung enthalten.')
|
|
inventory_default = 'inventory/hosts.local.yml' if (ROOT / 'inventory/hosts.local.yml').exists() else 'inventory/hosts.yml'
|
|
inventory = ask('Inventory für den Rückbau', inventory_default, local_file)
|
|
command = [executable, '-i', str(Path(inventory).expanduser().resolve()), 'playbook/logout-remove.yml']
|
|
if yes('SSH-Passwort abfragen?'):
|
|
command.append('--ask-pass')
|
|
if yes('sudo-Passwort abfragen?'):
|
|
command.append('--ask-become-pass')
|
|
print('Entfernt nur den verwalteten PVE-Logout-Patch. Keycloak/OIDC und Sicherungen bleiben erhalten.')
|
|
if not yes('Logout-Patch auf den PVE-Hosts dieses Inventory jetzt zurückbauen?'):
|
|
print('Abgebrochen; keine Änderung.')
|
|
return
|
|
subprocess.run(command, check=True)
|
|
config['pve_logout_enabled'] = False
|
|
atomic_write(config_path, yaml.safe_dump(config, allow_unicode=True, sort_keys=False).encode())
|
|
print('Rückbau abgeschlossen; pve_logout_enabled=false gespeichert. PVE im Browser vollständig neu laden.')
|
|
|
|
|
|
def main():
|
|
os.chdir(ROOT)
|
|
if not sys.stdin.isatty():
|
|
raise RuntimeError('Bitte interaktiv in einem Terminal starten: python3 setup.py')
|
|
vault_bin = shutil.which('ansible-vault')
|
|
if not vault_bin:
|
|
raise RuntimeError('Ansible fehlt. Zuerst die Python-Umgebung aktivieren und ansible-core installieren (README).')
|
|
paths = [ROOT / 'inventory/hosts.local.yml', ROOT / 'group_vars/all.yml', ROOT / 'group_vars/vault.yml']
|
|
print('PVE-IDM Einrichtung · Enter übernimmt den angezeigten Standardwert.\n'
|
|
'Konfiguriert bestehende PVE-/Keycloak-Installationen; erzeugt keine VM.\n'
|
|
'Vorhandene Werte werden nicht eingelesen; bei erneutem Start alles neu eingeben.')
|
|
if any(p.exists() for p in paths):
|
|
if not yes('Vorhandene lokale Konfiguration vollständig ersetzen?'):
|
|
print('Abgebrochen; vorhandene Dateien bleiben erhalten.')
|
|
return
|
|
pve_alias, pve_host = host('PVE', 'ts01', 'ts01.heim.lan', 'root')
|
|
kc_alias, kc_host = host('Keycloak-VM', 'keycloak-vm', 'keycloak.service.heim.lan', 'ansible')
|
|
if pve_alias == kc_alias:
|
|
raise RuntimeError('Die beiden Inventory-Namen müssen verschieden sein.')
|
|
ask_ssh = yes('SSH-Passwort beim späteren Ansible-Lauf abfragen?')
|
|
ask_become = yes('sudo-Passwort beim späteren Ansible-Lauf abfragen?')
|
|
print('\nOIDC und Browser-Adressen (TLS-Zertifikate müssen zu diesen Namen passen)')
|
|
config = {}
|
|
config['keycloak_base_url'] = ask('Keycloak HTTPS-Basisadresse inkl. Port',
|
|
'https://keycloak.service.heim.lan:8443', https_url)
|
|
for key, label, default in [
|
|
('keycloak_realm', 'Keycloak-Realm', 'main.heim.lan'),
|
|
('pve_realm', 'PVE-Realm und Gruppensuffix', 'main.heim.lan'),
|
|
('keycloak_client_id', 'Keycloak Client-ID', 'PVE-SERVER'),
|
|
('keycloak_admin_realm', 'Admin-Realm', 'master'),
|
|
('keycloak_admin_client_id', 'Admin-Client-ID', 'admin-cli')]:
|
|
config[key] = ask(label, default, identifier)
|
|
issuer = config['keycloak_base_url'] + '/realms/' + config['keycloak_realm']
|
|
config['pve_oidc_issuer'] = ask('OIDC-Issuer (muss zur Basisadresse/Realm passen)', issuer,
|
|
lambda v: None if v == issuer else invalid('Issuer muss ' + issuer + ' sein.'))
|
|
def redirects(value):
|
|
for url in value.split(','):
|
|
https_url(url.strip(), root=True)
|
|
config['pve_redirect_uris'] = list(dict.fromkeys(u.strip() for u in ask(
|
|
'PVE-Browser-URLs, mehrere mit Komma trennen', 'https://ts01.heim.lan:8006/', redirects).split(',')))
|
|
config['pve_logout_enabled'] = yes('PVE-Logout zu Keycloak weiterleiten (optionaler WebUI-Patch)?', True)
|
|
config['pve_logout_redirect_uri'] = ask('Rücksprung nach Keycloak-Logout', config['pve_redirect_uris'][0],
|
|
lambda v: None if v in config['pve_redirect_uris'] else invalid('Eine der angegebenen PVE-Browser-URLs wählen.'))
|
|
print('\nSessions in Sekunden: 900 = 15 Minuten; 28800 = 8 Stunden')
|
|
while True:
|
|
for key, label, default in [
|
|
('keycloak_sso_idle', 'SSO Idle', '900'), ('keycloak_sso_max', 'SSO Max', '28800'),
|
|
('keycloak_client_idle', 'Client Idle', '900'), ('keycloak_client_max', 'Client Max', '28800')]:
|
|
config[key] = int(ask(label, default, integer))
|
|
if (config['keycloak_sso_idle'] <= config['keycloak_sso_max'] and
|
|
config['keycloak_client_idle'] <= config['keycloak_client_max'] and
|
|
config['keycloak_client_idle'] <= config['keycloak_sso_idle'] and
|
|
config['keycloak_client_max'] <= config['keycloak_sso_max']):
|
|
break
|
|
print('Max muss mindestens Idle sein; Client-Werte dürfen SSO-Werte nicht überschreiten. Erneut eingeben.')
|
|
print('\nCA und Installationspfade')
|
|
config['heimlan_ca_src'] = str(Path(ask('Root-CA-Datei auf diesem Mac/Controller',
|
|
str(ROOT / 'files/HEIMLAN_RootCA.crt'), local_file)).expanduser().resolve())
|
|
config['heimlan_ca_sha256'] = ask('Optionaler geprüfter CA-SHA256-Fingerprint (leer = keiner)', '',
|
|
lambda v: None if not v or re.fullmatch(r'(?:[0-9a-fA-F]{2}:){31}[0-9a-fA-F]{2}', v)
|
|
else invalid('SHA256 als 32 Hex-Paare mit Doppelpunkten eingeben.'))
|
|
for key, label, default in [
|
|
('system_ca_bundle', 'System-CA-Bundle auf den Zielhosts', '/etc/ssl/certs/ca-certificates.crt'),
|
|
('keycloak_home', 'Keycloak-Installation auf der VM', '/opt/keycloak'),
|
|
('java_cacerts_path', 'Truststore der tatsächlich verwendeten JVM', '/etc/ssl/certs/java/cacerts'),
|
|
('java_keytool', 'Java-keytool auf der VM', '/usr/bin/keytool')]:
|
|
config[key] = ask(label, default, absolute_path)
|
|
for key, label, default in [
|
|
('keycloak_service', 'Keycloak systemd-Dienst', 'keycloak'),
|
|
('keycloak_user', 'Keycloak Servicebenutzer', 'keycloak'),
|
|
('keycloak_group', 'Keycloak Servicegruppe', 'keycloak'),
|
|
('java_ca_alias', 'Verwalteter Java-CA-Alias', 'heimlan-rootca-ansible')]:
|
|
config[key] = ask(label, default, identifier)
|
|
def roles(value):
|
|
selected = [v.strip() for v in value.split(',')]
|
|
if not selected or any(v not in ROLES for v in selected) or len(set(selected)) != len(selected):
|
|
invalid('Nur eindeutige Rollen aus der angezeigten Liste verwenden; NoAccess ist ausgeschlossen.')
|
|
config['pve_roles'] = [v.strip() for v in ask('Zu verwaltende PVE-Rollen, mit Komma trennen',
|
|
','.join(ROLES), roles).split(',')]
|
|
print('\nZugangsdaten (Passwörter werden nicht angezeigt)')
|
|
secrets = {'vault_keycloak_admin_username': ask('Keycloak Admin-Benutzername', '', required)}
|
|
secrets['vault_keycloak_admin_password'] = secret('Keycloak Admin-Passwort')
|
|
while True:
|
|
secrets['vault_keycloak_client_secret'] = secret('Gemeinsames PVE/Keycloak Client-Secret', 16, 256)
|
|
if secrets['vault_keycloak_client_secret'] == secrets['vault_keycloak_client_secret'].strip():
|
|
break
|
|
print('Client-Secret darf keine äußeren Leerzeichen enthalten.')
|
|
secrets['vault_java_cacerts_password'] = secret('Bestehendes Java-Truststore-Passwort')
|
|
vault_password = secret('Passwort zum Verschlüsseln der lokalen Ansible-Vault-Datei', 8)
|
|
for key in ('keycloak_admin_username', 'keycloak_admin_password', 'keycloak_client_secret', 'java_cacerts_password'):
|
|
config[key] = '{{ vault_' + key + ' }}'
|
|
inventory = {'all': {'children': {
|
|
'pve': {'hosts': {pve_alias: pve_host}}, 'keycloak': {'hosts': {kc_alias: kc_host}}}}}
|
|
print(f'\nPVE: {pve_alias} → {pve_host["ansible_host"]}:{pve_host["ansible_port"]}\n'
|
|
f'Keycloak: {kc_alias} → {kc_host["ansible_host"]}:{kc_host["ansible_port"]}\n'
|
|
f'Issuer: {issuer}\nKonfiguration wird lokal gespeichert; Secrets nur verschlüsselt.')
|
|
if not yes('Konfiguration jetzt speichern?', True):
|
|
print('Abgebrochen; keine Dateien gespeichert.')
|
|
return
|
|
encrypted = encrypt_vault(secrets, vault_password, vault_bin)
|
|
# JSON is valid YAML and avoids interpolation/quoting of user-entered values.
|
|
atomic_write(paths[0], (json.dumps(inventory, indent=2) + '\n').encode())
|
|
atomic_write(paths[1], (json.dumps(config, indent=2) + '\n').encode())
|
|
atomic_write(paths[2], encrypted)
|
|
command = ['ansible-playbook', '-i', 'inventory/hosts.local.yml', 'playbook/site.yml', '--ask-vault-pass']
|
|
if ask_ssh:
|
|
command.append('--ask-pass')
|
|
if ask_become:
|
|
command.append('--ask-become-pass')
|
|
print('\nGespeichert. Später starten mit:\n ' + ' '.join(command))
|
|
print('ACL-Lauf nach dem ersten Login:\n ansible-playbook -i inventory/hosts.local.yml playbook/acl.yml')
|
|
if yes('Setup jetzt auf den Zielhosts ausführen?'):
|
|
subprocess.run(command, check=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
parser = argparse.ArgumentParser(description='PVE-IDM Einrichtung und Logout-Rückbau')
|
|
parser.add_argument('--rollback-logout', action='store_true', help='Logout-Patch entfernen und lokal deaktivieren')
|
|
args = parser.parse_args()
|
|
if args.rollback_logout:
|
|
rollback_logout()
|
|
else:
|
|
main()
|
|
except (KeyboardInterrupt, EOFError):
|
|
print('\nAbgebrochen.', file=sys.stderr)
|
|
sys.exit(130)
|
|
except (RuntimeError, OSError, subprocess.CalledProcessError) as exc:
|
|
print(f'Fehler: {exc}', file=sys.stderr)
|
|
sys.exit(1)
|