Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Improve login fake response structure to reduce username enumeration (#2469)
Leendert de Borstf18430c7b5b7
diff --git a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/AuthController.csindex f0864d7fd..296e3490d 100644--- a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs@@ -136,12 +136,12 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMvar user = await userManager.FindByNameAsync(model.Username);- // If user doesn't exist, generate or retrieve fake data to prevent user enumeration attacks.+ // A non-existent user answers like an upgraded account (as v2 does), to prevent user enumeration attacks.if (user == null){// Log the attempt internallyawait authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);- return FakeLoginResponse(model);+ return UpgradeRequiredResponse();}// Check if the account is locked out.@@ -165,7 +165,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// A v1 client can only answer a legacy verifier; for an upgraded one it would report a wrong password.if (latestVaultEncryptionSettings.EncryptionType != Defaults.LegacyEncryptionType){- return StatusCode(426, new { error = "UPGRADE_REQUIRED", message = "Your client is out of date. Please update to access this vault." });+ return UpgradeRequiredResponse();}var srpIdentity = AuthHelper.GetSrpIdentity(user);@@ -979,40 +979,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}/// <summary>- /// Generate a fake login response for a user that does not exist to prevent user enumeration attacks.+ /// The response for an account a v1 client cannot sign in to./// </summary>- /// <param name="model">The login initiate request model.</param>/// <returns>IActionResult.</returns>- private OkObjectResult FakeLoginResponse(LoginInitiateRequest model)- {- // Generate a cache key for fake data- var fakeDataCacheKey = AuthHelper.CachePrefixFakeData + model.Username;-- // Try to get cached fake data first- if (!cache.TryGetValue(fakeDataCacheKey, out (string Salt, string Verifier, string SrpIdentity) fakeData))- {- // Generate new fake data if not cached- var client = new SrpClient();- var fakeSalt = client.GenerateSalt();- var fakePrivateKey = client.DerivePrivateKey(fakeSalt, model.Username, "fakePassword");- var fakeVerifier = client.DeriveVerifier(fakePrivateKey);-- // A fake identity is a random GUID, like a real one, so the response does not reveal whether the account exists.- fakeData = (fakeSalt, fakeVerifier, Guid.NewGuid().ToString());-- // Cache the fake data for 4 hours- cache.Set(fakeDataCacheKey, fakeData, TimeSpan.FromHours(4));- }-- // Always generate a new ephemeral for the fake data, as this is also done for existing users.- var fakeEphemeral = Srp.GenerateEphemeralServer(fakeData.Verifier);-- // Return the same response format as for real users- return Ok(new LoginInitiateResponse(- fakeData.Salt,- fakeEphemeral.Public,- Defaults.LegacyEncryptionType,- Defaults.EncryptionSettings,- fakeData.SrpIdentity));- }+ private ObjectResult UpgradeRequiredResponse() => StatusCode(426, new { error = "UPGRADE_REQUIRED", message = "Your client is out of date. Please update to access this vault." });}diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex 6bdc6d906..3c38df3af 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -16,6 +16,7 @@ using AliasServerDb;using AliasServerDb.Retention;using AliasVault.Api.Headers;using AliasVault.Api.Helpers;+using AliasVault.Api.Models;using AliasVault.Auth;using AliasVault.Auth.IpAddress;using AliasVault.Cryptography;@@ -47,14 +48,12 @@ using SecureRemotePassword;/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>/// <param name="config">Config instance.</param>/// <param name="settingsService">ServerSettingsService instance.</param>-/// <param name="registrationRateLimitService">RegistrationRateLimitService instance.</param>/// <param name="ipBlockListService">IpBlockListService instance.</param>-/// <param name="mobileLoginRateLimitService">MobileLoginRateLimitService instance.</param>/// <param name="registrationInviteService">RegistrationInviteService instance.</param>[Route("v{version:apiVersion}/[controller]")][ApiController][ApiVersion("2")]-public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService, RegistrationInviteService registrationInviteService) : ControllerBase+public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, IpBlockListService ipBlockListService, RegistrationInviteService registrationInviteService) : ControllerBase{/// <summary>/// Access token validity in minutes.@@ -103,7 +102,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM{// Log the attempt internallyawait authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);- return FakeLoginResponse(model);+ return FakeLoginResponse(FakeLoginHelper.Create(model.Username));}// Check if the account is locked out.@@ -401,9 +400,10 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// Register endpoint used to register a new user./// </summary>/// <param name="model">Register request model.</param>+ /// <param name="registrationRateLimitService">RegistrationRateLimitService instance.</param>/// <returns>IActionResult.</returns>[HttpPost("register")]- public async Task<IActionResult> Register([FromBody] RegisterRequest model)+ public async Task<IActionResult> Register([FromBody] RegisterRequest model, [FromServices] RegistrationRateLimitService registrationRateLimitService){// Without public registration only an invite code holder may register. The invite use is taken right before the account is created.var requiresInvite = !config.PublicRegistrationEnabled;@@ -806,10 +806,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// Initiates a mobile login request. The client shows the returned request id as a QR code and keeps the poll secret to itself./// </summary>/// <param name="model">The mobile login initiate request model.</param>+ /// <param name="mobileLoginRateLimitService">MobileLoginRateLimitService instance.</param>/// <returns>IActionResult.</returns>[HttpPost("mobile-login/initiate")][AllowAnonymous]- public async Task<IActionResult> InitiateMobileLogin([FromBody] MobileLoginInitiateRequest model)+ public async Task<IActionResult> InitiateMobileLogin([FromBody] MobileLoginInitiateRequest model, [FromServices] MobileLoginRateLimitService mobileLoginRateLimitService){// Reject invalid public key structure.if (!MobileLoginPublicKeyValidator.IsValid(model.ClientPublicKey))@@ -1560,40 +1561,14 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}/// <summary>- /// Generate a fake login response for a user that does not exist to prevent user enumeration attacks.+ /// Generate the login response of a user that does not exist, from its fake profile, to prevent user enumeration attacks./// </summary>- /// <param name="model">The login initiate request model.</param>+ /// <param name="profile">The fake login profile of the username.</param>/// <returns>IActionResult.</returns>- private OkObjectResult FakeLoginResponse(LoginInitiateRequest model)+ private OkObjectResult FakeLoginResponse(FakeLoginProfile profile){- // Generate a cache key for fake data- var fakeDataCacheKey = AuthHelper.CachePrefixFakeData + model.Username;-- // Try to get cached fake data first- if (!cache.TryGetValue(fakeDataCacheKey, out (string Salt, string Verifier, string SrpIdentity) fakeData))- {- // Generate new fake data if not cached- var client = new SrpClient();- var fakeSalt = client.GenerateSalt();- var fakePrivateKey = client.DerivePrivateKey(fakeSalt, model.Username, "fakePassword");- var fakeVerifier = client.DeriveVerifier(fakePrivateKey);-- // A fake identity is a random GUID, like a real one, so the response does not reveal whether the account exists.- fakeData = (fakeSalt, fakeVerifier, Guid.NewGuid().ToString());-- // Cache the fake data for 4 hours- cache.Set(fakeDataCacheKey, fakeData, TimeSpan.FromHours(4));- }-- // Always generate a new ephemeral for the fake data, as this is also done for existing users.- var fakeEphemeral = Srp.GenerateEphemeralServer(fakeData.Verifier);-- // Return the same response format as for real users- return Ok(new LoginInitiateResponse(- fakeData.Salt,- fakeEphemeral.Public,- Defaults.EncryptionType,- Defaults.EncryptionSettings,- fakeData.SrpIdentity));+ // Always generate a new ephemeral, as this is also done for existing users.+ var fakeEphemeral = Srp.GenerateEphemeralServer(profile.Verifier);+ return Ok(new LoginInitiateResponse(profile.Salt, fakeEphemeral.Public, Defaults.EncryptionType, Defaults.EncryptionSettings, profile.SrpIdentity));}}diff --git a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs b/apps/server/AliasVault.Api/Helpers/AuthHelper.csindex 9a2bbc1b2..c576a22fb 100644--- a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs@@ -25,11 +25,6 @@ public static class AuthHelper/// </summary>public static readonly string CachePrefixEphemeral = "LoginEphemeral_";- /// <summary>- /// Cache prefix for storing fake data for non-existent users.- /// </summary>- public static readonly string CachePrefixFakeData = "FakeData_";-/// <summary>/// Gets the SRP identity to use for a user, falling back to the lowercase username for accounts that were created/// before SRP identities existed (pre-0.26.0). TODO: remove this fallback in a future version.diff --git a/apps/server/AliasVault.Api/Helpers/FakeLoginHelper.cs b/apps/server/AliasVault.Api/Helpers/FakeLoginHelper.csnew file mode 100644index 000000000..24f546c66--- /dev/null+++ b/apps/server/AliasVault.Api/Helpers/FakeLoginHelper.cs@@ -0,0 +1,54 @@+//-----------------------------------------------------------------------+// <copyright file="FakeLoginHelper.cs" company="aliasvault">+// Copyright (c) aliasvault. All rights reserved.+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.Api.Helpers;++using System.Security.Cryptography;+using System.Text;+using AliasVault.Api.Models;+using AliasVault.Shared.Server.Utilities;+using SecureRemotePassword;++/// <summary>+/// Creates the SRP values for a username that does not exist, derived from an HMAC of the username under a server+/// secret, so they are the same on every request, API instance and restart, like those of a real account.+/// </summary>+public static class FakeLoginHelper+{+ private static readonly Lazy<byte[]> ProfileKey = new(() => HKDF.DeriveKey(HashAlgorithmName.SHA256, Encoding.UTF8.GetBytes(SecretReader.GetJwtKey()), 32, info: Encoding.UTF8.GetBytes("AliasVault fake login profile")));++ /// <summary>+ /// Gets the fake login profile for a username that does not exist.+ /// </summary>+ /// <param name="username">The username as the client sent it.</param>+ /// <returns>The fake login profile.</returns>+ public static FakeLoginProfile Create(string username) => Create(ProfileKey.Value, username);++ /// <summary>+ /// Derives the fake login profile of a username from a key.+ /// </summary>+ /// <param name="key">The secret key.</param>+ /// <param name="username">The username as the client sent it.</param>+ /// <returns>The fake login profile.</returns>+ public static FakeLoginProfile Create(byte[] key, string username)+ {+ // Normalized like the username lookup, so usernames that resolve to the same account get the same profile.+ var digest = HMACSHA512.HashData(key, Encoding.UTF8.GetBytes(username.ToUpperInvariant()));++ // Uppercase hex and a lowercase version 4 GUID, like the salt and SRP identity current clients create.+ var salt = Convert.ToHexString(digest, 0, 32);+ var identityBytes = digest.AsSpan(32, 16).ToArray();+ identityBytes[6] = (byte)((identityBytes[6] & 0x0F) | 0x40);+ identityBytes[8] = (byte)((identityBytes[8] & 0x3F) | 0x80);+ var srpIdentity = new Guid(identityBytes, bigEndian: true).ToString();++ var client = new SrpClient();+ var verifier = client.DeriveVerifier(client.DerivePrivateKey(salt, srpIdentity, Convert.ToHexString(digest, 48, 16)));++ return new FakeLoginProfile(salt, verifier, srpIdentity);+ }+}diff --git a/apps/server/AliasVault.Api/Models/FakeLoginProfile.cs b/apps/server/AliasVault.Api/Models/FakeLoginProfile.csnew file mode 100644index 000000000..e1212a847--- /dev/null+++ b/apps/server/AliasVault.Api/Models/FakeLoginProfile.cs@@ -0,0 +1,16 @@+//-----------------------------------------------------------------------+// <copyright file="FakeLoginProfile.cs" company="aliasvault">+// Copyright (c) aliasvault. All rights reserved.+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.Api.Models;++/// <summary>+/// The SRP values a non-existent username answers with, the same on every request.+/// </summary>+/// <param name="Salt">The SRP salt.</param>+/// <param name="Verifier">The SRP verifier the server ephemeral is created from.</param>+/// <param name="SrpIdentity">The SRP identity.</param>+public sealed record FakeLoginProfile(string Salt, string Verifier, string SrpIdentity);