Exemple #1
0
function delete_nfsen_source($data)
{
    if (!Session::am_i_admin()) {
        $return['error'] = TRUE;
        $return['msg'] = _('Action not authorized');
        return $return;
    }
    require_once '../sensor/nfsen_functions.php';
    $sensor = $data['sensor'];
    ossim_valid($sensor, OSS_ALPHA, 'illegal:' . _('Nfsen Source'));
    if (ossim_error()) {
        $info_error = _('Error') . ': ' . ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $info_error;
        return $return;
    }
    $res = delete_nfsen($sensor);
    if ($res['status'] == 'success') {
        $return['error'] = FALSE;
        $return['msg'] = _('Source deleted successfully');
        //To forcer load variables in session again
        unset($_SESSION['tab']);
    } else {
        $return['error'] = TRUE;
        $return['msg'] = $res['data'];
    }
    return $return;
}
function check_ossim_error()
{
    if (ossim_error()) {
        $error = ossim_get_error();
        ossim_clean_error();
        Av_exception::throw_error(Av_exception::USER_ERROR, $error);
    }
}
Exemple #3
0
function check_ossim_error($throw_excep = TRUE)
{
    if (ossim_error()) {
        $error = ossim_get_error();
        ossim_clean_error();
        if ($throw_excep) {
            Av_exception::throw_error(Av_exception::USER_ERROR, $error);
        } else {
            Util::response_bad_request($error);
        }
    }
}
function modify_plugingroup_plugin($conn, $data)
{
    $plugin_group = $data['plugin_group'];
    $plugin_id = $data['plugin_id'];
    $sids_str = $data['plugin_sids'];
    ossim_valid($plugin_id, OSS_DIGIT, 'illegal:' . _("Plugin ID"));
    ossim_valid($plugin_group, OSS_HEX, 'illegal:' . _("Plugin GroupID"));
    if (ossim_error()) {
        $info_error = "Error: " . ossim_get_error();
        ossim_clean_error();
        $return['error'] = true;
        $return['msg'] = $info_error;
        return $return;
    }
    $total_sel = 1;
    if (is_array($sids_str)) {
        $total_sel = count($sids_str);
        $sids_str = implode(',', $sids_str);
    }
    if ($sids_str !== '') {
        list($valid, $data) = Plugin_sid::validate_sids_str($sids_str);
        if (!$valid) {
            $return['error'] = true;
            $return['msg'] = _("Error for data source ") . $plugin_id . ': ' . $data;
            return $return;
        }
        if ($sids_str == "ANY") {
            $sids_str = "0";
        } else {
            $total = Plugin_sid::get_sidscount_by_id($conn, $plugin_id);
            $sids_str = $total_sel == $total ? "0" : $sids_str;
        }
        Plugin_group::edit_plugin($conn, $plugin_group, $plugin_id, $sids_str);
    }
    $return['error'] = false;
    $return['output'] = '';
    return $return;
}
function modify_deploy_hosts($wizard, $data)
{
    $os = $data['os'];
    $hosts = $data['hosts'];
    $username = $data['username'];
    $password = $data['password'];
    $domain = $data['domain'];
    ossim_valid($os, "windows|linux", 'illegal:' . _('Deploy Option'));
    ossim_valid($hosts, OSS_HEX, 'illegal:' . _('Host'));
    ossim_valid($username, OSS_USER_2, 'illegal:' . _('Username'));
    ossim_valid($password, OSS_PASSWORD, 'illegal:' . _('Password'));
    ossim_valid($domain, OSS_NOECHARS, OSS_ALPHA, OSS_PUNC_EXT, OSS_NULLABLE, 'illegal:' . _('Domain'));
    if (ossim_error()) {
        $response['error'] = TRUE;
        $response['msg'] = ossim_get_error();
        ossim_clean_error();
        return $response;
    }
    $domain = $os == 'windows' ? $domain : '';
    //Encrypting password to save it in the object
    $pass_c = Util::encrypt($password, Util::get_system_uuid());
    //First we clean the deploy info stored in the object
    $wizard->clean_step_data();
    //Saving the info to achieve the deploy
    $wizard->set_step_data('deploy_os', $os);
    $wizard->set_step_data('deploy_username', $username);
    $wizard->set_step_data('deploy_password', $pass_c);
    $wizard->set_step_data('deploy_domain', $domain);
    $wizard->set_step_data('deploy_hosts', $hosts);
    //Setting the deploy step to 1 (Inicialized)
    $wizard->set_step_data('deploy_step', 1);
    //Saving wizard status
    $wizard->save_status();
    $response['error'] = FALSE;
    return $response;
}
Exemple #6
0
function draw_hosts_by_nets_os($conn, $data)
{
    global $empty_tree;
    $tree = array();
    $os = $data['os'];
    $id = $data['net'];
    ossim_valid($os, "windows|linux", 'illegal:' . _("Operating System"));
    ossim_valid($id, OSS_HEX, 'illegal:' . _("Network"));
    if (ossim_error()) {
        ossim_clean_error();
        return $empty_tree;
    }
    $prm = array('%"' . $os . '%');
    if ($id == '0') {
        $id_sql = ' AND n.id IS NULL';
    } else {
        $id_sql = ' AND n.id = UNHEX(?)';
        $prm[] = $id;
    }
    $sql = "SELECT DISTINCT hex(h.id) AS id , h.hostname AS name\n                FROM host_properties hp, host h\n                LEFT JOIN host_net_reference hn ON hn.host_id=h.id\n                LEFT JOIN net n ON n.id=hn.net_id\n                WHERE h.id=hp.host_id AND hp.property_ref=3 AND hp.value LIKE ? {$id_sql}";
    //Always cached
    $rs = $conn->CacheExecute($sql, $prm);
    if (!$rs || $rs->EOF) {
        return $empty_tree;
    }
    while (!$rs->EOF) {
        $tooltip = 'IPs: ' . Asset_host_ips::get_ips_to_string($conn, $rs->fields['id']);
        $_aux = array('key' => 'host_' . $rs->fields['id'], 'title' => $rs->fields['name'], 'isFolder' => FALSE, 'icon' => FALSE, 'type' => 'host', 'host_id' => $rs->fields['id'], 'tooltip' => $tooltip);
        $tree[] = $_aux;
        $rs->MoveNext();
    }
    return $tree;
}
function set_default_map($conn, $id)
{
    ossim_valid($id, OSS_HEX, 'illegal:' . _('Map'));
    if (ossim_error()) {
        $info_error = "Error: " . ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $info_error;
        return $return;
    }
    if (!is_map_editable($conn, $id)) {
        $return['error'] = TRUE;
        $return['msg'] = _("You do not have permission to edit this map");
        return $return;
    }
    $login = Session::get_session_user();
    $config = new User_config($conn);
    $config->set($login, "riskmap", $id, 'simple', "main");
    $return['error'] = FALSE;
    $return['msg'] = _("Default map changed successfully");
    return $return;
}
function draw_rss_url($widget_content = '')
{
    echo "\n\t\t<tr>\n\t\t\t<td class='nobborder' style='text-align:center;'><br>\n\t\t\t\t<div style='width:60%;margin:0 auto 0 auto;text-align:center;'>\n\t\t\t\t\t<strong>" . _('RSS Url') . ": </strong> <input style='width:250px' type='text' name='widget_content' id='widget_content' value='{$widget_content}'/>\n\t\t\t\t</div>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class='nobborder'><br></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class='nobborder' style='text-align:center;'>" . _('OR CHOOSE ONE OF THE FOLLOWING FEEDS') . ":</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class='nobborder'><br></td>\n\t\t</tr>";
    $feeds = array();
    $feeds_aux = array();
    $feeds_aux = file("../widgets/files/rss_feed_list.txt") or exit(_("Unable to get the RSS collection"));
    foreach ($feeds_aux as $f) {
        if (preg_match("/(^\\*)|(^\\W)/", $f)) {
            continue;
        }
        $feed = explode("####", trim($f));
        //Validation
        ossim_valid($feed[1], OSS_URL_ADDRESS, 'illegal:' . _("RSS Url"));
        ossim_valid($feed[0], OSS_TEXT, 'illegal:' . _("RSS Title"));
        if (ossim_error()) {
            ossim_clean_error();
            continue;
        }
        //End of validation
        $feeds[] = $feed;
    }
    echo "\n\t\t<tr>\n\t\t\t<td class='nobborder'>\n\t\t\t\t<div style='width:75%;margin:0 auto;padding-top:10px;'>\n\t\t\t\t\t<table width='100%' align='center' class='table_data'>\n\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t<th>" . _('Available RSS Feeds') . "</th>\n\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t<tbody>";
    $color = 0;
    foreach ($feeds as $feed) {
        $class = $color % 2 == 0 ? "lightgray" : "blank";
        echo "<tr class='{$class}' onclick='javascript:choose_option(\"" . $feed[1] . "\");'>\t\t\t\t\t\t\t\t\n\t\t\t\t<td class='td_report_name'>\n\t\t\t\t\t<a id='sel_{$color}' href='javascript:void(0);'>" . $feed[0] . "</a>\n\t\t\t\t</td>\n\t\t\t</tr>";
        $color++;
    }
    echo "\n\t\t\t\t\t</tbody>\n\t\t\t\t</table>\n\t\t\t</div>\n\t\t\t</td>\n\t\t</tr>";
    echo "\n\t\t<tr>\n\t\t\t<td class='nobborder'><br></td>\n\t\t</tr>";
}
Exemple #9
0
function schedule_scan($conn, $wizard, $data)
{
    $step = intval($wizard->get_step_data('scan_step'));
    $nets = $wizard->get_step_data('scan_nets');
    if ($step != 3 || count($nets) < 1) {
        $response['error'] = TRUE;
        $response['msg'] = _('Asset Scan not valid to schedule');
        return $response;
    }
    $sched = $data['sch_opt'];
    ossim_valid($sched, OSS_DIGIT, 'illegal:' . _("Schedule Option"));
    if (ossim_error()) {
        $response['error'] = TRUE;
        $response['msg'] = ossim_get_error();
        ossim_clean_error();
        $wizard->set_step_data('scan_nets', -1);
        return $response;
    }
    if ($sched == 1) {
        $period = 86400;
    } elseif ($sched == 2) {
        $period = 604800;
    } else {
        $period = 2419200;
    }
    $sensor_id = Av_sensor::get_default_sensor($conn);
    $name = _('Default_wizard_scan');
    $type = 5;
    $targets = array();
    foreach ($nets as $cidrs) {
        $cidrs = explode(' ', $cidrs);
        foreach ($cidrs as $cidr) {
            $targets[$cidr] = $cidr;
        }
    }
    $targets = implode(' ', $targets);
    $params = $targets . '#-T3 -A -sS -F';
    Inventory::insert($conn, $sensor_id, $name, $type, $period, $params, $targets);
    $response['error'] = FALSE;
    $response['data'] = array();
    return $response;
}
Exemple #10
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;
}
Exemple #11
0
function modify_device_host($conn, $data)
{
    $id = $data['id'];
    $type = $data['type'];
    $subtype = $data['subtype'];
    ossim_valid($id, OSS_HEX, 'illegal:' . _("Host ID"));
    ossim_valid($type, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Device Type"));
    ossim_valid($subtype, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Device Subtype"));
    if (ossim_error()) {
        $info_error = "Error: " . ossim_get_error();
        ossim_clean_error();
        $return['error'] = true;
        $return['msg'] = $info_error;
        return $return;
    }
    if (empty($type)) {
        $sql = "DELETE FROM host_types WHERE host_id = UNHEX(?)";
        $params = array($id);
    } else {
        $sql = "DELETE FROM host_types WHERE host_id = UNHEX(?)";
        $params = array($id);
        $conn->Execute($sql, $params);
        $sql = "REPLACE INTO host_types (host_id, type, subtype) VALUES (UNHEX(?), ?, ?)";
        $params = array($id, $type, $subtype);
    }
    if ($conn->Execute($sql, $params) === false) {
        $return['error'] = true;
        $return['msg'] = $conn->ErrorMsg();
    } else {
        Util::memcacheFlush(false);
        $return['error'] = false;
        $return['data'] = _('Device Property Modified Successfully');
    }
    return $return;
}
function build_crumb($data)
{
    Session::logcheck("dashboard-menu", "ControlPanelExecutiveEdit");
    $type = $data['type'];
    $step = $data['step'];
    $titles = array();
    $pro = Session::is_pro();
    ossim_valid($type, OSS_DIGIT, 'illegal:' . _("Breadcrumb"));
    ossim_valid($step, OSS_DIGIT, 'illegal:' . _("Step"));
    if (ossim_error()) {
        $info_error = "Error: " . ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $info_error;
        return $return;
    }
    switch ($type) {
        case 1:
            $titles = array(1 => utf8_encode(_("Select Type")), 2 => utf8_encode(_("Select Category")), 4 => utf8_encode(_("Customize Widget")), 5 => utf8_encode(_("Save Widget")));
            if ($pro) {
                $titles[3] = utf8_encode(_("Select Assets"));
            }
            break;
        case 2:
            $titles = array(1 => utf8_encode(_("Select Type")), 2 => utf8_encode(_("Insert Rss URL")), 4 => utf8_encode(_("Customize Widget")), 5 => utf8_encode(_("Save Widget")));
            break;
        case 3:
            $titles = array(1 => utf8_encode(_("Select Type")), 2 => utf8_encode(_("Insert Image URL")), 4 => utf8_encode(_("Customize Widget")), 5 => utf8_encode(_("Save Widget")));
            break;
        case 4:
            $titles = array(1 => utf8_encode(_("Select Type")), 2 => utf8_encode(_("Select Report")), 4 => utf8_encode(_("Customize Widget")), 5 => utf8_encode(_("Save Widget")));
            break;
        case 5:
            $titles = array(1 => utf8_encode(_("Select Type")), 2 => utf8_encode(_("Select OSSIM URL")), 4 => utf8_encode(_("Customize Widget")), 5 => utf8_encode(_("Save Widget")));
            break;
        case 6:
            $titles = array(1 => utf8_encode(_("Select Type")), 4 => utf8_encode(_("Customize Widget")), 5 => utf8_encode(_("Save Widget")));
            if ($pro) {
                $titles[3] = utf8_encode(_("Select Assets"));
            }
            break;
        case 7:
            $titles = array(1 => utf8_encode(_("Select Type")), 4 => utf8_encode(_("Customize Widget")), 5 => utf8_encode(_("Save Widget")));
            break;
    }
    $breadcrumb = "";
    ksort($titles);
    foreach ($titles as $i => $title) {
        if ($i > $step) {
            break;
        }
        if ($i == $step) {
            $class = "class='current'";
            $link = "#";
        } else {
            $class = "";
            $link = "wizard.php?backbc=1&step={$i}";
        }
        $breadcrumb .= "<li id='step{$i}' {$class}>\n\t\t\t\t\t\t\t<a href='{$link}'>" . $title . "</a>\n\t\t\t\t\t\t</li>";
    }
    $return['error'] = FALSE;
    $return['msg'] = $breadcrumb;
    return $return;
}
Exemple #13
0
function submit_scan($vuln_op, $sched_id, $sname, $notify_email, $schedule_type, $ROYEAR, $ROMONTH, $ROday, $time_hour, $time_min, $dayofweek, $dayofmonth, $timeout, $SVRid, $sid, $tarSel, $ip_list, $ip_exceptions_list, $ip_start, $ip_end, $named_list, $cidr, $subnet, $system, $cred_type, $credid, $acc, $domain, $accpass, $acctype, $passtype, $passstore, $wpolicies, $wfpolicies, $upolicies, $custadd_type, $cust_plugins, $is_enabled, $hosts_alive, $scan_locally, $nthweekday, $semail, $not_resolve, $time_interval, $biyear, $bimonth, $biday, $ssh_credential = "", $smb_credential = "")
{
    global $wdaysMap, $daysMap, $allowscan, $uroles, $username, $schedOptions, $adminmail, $mailfrom, $dbk, $dbconn;
    // credentials
    $credentials = $ssh_credential . "|" . $smb_credential;
    $btime_hour = $time_hour;
    // save local time
    $btime_min = $time_min;
    $bbiyear = $biyear;
    $bbimonth = $bimonth;
    $bbiday = $biday;
    $tz = Util::get_timezone();
    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 ($schedule_type == "D" || $schedule_type == "W" || $schedule_type == "M" || $schedule_type == "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;
        }
    }
    if ($not_resolve == "1") {
        $resolve_names = 0;
    } else {
        $resolve_names = 1;
    }
    $notify_email = str_replace(";", ",", $notify_email);
    $requested_run = "";
    $jobType = "M";
    $recurring = False;
    $targets = array();
    $time_value = "";
    $profile_desc = getProfileName($sid);
    $target_list = "";
    $need_authorized = "";
    $request = "";
    $plugs_list = "NULL";
    $fk_name = "NULL";
    $target_list = "NULL";
    $tmp_target_list = "";
    $jobs_names = array();
    $sjobs_names = array();
    $I3crID = "";
    if ($hosts_alive == "1") {
        // option: Only scan hosts that are alive
        $I3crID = "1";
    } else {
        $I3crID = "0";
    }
    // if ( $custadd_type == "" ) { $custadd_type = "N"; }
    // if ( $custadd_type != "N" && $cust_plugins != "" ) {
    // $plugs_list="";
    // $vals=preg_split( "/\s+|\r\n|,|;/", $cust_plugins );
    // foreach($vals as $v) {
    // $v=trim($v);
    // if ( strlen($v)>0 ) {
    // $plugs_list .= $v . "\n";
    // }
    // }
    // $plugs_list = "'".$plugs_list."'";
    // }
    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 = $wdaysMap[$dayofweek];
        $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 = mktime($bihour, $bimin, 0, $bimonth, $biday, $biyear);
        // selected datetime by user in UTC
        $current_in_seconds = mktime($hour, $min, 0, $mon, $mday, $year);
        // 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");
            $sched_message = "No reccurring Jobs Necessary";
            break;
        case "O":
            $requested_run = sprintf("%04d%02d%02d%06d", $ROYEAR, $ROMONTH, $ROday, $run_time);
            //error_log("O-> $requested_run\n" ,3,"/tmp/sched.log");
            $sched_message = "No reccurring Jobs Necessary";
            $recurring = True;
            $reccur_type = "Run Once";
            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;
                } else {
                    $next_day = gmdate("Ymd", strtotime("+1 day GMT", gmdate("U")));
                }
                // next day
            }
            $requested_run = sprintf("%08d%06d", $next_day, $run_time);
            //error_log("D-> $requested_run\n" ,3,"/tmp/sched.log");
            $recurring = True;
            $sched_message = "Schedule Reccurring";
            $reccur_type = "Daily";
            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 || $run_wday > $wday) {
                    $next_day = $year . $mon . $mday;
                } 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");
            //error_log("W-> $requested_run\n" ,3,"/tmp/sched.log");
            $recurring = True;
            $sched_message = "Schedule Reccurring";
            $reccur_type = "Weekly";
            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");
            //error_log("M-> $requested_run $begin_in_seconds $current_in_seconds\n" ,3,"/tmp/sched.log");
            $recurring = True;
            $sched_message = "Schedule Reccurring";
            $reccur_type = "Montly";
            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]), $nthweekday, $btime_hour, $btime_min, $array_time);
            } else {
                $requested_run = weekday_month(strtolower($daysMap[$dayofweek]), $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");
            //error_log("NW-> $requested_run\n" ,3,"/tmp/sched.log");
            $dayofmonth = $nthweekday;
            $recurring = True;
            $sched_message = "Schedule Reccurring";
            $reccur_type = "Nth weekday of the month";
            break;
        default:
            break;
    }
    $insert_time = gmdate("YmdHis");
    if (!empty($_SESSION["_vuln_targets"]) && count($_SESSION["_vuln_targets"]) > 0) {
        $arr_ctx = array();
        $sgr = array();
        foreach ($_SESSION["_vuln_targets"] as $target_selected => $server_id) {
            $sgr[$server_id][] = $target_selected;
            if (preg_match("/^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\/\\d{1,2}\$/i", $target_selected)) {
                $related_ctxs = array_values(Asset_net::get_id_by_ips($dbconn, $target_selected));
                if (is_array($related_ctxs) && count($related_ctxs) > 0) {
                    $arr_ctx[$target_selected] = key(array_shift($related_ctxs));
                }
            } else {
                if (preg_match("/^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\$/i", $target_selected)) {
                    $related_ctxs = array_values(Asset_host::get_id_by_ips($dbconn, $target_selected));
                    if (is_array($related_ctxs) && count($related_ctxs) > 0) {
                        $arr_ctx[$target_selected] = key(array_shift($related_ctxs));
                        // to assign a ctx for a IP
                    }
                } else {
                    if (valid_hostname($target_selected) || valid_fqdns($target_selected)) {
                        $filters = array('where' => "hostname like '{$target_selected}' OR fqdns like '{$target_selected}'");
                        $_hosts_data = Asset_host::get_basic_list($dbconn, $filters);
                        $host_list = $_hosts_data[1];
                        if (count($host_list) > 0) {
                            $first_host = array_shift($host_list);
                            $hips = explode(",", $first_host['ips']);
                            foreach ($hips as $hip) {
                                $hip = trim($hip);
                                $arr_ctx[$hip] = $first_host['ctx'];
                            }
                        }
                    }
                }
            }
        }
        ossim_clean_error();
        unset($_SESSION["_vuln_targets"]);
        // clean scan targets
        $query = array();
        $IP_ctx = array();
        foreach ($arr_ctx as $aip => $actx) {
            $IP_ctx[] = $actx . "#" . $aip;
        }
        if ($vuln_op == "editrecurring" && $sched_id > 0) {
            $query[] = "DELETE FROM vuln_job_schedule WHERE id='{$sched_id}'";
            $i = 1;
            foreach ($sgr as $notify_sensor => $targets) {
                $target_list = implode("\n", $targets);
                $target_list .= "\n" . implode("\n", $ip_exceptions_list);
                $query[] = "INSERT INTO vuln_job_schedule ( name, username, fk_name, job_TYPE, schedule_type, day_of_week, day_of_month, \n                            time, email, meth_TARGET, meth_CRED, meth_VSET, meth_CUSTOM, meth_CPLUGINS, meth_Wfile, \n                            meth_Ucheck, meth_TIMEOUT, next_CHECK, createdate, enabled, resolve_names, time_interval, IP_ctx, credentials) VALUES ( '{$sname}', '{$username}', '" . Session::get_session_user() . "', '{$jobType}',\n                            '{$schedule_type}', '{$dayofweek}', '{$dayofmonth}', '{$time_value}', '{$notify_sensor}', '{$target_list}',\n                            {$I3crID}, '{$sid}', '{$custadd_type}', {$plugs_list}, {$semail}, '{$scan_locally}',\n                            '{$timeout}', '{$requested_run}', '{$insert_time}', '1', '{$resolve_names}' ,'{$time_interval}', '" . implode("\n", $IP_ctx) . "', '{$credentials}') ";
                $sjobs_names[] = $sname . $i;
                $i++;
            }
        } elseif ($recurring) {
            $i = 1;
            foreach ($sgr as $notify_sensor => $targets) {
                $target_list = implode("\n", $targets);
                $target_list .= "\n" . implode("\n", $ip_exceptions_list);
                $query[] = "INSERT INTO vuln_job_schedule ( name, username, fk_name, job_TYPE, schedule_type, day_of_week, day_of_month, \n                                time, email, meth_TARGET, meth_CRED, meth_VSET, meth_CUSTOM, meth_CPLUGINS, meth_Wfile, \n                                meth_Ucheck, meth_TIMEOUT, scan_ASSIGNED, next_CHECK, createdate, enabled, resolve_names, time_interval, IP_ctx, credentials) VALUES ( '{$sname}', '{$username}', '" . Session::get_session_user() . "', '{$jobType}',\n                                '{$schedule_type}', '{$dayofweek}', '{$dayofmonth}', '{$time_value}', '{$notify_sensor}', '{$target_list}',\n                                {$I3crID}, '{$sid}', '{$custadd_type}', {$plugs_list}, {$semail}, '{$scan_locally}',\n                                '{$timeout}', '{$SVRid}', '{$requested_run}', '{$insert_time}', '1', '{$resolve_names}' , '{$time_interval}', '" . implode("\n", $IP_ctx) . "', '{$credentials}') ";
                $sjobs_names[] = $sname . $i;
                $i++;
            }
        } else {
            $i = 1;
            foreach ($sgr as $notify_sensor => $targets) {
                $target_list = implode("\n", $targets);
                $target_list .= "\n" . implode("\n", $ip_exceptions_list);
                $query[] = "INSERT INTO vuln_jobs ( name, username, fk_name, job_TYPE, meth_SCHED, meth_TARGET,  meth_CRED,\n                        meth_VSET, meth_CUSTOM, meth_CPLUGINS, meth_Wfile, meth_TIMEOUT, scan_ASSIGNED,\n                        scan_SUBMIT, scan_next, scan_PRIORITY, status, notify, authorized, author_uname, resolve_names, credentials ) VALUES ( '{$sname}',\n                        '{$username}', '" . Session::get_session_user() . "', '{$jobType}', '{$schedule_type}', '{$target_list}', {$I3crID}, '{$sid}', '{$custadd_type}', {$plugs_list},\n                         {$semail}, '{$timeout}', '{$SVRid}', '{$insert_time}', '{$requested_run}', '3',\n                        'S', '{$notify_sensor}', '{$scan_locally}', '" . implode("\n", $IP_ctx) . "', '{$resolve_names}' , '{$credentials}') ";
                // echo "$query1";
                // die();
                $jobs_names[] = $sname . $i;
                $i++;
            }
        }
        $query_insert_time = gen_strtotime($insert_time, "");
        foreach ($query as $sql) {
            $error_updating = false;
            $error_inserting = false;
            if ($dbconn->execute($sql) === false) {
                echo _("Error creating scan job") . ": " . $dbconn->ErrorMsg();
                if ($vuln_op == "editrecurring") {
                    $error_updating = true;
                } else {
                    $error_creating = true;
                }
            } else {
                $config_nt = array('content' => "", 'options' => array('type' => "nf_success", 'cancel_button' => false), 'style' => 'width: 40%; margin: 20px auto; text-align: center;');
                if ($vuln_op == "editrecurring" && !$error_updating) {
                    $config_nt["content"] = _("Successfully Updated Recurring Job");
                    $nt = new Notification('nt_1', $config_nt);
                    $nt->show();
                } elseif (!$error_creating) {
                    $config_nt["content"] = _("Successfully Submitted Job");
                    $nt = new Notification('nt_1', $config_nt);
                    $nt->show();
                    //logAccess( "Submitted Job [ $jid ] $request" );
                    foreach ($jobs_names as $job_name) {
                        $infolog = array($job_name);
                        Log_action::log(66, $infolog);
                    }
                    foreach ($sjobs_names as $job_name) {
                        $infolog = array($job_name);
                        Log_action::log(67, $infolog);
                    }
                } else {
                    echo "<br><center>" . _("Failed Job Creation") . "</center>";
                }
                ?>
                <script type="text/javascript">
                //<![CDATA[                    
                document.location.href='<?php 
                echo Menu::get_menu_url(AV_MAIN_PATH . '/vulnmeter/manage_jobs.php', 'environment', 'vulnerabilities', 'scan_jobs');
                ?>
'; 
                //]]>
                </script>
                <?php 
            }
        }
    }
    // count($_SESSION["_vuln_targets"])>0
    echo "</b></center>";
}
Exemple #14
0
function delete_alarm($conn, $data)
{
    $id = $data['id'];
    //Validating ID before closing the alarm
    ossim_valid($id, OSS_HEX, 'illegal:' . _("Backlog ID"));
    if (ossim_error()) {
        $info_error = "Error: " . ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $info_error;
        return $return;
    }
    //Opening the alarm
    Alarm::delete_backlog($conn, $id);
    $return['error'] = FALSE;
    $return['msg'] = _('Alarm deleted successfully');
    return $return;
}
Exemple #15
0
function delete_engine($conn, $data)
{
    $id = $data['engine'];
    ossim_valid($id, OSS_HEX, 'illegal:' . _('Engine ID'));
    if (ossim_error()) {
        $info_error = _('Error') . ': ' . ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $info_error;
        return $return;
    }
    if ($id == Session::get_default_engine($conn)) {
        $return['error'] = TRUE;
        $return['msg'] = _('It is not allowed to delete the default engine');
        return $return;
    }
    $contexts = Acl::get_contexts_by_engine($conn, $id);
    if (count($contexts) > 0) {
        $return['error'] = TRUE;
        $return['msg'] = _('There are contexts asociated to this engine. You are not allowed to delete this engine');
        return $return;
    }
    Acl::delete_entities($conn, $id);
    Alarm::delete_from_taxonomy($conn, $id);
    $id = Util::uuid_format($id);
    if (is_dir(_MAIN_PATH . "/{$id}")) {
        Directive_editor::remove_engine($id);
    }
    Web_indicator::set_on('Reload_servers');
    $return['error'] = FALSE;
    $return['data'] = '';
    return $return;
}
function insert_link($conn, $data)
{
    $new_linkname = $data['link'];
    $id_document = $data['id'];
    $link_type = $data['type'];
    ossim_valid($link_type, OSS_INPUT, 'Illegal:' . _('Link Type'));
    ossim_valid($id_document, OSS_DIGIT, 'Illegal:' . _('Document ID'));
    switch ($link_type) {
        case 'directive':
            ossim_valid($new_linkname, OSS_DIGIT, 'illegal:' . _('Directive'));
            break;
        case 'incident':
            ossim_valid($new_linkname, OSS_DIGIT, 'illegal:' . _('Incident ID'));
            break;
        case 'plugin_sid':
            $plugin = explode('##', $new_linkname);
            ossim_valid($plugin[0], OSS_DIGIT, 'illegal:' . _('Plugin SID'));
            ossim_valid($plugin[1], OSS_DIGIT, 'illegal:' . _('Plugin ID'));
            break;
        case 'host':
        case 'host_group':
        case 'net':
        case 'net_group':
            ossim_valid($new_linkname, OSS_HEX, 'illegal:' . _('Asset ID'));
            break;
        case 'taxonomy':
            $tax = explode('##', $new_linkname);
            ossim_valid($tax[0], OSS_DIGIT, 'illegal:' . _('Product Type'));
            ossim_valid($tax[1], OSS_DIGIT, 'illegal:' . _('Category'));
            ossim_valid($tax[2], OSS_DIGIT, 'illegal:' . _('Subcategory'));
            break;
        default:
            $return['error'] = TRUE;
            $return['msg'] = _('Invalid Link Type');
            return $return;
    }
    if (ossim_error()) {
        $info_error = _('Error') . ': ' . ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $info_error;
        return $return;
    }
    $result = Repository::insert_relationships($conn, $id_document, $link_type, $new_linkname);
    if (!empty($result)) {
        $return['error'] = TRUE;
        $return['msg'] = $result;
        return $return;
    }
    if ($link_type == 'plugin_sid') {
        $result = Repository::insert_snort_references($conn, $id_document, $plugin[1], $plugin[0]);
        if (!empty($result)) {
            $return['error'] = TRUE;
            $return['msg'] = $result;
            return $return;
        }
    }
    $info_item['key'] = $new_linkname;
    $info_item['id'] = $id_document;
    $info_item['type'] = $link_type;
    $item_html = build_item_list($conn, $info_item);
    $return['error'] = FALSE;
    $return['data'] = $item_html;
    $return['msg'] = _('Link inserted successfully');
    return $return;
}
function change_disable_option($data)
{
    $panel = $data['panel'];
    $user = $data['user'];
    ossim_valid($panel, OSS_DIGIT, 'illegal:' . _("Tab"));
    ossim_valid($user, OSS_USER, 'illegal:' . _("User"));
    if (ossim_error()) {
        $info_error = "Error: " . ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $info_error;
        return $return;
    }
    if (!get_user_valid($user)) {
        $return['error'] = TRUE;
        $return['msg'] = _('You do not have permission to modify this tab');
        return $return;
    }
    try {
        $tab = new Dashboard_tab($panel, $user);
        $tab->set_visible(1 - intval($tab->is_visible()));
        $tab->save_db();
    } catch (Exception $e) {
        $return['error'] = TRUE;
        $return['msg'] = $e->getMessage();
        return $return;
    }
    $return['error'] = FALSE;
    $return['msg'] = _("Visibility Option Changed Successfully");
    return $return;
}
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;
}
Exemple #19
0
function import_assets_csv($filename)
{
    require_once 'classes/Util.inc';
    $response = array();
    $db = new ossim_db();
    $conn = $db->connect();
    if (($content = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) == false) {
        $response['file_errors'] = "Failed to read file";
        $response['status'] = false;
        return $response;
    } else {
        foreach ($content as $k => $v) {
            $data[] = explode(";", $v);
        }
    }
    $cont = 0;
    ini_set('max_execution_time', 180);
    ids_valid($data);
    if (count($data) <= 0) {
        $response['file_errors'] = _("Incompatible file format");
        $response['status'] = false;
        return $response;
    }
    $allowed_sensors = Session::allowedSensors();
    if (!empty($allowed_sensors)) {
        $my_allowed_sensors = explode(',', $allowed_sensors);
    } else {
        $response['file_errors'] = _("You need at least one sensor assigned");
        $response['status'] = false;
        return $response;
    }
    foreach ($data as $k => $v) {
        $response['status'] = true;
        $response['read_line'] = $cont;
        $cont++;
        if (count($v) != 8) {
            $response['line_errors'][$cont][] = array("Line", _("Format not allowed"));
            $response['status'] = false;
        }
        $param = array();
        foreach ($v as $i => $field) {
            $parameter = trim($field);
            $pattern = '/^\\"|\\"$|^\'|\'$/';
            $param[] = preg_replace($pattern, '', $parameter);
        }
        //IP
        if (!ossim_valid($param[0], OSS_IP_ADDR, 'illegal:' . _("IP"))) {
            $response['line_errors'][$cont][] = array("IP", ossim_get_error_clean());
            $response['status'] = false;
        }
        //Hostname
        if (empty($param[1])) {
            $param[1] = $param[0];
        } else {
            if (!ossim_valid($param[1], OSS_SCORE, OSS_ALPHA, OSS_PUNC, 'illegal:' . _("Hostname"))) {
                $response['line_errors'][$cont][] = array("Hostname", ossim_get_error_clean());
                $response['status'] = false;
                ossim_clean_error();
            }
        }
        //FQDNs
        if (!empty($param[2])) {
            $fqdns_list = explode(",", $param[2]);
            foreach ($fqdns_list as $k => $fqdn) {
                if (!ossim_valid(trim($fqdn), OSS_NULLABLE, OSS_ALPHA, OSS_PUNC, 'illegal:' . _("FQDN/Aliases"))) {
                    $response['line_errors'][$cont][] = array("FQDN/Aliases", ossim_get_error_clean());
                    $response['status'] = false;
                    ossim_clean_error();
                }
            }
        }
        //Description
        if (!ossim_valid($param[3], OSS_NULLABLE, OSS_SCORE, OSS_ALPHA, OSS_PUNC, OSS_AT, 'illegal:' . _("Description"))) {
            $response['line_errors'][$cont][] = array("Description", ossim_get_error_clean());
            $response['status'] = false;
            ossim_clean_error();
        }
        //Asset
        if ($param[4] == '') {
            $param[4] = 2;
        } else {
            if (!ossim_valid($param[4], OSS_NULLABLE, OSS_DIGIT, 'illegal:' . _("Asset value"))) {
                $response['line_errors'][$cont][] = array("Asset", ossim_get_error_clean());
                $response['status'] = false;
                ossim_clean_error();
            }
        }
        //NAT
        if (!ossim_valid($param[5], OSS_NULLABLE, OSS_IP_ADDR, 'illegal:' . _("NAT"))) {
            $response['line_errors'][$cont][] = array("NAT", ossim_get_error_clean());
            $response['status'] = false;
            ossim_clean_error();
        }
        //Sensors
        $sensors = array();
        if (!empty($param[6])) {
            $sensor_name = array();
            $list = explode(",", $param[6]);
            $sensors_list = array_intersect($list, $my_allowed_sensors);
            if (!empty($sensors_list)) {
                foreach ($sensors_list as $sensor) {
                    $sensors[] = Sensor::get_sensor_name($conn, $sensor);
                }
            } else {
                $response['line_errors'][$cont][] = array("Sensors", _("You need at least one allowed Sensor"));
                $response['status'] = false;
                ossim_clean_error();
            }
        } else {
            $response['line_errors'][$cont][] = array("Sensors", _("Column Sensors is empty"));
            $response['status'] = false;
            ossim_clean_error();
        }
        $list_os = array("Windows", "Linux", "FreeBSD", "NetBSD", "OpenBSD", "MacOS", "Solaris", "Cisco", "AIX", "HP-UX", "Tru64", "IRIX", "BSD/OS", "SunOS", "Plan9", "IPhone");
        //Operating System
        if (!empty($param[7]) && !in_array($param[7], $list_os)) {
            $param[7] = "Unknown";
        }
        if ($response['status'] == true) {
            //Parameters
            $ip = $param[0];
            $hostname = $param[1];
            $asset = $param[4];
            $threshold_c = 30;
            $threshold_a = 30;
            $rrd_profile = "";
            $alert = 0;
            $persistence = 0;
            $nat = $param[5];
            $descr = $param[3];
            $os = $param[7];
            $fqdns = $param[2];
            $latitude = '';
            $longitude = '';
            $icon = 0;
            if (!Host::in_host($conn, $ip)) {
                Host::insert($conn, $ip, $hostname, $asset, $threshold_c, $threshold_a, $rrd_profile, $alert, $persistence, $nat, $sensors, $descr, $os, $mac, $mac_vendor, $latitude, $longitude, $fqdns, $icon);
            } else {
                Host::update($conn, $ip, $hostname, $asset, $threshold_c, $threshold_a, $rrd_profile, $alert, $persistence, $nat, $sensors, $descr, $os, $mac, $mac_vendor, $latitude, $longitude, $fqdns, $icon);
            }
        }
    }
    $response['read_line'] = $cont;
    return $response;
}
function get_subcategories($conn, $data)
{
    $ctx = empty($data['ctx']) ? Session::get_default_ctx() : $data['ctx'];
    $id = $data['id'];
    ossim_valid($ctx, OSS_HEX, 'illegal:' . _("CTX"));
    ossim_valid($id, OSS_HEX, OSS_NULLABLE, 'illegal:' . _("Category ID"));
    if (ossim_error()) {
        $info_error = "Error: " . ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $info_error;
        return $return;
    }
    $result = "<option value='0' selected='selected'>" . _("ANY") . "</option>";
    $query = "SELECT id, name FROM subcategory where cat_id = ?";
    $params = array($id);
    if (!($rs =& $conn->Execute($query, $params))) {
        $return['error'] = TRUE;
        $return['msg'] = $conn->ErrorMsg();
        return $return;
    } else {
        while (!$rs->EOF) {
            $result .= "<option value='" . $rs->fields["id"] . "'>" . $rs->fields["name"] . "</option>\n";
            $rs->MoveNext();
        }
    }
    $return['error'] = FALSE;
    $return['data'] = $result;
    return $return;
}
Exemple #21
0
function validate_parameter($type, $parameter)
{
    $res = TRUE;
    ossim_clean_error();
    switch ($type) {
        case 'date':
            ossim_valid($parameter, OSS_DATE, 'illegal:' . _('Date'));
            if (ossim_error()) {
                $res = _('Invalid Date-time. Format allowed: YYYY-MM-DD');
            }
            break;
        case 'year':
            if ($parameter > 1970 && $parameter < 3000) {
                $res = _('Invalid Year. Format allowed: YYYY [1970-3000]');
            }
        case 'month':
            if ($parameter > 0 && $parameter < 13) {
                $res = _('Invalid Month. Format allowed: MM [00-12]');
            }
            break;
    }
    return $res;
}
function save_filter($conn, $filters, $data)
{
    //Getting the number of filters to be applied of the group
    $cont = $filters->get_num_filter_added();
    //We need at least one, otherwise we show an error.
    if ($cont < 1) {
        $return['error'] = TRUE;
        $return['msg'] = _('At least one filter needed');
        return $return;
    }
    $name = utf8_decode($data['name']);
    $descr = utf8_decode($data['descr']);
    ossim_valid($name, OSS_NOECHARS, OSS_ALPHA, OSS_PUNC, 'illegal:' . _('Group Name'));
    ossim_valid($descr, OSS_ALPHA, OSS_NULLABLE, OSS_PUNC, OSS_AT, OSS_NL, 'illegal:' . _('Description'));
    if (ossim_error()) {
        $response['error'] = TRUE;
        $response['msg'] = ossim_get_error();
        ossim_clean_error();
        return $response;
    }
    //Trying to save the filters, in case of error an exception will arise
    try {
        $new_id = Util::uuid();
        $ctx = Session::get_default_ctx();
        $group = new Asset_group($new_id);
        $group->set_name($name);
        $group->set_descr($descr);
        $group->set_ctx($ctx);
        $group->save_in_db($conn);
        $group->save_assets_from_search($conn);
        $filters->empty_filter_search($conn);
        $return['error'] = FALSE;
        $return['id'] = $new_id;
        $return['msg'] = 'ok';
        Asset_filter_list::delete_filters_from_session();
    } catch (Exception $e) {
        $return['error'] = TRUE;
        $return['msg'] = $e->getMessage();
    }
    return $return;
}
Exemple #23
0
*
*/
/*
*
* <-------------------------   BODY OF THE SCRIPT   -------------------------> 
*
*/
$action = POST("action");
//Action to perform.
$data = POST("data");
//Data related to the action.
ossim_valid($action, OSS_INPUT, 'illegal:' . _("Action"));
if (ossim_error()) {
    $response['error'] = TRUE;
    $response['msg'] = ossim_get_error();
    ossim_clean_error();
    echo json_encode($response);
    die;
}
//Default values for the response.
$response['error'] = TRUE;
$response['msg'] = _('Error when processing the request');
//checking if it is an ajax request
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    //Checking token
    if (!Token::verify('tk_welcome_wizard', GET('token'))) {
        $response['error'] = TRUE;
        $response['msg'] = _('Invalid Action');
    } else {
        //Getting the object with the filters. Unserialize needed.
        $wizard = Welcome_wizard::get_instance();
function import_assets_from_csv($filename, $iic, $ctx, $import_type)
{
    //Process status
    $summary = array('general' => array('status' => '', 'data' => '', 'statistics' => array('total' => 0, 'warnings' => 0, 'errors' => 0, 'saved' => 0)), 'by_nets' => array());
    $db = new ossim_db();
    $conn = $db->connect();
    $str_data = file_get_contents($filename);
    if ($str_data === FALSE) {
        $summary['general']['status'] = 'error';
        $summary['general']['data']['errors'] = _('Failed to read data from CSV file');
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    $array_data = preg_split('/\\n|\\r/', $str_data);
    foreach ($array_data as $k => $v) {
        if (trim($v) != '') {
            $data[] = explode('";"', trim($v));
        }
    }
    set_time_limit(360);
    /*********************************************************************************************************************
     * From net section:
     *  - Version 4.x.x: "Netname"*;"CIDRs(CIDR1,CIDR2,...)"*;"Description";"Asset value"*;"Net ID"
     *  - Version 3.x.x: "Netname"*;"CIDRs(CIDR1,CIDR2,...)"*;"Description";"Asset value";"Sensors(Sensor1,Sensor2,...)"*
     *
     * From welcome wizard:
     *  - Version 4.x.x: "Netname"*;"CIDRs(CIDR1,CIDR2,...)"*;"Description"   
     *
     *********************************************************************************************************************/
    //Check file size
    if (count($data) <= 0 || count($data) == 1 && preg_match('/Netname/', $data[0][0])) {
        $summary['general']['status'] = 'error';
        $summary['general']['data'] = _('CSV file is empty');
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    //Check importation type and headers
    $csv_headers = array();
    if ($import_type == 'networks') {
        if (preg_match('/Net ID/', $data[0][4]) || preg_match('/Sensors/', $data[0][4])) {
            $csv_headers = array_shift($data);
        } else {
            $summary['general']['status'] = 'error';
            $summary['general']['data'] = _('Headers not found');
            $summary['general']['statistics']['errors'] = 1;
            return $summary;
        }
    }
    //Setting total nets to import
    $summary['general']['statistics']['total'] = count($data);
    //Allowed sensors
    $filters = array('where' => "acl_sensors.entity_id = UNHEX('{$ctx}')");
    $a_sensors = Av_sensor::get_basic_list($conn, $filters);
    $sensor_ids = array_keys($a_sensors);
    if (count($sensor_ids) == 0) {
        $summary['general']['status'] = 'error';
        $s_error_msg = Session::is_pro() ? _('There is no sensor for this context') : _('There is no sensor for this net');
        $summary['general']['data'] = $s_error_msg;
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    Util::disable_perm_triggers($conn, TRUE);
    foreach ($data as $k => $v) {
        //Clean previous errors
        ossim_clean_error();
        $num_line = $k + 1;
        //Set default status
        $summary['by_nets'][$num_line]['status'] = 'error';
        //Check file format
        $cnd_1 = $import_type == 'networks' && count($v) < 5;
        $cnd_2 = $import_type == 'welcome_wizard_nets' && count($v) < 3;
        if ($cnd_1 || $cnd_2) {
            $summary['by_nets'][$num_line]['errors']['Format'] = _('Number of fields is incorrect');
            $summary['general']['statistics']['errors']++;
            continue;
        }
        //Clean values
        $param = array();
        foreach ($v as $field) {
            $parameter = trim($field);
            $pattern = '/^\\"|\\"$|^\'|\'$/';
            $param[] = preg_replace($pattern, '', $parameter);
        }
        //Values
        $is_in_db = FALSE;
        $net_id = '';
        $name = $param[0];
        $cidrs = preg_replace("/[\n\r\t]+/", '', $param[1]);
        $descr = $param[2];
        $asset_value = $param[3] == '' ? 2 : intval($param[3]);
        $sensors = $sensor_ids;
        //Permissions
        $can_i_create_assets = Session::can_i_create_assets();
        $can_i_modify_ips = TRUE;
        //CIDRs
        if (!ossim_valid($cidrs, OSS_IP_CIDR, 'illegal:' . _('CIDR'))) {
            $summary['by_nets'][$num_line]['errors']['CIDRs'] = ossim_get_error_clean();
            $summary['general']['statistics']['errors']++;
            continue;
        }
        //Check Net ID �Is there a net registered in the System?
        $net_ids = Asset_net::get_id_by_ips($conn, $cidrs, $ctx);
        $net_id = key($net_ids);
        if (!empty($net_id)) {
            $is_in_db = TRUE;
        } else {
            $net_id = Util::uuid();
        }
        // Special case: Forced Net ID [Version 4.x.x]
        if ($import_type == 'networks' && preg_match('/Net ID/', $csv_headers[4])) {
            $csv_net_id = strtoupper($param[4]);
            if ($is_in_db == TRUE && $csv_net_id != $net_id) {
                $id_error_msg = _('Net is already registered in the System with another Net ID');
                $summary['by_nets'][$num_line]['errors']['Net'] = $id_error_msg;
                $summary['general']['statistics']['errors']++;
                continue;
            }
        }
        //Netname
        if (!empty($iic)) {
            $name = clean_iic($name);
        }
        if (!ossim_valid($name, OSS_NOECHARS, OSS_NET_NAME, 'illegal:' . _('Netname'))) {
            ossim_clean_error();
            $name = clean_iic($name);
            $name = clean_echars($name);
            $warning_msg = _('Netname has invalid characters') . '<br/>' . _('Netname will be replaced by') . ": <strong>{$name}</strong>";
            $summary['by_nets'][$num_line]['warnings']['Netname'] = $warning_msg;
            $summary['by_nets'][$num_line]['status'] = 'warning';
            $summary['general']['statistics']['warnings']++;
            if (!ossim_valid($name, OSS_NOECHARS, OSS_NET_NAME, 'illegal:' . _('Netname'))) {
                unset($summary['by_nets'][$num_line]['warnings']);
                $summary['general']['statistics']['warnings']--;
                $summary['by_nets'][$num_line]['status'] = 'error';
                $summary['by_nets'][$num_line]['errors']['Netname'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
        }
        //Description
        if (!ossim_valid($descr, OSS_NULLABLE, OSS_AT, OSS_TEXT, '\\t', 'illegal:' . _('Description'))) {
            $summary['by_nets'][$num_line]['errors']['Description'] = ossim_get_error_clean();
            $summary['general']['statistics']['errors']++;
            continue;
        } else {
            if (mb_detect_encoding($descr . ' ', 'UTF-8,ISO-8859-1') == 'UTF-8') {
                $descr = mb_convert_encoding($descr, 'HTML-ENTITIES', 'UTF-8');
            }
        }
        //Sensor
        if ($is_in_db == FALSE) {
            //Only update net sensors with unregistered nets
            if ($import_type == 'networks' && preg_match('/Sensors/', $csv_headers[4])) {
                //Special case: Sensors in CSV file //[Version 3.x.x]
                $sensors = array();
                $_sensors = explode(',', $param[4]);
                if (is_array($_sensors) && !empty($_sensors)) {
                    $_sensors = array_flip($_sensors);
                    if (is_array($a_sensors) && !empty($a_sensors)) {
                        foreach ($a_sensors as $s_id => $s_data) {
                            if (array_key_exists($s_data['ip'], $_sensors)) {
                                $sensors[] = $s_id;
                            }
                        }
                    }
                }
                if (!is_array($sensors) || empty($sensors)) {
                    $s_error_msg = Session::is_pro() ? _('There is no sensors for this context') : _('There is no sensors for this IP');
                    $summary['by_nets'][$num_line]['errors']['Sensors'] = $s_error_msg;
                    $summary['general']['statistics']['errors']++;
                    continue;
                }
            }
        }
        /***********************************************************
         ********** Only for importation from net section **********
         ***********************************************************/
        if ($import_type == 'networks') {
            //Asset
            if (!ossim_valid($asset_value, OSS_DIGIT, 'illegal:' . _('Asset value'))) {
                $summary['by_nets'][$num_line]['errors']['Asset value'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
        }
        //Insert/Update net in database
        if (count($summary['by_nets'][$num_line]['errors']) == 0) {
            try {
                $net = new Asset_net($net_id);
                if ($is_in_db == TRUE) {
                    $net->load_from_db($conn, $net_id);
                    $can_i_modify_ips = Asset_net::can_i_modify_ips($conn, $net_id);
                } else {
                    if ($can_i_create_assets == FALSE) {
                        $n_error_msg = _('Net') . ' ' . $name . ' ' . _("not allowed. You don't have permissions to import this net");
                        $summary['by_nets'][$num_line]['errors']['Net'] = $n_error_msg;
                        $summary['general']['statistics']['errors']++;
                        continue;
                    }
                }
                //Check CIDRs
                if ($can_i_modify_ips == TRUE) {
                    $aux_cidr = explode(',', $cidrs);
                    foreach ($aux_cidr as $cidr) {
                        $net_ids = Asset_net::get_id_by_ips($conn, $cidr, $ctx);
                        unset($net_ids[$net_id]);
                        if (!empty($net_ids)) {
                            $c_error_msg = _('CIDR') . ' ' . $cidrs . ' ' . _("not allowed. CIDR {$cidr} already exists for this entity");
                            $summary['by_nets'][$num_line]['errors']['CIDRs'] = $c_error_msg;
                            $summary['general']['statistics']['errors']++;
                            break;
                        } else {
                            if (Session::get_net_where() != '') {
                                if (!Asset_net::is_cidr_in_my_nets($conn, $cidr, $ctx)) {
                                    $c_error_msg = _('CIDR') . ' ' . $cidrs . ' ' . _("not allowed. CIDR {$cidr} out of range. Check your asset filter");
                                    $summary['by_nets'][$num_line]['errors']['CIDRs'] = $c_error_msg;
                                    $summary['general']['statistics']['errors']++;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    $c_error_msg = _('Net') . ' ' . $name . ': ' . _("CIDRs not allowed. CIDRs wasn't be modified");
                    $summary['by_nets'][$num_line]['status'] = 'warning';
                    $summary['general']['warnings']['errors']++;
                    $summary['by_nets'][$num_line]['warnings']['CIDRs'] = $c_error_msg;
                }
                //Setting new values
                if (count($summary['by_nets'][$num_line]['errors']) == 0) {
                    $net->set_ctx($ctx);
                    $net->set_name($name);
                    $net->set_descr($descr);
                    if ($is_in_db == FALSE) {
                        if ($can_i_modify_ips == TRUE) {
                            $net->set_ips($cidrs);
                        }
                        $net->set_sensors($sensors);
                    }
                    $net->set_asset_value($asset_value);
                    $net->save_in_db($conn, FALSE);
                    $summary['general']['statistics']['saved']++;
                    $summary['by_nets'][$num_line]['data'] = $is_in_db == TRUE ? _('Net updated') : _('New new inserted');
                    //Keep warnings
                    if ($summary['by_nets'][$num_line]['status'] != 'warning') {
                        $summary['by_nets'][$num_line]['status'] = 'success';
                    }
                }
            } catch (Exception $e) {
                $summary['by_nets'][$num_line]['errors']['Database error'] = $e->getMessage();
                $summary['general']['statistics']['errors']++;
            }
        }
    }
    if ($summary['general']['statistics']['saved'] > 0) {
        if ($summary['general']['statistics']['errors'] == 0) {
            $summary['general']['status'] = 'success';
            $summary['general']['data'] = _('All nets have been imported successfully');
        } else {
            $summary['general']['status'] = 'warning';
            $summary['general']['data'] = _('Some nets could not be imported successfully');
        }
        Util::disable_perm_triggers($conn, FALSE);
        try {
            Asset_net::report_changes($conn, 'nets');
        } catch (Exception $e) {
            error_log($e->getMessage(), 0);
        }
    } else {
        $summary['general']['statistics']['errors'] = count($data);
        //CSV file is not empty, but all lines are wrong
        if (empty($summary['general']['status'])) {
            $summary['general']['status'] = 'error';
            $summary['general']['data'] = _('Nets could not be imported');
        }
    }
    $db->close();
    return $summary;
}
function delete_group($conn, $data)
{
    $groups = $data['groups'];
    //Validating parameters
    ossim_valid($groups, OSS_INPUT, 'illegal:' . _("Alarm Group IDs"));
    if (ossim_error()) {
        $info_error = "Error: " . ossim_get_error();
        ossim_clean_error();
        $return['error'] = TRUE;
        $return['msg'] = $info_error;
        return $return;
    }
    $params = array();
    $params['groups'] = "'" . implode("','", $groups) . "'";
    $user = Session::get_session_user();
    $file = Alarm_groups::delete_alarms_from_groups($conn, $params);
    $cmd = 'php /usr/share/ossim/scripts/alarms/bg_alarms.php ? ? > /dev/null 2>&1 &';
    $params = array($user, $file);
    Util::execute_command($cmd, $params);
    $return['error'] = FALSE;
    $return['data'] = '';
    return $return;
}
Exemple #26
-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();
    }
}