Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Rewrite webauthn implementation to use PRF (#269)
Leendert de Borste7e66a628585
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razorindex 8c59d0267..ffb9d47fc 100644--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor@@ -62,7 +62,7 @@Console.WriteLine($"webauthCredentialDerivedKey.DerivedKey: {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.DerivedKey, webauthCredentialDerivedKey.CredentialId);+ await AuthService.SetWebAuthnEnabledAsync(true, webauthCredentialDerivedKey.CredentialId, webauthCredentialDerivedKey.Salt, webauthCredentialDerivedKey.DerivedKey);await LoadData();}@@ -73,7 +73,7 @@public async Task DisableWebAuthn(){// Set local storage var to indicate that WebAuthn is disabled and we should not try to use it to unlock the vault.- await AuthService.SetWebAuthnEnabledAsync(false, string.Empty, string.Empty);+ await AuthService.SetWebAuthnEnabledAsync(false, string.Empty, string.Empty, string.Empty);await LoadData();}diff --git a/src/AliasVault.Client/Services/Auth/AuthService.cs b/src/AliasVault.Client/Services/Auth/AuthService.csindex b9d83815b..658d43490 100644--- a/src/AliasVault.Client/Services/Auth/AuthService.cs+++ b/src/AliasVault.Client/Services/Auth/AuthService.cs@@ -171,12 +171,13 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca{var encryptedEncryptionKey = await localStorage.GetItemAsStringAsync("webAuthnEncryptedEncryptionKey");var webauthnCredentialId = await localStorage.GetItemAsStringAsync("webAuthnCredentialId");- if (string.IsNullOrEmpty(encryptedEncryptionKey) || string.IsNullOrEmpty(webauthnCredentialId))+ 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.");}- var webauthnCredentialDerivedKey = await jsInteropService.GetWebAuthnCredentialDerivedKey(username, webauthnCredentialId);+ var webauthnCredentialDerivedKey = await jsInteropService.GetWebAuthnCredentialDerivedKey(webauthnCredentialId, webauthnSalt);if (webauthnCredentialDerivedKey is null){throw new InvalidOperationException("WebAuthn credential derived key is not set.");@@ -186,7 +187,7 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService locaConsole.WriteLine($"encryptedEncryptionKey: {encryptedEncryptionKey}");// Decrypt the encrypted encryption key with the WebAuthn derived key.- var decryptedString = await jsInteropService.SymmetricDecrypt(encryptedEncryptionKey, webauthnCredentialDerivedKey.Value.DerivedKey);+ var decryptedString = await jsInteropService.SymmetricDecrypt(encryptedEncryptionKey, webauthnCredentialDerivedKey);Console.WriteLine($"decryptedString: {decryptedString}");@@ -198,17 +199,18 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca/// If set to false, the user will be prompted to enter the master password instead./// </summary>/// <param name="enabled">True if WebAuthn is enabled, otherwise false.</param>- /// <param name="webauthCredentialDerivedKey">WebAuthn credential derived key.</param>/// <param name="webauthCredentialId">WebAuthn credential ID.</param>+ /// <param name="webauthSalt">WebAuthn salt.</param>+ /// <param name="webauthCredentialDerivedKey">WebAuthn credential derived key.</param>/// <returns>Task.</returns>- public async Task SetWebAuthnEnabledAsync(bool enabled, string? webauthCredentialDerivedKey, string? webauthCredentialId)+ public async Task SetWebAuthnEnabledAsync(bool enabled, string? webauthCredentialId, string? webauthSalt, string? webauthCredentialDerivedKey){await localStorage.SetItemAsStringAsync("webAuthnEnabled", enabled.ToString().ToLower());Console.WriteLine($"Set webAuthnEnabled to {enabled}");// Encrypt the current encryption key with the webauthn derived key and store it in local storage.- if (enabled && !string.IsNullOrEmpty(webauthCredentialDerivedKey) && !string.IsNullOrEmpty(webauthCredentialId))+ if (enabled && !string.IsNullOrEmpty(webauthCredentialId) && !string.IsNullOrEmpty(webauthSalt) && !string.IsNullOrEmpty(webauthCredentialDerivedKey)){Console.WriteLine("Encrypting encryption key with webauthn derived key");var encryptionKeyBase64 = Convert.ToBase64String(GetEncryptionKey());@@ -216,8 +218,17 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService locavar encryptedEncryptionKey = await jsInteropService.SymmetricEncrypt(encryptionKeyBase64, webauthCredentialDerivedKey);Console.WriteLine($"encryptedEncryptionKey: {encryptedEncryptionKey}");Console.WriteLine($"webauthCredentialDerivedKey: {webauthCredentialDerivedKey}");- await localStorage.SetItemAsStringAsync("webAuthnEncryptedEncryptionKey", encryptedEncryptionKey);await localStorage.SetItemAsStringAsync("webAuthnCredentialId", webauthCredentialId);+ await localStorage.SetItemAsStringAsync("webAuthnSalt", webauthSalt);+ await localStorage.SetItemAsStringAsync("webAuthnEncryptedEncryptionKey", encryptedEncryptionKey);+ }+ else+ {+ // Clear the WebAuthn credential ID, salt and derived key if WebAuthn is disabled.+ await localStorage.RemoveItemAsync("webAuthnCredentialId");+ await localStorage.RemoveItemAsync("webAuthnSalt");+ await localStorage.RemoveItemAsync("webAuthnCredentialDerivedKey");+ await localStorage.RemoveItemAsync("webAuthnEncryptedEncryptionKey");}}@@ -309,7 +320,7 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService locaprivate async Task RevokeTokenAsync(){// Remove webauthn enabled flag.- await SetWebAuthnEnabledAsync(false, null, null);+ await SetWebAuthnEnabledAsync(false, null, null, null);var tokenInput = new TokenModel{diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.csindex dc4b46951..54875b497 100644--- a/src/AliasVault.Client/Services/JsInteropService.cs+++ b/src/AliasVault.Client/Services/JsInteropService.cs@@ -160,18 +160,16 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)/// <summary>/// Gets the WebAuthn credential derived key used to encrypt or decrypt the persisted vault encryption key./// </summary>- /// <param name="username">The username for the credential.</param>/// <param name="credentialId">The credential ID to use.</param>- /// <returns>A tuple containing the credential ID and the derived key.</returns>+ /// <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>- public async Task<(string CredentialId, string DerivedKey)?> GetWebAuthnCredentialDerivedKey(string username, string credentialId)+ public async Task<string> GetWebAuthnCredentialDerivedKey(string credentialId, string salt){try{- var result = await jsRuntime.InvokeAsync<WebAuthnResult>("getWebAuthnCredentialAndDeriveKey", username, credentialId);- return result != null- ? (result.CredentialId, result.DerivedKey)- : throw new CryptographicException("Failed to get WebAuthn credential");+ var derivedKey = await jsRuntime.InvokeAsync<string?>("getWebAuthnCredentialAndDeriveKey", credentialId, salt);+ return derivedKey ?? throw new CryptographicException("Failed to get WebAuthn credential");}catch (JSException ex){@@ -184,16 +182,16 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)/// Gets or creates the WebAuthn credential derived key used to encrypt or decrypt the persisted vault encryption key./// </summary>/// <param name="username">The username for the credential.</param>- /// <returns>A tuple containing the credential ID and the derived key.</returns>+ /// <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>- public async Task<(string CredentialId, string DerivedKey)> CreateWebAuthnCredentialDerivedKey(string username)+ 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.DerivedKey)+ ? (result.CredentialId, result.Salt, result.DerivedKey): throw new CryptographicException("Failed to get or create WebAuthn credential");}catch (JSException ex)@@ -213,6 +211,11 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)/// </summary>public string CredentialId { get; set; } = null!;+ /// <summary>+ /// Gets or sets the salt as a base64 string.+ /// </summary>+ public string Salt { get; set; } = null!;+/// <summary>/// Gets or sets the derived key as a base64 string./// </summary>diff --git a/src/AliasVault.Client/wwwroot/js/utilities.js b/src/AliasVault.Client/wwwroot/js/utilities.jsindex fc3157f46..369b260fb 100644--- a/src/AliasVault.Client/wwwroot/js/utilities.js+++ b/src/AliasVault.Client/wwwroot/js/utilities.js@@ -122,14 +122,12 @@ window.initTopMenu = function() {* @param id*/function generateQrCode(id) {- console.log(`Generating QR code for element with id "${id}".`);// Find the element by idconst element = document.getElementById(id);// Check if the element existsif (!element) {- console.log(`Element with id "${id}" not found. QR code generation aborted.`);- return; // Silently fail+ return;}// Get the data-url attribute@@ -137,8 +135,7 @@ function generateQrCode(id) {// Check if data-url existsif (!dataUrl) {- console.log(`No data-url attribute found on element with id "${id}". QR code generation aborted.`);- return; // Silently fail+ return;}// Create a container for the QR code@@ -160,120 +157,116 @@ function generateQrCode(id) {/*** Gets or creates a WebAuthn credential and derives a key from it.- * @param {string} username - The username to associate with the credential.* @param {string} credentialIdToUse - The credentialId to use if one exists.- * * @returns {Promise<{credentialId: string, derivedKey: string} | null>} An object containing the credentialId and derived key, or null if unsuccessful. */-async function getWebAuthnCredentialAndDeriveKey(username, credentialIdToUse = null) {+ * @param {string} salt - The salt to use when deriving the key.+ * @returns {Promise<string>} The derived key as a base64 string.+ */+async function getWebAuthnCredentialAndDeriveKey(credentialIdToUse, salt) {const rpId = window.location.hostname;const challenge = crypto.getRandomValues(new Uint8Array(32));- const userId = new TextEncoder().encode(username);-- let credentialId;-- let allowCredentials = [];- if (credentialIdToUse) {- allowCredentials = [{- id: Uint8Array.from(atob(credentialIdToUse), c => c.charCodeAt(0)),- type: 'public-key'- }];- }try {// Try to get an existing credential- const credential = await navigator.credentials.get({+ const existingCredential = await navigator.credentials.get({publicKey: {challenge,rpId,userVerification: "preferred",- allowCredentials+ allowCredentials: [{+ id: Uint8Array.from(atob(credentialIdToUse), c => c.charCodeAt(0)),+ type: 'public-key'+ }],+ extensions: {+ prf: {+ eval: {+ first: Uint8Array.from(atob(salt), c => c.charCodeAt(0)),+ },+ },+ },}});- credentialId = new Uint8Array(credential.rawId);- } catch (error) {- console.log("No existing credential found:", error);- }- if (!credentialId) {- console.error("No credentialId found.");+ // 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");+ }++ if (!extensionsResult.prf || !extensionsResult.prf.results || !extensionsResult.prf.results.first) {+ throw new Error("Failed to derive key using PRF extension");+ }++ const derivedKey = extensionsResult.prf.results.first;+ return btoa(String.fromCharCode.apply(null, new Uint8Array(derivedKey)));+ } catch (error) {+ console.log("No existing WebAuthn credential found:", error);return null;}-- return deriveWebAuthnKey(credentialId, userId);}/*** Creates a WebAuthn credential and derives a key from it.* @param {string} username - The username to associate with the credential.- * * @returns {Promise<{credentialId: string, derivedKey: string} | null>} An object containing the credentialId and derived key, or null if unsuccessful. */+ * * @returns {Promise<{credentialId: string, salt: string, derivedKey: string} | null>} An object containing the credentialId, salt and derived key, or null if unsuccessful.+ */async function createWebAuthnCredentialAndDeriveKey(username) {const rpId = window.location.hostname;const challenge = crypto.getRandomValues(new Uint8Array(32));- const userId = new TextEncoder().encode(username);+ const salt = crypto.getRandomValues(new Uint8Array(32));// Create a new credentialtry {const newCredential = await navigator.credentials.create({publicKey: {challenge,- rp: {name: "AliasVault", id: rpId},- user: {id: userId, name: username, displayName: username},- pubKeyCredParams: [{alg: -7, type: "public-key"}],+ rp: {+ name: "AliasVault",+ id: rpId},+ user: {+ id: crypto.getRandomValues(new Uint8Array(32)),+ name: username,+ displayName: username+ },+ pubKeyCredParams: [{+ alg: -7,+ type: "public-key"+ }],authenticatorSelection: {authenticatorAttachment: "platform",userVerification: "preferred",residentKey: "required"- }+ },+ extensions: {+ prf: {+ eval: {+ first: salt,+ },+ },+ },}});- credentialId = new Uint8Array(newCredential.rawId);- } catch (createError) {- console.error("Error creating new credential:", createError);- return null;- }- if (!credentialId) {- console.error("No credentialId found.");+ // 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");+ }++ if (!extensionsResult.prf || !extensionsResult.prf.results || !extensionsResult.prf.results.first) {+ throw new Error("Failed to derive key using PRF extension");+ }++ const derivedKey = extensionsResult.prf.results.first;+ const credentialId = new Uint8Array(newCredential.rawId);++ return {+ CredentialId: btoa(String.fromCharCode.apply(null, credentialId)),+ Salt: btoa(String.fromCharCode.apply(null, salt)),+ DerivedKey: btoa(String.fromCharCode.apply(null, new Uint8Array(derivedKey))),+ };+ } catch (createError) {+ console.error("Error creating new WebAuthn credential:", createError);return null;}-- return deriveWebAuthnKey(credentialId, userId);}-/**- * Derives a key from a WebAuthn credentialId.- * @param credentialId- * @param userId- * @returns {{CredentialId: string, DerivedKey: string}}- */-async function deriveWebAuthnKey(credentialId, userId) {- // TODO: this uses the credentialId which is not actually the secure private part?-- // Derive a key from the credentialId- const keyMaterial = await crypto.subtle.importKey(- "raw",- credentialId,- { name: "PBKDF2" },- false,- ["deriveBits"]- );-- const derivedBits = await crypto.subtle.deriveBits(- {- name: "PBKDF2",- salt: userId,- iterations: 100000,- hash: "SHA-256"- },- keyMaterial,- 256 // 256 bits- );-- // Convert to base64- const derivedKey = btoa(String.fromCharCode.apply(null, new Uint8Array(derivedBits)));- const credentialIdBase64 = btoa(String.fromCharCode.apply(null, new Uint8Array(credentialId)));-- console.log(`credentialId: ${credentialId}`);- console.log(`credentialIdBase64: ${credentialIdBase64}`);-- return { CredentialId: credentialIdBase64, DerivedKey: derivedKey };-}