-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFIDOWebAuthn.cs
More file actions
375 lines (311 loc) · 14.8 KB
/
Copy pathFIDOWebAuthn.cs
File metadata and controls
375 lines (311 loc) · 14.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
using System.Text;
using System.Text.Json;
using System.Security.Cryptography;
using WebAuthn_Client_.NET.Cryptographic;
using WebAuthn_Client_.NET.Storage;
namespace WebAuthn_Client_.NET
{
public class FIDOWebAuthn
{
public byte[] AAGUID = Convert.FromHexString("b53976664885aa6bcebfe52262a439a2"); //Chromium Browser
public int CredLen = 64;
public readonly ICredentialStorage _storage;
private readonly Dictionary<CoseAlgorithm, ICryptographicProvider> _cryptoProviders;
private readonly Random _random;
public FIDOWebAuthn(ICredentialStorage? storage = null)
{
_storage = storage ?? new CsvCredentialStorage();
_random = new Random();
_cryptoProviders = new Dictionary<CoseAlgorithm, ICryptographicProvider>
{
// Extend with more cryptographic providers as needed
{ CoseAlgorithm.ES256, new ES256Provider() },
{ CoseAlgorithm.RS256, new RS256Provider() }
};
}
// Create credential (registration)
public PublicKeyCredential Create(string jsonInput, string? Origin = null)
{
try
{
var options = JsonSerializer.Deserialize<PublicKeyCredentialCreationOptions>(jsonInput)!;
return CreateCredential(options, Origin);
}
catch (JsonException ex)
{
throw new ArgumentException($"Invalid JSON input: {ex.Message}", ex);
}
}
public PublicKeyCredential Create(PublicKeyCredentialCreationOptions options, string? Origin = null)
{
return CreateCredential(options, Origin);
}
// Get credential (authentication)
public PublicKeyCredential Get(string jsonInput, string? Origin = null)
{
try
{
var options = JsonSerializer.Deserialize<PublicKeyCredentialRequestOptions>(jsonInput)!;
return GetCredential(options, Origin);
}
catch (JsonException ex)
{
throw new ArgumentException($"Invalid JSON input: {ex.Message}", ex);
}
}
public PublicKeyCredential Get(PublicKeyCredentialRequestOptions options, string? Origin = null)
{
return GetCredential(options, Origin);
}
private PublicKeyCredential CreateCredential(PublicKeyCredentialCreationOptions options, string? Origin = null)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
if (string.IsNullOrEmpty(options.Challenge))
throw new ArgumentException("Challenge is required");
if (options.Rp == null)
throw new ArgumentException("Relying party information is required");
if (options.User == null || string.IsNullOrEmpty(options.User.Id))
throw new ArgumentException("User information is required");
var rpId = GetEffectiveRpId(options.Rp.Id, Origin);
Origin ??= $"https://{rpId}";
// Select algorithm
var algorithm = SelectAlgorithm(options.PubKeyCredParams) ?? throw new NotSupportedException("No supported algorithm found");
var provider = _cryptoProviders[algorithm];
// Generate credential ID
var credentialId = GenerateCredentialId();
var credentialIdBytes = Convert.FromBase64String(credentialId);
// Generate key pair
var (publicKey, privateKey) = provider.GenerateKeyPair();
// Create and save credential record
var credentialRecord = new CredentialRecord
{
CredentialId = credentialId,
UserId = options.User.Id,
UserName = options.User.Name,
RpId = rpId,
Algorithm = algorithm.ToString(),
PublicKey = publicKey,
PrivateKey = privateKey,
SignCount = 0,
CreatedAt = DateTime.UtcNow
};
_storage.SaveCredential(credentialRecord);
// Create client data
var clientData = new ClientData
{
Type = "webauthn.create",
Challenge = options.Challenge,
Origin = Origin,
CrossOrigin = false
};
var clientDataJson = JsonSerializer.Serialize(clientData);
var clientDataBytes = Encoding.UTF8.GetBytes(clientDataJson);
// Create COSE public key
var cosePublicKey = CborHelper.EncodeCoseKey(publicKey, algorithm);
// Create authenticator data with proper CBOR-encoded credential public key
var authenticatorData = CreateAuthenticatorData(rpId, true, credentialIdBytes, cosePublicKey);
// This mock authenticator always returns anonymized "none" attestation,
// regardless of the relying party's attestation conveyance preference.
var attestationObject = CborHelper.EncodeAttestationObject(authenticatorData);
// Create response
var response = new AuthenticatorAttestationResponse
{
ClientDataJSON = Base64UrlHelper.Encode(clientDataBytes),
AttestationObject = Base64UrlHelper.Encode(attestationObject),
};
return new PublicKeyCredential
{
Id = Base64UrlHelper.Encode(credentialIdBytes),
RawId = Base64UrlHelper.Encode(credentialIdBytes),
Response = response,
AuthenticatorAttachment = "platform"
};
}
private PublicKeyCredential GetCredential(PublicKeyCredentialRequestOptions options, string? Origin = null)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
if (string.IsNullOrEmpty(options.Challenge))
throw new ArgumentException("Challenge is required");
var rpId = GetEffectiveRpId(options.RpId, Origin);
// Find matching credential
CredentialRecord? credential = null;
var triedCredentialIds = new List<string>();
if (options.AllowCredentials?.Count > 0)
{
foreach (var allowedCred in options.AllowCredentials)
{
var storageLookupId = Convert.ToBase64String(Base64UrlHelper.Decode(allowedCred.Id));
triedCredentialIds.Add($"{Shorten(allowedCred.Id)}=>{Shorten(storageLookupId)}");
credential = _storage.GetCredential(storageLookupId);
if (credential != null) break;
}
}
else
{
// If no specific credentials are allowed, get the first one
var credentials = _storage.GetCredentialsByRp(rpId);
if (credentials.Count > 0)
{
credential = credentials[0]; // Just take the first one
}
}
if (credential == null)
throw new InvalidOperationException(BuildNoMatchingCredentialMessage(rpId, options, triedCredentialIds));
// Verify RP ID matches
if (credential.RpId != rpId)
throw new UnauthorizedAccessException($"RP ID mismatch. Requested RP ID '{rpId}', but stored credential RP ID is '{credential.RpId}'. Credential ID: {Shorten(credential.CredentialId)}.");
// Create client data
Origin ??= $"https://{credential.RpId}";
var clientData = new ClientData
{
Type = "webauthn.get",
Challenge = options.Challenge,
Origin = Origin,
CrossOrigin = false
};
var clientDataJson = JsonSerializer.Serialize(clientData);
var clientDataBytes = Encoding.UTF8.GetBytes(clientDataJson);
// Create authenticator data (no attested credential data for authentication)
credential.SignCount++;
var authenticatorData = CreateAuthenticatorData(credential.RpId, false, null, null, credential.SignCount);
// Create signature
var dataToSign = new List<byte>();
dataToSign.AddRange(authenticatorData);
dataToSign.AddRange(SHA256.HashData(clientDataBytes));
var algorithmEnum = Enum.Parse<CoseAlgorithm>(credential.Algorithm);
var provider = _cryptoProviders[algorithmEnum];
var signature = provider.Sign(dataToSign.ToArray(), credential.PrivateKey);
// Update sign count in storage
_storage.UpdateSignCount(credential.CredentialId, credential.SignCount);
// Create response
var response = new AuthenticatorAssertionResponse
{
ClientDataJSON = Base64UrlHelper.Encode(clientDataBytes),
AuthenticatorData = Base64UrlHelper.Encode(authenticatorData),
Signature = Base64UrlHelper.Encode(signature),
UserHandle = credential.UserId
};
var credentialIdBytes = Base64UrlHelper.Decode(credential.CredentialId);
return new PublicKeyCredential
{
Id = Base64UrlHelper.Encode(credentialIdBytes),
RawId = Base64UrlHelper.Encode(credentialIdBytes),
Response = response,
AuthenticatorAttachment = "platform"
};
}
private CoseAlgorithm? SelectAlgorithm(List<PublicKeyCredentialParameters>? pubKeyCredParams)
{
if (pubKeyCredParams == null) return CoseAlgorithm.ES256; // Default
foreach (var param in pubKeyCredParams)
{
if (Enum.IsDefined(typeof(CoseAlgorithm), param.Alg))
{
var algorithm = (CoseAlgorithm)param.Alg;
if (_cryptoProviders.ContainsKey(algorithm))
return algorithm;
}
}
return null;
}
private string GenerateCredentialId()
{
var bytes = new byte[CredLen];
_random.NextBytes(bytes);
return Convert.ToBase64String(bytes);
}
private static string GetEffectiveRpId(string? rpId, string? origin)
{
if (!string.IsNullOrWhiteSpace(rpId))
return rpId;
if (string.IsNullOrWhiteSpace(origin))
throw new ArgumentException("Relying party ID is required when origin is not provided");
if (!Uri.TryCreate(origin, UriKind.Absolute, out var originUri) ||
string.IsNullOrWhiteSpace(originUri.IdnHost))
throw new ArgumentException("Origin must be an absolute URI when relying party ID is not provided");
return originUri.IdnHost.TrimEnd('.').ToLowerInvariant();
}
private string BuildNoMatchingCredentialMessage(
string rpId,
PublicKeyCredentialRequestOptions options,
List<string> triedCredentialIds)
{
var credentialsForRp = _storage.GetCredentialsByRp(rpId);
var allCredentials = _storage.GetAllCredentials();
var allowCredentialsCount = options.AllowCredentials?.Count ?? 0;
var message = new StringBuilder();
message.Append($"No matching credential found. Effective RP ID: '{rpId}'. ");
message.Append($"allowCredentials count: {allowCredentialsCount}. ");
if (triedCredentialIds.Count > 0)
{
message.Append("Tried credential IDs: ");
message.Append(string.Join(", ", triedCredentialIds));
message.Append(". ");
}
message.Append($"Stored credentials for RP: {credentialsForRp.Count}. ");
if (credentialsForRp.Count > 0)
{
message.Append("Stored credential IDs for RP: ");
message.Append(string.Join(", ", credentialsForRp.Select(c => Shorten(c.CredentialId))));
message.Append(". ");
}
message.Append($"Stored credentials total: {allCredentials.Count}. ");
if (allCredentials.Count > 0)
{
message.Append("Stored RP IDs: ");
message.Append(string.Join(", ", allCredentials.Select(c => c.RpId).Distinct().OrderBy(r => r)));
message.Append(".");
}
return message.ToString();
}
private static string Shorten(string value)
{
if (string.IsNullOrEmpty(value) || value.Length <= 16)
return value;
return $"{value[..8]}...{value[^8..]}";
}
private byte[] CreateAuthenticatorData(string rpId, bool includeAttestedCredentialData,
byte[]? credentialIdBytes = null, byte[]? cosePublicKey = null, int signCount = 0)
{
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream))
{
// RP ID hash (32 bytes)
var rpIdBytes = Encoding.UTF8.GetBytes(rpId);
var rpIdHash = SHA256.HashData(rpIdBytes);
writer.Write(rpIdHash);
// Flags (1 byte)
byte flags = 0x01; // User present (UP)
flags |= 0x04; // User verified (UV)
flags |= 0x08; // Backup Eligibility (BE)
flags |= 0x10; // Backup State (BS)
if (includeAttestedCredentialData)
flags |= 0x40; // Attested credential data included (AT)
writer.Write(flags);
// Signature counter (4 bytes, big-endian)
var counterBytes = BitConverter.GetBytes((uint)signCount);
if (BitConverter.IsLittleEndian)
Array.Reverse(counterBytes);
writer.Write(counterBytes);
// Attested credential data (only for registration)
if (includeAttestedCredentialData && credentialIdBytes != null && cosePublicKey != null)
{
// AAGUID (16 bytes)
writer.Write(AAGUID);
// Credential ID length (2 bytes, big-endian)
var lengthBytes = BitConverter.GetBytes((ushort)credentialIdBytes.Length);
if (BitConverter.IsLittleEndian)
Array.Reverse(lengthBytes);
writer.Write(lengthBytes);
// Credential ID
writer.Write(credentialIdBytes);
// Credential public key (CBOR-encoded COSE key)
writer.Write(cosePublicKey);
}
return stream.ToArray();
}
}
}
}