#!/usr/bin/perl -T # # postfwd - postfix firewall daemon # # Please see `postfwd -h` for usage or # `postfwd -m` for detailed instructions. # ### SUB init package postfwd; use strict; # Includes use Sys::Syslog qw(:DEFAULT setlogsock); use Getopt::Long 2.25 qw(:config no_ignore_case bundling); use POSIX qw(setsid setuid setgid setlocale strftime LC_ALL); use Pod::Usage; use Net::CIDR::Lite; use Net::Server::Multiplex; use vars qw(@ISA); @ISA = qw(Net::Server::Multiplex); # Program constants our($NAME) = 'postfwd'; our($VERSION) = '1.03'; # Networking options (use -i, -p and -R to change) our($def_net_pid) = "/var/run/".$NAME.".pid"; our($def_net_chroot) = ""; our($def_net_interface) = "127.0.0.1"; our($def_net_port) = "10040"; our($def_net_user) = "nobody"; our($def_net_group) = "nobody"; our($def_net_proto) = "tcp"; # change this, to match your POD requirements # we need pod2text for the -m switch (manual) $ENV{PATH} = "/bin:/usr/bin:/usr/local/bin"; $ENV{ENV} = ""; our($cmd_manual) = "pod2text"; our($cmd_pager) = "more"; # default action, do not change # unless you really know why our($default_action) = "dunno"; # default maximum values for the score() command # if exceeded, the specified action will be returned # may be overwritten by the --scores switch at the command-line # or the score= item in your ruleset files. please see manual. our(%MAX_SCORES) = ( "5.0" => "554 5.7.1 ".$NAME." score exceeded" ); # Status interval, displays stats when using `-S` switch # override with `-S ` at command-line our($Stat_Interval_Time) = 600; # Timeout for request cache, results for identical requests will be # cached until config is reloaded or this time (in seconds) expired # can be changed with `-c` command-line option our($REQUEST_MAX_CACHE) = 600; # RBL / RHSBL parameters, use "rbl = //" # to override for each RBL in your config # maximum cache time in seconds, use 0 to deactivate our($RBL_MAX_CACHE) = 600; # default rbl reply if not specified our($RBL_DEFAULT) = '^127\.0\.0\.\d+$'; # these items have to be compared as... # scoring our($COMP_SCORES) = "score"; # numeric items our($COMP_NUMERIC_ITEMS) = "(recipient_count|size|encryption_keysize)"; # networks in CIDR notation (a.b.c.d/nn) our($COMP_NETWORK_CIDRS) = "client_address"; # RBL checks our($COMP_RBL_KEY) = "rbl"; our($COMP_RBL_CNT) = "rblcount"; our($COMP_RHSBL_KEY) = "rhsbl"; our($COMP_RHSBL_CNT) = "rhsblcount"; # date checks our($COMP_DATE) = "date"; our($COMP_TIME) = "time"; # macros our($COMP_ACL) = "[\&][\&]"; # negation our($COMP_NEG) = "[\!][\!]"; # variables our($COMP_VAR) = "[\$][\$]"; # always true our($COMP_ACTION) = "action"; our($COMP_ID) = "id"; # these items allow whitespace-or-comma-separated values our($COMP_CSV) = "($COMP_NETWORK_CIDRS|$COMP_RBL_KEY|$COMP_RHSBL_KEY)"; # dont treat these as lists our($COMP_SINGLE) = "($COMP_ID|$COMP_ACTION|$COMP_SCORES|$COMP_NUMERIC_ITEMS|$COMP_RBL_CNT|$COMP_RHSBL_CNT)"; # Syslogging options # NOTE: try changing the $syslog_socktype line if syslogging does not # work on your system. Some operating systems (like Solaris) prefer 'inet'. our($syslog_name) = $NAME; our($syslog_socktype) = ($^O eq 'solaris') ? 'inet' : 'unix'; # inet, unix, stream, console our($syslog_facility) = "mail"; our($syslog_options) = "pid"; our($syslog_priority) = "info"; # save command-line our(@CommandArgs) = @ARGV; # initializations - do not change our(@Configs,@Rules) = (); our(%Config_Cache, %RBL_Cache, %Request_Cache) = (); our(%Matches, %attr, %opt_scores, %ACLs) = (); our($Counter_Requests,$Counter_Hits,$Counter_Interval,$Counter_Top) = 0; our($Starttime,$Startdate) = 0; use vars qw( $opt_daemon $opt_instantconfig $opt_nodns $opt_summary $net_interface $net_port $net_user $net_group $net_chroot $net_pid $opt_perfmon $opt_test $opt_verbose $opt_cache_domain_only $opt_cache_no_size $opt_showconfig $opt_stdoutlog ); ### SUB tools # # send log message # escaping % character for safe syslogging # sub mylogs { my($prio) = shift(@_); my($msg) = shift(@_); # dangerous % will be replaced by %% $msg =~ s/\%/%%/g; unless ($opt_stdoutlog) { syslog $prio, "$msg", @_ if (($prio eq "crit") or not($opt_perfmon)); } else { printf "[LOGS $prio]: $msg\n", @_ if (($prio eq "crit") or not($opt_perfmon)); }; } # # send log message # no escaping for the % character - use only for safe output (stats) # sub mylog { my($prio) = shift(@_); my($msg) = shift(@_); unless ($opt_stdoutlog) { syslog $prio, "$msg", @_ if (($prio eq "crit") or not($opt_perfmon)); } else { printf "[LOG $prio]: $msg\n", @_ if (($prio eq "crit") or not($opt_perfmon)); }; } # # print a string to STDOUT # sub myprint { my($msg) = shift(@_); print STDOUT $msg, @_ unless $opt_perfmon; } # # print formatted string to STDOUT # sub myprintf { my($msg) = shift(@_); printf STDOUT $msg, @_ unless $opt_perfmon; } sub show_stats { my($now) = time; my($rblitems) = 0; my($totalreqpermin) = ( ((($now - $Starttime) > 0) ? ($Counter_Requests / ($now - $Starttime)) : 0 ) * 60); my($lastreqpermin) = ( (($Stat_Interval_Time > 0) ? ($Counter_Interval / $Stat_Interval_Time) : 0 ) * 60); $Counter_Top = $lastreqpermin if ($lastreqpermin > $Counter_Top); map ($rblitems += scalar keys %{$RBL_Cache{$_}}, (keys %RBL_Cache)); mylog "notice", "[STATS] Counters: %d seconds uptime since %s", ($now - $Starttime), $Startdate; mylog "notice", "[STATS] Requests: %d overall, %d last interval, %.2f%% cache hits", $Counter_Requests, $Counter_Interval, ($Counter_Requests > 0) ? (($Counter_Hits / $Counter_Requests) * 100) : 0; mylog "notice", "[STATS] Averages: %.2f overall, %.2f last interval, %.2f top", $totalreqpermin, $lastreqpermin, $Counter_Top; mylog "notice", "[STATS] Contents: %d rules, %d cached requests, %d cached dnsbl results", $#Rules, scalar keys %Request_Cache, $rblitems; # per rule stats map { mylogs "notice", "[STATS] Rule ID: $_ matched: $Matches{$_} times" } (sort keys %Matches); $Counter_Interval = 0; }; # # Log an error and abort. # sub fatal_exit { my($msg) = shift(@_); warn "fatal: $msg", @_; exit 1; } # # finish program # sub end_program { show_stats (time) if $opt_summary; mylogs "notice", $NAME." ".$VERSION." terminated" if $opt_daemon; exit; }; # # run a shell command # sub exec_cmd { my($mycmd) = @_; my($myresult) = ( system($mycmd) ); if ( $myresult ) { myprint "Could not execute `".$mycmd."` (Error: ".$myresult.")\n"; myprint "Please check the \$ENV{PATH} setting in the first lines of this program.\n"; myprint "Current setting: \"".$ENV{PATH}."\"\n"; }; return not($myresult); } ### SUB configuration # # sets an action for a score # sub modify_score { (my($myscore), my($myaction)) = @_; if ($opt_verbose) { if ( exists($MAX_SCORES{$myscore}) ) { mylogs "notice", "redefined score $myscore with action=\"$myaction\""; } else { mylogs "notice", "setting new score $myscore with action=\"$myaction\""; }; }; $MAX_SCORES{$myscore} = $myaction; }; # # process configuration # sub acl_parser { my($myline) = @_; if ( $myline =~ /^\s*($COMP_ACL[\-\w]+)\s*{\s*(.*?)\s*;\s*}[\s;]*$/ ) { $ACLs{$1} = $2; $myline = ""; } else { while ( $myline =~ /($COMP_ACL[\-\w]+)/) { my($acl) = $1; $myline =~ s/\s*$acl\s*/$ACLs{$acl}/g if exists($ACLs{$acl}); }; }; return $myline; } sub parse_config_line { my($mynum, $myindex, $myline) = @_; my(%myrule) = (); my($mykey, $myvalue); if ( $myline = acl_parser ($myline) ) { unless ( $myline =~ /^\s*[^=\s]+\s*=\s*([^;\s]+\s*)+(;\s*[^=\s]+\s*=\s*([^;\s]+\s*)+)*[;\s]*$/ ) { warn "warning: ignoring invalid line ".$mynum.": \"".$myline."\""; } else { # separate items foreach (split /;/, $myline) { # remove whitespaces around s/^\s*(.*?)\s*=\s*(.*?)\s*$/$1=$2/; ($mykey, $myvalue) = split /=/; if ($mykey =~ /^$COMP_CSV$/) { push ( @{$myrule{$mykey}}, (split /[,\s]+/, $myvalue) ); } elsif ($mykey =~ /^$COMP_SINGLE$/) { $myrule{$mykey} = $myvalue; } else { push ( @{$myrule{$mykey}}, $myvalue ); }; }; unless (exists($myrule{$COMP_ACTION})) { $myrule{$COMP_ACTION} = "WARN rule found but no action was defined"; mylogs "notice", "warning: Rule ".$myindex." (line ".$mynum."): contains no action - default will be used"; }; unless (exists($myrule{$COMP_ID})) { $myrule{$COMP_ID} = "R-".$myindex; mylogs "notice", "notice: Rule $myindex (line $mynum): contains no rule identifier - will use \"$myrule{id}\"" if $opt_verbose; }; mylogs $syslog_priority, "loaded: Rule $myindex (line $mynum): id->\"$myrule{id}\" action->\"$myrule{action}\"" if $opt_verbose; }; }; return %myrule; } sub read_config_file { my($myindex, $myfile) = @_; my(%myrule, @myruleset) = (); my($mybuffer) = ""; unless (-e $myfile) { warn "error: file ".$myfile." not found - file will be ignored"; } else { unless (open (IN, "<$myfile")) { warn "error: could not open ".$myfile." - file will be ignored"; } else { mylogs $syslog_priority, "reading file $myfile" if $opt_verbose; while () { chomp; s/(\"|#.*)//g; next if /^\s*$/; if (/(.*)\\\s*$/) { $mybuffer = $mybuffer.$1; next; }; %myrule = parse_config_line ($., ($#myruleset+$myindex+1), $mybuffer.$_); push ( @myruleset, { %myrule } ) if (%myrule); $mybuffer = ""; }; close (IN); mylogs $syslog_priority, "loaded: Rules $myindex - ".($myindex + $#myruleset)." from file \"$myfile\"" if $opt_verbose; }; }; return @myruleset; } sub read_config { my(%myrule, @myruleset) = (); my($mytype,$myitem,$config); undef(@Rules); undef(%Request_Cache); for $config (@Configs) { ($mytype,$myitem) = split /,/, $config; if ($mytype eq "r" or $mytype eq "rule") { %myrule = parse_config_line (0, ($#Rules + 1), $myitem); push ( @Rules, { %myrule } ) if (%myrule); } elsif ($mytype eq "f" or $mytype eq "file") { if ( $Config_Cache{$myitem}{lastread} > (stat $myitem)[9] ) { mylogs $syslog_priority, "file \"$myitem\" unchanged - using cached ruleset (mtime: ".(stat $myitem)[9].", cache: $Config_Cache{$myitem}{lastread})" if $opt_verbose; push ( @Rules, @{$Config_Cache{$myitem}{ruleset}} ); } else { @myruleset = read_config_file (($#Rules+1), $myitem); if (@myruleset) { push ( @Rules, @myruleset ); $Config_Cache{$myitem}{lastread} = time; @{$Config_Cache{$myitem}{ruleset}} = @myruleset; }; }; }; }; } sub show_config { my($index,$line,$mykey); if ($opt_verbose) { myprint "=" x 75, "\n"; myprintf "Rule count: %s\n", ($#Rules + 1); myprint "=" x 75, "\n"; }; for $index (0 .. $#Rules) { next unless exists $Rules[$index]; myprintf "Rule %3d: id->\"%s\"; action->\"%s\"", $index, $Rules[$index]{$COMP_ID}, $Rules[$index]{$COMP_ACTION}; $line = ($opt_verbose) ? "\n\t " : ""; for $mykey ( reverse sort keys %{$Rules[$index]} ) { unless (($mykey eq $COMP_ACTION) or ($mykey eq $COMP_ID)) { $line .= "; " if !($opt_verbose); $line .= ($mykey =~ /^$COMP_SINGLE$/) ? $mykey."->\"".$Rules[$index]{$mykey}."\"" : $mykey."->\"".(join ', ', @{$Rules[$index]{$mykey}})."\""; $line .= " ; " if $opt_verbose; }; }; $line =~ s/\s*\;\s*$// if $opt_verbose; myprintf "%s\n", $line; myprint "-" x 75, "\n" if $opt_verbose; }; } ### SUB rblcheck # # check RBLs # sub rbl_check { my($mytype,$myrbl,$myval) = @_; my($myip,$myrip,$myanswer,$myrblans,$myrbltime,$myresult,$mystart,$myend); my($g1,$g2,$g3,$g4,$checkip,@addrs); my($now) = time; # separate rbl-name and answer ($myrbl, $myrblans, $myrbltime) = split /\//, $myrbl; $myrblans = $RBL_DEFAULT unless $myrblans; $myrbltime = $RBL_MAX_CACHE unless $myrbltime; # wipe out old cache entries foreach $checkip (keys %{$RBL_Cache{$myrbl}}) { if ( (($now - @{$RBL_Cache{$myrbl}{$checkip}}[1]) > $myrbltime) ) { delete $RBL_Cache{$myrbl}{$checkip}; mylogs $syslog_priority, "deleted rbl-cache for $checkip on $myrbl" if $opt_verbose; }; }; # query our cache if ( exists($RBL_Cache{$myrbl}{$myval}) ) { ($myanswer, $mystart, $myend) = @{$RBL_Cache{$myrbl}{$myval}}; $myresult = ( $myanswer =~ /$myrblans/ ); mylogs $syslog_priority, "[DNSBL] client $myval listed on ".uc($mytype).":$myrbl (answer: $myanswer, cached: ".($now - $mystart)."s ago)" if ( $myresult and $opt_verbose ); } else { # create query $myval =~ /^([^\[]+)\[([^\]]+)\]/; $myip = ($mytype eq $COMP_RBL_KEY) ? join(".", reverse(split(/\./, $2))) : $1; $myrip = $myip.".".$myrbl; if ( ($mytype eq $COMP_RHSBL_KEY) and ($myip eq "unknown") ) { mylogs $syslog_priority, "skipped rhsbl query: $myrbl $myip ($myrip)" if $opt_verbose; } else { mylogs $syslog_priority, "query $mytype: $myrbl $myip ($myrip)" if $opt_verbose; # resolve $mystart = time; ($g1,$g2,$g3,$g4,@addrs) = gethostbyname($myrip); $myend = time; # compare $myanswer = ($addrs[0]) ? join (".", unpack('C4',$addrs[0])) : "_error_"; $myresult = ( $myanswer =~ /$myrblans/ ); mylogs $syslog_priority, "[DNSBL] client $myval listed on ".uc($mytype).":$myrbl (answer: $myanswer, time: ".($myend - $mystart)."s)" if $myresult; @{$RBL_Cache{$myrbl}{$myval}} = ($myanswer, $mystart, $myend); }; }; return $myresult; } ### SUB ruleset # # get a rule number by id # sub get_rule_by_id { my($id) = @_; my($matched,$myresult) = ""; my($index); RULE: for $index (0 .. $#Rules) { next unless exists $Rules[$index]; $matched = ( $id eq $Rules[$index]{$COMP_ID} ); $myresult = $index if $matched; last RULE if $matched; }; return $myresult; } # # returns content of !!() when given # sub deneg_item { return ( (@_[0] =~ /^$COMP_NEG\s*\(?\s*(.+?)\s*\)?$/) ? $1 : '' ); }; # # compare item # use: compare_item ( TYPE, RULEITEM, MIN, REQUESTITEM ); # sub compare_item { my($mykey,$mymask,$mymin,$myitem, %request) = @_; my($rcount) = 0; #my($cmp,$neg,$myresult) = ""; my($cmp,$neg,$myresult); # # CIDR values (client address, ...) if ( $mykey =~ /^$COMP_NETWORK_CIDRS$/ ) { CIDR: foreach $cmp (@{$mymask}) { mylogs $syslog_priority, "compare-cidr $mykey: \"$myitem\" -> \"$cmp\"" if ($opt_verbose > 1); $cmp = $neg if ($neg = deneg_item($cmp)); mylogs $syslog_priority, "negate $mykey: \"$myitem\" -> \"$cmp\"" if ($neg and ($opt_verbose > 1)); my $myref = Net::CIDR::Lite->new($cmp); $myresult = ( $myref->find($myitem) ); undef($myref); $myresult = not($myresult) if $neg; mylogs $syslog_priority, "match $mykey: ".($myresult ? "TRUE" : "FALSE") if ($opt_verbose > 1); last CIDR if $myresult; }; # # numeric values (size, tls key length, ...) } elsif ( $mykey =~ /^$COMP_NUMERIC_ITEMS$/ ) { mylogs $syslog_priority, "compare-numeric $mykey: \"$myitem\" -> \"$mymask\"" if ($opt_verbose > 1); $mymask = $neg if ($neg = deneg_item($mymask)); mylogs $syslog_priority, "negate $mykey: \"$myitem\" -> \"$mymask\"" if ($neg and ($opt_verbose > 1)); $myitem ||= "0"; $mymask ||= "0"; $myresult = ( $myitem >= $mymask ); $myresult = not($myresult) if $neg; mylogs $syslog_priority, "match $mykey: ".($myresult ? "TRUE" : "FALSE") if ($opt_verbose > 1); # # RBL checks } elsif ( not($opt_nodns) and (($mykey eq $COMP_RBL_KEY) or ($mykey eq $COMP_RHSBL_KEY)) ) { RBLS: foreach $cmp (@{$mymask}) { mylogs $syslog_priority, "compare-rbl $mykey: \"$myitem\" -> \"$cmp\"" if ($opt_verbose > 1); $cmp = $neg if ($neg = deneg_item($cmp)); mylogs $syslog_priority, "negate $mykey: \"$myitem\" -> \"$cmp\"" if ($neg and ($opt_verbose > 1)); last RBLS unless $cmp; mylogs $syslog_priority, "count1 $mykey: \"$mymin\" -> \"$rcount\"" if ($opt_verbose > 1); $rcount++ if ( rbl_check ($mykey, $cmp, $myitem) ); mylogs $syslog_priority, "count2 $mykey: \"$mymin\" -> \"$rcount\"" if ($opt_verbose > 1); $myresult = ( $rcount >= $mymin ); $myresult = not($myresult) if $neg; mylogs $syslog_priority, "match $mykey: ".($myresult ? "TRUE" : "FALSE") if ($opt_verbose > 1); last RBLS if $myresult; }; # # date/time check } elsif ( ($mykey eq $COMP_DATE) or ($mykey eq $COMP_TIME) ) { DATS: foreach $cmp (@{$mymask}) { mylogs $syslog_priority, "compare-date $mykey: \"$myitem\" -> \"$cmp\"" if ($opt_verbose > 1); $cmp = $neg if ($neg = deneg_item($cmp)); mylogs $syslog_priority, "negate $mykey: \"$myitem\" -> \"$cmp\"" if ($neg and ($opt_verbose > 1)); next DATS unless $cmp; my($isec,$imin,$ihour,$iday,$imon,$iyear) = split (',', $myitem); my($rmin,$rmax) = split ('-', $cmp); my($idat); if ( $mykey eq $COMP_DATE ) { $idat = ($iyear + 1900) . ((($imon+1) < 10) ? '0'.($imon+1) : ($imon+1)) . (($iday < 10) ? '0'.$iday : $iday); $rmin = ($rmin) ? join ('', reverse split ('\.', $rmin)) : $idat; $rmax = ($rmax) ? join ('', reverse split ('\.', $rmax)) : $idat; } else { $idat = (($ihour < 10) ? '0'.$ihour : $ihour) . (($imin < 10) ? '0'.$imin : $imin) . (($isec < 10) ? '0'.$isec : $isec); $rmin = ($rmin) ? join ('', split ('\:', $rmin)) : $idat; $rmax = ($rmax) ? join ('', split ('\:', $rmax)) : $idat; }; $myresult = (($rmin <= $idat) and ($rmax >= $idat)); $myresult = not($myresult) if $neg; mylogs $syslog_priority, "match $mykey: ".($myresult ? "TRUE" : "FALSE") if ($opt_verbose > 1); last DATS if $myresult; }; # # default: compare values } else { VALS: foreach $cmp (@{$mymask}) { mylogs $syslog_priority, "compare-default $mykey: \"$myitem\" -> \"$cmp\"" if ($opt_verbose > 1); $cmp = $neg if ($neg = deneg_item($cmp)); mylogs $syslog_priority, "negate $mykey: \"$myitem\" -> \"$cmp\"" if ($neg and ($opt_verbose > 1)); next VALS unless $cmp; if ( $cmp =~ /^$COMP_VAR\s*\(?\s*(.+?)\s*\)?$/ ) { $cmp = $request{$1}; mylogs $syslog_priority, "substitute $mykey: \"$myitem\" -> \"$cmp\"" if ($opt_verbose > 1); next VALS unless $cmp; $myresult = ( lc($myitem) eq lc($cmp) ) if $myitem; } else { $myresult = ( $myitem =~ /$cmp/i ) if $myitem; }; $myresult = not($myresult) if $neg; mylogs $syslog_priority, "match $mykey: ".($myresult ? "TRUE" : "FALSE") if ($opt_verbose > 1); last VALS if $myresult; }; }; return $myresult; } # # compare request against a single rule # sub compare_rule { (my($index), my($date), my(%request)) = @_; my($mykey,$myresult,$myitem,$cmp,$num); mylogs $syslog_priority, "rule: $index, id: $Rules[$index]{$COMP_ID}" if ($opt_verbose > 1); ITEM: for $mykey ( keys %{$Rules[$index]} ) { # always true next ITEM if ( $myresult = (($mykey eq $COMP_ID) or ($mykey eq $COMP_ACTION)) ); next ITEM if ( $myresult = (($mykey eq $COMP_RBL_CNT) or ($mykey eq $COMP_RHSBL_CNT)) ); # integration at this point enables redefining scores within ruleset if ($mykey eq $COMP_SCORES) { modify_score ($Rules[$index]{$mykey},$Rules[$index]{$COMP_ACTION}); undef($myresult); } else { # prepare rbl/rhsbl lookups if ( ($mykey eq $COMP_RBL_KEY) or ($mykey eq $COMP_RHSBL_KEY) ) { $cmp = $request{"client_name"}."[".$request{"client_address"}."]"; $num = ( ($mykey eq $COMP_RBL_KEY) ? $Rules[$index]{$COMP_RBL_CNT} : $Rules[$index]{$COMP_RHSBL_CNT} ); $num = 1 if $num < 1; # prepare date check } elsif ( ($mykey eq $COMP_DATE) or ($mykey eq $COMP_TIME) ) { $cmp = $date; $num = 0; # default: compare against request attribute } else { $cmp = $request{$mykey}; $num = 0; }; $myresult = (compare_item($mykey, $Rules[$index]{$mykey}, $num, $cmp, %request)); }; last ITEM if !($myresult); }; return $myresult; } ### SUB access policy # # access policy routine # sub smtpd_access_policy { my(%myattr) = @_; my($myaction) = $default_action; my($index) = 1; my($now) = time; my($date) = join(',', localtime($now)); my($mykey,$cacheid,$myline,$matched,$checkreq) = ""; # Request cache enabled? if ( $REQUEST_MAX_CACHE > 0 ) { # construct request identifier REQITEM: foreach $checkreq (sort keys %myattr) { next REQITEM unless $myattr{$checkreq}; next REQITEM if ( ($checkreq eq "instance") or ($checkreq eq "queue_id") ); next REQITEM if ( $opt_cache_no_size and ($checkreq eq "size") ); if ( $opt_cache_domain_only and ($checkreq eq "recipient") ) { $myattr{$checkreq} =~ /^[^@]+(@[^@]+)$/; $cacheid .= $1.";" } else { $cacheid .= $myattr{$checkreq}.";" }; }; # wipe out old cache entries foreach $checkreq (keys %Request_Cache) { if ( (($now - $Request_Cache{$checkreq}{"time"}) > $REQUEST_MAX_CACHE) ) { delete $Request_Cache{$checkreq}; mylogs $syslog_priority, "deleted request-cache $checkreq after ".($now - $Request_Cache{$checkreq}{"time"})." seconds" if $opt_verbose; }; }; }; # check cache or if ( ($REQUEST_MAX_CACHE > 0) and (exists($Request_Cache{$cacheid}{$COMP_ACTION})) ) { $Counter_Hits++; $myaction = $Request_Cache{$cacheid}{$COMP_ACTION}; if ( $Request_Cache{$cacheid}{"hit"} ) { $Matches{$Request_Cache{$cacheid}{$COMP_ID}}++; mylogs $syslog_priority, "[CACHE] rule=".get_rule_by_id ($Request_Cache{$cacheid}{$COMP_ID}) . ", id=".$Request_Cache{$cacheid}{$COMP_ID} . ", client=".$myattr{"client_name"}."[".$myattr{"client_address"}."]" . ", sender=".$myattr{"sender"} . ", recipient=".$myattr{"recipient"} . ", helo=".$myattr{"helo_name"} . ", proto=".$myattr{"protocol_name"} . ", state=".$myattr{"protocol_state"} . ", action=".$Request_Cache{$cacheid}{$COMP_ACTION}; }; # check rules } else { my($score) = 0; # load config if '-I' was set read_config if $opt_instantconfig; if ($#Rules < 0) { warn "critical: no rules found - i feel useless (have you set -f or -r?)"; } else { RULE: for ($index=0;$index<=$#Rules;$index++) { # compare request against rule next unless exists $Rules[$index]; $matched = compare_rule ($index, $date, %myattr); # matched? prepare logline, increase counters if ($matched) { $myaction = $Rules[$index]{$COMP_ACTION}; $Matches{$Rules[$index]{$COMP_ID}}++; $myline = "rule=".$index . ", id=".$Rules[$index]{$COMP_ID} . ", client=".$myattr{"client_name"}."[".$myattr{"client_address"}."]" . ", sender=".$myattr{"sender"} . ", recipient=".$myattr{"recipient"} . ", helo=".$myattr{"helo_name"} . ", proto=".$myattr{"protocol_name"} . ", state=".$myattr{"protocol_state"}; # check for postfwd action if ($myaction =~ /^([a-zA-Z]{4,5})\(([^\)]*)\)$/) { my($mycmd,$myarg) = ($1, $2); # jump() command if ($mycmd eq "jump") { my($ruleno) = get_rule_by_id ($myarg); if ($ruleno) { mylogs $syslog_priority, "[RULES] ".$myline.", jump to rule $ruleno (id $myarg)"; $index = $ruleno - 1; } else { warn "[RULES] ".$myline." - error: jump failed, can not find rule-id ".$myarg." - ignoring"; }; $myaction = $default_action; # wait() command } elsif ($mycmd eq "wait") { mylogs $syslog_priority, "[RULES] ".$myline.", delaying for $myarg seconds"; sleep $myarg; $myaction = $default_action; # score() command } elsif ($mycmd eq "score") { $myaction = $default_action; if ($myarg =~/^[-+]*[0-9]{1,4}(\.[0-9]{1,2})*$/) { $score += $myarg; mylogs $syslog_priority, "[SCORE] ".$myline.", modifying score about ".$myarg." points to ". $score; my($max_score); foreach $max_score (reverse sort keys %MAX_SCORES) { if ($score >= $max_score) { $myaction=$MAX_SCORES{$max_score}; $myline .= ", action=".$myaction." (score ".$score."/".$max_score.")"; mylogs $syslog_priority, "[RULES] ".$myline; last RULE; }; }; } else { mylogs $syslog_priority, "[RULES] ".$myline.", invalid value for score \"$myarg\" - ignoring"; }; # note() command } elsif ($mycmd eq "note") { mylogs $syslog_priority, "[RULES] ".$myline." - note: ".$myarg if $myarg; $myaction = $default_action; # quit() command } elsif ($mycmd eq "quit") { warn "[RULES] ".$myline." - critical: quit (".$myarg.")"; exit($myarg); # file() command } elsif ($mycmd eq "file") { warn "[RULES] ".$myline." - error: command file() has not been implemented yet - ignoring"; $myaction = $default_action; # exec() command } elsif ($mycmd eq "exec") { warn "[RULES] ".$myline." - error: command exec() has not been implemented yet - ignoring"; $myaction = $default_action; } else { warn "[RULES] ".$myline." - error: unknown command \"".$1."\" - ignoring"; $myaction = $default_action; }; # normal rule. returns $action. } else { $myline .= ", action=".$Rules[$index]{$COMP_ACTION}; mylogs $syslog_priority, "[RULES] ".$myline; last RULE; }; } else {undef($myline)}; }; }; # update cache $Request_Cache{$cacheid}{"time"} = $now; $Request_Cache{$cacheid}{$COMP_ACTION} = $myaction; $Request_Cache{$cacheid}{"hit"} = $matched; $Request_Cache{$cacheid}{$COMP_ID} = $Rules[$index]{$COMP_ID} if $matched; }; $myaction = $default_action if ($opt_test or !($myaction)); return $myaction; } # # process request # sub process_request_line { my($client) = shift; my($request) = @_; my($output) = ""; if ($request =~ /^([^=\r\n]+)=([^\r\n]*)\r?\n/) { $attr{$client}{substr($1, 0, 512)} = substr($2, 0, 512); } elsif ($request eq "\n") { if ($opt_verbose > 1) { for (keys %{$attr{$client}}) { mylogs $syslog_priority, "Attribute: $_=$attr{$client}{$_}"; }; }; fatal_exit "unrecognized request type: '$attr{$client}{request}'" unless $attr{$client}{"request"} eq "smtpd_access_policy"; my($action) = smtpd_access_policy(%{$attr{$client}}); mylogs $syslog_priority, "Action: $action" if $opt_verbose; $output = "action=$action\n\n"; delete $attr{$client}; $Counter_Requests++; $Counter_Interval++; } else { chop; warn "error: ignoring garbage: \"".$request."\""; }; return $output; }; #### MAIN #### # parse command-line GetOptions ( 't|test' => \$opt_test, 'v|verbose' => sub { $opt_verbose++ }, 'l|logname=s' => \$syslog_name, 'n|nodns' => \$opt_nodns, 'd|daemon' => \$opt_daemon, 'I|instantcfg' => \$opt_instantconfig, 'P|perfmon' => \$opt_perfmon, 'L|stdoutlog' => \$opt_stdoutlog, 'i|interface=s' => \$net_interface, 'p|port=s' => \$net_port, 'R|chroot=s' => \$net_chroot, 'pid|pidfile=s' => \$net_pid, 'u|user=s' => \$net_user, 'g|group=s' => \$net_group, 'c|cache=i' => \$REQUEST_MAX_CACHE, 'cache-rdomain-only' => \$opt_cache_domain_only, 'cache-no-size' => \$opt_cache_no_size, 'S|summary:i' => \$opt_summary, 's|scores=s' => \%opt_scores, 'f|file=s' => sub{ my($opt,$value) = @_; push (@Configs, $opt.','.$value) }, 'r|rule=s' => sub{ my($opt,$value) = @_; push (@Configs, $opt.','.$value) }, 'V|version' => sub{ print "$NAME $VERSION\n"; exit 1; }, 'C|showconfig' => \$opt_showconfig, 'h|H|?|help|Help|HELP' => sub{ pod2usage (-msg => "\nPlease see \"".$NAME." -m\" for detailed instructions.\n", -verbose => 1); }, 'm|M|manual' => sub{ # contructing command string (de-tainting $0) $cmd_manual .= ($0 =~ /^([-\@\/\w. ]+)$/) ? " \"".$1 : " \"".$NAME; $cmd_manual .= "\" | ".$cmd_pager; exec_cmd ($cmd_manual); exit 1; }, ) or pod2usage (-msg => "\nPlease see \"".$NAME." -m\" for detailed instructions.\n", -verbose => 1); # init syslog setlogsock $syslog_socktype; $syslog_options = 'cons,pid' unless $opt_daemon; openlog $syslog_name, $syslog_options, $syslog_facility; # read configuration read_config; if ($opt_showconfig) { show_config; exit 1; }; # check modes mylogs "notice", "TESTMODE: set - will return ".$default_action." to all requests" if ($opt_test); if ($opt_verbose) { $opt_summary ||= $Stat_Interval_Time; mylogs "notice", "VERBOSE: set"; }; # -n - skip dns based checks mylogs "notice", "NODNS: set - will skip all dns based checks" if $opt_nodns; # init scores from command-line map ( modify_score (each %opt_scores), (keys %opt_scores) ); # get summary interval time, set next display time $Stat_Interval_Time = $opt_summary if $opt_summary; $Starttime = time; $Startdate = strftime("%a, %d %b %Y %T %Z", localtime); # de-taint arguments $net_interface = ( $net_interface =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/ ) ? $1 : $def_net_interface; $net_port = ( $net_port =~ /^(\d+)$/ ) ? $1 : $def_net_port; $net_user = ( $net_user =~ /^([\w]+)$/ ) ? $1 : $def_net_user; $net_group = ( $net_group =~ /^([\w]+)$/ ) ? $1 : $def_net_group; $net_chroot = ( $net_chroot =~ /^([-\@\/\w. ]+)$/ ) ? $1 : $def_net_chroot; $net_pid = ( $net_pid =~ /^([-\@\/\w. ]+)$/ ) ? $1 : $def_net_pid; $syslog_name = ( $syslog_name =~ /^([-\w.]+)$/ ) ? $1 : $NAME; # Unbuffer standard output. select((select(STDOUT), $| = 1)[0]); if ($opt_daemon) { # # Networking # # The networking part is implemented as non-forking server. It handles multiple client # connections via non-blocking sockets using queueing via IO::Multiplex. # Please check http://search.cpan.org/dist/Net-Server/lib/Net/Server/Multiplex.pm for info. # # create server object my $server = bless { server => { commandline => [$0, @CommandArgs], port => $net_port, host => $net_interface, proto => $def_net_proto, user => $net_user, group => $net_group, chroot => $net_chroot ? $net_chroot : undef, setsid => $opt_daemon ? 1 : undef, pid_file => $net_pid ? $net_pid : undef, log_level => $opt_perfmon ? 0 : ($opt_verbose ? 3 : 2), log_file => $opt_perfmon ? undef : 'Sys::Syslog', syslog_logsock => $syslog_socktype, syslog_facility => $syslog_facility, syslog_ident => $syslog_name, }, }, 'postfwd'; ## run the servers main loop $server->run; # reload config on HUP signal sub sig_hup () { mylogs "notice", "catched HUP signal - reloading ruleset"; show_stats; read_config; }; # show stats on exit sub pre_server_close_hook() { mylogs "notice", "terminating..." if $opt_summary; end_program; }; # init sub pre_loop_hook() { # install signal handlers $SIG{__WARN__} = sub { mylogs "crit", "warning - \"@_\""; }; $SIG{__DIE__} = sub { fatal_exit "last err: \"$!\", detail: \"@_\""; }; $SIG{ALRM} = sub { show_stats; alarm ($Stat_Interval_Time); } if $opt_summary; mylogs $syslog_priority, "successfully installed signal handlers" if $opt_verbose; # process init umask 0077; setlocale(LC_ALL, 'C'); $0 = $0." ".join(" ",@CommandArgs); chdir "/" or fatal_exit "Could not chdir to /"; # set first status interval time if ($opt_summary) { alarm ($Stat_Interval_Time); mylogs $syslog_priority, "Setting status interval to $Stat_Interval_Time seconds"; }; # let's go mylogs $syslog_priority, "$NAME $VERSION ready for input"; }; # main loop sub mux_input() { my ($self, $mux, $client, $mydata) = @_; my ($request,$answer) = undef; # check request line and print output while ( $$mydata =~ s/(.*\n)// ) { # check request line and print output if ($request = $1) { print $client $answer if ( $answer = process_request_line $client, $request ); }; }; }; } else { # main loop for command line use # regexp is used to keep it similar to the server main loop my($request,$answer) = undef; while (<>) { # check request line and print output /(.*\n)/; if ($request = $1) { myprint $answer if ( $answer = process_request_line 0, $request ); }; }; # finishing end_program; }; die "should never see me..."; ## EOF __END__ =head1 NAME postfwd - postfix firewall daemon =head1 SYNOPSIS postfwd [OPTIONS] SOURCE1, SOURCE2, ... Ruleset: (at least one, multiple use is allowed): -f, --file reads rules from -r, --rule adds to config Scoring: -s, --scores = returns when score exceeds Networking: -d, --daemon run postfwd as daemon -i, --interface listen on interface -p, --port listen on port -u, --user set uid to user -g, --group set gid to group -R, --chroot chroot the daemon to -l, --logname