<?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: executes and prints the query results   
 *
 */

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

  /* acid_ag_main.php will include this file 
   *  - imported variables: $sql, $cnt_sql
   */

  ProcessCriteria();

  if ( $printing_ag )
  {
     $page = "acid_ag_main.php";
     $tmp_page_get = "&ag_action=view&ag_id=$ag_id&submit=x";
     $sql = $save_sql;
  }
  else
  {
     $page = "acid_qry_main.php";
     $cnt_sql = "SELECT COUNT(acid_event.cid) FROM acid_event ".$join_sql.$where_sql.$criteria_sql;
     $tmp_page_get = "";
  }

  /* 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("$page".$qs->SaveStateGET().$tmp_page_get);

  $qro->AddTitle(qroReturnSelectALLCheck());
  $qro->AddTitle("ID");

  if ($db->DB_type != "mssql")
    $qro->AddTitle("Signature", 
                "sig_a", " ",
                         " ORDER BY sig_name ASC",
                "sig_d", " ",
                         " ORDER BY sig_name DESC");
  else
    $qro->AddTitle("Signature",
                "sig_a", " ",
                         " ORDER BY CONVERT(varchar(255), sig_name) ASC",
                "sig_d", " ",
                         " ORDER BY CONVERT(varchar(255), sig_name) DESC");

  $qro->AddTitle("Timestamp",
                 "time_a", " ", " ORDER BY timestamp ASC ",
                 "time_d", " ", " ORDER BY timestamp DESC "); 
  $qro->AddTitle("Source<BR>Address", 
                 "sip_a", " ", " ORDER BY ip_src ASC",
                 "sip_d", " ", " ORDER BY ip_src DESC");
  $qro->AddTitle("Dest.<BR>Address", 
                 "dip_a", " ", " ORDER BY ip_dst ASC",
                 "dip_d", " ", " ORDER BY ip_dst DESC");
  $qro->AddTitle("Layer 4<BR>Proto", 
                 "proto_a", " ", " ORDER BY layer4_proto ASC",
                 "proto_d", " ", " ORDER BY layer4_proto DESC");

  if ( !$printing_ag)
     $sql = $sql.$join_sql.$where_sql.$criteria_sql;

  /* Apply sort criteria */
  if ( $qs->isCannedQuery() )
     $sql = $sql." ORDER BY timestamp DESC ";
  else
  {
     $sort_sql = $qro->GetSortSQL($qs->GetCurrentSort(), $qs->GetCurrentCannedQuerySort());
     $sql = $sql." ".$sort_sql[1];
  }

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

  /* 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>";
  }

  if ( !$printing_ag )
  {
     /* ***** Generate and print the criteria in human readable form */
     echo '<TABLE WIDTH="100%">
           <TR>
             <TD WIDTH="60%" VALIGN=TOP>';

     PrintCriteria($caller);

     echo '</TD>
           <TD WIDTH="40%" VALIGN=TOP>';
      
     PrintFramedBoxHeader("Summary Statistics", "#669999", "#FFFFFF");
     PrintGeneralStats($db, 1, $show_summary_stats, 
                       "$join_sql ", "$where_sql $criteria_sql"); 
     echo '<BR><LI><A HREF="acid_stat_time.php">Time profile</A> of alerts';
     PrintFramedBoxFooter();

     echo ' </TD>
           </TR>
          </TABLE>';
  }

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

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

    $i = 0;
    while ( ($myrow = $result->acidFetchRow()) && ($i < $qs->GetDisplayRowCnt() )/*($i < $limit_offset)*/ )
    {
      $current_sip32 = $myrow[4];
      $current_sip = acidLong2IP($current_sip32);
      $current_dip32 = $myrow[5];
      $current_dip = acidLong2IP($current_dip32); 
      $current_proto = $myrow[6];
      $current_sig = BuildSigByID($myrow[2], $db);
      $current_sig_txt = BuildSigByID($myrow[2], $db, 2);
      $current_sport = $current_dport = "";

      qroPrintEntryHeader($i);

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

      qroPrintEntry('<INPUT TYPE="checkbox" NAME="action_chk_lst['.$i.']" VALUE="'.
                    $tmp_rowid.'">');
      echo '    <INPUT TYPE="hidden" NAME="action_lst['.$i.']" VALUE="'.$tmp_rowid.'">';
      qroPrintEntry('<A HREF="acid_qry_alert.php?submit='.rawurlencode($tmp_rowid).
                    '&sort_order='.$qs->getCurrentSort().'">'.
                    $tmp_rowid.
                    '</A>');
      qroPrintEntry($current_sig);
      qroPrintEntry($myrow[3]);

      $tmp_iplookup = 'acid_qry_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';

      /* TCP or UDP show the associated port # */ 
      if ( $current_proto == TCP )
         $result4 = $db->acidExecute("SELECT tcp_sport, tcp_dport FROM tcphdr ".
                                     "WHERE sid=".$myrow[0]." AND cid=".$myrow[1]);
      else if ( $current_proto == UDP )
         $result4 = $db->acidExecute("SELECT udp_sport, udp_dport FROM udphdr ".
                                     "WHERE sid=".$myrow[0]." AND cid=".$myrow[1]);
      
      if ( ($current_proto == TCP) || ($current_proto == UDP) )
      {
         $myrow4 = $result4->acidFetchRow();

         if ( $myrow4[0] != "" )  $current_sport = ":".$myrow4[0];
         if ( $myrow4[1] != "" )  $current_dport = ":".$myrow4[1];
      }
      
      if ( $current_sip32 != "" )
      {
         qroPrintEntry('<A HREF="acid_stat_ipaddr.php?ip='.$current_sip.'&netmask=32">'.
                       $current_sip.
                       '</A><FONT SIZE="-1">'.$current_sport.'</FONT>');
      }
      else
      {
        /* if no IP address was found check if this is a spp_portscan message
         * and try to extract a source IP
         * - contrib: Michael Bell <michael.bell@web.de>
         */
        if ( stristr($current_sig_txt, "portscan") )
        {
           $line = split (" ", $current_sig_txt);
           foreach ($line as $ps_element) 
           {
             if ( ereg("[0-9]*\.[0-9]*\.[0-9]*\.[0-9]", $ps_element)  )
             {
                $ps_element = ereg_replace (":", "", $ps_element);
                qroPrintEntry("<A HREF=\"acid_stat_ipaddr.php?ip=".$ps_element."&netmask=32\">".
                              $ps_element."</A>");
             }
           }
        }
        else
           qroPrintEntry('<A HREF="acid_app_faq.php#1">unknown</A>');
      }

      if ( $current_dip32 != "" )
         qroPrintEntry('<A HREF="acid_stat_ipaddr.php?ip='.$current_dip.'&netmask32">'.
                       $current_dip.
                       '</A><FONT SIZE="-1">'.$current_dport.'</FONT>');
       else
         qroPrintEntry('<A HREF="acid_app_faq.php#1">unknown</A>');    

      qroPrintEntry('<FONT>'.IPProto2str($current_proto).'</FONT>');

      qroPrintEntryFooter();

      $i++;
      if ( ($current_proto == 6) || ($current_proto == 17) )
      {
         $result4->acidFreeRows();
         $myrow4[0] = $myrow4[1] = "";
      }
    }
    $result->acidFreeRows();

  $qro->PrintFooter();

  $qs->PrintBrowseButtons();
  $qs->PrintAlertActionButtons();
?>








