function check_ossim_error()
{
    if (ossim_error()) {
        $error = ossim_get_error();
        ossim_clean_error();
        Av_exception::throw_error(Av_exception::USER_ERROR, $error);
    }
}
function get_pulse_detail_from_id($conn)
{
    $type = POST('type');
    $pulse = POST('pulse');
    $id = POST('id');
    ossim_valid($type, 'alarm|event|alarm_event', 'illegal:' . _('Type'));
    ossim_valid($pulse, OSS_HEX, 'illegal:' . _('Pulse'));
    ossim_valid($id, OSS_HEX, 'illegal:' . _('ID'));
    if (ossim_error()) {
        Av_exception::throw_error(Av_exception::USER_ERROR, ossim_get_error_clean());
    }
    if ($type == 'alarm') {
        $pulse = Alarm::get_pulse_data_from_alarm($conn, $id, $pulse, TRUE);
    } elseif ($type == 'event') {
        $pulse = Siem::get_pulse_data_from_event($conn, $id, $pulse, FALSE, TRUE);
    } elseif ($type == 'alarm_event') {
        $pulse = Siem::get_pulse_data_from_event($conn, $id, $pulse, TRUE, TRUE);
    }
    return array('name' => $pulse['name'], 'descr' => $pulse['descr'], 'iocs' => array_values($pulse['iocs']));
}
Beispiel #3
0
function restart_search($conn, $data)
{
    $return['error'] = FALSE;
    $return['msg'] = '';
    $type = $data['type'];
    ossim_valid($type, 'asset', 'group', 'network', 'illegal:' . _("List Type"));
    if (ossim_error()) {
        $error = ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $error;
        return $return;
    }
    Filter_list::delete_filters_from_session();
    try {
        $object = 'Filter_' . $type . '_list';
        if (!class_exists($object)) {
            Av_exception::throw_error(Av_exception::USER_ERROR, _('Invalid List Type'));
        }
        $filter_list = new $object($conn);
        $filter_list->store_filter_list_session();
    } catch (Exception $e) {
        $return['error'] = TRUE;
        $return['msg'] = $e->getMessage();
    }
    return $return;
}
Beispiel #4
0
session_write_close();
Session::logcheck('environment-menu', 'EventsHidsConfig');
$events_hids_config = Session::menu_perms('environment-menu', 'EventsHidsConfig');
try {
    $db = new ossim_db();
    $conn = $db->connect();
    $sensor_id = POST('sensor_id');
    ossim_valid($sensor_id, OSS_HEX, 'illegal:' . _('Sensor ID'));
    if (!ossim_error()) {
        if (!Ossec_utilities::is_sensor_allowed($conn, $sensor_id)) {
            $e_msg = _('Error! Sensor not allowed');
            Av_exception::throw_error(Av_exception::USER_ERROR, $e_msg);
        }
    } else {
        $e_msg = ossim_get_error_clean();
        Av_exception::throw_error(Av_exception::USER_ERROR, $e_msg);
    }
    $agents = Ossec_agent::get_list($sensor_id);
    $data = array();
    if (is_array($agents) && !empty($agents)) {
        foreach ($agents as $agent_id => $a_data) {
            if (empty($a_data)) {
                continue;
            }
            $a_unique_id = md5($agent_id);
            $agent_actions = Ossec_agent::get_actions($agent_id, $a_data);
            if (!empty($a_data['host_id'])) {
                $asset_name = Asset_host::get_name_by_id($conn, $a_data['host_id']);
            } else {
                $asset_name = '-';
            }
Beispiel #5
0
*
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
Session::useractive();
if (!Session::am_i_admin()) {
    Av_exception::throw_error(Av_exception::USER_ERROR, _('You do not have permissions to see this section'));
}
$wizard = Welcome_wizard::get_instance();
if (!$wizard instanceof Welcome_wizard) {
    Av_exception::throw_error(Av_exception::USER_ERROR, "There was an error, the Welcome_wizard object doesn't exist");
}
//Getting the scan step to know if we have a scan running
$step = intval($wizard->get_step_data('scan_step'));
//Selected nets
$nets_selected = $wizard->get_step_data('scan_nets');
$nets_selected = is_array($nets_selected) ? $nets_selected : array();
$n_ids = array_fill_keys(array_keys($nets_selected), 1);
$paths = Asset::get_path_url(FALSE);
$iframe_url = $paths['network']['views'] . 'import_all_nets.php?import_type=welcome_wizard_nets';
?>
<!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 _("AlienVault " . (Session::is_pro() ? "USM" : "OSSIM"));
Beispiel #6
0
                    $curid = $rs->fields['id'];
                }
            }
            $id = Av_report::get_new_report_module_id($conn);
            if ($curid > 0) {
                $sql = "UPDATE custom_report_types SET name=?,type='Custom Security Events',file='SIEM/CustomList.php',inputs='Number of Events:top:text:OSS_DIGIT:25:1000',custom_report_types.sql=? WHERE id=?";
                $params = array($name, "{$query1};{$query2};{$columns}", $curid);
            } else {
                $sql = "INSERT INTO custom_report_types (id,name,type,file,inputs,custom_report_types.sql) VALUES (?,?,'Custom Security Events','SIEM/CustomList.php','Number of Events:top:text:OSS_DIGIT:25:1000',?)";
                $params = array($id, $name, "{$query1};{$query2};{$columns}");
            }
            if ($conn->Execute($sql, $params)) {
                $msg = $curid > 0 ? _("Report Module") . " <b>'Custom Security Events - {$name}'</b> " . _("successfully updated") : _("Report Module successfully created as") . " <b>'Custom Security Events - {$name}'</b>";
                $msg_type = 'nf_success';
            } else {
                Av_exception::write_log(Av_exception::DB_ERROR, $conn->ErrorMsg());
                $msg = _("Error creating a new report type.");
                $msg_type = 'nf_error';
            }
            $db->close();
        } else {
            $msg = _("Error creating a new report type.");
            $msg_type = 'nf_error';
        }
    }
}
$tags = get_tags($idm_enabled);
if ($opensource) {
    unset($tags['PLUGIN_SOURCE_TYPE']);
    unset($tags['PLUGIN_SID_CATEGORY']);
    unset($tags['PLUGIN_SID_SUBCATEGORY']);
ossim_valid($search_str, OSS_INPUT, OSS_NULLABLE, 'illegal: ' . _('Search String'));
ossim_valid($from, OSS_DIGIT, 'illegal: ' . _('Configuration Parameter 2'));
ossim_valid($sec, OSS_DIGIT, 'illegal: ' . _('Configuration Parameter 3'));
if (ossim_error()) {
    $response['sEcho'] = intval($sec);
    $response['iTotalRecords'] = 0;
    $response['iTotalDisplayRecords'] = 0;
    $response['aaData'] = array();
    echo json_encode($response);
    exit;
}
// Get object from session
$asset_object = unserialize($_SESSION['asset_detail'][$asset_id]);
$class_name = get_class($asset_object);
if (!is_object($asset_object)) {
    Av_exception::throw_error(Av_exception::DB_ERROR, _('Error retrieving the asset data from Memory'));
}
$db = new ossim_db();
$conn = $db->connect();
$filters = array('where' => 'host_properties.property_ref <> 8', 'limit' => "{$from}, {$maxrows}");
if ($search_str != '') {
    $search_str = escape_sql($search_str, $conn);
    $filters['where'] .= ' AND host_properties.value LIKE "%' . $search_str . '%"';
}
// DATA
list($properties, $total) = $asset_object->get_properties($conn, $filters);
$data = array();
foreach ($properties as $_host_id => $prop_list) {
    $_host_aux = Asset_host::get_object($conn, $_host_id);
    $host = $_host_aux->get_name() . ' (' . $_host_aux->get_ips()->get_ips('string') . ')';
    foreach ($prop_list as $prop_id => $prop_data) {
function make_sid_filter($conn, $ip)
{
    $sids = array();
    if (preg_match("/\\d+\\/\\d+/", $ip)) {
        $aux = Cidr::expand_cidr($ip, 'SHORT', 'IP');
        if ($aux[0] == 'I' && $aux[1] == 'P') {
            $aux[0] = '0x0';
            $aux[1] = '0x0';
        } else {
            $aux[0] = bin2hex(inet_pton($aux[0]));
            $aux[1] = bin2hex(inet_pton($aux[1]));
        }
        $query = "SELECT d.id FROM alienvault_siem.device d, alienvault.sensor s \n\t\t          WHERE d.sensor_id=s.id \n\t\t          AND ( (s.ip >= UNHEX('" . $aux[0] . "') AND s.ip <= UNHEX('" . $aux[1] . "')) \n\t\t          OR (d.device_ip>=UNHEX('" . $aux[0] . "') AND d.device_ip <= UNHEX('" . $aux[1] . "')) )";
    } else {
        $ip = bin2hex(@inet_pton($ip));
        $query = "SELECT d.id FROM alienvault_siem.device d, alienvault.sensor s \n\t\t          WHERE d.sensor_id = s.id AND ( s.ip = UNHEX('{$ip}') OR d.device_ip = UNHEX('{$ip}') )";
    }
    //echo $query;
    if (!($rs =& $conn->Execute($query))) {
        Av_exception::throw_error(Av_exception::DB_ERROR, $conn->ErrorMsg());
    }
    while (!$rs->EOF) {
        $sids[] = $rs->fields['id'];
        $rs->MoveNext();
    }
    return implode(',', $sids);
}
Beispiel #9
0
ossim_valid($level, OSS_LETTER, ',', OSS_NULLABLE, 'illegal:' . _('Level Param'));
/***************************
 ****** RESPONSE VARS ******
 ***************************/
// Response array
$response = array();
// Array to store data
$data = array();
$total_messages = 0;
try {
    // If validation errors throw new exception with error details
    if (ossim_error()) {
        Av_exception::throw_error(Av_exception::USER_ERROR, ossim_get_error_clean());
    }
    if (strlen($search_str) > 30) {
        Av_exception::throw_error(Av_exception::USER_ERROR, 'Search string very long. Max length 30 characters');
    }
    /*********************
     ****** Filters ******
     *********************/
    /**
     * Returns order_by string by column
     *
     * @param  integer  $order
     *
     * @return string
     */
    $order_by = function ($order) {
        switch ($order) {
            case 0:
                return 'creation_time';
Beispiel #10
0
function get_map_objects($conn, $map, $map_array = array(), $obj_array = array())
{
    $map_array[$map]++;
    $query = "select * from risk_indicators where name <> 'rect' AND map = UNHEX(?)";
    $rs4 = $conn->Execute($query, array($map));
    if (!$rs4) {
        Av_exception::write_log(Av_exception::DB_ERROR, $conn->ErrorMsg());
    } else {
        while (!$rs4->EOF) {
            //It's a map
            if (preg_match("/view\\.php\\?map\\=([a-fA-F0-9]*)/", $rs4->fields['url'], $found)) {
                if (!$map_array[$found[1]]) {
                    list($map_array, $obj_array) = get_map_objects($conn, $found[1], $map_array, $obj_array);
                }
            } else {
                if (!$obj_array[$rs4->fields['id']]) {
                    $obj_array[$rs4->fields['id']] = $rs4->fields;
                }
            }
            $rs4->MoveNext();
        }
    }
    return array($map_array, $obj_array);
}
$only_unread = POST('only_unread') ? POST('only_unread') : '';
/**********************************
 ****** VALIDATE POST PARAMS ******
 **********************************/
ossim_valid($search, OSS_INPUT, OSS_NULLABLE, 'illegal:' . _('Search String'));
ossim_valid($only_unread, OSS_LETTER, OSS_NULLABLE, 'illegal:' . _('Only Unread Param'));
/***************************
 ****** RESPONSE VARS ******
 ***************************/
// Response array
$response = array();
// Array to store data
$data = array();
try {
    if (ossim_error()) {
        Av_exception::throw_error(Av_exception::USER_ERROR, ossim_get_error_clean());
    }
    /**********************
     ****** FILTERS *******
     **********************/
    $filters = array();
    if (!empty($search)) {
        $filters['search'] = $search;
    }
    if (!empty($only_unread)) {
        $filters['only_unread'] = 'true';
    }
    /**********************
     ****** GET DATA ******
     **********************/
    $status = new System_notifications();
Beispiel #12
0
function import_assets_from_csv($filename, $iic, $ctx, $import_type)
{
    //Process status
    $summary = array('general' => array('status' => '', 'data' => '', 'statistics' => array('total' => 0, 'warnings' => 0, 'errors' => 0, 'saved' => 0)), 'by_nets' => array());
    $db = new ossim_db();
    $conn = $db->connect();
    $str_data = file_get_contents($filename);
    if ($str_data === FALSE) {
        $summary['general']['status'] = 'error';
        $summary['general']['data']['errors'] = _('Failed to read data from CSV file');
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    $array_data = preg_split('/\\n|\\r/', $str_data);
    foreach ($array_data as $k => $v) {
        if (trim($v) != '') {
            $data[] = explode('";"', trim($v));
        }
    }
    /******************************************************************************************************************
     * From net section:
     *  - Version 4.x.x or higher: "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 or higher: "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();
        $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;
        $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 or higher]
        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_ALL, '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 = sprintf(_("Error! The CIDR %s is not allowed. Please check with your account admin for more information"), $cidrs);
                                    $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 cannot 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 successfully imported');
        } else {
            $summary['general']['status'] = 'warning';
            $summary['general']['data'] = _('Some nets cannot be imported');
        }
        Util::disable_perm_triggers($conn, FALSE);
        try {
            Asset_net::report_changes($conn, 'nets');
        } 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'] = _('Nets cannot be imported');
        }
    }
    $db->close();
    return $summary;
}
ossim_valid($intent, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Intent"));
ossim_valid($directive_id, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Directive ID"));
ossim_valid($num_events, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Num Events"));
ossim_valid($num_events_op, OSS_ALPHA, OSS_NULLABLE, 'illegal:' . _("Num Events Operator"));
ossim_valid($tag, OSS_HEX, OSS_NULLABLE, 'illegal:' . _("Tag"));
ossim_valid($no_resolv, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("No Resolv"));
ossim_valid($hide_closed, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Hide Closed"));
ossim_valid($show_options, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Show Options"));
if (ossim_error()) {
    $response['sEcho'] = $sec;
    $response['iTotalRecords'] = 0;
    $response['iTotalDisplayRecords'] = 0;
    $response['aaData'] = '';
    $error = ossim_get_error();
    ossim_clean_error();
    Av_exception::write_log(Av_exception::USER_ERROR, $error);
    echo json_encode($response);
    exit;
}
if (empty($show_options) || ($show_options < 1 || $show_options > 4)) {
    $show_options = 1;
}
$db = new ossim_db(TRUE);
$conn = $db->connect();
$db_groups = Alarm_groups::get_dbgroups($conn);
$criteria = array('group_type' => $group_type, 'show_options' => $show_options, 'hide_closed' => $hide_closed, 'from_date' => $date_from, 'to_date' => $date_to, 'ip_src' => $src_ip, 'ip_dst' => $dst_ip, 'asset_group' => $asset_group, 'sensor' => $sensor_query, 'query' => $alarm_name, 'directive_id' => $directive_id, 'intent' => $intent, 'num_events' => $num_events, 'num_events_op' => $num_events_op, 'tag' => $tag, 'limit' => "LIMIT {$offset}, {$limit}");
list($alarm_group, $total) = Alarm_groups::get_grouped_alarms($conn, $criteria, TRUE);
$results = array();
foreach ($alarm_group as $group) {
    $res = array();
    $group_id = $group['group_id'];
                    $response['data']['components_added_msg'] = sprintf($msg, $num_components, $component_type);
                    break;
                    // Delete components
                // Delete components
                case 'delete_components':
                    $tag->remove_components_from_filter($conn);
                    $msg = _('Your label has been deleted from  %d %s(s). You can view asset labels in the asset details');
                    $response['data']['components_deleted_msg'] = sprintf($msg, $num_components, $component_type);
                    break;
                default:
                    Av_exception::throw_error(Av_exception::USER_ERROR, _('Invalid action - please try again'));
            }
        }
        $response['status'] = 'OK';
        $response['data']['id'] = $tag->get_id();
        $response['data']['name'] = $tag->get_name();
        $response['data']['class'] = $tag->get_class();
    } else {
        Av_exception::throw_error(Av_exception::USER_ERROR, _('Action can not be completed'));
    }
} catch (\Exception $e) {
    $error_msg = $e->getMessage();
    if (empty($error_msg)) {
        $error_msg = _('Sorry, operation was not completed due to an error when processing the request');
    }
    $response['status'] = 'error';
    $response['data'] = $error_msg;
}
$db->close();
echo json_encode($response);
exit;
function SIEM_trends_week($param = '')
{
    global $tz;
    $tzc = Util::get_tzc($tz);
    $data = array();
    $plugins = '';
    $plugins_sql = '';
    $db = new ossim_db(TRUE);
    $dbconn = $db->connect();
    $_asset_where = make_asset_filter();
    $asset_where = $_asset_where[1];
    $sensor_where = make_ctx_filter() . $asset_where;
    $tax_join = '';
    if (preg_match("/taxonomy\\=(.+)/", $param, $found)) {
        if ($found[1] == 'honeypot') {
            $tax_join = 'alienvault.plugin_sid p, ';
            $tax_where = 'AND acid_event.plugin_id = p.plugin_id AND acid_event.plugin_sid = p.sid AND p.category_id = 19';
        }
        $param = '';
    } elseif ($param == 'ossec%') {
        $plugins_sql = 'AND acid_event.plugin_id between 7000 and 7999';
        $plugins = '7000-7999';
    }
    $sqlgraph = "SELECT COUNT(acid_event.id) as num_events, day(convert_tz(timestamp,'+00:00','{$tzc}')) AS intervalo, monthname(convert_tz(timestamp,'+00:00','{$tzc}')) AS suf \n        FROM {$tax_join} alienvault_siem.acid_event \n        WHERE timestamp BETWEEN '" . gmdate("Y-m-d 00:00:00", gmdate("U") - 604800) . "' AND '" . gmdate("Y-m-d 23:59:59") . "' {$plugins_sql} {$sensor_where} {$tax_where} \n        GROUP BY suf, intervalo \n        ORDER BY suf, intervalo";
    if (!($rg =& $dbconn->CacheExecute($sqlgraph))) {
        Av_exception::write_log(Av_exception::DB_ERROR, $dbconn->ErrorMsg());
    } else {
        while (!$rg->EOF) {
            $hours = $rg->fields['intervalo'] . ' ' . substr($rg->fields['suf'], 0, 3);
            $data[$hours] = $rg->fields['num_events'];
            $rg->MoveNext();
        }
    }
    $db->close();
    return $param != '' ? array($data, $plugins) : $data;
}
Beispiel #16
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 #17
0
function do_scan($wizard)
{
    try {
        $next_step = 1;
        $data = array('finish' => FALSE);
        //File to cache scan object
        $user = Session::get_session_user();
        $scan_file = 'w_last_asset_object-' . md5($user);
        $step = intval($wizard->get_step_data('scan_step'));
        if ($step == 0) {
            @unlink($scan_file);
        }
        $obj = Av_scan::get_object_from_file($scan_file);
        if (!is_object($obj) || empty($obj)) {
            $nets = $wizard->get_step_data('scan_nets');
            if (count($nets) < 1) {
                $e_msg = _('Invalid networks selected to scan');
                Av_exception::throw_error(Av_exception::USER_ERROR, $e_msg);
            }
            $nets = implode(' ', $nets);
            $scan_options = array('scan_type' => 'fast', 'scan_timing' => 'T3', 'autodetect_os' => 'true', 'reverse_dns' => 'true', 'scan_ports' => '', 'idm' => 'false');
            $obj = new Av_scan($nets, 'local', $scan_options);
            $obj->run();
            Av_scan::set_object_in_file($obj, $scan_file);
        }
        $aux_status = $obj->get_status();
        $status = $aux_status['status']['code'];
        $total = $aux_status['number_of_targets'];
        switch ($status) {
            case Av_scan::ST_SEARCH_FINISHED:
            case Av_scan::ST_SCANNING_HOSTS:
            case Av_scan::ST_SCAN_FINISHED:
                $next_step = $total > 0 ? 2 : 3;
                $wizard->set_step_data('scan_hosts', $total);
                $data = array('finish' => TRUE);
                break;
        }
        $wizard->set_step_data('scan_step', $next_step);
        //error_log("Step: $step\n", 3, '/tmp/test_wizard');
        //error_log("Next Step: $next_step\n", 3, '/tmp/test_wizard');
        //error_log(var_export($aux_status, TRUE)."\n", 3, '/tmp/test_wizard');
        $response['error'] = FALSE;
        $response['data'] = $data;
        $wizard->save_status();
    } catch (Exception $e) {
        //error_log("Error: ".$e->getMessage()."\n", 3, '/tmp/test_wizard');
        $msg = _('Error! Asset scan cannot be completed.  Please try again');
        set_scan_error_message($wizard, $msg);
        $response['error'] = TRUE;
    }
    return $response;
}
Beispiel #18
0
*/
require_once 'av_init.php';
Session::admin_logcheck_ajax();
session_write_close();
/*
* This function retrieves the OTX config information.
*
* @return array
*
*/
function get_otx_info()
{
    $otx = new Otx();
    $otx->load();
    return array('token' => $otx->get_token(), 'username' => $otx->get_username(), 'user_id' => $otx->get_user_id(), 'contributing' => $otx->is_contributing(), 'key_version' => $otx->get_key_version(), 'latest_update' => $otx->get_latest_update());
}
//Checking the action to perform.
$action = POST('action');
$result = array();
try {
    switch ($action) {
        case 'info':
            $result = get_otx_info();
            break;
        default:
            Av_exception::throw_error(Av_exception::USER_ERROR, _('Invalid Action.'));
    }
} catch (Exception $e) {
    Util::response_bad_request($e->getMessage());
}
echo json_encode($result);
Beispiel #19
0
 function baseExecute($sql, $start_row = 0, $num_rows = -1, $die_on_error = true, $params = array())
 {
     if (preg_match("/\\s+(WHERE|AND)\\s+1\\s*=\\s*1\\s*\$/i", $sql)) {
         $sql = preg_replace("/(WHERE|AND)\\s+1\\s*=\\s*1\\s*\$/i", "", $sql);
     }
     global $debug_mode, $sql_trace_mode;
     /* ** Begin DB specific SQL fix-up ** */
     if ($this->DB_type == "mssql") {
         $sql = preg_replace("/''/i", "NULL", $sql);
     }
     $this->lastSQL = $sql;
     $limit_str = "";
     $cache_secs = preg_match("/FOUND_ROWS/i", $sql) ? -1 : $this->DB_memcache;
     //file_put_contents("/tmp/fr", "$cache_secs-$sql\n", FILE_APPEND);
     /* Check whether need to add a LIMIT / TOP / ROWNUM clause */
     if ($num_rows == -1) {
         // If we have $params we must force not-cache
         if ($this->DB_memcache > 0 && count($params) == 0) {
             $rs = new baseRS($this->DB->CacheExecute($cache_secs, $sql), $this->DB_type);
         } else {
             $rs = new baseRS($this->DB->Execute($sql, $params), $this->DB_type);
         }
     } else {
         if ($this->DB_type == "mysql" || $this->DB_type == "mysqli" || $this->DB_type == "mysqlt" || $this->DB_type == "maxsql") {
             //echo "Objeto DB:".var_dump($this->DB)."<br>";
             //echo "<br>EJECUTANDO($cache_secs): ".$sql . " LIMIT " . $start_row . ", " . $num_rows." en ".$this->DB_type."<br>";
             if ($this->DB_memcache > 0) {
                 $tmprow = $this->DB->CacheExecute($cache_secs, $sql . " LIMIT " . $start_row . ", " . $num_rows);
             } else {
                 $tmprow = $this->DB->Execute($sql . " LIMIT " . $start_row . ", " . $num_rows);
             }
             //print_r($_GET);
             //print_r($_SESSION);
             $rs = new baseRS($tmprow, $this->DB_type);
             $limit_str = " LIMIT " . $start_row . ", " . $num_rows;
             //echo "<br>ROW:";
             //var_dump($tmprow);
             //echo "<br>ERROR MSG: " . $this->baseErrorMessage(). "<br>";
         } else {
             if ($this->DB_type == "oci8") {
                 $rs = new baseRS($this->DB->Execute($sql), $this->DB_type);
                 $limit_str = " LIMIT " . $start_row . ", " . $num_rows;
             } else {
                 if ($this->DB_type == "postgres") {
                     $rs = new baseRS($this->DB->Execute($sql . " LIMIT " . $num_rows . " OFFSET " . $start_row), $this->DB_type);
                     $limit_str = " LIMIT " . $num_rows . " OFFSET " . $start_row;
                 } else {
                     if ($this->DB_memcache > 0) {
                         $rs = new baseRS($this->DB->CacheExecute($cache_secs, $sql), $this->DB_type);
                     } else {
                         $rs = new baseRS($this->DB->Execute($sql), $this->DB_type);
                     }
                     $i = 0;
                     while ($i < $start_row && $rs) {
                         if (!$rs->row->EOF) {
                             $rs->row->MoveNext();
                         }
                         $i++;
                     }
                 }
             }
         }
     }
     if ($sql_trace_mode > 0) {
         fputs($this->sql_trace, $sql . "{$limit_str}\n");
         fflush($this->sql_trace);
     }
     if ((!$rs || $this->baseErrorMessage() != "") && $die_on_error) {
         Av_exception::write_log(Av_exception::DB_ERROR, $this->DB->ErrorMsg());
         echo '</TABLE></TABLE></TABLE><CENTER><span style="font-size:11px;color:#555555"><B><br>' . gettext("Unable to query the database to retrieve some table information. Try fewer conditions.") . '</B></span></CENTER><script>$("#actions_link").prop("disabled",true);</script>';
         die;
     } else {
         return $rs;
     }
 }
Beispiel #20
0
        } else {
            foreach ($active_plugins[$asset_id_canonical] as $pdata) {
                $models = array();
                $versions = array();
                if ($pdata['vendor'] != '') {
                    try {
                        $models = Software::get_models_by_vendor($pdata['vendor']);
                    } catch (Exception $e) {
                        Av_exception::write_log(Av_exception::USER_ERROR, $e->getMessage());
                    }
                }
                if ($pdata['model'] != '') {
                    try {
                        $versions = Software::get_versions_by_model($pdata['vendor'] . ':' . $pdata['model']);
                    } catch (Exception $e) {
                        Av_exception::write_log(Av_exception::USER_ERROR, $e->getMessage());
                    }
                }
                $plugin_list[$asset_id][] = array('vendor' => $pdata['vendor'], 'model' => $pdata['vendor'] . ':' . $pdata['model'], 'version' => $pdata['vendor'] . ':' . $pdata['model'] . ':' . $pdata['version'], 'model_list' => $models, 'version_list' => $versions);
            }
        }
        $device_list[$asset_id] = array("name" => $host['name'], "ips" => Asset::format_to_print($host['ips']), "plugins" => $plugin_list[$asset_id]);
    }
} else {
    $empty_msg = _('There are no network devices found. Return to the asset discovery step by clicking back to either discover or add network devices.');
}
/*  Subtitle Texts */
$subtitle_1 = '';
$subtitle_2 = '';
if ($total == 1) {
    $subtitle_1 = _('During the asset discovery scan we found 1 network device on your network');
Beispiel #21
0
function delete_note($conn)
{
    $validate = array('note_id' => array('validation' => 'OSS_DIGIT', 'e_message' => 'illegal:' . _('Note ID')));
    $validation_errors = validate_form_fields('POST', $validate);
    if (is_array($validation_errors) && !empty($validation_errors)) {
        Av_exception::throw_error(Av_exception::USER_ERROR, _('Error! Note could not be deleted'));
    }
    $note_id = POST('note_id');
    $result = Notes::delete($conn, $note_id);
    if ($result == TRUE) {
        $data['msg'] = _('Note deleted successfully');
    } else {
        Av_exception::throw_error(Av_exception::USER_ERROR, _('Error! Note could not be deleted'));
    }
    return $data;
}
function check_deploy_status($conn, $wizard)
{
    $data = array();
    $os = $wizard->get_step_data('deploy_os');
    //Linux Deployment Status --> Apply Configuration
    if ($os == 'linux') {
        $sensor_id = get_sensor_id();
        $error_apply = FALSE;
        try {
            list($agentless_list, $al_total) = Ossec_agentless::get_list($conn, $sensor_id, ' AND status = 1');
            if ($al_total > 0) {
                Ossec_agentless::save_in_config($conn, $sensor_id, $agentless_list);
            }
            //Enabling agentless
            Ossec_control::execute_action($sensor_id, 'enable_al');
            //Restarting ossec
            Ossec_control::execute_action($sensor_id, 'restart');
            // Delete "/var/tmp/.reload_<sensor_id>" file in order to hide the "Apply Changes" button
            @unlink('/var/tmp/.reload_' . $sensor_id);
        } catch (Exception $e) {
            $error_apply = $e->getMessage();
        }
        //If there was an error applying the configuration we show the error
        if ($error_apply !== FALSE) {
            $error_apply_msg = _('Error Applying Agentless Configuration');
            set_scan_error_message($wizard, $error_apply_msg);
            Av_exception::write_log(Av_exception::USER_ERROR, $error_apply);
            $response['error'] = TRUE;
            return $response;
        }
        //If everything was right, the percent is 100% and the remaining is 0
        $data['finish'] = TRUE;
        $data['percent'] = 100;
        $data['remaining'] = 0;
        //Setting the deployment status to 3 --> Finished
        $wizard->set_step_data('deploy_step', 3);
    } elseif ($os == 'windows') {
        $jobs = $wizard->get_step_data('deploy_jobs');
        //If the array of jobs IDs is empty, we are finished
        if (!is_array($jobs) || count($jobs) == 0) {
            $data['finish'] = TRUE;
            $data['percent'] = 100;
            $data['remaining'] = 0;
            //Setting the deployment status to 3 --> Finished
            $wizard->set_step_data('deploy_step', 3);
        } else {
            $succes = 0;
            //Going through the jobs
            foreach ($jobs as $id => $job) {
                try {
                    //Getting the status of the job
                    $state = Welcome_wizard::current_jobs($job['job_id']);
                    if ($state['job_status'] == 'task-succeeded') {
                        //If it is success, we count it and we delete it from the jobs array
                        if ($state['job_result'][0] === TRUE) {
                            unset($jobs[$id]);
                            $succes++;
                        } elseif ($state['job_result'][0] === FALSE) {
                            unset($jobs[$id]);
                            Av_exception::write_log(Av_exception::USER_ERROR, $job['agent'] . ': ' . $state['job_result'][1]);
                        }
                    } elseif ($state['job_status'] == 'task-failed' || $state['job_status'] == 'task-revoked') {
                        unset($jobs[$id]);
                        $_msg = $job['agent'] . ': ' . _("Couldn't complete windows OSSEC agent deploy: ") . $state['job_status'];
                        Av_exception::write_log(Av_exception::USER_ERROR, $_msg);
                    }
                } catch (Exception $e) {
                    //In case of critical error we delete from the array to avoid loops
                    unset($jobs[$id]);
                    Av_exception::write_log(Av_exception::USER_ERROR, $job['agent'] . ': ' . $e->getMessage());
                }
            }
            //IF after checking the status, the array is empty, we are finished
            if (!is_array($jobs) || count($jobs) == 0) {
                $data['finish'] = TRUE;
                $data['percent'] = 100;
                $data['remaining'] = 0;
                //Setting the deployment status to 3 --> Finished
                $wizard->set_step_data('deploy_step', 3);
            } else {
                //Total number of host that were selected to be deployed
                $total = $wizard->get_step_data('deploy_total_ips');
                $total = $total < 1 ? 1 : $total;
                //Number of host left to be deployed --> Pending jobs
                $current = count($jobs);
                //Percentage of the remaining hosts
                $pending = $total - $current;
                $percent = round(100 * ($pending / $total));
                $data['finish'] = FALSE;
                $data['percent'] = $percent;
                $data['remaining'] = $current;
            }
            //Updating the number of host successfully deployed
            $deployed = $wizard->get_step_data('deploy_success');
            $deployed += $succes;
            $wizard->set_step_data('deploy_success', $deployed);
            //Updating the array of jobs left
            $wizard->set_step_data('deploy_jobs', $jobs);
        }
    }
    //Saving wizard status
    $wizard->save_status();
    $response['error'] = FALSE;
    $response['data'] = $data;
    return $response;
}
/**
* This function manages generic exceptions
*
* @param object  $e  Generic exception object
*
* @return void
*/
function av_exception_handler($e)
{
    require_once 'classes/av_exception.inc';
    Av_exception::display($e);
}
Beispiel #24
0
$conn = $db->connect();
switch ($action) {
    case 'track_usage_information':
        try {
            //Validate Token
            $token = POST('token');
            if (Token::verify('tk_tui', $token) == FALSE) {
                $t_error = Token::create_error_message();
                Av_exception::throw_error(Av_exception::USER_ERROR, $t_error);
            }
            if (Session::am_i_admin()) {
                $tui = intval(POST('tui'));
                $tui_status = $tui > 0 ? 1 : 0;
                $config = new Config();
                $config->update('track_usage_information', $tui_status);
                $client = new Alienvault_client();
                $tui_status = $tui > 0 ? TRUE : FALSE;
                $client->system()->set_telemetry($tui_status);
                $data['status'] = 'success';
                $data['data'] = _('Your changes have been saved');
            } else {
                Av_exception::throw_error(Av_exception::USER_ERROR, _('You do not have the correct permissions to configure this option. Please contact system administrator with any questions'));
            }
        } catch (Exception $e) {
            $db->close();
            Util::response_bad_request($e->getMessage());
        }
        break;
}
$db->close();
echo json_encode($data);
* along with this package; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA  02110-1301  USA
*
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
Session::logcheck("analysis-menu", "ControlPanelAlarms");
$q = strtolower(GET("q"));
ossim_valid($q, OSS_TEXT, 'illegal:' . _("Query"));
// Empty results when error in validation
if (ossim_error()) {
    exit;
}
$db = new ossim_db();
$conn = $db->connect();
$q = escape_sql($q, $conn);
$sql = "SELECT DISTINCT sid, plugin_id, name FROM plugin_sid WHERE lower(name) LIKE '%{$q}%';";
if (!($rs = $conn->Execute($sql))) {
    Av_exception::throw_error(Av_exception::DB_ERROR, $conn->ErrorMsg());
} else {
    while (!$rs->EOF) {
        echo $rs->fields["plugin_id"] . "-" . $rs->fields["sid"] . "###" . $rs->fields["name"] . "\n";
        $rs->MoveNext();
    }
}
Beispiel #26
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;
}
Beispiel #27
0
        }
        $asset_object = $class_name::get_object($conn, $asset_id);
        if (array_key_exists($order, $orders_by_columns)) {
            $order = $orders_by_columns[$order];
        } else {
            $order = "lr.risk";
        }
        // Property filter
        $filters = array('limit' => "{$from}, {$maxrows}", 'order_by' => "{$order} {$torder}");
        if ($search_str != '') {
            $search_str = escape_sql($search_str, $conn);
            $filters['where'] = 'p.name LIKE "%' . $search_str . '%"';
        }
        list($vulns, $total) = $asset_object->get_vulnerabilities($conn, '', $filters);
    } else {
        Av_exception::throw_error(Av_exception::USER_ERROR, _('Error retrieving information'));
    }
} catch (Exception $e) {
    $db->close();
    Util::response_bad_request($e->getMessage());
}
// DATA
$data = array();
foreach ($vulns as $_asset_id => $asset_vulns) {
    $_host_aux = Asset_host::get_object($conn, $_asset_id);
    foreach ($asset_vulns as $vuln) {
        $_host = $class_name == 'asset_host' ? $vuln['ip'] : $_host_aux->get_name() . " (" . $_host_aux->get_ips()->get_ips('string') . ")";
        $data[] = array(date("Y-m-d H:i:s", strtotime($vuln['date'])), $_host, $vuln['plugin'], $vuln['plugin_id'], $vuln['service'], Vulnerabilities::get_severity_by_risk($vuln['risk']));
    }
}
$response['sEcho'] = $sec;
Beispiel #28
0
$sm_perms = array('EventsHids', 'EventsHidsConfig');
$sensor_id = POST('sensor_id');
$agent_id = POST('agent_id');
$agent_ip = POST('agent_ip');
if (Session::menu_perms($m_perms, $sm_perms)) {
    try {
        ossim_valid($agent_id, OSS_DIGIT, 'illegal:' . _('Agent ID'));
        ossim_valid($sensor_id, OSS_HEX, 'illegal:' . _('Sensor ID'));
        if ($agent_ip != 'any') {
            ossim_valid($agent_ip, OSS_IP_CIDR_0, 'illegal:' . _('Agent IP'));
        }
        if (!ossim_error()) {
            $db = new ossim_db();
            $conn = $db->connect();
            if (!Ossec_utilities::is_sensor_allowed($conn, $sensor_id)) {
                Av_exception::throw_error(Av_exception::USER_ERROR, _('Error! Sensor not allowed'));
            }
            $db->close();
        }
        $more_info = Ossec_agent::get_info($sensor_id, $agent_id);
        $last_scan_dates = '';
        if (Asset_host_ips::valid_ip($agent_ip)) {
            $last_scan_dates = Ossec_agent::get_last_scans($sensor_id, $agent_ip);
        }
        if (is_array($more_info) && !empty($more_info)) {
            $syscheck_date = empty($last_scan_dates['syscheck']) ? $more_info[7] : $last_scan_dates['syscheck'];
            $rootcheck_date = empty($last_scan_dates['rootcheck']) ? $more_info[8] : $last_scan_dates['rootcheck'];
            ?>
            <table class='t_agent_mi'>
                <tr><td colspan='2' style='text-align: center;'><?php 
            echo _('Agent information');
function getSourceCoordYear($conn, $date_from = "", $date_to = "")
{
    $data = array();
    if ($date_from == "" || $date_to == "") {
        // Last Month by default
        $date_from = strftime("%Y-%m-%d", time() - 24 * 60 * 60 * 30);
        $date_to = strftime("%Y-%m-%d", time());
    }
    $tab = getSourceRepartitionYear($conn, $date_from, $date_to);
    if (is_array($tab)) {
        foreach ($tab as $pays => $volume) {
            $sql = "select distinct(g.nom),g.abs,g.ord from datawarehouse.geo g, datawarehouse.ip2country i where UPPER(g.pays)=UPPER(i.a2) and i.country = ?;";
            $rs = $conn->Execute($sql, array($pays));
            if (!$rs) {
                Av_exception::write_log(Av_exception::DB_ERROR, $conn->ErrorMsg());
                return $data;
            }
            $result = $rs->fields;
            if ($result['ord'] && $result['abs']) {
                array_push($data, array("nom" => $result['nom'], "abs" => $result['abs'], "ord" => $result['ord'], "volume" => $volume));
            }
        }
    }
    return $data;
}
Beispiel #30
-2
function submit_scan($SVRid, $job_name, $ssh_credential, $smb_credential, $schedule_type, $not_resolve, $user, $entity, $targets, $scheduled_status, $hosts_alive, $sid, $send_email, $timeout, $scan_locally, $dayofweek, $dayofmonth, $ROYEAR, $ROMONTH, $ROday, $time_hour, $time_min, $time_interval, $sched_id, $biyear, $bimonth, $biday, $nthweekday, $tz, $daysMap)
{
    $db = new ossim_db();
    $dbconn = $db->connect();
    $credentials = $ssh_credential . '|' . $smb_credential;
    $username = valid_hex32($entity) ? $entity : $user;
    if (empty($username)) {
        $username = Session::get_session_user();
    }
    $btime_hour = $time_hour;
    // save local time
    $btime_min = $time_min;
    $bbiyear = $biyear;
    $bbimonth = $bimonth;
    $bbiday = $biday;
    if ($schedule_type == 'O') {
        // date and time for run once
        if (empty($ROYEAR)) {
            $ROYEAR = gmdate('Y');
        }
        if (empty($ROMONTH)) {
            $ROMONTH = gmdate('m');
        }
        if (empty($ROday)) {
            $ROday = gmdate('d');
        }
        list($_y, $_m, $_d, $_h, $_u, $_s, $_time) = Util::get_utc_from_date($dbconn, "{$ROYEAR}-{$ROMONTH}-{$ROday} {$time_hour}:{$time_min}:00", $tz);
        $ROYEAR = $_y;
        $ROMONTH = $_m;
        $ROday = $_d;
        $time_hour = $_h;
        $time_min = $_u;
    } else {
        if (in_array($schedule_type, array('D', 'W', 'M', 'NW'))) {
            // date and time for Daily, Day of Week, Day of month, Nth weekday of month
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, "{$biyear}-{$bimonth}-{$biday} {$time_hour}:{$time_min}:00", $tz);
            $biyear = $b_y;
            $bimonth = $b_m;
            $biday = $b_d;
            $time_hour = $b_h;
            $time_min = $b_u;
        }
    }
    $resolve_names = $not_resolve == '1' ? 0 : 1;
    if ($schedule_type != 'N') {
        // current datetime in UTC
        $arrTime = explode(":", gmdate('Y:m:d:w:H:i:s'));
        $year = $arrTime[0];
        $mon = $arrTime[1];
        $mday = $arrTime[2];
        $wday = $arrTime[3];
        $hour = $arrTime[4];
        $min = $arrTime[5];
        $sec = $arrTime[6];
        $timenow = $hour . $min . $sec;
        $run_wday = $daysMap[$dayofweek]['number'];
        $run_time = sprintf('%02d%02d%02d', $time_hour, $time_min, '00');
        $run_mday = $dayofmonth;
        $time_value = "{$time_hour}:{$time_min}:00";
        $ndays = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        $begin_in_seconds = Util::get_utc_unixtime("{$biyear}-{$bimonth}-{$biday} {$time_hour}:{$time_min}:00") - 3600 * $tz;
        $current_in_seconds = gmdate('U');
        // current datetime in UTC
        if (strlen($bimonth) == 1) {
            $bimonth = '0' . $bimonth;
        }
        if (strlen($biday) == 1) {
            $biday = '0' . $biday;
        }
    }
    switch ($schedule_type) {
        case 'N':
            $requested_run = gmdate('YmdHis');
            break;
        case 'O':
            $requested_run = sprintf('%04d%02d%02d%06d', $ROYEAR, $ROMONTH, $ROday, $run_time);
            break;
        case 'D':
            if ($begin_in_seconds > $current_in_seconds) {
                $next_day = $biyear . $bimonth . $biday;
                // selected date by user
            } else {
                if ($run_time > $timenow) {
                    $next_day = $year . $mon . $mday;
                    // today
                } else {
                    $next_day = gmdate("Ymd", strtotime("+1 day GMT", gmdate("U")));
                    // next day
                }
            }
            $requested_run = sprintf("%08d%06d", $next_day, $run_time);
            break;
        case 'W':
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                $wday = date("w", mktime(0, 0, 0, $bimonth, $biday, $biyear));
                // make week day for begin day
                if ($run_wday == $wday) {
                    $next_day = $biyear . $bimonth . $biday;
                    // selected date by user
                } else {
                    $next_day = gmdate("Ymd", strtotime("next " . $ndays[$run_wday] . " GMT", mktime(0, 0, 0, $bimonth, $biday, $biyear)));
                }
            } else {
                if ($run_wday == $wday && $run_time > $timenow) {
                    $next_day = $year . $mon . $mday;
                    // today
                } else {
                    $next_day = gmdate("Ymd", strtotime("next " . $ndays[$run_wday] . " GMT", gmdate("U")));
                    // next week
                }
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})/", $next_day, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " {$btime_hour}:{$btime_min}:00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            break;
        case 'M':
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                if ($run_mday >= $biday) {
                    $next_day = $biyear . $bimonth . ($run_mday < 10 ? "0" : "") . $run_mday;
                    // this month
                } else {
                    $next_day = sprintf("%06d%02d", gmdate("Ym", strtotime("next month GMT", mktime(0, 0, 0, $bimonth, $biday, $biyear))), $run_mday);
                }
            } else {
                if ($run_mday > $mday || $run_mday == $mday && $run_time > $timenow) {
                    $next_day = $year . $mon . ($run_mday < 10 ? "0" : "") . $run_mday;
                    // this month
                } else {
                    $next_day = sprintf("%06d%02d", gmdate("Ym", strtotime("next month GMT", gmdate("U"))), $run_mday);
                }
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})/", $next_day, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " {$btime_hour}:{$btime_min}:00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            break;
        case 'NW':
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                $array_time = array('month' => $bbimonth, 'day' => $bbiday, 'year' => $bbiyear);
                $requested_run = weekday_month(strtolower($daysMap[$dayofweek]['text']), $nthweekday, $btime_hour, $btime_min, $array_time);
            } else {
                $requested_run = weekday_month(strtolower($daysMap[$dayofweek]['text']), $nthweekday, $btime_hour, $btime_min);
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/", $requested_run, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " " . $found[4] . ":" . $found[5] . ":00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            $dayofmonth = $nthweekday;
            break;
        default:
            break;
    }
    $insert_time = gmdate('YmdHis');
    if (!empty($_SESSION['_vuln_targets']) && count($_SESSION['_vuln_targets']) > 0) {
        $sgr = array();
        foreach ($_SESSION['_vuln_targets'] as $target_selected => $server_id) {
            $sgr[$server_id][] = $target_selected;
        }
        ossim_clean_error();
        unset($_SESSION['_vuln_targets']);
        // clean scan targets
        $resolve_names = $not_resolve == '1' ? 0 : 1;
        $queries = array();
        $bbimonth = strlen($bbimonth) == 1 ? '0' . $bbimonth : $bbimonth;
        $bbiday = strlen($bbiday) == 1 ? '0' . $bbiday : $bbiday;
        $qc = 0;
        if ($schedule_type == 'N') {
            foreach ($sgr as $notify_sensor => $target_list) {
                $target_list = implode("\n", $target_list);
                $params = array($job_name, $username, Session::get_session_user(), $schedule_type, $target_list, $hosts_alive, $sid, $send_email, $timeout, $SVRid, $insert_time, $requested_run, '3', 'S', $notify_sensor, $scan_locally, '', $resolve_names, $credentials);
                $queries[$qc]['query'] = 'INSERT INTO vuln_jobs ( name, username, fk_name, meth_SCHED, meth_TARGET,  meth_CRED,
                    meth_VSET, meth_Wfile, meth_TIMEOUT, scan_ASSIGNED,
                    scan_SUBMIT, scan_next, scan_PRIORITY, status, notify, authorized, author_uname, resolve_names, credentials )
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
                $queries[$qc]['params'] = $params;
                $qc++;
            }
        } else {
            $params = array($bbiyear . $bbimonth . $bbiday, $job_name, $username, Session::get_session_user(), $schedule_type, $dayofweek, $dayofmonth, $time_value, implode("\n", $targets), $hosts_alive, $sid, $send_email, $scan_locally, $timeout, $requested_run, $insert_time, strval($scheduled_status), $resolve_names, $time_interval, '', $credentials, $SVRid);
            $queries[$qc]['query'] = 'INSERT INTO vuln_job_schedule ( begin, name, username, fk_name, schedule_type, day_of_week, day_of_month, time, meth_TARGET, meth_CRED, meth_VSET, meth_Wfile,  meth_Ucheck, meth_TIMEOUT, next_CHECK, createdate, enabled, resolve_names, time_interval, IP_ctx, credentials, email)
                                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ';
            $queries[$qc]['params'] = $params;
            $qc++;
        }
        $execute_errors = array();
        foreach ($queries as $id => $sql_data) {
            $rs = $dbconn->execute($sql_data['query'], $sql_data['params']);
            if ($rs === FALSE) {
                $execute_errors[] = $dbconn->ErrorMsg();
            }
        }
        if (empty($execute_errors) && $schedule_type != 'N') {
            // We have to update the vuln_job_assets
            if (intval($sched_id) == 0) {
                $query = ossim_query('SELECT LAST_INSERT_ID() as sched_id');
                $rs = $dbconn->Execute($query);
                if (!$rs) {
                    Av_exception::throw_error(Av_exception::DB_ERROR, $dbconn->ErrorMsg());
                } else {
                    $sched_id = $rs->fields['sched_id'];
                }
            }
            Vulnerabilities::update_vuln_job_assets($dbconn, 'insert', $sched_id, 0);
        }
        $config_nt = array('content' => '', 'options' => array('type' => 'nf_success', 'cancel_button' => FALSE), 'style' => 'width: 40%; margin: 20px auto; text-align: center;');
        $config_nt['content'] = empty($execute_errors) ? _('Successfully Submitted Job') : _('Error creating scan job:') . implode('<br>', $execute_errors);
        $nt = new Notification('nt_1', $config_nt);
        $nt->show();
        $dbconn->close();
    }
}