CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s
The instance now starts on its own from KHAEMHAT_* variables: it migrates the system and company databases, creates the super user and the first company, and only then reports ready. Users sign in with password and TOTP through revocable database sessions, and licences decide which modules and how many companies are available. - Configuration: every wrong variable reported at once (exit code 2), _FILE variants - Accounts, password policy and lockout, TOTP with recovery codes, session states with token rotation, security audit with a hash chain - Sign-in pages (mockups 001-003), authorization attributes, security headers and a CSP without inline scripts, login rate limit - Signed licences, activation codes, test mode, licence tool - DataProtection keys in the system database, encrypted with the instance key - Memory or Redis cache (in-house RESP client) that falls back to memory - Database log by section with trace id; cron scheduler with locks and system jobs; record history (audit_log) - Company creation, states, company context and X-Company, 503 in maintenance - In-memory SQLite databases stay alive for the process (tests, demo) - Tests for all of the above, ADR 0019, wiki, SECURITY, CHANGELOG, STATUS, DATA-MODEL Refs #15 #16 #17 #18 #19 #20 #21 #22 #23 #24 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
113 lines
4.1 KiB
C#
113 lines
4.1 KiB
C#
using System.Globalization;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace Khaemhat.Infrastructure.Security;
|
|
|
|
/// <summary>The result of checking a password against a stored hash.</summary>
|
|
public enum PasswordVerification
|
|
{
|
|
/// <summary>The password does not match (or the hash is not readable).</summary>
|
|
Failed = 0,
|
|
|
|
/// <summary>The password matches.</summary>
|
|
Succeeded = 1,
|
|
|
|
/// <summary>The password matches, but the hash uses older parameters: store a new hash.</summary>
|
|
SucceededRehashNeeded = 2,
|
|
}
|
|
|
|
/// <summary>
|
|
/// Password hashes with PBKDF2-HMAC-SHA256 (SPEC §7.3): 600,000 iterations, a random 16-byte salt and a 32-byte
|
|
/// result, stored as <c>pbkdf2-sha256$600000$<salt base64>$<hash base64></c>. The comparison runs in
|
|
/// constant time.
|
|
/// </summary>
|
|
public static class PasswordHasher
|
|
{
|
|
/// <summary>The algorithm prefix of the stored format.</summary>
|
|
public const string Algorithm = "pbkdf2-sha256";
|
|
|
|
/// <summary>The iterations of new hashes (OWASP 2023 recommendation for PBKDF2-HMAC-SHA256).</summary>
|
|
public const int Iterations = 600_000;
|
|
|
|
private const int SaltLength = 16;
|
|
private const int HashLength = 32;
|
|
|
|
/// <summary>Hashes a password with a new random salt.</summary>
|
|
/// <param name="password">The password.</param>
|
|
/// <returns>The stored form.</returns>
|
|
public static string Hash(string password) => Hash(password, Iterations);
|
|
|
|
/// <summary>Hashes a password with the given iterations (tests use fewer to stay fast).</summary>
|
|
/// <param name="password">The password.</param>
|
|
/// <param name="iterations">The PBKDF2 iterations.</param>
|
|
/// <returns>The stored form.</returns>
|
|
public static string Hash(string password, int iterations)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(password);
|
|
ArgumentOutOfRangeException.ThrowIfLessThan(iterations, 1);
|
|
var salt = RandomNumberGenerator.GetBytes(SaltLength);
|
|
var hash = Derive(password, salt, iterations);
|
|
return string.Join('$', Algorithm, iterations.ToString(CultureInfo.InvariantCulture), Convert.ToBase64String(salt), Convert.ToBase64String(hash));
|
|
}
|
|
|
|
/// <summary>Checks a password against a stored hash.</summary>
|
|
/// <param name="storedHash">The stored form; <see langword="null"/> never matches.</param>
|
|
/// <param name="password">The password typed.</param>
|
|
/// <returns>The outcome.</returns>
|
|
public static PasswordVerification Verify(string? storedHash, string password)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(password);
|
|
if (!TryParse(storedHash, out var iterations, out var salt, out var expected))
|
|
{
|
|
return PasswordVerification.Failed;
|
|
}
|
|
|
|
var actual = Derive(password, salt, iterations, expected.Length);
|
|
if (!CryptographicOperations.FixedTimeEquals(actual, expected))
|
|
{
|
|
return PasswordVerification.Failed;
|
|
}
|
|
|
|
return iterations < Iterations ? PasswordVerification.SucceededRehashNeeded : PasswordVerification.Succeeded;
|
|
}
|
|
|
|
private static byte[] Derive(string password, byte[] salt, int iterations, int length = HashLength)
|
|
{
|
|
var bytes = Encoding.UTF8.GetBytes(password);
|
|
try
|
|
{
|
|
return Rfc2898DeriveBytes.Pbkdf2(bytes, salt, iterations, HashAlgorithmName.SHA256, length);
|
|
}
|
|
finally
|
|
{
|
|
CryptographicOperations.ZeroMemory(bytes);
|
|
}
|
|
}
|
|
|
|
private static bool TryParse(string? stored, out int iterations, out byte[] salt, out byte[] hash)
|
|
{
|
|
iterations = 0;
|
|
salt = [];
|
|
hash = [];
|
|
var parts = stored?.Split('$');
|
|
if (parts is not { Length: 4 } || parts[0] != Algorithm
|
|
|| !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out iterations) || iterations < 1)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
salt = Convert.FromBase64String(parts[2]);
|
|
hash = Convert.FromBase64String(parts[3]);
|
|
}
|
|
catch (FormatException)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return salt.Length >= 8 && hash.Length >= 16;
|
|
}
|
|
}
|