$nt->show();
     Util::make_form("POST", "newsensorform.php?id={$sensor_id}&ip={$ip}&sname={$sname}");
     exit;
 }
 $db = new ossim_db();
 $conn = $db->connect();
 $newcontext = POST('newcontext') != '' ? POST('newcontext') : $sname;
 if (POST('isolated') == 1 && $newcontext != '') {
     // Isolated sensor. Creating a new context first
     $new_context_uuid = Session::clone_default_ctx($conn, $newcontext);
     $entities = array($new_context_uuid);
     // Refresh current permissions
     $_SESSION['_user_vision'] = Acl::get_user_vision($conn);
 } elseif (POST('isolated') == 0 && preg_match("/[a-f\\d]{32}/i", POST('neighborsensor'))) {
     // Use selected sensor context
     $entities = array_keys(Av_sensor::get_ctx_by_id($conn, POST('neighborsensor')));
 }
 try {
     $old = new Av_Sensor($sensor_id);
     $old->load_from_db($conn);
     $cproperties = $old->get_properties();
     $new = new Av_Sensor($sensor_id);
     $new->set_properties($cproperties);
     $new->set_name($sname);
     $new->set_ip($ip);
     $new->set_priority($priority);
     $new->set_port($port);
     $new->set_tzone($tzone);
     $new->set_descr($descr);
     $new->set_rpass($rpass);
     foreach ($entities as $ctx) {
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
Session::logcheck('configuration-menu', 'PolicySensors');
$sensor_id = POST('sensor_id');
$nagios_user = POST('user');
$nagios_pass = POST('pass');
ossim_valid($sensor_id, OSS_HEX, 'illegal:' . _('Sensor ID'));
ossim_valid($nagios_user, OSS_ALPHA, OSS_PUNC, OSS_SPACE, OSS_NULLABLE, 'illegal:' . _('Nagios User'));
ossim_valid($nagios_pass, OSS_PASSWORD, OSS_NULLABLE, 'illegal:' . _('Nagios Password'));
if (ossim_error()) {
    die(ossim_error());
}
$db = new ossim_db();
$conn = $db->connect();
$sensor = Av_sensor::get_object($conn, $sensor_id);
if (Util::is_fake_pass($nagios_pass)) {
    $nagios_options = $sensor->get_nagios_credentials($conn);
    $nagios_pass = $nagios_options['password'];
}
try {
    $url = $sensor->get_nagios_url($nagios_user, $nagios_pass);
    if ($url != '') {
        echo "<img src='../pixmaps/tick.png'/>";
    }
} catch (Exception $e) {
    echo preg_replace("/\\:.*/", '', $e->getMessage());
}
$db->close();
Beispiel #3
0
 // load the default values for the form
 if ($action == 'create_scan') {
     $conf = $GLOBALS['CONF'];
     $scan_locally = $conf->get_conf('nessus_pre_scan_locally');
     $timeout = 28800;
     $hosts_alive = 1;
 }
 $hosts_alive_data = get_host_alive_attributes($hosts_alive, $targets);
 $scan_locally_checked = $scan_locally == 1 ? 'checked="checked"' : '';
 $resolve_names_checked = $not_resolve == 1 ? 'checked="checked"' : '';
 $email_notification = array();
 $email_notification['no'] = $send_email == 0 ? 'checked="checked"' : '';
 $email_notification['yes'] = $send_email == 1 ? 'checked="checked"' : '';
 // load sensors
 $filters = array('where' => 'sensor_properties.has_vuln_scanner = 1');
 list($all_sensors, $s_total) = Av_sensor::get_list($conn);
 foreach ($all_sensors as $_sensor_id => $sensor_data) {
     $all_sensors[$_sensor_id]['selected'] = $_sensor_id == $SVRid ? 'selected="selected"' : '';
 }
 // load profiles
 $args = '';
 if (!Session::am_i_admin()) {
     list($owners, $sqlowners) = Vulnerabilities::get_users_and_entities_filter($conn);
     $owners[] = '0';
     $sql_perms .= " OR owner IN('" . implode("', '", $owners) . "')";
     $args = "WHERE name='Default' OR name='Deep' OR name='Ultimate' " . $sql_perms;
 }
 $query = "SELECT id, name, description, owner, type FROM vuln_nessus_settings {$args} ORDER BY name";
 $conn->SetFetchMode(ADODB_FETCH_BOTH);
 $result = $conn->execute($query);
 while (!$result->EOF) {
Beispiel #4
0
?>
 ...</span>
	</div>
</div>



<?php 
ob_flush();
$conf = $GLOBALS['CONF'];
$acid_link = $conf->get_conf('acid_link');
$acid_prefix = $conf->get_conf('event_viewer');
$acid_main_link = str_replace('//', '/', $conf->get_conf('acid_link') . '/' . $acid_prefix . "_qry_main.php?clear_allcriteria=1&search=1&bsf=Query+DB&ossim_risk_a=+");
$db_sensor_list = array();
$list_no_active = array();
$aux_sensor_list = Av_sensor::get_basic_list($conn);
if (is_array($aux_sensor_list)) {
    foreach ($aux_sensor_list as $aux_s_data) {
        $db_sensor_list[] = $aux_s_data['ip'];
        $db_sensor_rel[$aux_s_data['ip']] = $aux_s_data['name'];
        $list_no_active[$aux_s_data['ip']] = $aux_s_data['name'];
    }
}
list($sensor_list, $err) = server_get_sensors();
if ($err != '') {
    $info_error[] = $err;
}
if (!$sensor_list && empty($ip_get)) {
    $info_error[] = _("There aren't any sensors connected to OSSIM server");
}
$ossim_conf = $GLOBALS['CONF'];
function get_notifications($conn)
{
    $notifications = array();
    if (Session::menu_perms('configuration-menu', 'PolicySensors')) {
        $new_sensors = Av_sensor::get_unregistered($conn);
        if (count($new_sensors) > 0) {
            $notif['msg'] = count($new_sensors) > 1 ? _('New Sensors Detected') : _('New Sensor Detected');
            $notif['class'] = 'nl_sensors';
            $notifications[$notif['class']] = $notif;
        }
    }
    if (Session::am_i_admin()) {
        $trial_days = calc_days_to_expire();
        if ($trial_days !== FALSE) {
            $notif['msg'] = $trial_days == 0 ? _('Trial Version expired') : $trial_days . ' ' . _('Days Left of Free Trial');
            $notif['class'] = 'nl_trial';
            $notifications[$notif['class']] = $notif;
        }
        $new_updates = get_only_updates();
        if ($new_updates == TRUE) {
            $notif['msg'] = _('New Updates Available');
            $notif['class'] = 'nl_updates';
            $notifications[$notif['class']] = $notif;
        }
        $unread = get_status_messages();
        if ($unread) {
            $notif['msg'] = _('New Warnings & Errors');
            $notif['class'] = 'nl_messages';
            $notifications[$notif['class']] = $notif;
        }
        $otx = calc_otx_notif();
        if ($otx === TRUE) {
            $notif['msg'] = _('Contribute to AlienVault OTX');
            $notif['class'] = 'nl_otx';
            $notifications[$notif['class']] = $notif;
        }
        $devices = calc_devices_total($conn);
        $max_dev = intval($_SESSION["_max_devices"]);
        //This val is loaded when the users log in. (session.inc)
        if ($max_dev > 0 && $devices > $max_dev) {
            $over = $devices - $max_dev;
            $notif['msg'] = _("License Violation - {$over} Assets Over");
            $notif['class'] = 'nl_device_exceed';
            $notifications[$notif['class']] = $notif;
        }
    }
    $return['error'] = FALSE;
    $return['output'] = $notifications;
    return $return;
}
    $res = $conn->query("SELECT id,name,value FROM acl_perm WHERE type='MENU'");
    while ($rw = $res->fetchRow()) {
        $ret[$rw['name']][$rw['value']] = $rw['id'];
    }
    return $ret;
}
ini_set("include_path", ".:/usr/share/ossim/include:/usr/share/phpgacl");
$force_gacl = true;
require_once 'av_init.php';
$gacl = $GLOBALS['ACL'];
/* connect to db */
$db = new ossim_db();
$conn = $db->connect();
try {
    $net_list = Asset_net::get_all($conn);
    $sensor_list = Av_sensor::get_all($conn);
} catch (Exception $e) {
    print $e->getMessage();
    exit;
}
$permids = get_permids($conn);
$users = Session::get_list($conn);
foreach ($users as $user) {
    $nets = "";
    $sensors = "";
    $perms = array();
    $login = $user->get_login();
    if ($user->get_is_admin() || $login == ACL_DEFAULT_OSSIM_ADMIN) {
        continue;
    }
    // Skip admin user
*
* 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;
                 ossim_valid($destination, OSS_IP_CIDR, 'illegal:' . _('Destination cidr'));
                 $destination_type = 'net';
             }
         }
         if (ossim_error()) {
             $info_error[] = ossim_get_error();
             ossim_clean_error();
         } else {
             $tdestinations[] = $destination;
         }
     }
 } else {
     $tdestinations = array();
 }
 // Launch scan
 $info_sensor = $sensors_status[Av_sensor::get_name_by_ip($dbconn, $sensor_ip)];
 if ($sensor_ip != '' && $sensor_interface != '' && intval($timeout) > 0 && count($info_error) == 0 && ($info_sensor[0] == 0 || $info_sensor[0] == -1)) {
     $rlaunch_scan = $scan->launch_scan($tsources, $tdestinations, $sensor_ip, $sensor_interface, $timeout, $cap_size, $raw_filter);
     if ($rlaunch_scan["status"] === true) {
         $content = _('Launching capture... wait a few seconds');
         $type = 'nf_success';
     } else {
         $content = $rlaunch_scan['message'];
         $type = 'nf_warning';
     }
     $jtimeout = 4000;
 } else {
     if ($info_sensor[0] != -1 && ($info_sensor[0] == 1 || $info_sensor[0] == 2)) {
         $content = _('The sensor is busy');
         $type = 'nf_warning';
     }
     if ($taxonomy_list = $policy->get_taxonomy_conditions($conn)) {
         foreach ($taxonomy_list as $tax) {
             $tax_id = $tax->get_product_type_id() . "@" . $tax->get_category_id() . "@" . $tax->get_subcategory_id();
             $tax_val = $filter['ptype'][$tax->get_product_type_id()] . " | " . $filter['cat'][$tax->get_category_id()] . " | " . $filter['subcat'][$tax->get_subcategory_id()];
             $tax_filters[$tax_id] = $tax_val;
             $flag_events = false;
         }
     }
 }
 //SENSOR
 $sensor_exist = $policy->exist_sensors($conn);
 if ($sensor_list = $policy->get_sensors($conn)) {
     foreach ($sensor_list as $sensor) {
         if (!check_any($sensor->get_sensor_id())) {
             if ($sensor_exist[$sensor->get_sensor_id()] != 'false') {
                 $sensors['sensor_' . $sensor->get_sensor_id()] = Av_sensor::get_name_by_id($conn, $sensor->get_sensor_id());
                 $flag_sensors = false;
             }
         } else {
             $sensors[$sensor->get_sensor_id()] = _('ANY');
         }
     }
 }
 //Time Filters
 $policy_time = $policy->get_time($conn);
 $time_begin[0] = $policy_time->get_month_start();
 $time_begin[1] = $policy_time->get_month_day_start();
 $time_begin[2] = $policy_time->get_week_day_start();
 $time_begin[3] = $policy_time->get_hour_start();
 $time_begin[4] = $policy_time->get_minute_start();
 $time_end[0] = $policy_time->get_month_end();
Beispiel #10
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;
}
Beispiel #11
0
function schedule_scan($conn, $wizard, $data)
{
    $step = intval($wizard->get_step_data('scan_step'));
    $nets = $wizard->get_step_data('scan_nets');
    if ($step != 3 || count($nets) < 1) {
        $response['error'] = TRUE;
        $response['msg'] = _('Asset Scan not valid to schedule');
        return $response;
    }
    $sched = $data['sch_opt'];
    ossim_valid($sched, OSS_DIGIT, 'illegal:' . _("Schedule Option"));
    if (ossim_error()) {
        $response['error'] = TRUE;
        $response['msg'] = ossim_get_error();
        ossim_clean_error();
        $wizard->set_step_data('scan_nets', -1);
        return $response;
    }
    if ($sched == 1) {
        $period = 86400;
    } elseif ($sched == 2) {
        $period = 604800;
    } else {
        $period = 2419200;
    }
    $sensor_id = Av_sensor::get_default_sensor($conn);
    $name = _('Default_wizard_scan');
    $type = 5;
    $targets = array();
    foreach ($nets as $cidrs) {
        $cidrs = explode(' ', $cidrs);
        foreach ($cidrs as $cidr) {
            $targets[$cidr] = $cidr;
        }
    }
    $targets = implode(' ', $targets);
    $params = $targets . '#-T3 -A -sS -F';
    Inventory::insert($conn, $sensor_id, $name, $type, $period, $params, $targets);
    $response['error'] = FALSE;
    $response['data'] = array();
    return $response;
}
Beispiel #12
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', 'PolicyHosts');
session_write_close();
/****************************************************
 ********************* Tooltips *********************
 ****************************************************/
$t_location = '<div>' . _("You can type any location (address, country, city, ...)") . '</div>';
//Database connection
$db = new ossim_db();
$conn = $db->connect();
//Getting all sensors
$filters = array('order_by' => "priority DESC");
list($all_sensors, $s_total) = Av_sensor::get_list($conn, $filters, FALSE, TRUE);
//Common Context
$ctx = Asset_host::get_common_ctx($conn);
//Closing database connection
$db->close();
?>

<div id="bk_tg_container">

    <div id='tg_av_info'></div>

    <div class="legend">
        <?php 
echo _('Only filled values will be updated');
?>
    </div>
$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);
$rep_activities = Reputation::get_reputation_activities($conn, "ORDER BY descr", $db_memcache);
$rep_severities = array("ANY", "High", "Medium", "Low");
//
// added default home host/lan to SESSION[ip_addr]
//
if ($_GET["addhomeips"] == "src" || $_GET["addhomeips"] == "dst") {
    $_nets = Asset_net::get_all($conn, TRUE);
    // adding all not external lans
    $local_ips = array();
    $total_ips = 0;
    foreach ($_nets as $current_net) {
        $cirds = explode(",", $current_net['ips']);
        foreach ($cirds as $cidr) {
Beispiel #14
0
function sensor_list($conn, $page, $search)
{
    $filters = array();
    $filters['limit'] = get_query_limits($page);
    if ($search != '') {
        $search = utf8_decode($search);
        $search = escape_sql($search, $conn);
        $filters['where'] = " name LIKE '%{$search}%' OR inet6_ntoa(ip) LIKE '%{$search}%'";
    }
    $filters['order_by'] = 'name ASC';
    try {
        list($sensors, $total) = Av_sensor::get_list($conn, $filters, TRUE, TRUE);
    } catch (Exception $e) {
        $return['error'] = TRUE;
        $return['msg'] = $e->getMessage();
        return $return;
    }
    //If we have at least one element...
    if ($total > 0) {
        //Getting the nets already selected in the filter.
        $selected = get_selected_values(14);
    }
    $list = array();
    //Going through the list to format the elements properly:
    foreach ($sensors as $id => $sensor) {
        $_chk = $selected[$id] != '' ? TRUE : FALSE;
        $_sensor = array('id' => $id, 'name' => $sensor['name'], 'extra' => $sensor['ip'], 'checked' => $_chk);
        $list[$id] = $_sensor;
    }
    $data['total'] = intval($total);
    $data['list'] = $list;
    $return['error'] = FALSE;
    $return['data'] = $data;
    return $return;
}
Beispiel #15
0
    //Validating icon format and size
    $icon = '';
    if (is_uploaded_file($_FILES['icon']['tmp_name'])) {
        $icon = file_get_contents($_FILES['icon']['tmp_name']);
    }
    if ($icon != '') {
        $image = @imagecreatefromstring($icon);
        if (!$image || imagesx($image) > 400 || imagesy($image) > 400) {
            $validation_errors['icon'] = _('Image format is not allowed');
        }
    }
    //Validating Sensors
    if (is_array($sensors) && !empty($sensors)) {
        foreach ($sensors as $sensor) {
            if (!Av_sensor::is_allowed($conn, $sensor)) {
                $validation_errors['sboxs[]'] .= sprintf(_("Error! Sensor %s cannot be assigned to this asset"), Av_sensor::get_name_by_id($conn, $sensor)) . "<br/>";
            }
        }
    }
    $db->close();
}
$data['status'] = 'OK';
$data['data'] = $validation_errors;
if (POST('ajax_validation_all') == TRUE) {
    if (is_array($validation_errors) && !empty($validation_errors)) {
        $data['status'] = 'error';
    }
    echo json_encode($data);
    exit;
} else {
    if (is_array($validation_errors) && !empty($validation_errors)) {
Beispiel #16
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 dirname(__FILE__) . '/../../conf/config.inc';
Session::logcheck('environment-menu', 'EventsHidsConfig');
$sensor_id = REQUEST('sensor_id');
ossim_valid($sensor_id, OSS_HEX, 'illegal:' . _('Sensor ID'));
if (!ossim_error()) {
    $db = new ossim_db();
    $conn = $db->connect();
    if (!Ossec_utilities::is_sensor_allowed($conn, $sensor_id)) {
        $db->close();
        $error_msg = sprintf(_("Sensor %s not allowed. Please check with your account admin for more information"), Av_sensor::get_name_by_id($conn, $sensor_id));
        echo ossim_error($error_msg);
        exit;
    }
    $db->close();
}
//Current sensor
$_SESSION['ossec_sensor'] = $sensor_id;
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title><?php 
echo _('OSSIM Framework');
?>
Beispiel #17
0
$sname = POST('sname');
$ip = POST('ip');
$priority = POST('priority');
$port = POST('port');
$tzone = POST('tzone');
$descr = POST('descr');
$location = POST('location');
$entities = POST('entities');
$validation_errors = validate_form_fields('POST', $validate);
if (empty($validation_errors['ip'])) {
    if (preg_match('/,/', $ip)) {
        $validation_errors['ip'] = _('Invalid IP address. Format allowed') . ": nnn.nnn.nnn.nnn <br/>" . _('Entered IP') . ": '<strong>" . Util::htmlentities($ip) . "</strong>'";
    } else {
        $db = new ossim_db();
        $conn = $db->connect();
        $aux_id = Av_sensor::get_id_by_ip($conn, $ip);
        $db->close();
        if (!empty($aux_id)) {
            $validation_errors['ip'] = _('Error! IP address associated with another sensor');
        }
    }
}
$data['status'] = 'OK';
$data['data'] = $validation_errors;
if (POST('ajax_validation_all') == TRUE) {
    if (is_array($validation_errors) && !empty($validation_errors)) {
        $data['status'] = 'error';
        echo json_encode($data);
    } else {
        $data['status'] = 'OK';
        echo json_encode($data);
Beispiel #18
0
<table class='t_sc'>
    <tr>
        <th class='_label'><?php 
display_label($cnf_data['sensor_interfaces']);
?>
</th>
        <td class='_data'>
            <div id='c_ifaces'>
                <?php 
$id = $cnf_data['sensor_interfaces']['id'];
$s_ifaces = $cnf_data['sensor_interfaces']['value'];
$s_ifaces = array_flip($s_ifaces);
//Interfaces
$interfaces = array();
try {
    $interfaces = Av_sensor::get_interfaces($system_id);
} catch (Exception $e) {
}
?>

                <select class='vfield multiselect' id='<?php 
echo $id;
?>
' name='<?php 
echo $id . "[]";
?>
' multiple='multiple'>
                    <?php 
foreach ($interfaces as $iface) {
    $i_name = $iface['name'];
    $id_iface = md5($i_name);
Beispiel #19
0
$db = new ossim_db();
$conn = $db->connect();
if (!empty($task_id)) {
    try {
        $task_obj = Inventory::get_object($conn, $task_id);
        $name = $task_obj['task_name'];
        $sensor_id = $task_obj['task_sensor'];
        $params = $task_obj['task_params'];
        $period = $task_obj['task_period'];
    } catch (Exception $e) {
        echo ossim_error($e->getMessage());
        exit;
    }
}
//Sensors
$sensors = Av_sensor::get_basic_list($conn);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title><?php 
echo _('OSSIM Framework');
?>
</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
    <meta http-equiv="Pragma" content="no-cache">

    <?php 
//CSS Files
$_files = array(array('src' => 'av_common.css?t=' . Util::get_css_id(), 'def_path' => TRUE), array('src' => 'jquery-ui.css', 'def_path' => TRUE), array('src' => 'tipTip.css', 'def_path' => TRUE));
Beispiel #20
0
        $type = 'other';
        break;
    default:
        die(_('Wrong type'));
}
$limit = $limit < 1 || $limit > 7 ? 1 : $limit;
$end = time();
$begind = $end - $limit * 86400;
//86400 belongs to 24 hours in seconds --> 24*60*60
$nfsen_sensors = get_nfsen_sensors();
$sensor_list = '';
foreach ($nfsen_sensors as $flow_id => $sdata) {
    if (!Av_sensor::is_channel_allowed($conn, $flow_id)) {
        continue;
    }
    $sname = Av_sensor::get_nfsen_channel_name($conn, $flow_id);
    $sensor_list .= "{$flow_id};{$sname}:";
}
$sensor_list = preg_replace('/:$/i', '', $sensor_list);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<?php 
//If the refresh is enabled, we set it up in the meta.
if (isset($winfo['refresh']) && $winfo['refresh'] != 0) {
    echo '<meta http-equiv="refresh" content="' . $winfo['refresh'] . '">';
}
?>
	<title><?php 
Beispiel #21
0
*
*/
require_once 'av_init.php';
require_once 'get_sensors.php';
Session::logcheck('configuration-menu', 'PolicySensors');
$av_menu = @unserialize($_SESSION['av_menu']);
// Load column layout
require_once '../conf/layout.php';
$category = 'policy';
$name_layout = 'sensors_layout';
$layout = load_layout($name_layout, $category);
$active_sensors = "<div id=\"c_active_sensor\"><a href=\"sensor.php?onlyactive=1\"><div id=\"active_sensors\" class=\"bold\" style=\"color: green;\"> - </div></a></div>";
$total_sensors = "<a href=\"sensor.php\"><div id=\"total_sensors\" class=\"bold\" style=\"color: black;\"> - </div></a>";
$db = new ossim_db();
$conn = $db->connect();
$unregistered_sensors = Av_sensor::get_unregistered($conn);
$db->close();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title><?php 
echo _('OSSIM Framework');
?>
</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
    <meta http-equiv="Pragma" content="no-cache"/>
    <meta http-equiv="X-UA-Compatible" content="IE=7" />
    <link rel="stylesheet" type="text/css" href="../style/av_common.css?t=<?php 
echo Util::get_css_id();
Beispiel #22
0
 $ips = $_ips->get_ips();
 //Checking HIDS Sensor
 $cnd_1 = Ossec_utilities::is_sensor_allowed($conn, $sensor_id) == FALSE;
 $asset_sensors = Asset_host_sensors::get_sensors_by_id($conn, $asset_id);
 $cnd_2 = empty($asset_sensors[$sensor_id]);
 if ($cnd_1 || $cnd_2) {
     $validation_errors['sensor_id'] = sprintf(_("Sensor %s not allowed. Please check with your account admin for more information"), Av_sensor::get_name_by_id($conn, $sensor_id));
 } else {
     $system_ids = Av_center::get_system_id_by_component($conn, $sensor_id);
     $res = Av_center::get_system_info_by_id($conn, $system_ids['non-canonical']);
     if ($res['status'] == 'success') {
         //We use this function to calculate sensor name because in HA environments there are two systems for one Sensor ID
         if (empty($res['data']['ha_ip'])) {
             $sensor_name = $res['data']['name'];
         } else {
             $sensor_name = Av_sensor::get_name_by_id($conn, $sensor_id);
         }
         $sensor_ip = $res['data']['current_ip'];
         if (Ossec_utilities::get_default_sensor_id() == $sensor_id && empty($res['data']['ha_ip'])) {
             $sensor_ip = $res['data']['admin_ip'];
         }
         $sensor_ip_txt = $sensor_ip . ' [' . $sensor_name . ']';
     }
     //Getting Agent information
     $_aux_agent = Asset_host::get_related_hids_agents($conn, $asset_id, $sensor_id);
     $agent_key = md5(strtoupper($sensor_id) . '#' . $agent_id);
     $agent = $_aux_agent[$agent_key];
     if (empty($agent)) {
         $validation_errors['agent_id'] = _('Error! Agent information cannot be retrieved from system');
     } else {
         $agent_descr = $agent['name'] . ' (' . $agent['ip_cidr'] . ')';
Beispiel #23
0
    ?>
</label>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="center noborder">
                                        <input type="hidden" name="entities[]" id="entities" class='vfield' value="<?php 
    echo Session::get_default_ctx();
    ?>
"/>
                                        <input type="hidden" name="num_entities_check" id="num_entities_check" value=""/>
                                        <br>

                                        <select name="neighborsensor" class='vfield' id="neighborsensor" style="width:150px">
                                            <?php 
    list($s_list, $s_total) = Av_sensor::get_list($conn, array(), FALSE, TRUE);
    $empty = 1;
    foreach ($s_list as $s_id => $s_data) {
        if ($s_data['properties']['version'] != 'unknown') {
            echo "<option value='" . $s_id . "'>" . $s_data['name'] . "\n";
            $empty = 0;
        }
    }
    if ($empty) {
        echo "<option value='00000000000000000000000000000000'>" . _('Local sensor') . "\n";
    }
    ?>
                                        </select>
                                    </td>
                                    <td class="center noborder" style="padding-left:10px">
                                        <input type="hidden" class='vfield' style="width:120px" name="newcontext" value="<?php 
Beispiel #24
0
            }
        }
        break;
}
ossim_valid($sid, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Sid"));
if (ossim_error()) {
    die(_("Invalid Parameter Sid"));
}
if (isset($_POST['authorized_users'])) {
    foreach ($_POST['authorized_users'] as $user) {
        $users[] = Util::htmlentities(escape_sql(trim($user), $dbconn), ENT_QUOTES);
    }
}
$sIDs = array();
if (Vulnerabilities::scanner_type() == 'omp') {
    list($sensor_list, $total) = Av_sensor::get_list($dbconn);
    foreach ($sensor_list as $sensor_id => $sensor_data) {
        if (intval($sensor_data['properties']['has_vuln_scanner']) == 1) {
            $sIDs[] = array('name' => $sensor_data['name'], 'id' => $sensor_id);
        }
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title> <?php 
echo gettext("Vulnmeter");
?>
 </title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
Beispiel #25
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();
    }
}
Beispiel #26
0
         $flag_events = false;
     }
 }
 if ($flag_events) {
     $event_types = "<b>" . _('DS Groups') . ":</b><br>" . $plugingroups;
 } else {
     $event_types = "<b>" . _('Taxonomy') . ":</b><br>" . $taxonomy;
 }
 $xml .= "<cell><![CDATA[" . $event_types . "]]></cell>";
 if ($engine != 'engine') {
     $sensors = "";
     $sensor_exist = $policy->exist_sensors($conn);
     if ($sensor_list = $policy->get_sensors($conn)) {
         foreach ($sensor_list as $sensor) {
             if (!check_any($sensor->get_sensor_id())) {
                 $sensors .= ($sensors == "" ? "" : "<br/>") . Av_sensor::get_name_by_id($conn, $sensor->get_sensor_id());
                 if ($sensor_exist[$sensor->get_sensor_id()] == 'false') {
                     $sensors = '<div title="' . _('sensor non-existent') . '">' . $sensors;
                     $sensors .= '<a href="newpolicyform.php?id=' . $id . '&sensorNoExist=true#tabs-5"><img style="vertical-align: middle" src="../pixmaps/tables/cross-small-circle.png" /></a></div>';
                 }
             }
         }
     }
     if (empty($sensors)) {
         $sensors = "<font color='#AAAAAA'><b>ANY</b></font>";
     }
     $xml .= "<cell><![CDATA[" . $sensors . "]]></cell>";
 }
 if ($policy_time = $policy->get_time($conn)) {
     $tzone = $policy_time->get_timezone();
     $begin_range = "";
function main_page($viewall, $sortby, $sortdir)
{
    global $uroles, $username, $dbconn, $hosts;
    global $arruser, $user;
    $dbconn->SetFetchMode(ADODB_FETCH_BOTH);
    $tz = Util::get_timezone();
    if ($sortby == "") {
        $sortby = "id";
    }
    if ($sortdir == "") {
        $sortdir = "DESC";
    }
    $sql_order = "order by {$sortby} {$sortdir}";
    if (Session::menu_perms("environment-menu", "EventsVulnerabilitiesScan")) {
        ?>
		<div style="width:50%; position: relative; height: 5px; float:left">
			
			<div style="width:100%; position: absolute; top: -41px;left:0px;">
    			<div style="float:left; height:28px; margin:5px 5px 0px 0px;">
    				<a class="button" href="<?php 
        echo Menu::get_menu_url(AV_MAIN_PATH . '/vulnmeter/sched.php?smethod=schedule&hosts_alive=1&scan_locally=1', 'environment', 'vulnerabilities', 'scan_jobs');
        ?>
">
                            <?php 
        echo _("New Scan Job");
        ?>
    				</a>
    			</div>
    			
    			<div style="float:left;height:28px;margin:5px 5px 0px -2px;">
    				<a class="greybox button av_b_secondary" href="import_nbe.php" title="<?php 
        echo _("Import nbe file");
        ?>
">
    				        <?php 
        echo _("Import nbe file");
        ?>
    				</a>
    			</div>
			</div>		
			
		</div>
		
		<?php 
    }
    if (intval($_GET['page']) != 0) {
        $page = intval($_GET['page']);
    } else {
        $page = 1;
    }
    $pagesize = 10;
    if ($username == "admin") {
        $query = "SELECT count(id) as num FROM vuln_jobs";
    } else {
        $query = "SELECT count(id) as num FROM vuln_jobs where username='******'";
    }
    $result = $dbconn->Execute($query);
    $jobCount = $result->fields["num"];
    $num_pages = ceil($jobCount / $pagesize);
    //echo "num_pages:[".$num_pages."]";
    //echo "jobCount:[".$jobCount."]";
    //echo "page:[".$page."]";
    if (Vulnerabilities::scanner_type() == "omp") {
        // We can display scan status with OMP protocol
        echo Vulnerabilities::get_omp_running_scans($dbconn);
    } else {
        // Nessus
        all_jobs(0, 10, "R");
    }
    ?>

<?php 
    $schedulejobs = _("Scheduled Jobs");
    echo <<<EOT

   <table style='margin-top:20px;' class='w100 transparent'><tr><td class='sec_title'>{$schedulejobs}</td></tr></table>
   <table summary="Job Schedules" class='w100 table_list'>
EOT;
    if ($sortdir == "ASC") {
        $sortdir = "DESC";
    } else {
        $sortdir = "ASC";
    }
    $arr = array("name" => "Name", "schedule_type" => "Schedule Type", "time" => "Time", "next_CHECK" => "Next Scan", "enabled" => "Status");
    // modified by hsh to return all scan schedules
    if (empty($arruser)) {
        $query = "SELECT t2.name as profile, t1.meth_TARGET, t1.id, t1.name, t1.schedule_type, t1.meth_VSET, t1.meth_TIMEOUT, t1.username, t1.enabled, t1.next_CHECK, t1.email\n              FROM vuln_job_schedule t1 LEFT JOIN vuln_nessus_settings t2 ON t1.meth_VSET=t2.id ";
    } else {
        $query = "SELECT t2.name as profile, t1.meth_TARGET, t1.id, t1.name, t1.schedule_type, t1.meth_VSET, t1.meth_TIMEOUT, t1.username, t1.enabled, t1.next_CHECK, t1.email\n              FROM vuln_job_schedule t1 LEFT JOIN vuln_nessus_settings t2 ON t1.meth_VSET=t2.id WHERE username in ({$user}) ";
    }
    $query .= $sql_order;
    $result = $dbconn->execute($query);
    if ($result->EOF) {
        echo "<tr><td class='empty_results' height='20' style='text-align:center;'>" . _("No Scheduled Jobs") . "</td></tr>";
    }
    if (!$result->EOF) {
        echo "<tr>";
        foreach ($arr as $order_by => $value) {
            echo "<th><a href=\"manage_jobs.php?sortby={$order_by}&sortdir={$sortdir}\">" . _($value) . "</a></th>";
        }
        if (Session::menu_perms("environment-menu", "EventsVulnerabilitiesScan")) {
            echo "<th>" . _("Action") . "</th></tr>";
        }
    }
    $colors = array("#FFFFFF", "#EEEEEE");
    $color = 0;
    while (!$result->EOF) {
        list($profile, $targets, $schedid, $schedname, $schedtype, $sid, $timeout, $user, $schedstatus, $nextscan, $servers) = $result->fields;
        $name = Av_sensor::get_name_by_id($dbconn, $servers);
        $servers = $name != '' ? $name : "unknown";
        $targets_to_resolve = explode("\n", $targets);
        $ttargets = array();
        foreach ($targets_to_resolve as $id_ip) {
            if (preg_match("/^([a-f\\d]{32})#\\d+\\.\\d+\\.\\d+\\.\\d+\\/\\d{1,2}/i", $id_ip, $found) && Asset_net::is_in_db($dbconn, $found[1])) {
                $ttargets[] = preg_replace("/^([a-f\\d]{32})#/i", "", $id_ip) . " (" . Asset_net::get_name_by_id($dbconn, $found[1]) . ")";
            } else {
                if (preg_match("/^([a-f\\d]{32})#\\d+\\.\\d+\\.\\d+\\.\\d+/i", $id_ip, $found) && Asset_host::is_in_db($dbconn, $found[1])) {
                    $ttargets[] = preg_replace("/^([a-f\\d]{32})#/i", "", $id_ip) . " (" . Asset_host::get_name_by_id($dbconn, $found[1]) . ")";
                } else {
                    $ttargets[] = preg_replace("/[a-f\\d]{32}/i", "", $id_ip);
                }
            }
        }
        $targets = implode("<BR/>", $ttargets);
        $tz = intval($tz);
        $nextscan = gmdate("Y-m-d H:i:s", Util::get_utc_unixtime($nextscan) + 3600 * $tz);
        preg_match("/\\d+\\-\\d+\\-\\d+\\s(\\d+:\\d+:\\d+)/", $nextscan, $found);
        $time = $found[1];
        switch ($schedtype) {
            case "N":
                $stt = _("Once (Now)");
                break;
            case "O":
                $stt = _("Once");
                break;
            case "D":
                $stt = _("Daily");
                break;
            case "W":
                $stt = _("Weekly");
                break;
            case "M":
                $stt = _("Monthly");
                break;
            case "Q":
                $stt = _("Quarterly");
                break;
            case "H":
                $stt = _("On Hold");
                break;
            case "NW":
                $stt = _("N<sup>th</sup> weekday of the month");
                break;
            default:
                $stt = "&nbsp;";
                break;
        }
        switch ($schedstatus) {
            case "1":
                $itext = _("Disable Scheduled Job");
                $isrc = "images/stop_task.png";
                $ilink = "manage_jobs.php?disp=setstatus&schedid={$schedid}&enabled=0";
                break;
            default:
                $itext = _("Enable Scheduled Job");
                $isrc = "images/play_task.png";
                $ilink = "manage_jobs.php?disp=setstatus&schedid={$schedid}&enabled=1";
                break;
        }
        if (!Session::menu_perms("environment-menu", "EventsVulnerabilitiesScan")) {
            $ilink = "javascript:return false;";
        }
        if ($schedstatus) {
            $txt_enabled = "<td><a href=\"{$ilink}\"><font color=\"green\">" . _("Enabled") . "</font></a></td>";
        } else {
            $txt_enabled = "<td><a href=\"{$ilink}\"><font color=\"red\">" . _("Disabled") . "</font></a></td>";
        }
        require_once 'classes/Security.inc';
        if (valid_hex32($user)) {
            $user = Session::get_entity_name($dbconn, $user);
        }
        echo "<tr bgcolor=\"" . $colors[$color % 2] . "\">";
        if ($profile == "") {
            $profile = _("Default");
        }
        echo "<td><span class=\"tip\" title=\"<b>" . _("Owner") . ":</b> {$user}<br><b>" . _("Server") . ":</b> {$servers}<br /><b>" . _("Scheduled Job ID") . ":</b> {$schedid}<br><b>" . _("Profile") . ":</b> {$profile}<br><b>" . _("Targets") . ":</b><br>" . $targets . "\">{$schedname}</span></td>";
        ?>
    <td><?php 
        echo $stt;
        ?>
</td>
    <td><?php 
        echo $time;
        ?>
</td>
    <td><?php 
        echo $nextscan;
        ?>
</td>
<?php 
        echo <<<EOT
    {$txt_enabled}
    <td style="padding-top:2px;"><a href="{$ilink}"><img alt="{$itext}" src="{$isrc}" border=0 title="{$itext}"></a>&nbsp;
EOT;
        if (Session::menu_perms("environment-menu", "EventsVulnerabilitiesScan")) {
            echo "<a href='" . Menu::get_menu_url(AV_MAIN_PATH . '/vulnmeter/sched.php?disp=edit_sched&sched_id=' . $schedid, 'environment', 'vulnerabilities', 'scan_jobs') . "'><img src='images/pencil.png' title='" . _("Edit Scheduled") . "'></a>&nbsp;";
            echo "<a href='manage_jobs.php?disp=delete&amp;schedid={$schedid}' onclick='return confirmDelete();'><img src='images/delete.gif' title='" . gettext("Delete Scheduled") . "'></a>";
        }
        echo "</td>";
        echo <<<EOT
</tr>
EOT;
        $result->MoveNext();
        $color++;
    }
    echo <<<EOT
</table>
EOT;
    ?>
<br />
<?php 
    $out = all_jobs(($page - 1) * $pagesize, $pagesize);
    ?>
<table width="100%" align="center" class="transparent" cellspacing="0" cellpadding="0">
    <tr>
        <td class="nobborder" valign="top" style="padding-top:5px;">
            <div class="fright">
                <?php 
    if ($out != 0 && $num_pages != 1) {
        $page_url = "manage_jobs.php";
        if ($page == 1 && $page == $num_pages) {
            echo '<a href="" class="link_paginate_disabled" onclick="return false">< ' . _("PREVIOUS") . '</a>';
            echo '<a class="lmargin link_paginate_disabled" href="" onclick="return false">' . _("NEXT") . ' ></a>';
        } elseif ($page == 1) {
            echo '<a href="" class="link_paginate_disabled" onclick="return false">< ' . _("PREVIOUS") . '</a>';
            echo '<a class="lmargin" href="' . $page_url . '?page=' . ($page + 1) . '">' . _("NEXT") . ' ></a>&nbsp;';
        } elseif ($page == $num_pages) {
            echo '<a href="' . $page_url . '?page=' . ($page - 1) . '">< ' . _("PREVIOUS") . '</a>';
            echo '<a class="lmargin link_paginate_disabled" href="" onclick="return false">' . _("NEXT") . ' ></a>';
        } else {
            echo '<a href="' . $page_url . '?page=' . ($page - 1) . '">< ' . _("PREVIOUS") . '</a><a class="lmargin" href="' . $page_url . '?page=' . ($page + 1) . '">' . _("NEXT") . ' ></a>';
        }
    }
    ?>
            </div>
        </td>
    </tr>
    </table>
<?php 
}
Beispiel #28
0
                      <th>
                         <strong><?php 
    echo _('Scanner IP');
    ?>
</strong>
                      </th>
                      <th>
                         <strong><?php 
    echo _('Scanner connection');
    ?>
</strong>
                      </th>
                  </tr>
                  <?php 
    foreach ($ctest as $k => $v) {
        $sensor_ip = Av_sensor::get_ip_by_id($conn, $k);
        if ($v == '') {
            echo '<tr><td class="nobborder" style="text-align:center;padding:0px 10px;">' . $sensor_ip . '</td>';
            echo '<td class="nobborder" style="text-align:center;padding:0px 10px;"><img class="vcheck_' . md5($sensor_ip) . '" src="../pixmaps/tick.png" border="0" /></td></tr>';
        } else {
            $nf_type = "nf_error";
            echo "<tr><td class='nobborder sstatus' >" . $sensor_ip . "</td>";
            echo "<td width='300' class='nobborder sstatus' >";
            if (preg_match("/Failed to acquire socket/", $v)) {
                $v = 'Unable to connect to vulnerability scanner. If the system has been updated recently the vulnerability scanner is rebuilding its database. Please wait a few minutes.';
                $nf_type = 'nf_warning';
            }
            $config_nt = array('content' => _($v), 'options' => array('type' => $nf_type, 'cancel_button' => false), 'style' => 'width: 80%; margin: 10px auto; text-align: left;');
            $nt = new Notification('nt_2', $config_nt);
            $nt->show();
            echo '</td></tr>';
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;
}
Beispiel #30
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_hosts' => 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));
        }
    }
    /*************************************************************************************************************************************
     * From asset section:
     *  - Version 4.x.x or higher: "IP (IP1,IP2,...)";"Hostname";"FQDNs(FQDN1,FQDN2,...)";"Description";"Asset value";"Operating System";
     *                   "Latitude";"Longitude";"Host ID";"External Asset";"Device Types(Type1,Type2,...)"
     *
     *  - Version 3.x.x: "IP"*;"Hostname";"FQDNs(FQDN1,FQDN2,...)";"Description";"Asset value";"Sensors(Sensor1,Sensor2,...)";
     *                   "Operating System";"Latitude";"Longitude"
     *
     * From welcome wizard:
     *  - Version 4.x.x or higher: "IP (IP1,IP2,...)";"Hostname";"Description";"Operating System";"Device Type(Type1,Type2,...)"
     *
     **************************************************************************************************************************************/
    //Check file size
    if (count($data) <= 0 || count($data) == 1 && preg_match('/IP/', $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 == 'hosts') {
        if (preg_match('/Operating System/', $data[0][5]) || preg_match('/Sensors/', $data[0][5])) {
            $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 hosts to import
    $summary['general']['statistics']['total'] = count($data);
    //Getting all Operating System
    $all_os = Properties::get_all_os();
    //Getting devices types
    $all_devices = array();
    $aux_all_devices = Devices::get_all_for_filter($conn);
    $_all_devices = $aux_all_devices[0];
    foreach ($_all_devices as $d_data) {
        $d_key = $d_data['type_name'];
        $d_key .= $d_data['subtype_id'] != 0 ? ':' . $d_data['subtype_name'] : '';
        $all_devices[$d_key] = $d_data['type_id'] . ':' . $d_data['subtype_id'];
    }
    //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 sensors for this context') : _('There is no sensors for this IP address');
        $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_hosts'][$num_line]['status'] = 'error';
        //Check file format
        $cnd_1 = $import_type == 'hosts' && count($v) < 9;
        $cnd_2 = $import_type == 'welcome_wizard_hosts' && count($v) < 5;
        if ($cnd_1 || $cnd_2) {
            $summary['by_hosts'][$num_line]['errors']['Format'] = _('Number of fields is incorrect');
            $summary['general']['statistics']['errors']++;
            continue;
        }
        //Clean values
        $param = array();
        $index = 0;
        $max_index = count($v) - 1;
        foreach ($v as $field) {
            $parameter = trim($field);
            if ($index == 0) {
                $pattern = '/^\\"|^\'/';
                $param[] = preg_replace($pattern, '', $parameter);
            } else {
                if ($index == $max_index) {
                    $pattern = '/\\"$|\'$/';
                    $param[] = preg_replace($pattern, '', $parameter);
                } else {
                    $param[] = $parameter;
                }
            }
            $index++;
        }
        //Values
        $is_in_db = FALSE;
        $host_id = '';
        $sensors = $sensor_ids;
        $csv_ips = preg_replace("/\\s+/", '', $param[0]);
        if (!empty($param[1])) {
            $name = $param[1];
        } else {
            $aux_name = str_replace(' ', '', $csv_ips);
            $aux_name = str_replace(',', '-', $aux_name);
            $name = Asset_host::get_autodetected_name($aux_name);
        }
        if ($import_type == 'hosts') {
            $fqdns = $param[2];
            $descr = $param[3];
            $asset_value = !empty($param[4]) ? $param[4] : 2;
            if (preg_match('/Host ID/', $csv_headers[8])) {
                $os = $param[5];
                $latitude = floatval($param[6]);
                $longitude = floatval($param[7]);
                $external = empty($param[9]) ? 0 : intval($param[9]);
                $csv_devices = $param[10];
            } else {
                $os = $param[6];
                $latitude = floatval($param[7]);
                $longitude = floatval($param[8]);
                $external = 0;
                $csv_devices = '';
            }
        } else {
            $descr = $param[2];
            $os = $param[3];
            $latitude = 0;
            $longitude = 0;
            $asset_value = 2;
            $external = 0;
            $csv_devices = $param[4];
        }
        //Permissions
        $can_i_create_assets = Session::can_i_create_assets();
        $can_i_modify_ips = TRUE;
        //IPs
        if (!ossim_valid($csv_ips, OSS_IP_ADDR, 'illegal:' . _('IP'))) {
            $summary['by_hosts'][$num_line]['errors']['IP'] = ossim_get_error_clean();
            $summary['general']['statistics']['errors']++;
            continue;
        }
        //Check Host ID: Is there a host registered in the System?
        $host_ids = Asset_host::get_id_by_ips($conn, $csv_ips, $ctx);
        $host_id = key($host_ids);
        if (!empty($host_id)) {
            $is_in_db = TRUE;
        } else {
            $host_id = Util::uuid();
        }
        // Special case: Forced Host ID [Version 4.x.x or higher]
        if ($import_type == 'hosts' && preg_match('/Host ID/', $csv_headers[8]) && valid_hex32($param[8])) {
            $csv_hosts_id = strtoupper($param[8]);
            if ($is_in_db == TRUE && $csv_hosts_id != $host_id) {
                $id_error_msg = _('Host is already registered in the System with another Host ID');
                $summary['by_hosts'][$num_line]['errors']['Host'] = $id_error_msg;
                $summary['general']['statistics']['errors']++;
                continue;
            } else {
                if ($is_in_db == FALSE) {
                    $host_id = $csv_hosts_id;
                    // Save host ID to insert it
                }
            }
        }
        //Hostname
        if (!empty($iic)) {
            $name = clean_iic($name);
        }
        if (!ossim_valid($name, OSS_HOST_NAME, 'illegal:' . _('Hostname'))) {
            ossim_clean_error();
            $name = Asset_host::create_valid_name($name);
            $warning_msg = _('Hostname does not match with RFC 1123 specifications') . '<br/>' . _('Hostname will be replaced by') . ": <strong>{$name}</strong>";
            $summary['by_hosts'][$num_line]['warnings']['Hostname'] = $warning_msg;
            $summary['by_hosts'][$num_line]['status'] = 'warning';
            $summary['general']['statistics']['warnings']++;
            if (!ossim_valid($name, OSS_HOST_NAME, 'illegal:' . _('Hostname'))) {
                unset($summary['by_hosts'][$num_line]['warnings']);
                $summary['general']['statistics']['warnings']--;
                $summary['by_hosts'][$num_line]['status'] = 'error';
                $summary['by_hosts'][$num_line]['errors']['Hostname'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
        }
        //Description
        if (!ossim_valid($descr, OSS_NULLABLE, OSS_ALL, 'illegal:' . _('Description'))) {
            $summary['by_hosts'][$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');
            }
        }
        //Operating System
        $os_pattern = '/' . preg_quote(implode('|', $all_os), '/') . '/';
        $os_pattern = str_replace('\\|', '|', $os_pattern);
        if (!empty($os) && !preg_match($os_pattern, $os)) {
            $warning_msg = _('Operating System unknown');
            $summary['by_hosts'][$num_line]['warnings']['Operating System'] = $warning_msg;
            $summary['by_hosts'][$num_line]['status'] = 'warning';
            $summary['general']['statistics']['warnings']++;
            $os = 'Unknown';
        }
        //Devices Types
        $devices = array();
        $unallowed_devices = array();
        if (!empty($csv_devices)) {
            $aux_devices = explode(',', $csv_devices);
            if (is_array($aux_devices) && !empty($aux_devices)) {
                foreach ($aux_devices as $d_name) {
                    $d_name = trim($d_name);
                    if (array_key_exists($d_name, $all_devices)) {
                        $devices[] = $all_devices[$d_name];
                    } else {
                        $unallowed_devices[] = $d_name;
                    }
                }
                if (!empty($unallowed_devices)) {
                    $warning_msg = _('Some devices could not be added (Type and/or subtype unknown)') . ': ' . implode(',', $unallowed_devices);
                    $summary['by_hosts'][$num_line]['warnings']['Devices'] = $warning_msg;
                    $summary['by_hosts'][$num_line]['status'] = 'warning';
                    $summary['general']['statistics']['warnings']++;
                }
            }
        }
        //Sensor
        if ($is_in_db == FALSE) {
            //Only update host sensors with unregistered hosts
            if ($import_type == 'hosts' && preg_match('/Sensors/', $csv_headers[5])) {
                //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 address');
                    $summary['by_hosts'][$num_line]['errors']['Sensors'] = $s_error_msg;
                    $summary['general']['statistics']['errors']++;
                    continue;
                }
            }
        }
        /***********************************************************
         ********** Only for importation from host section **********
         ***********************************************************/
        if ($import_type == 'hosts') {
            //FQDNs
            if (!ossim_valid($fqdns, OSS_FQDNS, OSS_NULLABLE, 'illegal:' . _('FQDN/Aliases'))) {
                $summary['by_hosts'][$num_line]['errors']['FQDN/Aliases'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
            //Asset
            if (!ossim_valid($asset_value, OSS_DIGIT, 'illegal:' . _('Asset value'))) {
                $summary['by_hosts'][$num_line]['errors']['Asset value'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
            //Latitude
            if (!empty($latitude)) {
                if (!ossim_valid(trim($latitude), OSS_NULLABLE, OSS_DIGIT, OSS_DOT, '\\-', 'illegal:' . _('Latitude'))) {
                    $summary['by_hosts'][$num_line]['errors']['Latitude'] = ossim_get_error_clean();
                    $summary['general']['statistics']['errors']++;
                    continue;
                }
            }
            //Longitude
            if (!empty($longitude)) {
                if (!ossim_valid(trim($longitude), OSS_NULLABLE, OSS_DIGIT, OSS_DOT, '\\-', 'illegal:' . _('Longitude'))) {
                    $summary['by_hosts'][$num_line]['errors']['Longitude'] = ossim_get_error_clean();
                    $summary['general']['statistics']['errors']++;
                    continue;
                }
            }
        }
        //Insert/Update host in database
        if (count($summary['by_hosts'][$num_line]['errors']) == 0) {
            try {
                $host = new Asset_host($conn, $host_id);
                if ($is_in_db == TRUE) {
                    $host->load_from_db($conn, $host_id);
                    $can_i_modify_ips = Asset_host::can_i_modify_ips($conn, $host_id);
                } else {
                    if ($can_i_create_assets == FALSE) {
                        $n_error_msg = _('Host') . ' ' . $name . ' ' . _("not allowed. You don't have permissions to import this host");
                        $summary['by_hosts'][$num_line]['errors']['Net'] = $n_error_msg;
                        $summary['general']['statistics']['errors']++;
                        continue;
                    }
                }
                //Check IPs
                if ($can_i_modify_ips == TRUE) {
                    $aux_ips = explode(',', $csv_ips);
                    foreach ($aux_ips as $ip) {
                        $host_ids = Asset_host::get_id_by_ips($conn, $ip, $ctx);
                        unset($host_ids[$host_id]);
                        if (!empty($host_ids)) {
                            $c_error_msg = _('IP') . ' ' . $csv_ips . ' ' . _("not allowed. IP {$ip} already exists for this entity");
                            $summary['by_hosts'][$num_line]['errors']['IP'] = $c_error_msg;
                            $summary['general']['statistics']['errors']++;
                            break;
                        } else {
                            $cnd_1 = Session::get_net_where() != '' && !Session::only_ff_net();
                            $cnd_2 = Asset_host::is_ip_in_cache_cidr($conn, $ip, $ctx, TRUE);
                            if ($cnd_1 && !$cnd_2) {
                                $c_error_msg = sprintf(_("Error! The IP %s is not allowed. Please check with your account admin for more information"), $csv_ips);
                                $summary['by_hosts'][$num_line]['errors']['IP'] = $c_error_msg;
                                $summary['general']['statistics']['errors']++;
                                break;
                            }
                        }
                    }
                } else {
                    $c_error_msg = _('Host') . ' ' . $name . ': ' . _("IP address not allowed. IP address cannot be modified");
                    $summary['by_hosts'][$num_line]['status'] = 'warning';
                    $summary['general']['warnings']['errors']++;
                    $summary['by_hosts'][$num_line]['warnings']['IP'] = $c_error_msg;
                }
                //Setting new values
                if (count($summary['by_hosts'][$num_line]['errors']) == 0) {
                    $host->set_ctx($ctx);
                    $host->set_name($name);
                    $host->set_descr($descr);
                    if ($is_in_db == FALSE) {
                        if ($can_i_modify_ips == TRUE) {
                            if (is_array($aux_ips) && !empty($aux_ips)) {
                                $ips = array();
                                foreach ($aux_ips as $ip) {
                                    $ips[$ip] = array('ip' => $ip, 'mac' => NULL);
                                }
                                $host->set_ips($ips);
                            }
                        }
                        $host->set_sensors($sensors);
                    }
                    if (!empty($fqdns)) {
                        $host->set_fqdns($fqdns);
                    }
                    $host->set_external($external);
                    $host->set_location($latitude, $longitude);
                    $host->set_asset_value($asset_value);
                    $host->set_devices($devices);
                    $host->save_in_db($conn, FALSE);
                    //Save Operating System
                    if (!empty($os)) {
                        Asset_host_properties::save_property_in_db($conn, $host_id, 3, $os, 2);
                    }
                    $summary['general']['statistics']['saved']++;
                    $summary['by_hosts'][$num_line]['data'] = $is_in_db == TRUE ? _('Asset updated') : _('New asset inserted');
                    //Keep warnings
                    if ($summary['by_hosts'][$num_line]['status'] != 'warning') {
                        $summary['by_hosts'][$num_line]['status'] = 'success';
                    }
                }
            } catch (Exception $e) {
                $summary['by_hosts'][$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 assets have been successfully imported ');
        } else {
            $summary['general']['status'] = 'warning';
            $summary['general']['data'] = _('Some assets cannot be imported');
        }
        Util::disable_perm_triggers($conn, FALSE);
        try {
            Asset_host::report_changes($conn, 'hosts');
        } catch (Exception $e) {
            Av_exception::write_log(Av_exception::USER_ERROR, $e->getMessage());
        }
    } 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'] = _('Assets cannot be imported');
        }
    }
    @$conn->Execute("REPLACE INTO alienvault.host_net_reference SELECT host.id,net_id FROM alienvault.host, alienvault.host_ip, alienvault.net_cidrs WHERE host.id = host_ip.host_id AND host_ip.ip >= net_cidrs.begin AND host_ip.ip <= net_cidrs.end");
    $db->close();
    return $summary;
}