Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add max length for mobile login requests and add rate limiting (#2332)
Leendert de Borst1435e5e3205f
diff --git a/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor b/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razorindex 5ab79a971..716303d9b 100644--- a/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor+++ b/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor@@ -37,6 +37,11 @@<input type="number" @bind="Settings.MaxRegistrationsPerIpPer24Hours" id="maxRegistrationsPerIp" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500"><p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Maximum number of new account registrations allowed from a single IP address (/24 range) within a 24 hour period. Set to 0 to disable rate limiting. Recommended: 5-10 for most deployments.</p></div>+ <div>+ <label for="maxMobileLoginRequestsPerIp" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Max Mobile Login Requests per IP per Minute</label>+ <input type="number" @bind="Settings.MaxMobileLoginRequestsPerIpPerMinute" id="maxMobileLoginRequestsPerIp" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">+ <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Maximum number of QR code mobile login requests that can be started from a single IP address (/24 range) within one minute. Set to 0 to disable rate limiting. Recommended: 10 for most deployments.</p>+ </div></div></div>diff --git a/apps/server/AliasVault.Api/Controllers/AuthController.cs b/apps/server/AliasVault.Api/Controllers/AuthController.csindex abed6fff2..9e65abc86 100644--- a/apps/server/AliasVault.Api/Controllers/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/AuthController.cs@@ -49,10 +49,11 @@ using SecureRemotePassword;/// <param name="settingsService">ServerSettingsService instance.</param>/// <param name="registrationRateLimitService">RegistrationRateLimitService instance.</param>/// <param name="ipBlockListService">IpBlockListService instance.</param>+/// <param name="mobileLoginRateLimitService">MobileLoginRateLimitService instance.</param>[Route("v{version:apiVersion}/[controller]")][ApiController][ApiVersion("1")]-public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService) : ControllerBase+public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService) : ControllerBase{/// <summary>/// Timeout in minutes for mobile login requests. Clients use 2 minutes for countdown, we use 3 here to give a bit of extra buffer time.@@ -649,7 +650,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM[AllowAnonymous]public async Task<IActionResult> InitiateMobileLogin([FromBody] MobileLoginInitiateRequest model){- await using var context = await dbContextFactory.CreateDbContextAsync();+ // Reject invalid public key structure.+ if (!MobileLoginPublicKeyValidator.IsValid(model.ClientPublicKey))+ {+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_INVALID_PUBLIC_KEY, 400));+ }// Check the IP blocklist.if (await ipBlockListService.IsBlockedForLoginAsync(IpAddressUtility.GetRawIpAddressFromContext(HttpContext)))@@ -658,6 +663,17 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400));}+ // Check IP-based mobile login rate limit.+ var settings = await settingsService.GetAllSettingsAsync();+ var ipAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);+ if (await mobileLoginRateLimitService.IsRateLimitExceededAsync(ipAddress, settings.MaxMobileLoginRequestsPerIpPerMinute))+ {+ await authLoggingService.LogAuthEventFailAsync("n/a", AuthEventType.MobileLogin, AuthFailureReason.MobileLoginRateLimitExceeded);+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_RATE_LIMIT_EXCEEDED, 429));+ }++ await using var context = await dbContextFactory.CreateDbContextAsync();+// Generate a unique request IDvar requestId = Guid.NewGuid().ToString("N");@@ -667,7 +683,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMId = requestId,ClientPublicKey = model.ClientPublicKey,CreatedAt = timeProvider.UtcNow,- ClientIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled),+ ClientIpAddress = ipAddress,};context.MobileLoginRequests.Add(loginRequest);diff --git a/apps/server/AliasVault.Api/Helpers/MobileLoginPublicKeyValidator.cs b/apps/server/AliasVault.Api/Helpers/MobileLoginPublicKeyValidator.csnew file mode 100644index 000000000..2d9908f3a--- /dev/null+++ b/apps/server/AliasVault.Api/Helpers/MobileLoginPublicKeyValidator.cs@@ -0,0 +1,129 @@+//-----------------------------------------------------------------------+// <copyright file="MobileLoginPublicKeyValidator.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.Buffers.Text;+using System.Text.Json;++/// <summary>+/// Validates the client public key supplied when initiating a mobile login request. Clients send the+/// RSA-OAEP public key as a JSON serialized JWK, so anything that is not a well-formed RSA public JWK+/// of an accepted key size is rejected before it is persisted.+/// </summary>+public static class MobileLoginPublicKeyValidator+{+ /// <summary>+ /// Maximum accepted length for the serialized JWK. Current clients generate RSA-2048 keys, which are +/- 500 characters long.+ /// </summary>+ public const int MaxLength = 2048;++ /// <summary>+ /// Smallest accepted modulus in bytes (RSA-2048), which is what all current clients generate.+ /// </summary>+ private const int MinModulusBytes = 256;++ /// <summary>+ /// Largest accepted modulus in bytes (RSA-4096), leaving room for a future key size increase.+ /// </summary>+ private const int MaxModulusBytes = 512;++ /// <summary>+ /// Determines whether the supplied value is a well-formed RSA public JWK that we accept.+ /// </summary>+ /// <param name="publicKey">The raw value as supplied by the client.</param>+ /// <returns>True when the value is acceptable, false otherwise.</returns>+ public static bool IsValid(string? publicKey)+ {+ // Bound the input before parsing it so oversized payloads stay cheap to reject.+ if (string.IsNullOrEmpty(publicKey) || publicKey.Length > MaxLength)+ {+ return false;+ }++ try+ {+ using var document = JsonDocument.Parse(publicKey);+ var root = document.RootElement;++ if (root.ValueKind != JsonValueKind.Object)+ {+ return false;+ }++ // The mobile login handshake only uses RSA keys.+ if (!TryGetNonEmptyString(root, "kty", out var keyType) || keyType != "RSA")+ {+ return false;+ }++ // A public JWK must not carry private key material.+ if (root.TryGetProperty("d", out _))+ {+ return false;+ }++ // The public exponent must be present and base64url decodable.+ if (!TryGetNonEmptyString(root, "e", out var exponent) || GetBase64UrlByteLength(exponent) <= 0)+ {+ return false;+ }++ // The modulus determines the key size, which must fall within the accepted range.+ if (!TryGetNonEmptyString(root, "n", out var modulus))+ {+ return false;+ }++ return GetBase64UrlByteLength(modulus) is >= MinModulusBytes and <= MaxModulusBytes;+ }+ catch (JsonException)+ {+ return false;+ }+ }++ /// <summary>+ /// Reads a JWK member that is required to be a non-empty JSON string.+ /// </summary>+ /// <param name="root">The JWK object.</param>+ /// <param name="name">The member name to read.</param>+ /// <param name="value">The member value when present.</param>+ /// <returns>True when the member exists and holds a non-empty string.</returns>+ private static bool TryGetNonEmptyString(JsonElement root, string name, out string value)+ {+ value = string.Empty;++ if (!root.TryGetProperty(name, out var element) || element.ValueKind != JsonValueKind.String)+ {+ return false;+ }++ value = element.GetString() ?? string.Empty;+ return value.Length > 0;+ }++ /// <summary>+ /// Returns the decoded byte length of a base64url encoded JWK member. Values that are not valid+ /// base64url, or that decode to more bytes than the largest key we accept, return -1.+ /// </summary>+ /// <param name="value">The base64url encoded value.</param>+ /// <returns>The decoded length in bytes, or -1 when the value is not acceptable.</returns>+ private static int GetBase64UrlByteLength(string value)+ {+ Span<byte> buffer = stackalloc byte[MaxModulusBytes + 4];++ try+ {+ return Base64Url.TryDecodeFromChars(value, buffer, out var bytesWritten) ? bytesWritten : -1;+ }+ catch (FormatException)+ {+ return -1;+ }+ }+}diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.csindex 9923ca071..219b3692b 100644--- a/apps/server/AliasVault.Api/Program.cs+++ b/apps/server/AliasVault.Api/Program.cs@@ -87,6 +87,7 @@ builder.Services.AddScoped<AuthLoggingService>();builder.Services.AddScoped<ServerSettingsService>();builder.Services.AddScoped<RegistrationRateLimitService>();builder.Services.AddScoped<IpBlockListService>();+builder.Services.AddScoped<MobileLoginRateLimitService>();builder.Services.AddSingleton<FaviconRateLimitService>();builder.Services.AddScoped<RateLimitService>();builder.Services.AddHttpContextAccessor();diff --git a/apps/server/Databases/AliasServerDb/AuthLog.cs b/apps/server/Databases/AliasServerDb/AuthLog.csindex c69367b38..fa2589f68 100644--- a/apps/server/Databases/AliasServerDb/AuthLog.cs+++ b/apps/server/Databases/AliasServerDb/AuthLog.cs@@ -62,6 +62,12 @@ public enum AuthFailureReason/// </summary>IpBlocked = 9,+ /// <summary>+ /// Indicates that the mobile login attempt was blocked because the client created too many+ /// mobile login requests in a short period.+ /// </summary>+ MobileLoginRateLimitExceeded = 10,+/// <summary>/// Indicates that the failure reason was unknown./// </summary>diff --git a/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs b/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.csindex b7d7afd7f..e148217f3 100644--- a/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs+++ b/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs@@ -84,4 +84,10 @@ public class ServerSettingsModel/// Set to 0 to disable IP-based registration rate limiting./// </summary>public int MaxRegistrationsPerIpPer24Hours { get; set; } = 5;++ /// <summary>+ /// Gets or sets the maximum number of mobile login requests allowed per IP address (/24 range) within+ /// one minute. Defaults to 10. Set to 0 to disable mobile login rate limiting.+ /// </summary>+ public int MaxMobileLoginRequestsPerIpPerMinute { get; set; } = 10;}diff --git a/apps/server/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs b/apps/server/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.csindex af30f1bb8..121ba7f87 100644--- a/apps/server/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs+++ b/apps/server/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs@@ -196,6 +196,11 @@ public class ServerSettingsService(IAliasServerDbContextFactory dbContextFactorymodel.MaxRegistrationsPerIpPer24Hours = maxRegistrations;}+ if (int.TryParse(settings.GetValueOrDefault("MaxMobileLoginRequestsPerIpPerMinute"), out var maxMobileLoginRequests))+ {+ model.MaxMobileLoginRequestsPerIpPerMinute = maxMobileLoginRequests;+ }+if (int.TryParse(settings.GetValueOrDefault("MobileLoginLogRetentionDays"), out var mobileLoginDays)){model.MobileLoginLogRetentionDays = mobileLoginDays;@@ -225,6 +230,7 @@ public class ServerSettingsService(IAliasServerDbContextFactory dbContextFactoryawait SetSettingAsync("RefreshTokenLifetimeShort", model.RefreshTokenLifetimeShort.ToString());await SetSettingAsync("RefreshTokenLifetimeLong", model.RefreshTokenLifetimeLong.ToString());await SetSettingAsync("MaxRegistrationsPerIpPer24Hours", model.MaxRegistrationsPerIpPer24Hours.ToString());+ await SetSettingAsync("MaxMobileLoginRequestsPerIpPerMinute", model.MaxMobileLoginRequestsPerIpPerMinute.ToString());await SetSettingAsync("MobileLoginLogRetentionDays", model.MobileLoginLogRetentionDays.ToString());}}diff --git a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.csindex 4a0f7797a..a93652154 100644--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs@@ -153,4 +153,14 @@ public enum ApiErrorCode/// Generic user account registration failure./// </summary>REGISTRATION_FAILED,++ /// <summary>+ /// Mobile login request contains an invalid client public key.+ /// </summary>+ MOBILE_LOGIN_INVALID_PUBLIC_KEY,++ /// <summary>+ /// Too many mobile login requests were created from this client in a short period.+ /// </summary>+ MOBILE_LOGIN_RATE_LIMIT_EXCEEDED,}diff --git a/apps/server/Utilities/AliasVault.Auth/MobileLoginRateLimitService.cs b/apps/server/Utilities/AliasVault.Auth/MobileLoginRateLimitService.csnew file mode 100644index 000000000..462ade8e4--- /dev/null+++ b/apps/server/Utilities/AliasVault.Auth/MobileLoginRateLimitService.cs@@ -0,0 +1,72 @@+//-----------------------------------------------------------------------+// <copyright file="MobileLoginRateLimitService.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.Auth;++using System;+using System.Linq;+using System.Threading.Tasks;+using AliasServerDb;+using AliasVault.Auth.IpAddress;+using Microsoft.EntityFrameworkCore;++/// <summary>+/// Service for checking mobile login request rate limits based on IP address.+/// </summary>+/// <param name="dbContextFactory">IDbContextFactory instance.</param>+public class MobileLoginRateLimitService(IAliasServerDbContextFactory dbContextFactory)+{+ /// <summary>+ /// Length of the window the limit is enforced over.+ /// </summary>+ private const int WindowMinutes = 1;++ /// <summary>+ /// Checks if the given IP address has exceeded the mobile login request rate limit.+ /// </summary>+ /// <param name="ipAddress">The IP address to check (should be /24 anonymized).</param>+ /// <param name="maxRequestsPerIpPerMinute">Maximum number of mobile login requests allowed per IP per minute. Set to 0 to disable rate limiting.</param>+ /// <returns>True if the rate limit has been exceeded, false otherwise.</returns>+ public async Task<bool> IsRateLimitExceededAsync(string? ipAddress, int maxRequestsPerIpPerMinute)+ {+ if (string.IsNullOrEmpty(ipAddress))+ {+ return false;+ }++ // If rate limiting is disabled (0), allow the request.+ if (maxRequestsPerIpPerMinute <= 0)+ {+ return false;+ }++ // With IP logging disabled every request is stored under the same placeholder, so counting would+ // put all clients in one bucket and lock out everyone. Per-IP limiting needs recorded IPs.+ if (ipAddress == IpAddressUtility.AnonymizedIp)+ {+ return false;+ }++ var requestCount = await GetRequestCountAsync(ipAddress);++ return requestCount >= maxRequestsPerIpPerMinute;+ }++ /// <summary>+ /// Gets the current count of mobile login requests created from the given IP in the last minute.+ /// </summary>+ /// <param name="ipAddress">The IP address to check.</param>+ /// <returns>The count of mobile login requests.</returns>+ public async Task<int> GetRequestCountAsync(string ipAddress)+ {+ await using var dbContext = await dbContextFactory.CreateDbContextAsync();+ var cutoffTime = DateTime.UtcNow.AddMinutes(-WindowMinutes);+ var count = await dbContext.MobileLoginRequests.Where(x => x.ClientIpAddress == ipAddress && x.CreatedAt >= cutoffTime).CountAsync();++ return count;+ }+}