-
Notifications
You must be signed in to change notification settings - Fork 9
/
MIMEDefang.pm
1255 lines (1040 loc) · 34.2 KB
/
MIMEDefang.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
#
# This program may be distributed under the terms of the GNU General
# Public License, Version 2.
#
=head1 NAME
Mail::MIMEDefang - email filtering milter
=head1 DESCRIPTION
Mail::MIMEDefang is a framework for filtering e-mail.
It uses Sendmail's "Milter" API, some C glue code, and some Perl code to let you write high-performance mail filters in Perl.
People use MIMEDefang to:
Block viruses
Block or tag spam
Remove HTML mail parts
Add boilerplate disclaimers to outgoing mail
Remove or alter attachments
Replace attachments with URL's
Implement sophisticated access controls.
You're limited only by your imagination. If you can think of it and code it in Perl, you can do it with MIMEDefang.
=head1 METHODS
=over 4
=cut
package Mail::MIMEDefang;
use warnings;
no warnings qw(once uninitialized);
require Exporter;
use Carp;
use Errno qw(ENOENT EACCES);
use File::Spec;
use MIME::Entity;
use MIME::WordDecoder;
our @ISA = qw(Exporter);
our @EXPORT;
our @EXPORT_OK;
our $VERSION = '3.4.1';
@EXPORT = qw{
$AddWarningsInline @StatusTags
$Action $Administrator $AdminName $AdminAddress $DoStatusTags
$Changed $CSSHost $DaemonAddress $DaemonName
$DefangCounter $Domain $EntireMessageQuarantined
$MessageID $Rebuild $QuarantineCount
$QuarantineSubdir $QueueID $MsgID $MIMEDefangID
$RelayAddr $WasResent $RelayHostname
$RealRelayAddr $RealRelayHostname
$ReplacementEntity $Sender $ServerMode $Subject $SubjectCount
$ClamdSock $SophieSock $TrophieSock
$Helo @ESMTPArgs
@SenderESMTPArgs %RecipientESMTPArgs
$TerminateAndDiscard $URL $VirusName
$CurrentVirusScannerMessage @AddedParts
$VirusScannerMessages $WarningLocation $WasMultiPart
$CWD $FprotdHost $Fprotd6Host
$NotifySenderSubject $NotifyAdministratorSubject
$ValidateIPHeader
$QuarantineSubject $SALocalTestsOnly $NotifyNoPreamble
%Actions %Stupidity @FlatParts @Recipients @Warnings %Features
$SyslogFacility $GraphDefangSyslogFacility
$MaxMIMEParts $InMessageContext $InFilterContext $PrivateMyHostName
$EnumerateRecipients $InFilterEnd $FilterEndReplacementEntity
$AddApparentlyToForSpamAssassin $WarningCounter
@VirusScannerMessageRoutines @VirusScannerEntityRoutines
$VirusScannerRoutinesInitialized
%SendmailMacros %RecipientMailers $CachedTimezone $InFilterWrapUp
$SuspiciousCharsInHeaders
$SuspiciousCharsInBody
$GeneralWarning
$HTMLFoundEndBody $HTMLBoilerplate $SASpamTester
$results_fh
init_globals print_and_flush detect_and_load_perl_modules
init_status_tag push_status_tag pop_status_tag
signal_changed signal_unchanged md_syslog md_graphdefang_log
write_result_line in_message_context in_filter_context in_filter_wrapup
in_filter_end percent_decode percent_encode percent_encode_for_graphdefang
send_mail send_multipart_mail send_quarantine_notifications signal_complete send_admin_mail
md_version set_status_tag
};
@EXPORT_OK = qw{
detect_antivirus_support
};
#***********************************************************************
# %PROCEDURE: md_version
# %ARGUMENTS:
# None
# %RETURNS:
# MIMEDefang version
#***********************************************************************
sub md_version {
return $VERSION;
}
=item init_globals
Initialize global variables used across MIMEDefang instance
and filter.
=cut
sub init_globals {
my ($self, @params) = @_;
$CWD = $Features{'Path:SPOOLDIR'};
$InMessageContext = 0;
$InFilterEnd = 0;
$InFilterContext = 0;
$InFilterWrapUp = 0;
undef $FilterEndReplacementEntity;
$Action = "";
$Changed = 0;
$DefangCounter = 0;
$Domain = "";
$MIMEDefangID = "";
$MsgID = "NOQUEUE";
$MessageID = "NOQUEUE";
$Helo = "";
$QueueID = "NOQUEUE";
$QuarantineCount = 0;
$Rebuild = 0;
$EntireMessageQuarantined = 0;
$QuarantineSubdir = "";
$RelayAddr = "";
$RealRelayAddr = "";
$WasResent = 0;
$RelayHostname = "";
$RealRelayHostname = "";
$Sender = "";
$Subject = "";
$SubjectCount = 0;
$SuspiciousCharsInHeaders = 0;
$SuspiciousCharsInBody = 0;
$TerminateAndDiscard = 0;
$VirusScannerMessages = "";
$VirusName = "";
$WasMultiPart = 0;
$WarningCounter = 0;
undef %Actions;
undef %SendmailMacros;
undef %RecipientMailers;
undef %RecipientESMTPArgs;
undef @FlatParts;
undef @Recipients;
undef @Warnings;
undef @AddedParts;
undef @StatusTags;
undef @ESMTPArgs;
undef @SenderESMTPArgs;
undef $results_fh;
}
=item print_and_flush(text)
Prints to stdout and flush buffer.
=cut
sub print_and_flush
{
local $| = 1;
print($_[0], "\n");
}
=item md_openlog(tag, facility)
Initialize e syslog object using Sys::Syslog or Unix::Syslog as
appropriate.
=item md_syslog(facility, msg)
Prints a message to syslog(3) using the specified facility
=cut
{
# Reworked detection/usage of Sys::Syslog or Unix::Syslog as
# appropriate is mostly borrowed from Log::Syslog::Abstract, to which
# I'd love to convert at some point.
my $_syslogsub = undef;
my $_openlogsub = undef;
my $_fac_map = undef;
#***********************************************************************
# %PROCEDURE: md_openlog
# %ARGUMENTS:
# tag -- syslog tag ("mimedefang.pl")
# facility -- Syslog facility as a string
# %RETURNS:
# Nothing
# %DESCRIPTION:
# Opens a log using either Unix::Syslog or Sys::Syslog
#***********************************************************************
sub md_openlog
{
my ($tag, $facility) = @_;
if( ! defined $_openlogsub ) {
# Try Unix::Syslog first, then Sys::Syslog
eval qq{use Unix::Syslog qw( :macros ); };
if(!$@) {
($_openlogsub, $_syslogsub) = _wrap_for_unix_syslog();
} else {
eval qq{use Sys::Syslog ();};
if(!$@) {
($_openlogsub, $_syslogsub) = _wrap_for_sys_syslog();
} else {
croak q{Unable to detect either Unix::Syslog or Sys::Syslog};
}
}
}
return $_openlogsub->($tag, 'pid,ndelay', $facility);
}
#***********************************************************************
# %PROCEDURE: md_syslog
# %ARGUMENTS:
# facility -- Syslog facility as a string
# msg -- message to log
# %RETURNS:
# Nothing
# %DESCRIPTION:
# Calls syslog, either in Sys::Syslog or Unix::Syslog package
#***********************************************************************
sub md_syslog
{
my ($facility, $msg) = @_;
if(!$_syslogsub) {
md_openlog('mimedefang.pl', $SyslogFacility);
}
if (defined $MsgID && $MsgID ne 'NOQUEUE') {
return $_syslogsub->($facility, '%s', $MsgID . ': ' . $msg);
} else {
return $_syslogsub->($facility, '%s', $msg);
}
}
sub _wrap_for_unix_syslog
{
my $openlog = sub {
my ($id, $flags, $facility) = @_;
croak q{first argument must be an identifier string} unless defined $id;
croak q{second argument must be flag string} unless defined $flags;
croak q{third argument must be a facility string} unless defined $facility;
return Unix::Syslog::openlog( $id, _convert_flags( $flags ), _convert_facility( $facility ) );
};
my $syslog = sub {
my $facility = shift;
return Unix::Syslog::syslog( _convert_facility( $facility ), @_);
};
return ($openlog, $syslog);
}
sub _wrap_for_sys_syslog
{
my $openlog = sub {
# Debian Stretch version is 0.33_01...dammit!
my $ver = $Sys::Syslog::VERSION;
$ver =~ s/_.*//;
if( $ver < 0.16 ) {
# Older Sys::Syslog versions still need
# setlogsock(). RHEL5 still ships with 0.13 :(
Sys::Syslog::setlogsock([ 'unix', 'tcp', 'udp' ]);
}
return Sys::Syslog::openlog(@_);
};
my $syslog = sub {
return Sys::Syslog::syslog(@_);
};
return ($openlog, $syslog);
}
sub _convert_flags
{
my($flags) = @_;
my $flag_map = {
pid => Unix::Syslog::LOG_PID(),
ndelay => Unix::Syslog::LOG_NDELAY(),
};
my $num = 0;
foreach my $thing (split(/,/, $flags)) {
next unless exists $flag_map->{$thing};
$num |= $flag_map->{$thing};
}
return $num;
}
sub _convert_facility
{
my($facility) = @_;
my $num = 0;
foreach my $thing (split(/\|/, $facility)) {
if (!defined($_fac_map) ||
!exists($_fac_map->{$thing})) {
$_fac_map->{$thing} = _fac_to_num($thing);
}
next unless defined $_fac_map->{$thing};
$num |= $_fac_map->{$thing};
}
return $num;
}
my %special = (
error => 'err',
panic => 'emerg',
);
# Some of the Unix::Syslog 'macros' tag exports aren't
# constants, so we need to ignore them if found.
my %blacklisted = map { $_ => 1 } qw(mask upto pri makepri fac);
sub _fac_to_num
{
my ($thing) = @_;
return if exists $blacklisted{$thing};
$thing = $special{$thing} if exists $special{$thing};
$thing = 'LOG_' . uc($thing);
return unless grep { $_ eq $thing } @ {$Unix::Syslog::EXPORT_TAGS{macros} };
return eval "Unix::Syslog::$thing()";
}
}
=item md_graphdefang_log
This is called to log events that occur during mimedefang processing.
It should be called from mimedefang-filter with appropriate
event names and values.
Possible examples:
C<md_graphdefang_log('virus',$VirusName,$filename);>
C<md_graphdefang_log('spam',$hits);>
C<md_graphdefang_log('bad_filename',$filename,$extension);>
If you need to log UTF-8 strings you can call the sub as:
C<md_graphdefang_log('spam',$hits, undef, 1);>
=cut
#***********************************************************************
# %PROCEDURE: md_graphdefang_log
# %ARGUMENTS:
# event -- The name of the event that is being logged. Examples
# include virus, spam, mail, etc.
# value1 -- (optional) A value associated with the event being logged.
# value2 -- (optional) A value associated with the event being logged.
# utf8_decode -- (optional) A boolean value that indicates if we want to
# decode UTF-8 encoded strings
# %RETURNS:
# Nothing
# %DESCRIPTION:
# This is called to log events that occur during mimedefang processing.
# It should be called from mimedefang-filter with appropriate
# event names and values. Possible examples:
# md_graphdefang_log('virus',$VirusName,$filename);
# md_graphdefang_log('spam',$hits);
# md_graphdefang_log('spam',$hits, undef, 1);
# md_graphdefang_log('bad_filename',$filename,$extension);
#***********************************************************************
sub md_graphdefang_log
{
return unless defined($GraphDefangSyslogFacility);
return if (!in_message_context("md_graphdefang_log"));
my $event = shift;
my $value1 = shift;
my $value2 = shift;
my $utf8_decode = shift;
$value1 = "" unless defined($value1);
$value2 = "" unless defined($value2);
$utf8_decode = 0 unless defined($utf8_decode);
my $lcsender = percent_encode_for_graphdefang(lc($Sender));
# Make values safe for graphdefang
my $id = percent_encode_for_graphdefang($MsgID);
my $subj;
if($utf8_decode eq 1) {
eval {
no warnings 'utf8';
$subj = mime_to_perl_string($Subject);
$event = mime_to_perl_string($event);
$value1 = mime_to_perl_string($value1);
$value2 = mime_to_perl_string($value2);
$subj =~ s/\P{Print}//g;
$event =~ s/\P{Print}//g;
$value1 =~ s/\P{Print}//g;
$value2 =~ s/\P{Print}//g;
if (utf8::is_utf8($subj)) {
utf8::encode($subj);
}
if (utf8::is_utf8($event)) {
utf8::encode($event);
}
if (utf8::is_utf8($value1)) {
utf8::encode($value1);
}
if (utf8::is_utf8($value2)) {
utf8::encode($value2);
}
};
} else {
$subj = percent_encode_for_graphdefang($Subject);
$event = percent_encode_for_graphdefang($event);
$value1 = percent_encode_for_graphdefang($value1);
$value2 = percent_encode_for_graphdefang($value2);
}
if ($EnumerateRecipients || scalar(@Recipients) == 1) {
foreach my $recipient (@Recipients) {
my $lcrecipient = percent_encode_for_graphdefang(lc($recipient));
md_syslog("$GraphDefangSyslogFacility|info","MDLOG,$id," .
"$event,$value1,$value2,$lcsender," .
"$lcrecipient,$subj");
}
} else {
my $lcrecipient = "rcpts=" . scalar(@Recipients);
$lcrecipient = percent_encode_for_graphdefang($lcrecipient);
md_syslog("$GraphDefangSyslogFacility|info","MDLOG,$id," .
"$event,$value1,$value2,$lcsender," .
"$lcrecipient,$subj");
}
}
=item detect_and_load_perl_modules
Automatically detect and load Perl modules needed for some features
like SpamAssassin, rbl checks, zip file listing and HTML parsing.
=cut
# Detect these Perl modules at run-time. Can explicitly prevent
# loading of these modules by setting $Features{"xxx"} = 0;
#
# You can turn off ALL auto-detection by setting
# $Features{"AutoDetectPerlModules"} = 0;
sub detect_and_load_perl_modules() {
my ($use_sa, $use_html, $use_zip, $use_dns);
if (!defined($Features{"AutoDetectPerlModules"}) or
$Features{"AutoDetectPerlModules"}) {
if (!defined($Features{"SpamAssassin"}) or ($Features{"SpamAssassin"} eq 1)) {
(eval 'use Mail::SpamAssassin (); $use_sa = 1;')
or $use_sa = 0;
}
$Features{"SpamAssassin"} = $use_sa;
if (!defined($Features{"HTML::Parser"}) or ($Features{"HTML::Parser"} eq 1)) {
(eval 'use HTML::Parser; $use_html = 1;')
or $use_html = 0;
}
$Features{"HTML::Parser"} = $use_html;
if (!defined($Features{"Archive::Zip"}) or ($Features{"Archive::Zip"} eq 1)) {
(eval 'use Archive::Zip; $use_zip = 1;')
or $use_zip = 0;
}
$Features{"Archive::Zip"} = $use_zip;
if (!defined($Features{"Net::DNS"}) or ($Features{"Net::DNS"} eq 1)) {
(eval 'use Net::DNS; $use_dns = 1;')
or $use_dns = 0;
}
$Features{"Net::DNS"} = $use_dns;
if(exists &Mail::MIMEDefang::Actions::md_init) {
Mail::MIMEDefang::Actions::md_init();
}
if(exists &Mail::MIMEDefang::Antispam::md_init) {
Mail::MIMEDefang::Antispam::md_init();
}
if(exists &Mail::MIMEDefang::Antivirus::md_init) {
Mail::MIMEDefang::Antivirus::md_init();
}
if(exists &Mail::MIMEDefang::Mail::md_init) {
Mail::MIMEDefang::Mail::md_init();
}
if(exists &Mail::MIMEDefang::MIME::md_init) {
Mail::MIMEDefang::MIME::md_init();
}
if(exists &Mail::MIMEDefang::Net::md_init) {
Mail::MIMEDefang::Net::md_init();
}
if(exists &Mail::MIMEDefang::RFC2822::md_init) {
Mail::MIMEDefang::RFC2822::md_init();
}
if(exists &Mail::MIMEDefang::Utils::md_init) {
Mail::MIMEDefang::Utils::md_init();
}
}
}
=item detect_antivirus_support
Check if antivirus support should be loaded by looking at %Features
=cut
# Detect if antivirus support should be enabled
sub detect_antivirus_support() {
return 1 if (!defined $Features{"AutoDetectPerlModules"});
foreach my $k ( keys %Features ) {
if($k =~ /^Virus\:/) {
if($Features{$k} ne 0) {
return 1;
}
}
}
return 0;
}
=item init_status_tag
Open the status file descriptor
=cut
# Try to open the status descriptor
sub init_status_tag
{
return unless $DoStatusTags;
if(open(STATUS_HANDLE, ">&=3")) {
STATUS_HANDLE->autoflush(1);
} else {
$DoStatusTags = 0;
}
}
=item set_status_tag(depth, tag)
Sets the status tag for this worker inside the multiplexor.
=cut
#***********************************************************************
# %PROCEDURE: set_status_tag
# %ARGUMENTS:
# nest_depth -- nesting depth
# tag -- status tag
# %DESCRIPTION:
# Sets the status tag for this worker inside the multiplexor.
# %RETURNS:
# Nothing
#***********************************************************************
sub set_status_tag
{
return unless $DoStatusTags;
my ($depth, $tag) = @_;
$tag ||= '';
if($tag eq '') {
print STATUS_HANDLE "\n";
return;
}
$tag =~ s/[^[:graph:]]/ /g;
if(defined($MsgID) and ($MsgID ne "NOQUEUE")) {
print STATUS_HANDLE percent_encode("$depth: $tag $MsgID") . "\n";
} else {
print STATUS_HANDLE percent_encode("$depth: $tag") . "\n";
}
}
=item push_status_tag(tag)
Updates status tag inside multiplexor and pushes onto stack.
=cut
#***********************************************************************
# %PROCEDURE: push_status_tag
# %ARGUMENTS:
# tag -- tag describing current status
# %DESCRIPTION:
# Updates status tag inside multiplexor and pushes onto stack.
# %RETURNS:
# Nothing
#***********************************************************************
sub push_status_tag
{
return unless $DoStatusTags;
my ($tag) = @_;
push(@StatusTags, $tag);
if($tag ne '') {
$tag = "> $tag";
}
set_status_tag(scalar(@StatusTags), $tag);
}
=item pop_status_tag
Pops previous status of stack and sets tag in multiplexor.
=cut
#***********************************************************************
# %PROCEDURE: pop_status_tag
# %ARGUMENTS:
# None
# %DESCRIPTION:
# Pops previous status of stack and sets tag in multiplexor.
# %RETURNS:
# Nothing
#***********************************************************************
sub pop_status_tag
{
return unless $DoStatusTags;
pop @StatusTags;
my $tag = $StatusTags[0] || 'no_tag';
set_status_tag(scalar(@StatusTags), "< $tag");
}
=item percent_encode(str)
Encode a string with unsafe chars as "%XY" where X and Y are hex digits.
=cut
#***********************************************************************
# %PROCEDURE: percent_encode
# %ARGUMENTS:
# str -- a string, possibly with newlines and control characters
# %RETURNS:
# A string with unsafe chars encoded as "%XY" where X and Y are hex
# digits. For example:
# "foo\r\nbar\tbl%t" ==> "foo%0D%0Abar%09bl%25t"
#***********************************************************************
sub percent_encode {
my($str) = @_;
$str =~ s/([^\x21-\x7e]|[%\\'"])/sprintf("%%%02X", unpack("C", $1))/ge;
#" Fix emacs highlighting...
return $str;
}
=item percent_encode_for_graphdefang(str)
Encode a string with unsafe chars as "%XY" where X and Y are hex digits.
Quotes or spaces are not encoded but commas are encoded.
=cut
#***********************************************************************
# %PROCEDURE: percent_encode_for_graphdefang
# %ARGUMENTS:
# str -- a string, possibly with newlines and control characters
# %RETURNS:
# A string with unsafe chars encoded as "%XY" where X and Y are hex
# digits. For example:
# "foo\r\nbar\tbl%t" ==> "foo%0D%0Abar%09bl%25t"
# This differs slightly from percent_encode because we don't encode
# quotes or spaces, but we do encode commas.
#***********************************************************************
sub percent_encode_for_graphdefang {
my($str) = @_;
$str =~ s/([^\x20-\x7e]|[%\\,])/sprintf("%%%02X", unpack("C", $1))/ge;
#" Fix emacs highlighting...
return $str;
}
=item percent_decode(str)
Decode a string previously encoded by percent_encode().
=cut
#***********************************************************************
# %PROCEDURE: percent_decode
# %ARGUMENTS:
# str -- a string encoded by percent_encode
# %RETURNS:
# The decoded string. For example:
# "foo%0D%0Abar%09bl%25t" ==> "foo\r\nbar\tbl%t"
#***********************************************************************
sub percent_decode {
my($str) = @_;
$str =~ s/%([0-9A-Fa-f]{2})/pack("C", hex($1))/ge;
return $str;
}
=item write_result_line ( $cmd, @args )
Writes a result line to the RESULTS file.
$cmd should be a one-letter command for the RESULTS file
@args are the arguments for $cmd, if any. They will be percent_encode()'ed
before being written to the file.
Returns 0 or 1 and an optional warning message.
=cut
sub write_result_line
{
my $cmd = shift;
# Do nothing if we don't yet have a dedicated working directory
if ($CWD eq $Features{'Path:SPOOLDIR'}) {
md_syslog('warning', "write_result_line called before working directory established");
return;
}
my $line = $cmd . join ' ', map { percent_encode($_) } @_;
if (!$results_fh) {
$results_fh = IO::File->new('>>RESULTS');
if (!$results_fh) {
croak("Could not open RESULTS file: $!");
}
}
# We have a 16kb limit on the length of lines in RESULTS, including
# trailing newline and null used in the milter. So, we limit $cmd +
# $args to 16382 bytes.
if( length $line > 16382 ) {
md_syslog( 'warning', "Cannot write line over 16382 bytes long to RESULTS file; truncating. Original line began with: " . substr $line, 0, 40);
$line = substr $line, 0, 16382;
}
print $results_fh "$line\n" or croak "Could not write RESULTS line: $!";
return;
}
=item signal_unchanged
Tells mimedefang C program message has not been altered.
=cut
#***********************************************************************
# %PROCEDURE: signal_unchanged
# %ARGUMENTS:
# None
# %RETURNS:
# Nothing
# %DESCRIPTION:
# Tells mimedefang C program message has not been altered (does nothing...)
#***********************************************************************
sub signal_unchanged {
}
=item signal_changed
Tells mimedefang C program message has been altered.
=cut
#***********************************************************************
# %PROCEDURE: signal_changed
# %ARGUMENTS:
# None
# %RETURNS:
# Nothing
# %DESCRIPTION:
# Tells mimedefang C program message has been altered.
#***********************************************************************
sub signal_changed {
write_result_line("C", "");
}
=item in_message_context(name)
Returns 1 if we are processing a message; 0 otherwise.
=cut
#***********************************************************************
# %PROCEDURE: in_message_context
# %ARGUMENTS:
# name -- a string to syslog if we are not in a message context
# %RETURNS:
# 1 if we are processing a message; 0 otherwise. Returns 0 if
# we're in filter_relay, filter_sender or filter_recipient
#***********************************************************************
sub in_message_context {
my($name) = @_;
return 1 if ($InMessageContext);
md_syslog('warning', "$name called outside of message context");
return 0;
}
=item in_filter_wrapup(name)
Returns 1 if we are not in filter wrapup; 0 otherwise.
=cut
#***********************************************************************
# %PROCEDURE: in_filter_wrapup
# %ARGUMENTS:
# name -- a string to syslog if we are in filter wrapup
# %RETURNS:
# 1 if we are not in filter wrapup; 0 otherwise.
#***********************************************************************
sub in_filter_wrapup {
my($name) = @_;
if ($InFilterWrapUp) {
md_syslog('warning', "$name called inside filter_wrapup context");
return 1;
}
return 0;
}
=item in_filter_context
Returns 1 if we are inside filter or filter_multipart, 0 otherwise.
=cut
#***********************************************************************
# %PROCEDURE: in_filter_context
# %ARGUMENTS:
# name -- a string to syslog if we are not in a filter context
# %RETURNS:
# 1 if we are inside filter or filter_multipart, 0 otherwise.
#***********************************************************************
sub in_filter_context {
my($name) = @_;
return 1 if ($InFilterContext);
md_syslog('warning', "$name called outside of filter context");
return 0;
}
=item in_filter_end(name)
Returns 1 if we are inside filter_end 0 otherwise.
=cut
#***********************************************************************
# %PROCEDURE: in_filter_end
# %ARGUMENTS:
# name -- a string to syslog if we are not in filter_end
# %RETURNS:
# 1 if we are inside filter_end 0 otherwise.
#***********************************************************************
sub in_filter_end {
my($name) = @_;
return 1 if ($InFilterEnd);
md_syslog('warning', "$name called outside of filter_end");
return 0;
}
=item send_quarantine_notifications
Sends quarantine notification message, if anything was quarantined.
=cut
#***********************************************************************
# %PROCEDURE: send_quarantine_notifications
# %ARGUMENTS:
# None
# %RETURNS:
# Nothing
# %DESCRIPTION:
# Sends quarantine notification message, if anything was quarantined
#***********************************************************************
sub send_quarantine_notifications {
# If there are quarantined parts, e-mail a report
if ($QuarantineCount > 0 || $EntireMessageQuarantined) {
my($body);
my $hostname = Mail::MIMEDefang::Net::get_host_name();
if ($QuarantineCount >= 1) {
$body .= "An e-mail had $QuarantineCount part";
$body .= "s" if ($QuarantineCount != 1);
} else {
$body .= "An e-mail message was";
}
$body .= " quarantined in the directory\n";
$body .= "$QuarantineSubdir on " . Mail::MIMEDefang::Net::get_host_name() . ".\n\n";
$body .= "The sender was '$Sender'.\n\n" if defined($Sender);
$body .= "The Sendmail queue identifier was $QueueID.\n\n" if ($QueueID ne "NOQUEUE");
$body .= "The relay machine was $RelayHostname ($RelayAddr).\n\n";
if ($EntireMessageQuarantined) {
$body .= "The entire message was quarantined in $QuarantineSubdir/ENTIRE_MESSAGE\n\n";
}
foreach my $recip (@Recipients) {
$body .= "Recipient: $recip\n";
}
my $donemsg = 0;
my $i;
for ($i=0; $i<=$QuarantineCount; $i++) {
if (open(IN, "<", "$QuarantineSubdir/MSG.$i")) {
if (!$donemsg) {
$body .= "Quarantine Messages:\n";
$donemsg = 1;
}
while(<IN>) {
$body .= $_;
}
close(IN);
}
}
if ($donemsg) {
$body .= "\n";
}
if (open(IN, "<", "$QuarantineSubdir/HEADERS")) {
$body .= "\n----------\nHere are the message headers:\n";
while(<IN>) {
$body .= $_;
}
close(IN);
}
for ($i=1; $i<=$QuarantineCount; $i++) {
if (open(IN, "<", "$QuarantineSubdir/PART.$i.HEADERS")) {
$body .= "\n----------\nHere are the headers for quarantined part $i:\n";
while(<IN>) {
$body .= $_;
}
close(IN);
}
}
if ($#Warnings >= 0) {
$body .= "\n----------\nHere are the warning details:\n\n";
$body .= "@Warnings";
}
my $mime = MIME::Entity->build(
From => "\"$DaemonName\" <$DaemonAddress>",
To => "\"$AdminName\" <$AdminAddress>",
Subject => $QuarantineSubject,
Encoding => 'quoted-printable',
Data => [$body],
Type => "text/plain");
$mime->head->add('Auto-Submitted', 'auto-generated');
$mime->head->add('Precedence', 'bulk');
send_mail($DaemonAddress, $DaemonName, $AdminAddress, $mime->stringify);
}
}
=item signal_complete
Tells mimedefang C program Perl filter has finished successfully.
Also mails any quarantine notifications and sender notifications.
=cut
#***********************************************************************
# %PROCEDURE: signal_complete
# %ARGUMENTS:
# None
# %RETURNS:
# Nothing
# %DESCRIPTION:
# Tells mimedefang C program Perl filter has finished successfully.
# Also mails any quarantine notifications and sender notifications.
#***********************************************************************
sub signal_complete {
# Send notification to sender, if required
if ($Sender ne '<>' && -r "NOTIFICATION") {
my $body = "";
unless($NotifyNoPreamble) {
$body .= "An e-mail you sent with message-id $MessageID\n";
$body .= "was modified by our mail scanning software.\n\n";
$body .= "The recipients were:";
foreach my $recip (@Recipients) {
$body .= " $recip";
}
$body .= "\n\n";
}