Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add encryption to email attachments (#148)

Leendert de Borstd9f929ec6398
diff --git a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
index cc6b95c43..3777b2955 100644
--- a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
+++ b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
@@ -335,7 +335,6 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
return false;
}
- // Set the "to" for the email to the actual one we are looping through now.
var insertedId = await InsertEmailIntoDatabase(message, new MailAddress(toAddress.AsAddress()), userPublicKey);
logger.LogInformation(
"Email for {ToAddress} successfully saved into database with ID {insertedId}.",
diff --git a/src/Tests/AliasVault.IntegrationTests/AliasVault.IntegrationTests.csproj b/src/Tests/AliasVault.IntegrationTests/AliasVault.IntegrationTests.csproj
index 939ba9b08..ba01ea170 100644
--- a/src/Tests/AliasVault.IntegrationTests/AliasVault.IntegrationTests.csproj
+++ b/src/Tests/AliasVault.IntegrationTests/AliasVault.IntegrationTests.csproj
@@ -9,6 +9,16 @@
<IsTestProject>true</IsTestProject>
</PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <DocumentationFile>bin\Debug\net8.0\AliasVault.IntegrationTests.xml</DocumentationFile>
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ </PropertyGroup>
+
+ <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
+ <DocumentationFile>bin\Release\net8.0\AliasVault.IntegrationTests.xml</DocumentationFile>
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ </PropertyGroup>
+
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0"/>
<PackageReference Include="MailKit" Version="4.7.1.1" />
@@ -16,6 +26,10 @@
<PackageReference Include="NUnit" Version="3.14.0"/>
<PackageReference Include="NUnit.Analyzers" Version="3.9.0"/>
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
</ItemGroup>
<ItemGroup>
diff --git a/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs b/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
index 2b34f3ebd..1a03ad5e9 100644
--- a/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
+++ b/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
@@ -7,14 +7,18 @@
namespace AliasVault.IntegrationTests.SmtpServer;
+using System.Text;
using AliasServerDb;
using Cryptography;
-using MailKit.Security;
using MailKit.Net.Smtp;
+using MailKit.Security;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using MimeKit;
+/// <summary>
+/// SmtpServerTests class.
+/// </summary>
[TestFixture]
public class SmtpServerTests
{
@@ -43,6 +47,7 @@ public class SmtpServerTests
/// <summary>
/// Setup logic for every test.
/// </summary>
+ /// <returns>Task.</returns>
[SetUp]
public async Task Setup()
{
@@ -81,7 +86,6 @@ public class SmtpServerTests
};
dbContext.UserEmailClaims.Add(emailClaim2);
-
// Create public key.
var encryptionKey = new UserEncryptionKey
{
@@ -97,6 +101,7 @@ public class SmtpServerTests
/// <summary>
/// Tear down logic for every test.
/// </summary>
+ /// <returns>Task.</returns>
[TearDown]
public async Task TearDown()
{
@@ -107,6 +112,7 @@ public class SmtpServerTests
/// <summary>
/// Tests sending a single email in plain format to the SMTP server with valid claim to check if it is processed correctly.
/// </summary>
+ /// <returns>Task.</returns>
[Test]
public async Task SingleEmailPlain()
{
@@ -116,7 +122,7 @@ public class SmtpServerTests
message.To.Add(new MailboxAddress("Test Recipient", "[email protected]"));
message.Subject = "Test Email";
const string textBody = "This is a test email plain.";
- message.Body = new BodyBuilder { TextBody = textBody}.ToMessageBody();
+ message.Body = new BodyBuilder { TextBody = textBody }.ToMessageBody();
await SendMessageToSmtpServer(message);
// Check if the email is in the database.
@@ -142,6 +148,7 @@ public class SmtpServerTests
/// <summary>
/// Tests sending a single email in html format to the SMTP server to check if it is processed correctly.
/// </summary>
+ /// <returns>Task.</returns>
[Test]
public async Task SingleEmailHtml()
{
@@ -174,6 +181,7 @@ public class SmtpServerTests
/// <summary>
/// Tests sending a single email in multipart format to the SMTP server to check if it is processed correctly.
/// </summary>
+ /// <returns>Task.</returns>
[Test]
public async Task SingleEmailMultipart()
{
@@ -184,7 +192,7 @@ public class SmtpServerTests
message.Subject = "Test Email with multipart body.";
const string textBody = "This is a test email multipart.";
const string htmlBody = "<html><body><h1>This is a test email multipart.</h1></body></html>";
- message.Body = new BodyBuilder { TextBody = textBody, HtmlBody = htmlBody}.ToMessageBody();
+ message.Body = new BodyBuilder { TextBody = textBody, HtmlBody = htmlBody }.ToMessageBody();
await SendMessageToSmtpServer(message);
// Check if the email is in the database.
@@ -207,6 +215,7 @@ public class SmtpServerTests
/// <summary>
/// Tests sending a single email in plain format to the SMTP server to check if it is processed correctly.
/// </summary>
+ /// <returns>Task.</returns>
[Test]
public async Task MultipleRecipientsEmail()
{
@@ -219,7 +228,7 @@ public class SmtpServerTests
message.Subject = "Test Email";
const string textBody = "This is a test email plain.";
- message.Body = new BodyBuilder { TextBody = textBody}.ToMessageBody();
+ message.Body = new BodyBuilder { TextBody = textBody }.ToMessageBody();
await SendMessageToSmtpServer(message);
// Check that two emails are in the database, one for each allowed recipient.
@@ -238,7 +247,7 @@ public class SmtpServerTests
message.To.Add(new MailboxAddress("Test Recipient", "[email protected]"));
message.Subject = "Test Email";
const string textBody = "This is a test email plain.";
- message.Body = new BodyBuilder { TextBody = textBody}.ToMessageBody();
+ message.Body = new BodyBuilder { TextBody = textBody }.ToMessageBody();
// Expect error from SmtpClient when sending email to unknown domain.
Assert.ThrowsAsync<SmtpCommandException>(async () => await SendMessageToSmtpServer(message));
@@ -257,16 +266,45 @@ public class SmtpServerTests
message.To.Add(new MailboxAddress("Test Recipient", "[email protected]"));
message.Subject = "Test Email";
const string textBody = "This is a test email plain.";
- message.Body = new BodyBuilder { TextBody = textBody}.ToMessageBody();
+ message.Body = new BodyBuilder { TextBody = textBody }.ToMessageBody();
// Expect error from SmtpClient when sending email to unknown domain.
Assert.ThrowsAsync<SmtpCommandException>(async () => await SendMessageToSmtpServer(message));
}
+ /// <summary>
+ /// Tests sending a single email in plain format to the SMTP server to check if it is processed correctly.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task AttachmentEmail()
+ {
+ var message = new MimeMessage();
+ message.From.Add(new MailboxAddress("Test Sender", "[email protected]"));
+ message.To.Add(new MailboxAddress("Test Recipient", "[email protected]"));
+ message.Subject = "Test Email with attachment";
+
+ var bodyBuilder = new BodyBuilder();
+ bodyBuilder.TextBody = "This is a test email with attachment.";
+
+ // Add attachment using BodyBuilder
+ byte[] attachmentData = Encoding.UTF8.GetBytes("This is an attachment.");
+ bodyBuilder.Attachments.Add("attachment.txt", attachmentData, ContentType.Parse("text/plain"));
+
+ message.Body = bodyBuilder.ToMessageBody();
+
+ await SendMessageToSmtpServer(message);
+
+ // Check that attachment is in the database and the bytes are encrypted.
+ Assert.That(await _testHostBuilder.GetDbContext().EmailAttachments.CountAsync(), Is.EqualTo(1));
+ var attachment = await _testHostBuilder.GetDbContext().EmailAttachments.FirstAsync();
+ Assert.That(attachment.Bytes, Is.Not.EqualTo(attachmentData), "Email attachment bytes are not encrypted. Check email encryption logic.");
+ }
+
/// <summary>
/// Sends a message to the SMTP server.
/// </summary>
- /// <param name="message"></param>
+ /// <param name="message">MimeMessage to send.</param>
private static async Task SendMessageToSmtpServer(MimeMessage message)
{
using var client = new SmtpClient();
diff --git a/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs b/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs
index a1d720949..54f561814 100644
--- a/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs
+++ b/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs
@@ -9,15 +9,15 @@ namespace AliasVault.IntegrationTests.SmtpServer;
using System.Data.Common;
using AliasServerDb;
+using AliasVault.SmtpService;
using AliasVault.SmtpService.Handlers;
using AliasVault.SmtpService.Workers;
-using SmtpService;
-using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Data.Sqlite;
-using Microsoft.EntityFrameworkCore;
using global::SmtpServer;
using global::SmtpServer.Storage;
+using Microsoft.Data.Sqlite;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
/// <summary>
/// Builder class for creating a test host for the SmtpServiceWorker in order to run integration tests against it.
@@ -55,7 +55,7 @@ public class TestHostBuilder
/// <summary>
/// Builds the SmtpService test host.
/// </summary>
- /// <returns></returns>
+ /// <returns>IHost.</returns>
public IHost Build()
{
// Create a persistent in-memory database for the duration of the test.
@@ -68,7 +68,8 @@ public class TestHostBuilder
/// <summary>
/// Builds the SmtpService test host with a provided database connection.
/// </summary>
- /// <returns></returns>
+ /// <param name="dbConnection">The database connection to use for the test.</param>
+ /// <returns>IHost.</returns>
public IHost Build(DbConnection dbConnection)
{
// Create a persistent in-memory database for the duration of the test.
@@ -80,7 +81,7 @@ public class TestHostBuilder
services.AddSingleton(new Config
{
AllowedToDomains = new List<string> { "example.tld" },
- SmtpTlsEnabled = "false"
+ SmtpTlsEnabled = "false",
});
services.AddSingleton(_dbConnection);
@@ -106,12 +107,10 @@ public class TestHostBuilder
.Port(2525, false))
.Endpoint(serverBuilder =>
serverBuilder
- .Port(5870, false)
- );
+ .Port(5870, false));
return new SmtpServer(options.Build(), provider.GetRequiredService<IServiceProvider>());
- }
- );
+ });
services.AddHostedService<SmtpServerWorker>();
diff --git a/src/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs b/src/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs
index 51338a800..1d403e953 100644
--- a/src/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs
+++ b/src/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs
@@ -138,4 +138,33 @@ public class SrpArgonEncryptionTests
// Ensure the keys match.
Assert.That(clientSession.Key, Is.EqualTo(serverSession.Key));
}
+
+ /// <summary>
+ /// Test byte array encryption and decryption overload methods.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task TestByteArrayEncryption()
+ {
+ string password = "your-password";
+ string salt = "your-salt";
+
+ // Derive a key from the password using Argon2id
+ byte[] key = await Encryption.DeriveKeyFromPasswordAsync(password, salt);
+
+ // Generate random byte array of 1000 bytes
+ byte[] plainBytes = new byte[1000];
+ new Random().NextBytes(plainBytes);
+
+ // SymmetricEncrypt the plainBytes
+ var cipherBytes = Encryption.SymmetricEncrypt(plainBytes, key);
+
+ Assert.That(cipherBytes, Is.Not.Null);
+ Assert.That(cipherBytes, Is.Not.Empty);
+ Assert.That(cipherBytes, Is.Not.EqualTo(plainBytes));
+
+ // SymmetricDecrypt the cipherBytes
+ var decrypted = Encryption.SymmetricDecrypt(cipherBytes, key);
+ Assert.That(decrypted, Is.EqualTo(plainBytes));
+ }
}
diff --git a/src/Utilities/Cryptography/EmailEncryption.cs b/src/Utilities/Cryptography/EmailEncryption.cs
index 89b622748..b08af670e 100644
--- a/src/Utilities/Cryptography/EmailEncryption.cs
+++ b/src/Utilities/Cryptography/EmailEncryption.cs
@@ -47,6 +47,12 @@ public static class EmailEncryption
email.FromLocal = Encryption.SymmetricEncrypt(email.FromLocal, symmetricKey);
email.FromDomain = Encryption.SymmetricEncrypt(email.FromDomain, symmetricKey);
+ // Encrypt all attachments with the symmetric key.
+ foreach (var attachment in email.Attachments)
+ {
+ attachment.Bytes = Encryption.SymmetricEncrypt(attachment.Bytes, symmetricKey);
+ }
+
// Encrypt the symmetric key with the user's public key.
email.EncryptedSymmetricKey = Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, userEncryptionKey.PublicKey);
email.UserEncryptionKeyId = userEncryptionKey.Id;
diff --git a/src/Utilities/Cryptography/Encryption.cs b/src/Utilities/Cryptography/Encryption.cs
index 5b06c6fe3..ac57d6535 100644
--- a/src/Utilities/Cryptography/Encryption.cs
+++ b/src/Utilities/Cryptography/Encryption.cs
@@ -97,6 +97,18 @@ public static class Encryption
/// <param name="key">Key to use for encryption (must be 32 bytes for AES-256).</param>
/// <returns>The encrypted string (ciphertext).</returns>
public static string SymmetricEncrypt(string plaintext, byte[] key)
+ {
+ var encryptedBytes = SymmetricEncrypt(Encoding.UTF8.GetBytes(plaintext), key);
+ return Convert.ToBase64String(encryptedBytes);
+ }
+
+ /// <summary>
+ /// SymmetricEncrypt a byte array using AES-256 GCM.
+ /// </summary>
+ /// <param name="plainBytes">The plain byte array.</param>
+ /// <param name="key">Key to use for encryption (must be 32 bytes for AES-256).</param>
+ /// <returns>The encrypted string (ciphertext).</returns>
+ public static byte[] SymmetricEncrypt(byte[] plainBytes, byte[] key)
{
byte[] iv = new byte[12];
SecureRandom random = new();
@@ -106,16 +118,15 @@ public static class Encryption
AeadParameters parameters = new(new KeyParameter(key), 128, iv, null);
gcm.Init(true, parameters);
- byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
- byte[] ciphertextBytes = new byte[gcm.GetOutputSize(plaintextBytes.Length)];
- int outputLength = gcm.ProcessBytes(plaintextBytes, 0, plaintextBytes.Length, ciphertextBytes, 0);
+ byte[] ciphertextBytes = new byte[gcm.GetOutputSize(plainBytes.Length)];
+ int outputLength = gcm.ProcessBytes(plainBytes, 0, plainBytes.Length, ciphertextBytes, 0);
gcm.DoFinal(ciphertextBytes, outputLength);
byte[] combined = new byte[iv.Length + ciphertextBytes.Length];
Array.Copy(iv, 0, combined, 0, iv.Length);
Array.Copy(ciphertextBytes, 0, combined, iv.Length, ciphertextBytes.Length);
- return Convert.ToBase64String(combined);
+ return combined;
}
/// <summary>
@@ -126,13 +137,23 @@ public static class Encryption
/// <returns>The original plaintext string.</returns>
public static string SymmetricDecrypt(string ciphertext, byte[] key)
{
- byte[] fullCipher = Convert.FromBase64String(ciphertext);
+ var plainBytes = SymmetricDecrypt(Convert.FromBase64String(ciphertext), key);
+ return Encoding.UTF8.GetString(plainBytes).TrimEnd('\0');
+ }
+ /// <summary>
+ /// SymmetricDecrypt a cipher byte array using AES-256 GCM.
+ /// </summary>
+ /// <param name="encryptedBytes">The encrypted byte array (cipherBytes).</param>
+ /// <param name="key">The key used to originally encrypt the string.</param>
+ /// <returns>The original plaintext string.</returns>
+ public static byte[] SymmetricDecrypt(byte[] encryptedBytes, byte[] key)
+ {
byte[] iv = new byte[12];
- byte[] cipherBytes = new byte[fullCipher.Length - iv.Length];
+ byte[] cipherBytes = new byte[encryptedBytes.Length - iv.Length];
- Array.Copy(fullCipher, 0, iv, 0, iv.Length);
- Array.Copy(fullCipher, iv.Length, cipherBytes, 0, cipherBytes.Length);
+ Array.Copy(encryptedBytes, 0, iv, 0, iv.Length);
+ Array.Copy(encryptedBytes, iv.Length, cipherBytes, 0, cipherBytes.Length);
GcmBlockCipher gcm = new(new AesEngine());
AeadParameters parameters = new(new KeyParameter(key), 128, iv, null);
@@ -142,7 +163,7 @@ public static class Encryption
int outputLength = gcm.ProcessBytes(cipherBytes, 0, cipherBytes.Length, plaintextBytes, 0);
gcm.DoFinal(plaintextBytes, outputLength);
- return Encoding.UTF8.GetString(plaintextBytes).TrimEnd('\0');
+ return plaintextBytes;
}
/// <summary>