From 07831cff85410cbfe9b096e01c7d71697bed1314 Mon Sep 17 00:00:00 2001 From: Samer Salameh Date: Wed, 18 Nov 2026 09:07:23 +0300 Subject: [PATCH] Security hardening: login throttle, password rules, security headers, non-root container, QA port on loopback Co-Authored-By: Claude Sonnet 5.5 --- deploy/prod/apache-ntp.conf | 5 ++ deploy/qa/Dockerfile | 3 + deploy/qa/apache-ntpv2.conf | 5 ++ deploy/qa/docker-compose.yml | 2 +- .../ErrorHandling/GlobalExceptionHandler.cs | 1 + src/NTP.Api/Program.cs | 23 ++++++ src/NTP.Application/Auth/AuthService.cs | 23 +++++- src/NTP.Application/Auth/AuthValidators.cs | 6 +- src/NTP.Application/Auth/LoginThrottle.cs | 71 +++++++++++++++++++ src/NTP.Application/Common/Exceptions.cs | 3 + src/NTP.Application/DependencyInjection.cs | 2 + tests/NTP.Tests/LoginThrottleTests.cs | 54 ++++++++++++++ 12 files changed, 195 insertions(+), 3 deletions(-) create mode 100644 src/NTP.Application/Auth/LoginThrottle.cs create mode 100644 tests/NTP.Tests/LoginThrottleTests.cs diff --git a/deploy/prod/apache-ntp.conf b/deploy/prod/apache-ntp.conf index e206cc1..4ccc270 100644 --- a/deploy/prod/apache-ntp.conf +++ b/deploy/prod/apache-ntp.conf @@ -21,6 +21,11 @@ ProxyPreserveHost On RequestHeader set X-Forwarded-Proto "https" + # browser hardening (the API also sets these; Apache covers its own error pages) + Header always set Strict-Transport-Security "max-age=31536000" + Header always set X-Content-Type-Options "nosniff" + Header always set X-Frame-Options "DENY" + Header always set Referrer-Policy "same-origin" ProxyTimeout 120 ProxyPass / http://127.0.0.1:8081/ ProxyPassReverse / http://127.0.0.1:8081/ diff --git a/deploy/qa/Dockerfile b/deploy/qa/Dockerfile index 02f2a1d..55b2048 100644 --- a/deploy/qa/Dockerfile +++ b/deploy/qa/Dockerfile @@ -20,6 +20,9 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app COPY --from=api /app ./ COPY --from=web /web/dist ./wwwroot +# run as the image's built-in non-root user "app"; the API only writes to App_Data (QA attachments) and the mounted attachment folder +RUN mkdir -p /app/App_Data && chown -R app:app /app/App_Data +USER app ENV ASPNETCORE_URLS=http://+:8080 \ ASPNETCORE_FORWARDEDHEADERS_ENABLED=true \ TZ=Asia/Amman diff --git a/deploy/qa/apache-ntpv2.conf b/deploy/qa/apache-ntpv2.conf index 3679c6c..287caca 100644 --- a/deploy/qa/apache-ntpv2.conf +++ b/deploy/qa/apache-ntpv2.conf @@ -22,6 +22,11 @@ ProxyPreserveHost On RequestHeader set X-Forwarded-Proto "https" + # browser hardening (the API also sets these; Apache covers its own error pages) + Header always set Strict-Transport-Security "max-age=31536000" + Header always set X-Content-Type-Options "nosniff" + Header always set X-Frame-Options "DENY" + Header always set Referrer-Policy "same-origin" ProxyTimeout 120 ProxyPass / http://127.0.0.1:8081/ ProxyPassReverse / http://127.0.0.1:8081/ diff --git a/deploy/qa/docker-compose.yml b/deploy/qa/docker-compose.yml index 837635a..56f8b7e 100644 --- a/deploy/qa/docker-compose.yml +++ b/deploy/qa/docker-compose.yml @@ -13,4 +13,4 @@ services: ASPNETCORE_ENVIRONMENT: QA TZ: Asia/Amman ports: - - "0.0.0.0:8081:8080" + - "127.0.0.1:8081:8080" diff --git a/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs b/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs index dbd1b62..7dd3c54 100644 --- a/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs +++ b/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs @@ -62,6 +62,7 @@ internal sealed class GlobalExceptionHandler( .ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray())), ValidationException v => (400, "Validation failed", v.Message, null), // Business rules: Title/Detail carry the legacy (Arabic) user-facing message; "code" extension is stable. + TooManyAttemptsException tm => (429, tm.Message, tm.Message, null), AuthenticationFailedException af => (401, af.Message, af.Message, null), ForbiddenException fe => (403, fe.Message, fe.Message, null), BusinessException be => (422, be.Message, be.Message, null), diff --git a/src/NTP.Api/Program.cs b/src/NTP.Api/Program.cs index 60924bc..dbbf5ad 100644 --- a/src/NTP.Api/Program.cs +++ b/src/NTP.Api/Program.cs @@ -48,6 +48,29 @@ var app = builder.Build(); var oracle = app.Services.GetRequiredService>().Value; app.Logger.LogInformation("Oracle connection: {ConnectionString}", oracle.ToSafeString()); +// Browser hardening headers on every response (API and the web app it serves). The CSP fits the built web app: own scripts only, +// MUI inline styles, the Cairo font from Google Fonts, PDFs shown in a blob: iframe. Not applied in Development (Vite hot reload). +if (!app.Environment.IsDevelopment()) +{ + const string csp = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " + + "font-src 'self' data: https://fonts.gstatic.com; img-src 'self' data: blob:; connect-src 'self'; " + + "frame-src 'self' blob:; object-src 'self' blob:; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"; + app.Use(async (ctx, next) => + { + ctx.Response.OnStarting(() => + { + var h = ctx.Response.Headers; + h["X-Content-Type-Options"] = "nosniff"; + h["X-Frame-Options"] = "DENY"; + h["Referrer-Policy"] = "same-origin"; + h["Content-Security-Policy"] = csp; + if (ctx.Request.IsHttps) h["Strict-Transport-Security"] = "max-age=31536000"; // https is known from X-Forwarded-Proto + return Task.CompletedTask; + }); + await next(); + }); +} + app.UseCors("Frontend"); // first, so error responses also carry CORS headers app.UseExceptionHandler(); app.UseStatusCodePages(); diff --git a/src/NTP.Application/Auth/AuthService.cs b/src/NTP.Application/Auth/AuthService.cs index 73e08b9..e217ba9 100644 --- a/src/NTP.Application/Auth/AuthService.cs +++ b/src/NTP.Application/Auth/AuthService.cs @@ -22,8 +22,10 @@ public sealed class AuthService( ICurrentUser currentUser, IValidator loginValidator, IValidator changePasswordValidator, - IValidator languageValidator) : IAuthService + IValidator languageValidator, + LoginThrottle throttle) : IAuthService { + private const string TooManyAttemptsMessage = "محاولات دخول خاطئة كثيرة، يرجى المحاولة بعد {0} دقيقة"; // Legacy messages (kept verbatim). public const string InvalidLoginMessage = "معلومات الدخول خاطئة ... حاول مرة أخرى"; private const string NoActiveBoothMessage = "لا يمكنك الدخول, يرجى مراجعة رئيس الشفت"; @@ -43,6 +45,25 @@ public sealed class AuthService( { await loginValidator.ValidateAndThrowAsync(request, ct); + var throttleKey = request.UserName.Trim().ToLowerInvariant(); + if (throttle.BlockedFor(throttleKey, client.IpAddress) is { } wait) + throw new TooManyAttemptsException("TOO_MANY_ATTEMPTS", string.Format(TooManyAttemptsMessage, Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes)))); + + try + { + var result = await SignInAsync(request, client, ct); + throttle.RecordSuccess(throttleKey); + return result; + } + catch (AuthenticationFailedException ex) when (ex.Code == "INVALID_CREDENTIALS") + { + throttle.RecordFailure(throttleKey, client.IpAddress); + throw; + } + } + + private async Task SignInAsync(LoginRequest request, ClientInfo client, CancellationToken ct) + { var parts = request.UserName.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (parts.Length != 2) throw Invalid(); diff --git a/src/NTP.Application/Auth/AuthValidators.cs b/src/NTP.Application/Auth/AuthValidators.cs index 96b6349..c0a9989 100644 --- a/src/NTP.Application/Auth/AuthValidators.cs +++ b/src/NTP.Application/Auth/AuthValidators.cs @@ -16,7 +16,11 @@ public sealed class ChangePasswordRequestValidator : AbstractValidator x.OldPassword).NotEmpty().MaximumLength(200); - RuleFor(x => x.NewPassword).NotEmpty().MaximumLength(200); + // login keeps accepting every existing password; only a NEW password has to be reasonably strong + RuleFor(x => x.NewPassword).NotEmpty().MaximumLength(200) + .MinimumLength(8).WithMessage("كلمة السر يجب ألا تقل عن 8 خانات") + .Must(p => p is not null && p.Any(char.IsLetter) && p.Any(char.IsDigit)).WithMessage("كلمة السر يجب أن تحتوي على أحرف وأرقام") + .Must((r, p) => p != r.OldPassword).WithMessage("كلمة السر الجديدة يجب أن تختلف عن القديمة"); RuleFor(x => x.ConfirmNewPassword) .Equal(x => x.NewPassword).When(x => x.ConfirmNewPassword is not null) .WithMessage("كلمة السر الجديدة غير متطابقة"); diff --git a/src/NTP.Application/Auth/LoginThrottle.cs b/src/NTP.Application/Auth/LoginThrottle.cs new file mode 100644 index 0000000..c25ce31 --- /dev/null +++ b/src/NTP.Application/Auth/LoginThrottle.cs @@ -0,0 +1,71 @@ +using System.Collections.Concurrent; + +namespace NTP.Application.Auth; + +/// +/// Slows down password guessing: after failed sign-ins of one login (or from one address) +/// inside , further attempts are refused until the oldest failure leaves the window. A success clears the login. +/// In memory per API instance (one container in production). The login key does not depend on the client address, so a forged +/// X-Forwarded-For header cannot get around the per-login limit. +/// +public sealed class LoginThrottle(TimeProvider clock) +{ + public const int MaxPerLogin = 5; + public const int MaxPerIp = 30; + public static readonly TimeSpan Window = TimeSpan.FromMinutes(15); + + private readonly ConcurrentDictionary> _failures = new(StringComparer.OrdinalIgnoreCase); + + private static string LoginKey(string login) => "L:" + login; + private static string IpKey(string? ip) => "I:" + (ip ?? "?"); + + /// How long the caller must wait, or null when the attempt may proceed. + public TimeSpan? BlockedFor(string login, string? ip) => + Max(Remaining(LoginKey(login), MaxPerLogin), Remaining(IpKey(ip), MaxPerIp)); + + public void RecordFailure(string login, string? ip) + { + Add(LoginKey(login)); + Add(IpKey(ip)); + } + + public void RecordSuccess(string login) => _failures.TryRemove(LoginKey(login), out _); + + private TimeSpan? Remaining(string key, int max) + { + if (!_failures.TryGetValue(key, out var q)) return null; + lock (q) + { + Trim(q); + if (q.Count < max) return null; + return q.Peek() + Window - clock.GetUtcNow(); + } + } + + private void Add(string key) + { + var q = _failures.GetOrAdd(key, _ => new Queue()); + lock (q) + { + Trim(q); + q.Enqueue(clock.GetUtcNow()); + } + if (_failures.Count > 20_000) Sweep(); + } + + private void Trim(Queue q) + { + var limit = clock.GetUtcNow() - Window; + while (q.Count > 0 && q.Peek() <= limit) q.Dequeue(); + } + + private void Sweep() + { + foreach (var (key, q) in _failures) + { + lock (q) { Trim(q); if (q.Count == 0) _failures.TryRemove(key, out _); } + } + } + + private static TimeSpan? Max(TimeSpan? a, TimeSpan? b) => a is null ? b : b is null ? a : a > b ? a : b; +} diff --git a/src/NTP.Application/Common/Exceptions.cs b/src/NTP.Application/Common/Exceptions.cs index ba2e7b8..3a37c0b 100644 --- a/src/NTP.Application/Common/Exceptions.cs +++ b/src/NTP.Application/Common/Exceptions.cs @@ -20,5 +20,8 @@ public class BusinessException(string code, string message) : Exception(message) /// Credentials / account state rejected (HTTP 401). Same shape as . public sealed class AuthenticationFailedException(string code, string message) : BusinessException(code, message); +/// Too many failed sign-ins (HTTP 429). +public sealed class TooManyAttemptsException(string code, string message) : BusinessException(code, message); + /// Authenticated but the role/rules do not allow the action (HTTP 403). public sealed class ForbiddenException(string code, string message) : BusinessException(code, message); diff --git a/src/NTP.Application/DependencyInjection.cs b/src/NTP.Application/DependencyInjection.cs index 5ef395d..36f845f 100644 --- a/src/NTP.Application/DependencyInjection.cs +++ b/src/NTP.Application/DependencyInjection.cs @@ -15,6 +15,8 @@ public static class DependencyInjection var assembly = typeof(DependencyInjection).Assembly; services.AddValidatorsFromAssembly(assembly, includeInternalTypes: true); services.AddConventionalServices(assembly); + services.AddSingleton(TimeProvider.System); + services.AddSingleton(); return services; } } diff --git a/tests/NTP.Tests/LoginThrottleTests.cs b/tests/NTP.Tests/LoginThrottleTests.cs new file mode 100644 index 0000000..dab2793 --- /dev/null +++ b/tests/NTP.Tests/LoginThrottleTests.cs @@ -0,0 +1,54 @@ +using NTP.Application.Auth; + +namespace NTP.Tests; + +internal sealed class FakeTimeProvider(DateTimeOffset start) : TimeProvider +{ + private DateTimeOffset _now = start; + public override DateTimeOffset GetUtcNow() => _now; + public void Advance(TimeSpan by) => _now += by; +} + +public class LoginThrottleTests +{ + private static (LoginThrottle t, FakeTimeProvider clock) Make() + { + var clock = new FakeTimeProvider(new DateTimeOffset(2026, 1, 1, 8, 0, 0, TimeSpan.Zero)); + return (new LoginThrottle(clock), clock); + } + + [Fact] + public void Blocks_a_login_after_five_failures_and_frees_it_after_the_window() + { + var (t, clock) = Make(); + for (var i = 0; i < LoginThrottle.MaxPerLogin; i++) + { + Assert.Null(t.BlockedFor("aseza.1", $"10.0.0.{i}")); // different addresses: the limit follows the login + t.RecordFailure("aseza.1", $"10.0.0.{i}"); + } + Assert.NotNull(t.BlockedFor("aseza.1", "10.9.9.9")); + Assert.Null(t.BlockedFor("aseza.2", "10.9.9.9")); // another login is not affected + + clock.Advance(LoginThrottle.Window + TimeSpan.FromSeconds(1)); + Assert.Null(t.BlockedFor("aseza.1", "10.9.9.9")); + } + + [Fact] + public void Success_clears_the_login() + { + var (t, _) = Make(); + for (var i = 0; i < 4; i++) t.RecordFailure("aseza.1", "10.0.0.1"); + t.RecordSuccess("aseza.1"); + t.RecordFailure("aseza.1", "10.0.0.1"); + Assert.Null(t.BlockedFor("aseza.1", "10.0.0.1")); + } + + [Fact] + public void Blocks_an_address_that_tries_many_logins() + { + var (t, _) = Make(); + for (var i = 0; i < LoginThrottle.MaxPerIp; i++) t.RecordFailure($"aseza.{i}", "10.0.0.1"); + Assert.NotNull(t.BlockedFor("aseza.new", "10.0.0.1")); + Assert.Null(t.BlockedFor("aseza.new", "10.0.0.2")); + } +}