#!/usr/bin/perl -T -w # # 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.10pre1'; # 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"; # always true our($COMP_ACTION) = "action"; our($COMP_ID) = "id"; # separator #our($COMP_SEPARATOR) = "="; #our($COMP_SEPARATOR) = "[=\~\<\>]?="; our($COMP_SEPARATOR) = "[=\~\<\>]?=|=[=\~\<\>]"; # macros our($COMP_ACL) = "[\&][\&]"; # negation our($COMP_NEG) = "[\!][\!]"; # variables our($COMP_VAR) = "[\$][\$]"; # 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_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, %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 ); # # these subroutines will integrate additional attributes to a request # call: %result = plugin_sub{foo} (%request) # save: $result{$_} # our(%plugin_sub) = ( # enables the execution of rules on the # specified postfwd version "version" => sub { my(%request) = @_; my(%result) = (); $result{$_} = $NAME." ".$VERSION; return %result; }, "sender_localpart" => sub { my(%request) = @_; my(%result) = (); $request{sender} =~ /(.*)@[^@]*$/; $result{$_} = $1; return %result; }, "sender_domain" => sub { my(%request) = @_; my(%result) = (); $request{sender} =~ /@([^@]*)$/; $result{$_} = $1; return %result; }, "recipient_localpart" => sub { my(%request) = @_; my(%result) = (); $request{recipient} =~ /(.*)@[^@]*$/; $result{$_} = $1; return %result; }, "recipient_domain" => sub { my(%request) = @_; my(%result) = (); $request{recipient} =~ /@([^@]*)$/; $result{$_} = $1; return %result; }, ); ### 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; $Counter_Interval ||= 0; $Counter_Top ||= 0; $Counter_Hits ||= 0; my($totalreqpermin) = ( ((($now - $Starttime) > 0) ? ($Counter_Requests / ($now - $Starttime)) : 0 ) * 60); my($lastreqpermin) = ($Counter_Interval / (((defined $Stat_Interval_Time) and ($Stat_Interval_Time > 0)) ? $Stat_Interval_Time : 1)) * 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(@mypair) = (); my($mykey, $myvalue, $mycomp); if ( $myline = acl_parser ($myline) ) { unless ( $myline =~ /^\s*[^=\s]+\s*$COMP_SEPARATOR\s*([^;\s]+\s*)+(;\s*[^=\s]+\s*$COMP_SEPARATOR\s*([^;\s]+\s*)+)*[;\s]*$/ ) { warn "warning: ignoring invalid line ".$mynum.": \"".$myline."\""; } else { # separate items foreach (split /;/, $myline) { # remove whitespaces around s/^\s*(.*?)\s*($COMP_SEPARATOR)\s*(.*?)\s*$/$1$2$3/; $mycomp = $2; @mypair = split /$COMP_SEPARATOR/; $mykey = shift (@mypair); $myvalue = join ("=", @mypair); if ($mykey =~ /^$COMP_CSV$/) { push ( @{$myrule{$mykey}}, (split /[,\s]+/, $mycomp.";".$myvalue) ); } elsif ($mykey =~ /^$COMP_SINGLE$/) { $myrule{$mykey} = $myvalue; } else { push ( @{$myrule{$mykey}}, $mycomp.";".$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 ( (defined $Config_Cache{$myitem}{lastread}) and ($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 .= "; " unless $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) ) { mylogs $syslog_priority, "removing rbl-cache for $checkip on $myrbl" if $opt_verbose; delete $RBL_Cache{$myrbl}{$checkip}; }; }; # 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; } # # extracts some request information # sub plugin { my(%request) = @_; my(%result) = (); foreach (keys %plugin_sub) { %result = (%result, &{$plugin_sub{$_}}(%request)) if (defined $plugin_sub{$_}); }; map { $result{$_} = '' unless $result{$_} } (keys %result); return %result; }; # # returns content of !!() negation # sub deneg_item { my($val) = (defined $_[0]) ? $_[0] : ''; return ( ($val =~ /^$COMP_NEG\s*\(?\s*(.+?)\s*\)?$/) ? $1 : '' ); }; # # resolves $$() variables # sub devar_item { my($cmp,$val,$myitem,%request) = @_; my($pre,$post,$var,$myresult) = ''; while ( ($val =~ /(.*)$COMP_VAR\s*(\w+)(.*)/g) or ($val =~ /(.*)$COMP_VAR\s*\((\w+)\)(.*)/g) ) { ($pre,$var,$post) = ($1,$2,$3); if (defined $request{$var}) { $myresult=$val=$pre.$request{$var}.$post; }; mylogs $syslog_priority, "substitute : \"$myitem\" \"$cmp\" \"$val\"" if ($opt_verbose > 1); }; return $myresult; }; # # compare item subroutines # must take compare_item_foo ( $COMPARE_TYPE, $RULEITEM, $REQUESTITEM, %REQUEST, %REQUESTINFO ); # sub compare_item_cidr { my($cmp,$val,$myitem,%request) = @_; my($myresult); mylogs $syslog_priority, "type cidr : \"$myitem\" \"$cmp\" \"$val\"" if ($opt_verbose > 1); my $myref = Net::CIDR::Lite->new($val); $myresult = ( $myref->find($myitem) ); return $myresult; }; sub compare_item_numeric { my($cmp,$val,$myitem,%request) = @_; my($myresult); mylogs $syslog_priority, "type numeric : \"$myitem\" \"$cmp\" \"$val\"" if ($opt_verbose > 1); $myitem ||= "0"; $val ||= "0"; if (($cmp eq '<=') or ($cmp eq '=<')) { $myresult = ($myitem <= $val); } elsif ($cmp eq '==') { $myresult = ($myitem == $val); } else { $myresult = ($myitem >= $val); }; return $myresult; }; sub compare_item_rbl { my($cmp,$val,$myitem,%request) = @_; my($myresult) = not($opt_nodns); mylogs $syslog_priority, "type rbl : \"$myitem\" \"$cmp\" \"$val\"" if ($opt_verbose > 1); $myresult = ( rbl_check ($COMP_RBL_KEY, $val, $myitem) ) if $myresult; return $myresult; }; sub compare_item_rhsbl { my($cmp,$val,$myitem,%request) = @_; my($myresult) = not($opt_nodns); mylogs $syslog_priority, "type rhsbl : \"$myitem\" \"$cmp\" \"$val\"" if ($opt_verbose > 1); $myresult = ( rbl_check ($COMP_RHSBL_KEY, $val, $myitem) ) if $myresult; return $myresult; }; sub compare_item_date { my($cmp,$val,$myitem,%request) = @_; my($myresult); mylogs $syslog_priority, "type date : \"$myitem\" \"$cmp\" \"$val\"" if ($opt_verbose > 1); my($isec,$imin,$ihour,$iday,$imon,$iyear) = split (',', $myitem); my($rmin,$rmax) = split ('-', $val); my($idat); $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; $myresult = (($rmin <= $idat) and ($rmax >= $idat)); return $myresult; }; sub compare_item_time { my($cmp,$val,$myitem,%request) = @_; my($myresult); mylogs $syslog_priority, "type time : \"$myitem\" \"$cmp\" \"$val\"" if ($opt_verbose > 1); my($isec,$imin,$ihour,$iday,$imon,$iyear) = split (',', $myitem); my($rmin,$rmax) = split ('-', $val); my($idat); $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)); return $myresult; }; sub compare_item_default { my($cmp,$val,$myitem,%request) = @_; my($var,$myresult); mylogs $syslog_priority, "type default : \"$myitem\" \"$cmp\" \"$val\"" if ($opt_verbose > 1); # substitute check for $$vars in action $val = $var if ( $var = devar_item ($cmp,$val,$myitem,%request) ); # backward compatibility $cmp = '==' if ( ($var) and ($cmp eq '=') ); if ($cmp eq '==') { $myresult = ( lc($myitem) eq lc($val) ) if $myitem; } elsif (($cmp eq '<=') or ($cmp eq '=<')) { $myresult = ($myitem <= $val); } elsif (($cmp eq '>=') or ($cmp eq '=>')) { $myresult = ($myitem >= $val); } else { $myresult = ( $myitem =~ /$val/i ) if $myitem; }; return $myresult; }; # # compare item main # use: compare_item ( $TYPE, $RULEITEM, $MINIMUMHITS, $REQUESTITEM, %REQUEST, %REQUESTINFO ); # sub compare_item { my($mykey,$mymask,$mymin,$myitem, %request) = @_; my($val,$cmp,$neg,$myresult,$compare_proc); my($rcount) = 0; $mymin ||= 1; # # determine the right compare function if ( $mykey eq $COMP_NETWORK_CIDRS ) { $compare_proc = \&compare_item_cidr; } elsif ( $mykey eq $COMP_RBL_KEY ) { $compare_proc = \&compare_item_rbl; } elsif ( $mykey eq $COMP_RHSBL_KEY ) { $compare_proc = \&compare_item_rhsbl; } elsif ( $mykey eq $COMP_DATE ) { $compare_proc = \&compare_item_date; } elsif ( $mykey eq $COMP_TIME ) { $compare_proc = \&compare_item_time; } elsif ( $mykey =~ /^$COMP_NUMERIC_ITEMS$/ ) { $compare_proc = \&compare_item_numeric; } else { $compare_proc = \&compare_item_default; }; # # now compare request and every single rule item ITEM: foreach (@{$mymask}) { ($cmp, $val) = split ";"; next ITEM unless ($cmp and $val); mylogs $syslog_priority, "compare $mykey: \"$myitem\" \"$cmp\" \"$val\"" if ($opt_verbose > 1); $val = $neg if ($neg = deneg_item($val)); mylogs $syslog_priority, "negate $mykey: \"$myitem\" \"$cmp\" \"$val\"" if ($neg and ($opt_verbose > 1)); next ITEM unless $val; $myresult = &{$compare_proc}($cmp,$val,$myitem,%request); mylogs $syslog_priority, "match $mykey: ".($myresult ? "TRUE" : "FALSE") if ($opt_verbose > 1); $myresult = not($myresult) if $neg; $rcount++ if $myresult; $myresult = ( $rcount >= $mymin ); mylogs $syslog_priority, "count $mykey: request=$rcount minimum: $mymin result: ".($myresult ? "TRUE" : "FALSE") if ($opt_verbose > 1); last ITEM if $myresult; }; return $myresult; }; # # compare request against a single rule # sub compare_rule { my($index,$date,%request) = @_; my($mykey,$myresult,$myitem,$val,$cmp); my($num) = 1; 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) ) { $val = $request{"client_name"}."[".$request{"client_address"}."]"; $num = ( ($mykey eq $COMP_RBL_KEY) ? $Rules[$index]{$COMP_RBL_CNT} : $Rules[$index]{$COMP_RHSBL_CNT} ); # prepare date check } elsif ( ($mykey eq $COMP_DATE) or ($mykey eq $COMP_TIME) ) { $val = $date; # default: compare against request attribute } else { $val = $request{$mykey}; }; $myresult = (compare_item($mykey, $Rules[$index]{$mykey}, $num, $val, %request)); }; last ITEM unless $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 cache 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 ( defined $plugin_sub{$checkreq} ); 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}.";" }; }; mylogs $syslog_priority, "created cache-id: $cacheid" if ($opt_verbose > 1); # wipe out old cache entries foreach $checkreq (keys %Request_Cache) { if ( (($now - $Request_Cache{$checkreq}{"time"}) > $REQUEST_MAX_CACHE) ) { mylogs $syslog_priority, "removing request-cache $checkreq after ".($now - $Request_Cache{$checkreq}{"time"})." seconds" if ($opt_verbose > 1); delete $Request_Cache{$checkreq}; }; }; }; # 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"} . ", delay=".(time - $now)."s" . ", action=".$Request_Cache{$cacheid}{$COMP_ACTION}; }; # check rules } else { my($score) = 0; my($var) = ''; # 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 { if ( my(%plugin_attr) = plugin (%myattr) ) { %myattr = (%myattr, %plugin_attr); map {mylogs $syslog_priority, "Add key: $_=$plugin_attr{$_}" } (keys %plugin_attr) if ($opt_verbose > 1); }; 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}}++; # substitute check for $$vars in action $myaction = $var if ( $var = devar_item ("=",$myaction,"action",%myattr) ); $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 =~/^([\+\-\*\/\=]?)(\d+)[\.,](\d+)$/) { my($mod, $val) = ($1, $2 + $3 / 10); if ($mod eq '-') { $score -= $val; } elsif ($mod eq '*') { $score *= $val; } elsif ($mod eq '/') { $score /= $val; } elsif ($mod eq '=') { $score = $val; } else { $score += $val; }; $score =~ s/^(\-?\d+)([\.,]\d\d?)?.*/$1$2/; 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 .= ", delay=".(time - $now)."s, 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 .= ", delay=".(time - $now)."s, action=".$myaction; mylogs $syslog_priority, "[RULES] ".$myline; last RULE; }; } else {undef($myline)}; }; }; # update cache if ( $REQUEST_MAX_CACHE > 0 ) { $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; }; #### 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); $opt_verbose = 0 unless $opt_verbose; # 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 ||= $def_net_interface; $net_port ||= $def_net_port; $net_user ||= $def_net_user; $net_group ||= $def_net_group; $net_chroot ||= $def_net_chroot; $net_pid ||= $def_net_pid; $syslog_name ||= $NAME; $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; my (%myattr) = (); # check request and print output while ( $$mydata =~ s/^([^\r\n]*)\r?\n// ) { # check request line and print output next unless defined $1; $request = $1; if ($request =~ /([^=]+)=(.*)/) { $myattr{substr($1, 0, 512)} = substr($2, 0, 512); } elsif ($request eq '') { if ($opt_verbose > 1) { for (keys %myattr) { mylogs $syslog_priority, "Client: $client Attribute: $_=$myattr{$_}"; }; }; unless ($myattr{"request"} eq "smtpd_access_policy") { warn "ignoring unrecognized request type: '$myattr{request}'" } else { my($action) = smtpd_access_policy(%myattr); mylogs $syslog_priority, "Client: $client Action: $action" if $opt_verbose; print $client "action=$action\n\n"; $Counter_Requests++; $Counter_Interval++; }; } else { chop; warn "error: ignoring garbage from $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; my (%myattr) = (); while (<>) { # check request and print output s/^([^\r\n]*)\r?\n//; next unless defined $1; $request = $1; if ($request =~ /([^=]+)=(.*)/) { $myattr{substr($1, 0, 512)} = substr($2, 0, 512); } elsif ($request eq '') { if ($opt_verbose > 1) { for (keys %myattr) { mylogs $syslog_priority, "Attribute: $_=$myattr{$_}"; }; }; unless ($myattr{"request"} eq "smtpd_access_policy") { warn "ignoring unrecognized request type: '$myattr{request}'" } else { my($action) = smtpd_access_policy(%myattr); mylogs $syslog_priority, "Action: $action" if $opt_verbose; myprint "action=$action\n\n"; $Counter_Requests++; $Counter_Interval++; }; } else { chop; warn "error: ignoring garbage \"".$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