Location: PHPKode > projects > SnortCenter 2.x > snortcenter-release/db_pars.php
<?php
    /*
    ** SnortCenter Copyright (C) 2001,2002,2003 Stefan Dens
    **
    ** Author: Stefan Dens <hide@address.com>
    **
    ** This program is free software; you can redistribute it and/or modify
    ** it under the terms of the GNU General Public License as published by
    ** the Free Software Foundation; either version 2 of the License, or
    ** (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU General Public License for more details.
    **
    ** You should have received a copy of the GNU General Public License
    ** along with this program; if not, write to the Free Software
    ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
    */
?>
<?php
    include('config.php');
    include('top.inc.php');
    include("parser.php");
    include("sensor.inc.php");
     
    $db = NewACIDDBConnection($DBlib_path, $DBtype);
    $db->acidConnect($DB_dbname, $DB_host, $DB_port, $DB_user, $DB_password);
     
    if ($source == "net") {
        if (!$force) {
            $sql = "SELECT md5 FROM snortcenter_cfg WHERE filename = 'snortrules.tar.gz'";
            $result = $db->acidExecute($sql);
            $md5 = $result->acidFetchRow();
            if ($proxy  != '') {
                $proxyline = "--proxy $proxy";
            }
            if (strpos($_SERVER["SERVER_SOFTWARE"], "Win")  !== false) {
                if ($curl_path  != '') {
                    $curl_path = rtrim($curl_path, '\\') . '\\';
                }
                $fp = popen($curl_path."curl -s $proxyline $snortrules_url.md5", "r");
            } else {
                if ($curl_path  != '') {
                    $curl_path = rtrim($curl_path, '/') . '/';
                }
                $fp = popen($curl_path."curl -s $proxyline $snortrules_url.md5 2>/dev/null", "r");
            }
            while (!feof($fp)) {
                $foo = explode('=', fgets($fp, 4096));
                if (strpos($foo[0], 'MD5')  !== false) {
                    $foo[1] = trim($foo[1]);
                    if ($foo[1]  != $md5[0]) {
                        echo "<CENTER><B>New MD5 Checksum found: $foo[1]</B></CENTER><BR>";
                        if ($md5 == '') {
                            $sql = "INSERT INTO snortcenter_cfg (filename, md5) VALUES ('snortrules.tar.gz', '$foo[1]')";
                        } else {
                            $sql = "UPDATE snortcenter_cfg SET md5 = '".$foo[1]."' WHERE filename = 'snortrules.tar.gz'";
                        }
                        $result = $db->acidExecute($sql);
                        $new_checksum = 'yes';
                    } else {
                        echo "<CENTER><B>Same MD5 Checksum found, No update this time ...</B></CENTER>";
                    }
                }
            }
            pclose($fp);
        }
        if ($new_checksum == 'yes' || $force == "yes") {
            if ($proxy !='') { $proxyline = "--proxy $proxy"; }
            if (strpos($_SERVER["SERVER_SOFTWARE"], "Win") !== false) {
        	if ($curl_path !='') { $curl_path = rtrim($curl_path,'\\') . '\\'; }
                $fp=popen($curl_path."curl -s $proxyline $snortrules_url | gunzip -dcf - | tar -xOf - rules/*.rules rules/*.conf rules/*.config", "r");
            }
            else {
        	if ($curl_path !='') { $curl_path = rtrim($curl_path,'/') . '/'; }
        	$fp=popen($curl_path."curl -s $proxyline $snortrules_url 2>/dev/null | tar xzOf - rules/*.rules rules/*.conf rules/*.config", "r");
            }
	    $auto = 1;
            rule_insert($fp,$db,$auto);
            pclose($fp);
        }
    }
             
            if ($source == "upload") {
        	if (ini_get('file_uploads') == 1) {
	            echo '<BR><CENTER><FONT color="FFFFFF">Snort conf/rule file to Upload</FONT><BR>'."\n";
	            echo '<form method="POST" enctype="multipart/form-data" action="db_pars.php">'."\n";
	            echo "<input type=\"file\" name=\"uploadedfile\" size=\"30\">\n";
	            echo "<input type=\"hidden\" name=\"max_file_size\" value=\"1000000\">\n";
	            echo "<input type=\"hidden\" name=\"file\" value=\"ok\">\n";
	            echo "<input type=\"hidden\" name=\"sensor_id\" value=\"$sensor_id\">\n";
	            echo "&nbsp;<input type=\"submit\" value=\"UPLOAD\"></FORM></CENTER>\n";
                }
                else {
	            echo "<CENTER><BR>PHP doesn't allow to upload files.<BR>Edit your php.ini file and change 'file_uploads = On'<BR><BR></CENTER>";
    	        }
            }
             
            if ($file=="ok"){
		$auto = 0;
                if (ini_get('register_globals') != 1) {
	            if ($_FILES['uploadedfile'] != "") {
			if ( preg_match('/\.tar\.gz/', $_FILES['uploadedfile']['name']) ) {
			    $auto = 1;
			    $filename = $_FILES['uploadedfile']['tmp_name'];
	                    $fp=popen("tar xzOf $filename rules/*.rules rules/*.conf rules/*.config", "r");
	                    rule_insert($fp,$db,$auto);
	                    fclose($fp);
			} else {
	                    $fp=fopen($_FILES['uploadedfile']['tmp_name'], "r");
	                    rule_insert($fp,$db,$auto);
	                    fclose($fp);
			}
	            }
                }
                else {
	            if ($uploadedfile != "") {
	                $fp=fopen($uploadedfile, "r");
	                rule_insert($fp,$db,$auto);
	                fclose($fp);
        	    }
                }
            }
             
            if ($source == "cp_upload") {
		echo '<BR><CENTER><FONT color="FFFFFF">Copy & Past Snort rules to insert</FONT><BR>'."\n";
                echo '<form method="GET" action="db_pars.php">'."\n";
                echo '<TEXTAREA name=cp_rules rows=10 cols=90></TEXTAREA>';
	        echo "<input type=\"hidden\" name=\"sensor_id\" value=\"$sensor_id\">\n";
    	        echo "<BR><input type=\"submit\" value=\"Pars\"></FORM></CENTER>\n";
            }
             
            if ($cp_rules){
		$auto = 0;
                if (strpos($_SERVER["SERVER_SOFTWARE"], "Win") !== false) {
	            $tmpfname = tempnam ("c:/temp", "cp_");
                }
                else {
	            $tmpfname = tempnam ("/tmp", "cp_");
                }
                $fpo = fopen ("$tmpfname", "w");
                fwrite($fpo,stripslashes($cp_rules));
                fclose($fpo);
                $fp=fopen($tmpfname, "r");
                rule_insert($fp,$db,$auto);
                fclose($fp);
            }
             
            function rule_insert($fp,$db,$auto){
        	global $send_mail, $mail, $webmaster_email,$curl_timeout, $curl_path, $push;
	        $file_count = 0;
		include_once('list.inc.php');
        	while (!feof($fp)) {
        	    $foo = fgets($fp,4096);
//Parse Multiple Lines into One, Http_Inspect Preprocessor Caused This : )
                        $tmp1 = explode(' ',$foo);
                        $tmp2 = count($tmp1)-1;
                        while(strcmp(trim($tmp1[$tmp2]),'\\') == 0) {
                                array_pop($tmp1);
                                $foo = implode(' ',$tmp1);
                                $foo2 = fgets($fp,4096);
                                $foo = $foo.$foo2;
                                $tmp1 = explode(' ',$foo);
                                $tmp2 = count($tmp1) -1;
                        }
//End String Parser
		    if (strpos($foo, 'Id: ') == 3) {
	            	$foo1 = explode(',',$foo,2);
    			$foo2 = explode('Id:',trim($foo1[0]),2);
    			$foo3 = explode('$',trim($foo2[1]),2);
        		$file = trim($foo3[0]);
	            } else {
	        	$rule = pars_rule($foo);
			if ($rule['sid'] != '') {
	    		    $sid_in_config_where .= " sid != '".$rule['sid']."' AND";
			}
			if ($rule['action'] == "include") {
			    if (strpos($rule['rule_options'], '.rules') !== false) {
				if (trim($rule['rule_options']) != 'local.rules') {
				    $def_rule_cat[] = trim($rule['rule_options']);
				    # echo $rule['rule_options'] . '<br>';
				}
			    }
			}
    		        if (!$file) { $file = 'Unknown-Catagory.rules'; }
			if ($file != 'deleted.rules') {
	                        $count = write_rule($rule, $file, $auto, $db);
		        	$file_tmp=$count[0];
	                	if ($count[1]) {
				    if ($count[1] == 'add-var') { $file_count++; $new_var[] = $foo; $add_var[] = $count[2]; $var_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'update-var') { $file_count++; $update_var[] = $foo; $var_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'nochange-var') { $var_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'add-spp') { $file_count++; $new_spp[] = $foo; $add_spp[] = $count[2]; $spp_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'update-spp') { $file_count++; $update_spp[] = $foo; $spp_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'nochange-spp') { $spp_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'add-spo') { $file_count++; $new_spo[] = $foo; $add_spo[] = $count[2]; $spo_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'update-spo') { $file_count++; $update_spo[] = $foo; $spo_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'nochange-spo') { $var_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'add-ruletype') { $file_count++; $new_ruletype[] = $foo; $add_ruletype[] = $count[2]; $ruletype_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'update-ruletype') { $file_count++; $update_ruletype[] = $foo; $ruletype_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'nochange-ruletype') { $ruletype_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'add-config') { $file_count++; $new_config[$file_tmp][] = $foo; $add_config[] = $count[2]; $config_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'update-config') { $file_count++; $update_config[$file_tmp][] = $foo; $config_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'nochange-config') { $config_in_config_where .= " id != '".$count[2]."' AND"; }
				    elseif ($count[1] == 'add-rule') { $file_count++; $new_rule[$file_tmp][] = $foo; }
    				    elseif ($count[1] == 'update-rule') { $file_count++; $update_rule[$file_tmp][] = $foo; }
				}
        		}
		    }
        	}
		if ($auto != 0) { # begin auto
		    # Activate new variable, preprocessors, output plugins, ruletypes, configs for all snesor
		    $result_sensor = $db->acidExecute('select id from sensor');
	    	    while ($myrow_sensor = $result_sensor->acidFetchRow()) {
			if ($add_var) { activate($add_var, 'vars', $myrow_sensor[0], $db); }
			if ($add_spp) { activate($add_spp, 'preprocessor', $myrow_sensor[0], $db); }
			if ($add_spo) { activate($add_spo, 'output', $myrow_sensor[0], $db); }
			if ($add_ruletype) { activate($add_ruletype, 'ruletype', $myrow_sensor[0], $db); }
			if ($add_config) { activate($add_config, 'config', $myrow_sensor[0], $db); }
	
			# Deactivate removed variables, spp, spo, ruletypes, config
			if ($var_in_config_where) { $del_var_array = deactivate_removed($var_in_config_where, 'vars', $myrow_sensor[0], $db); }
		        if ($spp_in_config_where) { $del_spp_array = deactivate_removed($spp_in_config_where, 'preprocessor', $myrow_sensor[0], $db); }
	    		if ($spo_in_config_where) { $del_spo_array = deactivate_removed($spo_in_config_where, 'output', $myrow_sensor[0], $db); }
			if ($ruletype_in_config_where) { $del_ruletype_array = deactivate_removed($ruletype_in_config_where, 'ruletype', $myrow_sensor[0], $db); }
			if ($config_in_config_where) { $del_config_array = deactivate_removed($config_in_config_where, 'config', $myrow_sensor[0], $db); }
		    }
		    if ($del_var_array) { $del_var = get_removed($del_var_array, 'vars', $db); }
		    if ($del_spp_array) { $del_spp = get_removed($del_spp_array, 'preprocessor', $db); }
		    if ($del_spo_array) { $del_spo = get_removed($del_spo_array, 'output', $db); }
		    if ($del_ruletype_array) { $del_ruletype = get_removed($del_ruletype_array, 'ruletype', $db); }
		    if ($del_config_array) { $del_config = get_removed($del_config_array, 'config', $db); }
		    if ($del_var) $file_count++;
		    if ($del_spp) $file_count++;
		    if ($del_spo) $file_count++;
		    if ($del_ruletype) $file_count++;
		    if ($del_config) $file_count++;
		    
		    # createtemplate: Default Deleted Snort Rules	
		    if ($sid_in_config_where) {
			$sid_in_config_where = rtrim($sid_in_config_where, ' AND');
			# get array to display report
			$sql = "select sid, msg, category FROM rules WHERE ($sid_in_config_where AND category != 'local.rules' AND category != 'deleted.rules')";
			$result_del = $db->acidExecute($sql);
        		while ($myrow = $result_del->acidFetchRow()) {
			    $category = $myrow[2];
			    $del_rules[$category][] = 'sid: '.$myrow[0].'; msg: '.$myrow[1].';';
			}
			if ($del_rules) $file_count++;
			# move deleted rules to category deleted.rules and create template
			$sql = "select sid FROM rules WHERE ($sid_in_config_where AND category != 'local.rules' AND category != 'Unknown-Catagory.rules')";
			$result_del = $db->acidExecute($sql);
        		while ($myrow = $result_del->acidFetchRow()) {
			    $result = $db->acidExecute("UPDATE rules SET category= 'deleted.rules', rule_mark = 'del' WHERE sid = '$myrow[0]'");		
			    $del_add_sid .= '|'.$myrow[0].'|;';
			}
			$result = $db->acidExecute("UPDATE rules_template SET add_sid = '$del_add_sid' WHERE template_name = 'Activate unconfirmed deleted rules'");
		    }

		    # create Default templates
		    if ($def_rule_cat) {
			$where = 'WHERE (';
			$where_not = 'WHERE (';
			foreach($def_rule_cat as $rule_cat) {
			    $where .= " category = '$rule_cat' OR";
			    $where_not .= " category != '$rule_cat' AND";
			}
			$where = rtrim($where, ' OR');
	        	$where .= " ) AND (category != 'local.rules' AND category != 'Unknown-Catagory.rules' AND rule_mark != 'del')";
	        	$where_not .= " category != 'local.rules' AND category != 'Unknown-Catagory.rules' AND rule_mark != 'del')";
			# create template: Default Activated Snort Rules
			$sql = "select sid FROM rules $where";
			$result = $db->acidExecute($sql);
	        	while ($myrow = $result->acidFetchRow()) {
	    		    $add_sid .= '|'.$myrow[0].'|;';
			}
			$result = $db->acidExecute("UPDATE rules_template SET add_sid = '$add_sid' WHERE template_name = 'Activate Default Active Snort Ruleset'");
			# createtemplate: Default Disabled Snort Rules	
			$sql = "select sid FROM rules $where_not";
			$result = $db->acidExecute($sql);
	        	while ($myrow = $result->acidFetchRow()) {
			    $dis_add_sid .= '|'.$myrow[0].'|;';
			}
			$result = $db->acidExecute("UPDATE rules_template SET add_sid = '$dis_add_sid' WHERE template_name = 'Activate Default Inactive Snort Ruleset'");
		    }
		} # end auto
                if ($file_count > 0) {
	    	    echo "<CENTER><B>Update Report</B></CENTER>";
        	    echo "<table align=center border=0 cellspacing=0 cellpadding=0 width=90%><tr>";
        	    # -------- Begin left table --------------
        	    echo "<TD width=48% valign=top>";
            	    echo "<table align=center border=0 cellpadding=1 cellspacing=0 width=100%><tr bgcolor=#f9f890><td>";
            	    echo "<table style=\"font-size:12px; font-family: Verdana;\" align=center border=0 cellspacing=0 cellpadding=0 width=100%>";
            	    if ($send_mail == 1) {
	        	$date = date("l dS of F Y h:i:s A");
			$send_params['body'] .= "--- Update Report on $date ---\r\n";
            	    }
		    if ($new_var) $send_params['body'] .= print_report($new_var, 'New Variables');
		    if ($update_var) $send_params['body'] .= print_report($update_var, 'Updated Variables');
		    if ($del_var) $send_params['body'] .= print_report($del_var, 'Removed Variables');
		    if ($new_spp) $send_params['body'] .= print_report($new_spp, 'New Preprocessors');
		    if ($update_spp) $send_params['body'] .= print_report($update_spp, 'Updated Preprocessors');
		    if ($del_spp) $send_params['body'] .= print_report($del_spp, 'Removed Preprocessors');
		    if ($new_spo) $send_params['body'] .= print_report($new_spo, 'New Output Plugins');
		    if ($update_spo) $send_params['body'] .= print_report($update_spo, 'Updated Output Plugins');
		    if ($del_spo) $send_params['body'] .= print_report($del_spo, 'Removed Output Plugins');
		    if ($new_ruletype) $send_params['body'] .= print_report($new_ruletypes, 'New Ruletypes');
		    if ($update_ruletype) $send_params['body'] .= print_report($update_ruletypes, 'Updated Ruletypes');
		    if ($del_ruletype) $send_params['body'] .= print_report($del_ruletype, 'Removed Ruletypes');
		    if ($new_config['Reference(s)']) $send_params['body'] .= print_report($new_config['Reference(s)'], 'New References');
		    if ($update_config['Reference(s)']) $send_params['body'] .= print_report($update_config['Reference(s)'], 'Updated References');
		    if ($new_config['Classification(s)']) $send_params['body'] .= print_report($new_config['Classification(s)'], 'New Classifications');
		    if ($update_config['Classification(s)']) $send_params['body'] .= print_report($update_config['Classification(s)'], 'Updated Classifications');
		    if ($del_config) $send_params['body'] .= print_report($del_config, 'Removed Classification/Reference');
		    if ($new_rule) $send_params['body'] .= print_report($new_rule, 'New Rules');
		    if ($update_rule) $send_params['body'] .= print_report($update_rule, 'Updated Rules');
		    if ($del_rules) $send_params['body'] .= print_report($del_rules, 'Removed Rules');
        	    echo "</TABLE></TD></TR></TABLE></TD></TR></TABLE><BR>";
             
    		    if ($send_mail == 1) {
	        	include('smtp.inc.php');
			$mail['timeout'] = 20;
			$mail['helo'] = 'SnortCenter';   // What to use when sending the helo command. Typically, your domain/hostname
	        	$send_params['recipients'] = array("$webmaster_email"); // The recipients (can be multiple)
	        	$send_params['headers']  = array(
	        	'From: SnortCenter',"To: $webmaster_email",
	        	'Subject: SnortCenter Rule update report'
    	    		);
	        	$send_params['from']  = 'SnortCenter'; // This is used as in the MAIL FROM: cmd
			$smtp = smtp::connect($mail);
	        	if ($smtp) {
	        	    if(!$smtp->send($send_params)) {
	            		print_r($smtp->errors);
	        	    }
			} else { print_r($smtp->errors); }
            	    }
        	}
        	else {
        	    echo "<BR><CENTER><B>No update this time ...</B></CENTER><BR>";
        	}
             
        	if ($push == 'yes' && $file_count > 0) {
        	    $result = $db->acidExecute("select id, interface, enable from sensor");
        	    while ($myrow = $result->acidFetchRow()) {
		        if ($myrow[enable] == '1'){
		            $status = check_status($myrow['id'],$db);
	                }
	                else $status = 'disable';
	                if ($status == 'disable'){
		            $connect=2;
	                }
	                elseif(strstr($status,'Snort not Running')) {
		            $connect=1;
	                }
	                elseif(strstr($status,'Pid')){
		            $connect=1;
	                }
	                else{
		            $connect=0;
	                }
	                if ($connect == 1){
			    global $senstmpfnam;
		            $sensor_id = $myrow['id'];
		            $url = get_curl_url("upload",$sensor_id,$db);
		            $sensor_name = create_config("push", $sensor_id, $db);
		            if (strpos($_SERVER["SERVER_SOFTWARE"], "Win") !== false) {
		        	if ($curl_path !='') { $curl_path = rtrim($curl_path,'\\') . '\\'; }
		            }
		            else {
		                if ($curl_path !='') { $curl_path = rtrim($curl_path,'/') . '/'; }
		            }

		            $r_option = find_interface_pid($sensor_id,$db);
		            $curl_option = get_curl_option();
			    exec($curl_path."curl $curl_option -s -S --connect-timeout $curl_timeout -F \"interface=$myrow[interface]\" -F \"r_option=$r_option\" -F upload=@\"$senstmpfnam\" $url ", $return_string);
		            foreach ($return_string as $tmp_line) {
		                $line .= $tmp_line;
		            }
		            $cmd_err = push_cmd_line($sensor_id,$db);
		            echo "$line<BR>$cmd_err";
		            $url = get_curl_url("index",$sensor_id,$db);
		            $r_option = find_interface_pid($sensor_id,$db);
		            exec($curl_path."curl $curl_option -s -S --connect-timeout $curl_timeout -d \"sensor_control=stop&interface=$myrow[interface]&r_option=$r_option\" $url 2>&1", $return_string);
		            foreach ($return_string as $tmp_line) {
		                $line .= $tmp_line;
		            }
		            echo "<BR>$line";
		            $r_option = find_interface_pid($sensor_id,$db);
		            exec($curl_path."curl $curl_option -s -S --connect-timeout $curl_timeout -d \"sensor_control=start&interface=$myrow[interface]&r_option=$r_option\" $url 2>&1", $return_string);
		            foreach ($return_string as $tmp_line) {
		                $line .= $tmp_line;
		            }
		            echo "<BR>$line";
		            sleep(1); # give snort time to start
		        }
	            }
	        }
            }
             
            $db->acidClose();
            include('bottom.inc.php');
        ?>


Return current item: SnortCenter 2.x