diff --git a/PVE-IDM/CHANGELOG.md b/PVE-IDM/CHANGELOG.md index a5a7e8c..e563df2 100644 --- a/PVE-IDM/CHANGELOG.md +++ b/PVE-IDM/CHANGELOG.md @@ -1,5 +1,13 @@ # Änderungsprotokoll +## [1.3.0] – 2026-09-09 + +- Optionaler Logout über zwei Keycloak-Adressen (IP und FQDN) nacheinander. +- Exakt kodierte Rücksprungkette und automatische Registrierung beider benötigten + Post-Logout-Redirects am Client, ohne Wildcards. +- TLS-/Issuer-Prüfung beider Aliase und Auswahl im Einrichtungsassistenten. +- Gemeinsame URL-Erzeugung für Ansible und Patch, Test der verschachtelten Redirects. + ## [1.2.1] – 2026-09-09 - Rückbau direkt über `setup.py --rollback-logout` mit Inventory-/SSH-/sudo-Abfragen. diff --git a/PVE-IDM/README.md b/PVE-IDM/README.md index 60c05b2..3f695c2 100644 --- a/PVE-IDM/README.md +++ b/PVE-IDM/README.md @@ -1,6 +1,6 @@ # PVE 9 + Keycloak OIDC für HEIMLAN -Version: **1.2.1** · [Änderungsprotokoll](CHANGELOG.md) · [Versionsdatei](VERSION) +Version: **1.3.0** · [Änderungsprotokoll](CHANGELOG.md) · [Versionsdatei](VERSION) Dieses Ansible-Setup konfiguriert den bestehenden PVE-Host **ts01** und eine bestehende **Keycloak-VM**. Es installiert die private Root-CA auf beiden Betriebssystemen sowie im Java- und Keycloak-Truststore, richtet Realm, Client, Gruppen, Mapper und Sessions ein und ergänzt PVE-ACLs ausschließlich für bereits vorhandene Gruppen. Alle Module gehören zu `ansible.builtin`. @@ -287,3 +287,55 @@ python3 /root/pve-idm-logout-patch.py \ Auch dieser Rückbau ist bereits im Patch-Skript eingebaut. Anschließend die PVE-Seite vollständig neu laden. Keycloak-Konfiguration und Sicherungsdateien bleiben erhalten. + +## Keycloak-Logout über IP und FQDN (ab 1.3.0) + +Im Assistenten `Keycloak über IP UND FQDN abmelden?` mit `j` beantworten und +`https://9.99.30.11:8443` sowie `https://keycloak.service.heim.lan:8443` eingeben. +Alternativ in der lokalen Konfiguration: + +```yaml +pve_logout_enabled: true +pve_logout_redirect_uri: https://192.168.1.231:8006/ +pve_logout_endpoints: + - https://9.99.30.11:8443/realms/main.heim.lan/protocol/openid-connect/logout + - https://keycloak.service.heim.lan:8443/realms/main.heim.lan/protocol/openid-connect/logout +``` + +Die Rücksprungadresse muss in `pve_redirect_uris` stehen. PVE-Zugriff per IP und DNS +ist über mehrere Einträge in dieser Liste möglich. Die Logout-Rückkehr erfolgt zur +gewählten festen Adresse. Andere PVE-Tabs/Host-Cookies werden dadurch nicht gelöscht. + +Der Browser meldet die Keycloak-Sitzung zunächst über die erste, dann über die zweite +Adresse ab. Die zweite Logout-URL einschließlich ihrer kodierten Rücksprungadresse +wird als exakter erlaubter Post-Logout-Redirect am Client registriert, ebenso die finale +PVE-Adresse. Es gibt keine Wildcard-Freigabe. Der Assistent/Ansible erzeugt die Kodierung; +nicht manuell Markdown-Links in URLs einsetzen. Die vorhandene Post-Logout-Redirect-Liste +wird durch die für diesen Ablauf benötigten Einträge ersetzt. + +Bis zu zwei Bestätigungsseiten sind möglich. Erst nach Abschluss der gesamten Kette +sind beide Browser-Sitzungen angesprochen worden. Abbruch, Nichterreichbarkeit eines +Hosts oder ein vorgeschalteter Identity Provider können den Ablauf unterbrechen bzw. +eine neue automatische Anmeldung verursachen. Der Ablauf ist kein serverseitiger +Global-Logout aller Sitzungen des Benutzers auf anderen Geräten. + +Beide Adressen brauchen gültiges HTTPS: im Zertifikat DNS-SAN für den FQDN und IP-SAN +für `9.99.30.11` (oder passende separate Zertifikate). Die CA-Prüfung wird nicht +abgeschaltet. Ein Fehler hierbei muss an Zertifikat/Truststore behoben werden. + +Es bleibt **ein kanonischer OIDC-Issuer**. IP und FQDN sind Zugriffsaliase desselben +Realms; die Discovery-Antwort beider Aliase muss denselben Issuer liefern. Die bestehende +Issuer-Konfiguration nicht allein aufgrund der Browser-URL ändern. Wenn beide Aliase +unterschiedliche Issuer ausliefern, Keycloaks Hostname-Konfiguration zuerst vereinheitlichen. +Der Logout-Modus ändert weder den Login-Issuer noch Serverzertifikate automatisch. + +Installation auf bereits eingerichteten Hosts: + +```bash +ansible-playbook -i inventory/hosts.local.yml playbook/logout.yml --ask-vault-pass +``` + +Danach PVE mit deaktiviertem Browsercache neu laden. Je einen Testlogin über die +verwendeten Keycloak-Adressen durchführen und nach vollständigem Logout die Sessions +prüfen, bevor erneut angemeldet wird. Lokal sind Kodierung, Patch, Realm-Zuordnung, +Rückbau und Wiederholung geprüft; der vollständige Ablauf auf deinem Keycloak steht aus. diff --git a/PVE-IDM/VERSION b/PVE-IDM/VERSION index 6085e94..f0bb29e 100644 --- a/PVE-IDM/VERSION +++ b/PVE-IDM/VERSION @@ -1 +1 @@ -1.2.1 +1.3.0 diff --git a/PVE-IDM/group_vars/all.yml.example b/PVE-IDM/group_vars/all.yml.example index 10a820e..1800ba3 100644 --- a/PVE-IDM/group_vars/all.yml.example +++ b/PVE-IDM/group_vars/all.yml.example @@ -52,3 +52,6 @@ pve_roles: # Optionaler PVE-Desktop-Logout-Patch (Keycloak fragt ggf. nach Bestätigung). pve_logout_enabled: false pve_logout_redirect_uri: "{{ pve_redirect_uris[0] }}" +# Leer: Discovery-Endpunkt. Optional IP und FQDN desselben Keycloak-Realms. +# Beide TLS-Zertifikatsnamen müssen gültig sein; maximal zwei Endpunkte. +pve_logout_endpoints: [] diff --git a/PVE-IDM/playbook/filter_plugins/logout_plan.py b/PVE-IDM/playbook/filter_plugins/logout_plan.py new file mode 100644 index 0000000..176df3f --- /dev/null +++ b/PVE-IDM/playbook/filter_plugins/logout_plan.py @@ -0,0 +1,9 @@ +"""Shared deterministic logout URL encoding for Ansible and the PVE patch.""" +import importlib.util +from pathlib import Path +spec = importlib.util.spec_from_file_location('pve_idm_patch', Path(__file__).resolve().parents[2] / 'scripts/logout_patch.py') +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +class FilterModule: + def filters(self): + return {'pve_idm_logout_plan': module.logout_plan} diff --git a/PVE-IDM/scripts/logout_patch.py b/PVE-IDM/scripts/logout_patch.py index 7f3a088..18b79f1 100644 --- a/PVE-IDM/scripts/logout_patch.py +++ b/PVE-IDM/scripts/logout_patch.py @@ -7,7 +7,7 @@ import os from pathlib import Path import re import tempfile -from urllib.parse import urlsplit +from urllib.parse import urlsplit, urlencode MARK = '/* PVE-IDM LOGOUT v1 */' ANCHOR = re.compile(r"(text:\s*gettext\('Logout'\),\s*handler:\s*function\s*\(\)\s*\{)(\s*PVE\.data\.ResourceStore\.loadData\(\[\],\s*false\);\s*me\.showLogin\(\);)") @@ -33,28 +33,50 @@ def write(path, data, mode=0o600, owner=None): os.unlink(tmp) -def render(text, realm, endpoint, client, redirect): +def logout_plan(endpoints, client, redirect): + if not isinstance(endpoints, list) or not 1 <= len(endpoints) <= 2 or len(set(endpoints)) != len(endpoints): + raise ValueError('Ein oder zwei unterschiedliche Keycloak-Logout-Endpunkte erforderlich.') + for url in endpoints + [redirect]: + u = urlsplit(url) + if (u.scheme != 'https' or not u.hostname or u.username or u.password or + u.fragment or u.query or any(c.isspace() for c in url) or '*' in url): + raise ValueError('Nur exakte HTTPS-Adressen ohne Query oder Zugangsdaten verwenden.') + for endpoint in endpoints: + if not urlsplit(endpoint).path.endswith('/protocol/openid-connect/logout'): + raise ValueError('Keycloak-Logout-Endpunkt erwartet.') + result = redirect + allowed = [] + for endpoint in reversed(endpoints): + allowed.append(result) + result = endpoint + '?' + urlencode({'client_id': client, 'post_logout_redirect_uri': result}) + return {'url': result, 'allowed_redirects': allowed, 'endpoints': endpoints} + + +def render(text, realm, endpoint, client, redirect, endpoints=None): if MARK in text or len(list(ANCHOR.finditer(text))) != 1: raise ValueError('Unbekannter oder mehrdeutiger Logout-Code; keine Änderung.') for url in (endpoint, redirect): u = urlsplit(url) if u.scheme != 'https' or not u.hostname or u.username or u.password or u.fragment or u.query: raise ValueError('Nur feste HTTPS-URLs ohne Query/Zugangsdaten erlaubt.') - cfg = json.dumps(dict(realm=realm, endpoint=endpoint, client=client, redirect=redirect), ensure_ascii=True) + if endpoints: + plan = logout_plan(endpoints, client, redirect) + logout_url = plan['url'] + else: + logout_url = endpoint + '?' + urlencode({'client_id': client, 'post_logout_redirect_uri': redirect}) + cfg = json.dumps(dict(realm=realm, endpoint=endpoint, client=client, redirect=redirect, logoutUrl=logout_url), ensure_ascii=True) def replace(match): return (match[1] + '\n' + MARK + '\n' 'const pveIdmUser = Proxmox.UserName || "";\n' 'const pveIdmConfig = ' + cfg + ';\n' + match[2] + '\n' 'if (pveIdmUser.endsWith("@" + pveIdmConfig.realm)) {\n' - ' const pveIdmUrl = new URL(pveIdmConfig.endpoint);\n' - ' pveIdmUrl.searchParams.set("client_id", pveIdmConfig.client);\n' - ' pveIdmUrl.searchParams.set("post_logout_redirect_uri", pveIdmConfig.redirect);\n' + ' const pveIdmUrl = new URL(pveIdmConfig.logoutUrl);\n' ' window.setTimeout(function () { window.location.assign(pveIdmUrl.href); }, 0);\n' '}\n/* END PVE-IDM LOGOUT v1 */\n') return ANCHOR.sub(replace, text) -def apply(target, directory, enabled, version='', realm='', endpoint='', client='', redirect=''): +def apply(target, directory, enabled, version='', realm='', endpoint='', client='', redirect='', endpoints=None): if target.is_symlink() or not target.is_file(): raise ValueError('JavaScript-Ziel muss eine reguläre Datei sein.') current = target.read_bytes() @@ -75,7 +97,7 @@ def apply(target, directory, enabled, version='', realm='', endpoint='', client= for suffix in ('.gz', '.br'): if Path(str(target) + suffix).exists(): raise ValueError('Vorkomprimiertes JS gefunden; Auslieferung zuerst prüfen.') - desired = render(base.decode(), realm, endpoint, client, redirect).encode() + desired = render(base.decode(), realm, endpoint, client, redirect, endpoints).encode() else: desired = base if desired == current: @@ -103,7 +125,9 @@ if __name__ == '__main__': parser.add_argument('--enabled', choices=['true', 'false'], required=True) for option in ('version', 'realm', 'endpoint', 'client', 'redirect'): parser.add_argument('--' + option, default='') + parser.add_argument('--endpoints-json', default='[]', help='JSON-Liste mit maximal zwei Logout-Endpunkten') args = vars(parser.parse_args()) + args['endpoints'] = json.loads(args.pop('endpoints_json')) args['target'] = Path(args['target']) args['directory'] = Path(args.pop('state_dir')) args['enabled'] = args['enabled'] == 'true' diff --git a/PVE-IDM/setup.py b/PVE-IDM/setup.py index 143c73a..92787ab 100644 --- a/PVE-IDM/setup.py +++ b/PVE-IDM/setup.py @@ -234,6 +234,13 @@ def main(): 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.')) + config['pve_logout_endpoints'] = [] + if config['pve_logout_enabled'] and yes('Keycloak über IP UND FQDN abmelden?'): + for label in ('Erste Keycloak-Adresse (z. B. https://9.99.30.11:8443)', 'Zweite Keycloak-Adresse (FQDN)'): + base = ask(label, '', https_url) + config['pve_logout_endpoints'].append(base + '/realms/' + config['keycloak_realm'] + '/protocol/openid-connect/logout') + if len(set(config['pve_logout_endpoints'])) != 2: + raise RuntimeError('Für dualen Logout zwei unterschiedliche Adressen verwenden.') print('\nSessions in Sekunden: 900 = 15 Minuten; 28800 = 8 Stunden') while True: for key, label, default in [ diff --git a/PVE-IDM/tasks/keycloak.yml b/PVE-IDM/tasks/keycloak.yml index 9951522..9e5e342 100644 --- a/PVE-IDM/tasks/keycloak.yml +++ b/PVE-IDM/tasks/keycloak.yml @@ -104,9 +104,12 @@ kc_session_attributes: client.session.idle.timeout: "{{ keycloak_client_idle | string }}" client.session.max.lifespan: "{{ keycloak_client_max | string }}" + - name: Prepare verified logout redirect chain + ansible.builtin.include_tasks: logout_plan.yml + when: pve_logout_enabled | default(false) | bool - name: Register explicit post-logout return address ansible.builtin.set_fact: - kc_session_attributes: "{{ kc_session_attributes | combine({'post.logout.redirect.uris': pve_logout_redirect_uri}) }}" + kc_session_attributes: "{{ kc_session_attributes | combine({'post.logout.redirect.uris': logout_plan.allowed_redirects | join('##')}) }}" when: pve_logout_enabled | default(false) | bool - name: Create confidential PVE client ansible.builtin.uri: diff --git a/PVE-IDM/tasks/logout.yml b/PVE-IDM/tasks/logout.yml index 6979c92..74d6800 100644 --- a/PVE-IDM/tasks/logout.yml +++ b/PVE-IDM/tasks/logout.yml @@ -7,26 +7,8 @@ register: logout_version changed_when: false when: pve_logout_enabled | default(false) | bool -- name: Validate logout return address - ansible.builtin.assert: - that: - - pve_logout_redirect_uri in pve_redirect_uris - fail_msg: 'Logout-Rücksprung muss einer konfigurierten PVE-Browser-URL entsprechen.' - when: pve_logout_enabled | default(false) | bool -- name: Discover verified Keycloak logout endpoint - ansible.builtin.uri: - url: "{{ pve_oidc_issuer }}/.well-known/openid-configuration" - validate_certs: true - ca_path: "{{ system_ca_bundle }}" - use_proxy: false - follow_redirects: none - register: logout_discovery - when: pve_logout_enabled | default(false) | bool -- name: Validate discovered endpoint and issuer - ansible.builtin.assert: - that: - - logout_discovery.json.issuer == pve_oidc_issuer - - logout_discovery.json.end_session_endpoint == pve_oidc_issuer ~ '/protocol/openid-connect/logout' +- name: Prepare verified logout sequence + ansible.builtin.include_tasks: logout_plan.yml when: pve_logout_enabled | default(false) | bool - name: Install guarded patch helper ansible.builtin.copy: @@ -52,6 +34,8 @@ - "{{ pve_realm }}" - --endpoint - "{{ (logout_discovery.json | default({})).get('end_session_endpoint', '') }}" + - --endpoints-json + - "{{ (logout_plan | default({})).get('endpoints', []) | to_json }}" - --client - "{{ keycloak_client_id }}" - --redirect diff --git a/PVE-IDM/tasks/logout_plan.yml b/PVE-IDM/tasks/logout_plan.yml new file mode 100644 index 0000000..2825298 --- /dev/null +++ b/PVE-IDM/tasks/logout_plan.yml @@ -0,0 +1,31 @@ +- name: Read canonical discovery with CA verification + ansible.builtin.uri: + url: "{{ pve_oidc_issuer }}/.well-known/openid-configuration" + validate_certs: true + ca_path: "{{ system_ca_bundle }}" + use_proxy: false + follow_redirects: none + register: logout_discovery +- name: Validate canonical issuer and return address + ansible.builtin.assert: + that: + - logout_discovery.json.issuer == pve_oidc_issuer + - pve_logout_redirect_uri in pve_redirect_uris +- name: Build explicit logout sequence and exact allowed redirects + ansible.builtin.set_fact: + logout_plan: "{{ (pve_logout_endpoints | default([]) or [logout_discovery.json.end_session_endpoint]) | pve_idm_logout_plan(keycloak_client_id, pve_logout_redirect_uri) }}" +- name: Verify both host certificates and realm discovery + ansible.builtin.uri: + url: "{{ item | regex_replace('/protocol/openid-connect/logout$', '/.well-known/openid-configuration') }}" + validate_certs: true + ca_path: "{{ system_ca_bundle }}" + use_proxy: false + follow_redirects: none + loop: "{{ logout_plan.endpoints }}" + register: logout_alias_discovery +- name: Require all aliases to advertise the same canonical realm issuer + ansible.builtin.assert: + that: item.json.issuer == pve_oidc_issuer + loop: "{{ logout_alias_discovery.results }}" + loop_control: + label: "{{ item.item }}" diff --git a/PVE-IDM/tests/test_logout.py b/PVE-IDM/tests/test_logout.py index d460463..50218de 100644 --- a/PVE-IDM/tests/test_logout.py +++ b/PVE-IDM/tests/test_logout.py @@ -2,6 +2,7 @@ import importlib.util from pathlib import Path import tempfile import json +from urllib.parse import urlsplit, parse_qs import shutil import subprocess import unittest @@ -18,6 +19,23 @@ handler: function () { class LogoutTests(unittest.TestCase): + def test_two_host_redirect_chain(self): + endpoints = ['https://9.99.30.11:8443/realms/main.heim.lan/protocol/openid-connect/logout', + 'https://keycloak.service.heim.lan:8443/realms/main.heim.lan/protocol/openid-connect/logout'] + plan = patch.logout_plan(endpoints, 'PVE-SERVER', 'https://192.168.1.231:8006/') + first = urlsplit(plan['url']) + self.assertEqual(first.hostname, '9.99.30.11') + next_url = parse_qs(first.query)['post_logout_redirect_uri'][0] + self.assertIn(next_url, plan['allowed_redirects']) + second = urlsplit(next_url) + self.assertEqual(second.hostname, 'keycloak.service.heim.lan') + self.assertEqual(parse_qs(second.query)['post_logout_redirect_uri'], ['https://192.168.1.231:8006/']) + self.assertEqual(len(plan['allowed_redirects']), 2) + for endpoints_bad in ([], endpoints * 2, [endpoints[0]] * 2, ['http://kc/logout'], + ['https://kc/logout?next=bad'], ['https://kc/not-logout']): + with self.assertRaises(ValueError): + patch.logout_plan(endpoints_bad, 'PVE-SERVER', 'https://pve/') + def test_lifecycle_and_update(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp)