<?php
/*  
 * Analysis Console for Intrusion Databases (ACID)
 *
 * Author: Roman Danyliw <rdd@cert.org>, <roman@danyliw.com>
 *
 * Copyright (C) 2000, 2001 Carnegie Mellon University
 * (see the file 'acid_main.php' for license details)
 *
 * Purpose:   
 *
 * Input GET/POST variables
 *   - submit:
 *   - time:
 *   - time_sep:
 */

  include ("acid_constants.inc");
  include ("acid_conf.php");
  include ("acid_include.inc");
  include_once ("acid_db_common.php");
  include_once ("acid_common.php");
  include_once ("acid_graph_common.php");

  $et = new EventTiming($debug_time_mode);
  $cs = new CriteriaState("acid_stat_alerts.php");
  $cs->ReadState();
  
  session_start();
  session_register('xdata');

  $submit = ImportHTTPVar("submit");
  $data_source = ImportHTTPVar("data_source");
  $chart_type = ImportHTTPVar("chart_type");
  $chart_interval = ImportHTTPVar("chart_interval");

  $chart_begin_hour = ImportHTTPVar("chart_begin_hour");
  $chart_begin_month = ImportHTTPVar("chart_begin_month");
  $chart_begin_day = ImportHTTPVar("chart_begin_day");
  $chart_begin_year = ImportHTTPVar("chart_begin_year");

  $chart_end_hour = ImportHTTPVar("chart_end_hour");
  $chart_end_month = ImportHTTPVar("chart_end_month");
  $chart_end_day = ImportHTTPVar("chart_end_day");
  $chart_end_year = ImportHTTPVar("chart_end_year");

  $chart_style = ImportHTTPVar("chart_style");
  $rotate_xaxis_lbl = ImportHTTPVar("rotate_xaxis_lbl");

  $page_title = "Graph Alert Data";
  PrintACIDSubHeader($page_title, $page_title, $cs->GetBackLink());

  LoadGraphingLib($ChartLib_path);

  /* Connect to the Alert database */
  $db = NewACIDDBConnection($DBlib_path, $DBtype);
  $db->acidDBConnect($db_connect_method,
                     $alert_dbname, $alert_host, $alert_port, $alert_user, $alert_password);

  if ( $event_cache_auto_update == 1 )  UpdateAlertCache($db);
?>

<FORM ACTION="acid_graph_main.php" METHOD="post">

<TABLE WIDTH="100%" BORDER=2 BGCOLOR="#CCCC99">
  <TR>
     <TD COLSPAN=2>
<?php
  set_time_limit($max_script_runtime);

  /* Set default chart values */
  if ( $submit == "" )
  {
     $height = 400;
     $width = 400;
     $user_chart_title = "ACID Chart";
     $min_size = 0;
     $rotate_xaxis_lbl = 0;
     $xaxis_label_inc = 1;
     $yaxis_scale = 0;
     $chart_style = "bar";
     $use_alerts = 0;
     $chart_begin_hour = " ";
     $chart_end_hour = " ";
  }

  echo '<B>Chart Title:</B> &nbsp;
            <INPUT TYPE="text" NAME="user_chart_title" SIZE=60 VALUE="'.$user_chart_title.'"><BR>'; 
        
  echo '<B>Chart Type:</B>&nbsp;
        <SELECT NAME="chart_type">
         <OPTION VALUE=" "  '.chk_select($chart_type, " ").'>{ chart type }
         <OPTION VALUE="1" '.chk_select($chart_type, "1").'>Time (hour) vs. Number of Alerts
         <OPTION VALUE="2" '.chk_select($chart_type, "2").'>Time (day) vs. Number of Alerts
         <!--<OPTION VALUE="3" '.chk_select($chart_type, "3").'>Time (week) vs. Number of Alerts-->
         <OPTION VALUE="4" '.chk_select($chart_type, "4").'>Time (month) vs. Number of Alerts
         <!--<OPTION VALUE="5" '.chk_select($chart_type, "5").'>Time (year) vs. Number of Alerts-->
         <OPTION VALUE="6" '.chk_select($chart_type, "6").'>Src. IP address vs. Number of Alerts
         <OPTION VALUE="7" '.chk_select($chart_type, "7").'>Dst. IP address vs. Number of Alerts
         <OPTION VALUE="8" '.chk_select($chart_type, "8").'>Dst. UDP Port vs. Number of Alerts
         <OPTION VALUE="10" '.chk_select($chart_type, "10").'>Src. UDP Port vs. Number of Alerts
         <OPTION VALUE="9" '.chk_select($chart_type, "9").'>Dst. TCP Port vs. Number of Alerts
         <OPTION VALUE="11" '.chk_select($chart_type, "11").'>Src. TCP Port vs. Number of Alerts
         <!--<OPTION VALUE="12" '.chk_select($chart_type, "12").'>Sig. Classification vs. Number of Alerts -->
        </SELECT>';

  // Do you need other periods? Simply add them!
  echo '&nbsp;&nbsp;<b>Chart Period:</B>&nbsp;
        <SELECT NAME="chart_interval">
         <OPTION VALUE="0"  '.chk_select($chart_interval, "0").'>no period
         <OPTION VALUE="7" '.chk_select($chart_interval, "7").'>7 (a week)
         <OPTION VALUE="24" '.chk_select($chart_interval, "24").'>24 (whole day)
         <OPTION VALUE="168" '.chk_select($chart_interval, "168").'>168 (24x7)
        </SELECT><BR>';

  echo '&nbsp;&nbsp;<B>Size: (width x height)</B>
        &nbsp;<INPUT TYPE="text" NAME="width" SIZE=4 VALUE="'.$width.'">
        &nbsp;<B>x</B>
        &nbsp;<INPUT TYPE="text" NAME="height" SIZE=4 VALUE="'.$height.'">
        &nbsp;&nbsp;';
  echo '<B>Graph type:</B> &nbsp;&nbsp;
            <INPUT TYPE="radio" NAME="chart_style" 
                   VALUE="bars" '.chk_check($chart_style, "bars").'> bar &nbsp;&nbsp
            <INPUT TYPE="radio" NAME="chart_style" 
                   VALUE="thinbarline" '.chk_check($chart_style, "thinbarline").'> thin bar &nbsp&nbsp;
            <INPUT TYPE="radio" NAME="chart_style" 
                   VALUE="linepoints" '.chk_check($chart_style, "linepoints").'> line &nbsp;&nbsp
            <!--<INPUT TYPE="radio" NAME="chart_style" 
                   VALUE="pie" '.chk_check($chart_style, "pie").'> pie -->';

  echo '<br><b>Chart Begin:</B>&nbsp;
        <SELECT NAME="chart_begin_hour">
         <OPTION VALUE=" "  '.chk_select($chart_begin_hour, " ").' >{hour}'."\n";
        for ( $i = 0; $i <= 23; $i++ )
            echo "<OPTION VALUE=\"$i\" ".chk_select($chart_begin_hour, $i)." >$i\n";

  echo '</SELECT>
        <SELECT NAME="chart_begin_day">
         <OPTION VALUE=" "  '.chk_select($chart_begin_day, " ").'>{day}';
        for ( $i = 1; $i <= 31; $i++ )
            echo "<OPTION VALUE=\"$i\" ".chk_select($chart_begin_day, $i).">$i\n";

  echo '</SELECT>
        <SELECT NAME="chart_begin_month">
         <OPTION VALUE=" "  '.chk_select($chart_begin_month, " ").'>{month}
         <OPTION VALUE="01" '.chk_select($chart_begin_month, "01").'>January
         <OPTION VALUE="02" '.chk_select($chart_begin_month, "02").'>February
         <OPTION VALUE="03" '.chk_select($chart_begin_month, "03").'>March
         <OPTION VALUE="04" '.chk_select($chart_begin_month, "04").'>April
         <OPTION VALUE="05" '.chk_select($chart_begin_month, "05").'>May
         <OPTION VALUE="06" '.chk_select($chart_begin_month, "06").'>June
         <OPTION VALUE="07" '.chk_select($chart_begin_month, "07").'>July
         <OPTION VALUE="08" '.chk_select($chart_begin_month, "08").'>August
         <OPTION VALUE="09" '.chk_select($chart_begin_month, "09").'>September
         <OPTION VALUE="10" '.chk_select($chart_begin_month, "10").'>October
         <OPTION VALUE="11" '.chk_select($chart_begin_month, "11").'>November
         <OPTION VALUE="12" '.chk_select($chart_begin_month, "12").'>December
        </SELECT>
        <SELECT NAME="chart_begin_year">
        <OPTION VALUE=" " '.chk_select($chart_begin_year, " ").'>{year}
        <OPTION VALUE="1999" '.chk_select($chart_begin_year, "1999").'>1999
        <OPTION VALUE="2000" '.chk_select($chart_begin_year, "2000").'>2000
        <OPTION VALUE="2001" '.chk_select($chart_begin_year, "2001").'>2001
        <OPTION VALUE="2002" '.chk_select($chart_begin_year, "2002").'>2002
        <OPTION VALUE="2003" '.chk_select($chart_begin_year, "2003").'>2003
        </SELECT>';

  echo '<br><b>Chart End:</B>&nbsp;&nbsp;&nbsp;&nbsp;
        <SELECT NAME="chart_end_hour">
         <OPTION VALUE=" "  '.chk_select($chart_end_hour, " ").'>{hour}'."\n";
        for ( $i = 0; $i <= 23; $i++ )
           echo "<OPTION VALUE=$i ".chk_select($chart_end_hour, $i).">$i\n";

  echo '</SELECT>
        <SELECT NAME="chart_end_day">
         <OPTION VALUE=" "  '.chk_select($chart_end_day, " ").'>{day}'."\n";
        for ( $i = 1; $i <= 31; $i++ )
           echo "<OPTION VALUE=$i ".chk_select($chart_end_day, $i).">$i\n";

  echo '</SELECT>
        <SELECT NAME="chart_end_month">
         <OPTION VALUE=" "  '.chk_select($chart_end_month, " ").'>{month}
         <OPTION VALUE="01" '.chk_select($chart_end_month, "01").'>January
         <OPTION VALUE="02" '.chk_select($chart_end_month, "02").'>February
         <OPTION VALUE="03" '.chk_select($chart_end_month, "03").'>March
         <OPTION VALUE="04" '.chk_select($chart_end_month, "04").'>April
         <OPTION VALUE="05" '.chk_select($chart_end_month, "05").'>May
         <OPTION VALUE="06" '.chk_select($chart_end_month, "06").'>June
         <OPTION VALUE="07" '.chk_select($chart_end_month, "07").'>July
         <OPTION VALUE="08" '.chk_select($chart_end_month, "08").'>August
         <OPTION VALUE="09" '.chk_select($chart_end_month, "09").'>September
         <OPTION VALUE="10" '.chk_select($chart_end_month, "10").'>October
         <OPTION VALUE="11" '.chk_select($chart_end_month, "11").'>November
         <OPTION VALUE="12" '.chk_select($chart_end_month, "12").'>December
        </SELECT>
        <SELECT NAME="chart_end_year">
        <OPTION VALUE=" " '.chk_select($chart_end_year, " ").'>{year}
        <OPTION VALUE="1999" '.chk_select($chart_end_year, "1999").'>1999
        <OPTION VALUE="2000" '.chk_select($chart_end_year, "2000").'>2000
        <OPTION VALUE="2001" '.chk_select($chart_end_year, "2001").'>2001
        <OPTION VALUE="2002" '.chk_select($chart_end_year, "2002").'>2002
        <OPTION VALUE="2003" '.chk_select($chart_end_year, "2003").'>2003
        </SELECT>';



  echo '<INPUT TYPE="submit" NAME="submit" VALUE="Graph Alerts"><BR>
        &nbsp;&nbsp; <BR>
        </TD></TR>';

  echo '<TR><TD>
        <TABLE WIDTH="100%" BORDER=1>
        <TR>
         <TD ALIGN="CENTER" WIDTH="70%"><B>X Axis</B></TD>
         <TD ALIGN="CENTER" WIDTH="30%"><B>Y Axis</B></TD>
        </TR>
        <TR>
         <TD>
           <B>Data Source:</B> &nbsp;
           <SELECT NAME="data_source">
           <OPTION VALUE=" " '.chk_select($data_source, " ").'>{ data source (AG) }';
           
           $temp_sql = "SELECT ag_id, ag_name FROM acid_ag";
           $tmp_result = $db->acidExecute($temp_sql);
           if ( ( $tmp_result ) )
           {
              while ( $myrow = $tmp_result->acidFetchRow() )
                echo '<OPTION VALUE="'.$myrow[0].'" '.chk_select($data_source, $myrow[0]).'>'.
                     '['.$myrow[0].'] '.$myrow[1];

              $tmp_result->acidFreeRows();
           }
 
           echo '</SELECT><BR>'.
                 /*<!--<B>Use Alerts of Type:</B>
                   <SELECT NAME="use_alerts">
                     <OPTION VALUE="0" '.chk_select($use_alerts, 0).'>alerts+portscans 
                     <OPTION VALUE="1" '.chk_select($use_alerts, 1).'>alerts only
                     <OPTION VALUE="2" '.chk_select($use_alerts, 2).'>portscans only
                     <OPTION VALUE="3" '.chk_select($use_alerts, 3).'>alert and portscans seperately
                   </SELECT><BR>-->*/
                 '<B>Minimum Threshold Value ( &gt;= ):</B> 
                 <INPUT TYPE="text" NAME="min_size" SIZE=5 VALUE='.$min_size.'>
                 &nbsp;&nbsp;
                 <INPUT TYPE="checkbox" NAME="rotate_xaxis_lbl" VALUE="1" '.
                   chk_check($rotate_xaxis_lbl, "1").'>
                 &nbsp;
                 <B>Rotate Axis Labels (90 degrees)</B><BR>
                 <B>Display X-axis label every
                 <INPUT TYPE="text" NAME="xaxis_label_inc" SIZE=4 VALUE='.$xaxis_label_inc.'>
                 &nbsp; data points
         </TD>
         <TD>
           <INPUT TYPE="checkbox" NAME="yaxis_scale" VALUE="1">&nbsp;Y-axis logarithmic
         </TD>
        </TR>
        </TABLE></TD></TR>';
  echo '</TABLE>';

  echo '</FORM>

        <P><HR>';

  $data_pnt_cnt = 0;
  /* Error Conditions */
  //if ( $submit != "" && $data_source == " " )
  //   echo '<FONT><B>No AG was selected for the data source</B>.</FONT>';     
  if ( $submit != "" && $chart_type == " " )
     echo '<FONT><B>No chart type was specified</B>.</FONT>';
  //else if ( $data_source == " " )
  //   echo '<FONT><B>No AG was specified</B>.</FONT>';

  /* Calculate the data set */
  else if ($submit != "")
  {
     if ( $data_source == " " )
     {
        ErrorMessage("No AG was specified.  Using all alerts.");
        $data_source = NULL;
     }

     unset($xdata);
     unset($xlabel);

     if ( $debug_mode > 1 )  echo "<H3>Starting data import ...</H3>";

     /* Building Criteria */
     $time_constraint = ProcessChartTimeConstraint($chart_begin_hour, 
                                                   $chart_begin_day, 
                                                   $chart_begin_month, 
                                                   $chart_begin_year,
                                                   $chart_end_hour,  
                                                   $chart_end_day,  
                                                   $chart_end_month, 
                                                   $chart_end_year );

     $criteria = array(2);
     if ( $data_source != NULL )
     {
        $criteria[0] = "LEFT JOIN acid_ag_alert ".
                      "ON (acid_event.sid=acid_ag_alert.ag_sid AND acid_event.cid=acid_ag_alert.ag_cid) ";
        $criteria[1] = "ag_id = $data_source";

        if ( $time_constraint != NULL )
           $criteria[1] = $criteria[1].$time_constraint; 
     }
     else
     {
        $criteria[0] = "";
        $criteria[1] = "acid_event.sid > 0 ".$time_constraint;
     }

     if ( $debug_mode > 0 ) 
     {
       echo "<H3>Chart criteria</H3><PRE>";
       print_r($criteria);
       echo "</PRE>";
     }

     switch ($chart_type)
     {
         case 1:
         case 2:
         case 3:
         case 4:
         case 5:
         {
            $chart_title = "Time vs. Number of Alerts";
            $xaxis_label = "Time";
            $yaxis_label = "Alert Occurrences";
            $data_pnt_cnt = GetTimeDataSet($xdata, $chart_type, $data_source, $min_size, $criteria);
            $chart_title = $chart_title."\n ( ".$xdata[0][0]." - ".$xdata[count($xdata)-1][0]." )";
            break;
         }
         case 6:  // Src. IP vs. Num Alerts
         {
            $chart_title = "Source IP vs. Number of Alerts";
            $xaxis_label = "Source IP Address";
            $yaxis_label = "Alert Occurrences";

            $data_pnt_cnt = GetIPDataSet($xdata, $chart_type, $data_source, $min_size, $criteria);
            break;
         }
         case 7:  // Dst. IP vs. Num Alerts
         {
            $chart_title = "Destination IP vs. Number of Alerts";
            $xaxis_label = "Destination IP Address";
            $yaxis_label = "Alert Occurrences";

            $data_pnt_cnt = GetIPDataSet($xdata, $chart_type, $data_source, $min_size, $criteria);
            break;
         }
         case 8:  // UDP Port vs. Num Alerts 
         {
            $chart_title = "UDP Port (Destination) vs. Number of Alerts";
            $xaxis_label = "Dst. UDP Port";
            $yaxis_label = "Alert Occurrences";

            $data_pnt_cnt = GetPortDataSet($xdata, $chart_type, $data_source, $min_size, $criteria);
            break;
         }
         case 10:  // UDP Port vs. Num Alerts 
         {
            $chart_title = "UDP Port (Source) vs. Number of Alerts";
            $xaxis_label = "Src. UDP Port";
            $yaxis_label = "Alert Occurrences";

            $data_pnt_cnt = GetPortDataSet($xdata, $chart_type, $data_source, $min_size, $criteria);
            break;
         }
         case 9:  // TCP Port vs. Num Alerts 
         {
            $chart_title = "TCP Port (Destination) vs. Number of Alerts";
            $xaxis_label = "Dst. TCP Port";
            $yaxis_label = "Alert Occurrences";

            $data_pnt_cnt = GetPortDataSet($xdata, $chart_type, $data_source, $min_size, $criteria);
            break;
         }
         case 11:  // TCP Port vs. Num Alerts 
         {
            $chart_title = "TCP Port (Source) vs. Number of Alerts";
            $xaxis_label = "Src. TCP Port";
            $yaxis_label = "Alert Occurrences";

            $data_pnt_cnt = GetPortDataSet($xdata, $chart_type, $data_source, $min_size, $criteria);
            break;
         }
         case 12:  // Classification vs. Num Alerts 
         {
            $chart_title = "Signature Classification vs. Number of Alerts";
            $xaxis_label = "Classification";
            $yaxis_label = "Alert Occurrences";

            $data_pnt_cnt = GetClassificationDataSet($xdata, $chart_type, $data_source, $min_size, $criteria);
            break;
         }
     }

     if ( $data_pnt_cnt > 0 )
     {
        if ( $debug_mode > 0 )
        {
           echo "chart_type = $chart_type<BR>
                 data_source = $data_source<BR>";
           echo "<H3>Handling Period if necessary ...</H3>\n";
        }

        if ( $chart_interval ) {
          // set up array
          for ( $i = 0; $i < $chart_interval; $i++ ) {
            $chart_array [$i][0] = $i;
            $chart_array [$i][1] = 0;
          }
          // loading data
          for ( $i = 0; $i < count ($xdata); $i++ ) {
            $chart_array [ $i % $chart_interval ][1] += $xdata [$i][1];
          }
          // set up xdata
          $xdata = $chart_array;
        }

        if ( $debug_mode > 0 )   
           echo "<H3>Dumping data ... (writing only every $xaxis_label_inc)</H3>";
        $data_str = "";
        $data_lbl_str = "";
        for ( $i = 0; $i < count($xdata); $i++)
        {
          if ( $debug_mode > 0 )
             echo $i." -- ".$xdata[$i][0]." - ".$xdata[$i][1]."<BR>";
        
          /* Apply the X-Axis label clean-up -- 
           * only write every N axis labels (erase the rest) 
           */
          if ( ($i % $xaxis_label_inc ) != 0 )
             $xdata[$i][0] = "";
        }

        if ( $debug_mode > 0 )  echo "<H3>Drawing graph ($width x $height)</H3>";

        $et->Mark("Extracting data");
        echo '<CENTER>
              <TABLE BGCOLOR="#000000" CELLSPACING=0 CELLPADDING=2 BORDER=0>
              <TR>
              <TD>';

        echo "<CENTER>
              <IMG SRC=\"acid_graph_display.php?width=$width&height=$height".
                      "&title=".rawurlencode($user_chart_title."\n".$chart_title).
                      "&xaxis_label=".rawurlencode($xaxis_label).
                      "&yaxis_label=".rawurlencode($yaxis_label).
                      "&yaxis_scale=".rawurlencode($yaxis_scale).
                      "&rotate_xaxis_lbl=".rawurlencode($rotate_xaxis_lbl).
                      "&style=".$chart_style.
                      /*$data_str.$data_lbl_str.*/"\"></CENTER>";

        echo '</TD>
              </TR>
              </TABLE>
              </CENTER>';
        $et->Mark("Rendering graph");
      }
      else
        ErrorMessage("No data points to plot");
   }

  $et->PrintTiming();

  PrintACIDSubFooter();
?>

