Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
90.38% |
47 / 52 |
|
70.00% |
7 / 10 |
CRAP | |
0.00% |
0 / 1 |
| crypto | |
90.38% |
47 / 52 |
|
70.00% |
7 / 10 |
23.47 | |
0.00% |
0 / 1 |
| b64u_encode | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| b64u_decode | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
| generate_keys | |
71.43% |
5 / 7 |
|
0.00% |
0 / 1 |
5.58 | |||
| public_pem | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| private_pem | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| encrypt | |
83.33% |
10 / 12 |
|
0.00% |
0 / 1 |
3.04 | |||
| vapid | |
90.91% |
10 / 11 |
|
0.00% |
0 / 1 |
3.01 | |||
| der_to_raw | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
| raw_to_der | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
4 | |||
| pad32 | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | // This file is part of Moodle - https://moodle.org/ |
| 3 | // |
| 4 | // Moodle is free software: you can redistribute it and/or modify |
| 5 | // it under the terms of the GNU General Public License as published by |
| 6 | // the Free Software Foundation, either version 3 of the License, or |
| 7 | // (at your option) any later version. |
| 8 | // |
| 9 | // Moodle is distributed in the hope that it will be useful, |
| 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | // GNU General Public License for more details. |
| 13 | // |
| 14 | // You should have received a copy of the GNU General Public License |
| 15 | // along with Moodle. If not, see <https://www.gnu.org/licenses/>. |
| 16 | |
| 17 | namespace message_webpush\local; |
| 18 | |
| 19 | /** |
| 20 | * Web Push message encryption (RFC 8291, aes128gcm from RFC 8188) and VAPID tokens (RFC 8292), with PHP OpenSSL only. |
| 21 | * |
| 22 | * @package message_webpush |
| 23 | * @copyright 2026 DevLMS |
| 24 | * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later |
| 25 | */ |
| 26 | class crypto { |
| 27 | /** @var string DER prefix of a P-256 SubjectPublicKeyInfo; the 65-byte point follows. */ |
| 28 | private const SPKI_PREFIX = '3059301306072a8648ce3d020106082a8648ce3d030107034200'; |
| 29 | |
| 30 | /** @var int Record size written in the header; one record holds the whole message (RFC 8291 section 4). */ |
| 31 | private const RECORD_SIZE = 4096; |
| 32 | |
| 33 | /** |
| 34 | * Base64url without padding. |
| 35 | * |
| 36 | * @param string $bytes |
| 37 | * @return string |
| 38 | */ |
| 39 | public static function b64u_encode(string $bytes): string { |
| 40 | return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '='); |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Decode base64url, with or without padding. |
| 45 | * |
| 46 | * @param string $text |
| 47 | * @return string bytes, '' when the text is not base64url |
| 48 | */ |
| 49 | public static function b64u_decode(string $text): string { |
| 50 | $decoded = base64_decode(strtr($text, '-_', '+/'), true); |
| 51 | return $decoded === false ? '' : $decoded; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * A new P-256 key pair. |
| 56 | * |
| 57 | * @return array|null ['public' => 65 raw bytes, 'private' => PEM], or null when OpenSSL cannot make one |
| 58 | */ |
| 59 | public static function generate_keys(): ?array { |
| 60 | $key = @openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]); |
| 61 | if ($key === false || !@openssl_pkey_export($key, $pem)) { |
| 62 | return null; |
| 63 | } |
| 64 | $details = openssl_pkey_get_details($key); |
| 65 | if (empty($details['ec']['x']) || empty($details['ec']['y'])) { |
| 66 | return null; |
| 67 | } |
| 68 | return ['public' => "\x04" . self::pad32($details['ec']['x']) . self::pad32($details['ec']['y']), 'private' => $pem]; |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * PEM for a raw uncompressed P-256 public point. |
| 73 | * |
| 74 | * @param string $raw 65 bytes starting with 0x04 |
| 75 | * @return string |
| 76 | */ |
| 77 | public static function public_pem(string $raw): string { |
| 78 | return "-----BEGIN PUBLIC KEY-----\n" . chunk_split(base64_encode(hex2bin(self::SPKI_PREFIX) . $raw), 64, "\n") . |
| 79 | "-----END PUBLIC KEY-----\n"; |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * PEM (SEC 1) for a raw P-256 private scalar and its public point. |
| 84 | * |
| 85 | * @param string $d 32 bytes |
| 86 | * @param string $public 65 bytes |
| 87 | * @return string |
| 88 | */ |
| 89 | public static function private_pem(string $d, string $public): string { |
| 90 | $der = hex2bin('30770201010420') . $d . hex2bin('a00a06082a8648ce3d030107a144034200') . $public; |
| 91 | return "-----BEGIN EC PRIVATE KEY-----\n" . chunk_split(base64_encode($der), 64, "\n") . "-----END EC PRIVATE KEY-----\n"; |
| 92 | } |
| 93 | |
| 94 | /** |
| 95 | * Encrypt one push message for one browser subscription. |
| 96 | * |
| 97 | * @param string $plaintext at most 3993 bytes (RFC 8291 section 4) |
| 98 | * @param string $uapublic the subscription's p256dh key, 65 raw bytes |
| 99 | * @param string $auth the subscription's auth secret, 16 raw bytes |
| 100 | * @param array|null $as sender key pair for this message; a new one is made when null (tests pass fixed ones) |
| 101 | * @param string|null $salt 16 bytes; random when null |
| 102 | * @return string the request body: aes128gcm header followed by the single record |
| 103 | */ |
| 104 | public static function encrypt( |
| 105 | string $plaintext, |
| 106 | string $uapublic, |
| 107 | string $auth, |
| 108 | ?array $as = null, |
| 109 | ?string $salt = null |
| 110 | ): string { |
| 111 | $as = $as ?? self::generate_keys(); |
| 112 | if ($as === null) { |
| 113 | throw new \coding_exception('PHP OpenSSL cannot make P-256 keys'); |
| 114 | } |
| 115 | $salt = $salt ?? random_bytes(16); |
| 116 | |
| 117 | $secret = openssl_pkey_derive(self::public_pem($uapublic), $as['private'], 32); |
| 118 | if ($secret === false) { |
| 119 | throw new \coding_exception('The browser key is not a P-256 point'); |
| 120 | } |
| 121 | // RFC 8291 section 3.4: combine the ECDH secret with the auth secret, then RFC 8188 key and nonce. |
| 122 | $ikm = hash_hkdf('sha256', $secret, 32, "WebPush: info\x00" . $uapublic . $as['public'], $auth); |
| 123 | $cek = hash_hkdf('sha256', $ikm, 16, "Content-Encoding: aes128gcm\x00", $salt); |
| 124 | $nonce = hash_hkdf('sha256', $ikm, 12, "Content-Encoding: nonce\x00", $salt); |
| 125 | |
| 126 | // Padding delimiter 0x02 marks the last (only) record. |
| 127 | $cipher = openssl_encrypt($plaintext . "\x02", 'aes-128-gcm', $cek, OPENSSL_RAW_DATA, $nonce, $tag, '', 16); |
| 128 | return $salt . pack('N', self::RECORD_SIZE) . chr(strlen($as['public'])) . $as['public'] . $cipher . $tag; |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * The Authorization header value for one push service (RFC 8292 section 3). |
| 133 | * |
| 134 | * @param string $endpoint the subscription endpoint |
| 135 | * @param string $public site public key, 65 raw bytes |
| 136 | * @param string $private site private key, PEM |
| 137 | * @param string $subject https URL or mailto: contact for the push service |
| 138 | * @param int $now current time |
| 139 | * @return string "vapid t=..., k=..." |
| 140 | */ |
| 141 | public static function vapid(string $endpoint, string $public, string $private, string $subject, int $now): string { |
| 142 | $parts = parse_url($endpoint); |
| 143 | $audience = $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : ''); |
| 144 | $head = self::b64u_encode(json_encode(['typ' => 'JWT', 'alg' => 'ES256'])); |
| 145 | // Expiry under the 24 hour maximum of RFC 8292 section 2. |
| 146 | $claims = self::b64u_encode(json_encode( |
| 147 | ['aud' => $audience, 'exp' => $now + 12 * HOURSECS, 'sub' => $subject], |
| 148 | JSON_UNESCAPED_SLASHES |
| 149 | )); |
| 150 | if (!openssl_sign("$head.$claims", $der, $private, OPENSSL_ALGO_SHA256)) { |
| 151 | throw new \coding_exception('Could not sign the VAPID token'); |
| 152 | } |
| 153 | return 'vapid t=' . $head . '.' . $claims . '.' . self::b64u_encode(self::der_to_raw($der)) . ', k=' . |
| 154 | self::b64u_encode($public); |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * Turn an OpenSSL DER ECDSA signature into the 64-byte r||s form JWS uses (RFC 7518 section 3.4). |
| 159 | * |
| 160 | * @param string $der |
| 161 | * @return string |
| 162 | */ |
| 163 | public static function der_to_raw(string $der): string { |
| 164 | // SEQUENCE { INTEGER r, INTEGER s }; P-256 signatures are short enough for one-byte lengths. |
| 165 | $offset = 2; |
| 166 | $out = ''; |
| 167 | for ($i = 0; $i < 2; $i++) { |
| 168 | $length = ord($der[$offset + 1]); |
| 169 | $out .= self::pad32(substr($der, $offset + 2, $length)); |
| 170 | $offset += 2 + $length; |
| 171 | } |
| 172 | return $out; |
| 173 | } |
| 174 | |
| 175 | /** |
| 176 | * Turn a 64-byte r||s signature back into DER, for openssl_verify. |
| 177 | * |
| 178 | * @param string $raw |
| 179 | * @return string |
| 180 | */ |
| 181 | public static function raw_to_der(string $raw): string { |
| 182 | $body = ''; |
| 183 | foreach ([substr($raw, 0, 32), substr($raw, 32, 32)] as $int) { |
| 184 | $int = ltrim($int, "\x00"); |
| 185 | if ($int === '' || ord($int[0]) > 0x7f) { |
| 186 | $int = "\x00" . $int; |
| 187 | } |
| 188 | $body .= "\x02" . chr(strlen($int)) . $int; |
| 189 | } |
| 190 | return "\x30" . chr(strlen($body)) . $body; |
| 191 | } |
| 192 | |
| 193 | /** |
| 194 | * Left-pad or trim a big-endian integer to 32 bytes. |
| 195 | * |
| 196 | * @param string $int |
| 197 | * @return string |
| 198 | */ |
| 199 | private static function pad32(string $int): string { |
| 200 | return str_pad(substr(ltrim($int, "\x00"), -32), 32, "\x00", STR_PAD_LEFT); |
| 201 | } |
| 202 | } |