[Mimedefang] Wide character in print at /usr/bin/mimedefang.pl
vieri at openmailbox.org
vieri at openmailbox.org
Thu Mar 12 04:38:21 EDT 2015
On 2015-03-12 08:38, Steffen Kaiser wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> On Wed, 11 Mar 2015, vieri at openmailbox.org wrote:
>> On 2015-03-10 20:20, vieri at openmailbox.org wrote:
>>> Hi,
>>>
>>> I noticed that a decade ago some users detected "Wide character in
>>> print" messages in their mimedefang logs.
>>> It was supposedly fixed by adding
>
>>> export LC_ALL=C
>
>>> in the mimedefang init script.
>>>
>>> (perl unicode issue)
>>>
>>> However, my Linux distro (Gentoo) runs the following in the
>>> mimedefang
>>> init script:
>>>
>>> LC_ALL=C
>>> export LC_ALL
>>>
>>> but I'm occasionally getting the "Wide character in print" messages.
>>>
>>> I'm running v 2.75 and Perl 5.18.2.
>>>
>>> Any ideas?
>>
>> Hi again,
>>
>> Just wanted to add that I modified /usr/bin/mimedefang.pl for
>> debugging purposes:
>>
>> /usr/bin/mimedefang.pl:
>>
>> sub action_notify_sender ($) {
>> [...]
>> if (open(FILE, ">>NOTIFICATION")) {
>> <------>md_syslog('err', "action_notify_sender print FILE $msg");
>> [...]
>>
>> If I check the logs, this is what I get (basically I have a custom
>> filter which calls action_notify_sender with the name of each attached
>> file):
>>
>> action_notify_sender print FILE ComposicioÌ..pdf
>>
>> So mimedefang and perl are choking on non-ASCII characters with "Wide
>> character in print" messages.
>>
>> Unfortunately the consequence of all this is that some e-mail messages
>> aren't processed and are kept in the queue and not sent:
>>
>> Mar 11 18:19:38 mail1 mimedefang-multiplexor[31444]: A0C4A326EB1:
>> Slave 1 stderr: open body: Invalid argument at
>> /usr/lib/perl5/vendor_perl/5.18.2/MIME/Entity.pm line 1878.
>
> Could you post your filter?
If you don't mind, I'm sending the whole mimedefang-filter file as a
text attachment.
Thanks,
Vieri
-------------- next part --------------
# -*- Perl -*-
#***********************************************************************
#
# mimedefang-filter
#
# Suggested minimum-protection filter for Microsoft Windows clients, plus
# SpamAssassin checks if SpamAssassin is installed.
#
# Copyright (C) 2002 Roaring Penguin Software Inc.
#
# This program may be distributed under the terms of the GNU General
# Public License, Version 2, or (at your option) any later version.
#
# $Id$
#***********************************************************************
# use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
#***********************************************************************
# Set administrator's e-mail address here. The administrator receives
# quarantine messages and is listed as the contact for site-wide
# MIMEDefang policy. A good example would be 'defang-admin at mydomain.com'
#***********************************************************************
$AdminAddress = 'postmaster at mydomain.org';
$AdminName = "IT";
#***********************************************************************
# Set the e-mail address from which MIMEDefang quarantine warnings and
# user notifications appear to come. A good example would be
# 'mimedefang at mydomain.com'. Make sure to have an alias for this
# address if you want replies to it to work.
#***********************************************************************
$DaemonAddress = 'mail at mydomain.org';
$DaemonName = "MDIT";
#***********************************************************************
# If you set $AddWarningsInline to 1, then MIMEDefang tries *very* hard
# to add warnings directly in the message body (text or html) rather
# than adding a separate "WARNING.TXT" MIME part. If the message
# has no text or html part, then a separate MIME part is still used.
#***********************************************************************
$AddWarningsInline = 1;
#***********************************************************************
# To enable syslogging of virus and spam activity, add the following
# to the filter:
# md_graphdefang_log_enable();
# You may optionally provide a syslogging facility by passing an
# argument such as: md_graphdefang_log_enable('local4'); If you do this, be
# sure to setup the new syslog facility (probably in /etc/syslog.conf).
# An optional second argument causes a line of output to be produced
# for each recipient (if it is 1), or only a single summary line
# for all recipients (if it is 0.) The default is 1.
# Comment this line out to disable logging.
#***********************************************************************
md_graphdefang_log_enable('mail', 1);
#***********************************************************************
# Uncomment this to block messages with more than 50 parts. This will
# *NOT* work unless you're using Roaring Penguin's patched version
# of MIME tools, version MIME-tools-5.411a-RP-Patched-02 or later.
#
# WARNING: DO NOT SET THIS VARIABLE unless you're using at least
# MIME-tools-5.411a-RP-Patched-02; otherwise, your filter will fail.
#***********************************************************************
# $MaxMIMEParts = 50;
$GeneralWarning = "NOTE: This e-mail has been modified automatically. Please follow the instructions below.\n\n";
#***********************************************************************
# Set various stupid things your mail client does below.
#***********************************************************************
# Set the next one if your mail client cannot handle multiple "inline"
# parts.
$Stupidity{"NoMultipleInlines"} = 1;
# Detect and load Perl modules
detect_and_load_perl_modules();
# This procedure returns true for entities with bad filenames.
sub filter_bad_filename {
my($entity) = @_;
my($bad_exts, $re);
# Bad extensions
$bad_exts = '(ade|adp|app|asd|asf|asx|bas|bat|chm|cmd|com|cpl|crt|dll|exe|fxp|hlp|hta|hto|inf|ini|ins|isp|jse?|lib|lnk|mdb|mde|msc|msi|msp|mst|ocx|pcd|pif|prg|reg|scr|sct|sh|shb|shs|sys|url|vb|vbe|vbs|vcs|vxd|wmd|wms|wmz|wsc|wsf|wsh|\{[^\}]+\})';
# Do not allow:
# - CLSIDs {foobarbaz}
# - bad extensions (possibly with trailing dots) at end
$re = '\.' . $bad_exts . '\.*$';
return 1 if (re_match($entity, $re));
# Look inside ZIP files
if (re_match($entity, '\.zip$') and
$Features{"Archive::Zip"}) {
my $bh = $entity->bodyhandle();
if (defined($bh)) {
my $path = $bh->path();
if (defined($path)) {
return re_match_in_zip_directory($path, $re);
}
}
}
return 0;
}
#***********************************************************************
# %PROCEDURE: custom_action_replace_with_warning
# %ARGUMENTS:
# msg -- warning message
# mtype -- mime type
# mext -- extension
# mname -- file name
# %RETURNS:
# Nothing
# %DESCRIPTION:
# Makes a note to drop the current part and replace it with a warning
#***********************************************************************
sub custom_action_replace_with_warning ($;$$$) {
my($msg, $mtype, $mext, $mname) = @_;
return 0 if (!in_filter_context("custom_action_replace_with_warning"));
$Actions{'replace_with_warning'}++;
$Action = "replace";
$mtype = "text/plain" unless defined($mtype);
$mext = "txt" unless defined($mext);
$mname = "warning" unless defined($mname);
$ReplacementEntity = MIME::Entity->build(Type => $mtype,
Encoding => "-suggest",
Data => [ "$msg\n" ]);
$WarningCounter++;
$ReplacementEntity->head->mime_attr("Content-Type.name" => "$mname$WarningCounter.$mext");
$ReplacementEntity->head->mime_attr("Content-Disposition" => "inline");
$ReplacementEntity->head->mime_attr("Content-Disposition.filename" => "$mname$WarningCounter.$mext");
return 1;
}
#***********************************************************************
# %PROCEDURE: custom_action_replace_with_file
# %ARGUMENTS:
# entity -- mime entity
# nfname -- new file path
# nfdesc -- description
# nftype -- mime type
# nfencode -- encoding
# %RETURNS:
# Nothing
# %DESCRIPTION:
# Makes a note to drop the current part and replace it with a file
#***********************************************************************
sub custom_action_replace_with_file ($$;$$$$$) {
my($entity, $nfpath, $nfname, $nftype, $nfencode, $nfdispo) = @_;
return 0 if (!in_filter_context("custom_action_replace_with_file"));
$Actions{'replace_with_file'}++;
$Action = "replace";
$nftype = "application/octet-stream" unless defined($nftype);
$nfname = "" unless defined($nfname);
$nfencode = "base64" unless defined($nfencode);
$nfdispo = "attachment" unless defined($nfdispo);
$ReplacementEntity = MIME::Entity->build(Type => $nftype,
Encoding => $nfencode,
Path => $nfpath,
Filename => $nfname,
Disposition => $nfdispo);
copy_or_link($nfpath, $entity->bodyhandle->path) or return 0;
return 1;
}
#***********************************************************************
# %PROCEDURE: custom_action_replace_with_url
# %ARGUMENTS:
# entity -- part to replace
# doc_root -- document root in which to place file
# base_url -- base URL for retrieving document
# msg -- message to replace document with. The string "_URL_" is
# replaced with the actual URL of the part.
# mtype -- message mime type (for the warning msg)
# mext -- message extension (for the warning msg)
# mname -- message name (for the warning msg)
# cd_data -- optional Content-Disposition filename data to save
# salt -- optional salt to add to SHA1 hash.
# %RETURNS:
# 1 on success, 0 on failure
# %DESCRIPTION:
# Places the part in doc_root/{sha1_of_part}.ext and replaces it with
# an mtype part giving the URL for pickup.
#***********************************************************************
sub custom_action_replace_with_url ($$$$;$$$$$) {
my($entity, $doc_root, $base_url, $msg, $mtype, $mext, $mname, $cd_data, $salt) = @_;
my($ctx);
my($path);
my($fname, $ext, $name, $url);
my $extension = "";
return 0 unless in_filter_context("custom_action_replace_with_url");
return 0 unless defined($entity->bodyhandle);
$path = $entity->bodyhandle->path;
return 0 unless defined($path);
open(IN, "<$path") or return 0;
$ctx = Digest::SHA1->new;
$ctx->addfile(*IN);
$ctx->add($salt) if defined($salt);
close(IN);
$fname = takeStabAtFilename($entity);
$fname = "" unless defined($fname);
$extension = $1 if ($fname =~ /(\.[^.]*)$/);
# Use extension if it is .[alpha,digit,underscore]
$extension = "" unless ($extension =~ /^\.[A-Za-z0-9_]*$/);
# Filename to save
$name = $ctx->hexdigest . $extension;
$fname = $doc_root . "/" . $name;
$url = $base_url . "/" . $name;
if (-r $fname) {
# If file exists, then this is either a duplicate or someone
# has defeated SHA1. Just update the mtime on the file.
my($now);
$now = time;
utime($now, $now, $fname);
} else {
copy_or_link($path, $fname) or return 0;
# In case umask is whacked...
chmod 0644, $fname;
}
# save optional Content-Disposition data
if (defined($cd_data) and ($cd_data ne "")) {
# mime type hack because File-MMagic doesn't always work as expected:
$hasTab = 0 unless ($hasTab = index($cd_data, "\t"));
if ($hasTab <= 0) {
if ($extension eq '.xls') {
$cd_data = "application/vnd.ms-excel\t" . $cd_data;
}
elsif ($extension eq '.ppt') {
$cd_data = "application/vnd.ms-powerpoint\t" . $cd_data;
}
elsif ($extension eq '.pps') {
$cd_data = "application/vnd.ms-powerpoint\t" . $cd_data;
}
md_syslog('warning', "custom_action_replace_with_url MODIFIED cd_data: $cd_data - extension: $extension.");
}
# mime type hack.
if (open CDF, ">$doc_root/.$name") {
print CDF $cd_data;
close CDF;
chmod 0644, "$doc_root/.$name";
}
}
push(@custom_attachURLlist, $cd_data."\n".$url."\n");
# push(@custom_attachURLlist4html, $cd_data."\n<a href=\"".$url."\">".$fname."</a>\n");
push(@custom_attachURLlist4html, $cd_data."\n<a href=\"".$url."\">".$url."</a>\n");
$msg =~ s/_URL_/$url/g;
if (defined($mtype) and ($mtype ne "") and defined($mext) and ($mext ne "") and defined($mname) and ($mname ne "")) {
custom_action_replace_with_warning($msg, $mtype, $mext, $mname);
}
else {
custom_action_replace_with_warning($msg);
}
return 1;
}
#***********************************************************************
# %PROCEDURE: custom_list_replacement_urls
# %ARGUMENTS:
# entity
# %RETURNS:
# nothing
# %DESCRIPTION:
# Lists replacement URLs at end of body message for all removed attachments.
# Must be called from filter_end.
#***********************************************************************
sub custom_list_replacement_urls ($;$$) {
my($entity, $header, $footer) = @_;
my $plain = $header.join("\n", @custom_attachURLlist).$footer;
# my $html = $plain;
my $html = $header.join("\n", @custom_attachURLlist4html).$footer;
# $html =~ s|(http://\S*)|<a href="$1">$1</a>|g;
$html =~ s/\n/<br>\n/g;
append_text_boilerplate($entity, $plain, 0);
append_html_boilerplate($entity, $html, 0);
}
#***********************************************************************
# %PROCEDURE: filter_begin
# %ARGUMENTS:
# $entity -- the parsed MIME::Entity
# %RETURNS:
# Nothing
# %DESCRIPTION:
# Called just before e-mail parts are processed
#***********************************************************************
sub filter_begin {
my($entity) = @_;
@custom_attachURLlist = ();
@custom_attachURLlist4html = ();
# ALWAYS drop messages with suspicious chars in headers
if ($SuspiciousCharsInHeaders) {
md_graphdefang_log('suspicious_chars');
# action_quarantine_entire_message("Message quarantined because of suspicious characters in headers");
# Do NOT allow message to reach recipient(s)
return action_discard();
}
# Copy original message into work directory as an "mbox" file for
# virus-scanning
md_copy_orig_msg_to_work_dir_as_mbox_file();
# Scan for viruses if any virus-scanners are installed
my($code, $category, $action) = message_contains_virus();
# Lower level of paranoia - only looks for actual viruses
$FoundVirus = ($category eq "virus");
# Higher level of paranoia - takes care of "suspicious" objects
# $FoundVirus = ($action eq "quarantine");
md_graphdefang_log('virus check', $category, $action);
if ($FoundVirus) {
md_graphdefang_log('virus', $VirusName, $RelayAddr);
md_syslog('warning', "Discarding because of virus $VirusName");
return action_discard();
}
#check for known spam patterns:
my $custom_blockcontent = 0;
if ((open(MESSAGEHEADERS,"./HEADERS")) && (open(MESSAGEBODY,"./INPUTMSG"))) {
# Let's try to get unwanted HEADER content from text file:
if (open(UNWANTED, "</etc/mail/custom/custom_blacklist_content_headers")) {
while(<UNWANTED>)
{
seek MESSAGEHEADERS, 0, 0;
my $BANLINE = $_;
chomp($BANLINE);
# $BANLINE =~ tr/\015//d;
# $BANLINE =~ s/\r\n//g;
# $BANLINE =~ s/\n//g;
$BANLINE =~ s/\r//g;
if ((length($BANLINE) > 0) && (grep{/$BANLINE/} <MESSAGEHEADERS>)){
$custom_blockcontent = 1;
md_graphdefang_log('mail', "CUSTOM_BAN: Discarding because of SPAM marker [$BANLINE] in headers", 'ban_content');
last;
}
}
close(UNWANTED);
} else { # if open UNWANTED
md_graphdefang_log('mail', "CUSTOM_BAN_ERROR_NO_UNWANTED_HEADERS_DATA", 'ban_content');
}
# Let's try to get unwanted BODY content from text file:
if (($custom_blockcontent == 0) && (open(UNWANTED, "</etc/mail/custom/custom_blacklist_content_body"))) {
while(<UNWANTED>)
{
seek MESSAGEBODY, 0, 0;
my $BANLINE = $_;
chomp($BANLINE);
$BANLINE =~ s/\r//g;
if ((length($BANLINE) > 0) && (grep{/$BANLINE/} <MESSAGEBODY>)){
$custom_blockcontent = 1;
md_graphdefang_log('mail', "CUSTOM_BAN: Discarding because of SPAM marker [$BANLINE] in body", 'ban_content');
last;
}
}
close(UNWANTED);
} else { # if open UNWANTED
md_graphdefang_log('mail', "CUSTOM_BAN_ERROR_NO_UNWANTED_BODY_DATA_OR_ALREADY_BANNED", 'ban_content');
}
# Let's try to get suspicious HEADER and BODY content from text file:
if (($custom_blockcontent == 0) && (open(UNWANTED, "</etc/mail/custom/custom_alertlist_content"))) {
while(<UNWANTED>)
{
seek MESSAGEHEADERS, 0, 0;
seek MESSAGEBODY, 0, 0;
my $BANLINE = $_;
chomp($BANLINE);
$BANLINE =~ s/\r//g;
if ((length($BANLINE) > 0) && ((grep{/$BANLINE/} <MESSAGEHEADERS>) || (grep{/$BANLINE/} <MESSAGEBODY>))){
md_graphdefang_log('mail', "CUSTOM_ALERT: Alerting because of SUSPICIOUS marker [$BANLINE] in message", 'alert_content');
last;
}
}
close(UNWANTED);
} else { # if open UNWANTED
md_graphdefang_log('mail', "CUSTOM_ALERT_ERROR_NO_UNWANTED_DATA_OR_ALREADY_BANNED", 'alert_content');
}
close(MESSAGEHEADERS);
close(MESSAGEBODY);
} else { # if open MESSAGEHEADERS and MESSAGEBODY
md_graphdefang_log('mail', "CUSTOM_BAN_ERROR_NO_MESSAGE_DATA", 'ban_content');
}
return action_discard() if ($custom_blockcontent);
if ($action eq "tempfail") {
# action_tempfail("Problem running virus-scanner");
md_syslog('warning', "Problem running virus scanner: code=$code, category=$category, action=$action");
}
action_add_header("X-FHM-Filter", "Message from $Sender was filtered by FHM.");
}
#***********************************************************************
# %PROCEDURE: filter
# %ARGUMENTS:
# entity -- a Mime::Entity object (see MIME-tools documentation for details)
# fname -- the suggested filename, taken from the MIME Content-Disposition:
# header. If no filename was suggested, then fname is ""
# ext -- the file extension (everything from the last period in the name
# to the end of the name, including the period.)
# type -- the MIME type, taken from the Content-Type: header.
#
# NOTE: There are two likely and one unlikely place for a filename to
# appear in a MIME message: In Content-Disposition: filename, in
# Content-Type: name, and in Content-Description. If you are paranoid,
# you will use the re_match and re_match_ext functions, which return true
# if ANY of these possibilities match. re_match checks the whole name;
# re_match_ext checks the extension. See the sample filter below for usage.
# %RETURNS:
# Nothing
# %DESCRIPTION:
# This function is called once for each part of a MIME message.
# There are many action_*() routines which can decide the fate
# of each part; see the mimedefang-filter man page.
#***********************************************************************
sub filter {
my($entity, $fname, $ext, $type) = @_;
return if message_rejected(); # Avoid unnecessary work
$NotifySenderSubject = "AVISO correo";
# Block message/partial parts
if (lc($type) eq "message/partial") {
md_graphdefang_log('message/partial');
action_bounce("MIME type message/partial not accepted here");
return action_discard();
}
# If it's the postmaster (or unknown sender) then remove all attachments
if ( ($Sender eq '<>') && ($fname ne '') ) {
md_graphdefang_log('mail', 'CUSTOM_UNKNOWN_SENDER', $fname);
return action_drop_with_warning("Attachment removed due to unknown sender: $fname\n");
}
# Some senders do not get their mail filtered
# Also, some recipients do not get their mail filtered
my($custom_applyfilter) = 1;
# Some senders get their mail filtered (LAB GLIMS only, for now)
my($custom_applysecurefilter) = 0;
# if e-mail sender is NOT local then do NOT filter
if ( (index($Sender, '@myotherdomain.org>') == -1) && (index($Sender, '@mydomain.org>') == -1) ) {
$custom_applyfilter = 0;
return action_accept();
}
# return immediately; no file size checks...
if ($custom_applysecurefilter eq 1) {
if ($fname ne '') {
#action_notify_sender("Processed file: $fname.\n\n");
return custom_action_replace_with_url($entity,"/var/www/localhost/htdocs/securedownloads/dkduueeksdfuh3447373","https://securedownloads.myotherdomain.org/securedownloads/dkduueeksdfuh3447373","You can download the file from here:<br>\n<br>\n<a href='_URL_'>_URL_</a><br>\n<br>\nWARNING: the attached file $fname will be available for a period of 30 days.<br>\n","text/html","html","attachment",$fname);
} else {
return custom_action_replace_with_warning("My Org\n\n");
#return 1;
}
}
# Let's try to grab user list from text file:
open(VIPUSERS, "</etc/mail/custom/custom_whitelist_senders");
while(<VIPUSERS>)
{
my($VIPLINE) = $_;
chomp($VIPLINE);
$VIPLINE =~ s/\r//g;
if ( $Sender =~ /<$VIPLINE@/i ) {
$custom_applyfilter = 0;
md_graphdefang_log('mail', 'CUSTOM_NOFILTER_SENDER_AUTO', 'priv_senders');
}
}
if ( ($fname eq '') || ($Sender eq '<>') ) {
$custom_applyfilter = 0;
md_graphdefang_log('mail', 'CUSTOM_NOFILTER_UNSPEC', 'unspecified_fname_or_sender');
}
my($custom_size, $custom_bandwidth);
my($custom_size_max, $custom_bandwidth_max);
my($custom_size_max2, $custom_bandwidth_max2);
$custom_bandwidth = (stat("./INPUTMSG"))[7]*scalar(@Recipients);
md_graphdefang_log('mail', 'CUSTOM_BANDWIDTH', $custom_bandwidth);
$custom_size = (stat($entity->bodyhandle->path))[7];
md_graphdefang_log('mail', 'CUSTOM_MSG_PART_SIZE', $custom_size);
# max message size
$custom_size_max = 4*1024*1024;
$custom_bandwidth_max = 8*1024*1024;
$custom_size_max2 = 40*1024*1024;
$custom_bandwidth_max2 = 150*1024*1024;
if ( ($custom_size > $custom_size_max2) || ($custom_bandwidth > $custom_bandwidth_max2) ) {
$custom_applyfilter = 1;
}
if ($custom_applyfilter eq 1) {
# If it's not a compressed file then zip it, if possible
my($comp_exts, $re);
$comp_exts = '(zip|gz|tgz|bz2|Z|\{[^\}]+\})';
$re = '\.' . $comp_exts . '\.*$';
my $zipped;
# Dec. 2010: do NOT create ZIP files because some recipients don't have uncompression software...
#if ( ($Features{"Archive::Zip"}) && (!re_match($entity, $re)) ) {
# md_graphdefang_log('mail', 'CUSTOM_COMPRESS', $fname);
# my $zip = Archive::Zip->new();
# my $member;
# $member = $zip->addFile($entity->bodyhandle->path, $fname);
# # compress (DEFLATED) or not (STORED)
# $member->desiredCompressionMethod( COMPRESSION_DEFLATED );
# $member->desiredCompressionLevel( COMPRESSION_LEVEL_BEST_COMPRESSION );
# $member->setLastModFileDateTimeFromUnix( 318211200 );
# $fname = "$fname.zip" unless $fname =~ s/\.[^.]*$/\.zip/;
# $zip->writeToFileNamed("./Work/CUSTOM_$fname");
# custom_action_replace_with_file($entity, "./Work/CUSTOM_$fname", $fname);
# $zipped = 1;
#}
if ( ($custom_size > $custom_size_max) || ($custom_bandwidth > $custom_bandwidth_max) ) {
action_notify_sender("The file $fname has been sent to the recipient as a web link.\n");
return custom_action_replace_with_url($entity,"/var/www/localhost/htdocs/downloads/sdsfd67sf6dsfdsfd78","http://downloads.myotherdomain.org/downloads/sdsfd67sf6dsfdsfd78","<i>You can download the attached file from here:</i><br>\n<br>\n<a href='_URL_'>_URL_</a><br>\n<br>\nNOTE: the file ($fname - $custom_size bytes) will be available for a period of 30 days.\n","text/html","html","attachment",$fname);
}
if ($zipped) {
return 1;
}
}
return action_accept();
}
#***********************************************************************
# %PROCEDURE: filter_multipart
# %ARGUMENTS:
# entity -- a Mime::Entity object (see MIME-tools documentation for details)
# fname -- the suggested filename, taken from the MIME Content-Disposition:
# header. If no filename was suggested, then fname is ""
# ext -- the file extension (everything from the last period in the name
# to the end of the name, including the period.)
# type -- the MIME type, taken from the Content-Type: header.
# %RETURNS:
# Nothing
# %DESCRIPTION:
# This is called for multipart "container" parts such as message/rfc822.
# You cannot replace the body (because multipart parts have no body),
# but you should check for bad filenames.
#***********************************************************************
sub filter_multipart {
my($entity, $fname, $ext, $type) = @_;
return if message_rejected(); # Avoid unnecessary work
md_graphdefang_log('CUSTOM_MULTIPART_DATA', $fname, $type);
if (filter_bad_filename($entity)) {
md_graphdefang_log('bad_filename', $fname, $type);
action_notify_administrator("A MULTIPART attachment of type $type, named $fname was dropped.\n");
return action_drop_with_warning("An attachment of type $type, named $fname was removed from this document as it\nconstituted a security hazard. If you require this document, please contact\nthe sender and arrange an alternate means of receiving it.\n");
}
# Block message/partial parts
if (lc($type) eq "message/partial") {
md_graphdefang_log('message/partial');
action_bounce("MIME type message/partial not accepted here");
return;
}
return action_accept();
}
#***********************************************************************
# %PROCEDURE: defang_warning
# %ARGUMENTS:
# oldfname -- the old file name of an attachment
# fname -- the new "defanged" name
# %RETURNS:
# A warning message
# %DESCRIPTION:
# This function customizes the warning message when an attachment
# is defanged.
#***********************************************************************
sub defang_warning {
my($oldfname, $fname) = @_;
return
"The attached file '$oldfname' was converted to '$fname'.\n" .
"To restore it, right-click and Save As\n" .
"'$oldfname'\n";
}
# If SpamAssassin found SPAM, append report. We do it as a separate
# attachment of type text/plain
sub filter_end {
my($entity) = @_;
# If you want quarantine reports, uncomment next line
# send_quarantine_notifications();
# IMPORTANT NOTE: YOU MUST CALL send_quarantine_notifications() AFTER
# ANY PARTS HAVE BEEN QUARANTINED. SO IF YOU MODIFY THIS FILTER TO
# QUARANTINE SPAM, REWORK THE LOGIC TO CALL send_quarantine_notifications()
# AT THE END!!!
# No sense doing any extra work
return if message_rejected();
# Spam checks if SpamAssassin is installed
if ($Features{"SpamAssassin"}) {
if (-s "./INPUTMSG" < 100*1024) {
# Only scan messages smaller than 100kB. Larger messages
# are extremely unlikely to be spam, and SpamAssassin is
# dreadfully slow on very large messages.
my($hits, $req, $names, $report) = spam_assassin_check();
my($score);
if ($hits < 40) {
$score = "*" x int($hits);
} else {
$score = "*" x 40;
}
md_graphdefang_log('CUSTOM_LOG_INFO_SPAM_HITS_SCORE', $hits, $score);
# We add a header which looks like this:
# X-Spam-Score: 6.8 (******) NAME_OF_TEST,NAME_OF_TEST
# The number of asterisks in parens is the integer part
# of the spam score clamped to a maximum of 40.
# MUA filters can easily be written to trigger on a
# minimum number of asterisks...
if ($hits >= $req) {
action_change_header("X-Spam-Score", "$hits ($score) $names");
md_graphdefang_log('spam', $hits, $RelayAddr);
action_change_header('Subject', "**MYORG-SPAM** $Subject");
# If you find the SA report useful, add it, I guess...
#action_add_part($entity, "text/plain", "-suggest",
# "$report\n",
# "SpamReport.txt", "inline");
} else {
# Delete any existing X-Spam-Score header?
action_delete_header("X-Spam-Score");
}
}
}
# I HATE HTML MAIL! If there's a multipart/alternative with both
# text/plain and text/html parts, nuke the text/html. Thanks for
# wasting our disk space and bandwidth...
# If you want to strip out HTML parts if there is a corresponding
# plain-text part, uncomment the next line.
# remove_redundant_html_parts($entity);
md_graphdefang_log('mail_in');
if (@custom_attachURLlist > 0) {
&custom_list_replacement_urls($entity,"\n\n============================\n\nPlease click on each link to download.\n\n","\nData available during a period of 30 days.\n\n------- ------\n=== END MESSAGE ===\n")
}
if ($Sender eq '<>') {
append_text_boilerplate($entity, "\n------\nPlease do not send the message again. Message ID $MessageID.", 0);
my($custom_msgid) = $MessageID;
$custom_msgid =~ s/\@/-/g;
my($custom_okchars) = '-a-zA-Z0-9_.';
$custom_msgid =~ s/[^$custom_okchars]//g;
my($custom_recip) = $Recipients[0];
$custom_recip =~ s/\@/-/g;
$custom_recip =~ s/[^$custom_okchars]//g;
$custom_recip = substr($custom_recip, 0, 30);
my($custom_bkfname) = "/SAMBA/Trouble_email/msg_".$custom_msgid."_".$custom_recip."_".time()."_".int(rand(100)).".eml";
copy_or_link("./INPUTMSG", $custom_bkfname);
chmod 0666, $custom_bkfname;
}
# Deal with malformed MIME.
# Some viruses produce malformed MIME messages that are misinterpreted
# by mail clients. They also might slip under the radar of MIMEDefang.
# If you are worried about this, you should canonicalize all
# e-mail by uncommenting the action_rebuild() line. This will
# force _all_ messages to be reconstructed as valid MIME. It will
# increase the load on your server, and might break messages produced
# by marginal software. Your call.
# action_rebuild();
}
# DO NOT delete the next line, or Perl will complain.
1;
More information about the MIMEDefang
mailing list