Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add max email size limit to SmtpServer config to reject too large messages outright (#2460)
Leendert de Borstd1abb876b139
diff --git a/apps/server/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/apps/server/AliasVault.SmtpService/Handlers/DatabaseMessageStore.csindex 407c1a060..24858701b 100644--- a/apps/server/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs+++ b/apps/server/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs@@ -31,6 +31,11 @@ using SmtpServer.Storage;/// <param name="dbContextFactory">IDbContextFactory instance.</param>public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config config, IAliasServerDbContextFactory dbContextFactory) : MessageStore{+ /// <summary>+ /// Maximum accepted raw message size in bytes: 10 MB of content plus headroom for MIME encoding overhead.+ /// </summary>+ public const int MaxEmailSizeInBytes = (int)(10 * 1024 * 1024 * 1.4);+/// <summary>/// Attachment bodies smaller than this are left inline in the message source. Detaching them would trade a/// download saving too small to notice for an extra round trip whenever the user opens the attachment.@@ -61,10 +66,7 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c{try{- // Check email size limit- var maxEmailSizeInMegabytes = 10;- var maxEmailSizeInBytes = (long)((maxEmailSizeInMegabytes * 1024 * 1024) * 1.4);- if (buffer.Length > maxEmailSizeInBytes)+ if (buffer.Length > MaxEmailSizeInBytes){return SmtpResponse.SizeLimitExceeded;}diff --git a/apps/server/AliasVault.SmtpService/Program.cs b/apps/server/AliasVault.SmtpService/Program.csindex ab250bc89..d45d7bdcf 100644--- a/apps/server/AliasVault.SmtpService/Program.cs+++ b/apps/server/AliasVault.SmtpService/Program.cs@@ -16,7 +16,6 @@ using AliasVault.SmtpService;using AliasVault.SmtpService.Handlers;using AliasVault.SmtpService.Workers;using AliasVault.WorkerStatus.ServiceExtensions;-using Microsoft.Extensions.Configuration;using SmtpServer;using SmtpServer.Storage;@@ -85,10 +84,11 @@ builder.Services.AddSingleton({// Use SmtpServerWorker logger so logs appear in the database (it's in the allowed sources list).var logger = provider.GetRequiredService<ILogger<SmtpServerWorker>>();- var configuration = provider.GetRequiredService<IConfiguration>();logger.LogInformation("SMTP advertised hostname (banner / EHLO): {AdvertisedHostname}", advertisedHostname);+var options = new SmtpServerOptionsBuilder()- .ServerName(advertisedHostname);+ .ServerName(advertisedHostname)+ .MaxMessageSize(DatabaseMessageStore.MaxEmailSizeInBytes, MaxMessageSizeHandling.Strict);if (tlsAvailable && loadedCertificate != null){diff --git a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/Helpers/TestHostBuilder.cs b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/Helpers/TestHostBuilder.csindex 1aad1422b..b9320c551 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/Helpers/TestHostBuilder.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/Helpers/TestHostBuilder.cs@@ -110,7 +110,8 @@ public class TestHostBuilder : AbstractTestHostBuilderEnvironment.GetEnvironmentVariable("SMTP_ADVERTISED_HOSTNAME"),Dns.GetHostName);var options = new SmtpServerOptionsBuilder()- .ServerName(advertisedHostname);+ .ServerName(advertisedHostname)+ .MaxMessageSize(DatabaseMessageStore.MaxEmailSizeInBytes, MaxMessageSizeHandling.Strict);// Note: port 25 doesn't work in GitHub actions so we use these instead for the integration tests:// - 2525 for the SMTP serverdiff --git a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.csindex ac94f174f..7e65c2b7f 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs@@ -12,6 +12,7 @@ using System.Net.Sockets;using System.Text;using AliasVault.Cryptography;using AliasVault.IntegrationTests.SmtpServer.Helpers;+using AliasVault.SmtpService.Handlers;using MailKit.Net.Smtp;using MailKit.Security;using Microsoft.EntityFrameworkCore;@@ -166,6 +167,60 @@ public class SmtpServerTestsAssert.That(rcptResponse, Does.StartWith("250"));}+ /// <summary>+ /// EHLO should advertise the maximum message size so compliant senders refuse oversized mail up front.+ /// </summary>+ /// <returns>Task.</returns>+ [Test]+ public async Task Ehlo_AdvertisesMaxMessageSize()+ {+ using var client = await ConnectRawSmtpClient();+ using var stream = client.GetStream();++ _ = await ReadSmtpLineAsync(stream); // Greeting+ var ehloResponse = await SendSmtpCommandAsync(stream, "EHLO localhost");+ Assert.That(ehloResponse, Does.Contain($"SIZE {DatabaseMessageStore.MaxEmailSizeInBytes}"));+ }++ /// <summary>+ /// A DATA section larger than the maximum message size should end the session without storing anything.+ /// </summary>+ /// <returns>Task.</returns>+ [Test]+ public async Task OversizedData_IsRejectedAndNotStored()+ {+ using var client = await ConnectRawSmtpClient();+ using var stream = client.GetStream();++ _ = await ReadSmtpLineAsync(stream); // Greeting+ Assert.That(await SendSmtpCommandAsync(stream, "HELO localhost"), Does.StartWith("250"));+ Assert.That(await SendSmtpCommandAsync(stream, "MAIL FROM:<[email protected]>"), Does.StartWith("250"));+ Assert.That(await SendSmtpCommandAsync(stream, "RCPT TO:<[email protected]>"), Does.StartWith("250"));+ Assert.That(await SendSmtpCommandAsync(stream, "DATA"), Does.StartWith("354"));++ // Stream twice the limit; the server may close the connection before everything is written.+ var line = Encoding.ASCII.GetBytes(new string('a', 998) + "\r\n");+ var linesToSend = (DatabaseMessageStore.MaxEmailSizeInBytes * 2) / line.Length;+ try+ {+ await stream.WriteAsync(Encoding.ASCII.GetBytes("Subject: oversized\r\n\r\n"));+ for (var i = 0; i < linesToSend; i++)+ {+ await stream.WriteAsync(line);+ }++ await stream.WriteAsync(Encoding.ASCII.GetBytes("\r\n.\r\n"));+ await stream.FlushAsync();+ }+ catch (IOException)+ {+ // Expected when the server ends the session mid-transfer.+ }++ var storedCount = await _testHostBuilder.GetDbContext().Emails.CountAsync();+ Assert.That(storedCount, Is.Zero);+ }+/// <summary>/// Tests sending a single email in plain format to the SMTP server with valid claim to check if it is processed correctly./// </summary>