Security hardening: login throttle, password rules, security headers, non-root container, QA port on loopback
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
025fbe9af8
commit
07831cff85
|
|
@ -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/
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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/
|
||||
|
|
|
|||
|
|
@ -13,4 +13,4 @@ services:
|
|||
ASPNETCORE_ENVIRONMENT: QA
|
||||
TZ: Asia/Amman
|
||||
ports:
|
||||
- "0.0.0.0:8081:8080"
|
||||
- "127.0.0.1:8081:8080"
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
|
|
|
|||
|
|
@ -48,6 +48,29 @@ var app = builder.Build();
|
|||
var oracle = app.Services.GetRequiredService<IOptions<OracleOptions>>().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();
|
||||
|
|
|
|||
|
|
@ -22,8 +22,10 @@ public sealed class AuthService(
|
|||
ICurrentUser currentUser,
|
||||
IValidator<LoginRequest> loginValidator,
|
||||
IValidator<ChangePasswordRequest> changePasswordValidator,
|
||||
IValidator<SetLanguageRequest> languageValidator) : IAuthService
|
||||
IValidator<SetLanguageRequest> 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<LoginResponse> SignInAsync(LoginRequest request, ClientInfo client, CancellationToken ct)
|
||||
{
|
||||
var parts = request.UserName.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
if (parts.Length != 2)
|
||||
throw Invalid();
|
||||
|
|
|
|||
|
|
@ -16,7 +16,11 @@ public sealed class ChangePasswordRequestValidator : AbstractValidator<ChangePas
|
|||
public ChangePasswordRequestValidator()
|
||||
{
|
||||
RuleFor(x => 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("كلمة السر الجديدة غير متطابقة");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,71 @@
|
|||
using System.Collections.Concurrent;
|
||||
|
||||
namespace NTP.Application.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Slows down password guessing: after <see cref="MaxPerLogin"/> failed sign-ins of one login (or <see cref="MaxPerIp"/> from one address)
|
||||
/// inside <see cref="Window"/>, 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.
|
||||
/// </summary>
|
||||
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<string, Queue<DateTimeOffset>> _failures = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private static string LoginKey(string login) => "L:" + login;
|
||||
private static string IpKey(string? ip) => "I:" + (ip ?? "?");
|
||||
|
||||
/// <summary>How long the caller must wait, or null when the attempt may proceed.</summary>
|
||||
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<DateTimeOffset>());
|
||||
lock (q)
|
||||
{
|
||||
Trim(q);
|
||||
q.Enqueue(clock.GetUtcNow());
|
||||
}
|
||||
if (_failures.Count > 20_000) Sweep();
|
||||
}
|
||||
|
||||
private void Trim(Queue<DateTimeOffset> 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;
|
||||
}
|
||||
|
|
@ -20,5 +20,8 @@ public class BusinessException(string code, string message) : Exception(message)
|
|||
/// <summary>Credentials / account state rejected (HTTP 401). Same shape as <see cref="BusinessException"/>.</summary>
|
||||
public sealed class AuthenticationFailedException(string code, string message) : BusinessException(code, message);
|
||||
|
||||
/// <summary>Too many failed sign-ins (HTTP 429).</summary>
|
||||
public sealed class TooManyAttemptsException(string code, string message) : BusinessException(code, message);
|
||||
|
||||
/// <summary>Authenticated but the role/rules do not allow the action (HTTP 403).</summary>
|
||||
public sealed class ForbiddenException(string code, string message) : BusinessException(code, message);
|
||||
|
|
|
|||
|
|
@ -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<NTP.Application.Auth.LoginThrottle>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue