Skip to content

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

Update SmtpServer with configurable certificates dir for Docker bind mount (#112)

Leendert de Borstd83978994f4f
diff --git a/apps/server/Services/AliasVault.SmtpService/Certificates/README.md b/apps/server/Services/AliasVault.SmtpService/Certificates/README.md
index f06339383..54152efc5 100644
--- a/apps/server/Services/AliasVault.SmtpService/Certificates/README.md
+++ b/apps/server/Services/AliasVault.SmtpService/Certificates/README.md
@@ -1,6 +1,5 @@
-Place the certificates for the SMTP service here.
-The certificates must be in .p12 format and can be any name. Multiple certificates will be combined into one.
+# SMTP TLS Certificates
-The certificates must be without password.
+This directory is for local development only. In production Docker deployments, certificates should be placed in:
-Make sure to restart the SMTP service after adding new certificates.
+- `./certificates/smtp/` (mounted to `/certificates/smtp` in container)
diff --git a/apps/server/Services/AliasVault.SmtpService/Config.cs b/apps/server/Services/AliasVault.SmtpService/Config.cs
index 66174e9be..6d751b7a0 100644
--- a/apps/server/Services/AliasVault.SmtpService/Config.cs
+++ b/apps/server/Services/AliasVault.SmtpService/Config.cs
@@ -17,6 +17,18 @@ public class Config
/// </summary>
public string SmtpTlsEnabled { get; set; } = "false";
+ /// <summary>
+ /// Gets or sets the path to the directory containing SMTP TLS certificates.
+ /// Defaults to /certificates/smtp in Docker environments.
+ /// </summary>
+ public string SmtpCertificatesPath { get; set; } = "/certificates/smtp";
+
+ /// <summary>
+ /// Gets or sets an error message if TLS certificate loading failed.
+ /// This is used to log a warning when falling back to non-TLS mode.
+ /// </summary>
+ public string? TlsCertificateError { get; set; }
+
/// <summary>
/// Gets or sets the domains that the SMTP service is listening for.
/// Domains not in this list will be rejected.
diff --git a/apps/server/Services/AliasVault.SmtpService/Program.cs b/apps/server/Services/AliasVault.SmtpService/Program.cs
index 65b92f13c..9d65cf85e 100644
--- a/apps/server/Services/AliasVault.SmtpService/Program.cs
+++ b/apps/server/Services/AliasVault.SmtpService/Program.cs
@@ -37,6 +37,30 @@ config.AllowedToDomains = emailDomains.Split(',').ToList();
var tlsEnabled = Environment.GetEnvironmentVariable("SMTP_TLS_ENABLED") ?? "false";
config.SmtpTlsEnabled = tlsEnabled;
+
+var certPath = Environment.GetEnvironmentVariable("SMTP_CERTIFICATES_PATH") ?? "/certificates/smtp";
+config.SmtpCertificatesPath = certPath;
+
+// Check if TLS is requested but certificates are not available, if so, fallback to non-TLS mode.
+var tlsAvailable = false;
+X509Certificate2? loadedCertificate = null;
+string? loadedCertificateFile = null;
+if (config.SmtpTlsEnabled == "true")
+{
+ var certResult = TryLoadCertificate(config.SmtpCertificatesPath);
+ if (certResult.Success)
+ {
+ tlsAvailable = true;
+ loadedCertificate = certResult.Certificate;
+ loadedCertificateFile = certResult.CertificateFile;
+ }
+ else
+ {
+ // TLS was requested but certificate loading failed: will log warning after host is built.
+ config.TlsCertificateError = certResult.ErrorMessage;
+ }
+}
+
builder.Services.AddSingleton(config);
builder.Services.AddAliasVaultDatabaseConfiguration(builder.Configuration);
@@ -44,28 +68,45 @@ builder.Services.AddTransient<IMessageStore, DatabaseMessageStore>();
builder.Services.AddSingleton(
provider =>
{
+ // Use SmtpServerWorker logger so logs appear in the database (it's in the allowed sources list).
+ var logger = provider.GetRequiredService<ILogger<SmtpServerWorker>>();
var options = new SmtpServerOptionsBuilder()
.ServerName("aliasvault");
- if (config.SmtpTlsEnabled == "true")
+ if (tlsAvailable && loadedCertificate != null)
{
- // With TLS and certificate support.
+ // TLS enabled with valid certificate.
+ logger.LogInformation(
+ "SMTP TLS enabled successfully. Certificate: {CertFile}, Subject: {Subject}, Expires: {Expiry}",
+ loadedCertificateFile,
+ loadedCertificate.Subject,
+ loadedCertificate.NotAfter.ToString("yyyy-MM-dd"));
options.Endpoint(serverBuilder =>
serverBuilder
.Port(25, false)
.AllowUnsecureAuthentication()
- .Certificate(CreateCertificate())
+ .Certificate(loadedCertificate)
.SupportedSslProtocols(System.Security.Authentication.SslProtocols.Tls12))
.Endpoint(serverBuilder =>
serverBuilder
.Port(587, false)
.AllowUnsecureAuthentication()
- .Certificate(CreateCertificate())
+ .Certificate(loadedCertificate)
.SupportedSslProtocols(System.Security.Authentication.SslProtocols.Tls12));
}
else
{
- // No TLS
+ // No TLS: either not requested or certificate not available.
+ if (config.SmtpTlsEnabled == "true" && !string.IsNullOrEmpty(config.TlsCertificateError))
+ {
+ // TLS was requested but failed: log warning.
+ logger.LogWarning(
+ "SMTP TLS is enabled but certificate could not be loaded: {Error}. " +
+ "Falling back to non-TLS mode. To fix: place valid .pem certificate file(s) in {CertPath}",
+ config.TlsCertificateError,
+ config.SmtpCertificatesPath);
+ }
+
options.Endpoint(serverBuilder =>
serverBuilder
.Port(25, false))
@@ -75,37 +116,46 @@ builder.Services.AddSingleton(
}
return new SmtpServer.SmtpServer(options.Build(), provider.GetRequiredService<IServiceProvider>());
+ });
- static X509Certificate2 CreateCertificate()
+// Attempts to load a TLS certificate from the specified directory.
+static (bool Success, X509Certificate2? Certificate, string? CertificateFile, string? ErrorMessage) TryLoadCertificate(string certificatesDirectory)
+{
+ try
+ {
+ // Check if directory exists.
+ if (!Directory.Exists(certificatesDirectory))
{
- // Specify the directory where PEM files are stored.
- string certificatesDirectory = "Certificates";
+ return (false, null, null, $"Certificate directory does not exist: {certificatesDirectory}");
+ }
- // Get all PEM files in the directory.
- string[] pemFiles = Directory.GetFiles(certificatesDirectory, "*.pem");
+ // Get all PEM files in the directory (expecting a single file with all domains as SANs).
+ string[] pemFiles = Directory.GetFiles(certificatesDirectory, "*.pem");
- // Check if there are any PEM files found.
- if (pemFiles.Length == 0)
- {
- throw new FileNotFoundException("No PEM files found in the specified directory.");
- }
+ if (pemFiles.Length == 0)
+ {
+ return (false, null, null, $"No .pem certificate files found in folder: '{certificatesDirectory}'");
+ }
- // Use the first PEM file found
- string firstPemFile = pemFiles[0];
+ // Use the first PEM file found (alphabetically). Only one certificate file should be present.
+ // For multiple mail domains, use a single certificate with Subject Alternative Names (SANs).
+ string firstPemFile = pemFiles[0];
+ string fileName = Path.GetFileName(firstPemFile);
- // Create an X509Certificate2 object from the PEM file.
- var cert = X509Certificate2.CreateFromPemFile(firstPemFile);
+ // Create an X509Certificate2 object from the PEM file.
+ var cert = X509Certificate2.CreateFromPemFile(firstPemFile);
- // Convert the X509Certificate2 object to a PFX file then immediately load it again
- // NOTE: this is important because saving the object to a PFX file to disk for a brief
- // second will allow Windows to correctly load the certificate with the private key.
- // If we don't do this, the certificate will be loaded without the private key and
- // will throw error on Windows:
- // "The TLS server credential's certificate does not have a private key information property attached to it"
- var certBytes = cert.Export(X509ContentType.Pfx, "password");
- return X509CertificateLoader.LoadPkcs12(certBytes, "password", X509KeyStorageFlags.DefaultKeySet);
- }
- });
+ // Convert the X509Certificate2 object to a PFX file then immediately load it again.
+ var certBytes = cert.Export(X509ContentType.Pfx, "password");
+ var loadedCert = X509CertificateLoader.LoadPkcs12(certBytes, "password", X509KeyStorageFlags.DefaultKeySet);
+
+ return (true, loadedCert, fileName, null);
+ }
+ catch (Exception ex)
+ {
+ return (false, null, null, $"Failed to load certificate: {ex.Message}");
+ }
+}
// -----------------------------------------------------------------------
// Register hosted services via Status library wrapper in order to monitor and control (start/stop) them via the database.
diff --git a/apps/server/Services/AliasVault.SmtpService/Properties/launchSettings.json b/apps/server/Services/AliasVault.SmtpService/Properties/launchSettings.json
index 749b86445..2e8d97ed4 100644
--- a/apps/server/Services/AliasVault.SmtpService/Properties/launchSettings.json
+++ b/apps/server/Services/AliasVault.SmtpService/Properties/launchSettings.json
@@ -5,7 +5,8 @@
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development",
"PRIVATE_EMAIL_DOMAINS": "example.tld,example2.tld,disabled.tld",
- "SMTP_TLS_ENABLED": "false"
+ "SMTP_TLS_ENABLED": "false",
+ "SMTP_CERTIFICATES_PATH": "Certificates"
},
"dotnetRunMessages": true
},