]> Raphaƫl G. Git Repositories - tools/blob - blacklist
ec10c88e28490e9add39e8a68e73b7546faad22a
[tools] / blacklist
1 #! /usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use IPC::System::Simple qw(capturex);
7 use Data::Validate::IP;
8
9 my %ip4s = ();
10 my %ip6s = ();
11 my @blrule4s = ();
12 my @blrule6s = ();
13 my $whitelist = qr/^(?:127.|5.9.143.173|85.68.182.45|195.25.233.49|::1|2a01:4f8:190:22a6:)/;
14 my @userlist = ('rapsys');
15
16 # Extract sshd.service scan
17 map {
18 if (/Failed password for (?:invalid user )?(.+) from (.+) port [0-9]+ ssh2/ && grep($_ ne $1, @userlist) && $2 !~ /$whitelist/) {
19 if (Data::Validate::IP::is_ipv4($2)) {
20 $ip4s{$2}=1;
21 } elsif (Data::Validate::IP::is_ipv6($2)) {
22 $ip6s{$2}=1;
23 }
24 }
25 } capturex('journalctl', '-u', 'sshd.service');
26
27 # Extract kernel port scan
28 map {
29 if (/Shorewall:net-fw:DROP:.* SRC=([^\s]+) DST=.*/ && $1 !~ /$whitelist/) {
30 if (Data::Validate::IP::is_ipv4($1)) {
31 $ip4s{$1}=1;
32 } elsif (Data::Validate::IP::is_ipv6($1)) {
33 $ip6s{$1}=1;
34 }
35 }
36 } capturex('journalctl', '-k');
37
38 # Open blrule4s file for reading
39 open (my $fh, '<', '/etc/shorewall/blrules') or die "Can't open < /etc/shorewall/blrules: $!";
40
41 # Populate with comments
42 @blrule4s = map { chomp($_); if (/^#/) { $_; } else { (); } } <$fh>;
43
44 # Prepend header
45 push @blrule4s, "WHITELIST\tnet:5.9.143.173\tall";
46 push @blrule4s, "WHITELIST\tnet:85.68.182.45\tall";
47 push @blrule4s, "WHITELIST\tnet:195.25.233.49\tall";
48
49 # Build blacklist
50 map { push @blrule4s, "DROP\t\tnet:".$_.(length lt 12?"\t":'')."\tfw"; } sort keys %ip4s;
51
52 # Close blrule4s file
53 close $fh or die "Can't close fh: $!";
54
55 # Open blrule4s file for writing
56 open ($fh, '>', '/etc/shorewall/blrules') or die "Can't open > /etc/shorewall/blrules: $!";
57
58 # Inject content of blacklist
59 map { print $fh $_."\n"; } @blrule4s;
60
61 # Close blrule4s file
62 close $fh or die "Can't close fh: $!";
63
64 # Print ipv6 to update hash
65 #XXX; right now it don't seems scanned at all...
66 for (sort keys %ip6s) {
67 print $_."\n";
68 }
69
70 # Restart shorewall service
71 capturex('systemctl', 'restart', 'shorewall.service');