mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-17 12:59:25 +00:00
Add E2EE recovery and device rotation
Add signed, encrypted recovery archives with revision checks, account-certified device enrollment and key rotation, and historical signer lookup. Include the database migration, API endpoints, tests, and updated E2EE documentation.
This commit is contained in:
@@ -33,7 +33,8 @@ public sealed class E2eeService(GovorDbContext context)
|
||||
// remain available for offline devices until their session is explicitly revoked.
|
||||
var sessions = await context.UserCryptoSessions.AsNoTracking().Include(c => c.SignedPreKey)
|
||||
.Include(c => c.UserSession)
|
||||
.Where(c => members.Contains(c.UserSession.UserId) && !c.UserSession.IsRevoked)
|
||||
.Where(c => members.Contains(c.UserSession.UserId) && !c.UserSession.IsRevoked &&
|
||||
(c.AccountIdentityKey != null || !context.E2eeRecoveryVaults.Any(v => v.UserId == c.UserSession.UserId)))
|
||||
.Take(E2eeProtocol.MaxDevices + 1).ToListAsync();
|
||||
var devices = sessions.Select(s => ToDeviceKey(s)).ToArray();
|
||||
if (devices.Length > E2eeProtocol.MaxDevices)
|
||||
@@ -49,6 +50,11 @@ public sealed class E2eeService(GovorDbContext context)
|
||||
if (key.UserId != user || key.SessionId != sessionId)
|
||||
throw new UnauthorizedAccessException("E2EE key must belong to the current session.");
|
||||
E2eeProtocol.ValidatePublicKey(key);
|
||||
var account = await context.E2eeRecoveryVaults.AsNoTracking().SingleOrDefaultAsync(v => v.UserId == user);
|
||||
if (account is not null && key.AccountIdentityKey != account.IdentityKey)
|
||||
throw new UnauthorizedAccessException("Restore the account archive before enrolling this device.");
|
||||
if (key.AccountIdentityKey is not null && account is null)
|
||||
throw new InvalidOperationException("Upload the encrypted recovery archive before registering device keys.");
|
||||
var session = await context.UserSessions.Include(s => s.CryptoSession)
|
||||
.ThenInclude(c => c.SignedPreKey).SingleOrDefaultAsync(s => s.Id == sessionId &&
|
||||
s.UserId == user && !s.IsRevoked && s.ExpiresAt > DateTime.UtcNow)
|
||||
@@ -56,10 +62,30 @@ public sealed class E2eeService(GovorDbContext context)
|
||||
if (session.CryptoSession is not null)
|
||||
{
|
||||
var existing = ToDeviceKey(session.CryptoSession, user);
|
||||
if (existing.Fingerprint != key.Fingerprint)
|
||||
throw new InvalidOperationException("Session keys are immutable. Create a new session to change devices.");
|
||||
if (existing.Fingerprint == key.Fingerprint)
|
||||
{
|
||||
if (existing.AccountIdentityKey is null && key.AccountIdentityKey is not null && key.Generation == 0)
|
||||
{
|
||||
ApplyCertificate(session.CryptoSession, key);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
else if (existing.Generation != key.Generation || existing.AccountIdentityKey != key.AccountIdentityKey)
|
||||
throw new InvalidOperationException("Device generation mismatch.");
|
||||
return;
|
||||
}
|
||||
if (account is null || key.AccountIdentityKey != account.IdentityKey ||
|
||||
key.Generation != existing.Generation + 1 || key.PreviousFingerprint != existing.Fingerprint ||
|
||||
key.IdentityKey != existing.IdentityKey)
|
||||
throw new InvalidOperationException("A signed, consecutive device key rotation is required.");
|
||||
var rotating = session.CryptoSession;
|
||||
rotating.SignedPreKey.PublicSignedPreKey = Convert.FromBase64String(key.EncryptionKey);
|
||||
rotating.SignedPreKey.SignedPreKeySignature = Convert.FromBase64String(key.Signature);
|
||||
ApplyCertificate(rotating, key);
|
||||
await context.SaveChangesAsync();
|
||||
return;
|
||||
}
|
||||
if (key.Generation != 0 || key.PreviousFingerprint is not null)
|
||||
throw new InvalidOperationException("A newly enrolled device must start at generation zero.");
|
||||
var cryptoId = Guid.NewGuid();
|
||||
var crypto = new UserCryptoSession
|
||||
{
|
||||
@@ -74,10 +100,82 @@ public sealed class E2eeService(GovorDbContext context)
|
||||
OneTimePreKeys = new List<OneTimePreKey>()
|
||||
};
|
||||
context.UserCryptoSessions.Add(crypto);
|
||||
ApplyCertificate(crypto, key);
|
||||
session.CryptoSession = crypto;
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task<RecoveryState> GetRecoveryAsync(Guid user)
|
||||
{
|
||||
var value = await context.E2eeRecoveryVaults.AsNoTracking().SingleOrDefaultAsync(v => v.UserId == user);
|
||||
return new(value is null ? null : new(user, value.Revision, value.IdentityKey, value.Ciphertext, value.Signature));
|
||||
}
|
||||
|
||||
public async Task<RecoveryVault> SaveRecoveryAsync(Guid user, SaveRecoveryVault request)
|
||||
{
|
||||
if (request.ExpectedRevision < 0 || request.ExpectedRevision == long.MaxValue)
|
||||
throw new ArgumentException("Invalid archive revision.");
|
||||
var value = new RecoveryVault(user, request.ExpectedRevision + 1, request.IdentityKey, request.Ciphertext, request.Signature);
|
||||
E2eeRecoveryProtocol.Validate(value);
|
||||
var existing = await context.E2eeRecoveryVaults.SingleOrDefaultAsync(v => v.UserId == user);
|
||||
if (existing is null)
|
||||
{
|
||||
if (request.ExpectedRevision != 0) throw new InvalidOperationException("Archive revision conflict.");
|
||||
context.E2eeRecoveryVaults.Add(new E2eeRecoveryVault { UserId = user, Revision = value.Revision,
|
||||
IdentityKey = value.IdentityKey, Ciphertext = value.Ciphertext, Signature = value.Signature });
|
||||
}
|
||||
else
|
||||
{
|
||||
if (existing.IdentityKey != request.IdentityKey || existing.Revision != request.ExpectedRevision)
|
||||
throw new InvalidOperationException("Archive identity or revision conflict.");
|
||||
existing.Revision = value.Revision;
|
||||
existing.Ciphertext = value.Ciphertext;
|
||||
existing.Signature = value.Signature;
|
||||
}
|
||||
try { await context.SaveChangesAsync(); }
|
||||
catch (DbUpdateException) { context.ChangeTracker.Clear(); throw new InvalidOperationException("Archive revision conflict."); }
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void ApplyCertificate(UserCryptoSession crypto, DeviceKey key)
|
||||
{
|
||||
crypto.AccountIdentityKey = key.AccountIdentityKey;
|
||||
crypto.AccountSignature = key.AccountSignature;
|
||||
crypto.Generation = key.Generation;
|
||||
crypto.PreviousFingerprint = key.PreviousFingerprint;
|
||||
}
|
||||
|
||||
public async Task<DeviceKey[]> GetOwnDevicesAsync(Guid user) =>
|
||||
(await context.UserCryptoSessions.AsNoTracking().Include(c => c.SignedPreKey).Include(c => c.UserSession)
|
||||
.Where(c => c.UserSession.UserId == user).ToListAsync()).Select(c => ToDeviceKey(c)).ToArray();
|
||||
|
||||
public async Task CertifyHistoricalDeviceAsync(Guid user, DeviceKey key)
|
||||
{
|
||||
E2eeProtocol.ValidatePublicKey(key);
|
||||
E2eeRecoveryProtocol.VerifyCertificate(key);
|
||||
var root = await context.E2eeRecoveryVaults.AsNoTracking().SingleOrDefaultAsync(v => v.UserId == user);
|
||||
var crypto = await context.UserCryptoSessions.Include(c => c.SignedPreKey).Include(c => c.UserSession)
|
||||
.SingleOrDefaultAsync(c => c.UserSessionId == key.SessionId && c.UserSession.UserId == user);
|
||||
if (root is null || root.IdentityKey != key.AccountIdentityKey || key.UserId != user || crypto is null)
|
||||
throw new UnauthorizedAccessException("Only the account owner may certify historical device keys.");
|
||||
var stored = ToDeviceKey(crypto);
|
||||
if (stored.Fingerprint != key.Fingerprint || stored.Generation != key.Generation ||
|
||||
stored.PreviousFingerprint != key.PreviousFingerprint)
|
||||
throw new InvalidOperationException("Historical device keys cannot be changed.");
|
||||
ApplyCertificate(crypto, key);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task<DeviceKey?> GetHistoricalSignerAsync(Guid user, Guid conversation, RecipientType type, Guid session)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
public async Task<EncryptedMessage?> ValidateAsync(string content, Guid sender, Guid conversation,
|
||||
RecipientType type, Guid? replyTo, Guid[] media, Guid? editedMessage = null)
|
||||
{
|
||||
@@ -104,12 +202,14 @@ public sealed class E2eeService(GovorDbContext context)
|
||||
.ThenInclude(c => c.SignedPreKey).SingleOrDefaultAsync(s => s.Id == envelope.Sender.SessionId &&
|
||||
s.UserId == sender && !s.IsRevoked && s.ExpiresAt > DateTime.UtcNow);
|
||||
if (signingSession?.CryptoSession is null ||
|
||||
ToDeviceKey(signingSession.CryptoSession, sender).Fingerprint != envelope.Sender.Fingerprint)
|
||||
ToDeviceKey(signingSession.CryptoSession, sender).Fingerprint != envelope.Sender.Fingerprint ||
|
||||
signingSession.CryptoSession.AccountIdentityKey != envelope.Sender.AccountIdentityKey ||
|
||||
signingSession.CryptoSession.Generation != envelope.Sender.Generation)
|
||||
throw new UnauthorizedAccessException("E2EE signing device is unknown or revoked.");
|
||||
var directory = await GetConversationKeysAsync(sender, conversation, type);
|
||||
var expected = directory.Devices.Select(k => k.Fingerprint).Distinct().Order(StringComparer.Ordinal);
|
||||
if (!expected.SequenceEqual(envelope.Recipients.Order(StringComparer.Ordinal)))
|
||||
throw new ArgumentException("Conversation devices changed. Reload and verify the recipient keys.");
|
||||
throw new ArgumentException(E2eeProtocol.DevicesChangedError);
|
||||
return envelope;
|
||||
}
|
||||
|
||||
@@ -117,5 +217,9 @@ public sealed class E2eeService(GovorDbContext context)
|
||||
new(user ?? session.UserSession.UserId, session.UserSessionId,
|
||||
Convert.ToBase64String(session.PublicIdentityKey),
|
||||
Convert.ToBase64String(session.SignedPreKey.PublicSignedPreKey),
|
||||
Convert.ToBase64String(session.SignedPreKey.SignedPreKeySignature));
|
||||
Convert.ToBase64String(session.SignedPreKey.SignedPreKeySignature))
|
||||
{
|
||||
AccountIdentityKey = session.AccountIdentityKey, AccountSignature = session.AccountSignature,
|
||||
Generation = session.Generation, PreviousFingerprint = session.PreviousFingerprint
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user