forked from webauthn-open-source/fido2-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.js
641 lines (495 loc) · 18.5 KB
/
validator.js
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/* eslint-disable no-invalid-this */
// validators are a mixin, so it's okay that we're using 'this' all over the place
"use strict";
var crypto = require("crypto");
var { URL } = require("url");
var {
printHex,
isBase64Url,
checkOrigin,
bufEqual,
isPem,
isPositiveInteger,
coerceToBase64Url
} = require("./utils");
var Fido2Lib;
async function validateExpectations() {
/* eslint complexity: ["off"] */
var req = this.requiredExpectations;
var exp = this.expectations;
if (!(exp instanceof Map)) {
throw new Error("expectations should be of type Map");
}
if (Array.isArray(req)) {
req = new Set([req]);
}
if (!(req instanceof Set)) {
throw new Error("requiredExpectaions should be of type Set");
}
for (let field of req) {
if (!exp.has(field)) {
throw new Error(`expectation did not contain value for '${field}'`);
}
}
if (req.size !== exp.size) {
throw new Error(`wrong number of expectations: should have ${req.size} but got ${exp.size}`);
}
// origin - isValid
if (req.has("origin")) {
var expectedOrigin = exp.get("origin");
checkOrigin(expectedOrigin);
}
// challenge - is valid base64url string
if (exp.has("challenge")) {
var challenge = exp.get("challenge");
if (typeof challenge !== "string") {
throw new Error("expected challenge should be of type String, got: " + typeof challenge);
}
if (!isBase64Url(challenge)) {
throw new Error("expected challenge should be properly encoded base64url String");
}
}
// flags - is Array or Set
if (req.has("flags")) {
var validFlags = new Set(["UP", "UV", "UP-or-UV", "AT", "ED"]);
var flags = exp.get("flags");
for (let flag of flags) {
if (!validFlags.has(flag)) {
throw new Error(`expected flag unknown: ${flag}`);
}
}
}
// prevCounter
if (req.has("prevCounter")) {
var prevCounter = exp.get("prevCounter");
if (!isPositiveInteger(prevCounter)) {
throw new Error("expected counter to be positive integer");
}
}
// publicKey
if (req.has("publicKey")) {
var publicKey = exp.get("publicKey");
if (!isPem(publicKey)) {
throw new Error("expected publicKey to be in PEM format");
}
}
// userHandle
if (req.has("userHandle")) {
var userHandle = exp.get("userHandle");
if (userHandle !== null &&
typeof userHandle !== "string") {
throw new Error("expected userHandle to be null or string");
}
}
this.audit.validExpectations = true;
return true;
}
function validateCreateRequest() {
var req = this.request;
if (typeof req !== "object") {
throw new TypeError("expected request to be Object, got " + typeof req);
}
if (!(req.rawId instanceof ArrayBuffer) &&
!(req.id instanceof ArrayBuffer)) {
throw new TypeError("expected 'id' or 'rawId' field of request to be ArrayBuffer, got rawId " + typeof req.rawId + " and id " + typeof req.id);
}
if (typeof req.response !== "object") {
throw new TypeError("expected 'response' field of request to be Object, got " + typeof req.response);
}
if (typeof req.response.attestationObject !== "string" &&
!(req.response.attestationObject instanceof ArrayBuffer)) {
throw new TypeError("expected 'response.attestationObject' to be base64 String or ArrayBuffer");
}
if (typeof req.response.clientDataJSON !== "string" &&
!(req.response.clientDataJSON instanceof ArrayBuffer)) {
throw new TypeError("expected 'response.clientDataJSON' to be base64 String or ArrayBuffer");
}
this.audit.validRequest = true;
return true;
}
function validateAssertionResponse() {
var req = this.request;
if (typeof req !== "object") {
throw new TypeError("expected request to be Object, got " + typeof req);
}
if (!(req.rawId instanceof ArrayBuffer) &&
!(req.id instanceof ArrayBuffer)) {
throw new TypeError("expected 'id' or 'rawId' field of request to be ArrayBuffer, got rawId " + typeof req.rawId + " and id " + typeof req.id);
}
if (typeof req.response !== "object") {
throw new TypeError("expected 'response' field of request to be Object, got " + typeof req.response);
}
if (typeof req.response.clientDataJSON !== "string" &&
!(req.response.clientDataJSON instanceof ArrayBuffer)) {
throw new TypeError("expected 'response.clientDataJSON' to be base64 String or ArrayBuffer");
}
if (typeof req.response.authenticatorData !== "string" &&
!(req.response.authenticatorData instanceof ArrayBuffer)) {
throw new TypeError("expected 'response.authenticatorData' to be base64 String or ArrayBuffer");
}
if (typeof req.response.signature !== "string" &&
!(req.response.signature instanceof ArrayBuffer)) {
throw new TypeError("expected 'response.signature' to be base64 String or ArrayBuffer");
}
if (typeof req.response.userHandle !== "string" &&
!(req.response.userHandle instanceof ArrayBuffer) &&
req.response.userHandle !== undefined) {
throw new TypeError("expected 'response.userHandle' to be base64 String, ArrayBuffer, or undefined");
}
this.audit.validRequest = true;
return true;
}
async function validateRawClientDataJson() {
// XXX: this isn't very useful, since this has already been parsed...
var rawClientDataJson = this.clientData.get("rawClientDataJson");
if (!(rawClientDataJson instanceof ArrayBuffer)) {
throw new Error("clientData clientDataJson should be ArrayBuffer");
}
this.audit.journal.add("rawClientDataJson");
return true;
}
async function validateId() {
var rawId = this.clientData.get("rawId");
if (!(rawId instanceof ArrayBuffer)) {
throw new Error("expected id to be of type ArrayBuffer");
}
var credId = this.authnrData.get("credId");
if (credId !== undefined && !bufEqual(rawId, credId)) {
throw new Error("id and credId were not the same");
}
this.audit.journal.add("rawId");
return true;
}
async function validateOrigin() {
var expectedOrigin = this.expectations.get("origin");
var clientDataOrigin = this.clientData.get("origin");
var origin = checkOrigin(clientDataOrigin);
if (origin !== expectedOrigin) {
throw new Error("clientData origin did not match expected origin");
}
this.audit.journal.add("origin");
return true;
}
async function validateCreateType() {
var type = this.clientData.get("type");
if (type !== "webauthn.create") {
throw new Error("clientData type should be 'webauthn.create', got: " + type);
}
this.audit.journal.add("type");
return true;
}
async function validateGetType() {
var type = this.clientData.get("type");
if (type !== "webauthn.get") {
throw new Error("clientData type should be 'webauthn.get'");
}
this.audit.journal.add("type");
return true;
}
async function validateChallenge() {
var expectedChallenge = this.expectations.get("challenge");
var challenge = this.clientData.get("challenge");
if (typeof challenge !== "string") {
throw new Error("clientData challenge was not a string");
}
if (!isBase64Url(challenge)) {
throw new TypeError("clientData challenge was not properly encoded base64url");
}
challenge = challenge.replace(/={1,2}$/, "");
// console.log("challenge", challenge);
// console.log("expectedChallenge", expectedChallenge);
if (challenge !== expectedChallenge) {
throw new Error("clientData challenge mismatch");
}
this.audit.journal.add("challenge");
return true;
}
async function validateTokenBinding() {
// TODO: node.js can't support token binding right now :(
var tokenBinding = this.clientData.get("tokenBinding");
if (typeof tokenBinding === "object") {
if (tokenBinding.status !== "not-supported" &&
tokenBinding.status !== "supported") {
throw new Error("tokenBinding status should be 'not-supported' or 'supported', got: " + tokenBinding.status);
}
if (Object.keys(tokenBinding).length != 1) {
throw new Error("tokenBinding had too many keys");
}
} else if (tokenBinding !== undefined) {
throw new Error("Token binding field malformed: " + tokenBinding);
}
// TODO: add audit.info for token binding status so that it can be used for policies, risk, etc.
this.audit.journal.add("tokenBinding");
return true;
}
async function validateRawAuthnrData() {
// XXX: this isn't very useful, since this has already been parsed...
var rawAuthnrData = this.authnrData.get("rawAuthnrData");
if (!(rawAuthnrData instanceof ArrayBuffer)) {
throw new Error("authnrData rawAuthnrData should be ArrayBuffer");
}
this.audit.journal.add("rawAuthnrData");
return true;
}
async function validateAttestation() {
// have to require here to prevent circular dependency
if (!Fido2Lib) Fido2Lib = require("../index").Fido2Lib; // eslint-disable-line global-require
return Fido2Lib.validateAttestation.call(this);
}
async function validateAssertionSignature() {
var expectedSignature = this.authnrData.get("sig");
var publicKey = this.expectations.get("publicKey");
var rawAuthnrData = this.authnrData.get("rawAuthnrData");
var rawClientData = this.clientData.get("rawClientDataJson");
// console.log("publicKey", publicKey);
// printHex("expectedSignature", expectedSignature);
// printHex("rawAuthnrData", rawAuthnrData);
// printHex("rawClientData", rawClientData);
const hash = crypto.createHash("SHA256");
hash.update(abToBuf(rawClientData));
var clientDataHashBuf = hash.digest();
var clientDataHash = new Uint8Array(clientDataHashBuf).buffer;
// printHex("clientDataHash", clientDataHash);
const verify = crypto.createVerify("SHA256");
verify.write(abToBuf(rawAuthnrData));
verify.write(abToBuf(clientDataHash));
verify.end();
var res = verify.verify(publicKey, abToBuf(expectedSignature));
if (!res) {
throw new Error("signature validation failed");
}
this.audit.journal.add("sig");
return true;
}
function abToBuf(ab) {
return Buffer.from(new Uint8Array(ab));
}
async function validateRpIdHash() {
var rpIdHash = this.authnrData.get("rpIdHash");
if (rpIdHash instanceof Buffer) {
rpIdHash = new Uint8Array(rpIdHash).buffer;
}
if (!(rpIdHash instanceof ArrayBuffer)) {
throw new Error("couldn't coerce clientData rpIdHash to ArrayBuffer");
}
var domain = new URL(this.clientData.get("origin")).hostname;
var createdHash = new Uint8Array(crypto.createHash("sha256").update(domain).digest()).buffer;
// wouldn't it be weird if two SHA256 hashes were different lengths...?
if (rpIdHash.byteLength !== createdHash.byteLength) {
throw new Error("authnrData rpIdHash length mismatch");
}
rpIdHash = new Uint8Array(rpIdHash);
createdHash = new Uint8Array(createdHash);
for (let i = 0; i < rpIdHash.byteLength; i++) {
if (rpIdHash[i] !== createdHash[i]) {
throw new TypeError("authnrData rpIdHash mismatch");
}
}
this.audit.journal.add("rpIdHash");
return true;
}
async function validateFlags() {
var expectedFlags = this.expectations.get("flags");
var flags = this.authnrData.get("flags");
for (let expFlag of expectedFlags) {
if (expFlag === "UP-or-UV") {
if (flags.has("UP") || flags.has("UV")) {
continue;
} else {
throw new Error("expected User Presence (UP) or User Verification (UV) flag to be set and neither was");
}
}
if (!flags.has(expFlag)) {
throw new Error(`expected flag was not set: ${expFlag}`);
}
}
this.audit.journal.add("flags");
return true;
}
async function validateInitialCounter() {
var counter = this.authnrData.get("counter");
// TODO: does counter need to be zero initially? probably not... I guess..
if (typeof counter !== "number") {
throw new Error("authnrData counter wasn't a number");
}
this.audit.journal.add("counter");
return true;
}
async function validateAaguid() {
var aaguid = this.authnrData.get("aaguid");
if (!(aaguid instanceof ArrayBuffer)) {
throw new Error("authnrData AAGUID is not ArrayBuffer");
}
if (aaguid.byteLength !== 16) {
throw new Error("authnrData AAGUID was wrong length");
}
this.audit.journal.add("aaguid");
return true;
}
async function validateCredId() {
var credId = this.authnrData.get("credId");
var credIdLen = this.authnrData.get("credIdLen");
if (!(credId instanceof ArrayBuffer)) {
throw new Error("authnrData credId should be ArrayBuffer");
}
if (typeof credIdLen !== "number") {
throw new Error("authnrData credIdLen should be number, got " + typeof credIdLen);
}
if (credId.byteLength !== credIdLen) {
throw new Error("authnrData credId was wrong length");
}
this.audit.journal.add("credId");
this.audit.journal.add("credIdLen");
return true;
}
async function validatePublicKey() {
// XXX: the parser has already turned this into PEM at this point
// if something were malformatted or wrong, we probably would have
// thrown an error well before this.
// Maybe we parse the ASN.1 and make sure attributes are correct?
// Doesn't seem very worthwhile...
var cbor = this.authnrData.get("credentialPublicKeyCose");
var jwk = this.authnrData.get("credentialPublicKeyJwk");
var pem = this.authnrData.get("credentialPublicKeyPem");
// cbor
if (!(cbor instanceof ArrayBuffer)) {
throw new Error("authnrData credentialPublicKeyCose isn't of type ArrayBuffer");
}
this.audit.journal.add("credentialPublicKeyCose");
// jwk
if (typeof jwk !== "object") {
throw new Error("authnrData credentialPublicKeyJwk isn't of type Object");
}
if (typeof jwk.kty !== "string") {
throw new Error("authnrData credentialPublicKeyJwk.kty isn't of type String");
}
if (typeof jwk.alg !== "string") {
throw new Error("authnrData credentialPublicKeyJwk.alg isn't of type String");
}
switch (jwk.kty) {
case "EC":
if (typeof jwk.crv !== "string") {
throw new Error("authnrData credentialPublicKeyJwk.crv isn't of type String");
}
break;
case "RSA":
if (typeof jwk.n !== "string") {
throw new Error("authnrData credentialPublicKeyJwk.n isn't of type String");
}
if (typeof jwk.e !== "string") {
throw new Error("authnrData credentialPublicKeyJwk.e isn't of type String");
}
break;
default:
throw new Error("authnrData unknown JWK key type: " + jwk.kty);
}
this.audit.journal.add("credentialPublicKeyJwk");
// pem
if (typeof pem !== "string") {
throw new Error("authnrData credentialPublicKeyPem isn't of type String");
}
if (!isPem(pem)) {
throw new Error("authnrData credentialPublicKeyPem was malformatted");
}
this.audit.journal.add("credentialPublicKeyPem");
return true;
}
async function validateUserHandle() {
var userHandle = this.authnrData.get("userHandle");
if (userHandle === undefined ||
userHandle === null ||
userHandle === "") {
this.audit.journal.add("userHandle");
return true;
}
userHandle = coerceToBase64Url(userHandle, "userHandle");
var expUserHandle = this.expectations.get("userHandle");
if (typeof userHandle === "string" &&
userHandle === expUserHandle) {
this.audit.journal.add("userHandle");
return true;
}
throw new Error("unable to validate userHandle");
}
async function validateCounter() {
var prevCounter = this.expectations.get("prevCounter");
var counter = this.authnrData.get("counter");
console.log('FIDO COUNTER', counter);
console.log('FIDO PREVCOUNTER', prevCounter);
if (counter !== 0 && prevCounter !== 0 && counter <= prevCounter) {
throw new Error("counter rollback detected");
}
this.audit.journal.add("counter");
return true;
}
async function validateAudit() {
var journal = this.audit.journal;
var clientData = this.clientData;
var authnrData = this.authnrData;
for (let kv of clientData) {
let val = kv[0];
if (!journal.has(val)) {
throw new Error(`internal audit failed: ${val} was not validated`);
}
}
for (let kv of authnrData) {
let val = kv[0];
if (!journal.has(val)) {
throw new Error(`internal audit failed: ${val} was not validated`);
}
}
if (journal.size !== (clientData.size + authnrData.size)) {
throw new Error(`internal audit failed: ${journal.size} fields checked; expected ${clientData.size + authnrData.size}`);
}
if (!this.audit.validExpectations) {
throw new Error("internal audit failed: expectations not validated");
}
if (!this.audit.validRequest) {
throw new Error("internal audit failed: request not validated");
}
this.audit.complete = true;
return true;
}
function attach(o) {
var mixins = {
validateExpectations,
validateCreateRequest,
// clientData validators
validateRawClientDataJson,
validateOrigin,
validateId,
validateCreateType,
validateGetType,
validateChallenge,
validateTokenBinding,
// authnrData validators
validateRawAuthnrData,
validateAttestation,
validateAssertionSignature,
validateRpIdHash,
validateAaguid,
validateCredId,
validatePublicKey,
validateFlags,
validateUserHandle,
validateCounter,
validateInitialCounter,
validateAssertionResponse,
// audit structures
audit: {
validExpectations: false,
validRequest: false,
complete: false,
journal: new Set(),
warning: new Map(),
info: new Map()
},
validateAudit
};
for (let key of Object.keys(mixins)) {
o[key] = mixins[key];
}
}
module.exports = {
attach
};