Repository navigation
Expand file tree
/
Copy pathWebAuthnService.php
More file actions
519 lines (451 loc) · 17.4 KB
/
Copy pathWebAuthnService.php
File metadata and controls
519 lines (451 loc) · 17.4 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
<?php
declare(strict_types=1);
namespace ZeroTrust\Crypto;
use RuntimeException;
use ZeroTrust\Core\Config;
use ZeroTrust\Core\Database;
use ZeroTrust\Storage\StorageFactory;
/**
* Pure-PHP WebAuthn / Passkeys implementation (no external libraries).
* Supports platform authenticators, ES256 (P-256), challenge replay protection,
* and AEAD-encrypted credential storage.
*/
final class WebAuthnService
{
private const CHALLENGE_TTL = 300;
/**
* @return array<string, mixed>
*/
public static function generateRegistrationOptions(string $userUuid, string $username): array
{
$challenge = random_bytes(32);
$challengeB64 = self::base64urlEncode($challenge);
StorageFactory::get()->set('webauthn:reg:' . $userUuid, $challengeB64, self::CHALLENGE_TTL);
$rpId = self::getRpId();
$rpName = Config::get('APP_NAME', 'zerotrust-php') ?? 'zerotrust-php';
return [
'challenge' => $challengeB64,
'rp' => ['name' => $rpName, 'id' => $rpId],
'user' => [
'id' => self::base64urlEncode($userUuid),
'name' => $username,
'displayName' => $username,
],
'pubKeyCredParams' => [
['type' => 'public-key', 'alg' => -7],
['type' => 'public-key', 'alg' => -257],
],
'authenticatorSelection' => [
'authenticatorAttachment' => 'platform',
'residentKey' => 'preferred',
'userVerification' => 'preferred',
],
'timeout' => 60000,
'attestation' => 'none',
];
}
/**
* @param array<string, mixed> $clientDataJSON
* @return array{success: bool, message: string, credential_id?: string}
*/
public static function verifyAndStoreRegistration(
string $userUuid,
array $clientDataJSON,
string $attestationObjectB64,
string $credentialIdB64
): array {
$storage = StorageFactory::get();
$expectedChallengeB64 = $storage->get('webauthn:reg:' . $userUuid);
if ($expectedChallengeB64 === null) {
return ['success' => false, 'message' => 'Registration challenge expired or missing.'];
}
$clientData = self::parseClientData($clientDataJSON);
if ($clientData === null || ($clientData['type'] ?? '') !== 'webauthn.create') {
return ['success' => false, 'message' => 'Invalid clientDataJSON.'];
}
if (!hash_equals($expectedChallengeB64, (string) ($clientData['challenge'] ?? ''))) {
return ['success' => false, 'message' => 'Challenge mismatch.'];
}
if (!self::isValidOrigin((string) ($clientData['origin'] ?? ''))) {
return ['success' => false, 'message' => 'Invalid origin.'];
}
$attestationObject = self::base64urlDecode($attestationObjectB64);
if ($attestationObject === null) {
return ['success' => false, 'message' => 'Invalid attestationObject.'];
}
$authData = self::extractAuthDataFromAttestation($attestationObject);
if ($authData === null) {
return ['success' => false, 'message' => 'Could not parse authenticator data.'];
}
$rpIdHash = hash('sha256', self::getRpId(), true);
if (!hash_equals($rpIdHash, substr($authData, 0, 32))) {
return ['success' => false, 'message' => 'rpIdHash mismatch.'];
}
$publicKeyPem = self::extractPublicKeyPem($authData);
if ($publicKeyPem === null) {
return ['success' => false, 'message' => 'Could not extract public key (COSE parse failed).'];
}
$credential = [
'id' => $credentialIdB64,
'publicKey' => $publicKeyPem,
'signCount' => self::extractSignCount($authData),
'created_at' => time(),
];
self::storeCredential($userUuid, $credential);
$storage->delete('webauthn:reg:' . $userUuid);
return [
'success' => true,
'message' => 'Passkey registered successfully.',
'credential_id' => $credentialIdB64,
];
}
/**
* @return array<string, mixed>
*/
public static function generateAuthenticationOptions(string $userUuid): array
{
$challenge = random_bytes(32);
$challengeB64 = self::base64urlEncode($challenge);
StorageFactory::get()->set('webauthn:auth:' . $userUuid, $challengeB64, self::CHALLENGE_TTL);
$credentials = self::loadCredentials($userUuid);
$allowCredentials = [];
foreach ($credentials as $cred) {
$allowCredentials[] = ['type' => 'public-key', 'id' => (string) ($cred['id'] ?? '')];
}
return [
'challenge' => $challengeB64,
'timeout' => 60000,
'rpId' => self::getRpId(),
'allowCredentials' => $allowCredentials,
'userVerification' => 'preferred',
];
}
/**
* @param array<string, mixed> $clientDataJSON
* @return array{success: bool, message: string}
*/
public static function verifyAssertion(
string $userUuid,
string $credentialIdB64,
array $clientDataJSON,
string $authenticatorDataB64,
string $signatureB64
): array {
$storage = StorageFactory::get();
$expectedChallengeB64 = $storage->get('webauthn:auth:' . $userUuid);
if ($expectedChallengeB64 === null) {
return ['success' => false, 'message' => 'Authentication challenge expired or missing.'];
}
$credentials = self::loadCredentials($userUuid);
$credential = null;
foreach ($credentials as $c) {
if (hash_equals((string) ($c['id'] ?? ''), $credentialIdB64)) {
$credential = $c;
break;
}
}
if ($credential === null) {
return ['success' => false, 'message' => 'Unknown credential.'];
}
$clientData = self::parseClientData($clientDataJSON);
if ($clientData === null || ($clientData['type'] ?? '') !== 'webauthn.get') {
return ['success' => false, 'message' => 'Invalid clientDataJSON.'];
}
if (!hash_equals($expectedChallengeB64, (string) ($clientData['challenge'] ?? ''))) {
return ['success' => false, 'message' => 'Challenge mismatch.'];
}
if (!self::isValidOrigin((string) ($clientData['origin'] ?? ''))) {
return ['success' => false, 'message' => 'Invalid origin.'];
}
$authData = self::base64urlDecode($authenticatorDataB64);
if ($authData === null || strlen($authData) < 37) {
return ['success' => false, 'message' => 'Invalid authenticatorData.'];
}
$rpIdHash = hash('sha256', self::getRpId(), true);
if (!hash_equals($rpIdHash, substr($authData, 0, 32))) {
return ['success' => false, 'message' => 'rpIdHash mismatch.'];
}
$flags = ord($authData[32]);
if (($flags & 0x01) === 0) {
return ['success' => false, 'message' => 'User presence flag not set.'];
}
$clientDataRaw = json_encode($clientDataJSON, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
$clientDataHash = hash('sha256', $clientDataRaw, true);
$signedData = $authData . $clientDataHash;
$signature = self::base64urlDecode($signatureB64);
if ($signature === null) {
return ['success' => false, 'message' => 'Invalid signature encoding.'];
}
$publicKey = openssl_pkey_get_public((string) ($credential['publicKey'] ?? ''));
if ($publicKey === false) {
return ['success' => false, 'message' => 'Invalid stored public key.'];
}
$verified = openssl_verify($signedData, $signature, $publicKey, OPENSSL_ALGO_SHA256);
if ($verified !== 1) {
return ['success' => false, 'message' => 'Signature verification failed.'];
}
$newSignCount = self::extractSignCount($authData);
if ($newSignCount > 0 && $newSignCount <= (int) ($credential['signCount'] ?? 0)) {
return ['success' => false, 'message' => 'Sign count regression detected.'];
}
$credential['signCount'] = $newSignCount;
self::updateCredential($userUuid, $credential);
$storage->delete('webauthn:auth:' . $userUuid);
return ['success' => true, 'message' => 'Passkey authentication successful.'];
}
// --------------- helpers ---------------
private static function getRpId(): string
{
$url = Config::get('APP_URL', 'http://localhost') ?? 'http://localhost';
$host = parse_url($url, PHP_URL_HOST);
return is_string($host) && $host !== '' ? $host : 'localhost';
}
private static function isValidOrigin(string $origin): bool
{
$expected = rtrim(Config::get('APP_URL', 'http://localhost') ?? 'http://localhost', '/');
return hash_equals($expected, rtrim($origin, '/'));
}
/**
* @param array<string, mixed>|string $clientDataJSON
* @return ?array<string, mixed>
*/
private static function parseClientData(array|string $clientDataJSON): ?array
{
if (is_string($clientDataJSON)) {
$decoded = json_decode($clientDataJSON, true);
return is_array($decoded) ? $decoded : null;
}
return $clientDataJSON;
}
private static function base64urlEncode(string $data): string
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
private static function base64urlDecode(string $data): ?string
{
$remainder = strlen($data) % 4;
if ($remainder > 0) {
$data .= str_repeat('=', 4 - $remainder);
}
$decoded = base64_decode(strtr($data, '-_', '+/'), true);
return $decoded === false ? null : $decoded;
}
private static function extractAuthDataFromAttestation(string $attestationObject): ?string
{
try {
$offset = 0;
$map = self::cborDecode($attestationObject, $offset);
if (!is_array($map) || !isset($map['authData']) || !is_string($map['authData'])) {
return null;
}
return $map['authData'];
} catch (\Throwable) {
return null;
}
}
private static function extractSignCount(string $authData): int
{
if (strlen($authData) < 37) {
return 0;
}
$count = unpack('N', substr($authData, 33, 4));
return is_array($count) ? (int) ($count[1] ?? 0) : 0;
}
private static function extractPublicKeyPem(string $authData): ?string
{
if (strlen($authData) < 37) {
return null;
}
$offset = 37;
$flags = ord($authData[32]);
if (($flags & 0x40) === 0) {
return null;
}
$offset += 16; // AAGUID
if ($offset + 2 > strlen($authData)) {
return null;
}
$unpackedLen = unpack('n', substr($authData, $offset, 2));
$credIdLen = is_array($unpackedLen) ? (int) ($unpackedLen[1] ?? 0) : 0;
$offset += 2 + $credIdLen;
$coseRaw = substr($authData, $offset);
if ($coseRaw === '') {
return null;
}
try {
$coseOffset = 0;
$coseKey = self::cborDecode($coseRaw, $coseOffset);
} catch (\Throwable) {
return null;
}
if (!is_array($coseKey)) {
return null;
}
$kty = $coseKey[1] ?? null;
if ($kty === 2) { // EC2
$crv = $coseKey[-1] ?? null;
$x = $coseKey[-2] ?? null;
$y = $coseKey[-3] ?? null;
if ($crv === 1 && is_string($x) && is_string($y) && strlen($x) === 32 && strlen($y) === 32) {
return self::ecPublicKeyToPem($x, $y);
}
}
return null;
}
private static function ecPublicKeyToPem(string $x, string $y): string
{
$point = "\x04" . $x . $y;
$oidEcPublicKey = (string) hex2bin('06072a8648ce3d0201');
$oidPrime256v1 = (string) hex2bin('06082a8648ce3d030107');
$algorithm = self::asn1Sequence($oidEcPublicKey . $oidPrime256v1);
$bitString = "\x03" . self::asn1Length(strlen($point) + 1) . "\x00" . $point;
$spki = self::asn1Sequence($algorithm . $bitString);
return "-----BEGIN PUBLIC KEY-----\n" .
chunk_split(base64_encode($spki), 64, "\n") .
"-----END PUBLIC KEY-----";
}
private static function asn1Length(int $length): string
{
if ($length < 0x80) {
return chr($length);
}
if ($length < 0x100) {
return "\x81" . chr($length);
}
return "\x82" . pack('n', $length);
}
private static function asn1Sequence(string $contents): string
{
return "\x30" . self::asn1Length(strlen($contents)) . $contents;
}
// Minimal CBOR decoder
private static function cborDecode(string $data, int &$offset = 0): mixed
{
if ($offset >= strlen($data)) {
throw new RuntimeException('CBOR: unexpected end');
}
$header = ord($data[$offset++]);
$major = $header >> 5;
$info = $header & 0x1F;
$value = self::cborReadLength($data, $offset, $info);
return match ($major) {
0 => $value,
1 => -1 - $value,
2, 3 => self::cborReadBytes($data, $offset, $value),
4 => self::cborReadArray($data, $offset, $value),
5 => self::cborReadMap($data, $offset, $value),
7 => match ($info) { 20 => false, 21 => true, 22, 23 => null, default => $value },
default => throw new RuntimeException("CBOR unsupported major $major"),
};
}
private static function cborReadLength(string $data, int &$offset, int $info): int
{
if ($info < 24) {
return $info;
}
if ($info === 24) {
return ord($data[$offset++]);
}
if ($info === 25) {
$u = unpack('n', substr($data, $offset, 2));
$offset += 2;
return is_array($u) ? (int) ($u[1] ?? 0) : 0;
}
if ($info === 26) {
$u = unpack('N', substr($data, $offset, 4));
$offset += 4;
return is_array($u) ? (int) ($u[1] ?? 0) : 0;
}
throw new RuntimeException('CBOR length too large');
}
private static function cborReadBytes(string $data, int &$offset, int $length): string
{
$bytes = substr($data, $offset, $length);
$offset += $length;
return $bytes;
}
/**
* @return list<mixed>
*/
private static function cborReadArray(string $data, int &$offset, int $count): array
{
$arr = [];
for ($i = 0; $i < $count; $i++) {
$arr[] = self::cborDecode($data, $offset);
}
return $arr;
}
/**
* @return array<int|string, mixed>
*/
private static function cborReadMap(string $data, int &$offset, int $count): array
{
$map = [];
for ($i = 0; $i < $count; $i++) {
$k = self::cborDecode($data, $offset);
$v = self::cborDecode($data, $offset);
if (is_int($k) || is_string($k)) {
$map[$k] = $v;
}
}
return $map;
}
/**
* @param array<string, mixed> $credential
*/
private static function storeCredential(string $userUuid, array $credential): void
{
$existing = self::loadCredentials($userUuid);
$existing[] = $credential;
self::saveCredentials($userUuid, $existing);
}
/**
* @param array<string, mixed> $updated
*/
private static function updateCredential(string $userUuid, array $updated): void
{
$existing = self::loadCredentials($userUuid);
foreach ($existing as &$cred) {
if (hash_equals((string) ($cred['id'] ?? ''), (string) ($updated['id'] ?? ''))) {
$cred = $updated;
break;
}
}
self::saveCredentials($userUuid, $existing);
}
/**
* @return list<array<string, mixed>>
*/
private static function loadCredentials(string $userUuid): array
{
$pdo = Database::connection();
$stmt = $pdo->prepare('SELECT webauthn_credentials_encrypted FROM users WHERE uuid = :uuid LIMIT 1');
$stmt->execute([':uuid' => $userUuid]);
$row = $stmt->fetch();
if ($row === false || empty($row['webauthn_credentials_encrypted'])) {
return [];
}
try {
$json = CryptoEngine::decrypt(
(string) $row['webauthn_credentials_encrypted'],
$userUuid . '|webauthn',
'user-mfa'
);
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
return is_array($data) ? array_values($data) : [];
} catch (\Throwable) {
return [];
}
}
/**
* @param list<array<string, mixed>> $credentials
*/
private static function saveCredentials(string $userUuid, array $credentials): void
{
$pdo = Database::connection();
$json = json_encode($credentials, JSON_THROW_ON_ERROR);
$encrypted = CryptoEngine::encrypt($json, $userUuid . '|webauthn', 'user-mfa');
$stmt = $pdo->prepare('UPDATE users SET webauthn_credentials_encrypted = :cred WHERE uuid = :uuid');
$stmt->execute([':cred' => $encrypted, ':uuid' => $userUuid]);
}
}