Breaking wire-format change: dual-read (V1+V2) / single-write (V2) so existing user secrets, stored messages, and inter-tenant key keep working. Old clients and relays lose cross-version chat until both sides are upgraded. Relay - Switch clientEncrypt/masterEncrypt to AES-256-GCM with HKDF-derived per-ciphertext salts; keep CBC-V1 fallback on decrypt only. - On-bootstrap migration re-envelopes tenant secret_encrypted and the inter-tenant key to GCM-V2 (idempotent). - CORS: stop reflecting arbitrary Origin; allow own origin + optional RELAY_CORS_ORIGINS env allowlist; drop Access-Control-Allow-Credentials. - Generic error messages replace "no such user: <name>" enumeration. - Exception messages no longer echoed back; logged server-side. - Collab-lock max hold capped at 10min so a member can't grief-refresh forever. - Attachment filenames validated against hex.<ext> pattern. - Passwords min length 10; /api/account/password rate-limited. App / Electron client - Shared hyprcrdRelayEncrypt/Decrypt helpers (GCM-V2 write, V1 read). - Chat + collab-buckets plugins delegate to the shared helpers. - Poll + push + attachments migrated to the dual-format path. - /api/relay/settings GET returns has_key boolean; secret never echoed. - Setup endpoint now CSRF-checked. - SSRF: CURLOPT_PROTOCOLS restricted to HTTP(S) everywhere; bookmarks favicon fetch also blocks private/loopback/link-local. - Login / password-change rate limiter moved to DB-backed IP keying. - Passwords min length 10 throughout. - Zip import enforces per-file (25MB) and total (500MB) caps, extension allowlist, no-overwrite. - Verbose relay-push debug gated behind APP_DEBUG env. Version bumped to 2.0.0 (protocol-breaking). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
129 lines
5.7 KiB
PHP
129 lines
5.7 KiB
PHP
<?php
|
|
// Crypto helpers.
|
|
//
|
|
// Two envelope formats coexist during the v1.10 rollout:
|
|
//
|
|
// HYPRCRD-GCM-V2 — new: AES-256-GCM, per-ciphertext random salt + HKDF
|
|
// (authenticated, standard). Used for every new write.
|
|
// HYPRCRD-RELAY-V1 — legacy: AES-256-CBC, substr(hex(sha256(secret))) as a
|
|
// 32-byte ASCII key, no MAC. Dual-read only.
|
|
//
|
|
// For at-rest master-key encryption the legacy format carries no magic
|
|
// prefix (raw base64(iv || cipher)). The new format uses HYPRCRD-MGCM-V2.
|
|
//
|
|
// Same user secret works across both formats — only the KDF and cipher
|
|
// differ. Old data stays readable forever via the V1 fallback; new data
|
|
// is authenticated and cannot be silently mutated.
|
|
|
|
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
|
|
|
const HYPRCRD_GCM_MAGIC_CLIENT = 'HYPRCRD-GCM-V2';
|
|
const HYPRCRD_CBC_MAGIC_CLIENT = 'HYPRCRD-RELAY-V1';
|
|
const HYPRCRD_GCM_MAGIC_MASTER = 'HYPRCRD-MGCM-V2';
|
|
const HYPRCRD_HKDF_INFO_CLIENT = 'hyprcrd-relay-client-v2';
|
|
|
|
/**
|
|
* Encrypt a value at-rest with the master key. The master key is already
|
|
* cryptographically random (32 raw bytes), so no KDF stretching is needed —
|
|
* a fresh 12-byte nonce per ciphertext is enough for GCM.
|
|
*/
|
|
function masterEncrypt(string $plain, string $masterKeyHex): string {
|
|
$key = hex2bin($masterKeyHex);
|
|
$nonce = random_bytes(12);
|
|
$tag = '';
|
|
$cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag, '', 16);
|
|
return HYPRCRD_GCM_MAGIC_MASTER . "\n" . base64_encode($nonce . $cipher . $tag);
|
|
}
|
|
|
|
function masterDecrypt(string $encoded, string $masterKeyHex): string {
|
|
$key = hex2bin($masterKeyHex);
|
|
if (str_starts_with($encoded, HYPRCRD_GCM_MAGIC_MASTER)) {
|
|
$b64 = trim(substr($encoded, strlen(HYPRCRD_GCM_MAGIC_MASTER) + 1));
|
|
$raw = base64_decode($b64, true);
|
|
if (!$raw || strlen($raw) < 12 + 16 + 1) return '';
|
|
$nonce = substr($raw, 0, 12);
|
|
$tag = substr($raw, -16);
|
|
$cipher = substr($raw, 12, -16);
|
|
$plain = openssl_decrypt($cipher, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag);
|
|
return $plain !== false ? $plain : '';
|
|
}
|
|
// Legacy: base64(iv(16) || ciphertext) under AES-256-CBC, no prefix.
|
|
$raw = base64_decode($encoded, true);
|
|
if (!$raw || strlen($raw) < 17) return '';
|
|
$iv = substr($raw, 0, 16);
|
|
$cipher = substr($raw, 16);
|
|
return openssl_decrypt($cipher, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv) ?: '';
|
|
}
|
|
|
|
/**
|
|
* Encrypt with a user-chosen secret (client API "shared secret" and the
|
|
* relay-wide inter-tenant key). V2 format:
|
|
* magic "\n" base64( salt(16) || nonce(12) || ciphertext || tag(16) )
|
|
* Per-ciphertext salt feeds HKDF(SHA-256) to derive a fresh 32-byte subkey
|
|
* — defeats the weak legacy substr-of-hex KDF and removes cross-tenant
|
|
* key collisions for identical secrets.
|
|
*/
|
|
function clientEncrypt(string $plain, string $secret): string {
|
|
$salt = random_bytes(16);
|
|
$nonce = random_bytes(12);
|
|
$key = hash_hkdf('sha256', $secret, 32, HYPRCRD_HKDF_INFO_CLIENT, $salt);
|
|
$tag = '';
|
|
$cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag, '', 16);
|
|
return HYPRCRD_GCM_MAGIC_CLIENT . "\n" . base64_encode($salt . $nonce . $cipher . $tag);
|
|
}
|
|
|
|
function clientDecrypt(string $envelope, string $secret): string {
|
|
if (str_starts_with($envelope, HYPRCRD_GCM_MAGIC_CLIENT)) {
|
|
$b64 = trim(substr($envelope, strlen(HYPRCRD_GCM_MAGIC_CLIENT) + 1));
|
|
$raw = base64_decode($b64, true);
|
|
if (!$raw || strlen($raw) < 16 + 12 + 16 + 1) return '';
|
|
$salt = substr($raw, 0, 16);
|
|
$nonce = substr($raw, 16, 12);
|
|
$tag = substr($raw, -16);
|
|
$cipher = substr($raw, 28, -16);
|
|
$key = hash_hkdf('sha256', $secret, 32, HYPRCRD_HKDF_INFO_CLIENT, $salt);
|
|
$plain = openssl_decrypt($cipher, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag);
|
|
return $plain !== false ? $plain : '';
|
|
}
|
|
if (str_starts_with($envelope, HYPRCRD_CBC_MAGIC_CLIENT)) {
|
|
$b64 = trim(substr($envelope, strlen(HYPRCRD_CBC_MAGIC_CLIENT) + 1));
|
|
$raw = base64_decode($b64, true);
|
|
if (!$raw || strlen($raw) < 17) return '';
|
|
$key = substr(hash('sha256', $secret), 0, 32);
|
|
$iv = substr($raw, 0, 16);
|
|
$cipher = substr($raw, 16);
|
|
$result = openssl_decrypt($cipher, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
|
|
return $result !== false ? $result : '';
|
|
}
|
|
// Neither envelope — passthrough. Preserves the old behaviour where
|
|
// already-plaintext fields flowed through unchanged.
|
|
return $envelope;
|
|
}
|
|
|
|
/**
|
|
* Inter-tenant key: relay-wide shared "super secret" key. Set by the admin
|
|
* during initial setup (it's the third field in the setup form). Used to
|
|
* re-encrypt messages at rest so they can be routed between tenants.
|
|
*
|
|
* Returns null if not set yet.
|
|
*/
|
|
function getInterTenantKey(PDO $db, string $masterKey): ?string {
|
|
$stored = $db->query("SELECT value FROM settings WHERE key = 'inter_tenant_key'")->fetchColumn();
|
|
if (!$stored) return null;
|
|
$decrypted = masterDecrypt($stored, $masterKey);
|
|
return $decrypted !== '' ? $decrypted : null;
|
|
}
|
|
|
|
/** Set/replace the inter-tenant key. Stored encrypted with the master key. */
|
|
function setInterTenantKey(PDO $db, string $masterKey, string $newKey): void {
|
|
$encrypted = masterEncrypt($newKey, $masterKey);
|
|
$db->prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('inter_tenant_key', :v)")
|
|
->execute(['v' => $encrypted]);
|
|
}
|
|
|
|
/** True if the relay-wide super secret has been configured. */
|
|
function hasInterTenantKey(PDO $db): bool {
|
|
$stored = $db->query("SELECT value FROM settings WHERE key = 'inter_tenant_key'")->fetchColumn();
|
|
return !empty($stored);
|
|
}
|