# -*- 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: mimedefang-filter,v 1.1 2005/03/04 14:55:58 root Exp root $
#***********************************************************************

#***********************************************************************
# Configure Virus Scanners
#***********************************************************************
$ClamdSock = "/var/spool/MIMEDefang/clamd.sock";
$Features{'Virus:CLAMD'} = '/usr/sbin/clamd';
$Features{'Virus:CLAMAV'} = '/usr/bin/clamscan';

#***********************************************************************
# 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@mydomain.com'
#***********************************************************************
$AdminAddress = 'mimedefang@example.com';
$AdminName = "Fred Bacon";

#***********************************************************************
# Set the e-mail address from which MIMEDefang quarantine warnings and
# user notifications appear to come.  A good example would be
# 'mimedefang@mydomain.com'.  Make sure to have an alias for this
# address if you want replies to it to work.
#***********************************************************************
$DaemonAddress = 'mimedefang@example.com';

#***********************************************************************
# Enable network tests in SpamAssassin
#***********************************************************************
$SALocalTestsOnly = 0;

#***********************************************************************
# 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 = 0;

#***********************************************************************
# 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', 0);

#***********************************************************************
# 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;

#***********************************************************************
# Set various stupid things your mail client does below.
#***********************************************************************

# Set the next one if your mail client cannot handle multiple "inline"
# parts.
$Stupidity{"NoMultipleInlines"} = 0;

#***********************************************************************
# We need to have access to a second instance of SpamAssassin which is
# stored in a global variable.  I hope that this works here.
#***********************************************************************
use vars qw($SAToCTester);
undef $SAToCTester;

#***********************************************************************
# This is where we will store our hash of known journals.  They don't
# need to be in any particular order.  So just add new journals at the
# end of the list. 
#
# We use a hash table so that we don't need to worry about matching
# substrings by accident.
#
#   i.e. JMassSpectrom would also match EurJMassSpectrom as a string
#
# but not as a hash key.  They will be distinct.  The value stored with
# the hash key can really be anything, but I choose to make it the 
# number 1, which will evaluate to true if necessary.
# 
# The hash keys are the spamassassin meta rule names defined in the file
#
#   /etc/mail/journals/journals.cf
#
# (Rule names beginning with two underscores '__' are invisible.)
#***********************************************************************
%journal_list = (
 AAASPolicyAlert => 1,          AccChemRes => 1,                AerosolSciTechnol => 1,
 MolPhys => 1,                  TellusB => 1 );

# The next lines force SpamAssassin modules to be loaded and rules
# to be compiled immediately.  This may improve performance on busy
# mail servers.  Comment the lines out if you don't like them.
if ($Features{"SpamAssassin"}) {
    spam_assassin_init()->compile_now(1) if defined(spam_assassin_init());
    sa_journal_init()->compile_now(1) if defined(sa_journal_init());

# If you want to use auto-whitelisting:
#   if (defined($SASpamTester)) {
#       use Mail::SpamAssassin::DBBasedAddrList;
#       my $awl = Mail::SpamAssassin::DBBasedAddrList->new();
#       $SASpamTester->set_persistent_address_list_factory($awl) if defined($awl);
#   }
}

# 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|asx|bat|chm|cmd|com|cpl|crt|dll|exe|fxp|hlp|hta|hto|inf|ini|ins|isp|jse?|lib|mdb|mde|msc|msi|msp|mst|ocx|pcd|pif|prg|reg|scr|sct|sh|shb|shs|sys|vb|vbe|vxd|wmd|wms|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));

    return 0;
}

#***********************************************************************
# %PROCEDURE: filter_sender
# %ARGUMENTS:
#   sender     Envelope sender
#   ip         Relay machine's ip number
#   hostname   Relay machine's hostname
#   helo       HELO string from relaying machine
# %RETURNS:
#   code       Return code  
#   msg        Error message to log
#   smtp_code  SMTP Error code to return (optional)  
#   smtp_dsn   Delivery Service Notification message (optional)
#   delay      Delay time
# %DESCRIPTION:
#   Called during the sender resolution stage
#***********************************************************************
sub filter_sender () {
   my ($sender, $ip, $hostname, $helo) = @_;
   if (($helo =~ /^(d{1;,3})(.)(d{1;,3})(.)(d{1;,3})(.)(d{1;,3})$/) &&
       ($ip ne $helo)) {
        return ('REJECT',"Header forgery attempt, $ip claims to be $helo") 
   }

   return ('CONTINUE', "ok");
}

#***********************************************************************
# %PROCEDURE: filter_recipient
# %ARGUMENTS:
#   recipient   Envelope recipient
#   sender      Envelope sender
#   ip          Relay machine's ip number
#   hostname    Relay machine's hostname
#   first       Envelope address of first recipient
#   helo        HELO string from relaying machine
#   rcpt_mailer Sendmail mailer for recipient 
#   rcpt_host   Sendmail host for recipient
#   rcpt_addr   Sendmail address for recipient
# %RETURNS
#   code        Return code
#   msg         Error message to log 
#   smtp_code   SMTP Error code to return (optional)  
#   smtp_dsn    Delivery Service Notification message (optional)
#   delay       Delay time
# %DESCRIPTION:
#   Called during the recipient resolution stage
#***********************************************************************
sub filter_recipient () {
   my ($recipient, $sender, $ip, $hostname, $first, $helo,
          $rcpt_mailer, $rcpt_host, $rcpt_addr) = @_;

# It seems that we need this for SendmailMacros to be defined.
   read_commands_file();

# If the recipient is one of the internal alias mailing lists, then
# we should check to see if the message came from an internal ip
# of if the user authenticated themselves.  If not, then reject the
# message.  Otherwise, accept all messages at this stage.

   if ($recipient =~ /^<?(allexample|who|what|when|where|how)\@example\.com>?$/i) {
     if ($RelayAddr !~ /^10\./ and $RelayAddr !~ /^198\.4\.242\./
          and !defined($SendmailMacros{"auth_authen"})) {
       return ('REJECT', "Nonlocal user tried to use $recipient", '553', "Only Aerodyne users may use this address." );
     }
   }

   return ('CONTINUE', "ok");
}

#***********************************************************************
# %PROCEDURE: filter_begin
# %ARGUMENTS:
#  None
# %RETURNS:
#  Nothing
# %DESCRIPTION:
#  Called just before e-mail parts are processed
#***********************************************************************
sub filter_begin () {
    # ALWAYS drop messages with suspicious chars in headers
    if ($SuspiciousCharsInHeaders and $Sender !~ /service\.govdelivery\.com/ ) {
        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");

    if ($FoundVirus) {
	md_graphdefang_log('virus', $VirusName, $RelayAddr);
	md_syslog('warning', "Discarding because of virus $VirusName");
        action_quarantine_entire_message( "Quarantined virus: $VirusName" );
	return action_discard();
    }

    if ($action eq "tempfail") {
    	action_tempfail("Problem running virus-scanner");
    	md_syslog('warning', "Problem running virus scanner: code=$code, category=$category, action=$action");
    }
}

#***********************************************************************
# %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

    # 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 (filter_bad_filename($entity)) {
        md_graphdefang_log('bad_filename', $fname, $type);
    	return action_quarantine($entity, "An attachment named $fname was removed from this document as it\nconstituted a network security hazard.  If you require this document, \nplease contact the sender and arrange an alternate means of receiving it.\n");
    }

    # eml is bad if it's not multipart
    if (re_match($entity, '\.eml')) {
        md_graphdefang_log('non_multipart');
	return action_quarantine($entity, "A non-multipart attachment named $fname was removed from this document as it\nconstituted a network security hazard.  If you require this document, \nplease contact the sender and arrange an alternate means of receiving it.\n");
    }

    # Clean up HTML if Anomy::HTMLCleaner is installed.
    if ($Features{"HTMLCleaner"}) {
	if ($type eq "text/html") {
	    return anomy_clean_html($entity);
	}
    }

    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

    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_quarantine($entity,"An attachment of type $type, named $fname was removed from this document as it\nconstituted a network security hazard.  If you require this document, \nplease contact the sender and arrange an alternate means of receiving it.\n");
    }

    # eml is bad if it's not message/rfc822
    if (re_match($entity, '\.eml') and ($type ne "message/rfc822")) {
        md_graphdefang_log('non_rfc822',$fname);
	return action_drop_with_warning("A non-message/rfc822 attachment named $fname was removed from this document as it\nconstituted a network security hazard.  If you require this document, \nplease contact the 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
	"An attachment named '$oldfname' was converted to '$fname'.\n" .
	"To recover the file, right-click on the attachment 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();

    # First we want to deal with journals.
    # We require that SpamAssassin be installed, since our scheme is based
    # on SpamAssassin rules.
    if ($Features{"SpamAssassin"}) {
        # we want to search the list of recipients
        foreach $rcpt (@Recipients) {
            # We are only testing for TOCs in xxx and yyy's email
            if ( $rcpt =~ /^<?(xxx|yyy)\@example\.com>?$/i && !($Subject =~ /\[TOC\]/) ) {
                # first let's see if this is a journal.
                # We use a special instance of SpamAssassin with a limited
                # number of rules related to journals.
                my($hits, $req, $names, $report) = sa_journal_check();

                # Debugging help
                md_syslog ( 'warning', "Journal Names:  $names" );
                md_syslog ( 'warning', "Journal Subject: $Subject" );
                action_change_header ( "X-Journal-Rules", $names ); 

                # We should only have matched one journal, 
                # but take precautions just in case
                @journals = split /,/, $names;
                foreach $jname (@journals) {
                    if ( exists %journal_list->{$jname} ) {
                        # Okay, this is a journal, we need to remove the current 
                        # addressee and redirect the message to the mailing list
                        delete_recipient($rcpt);
                        action_change_header("To", '<who@example.com>');
                        add_recipient('<who@example.com>'); 

                        # we need to add the journal tag as a Keywords header
                        # so that GNU Mailman will recognize it.
                        action_change_header("Keywords", $jname );

                        # Since this was a journal table of contents, let's return here.
                        md_graphdefang_log('mail_in');
                        return;
                    }
                }
            }
        }
    }

    # Spam checks: See this is locally submitted and if SpamAssassin is installed
    if ( $RelayAddr !~ /^10\./ and $RelayAddr !~ /^198\.4\.242\./ and !defined($SendmailMacros{"auth_authen"})) {
        if ($Features{"SpamAssassin"}) {
  	    if (-s "./INPUTMSG" < 200*1024) {
  	        # Only scan messages smaller than 200kB.  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();

                # FWB
                if ( $hits > 0 ) {
                    md_syslog('info',"$MsgID: (spamassassin) hits: $hits" );
                }
            
                # Any positive non zero score should be labeled with
                # a X-Spam-Score header so that users can filter on it 
                #   X-Spam-Score: ========
                # The number of equal signs 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 equal signs...
                #
	        if ( $hits >= 1 ) {
                    my ($score);
		    if ( $hits < 40 ) {
		        $score = "=" x int($hits);
		    } else {
		        $score = "=" x 40;
		    }
                    action_change_header("X-Spam-Score", "$score");
	        }
                # FWB

	        if ($hits >= $req) {
                    md_graphdefang_log('spam', $hits, $RelayAddr);
		    # We add one header which looks like this:
		    #   X-Spam-Tests: 6.8 NAME_OF_TEST,NAME_OF_TEST
                    # and another header which looks like this:
                    action_change_header("X-Spam", "Yes");
		    action_change_header("X-Spam-Tests", "$hits $names");

                    # FWB
                    action_change_header("Subject","*****SPAM***** $Subject");
                    # FWB

		    # If you find the SA report useful, add it, I guess...
		    action_add_part($entity, "text/plain", "-suggest",
		                    "$report\n",
		   	 	    "SpamAssassinReport.txt", "inline");
	        } else {
                    # FWB: add a test score for non-spam as well, we want to see it
                    action_change_header("X-Spam", "No");
                    action_change_header("X-Spam-Tests", "No. hits=$hits required=$req test=$names" );
                    # FWB: END
	        }
 	    }
        }
    }

    # 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');

    # 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();
}

#***********************************************************************
# %PROCEDURE: sa_journal_is_toc
# %ARGUMENTS:
#  config -- optional configuration file
# %RETURNS:
#  1 if SpamAssassin thinks current message is SPAM; 0 otherwise
#  or if message could not be opened.
# %DESCRIPTION:
#  Scans message using SpamAssassin (http://www.spamassassin.org)
#***********************************************************************
sub sa_journal_is_toc (;$) {

    my($hits, $req, $tests, $report) = sa_journal_check(@_);
    return undef if (!defined($hits));

    return ($hits >= $req);
}

#***********************************************************************
# %PROCEDURE: sa_journal_check
# %ARGUMENTS:
#  config -- optional spamassassin config file
# %RETURNS:
#  An array of four elements,
#       Weight of message ('hits')
#       Number of hits required before SA conciders a message spam
#       Comma separated list of symbolic test names that were triggered
#       A 'report' string, detailing tests that failed and their weights
# %DESCRIPTION:
#  Scans message using SpamAssassin (http://www.spamassassin.org)
#***********************************************************************
sub sa_journal_check (;$) {

    my($status) = sa_journal_status(@_);
    return undef if (!defined($status));

    my $hits = $status->get_hits;
    my $req = $status->get_required_hits();
    my $names = $status->get_names_of_tests_hit();
    my $report = $status->get_report();

    $status->finish();

    return ($hits, $req, $names, $report);
}

#***********************************************************************
# %PROCEDURE: sa_journal_status
# %ARGUMENTS:
#  config -- optional spamassassin config file
# %RETURNS:
#  A Mail::SpamAssassin:PerMsgStatus object.
#  CALLER IS RESPONSIBLE FOR CALLING finish()
# %DESCRIPTION:
#  Scans message using SpamAssassin (http://www.spamassassin.org)
#***********************************************************************
sub sa_journal_status (;$) {

    my $object = sa_journal_init(@_);
    return undef unless $object;

    my $mail = sa_journal_mail();
    return undef unless $mail;

    my $status;
    push_status_tag("Running SpamAssassin");
    $status = $object->check($mail);
    $mail->finish();
    pop_status_tag();
    return $status;
}

#***********************************************************************
# %PROCEDURE: sa_journal_init
# %ARGUMENTS:
#  config -- optional spamassassin config file
# %RETURNS:
#  A Mail::SpamAssassin object.
# %DESCRIPTION:
#  Scans message using SpamAssassin (http://www.spamassassin.org)
#***********************************************************************
sub sa_journal_init (;$) {
    my($config) = @_;
    my $LOCAL_SITE_RULES_DIR = '/etc/mail/journals';
    my $LOCAL_STATE_DIR = '/var/lib';

    unless ($Features{"SpamAssassin"}) {
	md_syslog('err', "Attempt to call SpamAssassin function, but SpamAssassin is not installed.");
	return undef;
    }

    if (!defined($SAToCTester)) {
	if (!defined($config)) {
	    if (-r '/etc/mail/sa-mimedefang.cf') {
		$config = '/etc/mail/sa-mimedefang.cf';
            } else {
                return undef;
	    }
	}

	my $sa_args = {
		local_tests_only    => 1,
		dont_copy_prefs     => 1,
                site_rules_filename => $LOCAL_SITE_RULES_DIR,
                userstate_dir       => $LOCAL_STATE_DIR,
		userprefs_filename  => $config,
		user_dir            => $Features{'Path:QUARANTINEDIR'},
	};

	$SAToCTester = Mail::SpamAssassin->new( $sa_args );
	pop_status_tag();
    }

    return $SAToCTester;
}

#***********************************************************************
# %PROCEDURE: sa_journal_mail
# %ARGUMENTS:
#  none
# %RETURNS:
#  A Mail::SpamAssassin::Message object
#***********************************************************************
sub sa_journal_mail (;$) {

    unless ($Features{"SpamAssassin"}) {
	md_syslog('err', "Attempt to call SpamAssassin function, but SpamAssassin is not installed.");
	return undef;
    }

    open(IN, "<./INPUTMSG") or return undef;
    my @msg = <IN>;
    close(IN);

    # Synthesize a "Return-Path" and "Received:" header
    my @sahdrs;
    push (@sahdrs, "Return-Path: $Sender\n");
    push (@sahdrs, split(/^/m, synthesize_received_header()));
    push (@sahdrs, gen_msgid_header()) if ($MessageID eq "NOQUEUE");

    unshift (@msg, @sahdrs);
    if (!defined($SAToCTester)) {
	sa_journal_init(@_);
	return undef unless $SAToCTester;
    }
    return $SAToCTester->parse(\@msg);
}
# DO NOT delete the next line, or Perl will complain.
1;

