mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-17 21:09:00 +00:00
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:
@@ -33,6 +33,8 @@ public static class ConfigurationProgramExtensions
|
||||
public static void AddServices(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped<Govor.Application.E2ee.E2eeService>();
|
||||
services.AddSingleton<PasswordChallenges>();
|
||||
services.AddScoped<PasswordAccountService>();
|
||||
services.AddSingleton<IPasswordHasher, PasswordHasher>();
|
||||
services.AddSingleton<IUsernameValidator, UsernameValidator>();
|
||||
services.AddSingleton<IJwtTokenHasher, JwtTokenHasher>();
|
||||
|
||||
@@ -6,11 +6,15 @@ using Govor.Contracts.Requests;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SmartRes;
|
||||
using Govor.Application.Infrastructure.Extensions;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Govor.API.Controllers.Authentication;
|
||||
|
||||
[ApiController]
|
||||
[AllowAnonymous]
|
||||
[Authorize(Roles = "User,Admin")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
[Route("api/[controller]")]
|
||||
public class AuthController : Controller
|
||||
{
|
||||
@@ -19,28 +23,46 @@ public class AuthController : Controller
|
||||
private IAccountService _accountService;
|
||||
private ILogger<AuthController> _logger;
|
||||
private readonly IChatNotificationService _notifier;
|
||||
private readonly PasswordAccountService _passwords;
|
||||
private readonly ICurrentUserService _current;
|
||||
private readonly ICurrentUserSessionService _currentSession;
|
||||
|
||||
public AuthController(
|
||||
IAccountService accountService,
|
||||
IInvitesService invitesService,
|
||||
IUserSessionOpener userSessionOpener,
|
||||
ILogger<AuthController> logger,
|
||||
IChatNotificationService notifier)
|
||||
IChatNotificationService notifier,
|
||||
PasswordAccountService passwords = null,
|
||||
ICurrentUserService current = null,
|
||||
ICurrentUserSessionService currentSession = null)
|
||||
{
|
||||
_userSession = userSessionOpener;
|
||||
_accountService = accountService;
|
||||
_invitesService = invitesService;
|
||||
_logger = logger;
|
||||
_notifier = notifier;
|
||||
_passwords = passwords;
|
||||
_current = current;
|
||||
_currentSession = currentSession;
|
||||
}
|
||||
|
||||
[HttpPost("register")] // api/auth/register
|
||||
[AllowAnonymous, EnableRateLimiting("password-auth"), HttpPost("register")] // api/auth/register
|
||||
public async Task<IActionResult> Register([FromBody] RegistrationRequest request)
|
||||
{
|
||||
_logger.LogInformation("Processing registration request for: {Name}", request.Name);
|
||||
|
||||
PasswordCredentials credentials = null;
|
||||
if (request.SrpVerifier is not null)
|
||||
{
|
||||
credentials = new(1, request.SrpSalt, request.SrpIdentity, request.SrpVerifier);
|
||||
try { PasswordProtocol.Validate(credentials); }
|
||||
catch (CryptographicException) { return BadRequest("Invalid SRP credentials."); }
|
||||
}
|
||||
var result = await _invitesService.ValidateAsync(request.InviteLink)
|
||||
.BindAsync(invite => _accountService.RegistrationAsync(request.Name, request.Password, invite))
|
||||
.BindAsync(invite => credentials is null
|
||||
? _accountService.RegistrationAsync(request.Name, request.Password, invite)
|
||||
: _accountService.RegistrationWithPasswordProofAsync(request.Name, credentials, invite))
|
||||
.TapAsync(user => _logger.LogInformation("User {Username} ({Id}) registered successfully", user.Username, user.Id))
|
||||
.BindAsync(async user =>
|
||||
{
|
||||
@@ -62,7 +84,7 @@ public class AuthController : Controller
|
||||
return result.ToActionResult();
|
||||
}
|
||||
|
||||
[HttpPost("login")] // api/auth/login
|
||||
[AllowAnonymous, EnableRateLimiting("password-auth"), HttpPost("login")] // api/auth/login
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest request)
|
||||
{
|
||||
_logger.LogInformation("Processing registration request for: {Name}", request.Name);
|
||||
@@ -83,4 +105,77 @@ public class AuthController : Controller
|
||||
|
||||
return result.ToActionResult();
|
||||
}
|
||||
[AllowAnonymous, EnableRateLimiting("password-auth"), HttpPost("password/challenge")]
|
||||
public Task<IActionResult> Challenge(PasswordChallengeRequest request) =>
|
||||
Execute(async () => Ok(await _passwords.StartAsync(request)));
|
||||
|
||||
[AllowAnonymous, EnableRateLimiting("password-auth"), HttpPost("password/login")]
|
||||
public Task<IActionResult> Login(PasswordProof proof) => Execute(async () =>
|
||||
{
|
||||
return Ok(await _passwords.LoginAsync(proof, _userSession));
|
||||
});
|
||||
|
||||
[HttpGet("password")]
|
||||
public Task<IActionResult> Configuration() =>
|
||||
Execute(async () => Ok(await _passwords.GetAsync(_current.GetCurrentUserId())));
|
||||
|
||||
[HttpPut("password/enrollment")]
|
||||
public Task<IActionResult> Enroll(PasswordEnrollmentRequest request) => Execute(async () =>
|
||||
{
|
||||
await _passwords.EnrollAsync(_current.GetCurrentUserId(), request);
|
||||
return Ok(new { enrolled = true });
|
||||
});
|
||||
|
||||
[HttpPut("password/recovery")]
|
||||
public Task<IActionResult> SaveEnvelope(SavePasswordEnvelope request) => Execute(async () =>
|
||||
{
|
||||
await _passwords.SaveEnvelopeAsync(_current.GetCurrentUserId(), request.Envelope);
|
||||
return Ok(new { saved = true });
|
||||
});
|
||||
|
||||
[EnableRateLimiting("password-auth"), HttpPost("password/{purpose:regex(^(change|reset)$)}/challenge")]
|
||||
public Task<IActionResult> ActionChallenge(string purpose, PasswordChallengeRequest request) => Execute(async () =>
|
||||
Ok(await _passwords.StartAsync(request, purpose, _current.GetCurrentUserId(), _currentSession.GetUserSessionId())));
|
||||
|
||||
[EnableRateLimiting("password-auth"), HttpPost("password/{purpose:regex(^(change|reset)$)}/authorize")]
|
||||
public Task<IActionResult> AuthorizeAction(string purpose, PasswordProof proof) => Execute(async () =>
|
||||
Ok(await _passwords.AuthorizeAsync(_current.GetCurrentUserId(), _currentSession.GetUserSessionId(), proof,
|
||||
purpose)));
|
||||
|
||||
[HttpPost("password/change")]
|
||||
public Task<IActionResult> Change(ChangePasswordRequest request) => Execute(async () =>
|
||||
{
|
||||
await _passwords.ChangeAsync(_current.GetCurrentUserId(), _currentSession.GetUserSessionId(), request);
|
||||
return Ok(new { changed = true });
|
||||
});
|
||||
|
||||
[HttpPost("password/reset-encryption")]
|
||||
[RequestSizeLimit(4_120_000)]
|
||||
public Task<IActionResult> Reset(ResetEncryptionRequest request) => Execute(async () =>
|
||||
Ok(await _passwords.ResetAsync(_current.GetCurrentUserId(), _currentSession.GetUserSessionId(), request)));
|
||||
|
||||
private async Task<IActionResult> Execute(Func<Task<IActionResult>> action)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await action();
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return Unauthorized("Password proof is incorrect or expired.");
|
||||
}
|
||||
catch (Microsoft.EntityFrameworkCore.DbUpdateException)
|
||||
{
|
||||
return Conflict("Account changed. Retry the operation.");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return Conflict(ex.Message);
|
||||
}
|
||||
catch (Exception ex) when (ex is CryptographicException or ArgumentException or FormatException or
|
||||
System.Text.Json.JsonException or KeyNotFoundException)
|
||||
{
|
||||
return BadRequest("Invalid password authentication data.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,13 @@ public sealed class E2eeController(
|
||||
[HttpGet("recovery")]
|
||||
public async Task<IActionResult> Recovery() => Ok(await e2ee.GetRecoveryAsync(user.GetCurrentUserId()));
|
||||
|
||||
[HttpGet("identities/{peer:guid}/changes")]
|
||||
public async Task<IActionResult> IdentityChanges(Guid peer)
|
||||
{
|
||||
try { return Ok(await e2ee.GetIdentityChangesAsync(user.GetCurrentUserId(), peer)); }
|
||||
catch (UnauthorizedAccessException) { return Forbid(); }
|
||||
}
|
||||
|
||||
[HttpGet("devices")]
|
||||
public async Task<IActionResult> Devices() => Ok(await e2ee.GetOwnDevicesAsync(user.GetCurrentUserId()));
|
||||
|
||||
@@ -55,12 +62,13 @@ public sealed class E2eeController(
|
||||
}
|
||||
|
||||
[HttpGet("conversations/{type:int}/{conversationId:guid}/signers/{deviceSession:guid}")]
|
||||
public async Task<IActionResult> HistoricalSigner(int type, Guid conversationId, Guid deviceSession)
|
||||
public async Task<IActionResult> HistoricalSigner(int type, Guid conversationId, Guid deviceSession, [FromQuery] string identityKey = null)
|
||||
{
|
||||
if (type is < 0 or > 1) return BadRequest();
|
||||
try
|
||||
{
|
||||
var key = await e2ee.GetHistoricalSignerAsync(user.GetCurrentUserId(), conversationId, (RecipientType)type, deviceSession);
|
||||
if (identityKey?.Length > 1000) return BadRequest();
|
||||
var key = await e2ee.GetHistoricalSignerAsync(user.GetCurrentUserId(), conversationId, (RecipientType)type, deviceSession, identityKey);
|
||||
return key is null ? NotFound() : Ok(key);
|
||||
}
|
||||
catch (UnauthorizedAccessException) { return Forbid(); }
|
||||
|
||||
@@ -105,6 +105,13 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
options.AddPolicy("password-auth", context => System.Threading.RateLimiting.RateLimitPartition.GetFixedWindowLimiter(
|
||||
context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new System.Threading.RateLimiting.FixedWindowRateLimiterOptions
|
||||
{ PermitLimit = 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
|
||||
});
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
@@ -175,6 +182,7 @@ app.UseSwaggerUI();
|
||||
//app.UseHttpsRedirection();
|
||||
|
||||
app.UseRouting();
|
||||
app.UseRateLimiter();
|
||||
app.UseCors("AllowFrontend");
|
||||
|
||||
app.UseAuthentication();
|
||||
@@ -210,4 +218,4 @@ app.MapSwagger()
|
||||
|
||||
app.Map("/", () => "Not for browsers");
|
||||
|
||||
app.Run();
|
||||
app.Run();
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -3,17 +3,31 @@ using Govor.Domain.Common.Constants;
|
||||
|
||||
namespace Govor.Contracts.Requests;
|
||||
|
||||
public record RegistrationRequest
|
||||
public record RegistrationRequest : IValidatableObject
|
||||
{
|
||||
[Required]
|
||||
[StringLength(UserConstants.MAX_LENGHT_OF_NAME,
|
||||
MinimumLength = UserConstants.MIN_LENGHT_OF_NAME,
|
||||
ErrorMessage = "Username must be between 4 and 44 characters.")]
|
||||
public string Name { get; init; }
|
||||
[Required]
|
||||
[MinLength(8)]
|
||||
public string Password { get; init; }
|
||||
public string? Password { get; init; }
|
||||
public string? SrpSalt { get; init; }
|
||||
public string? SrpIdentity { get; init; }
|
||||
public string? SrpVerifier { get; init; }
|
||||
[MinLength(InvitationConstants.MIN_INVITATION_LENGTH)]
|
||||
public string InviteLink { get; init; }
|
||||
public string DeviceInfo { get; init; }
|
||||
|
||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||
{
|
||||
var proofRegistration = SrpSalt is not null || SrpIdentity is not null || SrpVerifier is not null;
|
||||
if (proofRegistration)
|
||||
{
|
||||
if (Password is not null || SrpSalt is null || SrpIdentity is null || SrpVerifier is null)
|
||||
yield return new ValidationResult("Provide complete SRP credentials without a plaintext password.");
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(Password))
|
||||
yield return new ValidationResult("Password is required.", [nameof(Password)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ public class E2eeRecoveryVaultConfiguration : IEntityTypeConfiguration<E2eeRecov
|
||||
b.Property(v => v.IdentityKey).HasMaxLength(200);
|
||||
b.Property(v => v.Signature).HasMaxLength(100);
|
||||
b.Property(v => v.Ciphertext).HasMaxLength(4_000_000);
|
||||
b.Property(v => v.PasswordCiphertext).HasMaxLength(4096);
|
||||
b.Property(v => v.PasswordSignature).HasMaxLength(100);
|
||||
b.HasOne<User>().WithOne().HasForeignKey<E2eeRecoveryVault>(v => v.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,10 @@ public class UserConfiguration : IEntityTypeConfiguration<User>
|
||||
public void Configure(EntityTypeBuilder<User> builder)
|
||||
{
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(u => u.SrpSalt).HasMaxLength(64);
|
||||
builder.Property(u => u.SrpIdentity).HasMaxLength(64);
|
||||
builder.Property(u => u.SrpVerifier).HasMaxLength(1024);
|
||||
builder.Property(u => u.CredentialVersion).IsConcurrencyToken();
|
||||
|
||||
builder.HasIndex(u => u.Username).IsUnique();
|
||||
builder.HasIndex(u => u.CreatedOn);
|
||||
@@ -32,4 +36,4 @@ public class UserConfiguration : IEntityTypeConfiguration<User>
|
||||
.IsRequired()
|
||||
.HasMaxLength(128);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ public class GovorDbContext(DbContextOptions<GovorDbContext> options) : DbContex
|
||||
public virtual DbSet<UserPushToken> UserPushTokens { get; set; }
|
||||
public virtual DbSet<UserCryptoSession> UserCryptoSessions { get; set; }
|
||||
public virtual DbSet<E2eeRecoveryVault> E2eeRecoveryVaults { get; set; }
|
||||
public DbSet<E2eeIdentityChange> E2eeIdentityChanges { get; set; }
|
||||
public virtual DbSet<SignedPreKey> SignedPreKeys { get; set; }
|
||||
public virtual DbSet<OneTimePreKey> OneTimePreKeys { get; set; }
|
||||
public virtual DbSet<Friendship> Friendships { get; set; }
|
||||
@@ -42,6 +43,14 @@ public class GovorDbContext(DbContextOptions<GovorDbContext> options) : DbContex
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<E2eeIdentityChange>(b =>
|
||||
{
|
||||
b.HasKey(c => new { c.UserId, c.Epoch });
|
||||
b.Property(c => c.PreviousIdentityKey).HasMaxLength(200);
|
||||
b.Property(c => c.IdentityKey).HasMaxLength(200);
|
||||
b.Property(c => c.PreviousDeviceKeyJson).HasMaxLength(10000);
|
||||
b.HasOne<User>().WithMany().HasForeignKey(c => c.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
modelBuilder.ApplyConfiguration(new E2eeRecoveryVaultConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new UserSessionConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new FriendshipConfiguration());
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,131 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Govor.Domain.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class PasswordBasedRecovery : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<long>(
|
||||
name: "CredentialVersion",
|
||||
table: "Users",
|
||||
type: "bigint",
|
||||
nullable: false,
|
||||
defaultValue: 0L);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "SrpIdentity",
|
||||
table: "Users",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "SrpSalt",
|
||||
table: "Users",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "SrpVerifier",
|
||||
table: "Users",
|
||||
type: "character varying(1024)",
|
||||
maxLength: 1024,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<long>(
|
||||
name: "Epoch",
|
||||
table: "E2eeRecoveryVaults",
|
||||
type: "bigint",
|
||||
nullable: false,
|
||||
defaultValue: 0L);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "PasswordCiphertext",
|
||||
table: "E2eeRecoveryVaults",
|
||||
type: "character varying(4096)",
|
||||
maxLength: 4096,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<long>(
|
||||
name: "PasswordCredentialVersion",
|
||||
table: "E2eeRecoveryVaults",
|
||||
type: "bigint",
|
||||
nullable: false,
|
||||
defaultValue: 0L);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "PasswordSignature",
|
||||
table: "E2eeRecoveryVaults",
|
||||
type: "character varying(100)",
|
||||
maxLength: 100,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "E2eeIdentityChanges",
|
||||
columns: table => new
|
||||
{
|
||||
UserId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Epoch = table.Column<long>(type: "bigint", nullable: false),
|
||||
PreviousIdentityKey = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
IdentityKey = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
ChangedAt = table.Column<long>(type: "bigint", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_E2eeIdentityChanges", x => new { x.UserId, x.Epoch });
|
||||
table.ForeignKey(
|
||||
name: "FK_E2eeIdentityChanges_Users_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "E2eeIdentityChanges");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CredentialVersion",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "SrpIdentity",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "SrpSalt",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "SrpVerifier",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Epoch",
|
||||
table: "E2eeRecoveryVaults");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PasswordCiphertext",
|
||||
table: "E2eeRecoveryVaults");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PasswordCredentialVersion",
|
||||
table: "E2eeRecoveryVaults");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PasswordSignature",
|
||||
table: "E2eeRecoveryVaults");
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Govor.Domain.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class PreserveResetSigners : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "PreviousDeviceKeyJson",
|
||||
table: "E2eeIdentityChanges",
|
||||
type: "character varying(10000)",
|
||||
maxLength: 10000,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "PreviousSessionId",
|
||||
table: "E2eeIdentityChanges",
|
||||
type: "uuid",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PreviousDeviceKeyJson",
|
||||
table: "E2eeIdentityChanges");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PreviousSessionId",
|
||||
table: "E2eeIdentityChanges");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -797,6 +797,39 @@ namespace Govor.Domain.Migrations
|
||||
b.ToTable("Admins");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeIdentityChange", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<long>("Epoch")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<long>("ChangedAt")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("IdentityKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("PreviousDeviceKeyJson")
|
||||
.HasMaxLength(10000)
|
||||
.HasColumnType("character varying(10000)");
|
||||
|
||||
b.Property<string>("PreviousIdentityKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<Guid?>("PreviousSessionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("UserId", "Epoch");
|
||||
|
||||
b.ToTable("E2eeIdentityChanges");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
@@ -807,11 +840,25 @@ namespace Govor.Domain.Migrations
|
||||
.HasMaxLength(4000000)
|
||||
.HasColumnType("character varying(4000000)");
|
||||
|
||||
b.Property<long>("Epoch")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("IdentityKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("PasswordCiphertext")
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)");
|
||||
|
||||
b.Property<long>("PasswordCredentialVersion")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("PasswordSignature")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<long>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("bigint");
|
||||
@@ -927,6 +974,10 @@ namespace Govor.Domain.Migrations
|
||||
b.Property<DateOnly>("CreatedOn")
|
||||
.HasColumnType("date");
|
||||
|
||||
b.Property<long>("CredentialVersion")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
@@ -942,6 +993,18 @@ namespace Govor.Domain.Migrations
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("SrpIdentity")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("SrpSalt")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("SrpVerifier")
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("character varying(1024)");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
@@ -1279,6 +1342,15 @@ namespace Govor.Domain.Migrations
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeIdentityChange", b =>
|
||||
{
|
||||
b.HasOne("Govor.Domain.Models.Users.User", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.E2eeRecoveryVault", b =>
|
||||
{
|
||||
b.HasOne("Govor.Domain.Models.Users.User", null)
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Govor.Domain.Models.Users.Crypto;
|
||||
|
||||
public sealed class E2eeIdentityChange
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public long Epoch { get; set; }
|
||||
public string PreviousIdentityKey { get; set; } = "";
|
||||
public string IdentityKey { get; set; } = "";
|
||||
public long ChangedAt { get; set; }
|
||||
public Guid? PreviousSessionId { get; set; }
|
||||
public string? PreviousDeviceKeyJson { get; set; }
|
||||
}
|
||||
@@ -7,4 +7,8 @@ public sealed class E2eeRecoveryVault
|
||||
public string IdentityKey { get; set; } = "";
|
||||
public string Ciphertext { get; set; } = "";
|
||||
public string Signature { get; set; } = "";
|
||||
public long Epoch { get; set; }
|
||||
public long PasswordCredentialVersion { get; set; }
|
||||
public string? PasswordCiphertext { get; set; }
|
||||
public string? PasswordSignature { get; set; }
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@ public class User
|
||||
public string Username {get; set;}
|
||||
public string Description {get; set;}
|
||||
public string PasswordHash {get; set;}
|
||||
public string? SrpSalt { get; set; }
|
||||
public string? SrpIdentity { get; set; }
|
||||
public string? SrpVerifier { get; set; }
|
||||
public long CredentialVersion { get; set; }
|
||||
public Guid IconId {get; set;}
|
||||
public DateOnly CreatedOn {get; set;}
|
||||
public DateTime WasOnline {get; set;}
|
||||
@@ -22,4 +26,4 @@ public class User
|
||||
|
||||
return Id == user.Id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+21
-14
@@ -5,11 +5,12 @@
|
||||
После входа актуальный клиент автоматически создаёт ключи, публикует только
|
||||
публичные данные и регистрирует устройство. После добавления друга или вступления
|
||||
в группу сообщения и файлы шифруются без диалогов сверки ключей или состава чата.
|
||||
На новом физическом устройстве нужно один раз ввести код с доверенного устройства
|
||||
(Настройки → Перенос истории / резервный код) либо сохранённый резервный код.
|
||||
После этого клиент скачивает зашифрованный архив и расшифровывает прежние сообщения
|
||||
и ключи вложений. Передача кода выполняется пользователем между своими устройствами;
|
||||
отдельного протокола QR-сопряжения или удалённого одобрения устройства пока нет.
|
||||
На новом физическом устройстве обычный вход восстанавливает историю по паролю,
|
||||
если парольная копия ключа уже настроена. Для прежнего архива без такой копии
|
||||
нужен код с доверенного устройства (Настройки → Перенос истории / резервный код)
|
||||
либо сохранённый резервный код. После восстановления копия настраивается автоматически.
|
||||
Подробные сценарии входа, смены/сброса пароля и команды запуска описаны в
|
||||
[password-recovery.md](password-recovery.md). QR-сопряжения пока нет.
|
||||
|
||||
Это расширение существующего протокола JOSE, **не реализация Signal/MLS**.
|
||||
Ротация ограничивает использование отдельного украденного ключа шифрования после
|
||||
@@ -31,8 +32,9 @@ forward secrecy или post-compromise security. Восстанавливаем
|
||||
|
||||
MAUI SecureStorage хранит приватные ключи устройств, резервный код, ключ аккаунта,
|
||||
архив ключей расшифровки и отпечатки известных аккаунтов. Область хранения разделена
|
||||
по адресу сервера и пользователю. Пароль аккаунта сам по себе не восстанавливает
|
||||
историю. При потере всех устройств и резервного кода восстановление невозможно.
|
||||
по адресу сервера и пользователю. Производный парольный ключ открывает отдельную
|
||||
зашифрованную копию резервного кода. Потеря прежнего пароля, всех устройств и кода
|
||||
делает старую историю невосстановимой; явный сброс позволяет начать с новыми ключами.
|
||||
|
||||
Сервер хранит публичные ключи, сертификаты, номера поколений и зашифрованный архив.
|
||||
В архив входят приватный ключ аккаунта, прежние RSA-ключи расшифровки с публичными
|
||||
@@ -46,8 +48,9 @@ MAUI SecureStorage хранит приватные ключи устройств
|
||||
связывает UserId, SessionId, отпечаток устройства, поколение и предыдущий отпечаток
|
||||
с этим ключом аккаунта. Новое устройство или ротация с тем же ключом аккаунта
|
||||
не требуют ручной сверки. Подмена уже известного ключа аккаунта блокирует отправку
|
||||
и отображение новых неподтверждённых данных. Автоматического сброса доверия нет;
|
||||
безопасный UX намеренной замены ключа аккаунта — отдельная будущая функция.
|
||||
и отображение новых неподтверждённых данных. Явный сброс после потери доступа
|
||||
публикует серверный журнал замены корневого ключа; клиент уведомляет собеседника
|
||||
при первом использовании нового ключа. Журнал является частью доверия серверу.
|
||||
|
||||
**Первая встреча доверяет каталогу сервера.** Прозрачности ключей нет. Состав группы
|
||||
и право вступления по-прежнему сообщает сервер; состав не подписывается участниками.
|
||||
@@ -80,8 +83,8 @@ MAUI SecureStorage хранит приватные ключи устройств
|
||||
Отзыв сессии исключает её из новых получателей, но не отзывает уже прочитанное,
|
||||
украденные секреты или ранее выгруженный архив. Резервный код и ключ аккаунта пока
|
||||
не ротируются автоматически. После компрометации всего устройства недостаточно
|
||||
обычной недельной ротации RSA; это требует отдельной процедуры восстановления
|
||||
доверия, отзыва сессий и замены секретов аккаунта.
|
||||
обычной недельной ротации RSA; в настройках есть отдельный явный сброс ключей
|
||||
аккаунта и кода с отзывом остальных сессий. Он не отменяет уже раскрытые данные.
|
||||
|
||||
## Архив и несколько устройств
|
||||
|
||||
@@ -91,7 +94,8 @@ IdentityKey и шифротекст. Внутри JWE также проверя
|
||||
|
||||
Обновление использует compare-and-swap по Revision. При конфликте клиент скачивает
|
||||
актуальную версию, объединяет ключи и известные аккаунты, затем повторяет запись
|
||||
(не более четырёх попыток). Ключ аккаунта на сервере неизменяем. Известная локально
|
||||
(не более четырёх попыток). Обычный маршрут архива не меняет ключ аккаунта;
|
||||
для этого требуется отдельный сброс со свежим доказательством пароля. Известная локально
|
||||
версия запрещает откат архива; новое устройство без сохранённого номера версии
|
||||
не способно доказать полноту истории при сокрытии последнего архива сервером.
|
||||
Обычная синхронизация выполняется не чаще раза в минуту, а регистрация нового
|
||||
@@ -122,12 +126,15 @@ IdentityKey и шифротекст. Внутри JWE также проверя
|
||||
|
||||
## Обновление существующих установок
|
||||
|
||||
1. Применить миграцию `20261024084524_E2eeRecoveryAndRotation` до обновления клиентов.
|
||||
1. Применить миграции `20261024084524_E2eeRecoveryAndRotation` и
|
||||
`20261024105815_PasswordBasedRecovery`, `20261024114709_PreserveResetSigners`
|
||||
до обновления клиентов.
|
||||
Сервер и клиенты должны обновляться согласованно. Старые клиенты не умеют
|
||||
сертифицировать устройства аккаунта с настроенным восстановлением.
|
||||
2. Открыть обновлённый клиент на устройстве, где ещё есть прежние ключи. Они входят
|
||||
в архив до публикации нового ключа; сохранить предложенный резервный код.
|
||||
3. На остальных устройствах ввести этот код и синхронизировать историю. Каждое
|
||||
3. Выполнить обновлённый вход на устройстве с ключами для создания парольной копии.
|
||||
На остальных устройствах войти по паролю; пока копии нет, нужен прежний код. Каждое
|
||||
старое устройство с уникальными, ещё не выгруженными ключами должно обновиться
|
||||
хотя бы один раз: отсутствующие приватные ключи сервер восстановить не может.
|
||||
4. Перед использованием с реальными данными проверить новый вход, восстановление,
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
# Вход по паролю и восстановление E2EE
|
||||
|
||||
## Пользовательские сценарии
|
||||
|
||||
Регистрация остаётся на экране регистрации и использует единственный
|
||||
`POST /api/auth/register` в `AuthController`. Отдельного контроллера регистрации нет.
|
||||
Новый клиент передаёт SRP salt/identity/verifier вместо открытого пароля.
|
||||
Существующие проверки имени, приглашения и обязательного канала сохранены.
|
||||
|
||||
После настройки парольной копии ключа обычный вход на новом устройстве восстанавливает
|
||||
зашифрованный архив истории автоматически. Пароль не хранится и не передаётся серверу
|
||||
новым методом входа. Локально в SecureStorage сохраняется производный ключ архива.
|
||||
Резервный код остаётся дополнительным способом переноса и восстановления.
|
||||
|
||||
В настройках доступны:
|
||||
|
||||
- **Сменить пароль с сохранением истории**: подтверждение прежнего пароля, новый
|
||||
пароль с повтором, перешифрование копии кода; ключ аккаунта и история сохраняются.
|
||||
Другие сессии и их push-токены отзываются.
|
||||
- **Начать общение с новыми ключами**: подтверждение потери истории и текущего пароля;
|
||||
создаются новый ключ аккаунта, код и ключи устройства, другие сессии отзываются.
|
||||
Собеседник получает уведомление при первой обработке нового ключа. Сверять ключи
|
||||
вручную не нужно. Необъявленная подмена закреплённого ключа по-прежнему блокируется.
|
||||
|
||||
Если забыт пароль, администратор может сбросить доступ к аккаунту, но этим не
|
||||
расшифровывает старую историю. После входа с выданным паролем пользователь задаёт
|
||||
новый пароль и восстанавливает прежний архив резервным кодом/с доверенного устройства.
|
||||
Без прежнего пароля, кода и доступного устройства старую историю восстановить нельзя;
|
||||
можно явно начать общение с новыми ключами. Уже полученная собеседниками история
|
||||
современных сертифицированных сообщений у них сохраняется.
|
||||
|
||||
## Переход со старого входа
|
||||
|
||||
Старый bcrypt-аккаунт один раз требует выбрать **другой** пароль. Только в этой
|
||||
явной процедуре старый пароль проверяется прежним серверным методом; новый пароль
|
||||
в сеть не отправляется. Сервер проверяет различие паролей, а не только UI.
|
||||
Если на сервере уже был архив без парольной копии, для первого восстановления
|
||||
всё ещё нужен прежний код либо устройство с ключами. Неизвестные секреты сервер
|
||||
не может создать задним числом. Старая refresh-сессия без нового входа также не
|
||||
имеет производного парольного ключа.
|
||||
|
||||
Клиент запоминает успешный SRP-вход для адреса сервера и имени. Если сервер позже
|
||||
предлагает старый вход, автоматической отправки пароля не происходит. На экране
|
||||
появляется действие «Продолжить после сброса пароля» только после такой ошибки.
|
||||
Обычная ссылка «Зарегистрируйтесь!» остаётся на месте. Первый вход с чистого
|
||||
устройства всё ещё доверяет настоящему серверу и HTTPS, включая предложение миграции.
|
||||
|
||||
## Протокол и хранение
|
||||
|
||||
Используется SRP-6a из `srp` 1.0.7 / srp.net, группа 4096 бит и SHA-512.
|
||||
Это не OPAQUE и не независимо проверенная реализация всего прикладного протокола.
|
||||
PBKDF2-SHA256 (600 000 итераций, случайная соль 32 байта) и отдельные контексты
|
||||
HKDF-SHA256 дают секрет аутентификации и ключ парольной копии. Они не совпадают;
|
||||
восстановление не использует общий сеансовый SRP-ключ.
|
||||
|
||||
Случайный резервный код шифрует основной архив. Парольный ключ шифрует копию кода
|
||||
в JWE dir/A256GCM. Подпись ключа аккаунта связывает её с владельцем, текущими SRP
|
||||
параметрами и версией учётных данных. Изменение пароля атомарно меняет verifier
|
||||
и эту копию. Сброс забытого пароля очищает парольную копию, сохраняя основной архив.
|
||||
В БД нет открытого пароля, кода или приватного ключа аккаунта. Однако кража БД
|
||||
позволяет подбирать слабые пароли офлайн; восстановление по паролю зависит от
|
||||
его стойкости. Получив пароль и архив, атакующий получает доступ к истории.
|
||||
|
||||
Challenge и подтверждения действий одноразовые, действуют две минуты; подтверждения
|
||||
смены пароля/сброса связаны с пользователем, сессией и назначением. Изменение версии
|
||||
учётных данных инвалидирует начатые доказательства. На клиенте журналы смены пароля
|
||||
и сброса ключей позволяют проверить серверный результат после потери ответа до
|
||||
замены локальных секретов. Старый пароль при нормальном входе не отправляется.
|
||||
|
||||
Замена ключа аккаунта публикуется в журнале `E2eeIdentityChanges` с последовательным
|
||||
epoch. Журнал доступен самому аккаунту и собеседникам с доступом к переписке;
|
||||
участник группы может проверить автора сохранённых сообщений после его выхода.
|
||||
Сервер авторизует сброс по свежему доказательству пароля, а не по подписи утраченного
|
||||
ключа. Это явная часть доверия серверу, не криптографическое доказательство
|
||||
непрерывности старого ключа. Исторические сертифицированные сообщения до сброса
|
||||
принимаются без отката текущего закреплённого ключа.
|
||||
|
||||
Публичный сертификат прежнего ключа текущей сессии сохраняется отдельно в журнале
|
||||
сброса: он нужен для проверки v1-сообщений, в которых ещё нет сертификата внутри.
|
||||
Запрос исторического автора принимает `identityKey` и проверяет доступ к чату;
|
||||
архивный сертификат не становится получателем новых сообщений и не возобновляет сессию.
|
||||
|
||||
Хранилище challenge пока находится в памяти процесса (лимит 1024). Для нескольких
|
||||
экземпляров нужны маршрутизация всего обмена на один экземпляр либо распределённое
|
||||
одноразовое хранилище. Лимит регистрации, входа и доказательств действий —
|
||||
30 запросов/минуту на RemoteIpAddress; фоновое чтение парольной копии в него не входит.
|
||||
За reverse proxy необходимо настроить доверенные forwarded headers и подходящие
|
||||
лимиты. HTTPS обязателен. Криптографический аудит и нагрузочная проверка нужны
|
||||
перед публичным выпуском. Ограничения FS/PCS и доверия группам из [e2ee.md](e2ee.md)
|
||||
сохраняются; парольное восстановление их не устраняет.
|
||||
|
||||
## API
|
||||
|
||||
Все маршруты находятся в `AuthController`. Регистрация и challenge/login анонимные;
|
||||
остальные требуют access token и определяют владельца из JWT.
|
||||
|
||||
| Метод | Маршрут | Назначение |
|
||||
| --- | --- | --- |
|
||||
| POST | /api/auth/register | Единая регистрация: SRP либо совместимый старый формат |
|
||||
| POST | /api/auth/password/challenge | Начать вход |
|
||||
| POST | /api/auth/password/login | Проверить доказательство; токены и серверное доказательство |
|
||||
| GET | /api/auth/password | Собственные параметры и зашифрованная копия кода |
|
||||
| PUT | /api/auth/password/enrollment | Однократное обновление старого входа |
|
||||
| PUT | /api/auth/password/recovery | Создать подписанную парольную копию кода |
|
||||
| POST | /api/auth/password/{change\|reset}/challenge | Начать подтверждение действия |
|
||||
| POST | /api/auth/password/{change\|reset}/authorize | Получить одноразовое разрешение |
|
||||
| POST | /api/auth/password/change | Атомарная смена пароля с сохранением архива |
|
||||
| POST | /api/auth/password/reset-encryption | Явный сброс ключей, новый архив и запись журнала |
|
||||
| GET | /api/e2ee/identities/{userId}/changes | История смены ключа доступного собеседника |
|
||||
|
||||
## Локальная проверка
|
||||
|
||||
Из корня серверного репозитория, с запущенной отдельной локальной PostgreSQL
|
||||
и созданной БД `govor_dev` (подставьте собственные реквизиты):
|
||||
|
||||
```powershell
|
||||
$env:ASPNETCORE_ENVIRONMENT = 'Development'
|
||||
$env:ConnectionStrings__GovorDbContext = 'Host=127.0.0.1;Port=5432;Database=govor_dev;Username=postgres;Password=YOUR_LOCAL_PASSWORD'
|
||||
$env:Firebase__Enabled = 'false'
|
||||
dotnet restore Govor.API/Govor.API.csproj
|
||||
dotnet run --project Govor.API/Govor.API.csproj --no-launch-profile -- --migrate-only
|
||||
dotnet run --project Govor.API/Govor.API.csproj --launch-profile http
|
||||
```
|
||||
|
||||
Первый `run` применяет все миграции и завершается; второй запускает API на
|
||||
`http://localhost:7155`. HTTP предназначен для локальной проверки. Для проверки
|
||||
на устройстве настройте доступный устройству адрес и HTTPS.
|
||||
Новые миграции — `20261024105815_PasswordBasedRecovery` и
|
||||
`20261024114709_PreserveResetSigners`, после `20261024084524_E2eeRecoveryAndRotation`.
|
||||
Пользовательская БД агентом не обновлялась.
|
||||
|
||||
Проверить регистрацию, повторный вход с чистым SecureStorage без ввода кода,
|
||||
смену пароля и вход новым паролем, восстановление кодом после административного
|
||||
сброса, явный сброс ключей и уведомление на втором аккаунте. Отдельно проверить
|
||||
потерю ответа при смене пароля/сбросе и повторный запуск клиента.
|
||||
|
||||
```powershell
|
||||
dotnet test Govor.Server.slnx
|
||||
# Из корня мобильного репозитория:
|
||||
dotnet test Govor.Mobile.Tests/Govor.Mobile.Tests.csproj
|
||||
dotnet build Govor.Mobile/Govor.Mobile.csproj -f net10.0-android -p:TargetFrameworks=net10.0-android
|
||||
```
|
||||
|
||||
Общие `PasswordProtocol` и `E2eeRecoveryProtocol` в двух репозиториях должны
|
||||
совпадать за исключением namespace. Источники SRP:
|
||||
[srp.net](https://github.com/secure-remote-password/srp.net),
|
||||
[пакет srp](https://www.nuget.org/packages/srp/1.0.7).
|
||||
@@ -0,0 +1,107 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Govor.Application.Authentication;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.Server.Tests;
|
||||
|
||||
public partial class ReadApiTests
|
||||
{
|
||||
[Test]
|
||||
public async Task PasswordAttemptsAreRateLimitedWithoutThrottlingBackgroundRecoveryReads()
|
||||
{
|
||||
var created = PasswordProtocol.Create("http-rate-limit-password");
|
||||
var user = await _db.Context.Users.SingleAsync(u => u.Id == _db.Bob);
|
||||
user.SrpSalt = created.Credentials.Salt; user.SrpIdentity = created.Credentials.Identity;
|
||||
user.SrpVerifier = created.Credentials.Verifier; user.CredentialVersion = 1;
|
||||
await _db.Context.SaveChangesAsync();
|
||||
Authorize();
|
||||
for (var attempt = 0; attempt < 31; attempt++)
|
||||
{
|
||||
using var read = await _client.GetAsync("/api/auth/password");
|
||||
Assert.That(read.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
}
|
||||
_client.DefaultRequestHeaders.Authorization = null;
|
||||
for (var attempt = 0; attempt < 31; attempt++)
|
||||
{
|
||||
using var proof = await _client.PostAsJsonAsync("/api/auth/password/challenge",
|
||||
new PasswordChallengeRequest(user.Username, new string('0', 1024)));
|
||||
Assert.That(proof.StatusCode, Is.EqualTo(attempt == 30 ? HttpStatusCode.TooManyRequests : HttpStatusCode.BadRequest));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SingleRegistrationRouteAcceptsSrpAndReturnsTokensForProtectedPasswordConfiguration()
|
||||
{
|
||||
Assert.That((await _client.GetAsync("/api/auth/password")).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
|
||||
var created = PasswordProtocol.Create("http-registration-password");
|
||||
var invitation = await _db.Context.Invitations.SingleAsync(i => i.Code == "test");
|
||||
invitation.Code = Guid.NewGuid().ToString("N");
|
||||
await _db.Context.SaveChangesAsync();
|
||||
object Request(string? password = null) => new { name = "НовыйУчастник456", inviteLink = invitation.Code,
|
||||
deviceInfo = "HTTP phone", srpSalt = created.Credentials.Salt, srpIdentity = created.Credentials.Identity,
|
||||
srpVerifier = created.Credentials.Verifier, password };
|
||||
Assert.That((await _client.PostAsJsonAsync("/api/auth/register", Request("plaintext-password"))).StatusCode,
|
||||
Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
var registered = await _client.PostAsJsonAsync("/api/auth/register", Request());
|
||||
Assert.That(registered.StatusCode, Is.EqualTo(HttpStatusCode.OK), await registered.Content.ReadAsStringAsync());
|
||||
using var tokens = JsonDocument.Parse(await registered.Content.ReadAsStringAsync());
|
||||
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokens.RootElement.GetProperty("accessToken").GetString());
|
||||
var configResponse = await _client.GetAsync("/api/auth/password");
|
||||
Assert.That(configResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK), await configResponse.Content.ReadAsStringAsync());
|
||||
Assert.That(configResponse.Headers.CacheControl?.NoStore, Is.True);
|
||||
var config = (await configResponse.Content.ReadFromJsonAsync<PasswordConfiguration>())!;
|
||||
Assert.That(config.Credentials, Is.EqualTo(created.Credentials));
|
||||
Assert.That(config.Envelope, Is.Null);
|
||||
var user = await _db.Context.Users.AsNoTracking().SingleAsync(u => u.Username == "НовыйУчастник456");
|
||||
Assert.That(user.PasswordHash, Is.EqualTo("srp-only"));
|
||||
Assert.That(user.CredentialVersion, Is.EqualTo(1));
|
||||
Assert.That((await _client.PostAsJsonAsync("/api/auth/login", new { name = user.Username,
|
||||
password = "http-registration-password", deviceInfo = "legacy" })).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HttpPasswordProofOpensSessionAndChangeRoutesConsumeSessionBoundAuthorization()
|
||||
{
|
||||
const string password = "http-password-proof";
|
||||
var created = PasswordProtocol.Create(password);
|
||||
var user = await _db.Context.Users.SingleAsync(u => u.Id == _db.Bob);
|
||||
user.PasswordHash = "srp-only"; user.SrpSalt = created.Credentials.Salt;
|
||||
user.SrpIdentity = created.Credentials.Identity; user.SrpVerifier = created.Credentials.Verifier;
|
||||
user.CredentialVersion = 1; await _db.Context.SaveChangesAsync();
|
||||
|
||||
async Task<(PasswordProof Proof, SecureRemotePassword.SrpClient Client, string Public, SecureRemotePassword.SrpSession Session)> Prove(string purpose)
|
||||
{
|
||||
var client = PasswordProtocol.Client(); var ephemeral = client.GenerateEphemeral();
|
||||
var route = purpose == "login" ? "challenge" : $"{purpose}/challenge";
|
||||
var response = await _client.PostAsJsonAsync("/api/auth/password/" + route, new PasswordChallengeRequest(user.Username, ephemeral.Public, "test phone"));
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK), await response.Content.ReadAsStringAsync());
|
||||
var challenge = (await response.Content.ReadFromJsonAsync<PasswordChallenge>())!;
|
||||
var derived = PasswordProtocol.Derive(password, challenge.Salt, challenge.Identity);
|
||||
var session = client.DeriveSession(ephemeral.Secret, challenge.PublicEphemeral, challenge.Salt, challenge.Identity,
|
||||
client.DerivePrivateKey(challenge.Salt, challenge.Identity, derived.Secret));
|
||||
return (new(challenge.ChallengeId, session.Proof), client, ephemeral.Public, session);
|
||||
}
|
||||
var login = await Prove("login");
|
||||
var response = await _client.PostAsJsonAsync("/api/auth/password/login", login.Proof);
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK), await response.Content.ReadAsStringAsync());
|
||||
var authenticated = (await response.Content.ReadFromJsonAsync<PasswordLoginResult>())!;
|
||||
login.Client.VerifySession(login.Public, login.Session, authenticated.ServerProof);
|
||||
Assert.That((await _client.PostAsJsonAsync("/api/auth/password/login", login.Proof)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
|
||||
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticated.AccessToken);
|
||||
var action = await Prove("change");
|
||||
var grantResponse = await _client.PostAsJsonAsync("/api/auth/password/change/authorize", action.Proof);
|
||||
Assert.That(grantResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK), await grantResponse.Content.ReadAsStringAsync());
|
||||
var grant = (await grantResponse.Content.ReadFromJsonAsync<PasswordActionResult>())!;
|
||||
action.Client.VerifySession(action.Public, action.Session, grant.ServerProof);
|
||||
var staleLogin = await Prove("login");
|
||||
var replacement = PasswordProtocol.Create("http-replacement-password");
|
||||
var request = new ChangePasswordRequest(grant.AuthorizationId, replacement.Credentials, null);
|
||||
Assert.That((await _client.PostAsJsonAsync("/api/auth/password/change", request)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
Assert.That((await _client.PostAsJsonAsync("/api/auth/password/change", request)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
|
||||
Assert.That((await _client.PostAsJsonAsync("/api/auth/password/login", staleLogin.Proof)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
|
||||
Assert.That((await _client.GetAsync("/api/auth/password")).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Govor.Application.Authentication;
|
||||
using Govor.Application.E2ee;
|
||||
using Govor.Application.Infrastructure.AdminsStuff;
|
||||
using Govor.Domain.Models.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SecureRemotePassword;
|
||||
|
||||
namespace Govor.Server.Tests;
|
||||
|
||||
[TestFixture]
|
||||
public class PasswordRecoveryTests
|
||||
{
|
||||
private const string Password = "correct-horse-2026";
|
||||
private TestDatabase _db = null!;
|
||||
private PasswordAccountService _service = null!;
|
||||
private PasswordChallenges _challenges = null!;
|
||||
private PasswordCredentials _credentials = null!;
|
||||
private string _archiveKey = null!, _root = null!, _code = null!, _name = null!;
|
||||
private UserSession _session = null!;
|
||||
[OneTimeSetUp]
|
||||
public void Keys()
|
||||
{
|
||||
(_credentials, _archiveKey) = PasswordProtocol.Create(Password);
|
||||
_root = E2eeRecoveryProtocol.GenerateIdentity(); _code = E2eeRecoveryProtocol.GenerateCode();
|
||||
}
|
||||
[SetUp]
|
||||
public async Task Setup()
|
||||
{
|
||||
_db = new(); _challenges = new(); _service = new(_db.Context, _challenges, new PasswordHasher());
|
||||
var user = await _db.Context.Users.SingleAsync(u => u.Id == _db.Alice);
|
||||
user.SrpSalt = _credentials.Salt; user.SrpIdentity = _credentials.Identity; user.SrpVerifier = _credentials.Verifier;
|
||||
user.PasswordHash = "srp-only"; user.CredentialVersion = 1; _name = user.Username;
|
||||
_session = new() { UserId = user.Id, ExpiresAt = DateTime.UtcNow.AddDays(2), RefreshTokenHash = Guid.NewGuid().ToString() };
|
||||
_db.Context.UserSessions.Add(_session);
|
||||
await _db.Context.SaveChangesAsync();
|
||||
var vault = E2eeRecoveryProtocol.Seal(user.Id, 1, _root, _code, "archived private keys");
|
||||
await new E2eeService(_db.Context).SaveRecoveryAsync(user.Id, new(0, vault.IdentityKey, vault.Ciphertext, vault.Signature));
|
||||
await _service.SaveEnvelopeAsync(user.Id, PasswordProtocol.Seal(user.Id, 1, _credentials, _root, _code, _archiveKey));
|
||||
}
|
||||
[TearDown] public void Cleanup() => _db.Dispose();
|
||||
|
||||
private async Task<(PasswordProof Proof, SrpClient Client, string Public, SrpSession Session)> Proof(string action = "login", string password = Password)
|
||||
{
|
||||
var client = PasswordProtocol.Client(); var ephemeral = client.GenerateEphemeral();
|
||||
var challenge = await _service.StartAsync(new(_name, ephemeral.Public, "test device"), action,
|
||||
action == "login" ? null : _db.Alice, action == "login" ? null : _session.Id);
|
||||
var derived = PasswordProtocol.Derive(password, challenge.Salt, challenge.Identity);
|
||||
var session = client.DeriveSession(ephemeral.Secret, challenge.PublicEphemeral, challenge.Salt, challenge.Identity,
|
||||
client.DerivePrivateKey(challenge.Salt, challenge.Identity, derived.Secret));
|
||||
return (new(challenge.ChallengeId, session.Proof), client, ephemeral.Public, session);
|
||||
}
|
||||
private async Task<Guid> Grant(string action)
|
||||
{
|
||||
var proof = await Proof(action);
|
||||
var result = await _service.AuthorizeAsync(_db.Alice, _session.Id, proof.Proof, action);
|
||||
proof.Client.VerifySession(proof.Public, proof.Session, result.ServerProof);
|
||||
return result.AuthorizationId;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PasswordIsProvedWithoutBeingSentAndArchiveKeyIsIndependentOfSessionKey()
|
||||
{
|
||||
var proof = await Proof();
|
||||
var verified = await _service.VerifyAsync(proof.Proof);
|
||||
proof.Client.VerifySession(proof.Public, proof.Session, verified.ServerProof);
|
||||
Assert.That(verified.User.Id, Is.EqualTo(_db.Alice));
|
||||
Assert.That(JsonSerializer.Serialize(proof.Proof), Does.Not.Contain(Password).And.Not.Contain(_archiveKey));
|
||||
var config = await _service.GetAsync(_db.Alice);
|
||||
Assert.That(PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!, _archiveKey), Is.EqualTo(_code));
|
||||
Assert.Catch(() => PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!,
|
||||
Jose.Base64Url.Encode(SHA256.HashData(Convert.FromHexString(proof.Session.Key)))));
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.VerifyAsync(proof.Proof));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task IncorrectPasswordAndCrossPurposeProofAreRejected()
|
||||
{
|
||||
var wrong = await Proof(password: "incorrect-password");
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.VerifyAsync(wrong.Proof));
|
||||
var action = await Proof("reset");
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.VerifyAsync(action.Proof));
|
||||
var other = await Proof("change");
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.AuthorizeAsync(_db.Bob, _session.Id, other.Proof, "change"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UnknownAccountReceivesAProofChallengeRatherThanALegacyPasswordRequest()
|
||||
{
|
||||
var challenge = await _service.StartAsync(new("not-an-account", PasswordProtocol.Client().GenerateEphemeral().Public));
|
||||
Assert.That(challenge.Legacy, Is.False);
|
||||
Assert.That(challenge.PublicEphemeral, Has.Length.EqualTo(1024));
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.VerifyAsync(new(challenge.ChallengeId, new string('0', 128))));
|
||||
Assert.ThrowsAsync<ArgumentException>(() => _service.StartAsync(new(_name, new string('0', 1024))));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KnownPasswordChangeRewrapsSameArchiveAndRevokesOtherSessions()
|
||||
{
|
||||
var other = new UserSession { UserId = _db.Alice, ExpiresAt = DateTime.UtcNow.AddDays(1), RefreshTokenHash = "another-session" };
|
||||
_db.Context.UserSessions.Add(other); await _db.Context.SaveChangesAsync();
|
||||
var replacement = PasswordProtocol.Create("replacement-password-2026");
|
||||
var envelope = PasswordProtocol.Seal(_db.Alice, 2, replacement.Credentials, _root, _code, replacement.ArchiveKey);
|
||||
var grant = await Grant("change");
|
||||
await _service.ChangeAsync(_db.Alice, _session.Id, new(grant, replacement.Credentials, envelope));
|
||||
var config = await _service.GetAsync(_db.Alice);
|
||||
Assert.That(PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!, replacement.ArchiveKey), Is.EqualTo(_code));
|
||||
Assert.That((await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!.IdentityKey, Is.EqualTo(E2eeRecoveryProtocol.PublicIdentity(_root)));
|
||||
Assert.That((await _db.Context.UserSessions.AsNoTracking().SingleAsync(s => s.Id == other.Id)).IsRevoked, Is.True);
|
||||
Assert.That((await _db.Context.UserSessions.AsNoTracking().SingleAsync(s => s.Id == _session.Id)).IsRevoked, Is.False);
|
||||
var old = await Proof(); Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.VerifyAsync(old.Proof));
|
||||
var updated = await Proof(password: "replacement-password-2026"); await _service.VerifyAsync(updated.Proof);
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.ChangeAsync(_db.Alice, _session.Id, new(grant, replacement.Credentials, envelope)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task InvalidPasswordChangeRollsBackCredentialsAndPreservesHistory()
|
||||
{
|
||||
var replacement = PasswordProtocol.Create("replacement-password-2026");
|
||||
var grant = await Grant("change");
|
||||
Assert.ThrowsAsync<ArgumentException>(() => _service.ChangeAsync(_db.Alice, _session.Id, new(grant, replacement.Credentials, null)));
|
||||
var config = await _service.GetAsync(_db.Alice);
|
||||
Assert.That(config.CredentialVersion, Is.EqualTo(1));
|
||||
Assert.That(PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!, _archiveKey), Is.EqualTo(_code));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ForgottenPasswordResetDoesNotReencryptHistoryWithTheAdministratorsNewPassword()
|
||||
{
|
||||
await new UsersService(_db.Context, new PasswordHasher()).SetPasswordAsync(_db.Alice, "administrator-reset-password");
|
||||
var user = await _db.Context.Users.AsNoTracking().SingleAsync(u => u.Id == _db.Alice);
|
||||
var vault = await _db.Context.E2eeRecoveryVaults.AsNoTracking().SingleAsync();
|
||||
Assert.That(user.SrpVerifier, Is.Null);
|
||||
Assert.That(vault.PasswordCiphertext, Is.Null);
|
||||
Assert.That(E2eeRecoveryProtocol.Open((await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!, _db.Alice, _code),
|
||||
Is.EqualTo("archived private keys"));
|
||||
Assert.That((await _db.Context.UserSessions.AsNoTracking().SingleAsync(s => s.Id == _session.Id)).IsRevoked, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExplicitEncryptionResetPublishesIdentityChangeAndNewPasswordRecoveryEnvelope()
|
||||
{
|
||||
var e2ee = new E2eeService(_db.Context);
|
||||
var formerKeys = E2eeProtocol.GenerateKeys();
|
||||
var formerDevice = E2eeRecoveryProtocol.Certify(E2eeProtocol.PublicKey(formerKeys, _db.Alice, _session.Id), _root);
|
||||
await e2ee.RegisterAsync(_db.Alice, _session.Id, formerDevice);
|
||||
_db.AddMessage(sender: _db.Alice);
|
||||
var previous = (await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!;
|
||||
var newRoot = E2eeRecoveryProtocol.GenerateIdentity(); var newCode = E2eeRecoveryProtocol.GenerateCode();
|
||||
var vault = E2eeRecoveryProtocol.Seal(_db.Alice, 2, newRoot, newCode, "new history only");
|
||||
var envelope = PasswordProtocol.Seal(_db.Alice, 1, _credentials, newRoot, newCode, _archiveKey);
|
||||
var grant = await Grant("reset");
|
||||
var reset = new ResetEncryptionRequest(grant, previous.IdentityKey, previous.Revision, vault, envelope);
|
||||
var change = await _service.ResetAsync(_db.Alice, _session.Id, reset);
|
||||
_db.Context.ChangeTracker.Clear(); // Device enrollment is a subsequent HTTP request with a fresh context.
|
||||
var newKeys = E2eeProtocol.GenerateKeys();
|
||||
await e2ee.RegisterAsync(_db.Alice, _session.Id,
|
||||
E2eeRecoveryProtocol.Certify(E2eeProtocol.PublicKey(newKeys, _db.Alice, _session.Id), newRoot));
|
||||
var historical = await e2ee.GetHistoricalSignerAsync(_db.Bob, _db.ChatId, Govor.Domain.Models.Messages.RecipientType.User,
|
||||
_session.Id, formerDevice.IdentityKey);
|
||||
Assert.That(historical, Is.EqualTo(formerDevice));
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => e2ee.GetHistoricalSignerAsync(_db.Outsider, _db.ChatId,
|
||||
Govor.Domain.Models.Messages.RecipientType.User, _session.Id, formerDevice.IdentityKey));
|
||||
Assert.That(change.PreviousIdentityKey, Is.EqualTo(previous.IdentityKey));
|
||||
Assert.That(change.Epoch, Is.EqualTo(1));
|
||||
Assert.That((await new E2eeService(_db.Context).GetIdentityChangesAsync(_db.Bob, _db.Alice)), Has.Length.EqualTo(1));
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => new E2eeService(_db.Context).GetIdentityChangesAsync(_db.Outsider, _db.Alice));
|
||||
var group = new Govor.Domain.Models.ChatGroup { Id = Guid.NewGuid(), Name = "Past author", Description = "" };
|
||||
var membership = new Govor.Domain.Models.GroupMembership { GroupId = group.Id, UserId = _db.Outsider, MemberSince = DateTime.UtcNow };
|
||||
_db.Context.ChatGroups.Add(group); _db.Context.GroupMemberships.Add(membership);
|
||||
await _db.Context.SaveChangesAsync();
|
||||
_db.AddMessage(sender: _db.Alice, chat: group.Id, type: Govor.Domain.Models.Messages.RecipientType.Group);
|
||||
Assert.That(await new E2eeService(_db.Context).GetIdentityChangesAsync(_db.Outsider, _db.Alice), Has.Length.EqualTo(1));
|
||||
membership.IsBanned = true; await _db.Context.SaveChangesAsync();
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => new E2eeService(_db.Context).GetIdentityChangesAsync(_db.Outsider, _db.Alice));
|
||||
var config = await _service.GetAsync(_db.Alice);
|
||||
Assert.That(PasswordProtocol.Open(_db.Alice, config.Credentials, config.Envelope!, _archiveKey), Is.EqualTo(newCode));
|
||||
var currentVault = (await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!;
|
||||
Assert.Catch(() => E2eeRecoveryProtocol.Open(currentVault, _db.Alice, _code));
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.ResetAsync(_db.Alice, _session.Id, reset));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task StaleEncryptionResetDoesNotReplaceTheExistingIdentity()
|
||||
{
|
||||
var root = E2eeRecoveryProtocol.GenerateIdentity(); var code = E2eeRecoveryProtocol.GenerateCode();
|
||||
var vault = E2eeRecoveryProtocol.Seal(_db.Alice, 3, root, code, "new history");
|
||||
var envelope = PasswordProtocol.Seal(_db.Alice, 1, _credentials, root, code, _archiveKey);
|
||||
var grant = await Grant("reset");
|
||||
Assert.ThrowsAsync<InvalidOperationException>(() => _service.ResetAsync(_db.Alice, _session.Id,
|
||||
new(grant, E2eeRecoveryProtocol.PublicIdentity(_root), 2, vault, envelope)));
|
||||
Assert.That((await new E2eeService(_db.Context).GetRecoveryAsync(_db.Alice)).Vault!.IdentityKey, Is.EqualTo(E2eeRecoveryProtocol.PublicIdentity(_root)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LegacyEnrollmentChecksOldPasswordAndRequiresADifferentReplacement()
|
||||
{
|
||||
var account = await _db.Context.Users.SingleAsync(u => u.Id == _db.Alice);
|
||||
account.SrpSalt = null; account.SrpIdentity = null; account.SrpVerifier = null;
|
||||
account.PasswordHash = new PasswordHasher().Hash(Password);
|
||||
await _db.Context.SaveChangesAsync();
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.EnrollAsync(_db.Alice, new(_credentials, "wrong-password")));
|
||||
Assert.ThrowsAsync<ArgumentException>(() => _service.EnrollAsync(_db.Alice, new(_credentials, Password)));
|
||||
var replacement = PasswordProtocol.Create("upgraded-password-2026");
|
||||
await _service.EnrollAsync(_db.Alice, new(replacement.Credentials, Password));
|
||||
Assert.That((await _service.GetAsync(_db.Alice)).Credentials, Is.EqualTo(replacement.Credentials));
|
||||
Assert.ThrowsAsync<InvalidOperationException>(() => _service.EnrollAsync(_db.Alice, new(replacement.Credentials, Password)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExpiredProofAndExpiredActionGrantCannotBeUsed()
|
||||
{
|
||||
var clock = new TestClock(); _challenges = new(clock); _service = new(_db.Context, _challenges, new PasswordHasher());
|
||||
var proof = await Proof(); clock.Now = clock.Now.AddMinutes(3);
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.VerifyAsync(proof.Proof));
|
||||
var grant = await Grant("change"); clock.Now = clock.Now.AddMinutes(3);
|
||||
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.ChangeAsync(_db.Alice, _session.Id, new(grant, _credentials, null)));
|
||||
}
|
||||
|
||||
private sealed class TestClock : TimeProvider
|
||||
{ public DateTimeOffset Now = DateTimeOffset.UtcNow; public override DateTimeOffset GetUtcNow() => Now; }
|
||||
}
|
||||
Reference in New Issue
Block a user