Add SRP password recovery and E2EE reset

Add proof-based password registration, login, enrollment, and change flows, with rate limiting and encrypted recovery-key envelopes. Support explicit E2EE identity resets while preserving historical signer verification, and document and test the new recovery workflows.
This commit is contained in:
Artemy
2026-10-24 22:19:08 +07:00
parent 55cc9538f7
commit a3401ceedf
29 changed files with 4322 additions and 36 deletions
@@ -33,7 +33,16 @@ public class AuthService : IAccountService
_clock = clock;
}
public async Task<Result<User, Error>> RegistrationAsync(string name, string password, Invitation invitation)
public Task<Result<User, Error>> RegistrationAsync(string name, string password, Invitation invitation) =>
RegisterCoreAsync(name, password, invitation, null);
public Task<Result<User, Error>> RegistrationWithPasswordProofAsync(string name, PasswordCredentials credentials, Invitation invitation)
{
PasswordProtocol.Validate(credentials);
return RegisterCoreAsync(name, null, invitation, credentials);
}
private async Task<Result<User, Error>> RegisterCoreAsync(string name, string? password, Invitation invitation, PasswordCredentials? credentials)
{
var validationResult = _usernameValidator.Validate(name);
if (validationResult.IsFailure)
@@ -48,7 +57,7 @@ public class AuthService : IAccountService
$"User with username '{name}' already exists."));
}
var passwordHash = _passwordHasher.Hash(password);
var passwordHash = credentials is null ? _passwordHasher.Hash(password!) : "srp-only";
var operationId = Guid.NewGuid();
return await _context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
@@ -81,7 +90,9 @@ public class AuthService : IAccountService
var user = new User
{
Id = operationId, Username = name, PasswordHash = passwordHash, Description = string.Empty,
CreatedOn = DateOnly.FromDateTime(now), IconId = Guid.Empty, WasOnline = now, InviteId = invitation.Id
CreatedOn = DateOnly.FromDateTime(now), IconId = Guid.Empty, WasOnline = now, InviteId = invitation.Id,
SrpSalt = credentials?.Salt, SrpIdentity = credentials?.Identity, SrpVerifier = credentials?.Verifier,
CredentialVersion = credentials is null ? 0 : 1
};
await _context.Users.AddAsync(user);
@@ -120,6 +131,8 @@ public class AuthService : IAccountService
$"User '{name}' is not registered."));
}
if (user.SrpVerifier is not null)
return Result.Failure<User>(Error.Unauthorized("Auth.PasswordProofRequired", "Use password proof authentication with an updated client."));
if (!_passwordHasher.Verify(password, user.PasswordHash))
{
return Result.Failure<User>(Error.Failure(
@@ -9,4 +9,5 @@ public interface IAccountService
{
public Task<Result<User, Error>> RegistrationAsync(string name, string password, Invitation invitation);
public Task<Result<User, Error>> LoginAsync(string name, string password);
}
public Task<Result<User, Error>> RegistrationWithPasswordProofAsync(string name, PasswordCredentials credentials, Invitation invitation);
}
@@ -0,0 +1,219 @@
using System.Security.Cryptography;
using Govor.Application.E2ee;
using Govor.Domain;
using Govor.Domain.Models.Users;
using Govor.Domain.Models.Users.Crypto;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Authentication;
public sealed class PasswordAccountService(GovorDbContext db, PasswordChallenges challenges, IPasswordHasher legacyHasher)
{
public static PasswordCredentials Credentials(User user) => user.SrpVerifier is null
? throw new InvalidOperationException("This account needs a one-time password upgrade.")
: new(1, user.SrpSalt!, user.SrpIdentity!, user.SrpVerifier);
public async Task<PasswordChallenge> StartAsync(PasswordChallengeRequest request, string purpose = "login",
Guid? user = null, Guid? session = null)
{
if (!PasswordProtocol.GroupElement(request.PublicEphemeral) || request.Name is null || request.Name.Length > 50 ||
request.DeviceInfo is null || request.DeviceInfo.Length > 256) throw new ArgumentException("Invalid password challenge.");
var account = user.HasValue ? await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == user) :
await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Username == request.Name);
if (account is { SrpVerifier: null })
return new(Guid.Empty, "", "", "", account.CredentialVersion, true);
// Unknown names receive a normal-looking challenge and always fail proof verification.
var credentials = account is null ? FakeCredentials() : Credentials(account);
var ephemeral = PasswordProtocol.Server().GenerateEphemeral(credentials.Verifier);
var entry = new PasswordChallenges.Entry(account?.Id ?? Guid.Empty, session ?? Guid.Empty, purpose,
account?.CredentialVersion ?? 0, credentials, ephemeral.Secret, request.PublicEphemeral,
request.DeviceInfo, challenges.Now.AddMinutes(2));
var id = challenges.Add(entry);
return new(id, credentials.Salt, credentials.Identity, ephemeral.Public, entry.CredentialVersion);
}
public async Task<(User User, string ServerProof, string DeviceInfo)> VerifyAsync(PasswordProof proof,
string purpose = "login", Guid? user = null, Guid? session = null)
{
var entry = challenges.Consume(proof.ChallengeId, purpose, user, session);
if (!PasswordProtocol.Hex(proof.Proof, 128)) throw new UnauthorizedAccessException("Invalid password proof.");
string serverProof;
try
{
var result = PasswordProtocol.Server().DeriveSession(entry.SecretEphemeral, entry.PublicEphemeral,
entry.Credentials.Salt, entry.Credentials.Identity, entry.Credentials.Verifier, proof.Proof);
serverProof = result.Proof;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{ throw new UnauthorizedAccessException("Incorrect password or invalid proof."); }
var account = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == entry.UserId);
if (account is null || account.CredentialVersion != entry.CredentialVersion ||
account.SrpVerifier != entry.Credentials.Verifier) throw new UnauthorizedAccessException("Credentials changed. Sign in again.");
return (account, serverProof, entry.DeviceInfo);
}
public async Task<PasswordActionResult> AuthorizeAsync(Guid user, Guid session, PasswordProof proof, string action)
{
var verified = await VerifyAsync(proof, action, user, session);
var grant = new PasswordChallenges.Entry(user, session, action + "-authorized", verified.User.CredentialVersion,
Credentials(verified.User), "", "", "", challenges.Now.AddMinutes(2));
return new(challenges.Add(grant), verified.ServerProof, verified.User.CredentialVersion);
}
public async Task<PasswordLoginResult> LoginAsync(PasswordProof proof, Govor.Application.Users.UserSessions.IUserSessionOpener sessions)
{
var verified = await VerifyAsync(proof);
return await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
{
await using var tx = await db.Database.BeginTransactionAsync();
if (await db.Users.Where(u => u.Id == verified.User.Id && u.CredentialVersion == verified.User.CredentialVersion)
.ExecuteUpdateAsync(u => u.SetProperty(u => u.CredentialVersion, u => u.CredentialVersion)) != 1)
throw new UnauthorizedAccessException("Credentials changed during login.");
var result = await sessions.OpenSessionAsync(verified.User, verified.DeviceInfo);
if (result.IsFailure) throw new InvalidOperationException("Unable to open the authenticated session.");
await tx.CommitAsync();
return new PasswordLoginResult(result.Value.refreshToken, result.Value.accessToken, verified.ServerProof, verified.User.CredentialVersion);
});
}
public async Task<PasswordConfiguration> GetAsync(Guid user)
{
var account = await db.Users.AsNoTracking().SingleAsync(u => u.Id == user);
var credentials = Credentials(account);
var recovery = await db.E2eeRecoveryVaults.AsNoTracking().SingleOrDefaultAsync(v => v.UserId == user);
var envelope = recovery is { PasswordCiphertext: not null, PasswordSignature: not null } &&
recovery.PasswordCredentialVersion == account.CredentialVersion
? new PasswordEnvelope(recovery.IdentityKey, recovery.PasswordCredentialVersion, recovery.PasswordCiphertext, recovery.PasswordSignature) : null;
return new(credentials, account.CredentialVersion, envelope);
}
public async Task EnrollAsync(Guid user, PasswordEnrollmentRequest request)
{
PasswordProtocol.Validate(request.Credentials);
var account = await db.Users.SingleAsync(u => u.Id == user);
if (account.SrpVerifier is not null) throw new InvalidOperationException("Password authentication is already upgraded.");
if (request.LegacyPassword is null || request.LegacyPassword.Length > 256 || !legacyHasher.Verify(request.LegacyPassword, account.PasswordHash))
throw new UnauthorizedAccessException("Incorrect current password.");
if (request.LegacyPassword.Length >= 8)
{
var old = PasswordProtocol.Derive(request.LegacyPassword, request.Credentials.Salt, request.Credentials.Identity);
var client = PasswordProtocol.Client();
if (client.DeriveVerifier(client.DerivePrivateKey(request.Credentials.Salt, request.Credentials.Identity, old.Secret)) == request.Credentials.Verifier)
throw new ArgumentException("The replacement password must differ from the former plaintext password.");
}
Apply(account, request.Credentials);
await db.SaveChangesAsync();
}
public async Task SaveEnvelopeAsync(Guid user, PasswordEnvelope envelope)
{
await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
{
await using var tx = await db.Database.BeginTransactionAsync();
if (await db.Users.Where(u => u.Id == user && u.CredentialVersion == envelope.CredentialVersion)
.ExecuteUpdateAsync(u => u.SetProperty(u => u.CredentialVersion, u => u.CredentialVersion)) != 1)
throw new InvalidOperationException("Password changed. Retry.");
var account = await db.Users.AsNoTracking().SingleAsync(u => u.Id == user);
PasswordProtocol.ValidateEnvelope(user, Credentials(account), envelope);
var recovery = await db.E2eeRecoveryVaults.SingleAsync(v => v.UserId == user);
if (recovery.IdentityKey != envelope.IdentityKey) throw new InvalidOperationException("Encryption identity changed. Retry.");
recovery.PasswordCredentialVersion = envelope.CredentialVersion;
recovery.PasswordCiphertext = envelope.Ciphertext;
recovery.PasswordSignature = envelope.Signature;
await db.SaveChangesAsync(); await tx.CommitAsync();
});
}
public async Task ChangeAsync(Guid user, Guid session, ChangePasswordRequest request)
{
PasswordProtocol.Validate(request.Credentials);
var grant = challenges.Consume(request.AuthorizationId, "change-authorized", user, session);
await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
{
await using var tx = await db.Database.BeginTransactionAsync();
if (await db.Users.Where(u => u.Id == user && u.CredentialVersion == grant.CredentialVersion)
.ExecuteUpdateAsync(u => u.SetProperty(u => u.CredentialVersion, u => u.CredentialVersion)) != 1)
throw new InvalidOperationException("Credentials changed. Retry.");
var account = await db.Users.SingleAsync(u => u.Id == user);
if (account.CredentialVersion != grant.CredentialVersion) throw new InvalidOperationException("Credentials changed. Retry.");
var recovery = await db.E2eeRecoveryVaults.SingleOrDefaultAsync(v => v.UserId == user);
if (recovery is not null)
{
if (request.Envelope is null || request.Envelope.IdentityKey != recovery.IdentityKey ||
request.Envelope.CredentialVersion != account.CredentialVersion + 1)
throw new ArgumentException("Changing a known password must preserve the encrypted recovery key.");
PasswordProtocol.ValidateEnvelope(user, request.Credentials, request.Envelope);
recovery.PasswordCiphertext = request.Envelope.Ciphertext;
recovery.PasswordSignature = request.Envelope.Signature;
recovery.PasswordCredentialVersion = request.Envelope.CredentialVersion;
}
Apply(account, request.Credentials);
await RevokeOtherSessionsAsync(user, session);
await db.SaveChangesAsync(); await tx.CommitAsync();
});
}
public async Task<AccountIdentityChange> ResetAsync(Guid user, Guid session, ResetEncryptionRequest request)
{
var grant = challenges.Consume(request.AuthorizationId, "reset-authorized", user, session);
E2eeRecoveryProtocol.Validate(request.Vault);
PasswordProtocol.ValidateEnvelope(user, grant.Credentials, request.Envelope);
if (request.Vault.UserId != user || request.Vault.Revision != request.ExpectedRevision + 1 ||
request.Envelope.IdentityKey != request.Vault.IdentityKey || request.Envelope.CredentialVersion != grant.CredentialVersion)
throw new ArgumentException("Invalid encryption reset context.");
AccountIdentityChange? change = null;
await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
{
await using var tx = await db.Database.BeginTransactionAsync();
if (await db.Users.Where(u => u.Id == user && u.CredentialVersion == grant.CredentialVersion)
.ExecuteUpdateAsync(u => u.SetProperty(u => u.CredentialVersion, u => u.CredentialVersion)) != 1)
throw new InvalidOperationException("Credentials changed. Retry.");
var account = await db.Users.AsNoTracking().SingleAsync(u => u.Id == user);
if (account.CredentialVersion != grant.CredentialVersion) throw new InvalidOperationException("Credentials changed. Retry.");
var recovery = await db.E2eeRecoveryVaults.SingleAsync(v => v.UserId == user);
if (recovery.IdentityKey != request.ExpectedIdentityKey || recovery.Revision != request.ExpectedRevision ||
recovery.IdentityKey == request.Vault.IdentityKey) throw new InvalidOperationException("Encryption identity changed. Retry.");
change = new(user, recovery.Epoch + 1, recovery.IdentityKey, request.Vault.IdentityKey,
challenges.Now.ToUnixTimeMilliseconds());
var previousDevice = (await new E2eeService(db).GetOwnDevicesAsync(user)).SingleOrDefault(d => d.SessionId == session);
db.E2eeIdentityChanges.Add(new() { UserId = user, Epoch = change.Epoch, PreviousIdentityKey = change.PreviousIdentityKey,
IdentityKey = change.IdentityKey, ChangedAt = change.ChangedAt,
PreviousSessionId = previousDevice?.SessionId,
PreviousDeviceKeyJson = previousDevice is null ? null : System.Text.Json.JsonSerializer.Serialize(previousDevice) });
recovery.Epoch = change.Epoch;
recovery.Revision = request.Vault.Revision;
recovery.IdentityKey = request.Vault.IdentityKey;
recovery.Ciphertext = request.Vault.Ciphertext;
recovery.Signature = request.Vault.Signature;
recovery.PasswordCiphertext = request.Envelope.Ciphertext;
recovery.PasswordSignature = request.Envelope.Signature;
recovery.PasswordCredentialVersion = request.Envelope.CredentialVersion;
await RevokeOtherSessionsAsync(user, session);
// Keep historical public certificates, but remove the current
// session's former identity so it can register under the new root.
await db.UserCryptoSessions.Where(c => c.UserSessionId == session).ExecuteDeleteAsync();
await db.SaveChangesAsync(); await tx.CommitAsync();
});
return change!;
}
private async Task RevokeOtherSessionsAsync(Guid user, Guid currentSession)
{
await db.UserSessions.Where(s => s.UserId == user && s.Id != currentSession)
.ExecuteUpdateAsync(s => s.SetProperty(s => s.IsRevoked, true));
await db.UserPushTokens.Where(t => t.UserId == user && t.UserSessionId != currentSession)
.ExecuteUpdateAsync(t => t.SetProperty(t => t.IsActive, false));
}
private static void Apply(User user, PasswordCredentials credentials)
{
user.PasswordHash = "srp-only";
user.SrpSalt = credentials.Salt; user.SrpIdentity = credentials.Identity; user.SrpVerifier = credentials.Verifier;
user.CredentialVersion++;
}
private static PasswordCredentials FakeCredentials()
{
var salt = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
var identity = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
return new(1, salt, identity, PasswordProtocol.Client().DeriveVerifier(Convert.ToHexString(RandomNumberGenerator.GetBytes(64))));
}
}
@@ -0,0 +1,35 @@
namespace Govor.Application.Authentication;
// Ephemeral proofs and authorizations are process-local, bounded and consumed
// exactly once. A restart invalidates pending handshakes, never long-term keys.
public sealed class PasswordChallenges(TimeProvider? clock = null)
{
private readonly TimeProvider _clock = clock ?? TimeProvider.System;
private readonly object _gate = new();
private readonly Dictionary<Guid, Entry> _entries = [];
public sealed record Entry(Guid UserId, Guid SessionId, string Purpose, long CredentialVersion,
PasswordCredentials Credentials, string SecretEphemeral, string PublicEphemeral,
string DeviceInfo, DateTimeOffset ExpiresAt);
public Guid Add(Entry entry)
{
lock (_gate)
{
foreach (var id in _entries.Where(p => p.Value.ExpiresAt <= _clock.GetUtcNow()).Select(p => p.Key).ToArray())
_entries.Remove(id);
if (_entries.Count >= 1024) throw new InvalidOperationException("Too many pending password proofs. Retry shortly.");
var key = Guid.NewGuid(); _entries.Add(key, entry); return key;
}
}
public Entry Consume(Guid id, string purpose, Guid? user = null, Guid? session = null)
{
lock (_gate)
{
if (!_entries.Remove(id, out var value) || value.ExpiresAt <= _clock.GetUtcNow() ||
value.Purpose != purpose || (user.HasValue && value.UserId != user) ||
(session.HasValue && value.SessionId != session)) throw new UnauthorizedAccessException("Password proof is expired or invalid.");
return value;
}
}
public DateTimeOffset Now => _clock.GetUtcNow();
}
@@ -0,0 +1,129 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Numerics;
using Jose;
using SecureRemotePassword;
using Govor.Application.E2ee;
namespace Govor.Application.Authentication;
public sealed record PasswordCredentials(int Version, string Salt, string Identity, string Verifier);
public sealed record PasswordEnvelope(string IdentityKey, long CredentialVersion, string Ciphertext, string Signature);
public sealed record PasswordConfiguration(PasswordCredentials Credentials, long CredentialVersion, PasswordEnvelope? Envelope);
public sealed record PasswordChallengeRequest(string Name, string PublicEphemeral, string DeviceInfo = "");
public sealed record PasswordChallenge(Guid ChallengeId, string Salt, string Identity, string PublicEphemeral, long CredentialVersion, bool Legacy = false);
public sealed record PasswordProof(Guid ChallengeId, string Proof);
public sealed record PasswordLoginResult(string RefreshToken, string AccessToken, string ServerProof, long CredentialVersion);
public sealed record PasswordActionResult(Guid AuthorizationId, string ServerProof, long CredentialVersion);
public sealed record PasswordEnrollmentRequest(PasswordCredentials Credentials, string? LegacyPassword = null);
public sealed record SavePasswordEnvelope(PasswordEnvelope Envelope);
public sealed record ChangePasswordRequest(Guid AuthorizationId, PasswordCredentials Credentials, PasswordEnvelope? Envelope);
public sealed record ResetEncryptionRequest(Guid AuthorizationId, string ExpectedIdentityKey, long ExpectedRevision,
RecoveryVault Vault, PasswordEnvelope Envelope);
public sealed record AccountIdentityChange(Guid UserId, long Epoch, string PreviousIdentityKey, string IdentityKey, long ChangedAt);
// SRP-6a is supplied by srp.net, rather than implemented here. Fixed parameters
// and separate HKDF domains prevent the authentication verifier/session key from
// being used as the key that opens the recovery archive.
public static class PasswordProtocol
{
public const int Iterations = 600_000;
public static SrpParameters Parameters() => SrpParameters.Create4096<SHA512>();
public static SrpClient Client() => new(Parameters());
public static SrpServer Server() => new(Parameters());
public static (PasswordCredentials Credentials, string ArchiveKey) Create(string password)
{
var salt = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
var identity = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
var (secret, archiveKey) = Derive(password, salt, identity);
var client = Client();
return (new(1, salt, identity, client.DeriveVerifier(client.DerivePrivateKey(salt, identity, secret))), archiveKey);
}
public static (string Secret, string ArchiveKey) Derive(string password, string salt, string identity)
{
if (password is null || password.Length is < 8 or > 256 || !Hex(salt, 64) || !Hex(identity, 64))
throw new CryptographicException("Invalid password or password parameters.");
var master = Rfc2898DeriveBytes.Pbkdf2(password, Convert.FromHexString(salt), Iterations, HashAlgorithmName.SHA256, 32);
try
{
var auth = HKDF.DeriveKey(HashAlgorithmName.SHA256, master, 32, info: Encoding.UTF8.GetBytes("govor-auth-v1\n" + identity));
var archive = HKDF.DeriveKey(HashAlgorithmName.SHA256, master, 32, info: Encoding.UTF8.GetBytes("govor-password-archive-v1\n" + identity));
try { return (Base64Url.Encode(auth), Base64Url.Encode(archive)); }
finally { CryptographicOperations.ZeroMemory(auth); CryptographicOperations.ZeroMemory(archive); }
}
finally { CryptographicOperations.ZeroMemory(master); }
}
public static void Validate(PasswordCredentials credentials)
{
if (credentials is null || credentials.Version != 1 || !Hex(credentials.Salt, 64) ||
!Hex(credentials.Identity, 64) || !Hex(credentials.Verifier, 1024) ||
!SrpUtility.IsValidVerifier(Parameters(), credentials.Verifier) || !GroupElement(credentials.Verifier))
throw new CryptographicException("Invalid SRP credentials.");
}
public static bool Hex(string? value, int length) => value?.Length == length &&
value.All(c => c is >= '0' and <= '9' or >= 'A' and <= 'F' or >= 'a' and <= 'f');
public static bool GroupElement(string? value)
{
if (!Hex(value, 1024)) return false;
var integer = new BigInteger(Convert.FromHexString(value!), isUnsigned: true, isBigEndian: true);
var prime = new BigInteger(Convert.FromHexString(Parameters().Prime.ToHex()), isUnsigned: true, isBigEndian: true);
return integer > 1 && integer < prime - 1;
}
public static PasswordEnvelope Seal(Guid user, long version, PasswordCredentials credentials,
string privateIdentity, string code, string archiveKey)
{
Validate(credentials);
var root = E2eeRecoveryProtocol.PublicIdentity(privateIdentity);
var key = Base64Url.Decode(archiveKey);
try
{
if (key.Length != 32) throw new CryptographicException("Invalid archive key.");
var ciphertext = Jose.JWT.Encode(new KeyPayload(1, user, root, version, code), key, JweAlgorithm.DIR, JweEncryption.A256GCM);
var envelope = new PasswordEnvelope(root, version, ciphertext, "");
return envelope with { Signature = E2eeRecoveryProtocol.SignAccountPayload(privateIdentity, Binding(user, credentials, envelope)) };
}
finally { CryptographicOperations.ZeroMemory(key); }
}
public static string Open(Guid user, PasswordCredentials credentials, PasswordEnvelope envelope, string archiveKey)
{
ValidateEnvelope(user, credentials, envelope);
var key = Base64Url.Decode(archiveKey);
try
{
if (key.Length != 32) throw new CryptographicException("Invalid archive key.");
var payload = JsonSerializer.Deserialize<KeyPayload>(Jose.JWT.Decode(envelope.Ciphertext, key,
JweAlgorithm.DIR, JweEncryption.A256GCM), E2eeProtocol.Json) ?? throw new CryptographicException("Invalid password archive.");
if (payload.Version != 1 || payload.UserId != user || payload.IdentityKey != envelope.IdentityKey ||
payload.CredentialVersion != envelope.CredentialVersion || Base64Url.Decode(payload.Code).Length != 32)
throw new CryptographicException("Password archive context mismatch.");
return payload.Code;
}
finally { CryptographicOperations.ZeroMemory(key); }
}
public static void ValidateEnvelope(Guid user, PasswordCredentials credentials, PasswordEnvelope envelope)
{
Validate(credentials);
if (user == Guid.Empty || envelope is null || envelope.CredentialVersion < 1 || envelope.Ciphertext is null ||
envelope.Ciphertext.Length is < 50 or > 4096 || envelope.Signature is null)
throw new CryptographicException("Invalid password archive.");
var parts = envelope.Ciphertext.Split('.');
if (parts.Length != 5 || parts[1].Length != 0) throw new CryptographicException("Invalid password archive JWE.");
using var header = JsonDocument.Parse(Base64Url.Decode(parts[0]));
if (header.RootElement.EnumerateObject().Count() != 2 || header.RootElement.GetProperty("alg").GetString() != "dir" ||
header.RootElement.GetProperty("enc").GetString() != "A256GCM") throw new CryptographicException("Invalid archive algorithms.");
E2eeRecoveryProtocol.VerifyAccountPayload(envelope.IdentityKey, Binding(user, credentials, envelope), envelope.Signature);
}
private static byte[] Binding(Guid user, PasswordCredentials credentials, PasswordEnvelope envelope) =>
JsonSerializer.SerializeToUtf8Bytes(new { purpose = "govor-password-recovery-v1", user,
credentials, envelope.IdentityKey, envelope.CredentialVersion, envelope.Ciphertext });
private sealed record KeyPayload(int Version, Guid UserId, string IdentityKey, long CredentialVersion, string Code);
}
@@ -49,6 +49,11 @@ public static class E2eeRecoveryProtocol
public static string AccountFingerprint(string identity) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("govor-account-v1\n" + identity)));
public static string SignAccountPayload(string privateIdentity, byte[] data)
{ using var key = PrivateIdentity(privateIdentity); return Sign(key, data); }
public static void VerifyAccountPayload(string publicIdentity, byte[] data, string signature)
{ using var key = PublicIdentityKey(publicIdentity); Verify(key, data, signature); }
public static DeviceKey Certify(DeviceKey device, string privateIdentity, long generation = 0,
string? previousFingerprint = null)
{
+34 -4
View File
@@ -111,6 +111,19 @@ public sealed class E2eeService(GovorDbContext context)
return new(value is null ? null : new(user, value.Revision, value.IdentityKey, value.Ciphertext, value.Signature));
}
public async Task<Govor.Application.Authentication.AccountIdentityChange[]> GetIdentityChangesAsync(Guid user, Guid peer)
{
if (user != peer && !await context.PrivateChats.AnyAsync(c =>
(c.UserAId == user && c.UserBId == peer) || (c.UserAId == peer && c.UserBId == user)) &&
!await context.GroupMemberships.AnyAsync(m => m.UserId == user && !m.IsBanned &&
(context.GroupMemberships.Any(p => p.GroupId == m.GroupId && p.UserId == peer && !p.IsBanned) ||
context.Messages.Any(msg => msg.RecipientType == RecipientType.Group && msg.RecipientId == m.GroupId && msg.SenderId == peer))))
throw new UnauthorizedAccessException();
return await context.E2eeIdentityChanges.AsNoTracking().Where(c => c.UserId == peer).OrderBy(c => c.Epoch)
.Select(c => new Govor.Application.Authentication.AccountIdentityChange(c.UserId, c.Epoch,
c.PreviousIdentityKey, c.IdentityKey, c.ChangedAt)).ToArrayAsync();
}
public async Task<RecoveryVault> SaveRecoveryAsync(Guid user, SaveRecoveryVault request)
{
if (request.ExpectedRevision < 0 || request.ExpectedRevision == long.MaxValue)
@@ -166,14 +179,31 @@ public sealed class E2eeService(GovorDbContext context)
await context.SaveChangesAsync();
}
public async Task<DeviceKey?> GetHistoricalSignerAsync(Guid user, Guid conversation, RecipientType type, Guid session)
public async Task<DeviceKey?> GetHistoricalSignerAsync(Guid user, Guid conversation, RecipientType type, Guid session, string? identityKey = null)
{
if (!await context.HasChatAccessAsync(user, conversation, type)) throw new UnauthorizedAccessException();
var crypto = await context.UserCryptoSessions.AsNoTracking().Include(c => c.SignedPreKey).Include(c => c.UserSession)
.SingleOrDefaultAsync(c => c.UserSessionId == session);
if (crypto is null || !await context.Messages.AnyAsync(m => m.RecipientId == conversation &&
m.RecipientType == type && m.SenderId == crypto.UserSession.UserId)) return null;
return ToDeviceKey(crypto);
var owner = await context.UserSessions.AsNoTracking().Where(s => s.Id == session).Select(s => (Guid?)s.UserId).SingleOrDefaultAsync();
if (owner is null || !await context.Messages.AnyAsync(m => m.RecipientId == conversation &&
m.RecipientType == type && m.SenderId == owner.Value)) return null;
if (crypto is not null)
{
var current = ToDeviceKey(crypto);
if (identityKey is null || current.IdentityKey == identityKey) return current;
}
// A reset replaces this session's signing key, but v1 messages still need
// the former account certificate. Public history never reactivates a key.
var previous = await context.E2eeIdentityChanges.AsNoTracking().Where(c => c.UserId == owner.Value &&
c.PreviousSessionId == session && c.PreviousDeviceKeyJson != null)
.OrderByDescending(c => c.Epoch).Select(c => c.PreviousDeviceKeyJson!).ToArrayAsync();
foreach (var json in previous)
{
var key = System.Text.Json.JsonSerializer.Deserialize<DeviceKey>(json, E2eeProtocol.Json);
if (key is not null && key.SessionId == session && key.UserId == owner &&
(identityKey is null || key.IdentityKey == identityKey)) return key;
}
return null;
}
public async Task<EncryptedMessage?> ValidateAsync(string content, Guid sender, Guid conversation,
@@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="srp" Version="1.0.7" />
<PackageReference Include="jose-jwt" Version="5.3.0" />
<PackageReference Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageReference Include="FirebaseAdmin" Version="3.6.0" />
@@ -33,6 +33,19 @@ public class UsersService : IUsersAdministration
return;
user.PasswordHash = _passwordHasher.Hash(password);
user.SrpVerifier = null;
user.SrpSalt = null;
user.SrpIdentity = null;
user.CredentialVersion++;
var recovery = await _context.E2eeRecoveryVaults.SingleOrDefaultAsync(v => v.UserId == userId);
if (recovery is not null)
{
// An administrator can reset authentication, but cannot rewrap an
// encryption key without knowing a client-side recovery secret.
recovery.PasswordCiphertext = null;
recovery.PasswordSignature = null;
recovery.PasswordCredentialVersion = 0;
}
var sessions = await _context.UserSessions.Where(s => s.UserId == userId && !s.IsRevoked).ToListAsync();
foreach (var session in sessions)