-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
725 lines (677 loc) · 36.4 KB
/
Copy pathProgram.cs
File metadata and controls
725 lines (677 loc) · 36.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
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using DarksFIDO2.Core;
using DarksFIDO2.Core.Interop;
using DarksFIDO2.Core.Passkeys;
using DarksFIDO2.Core.Security;
using DarksFIDO2.Core.Storage;
bool requireTpm = args.Contains("--require-tpm", StringComparer.OrdinalIgnoreCase);
var tests = new List<(string Name, Action Test)>
{
("RFC 6238 SHA-1 vector", TestTotp),
("Custom TOTP interval", TestTotpInterval),
("TPM detection", () => TestTpmDetection(requireTpm)),
("AES-GCM + HMAC tamper detection", TestVaultCrypto),
("Profile PIN + keyfile isolation and recovery", TestProfiles),
("Failure-safe keyfile rotation", TestKeyfileRotation),
("Transactional profile deletion", TestProfileDeletion),
("Profile-owned key cleanup", TestProfileOwnedKeyCleanup),
("Password-encrypted backup integrity", TestBackup),
("ECDSA signed audit export", TestAudit),
("Audit private key zeroed on lock", TestAuditKeyZeroing)
,("CTAP CBOR canonical round trip", TestCtapCbor)
,("Virtual passkey lifecycle", () => TestSoftwarePasskey(requireTpm))
,("Pending passkey confirmation and rejection cleanup", TestPendingPasskeyLifecycle)
,("Virtual passkey active-profile binding", TestPasskeyProfileBinding)
,("CTAP parser resource limits", TestCtapLimits)
,("WebAuthn RP, credential, flags, signature, and counter validation", TestWebAuthnOutputValidation)
,("Backup envelope work-factor limits", TestBackupLimits)
,("Tampered profile work-factor rejection", TestMetadataLimits)
,("Stale provider context cleanup", TestStaleProviderContext)
,("TOTP input limits", TestTotpLimits)
,("Audit CSV formula neutralization", TestAuditCsvInjection)
,("TPM key namespace and public key constraints", TestTpmNamespaceAndKeyValidation)
};
int failures = 0;
foreach ((string name, Action test) in tests)
{
try { test(); Console.WriteLine("PASS " + name); }
catch (Exception ex) { failures++; Console.Error.WriteLine("FAIL " + name + " — " + ex.Message); }
}
Console.WriteLine($"{tests.Count - failures}/{tests.Count} tests passed");
return failures == 0 ? 0 : 1;
static void TestTotp()
{
// RFC 6238 Appendix B: secret "12345678901234567890", T=59 => 94287082.
var entry = new TotpEntry { SecretBase32 = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", Digits = 8, Period = 30, Algorithm = "SHA1" };
string code = TotpService.GetCode(entry, DateTimeOffset.FromUnixTimeSeconds(59)).Code;
Assert(code == "94287082", "Unexpected RFC vector: " + code);
}
static void TestTotpInterval()
{
var entry = new TotpEntry { SecretBase32 = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", Digits = 6, Period = 60, Algorithm = "SHA1" };
TotpCode code = TotpService.GetCode(entry, DateTimeOffset.FromUnixTimeSeconds(59));
Assert(code.SecondsRemaining == 1, "The configured 60-second interval was not honored.");
Assert(code.Progress < 0.02, "The interval progress value is incorrect.");
}
static void TestTpmDetection(bool requireTpm)
{
var service = new TpmService();
var timer = Stopwatch.StartNew();
TpmStatus status = service.RefreshStatus();
timer.Stop();
Assert(timer.Elapsed < TimeSpan.FromSeconds(2), $"TPM detection blocked for {timer.ElapsedMilliseconds} ms.");
Assert(Enum.IsDefined(status.Mode), "TPM detection returned an invalid mode.");
if (requireTpm)
Assert(status.Mode == TpmMode.Tpm20, $"Expected this computer's TPM 2.0, detected {status.Version}: {status.Detail}");
Console.WriteLine($" TPM {status.Version} ({status.Manufacturer}) detected in {timer.ElapsedMilliseconds} ms");
}
static void TestVaultCrypto()
{
byte[] key = VaultCryptography.GenerateMasterKey();
try
{
Guid profileId = Guid.NewGuid();
var data = new VaultData { ProfileId = profileId, ProfileName = "Test" };
byte[] envelope = VaultCryptography.EncryptVault(data, key);
VaultEnvelope current = JsonSerializer.Deserialize<VaultEnvelope>(envelope, VaultCryptography.JsonOptions)
?? throw new InvalidOperationException("Vault envelope was not created.");
Assert(current.Magic == "DFV2", "New vault encryption did not use the profile-bound DFV2 format.");
VaultData roundTrip = VaultCryptography.DecryptVault(envelope, key, profileId);
Assert(roundTrip.ProfileName == "Test", "Round trip changed the payload.");
AssertThrows<CryptographicException>(() => VaultCryptography.DecryptVault(envelope, key, Guid.NewGuid()),
"A vault decrypted under the wrong profile identifier.");
current.Magic = "DFV9";
byte[] changedMagic = JsonSerializer.SerializeToUtf8Bytes(current, VaultCryptography.JsonOptions);
bool integrityCheckedFirst = false;
try { _ = VaultCryptography.DecryptVault(changedMagic, key, profileId); }
catch (CryptographicException ex) { integrityCheckedFirst = ex.Message.Contains("integrity", StringComparison.OrdinalIgnoreCase); }
Assert(integrityCheckedFirst, "The unauthenticated format marker was interpreted before the integrity check.");
byte[] tampered = envelope.ToArray();
tampered[tampered.Length / 2] ^= 1;
bool stopped = false;
try { _ = VaultCryptography.DecryptVault(tampered, key, profileId); } catch { stopped = true; }
Assert(stopped, "Tampered envelope was accepted.");
byte[] legacy = CreateLegacyVaultEnvelope(data, key);
VaultData migrated = VaultCryptography.DecryptVault(legacy, key, profileId);
Assert(migrated.ProfileId == profileId, "A valid legacy DFV1 vault could not be migrated.");
CryptographicOperations.ZeroMemory(changedMagic);
CryptographicOperations.ZeroMemory(tampered);
CryptographicOperations.ZeroMemory(legacy);
}
finally { CryptographicOperations.ZeroMemory(key); }
}
static void TestProfiles()
{
string root = TempDirectory();
byte[] keyfile = VaultCryptography.GenerateKeyfile();
var repo = new VaultRepository(new AppPaths(root), useTpm: false);
try
{
using (UnlockedProfile created = repo.CreateProfile(new ProfileCreationRequest("Personal", "Correct-Horse-7", keyfile, "R3C0V3RY-CODE-123")))
{
created.Data.TotpEntries.Add(new TotpEntry { Issuer = "Test", Account = "me", SecretBase32 = "GEZDGNBVGY3TQOJQ" });
repo.Save(created);
}
ProfileSummary summary = repo.LoadIndex().Profiles.Single();
bool wrongStopped = false;
try { using var _ = repo.Unlock(summary.Id, "wrong-pin", keyfile); } catch (CryptographicException) { wrongStopped = true; }
Assert(wrongStopped, "Wrong PIN unlocked the vault.");
byte[] wrongFile = RandomNumberGenerator.GetBytes(64);
bool fileStopped = false;
try { using var _ = repo.Unlock(summary.Id, "Correct-Horse-7", wrongFile); } catch (CryptographicException) { fileStopped = true; }
Assert(fileStopped, "Wrong keyfile unlocked the vault.");
using (UnlockedProfile opened = repo.Unlock(summary.Id, "Correct-Horse-7", keyfile)) Assert(opened.Data.TotpEntries.Count == 1, "Encrypted data was not restored.");
using (UnlockedProfile recovered = repo.UnlockWithRecovery(summary.Id, "Correct-Horse-7", "R3C0V3RY-CODE-123")) Assert(recovered.Data.ProfileName == "Personal", "Recovery unlock failed.");
using (UnlockedProfile opened = repo.Unlock(summary.Id, "Correct-Horse-7", keyfile))
AssertThrows<CryptographicException>(() => repo.ChangePin(opened, "A-New-Secure-Passphrase", null), "A keyfile profile accepted a PIN change without its keyfile.");
// Verify min 6-char PIN requirement
AssertThrows<ArgumentException>(() => repo.CreateProfile(new ProfileCreationRequest("ShortPin", "12345", null, null)), "Profile accepted < 6 character PIN.");
using (UnlockedProfile sixChar = repo.CreateProfile(new ProfileCreationRequest("SixChar", "123456", null, null)))
{
Assert(sixChar.Metadata.Name == "SixChar", "6-character PIN profile creation failed.");
}
// Verify dynamic index discovery from disk
File.Delete(repo.Paths.IndexPath);
ProfileIndex recoveredIndex = repo.LoadIndex();
Assert(recoveredIndex.Profiles.Any(p => p.Name == "Personal") && recoveredIndex.Profiles.Any(p => p.Name == "SixChar"), "Index dynamic discovery failed to recover profiles from disk.");
}
finally
{
CryptographicOperations.ZeroMemory(keyfile);
Directory.Delete(root, true);
}
}
static void TestProfileDeletion()
{
string root = TempDirectory();
var repo = new VaultRepository(new AppPaths(root), useTpm: false);
try
{
UnlockedProfile profile = repo.CreateProfile(new ProfileCreationRequest("Delete me", "Delete-Profile-7", null, null));
Guid id = profile.Metadata.Id;
string profileDirectory = repo.Paths.ProfileDirectory(id);
bool cleanupCalled = false;
repo.Delete(profile, "Delete me", _ => cleanupCalled = true);
Assert(cleanupCalled, "Profile deletion skipped the required owned-key cleanup phase.");
Assert(profile.IsDisposed, "Deleted profile key material remained unlocked.");
Assert(!Directory.Exists(profileDirectory), "Deleted profile files remained in the active profile directory.");
ProfileIndex index = repo.LoadIndex();
Assert(index.Profiles.Count == 0 && index.LastProfileId is null, "The deleted profile remained in the profile index.");
}
finally { Directory.Delete(root, true); }
}
static void TestKeyfileRotation()
{
string root = TempDirectory();
string currentPath = Path.Combine(root, "current.dfkey");
string nextPath = Path.Combine(root, "next.dfkey");
byte[] current = VaultCryptography.GenerateKeyfile();
byte[] next = VaultCryptography.GenerateKeyfile();
try
{
SecureFile.AtomicWrite(currentPath, current);
AssertThrows<InvalidOperationException>(
() => KeyfileRotationService.WriteThenCommit(nextPath, next, () => throw new InvalidOperationException("simulated vault write failure")),
"A simulated vault failure was not surfaced.");
Assert(File.Exists(currentPath) && CryptographicOperations.FixedTimeEquals(File.ReadAllBytes(currentPath), current),
"The current keyfile changed after a failed rotation.");
Assert(!File.Exists(nextPath), "An uncommitted replacement keyfile remained after rollback.");
KeyfileRotationService.WriteThenCommit(nextPath, next,
() => Assert(File.Exists(nextPath), "The replacement keyfile was not durable before the vault policy commit."));
Assert(CryptographicOperations.FixedTimeEquals(File.ReadAllBytes(nextPath), next), "The committed replacement keyfile changed.");
}
finally
{
CryptographicOperations.ZeroMemory(current);
CryptographicOperations.ZeroMemory(next);
Directory.Delete(root, true);
}
}
static void TestProfileOwnedKeyCleanup()
{
string root = TempDirectory();
var store = new SoftwarePasskeyStore(root);
Guid targetId = Guid.NewGuid();
Guid otherId = Guid.NewGuid();
SoftwarePasskeyCredential target = store.Create("target.example", "Target", RandomNumberGenerator.GetBytes(16), "target", "Target", targetId);
SoftwarePasskeyCredential other = store.Create("other.example", "Other", RandomNumberGenerator.GetBytes(16), "other", "Other", otherId);
var profile = new UnlockedProfile(
new ProfileMetadata { Id = targetId, Name = "Cleanup test" },
new VaultData { ProfileId = targetId, ProfileName = "Cleanup test" },
RandomNumberGenerator.GetBytes(32));
profile.Data.TpmKeys.Add(new TpmKeyRecord { Name = "Profile key", ProviderKeyName = $"DarksFIDO2.Key.{Guid.NewGuid():N}" });
profile.Data.FidoKeys.Add(new FidoKeyRecord { Name = "Platform key", Type = "Platform / Windows Hello", AuthenticatorId = "Windows", CredentialId = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)) });
var metadataRemoved = new List<string>();
var platformRemoved = new List<string>();
var tpmRemoved = new List<string>();
try
{
var cleanup = new ProfileDeletionService(
store,
credential => metadataRemoved.Add(Convert.ToHexString(credential.CredentialId)),
credential => platformRemoved.Add(credential.Name),
name => tpmRemoved.Add(name));
cleanup.DeleteOwnedKeys(profile);
Assert(metadataRemoved.Count == 1 && metadataRemoved[0] == Convert.ToHexString(target.CredentialId), "Provider metadata cleanup crossed a profile boundary.");
Assert(platformRemoved.SequenceEqual(["Platform key"]), "The profile platform credential was not removed.");
Assert(tpmRemoved.Count == 1, "The profile TPM key was not removed.");
Assert(store.List().Count == 1 && store.Find(otherId, other.CredentialId) is not null, "Provider cleanup deleted another profile's credential.");
}
finally
{
profile.Dispose();
store.RemoveProfile(otherId);
Directory.Delete(root, true);
}
}
static void TestBackup()
{
string root = TempDirectory();
string path = Path.Combine(root, "test.dfbackup");
try
{
var data = new VaultData { ProfileId = Guid.NewGuid(), ProfileName = "Backup test", TotpEntries = [new TotpEntry { Account = "A", SecretBase32 = "GEZDGNBVGY3TQOJQ" }] };
var service = new VaultBackupService();
service.Export(data, "long-backup-password", path);
Assert(service.Import(path, "long-backup-password").TotpEntries.Count == 1, "Backup round trip failed.");
byte[] bytes = File.ReadAllBytes(path); bytes[^20] ^= 1; File.WriteAllBytes(path, bytes);
bool stopped = false; try { _ = service.Import(path, "long-backup-password"); } catch { stopped = true; }
Assert(stopped, "Tampered backup was accepted.");
}
finally { Directory.Delete(root, true); }
}
static void TestAudit()
{
string root = TempDirectory(); string csv = Path.Combine(root, "audit.csv");
try
{
var data = new VaultData { AuditLog = [new AuditEvent { Type = "Test", Message = "Signed event" }] };
var service = new AuditExportService(); SignedAuditExport export = service.ExportSignedCsv(data, csv);
Assert(service.Verify(export.CsvPath, export.SignaturePath, export.PublicKeyPath), "Valid signature failed.");
File.AppendAllText(export.CsvPath, "tampered");
Assert(!service.Verify(export.CsvPath, export.SignaturePath, export.PublicKeyPath), "Tampered audit export verified.");
}
finally { Directory.Delete(root, true); }
}
static void TestAuditKeyZeroing()
{
string root = TempDirectory();
var repository = new VaultRepository(new AppPaths(root), useTpm: false);
UnlockedProfile profile = repository.CreateProfile(new ProfileCreationRequest("Audit memory", "Correct-Horse-7", null));
try
{
_ = new AuditExportService().ExportSignedCsv(profile.Data, Path.Combine(root, "audit.csv"));
repository.Save(profile);
byte[] privateKeyReference = profile.Data.AuditSigningPrivateKeyPkcs8
?? throw new InvalidOperationException("Audit signing key was not created.");
profile.Dispose();
Assert(profile.Data.AuditSigningPrivateKeyPkcs8 is null, "The disposed vault retained its audit private-key reference.");
Assert(privateKeyReference.All(value => value == 0), "The disposed vault left audit private-key bytes in managed memory.");
}
finally
{
profile.Dispose();
Directory.Delete(root, true);
}
}
static void TestCtapCbor()
{
byte[] hash = RandomNumberGenerator.GetBytes(32);
var input = new Dictionary<object, object?>
{
[1L] = hash,
[2L] = new Dictionary<object, object?> { ["id"] = "example.com", ["name"] = "Example" },
[3L] = new List<object?> { -7L, true, "public-key" }
};
Dictionary<object, object?> decoded = CtapCbor.Map(CtapCbor.Decode(CtapCbor.Encode(input)));
Assert(CryptographicOperations.FixedTimeEquals(CtapCbor.Bytes(decoded[1L]), hash), "CBOR byte string changed.");
Assert(CtapCbor.Text(CtapCbor.Map(decoded[2L])["id"]) == "example.com", "CBOR map changed.");
byte[] canonical = CtapCbor.Encode(new Dictionary<object, object?>
{
["bb"] = 1L,
[-1L] = 4L,
["a"] = 2L,
[1L] = 3L
});
Assert(canonical.SequenceEqual(new byte[] { 0xA4, 0x01, 0x03, 0x20, 0x04, 0x61, 0x61, 0x02, 0x62, 0x62, 0x62, 0x01 }),
"The CTAP encoder did not sort map keys canonically.");
}
static void TestSoftwarePasskey(bool requireTpm)
{
string root = TempDirectory();
var store = new SoftwarePasskeyStore(root);
SoftwarePasskeyCredential? credential = null;
Guid profileId = Guid.NewGuid();
try
{
credential = store.Create("example.com", "Example", RandomNumberGenerator.GetBytes(32), "user@example.com", "Test User", profileId);
if (requireTpm) Assert(credential.HardwareBacked, "Expected the passkey private key to use this computer's TPM.");
Assert(credential.RegistrationStatus == PasskeyRegistrationStatus.Pending, "A newly created site passkey was presented as confirmed before the relying party accepted it.");
Assert(store.PublicCoseKey(credential).Length > 60, "COSE public key was not generated.");
Assert(store.Sign(credential, RandomNumberGenerator.GetBytes(64)).Length > 60, "TPM passkey did not sign.");
Assert(store.Find(profileId, "example.com", [credential.CredentialId]) is not null, "Stored passkey was not found.");
Assert(store.IncrementCounter(credential) == 1, "Passkey counter was not persisted.");
Assert(store.Find(profileId, credential.CredentialId)?.RegistrationStatus == PasskeyRegistrationStatus.Confirmed, "A successful assertion did not confirm the pending site registration.");
}
finally
{
if (credential is not null) store.Remove(credential.CredentialId);
Directory.Delete(root, true);
}
}
static void TestPendingPasskeyLifecycle()
{
string root = TempDirectory();
var store = new SoftwarePasskeyStore(root);
Guid profileId = Guid.NewGuid();
SoftwarePasskeyCredential? rejected = null;
SoftwarePasskeyCredential? accepted = null;
try
{
rejected = store.Create("accounts.google.com", "Google", RandomNumberGenerator.GetBytes(32), "rejected@example.com", "Rejected", profileId);
Assert(rejected.RegistrationStatus == PasskeyRegistrationStatus.Pending, "The Google registration did not start as pending.");
Assert(store.Remove(profileId, rejected.CredentialId), "A rejected pending credential could not be removed.");
Assert(store.Find(profileId, rejected.CredentialId) is null, "A rejected credential remained in the provider store.");
rejected = null;
accepted = store.Create("accounts.google.com", "Google", RandomNumberGenerator.GetBytes(32), "accepted@example.com", "Accepted", profileId);
Assert(store.ConfirmRegistration(profileId, accepted.CredentialId), "A confirmed site registration could not be marked complete.");
SoftwarePasskeyCredential confirmed = store.Find(profileId, accepted.CredentialId) ?? throw new InvalidOperationException("Confirmed credential disappeared.");
Assert(confirmed.RegistrationStatus == PasskeyRegistrationStatus.Confirmed && confirmed.ConfirmedUtc is not null,
"The confirmed state was not persisted.");
}
finally
{
if (rejected is not null) store.Remove(profileId, rejected.CredentialId);
if (accepted is not null) store.Remove(profileId, accepted.CredentialId);
Directory.Delete(root, true);
}
}
static void TestPasskeyProfileBinding()
{
string root = TempDirectory();
var context = new PasskeyProviderContext(root);
var store = new SoftwarePasskeyStore(root);
SoftwarePasskeyCredential? firstCredential = null;
SoftwarePasskeyCredential? secondCredential = null;
Guid firstProfileId = Guid.NewGuid();
Guid secondProfileId = Guid.NewGuid();
try
{
context.SetActiveProfile(firstProfileId);
Assert(context.GetActiveProfileId() == firstProfileId, "The active profile marker was not restored.");
firstCredential = store.Create("accounts.google.com", "Google", RandomNumberGenerator.GetBytes(32), "first@example.com", "First", firstProfileId);
secondCredential = store.Create("accounts.google.com", "Google", RandomNumberGenerator.GetBytes(32), "second@example.com", "Second", secondProfileId);
Assert(store.Find(firstProfileId, "accounts.google.com", [])?.UserName == "first@example.com", "The first profile did not resolve its own passkey.");
Assert(store.Find(secondProfileId, "accounts.google.com", [])?.UserName == "second@example.com", "The second profile reused the first profile's passkey.");
Assert(store.Find(secondProfileId, "accounts.google.com", [firstCredential.CredentialId]) is null, "A credential ID from another profile crossed the profile boundary.");
context.Clear(firstProfileId);
Assert(context.GetActiveProfileId() is null, "Locking did not clear the active profile marker.");
}
finally
{
if (firstCredential is not null) store.Remove(firstCredential.CredentialId);
if (secondCredential is not null) store.Remove(secondCredential.CredentialId);
Directory.Delete(root, true);
}
}
static void TestCtapLimits()
{
AssertThrows<FormatException>(() => CtapCbor.Decode(new byte[CtapCbor.MaximumDocumentBytes + 1]), "Oversized CTAP CBOR was accepted.");
byte[] nested = Enumerable.Repeat((byte)0x81, CtapCbor.MaximumNestingDepth + 2).Append((byte)0xF6).ToArray();
AssertThrows<FormatException>(() => CtapCbor.Decode(nested), "Excessively nested CTAP CBOR was accepted.");
AssertThrows<FormatException>(() => CtapCbor.Decode([0x9A, 0xFF, 0xFF, 0xFF, 0xFF]), "A hostile CBOR collection count was accepted.");
AssertThrows<FormatException>(() => CtapCbor.Decode([0x62, 0xC3, 0x28]), "Invalid UTF-8 in CTAP text was accepted.");
AssertThrows<FormatException>(() => CtapCbor.Decode([0xA2, 0x01, 0x01, 0x01, 0x02]), "Duplicate CTAP map keys were accepted.");
AssertThrows<FormatException>(() => CtapCbor.Decode([0x18, 0x17]), "A non-minimal CTAP integer was accepted.");
AssertThrows<FormatException>(() => CtapCbor.Decode([0x58, 0x01, 0x00]), "A non-minimal CTAP length was accepted.");
AssertThrows<FormatException>(() => CtapCbor.Decode([0xA2, 0x02, 0x00, 0x01, 0x00]), "An unsorted CTAP map was accepted.");
AssertThrows<FormatException>(() => CtapCbor.Decode([0xA2, 0x41, 0x01, 0x00, 0x41, 0x01, 0x01]), "Duplicate CTAP byte-string map keys were accepted.");
AssertThrows<FormatException>(() => CtapCbor.Decode([0xA1, 0x81, 0x01, 0x00]), "A composite CTAP map key was accepted.");
using var hostile = new MemoryStream();
hostile.Write([0x99, 0x04, 0x00]);
for (int i = 0; i < 1024; i++) hostile.Write([0x84, 0xF6, 0xF6, 0xF6, 0xF6]);
AssertThrows<FormatException>(() => CtapCbor.Decode(hostile.ToArray()), "A CTAP document with excessive decoded objects was accepted.");
var excessive = Enumerable.Range(0, 1024).Select(_ => (object?)new List<object?> { null, null, null, null }).ToList();
AssertThrows<ArgumentException>(() => CtapCbor.Encode(excessive), "The CTAP encoder produced a document its decoder resource limits reject.");
var fuzz = new Random(0x0C7A_2B02);
for (int i = 0; i < 2_000; i++)
{
byte[] candidate = new byte[fuzz.Next(1, 513)];
fuzz.NextBytes(candidate);
try { _ = CtapCbor.Decode(candidate); }
catch (FormatException) { }
}
}
static void TestWebAuthnOutputValidation()
{
using ECDsa key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
ECParameters parameters = key.ExportParameters(false);
byte[] publicKeyCose = CtapCbor.Encode(new Dictionary<object, object?>
{
[1L] = 2L,
[3L] = -7L,
[-1L] = 1L,
[-2L] = parameters.Q.X!,
[-3L] = parameters.Q.Y!
});
byte[] credentialId = RandomNumberGenerator.GetBytes(32);
byte[] rpIdHash = SHA256.HashData(Encoding.UTF8.GetBytes("darksfido2.local"));
byte[] registration = new byte[55 + credentialId.Length + publicKeyCose.Length];
rpIdHash.CopyTo(registration, 0);
registration[32] = 0x45;
RandomNumberGenerator.Fill(registration.AsSpan(37, 16));
BinaryPrimitives.WriteUInt16BigEndian(registration.AsSpan(53, 2), (ushort)credentialId.Length);
credentialId.CopyTo(registration, 55);
publicKeyCose.CopyTo(registration, 55 + credentialId.Length);
WebAuthnService.RegistrationAuthenticatorData validated =
WebAuthnService.ValidateRegistrationAuthenticatorData(registration, credentialId);
Assert(validated.PublicKeyCoseBase64 == Convert.ToBase64String(publicKeyCose), "Registration did not retain the verified credential public key.");
byte[] assertion = new byte[37];
rpIdHash.CopyTo(assertion, 0);
assertion[32] = 0x05;
BinaryPrimitives.WriteUInt32BigEndian(assertion.AsSpan(33, 4), 1);
byte[] clientDataHash = RandomNumberGenerator.GetBytes(32);
byte[] signedData = new byte[assertion.Length + clientDataHash.Length];
assertion.CopyTo(signedData, 0);
clientDataHash.CopyTo(signedData, assertion.Length);
byte[] signedHash = SHA256.HashData(signedData);
byte[] signature = key.SignHash(signedHash, DSASignatureFormat.Rfc3279DerSequence);
uint counter = WebAuthnService.ValidateAssertionAuthenticatorData(
validated.PublicKeyCoseBase64, credentialId, credentialId, assertion, clientDataHash, signature, 0);
Assert(counter == 1, "A valid WebAuthn assertion counter was not returned.");
byte[] wrongRp = assertion.ToArray();
wrongRp[0] ^= 0x01;
AssertThrows<CryptographicException>(
() => WebAuthnService.ValidateAssertionAuthenticatorData(validated.PublicKeyCoseBase64, credentialId, credentialId, wrongRp, clientDataHash, signature, 0),
"A WebAuthn assertion for another relying party was accepted.");
byte[] missingUv = assertion.ToArray();
missingUv[32] = 0x01;
AssertThrows<CryptographicException>(
() => WebAuthnService.ValidateAssertionAuthenticatorData(validated.PublicKeyCoseBase64, credentialId, credentialId, missingUv, clientDataHash, signature, 0),
"A WebAuthn assertion without user verification was accepted.");
byte[] wrongCredential = credentialId.ToArray();
wrongCredential[0] ^= 0x01;
AssertThrows<CryptographicException>(
() => WebAuthnService.ValidateAssertionAuthenticatorData(validated.PublicKeyCoseBase64, credentialId, wrongCredential, assertion, clientDataHash, signature, 0),
"A WebAuthn assertion from another credential was accepted.");
byte[] badSignature = signature.ToArray();
badSignature[^1] ^= 0x01;
AssertThrows<CryptographicException>(
() => WebAuthnService.ValidateAssertionAuthenticatorData(validated.PublicKeyCoseBase64, credentialId, credentialId, assertion, clientDataHash, badSignature, 0),
"A WebAuthn assertion with a bad signature was accepted.");
AssertThrows<CryptographicException>(
() => WebAuthnService.ValidateAssertionAuthenticatorData(validated.PublicKeyCoseBase64, credentialId, credentialId, assertion, clientDataHash, signature, 1),
"A non-increasing WebAuthn signature counter was accepted.");
byte[] wrongRegistrationCredential = registration.ToArray();
wrongRegistrationCredential[55] ^= 0x01;
AssertThrows<CryptographicException>(
() => WebAuthnService.ValidateRegistrationAuthenticatorData(wrongRegistrationCredential, credentialId),
"Registration accepted a mismatched embedded credential identifier.");
}
static void TestBackupLimits()
{
string root = TempDirectory();
string path = Path.Combine(root, "hostile.dfbackup");
try
{
var service = new VaultBackupService();
service.Export(new VaultData { ProfileId = Guid.NewGuid(), ProfileName = "Bounded" }, "long-backup-password", path);
JsonObject envelope = JsonNode.Parse(File.ReadAllBytes(path))?.AsObject() ?? throw new InvalidOperationException("Backup JSON was not created.");
envelope["Iterations"] = int.MaxValue;
File.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(envelope));
var timer = Stopwatch.StartNew();
AssertThrows<CryptographicException>(() => service.Import(path, "long-backup-password"), "A hostile backup PBKDF2 work factor was accepted.");
timer.Stop();
Assert(timer.Elapsed < TimeSpan.FromSeconds(2), "Hostile backup parameters consumed excessive CPU time.");
}
finally { Directory.Delete(root, true); }
}
static void TestMetadataLimits()
{
string root = TempDirectory();
var paths = new AppPaths(root);
var repository = new VaultRepository(paths, useTpm: false);
Guid id;
using (UnlockedProfile profile = repository.CreateProfile(new ProfileCreationRequest("Metadata", "Correct-Horse-7", null))) id = profile.Metadata.Id;
try
{
string path = paths.MetadataPath(id);
byte[] protectedBytes = File.ReadAllBytes(path);
byte[] json = DpapiProtector.Unprotect(protectedBytes);
JsonObject metadata = JsonNode.Parse(json)?.AsObject() ?? throw new InvalidOperationException("Metadata JSON was not created.");
metadata["Pbkdf2Iterations"] = int.MaxValue;
byte[] modified = JsonSerializer.SerializeToUtf8Bytes(metadata);
byte[] reprotected = DpapiProtector.Protect(modified);
File.WriteAllBytes(path, reprotected);
CryptographicOperations.ZeroMemory(protectedBytes);
CryptographicOperations.ZeroMemory(json);
CryptographicOperations.ZeroMemory(modified);
CryptographicOperations.ZeroMemory(reprotected);
var timer = Stopwatch.StartNew();
AssertThrows<CryptographicException>(() => repository.Unlock(id, "Correct-Horse-7", null), "A hostile profile PBKDF2 work factor was accepted.");
timer.Stop();
Assert(timer.Elapsed < TimeSpan.FromSeconds(2), "Hostile profile metadata consumed excessive CPU time.");
}
finally { Directory.Delete(root, true); }
}
static void TestStaleProviderContext()
{
string root = TempDirectory();
try
{
var context = new PasskeyProviderContext(root);
Guid profileId = Guid.NewGuid();
context.SetActiveProfile(profileId);
string path = Path.Combine(root, "active-profile.dpapi");
byte[] protectedBytes = File.ReadAllBytes(path);
byte[] json = DpapiProtector.Unprotect(protectedBytes);
JsonObject marker = JsonNode.Parse(json)?.AsObject() ?? throw new InvalidOperationException("Context JSON was not created.");
marker["UpdatedUtc"] = DateTimeOffset.UtcNow.AddMinutes(-10).ToString("O");
byte[] modified = JsonSerializer.SerializeToUtf8Bytes(marker);
byte[] reprotected = DpapiProtector.Protect(modified);
File.WriteAllBytes(path, reprotected);
CryptographicOperations.ZeroMemory(protectedBytes);
CryptographicOperations.ZeroMemory(json);
CryptographicOperations.ZeroMemory(modified);
CryptographicOperations.ZeroMemory(reprotected);
Assert(context.GetActiveProfileId() is null, "An expired profile marker was treated as active.");
context.Clear(profileId);
Assert(!File.Exists(path), "An expired profile marker could not be cleared.");
}
finally { Directory.Delete(root, true); }
}
static void TestTotpLimits()
{
AssertThrows<FormatException>(() => TotpService.DecodeBase32(new string('A', 9_000)), "An oversized TOTP secret was accepted.");
AssertThrows<FormatException>(() => TotpService.ParseOtpAuthUri("otpauth://totp/test?secret=GEZDGNBVGY3TQOJQ&secret=GEZDGNBVGY3TQOJQ"), "Duplicate TOTP URI parameters were accepted.");
AssertThrows<ArgumentException>(() => TotpService.GetCode(new TotpEntry { SecretBase32 = "GEZDGNBVGY3TQOJQ", Algorithm = "MD5" }), "An unsupported TOTP algorithm was silently downgraded.");
}
static void TestAuditCsvInjection()
{
string root = TempDirectory();
try
{
var data = new VaultData { AuditLog = [new AuditEvent { Type = "Test", Message = "=HYPERLINK(\"https://example.invalid\")" }] };
SignedAuditExport export = new AuditExportService().ExportSignedCsv(data, Path.Combine(root, "audit.csv"));
string csv = File.ReadAllText(export.CsvPath);
Assert(csv.Contains("\"'=HYPERLINK", StringComparison.Ordinal), "A spreadsheet formula was not neutralized in the audit CSV.");
Assert(new AuditExportService().Verify(export.CsvPath, export.SignaturePath, export.PublicKeyPath), "The neutralized audit CSV signature failed.");
}
finally { Directory.Delete(root, true); }
}
static byte[] CreateLegacyVaultEnvelope(VaultData data, ReadOnlySpan<byte> masterKey)
{
byte[] aad = Encoding.UTF8.GetBytes("DarksFIDO2:vault:v1");
byte[] plaintext = JsonSerializer.SerializeToUtf8Bytes(data, VaultCryptography.JsonOptions);
byte[] encKey = VaultCryptography.Hkdf(masterKey, [], "DarksFIDO2:vault:encryption", 32);
byte[] macKey = VaultCryptography.Hkdf(masterKey, [], "DarksFIDO2:vault:integrity", 32);
byte[] nonce = RandomNumberGenerator.GetBytes(12);
byte[] ciphertext = new byte[plaintext.Length];
byte[] tag = new byte[16];
byte[] macInput = [];
try
{
using (var aes = new AesGcm(encKey, 16))
aes.Encrypt(nonce, plaintext, ciphertext, tag, aad);
macInput = Combine(aad, nonce, ciphertext, tag);
byte[] hmac = HMACSHA256.HashData(macKey, macInput);
return JsonSerializer.SerializeToUtf8Bytes(new VaultEnvelope
{
Magic = "DFV1",
Nonce = nonce,
Ciphertext = ciphertext,
Tag = tag,
Hmac = hmac
}, VaultCryptography.JsonOptions);
}
finally
{
CryptographicOperations.ZeroMemory(plaintext);
CryptographicOperations.ZeroMemory(encKey);
CryptographicOperations.ZeroMemory(macKey);
if (macInput.Length > 0) CryptographicOperations.ZeroMemory(macInput);
}
}
static void TestTpmNamespaceAndKeyValidation()
{
var validVault = new VaultData
{
ProfileId = Guid.NewGuid(),
ProfileName = "Test",
TpmKeys = [
new TpmKeyRecord
{
Name = "Test Key",
ProviderKeyName = $"DarksFIDO2.Key.{Guid.NewGuid():N}",
Algorithm = "ECDSA_P256",
PublicKeyBase64 = Convert.ToBase64String(RandomNumberGenerator.GetBytes(65))
}
]
};
DataValidation.Vault(validVault);
// Invalid namespace: Outside DarksFIDO2.Key.{Guid:N}
var badNamespaceVault = new VaultData
{
ProfileId = Guid.NewGuid(),
ProfileName = "Test",
TpmKeys = [
new TpmKeyRecord
{
Name = "Bad Key",
ProviderKeyName = "DarksFIDO2.TPM.Derived.12345",
Algorithm = "ECDSA_P256",
PublicKeyBase64 = Convert.ToBase64String(RandomNumberGenerator.GetBytes(65))
}
]
};
bool badNamespaceFailed = false;
try { DataValidation.Vault(badNamespaceVault); }
catch (CryptographicException) { badNamespaceFailed = true; }
Assert(badNamespaceFailed, "Key outside namespace was allowed.");
// Invalid empty public key
var emptyPkVault = new VaultData
{
ProfileId = Guid.NewGuid(),
ProfileName = "Test",
TpmKeys = [
new TpmKeyRecord
{
Name = "No PK Key",
ProviderKeyName = $"DarksFIDO2.Key.{Guid.NewGuid():N}",
Algorithm = "ECDSA_P256",
PublicKeyBase64 = ""
}
]
};
bool emptyPkFailed = false;
try { DataValidation.Vault(emptyPkVault); }
catch (CryptographicException) { emptyPkFailed = true; }
Assert(emptyPkFailed, "Empty public key was accepted.");
}
static byte[] Combine(params byte[][] parts)
{
byte[] result = new byte[parts.Sum(part => part.Length)];
int offset = 0;
foreach (byte[] part in parts)
{
part.CopyTo(result, offset);
offset += part.Length;
}
return result;
}
static string TempDirectory()
{
string path = Path.Combine(Path.GetTempPath(), "DarksFIDO2-Tests-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(path); return path;
}
static void Assert(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
static void AssertThrows<T>(Action action, string message) where T : Exception
{
try { action(); }
catch (T) { return; }
throw new InvalidOperationException(message);
}