#!/usr/local/bin/perl
#
# Hunnypot: Copyright 2004 Jeremy Kister
# Released under Perl's Artistic License.
# Function: make a tcprules file with information from the honeypot
# Author: Jeremy Kister (hunnypot-devel @t jeremykister.com) 
#

# put any rules that you need in /var/qmail/etc/tcp.smtp.template

use strict;
use DBI;

my $dbun = 'dbun';
my $dbpw = 'dbpw';
my $driver = 'mysql';
my $dsn = "DBI:${driver}:";
my $dbserver = 'mysql.example.net';
my $dbname = 'dbname';

if($driver =~ /Sybase/){
   $dsn .= "server=$dbserver";
}else{
   $dsn .= "host=${dbserver};database=${dbname}";
}

open(T, '/var/qmail/etc/tcp.smtp.template') || die "cannot open tcp.smtp.template: $!\n";
open(N, '>/var/qmail/etc/tcp.smtp.$$') || die "cannot write to tcp.smtp.tmp.$$: $!\n";
while(<T>){
	print N;
}
close T;

my $old = ($^T - 172800);
my $dbh = DBI->connect($dsn, $dbun, $dbpw, {RaiseError => 1});
my $sql = 'SELECT distinct ip FROM hunnypot WHERE timestamp > ' . $old;
my $sth = $dbh->prepare($sql);
$sth->execute;
while(my $row = $sth->fetchrow_hashref){
	my $ip = $row->{ip};
	my $sqla = 'SELECT times FROM hunnypot WHERE ip = ' . $dbh->quote($ip);
	my $stha = $dbh->prepare($sqla);
	$stha->execute;
	my $count=0;
	while(my $rowa = $stha->fetchrow_hashref){
		my $times = $rowa->{times};
		$count += $times;
	}
	if($count > 3){
		print N "${ip}:allow,REASON=\"hunnypot\",MAXCONNIP=\"1\",DIEMSG=\"421 please try later.\",RBLSMTPD=\"See http://www.example.net/mail-abuse/\"\n";
	}
}
$dbh->disconnect;

print N ':allow,MAXCONNIP="2",MAXCONNC="8",DIEMSG="421 please try later."' . "\n";
close N;
rename('/var/qmail/etc/tcp.smtp.$$','/var/qmail/etc/tcp.smtp') || die "cannot rename: $!\n";

