3 # OSSEC active-response script to store a suspicious IP address in a MySQL table.
5 # Available actions are:
6 # 'add' - Create a new record in the MySQL DB
7 # 'delete' - Remove a existing record
11 # 2010/10/24 xavir@rootshell.be Created
18 # -----------------------
19 # DB access configuration
20 # -----------------------
21 my $db_name = 'ossec_active_lists';
22 my $db_user = 'suspicious';
23 my $db_pass = 'xxxxxxxxxx';
25 my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
26 my $theTime = sprintf("%d-%02d-%02d %02d:%02d:%02d",
27 $yearOffset+1900, $month+1, $dayOfMonth, $hour, $minute, $second);
29 my $nArgs = $#ARGV + 1;
31 print STDERR "Usage: active-list.pl <action> <username> <ip>\n";
35 my $action = $ARGV[0];
36 my $ipAddr = $ARGV[2];
37 my $alertId = $ARGV[3];
38 my $ruleId = $ARGV[4];
40 if ($action ne "add" && $action ne "delete") {
41 WriteLog("Invalid action: $action\n");
45 if ($ipAddr =~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)/) {
46 if ($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255) {
47 WriteLog("Invalid IP address: $ipAddr\n");
52 WriteLog("Invalid IP address: $ipAddr\n");
55 WriteLog("active-list.pl $action $ipAddr $alertId $ruleId\n");
57 my $dbh = DBI->connect('DBI:mysql:' . $db_name, $db_user, $db_pass) || \
58 die "Could not connect to database: $DBI::errstr";
60 if ( $action eq "add" ) {
61 my $sth = $dbh->prepare('SELECT ip FROM ip_addresses WHERE ip = "' . $ipAddr . '"');
63 my $result = $sth->fetchrow_hashref();
65 $sth = $dbh->prepare('INSERT INTO ip_addresses VALUES ("' . $ipAddr . '","'. $theTime . '",' . $alertId . ',' . $ruleId . ',"Added by suspicious-ip Perl Script")');
67 WriteLog("Cannot insert new IP address: $DBI::errstr\n");
71 $sth = $dbh->prepare('UPDATE ip_addresses SET timestamp = "' . $theTime . '", alertid = ' . $alertId . ', ruleid = ' . $ruleId . ' WHERE ip = "' . $ipAddr . '"');
73 WriteLog("Cannot update IP address: $DBI::errstr\n");
78 my $sth = $dbh->prepare('DELETE FROM ip_addresses WHERE ip = "' . $ipAddr . '"');
80 WriteLog("Cannot remove IP address: $DBI::errstr\n");
89 if ( $_[0] eq "" ) { return; }
96 open(LOGH, ">>" . $pwd . "/../active-responses.log") || die "Cannot open log file.";
97 print LOGH $date . " " . $_[0];