forked from nodemailer/haraka-plugin-wildduck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1766 lines (1500 loc) · 66.2 KB
/
index.js
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-env es6 */
/* globals DENY: false, OK: false, DENYSOFT: false */
'use strict';
// disable config loading by Wild Duck
process.env.DISABLE_WILD_CONFIG = 'true';
const os = require('os');
const ObjectID = require('mongodb').ObjectID;
const db = require('./lib/db');
const DSN = require('haraka-dsn');
const punycode = require('punycode');
const SRS = require('srs.js');
const counters = require('wildduck/lib/counters');
const tools = require('wildduck/lib/tools');
const StreamCollect = require('./lib/stream-collect');
const Maildropper = require('wildduck/lib/maildropper');
const FilterHandler = require('wildduck/lib/filter-handler');
const autoreply = require('wildduck/lib/autoreply');
const consts = require('wildduck/lib/consts');
const wdErrors = require('wildduck/lib/errors');
const Gelf = require('gelf');
const addressparser = require('nodemailer/lib/addressparser');
const libmime = require('libmime');
DSN.rcpt_too_fast = () =>
DSN.create(
450,
'The user you are trying to contact is receiving mail at a rate that\nprevents additional messages from being delivered. Please resend your\nmessage at a later time. If the user is able to receive mail at that\ntime, your message will be delivered.',
2,
1
);
let defaultSpamRejectMessage =
'Our system has detected that this message is likely unsolicited mail.\nTo reduce the amount of spam this message has been blocked.';
exports.register = function() {
const plugin = this;
plugin.logdebug('Initializing rcpt_to Wild Duck plugin.', plugin);
plugin.load_wildduck_ini();
plugin.register_hook('init_master', 'init_wildduck_shared');
plugin.register_hook('init_child', 'init_wildduck_shared');
};
exports.load_wildduck_ini = function() {
const plugin = this;
plugin.cfg = plugin.config.get(
'wildduck.yaml',
{
booleans: ['attachments.decodeBase64', 'sender.enabled']
},
() => {
plugin.load_wildduck_ini();
}
);
};
exports.open_database = function(server, next) {
const plugin = this;
plugin.srsRewriter = new SRS({
secret: (plugin.cfg.srs && plugin.cfg.srs.secret) || 'secret'
});
plugin.rspamd = plugin.cfg.rspamd || {};
plugin.rspamd.forwardSkip = Number(plugin.rspamd.forwardSkip) || Number(plugin.cfg.spamScoreForwarding) || 0;
plugin.rspamd.blacklist = [].concat(plugin.rspamd.blacklist || []);
plugin.rspamd.softlist = [].concat(plugin.rspamd.softlist || []);
plugin.rspamd.responses = plugin.rspamd.responses || {};
plugin.hostname = (plugin.cfg.gelf && plugin.cfg.gelf.hostname) || os.hostname();
plugin.gelf =
plugin.cfg.gelf && plugin.cfg.gelf.enabled
? new Gelf(plugin.cfg.gelf.options)
: {
// placeholder
emit: (level, message) => {
plugin.loginfo('GELF ' + JSON.stringify(message), plugin);
}
};
wdErrors.setGelf(plugin.gelf);
plugin.loggelf = message => {
if (typeof message === 'string') {
message = {
short_message: message
};
}
message = message || {};
const component = (plugin.cfg.gelf && plugin.cfg.gelf.component) || 'mx';
if (!message.short_message || message.short_message.indexOf(component.toUpperCase()) !== 0) {
message.short_message = component.toUpperCase() + ' ' + (message.short_message || '');
}
message.facility = component; // facility is deprecated but set by the driver if not provided
message.host = plugin.hostname;
message.timestamp = Date.now() / 1000;
message._component = component;
Object.keys(message).forEach(key => {
if (!message[key]) {
delete message[key];
}
});
plugin.gelf.emit('gelf.log', message);
};
let createConnection = done => {
db.connect(server.notes.redis, plugin.cfg, (err, db) => {
if (err) {
return done(err);
}
plugin.db = db;
plugin.ttlcounter = counters(db.redis).ttlcounter;
plugin.db.messageHandler.loggelf = message => plugin.loggelf(message);
plugin.db.userHandler.loggelf = message => plugin.loggelf(message);
plugin.maildrop = new Maildropper({
db,
enabled: plugin.cfg.sender.enabled,
zone: plugin.cfg.sender.zone,
collection: plugin.cfg.sender.collection,
gfs: plugin.cfg.sender.gfs
});
plugin.filterHandler = new FilterHandler({
db,
sender: plugin.cfg.sender,
messageHandler: plugin.db.messageHandler,
loggelf: message => plugin.loggelf(message)
});
done();
});
};
let returned = false;
let tryCreateConnection = () => {
createConnection(err => {
if (err) {
if (!returned) {
plugin.logcrit('Database connection failed. ' + err.message, plugin);
returned = true;
next();
}
// keep trying to open up the DB connection
setTimeout(tryCreateConnection, 2 * 1000);
return;
}
plugin.loginfo('Database connection opened', plugin);
if (!returned) {
returned = true;
next();
}
});
};
tryCreateConnection();
};
exports.normalize_address = function(address) {
if (/^SRS\d+=/i.test(address.user)) {
// Try to fix case-mangled addresses where the intermediate MTA converts user part to lower case
// and thus breaks hash verification
let localAddress = address.user
// ensure that address starts with uppercase SRS
.replace(/^SRS\d+=/i, val => val.toUpperCase())
// ensure that the first entity that looks like SRS timestamp is uppercase
.replace(/([-=+][0-9a-f]{4})(=[A-Z2-7]{2}=)/i, (str, sig, ts) => sig + ts.toUpperCase());
return localAddress + '@' + punycode.toUnicode(address.host.toLowerCase().trim());
}
return tools.normalizeAddress(address.address());
};
exports.init_wildduck_shared = function(next, server) {
const plugin = this;
plugin.open_database(server, next);
};
exports.hook_deny = function(next, connection, params) {
const plugin = this;
const tnx = connection.transaction;
let remoteIp = connection.remote_ip;
if (tnx === null) {
next();
return;
}
let rcpts = tnx.rcpt_to || [];
if (!rcpts.length) {
rcpts = [false];
}
for (let rcpt of rcpts) {
let user;
let address = (rcpt && rcpt.address()) || false;
if (tnx.notes.targets && tnx.notes.targets.users) {
// try to resolve user id for the recipient address
for (let target of tnx.notes.targets.users) {
let uid = target[0];
let info = target[1];
if (info && info.recipient === address) {
user = uid;
}
}
}
let logdata = {
short_message: '[DENY:' + tnx.notes.sender + '] ' + tnx.uuid,
_mail_action: 'deny',
_from: tnx.notes.sender,
_queue_id: tnx.uuid,
_ip: remoteIp,
_proto: tnx.notes.transmissionType,
_to: address,
_user: user,
_rejector: params && params[2],
_reject_code: tnx.notes.rejectCode || (params && params[2]) || 'UNKNOWN'
};
let headerFrom = plugin.getHeaderFrom(tnx);
if (headerFrom) {
logdata._header_from_address = headerFrom.address;
logdata._header_from_value = tnx.header.get_all('From').join('; ');
}
let err = params && params[1];
if (typeof err === 'string') {
logdata._error = err;
} else if (err && typeof err === 'object') {
Object.keys(err).forEach(key => {
if (key === 'msg') {
logdata._error = err[key];
} else {
logdata['_error_' + key] = err[key];
}
});
}
plugin.loggelf(logdata);
}
next();
};
exports.hook_mail = function(next, connection, params) {
const plugin = this;
const tnx = connection.transaction;
let from = params[0];
tnx.notes.sender = from.address();
tnx.notes.id = new ObjectID();
tnx.notes.rateKeys = [];
tnx.notes.targets = {
users: new Map(),
forwards: new Map(),
recipients: new Set(),
autoreplies: new Map()
};
tnx.notes.transmissionType = []
.concat(connection.greeting === 'EHLO' ? 'E' : [])
.concat('SMTP')
.concat(connection.tls_cipher ? 'S' : [])
.join('');
plugin.loggelf({
short_message: '[MAIL FROM:' + tnx.notes.sender + '] ' + tnx.uuid,
_mail_action: 'mail_from',
_from: tnx.notes.sender,
_queue_id: tnx.uuid,
_ip: connection.remote_ip,
_proto: tnx.notes.transmissionType
});
return next();
};
exports.hook_rcpt = function(next, connection, params) {
const plugin = this;
const tnx = connection.transaction;
let tryCount = 0;
let tryTimer = false;
let returned = false;
let waitTimeout = false;
let runHandler = () => {
clearTimeout(tryTimer);
plugin.real_rcpt_handler(
(...args) => {
clearTimeout(waitTimeout);
if (returned) {
return;
}
returned = true;
let err = args && args[0];
if (err && /Error$/.test(err.name)) {
plugin.logerror(err, plugin, connection);
tnx.notes.rejectCode = 'ERRC01';
return next(DENYSOFT, 'Failed to process recipient, try again [ERRC01]');
}
next(...args);
},
connection,
params
);
};
// rcpt check requires access to the db which might not be available yet
let runCheck = () => {
if (returned) {
return;
}
if (!plugin.db) {
// database not opened yet
if (tryCount++ < 5) {
tryTimer = setTimeout(runCheck, tryCount * 150);
return;
}
clearTimeout(waitTimeout);
returned = true;
tnx.notes.rejectCode = 'ERRC02';
return next(DENYSOFT, 'Failed to process recipient, try again [ERRC02]');
}
runHandler();
};
waitTimeout = setTimeout(() => {
clearTimeout(waitTimeout);
if (returned) {
return;
}
returned = true;
tnx.notes.rejectCode = 'ERRC03';
return next(DENYSOFT, 'Failed to process recipient, try again [ERRC03]');
}, 8 * 1000);
runCheck();
};
exports.real_rcpt_handler = function(next, connection, params) {
const plugin = this;
const tnx = connection.transaction;
const remoteIp = connection.remote_ip;
const { recipients, forwards, autoreplies, users } = tnx.notes.targets;
let rcpt = params[0];
if (/\*/.test(rcpt.user)) {
// Using * is not allowed in addresses
tnx.notes.rejectCode = 'NO_SUCH_USER';
return next(DENY, DSN.no_such_user());
}
let address = plugin.normalize_address(rcpt);
recipients.add(address);
let resolution = false;
let hookDone = (...args) => {
if (resolution) {
let message = {
short_message: '[RCPT TO:' + rcpt.address() + '] ' + tnx.uuid,
_mail_action: 'rcpt_to',
_from: tnx.notes.sender,
_to: rcpt.address(),
_queue_id: tnx.uuid,
_ip: remoteIp,
_proto: tnx.notes.transmissionType
};
Object.keys(resolution).forEach(key => {
if (resolution[key]) {
message[key] = resolution[key];
}
});
plugin.loggelf(message);
}
next(...args);
};
plugin.logdebug('Checking validity of ' + address, plugin, connection);
if (/^SRS\d+=/.test(address)) {
let reversed = false;
try {
reversed = plugin.srsRewriter.reverse(address.substr(0, address.indexOf('@')));
let toDomain = punycode.toASCII(
(reversed[1] || '')
.toString()
.toLowerCase()
.trim()
);
if (!toDomain) {
plugin.logerror('SRS FAILED rcpt=' + address + ' error=Missing domain', plugin, connection);
resolution = {
_srs: 'yes',
_error: 'missing domain'
};
tnx.notes.rejectCode = 'NO_SUCH_USER';
return hookDone(DENY, DSN.no_such_user());
}
reversed = reversed.join('@');
} catch (err) {
plugin.logerror('SRS FAILED rcpt=' + address + ' error=' + err.message, plugin, connection);
resolution = {
full_message: err.stack,
_srs: 'yes',
_failure: 'yes',
_error: 'srs check failed',
_err_code: err.code
};
tnx.notes.rejectCode = 'NO_SUCH_USER';
return hookDone(DENY, DSN.no_such_user());
}
if (reversed) {
// accept SRS rewritten address
let key = reversed;
let selector = 'rcpt';
return plugin.checkRateLimit(connection, selector, key, false, (err, success) => {
if (err) {
resolution = {
full_message: err.stack,
_srs: 'yes',
_rate_limit: 'yes',
_selector: selector,
_failure: 'yes',
_error: 'rate limit check failed',
_err_code: err.code
};
err.code = err.code || 'RateLimit';
return hookDone(err);
}
if (!success) {
resolution = {
_srs: 'yes',
_rate_limit: 'yes',
_selector: selector,
_error: 'too many attempts'
};
tnx.notes.rejectCode = 'RATE_LIMIT';
return hookDone(DENYSOFT, DSN.rcpt_too_fast());
}
// update rate limit for this address after delivery
tnx.notes.rateKeys.push({ selector, key });
plugin.loginfo('SRS USING rcpt=' + address + ' target=' + reversed, plugin, connection);
forwards.set(reversed, { type: 'mail', value: reversed, recipient: rcpt.address() });
resolution = {
_srs: 'yes',
_rcpt_accepted: 'yes',
_forward_to: reversed
};
return hookDone(OK);
});
}
}
let handleForwardingAddress = addressData => {
plugin.ttlcounter(
'wdf:' + addressData._id.toString(),
addressData.targets.length,
addressData.forwards || consts.MAX_FORWARDS,
false,
(err, result) => {
if (err) {
// failed checks
resolution = {
full_message: err.stack,
_forward: 'yes',
_rate_limit: 'yes',
_selector: 'user',
_failure: 'yes',
_error: 'rate limit check failed',
_err_code: err.code
};
err.code = err.code || 'RateLimit';
return hookDone(err);
} else if (!result.success) {
connection.lognotice(
'RATELIMITED target=' +
addressData.address +
' key=' +
addressData._id +
' limit=' +
addressData.forwards +
' value=' +
result.value +
' ttl=' +
result.ttl,
plugin,
connection
);
resolution = {
_forward: 'yes',
_rate_limit: 'yes',
_selector: 'user',
_error: 'too many attempts'
};
tnx.notes.rejectCode = 'RATE_LIMIT';
return hookDone(DENYSOFT, DSN.rcpt_too_fast());
}
if (addressData.forwardedDisabled) {
// forwarded address is disabled for whatever reason
resolution = {
_address: addressData._id.toString(),
_error: 'disabled forwarded address',
_disabled_forwarded: 'yes'
};
tnx.notes.rejectCode = 'MBOX_DISABLED';
return hookDone(DENY, DSN.mbox_disabled());
}
plugin.loginfo(
'FORWARDING rcpt=' +
address +
' address=' +
addressData.address +
'[' +
addressData._id +
']' +
' target=' +
addressData.targets.map(target => ((target && target.value) || target).toString().replace(/\?.*$/, '')).join(','),
plugin,
connection
);
if (addressData.autoreply) {
autoreplies.set(addressData.addrview, addressData);
}
let forwardTargets = [];
let pos = 0;
let processTarget = () => {
if (pos >= addressData.targets.length) {
resolution = {
_forward: 'yes',
_rcpt_accepted: 'yes',
_forward_to: forwardTargets.join('\n') || 'empty_list'
};
return hookDone(OK);
}
let targetData = addressData.targets[pos++];
if (targetData.type === 'relay') {
// relay is not rate limited
targetData.recipient = addressData.address || rcpt.address();
// Do not use `targetData.value` alone as it might be the same for multiple recipients
forwards.set(`${targetData.recipient}:${targetData.value}`, targetData);
forwardTargets.push(targetData.recipient + ':' + (targetData.value || '').toString().replace(/\?.*$/, ''));
return setImmediate(processTarget);
}
if (targetData.type === 'http' || (targetData.type === 'mail' && !targetData.user)) {
if (targetData.type !== 'mail') {
forwardTargets.push(rcpt.address() + ':' + targetData.value);
targetData.recipient = rcpt.address();
} else {
forwardTargets.push(targetData.value);
}
forwards.set(targetData.value, targetData);
return setImmediate(processTarget);
}
if (targetData.type !== 'mail') {
// no idea what to do here, some new feature probably
return setImmediate(processTarget);
}
if (targetData.user && users.has(targetData.user.toString())) {
// already listed as a recipient
return setImmediate(processTarget);
}
// we have a target user, so we need to resolve user data
plugin.db.users.collection('users').findOne(
{ _id: targetData.user },
{
// extra fields are needed later in the filtering step
projection: {
_id: true,
name: true,
address: true,
forwards: true,
targets: true,
autoreply: true,
encryptMessages: true,
encryptForwarded: true,
pubKey: true,
spamLevel: true,
storageUsed: true,
quota: true
}
},
(err, userData) => {
if (err) {
err.code = 'InternalDatabaseError';
resolution = {
full_message: err.stack,
_collection: 'users',
_db_query: '_id:' + targetData.user,
_error: 'failed to make a db query',
_failure: 'yes',
_err_code: err.code
};
return hookDone(err);
}
if (!userData) {
// unknown user, treat as normal forward
targetData.recipient = rcpt.address();
forwards.set(targetData.value, targetData);
forwardTargets.push(targetData.value);
return setImmediate(processTarget);
}
if (userData.disabled) {
// disabled user, skip
forwardTargets.push(targetData.value + ':' + userData._id + '[disabled]');
return setImmediate(processTarget);
}
// max quota for the user
let quota = userData.quota || consts.MAX_STORAGE;
if (userData.storageUsed && quota <= userData.storageUsed) {
// can not deliver mail to this user, over quota, skip
forwardTargets.push(targetData.value + ':' + userData._id + '[over_quota]');
return setImmediate(processTarget);
}
users.set(userData._id.toString(), {
userData,
recipient: rcpt.address()
});
forwardTargets.push(targetData.value + ':' + userData._id);
setImmediate(processTarget);
}
);
};
setImmediate(processTarget);
}
);
};
let checkIpRateLimit = (userData, done) => {
if (!remoteIp) {
return done();
}
let key = remoteIp + ':' + userData._id.toString();
let selector = 'rcptIp';
plugin.checkRateLimit(connection, selector, key, false, (err, success) => {
if (err) {
resolution = {
full_message: err.stack,
_rate_limit: 'yes',
_selector: selector,
_user: userData._id.toString(),
_default_address: rcpt.address() !== userData.address ? userData.address : '',
_error: 'rate limit check failed',
_failure: 'yes',
_err_code: err.code
};
err.code = err.code || 'RateLimit';
return hookDone(err);
}
if (!success) {
resolution = {
_rate_limit: 'yes',
_selector: selector,
_error: 'too many attempts',
_user: userData._id.toString(),
_default_address: rcpt.address() !== userData.address ? userData.address : ''
};
tnx.notes.rejectCode = 'RATE_LIMIT';
return hookDone(DENYSOFT, DSN.rcpt_too_fast());
}
// update rate limit for this address after delivery
tnx.notes.rateKeys.push({ selector, key });
return done();
});
};
plugin.db.userHandler.resolveAddress(
address,
{
wildcard: true,
projection: {
name: true,
address: true,
addrview: true,
forwards: true,
autoreply: true,
targets: true, // only forwarded address has `targets` set
forwardedDisabled: true // only forwarded address has `targets` set
}
},
(err, addressData) => {
if (err) {
resolution = {
full_message: err.stack,
_api: 'resolveAddress',
_db_query: 'address:' + address,
_error: 'failed to resolve an address',
_failure: 'yes',
_err_code: err.code
};
err.code = err.code || 'ResolveAddress';
return hookDone(err);
}
if (addressData && addressData.targets) {
return handleForwardingAddress(addressData);
}
if (!addressData || !addressData.user) {
plugin.logdebug('No such user ' + address, plugin, connection);
resolution = {
_error: 'no such user',
_unknwon_user: 'yes'
};
tnx.notes.rejectCode = 'NO_SUCH_USER';
return hookDone(DENY, DSN.no_such_user());
}
plugin.db.userHandler.get(
addressData.user,
{
// extra fields are needed later in the filtering step
name: true,
address: true,
forwards: true,
receivedMax: true,
targets: true,
autoreply: true,
encryptMessages: true,
encryptForwarded: true,
pubKey: true,
spamLevel: true,
storageUsed: true,
quota: true
},
(err, userData) => {
if (err) {
resolution = {
full_message: err.stack,
_api: 'getUser',
_db_query: 'user:' + addressData.user,
_error: 'failed to fetch user',
_failure: 'yes',
_err_code: err.code
};
err.code = err.code || 'GetUserData';
return hookDone(err);
}
if (!userData) {
resolution = {
_error: 'no such user',
_unknwon_user: 'yes'
};
tnx.notes.rejectCode = 'NO_SUCH_USER';
return hookDone(DENY, DSN.no_such_user());
}
if (userData.disabled) {
// user is disabled for whatever reason
resolution = {
_user: userData._id.toString(),
_error: 'disabled user',
_disabled_user: 'yes'
};
tnx.notes.rejectCode = 'MBOX_DISABLED';
return hookDone(DENY, DSN.mbox_disabled());
}
// max quota for the user
let quota = userData.quota || consts.MAX_STORAGE;
if (userData.storageUsed && quota <= userData.storageUsed) {
// can not deliver mail to this user, over quota
resolution = {
_user: userData._id.toString(),
_error: 'user over quota',
_over_quota: 'yes',
_default_address: rcpt.address() !== userData.address ? userData.address : ''
};
tnx.notes.rejectCode = 'MBOX_FULL';
return hookDone(DENY, DSN.mbox_full());
}
checkIpRateLimit(userData, () => {
let key = userData._id.toString();
let selector = 'rcpt';
plugin.checkRateLimit(connection, selector, key, userData.receivedMax, (err, success) => {
if (err) {
resolution = {
full_message: err.stack,
_rate_limit: 'yes',
_selector: selector,
_user: userData._id.toString(),
_default_address: rcpt.address() !== userData.address ? userData.address : '',
_error: 'rate limit check failed',
_failure: 'yes',
_err_code: err.code
};
err.code = err.code || 'RateLimit';
return hookDone(err);
}
if (!success) {
resolution = {
_rate_limit: 'yes',
_selector: selector,
_error: 'too many attempts',
_user: userData._id.toString(),
_default_address: rcpt.address() !== userData.address ? userData.address : ''
};
tnx.notes.rejectCode = 'RATE_LIMIT';
return hookDone(DENYSOFT, DSN.rcpt_too_fast());
}
plugin.loginfo('RESOLVED rcpt=' + rcpt.address() + ' user=' + userData.address + '[' + userData._id + ']', plugin, connection);
// update rate limit for this address after delivery
tnx.notes.rateKeys.push({ selector, key, limit: userData.receivedMax });
users.set(userData._id.toString(), {
userData,
recipient: rcpt.address()
});
resolution = {
_user: userData._id.toString(),
_rcpt_accepted: 'yes',
_default_address: rcpt.address() !== userData.address ? userData.address : ''
};
return hookDone(OK);
});
});
}
);
}
);
};
exports.hook_queue = function(next, connection) {
const plugin = this;
const tnx = connection.transaction;
const queueId = tnx.uuid;
const remoteIp = connection.remote_ip;
const transhost = connection.hello.host;
let blacklisted = this.checkRspamdBlacklist(tnx);
if (blacklisted) {
// can not send DSN object for hook_queue as it is converted to [object Object]
tnx.notes.rejectCode = blacklisted.key;
return next(DENY, plugin.dsnSpamResponse(tnx, blacklisted.key).reply);
}
let softlisted = this.checkRspamdSoftlist(tnx);
if (softlisted) {
// can not send DSN object for hook_queue as it is converted to [object Object]
tnx.notes.rejectCode = softlisted.key;
return next(DENYSOFT, plugin.dsnSpamResponse(tnx, softlisted.key).reply);
}
// results about verification (TLS, SPF, DKIM)
let verificationResults = {
tls: false,
spf: false,
dkim: false
};
let tlsResults = connection.results.get('tls');
if (tlsResults && tlsResults.enabled) {
verificationResults.tls = tlsResults.cipher;
}
// find domain that sent this message (SPF Pass)
let spfResultsFrom = tnx.results.get('spf');
let spfResultsHelo = tnx.results.get('spf');
if (spfResultsFrom && spfResultsFrom.scope === 'mfrom' && spfResultsFrom.result === 'Pass') {
verificationResults.spf = tools.normalizeDomain(spfResultsFrom.domain);
} else if (spfResultsHelo && spfResultsHelo.scope === 'helo' && spfResultsHelo.result === 'Pass') {
verificationResults.spf = tools.normalizeDomain(spfResultsHelo.domain);
}
// find domain that DKIM signed this message. Prefer header from, otherwise use envelope from
if (tnx.notes.dkim_results) {
let dkimResults = Array.isArray(tnx.notes.dkim_results) ? tnx.notes.dkim_results : [].concat(tnx.notes.dkim_results || []);
let envelopeFrom = tnx.notes.sender;
let headerFrom = plugin.getHeaderFrom(tnx);
let envelopeDomain = (envelopeFrom && envelopeFrom.split('@').pop()) || '';
let headerDomain = (headerFrom && headerFrom.address && headerFrom.address.split('@').pop()) || '';
for (let dkimResult of dkimResults) {
if (dkimResult && dkimResult.result === 'pass') {
let domain = tools.normalizeDomain(dkimResult.domain);
if (headerDomain && domain === headerDomain) {
verificationResults.dkim = headerDomain;
break;
}
if (envelopeDomain && domain === envelopeDomain) {
verificationResults.dkim = envelopeDomain;
// do not break yet, maybe header domain result also exists
}
}
}
// no mathcing domain found, use the first valid one
if (!verificationResults.dkim && dkimResults.length) {
verificationResults.dkim = dkimResults[0].domain;
}
}
const { forwards, autoreplies, users } = tnx.notes.targets;
let messageId = (tnx.header.get('Message-Id') || '').toString();
let subject = (tnx.header.get('Subject') || '').toString();
let sendLogEntry = resolution => {
if (resolution) {
let rspamd = tnx.results.get('rspamd');
try {
subject = libmime.decodeWords(subject).trim();
} catch (E) {
// failed to parse value
}
let message = {
short_message: '[PROCESS] ' + queueId,
_mail_action: 'process',
_queue_id: queueId,
_ip: remoteIp,
_message_id: messageId.replace(/^[\s<]+|[\s>]+$/g, ''),
_spam_score: rspamd ? rspamd.score : '',
_spam_action: rspamd ? rspamd.action : '',
_from: tnx.notes.sender,
_subject: subject
};
Object.keys(resolution).forEach(key => {
if (resolution[key]) {
message[key] = resolution[key];
}
});
message._spam_tests = this.rspamdSymbols(tnx)
.map(symbol => `${symbol.key}=${symbol.score}`)
.join(', ');
plugin.loggelf(message);