Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Improve webauthn error reporting, add support for Yubikey (#269)

Leendert de Borstfc8d365c4995
diff --git a/src/AliasVault.Client/Auth/Pages/Unlock.razor b/src/AliasVault.Client/Auth/Pages/Unlock.razor
index d9bda8e75..9ba86bd2f 100644
--- a/src/AliasVault.Client/Auth/Pages/Unlock.razor
+++ b/src/AliasVault.Client/Auth/Pages/Unlock.razor
@@ -232,6 +232,10 @@ else
Logger.LogWarning("The decrypted encryption key does not match the persisted encryption key. Falling back to password unlock.");
}
}
+ catch (NotSupportedException)
+ {
+ GlobalNotificationService.AddErrorMessage("Your current browser does not support the WebAuthn PRF extension. Please login with your password instead.", true);
+ }
catch (Exception ex)
{
Logger.LogError(ex, "An error occurred while trying to unlock the vault with WebAuthn.");
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor
index ffb9d47fc..3edea207b 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor
@@ -1,4 +1,5 @@
@inherits MainBase
+@inject ILogger<PersistEncryptionKeySection> Logger
<div class="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
<h3 class="mb-2 text-lg font-medium text-gray-900 dark:text-white">Encryption key persist</h3>
@@ -55,14 +56,24 @@
/// </summary>
public async Task EnableWebAuthn()
{
- var webauthCredentialDerivedKey = await JsInteropService.CreateWebAuthnCredentialDerivedKey(await GetUsernameAsync());
-
- Console.WriteLine($"webauthCredentialDerivedKey: {webauthCredentialDerivedKey}");
- Console.WriteLine($"webauthCredentialDerivedKey.CredentialId: {webauthCredentialDerivedKey.CredentialId}");
- Console.WriteLine($"webauthCredentialDerivedKey.DerivedKey: {webauthCredentialDerivedKey.DerivedKey}");
+ try
+ {
+ var webauthCredentialDerivedKey = await JsInteropService.CreateWebAuthnCredentialDerivedKey(await GetUsernameAsync());
- // Set local storage var to indicate that WebAuthn is enabled and we should try to use it to unlock the vault.
- await AuthService.SetWebAuthnEnabledAsync(true, webauthCredentialDerivedKey.CredentialId, webauthCredentialDerivedKey.Salt, webauthCredentialDerivedKey.DerivedKey);
+ // Set local storage var to indicate that WebAuthn is enabled, and we should try to use it to unlock the vault.
+ await AuthService.SetWebAuthnEnabledAsync(true, webauthCredentialDerivedKey.CredentialId, webauthCredentialDerivedKey.Salt, webauthCredentialDerivedKey.DerivedKey);
+ }
+ catch (NotSupportedException)
+ {
+ GlobalNotificationService.AddErrorMessage("Your current browser does not support the WebAuthn PRF extension. Please try again with a different browser.", true);
+ return;
+ }
+ catch (Exception ex)
+ {
+ GlobalNotificationService.AddErrorMessage("An error occurred while trying to enable WebAuthn. Please try again (later).", true);
+ Logger.LogInformation(ex, "An error occurred while trying to enable WebAuthn.");
+ return;
+ }
await LoadData();
}
diff --git a/src/AliasVault.Client/Services/Auth/AuthService.cs b/src/AliasVault.Client/Services/Auth/AuthService.cs
index 658d43490..fe668a631 100644
--- a/src/AliasVault.Client/Services/Auth/AuthService.cs
+++ b/src/AliasVault.Client/Services/Auth/AuthService.cs
@@ -174,23 +174,14 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca
var webauthnSalt = await localStorage.GetItemAsStringAsync("webAuthnSalt");
if (string.IsNullOrEmpty(encryptedEncryptionKey) || string.IsNullOrEmpty(webauthnCredentialId) || string.IsNullOrEmpty(webauthnSalt))
{
- throw new InvalidOperationException("WebAuthn encrypted encryption key is not set or WebAuthn credential ID is not set.");
+ throw new NullReferenceException("WebAuthn encrypted encryption key is not set or WebAuthn credential ID is not set.");
}
var webauthnCredentialDerivedKey = await jsInteropService.GetWebAuthnCredentialDerivedKey(webauthnCredentialId, webauthnSalt);
- if (webauthnCredentialDerivedKey is null)
- {
- throw new InvalidOperationException("WebAuthn credential derived key is not set.");
- }
-
- Console.WriteLine($"webauthnCredentialDerivedKey: {webauthnCredentialDerivedKey}");
- Console.WriteLine($"encryptedEncryptionKey: {encryptedEncryptionKey}");
// Decrypt the encrypted encryption key with the WebAuthn derived key.
var decryptedString = await jsInteropService.SymmetricDecrypt(encryptedEncryptionKey, webauthnCredentialDerivedKey);
- Console.WriteLine($"decryptedString: {decryptedString}");
-
return Convert.FromBase64String(decryptedString);
}
diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.cs
index 54875b497..9313eafde 100644
--- a/src/AliasVault.Client/Services/JsInteropService.cs
+++ b/src/AliasVault.Client/Services/JsInteropService.cs
@@ -163,13 +163,31 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)
/// <param name="credentialId">The credential ID to use.</param>
/// <param name="salt">The salt to use.</param>
/// <returns>Derived key as base64 string.</returns>
- /// <exception cref="CryptographicException">Thrown when decryption fails due to a JavaScript error.</exception>
+ /// <exception cref="NotSupportedException">Thrown when the authenticator does not support the PRF extension.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the PRF key derivation fails.</exception>
+ /// <exception cref="CryptographicException">Thrown when there's an error getting the WebAuthn credential or when decryption fails.</exception>
public async Task<string> GetWebAuthnCredentialDerivedKey(string credentialId, string salt)
{
try
{
- var derivedKey = await jsRuntime.InvokeAsync<string?>("getWebAuthnCredentialAndDeriveKey", credentialId, salt);
- return derivedKey ?? throw new CryptographicException("Failed to get WebAuthn credential");
+ var result = await jsRuntime.InvokeAsync<WebAuthnGetCredentialResult>("getWebAuthnCredentialAndDeriveKey", credentialId, salt);
+
+ if (result.Error != null)
+ {
+ switch (result.Error)
+ {
+ case "PRF_NOT_SUPPORTED":
+ throw new NotSupportedException("Authenticator does not support the PRF extension.");
+ case "PRF_DERIVATION_FAILED":
+ throw new InvalidOperationException("Failed to derive key using PRF extension.");
+ case "WEBAUTHN_GET_ERROR":
+ throw new CryptographicException($"Failed to get WebAuthn credential: {result.Message}");
+ default:
+ throw new CryptographicException($"Unknown error occurred: {result.Error}");
+ }
+ }
+
+ return result.DerivedKey ?? throw new CryptographicException("Derived key is null");
}
catch (JSException ex)
{
@@ -184,15 +202,29 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)
/// <param name="username">The username for the credential.</param>
/// <returns>A tuple containing the credential ID, salt and the derived key.</returns>
/// <exception cref="CryptographicException">Thrown when decryption fails due to a JavaScript error.</exception>
+ /// <exception cref="NotSupportedException">Thrown when the authenticator does not support the PRF extension.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the PRF key derivation fails.</exception>
public async Task<(string CredentialId, string Salt, string DerivedKey)> CreateWebAuthnCredentialDerivedKey(string username)
{
try
{
- var result = await jsRuntime.InvokeAsync<WebAuthnResult>("createWebAuthnCredentialAndDeriveKey", username);
- Console.WriteLine($"Result: {result}");
- return result != null
- ? (result.CredentialId, result.Salt, result.DerivedKey)
- : throw new CryptographicException("Failed to get or create WebAuthn credential");
+ var result = await jsRuntime.InvokeAsync<WebAuthnCreateCredentialResult>("createWebAuthnCredentialAndDeriveKey", "AliasVault | " + username);
+ if (result.CredentialId is null || result.Salt is null || result.DerivedKey is null || result.Error is not null || result.Message is not null)
+ {
+ switch (result.Error)
+ {
+ case "PRF_NOT_SUPPORTED":
+ throw new NotSupportedException("Authenticator does not support the PRF extension.");
+ case "PRF_DERIVATION_FAILED":
+ throw new InvalidOperationException("Failed to derive key using PRF extension.");
+ case "WEBAUTHN_CREATE_ERROR":
+ throw new CryptographicException($"Failed to create WebAuthn credential: {result.Message}");
+ default:
+ throw new CryptographicException($"Unknown error occurred: {result.Error}");
+ }
+ }
+
+ return (result.CredentialId, result.Salt, result.DerivedKey);
}
catch (JSException ex)
{
@@ -204,21 +236,52 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)
/// <summary>
/// Represents the result of a WebAuthn credential operation.
/// </summary>
- private class WebAuthnResult
+ private class WebAuthnCreateCredentialResult
{
/// <summary>
/// Gets or sets the credential ID as a base64 string.
/// </summary>
- public string CredentialId { get; set; } = null!;
+ public string? CredentialId { get; set; }
/// <summary>
/// Gets or sets the salt as a base64 string.
/// </summary>
- public string Salt { get; set; } = null!;
+ public string? Salt { get; set; }
/// <summary>
/// Gets or sets the derived key as a base64 string.
/// </summary>
- public string DerivedKey { get; set; } = null!;
+ public string? DerivedKey { get; set; }
+
+ /// <summary>
+ /// Gets or sets the error message.
+ /// </summary>
+ public string? Error { get; set; }
+
+ /// <summary>
+ /// Gets or sets additional error details.
+ /// </summary>
+ public string? Message { get; set; }
+ }
+
+ /// <summary>
+ /// Represents the result of a WebAuthn get credential operation.
+ /// </summary>
+ private class WebAuthnGetCredentialResult
+ {
+ /// <summary>
+ /// Gets or sets the derived key.
+ /// </summary>
+ public string? DerivedKey { get; set; }
+
+ /// <summary>
+ /// Gets or sets the error message.
+ /// </summary>
+ public string? Error { get; set; }
+
+ /// <summary>
+ /// Gets or sets additional error details.
+ /// </summary>
+ public string? Message { get; set; }
}
}
diff --git a/src/AliasVault.Client/wwwroot/js/utilities.js b/src/AliasVault.Client/wwwroot/js/utilities.js
index 369b260fb..87ecb5bea 100644
--- a/src/AliasVault.Client/wwwroot/js/utilities.js
+++ b/src/AliasVault.Client/wwwroot/js/utilities.js
@@ -166,12 +166,11 @@ async function getWebAuthnCredentialAndDeriveKey(credentialIdToUse, salt) {
const challenge = crypto.getRandomValues(new Uint8Array(32));
try {
- // Try to get an existing credential
const existingCredential = await navigator.credentials.get({
publicKey: {
challenge,
rpId,
- userVerification: "preferred",
+ userVerification: "discouraged",
allowCredentials: [{
id: Uint8Array.from(atob(credentialIdToUse), c => c.charCodeAt(0)),
type: 'public-key'
@@ -186,21 +185,22 @@ async function getWebAuthnCredentialAndDeriveKey(credentialIdToUse, salt) {
}
});
- // Check if the authenticator supports the PRF extension
const extensionsResult = existingCredential.getClientExtensionResults();
if (!extensionsResult.prf) {
- throw new Error("Authenticator does not support the PRF extension");
+ return { error: "PRF_NOT_SUPPORTED" };
}
- if (!extensionsResult.prf || !extensionsResult.prf.results || !extensionsResult.prf.results.first) {
- throw new Error("Failed to derive key using PRF extension");
+ if (!extensionsResult.prf.results || !extensionsResult.prf.results.first) {
+ return { error: "PRF_DERIVATION_FAILED" };
}
const derivedKey = extensionsResult.prf.results.first;
- return btoa(String.fromCharCode.apply(null, new Uint8Array(derivedKey)));
+ return {
+ derivedKey: btoa(String.fromCharCode.apply(null, new Uint8Array(derivedKey)))
+ };
} catch (error) {
- console.log("No existing WebAuthn credential found:", error);
- return null;
+ console.error("Error getting WebAuthn credential:", error);
+ return { error: "WEBAUTHN_GET_ERROR", message: error.message };
}
}
@@ -214,8 +214,8 @@ async function createWebAuthnCredentialAndDeriveKey(username) {
const challenge = crypto.getRandomValues(new Uint8Array(32));
const salt = crypto.getRandomValues(new Uint8Array(32));
- // Create a new credential
try {
+ // Create the credential
const newCredential = await navigator.credentials.create({
publicKey: {
challenge,
@@ -227,14 +227,22 @@ async function createWebAuthnCredentialAndDeriveKey(username) {
name: username,
displayName: username
},
- pubKeyCredParams: [{
- alg: -7,
- type: "public-key"
- }],
+ pubKeyCredParams: [
+ { alg: -7, type: "public-key" }, // ES256
+ { alg: -257, type: "public-key" }, // RS256
+ { alg: -37, type: "public-key" }, // PS256
+ { alg: -8, type: "public-key" }, // EdDSA
+ { alg: -35, type: "public-key" }, // ES384
+ { alg: -36, type: "public-key" }, // ES512
+ { alg: -259, type: "public-key" }, // RS384
+ { alg: -258, type: "public-key" }, // RS512
+ { alg: -38, type: "public-key" }, // PS384
+ { alg: -39, type: "public-key" }, // PS512
+ ],
authenticatorSelection: {
- authenticatorAttachment: "platform",
- userVerification: "preferred",
- residentKey: "required"
+ userVerification: "discouraged",
+ residentKey: "discouraged",
+ requireResidentKey: false,
},
extensions: {
prf: {
@@ -246,14 +254,42 @@ async function createWebAuthnCredentialAndDeriveKey(username) {
}
});
- // Check if the authenticator supports the PRF extension
- const extensionsResult = newCredential.getClientExtensionResults();
- if (!extensionsResult.prf || !extensionsResult.prf.enabled) {
- throw new Error("Authenticator does not support the PRF extension");
+ let extensionsResult = newCredential.getClientExtensionResults();
+
+ if (!extensionsResult.prf) {
+ return { error: "PRF_NOT_SUPPORTED" };
+ }
+
+ if (!extensionsResult.prf.results || !extensionsResult.prf.results.first) {
+ alert("Your authenticator has been successfully registered. Please use your authenticator again to complete the process.")
+
+ // Note: Some authenticators do not return the derived key in the create response. In this case,
+ // we need to read the credential to get the derived key. This is required for certain passkeys
+ // such as Yubikey.
+ const existingCredential = await navigator.credentials.get({
+ publicKey: {
+ challenge,
+ rpId,
+ userVerification: "discouraged",
+ allowCredentials: [{
+ id: newCredential.rawId,
+ type: 'public-key'
+ }],
+ extensions: {
+ prf: {
+ eval: {
+ first: salt,
+ },
+ },
+ },
+ }
+ });
+
+ extensionsResult = existingCredential.getClientExtensionResults();
}
- if (!extensionsResult.prf || !extensionsResult.prf.results || !extensionsResult.prf.results.first) {
- throw new Error("Failed to derive key using PRF extension");
+ if (!extensionsResult.prf.results || !extensionsResult.prf.results.first) {
+ return { error: "PRF_DERIVATION_FAILED" };
}
const derivedKey = extensionsResult.prf.results.first;
@@ -266,7 +302,7 @@ async function createWebAuthnCredentialAndDeriveKey(username) {
};
} catch (createError) {
console.error("Error creating new WebAuthn credential:", createError);
- return null;
+ return { error: "WEBAUTHN_CREATE_ERROR", message: createError.message };
}
}