Пример #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
 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 check_phpgacl_install()
{
    global $gacl;
    $db_table_prefix = $gacl->_db_table_prefix;
    require_once "ossim_db.inc";
    $db = new ossim_db();
    if (!($conn = $db->phpgacl_connect())) {
        echo "<p align=\"center\">\n                <b>Can't connect to OSSIM acl database (phpgacl)</b><br/>\n                Check for phpgacl values at framework configuration\n                </p>";
        exit;
    }
    $query1 = OssimQuery("SELECT * FROM acl");
    $query2 = OssimQuery("SELECT * FROM " . $db_table_prefix . "_acl");
    if (!$conn->Execute($query1) and !$conn->Execute($query2)) {
        echo "\n        <p align=\"center\"><b>You need to configure phpGACL</b><br/>\n        Remember to setup the database connection at phpGACL config files!\n        <br/>\n        Click <a href=\"/phpgacl/setup.php\">here</a> to enter setup\n        </p>\n            ";
        exit;
    }
    $db->close($conn);
}
Пример #4
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;
}
Пример #5
0
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;
}
Пример #6
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;
}
Пример #7
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";
        }
    }
}
Пример #8
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");
Пример #9
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';
    }
}
Пример #10
0
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
require_once 'av_init.php';
Session::logcheck("analysis-menu", "EventsForensics");
$search = trim(GET('q'));
$max = intval(GET('limit'));
if (!$max) {
    $max = 50;
}
ossim_valid($search, OSS_NULLABLE, OSS_NOECHARS, OSS_ALPHA, OSS_SCORE, OSS_PUNC, 'illegal:' . _("search"));
if (ossim_error()) {
    die;
}
$db = new ossim_db(TRUE);
if (is_array($_SESSION['server']) && $_SESSION['server'][0] != '') {
    $conn = $db->custom_connect($_SESSION["server"][0], $_SESSION["server"][2], $_SESSION["server"][3]);
} else {
    $conn = $db->connect();
}
$params = array();
$filter = '';
if (!empty($search)) {
    $filter = 'WHERE INET6_NTOA(device_ip) LIKE CONCAT("%",?,"%")';
    $params[] = $search;
}
$query = "SELECT DISTINCT INET6_NTOA(device_ip) as ip FROM alienvault_siem.device {$filter}";
$rs = $conn->Execute($query, $params);
if ($rs) {
    while (!$rs->EOF) {
Пример #11
0
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;
}
Пример #12
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
Пример #13
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 
}
Пример #14
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);
Пример #15
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;
}
Пример #16
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);
    }
}
Пример #17
0
/*                                                         */
/* This program is intended for use in an authorized       */
/* manner only, and the author can not be held liable for  */
/* anything done with this program, code, or items         */
/* discovered with this program's use.                     */
/***********************************************************/
require_once 'av_init.php';
require_once 'functions.inc';
require_once 'config.php';
require_once 'ossim_sql.inc';
Session::logcheck("environment-menu", "EventsVulnerabilities");
$conf = $GLOBALS["CONF"];
$version = $conf->get_conf("ossim_server_version");
$nessus_path = $conf->get_conf("nessus_path");
$pro = Session::is_pro();
$db = new ossim_db();
$dbconn = $db->connect();
$dbconn->SetFetchMode(ADODB_FETCH_BOTH);
$getParams = array("disp", "item", "page", "delete", "prefs", "uid", "sid", "op", "confirm", "preenable", "bEnable");
$postParams = array("disp", "saveplugins", "page", "delete", "prefs", "uid", "sid", "op", "sname", "sdescription", "sautoenable", "item", "AllPlugins", "NonDoS", "DisableAll", "submit", "fam", "cloneid", "stype", "importplugins", "tracker", "preenable", "bEnable", "user", "entity");
switch ($_SERVER['REQUEST_METHOD']) {
    case "GET":
        foreach ($getParams as $gp) {
            if (isset($_GET[$gp])) {
                ${$gp} = Util::htmlentities(escape_sql(trim(GET($gp)), $dbconn), ENT_QUOTES);
            } else {
                ${$gp} = "";
            }
        }
        $submit = "";
        $AllPlugins = "";
Пример #18
0
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
Session::logcheck("environment-menu", "ReportsWireless");
require_once 'Wireless.inc';
$order = GET('order');
$si = intval(GET('index'));
$sensors = isset($_SESSION['sensors'][$si]) ? $_SESSION['sensors'][$si] : "";
ossim_valid($order, OSS_ALPHA, OSS_NULLABLE, 'illegal: order');
ossim_valid($sensors, OSS_ALPHA, OSS_PUNC, 'illegal: sensors');
if (ossim_error()) {
    die(ossim_error());
}
$db = new ossim_db();
$conn = $db->snort_connect();
?>
<table class="table_data" id="results">
	<thead>
        <tr>
            <th style='width:250px;'><?php 
echo _("Signature");
?>
</th>
            <th><?php 
echo _("Total #");
?>
</th>
            <th><?php 
echo _("Wireless IDS<br/>Sensor");
Пример #19
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);
    ?>
);
Пример #21
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();
    }
}
Пример #22
0
    require_once "ossim_conf.inc";
    $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');
}
Пример #23
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;
}
Пример #24
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;
}
Пример #25
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 "]";
}
Пример #26
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';
Пример #27
0
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
/*******************************************************************************/
/*                                                                             */
/* This script is called from nfsen packages to translate sensors uuid to name */
/*                                                                             */
/*******************************************************************************/
set_include_path('/usr/share/ossim/include');
error_reporting(0);
ini_set("display_errors", "0");
//This is used to avoid an error when there is not connection to mysql
if (!isset($GLOBALS["CONF"])) {
    $GLOBALS["CONF"] = array();
    require_once 'ossim_db.inc';
    $db = new ossim_db();
    unset($GLOBALS["CONF"]);
} else {
    require_once 'ossim_db.inc';
    $db = new ossim_db();
}
$uuid = $argv[1];
if (@$db->test_connect()) {
    $conn = $db->connect();
    $name = Av_sensor::get_nfsen_channel_name($conn, $uuid);
    $db->close();
} else {
    $name = empty($uuid) ? 'Unknown' : $uuid;
}
echo $name;
Пример #28
0
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
* 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';
require_once 'ossim_db.inc';
require_once 'general.php';
Session::logcheck("analysis-menu", "EventsForensics");
$it_security = "";
$address = "";
$tlfn = "";
$tz = Util::get_timezone();
$date = gmdate("Y-m-d H:i:s", gmdate("U") + 3600 * $tz);
$maintitle = $report_data['report_name'];
$db = new ossim_db();
$conn = $db->connect();
$t_params = array();
$t_params[] = $user;
$t_query = "SELECT dataV1, dataV2 \r\n\t\t  FROM datawarehouse.report_data \r\n\t\t  WHERE id_report_data_type=35 and user=?";
$conn->SetFetchMode(ADODB_FETCH_ASSOC);
$t_rs = $conn->Execute($t_query, $t_params);
if (!$t_rs) {
    $filter = '';
} else {
    $filter = '
	<table class="w100" cellspacing="0" cellpadding="0">
		<tr>
			<td style="text-align:left;width:40mm;font-size:10px;color:#535353;" valign="top">' . "Current Report Criteria:" . '</td>
		</tr>
		<tr>
Пример #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();
    }
}