/ Perl6


So I got a little tired of having to review my system log to find failed ssh attempts to block them in the firewall. I figured what a great chance to automate the process with some Perl6 code...

So the entire process goes like this:

  • Generate temp file from system log OR any text file.
  • Parse the output from the first commnad for unique ip addresses.
  • Processes each ip and add to firewall OR output to a text file.

Here is a simple overview and example command line code:
Process Overview

The main part that was needed was the adding the found IP address to an array. This will be the main focus of this post, as there are many different way to accomplish the other steps.

So in the main part of the code looks like this:

1 my $fh = open $dataFile, :r;
2 for $fh.lines {
3  if $_ ~~ /([\d ** 1..3] ** 4 % '.') / {
4    $total_ip++;
5    @ip_list.push($0.Str) if $0 !eq any(@ip_list);
6  }
7 }
8 $fh.close;

Here we open a file for reading, then iterate through the file line by line. On line 3, we do some pattern matching to find a valid IPv4 address. The [\d ** 1..3] ** 4 % '.' means to find 4 sets of 1,2, or 3 digits that have an . in between them. The entire pattern is surrounded by parenthesis which means to capture the match and place it into the match array,$0.

Next on line 5 is where some Perl6 magic happens.

@ip_list.push($0.Str) if $0 !eq any(@ip_list);

This will push the contents of the first match array $0 (which is a valid IP address) into the @ip_list array, Only if that IP address is not equal to any value already in the @ip_list array. The last part is what I believe is referred to as a Junction in Perl6. In fact I have found Perl6 Junctions very useful.

This bit of code prevents duplicate IP addresses from being added to the list of offending IP addresses. Once you have an list of IP addresses, just iterate through the array adding each IP address to a shell command to that adds the IP to your firewall.

This part will look different depending on what OS you are running and what firewall you are using. So I will leave it up to you to come up with you own implementation.

Here is a screenshot of the program running and adding the found IP's to the firewall drop list:
Log2Firewall Screenshot

One cool side note, the function to add IP addresses to the firewall was at one point part of the IP parsing program. I have seance split the two functions into their own programs. Now I have added a 3rd way to input offending IP addresses. By using the -i command line option, you will get a interactive shell where you can enter an IP address on the fly. When used with the journalctl -f command for a live view of the log, you can input that suspect IP address right there in the ip2firewall shell!