Files
NextFloorSymcon/NextFloor/libs/Access.php
T
2026-11-17 12:59:54 +01:00

201 lines
13 KiB
PHP

<?php
declare(strict_types=1);
/** Instance-local accounts and revocable HttpOnly sessions. Console actions are never exposed through the WebHook API. */
trait NextFloorAccess
{
private ?array $requestUser = null;
private ?array $requestScope = null;
private const SESSION_TTL = 43200;
private const SESSION_IDLE = 7200;
private function accessLock(callable $operation): mixed
{
$name = 'NextFloorAccess_' . $this->InstanceID;
$native = function_exists('IPS_SemaphoreEnter');
if ($native && !IPS_SemaphoreEnter($name, 3000)) throw new RuntimeException('access_busy');
try { return $operation(); }
finally { if ($native) IPS_SemaphoreLeave($name); }
}
private function accounts(): array { return $this->jsonAttribute('Accounts', []); }
/** A short-lived, single-use console ticket; no reusable admin credential in browser URLs. */
private function consoleUrl(): string
{
$ticket = $this->newToken();
$this->accessLock(function () use ($ticket): void {
$tickets = array_filter($this->jsonAttribute('ConsoleTickets', []), static fn(array $t): bool => $t['expires'] > time());
$tickets = array_slice($tickets, -19, null, true);
$tickets[hash('sha256', $ticket)] = ['expires' => time() + 90, 'epoch' => $this->ensureAccessToken()];
$this->writeJsonAttribute('ConsoleTickets', $tickets);
});
return '/hook/' . $this->hookPath() . '/designer?mode=designer&ticket=' . rawurlencode($ticket);
}
private function sessionCookie(): string { return 'NFSC_Session_' . $this->InstanceID; }
private function loginCookie(): string { return 'NFSC_Login_' . $this->InstanceID; }
private function accessCookie(string $name, string $value, int $expires = 0): void
{
setcookie($name, $value, ['expires' => $expires, 'path' => '/hook/' . $this->hookPath() . '/',
'secure' => $this->secureRequest(), 'httponly' => true, 'samesite' => 'Strict']);
}
private function secureRequest(): bool
{
// A proxy header can only strengthen cookie protection, never turn native HTTPS off.
return (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off') || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
}
private function createSession(string $accountID, array $account, bool $remember = false): array
{
$token = $this->newToken();
$id = hash('sha256', $token);
$session = ['account' => $accountID, 'epoch' => $account['epoch'], 'csrf' => $this->newToken(),
'expires' => time() + ($remember ? 2592000 : self::SESSION_TTL), 'idle' => $remember ? 604800 : self::SESSION_IDLE, 'seen' => time()];
// Called inside accessLock, including ticket exchange and password login.
$sessions = array_filter($this->jsonAttribute('Sessions', []), static fn(array $s): bool => $s['expires'] > time() && $s['seen'] > time() - ($s['idle'] ?? self::SESSION_IDLE));
if (count($sessions) >= 128) throw new RuntimeException('session_limit');
$sessions[$id] = $session;
$this->writeJsonAttribute('Sessions', $sessions);
$this->accessCookie($this->sessionCookie(), $token, $remember ? $session['expires'] : 0);
return [...$account, 'id' => $accountID, 'session_id' => $id, 'csrf' => $session['csrf']];
}
private function resolveSession(): ?array
{
$token = $_COOKIE[$this->sessionCookie()] ?? '';
if (!is_string($token) || preg_match('/^[a-f0-9]{64}$/D', $token) !== 1) return null;
return $this->accessLock(function () use ($token): ?array {
$id = hash('sha256', $token);
$sessions = $this->jsonAttribute('Sessions', []);
$s = $sessions[$id] ?? null;
if (!$s || $s['expires'] <= time() || $s['seen'] <= time() - ($s['idle'] ?? self::SESSION_IDLE)) return null;
$account = $s['account'] === '__console__' ? ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $this->ensureAccessToken()]
: ($this->accounts()[$s['account']] ?? null);
if (!$account || !$account['enabled'] || !hash_equals((string) $account['epoch'], (string) $s['epoch'])) return null;
if ($s['seen'] < time() - 60) {
$sessions[$id]['seen'] = time();
$this->writeJsonAttribute('Sessions', $sessions);
}
return [...$account, 'id' => $s['account'], 'session_id' => $id, 'csrf' => $s['csrf']];
});
}
private function exchangeConsoleTicket(string $ticket): bool
{
if (preg_match('/^[a-f0-9]{64}$/D', $ticket) !== 1) return false;
return $this->accessLock(function () use ($ticket): bool {
$tickets = $this->jsonAttribute('ConsoleTickets', []);
$key = hash('sha256', $ticket);
$grant = $tickets[$key] ?? null;
unset($tickets[$key]);
$this->writeJsonAttribute('ConsoleTickets', $tickets);
if (!$grant || $grant['expires'] <= time() || !hash_equals($this->ensureAccessToken(), $grant['epoch'])) return false;
$this->requestUser = $this->createSession('__console__', ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $grant['epoch']]);
return true;
});
}
private function safeMode(): string { return ($_GET['mode'] ?? '') === 'tile' ? 'tile' : 'designer'; }
private function entryUrl(string $tail = 'designer'): string { return '/hook/' . $this->hookPath() . '/' . $tail . '?mode=' . $this->safeMode(); }
private function accessRedirect(string $url): void { header('Location: ' . $url, true, 303); header('Cache-Control: no-store'); }
private function validOrigin(): bool
{
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin === '') return true; // non-browser clients still require the CSRF value and session cookie
$parts = parse_url($origin);
if (!is_array($parts) || ($parts['scheme'] ?? '') !== ($this->secureRequest() ? 'https' : 'http')) return false;
$authority = strtolower((string) ($parts['host'] ?? '') . (isset($parts['port']) ? ':' . $parts['port'] : ''));
return $authority !== '' && hash_equals(strtolower((string) ($_SERVER['HTTP_HOST'] ?? '')), $authority);
}
private function validCsrf(): bool
{
$value = $_SERVER['HTTP_X_NEXTFLOOR_CSRF'] ?? $_POST['csrf'] ?? '';
return $this->requestUser !== null && is_string($value) && $value !== '' && $this->validOrigin()
&& hash_equals($this->requestUser['csrf'], $value);
}
/** Login stays a regular HTML form, including with JavaScript disabled and on small touch screens. */
private function loginPage(string $error = '', int $status = 200): void
{
$csrf = $this->newToken();
$this->accessCookie($this->loginCookie(), $csrf);
$escape = static fn(string $s): string => htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
http_response_code($status);
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store');
$configured = count(array_filter($this->accounts(), static fn(array $a): bool => $a['enabled'])) > 0;
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
. '<title>Anmelden · ' . $escape($this->viewTitle()) . '</title><style>html{color-scheme:dark}body{margin:0;min-height:100dvh;display:grid;place-items:center;background:#0c1320;color:#e6edf5;font:16px/1.5 system-ui}main{box-sizing:border-box;width:min(420px,calc(100% - 32px));padding:32px;background:#1b2432;border:1px solid #344255;border-radius:18px;box-shadow:0 16px 60px #0005}h1{margin:0 0 4px;font-size:25px}p{color:#aebdce}label{display:block;margin:18px 0 6px}input,button{box-sizing:border-box;width:100%;padding:12px 14px;border-radius:9px;border:1px solid #465872;font:inherit}input{background:#101a28;color:inherit}button{margin-top:24px;background:#1bb8e8;color:#061624;font-weight:700;cursor:pointer}input:focus,button:focus{outline:2px solid #45d0ff;outline-offset:3px}[role=alert]{padding:10px;background:#82353555;border-radius:8px;color:#ffc4c4}.note{font-size:13px}</style></head><body><main><h1>'
. $escape($this->viewTitle()) . '</h1><p>Mit deinem NextFloor-Konto anmelden.</p>'
. ($error !== '' ? '<p role="alert">' . $escape($error) . '</p>' : '')
. ($configured ? '<form method="post" action="' . $escape($this->entryUrl('login')) . '"><input type="hidden" name="csrf" value="' . $csrf . '">'
. '<label for="username">Benutzername</label><input id="username" name="username" autocomplete="username" required maxlength="64" autofocus>'
. '<label for="password">Passwort</label><input id="password" name="password" type="password" autocomplete="current-password" required maxlength="72">'
. '<label style="display:flex;gap:9px;align-items:center;font-size:14px"><input style="width:auto" type="checkbox" name="remember" value="1">Angemeldet bleiben (30 Tage)</label><button type="submit">Anmelden</button></form><p class="note">Passwort vergessen? Der Symcon-Administrator kann es in der NextFloor-Instanz zurücksetzen.</p>'
: '<p role="status">Noch kein Benutzer eingerichtet. Lege in der Symcon-Konfiguration der NextFloor-Instanz zuerst einen Benutzer mit Passwort an.</p>')
. '</main></body></html>';
}
private function passwordLogin(): void
{
$csrf = $_POST['csrf'] ?? '';
$nonce = $_COOKIE[$this->loginCookie()] ?? '';
if (!$this->validOrigin() || !is_string($csrf) || !is_string($nonce) || strlen($nonce) !== 64 || !hash_equals($nonce, $csrf)) {
$this->loginPage('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.', 403);
return;
}
$name = is_string($_POST['username'] ?? null) ? mb_strtolower(trim($_POST['username'])) : '';
$password = is_string($_POST['password'] ?? null) ? $_POST['password'] : '';
$result = $this->accessLock(function () use ($name, $password): string {
$now = time();
$limits = array_filter($this->jsonAttribute('LoginThrottle', []), static fn(array $v): bool => $v['until'] > time());
$ipKey = 'ip:' . hash('sha256', (string) ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
$nameKey = 'name:' . hash('sha256', $name);
if (($limits[$ipKey]['count'] ?? 0) >= 40 || ($limits[$nameKey]['count'] ?? 0) >= 8) return 'limited';
$found = null;
foreach ($this->accounts() as $id => $a) if (mb_strtolower($a['name']) === $name) { $found = [$id, $a]; break; }
// Use the same platform algorithm/cost for an unknown username as for real accounts.
$hash = $found[1]['password'] ?? $this->ReadAttributeString('LoginDummyHash');
$valid = strlen($password) <= 72 && !str_contains($password, "\0") && password_verify($password, $hash);
if (!$valid || !$found || !$found[1]['enabled']) {
foreach ([$ipKey, $nameKey] as $key) $limits[$key] = ['count' => ($limits[$key]['count'] ?? 0) + 1, 'until' => $limits[$key]['until'] ?? $now + 900];
$this->writeJsonAttribute('LoginThrottle', array_slice($limits, -1024, null, true));
return 'invalid';
}
unset($limits[$nameKey]);
$this->writeJsonAttribute('LoginThrottle', $limits);
$this->requestUser = $this->createSession($found[0], $found[1], ($_POST['remember'] ?? '') === '1');
return 'ok';
});
if ($result !== 'ok') { $this->loginPage($result === 'limited' ? 'Zu viele Anmeldeversuche. Bitte in 15 Minuten erneut versuchen.' : 'Benutzername oder Passwort ist ungültig.', $result === 'limited' ? 429 : 401); return; }
$this->accessCookie($this->loginCookie(), '', time() - 3600);
$this->accessRedirect($this->entryUrl());
}
private function logoutSession(): void
{
$id = $this->requestUser['session_id'] ?? '';
$this->accessLock(function () use ($id): void {
$sessions = $this->jsonAttribute('Sessions', []); unset($sessions[$id]); $this->writeJsonAttribute('Sessions', $sessions);
});
$this->accessCookie($this->sessionCookie(), '', time() - 3600);
$this->requestUser = null;
$this->accessRedirect($this->entryUrl('login'));
}
private function publicAccess(): array
{
$admin = $this->requestUser['role'] === 'admin';
$canControl = $admin || ($this->requestUser['control_all'] ?? false);
foreach (['rooms', 'devices', 'objects'] as $group) foreach ($this->requestUser[$group] ?? [] as $g) if (($g['access'] ?? '') === 'control') $canControl = true;
return ['id' => $this->requestUser['id'], 'name' => $this->requestUser['name'], 'is_admin' => $admin,
'view_all' => $admin || ($this->requestUser['view_all'] ?? false), 'control_all' => $admin || ($this->requestUser['control_all'] ?? false), 'can_control' => $canControl];
}
}