/
SweepViruses.pm
3541 lines (3086 loc) · 120 KB
/
SweepViruses.pm
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
#
# MailScanner - SMTP Email Processor
# Copyright (C) 2019 MailScanner Team <https://mailscanner.info>
#
# $Id: SweepViruses.pm 5086 2011-03-16 19:37:02Z sysjkf $
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# https://www.mailscanner.info
#
package MailScanner::SweepViruses;
use strict 'vars';
use strict 'refs';
no strict 'subs'; # Allow bare words for parameter %'s
use POSIX;
use DirHandle;
use IO::Socket::INET;
use IO::Socket::UNIX;
use IO::Pipe;
use IO::File;
use vars qw($VERSION $ScannerPID);
### The package version, both in 1.23 style *and* usable by MakeMaker:
$VERSION = substr q$Revision: 5086 $, 10;
# Locking definitions for flock() which is used to lock the Lock file
my($LOCK_SH) = 1;
my($LOCK_EX) = 2;
my($LOCK_NB) = 4;
my($LOCK_UN) = 8;
# Sophos SAVI Library object and ide directory modification time
my($SAVI, $SAVIidedirmtime, $SAVIlibdirmtime, $SAVIinuse, %SAVIwatchfiles);
$SAVIidedirmtime = 0;
$SAVIlibdirmtime = 0;
$SAVIinuse = 0;
%SAVIwatchfiles = ();
# ClamAV Module object and library directory modification time
# my($Clam, $Claminuse, %Clamwatchfiles);
# $Claminuse = 0;
# %Clamwatchfiles = ();
# So we can kill virus scanners when we are HUPped
$ScannerPID = 0;
my $scannerlist = "";
#
# Virus scanner definitions table
#
my (
$S_NONE, # Not present
$S_UNSUPPORTED, # Present but you're on your own
$S_ALPHA, # Present but not tested -- we hope it works!
$S_BETA, # Present and tested to some degree -- we think it works!
$S_SUPPORTED, # People use this; it'd better work!
) = (0,1,2,3,4);
my %Scanners = (
generic => {
Name => 'Generic',
Lock => 'genericBusy.lock',
CommonOptions => '',
DisinfectOptions => '-disinfect',
ScanOptions => '',
InitParser => \&InitGenericParser,
ProcessOutput => \&ProcessGenericOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
savid => {
Name => 'Sophos',
Lock => 'sophosBusy.lock',
CommonOptions => '',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitSAVIDParser,
ProcessOutput => \&ProcessOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
sophossavi => {
Name => 'SophosSAVI',
Lock => 'sophosBusy.lock',
# In next line, '-ss' makes it work nice and quietly
CommonOptions => '',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitSophosSAVIParser,
ProcessOutput => \&ProcessSophosSAVIOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
sophos => {
Name => 'Sophos',
Lock => 'sophosBusy.lock',
# In next line, '-ss' makes it work nice and quietly
CommonOptions => '-sc -f -all -rec -ss -archive -cab -loopback ' .
'--no-follow-symlinks --no-reset-atime -TNEF',
DisinfectOptions => '-di',
ScanOptions => '',
InitParser => \&InitSophosParser,
ProcessOutput => \&ProcessSophosOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_SUPPORTED,
},
"f-secure-12" => {
name => "F-Secure-12",
Lock => 'f-secure12Busy.lock',
CommonOptions => '--quiet --scan-archives=yes --detect-encrypted-archives=no',
DisinfectOptions => '--malware=remove --pua=remove',
ScanOptions => '',
InitParser => \&InitFSecure12Parser,
ProcessOutput => \&ProcessFSecure12Output,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_SUPPORTED,
},
"f-secure" => {
Name => 'F-Secure',
Lock => 'f-secureBusy.lock',
CommonOptions => '--dumb --archive',
DisinfectOptions => '--auto --disinf',
ScanOptions => '',
InitParser => \&InitFSecureParser,
ProcessOutput => \&ProcessFSecureOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_SUPPORTED,
},
"f-secured" => {
Name => 'F-Secured',
Lock => 'f-secureBusy.lock',
CommonOptions => '',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitFSecuredParser,
ProcessOutput => \&ProcessOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
"f-protd-6" => {
Name => 'F-Protd6',
Lock => 'f-prot-6Busy.lock',
CommonOptions => '',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitFProtd6Parser,
ProcessOutput => \&ProcessOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
# "clamavmodule" => {
# Name => 'ClamAVModule',
# Lock => 'clamavBusy.lock',
# CommonOptions => '',
# DisinfectOptions => '',
# ScanOptions => '',
# InitParser => \&InitClamAVModParser,
# ProcessOutput => \&ProcessClamAVModOutput,
# SupportScanning => $S_SUPPORTED,
# SupportDisinfect => $S_NONE,
# },
"clamd" => {
Name => 'Clamd',
Lock => 'clamavBusy.lock',
CommonOptions => '',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitClamdParser,
ProcessOutput => \&ProcessClamdOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
# "clamav" => {
# Name => 'ClamAV',
# Lock => 'clamavBusy.lock',
# CommonOptions => '-r --infected --stdout',
# DisinfectOptions => '',
# ScanOptions => '',
# InitParser => \&InitClamAVParser,
# ProcessOutput => \&ProcessClamAVOutput,
# SupportScanning => $S_SUPPORTED,
# SupportDisinfect => $S_NONE,
# },
"bitdefender" => {
Name => 'Bitdefender',
Lock => 'bitdefenderBusy.lock',
CommonOptions => '--arc --mail --all',
DisinfectOptions => '--disinfect',
ScanOptions => '',
InitParser => \&InitBitdefenderParser,
ProcessOutput => \&ProcessBitdefenderOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_SUPPORTED,
},
"avg" => {
Name => 'Avg',
Lock => 'avgBusy.lock',
CommonOptions => '--arc', # Remove by Chris Richardson: -ext=*',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitAvgParser,
ProcessOutput => \&ProcessAvgOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
"none" => {
Name => 'None',
Lock => 'NoneBusy.lock',
CommonOptions => '',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&NeverHappens,
ProcessOutput => \&NeverHappens,
SupportScanning => $S_NONE,
SupportDisinfect => $S_NONE,
},
"avast" => {
Name => 'Avast',
Lock => 'avastBusy.lock',
CommonOptions => '-b -f -a',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitAvastParser,
ProcessOutput => \&ProcessAvastOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_SUPPORTED,
},
"avastd" => {
Name => 'Avastd',
Lock => 'avastBusy.lock',
CommonOptions => '-n',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitAvastdParser,
ProcessOutput => \&ProcessOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
"esets" => {
Name => 'esets',
Lock => 'esetsBusy.lock',
CommonOptions => '',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitEsetsParser,
ProcessOutput => \&ProcessEsetsOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_SUPPORTED,
},
"esetsefs" => {
Name => 'esetsefs',
Lock => 'esetsefsBusy.lock',
CommonOptions => '-s --profile="@In-depth scan"',
DisinfectOptions => '',
ScanOptions => '--readonly',
InitParser => \&InitEsetsEFSParser,
ProcessOutput => \&ProcessEsetsEFSOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_SUPPORTED,
},
"kse" => {
Name => 'KSE',
Lock => 'kseBusy.lock',
CommonOptions => '',
DisinfectOptions => '',
ScanOptions => '',
InitParser => \&InitKseParser,
ProcessOutput => \&ProcessOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
"drweb" => {
Name => 'DrWeb',
Lock => 'drwebBusy.lock',
CommonOptions => '',
DisinfectOptions => '-cu',
ScanOptions => '',
InitParser => \&InitDrwebParser,
ProcessOutput => \&ProcessDrwebOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_NONE,
},
"kaspersky" => {
Name => 'Kaspersky',
Lock => 'kasperskyBusy.lock',
CommonOptions => '',
DisinfectOptions => '-i2',
ScanOptions => '-i0',
InitParser => \&InitKasperskyParser,
ProcessOutput => \&ProcessKasperskyOutput,
SupportScanning => $S_SUPPORTED,
SupportDisinfect => $S_SUPPORTED,
},
);
# Initialise the Sophos SAVI library if we are using it.
sub initialise {
my(@scanners);
$scannerlist = MailScanner::Config::Value('virusscanners');
# If they have not configured the list of virus scanners, then try to
# use all the scanners they have installed, by using the same system
# that ms-update-vs uses to locate them all.
#print STDERR "Scanner list read from MailScanner.conf is \"$scannerlist\"\n";
if ($scannerlist =~ /^\s*auto\s*$/i) {
# If we have multiple clam types, then tend towards clamd
my %installed = map { $_ => 1 } InstalledScanners();
# delete $installed{'clamavmodule'} if $installed{'clamavmodule'} &&
# $installed{'clamd'};
# delete $installed{'clamav'} if $installed{'clamav'} &&
# ($installed{'clamd'} ||
# $installed{'clamavmodule'});
$scannerlist = join(' ', keys %installed);
MailScanner::Log::InfoLog("Auto: Found virus scanners: %s ", $scannerlist);
if ($scannerlist =~ /^\s*$/) {
MailScanner::Log::WarnLog("Warning: no virus scanners found via auto select");
#print STDERR "No virus scanners found to be installed at all!\n";
$scannerlist = "none";
}
}
$scannerlist =~ tr/,//d;
@scanners = split(" ", $scannerlist);
# Import the SAVI code and initialise the SAVI library
if (grep /^sophossavi$/, @scanners) {
$SAVIinuse = 1;
#print STDERR "SAVI in use\n";
InitialiseSAVI();
}
# # Import the ClamAV code and initialise the ClamAV library
# if (grep /^clamavmodule$/, @scanners) {
# $Claminuse = 1;
# #print STDERR "ClamAV Module in use\n";
# InitialiseClam();
# }
}
# sub InitialiseClam {
# # Initialise ClamAV Module
# MailScanner::Log::DieLog("ClamAV Perl module not found")
# unless eval 'require Mail::ClamAV';
# my $ver = $Mail::ClamAV::VERSION + 0.0;
# MailScanner::Log::DieLog("ClamAV Perl module must be at least version 0.12" .
# " and you only have version %.2f, and ClamAV must" .
# " be at least version 0.80", $ver)
# unless $ver >= 0.12;
# $Clam = new Mail::ClamAV(Mail::ClamAV::retdbdir())
# or MailScanner::Log::DieLog("ClamAV Module ERROR:: Could not load " .
# "databases from %s", Mail::ClamAV::retdbdir());
# $Clam->buildtrie;
# # Impose limits
# $Clam->maxreclevel(MailScanner::Config::Value('clamavmaxreclevel'));
# $Clam->maxfiles (MailScanner::Config::Value('clamavmaxfiles'));
# $Clam->maxfilesize(MailScanner::Config::Value('clamavmaxfilesize'));
# #0.93 $Clam->maxratio (MailScanner::Config::Value('clamavmaxratio'));
# # Build the hash of the size of all the watch files
# my(@watchglobs, $glob, @filelist, $file, $filecount);
# @watchglobs = split(" ", MailScanner::Config::Value('clamwatchfiles'));
# $filecount = 0;
# foreach $glob (@watchglobs) {
# @filelist = map { m/(.*)/ } glob($glob);
# foreach $file (@filelist) {
# $Clamwatchfiles{$file} = -s $file;
# $filecount++;
# }
# }
# MailScanner::Log::DieLog("None of the files matched by the \"Monitors " .
# "For ClamAV Updates\" patterns exist!") unless $filecount>0;
# #MailScanner::Log::WarnLog("\"Allow Password-Protected Archives\" should be set to just yes or no when using clamavmodule virus scanner")
# # unless MailScanner::Config::IsSimpleValue('allowpasszips');
# }
sub InitialiseSAVI {
# Initialise Sophos SAVI library
MailScanner::Log::DieLog("SAVI Perl module not found, did you install it?")
unless eval 'require SAVI';
my $SAVIidedir = MailScanner::Config::Value('sophoside');
$SAVIidedir = '/usr/local/Sophos/ide' unless $SAVIidedir;
my $SAVIlibdir = MailScanner::Config::Value('sophoslib');
$SAVIlibdir = '/usr/local/Sophos/lib' unless $SAVIlibdir;
$ENV{'SAV_IDE'} = $SAVIidedir;
print "INFO:: Meaningless output that goes nowhere, to keep SAVI happy\n";
$SAVI = new SAVI();
MailScanner::Log::DieLog("SophosSAVI ERROR:: initializing savi: %s (%s)",
SAVI->error_string($SAVI), $SAVI)
unless ref $SAVI;
my $version = $SAVI->version();
MailScanner::Log::DieLog("SophosSAVI ERROR:: getting version: %s (%s)",
$SAVI->error_string($version), $version)
unless ref $version;
MailScanner::Log::InfoLog("SophosSAVI %s (engine %d.%d) recognizing " .
"%d viruses", $version->string, $version->major,
$version->minor, $version->count);
my($ide,$idecount);
$idecount = 0;
foreach $ide ($version->ide_list) {
#MailScanner::Log::InfoLog("SophosSAVI IDE %s released %s",
# $ide->name, $ide->date);
$idecount++;
}
MailScanner::Log::InfoLog("SophosSAVI using %d IDE files", $idecount);
# I have removed "Mac" and "SafeMacDfHandling" from here as setting
# them gives an error.
my @options = qw(
FullSweep DynamicDecompression FullMacroSweep OLE2Handling
IgnoreTemplateBit VBA3Handling VBA5Handling OF95DecryptHandling
HelpHandling DecompressVBA5 Emulation PEHandling ExcelFormulaHandling
PowerPointMacroHandling PowerPointEmbeddedHandling ProjectHandling
ZipDecompression ArjDecompression RarDecompression UueDecompression
GZipDecompression TarDecompression CmzDecompression HqxDecompression
MbinDecompression !LoopBackEnabled
Lha SfxArchives MSCabinet TnefAttachmentHandling MSCompress
!DeleteAllMacros Vbe !ExecFileDisinfection VisioFileHandling
Mime ActiveMimeHandling !DelVBA5Project
ScrapObjectHandling SrpStreamHandling Office2001Handling
Upx PalmPilotHandling HqxDecompression
Pdf Rtf Html Elf WordB OutlookExpress
);
my $error = $SAVI->set('MaxRecursionDepth', 30, 1);
MailScanner::Log::DieLog("SophosSAVI ERROR:: setting MaxRecursionDepth:" .
" %s", $error) if defined $error;
foreach (@options) {
my $value = ($_ =~ s/^!//) ? 0 : 1;
$error = $SAVI->set($_, $value);
MailScanner::Log::WarnLog("SophosSAVI ERROR:: Setting %s: %s", $_, $error)
if defined $error;
}
## Store the last modified time of the SAVI lib directory, so we can check
## for major upgrades
my(@statresults);
#@statresults = stat($SAVIidedir);
#$SAVIidedirmtime = $statresults[9] or
# MailScanner::Log::WarnLog("Failed to read mtime of IDE dir %s",$SAVIidedir);
@statresults = stat($SAVIlibdir);
$SAVIlibdirmtime = $statresults[9] or
MailScanner::Log::WarnLog("Failed to read mtime of lib dir %s",$SAVIlibdir);
#MailScanner::Log::InfoLog("Watching modification date of %s and %s",
# $SAVIidedir, $SAVIlibdir);
# Build the hash of the size of all the watch files
my(@watchglobs, $glob, @filelist, $file, $filecount);
@watchglobs = split(" ", MailScanner::Config::Value('saviwatchfiles'));
$filecount = 0;
foreach $glob (@watchglobs) {
@filelist = map { m/(.*)/ } glob($glob);
foreach $file (@filelist) {
$SAVIwatchfiles{$file} = -s $file;
$filecount++;
}
}
MailScanner::Log::DieLog("None of the files matched by the \"Monitors " .
"For Sophos Updates\" patterns exist!") unless $filecount>0;
}
# Are there new Sophos IDE files?
# If so, abandon this child process altogether and start again.
# This is called from the main WorkForHours() loop
#
# If the lib directory has been updated, then a major Sophos update has
# happened. If the watch files have changed their size at all, or any
# of them have disappeared, then an IDE updated has happened.
# Normally just watch /u/l/S/ide/*.zip.
#
sub SAVIUpgraded {
my(@result, $idemtime, $libmtime, $watch, $size);
# If we aren't even using SAVI, then obviously we don't want to restart
return 0 unless $SAVIinuse;
#@result = stat(MailScanner::Config::Value('sophoside') ||
# '/usr/local/Sophos/ide');
#$idemtime = $result[9];
@result = stat(MailScanner::Config::Value('sophoslib') ||
'/opt/sophos-av/lib/sav');
# '/usr/local/Sophos/lib');
$libmtime = $result[9];
#if ($idemtime != $SAVIidedirmtime || $libmtime != $SAVIlibdirmtime) {
if ($libmtime != $SAVIlibdirmtime) {
MailScanner::Log::InfoLog("Sophos library update detected, " .
"resetting SAVI");
return 1;
}
while (($watch, $size) = each %SAVIwatchfiles) {
if ($size != -s $watch) {
MailScanner::Log::InfoLog("Sophos update of $watch detected, " .
"resetting SAVI");
keys %SAVIwatchfiles; # Necessary line to reset each()
return 1;
}
}
# No update detected
return 0;
}
# # Have the ClamAV database files been modified? (changed size)
# # If so, abandon this child process altogether and start again.
# # This is called from the main WorkForHours() loop
# #
# sub ClamUpgraded {
# my($watch, $size);
# return 0 unless $Claminuse;
# while (($watch, $size) = each %Clamwatchfiles) {
# if ($size != -s $watch) {
# MailScanner::Log::InfoLog("ClamAV update of $watch detected, " .
# "resetting ClamAV Module");
# keys %Clamwatchfiles; # Necessary line to reset each()
# return 1;
# }
# }
# # No update detected
# return 0;
# }
# Constructor.
sub new {
my $type = shift;
my $this = {};
#$this->{dir} = shift;
bless $this, $type;
return $this;
}
# Do all the commercial virus checking in here.
# If 2nd parameter is "disinfect", then we are disinfecting not scanning.
sub ScanBatch {
my $batch = shift;
my $ScanType = shift;
my($NumInfections, $success, $id, $BaseDir);
my(%Types, %Reports);
$NumInfections = 0;
$BaseDir = $global::MS->{work}->{dir};
chdir $BaseDir or die "Cannot chdir $BaseDir for virus scanning, $!";
my $scanattempts = MailScanner::Config::Value('virusscanattempts');
my $counter = 0;
my $scanstatus = 1;
while ($counter < $scanattempts) {
#print STDERR (($ScanType =~ /dis/i)?"Disinfecting":"Scanning") . " using ".
# "commercial virus scanners\n";
while($scanstatus) {
$success = TryCommercial($batch, '.', $BaseDir, \%Reports, \%Types,
\$NumInfections, $ScanType);
if ($success eq "ScAnNeRfAiLeD") {
if (MailScanner::Config::Value('retrybatchscanner') =~ /1/) {
MailScanner::Log::WarnLog("Virus Scanning: Batch scan failed, check A/V scanners! Trying again...");
# Match behvior of DropBatch delay since we aren't dropping the batch
sleep 10;
} else {
# Drop the batch instead of retrying
MailScanner::Log::WarnLog("Virus Scanning: No virus scanners worked, so message batch was abandoned and retried!");
$batch->DropBatch();
return 1;
}
} else {
$scanstatus = 0;
}
}
unless ($success) {
$counter++;
MailScanner::Log::WarnLog("Virus Scanning: Batch scan timed out, retry attempt %s", $counter);
# Small delay to give clamd another chance
sleep 10;
} else {
last;
}
}
unless ($success) {
# Virus checking the whole batch of messages timed out, so now check them
# one at a time to find the one with the DoS attack in it.
MailScanner::Log::WarnLog("Virus Scanning: No virus scanners worked, so messages will be tried again individually");
my $BaseDirH = new DirHandle;
MailScanner::Log::WarnLog("Virus Scanning: Clamd scan problem " .
"detected, trying individual messages!");
$BaseDirH->open('.')
or MailScanner::Log::DieLog("Can't open directory for scanning 1 message, $!");
while(defined($id = $BaseDirH->read())) {
next unless -d "$id"; # Only check directories
next if $id =~ /^\.+$/; # Don't check myself or my parent
$id =~ /^(.*)$/;
$id = $1;
next unless MailScanner::Config::Value('virusscan',$batch->{messages}{id}) =~ /1/;
$scanstatus = 1;
while($scanstatus) {
# The "./" is important as it gets the path right for parser code
$success = TryCommercial($batch, "./$id", $BaseDir, \%Reports,
\%Types, \$NumInfections, $ScanType);
if ($success eq 'ScAnNeRfAiLeD') {
if (MailScanner::Config::Value('retrybatchscanner') =~ /1/) {
MailScanner::Log::WarnLog("Virus Scanning: Batch scan failed, check A/V scanners! Trying again...");
# Match behvior of DropBatch delay since we aren't dropping the batch
sleep 10;
} else {
# If none of the scanners worked, then we need to abandon this batch
# Drop the batch instead of retrying
MailScanner::Log::WarnLog("Virus Scanning: No virus scanners worked, so message batch was abandoned and retried!");
$batch->DropBatch();
$BaseDirH->close();
return 1;
}
} else {
$scanstatus = 0;
}
}
unless ($success) {
# We have found the DoS attack message
if (MailScanner::Config::Value('stilldeliverunscannable') =~ /0/ ) {
$Reports{"$id"}{""} .=
MailScanner::Config::LanguageValue($batch->{messages}{$id},
'dosattack') . "\n";
$Types{"$id"}{""} .= "d";
MailScanner::Log::WarnLog("Virus Scanning: Failed to scan " .
"message due to Denial of Service or scan timeout %s", $id);
# No way here of incrementing the "otherproblems" counter. Ho hum.
} else {
MailScanner::Log::WarnLog("Virus Scanning: Unable to virus scan message, set to still deliver.");
}
}
}
$BaseDirH->close();
}
# Add all the %Reports and %Types to the message batch fields
MergeReports(\%Reports, \%Types, $batch);
# Return value is the number of infections we found
#print STDERR "Found $NumInfections infections!\n";
return $NumInfections;
}
# Merge all the virus reports and types into the properties of the
# messages in the batch. Doing this separately saves me changing
# the code of all the parsers to support the new OO structure.
# If we have at least 1 report for a message, and the "silent viruses" list
# includes the special keyword "All-Viruses" then mark the message as silent
# right now.
sub MergeReports {
my($Reports, $Types, $batch) = @_;
my($id, $reports, $attachment, $text);
my($cachedid, $cachedsilentflag);
my(%seenbefore);
# Let's do all the reports first...
$cachedid = 'uninitialised';
while (($id, $reports) = each %$Reports) {
#print STDERR "Report merging for \"$id\" and \"$reports\"\n";
next unless $id && $reports;
my $message = $batch->{messages}{"$id"};
# Skip this message if we didn't actually want it to be scanned.
next unless MailScanner::Config::Value('virusscan', $message) =~ /1/;
#print STDERR "Message is $message\n";
$message->{virusinfected} = 1;
# If the cached message id matches the current one, we are working on
# the same message as last time, so don't re-fetch the silent viruses
# list for this message.
if ($cachedid ne $id) {
my $silentlist = ' ' . MailScanner::Config::Value('silentviruses',
$message) . ' ';
$cachedsilentflag = ($silentlist =~ / all-viruses /i)?1:0;
$cachedid = $id;
}
# We can't be here unless there was a virus report for this message
$message->{silent} = 1 if $cachedsilentflag;
while (($attachment, $text) = each %$reports) {
#print STDERR "\tattachment \"$attachment\" has text \"$text\"\n";
#print STDERR "\tEntity of \"$attachment\" is \"" . $message->{file2entity} . "\"\n";
next unless $text;
# Sanitise the reports a bit
$text =~ s/\s{20,}/ /g;
$message->{virusreports}{"$attachment"} .= $text;
}
unless ($seenbefore{$id}) {
MailScanner::Log::NoticeLog("Infected message %s came from %s",
$id, $message->{clientip});
$seenbefore{$id} = 1;
}
}
# And then all the report types...
while (($id, $reports) = each %$Types) {
next unless $id && $reports;
my $message = $batch->{messages}{"$id"};
while (($attachment, $text) = each %$reports) {
next unless $text;
$message->{virustypes}{"$attachment"} .= $text;
}
}
}
# Try all the installed commercial virus scanners
# We are passed the directory to start scanning from,
# the message batch we are scanning,
# a ref to the infections counter.
# $ScanType can be one of "scan", "rescan", "disinfect".
sub TryCommercial {
my($batch, $dir, $BaseDir, $Reports, $Types, $rCounter, $ScanType) = @_;
my($scanner, @scanners, $disinfect, $result, $counter);
my($logtitle, $OneScannerWorked);
# If we aren't virus scanning *anything* then don't call the scanner
return 1 if MailScanner::Config::IsSimpleValue('virusscan') &&
!MailScanner::Config::Value('virusscan');
# $scannerlist is now a global for this file. If it was set to "auto"
# then I will have searched for all the scanners that appear to be
# installed. So by the time we get here, it should never be "auto" either.
# Unless of course they really have no scanners installed at all!
#$scannerlist = MailScanner::Config::Value('virusscanners');
$scannerlist =~ tr/,//d;
$scannerlist = "none" unless $scannerlist; # Catch empty setting
@scanners = split(" ", $scannerlist);
$counter = 0;
# Change actions and outputs depending on what we are trying to do
$disinfect = 0;
$disinfect = 1 if $ScanType !~ /scan/i;
$logtitle = "Virus Scanning";
$logtitle = "Virus Rescanning" if $ScanType =~ /re/i; # Rescanning
$logtitle = "Disinfection" if $ScanType =~ /dis/i; # Disinfection
# Work out the regexp for matching the spam-infected messages
# This is given by the user as a space-separated list of simple wildcard
# strings. Must split it up, escape everything, spot the * characters
# and join them together into one big regexp. Use lots of tricks from the
# Phishing regexp generator I wrote a month or two back.
my $spaminfsetting = MailScanner::Config::Value('spaminfected');
#$spaminfsetting = '*UNOFFICIAL HTML/* Sanesecurity.*'; # Test data
$spaminfsetting =~ s/\s+/ /g; # Squash multiple spaces
$spaminfsetting =~ s/^\s+//; # Trim leading and
$spaminfsetting =~ s/\s+$//; # trailing space.
$spaminfsetting =~ s/\s/ /g; # All tabs to spaces
$spaminfsetting =~ s/[^0-9a-z_ -]/\\$&/ig; # Quote every non-alnum except space.
$spaminfsetting =~ s/\\\*/.*/g; # Unquote any '*' characters as they map to .*
my @spaminfwords = split " ", $spaminfsetting;
# Combine all the words into an "or" list in a fast regexp,
# and anchor them all to the start and end of the string.
my $spaminfre = '(?:^\s*' . join('\s*$|^\s*', @spaminfwords) . '\s*$)';
$OneScannerWorked = 0;
foreach $scanner (@scanners) {
my $r1Counter = 0;
#print STDERR "Trying One Commercial: $scanner\n";
$result = TryOneCommercial($scanner,
MailScanner::Config::ScannerCmds($scanner),
$batch, $dir, $BaseDir, $Reports, $Types,
\$r1Counter, $disinfect, $spaminfre);
# If all the scanners failed, we flag it and abandon the batch.
# If even just one of them worked, we carry on.
if ($result ne 'ScAnNeRfAiLeD') {
$OneScannerWorked = 1;
}
unless ($result) {
MailScanner::Log::WarnLog("%s: Failed to complete, timed out", $scanner);
return 0;
}
$counter += $result;
MailScanner::Log::NoticeLog("%s: %s found %d infections", $logtitle,
$Scanners{$scanner}{Name}, $r1Counter)
if $r1Counter;
# Update the grand total of viruses found
$$rCounter += $r1Counter;
}
# If none of the scanners worked, then reject this batch.
if (!$OneScannerWorked) {
return 'ScAnNeRfAiLeD';
}
return $counter;
}
# Try one of the commercial virus scanners
sub TryOneCommercial {
my($scanner, $sweepcommandAndPath, $batch, $subdir, $BaseDir,
$Reports, $Types, $rCounter, $disinfect, $spaminfre) = @_;
my($sweepcommand, $instdir, $ReportScanner);
my($rScanner, $VirusLock, $voptions, $Name);
my($Counter, $TimedOut, $PipeReturn, $pid);
my($ScannerFailed);
MailScanner::Log::DieLog("Virus scanner \"%s\" not found " .
"in virus.scanners.conf file. Please check your " .
"spelling in \"Virus Scanners =\" line of " .
"MailScanner.conf", $scanner)
if $sweepcommandAndPath eq "";
# Split the sweepcommandAndPath into its 2 elements
$sweepcommandAndPath =~ /^([^,\s]+)[,\s]+([^,\s]+)$/
or MailScanner::Log::DieLog("Your virus.scanners.conf file does not " .
" have 3 words on each line. See if you " .
" have an old one left over by mistake.");
($sweepcommand, $instdir) = ($1, $2);
MailScanner::Log::DieLog("Never heard of scanner '$scanner'!")
unless $sweepcommand;
$rScanner = $Scanners{$scanner};
# November 2008: Always log the scanner name, strip it from the reports
# if the user doesn't want it.
# If they want the scanner name, then set it to non-blank
$Name = $rScanner->{"Name"}; # if MailScanner::Config::Value('showscanner');
$ReportScanner = MailScanner::Config::Value('showscanner');
if ($rScanner->{"SupportScanning"} == $S_NONE){
MailScanner::Log::DebugLog("Scanning using scanner \"$scanner\" " .
"not supported; not scanning");
return 1;
}
if ($disinfect && $rScanner->{"SupportDisinfect"} == $S_NONE){
MailScanner::Log::DebugLog("Disinfection using scanner \"$scanner\" " .
"not supported; not disinfecting");
return 1;
}
CheckCodeStatus($rScanner->{$disinfect?"SupportDisinfect":"SupportScanning"})
or MailScanner::Log::DieLog("Bad return code from CheckCodeStatus - " .
"should it have quit?");
$VirusLock = MailScanner::Config::Value('lockfiledir') . "/" .
$rScanner->{"Lock"}; # lock file
$voptions = $rScanner->{"CommonOptions"}; # Set common command line options
# Add the configured value for scanner time outs to the command line
# if the scanner is Panda
$voptions .= " -t:".MailScanner::Config::Value('virusscannertimeout')
if $rScanner->{"Name"} eq 'Panda';
# Add command line options to "scan only", or to disinfect
$voptions .= " " . $rScanner->{$disinfect?"DisinfectOptions":"ScanOptions"};
&{$$rScanner{"InitParser"}}($BaseDir, $batch); # Initialise scanner-specific parser
my $Lock = new FileHandle;
my $Kid = new FileHandle;
my $pipe;
# Check that the virus checker files aren't currently being updated,
# and wait if they are.
if (open($Lock, ">$VirusLock")) {
print $Lock "Virus check locked for " .
($disinfect?"disinfect":"scann") . "ing with $scanner $$\n";
} else {
#The lock file already exists, so just open for reading
open($Lock, "<$VirusLock")
or MailScanner::Log::WarnLog("Cannot lock $VirusLock, $!");
}
flock($Lock, $LOCK_SH);
MailScanner::Log::DebugLog("Commencing " .
($disinfect?"disinfect":"scann") . "ing with $scanner...");
$disinfect = 0 unless $disinfect; # Make sure it's not undef
$TimedOut = 0;
eval {
$pipe = $disinfect?'|-':'-|';
die "Can't fork: $!" unless defined($pid = open($Kid, $pipe));
if ($pid) {
# In the parent
local $SIG{ALRM} = sub { $TimedOut = 1; die "Command Timed Out" };
alarm MailScanner::Config::Value('virusscannertimeout');
$ScannerPID = $pid;
# Only process the output if we are scanning, not disinfecting
if ($disinfect) {
# Tell sweep to disinfect all files
print $Kid "A\n" if $scanner eq 'sophos';
#print STDERR "Disinfecting...\n";
} else {
my($ScannerOutput, $line);
while(defined ($line = <$Kid>)) {
# Note: this is a change in the spec for all the parsers
if ($line =~ /^ScAnNeRfAiLeD/) {
# The virus scanner failed for some reason, remove this batch
$ScannerFailed = 1;
last;
}
$ScannerOutput = &{$$rScanner{"ProcessOutput"}}($line, $Reports,
$Types, $BaseDir, $Name,
$spaminfre);
#print STDERR "Processing line \"$_\" produced $Counter\n";
if ($ScannerOutput eq 'ScAnNeRfAiLeD') {
$ScannerFailed = 1;
last;
}
$Counter += $ScannerOutput if $ScannerOutput > 0;
#print STDERR "Counter = \"$Counter\"\n";
# 20090730 Add support for spam-viruses, ie. spam reported as virus
#print STDERR "ScannerOutput = \"$ScannerOutput\"\n";
if ($ScannerOutput =~ s/^0\s+//) {
# It's a spam-virus and the infection name for the spam report
# is in $ScannerOutput
$ScannerOutput =~ /^(\S+)\s+(\S+)\s*$/;
my ($messageid, $report) = ($1, $2);
#print STDERR "Found spam-virus: $messageid, $report\n";
MailScanner::Log::WarnLog("Found spam based virus %s in %s",
$report, $messageid);
$batch->{messages}{"$messageid"}->{spamvirusreport} .= ', '
if $batch->{"$messageid"}->{spamvirusreport};
$batch->{messages}{"$messageid"}->{spamvirusreport} .= $report;
#print STDERR "id=" . $batch->{messages}{"$messageid"}->{id} . "\n";
}
}
# If they don't want the scanner name reported, strip the scanner name
$line =~ s/^$Name: // unless $ReportScanner;
}
close $Kid;
$PipeReturn = $?;
$pid = 0; # 2.54
alarm 0;
# Workaround for bug in perl shipped with Solaris 9,
# it doesn't unblock the SIGALRM after handling it.
eval {
my $unblockset = POSIX::SigSet->new(SIGALRM);
sigprocmask(SIG_UNBLOCK, $unblockset)
or die "Could not unblock alarm: $!\n";
};
} else {
# In the child
POSIX::setsid();
if ($scanner eq 'sophossavi') {
SophosSAVI($subdir, $disinfect);
exit;
# } elsif ($scanner eq 'clamavmodule') {
# ClamAVModule($subdir, $disinfect, $batch);
# exit;
} elsif ($scanner eq 'clamd') {
ClamdScan($subdir, $disinfect, $batch);
exit;
} elsif ( $scanner eq 'avastd' ) {
AvastdScan( $subdir, $disinfect, $batch );
exit;
} elsif ( $scanner eq 'kse' ) {
KseScan( $subdir, $disinfect, $batch );
exit;
} elsif ( $scanner eq 'f-protd-6' ) {
Fprotd6Scan( $subdir, $disinfect, $batch );
exit;
} elsif ( $scanner eq 'f-secured' ) {
FsecureScan( $subdir, $disinfect, $batch );
exit;
} elsif ( $scanner eq 'savid' ) {
SAVIDScan( $subdir, $disinfect, $batch );
exit;
} elsif ( $scanner eq 'esetsefs' ) {
# Pass entire $BaseDir instead of $subdir so that lslog
# can identify full path of threats in wrapper