<?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:   
 *
 */

  /* **************** Run the Query ************************************************** */

  /* If this is the first call to the search, process the raw user-entered criteria.
   * Otherwise, retrieve the previously generated SQL string from the shared state. 
   */
  if ( $num_result_rows == -1 )
  {
     ProcessCriteria();
     $sql = $sql.$join_sql.$where_sql.$criteria_sql;

     /* Apply sort criteria */
     if ( $caller == "last_tcp" || $caller == "last_udp" || 
         $caller == "last_icmp" || $caller == "last_any" )
            $sql = $sql." ORDER BY timestamp DESC ";
     else
     {
        if ( $sort_order == "time_a" )
           $sql = $sql." ORDER BY timestamp ASC ";  
        else if ( $sort_order == "time_d" )
           $sql = $sql." ORDER BY timestamp DESC ";
        else if ( $sort_order == "sig" )
           $sql = $sql." ORDER BY signature ";
     }
     $save_sql = $sql;
  }
  else
     $sql = $save_sql;

  /* Export the SQL into the shared state variable */
  /* if ( $save_sql == "" )
     $save_sql = $sql;
  else
     $sql = $save_sql; */

  if ( $debug_mode > 0 )
     echo "<P>SQL: $sql";

  /* 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 ( mysql_errno($db) > 0 )
     {
        ErrorMessage("<B>Query execution error:</B> ".mysql_error($db));
        die();
     }

     if ( $result  )
     {
        $num_result_rows = mysql_num_rows($result);
        mysql_free_result($result);
     }
     else
        $num_result_rows = 0;
   }

  /* Run the Query again for the actual data (with the LIMIT) */

  /* When display a Snapshot of alerts limit the number displayed */
  if ( $caller == "last_tcp" || $caller == "last_udp" || 
       $caller == "last_icmp" || $caller == "last_any" )
     $limit_tmp = " LIMIT 0, ".$last_num_alerts;
  else
     $limit_tmp = " LIMIT ".($current_view * $show_rows).",".$show_rows;

  if ( $save_sql != "" )
       $sql = $save_sql;
  $result = mysql_query($sql.$limit_tmp, $db);

  /* ***** Generate and print the criteria in human readable form */
  echo '<TABLE WIDTH="100%">
         <TR>
           <TD WIDTH="60%">';

        PrintCriteria($caller);
  /* ***** Print Analysis Links */
  $tmp_sql = CriteriaFromSQL($sql);
  $tmp_sql_s = "SELECT DISTINCT ip_src, ip_src0, ip_src1, ip_src2, ip_src3 ".$tmp_sql; 
  $tmp_sql_d = "SELECT DISTINCT ip_dst, ip_dst0, ip_dst1, ip_dst2, ip_dst3 ".$tmp_sql;
  if ( $caller == "last_tcp" || $caller == "last_udp" ||
       $caller == "last_icmp" || $caller == "last_any" )
       $tmp_sql_limit = " LIMIT 0, ".$last_num_alerts; 


  echo   '</TD>
           <TD WIDTH="40%" VALIGN=TOP>
            <TABLE WIDTH="100%" BORDER=1>
              <TR><TD class="sectiontitle">&nbsp;Statistics</TD></TR>
              <TR><TD>
               <UL>
                 <LI>General statistics
                 <LI>Unique addresses: '. 
                   BuildUniqueAddressLink($save_criteria, 1, 
                                         $tmp_sql_s." AND ip_src >= 0 ORDER BY ip_src".$tmp_sql_limit,"").
                   'source</A> | '.
                   BuildUniqueAddressLink($save_criteria, 2, 
                                         $tmp_sql_d." AND ip_dst >= 0 ORDER BY ip_dst".$tmp_sql_limit,"").
                   'destination</A>
                 <LI>'.
                   /*BuildUniqueAlertLink($tmp_sql, $save_criteria, "").*/
                                        'Alert Listing</A>
               </UL>
              </TD></TR></TABLE>
            </TD>
          </TR>
         </TABLE>';

  if ( $debug_mode == 1 )
     printf("<P>%s<HR>\n", $sql.$limit_tmp);

  /* Print the current view number and # of rows */
  if ( $num_result_rows != 0 )
  {
     $num_rows = mysql_num_rows($result);
     if (  $caller == "last_tcp" || $caller == "last_udp" || 
           $caller == "last_icmp" || $caller == "last_any" ) 
        printf("<HR><FONT><CENTER> Displaying <B>last %d</B> rows of %d</CENTER></FONT><BR>\n", 
               $last_num_alerts, $num_result_rows);
     else
        printf("<HR><FONT><CENTER>Displaying rows %d-%d of %d </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);
  }
  else
     printf("<P><HR><B>No Packets were found matching the specified criteria.  0 Rows returned.</B><P><P>\n");


  /* Print the search results */
  if ( $num_rows > 0 )
  {
     /* Client-side Javascript to select all the check-boxes on the screen
      *   - Bill Marque (wlmarque@hewitt.com) */
     echo '
          <SCRIPT Language=Javascript>
            function SelectAll()
            {
               for(var i=0;i<document.PacketForm.elements.length;i++)
               {
                  if(document.PacketForm.elements[i].type == "checkbox")
                  {
                    document.PacketForm.elements[i].checked = true;
                  }
               }
            }
      
            function UnselectAll()
            {
                for(var i=0;i<document.PacketForm.elements.length;i++)
                {
                    if(document.PacketForm.elements[i].type == "checkbox")
                    {
                      document.PacketForm.elements[i].checked = false;
                    }
                }
            }
           </SCRIPT>';

    echo '<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 WIDTH="100%">';
    echo '<TR>
             <TD><INPUT type=checkbox value="Select All" onClick="if (this.checked) SelectAll(); if (!this.checked) UnselectAll();"></TD>
              <TD CLASS="plfieldhdr">ID</TD>
              <TD CLASS="plfieldhdr">Signature</TD>
              <TD CLASS="plfieldhdr">TimeStamp</TD>
              <TD CLASS="plfieldhdr">Source<BR>Address</TD>
              <TD CLASS="plfieldhdr">Dest.<BR>Address</TD>
              <TD CLASS="plfieldhdr">Layer 4<BR>Protocol</TD>';

    /* Clear the old checked positions */
    for ( $i = 0; $i < $show_rows; $i++)  
    { 
        $action_lst[$i] = "";  
        $action_chk_lst[$i] = ""; 
    }

    for ( $i = 0; $i < $num_rows; $i++ )
    {
      $myrow = mysql_fetch_row($result);
      echo '<TR BGCOLOR="'.((($i % 2) == 0) ? "DDDDDD" : "FFFFFF").'">';

      $tmp_rowid = "#".(($current_view * $show_rows)+$i)."-(".$myrow[0]."-".$myrow[1].")";

      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.'">';
      echo '    <TD>';
      //if ( $caller == "last_tcp" || $caller == "last_udp" ||
      //     $caller == "last_icmp" || $caller == "last_any" )
      //   $save_sql = $save_sql." 0, ".$last_num_alerts; 

      echo '        <CENTER>
                    <A HREF="acid_pkt_main.php?submit='.rawurlencode($tmp_rowid).
                            '&save_sql='.rawurlencode($save_sql).'">'.$tmp_rowid.'</A>
                    </CENTER>';
      echo '        </FONT></TD>';
      echo '    <TD ALIGN=CENTER>'.BuildSigLookup($myrow[2]).'</TD>';
      echo '    <TD ALIGN=CENTER>'.$myrow[3];
      $tmp_iplookup = 'acid_pkt_main.php?sig%5B0%5D=%3D'.
                          '&num_result_rows=-1'.
                          '&time%5B0%5D%5B0%5D=+&time%5B0%5D%5B1%5D=+'.
                          '&submit=Query+DB&current_view=-1&ip_addr_cnt=2';
      echo '    <TD ALIGN=CENTER>';
      if ( $myrow[4] != "" )
         echo '   <A HREF="acid_stat_ipaddr.php?'.
                        'ip0='.$myrow[4].'&ip1='.$myrow[5].'&ip2='.$myrow[6].'&ip3='.$myrow[7].'&netmask=32">'.
                                $myrow[4].".".$myrow[5].".".$myrow[6].".".$myrow[7].'</A>';
      else
         echo '   <A HREF="acid_app_faq.php#1">unknown</A>';

      echo '    <TD ALIGN=CENTER>';
      if ( $myrow[8] != "" )
         echo '   <A HREF="acid_stat_ipaddr.php?'.
                        'ip0='.$myrow[8].'&ip1='.$myrow[9].'&ip2='.$myrow[10].'&ip3='.$myrow[11].'&netmask=32">'.
                                $myrow[8].".".$myrow[9].".".$myrow[10].".".$myrow[11].'</A>';
       else
         echo '   <A HREF="acid_app_faq.php#1">unknown</A>';    

      echo '    <TD ALIGN=CENTER><FONT>'.IPProto2str($myrow[12]).'</FONT></TD></TR>';
    }
    mysql_free_result($result);
  }
  echo "</TABLE>";

  /* Print Browsing Buttons
   *   Only print the browsing buttons if not returning a snapshot */
  if ( !($caller == "last_tcp" || $caller == "last_udp" || 
         $caller == "last_icmp" || $caller == "last_any") )
     PrintBrowseButtons($num_result_rows, $show_rows, $max_scroll_buttons, $current_view);

  /* Print out the Action information */
  if ( $num_result_rows > 0 ) 
     PrintQueryResultAction($action, $ag_add_key, 2); 
?>






