<?php
/*  
 * Analysis Console for Incident Databases (ACID)
 *
 * Author: Roman Danyliw <rdd@cert.org>, <roman@danyliw.com>
 *
 * Copyright (C) 2000 Carnegie Mellon University
 * (see the file 'acid_main.php' for license details)
 *
 * Purpose:   
 *
 */
?>

<?php
  include ("acid_db_common.php");
  include ("acid_common.php");
  include ("acid_stat_common.php");
  include ("acid_conf.php");
?>

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<!-- Analysis Console for Incident Databases (ACID) <?php echo $ACID_VERSION; ?> -->
<HTML>
  <HEAD>
    <META name="Author" content="Roman Danyliw">
    <TITLE>ACID: Unique Alert Listing</TITLE>
  <LINK rel="stylesheet" type="text/css" href="acid_style.css">

</HEAD>

<BODY>

<TABLE WIDTH="100%" BORDER=0 CELLSPACING=0 CELLPADDING=5>
<TR>
  <TD class="mainheader">
     <?php
       include("acid_hdr1.html");
     ?>
  </TD>
  <TD class="mainheadertitle">Alert Listing
     <?php if ( $caller == "most_frequent" ) echo ": Most Frequent $freq_num_alerts Alerts";
           if ( $caller == "last_alerts" )   echo ": Last $last_num_ualerts Alerts"; 
      ?></TD>
  <TD class="mainheader" ALIGN=RIGHT>
     <?php
       include("acid_hdr2.html");
     ?>
  </TD>

</TR>
</TABLE>
<P><P>

<?php

  /* Connect to the Alert database */
  $db=acid_mysql_connect($alert_host, $alert_port, $alert_user, $alert_password, $alert_dbname);
  mysql_select_db($alert_dbname, $db);

  $criteria = rawurldecode($criteria);
  $criteria_desc = rawurldecode($criteria_desc);
  $criteria_form = rawurldecode($criteria_form);

  SplitCriteriaFromSQL($criteria, $from, $where, $limits);

  if ( $debug_mode == 1 )
     echo "caller=$caller<BR>criteria=$criteria<BR>criteria_desc=$criteria_desc<BR>".
          "from=$from<BR>where=$where<BR>limit=$limits<BR>";

  /* Check whether have additional criteria on alerts */
  if ( $criteria != "" && $criteria_desc != "")
  {
     $where = " ".$where." ";
     $where_a = $where;
     $from = " ".$from." ";
     if ( strlen($where) > strlen(" WHERE ") )
        $where = " ".$where." AND ";
     
     $criteria2b = $criteria_form;

     echo '<TABLE BORDER=1>
           <TR><TD CLASS="metatitle">Criteria</TD>
               <TD>'.$criteria_desc.'</TD></TR>
           </TABLE>
           <HR>';
  }
  else
  {
     $from = " FROM event ";
     $where = " WHERE ";
     $criteria2b = "";
  }

  /* Initialized Data */
  if ( $submit == "" )
  {
     $num_result_rows = -1;
     $current_view = -1;
  }
  /* Moving among the views */
  else
    $current_view = $submit;

  /* Get total number of events */
  $event_cnt = EventCnt($db);

  /* create SQL to get Unique Alerts */
  $sql = "SELECT distinctrow signature ".$from.$where_a;

  /* Run the query to determine the number of rows (No LIMIT)*/
  if ( $num_result_rows == -1 )
  {
     $current_view = 0;
     $result = mysql_query($sql, $db);
     if ( $result  )
     {
        $num_result_rows = mysql_num_rows($result);
        mysql_free_result($result);
     }
     else
        $num_result_rows = 0;
   }
 
  /* Generate SQL with the sort criteria */
  if ( $sort_order == "sig" )      $field_tmp = " ";
  if ( $sort_order == "first" )    $field_tmp = ", min(timestamp) AS first_timestamp ";
  if ( $sort_order == "last" )     $field_tmp = ", max(timestamp) AS last_timestamp ";
  if ( $sort_order == "occur_a" )  $field_tmp = ", count(signature) AS sig_cnt ";
  if ( $sort_order == "occur_d" )  $field_tmp = ", count(signature) AS sig_cnt ";
  $sql = "SELECT distinctrow signature ".$field_tmp.$from.$where_a;

  $sort_tmp = " ORDER BY signature ";
  if ( $sort_order == "sig" )      $sort_tmp = " ORDER BY signature ASC";
  if ( $sort_order == "first" )    $sort_tmp = " GROUP BY signature ORDER BY first_timestamp ASC";
  if ( $sort_order == "last" )     $sort_tmp = " GROUP BY signature ORDER BY last_timestamp DESC";
  if ( $sort_order == "occur_a" )  $sort_tmp = " GROUP BY signature ORDER BY sig_cnt ASC";
  if ( $sort_order == "occur_d" )  $sort_tmp = " GROUP BY signature ORDER BY sig_cnt DESC ";

  /* Run the Query again for the actual data (with the LIMIT) */
  if ( $caller == "most_frequent" )
     $limit_tmp = " LIMIT 0,".$freq_num_alerts;
  else if ( $caller == "last_alerts" )
     $limit_tmp = " LIMIT 0,".$last_num_ualerts;
  else
     $limit_tmp = " LIMIT ".($current_view * $show_rows).",".$show_rows;

  if ( $debug_mode == 1 )
     echo $sql.$sort_tmp.$limit_tmp;

  $result = mysql_query($sql.$sort_tmp.$limit_tmp, $db);

  /* Print the current view number and # of rows */
  if ( $num_result_rows != 0 )
  {
     if ( $caller == "most_frequent" )
        printf("<FONT><CENTER>Displaying %d Most Frequent Alerts<BR> ".
            "</CENTER></FONT><BR>\n", 
            $freq_num_alerts);
     else if ( $caller == "last_alerts" )
        printf("<FONT><CENTER>Displaying the Last %d Alerts<BR> ".
            "</CENTER></FONT><BR>\n", 
            $last_num_alerts);
     else        
         printf("<FONT><CENTER>Displaying alerts %d-%d of %d total<BR> ".
            "(Aggregating %d events)</CENTER></FONT><BR>\n", 
            ($current_view * $show_rows)+1, 
            (($current_view * $show_rows) + $show_rows-1) < $num_result_rows ? 
            (($current_view * $show_rows) + $show_rows) : $num_result_rows, 
            $num_result_rows,
            $event_cnt);

     $param_str = "&criteria=".rawurlencode($criteria).
                  "&criteria_desc=".rawurlencode($criteria_desc);


     echo '<FONT><CENTER>'.
          'Sort by: '.
          '<A HREF="acid_stat_alerts.php?sort_order=sig'.$param_str.'">Signature</A> | '.
          'Total (<A HREF="acid_stat_alerts.php?sort_order=occur_a'.$param_str.'">ascending</A>, '.
                 '<A HREF="acid_stat_alerts.php?sort_order=occur_d'.$param_str.'">descending</A>) / '.
          '<A HREF="acid_stat_alerts.php?sort_order=first'.$param_str.'">First</A> / '.
          '<A HREF="acid_stat_alerts.php?sort_order=last'.$param_str.'">Last</A> Occurrences '.
          '</FONT></CENTER><P>';
  }
  else
     printf("<P><B>No Alerts were found.  Is the database empty?</B><P>\n");

  echo '<FONT>&nbsp<B>Queried DB on </B><FONT> : '.date("D F d, Y H:i:s",time()).'</FONT>';
  /* Print the Statistics on Each of the Unique Alerts */
  echo '<TABLE BORDER=1>
        <TR>
           <TD CLASS="plfieldhdr">Signature</TD>
           <TD CLASS="plfieldhdr">Total<BR> Occurrences</TD>
           <TD CLASS="plfieldhdr">Num of Sensors</TD>
           <TD CLASS="plfieldhdr">Unique Src. Addr</TD>
           <TD CLASS="plfieldhdr">Unique Dest. Addr</TD>
           <TD CLASS="plfieldhdr">First<BR> Occurance</TD>
           <TD CLASS="plfieldhdr">Last<BR> Occurance</TD>
        </TR>';

while ( $myrow = mysql_fetch_row ($result) )
{
     $sig_name = $myrow[0];

     /* get Total Occurance */
     $temp = "SELECT count(*) ".$from.$where." signature='".$sig_name."'";
     $result2 = mysql_query($temp, $db);
     $myrow2 = mysql_fetch_row($result2);
     $total_occurances = $myrow2[0];
     mysql_free_result($result2);
     //echo $temp;

     /* Number of Sensor  */
     $temp = "SELECT distinctrow event.sid ".$from.$where." signature='".$sig_name."'";
     $result2 = mysql_query($temp, $db);
     $num_sensors = mysql_num_rows($result2);
     mysql_free_result($result2);
     //echo $temp;

     /* Unique Source Address with this signature */
     if ( strstr($from, "iphdr")  )
        $temp = "SELECT distinctrow ip_src ".$from.$where."signature='".$sig_name."'";
     else
        $temp = "SELECT distinctrow ip_src ".$from.
                "LEFT JOIN iphdr ON event.sid=iphdr.sid AND event.cid=iphdr.cid ". 
                $where."signature='".$sig_name."'";

     $result2 = mysql_query($temp, $db);
     $myrow = mysql_fetch_row($result2);
     if ( $myrow[0] == "" )
        $num_src_ip = 0;
     else
        $num_src_ip = mysql_num_rows($result2);
     mysql_free_result($result2); 
     //echo $temp;

     /* Unique Dest. Address with this signature */
     if ( strstr($from, "iphdr")  )
        $temp = "SELECT distinctrow ip_dst ".$from.$where."signature='".$sig_name."'";
     else
        $temp = "SELECT distinctrow ip_dst ".$from.
                "LEFT JOIN iphdr ON event.sid=iphdr.sid AND event.cid=iphdr.cid ". 
                $where."signature='".$sig_name."'";

     $result2 = mysql_query($temp, $db);
     $myrow = mysql_fetch_row($result2);
     if ( $myrow[0] == "" )
        $num_dst_ip = 0;
     else
        $num_dst_ip = mysql_num_rows($result2);
     mysql_free_result($result2); 

     /* First and Last timestamp of this signature */
     $temp = "SELECT min(timestamp), max(timestamp) ".$from.$where." signature='".$sig_name."'";
     $result2 = mysql_query($temp, $db);
     $myrow = mysql_fetch_row($result2);
     $start_time = $myrow[0];
     $stop_time = $myrow[1];
     mysql_free_result($result2);
     //echo $temp;

     if (strstr($from, "iphdr") == "" )
        $from_link = $from." LEFT JOIN iphdr ON event.sid=iphdr.sid AND event.cid=iphdr.cid ";
     else
        $from_link = $from;

     /* Print out */ 
     echo '<TR>';
     echo '  <TD ALIGN=CENTER CLASS="plfield">'.BuildSigLookup($sig_name);
     echo '  <TD ALIGN=CENTER CLASS="plfield">
               <FONT>
               <A HREF="acid_pkt_main.php?sig%5B0%5D=%3D&sig%5B1%5D='.
                              (rawurlencode($sig_name)).'&caller=stat_alerts'.
                              '&submit=Query+DB&num_result_rows=-1'.$criteria2b.'">'.$total_occurances.'</A> 
                    ('.(round($total_occurances/$event_cnt*100)).'%)
               </FONT>';
     echo '  <TD ALIGN=CENTER CLASS="plfield"><FONT>'.$num_sensors.'</FONT>';
     echo '  <TD ALIGN=CENTER CLASS="plfield">
               <FONT>'.
               BuildUniqueAddressLink("Signature=".$sig_name.'<BR>'.$criteria_desc, 1,
                                      "SELECT DISTINCTROW ip_src, ip_src0, ip_src1, ip_src2, ip_src3 ".
                                      $from_link.
                                      $where." signature='".$sig_name."' ".
                                      "ORDER BY ip_src",
                                      "&sig[0]=%3D&sig[1]=".$sig_name).$num_src_ip.'</A>
               </FONT>';
     echo '  <TD ALIGN=CENTER CLASS="plfield">
               <FONT>'.
               BuildUniqueAddressLink("Signature=".$sig_name.'<BR>'.$criteria_desc, 2,
                                      "SELECT DISTINCTROW ip_dst, ip_dst0, ip_dst1, ip_dst2, ip_dst3 ".
                                      $from_link.
                                      $where." signature='".$sig_name."' ".
                                      "ORDER BY ip_dst",
                                      "&sig[0]=%3D&sig[1]=".$sig_name).$num_dst_ip.'</A>
               </FONT>';
     echo '  <TD ALIGN=CENTER CLASS="plfield"><FONT>'.$start_time.'</FONT>';
     echo '  <TD ALIGN=CENTER CLASS="plfield"><FONT>'.$stop_time.'</FONT>';
     echo '  </TR>';
}
mysql_free_result($result);

echo "</TABLE>\n";

echo '<FORM ACTION="acid_stat_alerts.php" METHOD="POST">';
echo '<INPUT TYPE="hidden" NAME="num_result_rows" VALUE="'.$num_result_rows.'">';
echo '<INPUT TYPE="hidden" NAME="current_view" VALUE="'.$current_view.'">';
echo '<INPUT TYPE="hidden" NAME="criteria" VALUE="'.rawurlencode($criteria).'">';
echo '<INPUT TYPE="hidden" NAME="criteria_desc" VALUE="'.rawurlencode($criteria_desc).'">';
echo '<INPUt TYPE="hidden" NAME="criteria_form" VALUE="'.rawurlencode($criteria_form).'">';

/* ****** Print out Browsing Buttons ********************************************/
if ( $caller != "most_frequent" || $caller != "last_alerts" )
   PrintBrowseButtons($num_result_rows, $show_rows, $max_scroll_buttons, $current_view);

echo '</FORM>';

  mysql_close($db);
?>



<P>
<TABLE WIDTH="100%" BORDER=0 CELLSPACING=0 CELLPADDING=5>
<TR>
  <TD class="mainheader">
     <?php
       include("acid_footer.html");
     ?>
  </TD>
</TR>
</TABLE>

</BODY>
