#!/usr/bin/perl

#
# Copyright (C) 2020 Nethesis S.r.l.
# http://www.nethesis.it - info@nethesis.it
#
# This script is part of Dante.
#
# Dante is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# Dante is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Dante.  If not, see COPYING.
#

#
# Return blacklists statistics in JSON format
#

use strict;
use warnings;
use POSIX qw(strftime);
use JSON;
use esmith::NetworksDB;
use esmith::ConfigDB;
use NethServer::TrustedNetworks;
use NetAddr::IP;
use File::Basename;

my %category_cache;
my %local_cache;
my @private_networks = (NetAddr::IP->new('10.0.0.0/8'), NetAddr::IP->new('172.16.0.0/12'), NetAddr::IP->new('192.168.0.0/16'));

sub is_local {
    my $ip = shift;

    if (!defined($local_cache{$ip})) {
        $local_cache{$ip} = 0;
    } else {
        return $local_cache{$ip};
    }
    my $needle = NetAddr::IP->new($ip);
    foreach (@private_networks) {
        if ($needle->within($_)) {
            $local_cache{$ip} = 1;
            last;
        }
    }

    return $local_cache{$ip};
}

sub get_category {
    my $sets = shift;
    my $ip = shift;

    if (!defined($category_cache{$ip})) {
        $category_cache{$ip} = '';
    } else {
        return $category_cache{$ip};
    }
 
    my $needle = NetAddr::IP->new($ip);
    foreach my $c (keys %{$sets}) {
        foreach (@{$sets->{$c}}) {
            if ($needle->within($_)) {
                $category_cache{$ip} = $c;
                last;
            }
        }
    }

    return $category_cache{$ip}
}


my $log = "/var/log/firewall.log";
my $date = strftime "%b %e", localtime;
my $yesterday = strftime "%Y%m%d", localtime(time() - (24 * 60 * 60));
my $previous_log = $log."-$yesterday";
my $previous_log_gz = $previous_log.".gz";
my $db = esmith::ConfigDB->open_ro();
my $status = $db->get_prop('blacklist', 'status') || 'disabled';

if (! -f $log || $status ne 'enabled') {
    exit 1;
}

# Load local networks
my @local_networks;
my $ndb = esmith::NetworksDB->open_ro();
foreach ($ndb->get_all()) {
    my $ip = $_->prop('ipaddr') || next;
    my $mask = $_->prop('netmask') || next;
    push(@local_networks,NetAddr::IP->new($ip, $mask));

}
foreach (NethServer::TrustedNetworks::list_cidr()) {
    push(@local_networks,NetAddr::IP->new($_));
}

# Load ipsets

# search IP inside loaded ipset
my %sets;

# list blacklist sets
open(PIPE, "/sbin/ipset -L -name|");
while (<PIPE>) {
    chomp;
    next if ($_ eq 'bl-whitelist'); # skip global whitelist
    if ($_ =~ /^bl\-/) {
        $sets{substr($_, 3)} = ();
    }
}
close(PIPE);

# load ipset ip addresses
foreach my $set (keys %sets) {
    my @ips;
    open(PIPE, "/sbin/ipset -L bl-$set|");
    while (<PIPE>) {
        chomp;
        push(@ips, NetAddr::IP->new($_)) if ($_ =~ /^\d/);
    }
    close(PIPE);
    $sets{$set} = \@ips;
}


my %categories;
foreach (keys %sets) {
    $categories{$_} = 0;
}

open(PIPE, "zgrep '$date' $log $previous_log $previous_log_gz 2>/dev/null | grep blacklst | grep -Eo 'SRC=([0-9]{1,3}[\.]){3}[0-9]{1,3} DST=([0-9]{1,3}[\.]){3}[0-9]{1,3}'| tr '=' ' '|");
while (my $row = <PIPE>) {

    my ($src_s, $src, $dst_s, $dst) = split(/\s/, $row);
    my $src_is_local = is_local($src);
    my $dst_is_local = is_local($dst);

    next if ($src_is_local && $dst_is_local);

    # find category
    if (!$src_is_local) {
        my $category = get_category(\%sets, $src);
        $categories{$category}++ if ($category);
    }

    # find category
    if (!$dst_is_local) {
        my $category = get_category(\%sets, $dst);
        $categories{$category}++ if ($category);
    }
}
close(PIPE);

print encode_json({
        minerId => basename($0),
        type => "chart",
        chartType => "pie",
        unit => "number",
        aggregationType => "number",
        categories => [ keys %categories ],
        series => [{
                name => "blacklist-attacks",
                data => [ values %categories  ]
            }]
    });
