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 '' . 'Anmelden · ' . $escape($this->viewTitle()) . '

' . $escape($this->viewTitle()) . '

Mit deinem NextFloor-Konto anmelden.

' . ($error !== '' ? '

' . $escape($error) . '

' : '') . ($configured ? '
' . '' . '' . '

Passwort vergessen? Der Symcon-Administrator kann es in der NextFloor-Instanz zurücksetzen.

' : '

Noch kein Benutzer eingerichtet. Lege in der Symcon-Konfiguration der NextFloor-Instanz zuerst einen Benutzer mit Passwort an.

') . '
'; } 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]; } }