442 lines
16 KiB
PHP
442 lines
16 KiB
PHP
|
|
<?php
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Web-Push ohne externe Abhängigkeiten.
|
||
|
|
*
|
||
|
|
* Verschlüsselung nach RFC 8291 (Content-Encoding `aes128gcm`) und
|
||
|
|
* Authentifizierung nach RFC 8292 (VAPID, JWT mit ES256). Beides baut nur auf
|
||
|
|
* Erweiterungen auf, die auf dem Shared Host vorhanden sind (openssl, curl).
|
||
|
|
*
|
||
|
|
* Konfiguration über app/config.local.php:
|
||
|
|
* push.public_key base64url des unkomprimierten P-256-Punkts (65 Byte)
|
||
|
|
* push.private_key base64url des privaten Schlüssels (32 Byte)
|
||
|
|
* push.subject Kontakt-URI, z. B. mailto:admin@example.org
|
||
|
|
*
|
||
|
|
* Die Schlüssel werden beim Deployment aus docs/credentials.txt übernommen.
|
||
|
|
*/
|
||
|
|
class WebPush {
|
||
|
|
|
||
|
|
/** Wie lange der Push-Dienst eine Nachricht aufbewahren darf, wenn das Gerät offline ist. */
|
||
|
|
const TTL = 86400;
|
||
|
|
|
||
|
|
/** Maximale Größe eines verschlüsselten Datensatzes (RFC 8188). */
|
||
|
|
const RECORD_SIZE = 4096;
|
||
|
|
|
||
|
|
/** Timeout für den Versand (einzelnes Abo, nicht der ganze Lauf) */
|
||
|
|
const TIMEOUT = 10;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Sind alle für den Versand nötigen Werte konfiguriert?
|
||
|
|
*
|
||
|
|
* @return bool
|
||
|
|
*/
|
||
|
|
public static function isConfigured() {
|
||
|
|
$public = self::publicKey();
|
||
|
|
if ($public === null) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
$point = self::base64UrlDecode($public);
|
||
|
|
return $point !== false && strlen($point) === 65 && self::privateKey() !== null;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Öffentlicher VAPID-Schlüssel als base64url (für `applicationServerKey` im Browser).
|
||
|
|
*
|
||
|
|
* @return string|null
|
||
|
|
*/
|
||
|
|
public static function publicKey() {
|
||
|
|
$key = config('push.public_key');
|
||
|
|
if (!is_string($key) || trim($key) === '') {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
return trim($key);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Kontakt-URI für den VAPID-Claim `sub`. Fällt auf APP_URL zurück.
|
||
|
|
*
|
||
|
|
* @return string
|
||
|
|
*/
|
||
|
|
public static function subject() {
|
||
|
|
$subject = config('push.subject');
|
||
|
|
if (!is_string($subject) || trim($subject) === '') {
|
||
|
|
$subject = config('app.public_url', 'https://drink-it-cold.programmschmiede.de');
|
||
|
|
}
|
||
|
|
return trim((string) $subject);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Privaten Schlüssel laden. Unterstützt das gespeicherte Format
|
||
|
|
* (base64url des 32-Byte-Skalars) und direkt hinterlegtes PEM.
|
||
|
|
*
|
||
|
|
* @return \OpenSSLAsymmetricKey|resource|null
|
||
|
|
*/
|
||
|
|
private static function privateKey() {
|
||
|
|
$raw = config('push.private_key');
|
||
|
|
if (!is_string($raw) || trim($raw) === '') {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
$raw = trim($raw);
|
||
|
|
|
||
|
|
if (strpos($raw, 'BEGIN') !== false) {
|
||
|
|
$key = openssl_pkey_get_private(str_replace('\n', "\n", $raw));
|
||
|
|
return $key === false ? null : $key;
|
||
|
|
}
|
||
|
|
|
||
|
|
$scalar = self::base64UrlDecode($raw);
|
||
|
|
$public = self::publicKey();
|
||
|
|
if ($scalar === false || strlen($scalar) !== 32 || $public === null) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
$point = self::base64UrlDecode($public);
|
||
|
|
if ($point === false || strlen($point) !== 65) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
$key = openssl_pkey_get_private(self::privateKeyPem($scalar, $point));
|
||
|
|
return $key === false ? null : $key;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Prüft einen Push-Endpunkt: HTTPS, plausibler Host, kein internes Ziel.
|
||
|
|
*
|
||
|
|
* @param string $endpoint
|
||
|
|
* @return bool
|
||
|
|
*/
|
||
|
|
public static function isValidEndpoint($endpoint) {
|
||
|
|
if (!is_string($endpoint) || strlen($endpoint) > 1000 || strlen($endpoint) < 10) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
$parts = parse_url($endpoint);
|
||
|
|
if (!$parts || empty($parts['scheme']) || empty($parts['host'])) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
if (strtolower($parts['scheme']) !== 'https') {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
$host = strtolower($parts['host']);
|
||
|
|
if ($host === 'localhost' || substr($host, -6) === '.local') {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
if (filter_var($host, FILTER_VALIDATE_IP)) {
|
||
|
|
// Keine privaten/reservierten Adressen (SSRF-Schutz).
|
||
|
|
if (!filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Prüft die Schlüssel eines Abos, bevor es gespeichert wird.
|
||
|
|
*
|
||
|
|
* @param string $p256dh base64url des Geräteschlüssels (65 Byte, unkomprimierter Punkt)
|
||
|
|
* @param string $auth base64url des Auth-Geheimnisses (16 Byte)
|
||
|
|
* @return bool
|
||
|
|
*/
|
||
|
|
public static function isValidKeyMaterial($p256dh, $auth) {
|
||
|
|
$point = self::base64UrlDecode($p256dh);
|
||
|
|
$secret = self::base64UrlDecode($auth);
|
||
|
|
return $point !== false && strlen($point) === 65 && $point[0] === "\x04"
|
||
|
|
&& $secret !== false && strlen($secret) === 16;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Versendet eine Nachricht an ein Abo.
|
||
|
|
*
|
||
|
|
* @param array $subscription ['endpoint' => string, 'p256dh' => string, 'auth' => string]
|
||
|
|
* @param array $payload Beliebige JSON-Struktur (Titel, Text, URL)
|
||
|
|
* @return array ['ok' => bool, 'status' => int, 'gone' => bool, 'error' => string]
|
||
|
|
*/
|
||
|
|
public static function send(array $subscription, array $payload) {
|
||
|
|
$result = ['ok' => false, 'status' => 0, 'gone' => false, 'error' => ''];
|
||
|
|
|
||
|
|
if (!self::isConfigured()) {
|
||
|
|
$result['error'] = 'VAPID ist nicht konfiguriert.';
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
if (!function_exists('curl_init')) {
|
||
|
|
$result['error'] = 'curl ist nicht verfügbar.';
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
|
||
|
|
foreach (['endpoint', 'p256dh', 'auth'] as $field) {
|
||
|
|
if (empty($subscription[$field])) {
|
||
|
|
$result['error'] = 'Abo unvollständig (' . $field . ').';
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if (!self::isValidEndpoint($subscription['endpoint'])) {
|
||
|
|
$result['error'] = 'Ungültiger Push-Endpunkt.';
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
$body = self::encrypt(json_encode($payload), $subscription['p256dh'], $subscription['auth']);
|
||
|
|
$headers = self::headers($subscription['endpoint']);
|
||
|
|
} catch (\Throwable $e) {
|
||
|
|
$result['error'] = $e->getMessage();
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
|
||
|
|
$curl = curl_init($subscription['endpoint']);
|
||
|
|
curl_setopt_array($curl, [
|
||
|
|
CURLOPT_POST => true,
|
||
|
|
CURLOPT_POSTFIELDS => $body,
|
||
|
|
CURLOPT_HTTPHEADER => $headers,
|
||
|
|
CURLOPT_RETURNTRANSFER => true,
|
||
|
|
CURLOPT_TIMEOUT => self::TIMEOUT,
|
||
|
|
CURLOPT_CONNECTTIMEOUT => 5,
|
||
|
|
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
||
|
|
CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTPS,
|
||
|
|
CURLOPT_FOLLOWLOCATION => false,
|
||
|
|
]);
|
||
|
|
$response = curl_exec($curl);
|
||
|
|
$status = (int)curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
|
||
|
|
$error = curl_error($curl);
|
||
|
|
curl_close($curl);
|
||
|
|
|
||
|
|
$result['status'] = $status;
|
||
|
|
if ($response === false) {
|
||
|
|
$result['error'] = $error !== '' ? $error : 'Verbindungsfehler.';
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
if ($status === 201 || $status === 202) {
|
||
|
|
$result['ok'] = true;
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
|
||
|
|
$result['gone'] = ($status === 404 || $status === 410);
|
||
|
|
$result['error'] = 'HTTP ' . $status;
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Baut die HTTP-Header inklusive VAPID-Autorisierung.
|
||
|
|
*
|
||
|
|
* @param string $endpoint
|
||
|
|
* @return string[]
|
||
|
|
*/
|
||
|
|
private static function headers($endpoint) {
|
||
|
|
$public = self::publicKey();
|
||
|
|
$parts = parse_url($endpoint);
|
||
|
|
if (!$parts || empty($parts['scheme']) || empty($parts['host'])) {
|
||
|
|
throw new \InvalidArgumentException('Ungültiger Push-Endpunkt.');
|
||
|
|
}
|
||
|
|
$audience = $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : '');
|
||
|
|
$jwt = self::vapidJwt($audience, $public);
|
||
|
|
|
||
|
|
return [
|
||
|
|
'Content-Type: application/octet-stream',
|
||
|
|
'Content-Encoding: aes128gcm',
|
||
|
|
'TTL: ' . self::TTL,
|
||
|
|
'Urgency: normal',
|
||
|
|
'Authorization: vapid t=' . $jwt . ', k=' . $public,
|
||
|
|
];
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Signiert die VAPID-Claims als ES256-JWT.
|
||
|
|
*
|
||
|
|
* @param string $audience Origin des Push-Dienstes
|
||
|
|
* @param string $publicKey base64url des öffentlichen Schlüssels
|
||
|
|
* @return string
|
||
|
|
*/
|
||
|
|
private static function vapidJwt($audience, $publicKey) {
|
||
|
|
$private = self::privateKey();
|
||
|
|
if (!$private) {
|
||
|
|
throw new \RuntimeException('VAPID_PRIVATE_KEY ist ungültig.');
|
||
|
|
}
|
||
|
|
|
||
|
|
$header = self::base64UrlEncode(json_encode(['typ' => 'JWT', 'alg' => 'ES256']));
|
||
|
|
$claims = self::base64UrlEncode(json_encode([
|
||
|
|
'aud' => $audience,
|
||
|
|
'exp' => time() + 43200,
|
||
|
|
'sub' => self::subject(),
|
||
|
|
]));
|
||
|
|
$unsigned = $header . '.' . $claims;
|
||
|
|
|
||
|
|
if (!openssl_sign($unsigned, $signature, $private, OPENSSL_ALGO_SHA256)) {
|
||
|
|
throw new \RuntimeException('VAPID-Signatur fehlgeschlagen.');
|
||
|
|
}
|
||
|
|
|
||
|
|
return $unsigned . '.' . self::base64UrlEncode(self::derToRaw($signature));
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Verschlüsselt die Nutzlast für ein Abo (RFC 8291, aes128gcm).
|
||
|
|
*
|
||
|
|
* @param string $payload
|
||
|
|
* @param string $p256dh base64url des Geräteschlüssels (65 Byte)
|
||
|
|
* @param string $auth base64url des Auth-Geheimnisses (16 Byte)
|
||
|
|
* @param string|null $salt Nur für Tests: feste Salt statt Zufall
|
||
|
|
* @param \OpenSSLAsymmetricKey|resource|null $ephemeral Nur für Tests: festes Server-Schlüsselpaar
|
||
|
|
* @return string Binärer Request-Body
|
||
|
|
*/
|
||
|
|
public static function encrypt($payload, $p256dh, $auth, $salt = null, $ephemeral = null) {
|
||
|
|
$uaPublic = self::base64UrlDecode($p256dh);
|
||
|
|
$authSecret = self::base64UrlDecode($auth);
|
||
|
|
if ($uaPublic === false || strlen($uaPublic) !== 65) {
|
||
|
|
throw new \InvalidArgumentException('p256dh ist ungültig.');
|
||
|
|
}
|
||
|
|
if ($authSecret === false || strlen($authSecret) !== 16) {
|
||
|
|
throw new \InvalidArgumentException('auth ist ungültig.');
|
||
|
|
}
|
||
|
|
|
||
|
|
// Einmaliges Server-Schlüsselpaar für diese Nachricht
|
||
|
|
if ($ephemeral === null) {
|
||
|
|
$ephemeral = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]);
|
||
|
|
}
|
||
|
|
if (!$ephemeral) {
|
||
|
|
throw new \RuntimeException('Temporärer EC-Schlüssel konnte nicht erzeugt werden.');
|
||
|
|
}
|
||
|
|
$details = openssl_pkey_get_details($ephemeral);
|
||
|
|
$asPublic = "\x04" . $details['ec']['x'] . $details['ec']['y'];
|
||
|
|
|
||
|
|
$uaKey = openssl_pkey_get_public(self::publicKeyPem($uaPublic));
|
||
|
|
if (!$uaKey) {
|
||
|
|
throw new \InvalidArgumentException('p256dh ist kein gültiger P-256-Punkt.');
|
||
|
|
}
|
||
|
|
$shared = openssl_pkey_derive($uaKey, $ephemeral, 32);
|
||
|
|
if ($shared === false) {
|
||
|
|
throw new \RuntimeException('ECDH-Schlüsselaustausch fehlgeschlagen.');
|
||
|
|
}
|
||
|
|
|
||
|
|
$prkKey = hash_hmac('sha256', $shared, $authSecret, true);
|
||
|
|
$ikm = self::hkdfExpand($prkKey, "WebPush: info\x00" . $uaPublic . $asPublic, 32);
|
||
|
|
|
||
|
|
$salt = $salt === null ? random_bytes(16) : $salt;
|
||
|
|
if (strlen($salt) !== 16) {
|
||
|
|
throw new \InvalidArgumentException('Salt muss 16 Byte lang sein.');
|
||
|
|
}
|
||
|
|
$prk = hash_hmac('sha256', $ikm, $salt, true);
|
||
|
|
$cek = self::hkdfExpand($prk, "Content-Encoding: aes128gcm\x00", 16);
|
||
|
|
$nonce = self::hkdfExpand($prk, "Content-Encoding: nonce\x00", 12);
|
||
|
|
|
||
|
|
$plain = $payload . "\x02";
|
||
|
|
$header = $salt . pack('N', self::RECORD_SIZE) . chr(65) . $asPublic;
|
||
|
|
// RFC 8188, Abschnitt 2.1: AAD ist ausdrücklich leer. Der Header wird
|
||
|
|
// nur übertragen, nicht authentifiziert.
|
||
|
|
$cipher = openssl_encrypt($plain, 'aes-128-gcm', $cek, OPENSSL_RAW_DATA, $nonce, $tag, '', 16);
|
||
|
|
if ($cipher === false) {
|
||
|
|
throw new \RuntimeException('Verschlüsselung fehlgeschlagen.');
|
||
|
|
}
|
||
|
|
|
||
|
|
return $header . $cipher . $tag;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* HKDF-Expand mit HMAC-SHA-256 (RFC 5869).
|
||
|
|
*
|
||
|
|
* @param string $prk Pseudozufälliger Schlüssel (Extract-Ergebnis)
|
||
|
|
* @param string $info Kontext
|
||
|
|
* @param int $length Gewünschte Länge
|
||
|
|
* @return string
|
||
|
|
*/
|
||
|
|
private static function hkdfExpand($prk, $info, $length) {
|
||
|
|
$output = '';
|
||
|
|
$block = '';
|
||
|
|
for ($i = 1; strlen($output) < $length; $i++) {
|
||
|
|
$block = hash_hmac('sha256', $block . $info . chr($i), $prk, true);
|
||
|
|
$output .= $block;
|
||
|
|
}
|
||
|
|
return substr($output, 0, $length);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Wandelt eine DER-Signatur (SEQUENCE aus r und s) in das für JWS nötige
|
||
|
|
* Rohformat (32 Byte r || 32 Byte s).
|
||
|
|
*
|
||
|
|
* @param string $der
|
||
|
|
* @return string
|
||
|
|
*/
|
||
|
|
private static function derToRaw($der) {
|
||
|
|
$offset = 2;
|
||
|
|
if (ord($der[1]) & 0x80) {
|
||
|
|
$offset += ord($der[1]) & 0x7f;
|
||
|
|
}
|
||
|
|
$rLength = ord($der[$offset + 1]);
|
||
|
|
$r = substr($der, $offset + 2, $rLength);
|
||
|
|
$sOffset = $offset + 2 + $rLength;
|
||
|
|
$sLength = ord($der[$sOffset + 1]);
|
||
|
|
$s = substr($der, $sOffset + 2, $sLength);
|
||
|
|
|
||
|
|
return str_pad(ltrim($r, "\x00"), 32, "\x00", STR_PAD_LEFT)
|
||
|
|
. str_pad(ltrim($s, "\x00"), 32, "\x00", STR_PAD_LEFT);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Baut aus dem privaten Skalar und dem öffentlichen Punkt ein SEC1-PEM.
|
||
|
|
*
|
||
|
|
* @param string $scalar 32 Byte
|
||
|
|
* @param string $point Unkomprimierter Punkt (65 Byte)
|
||
|
|
* @return string
|
||
|
|
*/
|
||
|
|
private static function privateKeyPem($scalar, $point) {
|
||
|
|
// SEC1: parameters [0] enthält nur die Kurve, publicKey [1] den Punkt.
|
||
|
|
$curve = self::derTlv(0xa0, self::curveOid());
|
||
|
|
$public = self::derTlv(0xa1, self::derTlv(0x03, "\x00" . $point));
|
||
|
|
$der = self::derTlv(0x30,
|
||
|
|
self::derTlv(0x02, "\x01")
|
||
|
|
. self::derTlv(0x04, $scalar)
|
||
|
|
. $curve
|
||
|
|
. $public
|
||
|
|
);
|
||
|
|
return self::pem('EC PRIVATE KEY', $der);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Baut aus einem unkomprimierten Punkt ein SPKI-PEM.
|
||
|
|
*
|
||
|
|
* @param string $point 65 Byte
|
||
|
|
* @return string
|
||
|
|
*/
|
||
|
|
private static function publicKeyPem($point) {
|
||
|
|
$algorithm = self::derTlv(0x30, self::ecOid() . self::curveOid());
|
||
|
|
$der = self::derTlv(0x30, $algorithm . self::derTlv(0x03, "\x00" . $point));
|
||
|
|
return self::pem('PUBLIC KEY', $der);
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function ecOid() {
|
||
|
|
return self::derTlv(0x06, "\x2a\x86\x48\xce\x3d\x02\x01");
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function curveOid() {
|
||
|
|
return self::derTlv(0x06, "\x2a\x86\x48\xce\x3d\x03\x01\x07");
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function pem($label, $der) {
|
||
|
|
return "-----BEGIN " . $label . "-----\n"
|
||
|
|
. chunk_split(base64_encode($der), 64, "\n")
|
||
|
|
. "-----END " . $label . "-----\n";
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function derTlv($tag, $value) {
|
||
|
|
return chr($tag) . self::derLength(strlen($value)) . $value;
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function derLength($length) {
|
||
|
|
if ($length < 0x80) {
|
||
|
|
return chr($length);
|
||
|
|
}
|
||
|
|
$bytes = ltrim(pack('N', $length), "\x00");
|
||
|
|
return chr(0x80 | strlen($bytes)) . $bytes;
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function base64UrlEncode($data) {
|
||
|
|
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function base64UrlDecode($data) {
|
||
|
|
if (!is_string($data)) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
$data = strtr($data, '-_', '+/');
|
||
|
|
$remainder = strlen($data) % 4;
|
||
|
|
if ($remainder) {
|
||
|
|
$data .= str_repeat('=', 4 - $remainder);
|
||
|
|
}
|
||
|
|
return base64_decode($data, true);
|
||
|
|
}
|
||
|
|
}
|