Files
2026-11-30 16:32:37 +00:00

332 lines
9.8 KiB
PHP

<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Webapp-specific security policy for the shared KeyCloak client.
*/
class WebAppKeyCloak extends KeyCloak {
private const MAX_PENDING_STATES = 8;
private const STATE_LIFETIME = 600;
private const STATE_SESSION_KEY = '_keycloak_oauth_states';
// checked in order; a nested path is only reached once its parent passed
private const TYPE_RULES = [
[['realm'], 'is_string', 'Invalid Keycloak configuration value'],
[['resource'], 'is_string', 'Invalid Keycloak configuration value'],
[['redirect-url'], 'is_string', 'Invalid Keycloak configuration value'],
[['realm-public-key'], 'is_string', 'Invalid Keycloak configuration value'],
[['secret'], 'is_string', 'Invalid Keycloak configuration value'],
[['public-client'], 'is_bool', 'Invalid Keycloak public-client setting'],
[['credentials'], 'is_array', 'Invalid Keycloak credentials'],
[['credentials', 'secret'], 'is_string', 'Invalid Keycloak credentials'],
];
/** @var null|self */
private static $instance;
/**
* Use a configured callback URL, or derive one without trusting Host and
* Request-URI headers supplied by the client.
*
* @param mixed $keycloakConfig decoded keycloak.json configuration
*/
public function __construct(mixed $keycloakConfig) {
if (is_string($keycloakConfig)) {
$keycloakConfig = json_decode($keycloakConfig, true);
}
if (!is_array($keycloakConfig)) {
$keycloakConfig = [];
}
foreach (self::TYPE_RULES as [$path, $isValid, $message]) {
$value = $keycloakConfig;
foreach ($path as $key) {
$value = $value[$key] ?? null;
}
if ($value !== null && !$isValid($value)) {
throw new InvalidArgumentException($message);
}
}
$authServerUrl = $keycloakConfig['auth-server-url'] ?? null;
if (!is_string($authServerUrl) || filter_var($authServerUrl, FILTER_VALIDATE_URL) === false) {
throw new InvalidArgumentException('Invalid Keycloak server URL');
}
$redirectUrl = self::callbackUrl($keycloakConfig);
if ($redirectUrl === null) {
throw new UnexpectedValueException('No valid Keycloak callback URL is configured');
}
// Older mapi-header releases access this optional key without a default.
if (($keycloakConfig['public-client'] ?? false) && !isset($keycloakConfig['realm-public-key'])) {
$keycloakConfig['realm-public-key'] = '';
}
parent::__construct($keycloakConfig);
$this->redirect_url = $redirectUrl;
}
/**
* Return the webapp Keycloak singleton configured by keycloak.json.
*/
public static function getInstance(): ?WebAppKeyCloak {
if (!defined('GROMOX_CONFIG_PATH')) {
define('GROMOX_CONFIG_PATH', '/etc/gromox/');
}
$configFile = GROMOX_CONFIG_PATH . 'keycloak.json';
if (self::$instance === null && is_file($configFile)) {
$config = json_decode((string) @file_get_contents($configFile), true);
if (!is_array($config)) {
error_log('Unable to load webapp Keycloak configuration');
return null;
}
try {
self::$instance = new self($config);
}
catch (InvalidArgumentException|UnexpectedValueException) {
error_log('Unable to load webapp Keycloak configuration');
return null;
}
}
return self::$instance;
}
/**
* Build an authorization URL and remember its one-time state value.
*
* The argument remains for compatibility with KeyCloak::login_url(); the
* validated callback established by the constructor is always used.
*
* @param string $redirectUrl ignored caller-supplied redirect URL
* @param bool $usePkce ignored parent-client compatibility option
*
* @return string authorization URL
*/
public function login_url($redirectUrl, $usePkce = false): string {
$state = bin2hex(random_bytes(32));
$this->storeState($state);
$params = [
'scope' => 'openid',
'client_id' => $this->client_id,
'state' => $state,
'redirect_uri' => $this->redirect_url,
'response_type' => 'code',
];
return $this->realm_url . '/protocol/openid-connect/auth?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
}
/**
* Consume a current state value exactly once.
*
* @param mixed $state callback state parameter
*
* @return bool true when the state was generated by this session
*/
public function consumeState($state) {
$states = $this->pendingStates();
if (!is_string($state) || preg_match('/\A[a-f0-9]{64}\z/D', $state) !== 1) {
$this->saveStates($states);
return false;
}
$key = hash('sha256', $state);
if (!isset($states[$key])) {
$this->saveStates($states);
return false;
}
unset($states[$key]);
$this->saveStates($states);
return true;
}
/**
* Require the introspection endpoint to return the JSON boolean true.
*
* @param mixed $token access token
*/
protected function validate_token(mixed $token): bool {
if (!isset($token)) {
return false;
}
$headers = ['Content-Type: application/x-www-form-urlencoded'];
$params = ['token' => $token->get_payload()];
if ($this->is_public) {
$params['client_id'] = $this->client_id;
}
else {
$headers[] = 'Authorization: Basic ' . base64_encode($this->client_id . ':' . $this->secret);
}
$response = $this->http_curl_request(
'POST',
'/protocol/openid-connect/token/introspect',
$headers,
http_build_query($params)
);
if ($response['code'] < 200 || $response['code'] > 299) {
return false;
}
try {
$data = json_decode((string) $response['body'], true, 512, JSON_THROW_ON_ERROR);
}
catch (JsonException) {
return false;
}
return is_array($data) && !array_key_exists('error', $data) && ($data['active'] ?? null) === true;
}
/**
* Choose and normalize the OAuth callback URL.
*
* The callback is the deployment directory (https://host/web), which is the
* redirect URI the grommunio-auth client template registers; nginx sends the
* browser on to index.php. A fixed SERVER_NAME is preferred. The stock nginx
* configuration serves grommunio Web from a catch-all server block
* (server_name _;), so the Host header is used when SERVER_NAME is not a
* usable host name. Set redirect-url in keycloak.json to pin the callback.
*
* @param array $config keycloak.json configuration
*
* @return null|string
*/
private static function callbackUrl($config) {
if (isset($config['redirect-url'])) {
return self::normalizeCallbackUrl($config['redirect-url']);
}
$scriptName = (string) ($_SERVER['SCRIPT_NAME'] ?? '/index.php');
$scriptName = preg_replace('/[\x00-\x1f\x7f]/', '', str_replace('\\', '/', $scriptName));
$directory = rtrim(dirname('/' . ltrim($scriptName, '/')), '/');
$serverName = (string) ($_SERVER['SERVER_NAME'] ?? '');
$host = (string) ($_SERVER['HTTP_HOST'] ?? '');
// SERVER_NAME never carries the port the browser used
if ($serverName !== '' && preg_match('~\A' . preg_quote($serverName, '~') . '(:\d{1,5})\z~i', $host, $match) === 1) {
$serverName .= $match[1];
}
foreach ([$serverName, $host] as $authority) {
// a host with an optional port, nothing that could smuggle in a path
if ($authority === '' || preg_match('~[^A-Za-z0-9.:\[\]-]~', $authority) === 1) {
continue;
}
$url = self::normalizeCallbackUrl('https://' . $authority . $directory);
if ($url !== null) {
return $url;
}
}
return null;
}
/**
* Normalize an absolute HTTPS callback URL.
*
* @param mixed $url
*
* @return null|string
*/
private static function normalizeCallbackUrl($url) {
if (!is_string($url) || $url === '' || strlen($url) > 4096 ||
preg_match('/[\x00-\x20\x5c\x7f]/', $url) === 1) {
return null;
}
$parts = @parse_url($url);
if ($parts === false || strtolower($parts['scheme'] ?? '') !== 'https' || empty($parts['host']) ||
isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment'])) {
return null;
}
$host = trim(strtolower((string) $parts['host']), '[]');
if (filter_var($host, FILTER_VALIDATE_IP) === false) {
$host = rtrim($host, '.');
if ($host === '' || strlen($host) > 253 || preg_match('/\A[0-9.]+\z/D', $host) === 1 ||
preg_match('/\A(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*\z/D', $host) !== 1) {
return null;
}
}
$port = $parts['port'] ?? 443;
if (!is_int($port) || $port < 1 || $port > 65535) {
return null;
}
$authority = str_contains($host, ':') ? '[' . $host . ']' : $host;
if ($port !== 443) {
$authority .= ':' . $port;
}
// Keycloak matches the string exactly, so keep the path as given
$path = $parts['path'] ?? '';
$query = isset($parts['query']) ? '?' . $parts['query'] : '';
return 'https://' . $authority . $path . $query;
}
/**
* Store a state value and retain a small set for concurrent login tabs.
*
* @param string $state
*/
private function storeState($state) {
$states = $this->pendingStates();
$states[hash('sha256', $state)] = time() + self::STATE_LIFETIME;
asort($states, SORT_NUMERIC);
if (count($states) > self::MAX_PENDING_STATES) {
$states = array_slice($states, -self::MAX_PENDING_STATES, null, true);
}
$this->saveStates($states);
}
/**
* Return pending, unexpired state hashes from the session.
*
* @return array<string, int>
*/
private function pendingStates() {
$stored = $_SESSION[self::STATE_SESSION_KEY] ?? [];
if (!is_array($stored)) {
return [];
}
$states = [];
$now = time();
foreach ($stored as $hash => $expires) {
if (is_string($hash) && preg_match('/\A[a-f0-9]{64}\z/D', $hash) === 1 &&
is_int($expires) && $expires >= $now) {
$states[$hash] = $expires;
}
}
return $states;
}
/**
* Save pending states, removing the session key when none remain.
*
* @param array $states
*/
private function saveStates($states) {
if (empty($states)) {
unset($_SESSION[self::STATE_SESSION_KEY]);
}
else {
$_SESSION[self::STATE_SESSION_KEY] = $states;
}
}
}