138 lines
6.3 KiB
Python
138 lines
6.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Guarded PVE 9 desktop logout patch. No credentials are used."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import tempfile
|
|
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\(\);)")
|
|
|
|
|
|
def digest(data):
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def write(path, data, mode=0o600, owner=None):
|
|
fd, tmp = tempfile.mkstemp(dir=path.parent)
|
|
try:
|
|
with os.fdopen(fd, 'wb') as stream:
|
|
stream.write(data)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
os.chmod(tmp, mode)
|
|
if owner is not None:
|
|
os.chown(tmp, *owner)
|
|
os.replace(tmp, path)
|
|
finally:
|
|
if os.path.exists(tmp):
|
|
os.unlink(tmp)
|
|
|
|
|
|
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.')
|
|
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.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='', 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()
|
|
statefile = directory / 'state.json'
|
|
state = json.loads(statefile.read_text()) if statefile.exists() else None
|
|
base = current
|
|
if MARK.encode() in current:
|
|
if not state or state['patched_sha256'] != digest(current) or state['target'] != str(target):
|
|
raise ValueError('Veränderter Patch oder fehlende Sicherungsdaten; automatischer Eingriff gestoppt.')
|
|
base = (directory / state['backup']).read_bytes()
|
|
if digest(base) != state['original_sha256']:
|
|
raise ValueError('Sicherung beschädigt; keine Änderung.')
|
|
elif not enabled:
|
|
return False # Already removed by a package update: never restore an old bundle.
|
|
if enabled:
|
|
if not re.search(r'pve-manager/9\.', version):
|
|
raise ValueError('Nur PVE 9 wird unterstützt.')
|
|
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, endpoints).encode()
|
|
else:
|
|
desired = base
|
|
if desired == current:
|
|
return False
|
|
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
stat = target.stat()
|
|
if enabled:
|
|
backup = digest(base) + '.js.orig'
|
|
backupfile = directory / backup
|
|
if backupfile.exists() and backupfile.read_bytes() != base:
|
|
raise ValueError('Sicherungskollision.')
|
|
if not backupfile.exists():
|
|
write(backupfile, base)
|
|
# Save recovery metadata before replacing the target; inconsistent states fail closed.
|
|
write(statefile, json.dumps(dict(target=str(target), backup=backup,
|
|
original_sha256=digest(base), patched_sha256=digest(desired), version=version)).encode())
|
|
write(target, desired, stat.st_mode & 0o777, (stat.st_uid, stat.st_gid))
|
|
return True
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--target', required=True)
|
|
parser.add_argument('--state-dir', required=True)
|
|
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'
|
|
try:
|
|
print(json.dumps({'changed': apply(**args)}))
|
|
except (ValueError, OSError, KeyError) as exc:
|
|
parser.exit(1, str(exc) + '\n')
|