/
index.js
1643 lines (1466 loc) · 52 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
const dns = require('dns');
const fs = require('fs');
const path = require('path');
const process = require('process');
const { debuglog } = require('util');
// eslint-disable-next-line n/no-deprecated-api
const punycode = require('punycode');
const ClamScan = require('clamscan');
const FileType = require('file-type');
const NaiveBayes = require('@ladjs/naivebayes');
const RE2 = require('re2');
const arrayJoinConjunction = require('array-join-conjunction');
const bitcoinRegex = require('bitcoin-regex');
const creditCardRegex = require('credit-card-regex');
const emailRegexSafe = require('email-regex-safe');
const emojiPatterns = require('emoji-patterns');
const escapeStringRegexp = require('escape-string-regexp');
const expandContractions = require('@stdlib/nlp-expand-contractions');
const fileExtension = require('file-extension');
const floatingPointRegex = require('floating-point-regex');
const franc = require('franc');
const getSymbolFromCurrency = require('currency-symbol-map');
const hasha = require('hasha');
const hexaColorRegex = require('hexa-color-regex');
const i18nLocales = require('i18n-locales');
const intoStream = require('into-stream');
const ipRegex = require('ip-regex');
const isBuffer = require('is-buffer');
const isSANB = require('is-string-and-not-blank');
const isStream = require('is-stream');
const isValidPath = require('is-valid-path');
const macRegex = require('mac-regex');
const macosVersion = require('macos-version');
const memoize = require('memoizee');
const mime = require('mime-types');
const ms = require('ms');
const natural = require('natural');
const normalizeUrl = require('normalize-url');
const phoneRegex = require('phone-regex');
const sanitizeHtml = require('sanitize-html');
const snowball = require('node-snowball');
const striptags = require('striptags');
const superagent = require('superagent');
const sw = require('stopword');
const toEmoji = require('gemoji/name-to-emoji');
const universalify = require('universalify');
const urlRegexSafe = require('url-regex-safe');
const validator = require('validator');
const which = require('which');
const { Iconv } = require('iconv');
const { codes } = require('currency-codes');
const { fromUrl, NO_HOSTNAME } = require('parse-domain');
const { parse } = require('node-html-parser');
const { simpleParser } = require('mailparser');
const debug = debuglog('spamscanner');
//
// NOTE: we periodically need to update this
//
// Source from: CC-CEDICT
// Licensed under Creative Commons Attribution-ShareAlike 4.0 International License
// <https://www.mdbg.net/chinese/dictionary?page=cc-cedict>
//
// <https://github.com/yishn/chinese-tokenizer>
//
const chineseTokenizer = require('chinese-tokenizer').loadFile(
path.join(__dirname, 'cedict_1_0_ts_utf-8_mdbg.txt')
);
const aggressiveTokenizer = new natural.AggressiveTokenizer();
const orthographyTokenizer = new natural.OrthographyTokenizer({
language: 'fi'
});
const aggressiveTokenizerFa = new natural.AggressiveTokenizerFa();
const aggressiveTokenizerFr = new natural.AggressiveTokenizerFr();
const aggressiveTokenizerId = new natural.AggressiveTokenizerId();
const aggressiveTokenizerIt = new natural.AggressiveTokenizerIt();
const tokenizerJa = new natural.TokenizerJa();
const aggressiveTokenizerNo = new natural.AggressiveTokenizerNo();
const aggressiveTokenizerPl = new natural.AggressiveTokenizerPl();
const aggressiveTokenizerPt = new natural.AggressiveTokenizerPt();
const aggressiveTokenizerEs = new natural.AggressiveTokenizerEs();
const aggressiveTokenizerSv = new natural.AggressiveTokenizerSv();
const aggressiveTokenizerRu = new natural.AggressiveTokenizerRu();
const aggressiveTokenizerVi = new natural.AggressiveTokenizerVi();
const stopwordsEn = new Set([
...require('natural/lib/natural/util/stopwords').words,
...sw.eng
]);
const stopwordsEs = new Set([
...require('natural/lib/natural/util/stopwords_es').words,
...sw.spa
]);
const stopwordsFa = new Set([
...require('natural/lib/natural/util/stopwords_fa').words,
...sw.fas
]);
const stopwordsFr = new Set([
...require('natural/lib/natural/util/stopwords_fr').words,
...sw.fra
]);
const stopwordsId = new Set([
...require('natural/lib/natural/util/stopwords_id').words,
...sw.ind
]);
const stopwordsJa = new Set([
...require('natural/lib/natural/util/stopwords_ja').words,
...sw.jpn
]);
const stopwordsIt = new Set([
...require('natural/lib/natural/util/stopwords_it').words,
...sw.ita
]);
const stopwordsNl = new Set([
...require('natural/lib/natural/util/stopwords_nl').words,
...sw.nld
]);
const stopwordsNo = new Set([
...require('natural/lib/natural/util/stopwords_no').words,
...sw.nob
]);
const stopwordsPl = new Set([
...require('natural/lib/natural/util/stopwords_pl').words,
...sw.pol
]);
const stopwordsPt = new Set([
...require('natural/lib/natural/util/stopwords_pt').words,
...sw.por,
...sw.porBr
]);
const stopwordsRu = new Set([
...require('natural/lib/natural/util/stopwords_ru').words,
...sw.rus
]);
const stopwordsSv = new Set([
...require('natural/lib/natural/util/stopwords_sv').words,
...sw.swe
]);
const stopwordsZh = new Set([
...require('natural/lib/natural/util/stopwords_zh').words,
...sw.zho
]);
const stopwordsRon = new Set(sw.ron);
const stopwordsTur = new Set(sw.tur);
const stopwordsVie = new Set(sw.vie);
const stopwordsDeu = new Set(sw.deu);
const stopwordsHun = new Set(sw.hun);
const stopwordsAra = new Set(sw.ara);
const stopwordsDan = new Set(sw.dan);
const stopwordsFin = new Set(sw.fin);
// TODO: add stopword pairing for these langs:
// afr
// ben
// bre
// bul
// cat
// ces
// ell
// epo
// est
// eus
// fra
// gle
// glg
// guj
// hau
// heb
// hin
// hrv
// hye
// kor
// kur
// lat
// lav
// lgg
// lggNd
// lit
// mar
// msa
// mya
// panGu
// slk
// slv
// som
// sot
// swa
// tgl
// tha
// ukr
// urd
// yor
// zul
// <https://stackoverflow.com/a/41353282>
// <https://www.ietf.org/rfc/rfc3986.txt>
const ENDING_RESERVED_REGEX = new RE2(
`[${escapeStringRegexp(":/?#[]@!$&'()*+,;=")}]+$`
);
const PKG = require('./package.json');
const VOCABULARY_LIMIT = require('./vocabulary-limit.js');
// TODO: convert this into a Map
const ISO_CODE_MAPPING = require('./iso-code-mapping.json');
const ISO_CODE_MAPPING_KEYS = Object.keys(ISO_CODE_MAPPING);
// <https://kb.smarshmail.com/Article/23567>
const EXECUTABLES = new Set(require('./executables.json'));
const REPLACEMENT_WORDS = require('./replacement-words.json');
const locales = new Set(i18nLocales.map((l) => l.toLowerCase()));
const normalizeUrlOptions = {
stripProtocol: true,
stripWWW: false,
removeQueryParameters: [],
removeTrailingSlash: true,
sortQueryParameters: false
};
// <https://stackoverflow.com/a/15926317>
// <https://github.com/uhop/node-re2#backreferences>
// <https://stackoverflow.com/a/26764609>
// <https://stackoverflow.com/a/9158444>
const ANCHOR_REGEX = new RE2(/<a.*?>.*?<\/a>/gi);
// <https://github.com/mathiasbynens/emoji-regex/issues/59#issuecomment-640418649>
const EMOJI_REGEX = new RE2(emojiPatterns.Emoji_All, 'gu');
const FLOATING_POINT_REGEX = new RE2(floatingPointRegex());
const CC_REGEX = new RE2(creditCardRegex());
const PHONE_REGEX = new RE2(phoneRegex());
const BITCOIN_REGEX = new RE2(bitcoinRegex());
const MAC_REGEX = new RE2(macRegex());
const HEXA_COLOR_REGEX = new RE2(hexaColorRegex());
// <https://github.com/NaturalNode/natural/issues/523#issuecomment-623287047>
// <https://github.com/yoshuawuyts/newline-remove>
const NEWLINE_REGEX = new RE2(/\r\n|\n|\r/gm);
// <https://stackoverflow.com/a/5917217>
const NUMBER_REGEX = new RE2(/\d[\d,.]*/g);
// NOTE: we use my package url-safe-regex instead
// of url-regex due to CVE advisory among other issues
// https://github.com/niftylettuce/url-regex-safe
const URL_REGEX = urlRegexSafe();
// NOTE: we use my package email-safe-regex instead
// of email-regex due to several issues
// https://github.com/niftylettuce/email-regex-safe
const EMAIL_REGEX = emailRegexSafe();
// <https://superuser.com/a/1182181>
const INITIALISM_REGEX = new RE2(/\b(?:[A-Z][a-z]*){2,}/g);
// <https://stackoverflow.com/q/35076016>
const ABBREVIATION_REGEX = new RE2(/\b(?:[a-zA-Z]\.){2,}/g);
const currencySymbols = [];
for (const code of codes()) {
const symbol = getSymbolFromCurrency(code);
if (
typeof symbol === 'string' &&
// eslint-disable-next-line unicorn/prefer-includes
currencySymbols.indexOf(symbol) === -1 &&
!new RE2(/^[a-z]+$/i).test(symbol)
)
currencySymbols.push(escapeStringRegexp(symbol));
}
const CURRENCY_REGEX = new RE2(new RegExp(currencySymbols.join('|'), 'g'));
// <https://spamassassin.apache.org/gtube/>
// <https://spamassassin.apache.org/gtube/gtube.txt>
const GTUBE =
'XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X';
const MAIL_PHISHING_PROPS = ['subject', 'from', 'to', 'cc', 'bcc', 'text'];
const TOKEN_HEADERS = [...MAIL_PHISHING_PROPS, 'html'];
// <https://github.com/sindresorhus/ip-regex>
const IP_REGEX = new RE2(ipRegex());
// strip zero-width characters
// <https://github.com/peerigon/parse-domain/issues/116>
const ZERO_WIDTH_REGEX = new RE2(/[\u{200B}-\u{200D}]/gu);
const isURLOptions = {
require_tld: false,
require_protocol: false,
require_host: false,
require_valid_protocol: false
};
class SpamScanner {
constructor(config = {}) {
this.config = {
debug:
process.env.NODE_ENV === 'test' ||
process.env.NODE_ENV === 'development',
checkIDNHomographAttack: false,
// note that if you attempt to train an existing `scanner.classifier`
// then you will need to re-use these, so we suggest you store them
replacements: config.replacements || require('./replacements.js'),
// <https://nodemailer.com/extras/mailparser/>
// NOTE: `iconv` package's Iconv cannot be used in worker threads
// AND it can not also be shared in worker threads either (e.g. cloned)
// <https://github.com/bnoordhuis/node-iconv/issues/211>
// BUT we MUST use it because otherwise emails won't get parsed
simpleParser: { Iconv },
// <https://github.com/NaturalNode/natural#bayesian-and-logistic-regression>
// (ham) + a few other datasets
// `wget --mirror --passive-ftp ftp://ftp.ietf.org/ietf-mail-archive`
// `wget --mirror --passive-ftp ftp://ftp.ietf.org/concluded-wg-ietf-mail-archive`
// (spam dataset is private at the moment)
classifier: config.classifier || require('./get-classifier.js'),
// default locale validated against i18n-locales
locale: 'en',
// we recommend to use axe/cabin, see https://cabinjs.com
logger: console,
// <https://github.com/apostrophecms/sanitize-html#what-are-the-default-options>
// <https://developer.mozilla.org/en-US/docs/Web/HTML/Element>
sanitizeHtml: {
allowedTags: [
'address',
'article',
'aside',
'footer',
'header',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'hgroup',
'nav',
'section',
'blockquote',
'dd',
'div',
'dl',
'dt',
'figcaption',
'figure',
'hr',
'li',
'main',
'ol',
'p',
'pre',
'ul',
'a',
'abbr',
'b',
'bdi',
'bdo',
'br',
'cite',
'code',
'data',
'dfn',
'em',
'i',
'kbd',
'mark',
'q',
'rp',
'rt',
'rtc',
'ruby',
's',
'samp',
'span',
'strong',
'sub',
'sup',
'time',
'u',
'var',
'wbr',
// area
// audio
// img
// map
// track
// video
// embed
// iframe
// object
// param
// picture
// source
// canvas
// noscript
// script
'del',
'ins',
'caption',
'col',
'colgroup',
'table',
'tbody',
'td',
'tfoot',
'th',
'thead',
'tr',
// NO FORM STUFF
'details',
'dalog',
'menu',
'summary',
// slot
// template
'center',
'marquee',
'strike'
],
allowedAttributes: false
},
userAgent: `${PKG.name}/${PKG.version}`,
timeout: ms('10s'),
clamscan: {
debugMode:
process.env.NODE_ENV === 'test' ||
process.env.NODE_ENV === 'development',
clamscan: {
path: which.sync('clamscan', { nothrow: true })
},
clamdscan: {
timeout: ms('10s'),
path: which.sync('clamdscan', { nothrow: true }),
socket: macosVersion.isMacOS
? '/tmp/clamd.socket'
: '/var/run/clamav/clamd.ctl'
}
},
hasha: {
algorithm: 'sha256'
},
vocabularyLimit: VOCABULARY_LIMIT,
// <https://github.com/medikoo/memoizee#expire-cache-after-given-period-of-time>
memoize: {
...config.memoize,
// override always
promise: true
},
// @ladjs/redis client instance
client: false,
cachePrefix: 'spamscanner',
ttlMs: ms('1h'),
// franc
franc: {
minLength: 5,
only: ISO_CODE_MAPPING_KEYS
},
// if franc detects multiple languages that have >= % threshold
// then if the locale detected was one of them, what is the probability
// it must have in order to override all the other matches
detectedLocaleOverrideProbability: 0.9,
...config
};
// ensure all replacements are there
if (typeof this.config.replacements !== 'object')
throw new Error('Replacements missing');
for (const replacement of REPLACEMENT_WORDS) {
if (!isSANB(this.config.replacements[replacement]))
throw new Error(`Replacement for "${replacement}" missing`);
}
this.classifier =
typeof this.config.classifier === 'object'
? this.config.classifier
: typeof this.config.classifier === 'string'
? isValidPath(this.config.classifier)
? require(this.config.classifier)
: JSON.parse(this.config.classifier)
: false;
this.classifier = NaiveBayes.fromJson(
this.classifier,
this.config.vocabularyLimit
);
// since we do tokenization ourselves
this.classifier.tokenizer = function (tokens) {
return tokens;
};
this.clamscan = this.config.clamscan === false ? false : new ClamScan();
this.getTokensAndMailFromSource = universalify.fromPromise(
this.getTokensAndMailFromSource.bind(this)
);
this.getPhishingResults = this.getPhishingResults.bind(this);
// this.getNSFWResuls = universalify.fromPromise(this.getNSFWResults.bind(this));
this.getExecutableResults = universalify.fromPromise(
this.getExecutableResults.bind(this)
);
this.scan = universalify.fromPromise(this.scan.bind(this));
this.getTokens = this.getTokens.bind(this);
this.parseLocale = this.parseLocale.bind(this);
this.getNormalizedUrl = this.getNormalizedUrl.bind(this);
this.getUrls = this.getUrls.bind(this);
this.malwareLookup = this.malwareLookup.bind(this);
this.isCloudflareBlocked = this.isCloudflareBlocked.bind(this);
this.getArbitraryResults = this.getArbitraryResults.bind(this);
this.getVirusResults = universalify.fromPromise(
this.getVirusResults.bind(this)
);
this.getHostname = this.getHostname.bind(this);
this.getClassification = this.getClassification.bind(this);
// memoized methods (either uses Redis or in-memory cache)
if (this.config.client)
this.memoizedIsCloudflareBlocked = async function (name) {
const key = `${this.config.cachePrefix}:${name}`;
try {
const value = await this.config.client.get(key);
if (value) {
let array = value.split(':');
if (array.length !== 2)
throw new Error('Length was not exactly two');
array = array.map((value_) => value_ === 'true');
return { isAdult: array[0], isMalware: array[1] };
}
} catch (err) {
this.config.logger.error(err);
}
const { isAdult, isMalware } = await this.isCloudflareBlocked(name);
// cache in the background
this.config.client
.set(key, `${isAdult}:${isMalware}`, 'PX', this.config.ttlMs)
.then(this.config.logger.info)
.catch(this.config.logger.error);
return { isAdult, isMalware };
};
else
this.memoizedIsCloudflareBlocked = memoize(
this.isCloudflareBlocked,
this.config.memoize
);
if (!locales.has(this.parseLocale(this.config.locale)))
throw new Error(
`Locale of ${this.config.locale} was not valid according to locales list.`
);
//
// set up regex helpers
//
this.EMAIL_REPLACEMENT_REGEX = new RE2(this.config.replacements.email, 'g');
const replacementRegexes = [];
for (const key of Object.keys(this.config.replacements)) {
replacementRegexes.push(
escapeStringRegexp(this.config.replacements[key])
);
}
this.REPLACEMENTS_REGEX = new RE2(
new RegExp(replacementRegexes.join('|'), 'g')
);
//
// set up helper Map and Sets for fast lookup
// (Set.has is 2x faster than includes, and 50% faster than indexOf)
//
this.WHITELISTED_WORDS = new Set(Object.values(this.config.replacements));
}
getHostname(link) {
link = link.trim().replace(/\.+$/, '').toLowerCase();
// strip zero-width characters
// <https://github.com/peerigon/parse-domain/issues/116>
link = link.replace(ZERO_WIDTH_REGEX, '');
// if it was not a valid URL then ignore it
if (!validator.isURL(link, isURLOptions)) return;
// <https://github.com/peerigon/parse-domain/issues/114>
if (validator.isIP(link)) return link;
// uses `new Url` (e.g. it adds http:// if it does not exist)
let unicode = link;
try {
unicode = punycode.toUnicode(link);
} catch (err) {
/*
Overflow: input needs wider integers to process
RangeError: Overflow: input needs wider integers to process
at error (punycode.js:42:8)
at decode (punycode.js:241:5)
at punycode.js:389:6
at map (punycode.js:57:20)
at mapDomain (punycode.js:84:18)
at Object.toUnicode (punycode.js:387:9)
at SpamScanner.getHostname
*/
this.config.logger.warn(err);
}
// NOTE: IPv6 is not currently working with parse-domain and I already filed an issue
// <https://github.com/peerigon/parse-domain/issues/114>
const url = fromUrl(unicode);
if (url === NO_HOSTNAME) {
// use ipv4 and ipv6 regex to get just the value
const matches = link.match(IP_REGEX) || [];
if (matches.length > 0) {
if (matches.length > 1)
this.config.logger.error(
new Error(
`${link} had more than one match for IPv4/IPv6: ${matches.join(
', '
)}`
)
);
return matches[0];
}
// if there were still no matches, then check if it was a phone number
if (new RE2(phoneRegex()).test(link)) return;
// if it was a file path, then ignore it
if (isValidPath(link)) return;
// it was most likely invalid as it was just "foo" or it started with a slash like "/newsletter/unsubscribe"
// this code should never be reached, but just in case we should know if something is weird
this.config.logger.warn(
new Error(`${link} was invalid and did not have a hostname`)
);
return;
}
return url;
}
getClassification(tokens) {
return Promise.resolve(this.classifier.categorize(tokens, true));
}
async getVirusResults(mail) {
const messages = [];
if (!this.clamscan) {
debug('clamscan disabled');
return messages;
}
if (!Array.isArray(mail.attachments) || mail.attachments.length === 0)
return messages;
try {
// if it was already loaded, clamscan won't reload itself
// it has logic built-in to return early with the already initialized instance
const clamscan = await this.clamscan.init(this.config.clamscan);
await Promise.all(
mail.attachments.map(async (attachment, i) => {
try {
const stream = isStream(attachment.content)
? attachment.content
: intoStream(attachment.content);
const { isInfected, viruses } = await clamscan.scanStream(stream);
const name = isSANB(attachment.filename)
? `"${attachment.filename}"`
: `#${i + 1}`;
if (isInfected)
messages.push(
`Attachment ${name} was infected with ${arrayJoinConjunction(
viruses
)}.`
);
} catch (err) {
this.config.logger.error(err);
}
})
);
} catch (err) {
this.config.logger.error(err);
}
return messages;
}
getArbitraryResults(mail) {
const messages = [];
let gtube = false;
// eslint-disable-next-line unicorn/prefer-includes
if (isSANB(mail.html) && mail.html.indexOf(GTUBE) !== -1) gtube = true;
// eslint-disable-next-line unicorn/prefer-includes
if (isSANB(mail.text) && !gtube && mail.text.indexOf(GTUBE) !== -1)
gtube = true;
if (gtube)
messages.push(
'Message detected to contain the GTUBE test from https://spamassassin.apache.org/gtube/.'
);
return messages;
}
// pass this a DNS over HTTPS endpoint to lookup for 0.0.0.0 result
async malwareLookup(endpoint, name) {
try {
const response = await superagent
.get(endpoint)
.query({
name,
type: 'A'
})
.timeout(this.config.timeout)
.set('Accept', 'application/dns-json')
.set('User-Agent', this.config.userAgent)
.send();
const body = JSON.parse(response.body);
return (
Array.isArray(body.Answer) &&
body.Answer.length === 1 &&
body.Answer[0].data === '0.0.0.0'
);
} catch (err) {
this.config.logger.error(err);
try {
//
// NOTE: note that in newer Node versions we will
// be able to configure a DNS lookup timeout
// and we should also support this DNS + fallback approach
// in Forward Email at some point in the future
// and additionally ensure that the DNS lookup fallback
// uses DNS over TLS with DNSSEC (+ documentation for self hosting)
//
const records = await dns.promises.resolve4(name);
return (
Array.isArray(records) &&
records.length === 1 &&
records[0] === '0.0.0.0'
);
} catch (err) {
this.config.logger.warn(err);
return false;
}
}
}
//
// DNS over HTTPS with Cloudflare for Family
// <https://one.one.one.one/family/>
// <https://developers.cloudflare.com/1.1.1.1/1.1.1.1-for-families/setup-instructions/dns-over-https/>
// <https://developers.cloudflare.com/1.1.1.1/dns-over-https/json-format/>
//
// curl -H 'accept: application/dns-json' 'https://family.cloudflare-dns.com/dns-query?name=phishing.example.com&type=A'
// {"Status":0,"TC":false,"RD":true,"RA":true,"AD":false,"CD":false,"Question":[{"name":"phishing.example.com","type":1}],"Answer":[{"name":"phishing.example.com","type":1,"TTL":60,"data":"0.0.0.0"}]}
//
async isCloudflareBlocked(name) {
//
// NOTE: this uses DNS over HTTPS with a fallback system-level DNS lookup
// (which would assume you are using either 1.1.1.2 + 1.0.0.2 OR 1.1.1.3 + 1.0.0.3)
// <https://developers.cloudflare.com/1.1.1.1/1.1.1.1-for-families>
//
// However we don't recommend this and therefore have our servers set to standard Cloudflare DNS
//
const [isAdult, isMalware] = await Promise.all([
this.malwareLookup('https://family.cloudflare-dns.com/dns-query', name),
this.malwareLookup('https://security.cloudflare-dns.com/dns-query', name)
]);
return { isAdult, isMalware };
}
//
// due to this issue and the fact that PhishTank adds invalid URL's
// we have to implement our own workaround to normalize a valid/invalid URL
// <https://github.com/sindresorhus/normalize-url/issues/111>
//
getNormalizedUrl(url) {
url = url.trim().replace(/\.+$/, '').toLowerCase();
// strip zero-width characters
// <https://github.com/peerigon/parse-domain/issues/116>
url = url.replace(ZERO_WIDTH_REGEX, '');
// don't return a URL if it was invalid after being trimmed
if (!validator.isURL(url, isURLOptions)) return;
let normalized = url;
try {
normalized = normalizeUrl(url, normalizeUrlOptions);
} catch (err) {
this.config.logger.error(err);
// <https://stackoverflow.com/questions/6680825/return-string-without-trailing-slash#comment11853012_6680877>
normalized = url
.replace('http://', '')
.replace('https://', '')
.replace(/\/+$/, '');
}
const hostname = fromUrl(normalized);
if (hostname === NO_HOSTNAME) {
this.config.logger.error(
new Error(`No hostname (URL: ${url}, NORMALIZED: ${normalized}`)
);
// if there were still no matches, then check if it was a phone number
if (new RE2(phoneRegex()).test(normalized)) return;
// if it was a file path, then ignore it
if (isValidPath(normalized)) return;
return normalized;
}
let unicode = hostname;
try {
unicode = punycode.toUnicode(hostname);
} catch (err) {
this.config.logger.warn(err);
}
try {
const object = new URL(
`http://${unicode}${normalized.slice(hostname.length)}`
);
//
// NOTE: we must strip reserved characters from the end of the string
// (even Gmail does this practice)
// <https://github.com/kevva/url-regex/issues/71>
const pathname = object.pathname.replace(ENDING_RESERVED_REGEX, '');
//
// NOTE: we strip querystring and hash here as we don't consider them
// which may ultimately lead to false positives on mass emailing services
// however we are taking this approach because these services should
// be enforcing strict anti-spam policies and prevention measures anyways
// (e.g. we will send them 429 retry or spam complaint status code
// which will in turn alert them to the issue with whoever is spamming)
//
return `${object.hostname}${pathname === '/' ? '' : pathname}`;
} catch (err) {
this.config.logger.error(err, { url, normalized });
return normalized;
}
}
// <https://github.com/kevva/url-regex/issues/70
// <https://github.com/sindresorhus/get-urls/blob/master/index.js
// <https://github.com/kevva/url-regex/issues/71>
// <https://github.com/kevva/url-regex/pull/35>
//
getUrls(text) {
// before we filter for URL's, we need to replace email addresses
// with hostnames, otherwise there will be incorrect matches
// due to the inaccuracy (which is unpreventable) from url-regex-safe
// when parsing email addresses, e.g. foo.it.beep.mx.bar@gmail.com
// would normally get parsed to [ foo.it, beep.mx, gmail.com ]
// but it should only get parsed to gmail.com since that's the hostname
// <https://github.com/kevva/url-regex/pull/67>
const urls =
text
.replace(NEWLINE_REGEX, ' ')
.replace(
EMAIL_REGEX,
(match) =>
` ${this.getHostname(match.slice(match.lastIndexOf('@') + 1))} `
)
.replace(URL_REGEX, (match, offset, string) => {
const nextChar = string.slice(
offset + match.length,
offset + match.length + 1
);
if (new RE2(/^\w$/).test(nextChar)) return ' ';
// only return a match if the case was the same when converted
// (this matches Gmail's behavior in parsing/rendering URL's)
if (match.toLowerCase() !== match && match.toUpperCase() !== match)
return ' ';
return ` ${match} `;
})
.match(URL_REGEX) || [];
const array = new Set();
for (const url of urls) {
const normalized = this.getNormalizedUrl(url);
if (normalized) array.add(normalized);
}
return [...array];
}
parseLocale(locale) {
// convert `franc` locales here to their locale iso2 normalized name
return locale.toLowerCase().split('-')[0].split('_')[0];
}
// <https://medium.com/analytics-vidhya/building-a-spam-filter-from-scratch-using-machine-learning-fc58b178ea56>
// <https://towardsdatascience.com/empirical-analysis-on-email-classification-using-the-enron-dataset-19054d558697>
// <https://blog.logrocket.com/natural-language-processing-for-node-js/>
// <https://github.com/NaturalNode/natural#stemmers>
// eslint-disable-next-line complexity
async getTokens(string, locale, isHTML = false) {
//
// parse HTML for <html> tag with lang attr
// otherwise if that wasn't found then look for this
// <meta http-equiv="Content-Language" content="en-us">
//
if (!locale && isHTML) {
const root = parse(string);
const metas = root.querySelectorAll('meta');
for (const meta of metas) {
if (
meta.getAttribute('http-equiv') === 'Content-Language' &&
isSANB(meta.getAttribute('content')) &&
locales.has(this.parseLocale(meta.getAttribute('content')))
) {
locale = this.parseLocale(meta.getAttribute('content'));
break;
}
}
const _metas = root.querySelectorAll('META');
for (const meta of _metas) {
if (
meta.getAttribute('http-equiv') === 'Content-Language' &&
isSANB(meta.getAttribute('content')) &&
locales.has(this.parseLocale(meta.getAttribute('content')))
) {
locale = this.parseLocale(meta.getAttribute('content'));
break;
}
}
if (!locale) {
const html = root.querySelector('html') || root.querySelector('HTML');
if (
html &&
isSANB(html.getAttribute('lang')) &&
locales.has(this.parseLocale(html.getAttribute('lang')))
)
locale = this.parseLocale(html.getAttribute('lang'));
}
}
if (isHTML) string = sanitizeHtml(string, this.config.sanitizeHtml);
string = striptags(string, [], ' ')
.trim()
// replace newlines
.replace(NEWLINE_REGEX, ' ')
//
// attackers may try to inject our replacements into the message
// therefore we should strip all of them before doing any replacements
//
.replace(this.REPLACEMENTS_REGEX, ' ');
//
// we should instead use language detection to determine
// what language/locale this message is in (as opposed to relying on headers)
// which could get arbitrarily modified by an attacker
// <https://github.com/wooorm/franc/issues/86> (accurate with min length)
// <https://github.com/FGRibreau/node-language-detect> (not too accurate)
//
const detectedLanguages = franc.all(string, this.config.franc);
if (Array.isArray(detectedLanguages) && detectedLanguages.length > 0) {
let detected = this.config.locale;
let probability = 0;
for (const lang of detectedLanguages) {
// if it was undetermined then break out and revert to default (English)
if (lang[0] && lang[0] === 'und') break;
//
// otherwise only use detected languages that have >= 90% accuracy
// and if no matches were found, the revert to use English as it's most likely spam
// (we can assume that users would understand a different language sent to them is spam)
// (so we can assume that language is spoofed to bypass English, the most widely spoken)
//
if (lang[0] && ISO_CODE_MAPPING[lang[0]] && lang[1]) {
// we don't want to check anything lower than our threshold
if (lang[1] < this.config.detectedLocaleOverrideProbability) break;