#!/usr/local/bin/perl -w # $Id: spam_filter.pm,v 1.1 2006/08/23 04:47:10 candy Exp candy $ use Socket; # inet_ntoa use strict; sub resolve($) { my ($host) = @_; my ($name, $aliases, $addrtype, $length, @addrs) = gethostbyname($host); my $remote = ""; if (defined($addrtype) && $addrtype == 2) { $remote = inet_ntoa($addrs[0]); } return $remote; } # sub rbl_match($$$) { my ($rbl, $ip, $host) = @_; my $len = length($rbl); my $match = 0; if (defined($ip)) { $match ||= ($rbl eq $ip) || ($rbl =~ /\.$/ && substr($ip, 0, $len) eq $rbl) } if (defined($host)) { $host =~ tr/A-Z/a-z/; $rbl =~ tr/A-Z/a-z/; $match ||= ($rbl eq $host) || ($rbl =~ /^\./ && substr($host, length($host) - $len, $len) eq $rbl); } return $match; } sub get_msg_links($) { my ($msg) = @_; my @list = (); while ($msg =~ /http:\/\/([a-zA-Z0-9\.\/\-+#_?~&%=^\@:;]+)/) { my $host = $1; $msg = $'; $host =~ s/\/.*//; push(@list, $host); } return @list; } # URL based spam filter # usage: # ($block, $reason) = spam_filter($msg, $url, $remote_ip, $remote_host); # if ($block) { # printf(STDERR "client %s(%s) denid by %s\n", $remore_ip, $remote_host, $reason); # } # sub spam_filter($$$$) { my ($msg, $url, $ip, $host) = @_; my $block = 0; my $reason = ""; my @hosts = get_msg_links($msg); if (defined($url) && $url ne "") { my $h = $url; $h =~ s/http:\/\///; $h =~ s/\/.*//; push(@hosts, $h); } if (open(RBL, ".htrbl")) { my $lbuf; while ($block == 0 && ($lbuf = )) { chomp($lbuf); $lbuf =~ s/#.*//; $lbuf =~ s/[ \t]*$//; if ($lbuf ne "") { if (rbl_match($lbuf, $ip, $host)) { $reason = "rbl " . $lbuf; $block = 1; } my $i = 0; while ($block == 0 && $i < $#hosts + 1) { my $link_host = $hosts[$i++]; my $link_ip = resolve($link_host); if (rbl_match($lbuf, $link_ip, $link_host)) { $reason = "bad link to " . $link_ip . "(" . $link_host . ")"; $block = 2; } } } } close(RBL); } if ($block == 0 && $msg =~ /sex/ ) { $reason = "contents filter"; $block = 1; } return ($block, $reason); } # my ($msg, $url, $remote_ip, $remote_host) = ($ARGV[0], $ARGV[1], $ARGV[2], $ARGV[3]); # printf("%s %s %s %s\n", $msg, $url, $remote_ip, $remote_host); # my ($block, $reason) = spam_filter($msg, $url, $remote_ip, $remote_host); #if ($block) { # printf(STDERR "client %s(%s) %s by %s\n", $ARGV[2], $ARGV[3], "denied", $reason); #} 1;