using System.Globalization; using System.Security.Authentication; using System.Security.Cryptography; using System.Text; namespace Titano.Data.Postgres; /// /// Client side of SCRAM-SHA-256 (RFC 5802 / RFC 7677) as PostgreSQL uses it: no channel binding /// (n,, GS2 header) and an empty user name, since the server takes the user from the startup packet. /// internal sealed class ScramSha256 { private readonly string _password; private readonly string _username; private readonly string _clientNonce; private string? _clientFirstBare; private byte[]? _expectedServerSignature; public ScramSha256(string password, string username = "", string? clientNonce = null) { _password = password; _username = username.Replace("=", "=3D", StringComparison.Ordinal).Replace(",", "=2C", StringComparison.Ordinal); _clientNonce = clientNonce ?? Convert.ToBase64String(RandomNumberGenerator.GetBytes(18)); } public const string Mechanism = "SCRAM-SHA-256"; /// The server proved knowledge of the password with a valid final signature. public bool IsServerVerified { get; private set; } public byte[] ClientFirstMessage() { _clientFirstBare = $"n={_username},r={_clientNonce}"; return Encoding.UTF8.GetBytes("n,," + _clientFirstBare); } /// Checks the server-first message and returns client-final with the proof. public byte[] ClientFinalMessage(ReadOnlySpan serverFirst) { if (_clientFirstBare is null) throw new InvalidOperationException("ClientFirstMessage must be sent first."); var serverFirstText = Encoding.UTF8.GetString(serverFirst); string? nonce = null, salt = null, iterations = null; foreach (var part in serverFirstText.Split(',')) { if (part.StartsWith("r=", StringComparison.Ordinal)) nonce = part[2..]; else if (part.StartsWith("s=", StringComparison.Ordinal)) salt = part[2..]; else if (part.StartsWith("i=", StringComparison.Ordinal)) iterations = part[2..]; } if (nonce is null || salt is null || iterations is null || !nonce.StartsWith(_clientNonce, StringComparison.Ordinal) || nonce.Length == _clientNonce.Length || !int.TryParse(iterations, NumberStyles.None, CultureInfo.InvariantCulture, out var count) || count < 1) throw new AuthenticationException("Invalid SCRAM server-first message."); var saltedPassword = Rfc2898DeriveBytes.Pbkdf2( Encoding.UTF8.GetBytes(SaslPrep(_password)), Convert.FromBase64String(salt), count, HashAlgorithmName.SHA256, 32); var clientKey = HMACSHA256.HashData(saltedPassword, "Client Key"u8); var storedKey = SHA256.HashData(clientKey); var withoutProof = "c=biws,r=" + nonce; var authMessage = Encoding.UTF8.GetBytes(_clientFirstBare + "," + serverFirstText + "," + withoutProof); var proof = HMACSHA256.HashData(storedKey, authMessage); for (var i = 0; i < proof.Length; i++) proof[i] ^= clientKey[i]; _expectedServerSignature = HMACSHA256.HashData(HMACSHA256.HashData(saltedPassword, "Server Key"u8), authMessage); return Encoding.UTF8.GetBytes(withoutProof + ",p=" + Convert.ToBase64String(proof)); } /// Verifies the server signature, proving the server knows the password too. public void VerifyServerFinal(ReadOnlySpan serverFinal) { var text = Encoding.UTF8.GetString(serverFinal); if (text.StartsWith("e=", StringComparison.Ordinal)) throw new AuthenticationException("SCRAM authentication failed: " + text[2..]); var end = text.IndexOf(',', StringComparison.Ordinal); var value = text.StartsWith("v=", StringComparison.Ordinal) ? text[2..(end < 0 ? text.Length : end)] : null; if (_expectedServerSignature is null || value is null || !CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(value), _expectedServerSignature)) throw new AuthenticationException("The server's SCRAM signature is invalid."); IsServerVerified = true; } /// /// SASLprep (RFC 4013) as PostgreSQL applies it: non-ASCII spaces become U+0020, "mapped to nothing" /// characters are dropped, then NFKC; a result with prohibited code points falls back to the raw password. /// The unassigned-code-point and bidi checks are omitted. /// internal static string SaslPrep(string password) { var ascii = true; foreach (var c in password) { if (c > 0x7F) { ascii = false; break; } } // Printable ASCII is unchanged by SASLprep; ASCII controls are prohibited, which also means "use raw". if (ascii) return password; var mapped = new StringBuilder(password.Length); foreach (var rune in password.EnumerateRunes()) { var v = rune.Value; if (v is 0x00A0 or 0x1680 or (>= 0x2000 and <= 0x200B) or 0x202F or 0x205F or 0x3000) mapped.Append(' '); else if (v is 0x00AD or 0x034F or 0x1806 or (>= 0x180B and <= 0x180D) or (>= 0x200C and <= 0x200D) or 0x2060 or (>= 0xFE00 and <= 0xFE0F) or 0xFEFF) continue; else mapped.Append(rune.ToString()); } var normalized = mapped.ToString().Normalize(NormalizationForm.FormKC); foreach (var rune in normalized.EnumerateRunes()) { if (IsProhibited(rune.Value)) return password; } return normalized; } private static bool IsProhibited(int v) => v < 0x20 || v is >= 0x7F and <= 0x9F // C.2.1, C.2.2 controls || v is 0x06DD or 0x070F or 0x180E or 0x2028 or 0x2029 or (>= 0x2060 and <= 0x2063) // C.2.2 || v is >= 0x1D173 and <= 0x1D17A || v is >= 0xE000 and <= 0xF8FF || v >= 0xF0000 // C.3 private use || v is >= 0xFDD0 and <= 0xFDEF || (v & 0xFFFE) == 0xFFFE // C.4 non-characters || v is >= 0xFFF9 and <= 0xFFFD // C.6 || v is >= 0x2FF0 and <= 0x2FFB // C.7 || v is 0x0340 or 0x0341 or 0x200E or 0x200F or (>= 0x202A and <= 0x202E) or (>= 0x206A and <= 0x206F) // C.8 || v is 0xE0001 or (>= 0xE0020 and <= 0xE007F); // C.9 } /// PostgreSQL's MD5 password response: "md5" + md5hex(md5hex(password + user) + salt). internal static class PgMd5 { public static string Response(string username, string password, ReadOnlySpan salt) { var inner = Hex(MD5.HashData(Encoding.UTF8.GetBytes(password + username))); var buffer = new byte[inner.Length + salt.Length]; Encoding.ASCII.GetBytes(inner, buffer); salt.CopyTo(buffer.AsSpan(inner.Length)); return "md5" + Hex(MD5.HashData(buffer)); } private static string Hex(byte[] bytes) => Convert.ToHexStringLower(bytes); }