-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
MailDemonService.cs
229 lines (210 loc) · 9.37 KB
/
MailDemonService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#region Imports
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using DnsClient;
using MailKit;
using MailKit.Net;
using MailKit.Net.Smtp;
using MimeKit;
using MimeKit.Utils;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using MimeKit.Cryptography;
using DnsClient.Internal;
using Microsoft.Extensions.Logging;
#endregion Imports
namespace MailDemon
{
public partial class MailDemonService : IDisposable
{
private class TcpListenerActive : TcpListener, IDisposable
{
public TcpListenerActive(IPEndPoint localEP) : base(localEP) { }
public TcpListenerActive(IPAddress localaddr, int port) : base(localaddr, port) { }
public new void Dispose() { Stop(); base.Dispose(); }
public new bool Active => base.Active;
}
private class CacheEntry
{
public int Count;
}
private TcpListenerActive server;
private CancellationToken cancelToken;
private readonly int streamTimeoutMilliseconds = 5000;
private readonly int maxMessageSize = 16777216;
private readonly int maxLineSize = 1024;
private readonly List<MailDemonUser> users = new List<MailDemonUser>();
private readonly MemoryCache cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = (1024 * 1024 * 16), CompactionPercentage = 0.9 });
private readonly int maxConnectionCount = 128;
private readonly MailboxAddress globalForwardAddress;
private readonly int maxFailuresPerIPAddress = 3;
private readonly HashSet<string> whiteListIP;
private readonly TimeSpan failureLockoutTimespan = TimeSpan.FromDays(1.0);
private readonly IPAddress ip;
private readonly int port = 25;
private readonly string greeting = "ESMTP & MailDemon &";
private readonly bool requireEhloIpHostMatch;
private readonly bool requireSpfMatch = true;
private readonly DkimSigner dkimSigner;
private readonly Microsoft.Extensions.Logging.ILogger logger;
public string Domain { get; private set; }
public IReadOnlyList<MailDemonUser> Users { get { return users; } }
public MailDemonService(string[] args, IConfiguration configuration, Microsoft.Extensions.Logging.ILogger logger)
{
this.logger = logger;
IConfigurationSection rootSection = configuration.GetSection("mailDemon");
Domain = (rootSection["domain"] ?? Domain);
ip = (string.IsNullOrWhiteSpace(rootSection["ip"]) ? IPAddress.Any : IPAddress.Parse(rootSection["ip"]));
port = rootSection.GetValue("port", port);
maxFailuresPerIPAddress = rootSection.GetValue("maxFailuresPerIPAddress", maxFailuresPerIPAddress);
whiteListIP = rootSection.GetValue("whitelistIP", string.Empty).ToString().Split(',').ToHashSet();
maxConnectionCount = rootSection.GetValue("maxConnectionCount", maxConnectionCount);
maxMessageSize = rootSection.GetValue("maxMessageSize", maxMessageSize);
globalForwardAddress = rootSection.GetValue("globalForwardAddress", globalForwardAddress);
greeting = (rootSection["greeting"] ?? greeting).Replace("\r", string.Empty).Replace("\n", string.Empty);
if (TimeSpan.TryParse(rootSection["failureLockoutTimespan"], out TimeSpan _failureLockoutTimespan))
{
failureLockoutTimespan = _failureLockoutTimespan;
}
failureLockoutTimespan = _failureLockoutTimespan;
IConfigurationSection userSection = rootSection.GetSection("users");
foreach (var child in userSection.GetChildren())
{
MailDemonUser user = new MailDemonUser(child["name"], child["displayName"], child["password"], child["address"], child["forwardAddress"], true);
users.Add(user);
logger.LogDebug("Loaded user {user}", user);
}
requireEhloIpHostMatch = rootSection.GetValue<bool>("requireEhloIpHostMatch", requireEhloIpHostMatch);
requireSpfMatch = rootSection.GetValue<bool>("requireSpfMatch", requireSpfMatch);
string dkimFile = rootSection.GetValue<string>("dkimPemFile", null);
string dkimSelector = rootSection.GetValue<string>("dkimSelector", null);
if (File.Exists(dkimFile) && !string.IsNullOrWhiteSpace(dkimSelector))
{
try
{
using StringReader stringReader = new StringReader(File.ReadAllText(dkimFile));
PemReader pemReader = new PemReader(stringReader);
object pemObject = pemReader.ReadObject();
AsymmetricKeyParameter privateKey = ((AsymmetricCipherKeyPair)pemObject).Private;
dkimSigner = new DkimSigner(privateKey, Domain, dkimSelector);
logger.LogWarning("Loaded dkim file at {path}", dkimFile);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to load dkim file at {path}", dkimFile);
}
}
sslCertificateFile = rootSection["sslCertificateFile"];
sslCertificatePrivateKeyFile = rootSection["sslCertificatePrivateKeyFile"];
if (!string.IsNullOrWhiteSpace(sslCertificateFile))
{
sslCertificatePassword = (rootSection["sslCertificatePassword"] ?? string.Empty).ToSecureString();
}
TestSslCertificate();
IConfigurationSection ignoreRegexSection = rootSection.GetSection("ignoreCertificateErrorsRegex");
if (ignoreRegexSection != null)
{
foreach (var child in ignoreRegexSection.GetChildren())
{
Regex re = new Regex(child["regex"].ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline);
foreach (var domain in child.GetSection("domains").GetChildren())
{
ignoreCertificateErrorsRegex[domain.Value] = re;
}
}
}
}
public async Task StartAsync(CancellationToken cancelToken)
{
server?.Dispose();
this.cancelToken = cancelToken;
server = new TcpListenerActive(IPAddress.Any, port);
server.Start(maxConnectionCount);
cancelToken.Register(Dispose);
try
{
while (server != null && server.Active)
{
TcpClient tcpClient = null;
try
{
// handle connection in background
tcpClient = await server.AcceptTcpClientAsync();
}
catch (ObjectDisposedException)
{
// ignore, happens on shutdown
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
if (!cancelToken.IsCancellationRequested)
{
logger.LogError(ex, "Error connecting incoming socket");
}
continue;
}
// process connection in background
ProcessConnection(tcpClient).GetAwaiter();
}
}
catch (Exception ex2)
{
logger.LogError(ex2, "Error shutting down smtp server");
}
logger.LogWarning("SMTP server is shutdown");
}
public void Dispose()
{
try
{
logger.LogWarning("Disposing SMTP server");
server?.Dispose();
}
catch
{
}
server = null;
}
private bool CheckBlocked(string ipAddress)
{
string key = "RateLimit_" + ipAddress;
return (cache.TryGetValue(key, out CacheEntry count) && count.Count >= maxFailuresPerIPAddress);
}
private void IncrementFailure(string ipAddress, string userName)
{
if (!whiteListIP.Contains(ipAddress))
{
string key = "RateLimit_" + ipAddress;
CacheEntry entry = cache.GetOrCreate(key, (i) =>
{
i.AbsoluteExpirationRelativeToNow = failureLockoutTimespan;
i.Size = (key.Length * 2) + 16; // 12 bytes for C# object plus 4 bytes int
return new CacheEntry();
});
Interlocked.Increment(ref entry.Count);
IPBan.IPBanPlugin.IPBanLoginFailed("SMTP", userName, ipAddress);
}
}
}
}