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

/*
 * $caller: an auxiliary variable used to determine the how the search parameters were entered (i.e.
 *          whether through a form or through another mechanism
 *  - "stat_alerts" : display results based on the the Alert Listings
 *  - "top_tcp" :
 *  - "top_udp" :
 *  - "top_icmp" :
 *  - "last_tcp" :
 *  - "last_udp" :
 *  - "last_icmp" :
 *
 * $submit: used to determine the next action which should be taken when the form is submitted.
 *  - "Query DB"       : triggers a query into the database
 *  - "ADD Time"       : adds another date/time row 
 *  - "ADD Addr"       : adds another IP address row
 *  - "ADD IP Field"   : adds another IP field row
 *  - "ADD TCP Port"   : adds another TCP port row
 *  - "ADD TCP Field"  : adds another TCP field row
 *  - "ADD UDP Port"   : adds another UDP port row
 *  - "ADD UDP Field"  : adds another UDP field row
 *  - "ADD ICMP Field" : adds another ICMP field row
 *  - "#X-(X-X)"       : sid-cid keys for a packet lookup
 *
 * $layer4: stores the layer 4 protocol used in query
 *
 * $save_sql: the current sql string generating the query
 *
 * $save_criteria: HTML-human readable criteria of the $save_sql string
 *
 * $num_result_rows: rows in the entire record set retried under the current 
 *                   query
 *
 * $current_view: current view of the result set
 *
 * Meta
 * ====
 *
 * $time[MAX][10]: stores the date/time of the packet detection
 *  - [][0] : (                           [][5] : hour  
 *  - [][1] : =, !=, <, <=, >, >=         [][6] : minute
 *  - [][2] : month                       [][7] : second
 *  - [][3] : day                         [][8] : (, )
 *  - [][4] : year                        [][9] : AND, OR
 *
 * $time_cnt : number of rows in the $time[][] structure
 *
 * IP Variables
 * ============
 *
 * $ip_addr[MAX][10]: stores an ip address parameters/operators row
 *  - [][0] : (                          [][5] : octet3 of address
 *  - [][1] : source, dest               [][6] : octet4 of address
 *  - [][2] : =, !=                      [][7] : network mask
 *  - [][3] : octet1 of address          [][8] : (, )
 *  - [][4] : octet2 of address          [][9] : AND, OR
 *
 * $ip_addr_cnt: number of rows in the $ip_addr[][] structure
 *
 * $ip_field[MAX][6]: stores all other ip fields parameters/operators row
 *  - [][0] : (                            [][3] : field value
 *  - [][1] : TOS, TTL, ID, offset, length [][4] : (, )
 *  - [][2] : =, !=, <, <=, >, >=          [][5] : AND, OR
 *
 * $ip_field_cnt: number of rows in the $ip_field[][] structure
 *
 * TCP Variables
 * =============
 *
 * $tcp_port[MAX][6]: stores all port parameters/operators row
 *  - [][0] : (                            [][3] : port value
 *  - [][1] : Source Port, Dest Port       [][4] : (, )
 *  - [][2] : =, !=, <, <=, >, >=          [][5] : AND, OR
 *
 * $tcp_port_cnt: number of rows in the $tcp_port[][] structure
 *
 * $tcp_flags[7]: stores all other tcp flags parameters/operators row
 *  - [0] : is, contains                   [4] : 8     (RST)
 *  - [1] : 1   (FIN)                      [5] : 16    (ACK)
 *  - [2] : 2   (SYN)                      [6] : 32    (URG)
 *  - [3] : 4   (PUSH)
 *
 * $tcp_field[MAX][6]: stores all other tcp fields parameters/operators row
 *  - [][0] : (                            [][3] : field value
 *  - [][1] : windows, URP                 [][4] : (, )
 *  - [][2] : =, !=, <, <=, >, >=          [][5] : AND, OR
 *
 * $tcp_field_cnt: number of rows in the $tcp_field[][] structure
 *
 * UDP Variables
 * =============
 *
 * $udp_port[MAX][6]: stores all port parameters/operators row
 *  - [][0] : (                            [][3] : port value
 *  - [][1] : Source Port, Dest Port       [][4] : (, )
 *  - [][2] : =, !=, <, <=, >, >=          [][5] : AND, OR
 *
 * $udp_port_cnt: number of rows in the $udp_port[][] structure
 *
 * $udp_field[MAX][6]: stores all other udp fields parameters/operators row
 *  - [][0] : (                            [][3] : field value
 *  - [][1] : length                       [][4] : (, )
 *  - [][2] : =, !=, <, <=, >, >=          [][5] : AND, OR
 *
 * $udp_field_cnt: number of rows in the $udp_field[][] structure
 *
 * ICMP Variables
 * ==============
 * $icmp_field[MAX][6]: stores all other icmp fields parameters/operators row
 *  - [][0] : (                            [][3] : field value
 *  - [][1] : code, length                 [][4] : (, )
 *  - [][2] : =, !=, <, <=, >, >=          [][5] : AND, OR
 *
 * $icmp_field_cnt: number of rows in the $icmp_field[][] structure
 *
 * Payload Variables
 * =================
 * $data_encode[2]: how the payload should be interpreted and converted
 *  - [0] : encoding type (hex, ascii)
 *  - [1] : conversion type (hex, ascii) 
 *
 * $data[MAX][5]: stores all the payload related parameters/operators row
 *  - [][0] : (                            [][3] : (, )
 *  - [][1] : =, !=                        [][4] : AND, OR
 *  - [][2] : field value
 *
 * $data_cnt: number of rows in the $data[][] structure
 */
?>

<?php
  include("acid_conf.php");
  include("acid_db_common.php");
  include("acid_common.php");
  include("acid_ag_common.php");
  include("acid_pkt_common.php");

/* Code to correct 'interesting' (read: unexplained) browser behavior */

/* Lynx incorrectly modifies appended variables at the end of the URL occasionally.
     e.g. ...Submit+Query&num_result_row=-1  becomes ...Submit+Query#_result_row=-1
   I am at a loss as to why this happens, however, I am inserting logic here and
   there to prevent it from breaking ACID too seriously. */
if ( $num_result_rows == "" )
   $num_result_rows = -1;

/* Something with Netscape 4.75 such that the $submit variable is no recognized
   under certain circumstances.  This one is a result of using HTTPS and 
   clicking on TCP traffic profile from acid_main.php */
if ( $layer4 != "" && $submit == "" )
   $submit = "Query DB";

/* End 'interesting' browser code fixes */

?>

<!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">

<?php
  if ( $caller == "last_tcp" || $caller == "last_udp" || 
       $caller == "last_icmp" || $caller == "last_any" )
       PrintFreshPage($refresh_stat_page, $stat_page_refresh_time);

    if ( $caller == "last_tcp" )
       echo '  <TITLE>ACID: Last '.$last_num_alerts.' TCP Alerts</TITLE>'; 
    else if ( $caller == "last_udp" )
       echo '  <TITLE>ACID: Last '.$last_num_alerts.' UDP Alerts</TITLE>'; 
    else if ( $caller == "last_icmp" )
       echo '  <TITLE>ACID: Last '.$last_num_alerts.' ICMP Alerts</TITLE>'; 
    else if ( $caller == "last_any" )
       echo '  <TITLE>ACID: Last '.$last_num_alerts.' Alerts</TITLE>';
    else if ( $caller == "stat_alerts" )
       echo '  <TITLE>ACID: Alert Search Results</TITLE>';
    else if ($submit == "Query DB" )
       echo '  <TITLE>ACID: Query Results</TITLE>';
    else if ( strstr($submit, "#") != "" )
       echo '  <TITLE>ACID: Packet Display</TITLE>';
    else 
       echo '  <TITLE>ACID: Query by Packet</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>
<?php
  if ( $caller == "last_tcp" )
     echo '  <TD class="mainheadertitle">Last '.$last_num_alerts.' TCP Alerts</TD>';
  else if ( $caller == "last_udp" )
     echo '  <TD class="mainheadertitle">Last '.$last_num_alerts.' UDP Alerts</TD>';
  else if ( $caller == "last_icmp" )
     echo '  <TD class="mainheadertitle">Last '.$last_num_alerts.' ICMP Alerts</TD>';
  else if ( $caller == "last_any" )
     echo '  <TD class="mainheadertitle">Last '.$last_num_alerts.' Alerts</TD>';
  else if ( $caller == "stat_alerts" )
     echo '  <TD class="mainheadertitle">Alert Search Results</TD>';
  else if ($submit == "Query DB" )
     echo '  <TD class="mainheadertitle">Query Results</TD>';
  else if ( strstr($submit, "#") != "" )
     echo '  <TD class="mainheadertitle">Packet Display</TD>';
  else
     echo '  <TD class="mainheadertitle">Query by Packet</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);

  $t = rawurldecode($save_criteria);
  $save_criteria = $t;
?>

<FORM METHOD="POST" NAME="PacketForm" ACTION="acid_pkt_main.php">

<?php
/* Initialized Data */
if ( $submit == "" )
{
   $time_cnt = 1;
   $ip_addr_cnt = 1;
   $ip_field_cnt = 1;
   $ip_opt_cnt = 1;
   $tcp_port_cnt = 1;
   $tcp_field_cnt = 1;
   $tcp_opt_cnt = 1;
   $udp_port_cnt = 1;
   $udp_field_cnt = 1;
   $icmp_field_cnt = 1;
   $data_cnt = 1;
   $layer4 = "";
   $save_sql = "";
   $save_criteria = "";
   $num_result_rows = -1;
   $current_view = -1;
}

if ( $submit == "TCP" )   {  $layer4 = "TCP";   }
if ( $submit == "UDP" )   {  $layer4 = "UDP";   }
if ( $submit == "ICMP" )  {  $layer4 = "ICMP";  }
if ( $submit == "no layer4" )  {  $layer4 = "";      }

if ( $submit == "ADD Time"             && $time_cnt < $MAX_ROWS)         
   AddCriteriaFormRow($submit, $layer4, $time_cnt, $time[$time_cnt-1][9]);
if ( $submit == "ADD Addr"             && $ip_addr_cnt < $MAX_ROWS)     
   AddCriteriaFormRow($submit, $layer4, $ip_addr_cnt, $ip_addr[$ip_addr_cnt-1][9]);
if ( $submit == "ADD IP Field"         && $ip_field_cnt < $MAX_ROWS)    
   AddCriteriaFormRow($submit, $layer4, $ip_field_cnt, $ip_field[$ip_field_cnt-1][5]);
/*if ( $submit == "ADD IP Option Field"  && $ip_opt_cnt < $MAX_ROWS)      
{  $submit = $layer4;  $ip_opt_cnt++;     }*/
if ( $submit == "ADD TCP Port"         && $tcp_port_cnt < $MAX_ROWS)    
   AddCriteriaFormRow($submit, $layer4, $tcp_port_cnt, $tcp_port[$tcp_port_cnt-1][5]);
if ( $submit == "ADD TCP Field"        && $tcp_field_cnt < $MAX_ROWS)   
   AddCriteriaFormRow($submit, $layer4, $tcp_field_cnt, $tcp_field[$tcp_field_cnt-1][5]);
/*if ( $submit == "ADD TCP Option Field" && $tcp_opt_cnt < $MAX_ROWS)     
{  $submit = $layer4;  $tcp_opt_cnt++;    } */
if ( $submit == "ADD UDP Port"         && $udp_port_cnt < $MAX_ROWS)    
   AddCriteriaFormRow($submit, $layer4, $udp_port_cnt, $udp_port[$udp_port_cnt-1][5]);
if ( $submit == "ADD UDP Field"        && $udp_field_cnt < $MAX_ROWS)
   AddCriteriaFormRow($submit, $layer4, $udp_field_cnt, $udp_field[$udp_field_cnt-1][5]);
if ( $submit == "ADD ICMP Field"       && $icmp_field_cnt < $MAX_ROWS)
   AddCriteriaFormRow($submit, $layer4, $icmp_field_cnt, $icmp_field[$icmp_field_cnt-1][5]);
if ( $submit == "ADD Payload"          && $data_cnt < $MAX_ROWS)
   AddCriteriaFormRow($submit, $layer4, $data_cnt, $data[$data_cnt-1][4]);

/* If the search form is configured to accept IP address as a single
 * field, re-populate the auxiliary array which breaks the addr into octets
 */
if ( $ip_address_input == 2 )
{
   for ( $i = 0; $i < $ip_addr_cnt; $i++)
   {
       $tmp = $ip_addrs[$i];
       if ( $ip_addrs[$i] != "" )
       {
          $ip_addr[$i][3] = strtok($tmp, ".");
          $ip_addr[$i][4] = strtok(".");
          $ip_addr[$i][5] = strtok(".");
          $ip_addr[$i][6] = strtok("");
       }
   }
}

/* Clean any SQL we passed */
InputSafeSQL($save_sql);

/* Dump some debugging information on the shared state */
if ( $debug_mode == 1 )
{
   PrintPageHeader();
   echo "<PRE>   
         <B>submit:</B> '$submit'
         <B>num_result_rows:</B> '$num_result_rows'  <B>current_view:</B> '$current_view'
         <B>layer4:</B> '$layer4'
         </PRE>";
   echo '<TABLE BORDER=1>';
   echo '<TR><TD>time_cnt<TD>ip_addr_cnt<TD>ip_field_cnt<TD>ip_opt_cnt<TD>tcp_port_cnt
             <TD>tcp_field_cnt<TD>tcp_opt_cnt<TD>udp_port_cnt<TD>udp_field_cnt
             <TD>icmp_field_cnt<TD>data_cnt</TR>';
   echo '<TR><TD>'.$time_cnt.'<TD>'.$ip_addr_cnt.'<TD>'.$ip_field_cnt.'<TD>'.$ip_opt_cnt.
            '<TD>'.$tcp_port_cnt.'<TD>'.$tcp_field_cnt.'<TD>'.$tcp_opt_cnt.
            '<TD>'.$udp_port_cnt.'<TD>'.$udp_field_cnt.'<TD>'.$icmp_field_cnt.
            '<TD>'.$data_cnt.'</TABLE>';
   printf("save_sql = %s<BR>", $save_sql);
   printf("save_criteria = %s<BR>", $save_criteria);
   printf("caller = %s<BR>", $caller);
   printf("action= %s<BR>\nag_add_key= %s<BR><HR>\n", $action, $ag_add_key);
}


if ( ($submit == "Selected" || $submit == "ALL on Screen" || $submit == "Entire Query") &&
     $action == " " )
   ErrorMessage("Some action was specified on the Alerts, but which one?");

/* add all alerts which were checked or on screen to the appropriate AG */
if ( ($action == "ag_by_id" || $action == "ag_by_name") &&
     ($submit == "Selected" || $submit == "ALL on Screen" || $submit == "Entire Query") )
{
   if ( $ag_add_key == "" )
      ErrorMessage("Could not add alerts since no AG was specified");
   else
   {
      if ($submit == "Selected")
      {
         /* if we are doing a packet lookup, only examine the first packet */
         if (strstr($caller, "#") != "")
            AddSelectedToAG($action_chk_lst, 1, $action, $ag_add_key, $submit, "", $db);
         else
            AddSelectedToAG($action_chk_lst, $show_rows, $action, $ag_add_key, $submit, "", $db);
      }
      else if ($submit == "ALL on Screen")
         AddSelectedToAG($action_lst, $show_rows, $action, $ag_add_key, $submit, "", $db);
      else if ($submit == "Entire Query")
      {
          if (  $caller == "last_tcp" || $caller == "last_udp" || 
             $caller == "last_icmp" || $caller == "last_any" )
          { 
             $limit_sql = " LIMIT 0, ".$last_num_alerts;
             $tmp_num = $last_num_alerts;
          }
          else
          {
             $limit_sql = "";
             $tmp_num = $num_result_rows;
          }  
          AddSelectedToAG($action_lst, $tmp_num, $action, $ag_add_key, $submit, $save_sql.$limit_sql, $db);      
      }

      if ( strstr($caller, "#") == "" )
         $submit = $current_view;
      else
         $submit = $caller;
   }
}

/*begin changes by SRH*/
/*email all alerts which were checked or on screen or in query*/
if ( ($action == "email_alert" ) &&
     ($submit == "Selected" || $submit == "ALL on Screen" || $submit == "Entire Query") )
{


include ("acid_email.php");

if ( strstr($caller, "#") == "" )
      $submit = $current_view;
   else
      $submit = $caller;

}
/* end changes by SRH */

/* delete all alerts which were checked or on screen  */
if ( ($action == "del_alert" ) &&
     ($submit == "Selected" || $submit == "ALL on Screen" || $submit == "Entire Query") )
{
   if ($submit == "Selected")
      DeleteSelectedAlerts($action_chk_lst, $show_rows, $submit, "", $num_result_rows, $db);
   else if ($submit == "ALL on Screen")
      DeleteSelectedAlerts($action_lst, $show_rows, $submit, "", $num_result_rows, $db);
   else if ($submit == "Entire Query")      
   {
      if (  $caller == "last_tcp" || $caller == "last_udp" || 
            $caller == "last_icmp" || $caller == "last_any" )
      { 
         $limit_sql = " LIMIT 0, ".$last_num_alerts;
         $tmp_num = $last_num_alerts;
      }
      else
      {
         $limit_sql = "";
         $tmp_num = $num_result_rows;
      }

      DeleteSelectedAlerts($action_lst, $tmp_num, $submit, $save_sql.$limit_sql, $num_result_rows, $db);
   }

   if ( strstr($caller, "#") == "" )
      $submit = $current_view;
   else
      $submit = $caller;
}

/* a browsing button was clicked */
if ( $num_result_rows > 0 && strstr($submit, "#") == "" )
{
    $current_view = $submit;
    $submit = "Query DB";
}

/* Run the SQL Query and get results */
if ( $submit == "Query DB" || 
     $caller == "last_any" || $caller == "last_tcp" || $caller == "last_udp" || $caller == "last_icmp")
{
   include("acid_pkt_sqlcalls.php");
}
/* Packet Lookup based on sid/cid */
else if ( strstr($submit, "#") != "" || strstr($caller, "#") != "")
{
   echo '<INPUT TYPE=hidden NAME="action_chk_lst[0]" VALUE="'.$submit.'">';   
   $caller = $submit;
   PacketLookup( $submit /* $caller */, $db, $save_sql, $mod_snort_config);
}

/* Return the input form to get more criteria from user */
else
{
   include("acid_pkt_form.php");

   echo '<P>
          <CENTER>
           <TABLE BORDER=1>
            <TR><TD>
              <FONT>
              <B>Sort order:</B>
              <INPUT TYPE="radio" NAME="sort_order" VALUE="none" '.chk_check($sort_order, "none").'> none |
              <INPUT TYPE="radio" NAME="sort_order" VALUE="time_a" '.chk_check($sort_order, "time_a").'> timestamp (ascend) |
              <INPUT TYPE="radio" NAME="sort_order" VALUE="time_d" '.chk_check($sort_order, "time_d").'> timestamp (descend) |
              <INPUT TYPE="radio" NAME="sort_order" VALUE="sig" '.chk_check($sort_order, "sig").'> signature <!--|
              <INPUT TYPE="radio" NAME="sort_order" VALUE="sip" '.chk_check($sort_order, "sip").'> source IP |
              <INPUT TYPE="radio" NAME="sort_order" VALUE="dip" '.chk_check($sort_order, "dip").'> dest. IP-->
              <BR>
              <CENTER><INPUT TYPE="submit" NAME="submit" VALUE="Query DB"></CENTER>
              </FONT>
             </TD></TR>
            </TABLE>
           </CENTER>';
}

/* Stores the neccessary variables for shared state between calls */
echo '<INPUT TYPE="hidden" NAME="time_cnt" VALUE="'.$time_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="layer4" VALUE="'.$layer4.'">';
echo '<INPUT TYPE="hidden" NAME="ip_addr_cnt" VALUE="'.$ip_addr_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="ip_field_cnt" VALUE="'.$ip_field_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="ip_opt_cnt" VALUE="'.$ip_opt_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="tcp_port_cnt" VALUE="'.$tcp_port_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="tcp_field_cnt" VALUE="'.$tcp_field_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="tcp_opt_cnt" VALUE="'.$tcp_opt_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="udp_port_cnt" VALUE="'.$udp_port_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="udp_field_cnt" VALUE="'.$udp_field_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="icmp_field_cnt" VALUE="'.$icmp_field_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="data_cnt" VALUE="'.$data_cnt.'">';
echo '<INPUT TYPE="hidden" NAME="save_sql" VALUE="'.$save_sql.'">';
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="save_criteria" VALUE="'.(rawurlencode($save_criteria)).'">';
echo '<INPUT TYPE="hidden" NAME="have_meta" VALUE="'.$have_meta.'">';
echo '<INPUT TYPE="hidden" NAME="have_ip" VALUE="'.$have_ip.'">';
echo '<INPUT TYPE="hidden" NAME="have_tcp" VALUE="'.$have_tcp.'">';
echo '<INPUT TYPE="hidden" NAME="have_udp" VALUE="'.$have_udp.'">';
echo '<INPUT TYPE="hidden" NAME="have_icmp" VALUE="'.$have_icmp.'">';
echo '<INPUT TYPE="hidden" NAME="have_data" VALUE="'.$have_data.'">';
echo '<INPUT TYPE="hidden" NAME="caller" VALUE="'.$caller.'">';
  mysql_close($db);
?>

</FORM>

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

</BODY>

</HTML>
