[Mimedefang] filter based on From/To headers?

Michael Sims michaels at crye-leike.com
Wed May 5 17:10:46 EDT 2004


Kelsey Cummings wrote:
> I need to check for 'invalid' From and To headers in our inbound email
> (primarily to catch spam that inserts 'JUNK at mail_server_hostname' into
> either header.)  Does anyone have an example of how they did this or
> pointers on where to wedge it in?

You basically need to open and traverse the "HEADERS" file that will be in the
current working directory during each slave's call to filter_begin() or
filter_end().  You can put the check in either sub, depending on what you want to do
with the email and the flow of your filter code.  Here's one possible (untested)
example:

open(HEADERS, '<./HEADERS');
my ($fromHeader, $toHeader);
while (<HEADERS>) {
  if (/^From:\s+(.*)\s*$/) {
    $fromHeader = $1;
  } elsif (/^To:\s+(.*)\s*$/) {
    $toHeader = $1;
  }
  last if (defined $fromHeader && defined $toHeader);
}
close(HEADERS);

That just extracts the values of those headers, but depending on the action you want
to take the above could be simplified.  If you just wanted to discard (or bounce)
any email that contained a keyword in either header:

open(HEADERS, '<./HEADERS');
my $discardFlag = 0;
while (<HEADERS>) {
  $discardFlag = 1 if (/^(?:From|To):.*JUNK\@mail_server_hostname/);
}
close(HEADERS);
return action_discard() if ($discardFlag);

One caveat:  I believe it is possible for the To header to contain multiple lines.
Each subsequent line should have a tab character at the beginning.  If you really
want to be accurate, you need to take that into account.  Probably easiest would be
to slurp the entire HEADERS file into one variable then use a regex to extract the
possible multi-line from and to headers.  Another alternative (possibly overkill)
would be to use MIME::Parser (part of MIME::Tools):

my $parser = new MIME::Parser;
$parser->output_to_core(1);

my $message    = $parser->parse_open('./HEADERS');
my $fromHeader = $message->head->get('From');
my $toHeader   = $message->head->get('To');

HTH



More information about the MIMEDefang mailing list