- SQLite restore holds every pool slot instead of the write lock first, removing a lock-order deadlock with sessions that begin to write. - PostgreSQL sessions always return their connection on dispose, a rollback while disposing never masks the original exception, and a busy session keeps its transaction until it is discarded. - The pool disposes a connection whose health check the caller cancels. - Listener commands keep their lock until the server answers and never tear a write with the caller's token; closing and pending no longer race. - Tag replacement locks the sequence and the tag row; unused-tag cleanup locks candidates and re-checks them with a fresh snapshot; render counts and stats refreshes lock the sequence row on PostgreSQL. - Sequence upserts keep rendered_count, which renders maintain. - AuthenticationOk after an unfinished SCRAM exchange is rejected. - Oversized read buffers are released; failed backups leave no .tmp; a zero idle lifetime is rejected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
142 lines
7.1 KiB
C#
142 lines
7.1 KiB
C#
using System.Globalization;
|
|
using System.Security.Authentication;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace Titano.Data.Postgres;
|
|
|
|
/// <summary>
|
|
/// Client side of SCRAM-SHA-256 (RFC 5802 / RFC 7677) as PostgreSQL uses it: no channel binding
|
|
/// (<c>n,,</c> GS2 header) and an empty user name, since the server takes the user from the startup packet.
|
|
/// </summary>
|
|
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";
|
|
|
|
/// <summary>The server proved knowledge of the password with a valid final signature.</summary>
|
|
public bool IsServerVerified { get; private set; }
|
|
|
|
public byte[] ClientFirstMessage()
|
|
{
|
|
_clientFirstBare = $"n={_username},r={_clientNonce}";
|
|
return Encoding.UTF8.GetBytes("n,," + _clientFirstBare);
|
|
}
|
|
|
|
/// <summary>Checks the server-first message and returns client-final with the proof.</summary>
|
|
public byte[] ClientFinalMessage(ReadOnlySpan<byte> 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));
|
|
}
|
|
|
|
/// <summary>Verifies the server signature, proving the server knows the password too.</summary>
|
|
public void VerifyServerFinal(ReadOnlySpan<byte> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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
|
|
}
|
|
|
|
/// <summary>PostgreSQL's MD5 password response: <c>"md5" + md5hex(md5hex(password + user) + salt)</c>.</summary>
|
|
internal static class PgMd5
|
|
{
|
|
public static string Response(string username, string password, ReadOnlySpan<byte> 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);
|
|
}
|