-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebpush_send.php
More file actions
executable file
·531 lines (477 loc) · 17.8 KB
/
Copy pathwebpush_send.php
File metadata and controls
executable file
·531 lines (477 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#!/usr/bin/env php
<?php
/**
* WebPush implementation in pure PHP.
*
* WebPush notification function, implementing the RFC 8030 (WebPush Protocol),
* RFC 8291 & RFC 8188 (Elliptic Curve Diffie-Hellman - ECDH and
* AES-GCM/AES-128-GCM - Authenticated Encryption with Associated Data) and RFC
* 8292 (Voluntary Application Server Identification - VAPID).
*
* Author: Ernani Azevedo <azevedo@voipdomain.io>
*/
// Generic helpers
/**
* Determine the length of a binary string using an 8-bit safe calculation to
* avoid multibyte-string pitfalls.
*
* @param string $data Binary string
* @return int Length in bytes
*/
function wp_safe_strlen ( string $data): int
{
return mb_strlen ( $data, "8bit");
}
/**
* Encode arbitrary binary data using URL-safe base64 (RFC 4648 §5) without
* padding characters.
*
* @param string $data Arbitrary binary input
* @return string Base64url-encoded string (no trailing "=")
*/
function wp_base64url_encode ( string $data): string
{
return rtrim ( strtr ( base64_encode ( $data), "+/", "-_"), "=");
}
/**
* Decode a URL-safe base64 string.
*
* @param string $data Base64url string (with or without padding)
* @return string Decoded binary
*/
function wp_base64url_decode ( string $data): string
{
$remainder = strlen ( $data) % 4;
if ( $remainder)
{
$data .= str_repeat ( "=", 4 - $remainder);
}
return base64_decode ( strtr ( $data, "-_", "+/"), true);
}
// ASN.1 helpers to build PEM from uncompressed EC point
/**
* Convert an uncompressed raw P-256 public key (65 bytes, 0x04||X||Y) into a
* PEM-encoded SubjectPublicKeyInfo structure usable by OpenSSL.
*
* @param string $uncompressed 65-byte binary string beginning with 0x04.
* @return string PEM string (-----BEGIN PUBLIC KEY----- ...)
* @throws RuntimeException If input is not a valid uncompressed point.
*/
function wp_p256_uncompressed_to_pem ( string $uncompressed): string
{
if ( wp_safe_strlen ( $uncompressed) !== 65 || $uncompressed[0] !== "\x04")
{
throw new RuntimeException ( "Invalid uncompressed P-256 public key");
}
// ASN.1 DER for:
// SEQUENCE
// {
// SEQUENCE { OID 1.2.840.10045.2.1 (ecPublicKey), OID 1.2.840.10045.3.1.7 (prime256v1) }
// BIT STRING <uncompressed point>
// }
$derPrefix = hex2bin ( "3059") . // SEQUENCE, length 0x59 (89)
hex2bin ( "3013") . // SEQ, len 0x13
hex2bin ( "0607") . hex2bin ( "2A8648CE3D0201") . // ecPublicKey OID
hex2bin ( "0608") . hex2bin ( "2A8648CE3D030107") . // prime256v1 OID
hex2bin ( "0342") . "\x00"; // BIT STRING, len 0x42=66, leading 0 unused bits
$der = $derPrefix . $uncompressed;
return "-----BEGIN PUBLIC KEY-----" . PHP_EOL .
chunk_split ( base64_encode ( $der), 64, PHP_EOL) .
"-----END PUBLIC KEY-----" . PHP_EOL;
}
// HKDF (RFC 5869, SHA-256) helper
/**
* HMAC-based Extract-and-Expand Key Derivation Function (HKDF) using SHA-256.
* Simplified variant where only one output block (N=1) is required – suitable
* for Web Push CEK/nonce derivation.
*
* @param string $salt Non-secret random salt (16 bytes for WebPush)
* @param string $ikm Input key material (secret)
* @param string $info Context-specific info string
* @param int $length Desired output length in bytes (<= 32 for SHA-256)
* @return string Pseudo-random key of $length bytes
*/
function wp_hkdf ( string $salt, string $ikm, string $info, int $length): string
{
$prk = hash_hmac ( "sha256", $ikm, $salt, true); // extract
$t = hash_hmac ( "sha256", $info . "\x01", $prk, true); // expand, N=1
return substr ( $t, 0, $length);
}
// EC Private Key (raw scalar) to PEM (RFC 5915) helper
/**
* Build PEM EC PRIVATE KEY from raw 32-byte scalar and optional uncompressed pub
* key.
*
* @param string $d 32-byte private scalar
* @param string|null $public[optional] 65-byte uncompressed public key
* (04||X||Y). If null, it will be
* calculated by OpenSSL.
*/
function wp_p256_priv_to_pem ( string $d, ?string $public = null): string
{
if ( wp_safe_strlen ( $d) !== 32)
{
throw new RuntimeException ( "Invalid private scalar length");
}
if ( $public !== null && wp_safe_strlen ( $public) !== 65)
{
throw new RuntimeException ( "Invalid public key length");
}
// ASN.1 construct
$seq = "";
$seq .= "\x02\x01\x01"; // INTEGER 1
$seq .= "\x04\x20" . $d; // OCTET STRING (32 bytes)
// Append curve OID [0] explicit prime256v1
$curveOid = hex2bin ( "2A8648CE3D030107"); // 1.2.840.10045.3.1.7
$seq .= "\xA0" . chr ( strlen ( $curveOid) + 2) . "\x06" . chr ( strlen ( $curveOid)) . $curveOid;
// Append public key if provided
if ( $public !== null)
{
$bitstring = "\x00" . $public; // 0 unused bits
$seq .= "\xA1" . chr ( strlen ( $bitstring) + 2) . "\x03" . chr ( strlen ( $bitstring)) . $bitstring;
}
$der = "\x30" . chr ( strlen ( $seq)) . $seq;
return "-----BEGIN EC PRIVATE KEY-----" . PHP_EOL .
chunk_split ( base64_encode ( $der), 64, PHP_EOL) .
"-----END EC PRIVATE KEY-----" . PHP_EOL;
}
// VAPID ES256 JWT builder helpers
/**
* Build VAPID headers.
*
* @param string $endpoint The subscription endpoint (used for audience)
* @param string $subj mailto: or URL subject
* @param string $privScalarB64u private key (url-b64) 32-byte scalar
* @param string $pubKeyB64u public key (url-b64) uncompressed 65-byte
* @param int $ttl[optional] seconds validity (default 12h)
* @return array ["Authorization"=>..., "Crypto-Key"=>...]
*/
function wp_vapid_headers ( string $endpoint, string $subj, string $privScalarB64u, string $pubKeyB64u, int $ttl = 43200): array
{
$aud = parse_url ( $endpoint, PHP_URL_SCHEME) . "://" . parse_url ( $endpoint, PHP_URL_HOST) . ( parse_url ( $endpoint, PHP_URL_PORT) ? ":" . parse_url ( $endpoint, PHP_URL_PORT) : "");
$header = array (
"typ" => "JWT",
"alg" => "ES256"
);
$claims = array (
"aud" => $aud,
"exp" => time () + $ttl,
"sub" => $subj
);
$token = wp_jwt_es256 ( $header, $claims, $privScalarB64u, $pubKeyB64u);
return array (
"Authorization" => "WebPush " . $token,
"Crypto-Key" => "p256ecdsa=" . $pubKeyB64u
);
}
/**
* Produce a compact JWS (JWT) signed with ES-256 suitable for VAPID.
*
* @param array $header JOSE header (typ, alg, …)
* @param array $claims JWT claims (aud, exp, sub…)
* @param string $privScalarB64u 32-byte P-256 private scalar (base64url)
* @param string $pubKeyB64u 65-byte uncompressed public key (base64url)
* @return string Compact JWS string header.payload.signature
*/
function wp_jwt_es256 ( array $header, array $claims, string $privScalarB64u, string $pubKeyB64u): string
{
$signingInput = wp_base64url_encode ( json_encode ( $header)) . "." . wp_base64url_encode ( json_encode ( $claims));
$sig = "";
openssl_sign ( $signingInput, $sig, wp_p256_priv_to_pem ( wp_base64url_decode ( $privScalarB64u), wp_base64url_decode ( $pubKeyB64u)), OPENSSL_ALGO_SHA256);
// Convert DER ECDSA signature to raw R||S 64-byte per JWS spec §3.4
$rawSig = wp_ecdsa_der_to_raw ( $sig);
return $signingInput . "." . wp_base64url_encode ( $rawSig);
}
/**
* Convert an ASN.1-DER encoded ECDSA signature to the raw R||S format required
* by JWS (RFC 7515 §3.4).
*
* @param string $der DER encoded ECDSA signature (SEQUENCE(INTEGER r, INTEGER s))
* @return string 64-byte binary string: r (32) || s (32)
* @throws RuntimeException If the DER structure is invalid or sizes differ.
*/
function wp_ecdsa_der_to_raw ( string $der): string
{
$offset = 0;
if ( ord ( $der[$offset++]) !== 0x30)
{
throw new RuntimeException ( "Invalid DER");
}
_asn1_len ( $der, $offset); // just parse length, offset already advanced inside
if ( ord ( $der[$offset++]) !== 0x02)
{
throw new RuntimeException ( "Invalid DER");
}
$rLen = _asn1_len ( $der, $offset);
$r = substr ( $der, $offset, $rLen);
$offset += $rLen;
if ( ord ( $der[$offset++]) !== 0x02)
{
throw new RuntimeException ( "Invalid DER");
}
$sLen = _asn1_len ( $der, $offset);
$s = substr ( $der, $offset, $sLen);
$r = ltrim ( $r, "\x00");
$s = ltrim ( $s, "\x00");
return str_pad ( $r, 32, "\x00", STR_PAD_LEFT) . str_pad ( $s, 32, "\x00", STR_PAD_LEFT);
}
/**
* Internal: Read an ASN.1 DER length from $data starting at $off and advance
* the reference offset to the first content byte.
*
* @param string $data DER-encoded binary
* @param int &$off Offset passed by reference – will be updated
* @return int Parsed length value
*/
function _asn1_len ( string $data, int &$off): int
{
$len = ord ( $data[$off++]);
if ( $len & 0x80)
{
$n = $len & 0x7F;
$len = 0;
for ( $i = 0; $i < $n; $i++)
{
$len = ( $len << 8) | ord ( $data[$off++]);
}
}
return $len;
}
// ECDH + CEK/nonce derivation and encryption helper
/**
* Encrypt payload according to WebPush content encoding.
*
* @param string $payload Plaintext (already padded if caller wants custom padding length 0)
* @param string $userPublicB64u Subscription p256dh
* @param string $userAuthB64u Subscription auth secret
* @param string $encoding[optional] "aes128gcm" (default) or "aesgcm"
* @return array [cipher=>..., salt, localPublicKey]
*/
function wp_webpush_encrypt ( string $payload, string $userPublicB64u, string $userAuthB64u, string $encoding = "aes128gcm"): array
{
if ( ! in_array ( $encoding, array ( "aesgcm", "aes128gcm"), true))
{
throw new InvalidArgumentException("Unsupported encoding");
}
$salt = random_bytes ( 16);
// Generate local key pair
$res = openssl_pkey_new ( array ( "private_key_type" => OPENSSL_KEYTYPE_EC, "curve_name" => "prime256v1"));
openssl_pkey_export ( $res, $privPem);
$details = openssl_pkey_get_details ( $res);
$localPubUncompressed = "\x04" . $details["ec"]["x"] . $details["ec"]["y"];
$userPubRaw = wp_base64url_decode ( $userPublicB64u);
$userPubPem = wp_p256_uncompressed_to_pem ( $userPubRaw);
// Compute shared secret
if ( ! $shared = openssl_pkey_derive ( $userPubPem, $privPem, 256))
{
throw new RuntimeException ( "ECDH derive failed");
}
$userAuth = wp_base64url_decode ( $userAuthB64u);
// IKM
if ( $encoding === "aesgcm")
{
$ikm = wp_hkdf ( $userAuth, $shared, "Content-Encoding: auth" . "\x00", 32);
} else { // aes128gcm
$ikm = wp_hkdf ( $userAuth, $shared, "WebPush: info" . "\x00" . $userPubRaw . $localPubUncompressed, 32);
}
// Context (only aesgcm)
$context = null;
if ( $encoding === "aesgcm")
{
$context = "\x00\x00A" . $userPubRaw . "\x00A" . $localPubUncompressed; // simplistic (65=0x41 "A")
}
// Info for key and nonce
if ( $encoding === "aesgcm")
{
$info_key = "Content-Encoding: aesgcm" . "\0" . "P-256" . $context;
$info_nonce = "Content-Encoding: nonce" . "\0" . "P-256" . $context;
} else {
$info_key = "Content-Encoding: aes128gcm" . "\0";
$info_nonce = "Content-Encoding: nonce" . "\0";
}
$cek = wp_hkdf ( $salt, $ikm, $info_key, 16);
$nonce = wp_hkdf ( $salt, $ikm, $info_nonce, 12);
// Encrypt
$tag = "";
$cipher = openssl_encrypt ( $payload, "aes-128-gcm", $cek, OPENSSL_RAW_DATA, $nonce, $tag);
$cipherText = $cipher . $tag;
// For aes128gcm, prepend content coding header per RFC
if ( $encoding === "aes128gcm")
{
$hdr = $salt .
pack ( "N", 4096) .
pack ( "C", wp_safe_strlen ( $localPubUncompressed)) .
$localPubUncompressed;
$cipherText = $hdr . $cipherText;
}
return array (
"cipher" => $cipherText,
"salt" => $salt,
"localPublicKey" => $localPubUncompressed
);
}
// Payload padding helper
/**
* Apply Web Push mandatory padding rules.
*
* @param string $payload Original payload (JSON)
* @param int $maxLen Maximum padded length (Encryption::MAX_* constants)
* @param string $encoding "aesgcm" | "aes128gcm"
* @return string Padded plaintext ready for encryption
* @throws InvalidArgumentException When payload exceeds $maxLen
*/
function wp_pad_payload ( string $payload, int $maxLen, string $encoding): string
{
$padLen = $maxLen ? $maxLen - wp_safe_strlen ( $payload) : 0;
if ( $padLen < 0)
{
throw new InvalidArgumentException ( "Payload too large");
}
if ( $encoding === "aesgcm")
{
return pack ( "n", $padLen) . str_pad ( $payload, $padLen + wp_safe_strlen($payload), "\x00", STR_PAD_LEFT);
}
if ( $encoding === "aes128gcm")
{
return str_pad ( $payload . "\x02", $padLen + wp_safe_strlen ( $payload), "\x00", STR_PAD_RIGHT);
}
throw new InvalidArgumentException ( "Unsupported encoding");
}
// Header composer helper
/**
* Assemble the HTTP headers for a single Web Push request.
*
* For aes128gcm: only VAPID’s p256ecdsa parameter is sent in Crypto-Key.
* For aesgcm: Crypto-Key carries both dh (ephemeral) and p256ecdsa, plus an
* additional Encryption header with the salt.
*
* @param string $endpoint Subscription endpoint (unused but handy for future)
* @param string $salt 16-byte salt (binary)
* @param string $localPub 65-byte local public key (binary)
* @param string $vapidAuth "WebPush <jwt>" Authorization header value
* @param string $vapidCrypto "p256ecdsa=<b64u(pub)>" fragment
* @param string $encoding "aesgcm" | "aes128gcm"
* @param int $ttl[optional] Time-To-Live seconds (default 4 weeks)
* @return string[] Array of header strings ready for cURL
*/
function wp_build_headers ( string $endpoint, string $salt, string $localPub, string $vapidAuth, string $vapidCrypto, string $encoding, int $ttl = 2419200): array
{
$headers = array (
"TTL: " . $ttl,
"Content-Encoding: " . $encoding,
"Content-Type: application/octet-stream",
"Authorization: " . $vapidAuth
);
$dh = wp_base64url_encode ( $localPub);
$saltB64 = wp_base64url_encode ( $salt);
if ( $encoding === "aesgcm")
{
$headers[] = "Crypto-Key: dh=" . $dh . ";" . $vapidCrypto;
$headers[] = "Encryption: salt=" . $saltB64;
} else { // aes128gcm
$headers[] = "Crypto-Key: " . $vapidCrypto;
}
return $headers;
}
// Send WebPush via cURL helper
/**
* Sends WebPush notification using cURL.
*
* @param array $subscription subscription array
* @param string $payload JSON string
* @param string $vapidPriv path to private key file or key content
* @param string $vapidPub path to public key file or key content
* @param string $vapidSubject[optional] subject of VAPID contact (default
* "mailto:admin@example.com")
* @param string $encoding[optional] "aes128gcm" (default) or "aesgcm"
* @return bool true if success, false otherwise
*/
function wp_send_webpush ( array $subscription, string $payload, string $vapidPriv, string $vapidPub, string $vapidSubject = "mailto:admin@example.com", string $encoding = "aes128gcm"): bool
{
$endpoint = $subscription["endpoint"];
$userPublic = $subscription["keys"]["p256dh"];
$userAuth = $subscription["keys"]["auth"];
// Padding & encryption
$maxLen = ( $encoding === "aes128gcm") ? 2820 : 4078;
$padded = wp_pad_payload ( $payload, $maxLen, $encoding);
$enc = wp_webpush_encrypt ( $padded, $userPublic, $userAuth, $encoding);
// VAPID headers
if ( strpos ( "-----BEGIN", $vapidPriv) || ( preg_match ( "/^[a-zA-Z0-9\-]$/", $vapidPriv) && strlen ( $vapidPriv) == 43))
{
$priv = trim ( $vapidPriv);
} else {
if ( ! is_readable ( $vapidPriv))
{
throw new RuntimeException ( "Cannot read private key file \"" . $vapidPriv . "\".");
}
$priv = trim ( file_get_contents ( $vapidPriv));
}
if ( strpos ( "-----BEGIN", $vapidPub) || ( preg_match ( "/^[a-zA-Z0-9\-]$/", $vapidPub) && strlen ( $vapidPub) == 87))
{
$pub = trim ( $vapidPub);
} else {
if ( ! is_readable ( $vapidPub))
{
throw new RuntimeException ( "Cannot read public key file \"" . $vapidPub . "\".");
}
$pub = trim ( file_get_contents ( $vapidPub));
}
$vapid = wp_vapid_headers ( $endpoint, $vapidSubject, $priv, $pub);
$headers = wp_build_headers ( $endpoint, $enc["salt"], $enc["localPublicKey"], $vapid["Authorization"], $vapid["Crypto-Key"], $encoding);
$headers[] = "Content-Length: " . strlen ( $enc["cipher"]);
// Send
$ch = curl_init ( $endpoint);
curl_setopt_array ( $ch, array (
CURLOPT_POST => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2TLS,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $enc["cipher"],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15
));
$response = curl_exec ( $ch);
if ( $response === false)
{
throw new RuntimeException ( "cURL error: " . curl_error ( $ch));
}
$status = curl_getinfo ( $ch, CURLINFO_HTTP_CODE);
curl_close ( $ch);
echo "cURL result:\n";
echo "Status: " . $status . "\n";
echo "Content: " . ( $response ? $response : "<<EMPTY>>") . "\n";
echo "\n";
return $status == 201;
}
// If executing in CLI, send notification
if ( PHP_SAPI === "cli" && basename ( __FILE__) === basename ( $_SERVER["SCRIPT_FILENAME"]))
{
[$script, $subFile, $encoding] = $argv + [null, "subscription.json", "aes128gcm"];
if ( ! in_array ( $encoding, array ( "aes128gcm", "aesgcm"), true))
{
fwrite ( STDERR, "Encoding must be aes128gcm or aesgcm" . PHP_EOL);
exit ( 1);
}
if ( ! $sub = json_decode ( @file_get_contents ( $subFile), true))
{
fwrite ( STDERR, "Invalid subscription file" . PHP_EOL);
exit ( 1);
}
if ( is_readable ( "payload.json"))
{
$payload = file_get_contents ( "payload.json");
} else {
$payload = "{\"title\":\"Hello from PHP!\",\"body\":\"This is a web push notification.\",\"icon\":\"https:\/\/www.php.net\/favicon.ico\",\"data\":{\"url\":\"http:\/\/127.0.0.1:8000\/\"}}";
}
echo "Debug information:\n";
echo "\n";
echo "Endpoint: " . $sub["endpoint"] . "\n";
echo "Encoding: " . $encoding . "\n";
echo "\n";
if ( wp_send_webpush ( $sub, $payload, "vapid_private.key", "vapid_public.key", "mailto:azevedo@voipdomain.io", $encoding))
{
echo "✅ Message sent successfully.\n";
} else {
echo "❌ Message failed to send.\n";
}
}
?>