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
17 use Regexp::IPv6 qw($IPv6_re);
19 # -----------------------
20 # DB access configuration
21 # -----------------------
22 my $db_name = 'ossec_active_lists';
23 my $db_user = 'suspicious';
24 my $db_pass = 'xxxxxxxxxx';
26 my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
27 my $theTime = sprintf("%d-%02d-%02d %02d:%02d:%02d",
28 $yearOffset+1900, $month+1, $dayOfMonth, $hour, $minute, $second);
30 my $nArgs = $#ARGV + 1;
32 print STDERR "Usage: active-list.pl <action> <username> <ip>\n";
36 my $action = $ARGV[0];
37 my $ipAddr = $ARGV[2];
38 my $alertId = $ARGV[3];
39 my $ruleId = $ARGV[4];
41 if ($action ne "add" && $action ne "delete") {
42 WriteLog("Invalid action: $action\n");
46 if ($ipAddr =~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)/) {
47 if ($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255) {
48 WriteLog("Invalid IP address: $ipAddr\n");
52 else if ($ipAddr =~ m/^$IPv6_re/) {
55 WriteLog("Invalid IP address: $ipAddr\n");
58 WriteLog("active-list.pl $action $ipAddr $alertId $ruleId\n");
60 my $dbh = DBI->connect('DBI:mysql:' . $db_name, $db_user, $db_pass) || \
61 die "Could not connect to database: $DBI::errstr";
63 if ( $action eq "add" ) {
64 my $sth = $dbh->prepare('SELECT ip FROM ip_addresses WHERE ip = "' . $ipAddr . '"');
66 my $result = $sth->fetchrow_hashref();
68 $sth = $dbh->prepare('INSERT INTO ip_addresses VALUES ("' . $ipAddr . '","'. $theTime . '",' . $alertId . ',' . $ruleId . ',"Added by suspicious-ip Perl Script")');
70 WriteLog("Cannot insert new IP address: $DBI::errstr\n");
74 $sth = $dbh->prepare('UPDATE ip_addresses SET timestamp = "' . $theTime . '", alertid = ' . $alertId . ', ruleid = ' . $ruleId . ' WHERE ip = "' . $ipAddr . '"');
76 WriteLog("Cannot update IP address: $DBI::errstr\n");
81 my $sth = $dbh->prepare('DELETE FROM ip_addresses WHERE ip = "' . $ipAddr . '"');
83 WriteLog("Cannot remove IP address: $DBI::errstr\n");
92 if ( $_[0] eq "" ) { return; }
99 open(LOGH, ">>" . $pwd . "/../active-responses.log") || die "Cannot open log file.";
100 print LOGH $date . " " . $_[0];