Encrypt per-user Gotify tokens at rest with sodium/openssl, add app_secret config, security headers, Apache .htaccess hardening, and restrictive permissions for stored settings.
278 lines
10 KiB
PHP
278 lines
10 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Optional Gotify addon for Oscar Admin.
|
|
* 100% optional - the admin panel works without this file.
|
|
*
|
|
* Per-user settings are stored in gotify-users.php (gitignored).
|
|
* Tokens are encrypted at rest (sodium secretbox / openssl AES-256-GCM).
|
|
* Global gotify_url/gotify_token in config are optional fallbacks.
|
|
*/
|
|
|
|
function admin_gotify_feature_enabled(): bool
|
|
{
|
|
if (!function_exists('admin_cfg')) return false;
|
|
return (bool) admin_cfg('gotify_enabled', false);
|
|
}
|
|
|
|
function admin_gotify_users_path(): string
|
|
{
|
|
return __DIR__ . '/gotify-users.php';
|
|
}
|
|
|
|
function admin_gotify_users_legacy_json_path(): string
|
|
{
|
|
return __DIR__ . '/gotify-users.json';
|
|
}
|
|
|
|
/**
|
|
* Key for encrypting Gotify tokens at rest.
|
|
* Prefers app_secret config; falls back to deterministic derivation from local config.
|
|
*/
|
|
function admin_gotify_key(): string
|
|
{
|
|
$secret = trim((string) (function_exists('admin_cfg') ? admin_cfg('app_secret', '') : ''));
|
|
if ($secret === '') {
|
|
$secret = (string) (function_exists('admin_cfg') ? admin_cfg('system_password', '') : '')
|
|
. '|' . (string) (function_exists('admin_cfg') ? admin_cfg('session_name', 'oscar_admin') : 'oscar_admin')
|
|
. '|oscar-admin-gotify';
|
|
}
|
|
return hash('sha256', $secret, true);
|
|
}
|
|
|
|
function admin_gotify_encrypt(string $plaintext): string
|
|
{
|
|
if ($plaintext === '') return '';
|
|
$key = admin_gotify_key();
|
|
if (function_exists('sodium_crypto_secretbox')) {
|
|
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
|
|
$cipher = sodium_crypto_secretbox($plaintext, $nonce, $key);
|
|
return 's1:' . base64_encode($nonce . $cipher);
|
|
}
|
|
$iv = random_bytes(12);
|
|
$tag = '';
|
|
$cipher = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
|
|
if ($cipher === false) return '';
|
|
return 'o1:' . base64_encode($iv . $tag . $cipher);
|
|
}
|
|
|
|
function admin_gotify_decrypt(string $value): string
|
|
{
|
|
$value = trim($value);
|
|
if ($value === '') return '';
|
|
if (str_starts_with($value, 's1:')) {
|
|
if (!function_exists('sodium_crypto_secretbox_open')) return '';
|
|
$raw = base64_decode(substr($value, 3), true);
|
|
if ($raw === false || strlen($raw) < SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES) return '';
|
|
$nonce = substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
|
|
$cipher = substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
|
|
$plain = sodium_crypto_secretbox_open($cipher, $nonce, admin_gotify_key());
|
|
return is_string($plain) ? $plain : '';
|
|
}
|
|
if (str_starts_with($value, 'o1:')) {
|
|
$raw = base64_decode(substr($value, 3), true);
|
|
if ($raw === false || strlen($raw) < 28) return '';
|
|
$iv = substr($raw, 0, 12);
|
|
$tag = substr($raw, 12, 16);
|
|
$cipher = substr($raw, 28);
|
|
$plain = openssl_decrypt($cipher, 'aes-256-gcm', admin_gotify_key(), OPENSSL_RAW_DATA, $iv, $tag);
|
|
return is_string($plain) ? $plain : '';
|
|
}
|
|
// Legacy plaintext token - returned as-is; will be migrated on next save.
|
|
return $value;
|
|
}
|
|
|
|
function admin_gotify_is_encrypted(string $value): bool
|
|
{
|
|
return str_starts_with($value, 's1:') || str_starts_with($value, 'o1:');
|
|
}
|
|
|
|
function admin_gotify_users_load(): array
|
|
{
|
|
$path = admin_gotify_users_path();
|
|
if (file_exists($path)) {
|
|
$data = @include $path;
|
|
return is_array($data) ? $data : [];
|
|
}
|
|
// One-time migration from legacy JSON if present.
|
|
$legacy = admin_gotify_users_legacy_json_path();
|
|
if (file_exists($legacy)) {
|
|
$raw = @file_get_contents($legacy);
|
|
$data = json_decode(is_string($raw) ? $raw : '', true);
|
|
if (is_array($data)) {
|
|
admin_gotify_users_save_all($data);
|
|
@unlink($legacy);
|
|
return $data;
|
|
}
|
|
}
|
|
return [];
|
|
}
|
|
|
|
function admin_gotify_users_save_all(array $data): bool
|
|
{
|
|
$path = admin_gotify_users_path();
|
|
$export = var_export($data, true);
|
|
$php = "<?php\ndeclare(strict_types=1);\n\n// Gotify per-user settings. Kept as PHP to avoid direct browser access.\n// Tokens are encrypted at rest; do not treat this file as public.\nreturn " . $export . ";\n";
|
|
$ok = @file_put_contents($path, $php, LOCK_EX) !== false;
|
|
if ($ok) {
|
|
@chmod($path, 0600);
|
|
}
|
|
return $ok;
|
|
}
|
|
|
|
function admin_gotify_user_get(string $screenName): ?array
|
|
{
|
|
if (!function_exists('admin_normalize_screen_name')) return null;
|
|
$key = admin_normalize_screen_name($screenName);
|
|
if ($key === '') return null;
|
|
$all = admin_gotify_users_load();
|
|
$row = $all[$key] ?? null;
|
|
if (!is_array($row)) return null;
|
|
$url = trim((string) ($row['url'] ?? ''));
|
|
$storedToken = trim((string) ($row['token'] ?? ''));
|
|
if ($url === '' || $storedToken === '') return null;
|
|
$token = admin_gotify_decrypt($storedToken);
|
|
if ($token === '') return null;
|
|
|
|
// Transparently migrate legacy plaintext tokens to encrypted storage.
|
|
if (!admin_gotify_is_encrypted($storedToken)) {
|
|
$row['token'] = admin_gotify_encrypt($token);
|
|
$row['updated_at'] = (string) ($row['updated_at'] ?? date('c'));
|
|
$all[$key] = $row;
|
|
admin_gotify_users_save_all($all);
|
|
}
|
|
|
|
return [
|
|
'url' => $url,
|
|
'token' => $token,
|
|
'priority' => max(0, min(10, (int) ($row['priority'] ?? admin_cfg('gotify_priority', 5)))),
|
|
'updated_at' => (string) ($row['updated_at'] ?? ''),
|
|
];
|
|
}
|
|
|
|
function admin_gotify_user_save(string $screenName, string $url, string $token, ?int $priority = null): array
|
|
{
|
|
if (!function_exists('admin_normalize_screen_name')) {
|
|
return ['ok' => false, 'error' => 'Missing admin helpers.'];
|
|
}
|
|
$key = admin_normalize_screen_name($screenName);
|
|
if ($key === '') return ['ok' => false, 'error' => 'Invalid screen name.'];
|
|
$url = rtrim(trim($url), '/');
|
|
$token = trim($token);
|
|
$priority = $priority ?? (int) admin_cfg('gotify_priority', 5);
|
|
$priority = max(0, min(10, $priority));
|
|
|
|
$all = admin_gotify_users_load();
|
|
if ($url === '' || $token === '') {
|
|
unset($all[$key]);
|
|
$saved = admin_gotify_users_save_all($all);
|
|
return $saved ? ['ok' => true, 'cleared' => true] : ['ok' => false, 'error' => 'Failed to save Gotify settings.'];
|
|
}
|
|
|
|
// Basic validation
|
|
if (!preg_match('#^https?://#i', $url)) {
|
|
return ['ok' => false, 'error' => 'Gotify URL must start with http:// or https://'];
|
|
}
|
|
|
|
$encToken = admin_gotify_encrypt($token);
|
|
if ($encToken === '') {
|
|
return ['ok' => false, 'error' => 'Failed to secure Gotify token.'];
|
|
}
|
|
|
|
$all[$key] = [
|
|
'screen_name' => $screenName,
|
|
'url' => $url,
|
|
'token' => $encToken,
|
|
'priority' => $priority,
|
|
'updated_at' => date('c'),
|
|
];
|
|
$saved = admin_gotify_users_save_all($all);
|
|
return $saved ? ['ok' => true, 'cleared' => false] : ['ok' => false, 'error' => 'Failed to save Gotify settings.'];
|
|
}
|
|
|
|
function admin_gotify_resolve(string $screenName): ?array
|
|
{
|
|
$user = admin_gotify_user_get($screenName);
|
|
if ($user) return $user;
|
|
// Optional global fallback
|
|
$url = rtrim(trim((string) admin_cfg('gotify_url', '')), '/');
|
|
$token = trim((string) admin_cfg('gotify_token', ''));
|
|
if ($url !== '' && $token !== '') {
|
|
return [
|
|
'url' => $url,
|
|
'token' => $token,
|
|
'priority' => max(0, min(10, (int) admin_cfg('gotify_priority', 5))),
|
|
'updated_at' => '',
|
|
'fallback' => true,
|
|
];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function admin_gotify_enabled(): bool
|
|
{
|
|
// Back-compat alias: feature toggle (not "is configured for a specific user").
|
|
return admin_gotify_feature_enabled();
|
|
}
|
|
|
|
function admin_gotify_send(string $title, string $message, ?int $priority = null, ?string $url = null, ?string $token = null): array
|
|
{
|
|
if (!admin_gotify_feature_enabled()) {
|
|
return ['ok' => false, 'status' => 0, 'error' => 'Gotify is not enabled', 'data' => null, 'raw' => ''];
|
|
}
|
|
|
|
$url = rtrim(trim((string) ($url ?? admin_cfg('gotify_url', ''))), '/');
|
|
$token = trim((string) ($token ?? admin_cfg('gotify_token', '')));
|
|
if ($url === '' || $token === '') {
|
|
return ['ok' => false, 'status' => 0, 'error' => 'Gotify is not configured', 'data' => null, 'raw' => ''];
|
|
}
|
|
|
|
$priority = $priority ?? (int) admin_cfg('gotify_priority', 5);
|
|
$priority = max(0, min(10, $priority));
|
|
|
|
$endpoint = $url . '/message?token=' . rawurlencode($token);
|
|
$payload = json_encode([
|
|
'title' => $title,
|
|
'message' => $message,
|
|
'priority' => $priority,
|
|
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
|
|
|
$ch = curl_init($endpoint);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_POST => true,
|
|
CURLOPT_HTTPHEADER => ['Content-Type: application/json; charset=utf-8', 'Accept: application/json'],
|
|
CURLOPT_POSTFIELDS => $payload,
|
|
CURLOPT_TIMEOUT => 10,
|
|
CURLOPT_CONNECTTIMEOUT => 5,
|
|
]);
|
|
|
|
$raw = curl_exec($ch);
|
|
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
|
$err = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
if ($raw === false) {
|
|
return ['ok' => false, 'status' => 0, 'error' => $err ?: 'Gotify request failed', 'data' => null, 'raw' => ''];
|
|
}
|
|
|
|
$decoded = json_decode($raw, true);
|
|
$ok = $status >= 200 && $status < 300;
|
|
return [
|
|
'ok' => $ok,
|
|
'status' => $status,
|
|
'error' => $ok ? null : (is_array($decoded) && isset($decoded['errorDescription']) ? (string) $decoded['errorDescription'] : ($raw !== '' ? $raw : 'HTTP ' . $status)),
|
|
'data' => $decoded,
|
|
'raw' => $raw,
|
|
];
|
|
}
|
|
|
|
function admin_gotify_send_for_user(string $screenName, string $title, string $message, ?int $priority = null): array
|
|
{
|
|
$cfg = admin_gotify_resolve($screenName);
|
|
if (!$cfg) {
|
|
return ['ok' => false, 'status' => 0, 'error' => 'No Gotify configuration for this user', 'data' => null, 'raw' => ''];
|
|
}
|
|
return admin_gotify_send($title, $message, $priority ?? $cfg['priority'], $cfg['url'], $cfg['token']);
|
|
}
|