#!/usr/bin/perl
#
#-----------------------------------
# PIX Logging Architecture (v2.00)
# General Configuration File
#-----------------------------------
#
#
# PIX Logging Architecture
# [Kristof Philipsen]
#
# This file is part of PIX Logging Architecture
#
# PIX Logging Architecture 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 2 of the License, or
# (at your option) any later version.
#
# PIX Logging Architecture 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 PIX Logging Architecture; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


use DBI;

require '../conf.pl';
require '../subs.pl';

use CGI ':standard';
use GD::Graph::bars;
use GD::Graph::lines;
use Date::Manip;

db_connect();

my %x_stat = ();
my %y_stat = ();
my %stat_profiles = ();


$query = new CGI;
$id = clean_input($query->param("id"));
$fw = clean_input($query->param("firewall"));
$datetime = clean_input($query->param("datetime"));
$acceptdrop = clean_input($query->param("acceptdrop"));
$xlabel= clean_input($query->param("label"));
$title= clean_input($query->param("title"));
$var_crit= clean_input($query->param('interval'));
$var_num= clean_input($query->param('num'));
$var_offset= clean_input($query->param('offset'));
$date_shift= clean_input($query->param('date_shift'));
$fw = clean_input($query->param("firewall"));
$maxvars= clean_input($query->param("maxvars"));
$var_tblfld= clean_input($query->param("tblfld"));
$var_tblval= clean_input($query->param("tblval"));
$var_legend= clean_input($query->param("legend"));
$compare= clean_input($query->param("compare"));

@yarray = ();
@xarray01 = ();
@xarray02 = ();
@xarray03 = ();

if ($acceptdrop eq "") {
    $acceptdrop="0";
}
if ($fw eq "") {
        $fw="\%";
}

if ($datetime eq "" || $datetime eq "YYYY-MM-DD") {
	$date=`date +%Y"-"%m"-"%d`;
	$date=~s/\n//g;
	$currenttime=`date +%Y"-"%m"-"%d" "%H":00:00"`;
        $currenttime=~s/\n//g;
} else {
	$date=$datetime;
	$date=~s/\n//g;
	$today=`date +%Y"-"%m"-"%d`;
        $today=~s/\n//g;
        if ($date eq $today) {
	$currenttime=`date +%Y"-"%m"-"%d" "%H":00:00"`;
        $currenttime=~s/\n//g;
        } else {
	$currenttime="$date 23:00:00";
	}
}

$stat_profiles->[0]->[0] = "select log_dst_pt,count(*) from traffic_log where log_time like \"$date\%\" and log_resource like \"$fw\" group by log_dst_pt order by count(*) desc limit 10";
$stat_profiles->[0]->[1] = "Destination Port";
$stat_profiles->[0]->[2] = "Number of Hits";
$stat_profiles->[0]->[3] = "Top Destination Ports ($date)";
$stat_profiles->[0]->[4] = "#5479d8";
$stat_profiles->[0]->[5] = "400";
$stat_profiles->[0]->[6] = "240";

$stat_profiles->[1]->[0] = "select log_src_pt,count(*) from traffic_log where log_time like \"$date\%\" and log_resource like \"$fw\" group by log_src_pt order by count(*) desc limit 10";
$stat_profiles->[1]->[1] = "Source Port";
$stat_profiles->[1]->[2] = "Number of Hits";
$stat_profiles->[1]->[3] = "Top Source Ports ($date)";
$stat_profiles->[1]->[4] = "#5479d8";
$stat_profiles->[1]->[5] = "400";
$stat_profiles->[1]->[6] = "240";

$stat_profiles->[2]->[0] = "select log_dst_ip,count(*) from traffic_log where log_time like \"$date\%\" and log_resource like \"$fw\" and log_message not like \"PIX-3-313001%\" group by log_dst_ip order by count(*) desc limit 10";
$stat_profiles->[2]->[1] = "Destination IP";
$stat_profiles->[2]->[2] = "Number of Hits";
$stat_profiles->[2]->[3] = "Top Destination IPs ($date)";
$stat_profiles->[2]->[4] = "#5479d8";
$stat_profiles->[2]->[5] = "400";
$stat_profiles->[2]->[6] = "240";

$stat_profiles->[3]->[0] = "select log_src_ip,count(*) from traffic_log where log_time like \"$date\%\" and log_resource like \"$fw\" group by log_src_ip order by count(*) desc limit 10";
$stat_profiles->[3]->[1] = "Source IP";
$stat_profiles->[3]->[2] = "Number of Hits";
$stat_profiles->[3]->[3] = "Top Source IPs ($date)";
$stat_profiles->[3]->[4] = "#5479d8";
$stat_profiles->[3]->[5] = "400";
$stat_profiles->[3]->[6] = "240";


if ($compare eq "1") {

if ($maxvars eq "1") {
   $tbl_val_01=$var_tblval;
   $legend_01=$var_legend;
}

if ($maxvars eq "2") {
 ($tbl_val_01,$tbl_val_02)=split(":",$var_tblval);
 ($legend_01,$legend_02)=split(":",$var_legend);
}

if ($maxvars eq "3") {
 ($tbl_val_01,$tbl_val_02,$tbl_val_03)=split(":",$var_tblval);
 ($legend_01,$legend_02,$legend_03)=split(":",$var_legend);
}

$parse_format="%Y-%m-%d";

if ($fw eq "") {
        $fw="\%";
}

$var_num=$var_num - 1;

if ($var_crit ne "hours") {
for ($i=$var_num;$i>=0;$i--) {
 $s_date=DateCalc($date,"$i $var_crit ago",\$err);
 if ($var_crit eq "months" || $var_crit eq "month") {
  $s_date=UnixDate($s_date,"%Y-%m-01");
  } else {
  $s_date=UnixDate($s_date,$parse_format);
 }
 $d="$i - $offset";
 if ($date_shift eq "0") {
  $e_date=$s_date;
  $start_date="$s_date 00:00:00";
  $end_date="$e_date 23:59:59";
  $xx_01=get_stat("$start_date","$end_date",$var_tblfld,$tbl_val_01,$fw);
  $xx_02=get_stat("$start_date","$end_date",$var_tblfld,$tbl_val_02,$fw);
  $xx_03=get_stat("$start_date","$end_date",$var_tblfld,$tbl_val_03,$fw);
  push @yarray, $e_date;
  #print "tcp: $xx_01\tudp: $xx_02\t icmp: $xx_03\n";
 }

 if ($date_shift eq "1") {
  $d=$i - 1;
  $e_date=DateCalc($date,"$d $var_crit ago",\$err);
  if ($var_crit eq "months" || $var_crit eq "month") {
   $e_date=UnixDate($e_date,"%Y-%m-01");
  } else {
   $e_date=UnixDate($e_date,$parse_format);
  }
  $start_date="$s_date 00:00:00";
  $end_date="$e_date 00:00:00";
  $xx_01=get_stat("$start_date","$end_date",$var_tblfld,$tbl_val_01,$fw);
                $xx_02=get_stat("$start_date","$end_date",$var_tblfld,$tbl_val_02,$fw);
                $xx_03=get_stat("$start_date","$end_date",$var_tblfld,$tbl_val_03,$fw);
  push @yarray, $s_date;
  #print "tcp: $xx_01\tudp: $xx_02\t icmp: $xx_03\n";
 }

 push @xarray01, $xx_01;
 push @xarray02, $xx_02;
 push @xarray03, $xx_03;
}
}

if ($var_crit eq "hours") {
    for ($i=$var_num;$i>=0;$i--) {
 $d="$i - $offset";
  $d=$i - 1;
  $s_date=DateCalc($currenttime,"$i $var_crit ago",\$err);
  $e_date=DateCalc($currenttime,"$d $var_crit ago",\$err);
  $s_date=UnixDate($s_date,"%Y-%m-%d %H:%M:%S");
  $e_date=UnixDate($e_date,"%Y-%m-%d %H:%M:%S");
  $start_date=$s_date;
  $end_date=$e_date;
  #print "$start_date\t$end_date\n";
  $xx_01=get_stat("$start_date","$end_date",$var_tblfld,$tbl_val_01,$fw);
  $xx_02=get_stat("$start_date","$end_date",$var_tblfld,$tbl_val_02,$fw);
  $xx_03=get_stat("$start_date","$end_date",$var_tblfld,$tbl_val_03,$fw);
  if ($start_date =~ /(.*) (.*):(.*):(.*)/) {
     $info="$1 $2:$3";
  }
  push @yarray, $info;
  #print "tcp: $xx_01\tudp: $xx_02\t icmp: $xx_03\n";

 push @xarray01, $xx_01;
 push @xarray02, $xx_02;
 push @xarray03, $xx_03;
}
}

if ($maxvars eq "1" ) {

  my @data = (
      [ @yarray ], [ @xarray01 ]
      );

  my $graph = new GD::Graph::bars(850,250);

  $graph->set(
      x_label         => $xlabel,
      y_label         => 'Logged Data',
      title           => $title,
      show_values     => 1,
      x_labels_vertical => 1,
      line_width      => 3
  )
  or warn $graph->error;
  $graph->set( dclrs => [ '#5479d8' ] );
  $graph->set_legend( $legend_01 );
  $graph->plot(\@data) or die $graph->error;

  print "Content-type: image/png\n\n";
  print $graph->gd->png;

}


if ($maxvars eq "2" ) {

  my @data = (
      [ @yarray ], [ @xarray02 ] , [ @xarray01 ]
      );

  my $graph = new GD::Graph::bars(850,250);

  $graph->set(
      x_label         => $xlabel,
      y_label         => 'Logged Data',
      title           => $title,
      show_values     => 1,
      x_labels_vertical => 1,
      line_width      => 3
  )
  or warn $graph->error;
  $graph->set_legend( $legend_01, $legend_02 );
  $graph->plot(\@data) or die $graph->error;

  print "Content-type: image/png\n\n";
  print $graph->gd->png;

}

if ($maxvars eq "3" ) {

  my @data = (
             [ @yarray ], [ @xarray03], [ @xarray02 ] , [ @xarray01 ]
             );

  my $graph = new GD::Graph::bars(850,250);

  $graph->set(
      x_label         => $xlabel,
      y_label         => 'Logged Data',
      title           => $title,
      show_values     => 1,
      x_labels_vertical => 1,
      line_width      => 3
  )
  or warn $graph->error;
  $graph->set_legend( $legend_01, $legend_02, $legend_03 );
  $graph->plot(\@data) or die $graph->error;

  print "Content-type: image/png\n\n";
  print $graph->gd->png;

}

} else {


$getstats_template = $stat_profiles->[$id]->[0];
$getstats_exec = $db_handle->prepare($getstats_template) or die "Couldn't prepare query '$getstats_template': $DBI::errstr\n";
$getstats_exec->execute();

$stats_count="0";

while (($x_stats,$y_stats) = $getstats_exec->fetchrow) {
      $x_stat->[$stats_count]=$x_stats;
      $y_stat->[$stats_count]=$y_stats;
      $stats_count++;
}

# Both the arrays should same number of entries.
my @data = ([$x_stat->[0], $x_stat->[1], $x_stat->[2], $x_stat->[3], $x_stat->[4], $x_stat->[5], $x_stat->[6], $x_stat->[7], $x_stat->[8], $x_stat->[9]],  
	    [$y_stat->[0], $y_stat->[1], $y_stat->[2], $y_stat->[3], $y_stat->[4], $y_stat->[5], $y_stat->[6], $y_stat->[7], $y_stat->[8], $y_stat->[9]]);

my $mygraph = GD::Graph::bars->new($stat_profiles->[$id]->[5],$stat_profiles->[$id]->[6]);
$mygraph->set(
    x_label     => $stat_profiles->[$id]->[1],
    y_label     => $stat_profiles->[$id]->[2],
    title       => $stat_profiles->[$id]->[3],
    x_labels_vertical => '1',
) or warn $mygraph->error;
$mygraph->set( dclrs => [ $stat_profiles->[$id]->[4] ] );

if ($id eq "dropaccept") {

 $getstats_template = $stat_profiles->[$id]->[0];
 $getstats_exec = $db_handle->prepare($getstats_template) or die "Couldn't prepare query '$getstats_template': $DBI::errstr\n";
 $getstats_exec->execute();

}

my $myimage = $mygraph->plot(\@data) or die $mygraph->error;
print "Content-type: image/png\n\n";
print $myimage->png;

}

