示例#1
0
function load_layout($name_layout, $category = 'policy')
{
    $db = new ossim_db();
    $conn = $db->connect();
    $config = new User_config($conn);
    $login = Session::get_session_user();
    $data = $config->get($login, $name_layout, 'php', $category);
    return $data == null ? array() : $data;
}
示例#2
0
文件: 2.2.php 项目: jhbsz/ossimTest
 function end_upgrade()
 {
     require_once 'ossim_db.inc';
     $dbsock = new ossim_db();
     $db = $dbsock->connect();
     $configxml = "/etc/ossim/server/config.xml";
     $name = "Not found";
     // Check server name
     if (file_exists($configxml)) {
         $lines = file($configxml);
         foreach ($lines as $line) {
             if (preg_match("/\\<server.*name=\"([^\"]+)\"/", $line, $found)) {
                 $name = $found[1];
             }
         }
     }
     // Search in DB for name
     $sql = "SELECT * FROM server_role WHERE name=\"{$name}\"";
     if (!($rs = $db->Execute($sql))) {
         print $db->ErrorMsg();
     } elseif (!$rs->EOF) {
         // Found -> Update
         $correlate = $rs->fields['correlate'] ? "yes" : "no";
         $cross_correlate = $rs->fields['cross_correlate'] ? "yes" : "no";
         $store = $rs->fields['store'] ? "yes" : "no";
         $qualify = $rs->fields['qualify'] ? "yes" : "no";
         $resend_alarm = $rs->fields['resend_alarm'] ? "yes" : "no";
         $resend_event = $rs->fields['resend_event'] ? "yes" : "no";
         $sign = $rs->fields['sign'] ? "yes" : "no";
         $sem = $rs->fields['sem'] ? "yes" : "no";
         $sim = $rs->fields['sim'] ? "yes" : "no";
         $alarms_to_syslog = $rs->fields['alarms_to_syslog'] ? "yes" : "no";
         require_once 'classes/Config.inc';
         $conf = new Config();
         $conf->update("server_correlate", $correlate);
         $conf->update("server_cross_correlate", $cross_correlate);
         $conf->update("server_store", $store);
         $conf->update("server_qualify", $qualify);
         $conf->update("server_forward_alarm", $resend_alarm);
         $conf->update("server_forward_event", $resend_event);
         $conf->update("server_sign", $sign);
         $conf->update("server_sem", $sem);
         $conf->update("server_sim", $sim);
         $conf->update("server_alarms_to_syslog", $alarms_to_syslog);
     }
     exec("sudo /etc/init.d/ossim-server restart");
     //
     // Reload ACLS
     //
     $this->reload_acls();
     return true;
 }
示例#3
0
function get_report_uuid()
{
    require_once 'classes/Session.inc';
    $uuid = Session::get_secure_id();
    $url = null;
    if (empty($uuid)) {
        $db = new ossim_db();
        $dbconn = $db->connect();
        $user = Session::get_session_user();
        $query = 'SELECT * FROM `users` WHERE login="******"';
        $result = $dbconn->Execute($query);
        if (is_array($result->fields) && !empty($result->fields)) {
            $pass = $result->fields["pass"];
            $uuid = sha1($user . "#" . $pass);
        } else {
            $uuid = false;
        }
    }
    return $uuid;
}
function get_user_icon($login, $pro)
{
    ${$pixmaps} = '../pixmaps/user-green.png';
    $db = new ossim_db();
    $conn = $db->connect();
    $user = Session::get_list($conn, "WHERE login='******'");
    if ($pro) {
        // Pro-version
        if ($login == ACL_DEFAULT_OSSIM_ADMIN || $user[0]->get_is_admin()) {
            $pixmaps = '../pixmaps/user-gadmin.png';
        } elseif (Acl::is_proadmin($conn, $user[0]->get_login())) {
            $pixmaps = '../pixmaps/user-business.png';
        }
    } else {
        // Open Source
        if ($login == ACL_DEFAULT_OSSIM_ADMIN || $user[0]->get_is_admin()) {
            $pixmaps = "../pixmaps/user-gadmin.png";
        }
    }
    $db->close();
    return $pixmaps;
}
示例#5
0
function SIEM_trends_week($param = '')
{
    global $tz;
    $tzc = Util::get_tzc($tz);
    $data = array();
    $plugins = '';
    $plugins_sql = '';
    $db = new ossim_db(TRUE);
    $dbconn = $db->connect();
    $_asset_where = make_asset_filter();
    $asset_where = $_asset_where[1];
    $sensor_where = make_ctx_filter() . $asset_where;
    $tax_join = '';
    if (preg_match("/taxonomy\\=(.+)/", $param, $found)) {
        if ($found[1] == 'honeypot') {
            $tax_join = 'alienvault.plugin_sid p, ';
            $tax_where = 'AND acid_event.plugin_id = p.plugin_id AND acid_event.plugin_sid = p.sid AND p.category_id = 19';
        }
        $param = '';
    } elseif ($param == 'ossec%') {
        $plugins_sql = 'AND acid_event.plugin_id between ' . OSSEC_MIN_PLUGIN_ID . ' AND ' . OSSEC_MAX_PLUGIN_ID;
        $plugins = OSSEC_MIN_PLUGIN_ID . '-' . OSSEC_MAX_PLUGIN_ID;
    }
    $sqlgraph = "SELECT SUM(acid_event.cnt) as num_events, day(convert_tz(timestamp,'+00:00','{$tzc}')) AS intervalo, monthname(convert_tz(timestamp,'+00:00','{$tzc}')) AS suf \n        FROM {$tax_join} alienvault_siem.ac_acid_event acid_event\n        WHERE timestamp BETWEEN '" . gmdate("Y-m-d 00:00:00", gmdate("U") - 604800) . "' AND '" . gmdate("Y-m-d 23:59:59") . "' {$plugins_sql} {$sensor_where} {$tax_where} \n        GROUP BY suf, intervalo \n        ORDER BY suf, intervalo";
    $rg = $dbconn->CacheExecute($sqlgraph);
    if (!$rg) {
        Av_exception::write_log(Av_exception::DB_ERROR, $dbconn->ErrorMsg());
    } else {
        while (!$rg->EOF) {
            $hours = $rg->fields['intervalo'] . ' ' . substr($rg->fields['suf'], 0, 3);
            $data[$hours] = $rg->fields['num_events'];
            $rg->MoveNext();
        }
    }
    $db->close();
    return $param != '' ? array($data, $plugins) : $data;
}
示例#6
0
function get_user_icon($login, $pro)
{
    require_once 'ossim_db.inc';
    $db = new ossim_db();
    $dbconn = $db->connect();
    $user = Session::get_list($dbconn, "WHERE login='******'");
    if ($pro) {
        // Pro-version
        if ($login == ACL_DEFAULT_OSSIM_ADMIN || $user[0]->get_is_admin()) {
            return "../pixmaps/user-gadmin.png";
        } elseif (Acl::is_proadmin($dbconn, $user[0]->get_login())) {
            return "../pixmaps/user-business.png";
        } else {
            return "../pixmaps/user-green.png";
        }
    } else {
        // Opensource
        if ($login == ACL_DEFAULT_OSSIM_ADMIN || $user[0]->get_is_admin()) {
            return "../pixmaps/user-gadmin.png";
        } else {
            return "../pixmaps/user-green.png";
        }
    }
}
示例#7
0
文件: utils.php 项目: jhbsz/ossimTest
function SIEM_trends_hids($agent_ip)
{
    include_once '../panel/sensor_filter.php';
    require_once 'classes/Plugin.inc';
    require_once 'classes/Util.inc';
    require_once 'ossim_db.inc';
    $tz = Util::get_timezone();
    $tzc = Util::get_tzc($tz);
    $data = array();
    $plugins = $plugins_sql = "";
    $db = new ossim_db();
    $dbconn = $db->connect();
    $sensor_where = make_sensor_filter($dbconn);
    // Ossec filter
    $oss_p_id_name = Plugin::get_id_and_name($dbconn, "WHERE name LIKE 'ossec%'");
    $plugins = implode(",", array_flip($oss_p_id_name));
    $plugins_sql = "AND acid_event.plugin_id in ({$plugins})";
    // Agent ip filter
    $agent_where = make_sid_filter($dbconn, $agent_ip);
    if ($agent_where == "") {
        $agent_where = "0";
    }
    $sqlgraph = "SELECT COUNT(acid_event.sid) as num_events, day(convert_tz(timestamp,'+00:00','{$tzc}')) as intervalo, monthname(convert_tz(timestamp,'+00:00','{$tzc}')) as suf FROM snort.acid_event LEFT JOIN ossim.plugin ON acid_event.plugin_id=plugin.id WHERE sid in ({$agent_where}) AND timestamp BETWEEN '" . gmdate("Y-m-d 00:00:00", gmdate("U") - 604800) . "' AND '" . gmdate("Y-m-d 23:59:59") . "' {$plugins_sql} {$sensor_where} GROUP BY suf,intervalo ORDER BY suf,intervalo";
    //print $sqlgraph;
    if (!($rg =& $dbconn->Execute($sqlgraph))) {
        return false;
    } else {
        while (!$rg->EOF) {
            $hours = $rg->fields["intervalo"] . " " . substr($rg->fields["suf"], 0, 3);
            $data[$hours] = $rg->fields["num_events"];
            $rg->MoveNext();
        }
    }
    $db->close($dbconn);
    return $data;
}
示例#8
0
<?php

/*****************************************************************************
*
*    License:
*
*   Copyright (c) 2003-2006 ossim.net
*   Copyright (c) 2007-2009 AlienVault
*   All rights reserved.
*
*   This package 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; version 2 dated June, 1991.
*   You may not use, modify or distribute this program under any other version
*   of the GNU General Public License.
*
*   This package 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 package; if not, write to the Free Software
*   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
*   MA  02110-1301  USA
*
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
示例#9
0
function import_assets_csv($filename)
{
    require_once 'classes/Util.inc';
    $response = array();
    $db = new ossim_db();
    $conn = $db->connect();
    if (($content = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) == false) {
        $response['file_errors'] = "Failed to read file";
        $response['status'] = false;
        return $response;
    } else {
        foreach ($content as $k => $v) {
            $data[] = explode(";", $v);
        }
    }
    $cont = 0;
    ini_set('max_execution_time', 180);
    ids_valid($data);
    if (count($data) <= 0) {
        $response['file_errors'] = _("Incompatible file format");
        $response['status'] = false;
        return $response;
    }
    $allowed_sensors = Session::allowedSensors();
    if (!empty($allowed_sensors)) {
        $my_allowed_sensors = explode(',', $allowed_sensors);
    } else {
        $response['file_errors'] = _("You need at least one sensor assigned");
        $response['status'] = false;
        return $response;
    }
    foreach ($data as $k => $v) {
        $response['status'] = true;
        $response['read_line'] = $cont;
        $cont++;
        if (count($v) != 8) {
            $response['line_errors'][$cont][] = array("Line", _("Format not allowed"));
            $response['status'] = false;
        }
        $param = array();
        foreach ($v as $i => $field) {
            $parameter = trim($field);
            $pattern = '/^\\"|\\"$|^\'|\'$/';
            $param[] = preg_replace($pattern, '', $parameter);
        }
        //IP
        if (!ossim_valid($param[0], OSS_IP_ADDR, 'illegal:' . _("IP"))) {
            $response['line_errors'][$cont][] = array("IP", ossim_get_error_clean());
            $response['status'] = false;
        }
        //Hostname
        if (empty($param[1])) {
            $param[1] = $param[0];
        } else {
            if (!ossim_valid($param[1], OSS_SCORE, OSS_ALPHA, OSS_PUNC, 'illegal:' . _("Hostname"))) {
                $response['line_errors'][$cont][] = array("Hostname", ossim_get_error_clean());
                $response['status'] = false;
                ossim_clean_error();
            }
        }
        //FQDNs
        if (!empty($param[2])) {
            $fqdns_list = explode(",", $param[2]);
            foreach ($fqdns_list as $k => $fqdn) {
                if (!ossim_valid(trim($fqdn), OSS_NULLABLE, OSS_ALPHA, OSS_PUNC, 'illegal:' . _("FQDN/Aliases"))) {
                    $response['line_errors'][$cont][] = array("FQDN/Aliases", ossim_get_error_clean());
                    $response['status'] = false;
                    ossim_clean_error();
                }
            }
        }
        //Description
        if (!ossim_valid($param[3], OSS_NULLABLE, OSS_SCORE, OSS_ALPHA, OSS_PUNC, OSS_AT, 'illegal:' . _("Description"))) {
            $response['line_errors'][$cont][] = array("Description", ossim_get_error_clean());
            $response['status'] = false;
            ossim_clean_error();
        }
        //Asset
        if ($param[4] == '') {
            $param[4] = 2;
        } else {
            if (!ossim_valid($param[4], OSS_NULLABLE, OSS_DIGIT, 'illegal:' . _("Asset value"))) {
                $response['line_errors'][$cont][] = array("Asset", ossim_get_error_clean());
                $response['status'] = false;
                ossim_clean_error();
            }
        }
        //NAT
        if (!ossim_valid($param[5], OSS_NULLABLE, OSS_IP_ADDR, 'illegal:' . _("NAT"))) {
            $response['line_errors'][$cont][] = array("NAT", ossim_get_error_clean());
            $response['status'] = false;
            ossim_clean_error();
        }
        //Sensors
        $sensors = array();
        if (!empty($param[6])) {
            $sensor_name = array();
            $list = explode(",", $param[6]);
            $sensors_list = array_intersect($list, $my_allowed_sensors);
            if (!empty($sensors_list)) {
                foreach ($sensors_list as $sensor) {
                    $sensors[] = Sensor::get_sensor_name($conn, $sensor);
                }
            } else {
                $response['line_errors'][$cont][] = array("Sensors", _("You need at least one allowed Sensor"));
                $response['status'] = false;
                ossim_clean_error();
            }
        } else {
            $response['line_errors'][$cont][] = array("Sensors", _("Column Sensors is empty"));
            $response['status'] = false;
            ossim_clean_error();
        }
        $list_os = array("Windows", "Linux", "FreeBSD", "NetBSD", "OpenBSD", "MacOS", "Solaris", "Cisco", "AIX", "HP-UX", "Tru64", "IRIX", "BSD/OS", "SunOS", "Plan9", "IPhone");
        //Operating System
        if (!empty($param[7]) && !in_array($param[7], $list_os)) {
            $param[7] = "Unknown";
        }
        if ($response['status'] == true) {
            //Parameters
            $ip = $param[0];
            $hostname = $param[1];
            $asset = $param[4];
            $threshold_c = 30;
            $threshold_a = 30;
            $rrd_profile = "";
            $alert = 0;
            $persistence = 0;
            $nat = $param[5];
            $descr = $param[3];
            $os = $param[7];
            $fqdns = $param[2];
            $latitude = '';
            $longitude = '';
            $icon = 0;
            if (!Host::in_host($conn, $ip)) {
                Host::insert($conn, $ip, $hostname, $asset, $threshold_c, $threshold_a, $rrd_profile, $alert, $persistence, $nat, $sensors, $descr, $os, $mac, $mac_vendor, $latitude, $longitude, $fqdns, $icon);
            } else {
                Host::update($conn, $ip, $hostname, $asset, $threshold_c, $threshold_a, $rrd_profile, $alert, $persistence, $nat, $sensors, $descr, $os, $mac, $mac_vendor, $latitude, $longitude, $fqdns, $icon);
            }
        }
    }
    $response['read_line'] = $cont;
    return $response;
}
示例#10
0
*
* You should have received a copy of the GNU General Public License
* along with this package; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA  02110-1301  USA
*
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'ossim_db.inc';
$db = new ossim_db();
$conn1 = $db->connect();
require 'general.php';
$htmlPdfReport->pageBreak();
$htmlPdfReport->setBookmark($title);
$htmlPdfReport->set($htmlPdfReport->newTitle($title, $date_from, $date_to, ''));
if (Session::menu_perms("analysis-menu", "EventsForensics")) {
    $htmlPdfReport->set('<table class="w100" style="padding:15px 0px 0px 0px;" cellpadding="2" cellspacing="2">');
    $list = $pdf->IncidentSummaryNoPDF($title, "Alarm", '', null, $args, null, $conn1, $user);
    unset($list['TipoIncidente']);
    $colors = array("red" => "px_red.png", "orange" => "px_orange.png", "green" => "px_green.png");
    $c = 0;
    $size = count($list);
    if ($size > 0) {
        $htmlPdfReport->set('
                    <tr>
                        <th style="width:30mm;" class="center">' . _("Date") . '</th>
示例#11
0
function DisplayProcessing()
{
    global $self;
    global $ListNOption;
    global $TopNOption;
    global $OutputFormatOption;
    global $IPStatOption;
    global $IPStatOrder;
    global $LimitScale;
    require_once 'av_init.php';
    $geoloc = new Geolocation("/usr/share/geoip/GeoLiteCity.dat");
    $db_aux = new ossim_db();
    $conn_aux = $db_aux->connect();
    $aux_ri_interfaces = Remote_interface::get_list($conn_aux, "WHERE status = 1");
    $ri_list = $aux_ri_interfaces[0];
    $ri_total = $aux_ri_interfaces[1];
    $ri_data = array();
    if ($ri_total > 0) {
        foreach ($ri_list as $r_interface) {
            $ri_data[] = array("name" => $r_interface->get_name(), "id" => "web_interfaces", "target" => "_blank", "url" => $r_interface->get_ip());
        }
    }
    $type = $detail_opts['type'] == "flows" ? 0 : ($detail_opts['type'] == "packets" ? 1 : 2);
    if ($ri_total >= 0) {
        echo '<a name="processing"></a>';
    }
    $detail_opts = $_SESSION['detail_opts'];
    $process_form = $_SESSION['process_form'];
    ?>
    <table style='width:100%;margin-top:15px;margin-bottom:5px;border:none'><tr>
    <td class='nobborder'><b><?php 
    echo _("Netflow Processing");
    ?>
</b></td>
    <td class='noborder nfsen_menu'>
        <a href='javascript:lastsessions()'><?php 
    echo _("List last 500 sessions");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("2","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Src IPs");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("3","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Dst IPs");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("5","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Src Port");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("6","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Dst Port");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("13","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Proto");
    ?>
</a>
    </td></tr></table>


<form action="<?php 
    echo $self;
    ?>
" onSubmit="return ValidateProcessForm()" id="FlowProcessingForm" method="POST" laction="<?php 
    echo $self;
    ?>
">
<?php 
    if (preg_match("/^\\d+\$/", $_SESSION['tend'])) {
        ?>
    <input type="hidden" name="tend" value="<?php 
        echo intval($_SESSION['tend']);
        ?>
" />
<?php 
    }
    if (preg_match("/^\\d+\$/", $_SESSION['tleft'])) {
        ?>
    <input type="hidden" name="tleft" value="<?php 
        echo intval($_SESSION['tleft']);
        ?>
" />
<?php 
    }
    if (preg_match("/^\\d+\$/", $_SESSION['tright'])) {
        ?>
    <input type="hidden" name="tright" value="<?php 
        echo intval($_SESSION['tright']);
        ?>
" />
<?php 
    }
    if ($_SESSION["detail_opts"]["cursor_mode"] != "") {
        ?>
    <input type="hidden" name="cursor_mode" value="<?php 
        echo Util::htmlentities($_SESSION["detail_opts"]["cursor_mode"]);
        ?>
" />
<?php 
    }
    if ($_SESSION["detail_opts"]["wsize"] != "") {
        ?>
    <input type="hidden" name="wsize" value="<?php 
        echo Util::htmlentities($_SESSION["detail_opts"]["wsize"]);
        ?>
" />
<?php 
    }
    if ($_SESSION["detail_opts"]["logscale"] != "") {
        ?>
    <input type="hidden" name="logscale" value="<?php 
        echo Util::htmlentities($_SESSION["detail_opts"]["logscale"]);
        ?>
" />
<?php 
    }
    if ($_SESSION["detail_opts"]["linegraph"] != "") {
        ?>
    <input type="hidden" name="linegraph" value="<?php 
        echo Util::htmlentities($_SESSION["detail_opts"]["linegraph"]);
        ?>
" />
<?php 
    }
    ?>
<input type="hidden" name="login" value="<?php 
    echo Util::htmlentities($_SESSION["_remote_login"]);
    ?>
" />
<table class='nfsen_filters'>
	<tr>
		<th class="thold"><?php 
    echo _("Source");
    ?>
</th>
		<th class="thold"><?php 
    echo _("Filter");
    ?>
</th>
		<th class="thold"><?php 
    echo _("Options");
    ?>
</th>
	</tr>

	<tr>
		<td style='vertical-align:top'>
			<select name="srcselector[]" id='SourceSelector' size="6" style="width: 100%" multiple='multiple'>
			<?php 
    foreach ($process_form['srcselector'] as $selected_channel) {
        $_tmp[$selected_channel] = 1;
    }
    $i = 0;
    foreach ($_SESSION['profileinfo']['channel'] as $channel) {
        $channel_name = $channel['name'];
        $checked = array_key_exists($channel['id'], $_tmp) ? 'selected' : '';
        echo "<OPTION value='" . Util::htmlentities($channel['id']) . "' {$checked}>{$channel_name}</OPTION>\n";
    }
    ?>
			</select>
			<div style='margin: 5px auto'>
				<input class="small av_b_secondary" type="button" name="JSbutton2" value="All Sources" onClick="SelectAllSources()"/>
			</div>
		</td>
	
		<td style="vertical-align:top;">
			<textarea name="filter" id="filter" multiline="true" wrap="phisical" rows="6" cols="50" maxlength="10240"><?php 
    if (is_array($process_form)) {
        $display_filter = array_key_exists('editfilter', $process_form) ? $process_form['editfilter'] : $process_form['filter'];
    } else {
        $display_filter = array();
    }
    if (count($display_filter) < 1 && GET('ip') != "" && GET('ip2') != "") {
        $display_filter[0] = "(src ip " . GET('ip') . " and dst ip " . GET('ip2') . ") or (src ip " . GET('ip2') . " and dst ip " . GET('ip') . ")";
    } elseif (count($display_filter) < 1 && GET('ip') != "") {
        $display_filter[0] = "src ip " . GET('ip') . " or dst ip " . GET('ip');
    } elseif (preg_match("/(\\d+\\.\\d+\\.\\d+\\.\\d+)/", $display_filter[0]) && GET('ip') != "" && GET('ip2') != "") {
        $ip1 = GET('ip');
        $ip2 = GET('ip2');
        $filter = "(src ip {$ip1} and dst ip {$ip2}) or (src ip {$ip2} and dst ip {$ip1})";
        $display_filter[0] = preg_replace("/\\(src ip \\d+\\.\\d+\\.\\d+\\.\\d+ and dst ip \\d+\\.\\d+\\.\\d+\\.\\d+\\) or \\(src ip \\d+\\.\\d+\\.\\d+\\.\\d+ and dst ip \\d+\\.\\d+\\.\\d+\\.\\d+\\)/", $filter, $display_filter[0]);
        $display_filter[0] = preg_replace("/src ip \\d+\\.\\d+\\.\\d+\\.\\d+ or dst ip \\d+\\.\\d+\\.\\d+\\.\\d+/", $filter, $display_filter[0]);
    } elseif (preg_match("/(\\d+\\.\\d+\\.\\d+\\.\\d+)/", $display_filter[0]) && GET('ip') != "") {
        $filter = "src ip " . GET('ip') . " or dst ip " . GET('ip');
        $display_filter[0] = preg_replace("/\\(src ip \\d+\\.\\d+\\.\\d+\\.\\d+ and dst ip \\d+\\.\\d+\\.\\d+\\.\\d+\\) or \\(src ip \\d+\\.\\d+\\.\\d+\\.\\d+ and dst ip \\d+\\.\\d+\\.\\d+\\.\\d+\\)/", $filter, $display_filter[0]);
        $display_filter[0] = preg_replace("/src ip \\d+\\.\\d+\\.\\d+\\.\\d+ or dst ip \\d+\\.\\d+\\.\\d+\\.\\d+/", $filter, $display_filter[0]);
    }
    foreach ($display_filter as $line) {
        print str_replace("&amp;", "&", Util::htmlentities(stripslashes($line))) . "\n";
    }
    ?>
</textarea>
			<?php 
    $deletefilter_display_style = is_array($process_form) && array_key_exists('editfilter', $process_form) ? '' : 'style="display:none;"';
    ?>
			
			<input type="image" name="filter_delete" id="filter_delete" title="<?php 
    echo _("Delete filter");
    ?>
" align="right"
				onClick="HandleFilter(3)" value="" src="icons/trash.png" <?php 
    echo $deletefilter_display_style;
    ?>
>
			<!-- <input type="image" name="filter_save" id="filter_save" title="Save filter" align="right"
				onClick="HandleFilter(2)" 
				value="" src="icons/save.png"> -->
			<input type="hidden" name="filter_name" id="filter_name" value="none">
			<div style='margin: 5px auto'>
				<span id="filter_span">and</span>
				<select name="DefaultFilter" id="DefaultFilter" onChange="HandleFilter(0)" size="1">
				<?php 
    print "<option value='-1' label='none'>&lt;none&gt;</option>\n";
    foreach ($_SESSION['DefaultFilters'] as $name) {
        $checked = $process_form['DefaultFilter'] == $name ? 'selected' : '';
        print "<option value='" . Util::htmlentities($name) . "' {$checked}>" . Util::htmlentities($name) . "</option>\n";
    }
    $editfilter_display_style = 'style="display:none;"';
    foreach ($_SESSION['DefaultFilters'] as $name) {
        if ($process_form['DefaultFilter'] == $name) {
            $editfilter_display_style = '';
        }
    }
    ?>
				</select>
				
				<input type="image" name="filter_save" id="filter_save" title="<?php 
    echo _("Save filter");
    ?>
"
					onClick="HandleFilter(2)" value="" src="icons/save.png" border="0" align="absmiddle"> 		
				
				<input type="image" name="filter_edit" id="filter_edit" title="Edit filter" <?php 
    echo $editfilter_display_style;
    ?>
					onClick="HandleFilter(1)" value="" src="icons/edit.png">
			</div>
			
			<script language="Javascript" type="text/javascript">
				var DefaultFilters = new Array();
				<?php 
    foreach ($_SESSION['DefaultFilters'] as $name) {
        print "DefaultFilters.push('" . Util::htmlentities($name) . "');\n";
    }
    if (array_key_exists('editfilter', $process_form)) {
        print "edit_filter = '" . Util::htmlentities($process_form['DefaultFilter']) . "';\n";
    }
    ?>
			</script>
		</td>
		<!-- Options start here -->
		<td style='padding: 0px;vertical-align:top;border:none;'>
			<table border="0" id="ProcessOptionTable" style="font-size:14px;font-weight:bold;width:100%;border:none">
				<tr>
					<td class='TDnfprocLabel' style='white-space:nowrap'>
					<?php 
    $i = 0;
    foreach (array('List Flows', 'Stat TopN') as $s) {
        $checked = $process_form['modeselect'] == $i ? 'checked' : '';
        print "<input type='radio' onClick='SwitchOptionTable({$i})' name='modeselect' id='modeselect{$i}' value='{$i}' {$checked}>{$s}&nbsp;";
        $i++;
    }
    $list_display_style = $process_form['modeselect'] == 0 ? '' : 'style="display:none;"';
    $stat_display_style = $process_form['modeselect'] == 0 ? 'style="display:none;"' : '';
    $formatselect_display_opts = $process_form['modeselect'] == 1 && $process_form['stattype'] != 0 ? 'style="display:none;"' : '';
    ?>
				   </td>
				   
				   <td class='TDnfprocControl' >
						<table class='noborder' style='margin: auto;'>
							<tr>
								<td class='nobborder'><input class="small av_b_secondary" type="button" name="JSbutton1" value="<?php 
    echo _("Clear Form");
    ?>
" onClick="ResetProcessingForm()"/></td>
								<td class='nobborder'><input class="small" type="submit" name="process" value="<?php 
    echo _("Process");
    ?>
" id="process_button" onClick="clean_remote_data();form_ok=true;" size="1"/></td>
								<?php 
    if (count($RemoteInterfacesData) > 0 && !isset($_POST['login'])) {
        ?>
									<td class='nobborder'><input type="button" name="remote_process" value="<?php 
        echo _("Remote Process");
        ?>
" id="remote_process_button" onclick="$('#rinterfaces').toggle()"/>
										<div id='container_rmp' style='position:relative;'>
											<div id="rinterfaces" style="position:absolute; top:0; right:0;display:none; margin:1px 0px 0px 2px; text-align:right;">
												<?php 
        foreach ($RemoteInterfacesData as $data) {
            $short_name = strlen($data['name']) > 12 ? substr($data['name'], 0, 12) . "..." : $data['name'];
            ?>
													<input type="button" onclick="remote_interface('<?php 
            echo $data["url"];
            ?>
')" style="width:180px; font-size: 11px;" title="<?php 
            echo $data["name"] . " [" . $data["url"] . "]";
            ?>
" value="<?php 
            echo $short_name . " [" . $data["url"] . "]";
            ?>
"/><br />
													<?php 
        }
        ?>
											</div>
										</div>
									</td>
									<?php 
    }
    ?>
							</tr>
						</table>
					</td>			
				</tr>
				
				<tr id="listNRow" <?php 
    echo $list_display_style;
    ?>
>
					<td class='TDnfprocLabel'><?php 
    echo _("Limit to");
    ?>
:</td>
					<td class='TDnfprocControl'>
						<select name="listN" id="listN" style="margin-left:1" size="1">
						<?php 
    for ($i = 0; $i < count($ListNOption); $i++) {
        $checked = $process_form['listN'] == $i ? 'selected' : '';
        print "<OPTION value='{$i}' {$checked}>" . $ListNOption[$i] . "</OPTION>\n";
    }
    ?>
						</select><?php 
    echo _("Flows");
    ?>
<br>
					</td>
				</tr>
				
				<tr id="topNRow" <?php 
    echo $stat_display_style;
    ?>
>
					<td class='TDnfprocLabel'><?php 
    echo _("Top");
    ?>
:</td>
					<td class='TDnfprocControl'> 
						<select name="topN" id="TopN" size="1">
							<?php 
    for ($i = 0; $i < count($TopNOption); $i++) {
        $checked = $process_form['topN'] == $i ? 'selected' : '';
        print "<OPTION value='{$i}' {$checked}>" . $TopNOption[$i] . "</OPTION>\n";
    }
    ?>
						</select>
					</td>
				</tr>
				
				<tr id="stattypeRow" <?php 
    echo $stat_display_style;
    ?>
>
					<td class="TDnfprocLabel"><?php 
    echo _("Stat");
    ?>
:</td>
					<td class="TDnfprocControl">
						<select name="stattype" id="StatTypeSelector" onChange="ShowHideOptions()" size="1">
						<?php 
    for ($i = 0; $i < count($IPStatOption); $i++) {
        $checked = $process_form['stattype'] == $i ? 'selected' : '';
        print "<OPTION value='{$i}' {$checked}>" . $IPStatOption[$i] . "</OPTION>\n";
    }
    ?>
						</select>
						order by&nbsp;
						<select name='statorder' id="statorder" size='1'>
						<?php 
    for ($i = 0; $i < count($IPStatOrder); $i++) {
        $checked = $process_form['statorder'] == $i ? 'selected' : '';
        print "<OPTION value='{$i}' {$checked}>" . $IPStatOrder[$i] . "</OPTION>\n";
    }
    ?>
						</select>					
					</td>
				</tr>
				
				<tr id="AggregateRow" <?php 
    echo $formatselect_display_opts;
    ?>
>
					<td class='TDnfprocLabel'><?php 
    echo _("Aggregate");
    ?>
</td>
					<td class='TDnfprocControl'>
						<input type="checkbox" name="aggr_bidir" id="aggr_bidir" value="checked" onClick="ToggleAggregate();"
							style="margin-left:1" <?php 
    echo Util::htmlentities($process_form['aggr_bidir']);
    ?>
>&nbsp;<?php 
    echo _("bi-directional");
    ?>
<br>
						<input type="checkbox" name="aggr_proto" id="aggr_proto" value="checked" 
							style="margin-left:1" <?php 
    echo Util::htmlentities($process_form['aggr_proto']);
    ?>
>&nbsp;<?php 
    echo _("proto");
    ?>
<br>
						<input type="checkbox" name="aggr_srcport" id="aggr_srcport" value="checked" 
							style="margin-left:1" <?php 
    echo Util::htmlentities($process_form['aggr_srcport']);
    ?>
>&nbsp;<?php 
    echo _("srcPort");
    ?>
						<input type="checkbox" name="aggr_srcip" id="aggr_srcip" value="checked" 
							style="margin-left:1" <?php 
    echo Util::htmlentities($process_form['aggr_srcip']);
    ?>
>&nbsp;
						<select name="aggr_srcselect" id="aggr_srcselect" onChange="NetbitEntry('src')" size="1">
							<?php 
    $i = 0;
    foreach (array('srcIP', 'srcIPv4/', 'srcIPv6/') as $s) {
        $checked = $process_form['aggr_srcselect'] == $i ? 'selected' : '';
        print "<option value='{$i}' {$checked}>{$s}</option>\n";
        $i++;
    }
    $_style = $process_form['aggr_srcselect'] == 0 ? 'style="display:none"' : '';
    ?>
						</select>
						<input size="3" type="text" name="aggr_srcnetbits" id="aggr_srcnetbits" 
							value="<?php 
    echo Util::htmlentities($process_form['aggr_srcnetbits']);
    ?>
" <?php 
    echo $_style;
    ?>
><br>
						<input type="checkbox" name="aggr_dstport" id="aggr_dstport" value="checked" 
							style="margin-left:1" <?php 
    echo Util::htmlentities($process_form['aggr_dstport']);
    ?>
>&nbsp;<?php 
    echo _("dstPort");
    ?>
						<input type="checkbox" name="aggr_dstip" id="aggr_dstip" value="checked" 
							style="margin-left:1" <?php 
    echo Util::htmlentities($process_form['aggr_dstip']);
    ?>
>&nbsp;
						<select name="aggr_dstselect" id="aggr_dstselect" onChange="NetbitEntry('dst')" size="1">
							<?php 
    $i = 0;
    foreach (array('dstIP', 'dstIPv4/', 'dstIPv6/') as $s) {
        $checked = $process_form['aggr_dstselect'] == $i ? 'selected' : '';
        print "<option value='{$i}' {$checked}>{$s}</option>\n";
        $i++;
    }
    $_style = $process_form['aggr_dstselect'] == 0 ? 'style="display:none"' : '';
    ?>
						</select>
						<input size="3" type="text" name="aggr_dstnetbits" id="aggr_dstnetbits" 
							value="<?php 
    echo Util::htmlentities($process_form['aggr_dstnetbits']);
    ?>
" <?php 
    echo $_style;
    ?>
><br>
					</td>
				</tr>
				
				<tr id="timesortedRow" <?php 
    echo $list_display_style;
    ?>
>
					<td class='TDnfprocLabel'><?php 
    echo _("Sort");
    ?>
:</td>
					<td class='TDnfprocControl'>
						<input type="checkbox" name="timesorted" id="timesorted" value="checked" 
							style="margin-left:1" <?php 
    echo Util::htmlentities($process_form['timesorted']);
    ?>
>
						<?php 
    echo _("start time of flows");
    ?>
</td>
				</tr>
				
				<tr id="limitoutputRow" <?php 
    echo $stat_display_style;
    ?>
>
					<td class='TDnfprocLabel'><?php 
    echo _("Limit");
    ?>
:</td>
					<td class='TDnfprocControl'>
						<input type="checkbox" name="limitoutput" id="limitoutput" value="checked" style="margin-left:1" 
							size="1" <?php 
    echo Util::htmlentities($process_form['limitoutput']);
    ?>
>
						<select name="limitwhat" id="limitwhat" size="1">
						<?php 
    $i = 0;
    foreach (array(gettext("Packets"), gettext("Traffic")) as $s) {
        $checked = $process_form['limitwhat'] == $i ? 'selected' : '';
        print "<option value='{$i}' {$checked}>{$s}</option>\n";
        $i++;
    }
    ?>
						</select>
						<select name="limithow" id="limithow" size="1">
						<?php 
    $i = 0;
    foreach (array('&gt;', '&lt;') as $s) {
        $checked = $process_form['limithow'] == $i ? 'selected' : '';
        print "<option value='{$i}' {$checked}>{$s}</option>\n";
        $i++;
    }
    ?>
						</select>
						<input type="text" name="limitsize" id="limitsize" value="<?php 
    echo Util::htmlentities($process_form['limitsize']);
    ?>
" SIZE="6" MAXLENGTH="8">
						<select name="limitscale" id="limitscale" size="1" style="margin-left:1">
						<?php 
    $i = 0;
    foreach ($LimitScale as $s) {
        $checked = $process_form['limitscale'] == $i ? 'selected' : '';
        print "<option value='{$i}' {$checked}>{$s}</option>\n";
        $i++;
    }
    ?>
						</select>
					</td>
				</tr>

				<tr id="outputRow">
					<td class='TDnfprocLabel'><?php 
    echo _("Output");
    ?>
:</td>
					<td class='TDnfprocControl'>
						<span id="FormatSelect" <?php 
    echo $formatselect_display_opts;
    ?>
>
						<select name="output" id="output" onChange="CustomOutputFormat()"  style="margin-left:1" size="1">
						<?php 
    foreach ($_SESSION['formatlist'] as $key => $value) {
        $checked = $process_form['output'] == $key ? 'selected' : '';
        print "<OPTION value='" . Util::htmlentities($key) . "' {$checked}>" . Util::htmlentities($key) . "</OPTION>\n";
    }
    $fmt = $_SESSION['formatlist'][$process_form['output']];
    if ($process_form['output'] == $fmt) {
        // built in format
        $space_display_style = '';
        $edit_display_style = 'style="display:none"';
    } else {
        $space_display_style = 'style="display:none"';
        $edit_display_style = '';
    }
    ?>
						</select>
						<script language="Javascript" type="text/javascript">
							var fmts = new Hash();
						<?php 
    foreach ($_SESSION['formatlist'] as $key => $value) {
        print "fmts.setItem('" . Util::htmlentities($key) . "', '" . Util::htmlentities($value) . "');\n";
    }
    ?>
						</script>
						<img src="icons/space.png" border="0" alt='space' id='space' <?php 
    echo $space_display_style;
    ?>
/>
						<a href="#null" onClick="EditCustomFormat()"
							title="<?php 
    echo _("Edit format");
    ?>
" ><IMG SRC="icons/edit.png" name="fmt_doedit" id="fmt_doedit" border="0" 
							<?php 
    echo $edit_display_style;
    ?>
 alt="Edit format"></a>
						</span>
						<input type="checkbox" name="IPv6_long" id="IPv6_long" style="margin-left:1" value="checked" <?php 
    echo Util::htmlentities($process_form['IPv6_long']);
    ?>
>
						&nbsp;/ <?php 
    echo _("IPv6 long");
    ?>
						<?php 
    $fmt_edit_display_style = $process_form['output'] == 'custom ...' ? '' : 'style="display:none"';
    ?>
						<span id="fmt_edit" <?php 
    echo $fmt_edit_display_style;
    ?>
>
						<br><?php 
    echo _("Enter custom output format");
    ?>
:<br>
						<input size="30" type="text" name="customfmt" id="customfmt" 
							value="<?php 
    echo Util::htmlentities($process_form['customfmt']);
    ?>
" >
						<input type="image" name="fmt_save" id="fmt_save" title="<?php 
    echo _("Save format");
    ?>
" 
							onClick="SaveOutputFormat()" 
							value="" src="icons/save.png">
						<input type="image" name="fmt_delete" id="fmt_delete" title="<?php 
    echo _("Delete format");
    ?>
" 
							onClick="DeleteOutputFormat()" 
							value="" src="icons/trash.png" <?php 
    echo $edit_display_style;
    ?>
>
						</span>
					</td>
				</tr>
			</table>
		</td>
	</tr>
<!--
<tr>
	<td></td><td></td>
	<td align="right" style="border:none">
		<input type="button" name="JSbutton1" value="<?php 
    echo _("Clear Form");
    ?>
" onClick="ResetProcessingForm()">
		<input type="submit" name="process" value="<?php 
    echo _("process");
    ?>
" id="process_button" onClick="form_ok=true;" size="1">
	</td>
</tr>
-->
</table>
</form>

<div id="lookupbox">
	<div id="lookupbar" align="right" style="background-color:olivedrab"><img src="icons/close.png"
		onmouseover="this.style.cursor='pointer';" onClick="hidelookup()" title="Close lookup box"></div>
	<iframe id="cframe" src="" frameborder="0" scrolling="auto" width="100%" height="166"></iframe>
</div>


<?php 
    if (!array_key_exists('run', $_SESSION)) {
        return;
    }
    print "<div class='flowlist'>\n";
    $run = $_SESSION['run'];
    if ($run != null) {
        $filter = $process_form['filter'];
        if ($process_form['DefaultFilter'] != -1) {
            $cmd_opts['and_filter'] = $process_form['DefaultFilter'];
        }
        $cmd_opts['type'] = ($_SESSION['profileinfo']['type'] & 4) > 0 ? 'shadow' : 'real';
        $cmd_opts['profile'] = $_SESSION['profileswitch'];
        $cmd_opts['srcselector'] = implode(':', $process_form['srcselector']);
        #print "<pre>\n";
        $patterns = array();
        $replacements = array();
        $patterns[0] = '/(\\s*)([^\\s]+)/';
        $replacements[0] = "\$1<a href='#null' onClick='lookup(\"\$2\", this, event)' title='lookup \$2'>\$2</a>";
        // gets HAP4NfSens plugin id. returns -1 if HAP4NfSen is not installed.
        function getHAP4NfSenId()
        {
            $plugins = GetPlugins();
            for ($i = 0; $i < count($plugins); $i++) {
                $plugin = $plugins[$i];
                if ($plugin == "HAP4NfSen") {
                    return $i;
                }
            }
            return -1;
        }
        ClearMessages();
        $cmd_opts['args'] = "-T {$run}";
        $cmd_opts['filter'] = $filter;
        $titcol = get_tit_col($run);
        $cmd_out = nfsend_query("run-nfdump", $cmd_opts);
        if (!is_array($cmd_out)) {
            ShowMessages();
        } else {
            $conf = $GLOBALS["CONF"];
            $solera = $conf->get_conf("solera_enable", FALSE) ? true : false;
            $db = new ossim_db();
            $conn = $db->connect();
            $sensors = $hosts = $ossim_servers = array();
            $tz = Util::get_timezone();
            list($hosts, $host_ids) = Asset_host::get_basic_list($conn, array(), TRUE);
            $entities = Session::get_all_entities($conn);
            $_sensors = Av_sensor::get_basic_list($conn);
            foreach ($_sensors as $s_id => $s) {
                $sensors[$s['ip']] = $s['name'];
            }
            /*$hap4nfsen_id = getHAP4NfSenId();
                    	        if ($hap4nfsen_id >= 0) {
            					// ICMP "port" filter are no currently supported by the HAP4NfSen plugin
            					function isChecked(&$form, $name) { // helper function used to find out, if an option is checked
            						return $form[$name]=="checked";
            					}
            					$ip_and_port_columns = preg_match('/(flow records)/i', $IPStatOption[$process_form['stattype']]) &&
            						((isChecked($process_form,'aggr_srcip') && isChecked($process_form,'aggr_srcport')) ||
            						(isChecked($process_form,'aggr_dstip') && isChecked($process_form,'aggr_dstport')));
            					$ip_contains_port =  $_SESSION["process_form"]["modeselect"]=='0' || !preg_match('/[ip|flow_records]/i', $IPStatOption[$process_form['stattype']]) ||
            								(preg_match('/(flow records)/i', $IPStatOption[$process_form['stattype']]) && !( // no boxes checked
            								isChecked($process_form,'aggr_srcip') || isChecked($process_form,'aggr_srcport') ||
            								isChecked($process_form,'aggr_dstip') || isChecked($process_form,'aggr_dstport')));
                    	                        $_SESSION["plugin"][$hap4nfsen_id]["cmd_opts"] = $cmd_opts;
            					$hap_pic = "<img src=\"plugins/HAP4NfSen/graphviz.png\" valign=\"middle\" border=\"0\" alt=\"HAP\" />";
            					$default_pattern = array_pop($patterns);
            					$default_replacement = array_pop($replacements);
            					if ($ip_contains_port) { // matches cases like ip:port
            						$max_prot_length = 5; // max. port length = 5 chars(highest port number = 65535)
            						for ($i=$max_prot_length;$i>=1;$i--) {
            							$diff = ($max_prot_length-$i); // difference between actual and max port length
            							$ip_port_pattern_icmp = "/(\s*)([^\s|^:]+)(:)(0\s{4}|\d\.\d\s{2}|\d{2}\.\d\|\d\.\d{2}\s|\d{2}\.\d{2})/";
            							$ip_port_pattern_normal = "/(\s*)([^\s|^:]+)(:)([\d|\.]{{$i}})(\s{{$diff}})/";
            							$spaces = '';
            							for ($k=0;$k<$diff;$k++) {$spaces = $spaces . ' ';} // spaces required to align hap viewer icons
                                                            	array_push($patterns, $ip_port_pattern_icmp);
            							array_push($replacements,  $default_replacement .
            								"$3$4 <a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&mode=new\" title='HAP graphlet for $2'>$hap_pic</a> ");
            							array_push($patterns, $ip_port_pattern_normal);
                                                            	array_push($replacements,  $default_replacement .
            								"$3$4$spaces <a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&port=$4&mode=new\" title='HAP graphlet for $2 on port $4'>$hap_pic</a> ");
            						}
            						array_push($patterns, '/(\sIP\sAddr:Port)/i');
                                                    	array_push($replacements, "$1  $hap_pic");
            					} else {
            						if ($ip_and_port_columns) { // matches cases when both ip and port are available but are located in separate columns
            							// ICMP verion
            							$ip_and_port_pattern = "/(\s*)([^\s]+)(\s+)(0|\d\.\d)/";
            							$ip_and_port_replacement = "$1$2$3$4 " .
            								"<a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&mode=new\" title='HAP graphlet for $2'>$hap_pic</a>";
            							array_push($patterns, $ip_and_port_pattern);
            							array_push($replacements, $ip_and_port_replacement);
            							// non-ICMP version with port filter
                                                                    $ip_and_port_pattern = "/(\s*)([^\s]+)(\s*)([\d|.]+)/";
                                                                    $ip_and_port_replacement = "$1$2$3$4 " .
                                                                            "<a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&port=$4&mode=new\" title='HAP graphlet for $2 on port $4'>$hap_pic</a>";
                                                                    array_push($patterns, $ip_and_port_pattern);
                                                                    array_push($replacements, $ip_and_port_replacement);
            							array_push($patterns, '/(\s\s(Src\sIP\sAddr\s*Src\sPt|Dst\sIP\sAddr\s*Dst\sPt))/i');
                                                                    array_push($replacements, "$1 $hap_pic");
            						} else { // matches all other cases
            							array_push($patterns, $default_pattern);
                                                    		array_push($replacements,  $default_replacement . 
            								" <a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&mode=new\" title='HAP graphlet for $2'>$hap_pic</a>");
            							array_push($patterns, '/(\s(|\s(Src|Dst))\sIP\sAddr)/i');
                                                            	array_push($replacements, "$1 $hap_pic");
            						}
            					}
            	                        }
            
            				if ( array_key_exists('arg', $cmd_out) ) {
            					print "** nfdump " . $cmd_out['arg'] . "\n";
            				}
            				if ( array_key_exists('filter', $cmd_out) ) {
            					print "nfdump filter:\n";
            					foreach ( $cmd_out['filter'] as $line ) {
            						print "$line\n";
            					}
            				}
            				foreach ( $cmd_out['nfdump'] as $line ) {
            					print preg_replace($patterns, $replacements, $line) . "\n";
            				}*/
            # parse command line
            #2009-12-09 17:08:17.596    40.262 TCP        192.168.1.9:80    ->   217.126.167.80:51694 .AP.SF   0       70   180978        1    35960   2585     1
            $list = preg_match("/\\-o extended/", $cmd_out['arg']) ? 1 : 0;
            $regex = $list ? "/(\\d\\d\\d\\d\\-.*?\\s.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+->\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?\\s*[KMG]?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*)/" : "/(\\d\\d\\d\\d\\-.*?\\s.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?\\s*[KMGT]?)\\s+(.*?)\\s+(.*?)\\s+(.*)/";
            echo '<div class="nfsen_list_title">' . _('Flows Info') . '</div>';
            echo "<table class='table_list'>";
            $geotools = false;
            if ($list && file_exists("../kml/GoogleEarth.php")) {
                $geotools = true;
                $geoips = array();
                $geotools_src = " <a href='' onclick='window.open(\"../kml/TourConfig.php?type=ip_src&ip=&flows=1\",\"Flows sources - Goggle Earth API\",\"width=1024,height=700,scrollbars=NO,toolbar=1\");return false'><img align='absmiddle' src='../pixmaps/google_earth_icon.png' border='0'></a>&nbsp;&nbsp;<a href='' onclick='window.open(\"../kml/IPGoogleMap.php?type=ip_src&ip=&flows=1\",\"Flows sources - Goggle Maps API\",\"width=1024,height=700,scrollbars=NO,toolbar=1\");return false'><img align='absmiddle' src='../pixmaps/google_maps_icon.png' border='0'></a>";
                $geotools_dst = " <a href='' onclick='window.open(\"../kml/TourConfig.php?type=ip_dst&ip=&flows=1\",\"Flows destinations - Goggle Earth API\",\"width=1024,height=700,scrollbars=NO,toolbar=1\");return false'><img align='absmiddle' src='../pixmaps/google_earth_icon.png' border='0'></a>&nbsp;&nbsp;<a href='' onclick='window.open(\"../kml/IPGoogleMap.php?type=ip_dst&ip=&flows=1\",\"Flows destinations - Goggle Maps API\",\"width=1024,height=700,scrollbars=NO,toolbar=1\");return false'><img align='absmiddle' src='../pixmaps/google_maps_icon.png' border='0'></a>";
            }
            echo $list ? "\n                \n                <tr>\n                    <th>" . _("Date flow start") . "<br><span style='font-size:8px'>" . Util::timezone($tz) . "</style></th>\n                    <th>" . _("Duration") . "</th>\n                    <th>" . _("Proto") . "</th>\n                    <th>" . _("Src IP Addr:Port") . "{$geotools_src}</th>\n                    <th>" . _("Dst IP Addr:Port") . "{$geotools_dst}</th>\n                    <th>" . _("Flags") . "</th>\n                    <th>" . _("Tos") . "</th>\n                    <th>" . _("Packets") . "</th>\n                    <th>" . _("Bytes") . "</th>\n                    <th>" . _("pps") . "</th>\n                    <th>" . _("bps") . "</th>\n                    <th>" . _("Bpp") . "</th>\n                    <th>" . _("Flows") . "</th>\n                \t" . ($solera ? "<th></th>" : "") . "\n                    </tr>" : "<tr>\n                    <th>" . _("Date flow seen") . "<br><span style='font-size:8px'>" . Util::timezone($tz) . "</style></th>\n                    <th>" . _("Duration") . "</th>\n                    <th>" . _("Proto") . "</th>\n                    <th>" . $titcol . "</th>\n                    <th>" . _("Flows") . "(%)</th>\n                    <th>" . _("Packets") . "(%)</th>\n                    <th>" . _("Bytes") . "(%)</th>\n                    <th>" . _("pps") . "</th>\n                    <th>" . _("bps") . "</th>\n                    <th>" . _("Bpp") . "</th>\n                \t" . ($solera ? "<th></th>" : "") . "\n                    </tr>";
            $status = $errors = array();
            $rep = new Reputation();
            //print_r($cmd_out['arg']);
            //print_r($cmd_out['nfdump']);
            foreach ($cmd_out['nfdump'] as $k => $line) {
                #capture status
                if (preg_match("/^(Summary|Time window|Total flows processed|Sys)\\:/", $line, $found)) {
                    $status[$found[1]] = str_replace($found[1] . ":", "", $line);
                }
                # capture errors
                if (preg_match("/ error /i", $line, $found)) {
                    if (preg_match("/stat\\(\\) error/i", $line)) {
                        $errors[] = _('The netflow information you are trying to access either has not been processed yet or does not exist. Please check your date filters.');
                        Av_exception::write_log(Av_exception::USER_ERROR, $line);
                    } else {
                        $errors[] = $line;
                    }
                }
                # print results
                $line = preg_replace("/\\(\\s(\\d)/", "(\\1", $line);
                // Patch for ( 0.3)
                $line = preg_replace("/(\\d)\\s*([KMGT])/", "\\1\\2", $line);
                // Patch for 1.2 M(99.6)
                $line = preg_replace("/(\\d+)(TCP|UDP|ICMP|IGMP)\\s/", "\\1 \\2 ", $line);
                // Patch for 9.003TCP
                $start = $end = $proto = "";
                $ips = $ports = array();
                if (preg_match($regex, preg_replace('/\\s*/', ' ', $line), $found)) {
                    echo "<tr class='tr_flow_data'>\n";
                    foreach ($found as $ki => $field) {
                        if ($ki > 0) {
                            $wrap = $ki == 1 ? "nowrap" : "";
                            $field = Util::htmlentities(preg_replace("/(\\:\\d+)\\.0\$/", "\\1", $field));
                            if (preg_match("/(\\d+\\.\\d+\\.\\d+\\.\\d+)(.*)/", $field, $fnd)) {
                                # match ip (resolve and geolocalize)
                                $ip = $fnd[1];
                                $port = $fnd[2];
                                list($name, $ctx, $host_id) = GetDataFromSingleIp($ip, $hosts);
                                if ($name == "" && $sensors[$ip] != "") {
                                    $name = $sensors[$ip];
                                }
                                $output = Asset_host::get_extended_name($conn, $geoloc, $ip, $ctx, $host_id, '');
                                $homelan = $output['is_internal'] || $name != "" && $name != $ip;
                                $icon = $output['html_icon'];
                                # reputation info
                                if (!is_array($_SESSION["_repinfo_ips"][$ip])) {
                                    $_SESSION["_repinfo_ips"][$ip] = $rep->get_data_by_ip($ip);
                                }
                                $rep_icon = Reputation::getrepimg($_SESSION["_repinfo_ips"][$ip][0], $_SESSION["_repinfo_ips"][$ip][1], $_SESSION["_repinfo_ips"][$ip][2], $ip);
                                $rep_bgcolor = Reputation::getrepbgcolor($_SESSION["_repinfo_ips"][$ip][0]);
                                $style_aux = $homelan ? 'style="font-weight:bold"' : '';
                                $bold_aux1 = $homelan ? '<b>' : '';
                                $bold_aux2 = $homelan ? '<b>' : '';
                                $field = '<div id="' . $ip . ';' . Util::htmlentities($name) . ';' . $host_id . '" id2="' . $ip . ';' . $ip . '" ctx="' . $ctx . '" class="HostReportMenu">' . $icon . ' <a ' . $style_aux . ' href="javascript:;">' . Util::htmlentities($name) . '</a>' . $bold_aux1 . $port . $bold_aux2 . ' ' . $rep_icon . '</div>';
                                $wrap = "nowrap style='{$rep_bgcolor}'";
                                $ips[] = $ip;
                                if ($geotools) {
                                    if ($ki == 4) {
                                        $geoips['ip_src'][$ip]++;
                                    } elseif ($ki == 5) {
                                        $geoips['ip_dst'][$ip]++;
                                    }
                                }
                                $ports[] = str_replace(":", "", $port);
                            }
                            if (preg_match("/(\\d+-\\d+-\\d+ \\d+:\\d+:\\d+)(.*)/", $field, $fnd)) {
                                # match date
                                $start = $end = $fnd[1];
                                $time = strtotime($fnd[1]);
                                $field = Util::htmlentities(gmdate("Y-m-d H:i:s", $time + 3600 * $tz) . "." . $fnd[2]);
                            }
                            if (preg_match("/(TCP|UDP|ICMP|RAW)/", $field, $fnd)) {
                                # match date
                                $proto = strtolower($fnd[1]);
                            }
                            print "<td {$wrap}>{$field}</td>";
                        }
                    }
                    // solera deepsee integration
                    if ($solera) {
                        echo "<td><a href=\"javascript:;\" onclick=\"solera_deepsee('" . Util::htmlentities($start) . "','" . Util::htmlentities($end) . "','" . Util::htmlentities($ips[0]) . "','" . Util::htmlentities($ports[0]) . "','" . Util::htmlentities($ips[1]) . "','" . Util::htmlentities($ports[1]) . "','" . Util::htmlentities($proto) . "')\"><img src='/ossim/pixmaps/solera.png' border='0' align='absmiddle'></a></td>";
                    }
                    echo "</tr>\n";
                }
            }
            echo "</table>";
            if ($geotools) {
                foreach ($geoips as $type => $list) {
                    $ipsfile = fopen("/var/tmp/flowips_" . Session::get_session_user() . ".{$type}", "w");
                    foreach ($list as $ip => $val) {
                        fputs($ipsfile, "{$ip}\n");
                    }
                    fclose($ipsfile);
                }
            }
            #Summary: total flows: 20, total bytes: 7701, total packets: 133, avg bps: 60, avg pps: 0, avg bpp: 57
            #Time window: 2009-12-10 08:21:30 - 2009-12-10 08:38:26
            #Total flows processed: 21, Records skipped: 0, Bytes read: 1128
            #Sys: 0.000s flows/second: 0.0        Wall: 0.000s flows/second: 152173.9
            if (count($status) > 0) {
                echo "<table class='transparent' style='margin-bottom:5px;width:100%'>";
                foreach ($status as $key => $line) {
                    $line = preg_replace("/(Wall)\\:/", "<span class='th_summary'>\\1</span>", $line);
                    $line = preg_replace("/\\,\\s+(.*?)\\:/", " <span class='th_summary'>\\1</span>", $line);
                    echo "<tr>\n                                    <td class='nobborder' style='padding: 4px;'>\n                                        <span class='th_summary'>{$key}</span>\n                                        {$line}\n                                    </td>\n                                  </tr>";
                }
                echo "</table>";
            }
            # stat() error '/home/dk/nfsen/profiles-data/live/device2/2009/12/10/nfcapd.200912100920': File not found!
            if (count($errors) > 0) {
                foreach ($errors as $line) {
                    echo "<div class='details_error'>" . _("ERROR FOUND: ") . "{$line}</div>";
                }
            }
            $conn->disconnect();
        }
        #print "</pre>\n";
    }
    print "</div>\n";
    $db_aux->close();
    $geoloc->close();
    return;
}
示例#12
0
function query_inventory($value)
{
    require_once 'ossim_db.inc';
    // Database Object
    $db = new ossim_db();
    $conn = $db->connect();
    $date_from = $_SESSION['inventory_search']['date_from'] != "" ? $_SESSION['inventory_search']['date_from'] : "1700-01-01";
    $date_to = $_SESSION['inventory_search']['date_to'] != "" ? $_SESSION['inventory_search']['date_to'] : "3000-01-01";
    $value = str_replace("/", "\\/", $value);
    $error = "";
    $matches = array();
    $ips = array();
    // OS
    $allips = array();
    $sql = "SELECT DISTINCT ip FROM host_os";
    if (!($rs =& $conn->Execute($sql))) {
        $error = _("Error in Query: {$sql}");
    } else {
        while (!$rs->EOF) {
            $allips[] = $rs->fields['ip'];
            $rs->MoveNext();
        }
    }
    foreach ($allips as $ip) {
        /*
        $anom0os = $anom1os = "";
        $sql2 = "SELECT os FROM host_os WHERE os LIKE '%$value%' AND ip=$ip AND anom=0 AND date >= '$date_from' AND date <= '$date_to' ORDER BY date DESC LIMIT 1";
        if (!$rs = & $conn->Execute($sql2, $params)) {
        	$error = _("Error in Query: $sql2");
        } else {
        	while (!$rs->EOF) {
        		$anom0os = $rs->fields['os'];
        		$rs->MoveNext();
        	}
        }
        $sql2 = "SELECT os FROM host_os WHERE os LIKE '%$value%' AND ip=$ip AND anom=1 AND date >= '$date_from' AND date <= '$date_to' ORDER BY date DESC LIMIT 1";
        if (!$rs = & $conn->Execute($sql2, $params)) {
        	$error = _("Error in Query: $sql2");
        } else {
        	while (!$rs->EOF) {
        		$anom1os = $rs->fields['os'];
        		$rs->MoveNext();
        	}
        }
        if ($anom0os != "") $matches[$anom0os][] = long2ip($ip); // Add IP to list
        elseif ($anom1os != "") $matches[$anom1os][] = long2ip($ip);
        */
        $ret = Host_os::get_ip_data($conn, long2ip($ip));
        $matches[$ret['os']][] = long2ip($ip);
    }
    // Services
    $allips = array();
    $sql = "SELECT DISTINCT ip FROM host_services";
    if (!($rs =& $conn->Execute($sql))) {
        $error = _("Error in Query: {$sql}");
    } else {
        while (!$rs->EOF) {
            $allips[] = $rs->fields['ip'];
            $rs->MoveNext();
        }
    }
    foreach ($allips as $ip) {
        $anom0serv = $anom1serv = "";
        $sql2 = "SELECT service FROM host_services WHERE service LIKE '%{$value}%' AND ip={$ip} AND anom=0 AND date >= '{$date_from}' AND date <= '{$date_to}' ORDER BY date DESC LIMIT 1";
        if (!($rs =& $conn->Execute($sql2, $params))) {
            $error = _("Error in Query: {$sql2}");
        } else {
            while (!$rs->EOF) {
                $anom0serv = $rs->fields['service'];
                $rs->MoveNext();
            }
            //if ($ip == 3232235781) return array(1,"matches IP $anom0serv");
        }
        $sql2 = "SELECT service FROM host_services WHERE service LIKE '%{$value}%' AND ip={$ip} AND anom=1 ORDER BY date AND date >= '{$date_from}' AND date <= '{$date_to}' DESC LIMIT 1";
        if (!($rs =& $conn->Execute($sql2, $params))) {
            $error = _("Error in Query: {$sql2}");
        } else {
            while (!$rs->EOF) {
                $anom1serv = $rs->fields['service'];
                $rs->MoveNext();
            }
        }
        if ($anom0serv != "") {
            $matches[$anom0serv][] = long2ip($ip);
        } elseif ($anom1serv != "") {
            $matches[$anom1serv][] = long2ip($ip);
        }
    }
    foreach ($matches as $os_service => $ips_arr) {
        //echo "found $os_service<br>";
        //return array(1,"matches ".implode(",",array_keys($matches)));
        if (preg_match("/{$value}/i", $os_service)) {
            $ips = $ips_arr;
        }
    }
    if ($error != "") {
        return array(1, $error);
    } else {
        return array(0, $ips);
    }
}
示例#13
0
function get_report_data($id = NULL)
{
    $conf = $GLOBALS['CONF'];
    $conf = !$conf ? new Ossim_conf() : $conf;
    $y = strftime('%Y', time() - 24 * 60 * 60 * 30);
    $m = strftime('%m', time() - 24 * 60 * 60 * 30);
    $d = strftime('%d', time() - 24 * 60 * 60 * 30);
    $reports['asset_report'] = array('report_name' => _('Asset Details'), 'report_id' => 'asset_report', 'type' => 'external', 'link_id' => 'link_ar_asset', 'link' => '', 'parameters' => array(array('name' => _('Host Name/IP/Network'), 'id' => 'ar_asset', 'type' => 'asset', 'default_value' => '')), 'access' => Session::menu_perms('environment-menu', 'PolicyHosts') || Session::menu_perms('environment-menu', 'PolicyNetworks'), 'send_by_email' => 0);
    $status_values = array('All' => array('text' => _('All')), 'Open' => array('text' => _('Open')), 'Assigned' => array('text' => _('Assigned')), 'Studying' => array('text' => _('Studying')), 'Waiting' => array('text' => _('Waiting')), 'Testing' => array('text' => _('Testing')), 'Closed' => array('text' => _('Closed')));
    $types_values = array('ALL' => array('text' => _('ALL')), 'Expansion Virus' => array('text' => _('Expansion Virus')), 'Corporative Nets Attack' => array('text' => _('Corporative Nets Attack')), 'Policy Violation' => array('text' => _('Policy Violation')), 'Security Weakness' => array('text' => _('Security Weakness')), 'Net Performance' => array('text' => _('Net Performance')), 'Applications and Systems Failures' => array('text' => _('Applications and Systems Failures')), 'Anomalies' => array('text' => _('Anomalies')), 'Vulnerability' => array('text' => _('Vulnerability')));
    $priority_values = array('High' => _('High'), 'Medium' => _('Medium'), 'Low' => _('Low'));
    $reports['tickets_report'] = array('report_name' => _('Tickets Report'), 'report_id' => 'tickets_report', 'type' => 'pdf', 'subreports' => array('title_page' => array('id' => 'title_page', 'name' => _('Title Page'), 'report_file' => 'os_reports/Common/titlepage.php'), 'alarm' => array('id' => 'alarm', 'name' => _('Alarm'), 'report_file' => 'os_reports/Tickets/Alarm.php'), 'event' => array('id' => 'event', 'name' => _('Event'), 'report_file' => 'os_reports/Tickets/Event.php'), 'anomaly' => array('id' => 'anomaly', 'name' => _('Anomaly'), 'report_file' => 'os_reports/Tickets/Anomaly.php'), 'vulnerability' => array('id' => 'vulnerability', 'name' => _('Vulnerability'), 'report_file' => 'os_reports/Tickets/Vulnerability.php')), 'parameters' => array(array('name' => _('Date Range'), 'date_from_id' => 'tr_date_from', 'date_to_id' => 'tr_date_to', 'type' => 'date_range', 'default_value' => array('date_from' => $y . '-' . $m . '-' . $d, 'date_to' => date('Y') . '-' . date('m') . '-' . date('d'))), array('name' => _('Status'), 'id' => 'tr_status', 'type' => 'select', 'values' => $status_values), array('name' => _('Type'), 'id' => 'tr_type', 'type' => 'select', 'values' => $types_values), array('name' => _('Priority'), 'id' => 'tr_priority', 'type' => 'checkbox', 'values' => $priority_values)), 'access' => Session::menu_perms('analysis-menu', 'IncidentsIncidents'), 'send_by_email' => 1);
    $reports['alarm_report'] = array('report_name' => _('Alarms Report'), 'report_id' => 'alarm_report', 'type' => 'pdf', 'subreports' => array('title_page' => array('id' => 'title_page', 'name' => _('Title Page'), 'report_file' => 'os_reports/Common/titlepage.php'), 'top_attacker_host' => array('id' => 'top_attacker_host', 'name' => _('Top 10 Attacker Host'), 'report_file' => 'os_reports/Alarms/AttackerHosts.php'), 'top_attacked_host' => array('id' => 'top_attacked_host', 'name' => _('Top 10 Attacked Host'), 'report_file' => 'os_reports/Alarms/AttackedHosts.php'), 'used_port' => array('id' => 'used_port', 'name' => _('Top 10 Used Ports'), 'report_file' => 'os_reports/Alarms/UsedPorts.php'), 'top_events' => array('id' => 'top_events', 'name' => _('Top 15 Alarms'), 'report_file' => 'os_reports/Alarms/TopAlarms.php'), 'events_by_risk' => array('id' => 'events_by_risk', 'name' => _('Top 15 Alarms by Risk'), 'report_file' => 'os_reports/Alarms/TopAlarmsByRisk.php')), 'parameters' => array(array('name' => _('Date Range'), 'date_from_id' => 'ar_date_from', 'date_to_id' => 'ar_date_to', 'type' => 'date_range', 'default_value' => array('date_from' => $y . '-' . $m . '-' . $d, 'date_to' => date('Y') . '-' . date('m') . '-' . date('d')))), 'access' => Session::menu_perms('analysis-menu', 'ControlPanelAlarms'), 'send_by_email' => 1);
    $reports['bc_pci_report'] = array('report_name' => _('Business & Compliance ISO PCI Report'), 'report_id' => 'bc_pci_report', 'type' => 'pdf', 'subreports' => array('title_page' => array('id' => 'title_page', 'name' => _('Title Page'), 'report_file' => 'os_reports/Common/titlepage.php'), 'threat_overview' => array('id' => 'threat_overview', 'name' => _('Threat overview'), 'report_file' => 'os_reports/BusinessAndComplianceISOPCI/ThreatOverview.php'), 'bri_risks' => array('id' => 'bri_risks', 'name' => _('Business real impact risks'), 'report_file' => 'os_reports/BusinessAndComplianceISOPCI/BusinessPotentialImpactsRisks.php'), 'ciap_impact' => array('id' => 'ciap_impact', 'name' => _('C.I.A Potential impact'), 'report_file' => 'os_reports/BusinessAndComplianceISOPCI/CIAPotentialImpactsRisks.php'), 'pci_dss' => array('id' => 'pci_dss', 'name' => _('PCI-DSS 2.0'), 'report_file' => 'os_reports/BusinessAndComplianceISOPCI/PCI-DSS.php'), 'pci_dss3' => array('id' => 'pci_dss3', 'name' => _('PCI-DSS 3.0'), 'report_file' => 'os_reports/BusinessAndComplianceISOPCI/PCI-DSS3.php'), 'trends' => array('id' => 'trends', 'name' => _('Trends'), 'report_file' => 'os_reports/BusinessAndComplianceISOPCI/Trends.php'), 'iso27002_p_impact' => array('id' => 'iso27002_p_impact', 'name' => _('ISO27002 Potential impact'), 'report_file' => 'os_reports/BusinessAndComplianceISOPCI/ISO27002PotentialImpact.php'), 'iso27001' => array('id' => 'iso27001', 'name' => _('ISO27001'), 'report_file' => 'os_reports/BusinessAndComplianceISOPCI/ISO27001.php')), 'parameters' => array(array('name' => _('Date Range'), 'date_from_id' => 'bc_pci_date_from', 'date_to_id' => 'bc_pci_date_to', 'type' => 'date_range', 'default_value' => array('date_from' => $y . '-' . $m . '-' . $d, 'date_to' => date('Y') . '-' . date('m') . '-' . date('d')))), 'access' => Session::menu_perms('report-menu', 'ReportsReportServer'), 'send_by_email' => 1);
    $reports['siem_report'] = array('report_name' => _('SIEM Events'), 'report_id' => 'siem_report', 'type' => 'pdf', 'subreports' => array('title_page' => array('id' => 'title_page', 'name' => _('Title Page'), 'report_file' => 'os_reports/Common/titlepage.php'), 'top_attacker_host' => array('id' => 'top_attacker_host', 'name' => _('Top 10 Attacker Host'), 'report_file' => 'os_reports/Siem/AttackerHosts.php'), 'top_attacked_host' => array('id' => 'top_attacked_host', 'name' => _('Top 10 Attacked Host'), 'report_file' => 'os_reports/Siem/AttackedHosts.php'), 'used_port' => array('id' => 'used_port', 'name' => _('Top 10 Used Ports'), 'report_file' => 'os_reports/Siem/UsedPorts.php'), 'top_events' => array('id' => 'top_events', 'name' => _('Top 15 Events'), 'report_file' => 'os_reports/Siem/TopEvents.php'), 'events_by_risk' => array('id' => 'events_by_risk', 'name' => _('Top 15 Events by Risk'), 'report_file' => 'os_reports/Siem/TopEventsByRisk.php')), 'parameters' => array(array('name' => _('Date Range'), 'date_from_id' => 'sr_date_from', 'date_to_id' => 'sr_date_to', 'type' => 'date_range', 'default_value' => array('date_from' => $y . '-' . $m . '-' . $d, 'date_to' => date('Y') . '-' . date('m') . '-' . date('d')))), 'access' => Session::menu_perms('analysis-menu', 'EventsForensics'), 'send_by_email' => 1);
    $reports['vulnerabilities_report'] = array('report_name' => _('Vulnerabilities Report'), 'report_id' => 'vulnerabilities_report', 'type' => 'external', 'target' => '_blank', 'link_id' => 'link_vr', 'link' => Menu::get_menu_url('../vulnmeter/lr_respdf.php?ipl=all&scantype=M', 'environment', 'vulnerabilities', 'overview'), 'access' => Session::menu_perms('analysis-menu', 'EventsVulnerabilities'), 'send_by_email' => 0);
    $reports['th_vuln_db'] = array('report_name' => _('Threats & Vulnerabilities Database'), 'report_id' => 'th_vuln_db', 'type' => 'external', 'link_id' => 'link_tvd', 'link' => Menu::get_menu_url('../vulnmeter/threats-db.php', 'environment', 'vulnerabilities', 'threat_database'), 'access' => Session::menu_perms('analysis-menu', 'EventsVulnerabilities'), 'send_by_email' => 0);
    $reports['ticket_status'] = array('report_name' => _('Tickets Status'), 'report_id' => 'ticket_status', 'type' => 'external', 'link_id' => 'link_tr', 'link' => Menu::get_menu_url('../report/incidentreport.php', 'analysis', 'tickets', 'tickets'), 'access' => Session::menu_perms('analysis-menu', 'IncidentsIncidents'), 'send_by_email' => 0);
    $db = new ossim_db();
    $conn = $db->connect();
    $user = Session::get_session_user();
    $session_list = Session::get_list($conn, 'ORDER BY login');
    if (preg_match('/pro|demo/', $conf->get_conf('ossim_server_version')) && !Session::am_i_admin()) {
        $myusers = Acl::get_my_users($conn, Session::get_session_user());
        if (count($myusers) > 0) {
            $is_pro_admin = 1;
        }
    }
    // User Log lists
    if (Session::am_i_admin()) {
        $user_values[''] = array('text' => _('All'));
        if ($session_list) {
            foreach ($session_list as $session) {
                $login = $session->get_login();
                $user_values[$login] = $login == $user ? array('text' => $login, 'selected' => TRUE) : array('text' => $login);
            }
        }
    } elseif ($is_pro_admin) {
        foreach ($myusers as $myuser) {
            $user_values[$myuser['login']] = array('text' => $myuser['login']);
            $user_values[$user] = array('text' => $user, 'selected' => TRUE);
        }
    } else {
        $user_values[$user] = array('text' => $user);
    }
    $code_list = Log_config::get_list($conn, 'ORDER BY descr');
    $action_values[''] = array('text' => _('All'));
    if ($code_list) {
        foreach ($code_list as $code_log) {
            $code_aux = $code_log->get_code();
            $action_values[$code_aux] = array('text' => '[' . sprintf("%02d", $code_aux) . '] ' . _(preg_replace('|%.*?%|', " ", $code_log->get_descr())));
        }
    }
    $reports['user_activity'] = array('report_name' => _('User Activity Report'), 'report_id' => 'user_activity', 'type' => 'external', 'link_id' => 'link_ua', 'link' => Menu::get_menu_url('../userlog/user_action_log.php', 'settings', 'settings', 'user_activity'), 'parameters' => array(array('name' => _('User'), 'id' => 'ua_user', 'type' => 'select', 'values' => $user_values), array('name' => _('Action'), 'id' => 'ua_action', 'type' => 'select', 'values' => $action_values)), 'access' => Session::menu_perms('settings-menu', 'ToolsUserLog'), 'send_by_email' => 0);
    $reports['geographic_report'] = array('report_name' => _('Geographic Report'), 'report_id' => 'geographic_report', 'type' => 'pdf', 'subreports' => array('title_page' => array('id' => 'title_page', 'name' => _('Title Page'), 'report_file' => 'os_reports/Common/titlepage.php'), 'geographic_report' => array('id' => 'geographic_report', 'name' => _('Geographic Report'), 'report_file' => 'os_reports/Various/Geographic.php')), 'parameters' => array(array('name' => _('Date Range'), 'date_from_id' => 'gr_date_from', 'date_to_id' => 'gr_date_to', 'type' => 'date_range', 'default_value' => array('date_from' => $y . '-' . $m . '-' . $d, 'date_to' => date('Y') . '-' . date('m') . '-' . date('d')))), 'access' => Session::menu_perms('analysis-menu', 'EventsForensics'), 'send_by_email' => 1);
    //Sensor list
    $sensor_values[''] = array('text' => ' -- ' . _('Sensors no found') . ' -- ');
    $filters = array('order_by' => 'name');
    $sensor_list = Av_sensor::get_basic_list($conn, $filters);
    $filters = array('order_by' => 'priority desc');
    list($sensor_list, $sensor_total) = Av_sensor::get_list($conn, $filters);
    if ($sensor_total > 0) {
        $sensor_values = array();
        foreach ($sensor_list as $s) {
            $properties = $s['properties'];
            if ($properties['has_nagios']) {
                $sensor_values[$s['ip']] = array('text' => $s['name']);
            }
        }
    }
    /* Nagios link */
    $nagios_link = $conf->get_conf('nagios_link');
    $scheme = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
    $path = !empty($nagios_link) ? $nagios_link : '/nagios3/';
    $port = !empty($_SERVER['SERVER_PORT']) ? ':' . $_SERVER['SERVER_PORT'] : "";
    $nagios = $port . $path;
    $section_values = array(urlencode($nagios . 'cgi-bin/trends.cgi') => array('text' => _('Trends')), urlencode($nagios . 'cgi-bin/avail.cgi') => array('text' => _('Availability')), urlencode($nagios . 'cgi-bin/histogram.cgi') => array('text' => _('Event Histogram')), urlencode($nagios . 'cgi-bin/history.cgi?host=all') => array('text' => _('Event History')), urlencode($nagios . 'cgi-bin/summary.cgi') => array('text' => _('Event Summary')), urlencode($nagios . 'cgi-bin/notifications.cgi') => array('text' => _('Notifications')), urlencode($nagios . 'cgi-bin/showlog.cgi') => array('text' => _('Performance Info')));
    $reports['availability_report'] = array('report_name' => _('Availability Report'), 'report_id' => 'availability_report', 'type' => 'external', 'link_id' => 'link_avr', 'click' => "nagios_link('avr_nagios_link', 'avr_sensor', 'avr_section');", 'parameters' => array(array('name' => _('Sensor'), 'id' => 'avr_sensor', 'type' => 'select', 'values' => $sensor_values), array('name' => 'Nagioslink', 'id' => 'avr_nagios_link', 'type' => 'hidden', 'default_value' => urlencode($scheme)), array('name' => _('Section'), 'id' => 'avr_section', 'type' => 'select', 'values' => $section_values)), 'access' => Session::menu_perms('environment-menu', 'MonitorsAvailability'), 'send_by_email' => 0);
    $db->close();
    if ($id == NULL) {
        ksort($reports);
        return $reports;
    } else {
        return !empty($reports[$id]) ? $reports[$id] : array();
    }
}
示例#14
0
 function end_upgrade($logfile)
 {
     $conn = new ossim_db();
     $db = $conn->connect();
     //
     // PROPERTIES
     //
     $properties = array();
     $db->StartTrans();
     $rs = $db->Execute("SELECT hex(host_id) as id,property_ref,last_modified,source_id,value,extra,tzone FROM alienvault.host_properties WHERE property_ref>0");
     while (!$rs->EOF) {
         $properties[] = $rs->fields;
         $rs->MoveNext();
     }
     $db->Execute("DELETE FROM alienvault.host_properties");
     @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
     foreach ($properties as $prop) {
         $values = json_decode($prop['value'], true);
         $sql = "INSERT IGNORE INTO alienvault.host_properties (host_id, property_ref, last_modified, source_id, value, extra, tzone) VALUES (UNHEX(?), ? ,? ,? ,? ,? ,?)";
         if (json_last_error() === JSON_ERROR_NONE && is_array($values)) {
             foreach ($values as $value) {
                 if ($prop['property_ref'] == 3) {
                     $value = preg_replace("/\\b(\\w+)\\s+\\1\\b/i", "\$1", preg_replace("/(.*?):(.*)/", "\$1 \$2", $value));
                 } elseif ($prop['property_ref'] == 8) {
                     $value = preg_replace("/\\|/", "@", $value);
                 }
                 $params = array($prop['id'], $prop['property_ref'], $prop['last_modified'], $prop['source_id'], $value, $prop['extra'], $prop['tzone']);
                 $db->Execute($sql, $params);
                 @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
                 if ($prop['property_ref'] == 3) {
                     break;
                     // Only the first OS
                 }
             }
         } else {
             if ($prop['property_ref'] == 3) {
                 $prop['value'] = preg_replace("/\\b(\\w+)\\s+\\1\\b/i", "\$1", preg_replace("/(.*?):(.*)/", "\$1 \$2", $prop['value']));
             } elseif ($prop['property_ref'] == 8) {
                 $prop['value'] = preg_replace("/\\|/", "@", $prop['value']);
             }
             $params = array($prop['id'], $prop['property_ref'], $prop['last_modified'], $prop['source_id'], $prop['value'], $prop['extra'], $prop['tzone']);
             $db->Execute($sql, $params);
             @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
         }
     }
     if (!$db->CompleteTrans()) {
         @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
         return 1;
     }
     $db->Execute("DELETE FROM alienvault.host_properties WHERE value like 'unknown%'");
     @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
     // HOST SOFTWARE CPE
     $cpes = array();
     $db->StartTrans();
     $rs = $db->Execute("SELECT DISTINCT cpe FROM host_software");
     while (!$rs->EOF) {
         $cpes[] = $rs->fields['cpe'];
         $rs->MoveNext();
     }
     foreach ($cpes as $cpe) {
         $params = array(Asset_host_software::get_software_name_by_cpe($db, $cpe), $cpe);
         $db->Execute("UPDATE host_software SET banner=? WHERE cpe=?", $params);
         @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
     }
     if (!$db->CompleteTrans()) {
         @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
         return 1;
     }
     //
     // VULN_JOB_ASSET
     //
     $jobs = array();
     $db->StartTrans();
     $rs = $db->Execute("SELECT id,meth_TARGET FROM alienvault.vuln_job_schedule");
     while (!$rs->EOF) {
         $jobs[] = array('id' => $rs->fields['id'], 'targets' => explode("\n", $rs->fields['meth_TARGET']));
         $rs->MoveNext();
     }
     foreach ($jobs as $job) {
         $db->Execute("DELETE FROM alienvault.vuln_job_assets WHERE job_id=? AND job_type=0", array($job['id']));
         @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
         foreach ($job['targets'] as $target) {
             if (preg_match("/(.*)#(.*)/", $target, $matches)) {
                 // ADD ASSET_ID
                 $sql = "INSERT IGNORE INTO alienvault.vuln_job_assets (job_id, job_type, asset_id) VALUES (?, 0, UNHEX(?))";
                 $params = array($job['id'], $matches[1]);
                 $db->Execute($sql, $params);
                 @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
                 if (preg_match("/\\/\\d+/", $matches[2])) {
                     // NETWORK MEMBERS
                     $sql = "INSERT IGNORE INTO alienvault.vuln_job_assets (job_id, job_type, asset_id) SELECT ?, 0, host_id FROM host_net_reference WHERE net_id=UNHEX(?)";
                     $params = array($job['id'], $matches[1]);
                     $db->Execute($sql, $params);
                     @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
                 }
             }
         }
     }
     if (!$db->CompleteTrans()) {
         @file_put_contents($logfile, $db->ErrorMsg(), FILE_APPEND);
         return 1;
     }
     $conn->close();
     return 0;
 }
if ($mode == 'init') {
    ?>
    <script type="text/javascript"> 
        parent.$("#pbar").progressBar(0);    
    </script> 
    <?php 
} else {
    ?>
    <script type="text/javascript">    
        parent.$("#pbar").progressBar();    
    </script> 
    <?php 
}
// Get networks and already hosts
$db = new ossim_db();
$conn_aux = $db->connect();
list($nets, $total) = Asset_net::get_list($conn_aux);
$i = 1;
// Search new hosts by networks
foreach ($nets as $net) {
    session_write_close();
    usleep(500000);
    ob_flush();
    ?>
        	
    <script type="text/javascript">
        parent.$("#pbar").progressBar(<?php 
    echo floor($i * 100 / $total);
    ?>
);
                        
示例#16
0
function PrintPredefinedViews()
{
    global $opensource;
    $current_str = $_SESSION['current_cview'] != "default" && $_SESSION['current_cview'] != "" ? Util::htmlentities($_SESSION['current_cview']) : _("Default");
    // Get default view
    require_once "ossim_conf.inc";
    $conf = $GLOBALS["CONF"];
    $idm_enabled = $conf->get_conf("enable_idm") == 1 && Session::is_pro() ? true : false;
    $login = Session::get_session_user();
    $db_aux = new ossim_db(true);
    $conn_aux = $db_aux->connect();
    $config = new User_config($conn_aux);
    $default_view = $config->get($login, 'custom_view_default', 'php', "siem") != "" ? $config->get($login, 'custom_view_default', 'php', "siem") : ($idm_enabled ? 'IDM' : 'default');
    $db_aux->close($conn_aux);
    ?>
    <button id="views_link" class="button av_b_secondary">
        <?php 
    echo _('Change View');
    ?>
 &nbsp;&#x25be;
    </button>

    <div id="custom_views" class="dropdown dropdown-secondary dropdown-close dropdown-tip dropdown-anchor-right dropdown-scrolling" style='display:none'>
        <ul id="custom_views_ul" class="dropdown-menu">
            <?php 
    if (Session::am_i_admin()) {
        ?>
            <li><a href="#" onclick="GB_show('<?php 
        echo _("Edit Current View");
        ?>
','/forensics/custom_view_edit.php?edit=1',480,700);$('#custom_views').hide();return false"><?php 
        echo _("Edit Current View");
        ?>
&nbsp;</a></li>
            <li><a href="#" onclick="GB_show('<?php 
        echo _("Create new custom view");
        ?>
','/forensics/custom_view_edit.php',480,700);$('#custom_views').hide();return false"><?php 
        echo _("Create New View");
        ?>
&nbsp;</a></li>
            <?php 
    }
    foreach ($_SESSION['views'] as $name => $attr) {
        $dname = $name == "default" ? "Default" : $name;
        $selected = $_SESSION['current_cview'] == $name ? "&#x25BA;&nbsp;" : "";
        ?>
                <li><a href="#" onclick="change_view('<?php 
        echo Util::htmlentities($name);
        ?>
');$('#custom_views').hide()"><?php 
        echo $selected . Util::htmlentities($dname);
        ?>
&nbsp;</a></li>
            <?php 
    }
    ?>
        </ul>
    </div>

    <?php 
}
示例#17
0
function GetOssimHostsFromHostGroups($hostgroup)
{
    $db = new ossim_db();
    $conn = $db->connect();
    $pg = array();
    try {
        $asset_group = new Asset_group($hostgroup);
        $asset_group->load_from_db($conn);
        $_hosts = $asset_group->get_hosts($conn, array(), TRUE);
        $hosts = $_hosts[0];
    } catch (Exception $e) {
        echo $e->getMessage();
        return $pg;
    }
    foreach ($hosts as $hg) {
        $pg[] = $hg[2];
        //  Array ( [0] => ID [1] => CTX [2] => IP [3] => Name )
    }
    $db->close();
    return $pg;
}
示例#18
0
function echochildrens($entities, $parent_id, $withusers, $entities_admin)
{
    $length_name = 50;
    echo ",children:[";
    /* Connect to db */
    $db = new ossim_db();
    $conn = $db->connect();
    $users_by_entity = Acl::get_users_by_entity($conn, $parent_id);
    $me = Session::get_session_user();
    $entities_types = Acl::get_entities_types($conn);
    $is_editable = $parent_id != "" && (!empty($users_by_entity[$me]) || Session::am_i_admin() || !empty($entities_admin[$me]));
    if ($is_editable) {
        echo "{title:'<font style=\"font-weight:normal\">" . _("All Assets") . "</font>', key:'ae_" . $parent_id . "', icon:'../../pixmaps/menu/assets.gif', isFolder:true, isLazy:true}";
        if ($withusers) {
            echo ",{title:'<font style=\"font-weight:normal\">" . _("Assets by user") . "</font>', key:'ue_" . $parent_id . "', icon:'../../pixmaps/menu/assets.gif', isFolder:true, isLazy:true}";
        }
    }
    $children = Acl::get_entity_childs($conn, $parent_id);
    if (!empty($children)) {
        $flag = false;
        foreach ($children as $index => $child_id) {
            $icon = "../../pixmaps/theme/any.png";
            $child = $entities[0][$child_id];
            $entity_allowed = Acl::entityAllowed($child_id);
            if ($entity_allowed == 2) {
                $child_link = "noLink: false";
                $child_url = "../acl/entities_edit.php?id=" . $child_id;
            } else {
                $child_link = "noLink: true";
                $child_url = "";
            }
            $child_key = "e_" . $child_id;
            $child_sn = strlen($child['name']) > $length_name ? substr($child['name'], 0, $length_name) . "..." : $child['name'];
            $child_name = Util::htmlentities($child['name']);
            $chil_ent_admin = $entities_admin;
            $chil_ent_admin[$child['admin_user']] = $child_id;
            if ($child['parent_id'] == $parent_id) {
                $title = "<font style=\"font-weight:bold;\">" . Util::htmlentities($child_sn) . "</font> <font style=\"color:gray\">[" . $entities_types[$child['type']]['name'] . "]</font>";
                $tooltip = Util::htmlentities($child['name']) . " [" . $entities_types[$child['type']]['name'] . "]";
                if ($flag || $is_editable) {
                    echo ",";
                }
                $flag = true;
                $h = "400";
                echo "{title:'" . $title . "', h:'{$h}', " . $child_link . ", url:'" . $child_url . "', tooltip:'{$tooltip}', key:'" . $child_key . "', icon:'{$icon}', expand:true, name:'{$child_name}'";
                echochildrens($entities, $child_id, $withusers, $entities_admin);
                echo "}";
            }
        }
    }
    echo "]";
}
示例#19
0
* Classes list:
*/
session_start();
require_once 'ossim_db.inc';
require_once 'classes/Alarm.inc';
require_once 'classes/Util.inc';
require_once 'classes/Host.inc';
require_once 'classes/Net.inc';
require_once 'classes/CIDR.inc';
require_once 'classes/Event_viewer.inc';
require_once 'classes/Security.inc';
require_once 'charts.php';
Session::logcheck("MenuControlPanel", "ControlPanelExecutive");
$db = new ossim_db();
$conn = $db->snort_connect();
$conn_ossim = $db->connect();
// plugins to resolv
$plugins = array();
$query1 = "SELECT id,name from plugin";
if (!($rs =& $conn_ossim->Execute($query1))) {
    print $conn_ossim->ErrorMsg();
    exit;
}
while (!$rs->EOF) {
    $plugins[$rs->fields["id"]] = preg_replace("/ossec-.*/", "ossec", $rs->fields["name"]);
    $rs->MoveNext();
}
$data = array();
$data[] = "";
$host = $_SESSION['host_report'];
// User sensor filtering
示例#20
0
function SendHeader($established)
{
    global $self, $m_opt, $sm_opt, $h_opt;
    global $TabList;
    header("Content-type: text/html; charset=ISO-8859-1");
    ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<meta http-equiv="Cache-Control" content="no-cache"/>
	<meta http-equiv="Pragma" content="no-cache"/>
	<link rel="stylesheet" type="text/css" href="../style/av_common.css?t=<?php 
    echo Util::get_css_id();
    ?>
">
	<link rel="stylesheet" type="text/css" href="../style/nfsen/nfsen.css">

	<script type="text/javascript" src="/ossim/js/jquery.min.js"></script>
	<script type='text/javascript' src="/ossim/js/notification.js"></script>
	<script type='text/javascript' src='/ossim/js/utils.js'></script>

<?php 
    include '../host_report_menu.php';
    if (!$established) {
        return;
    }
    $_tab = array_key_exists('tab', $_SESSION) ? $_SESSION['tab'] : 0;
    if (array_key_exists('tleft', $_SESSION)) {
        $str = $TabList[$_tab] == 'Details' ? strftime("%b %d %Y - %H:%M", $_SESSION['tleft']) : 'Overview';
    } else {
        $str = '';
    }
    ?>
    <title>
    <?php 
    if ($_REQUEST["login"]) {
        $name = strip_tags($_POST["name"]);
        $_SESSION["_nfsen_title"] = $name . " - Network Traffic";
    } elseif (empty($_SESSION["_nfsen_title"])) {
        $_SESSION["_nfsen_title"] = _("NFSEN");
    }
    echo Util::htmlentities($_SESSION["_nfsen_title"]) . _(' - Profile');
    ?>
 <?php 
    echo Util::htmlentities($_SESSION['profile']) . " {$str}";
    ?>
</title>

    <?php 
    $refresh = $_SESSION['refresh'];
    if ($TabList[$_tab] != 'Details' && $refresh > 0) {
        print "<meta HTTP-EQUIV='Refresh' CONTENT='" . Util::htmlentities($refresh) . "; URL=" . Util::htmlentities($self) . "?bookmark=" . Util::htmlentities($_SESSION['bookmark']) . "&bypassexpirationupdate=1'>\n";
    }
    if ($TabList[$_tab] == 'Details') {
        ?>
	   <link rel="stylesheet" type="text/css" href="../style/nfsen/detail.css">
	<?php 
    }
    if ($TabList[$_tab] == 'Stats') {
        ?>
	   <link rel="stylesheet" type="text/css" href="../style/nfsen/profileadmin.css">
	<?php 
    }
    if ($TabList[$_tab] == 'Alerts') {
        ?>
	   <link rel="stylesheet" type="text/css" href="../style/nfsen/alerting.css">
	   <?php 
    }
    ?>

	<script type="text/javascript" src="js/global.js"></script>
	<script type="text/javascript" src="js/menu.js"></script>
    <script type="text/javascript" src="../js/jquery.simpletip.js"></script>
    
    <!-- JQuery TipTip: -->
    <link rel="stylesheet" type="text/css" href="/ossim/style/tipTip.css"/>
    <script type="text/javascript" src="/ossim/js/jquery.tipTip-ajax.js"></script>
    
	<script type="text/javascript">
		function postload() {

		     // menu.php postload
			 $('#interface').change(function() {                        
                 send($(this).val(), $('#interface option:selected').text());
             });
             
             <?php 
    if (isset($_POST['ip'])) {
        ?>
                 send('<?php 
        echo Util::htmlentities($_POST['ip']);
        ?>
', $('#interface option:selected').text());
                 <?php 
    }
    ?>
             // ************

             $('.scriptinfo').tipTip({
                 defaultPosition: "down",
                 content: function (e) {
                    
                    var ip_data = $(this).attr('data-title');
                        ip_data = ip_data.split('-');
                    
                    $.ajax({
                        url: '../alarm/alarm_netlookup.php?ip=' + ip_data[0],
                        success: function (response) {
                          e.content.html(response); // the var e is the callback function data (see above)
                        }
                    });
                    return '<?php 
    echo _("Searching") . "...";
    ?>
'; // We temporary show a Please wait text until the ajax success callback is called.
                 }
              });
  			
			$(".repinfo").tipTip({
				defaultPosition: 'left',
				content: function (e) { 
					return $(this).attr('txt');
				}
			});  
                
			$('#filter').on('keyup', function(e){
                $(this).val(function(i, val) {
					return val.replace(/[\t\r\b]/g, '');
				});
			});
										  
			<?php 
    if (GET('ip') != "") {
        ?>
				$("#process_button").click();
				<?php 
    }
    ?>
			
		}

		function lastsessions() {
			$('#modeselect0').click();
			$("#listN option[value='3']").attr('selected', 'selected');
			$("#process_button").click();
		}
		
		function launch(val,order) {
			$('#modeselect1').click();
			$("#TopN option[value='0']").attr('selected', 'selected');
			$("#StatTypeSelector option[value='"+val+"']").attr('selected', 'selected');
			$("#statorder option[value='"+order+"']").attr('selected', 'selected');
			$("#process_button").click();
		}
		
		function remote_interface(ip) {
			$("#FlowProcessingForm").attr("action", "menu.php");
			$("#FlowProcessingForm").attr("target", "menu_nfsen");
			$("#FlowProcessingForm").append("<input type='hidden' name='process' value='Process' />");
			$("#FlowProcessingForm").append("<input type='hidden' name='ip' value='"+ip+"' />");
			$("#FlowProcessingForm").submit();
		}
		
		function clean_remote_data() {
			$("#FlowProcessingForm").removeAttr("target");
			$("#FlowProcessingForm").attr("action", $("#FlowProcessingForm").attr("laction")); // set the local action
		}
	</script>	
</head>

<body>

<?php 
    $db_aux = new ossim_db();
    $conn_aux = $db_aux->connect();
    $aux_ri_interfaces = Remote_interface::get_list($conn_aux, "WHERE status = 1");
    $ri_list = $aux_ri_interfaces[0];
    $ri_total = $aux_ri_interfaces[1];
    $db_aux->close();
    if (Session::am_i_admin() && count($ri_total) > 0) {
        include 'menu.php';
    }
}
示例#21
0
*/
require_once 'av_init.php';
if (Session::menu_perms("report-menu", "ReportsReportServer")) {
    include_once 'updateBd.php';
    require_once 'common.php';
    include 'general.php';
    /*
     * PCI Version, if 3.0 then this variable is predefined in PCI-DSS3.php
     * The code is shared with this only diference
     */
    $pci_version = $pci_version != '' ? $pci_version : '';
    $sql_year = "STR_TO_DATE( CONCAT( a.year, '-', a.month, '-', a.day ) , '%Y-%m-%d' ) >= '{$date_from}' AND STR_TO_DATE( CONCAT( a.year, '-', a.month, '-', a.day ) , '%Y-%m-%d' ) <= '{$date_to}'";
    //create
    require_once 'ossim_db.inc';
    $db1 = new ossim_db();
    $conn1 = $db1->connect();
    // Check if PCI database exists
    if (!pci_database_available($conn1, "PCI{$pci_version}")) {
        $htmlPdfReport->pageBreak();
        $htmlPdfReport->setBookmark($title);
        $htmlPdfReport->set($htmlPdfReport->newTitle($title, "", "", null));
        $htmlPdfReport->set('<table align="center" width="750" cellpadding="0" cellspacing="0"><tr><td>' . _('Database not found') . ': PCI' . $pci_version . '</td></tr></table><br/><br/>');
        $db1->close();
    } else {
        tmp_insert($conn1, "PCI{$pci_version}.R01_FW_Config");
        tmp_insert($conn1, "PCI{$pci_version}.R02_Vendor_default");
        tmp_insert($conn1, "PCI{$pci_version}.R03_Stored_cardholder");
        tmp_insert($conn1, "PCI{$pci_version}.R04_Data_encryption");
        tmp_insert($conn1, "PCI{$pci_version}.R05_Antivirus");
        tmp_insert($conn1, "PCI{$pci_version}.R06_System_app");
        tmp_insert($conn1, "PCI{$pci_version}.R07_Access_control");
示例#22
0
function GetOssimNetworkGroups()
{
    require_once "classes/Net_group.inc";
    require_once 'ossim_db.inc';
    $db = new ossim_db();
    $conn = $db->connect();
    $pg = array();
    $groups = Net_group::get_list($conn, "", " ORDER BY name");
    foreach ($groups as $ng) {
        $pg[] = $ng->get_name();
    }
    $conn->disconnect();
    return $pg;
}
示例#23
0
    $conf = $GLOBALS["CONF"];
    $ossim_link = $conf->get_conf("ossim_link", FALSE);
    $login_location = $ossim_link . '/session/login.php';
    header("Location: {$login_location}");
    exit;
}
require_once "classes/Util.inc";
// Timezone correction
$tz = Util::get_timezone();
$timetz = gmdate("U") + 3600 * $tz;
// time to generate dates with timezone correction
// Custom Views
require_once 'classes/User_config.inc';
$login = Session::get_session_user();
$db_aux = new ossim_db();
$conn_aux = $db_aux->connect();
$config = new User_config($conn_aux);
$_SESSION['views'] = $config->get($login, 'custom_views', 'php', "siem");
// First save of default view (important!)
if ($_SESSION['views']['default'] == "") {
    $_SESSION['views']['default']['cols'] = array('SIGNATURE', 'DATE', 'IP_PORTSRC', 'IP_PORTDST', 'ASSET', 'PRIORITY', 'RELIABILITY', 'RISK', 'IP_PROTO');
    $session_data = $_SESSION;
    foreach ($_SESSION as $k => $v) {
        if (preg_match("/^(_|alarms_|back_list|current_cview|views|ports_cache|acid_|report_|graph_radar|siem_event|deletetask|mdspw).*/", $k)) {
            unset($session_data[$k]);
        }
    }
    $_SESSION['views']['default']['data'] = $session_data;
    $config->set($login, 'custom_views', $_SESSION['views'], 'php', 'siem');
}
if ($_GET["search_str"] == "search term") {
示例#24
0
function echochildrens($entities, $parent_id, $entities_admin)
{
    /* Connect to db */
    $db = new ossim_db();
    $conn = $db->connect();
    $users_by_entity = Acl::get_users_by_entity($conn, $parent_id);
    $me = Session::get_session_user();
    $entities_types = Acl::get_entities_types($conn);
    $length_name = !empty($_GET['length_name']) ? GET('length_name') : 30;
    echo ",children:[";
    $is_editable = $parent_id != "" && (!empty($users_by_entity[$me]) || Session::am_i_admin() || !empty($entities_admin[$me]));
    if ($is_editable) {
        echo "{title:'<font style=\"font-weight:normal\">" . _("All Assets") . "</font>', url:'AllAssets', key:'e_" . $parent_id . "_allassets', icon:'../../pixmaps/menu/assets.gif', isFolder:false, expand:true,";
        echo "children:[ ";
        echo "{ key:'e_" . $parent_id . "_net', isFolder:true, isLazy:true, icon:'../../pixmaps/theme/net.png', title:'" . _("Networks") . "'},";
        echo "{ key:'e_" . $parent_id . "_sensor', isFolder:true, isLazy:true, icon:'../../pixmaps/theme/server.png', title:'" . _("Sensors") . "'}";
        echo "]}";
    }
    $children = Acl::get_entity_childs($conn, $parent_id);
    if (!empty($children)) {
        $flag = false;
        foreach ($children as $index => $child_id) {
            $icon = "../../pixmaps/theme/any.png";
            $child = $entities[0][$child_id];
            $entity_allowed = Acl::entityAllowed($child_id);
            $child_key = "e_" . $child_id;
            $child_sn = strlen($child['name']) > $length_name ? substr($child['name'], 0, $length_name) . "..." : $child['name'];
            $child_name = Util::htmlentities($child['name']);
            $chil_ent_admin = $entities_admin;
            $chil_ent_admin[$child['admin_user']] = $child_id;
            if ($child['parent_id'] == $parent_id) {
                $title = "<font style=\"font-weight:bold;\">" . Util::htmlentities($child_sn) . "</font> <font style=\"color:gray\">[" . $entities_types[$child['type']]['name'] . "]</font>";
                $tooltip = Util::htmlentities($child['name']) . " [" . $entities_types[$child['type']]['name'] . "]";
                if ($flag || $is_editable) {
                    echo ",";
                }
                $flag = true;
                echo "{title:'" . $title . "', tooltip:'{$tooltip}', noLink: true, url:'" . $child_url . "', key:'" . $child_key . "', icon:'{$icon}', expand:true, name:'{$child_name}'";
                echochildrens($entities, $child_id, $withusers, $entities_admin, $length_name);
                echo "}";
            }
        }
    }
    echo "]";
}
示例#25
0
function Logger_trends()
{
    require_once "forensics_stats.inc";
    require_once "../sem/process.inc";
    require_once 'ossim_db.inc';
    global $tz;
    $data = array();
    $db = new ossim_db();
    $dbconn = $db->connect();
    // Get remote logger servers
    list($logger_servers, $ip_to_name, $ip_list, $fcolors, $bcolors, $from_remote, $logger_colors) = get_logger_servers($dbconn);
    $db->close($dbconn);
    foreach ($logger_servers as $ip) {
        if ($ip != "127.0.0.1") {
            $cmd = "sudo /usr/share/ossim/www/sem/fetchremote_graph.pl panel {$tz} {$ip}";
            //echo $cmd;
            exec($cmd, $aux);
            foreach ($aux as $line) {
                if (preg_match("/(.*);(.*)\\=(.*)/", $line, $fnd)) {
                    // 9 12h;192.168.10.1=703
                    if (Session::sensorAllowed($fnd[2])) {
                        $data[$fnd[1]] = trim($fnd[3]);
                    }
                }
            }
        }
    }
    // local server
    $today = gmdate("j");
    $beforeyesterday = gmdate("j", strtotime("-2 day"));
    $yesterday = gmdate("j", strtotime("-1 day"));
    $tomorrow = gmdate("j", strtotime("+1 day"));
    $csy = get_day_csv(gmdate("Y", strtotime("-1 day")), gmdate("m", strtotime("-1 day")), gmdate("d", strtotime("-1 day")));
    $csv = get_day_csv(gmdate("Y"), gmdate("m"), gmdate("d"));
    //print_r($csy); print_r($csv);
    foreach ($csy as $key => $value) {
        $tzhour = $key + $tz;
        $day = $yesterday;
        if ($tzhour < 0) {
            $tzhour += 24;
            $day = $beforeyesterday;
        } elseif ($tzhour > 23) {
            $tzhour -= 24;
            $day = $today;
        }
        $data[$day . " " . $tzhour . "h"] += $value;
    }
    foreach ($csv as $key => $value) {
        $tzhour = $key + $tz;
        $day = $today;
        if ($tzhour < 0) {
            $tzhour += 24;
            $day = $yesterday;
        } elseif ($tzhour > 23) {
            $tzhour -= 24;
            $day = $tomorrow;
        }
        $data[$day . " " . $tzhour . "h"] += $value;
    }
    //print_r($data);
    return $data;
}
$version = $conf->get_conf("ossim_server_version", FALSE);
$opensource = !preg_match("/pro|demo/i", $version) ? true : false;
if (!isset($_SESSION["_user"])) {
    $ossim_link = $conf->get_conf("ossim_link", FALSE);
    $login_location = $ossim_link . '/session/login.php';
    header("Location: {$login_location}");
    exit;
}
// Solera API
$_SESSION["_solera"] = $conf->get_conf("solera_enable", FALSE) ? true : false;
//
// Get Host names to translate IP -> Host Name
require_once "ossim_db.inc";
$dbo = new ossim_db();
// Multiple Database Server selector
$conn = $dbo->connect();
$database_servers = Databases::get_list($conn);
$dbo->close();
//
if (is_array($_SESSION["server"]) && $_SESSION["server"][0] != "") {
    $dbo->enable_cache();
    $conn = $dbo->custom_connect($_SESSION["server"][0], $_SESSION["server"][2], $_SESSION["server"][3]);
} else {
    $dbo->enable_cache();
    $conn = $dbo->connect();
}
include_once "{$BASE_path}/base_common.php";
$sensors = $hosts = $ossim_servers = array();
$sensors = Av_sensor::get_basic_list($conn, array(), TRUE);
list($hosts, $host_ids) = Asset_host::get_basic_list($conn, array(), TRUE);
$entities = Session::get_all_entities($conn);
示例#27
0
* You should have received a copy of the GNU General Public License
* along with this package; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA  02110-1301  USA
*
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
Session::logcheck('configuration-menu', 'PolicyServers');
$db = new ossim_db();
$conn = $db->connect();
$id = GET('id');
$ip = GET('ip');
$sname = GET('name');
$update = intval(GET('update'));
$opensource = Session::is_pro() ? FALSE : TRUE;
$mssp = intval($conf->get_conf("alienvault_mssp"));
$local_id = $conf->get_conf("server_id");
ossim_valid($ip, OSS_IP_ADDR, OSS_NULLABLE, 'illegal:' . _('Server IP'));
ossim_valid($sname, OSS_ALPHA, OSS_PUNC, OSS_NULLABLE, 'illegal:' . _('Server Name'));
ossim_valid($id, OSS_HEX, OSS_NULLABLE, 'illegal:' . _('Server ID'));
if (ossim_error()) {
    die(ossim_error());
}
$action = 'newserver.php';
$all_rservers = Server::get_server_hierarchy($conn, $id);
function import_assets_from_csv($filename, $iic, $ctx, $import_type)
{
    //Process status
    $summary = array('general' => array('status' => '', 'data' => '', 'statistics' => array('total' => 0, 'warnings' => 0, 'errors' => 0, 'saved' => 0)), 'by_nets' => array());
    $db = new ossim_db();
    $conn = $db->connect();
    $str_data = file_get_contents($filename);
    if ($str_data === FALSE) {
        $summary['general']['status'] = 'error';
        $summary['general']['data']['errors'] = _('Failed to read data from CSV file');
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    $array_data = preg_split('/\\n|\\r/', $str_data);
    foreach ($array_data as $k => $v) {
        if (trim($v) != '') {
            $data[] = explode('";"', trim($v));
        }
    }
    set_time_limit(360);
    /*********************************************************************************************************************
     * From net section:
     *  - Version 4.x.x: "Netname"*;"CIDRs(CIDR1,CIDR2,...)"*;"Description";"Asset value"*;"Net ID"
     *  - Version 3.x.x: "Netname"*;"CIDRs(CIDR1,CIDR2,...)"*;"Description";"Asset value";"Sensors(Sensor1,Sensor2,...)"*
     *
     * From welcome wizard:
     *  - Version 4.x.x: "Netname"*;"CIDRs(CIDR1,CIDR2,...)"*;"Description"   
     *
     *********************************************************************************************************************/
    //Check file size
    if (count($data) <= 0 || count($data) == 1 && preg_match('/Netname/', $data[0][0])) {
        $summary['general']['status'] = 'error';
        $summary['general']['data'] = _('CSV file is empty');
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    //Check importation type and headers
    $csv_headers = array();
    if ($import_type == 'networks') {
        if (preg_match('/Net ID/', $data[0][4]) || preg_match('/Sensors/', $data[0][4])) {
            $csv_headers = array_shift($data);
        } else {
            $summary['general']['status'] = 'error';
            $summary['general']['data'] = _('Headers not found');
            $summary['general']['statistics']['errors'] = 1;
            return $summary;
        }
    }
    //Setting total nets to import
    $summary['general']['statistics']['total'] = count($data);
    //Allowed sensors
    $filters = array('where' => "acl_sensors.entity_id = UNHEX('{$ctx}')");
    $a_sensors = Av_sensor::get_basic_list($conn, $filters);
    $sensor_ids = array_keys($a_sensors);
    if (count($sensor_ids) == 0) {
        $summary['general']['status'] = 'error';
        $s_error_msg = Session::is_pro() ? _('There is no sensor for this context') : _('There is no sensor for this net');
        $summary['general']['data'] = $s_error_msg;
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    Util::disable_perm_triggers($conn, TRUE);
    foreach ($data as $k => $v) {
        //Clean previous errors
        ossim_clean_error();
        $num_line = $k + 1;
        //Set default status
        $summary['by_nets'][$num_line]['status'] = 'error';
        //Check file format
        $cnd_1 = $import_type == 'networks' && count($v) < 5;
        $cnd_2 = $import_type == 'welcome_wizard_nets' && count($v) < 3;
        if ($cnd_1 || $cnd_2) {
            $summary['by_nets'][$num_line]['errors']['Format'] = _('Number of fields is incorrect');
            $summary['general']['statistics']['errors']++;
            continue;
        }
        //Clean values
        $param = array();
        foreach ($v as $field) {
            $parameter = trim($field);
            $pattern = '/^\\"|\\"$|^\'|\'$/';
            $param[] = preg_replace($pattern, '', $parameter);
        }
        //Values
        $is_in_db = FALSE;
        $net_id = '';
        $name = $param[0];
        $cidrs = preg_replace("/[\n\r\t]+/", '', $param[1]);
        $descr = $param[2];
        $asset_value = $param[3] == '' ? 2 : intval($param[3]);
        $sensors = $sensor_ids;
        //Permissions
        $can_i_create_assets = Session::can_i_create_assets();
        $can_i_modify_ips = TRUE;
        //CIDRs
        if (!ossim_valid($cidrs, OSS_IP_CIDR, 'illegal:' . _('CIDR'))) {
            $summary['by_nets'][$num_line]['errors']['CIDRs'] = ossim_get_error_clean();
            $summary['general']['statistics']['errors']++;
            continue;
        }
        //Check Net ID �Is there a net registered in the System?
        $net_ids = Asset_net::get_id_by_ips($conn, $cidrs, $ctx);
        $net_id = key($net_ids);
        if (!empty($net_id)) {
            $is_in_db = TRUE;
        } else {
            $net_id = Util::uuid();
        }
        // Special case: Forced Net ID [Version 4.x.x]
        if ($import_type == 'networks' && preg_match('/Net ID/', $csv_headers[4])) {
            $csv_net_id = strtoupper($param[4]);
            if ($is_in_db == TRUE && $csv_net_id != $net_id) {
                $id_error_msg = _('Net is already registered in the System with another Net ID');
                $summary['by_nets'][$num_line]['errors']['Net'] = $id_error_msg;
                $summary['general']['statistics']['errors']++;
                continue;
            }
        }
        //Netname
        if (!empty($iic)) {
            $name = clean_iic($name);
        }
        if (!ossim_valid($name, OSS_NOECHARS, OSS_NET_NAME, 'illegal:' . _('Netname'))) {
            ossim_clean_error();
            $name = clean_iic($name);
            $name = clean_echars($name);
            $warning_msg = _('Netname has invalid characters') . '<br/>' . _('Netname will be replaced by') . ": <strong>{$name}</strong>";
            $summary['by_nets'][$num_line]['warnings']['Netname'] = $warning_msg;
            $summary['by_nets'][$num_line]['status'] = 'warning';
            $summary['general']['statistics']['warnings']++;
            if (!ossim_valid($name, OSS_NOECHARS, OSS_NET_NAME, 'illegal:' . _('Netname'))) {
                unset($summary['by_nets'][$num_line]['warnings']);
                $summary['general']['statistics']['warnings']--;
                $summary['by_nets'][$num_line]['status'] = 'error';
                $summary['by_nets'][$num_line]['errors']['Netname'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
        }
        //Description
        if (!ossim_valid($descr, OSS_NULLABLE, OSS_AT, OSS_TEXT, '\\t', 'illegal:' . _('Description'))) {
            $summary['by_nets'][$num_line]['errors']['Description'] = ossim_get_error_clean();
            $summary['general']['statistics']['errors']++;
            continue;
        } else {
            if (mb_detect_encoding($descr . ' ', 'UTF-8,ISO-8859-1') == 'UTF-8') {
                $descr = mb_convert_encoding($descr, 'HTML-ENTITIES', 'UTF-8');
            }
        }
        //Sensor
        if ($is_in_db == FALSE) {
            //Only update net sensors with unregistered nets
            if ($import_type == 'networks' && preg_match('/Sensors/', $csv_headers[4])) {
                //Special case: Sensors in CSV file //[Version 3.x.x]
                $sensors = array();
                $_sensors = explode(',', $param[4]);
                if (is_array($_sensors) && !empty($_sensors)) {
                    $_sensors = array_flip($_sensors);
                    if (is_array($a_sensors) && !empty($a_sensors)) {
                        foreach ($a_sensors as $s_id => $s_data) {
                            if (array_key_exists($s_data['ip'], $_sensors)) {
                                $sensors[] = $s_id;
                            }
                        }
                    }
                }
                if (!is_array($sensors) || empty($sensors)) {
                    $s_error_msg = Session::is_pro() ? _('There is no sensors for this context') : _('There is no sensors for this IP');
                    $summary['by_nets'][$num_line]['errors']['Sensors'] = $s_error_msg;
                    $summary['general']['statistics']['errors']++;
                    continue;
                }
            }
        }
        /***********************************************************
         ********** Only for importation from net section **********
         ***********************************************************/
        if ($import_type == 'networks') {
            //Asset
            if (!ossim_valid($asset_value, OSS_DIGIT, 'illegal:' . _('Asset value'))) {
                $summary['by_nets'][$num_line]['errors']['Asset value'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
        }
        //Insert/Update net in database
        if (count($summary['by_nets'][$num_line]['errors']) == 0) {
            try {
                $net = new Asset_net($net_id);
                if ($is_in_db == TRUE) {
                    $net->load_from_db($conn, $net_id);
                    $can_i_modify_ips = Asset_net::can_i_modify_ips($conn, $net_id);
                } else {
                    if ($can_i_create_assets == FALSE) {
                        $n_error_msg = _('Net') . ' ' . $name . ' ' . _("not allowed. You don't have permissions to import this net");
                        $summary['by_nets'][$num_line]['errors']['Net'] = $n_error_msg;
                        $summary['general']['statistics']['errors']++;
                        continue;
                    }
                }
                //Check CIDRs
                if ($can_i_modify_ips == TRUE) {
                    $aux_cidr = explode(',', $cidrs);
                    foreach ($aux_cidr as $cidr) {
                        $net_ids = Asset_net::get_id_by_ips($conn, $cidr, $ctx);
                        unset($net_ids[$net_id]);
                        if (!empty($net_ids)) {
                            $c_error_msg = _('CIDR') . ' ' . $cidrs . ' ' . _("not allowed. CIDR {$cidr} already exists for this entity");
                            $summary['by_nets'][$num_line]['errors']['CIDRs'] = $c_error_msg;
                            $summary['general']['statistics']['errors']++;
                            break;
                        } else {
                            if (Session::get_net_where() != '') {
                                if (!Asset_net::is_cidr_in_my_nets($conn, $cidr, $ctx)) {
                                    $c_error_msg = _('CIDR') . ' ' . $cidrs . ' ' . _("not allowed. CIDR {$cidr} out of range. Check your asset filter");
                                    $summary['by_nets'][$num_line]['errors']['CIDRs'] = $c_error_msg;
                                    $summary['general']['statistics']['errors']++;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    $c_error_msg = _('Net') . ' ' . $name . ': ' . _("CIDRs not allowed. CIDRs wasn't be modified");
                    $summary['by_nets'][$num_line]['status'] = 'warning';
                    $summary['general']['warnings']['errors']++;
                    $summary['by_nets'][$num_line]['warnings']['CIDRs'] = $c_error_msg;
                }
                //Setting new values
                if (count($summary['by_nets'][$num_line]['errors']) == 0) {
                    $net->set_ctx($ctx);
                    $net->set_name($name);
                    $net->set_descr($descr);
                    if ($is_in_db == FALSE) {
                        if ($can_i_modify_ips == TRUE) {
                            $net->set_ips($cidrs);
                        }
                        $net->set_sensors($sensors);
                    }
                    $net->set_asset_value($asset_value);
                    $net->save_in_db($conn, FALSE);
                    $summary['general']['statistics']['saved']++;
                    $summary['by_nets'][$num_line]['data'] = $is_in_db == TRUE ? _('Net updated') : _('New new inserted');
                    //Keep warnings
                    if ($summary['by_nets'][$num_line]['status'] != 'warning') {
                        $summary['by_nets'][$num_line]['status'] = 'success';
                    }
                }
            } catch (Exception $e) {
                $summary['by_nets'][$num_line]['errors']['Database error'] = $e->getMessage();
                $summary['general']['statistics']['errors']++;
            }
        }
    }
    if ($summary['general']['statistics']['saved'] > 0) {
        if ($summary['general']['statistics']['errors'] == 0) {
            $summary['general']['status'] = 'success';
            $summary['general']['data'] = _('All nets have been imported successfully');
        } else {
            $summary['general']['status'] = 'warning';
            $summary['general']['data'] = _('Some nets could not be imported successfully');
        }
        Util::disable_perm_triggers($conn, FALSE);
        try {
            Asset_net::report_changes($conn, 'nets');
        } catch (Exception $e) {
            error_log($e->getMessage(), 0);
        }
    } else {
        $summary['general']['statistics']['errors'] = count($data);
        //CSV file is not empty, but all lines are wrong
        if (empty($summary['general']['status'])) {
            $summary['general']['status'] = 'error';
            $summary['general']['data'] = _('Nets could not be imported');
        }
    }
    $db->close();
    return $summary;
}
示例#29
0
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
Session::logcheck("analysis-menu", "ControlPanelAlarms");
$vars = $_SESSION['_kdb_alarm_vars'];
$plugin_id = $_SESSION['_kdb_alarm_pid'];
$plugin_sid = $_SESSION['_kdb_alarm_psid'];
$docs = 0;
if ($plugin_id != '' && $plugin_sid != '') {
    $db_kdb = new ossim_db();
    $conn_kdb = $db_kdb->connect();
    //Taxonomy
    $ptype = Product_type::get_product_type_by_plugin($conn_kdb, $plugin_id);
    $cat = Category::get_category_subcategory_by_plugin($conn_kdb, $plugin_id, $plugin_sid);
    $keyname = (empty($ptype['id']) ? 0 : $ptype['id']) . "##" . (empty($cat['cid']) ? 0 : $cat['cid']) . "##" . (empty($cat['scid']) ? 0 : $cat['scid']);
    $repository_list['taxonomy'] = Repository::get_repository_linked($conn_kdb, $keyname, 'taxonomy');
    //Directive
    if ($plugin_id == '1505') {
        $repository_list['directive'] = Repository::get_linked_by_directive($conn_kdb, $plugin_sid);
    }
    //Plugin SID
    $keyname = "{$plugin_sid}##{$plugin_id}";
    $repository_list['plugin_sid'] = Repository::get_repository_linked($conn_kdb, $keyname, 'plugin_sid');
    $docs = count($repository_list['directive']) + count($repository_list['plugin_sid']) + count($repository_list['taxonomy']);
    $db_kdb->close($conn_kdb);
}
示例#30
-2
function submit_scan($SVRid, $job_name, $ssh_credential, $smb_credential, $schedule_type, $not_resolve, $user, $entity, $targets, $scheduled_status, $hosts_alive, $sid, $send_email, $timeout, $scan_locally, $dayofweek, $dayofmonth, $ROYEAR, $ROMONTH, $ROday, $time_hour, $time_min, $time_interval, $sched_id, $biyear, $bimonth, $biday, $nthweekday, $tz, $daysMap)
{
    $db = new ossim_db();
    $dbconn = $db->connect();
    $credentials = $ssh_credential . '|' . $smb_credential;
    $username = valid_hex32($entity) ? $entity : $user;
    if (empty($username)) {
        $username = Session::get_session_user();
    }
    $btime_hour = $time_hour;
    // save local time
    $btime_min = $time_min;
    $bbiyear = $biyear;
    $bbimonth = $bimonth;
    $bbiday = $biday;
    if ($schedule_type == 'O') {
        // date and time for run once
        if (empty($ROYEAR)) {
            $ROYEAR = gmdate('Y');
        }
        if (empty($ROMONTH)) {
            $ROMONTH = gmdate('m');
        }
        if (empty($ROday)) {
            $ROday = gmdate('d');
        }
        list($_y, $_m, $_d, $_h, $_u, $_s, $_time) = Util::get_utc_from_date($dbconn, "{$ROYEAR}-{$ROMONTH}-{$ROday} {$time_hour}:{$time_min}:00", $tz);
        $ROYEAR = $_y;
        $ROMONTH = $_m;
        $ROday = $_d;
        $time_hour = $_h;
        $time_min = $_u;
    } else {
        if (in_array($schedule_type, array('D', 'W', 'M', 'NW'))) {
            // date and time for Daily, Day of Week, Day of month, Nth weekday of month
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, "{$biyear}-{$bimonth}-{$biday} {$time_hour}:{$time_min}:00", $tz);
            $biyear = $b_y;
            $bimonth = $b_m;
            $biday = $b_d;
            $time_hour = $b_h;
            $time_min = $b_u;
        }
    }
    $resolve_names = $not_resolve == '1' ? 0 : 1;
    if ($schedule_type != 'N') {
        // current datetime in UTC
        $arrTime = explode(":", gmdate('Y:m:d:w:H:i:s'));
        $year = $arrTime[0];
        $mon = $arrTime[1];
        $mday = $arrTime[2];
        $wday = $arrTime[3];
        $hour = $arrTime[4];
        $min = $arrTime[5];
        $sec = $arrTime[6];
        $timenow = $hour . $min . $sec;
        $run_wday = $daysMap[$dayofweek]['number'];
        $run_time = sprintf('%02d%02d%02d', $time_hour, $time_min, '00');
        $run_mday = $dayofmonth;
        $time_value = "{$time_hour}:{$time_min}:00";
        $ndays = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        $begin_in_seconds = Util::get_utc_unixtime("{$biyear}-{$bimonth}-{$biday} {$time_hour}:{$time_min}:00") - 3600 * $tz;
        $current_in_seconds = gmdate('U');
        // current datetime in UTC
        if (strlen($bimonth) == 1) {
            $bimonth = '0' . $bimonth;
        }
        if (strlen($biday) == 1) {
            $biday = '0' . $biday;
        }
    }
    switch ($schedule_type) {
        case 'N':
            $requested_run = gmdate('YmdHis');
            break;
        case 'O':
            $requested_run = sprintf('%04d%02d%02d%06d', $ROYEAR, $ROMONTH, $ROday, $run_time);
            break;
        case 'D':
            if ($begin_in_seconds > $current_in_seconds) {
                $next_day = $biyear . $bimonth . $biday;
                // selected date by user
            } else {
                if ($run_time > $timenow) {
                    $next_day = $year . $mon . $mday;
                    // today
                } else {
                    $next_day = gmdate("Ymd", strtotime("+1 day GMT", gmdate("U")));
                    // next day
                }
            }
            $requested_run = sprintf("%08d%06d", $next_day, $run_time);
            break;
        case 'W':
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                $wday = date("w", mktime(0, 0, 0, $bimonth, $biday, $biyear));
                // make week day for begin day
                if ($run_wday == $wday) {
                    $next_day = $biyear . $bimonth . $biday;
                    // selected date by user
                } else {
                    $next_day = gmdate("Ymd", strtotime("next " . $ndays[$run_wday] . " GMT", mktime(0, 0, 0, $bimonth, $biday, $biyear)));
                }
            } else {
                if ($run_wday == $wday && $run_time > $timenow) {
                    $next_day = $year . $mon . $mday;
                    // today
                } else {
                    $next_day = gmdate("Ymd", strtotime("next " . $ndays[$run_wday] . " GMT", gmdate("U")));
                    // next week
                }
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})/", $next_day, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " {$btime_hour}:{$btime_min}:00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            break;
        case 'M':
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                if ($run_mday >= $biday) {
                    $next_day = $biyear . $bimonth . ($run_mday < 10 ? "0" : "") . $run_mday;
                    // this month
                } else {
                    $next_day = sprintf("%06d%02d", gmdate("Ym", strtotime("next month GMT", mktime(0, 0, 0, $bimonth, $biday, $biyear))), $run_mday);
                }
            } else {
                if ($run_mday > $mday || $run_mday == $mday && $run_time > $timenow) {
                    $next_day = $year . $mon . ($run_mday < 10 ? "0" : "") . $run_mday;
                    // this month
                } else {
                    $next_day = sprintf("%06d%02d", gmdate("Ym", strtotime("next month GMT", gmdate("U"))), $run_mday);
                }
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})/", $next_day, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " {$btime_hour}:{$btime_min}:00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            break;
        case 'NW':
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                $array_time = array('month' => $bbimonth, 'day' => $bbiday, 'year' => $bbiyear);
                $requested_run = weekday_month(strtolower($daysMap[$dayofweek]['text']), $nthweekday, $btime_hour, $btime_min, $array_time);
            } else {
                $requested_run = weekday_month(strtolower($daysMap[$dayofweek]['text']), $nthweekday, $btime_hour, $btime_min);
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/", $requested_run, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " " . $found[4] . ":" . $found[5] . ":00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            $dayofmonth = $nthweekday;
            break;
        default:
            break;
    }
    $insert_time = gmdate('YmdHis');
    if (!empty($_SESSION['_vuln_targets']) && count($_SESSION['_vuln_targets']) > 0) {
        $sgr = array();
        foreach ($_SESSION['_vuln_targets'] as $target_selected => $server_id) {
            $sgr[$server_id][] = $target_selected;
        }
        ossim_clean_error();
        unset($_SESSION['_vuln_targets']);
        // clean scan targets
        $resolve_names = $not_resolve == '1' ? 0 : 1;
        $queries = array();
        $bbimonth = strlen($bbimonth) == 1 ? '0' . $bbimonth : $bbimonth;
        $bbiday = strlen($bbiday) == 1 ? '0' . $bbiday : $bbiday;
        $qc = 0;
        if ($schedule_type == 'N') {
            foreach ($sgr as $notify_sensor => $target_list) {
                $target_list = implode("\n", $target_list);
                $params = array($job_name, $username, Session::get_session_user(), $schedule_type, $target_list, $hosts_alive, $sid, $send_email, $timeout, $SVRid, $insert_time, $requested_run, '3', 'S', $notify_sensor, $scan_locally, '', $resolve_names, $credentials);
                $queries[$qc]['query'] = 'INSERT INTO vuln_jobs ( name, username, fk_name, meth_SCHED, meth_TARGET,  meth_CRED,
                    meth_VSET, meth_Wfile, meth_TIMEOUT, scan_ASSIGNED,
                    scan_SUBMIT, scan_next, scan_PRIORITY, status, notify, authorized, author_uname, resolve_names, credentials )
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
                $queries[$qc]['params'] = $params;
                $qc++;
            }
        } else {
            $params = array($bbiyear . $bbimonth . $bbiday, $job_name, $username, Session::get_session_user(), $schedule_type, $dayofweek, $dayofmonth, $time_value, implode("\n", $targets), $hosts_alive, $sid, $send_email, $scan_locally, $timeout, $requested_run, $insert_time, strval($scheduled_status), $resolve_names, $time_interval, '', $credentials, $SVRid);
            $queries[$qc]['query'] = 'INSERT INTO vuln_job_schedule ( begin, name, username, fk_name, schedule_type, day_of_week, day_of_month, time, meth_TARGET, meth_CRED, meth_VSET, meth_Wfile,  meth_Ucheck, meth_TIMEOUT, next_CHECK, createdate, enabled, resolve_names, time_interval, IP_ctx, credentials, email)
                                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ';
            $queries[$qc]['params'] = $params;
            $qc++;
        }
        $execute_errors = array();
        foreach ($queries as $id => $sql_data) {
            $rs = $dbconn->execute($sql_data['query'], $sql_data['params']);
            if ($rs === FALSE) {
                $execute_errors[] = $dbconn->ErrorMsg();
            }
        }
        if (empty($execute_errors) && $schedule_type != 'N') {
            // We have to update the vuln_job_assets
            if (intval($sched_id) == 0) {
                $query = ossim_query('SELECT LAST_INSERT_ID() as sched_id');
                $rs = $dbconn->Execute($query);
                if (!$rs) {
                    Av_exception::throw_error(Av_exception::DB_ERROR, $dbconn->ErrorMsg());
                } else {
                    $sched_id = $rs->fields['sched_id'];
                }
            }
            Vulnerabilities::update_vuln_job_assets($dbconn, 'insert', $sched_id, 0);
        }
        $config_nt = array('content' => '', 'options' => array('type' => 'nf_success', 'cancel_button' => FALSE), 'style' => 'width: 40%; margin: 20px auto; text-align: center;');
        $config_nt['content'] = empty($execute_errors) ? _('Successfully Submitted Job') : _('Error creating scan job:') . implode('<br>', $execute_errors);
        $nt = new Notification('nt_1', $config_nt);
        $nt->show();
        $dbconn->close();
    }
}