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

  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_stat_common.php");
  include_once ("acid_qry_common.php");
  include_once ("acid_ag_common.php");

  $et = new EventTiming($debug_time_mode);
  $cs = new CriteriaState("acid_stat_sensor.php");
  $cs->ReadState();

  $qs = new QueryState();

  $submit = ImportHTTPVar("submit", VAR_DIGIT);
  $qs->MoveView($submit);             /* increment the view if necessary */

  $page_title = "Sensor Listing";
  PrintACIDSubHeader($page_title, $page_title, $cs->GetBackLink());
  
  /* 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);

  $criteria_clauses = ProcessCriteria();  
  PrintCriteria("");

  $from = " FROM acid_event ".$criteria_clauses[0];
  $where = " WHERE ".$criteria_clauses[1];

  $qs->AddValidAction("ag_by_id");
  $qs->AddValidAction("ag_by_name");
  $qs->AddValidAction("add_new_ag");
  $qs->AddValidAction("del_alert");
  $qs->AddValidAction("email_alert");
  $qs->AddValidAction("email_alert2");
  $qs->AddValidAction("csv_alert");
  $qs->AddValidAction("archive_alert");
  $qs->AddValidAction("archive_alert2");

  $qs->AddValidActionOp("Selected");
  $qs->AddValidActionOp("ALL on Screen");

  $qs->SetActionSQL($from.$where);
  $et->Mark("Initialization");

  $qs->RunAction($submit, PAGE_STAT_SENSOR, $db);
  $et->Mark("Alert Action");

  /* create SQL to get Unique Alerts */
  $cnt_sql = "SELECT count(DISTINCT acid_event.sid) ".$from.$where;

  /* Run the query to determine the number of rows (No LIMIT)*/
  $qs->GetNumResultRows($cnt_sql, $db);
  $et->Mark("Counting Result size");

  /* Setup the Query Results Table */
  $qro = new QueryResultsOutput("acid_stat_sensor.php?x=x");

  $qro->AddTitle(" ");
  $qro->AddTitle("Sensor", 
                "sid_a", " ",
                         " ORDER BY acid_event.sid ASC",
                "sid_d", " ",
                         " ORDER BY acid_event.sid DESC");  
  $qro->AddTitle("Name", 
                "sname_a", " ",
                         " ORDER BY sensor.name ASC",
                "sname_d", " ",
                         " ORDER BY sensor.name DESC");
  $qro->AddTitle("Total Events", 
                "occur_a", " ",
                         " ",
                "occur_d", " ",
                         " ");  

  $qro->AddTitle("Unique Events", 
                "occur_a", "", " ORDER BY sig_cnt ASC",
                "occur_d", "", " ORDER BY sig_cnt DESC");
  $qro->AddTitle("Src.<BR>Addr.", 
                "saddr_a", "", " ORDER BY saddr_cnt ASC",
                "saddr_d", "", " ORDER BY saddr_cnt DESC");
  $qro->AddTitle("Dest.<BR>Addr.", 
                "daddr_a", "", " ORDER BY daddr_cnt ASC",
                "daddr_d", "", " ORDER BY daddr_cnt DESC");
  $qro->AddTitle("First", 
                "first_a", "", " ORDER BY first_timestamp ASC",
                "first_d", "", " ORDER BY first_timestamp DESC");
  $qro->AddTitle("Last", 
                "last_a", "", " ORDER BY last_timestamp ASC",
                "last_d", "", " ORDER BY last_timestamp DESC");

  $sort_sql = $qro->GetSortSQL($qs->GetCurrentSort(), "");
  //if ( $sort_sql == NULL )
  //   ErrorMessage("Invalid or No Sort type was specified");

  $sql = "SELECT DISTINCT acid_event.sid, count(acid_event.cid) as event_cnt,".
         " count(distinct(acid_event.signature)) as sig_cnt, ".
         " count(distinct(acid_event.ip_src)) as saddr_cnt, ".
         " count(distinct(acid_event.ip_dst)) as daddr_cnt, ".
         "min(timestamp) as first_timestamp, max(timestamp) as last_timestamp".
         $sort_sql[0].$from.$where." GROUP BY acid_event.sid ".$sort_sql[1];

  /* Run the Query again for the actual data (with the LIMIT) */
  $result = $qs->ExecuteOutputQuery($sql, $db);
  $et->Mark("Retrieve Query Data");

  if ( $debug_mode == 1 )
  {
     $qs->PrintCannedQueryList();
     $qs->DumpState();
     echo "$sql<BR>";
  }

  /* Print the current view number and # of rows */
  $qs->PrintResultCnt();

  echo '<FORM METHOD="post" NAME="PacketForm" ACTION="acid_stat_sensor.php">';
  
  $qro->PrintHeader();

  $i = 0;
  while ( ($myrow = $result->acidFetchRow()) && ($i < $qs->GetDisplayRowCnt()) )
  {
    $sensor_id = $myrow[0];
    $event_cnt = $myrow[1];
    $unique_event_cnt = $myrow[2];
    $num_src_ip = $myrow[3];
    $num_dst_ip = $myrow[4];
    $start_time = $myrow[5];
    $stop_time = $myrow[6];

    /* Print out */ 
    qroPrintEntryHeader($i);    

    $tmp_rowid = $sensor_id;
    echo '    <TD><INPUT TYPE="checkbox" NAME="action_chk_lst['.$i.']" VALUE="'.$tmp_rowid.'"></TD>';
    echo '        <INPUT TYPE="hidden" NAME="action_lst['.$i.']" VALUE="'.$tmp_rowid.'">';

    qroPrintEntry($sensor_id);
    qroPrintEntry(GetSensorName($sensor_id, $db));
    qroPrintEntry('<A HREF="acid_qry_main.php?new=1&sensor='.$sensor_id.
                  '&num_result_rows=-1&submit=Query+DB">'.
                  $event_cnt.'</A>');

     //if ( ($raw_sensor_events[ $sensor_ids[$i] ] != 0) && ($event_cnt > 0) )
     //      echo  ' ('.(round($raw_sensor_events[ $sensor_ids[$i] ]/$event_cnt*100)).'%)';

     qroPrintEntry(BuildUniqueAlertLink("?sensor=".$sensor_id).$unique_event_cnt.'</A>');
     qroPrintEntry(BuildUniqueAddressLink(1, "&sensor=".$sensor_id).$num_src_ip.'</A>');
     qroPrintEntry(BuildUniqueAddressLink(2, "&sensor=".$sensor_id).$num_dst_ip.'</A>');
     qroPrintEntry($start_time);
     qroPrintEntry($stop_time);

     qroPrintEntryFooter();

     $i++;
  }

  $result->acidFreeRows();

  $qro->PrintFooter();

  $qs->PrintBrowseButtons();
  $qs->PrintAlertActionButtons();
  $qs->SaveState();
  $et->Mark("Get Query Elements");
  $et->PrintTiming();

  echo "\n</FORM>\n";
  
  PrintACIDSubFooter();
?>
