-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
539 lines (461 loc) · 21 KB
/
index.js
File metadata and controls
539 lines (461 loc) · 21 KB
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
'use strict';
const { request, RetryAgent, Agent } = require('undici');
const { decodeWords } = require('libmime');
const { toUnicode } = require('punycode');
const { randomBytes } = require('node:crypto');
function decodeHeaderLineIntoKeyValuePair(headerLine) {
let decodedHeaderStr;
let headerSeparatorPos = headerLine.indexOf(':');
if (headerSeparatorPos < 0) {
return headerLine;
}
let headerKey = headerLine.substring(0, headerSeparatorPos);
let headerValue = headerLine.substring(headerSeparatorPos + 1);
try {
decodedHeaderStr = decodeWords(headerValue);
} catch (err) {
// keep the value as is
decodedHeaderStr = headerValue;
}
return [headerKey.trim(), decodedHeaderStr.trim()];
}
const normalizeDomain = domain => {
domain = (domain || '').toLowerCase().trim();
try {
if (/^xn--/.test(domain)) {
domain = toUnicode(domain).normalize('NFC').toLowerCase().trim();
}
} catch {
// ignore
}
return domain;
};
const normalizeAddress = (address, asObject) => {
if (!address) {
return address || '';
}
const user = address
.substr(0, address.lastIndexOf('@'))
.normalize('NFC')
.toLowerCase()
.replace(/\+[^@]*$/, '')
.trim(); // get username from email, normalize it to NFC UTF-8, remove everything after plus sign, trim spaces
const domain = normalizeDomain(address.substr(address.lastIndexOf('@') + 1)); // normalize domain
const addr = user + '@' + domain; // actual user address
const unameview = user.replace(/\./g, ''); // remove dots
const addrview = unameview + '@' + domain; // address view
if (asObject) {
return {
user,
unameview,
addrview,
domain,
addr
};
}
return addr;
};
const loggelfForEveryUser = (app, short_message, data) => {
if (data._rcpt) {
if (!Array.isArray(data._rcpt)) {
data._rcpt = [data._rcpt];
}
} else {
data._rcpt = [''];
}
const cleanRcpt = data._rcpt.map(rcpt => normalizeAddress(rcpt, true).addrview);
data._rcpt.forEach((rcpt, i) => {
app.loggelf({
short_message,
...data,
_rcpt: rcpt,
_clean_rcpt: cleanRcpt[i]
});
});
};
// Global agent - connection pool
let agent;
let defaultAgent;
const retryStatusCodes = [500, 502, 503, 504];
const errorCodes = ['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN', 'ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']; // Default undici
module.exports.title = 'zilter';
module.exports.init = async app => {
const authPasswordTypeBySessionId = new Map();
const AUTH_PASSWORD_TYPE_TTL = 30 * 60 * 1000;
const AUTH_PASSWORD_TYPE_SWEEP_INTERVAL = 5 * 60 * 1000;
const sweepPasswordTypes = () => {
const now = Date.now();
for (const [sessionId, entry] of authPasswordTypeBySessionId.entries()) {
if (!entry || !entry.ts || now - entry.ts > AUTH_PASSWORD_TYPE_TTL) {
authPasswordTypeBySessionId.delete(sessionId);
}
}
};
const sweepTimer = setInterval(sweepPasswordTypes, AUTH_PASSWORD_TYPE_SWEEP_INTERVAL);
if (typeof sweepTimer.unref === 'function') {
sweepTimer.unref();
}
const getPasswordType = envelope => {
if (!envelope) return false;
// WD path: passwordType is retrieved directly from envelope object
if (envelope.passwordType) {
return envelope.passwordType;
}
// Zone‑MTA path: from smtp:auth + sessionId
const sessionId = envelope.sessionId || (envelope.session && envelope.session.id);
if (sessionId) {
const entry = authPasswordTypeBySessionId.get(sessionId);
if (entry && entry.passwordType) {
entry.ts = Date.now();
return entry.passwordType;
}
}
return false;
};
app.addHook('smtp:auth', (auth, session, next) => {
if (session?.id) {
if (auth?.passwordType) {
authPasswordTypeBySessionId.set(session.id, { passwordType: auth.passwordType, ts: Date.now() });
} else {
authPasswordTypeBySessionId.delete(session.id);
}
}
next();
});
app.addHook('message:queue', async (envelope, messageInfo) => {
// check with zilter
// if incorrect do app.reject()
const SUBJECT_MAX_ALLOWED_LENGTH = 16000;
const { userName, apiKey, serverHost, zilterUrl, logIncomingData } = app.config;
let { zilterFallbackUrl } = app.config;
let subjectMaxLength = app.config.subjectMaxLength;
if (!subjectMaxLength || subjectMaxLength > SUBJECT_MAX_ALLOWED_LENGTH) {
subjectMaxLength = SUBJECT_MAX_ALLOWED_LENGTH;
}
if (logIncomingData) {
// log available data
app.logger.info('Incoming data: ', envelope, messageInfo, envelope.headers.getList());
}
if (!userName || !apiKey) {
// if either username or apikey missing skip check
app.loggelf({
short_message: '[WILDDUCK-ZONEMTA-ZILTER] auth missing',
_plugin_status: 'error',
_error: 'Username and/or API key missing from config in order to auth to Zilter.'
});
return;
}
if (!serverHost) {
// log that we are missing serverhost and we're using the originhost instead
app.loggelf({
short_message: '[WILDDUCK-ZONEMTA-ZILTER] serverhost missing',
_plugin_status: 'warning',
_error: 'Serverhost config missing, using envelope originhost instead. Check config.'
});
}
if (!zilterUrl) {
app.loggelf({
short_message: '[WILDDUCK-ZONEMTA-ZILTER] zilter url missing',
_plugin_status: 'error',
_error: 'Zilter URL is missing, add it. Aborting check'
});
return;
}
if (!zilterFallbackUrl) {
// If no separate fallback given then default to original host
zilterFallbackUrl = zilterUrl;
}
if (!defaultAgent) {
// separate agent
const { keepAliveTimeout, keepAliveMaxTimeout } = app.config;
defaultAgent = new Agent({
keepAliveTimeout: keepAliveTimeout || 5000,
keepAliveMaxTimeout: keepAliveMaxTimeout || 600e3,
connections: 50, // allow 50 concurrent sockets, client objects
pipelining: 1 // enable keep-alive, but do not pipeline
});
}
if (!agent) {
// if agent has not yet been initialize then create one
const { keepAliveTimeout, keepAliveMaxTimeout, maxRetries, minRetryTimeout, maxRetryTimeout, timeoutFactor } = app.config;
agent = new RetryAgent(
new Agent({
keepAliveTimeout: keepAliveTimeout || 5000,
keepAliveMaxTimeout: keepAliveMaxTimeout || 600e3,
connections: 50, // allow 50 concurrent sockets, client objects
pipelining: 1 // enable keep-alive, but do not pipeline
}),
{
maxRetries: maxRetries || 3,
minTimeout: minRetryTimeout || 100,
maxTimeout: maxRetryTimeout || 300,
timeoutFactor: timeoutFactor || 1.5,
statusCodes: retryStatusCodes,
errorCodes,
methods: ['POST', 'HEAD', 'OPTIONS', 'CONNECT']
}
);
}
// check whether we need to resolve for email
let authenticatedUser = envelope.user || '';
let authenticatedUserAddress;
let sender;
const smtpUsernamePatternRegex = /\[([^\]]+)]/;
let passEmail = true; // by default pass email
let isTempFail = true; // by default tempfail
let userData = {};
try {
if (authenticatedUser.includes('@')) {
if (smtpUsernamePatternRegex.test(authenticatedUser)) {
// SMTP username[email]
let match = authenticatedUser.match(smtpUsernamePatternRegex);
if (match && match[1]) {
authenticatedUser = match[1]; // is email address
}
}
// SMTP email aadress login
// seems to be an email, no need to resolve, straight acquire the user id from addresses
// normalize address
let addrObj = normalizeAddress(authenticatedUser, true);
authenticatedUser = addrObj.addr;
// check for alias
let aliasData = await app.db.users.collection('domainaliases').findOne({ alias: addrObj.domain });
let addrview = addrObj.addrview; // default to addrview query as-is without alias
if (aliasData) {
// got alias data
const aliasDomain = aliasData.domain;
addrview = addrObj.unameview + '@' + aliasDomain; // set new query addrview
}
const addressData = await app.db.users.collection('addresses').findOne({ addrview });
sender = addressData.user.toString();
userData = await app.db.users.collection('users').findOne({ _id: addressData.user });
} else {
// current user authenticated via the username, resolve to email
authenticatedUser = authenticatedUser.replace(/\./g, '').normalize('NFC').toLowerCase().trim(); // Normalize username to unameview
userData = await app.db.users.collection('users').findOne({ unameview: authenticatedUser });
authenticatedUserAddress = userData.address; // main address of the user
sender = userData._id.toString(); // ID of the user
}
} catch (err) {
app.loggelf({
short_message: '[WILDDUCK-ZONEMTA-ZILTER] DB error',
_plugin_status: 'error',
_error: 'DB error. Check DB connection, or collection names, or filter params.',
_authenticated_user: authenticatedUser,
_err_json: err.toString()
});
return;
}
// construct Authorization header
const userBase64 = Buffer.from(`${userName}:${apiKey}`).toString('base64'); // authorization header
const messageSize = envelope.headers.build().length + envelope.bodySize; // RFC822 size (size of Headers + Body)
const messageHeadersList = [];
const allHeadersParsed = {};
// Change headers to the format that Zilter will accept
for (const headerObj of envelope.headers.getList()) {
// Get header Key and Value from line
const [headerKey, headerValue] = decodeHeaderLineIntoKeyValuePair(headerObj.line);
allHeadersParsed[headerKey] = headerValue;
messageHeadersList.push({
name: headerKey,
value: headerValue
});
}
const zilterId = randomBytes(8).toString('hex');
const originhost = serverHost || (envelope.originhost || '').replace('[', '').replace(']', '');
const transhost = (envelope.transhost || '').replace('[', '').replace(']', '') || originhost;
let subject = messageInfo.subject || allHeadersParsed.Subject || 'no subject';
subject = subject.substring(0, subjectMaxLength);
const messageIdHeaderVal = allHeadersParsed['Message-ID']?.replace('<', '').replace('>', '');
let zilterResponse;
const zilterRequestDataObj = {
host: originhost, // Originhost is a string that includes [] (array as a string literal)
'zilter-id': zilterId, // Random ID
sender, // Sender User ID (uid) in the system
helo: transhost, // Transhost is a string that includes [] (array as a string literal)
'authenticated-sender': authenticatedUserAddress || authenticatedUser, // Sender user email
'queue-id': envelope.id, // Queue ID of the envelope of the message
'rfc822-size': messageSize, // Size of the raw RFC822-compatible e-mail
from: envelope.from,
rcpt: envelope.to,
headers: messageHeadersList, // Message headers
pwned: !!userData.passwordPwned
};
const passwordType = getPasswordType(envelope);
if (passwordType) {
zilterRequestDataObj.passwordType = passwordType;
}
// Call Zilter with required params
try {
let res;
let hasRetriedAlready;
try {
res = await request(zilterUrl, {
dispatcher: defaultAgent,
method: 'POST',
body: JSON.stringify(zilterRequestDataObj),
headers: { Authorization: `Basic ${userBase64}`, 'Content-Type': 'application/json' }
});
if (retryStatusCodes.includes(res.statusCode)) {
// Retry with fallback url
hasRetriedAlready = true;
res = await request(zilterFallbackUrl, {
dispatcher: agent, // use RetryAgent so in case of request fail - retry
method: 'POST',
body: JSON.stringify(zilterRequestDataObj),
headers: { Authorization: `Basic ${userBase64}`, 'Content-Type': 'application/json' }
});
}
} catch (error) {
// Can be an error with an error code (ECONNRESET etc.) or a Timeout or a 5xx status
// Retry with fallback url if not retried before
if (!hasRetriedAlready) {
res = await request(zilterFallbackUrl, {
dispatcher: agent, // use RetryAgent so in case of request fail - retry
method: 'POST',
body: JSON.stringify(zilterRequestDataObj),
headers: { Authorization: `Basic ${userBase64}`, 'Content-Type': 'application/json' }
}); // If throws will be handled by outer catch block
} else {
throw error; // Throw original error to outer catch block
}
}
const resBodyJson = await res.body.json();
const debugJson = { ...resBodyJson };
zilterResponse = resBodyJson;
if (debugJson.symbols) {
['SENDER', 'SENDER_GROUP', 'WEBHOOK'].forEach(sym => delete debugJson.symbols[sym]);
}
['sender', 'action', 'zilter-id', 'client'].forEach(el => delete debugJson[el]);
if (res.statusCode === 401) {
// unauthorized Zilter, default to tempfail error return
loggelfForEveryUser(app, subject, {
_sender: sender,
_authenticated_sender: authenticatedUserAddress || authenticatedUser,
_rfc822_size: messageSize,
_app: 'zilter',
_rcpt: envelope.to,
_from: envelope.from,
_header_from: allHeadersParsed.From,
_header_to: allHeadersParsed.To,
_message_id: messageIdHeaderVal,
_subject: subject,
level: 5,
_zilter_error: 'Unauthorized error 401',
_ip: envelope.origin,
_debug_json: debugJson,
_pwned: !!userData.passwordPwned
});
// Log zilter unauthorized to console
const id = typeof envelope === 'object' ? envelope.id : envelope;
let messageInfoStr = messageInfo;
if (messageInfo && typeof messageInfo.format === 'function') {
messageInfoStr = messageInfo.format();
}
messageInfoStr = (messageInfoStr || '').toString().trim();
const msg = '%s NOQUEUE [unauthorized]' + (messageInfoStr ? ' (' + messageInfoStr + ')' : '');
app.logger.info(app.options.title, msg, id);
}
if (resBodyJson.action && resBodyJson.action !== 'accept') {
if (resBodyJson.action !== 'tempfail') {
isTempFail = false; // not a tempfail error
}
// not accepted, email did not pass checks
passEmail = false;
loggelfForEveryUser(app, subject, {
_sender: sender,
_authenticated_sender: authenticatedUserAddress || authenticatedUser,
_rfc822_size: messageSize,
_app: 'zilter',
_rcpt: envelope.to,
_from: envelope.from,
_header_from: allHeadersParsed.From,
_header_to: allHeadersParsed.To,
_message_id: messageIdHeaderVal,
_subject: subject,
level: 5,
_passed: 'N',
_action: resBodyJson.action,
_ip: envelope.origin,
_debug_json: debugJson,
_pwned: !!userData.passwordPwned
});
// Log zilter banned to console
const id = typeof envelope === 'object' ? envelope.id : envelope;
let messageInfoStr = messageInfo;
if (messageInfo && typeof messageInfo.format === 'function') {
messageInfoStr = messageInfo.format();
}
messageInfoStr = (messageInfoStr || '').toString().trim();
const msg =
'%s NOQUEUE [banned]' +
(messageInfoStr ? ' (' + messageInfoStr + ')' : '') +
(resBodyJson.action ? ` (passed=N action=${resBodyJson.action})` : ` (passed=N)`);
app.logger.info(app.options.title, msg, id);
} else if (resBodyJson.action && resBodyJson.action === 'accept') {
// accepted, so not a tempfail
isTempFail = false;
loggelfForEveryUser(app, subject, {
_sender: sender,
_authenticated_sender: authenticatedUserAddress || authenticatedUser,
_rfc822_size: messageSize,
_app: 'zilter',
_rcpt: envelope.to,
_from: envelope.from,
_header_from: allHeadersParsed.From,
_header_to: allHeadersParsed.To,
_message_id: messageIdHeaderVal,
_subject: subject,
level: 5,
_passed: 'Y',
_ip: envelope.origin,
_debug_json: debugJson,
_pwned: !!userData.passwordPwned
});
// Log Zilter pass check to console
const id = typeof envelope === 'object' ? envelope.id : envelope;
let messageInfoStr = messageInfo;
if (messageInfo && typeof messageInfo.format === 'function') {
messageInfoStr = messageInfo.format();
}
messageInfoStr = (messageInfoStr || '').toString().trim();
const msg =
'%s QUEUE [passed]' +
(messageInfoStr ? ' (' + messageInfoStr + ')' : '') +
(resBodyJson.action ? ` (passed=Y action=${resBodyJson.action})` : ` (passed=Y)`);
app.logger.info(app.options.title, msg, id);
}
} catch (err) {
// error, default to tempfail
loggelfForEveryUser(app, subject, {
_sender: sender,
_authenticated_sender: authenticatedUserAddress || authenticatedUser,
_rfc822_size: messageSize,
_app: 'zilter',
_rcpt: envelope.to,
_from: envelope.from,
_header_from: allHeadersParsed.From,
_header_to: allHeadersParsed.To,
_message_id: messageIdHeaderVal,
_subject: subject,
level: 5,
_zilter_error: err.message,
_ip: envelope.origin,
_pwned: !!userData.passwordPwned
});
}
if (!passEmail) {
// sending e-mail rejected
throw app.reject(
envelope,
'banned',
messageInfo,
`550 ${zilterResponse && zilterResponse.symbols ? `SENDING BLOCKED, REASON: ${zilterResponse.symbols.REJECT_REASON}` : 'SENDING BLOCKED'}`
);
}
if (isTempFail) {
throw app.reject(envelope, 'tempfail', messageInfo, 'Temporary error, please try again later.');
}
return;
});
};