$_list_data = Asset_host::get_basic_list($conn);
     $_host_aux = array_keys($_list_data[1]);
     foreach ($_host_aux as $h_id) {
         $assets_aux[] = Util::uuid_format($h_id);
     }
     $_list_data = Asset_net::get_list($conn);
     $_net_aux = array_keys($_list_data[0]);
     foreach ($_net_aux as $n_id) {
         $assets_aux[] = Util::uuid_format($n_id);
     }
     $_GET["from_list"] = implode(",", $assets_aux);
 }
 if ((Session::get_host_where() != "" || Session::get_net_where() != "") && (GET('to') == "ANY" || GET('to_list') == "")) {
     $_GET["to"] = "LIST";
     $assets_aux = array();
     $_list_data = Asset_host::get_basic_list($conn);
     $_host_aux = array_keys($_list_data[1]);
     foreach ($_host_aux as $h_id) {
         $assets_aux[] = Util::uuid_format($h_id);
     }
     $_list_data = Asset_net::get_list($conn);
     $_net_aux = array_keys($_list_data[0]);
     foreach ($_net_aux as $n_id) {
         $assets_aux[] = Util::uuid_format($n_id);
     }
     $_GET["to_list"] = implode(",", $assets_aux);
 }
 if (GET("from") == "LIST") {
     $_GET["from"] = GET("from_list");
 }
 if (GET("port_from") == "LIST") {
Example #2
0
*/
require_once 'av_init.php';
Session::logcheck('report-menu', 'ReportsReportServer');
//Get assets from Session
$assets = '<table class="w100" cellspacing="0" cellpadding="0">';
$cnd_1 = $_SESSION['_user_vision']['host_where'] && !Session::only_ff_host();
$cnd_2 = $_SESSION['_user_vision']['net_where'] && !Session::only_ff_net();
if ($cnd_1 || $cnd_2) {
    $db = new ossim_db();
    $conn = $db->connect();
    $assets .= '<tr>
                    <td style="text-align:left;width:25mm;font-size:10px;color:#535353;" valign="top">' . "Assets Selected:" . '</td>
                    <td class="nobborder" style="padding-left:5px;font-size:10px" valign="top">
                        <table class="w100" cellpadding="0" cellspacing="0">';
    if ($_SESSION['_user_vision']['host_where'] && !Session::only_ff_host()) {
        $_host_list = Asset_host::get_basic_list($conn);
        $hosts = $_host_list[1];
        foreach ($hosts as $host) {
            $assets .= '<tr><td class="nobborder" style="text-align:left;" valign="top">' . _('Host') . ': ' . $host['name'] . ' [' . $host['ips'] . ']</td></tr>';
        }
    }
    if ($_SESSION['_user_vision']['net_where'] && !Session::only_ff_net()) {
        $nets = Asset_net::get_list($conn);
        $_net_list = Asset_net::get_list($conn);
        $nets = $_net_list[0];
        foreach ($nets as $net) {
            $assets .= '<tr><td class="nobborder" style="text-align:left;" valign="top">' . _('Net') . ': ' . $net['name'] . ' [' . $net['ips'] . ']</td></tr>';
        }
    }
    $assets .= '     </table>
                </td>
Example #3
0
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, $nthdayofweek, $nthweekday, $tz, $daysMap, $ip_exceptions_list)
{
    $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[$nthdayofweek]['text']), $nthweekday, $btime_hour, $btime_min, $array_time);
            } else {
                $requested_run = weekday_month(strtolower($daysMap[$nthdayofweek]['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;
            $dayofweek = $nthdayofweek;
            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_nets = array_values(Asset_net::get_closest_nets($dbconn, $target_selected));
                $firs_net = $related_nets[0];
                $closetnet_id = $firs_net['id'];
                if (valid_hex32($closetnet_id)) {
                    $arr_ctx[$target_selected] = Asset_net::get_ctx_by_id($dbconn, $closetnet_id);
                }
            } else {
                if (preg_match('/^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/i', $target_selected)) {
                    $closetnet_id = key(Asset_host::get_closest_net($dbconn, $target_selected));
                    if (valid_hex32($closetnet_id)) {
                        $arr_ctx[$target_selected] = Asset_net::get_ctx_by_id($dbconn, $closetnet_id);
                    }
                } 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
        $resolve_names = $not_resolve == '1' ? 0 : 1;
        $queries = array();
        $IP_ctx = array();
        foreach ($arr_ctx as $aip => $actx) {
            $IP_ctx[] = $actx . '#' . $aip;
        }
        $bbimonth = strlen($bbimonth) == 1 ? '0' . $bbimonth : $bbimonth;
        $bbiday = strlen($bbiday) == 1 ? '0' . $bbiday : $bbiday;
        // Delete scheduled jobs if "Inmeditely" scheduled method is selected
        if (isset($sched_id) && $sched_id > 0 && $schedule_type == 'N') {
            $query = 'DELETE FROM vuln_job_schedule WHERE id = ?';
            $params = array($sched_id);
            $rs = $dbconn->Execute($query, $params);
            if (!$rs) {
                Av_exception::throw_error(Av_exception::DB_ERROR, $conn->ErrorMsg());
            }
        }
        $qc = 0;
        if ($schedule_type == 'N') {
            foreach ($sgr as $notify_sensor => $target_list) {
                $target_list = !empty($ip_exceptions_list) ? implode("\n", $target_list) . "\n" . implode("\n", $ip_exceptions_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, implode("\n", $IP_ctx), $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, implode("\n", $IP_ctx), $credentials, $SVRid);
            if (isset($sched_id) && $sched_id > 0) {
                $queries[$qc]['query'] = 'UPDATE vuln_job_schedule SET 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 = ?
                        WHERE id = ?';
                $params[] = $sched_id;
                $queries[$qc]['params'] = $params;
                $qc++;
            } else {
                $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($conn);
    }
}
Example #4
0
function DisplayProcessing()
{
    global $self;
    global $ListNOption;
    global $TopNOption;
    global $OutputFormatOption;
    global $IPStatOption;
    global $IPStatOrder;
    global $LimitScale;
    require_once 'av_init.php';
    $geoloc = new Geolocation("/usr/share/geoip/GeoLiteCity.dat");
    $db_aux = new ossim_db();
    $conn_aux = $db_aux->connect();
    $aux_ri_interfaces = Remote_interface::get_list($conn_aux, "WHERE status = 1");
    $ri_list = $aux_ri_interfaces[0];
    $ri_total = $aux_ri_interfaces[1];
    $ri_data = array();
    if ($ri_total > 0) {
        foreach ($ri_list as $r_interface) {
            $ri_data[] = array("name" => $r_interface->get_name(), "id" => "web_interfaces", "target" => "_blank", "url" => $r_interface->get_ip());
        }
    }
    $type = $detail_opts['type'] == "flows" ? 0 : ($detail_opts['type'] == "packets" ? 1 : 2);
    if ($ri_total >= 0) {
        echo '<a name="processing"></a>';
    }
    $detail_opts = $_SESSION['detail_opts'];
    $process_form = $_SESSION['process_form'];
    ?>
    <table style='width:100%;margin-top:15px;margin-bottom:5px;border:none'><tr>
    <td class='nobborder'><b><?php 
    echo _("Netflow Processing");
    ?>
</b></td>
    <td class='noborder nfsen_menu'>
        <a href='javascript:lastsessions()'><?php 
    echo _("List last 500 sessions");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("2","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Src IPs");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("3","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Dst IPs");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("5","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Src Port");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("6","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Dst Port");
    ?>
</a> |
        &nbsp;<a href='javascript:launch("13","<?php 
    echo $type;
    ?>
")'><?php 
    echo _("Top 10 Proto");
    ?>
</a>
    </td></tr></table>


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

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

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

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


<?php 
    if (!array_key_exists('run', $_SESSION)) {
        return;
    }
    print "<div class='flowlist'>\n";
    $run = $_SESSION['run'];
    if ($run != null) {
        $filter = $process_form['filter'];
        if ($process_form['DefaultFilter'] != -1) {
            $cmd_opts['and_filter'] = $process_form['DefaultFilter'];
        }
        $cmd_opts['type'] = ($_SESSION['profileinfo']['type'] & 4) > 0 ? 'shadow' : 'real';
        $cmd_opts['profile'] = $_SESSION['profileswitch'];
        $cmd_opts['srcselector'] = implode(':', $process_form['srcselector']);
        #print "<pre>\n";
        $patterns = array();
        $replacements = array();
        $patterns[0] = '/(\\s*)([^\\s]+)/';
        $replacements[0] = "\$1<a href='#null' onClick='lookup(\"\$2\", this, event)' title='lookup \$2'>\$2</a>";
        // gets HAP4NfSens plugin id. returns -1 if HAP4NfSen is not installed.
        function getHAP4NfSenId()
        {
            $plugins = GetPlugins();
            for ($i = 0; $i < count($plugins); $i++) {
                $plugin = $plugins[$i];
                if ($plugin == "HAP4NfSen") {
                    return $i;
                }
            }
            return -1;
        }
        ClearMessages();
        $cmd_opts['args'] = "-T {$run}";
        $cmd_opts['filter'] = $filter;
        $titcol = get_tit_col($run);
        $cmd_out = nfsend_query("run-nfdump", $cmd_opts);
        if (!is_array($cmd_out)) {
            ShowMessages();
        } else {
            $conf = $GLOBALS["CONF"];
            $solera = $conf->get_conf("solera_enable", FALSE) ? true : false;
            $db = new ossim_db();
            $conn = $db->connect();
            $sensors = $hosts = $ossim_servers = array();
            $tz = Util::get_timezone();
            list($hosts, $host_ids) = Asset_host::get_basic_list($conn, array(), TRUE);
            $entities = Session::get_all_entities($conn);
            $_sensors = Av_sensor::get_basic_list($conn);
            foreach ($_sensors as $s_id => $s) {
                $sensors[$s['ip']] = $s['name'];
            }
            /*$hap4nfsen_id = getHAP4NfSenId();
                    	        if ($hap4nfsen_id >= 0) {
            					// ICMP "port" filter are no currently supported by the HAP4NfSen plugin
            					function isChecked(&$form, $name) { // helper function used to find out, if an option is checked
            						return $form[$name]=="checked";
            					}
            					$ip_and_port_columns = preg_match('/(flow records)/i', $IPStatOption[$process_form['stattype']]) &&
            						((isChecked($process_form,'aggr_srcip') && isChecked($process_form,'aggr_srcport')) ||
            						(isChecked($process_form,'aggr_dstip') && isChecked($process_form,'aggr_dstport')));
            					$ip_contains_port =  $_SESSION["process_form"]["modeselect"]=='0' || !preg_match('/[ip|flow_records]/i', $IPStatOption[$process_form['stattype']]) ||
            								(preg_match('/(flow records)/i', $IPStatOption[$process_form['stattype']]) && !( // no boxes checked
            								isChecked($process_form,'aggr_srcip') || isChecked($process_form,'aggr_srcport') ||
            								isChecked($process_form,'aggr_dstip') || isChecked($process_form,'aggr_dstport')));
                    	                        $_SESSION["plugin"][$hap4nfsen_id]["cmd_opts"] = $cmd_opts;
            					$hap_pic = "<img src=\"plugins/HAP4NfSen/graphviz.png\" valign=\"middle\" border=\"0\" alt=\"HAP\" />";
            					$default_pattern = array_pop($patterns);
            					$default_replacement = array_pop($replacements);
            					if ($ip_contains_port) { // matches cases like ip:port
            						$max_prot_length = 5; // max. port length = 5 chars(highest port number = 65535)
            						for ($i=$max_prot_length;$i>=1;$i--) {
            							$diff = ($max_prot_length-$i); // difference between actual and max port length
            							$ip_port_pattern_icmp = "/(\s*)([^\s|^:]+)(:)(0\s{4}|\d\.\d\s{2}|\d{2}\.\d\|\d\.\d{2}\s|\d{2}\.\d{2})/";
            							$ip_port_pattern_normal = "/(\s*)([^\s|^:]+)(:)([\d|\.]{{$i}})(\s{{$diff}})/";
            							$spaces = '';
            							for ($k=0;$k<$diff;$k++) {$spaces = $spaces . ' ';} // spaces required to align hap viewer icons
                                                            	array_push($patterns, $ip_port_pattern_icmp);
            							array_push($replacements,  $default_replacement .
            								"$3$4 <a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&mode=new\" title='HAP graphlet for $2'>$hap_pic</a> ");
            							array_push($patterns, $ip_port_pattern_normal);
                                                            	array_push($replacements,  $default_replacement .
            								"$3$4$spaces <a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&port=$4&mode=new\" title='HAP graphlet for $2 on port $4'>$hap_pic</a> ");
            						}
            						array_push($patterns, '/(\sIP\sAddr:Port)/i');
                                                    	array_push($replacements, "$1  $hap_pic");
            					} else {
            						if ($ip_and_port_columns) { // matches cases when both ip and port are available but are located in separate columns
            							// ICMP verion
            							$ip_and_port_pattern = "/(\s*)([^\s]+)(\s+)(0|\d\.\d)/";
            							$ip_and_port_replacement = "$1$2$3$4 " .
            								"<a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&mode=new\" title='HAP graphlet for $2'>$hap_pic</a>";
            							array_push($patterns, $ip_and_port_pattern);
            							array_push($replacements, $ip_and_port_replacement);
            							// non-ICMP version with port filter
                                                                    $ip_and_port_pattern = "/(\s*)([^\s]+)(\s*)([\d|.]+)/";
                                                                    $ip_and_port_replacement = "$1$2$3$4 " .
                                                                            "<a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&port=$4&mode=new\" title='HAP graphlet for $2 on port $4'>$hap_pic</a>";
                                                                    array_push($patterns, $ip_and_port_pattern);
                                                                    array_push($replacements, $ip_and_port_replacement);
            							array_push($patterns, '/(\s\s(Src\sIP\sAddr\s*Src\sPt|Dst\sIP\sAddr\s*Dst\sPt))/i');
                                                                    array_push($replacements, "$1 $hap_pic");
            						} else { // matches all other cases
            							array_push($patterns, $default_pattern);
                                                    		array_push($replacements,  $default_replacement . 
            								" <a href=\"nfsen.php?tab=5&sub_tab=" . $hap4nfsen_id . "&ip=$2&mode=new\" title='HAP graphlet for $2'>$hap_pic</a>");
            							array_push($patterns, '/(\s(|\s(Src|Dst))\sIP\sAddr)/i');
                                                            	array_push($replacements, "$1 $hap_pic");
            						}
            					}
            	                        }
            
            				if ( array_key_exists('arg', $cmd_out) ) {
            					print "** nfdump " . $cmd_out['arg'] . "\n";
            				}
            				if ( array_key_exists('filter', $cmd_out) ) {
            					print "nfdump filter:\n";
            					foreach ( $cmd_out['filter'] as $line ) {
            						print "$line\n";
            					}
            				}
            				foreach ( $cmd_out['nfdump'] as $line ) {
            					print preg_replace($patterns, $replacements, $line) . "\n";
            				}*/
            # parse command line
            #2009-12-09 17:08:17.596    40.262 TCP        192.168.1.9:80    ->   217.126.167.80:51694 .AP.SF   0       70   180978        1    35960   2585     1
            $list = preg_match("/\\-o extended/", $cmd_out['arg']) ? 1 : 0;
            $regex = $list ? "/(\\d\\d\\d\\d\\-.*?\\s.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+->\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?\\s*[KMG]?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*)/" : "/(\\d\\d\\d\\d\\-.*?\\s.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?\\s*[KMGT]?)\\s+(.*?)\\s+(.*?)\\s+(.*)/";
            echo '<div class="nfsen_list_title">' . _('Flows Info') . '</div>';
            echo "<table class='table_list'>";
            $geotools = false;
            if ($list && file_exists("../kml/GoogleEarth.php")) {
                $geotools = true;
                $geoips = array();
                $geotools_src = " <a href='' onclick='window.open(\"../kml/TourConfig.php?type=ip_src&ip=&flows=1\",\"Flows sources - Goggle Earth API\",\"width=1024,height=700,scrollbars=NO,toolbar=1\");return false'><img align='absmiddle' src='../pixmaps/google_earth_icon.png' border='0'></a>&nbsp;&nbsp;<a href='' onclick='window.open(\"../kml/IPGoogleMap.php?type=ip_src&ip=&flows=1\",\"Flows sources - Goggle Maps API\",\"width=1024,height=700,scrollbars=NO,toolbar=1\");return false'><img align='absmiddle' src='../pixmaps/google_maps_icon.png' border='0'></a>";
                $geotools_dst = " <a href='' onclick='window.open(\"../kml/TourConfig.php?type=ip_dst&ip=&flows=1\",\"Flows destinations - Goggle Earth API\",\"width=1024,height=700,scrollbars=NO,toolbar=1\");return false'><img align='absmiddle' src='../pixmaps/google_earth_icon.png' border='0'></a>&nbsp;&nbsp;<a href='' onclick='window.open(\"../kml/IPGoogleMap.php?type=ip_dst&ip=&flows=1\",\"Flows destinations - Goggle Maps API\",\"width=1024,height=700,scrollbars=NO,toolbar=1\");return false'><img align='absmiddle' src='../pixmaps/google_maps_icon.png' border='0'></a>";
            }
            echo $list ? "\n                \n                <tr>\n                    <th>" . _("Date flow start") . "<br><span style='font-size:8px'>" . Util::timezone($tz) . "</style></th>\n                    <th>" . _("Duration") . "</th>\n                    <th>" . _("Proto") . "</th>\n                    <th>" . _("Src IP Addr:Port") . "{$geotools_src}</th>\n                    <th>" . _("Dst IP Addr:Port") . "{$geotools_dst}</th>\n                    <th>" . _("Flags") . "</th>\n                    <th>" . _("Tos") . "</th>\n                    <th>" . _("Packets") . "</th>\n                    <th>" . _("Bytes") . "</th>\n                    <th>" . _("pps") . "</th>\n                    <th>" . _("bps") . "</th>\n                    <th>" . _("Bpp") . "</th>\n                    <th>" . _("Flows") . "</th>\n                \t" . ($solera ? "<th></th>" : "") . "\n                    </tr>" : "<tr>\n                    <th>" . _("Date flow seen") . "<br><span style='font-size:8px'>" . Util::timezone($tz) . "</style></th>\n                    <th>" . _("Duration") . "</th>\n                    <th>" . _("Proto") . "</th>\n                    <th>" . $titcol . "</th>\n                    <th>" . _("Flows") . "(%)</th>\n                    <th>" . _("Packets") . "(%)</th>\n                    <th>" . _("Bytes") . "(%)</th>\n                    <th>" . _("pps") . "</th>\n                    <th>" . _("bps") . "</th>\n                    <th>" . _("Bpp") . "</th>\n                \t" . ($solera ? "<th></th>" : "") . "\n                    </tr>";
            $status = $errors = array();
            $rep = new Reputation();
            //print_r($cmd_out['arg']);
            //print_r($cmd_out['nfdump']);
            foreach ($cmd_out['nfdump'] as $k => $line) {
                #capture status
                if (preg_match("/^(Summary|Time window|Total flows processed|Sys)\\:/", $line, $found)) {
                    $status[$found[1]] = str_replace($found[1] . ":", "", $line);
                }
                # capture errors
                if (preg_match("/ error /i", $line, $found)) {
                    if (preg_match("/stat\\(\\) error/i", $line)) {
                        $errors[] = _('The netflow information you are trying to access either has not been processed yet or does not exist. Please check your date filters.');
                        Av_exception::write_log(Av_exception::USER_ERROR, $line);
                    } else {
                        $errors[] = $line;
                    }
                }
                # print results
                $line = preg_replace("/\\(\\s(\\d)/", "(\\1", $line);
                // Patch for ( 0.3)
                $line = preg_replace("/(\\d)\\s*([KMGT])/", "\\1\\2", $line);
                // Patch for 1.2 M(99.6)
                $line = preg_replace("/(\\d+)(TCP|UDP|ICMP|IGMP)\\s/", "\\1 \\2 ", $line);
                // Patch for 9.003TCP
                $start = $end = $proto = "";
                $ips = $ports = array();
                if (preg_match($regex, preg_replace('/\\s*/', ' ', $line), $found)) {
                    echo "<tr class='tr_flow_data'>\n";
                    foreach ($found as $ki => $field) {
                        if ($ki > 0) {
                            $wrap = $ki == 1 ? "nowrap" : "";
                            $field = Util::htmlentities(preg_replace("/(\\:\\d+)\\.0\$/", "\\1", $field));
                            if (preg_match("/(\\d+\\.\\d+\\.\\d+\\.\\d+)(.*)/", $field, $fnd)) {
                                # match ip (resolve and geolocalize)
                                $ip = $fnd[1];
                                $port = $fnd[2];
                                list($name, $ctx, $host_id) = GetDataFromSingleIp($ip, $hosts);
                                if ($name == "" && $sensors[$ip] != "") {
                                    $name = $sensors[$ip];
                                }
                                $output = Asset_host::get_extended_name($conn, $geoloc, $ip, $ctx, $host_id, '');
                                $homelan = $output['is_internal'] || $name != "" && $name != $ip;
                                $icon = $output['html_icon'];
                                # reputation info
                                if (!is_array($_SESSION["_repinfo_ips"][$ip])) {
                                    $_SESSION["_repinfo_ips"][$ip] = $rep->get_data_by_ip($ip);
                                }
                                $rep_icon = Reputation::getrepimg($_SESSION["_repinfo_ips"][$ip][0], $_SESSION["_repinfo_ips"][$ip][1], $_SESSION["_repinfo_ips"][$ip][2], $ip);
                                $rep_bgcolor = Reputation::getrepbgcolor($_SESSION["_repinfo_ips"][$ip][0]);
                                $style_aux = $homelan ? 'style="font-weight:bold"' : '';
                                $bold_aux1 = $homelan ? '<b>' : '';
                                $bold_aux2 = $homelan ? '<b>' : '';
                                $field = '<div id="' . $ip . ';' . Util::htmlentities($name) . ';' . $host_id . '" id2="' . $ip . ';' . $ip . '" ctx="' . $ctx . '" class="HostReportMenu">' . $icon . ' <a ' . $style_aux . ' href="javascript:;">' . Util::htmlentities($name) . '</a>' . $bold_aux1 . $port . $bold_aux2 . ' ' . $rep_icon . '</div>';
                                $wrap = "nowrap style='{$rep_bgcolor}'";
                                $ips[] = $ip;
                                if ($geotools) {
                                    if ($ki == 4) {
                                        $geoips['ip_src'][$ip]++;
                                    } elseif ($ki == 5) {
                                        $geoips['ip_dst'][$ip]++;
                                    }
                                }
                                $ports[] = str_replace(":", "", $port);
                            }
                            if (preg_match("/(\\d+-\\d+-\\d+ \\d+:\\d+:\\d+)(.*)/", $field, $fnd)) {
                                # match date
                                $start = $end = $fnd[1];
                                $time = strtotime($fnd[1]);
                                $field = Util::htmlentities(gmdate("Y-m-d H:i:s", $time + 3600 * $tz) . "." . $fnd[2]);
                            }
                            if (preg_match("/(TCP|UDP|ICMP|RAW)/", $field, $fnd)) {
                                # match date
                                $proto = strtolower($fnd[1]);
                            }
                            print "<td {$wrap}>{$field}</td>";
                        }
                    }
                    // solera deepsee integration
                    if ($solera) {
                        echo "<td><a href=\"javascript:;\" onclick=\"solera_deepsee('" . Util::htmlentities($start) . "','" . Util::htmlentities($end) . "','" . Util::htmlentities($ips[0]) . "','" . Util::htmlentities($ports[0]) . "','" . Util::htmlentities($ips[1]) . "','" . Util::htmlentities($ports[1]) . "','" . Util::htmlentities($proto) . "')\"><img src='/ossim/pixmaps/solera.png' border='0' align='absmiddle'></a></td>";
                    }
                    echo "</tr>\n";
                }
            }
            echo "</table>";
            if ($geotools) {
                foreach ($geoips as $type => $list) {
                    $ipsfile = fopen("/var/tmp/flowips_" . Session::get_session_user() . ".{$type}", "w");
                    foreach ($list as $ip => $val) {
                        fputs($ipsfile, "{$ip}\n");
                    }
                    fclose($ipsfile);
                }
            }
            #Summary: total flows: 20, total bytes: 7701, total packets: 133, avg bps: 60, avg pps: 0, avg bpp: 57
            #Time window: 2009-12-10 08:21:30 - 2009-12-10 08:38:26
            #Total flows processed: 21, Records skipped: 0, Bytes read: 1128
            #Sys: 0.000s flows/second: 0.0        Wall: 0.000s flows/second: 152173.9
            if (count($status) > 0) {
                echo "<table class='transparent' style='margin-bottom:5px;width:100%'>";
                foreach ($status as $key => $line) {
                    $line = preg_replace("/(Wall)\\:/", "<span class='th_summary'>\\1</span>", $line);
                    $line = preg_replace("/\\,\\s+(.*?)\\:/", " <span class='th_summary'>\\1</span>", $line);
                    echo "<tr>\n                                    <td class='nobborder' style='padding: 4px;'>\n                                        <span class='th_summary'>{$key}</span>\n                                        {$line}\n                                    </td>\n                                  </tr>";
                }
                echo "</table>";
            }
            # stat() error '/home/dk/nfsen/profiles-data/live/device2/2009/12/10/nfcapd.200912100920': File not found!
            if (count($errors) > 0) {
                foreach ($errors as $line) {
                    echo "<div class='details_error'>" . _("ERROR FOUND: ") . "{$line}</div>";
                }
            }
            $conn->disconnect();
        }
        #print "</pre>\n";
    }
    print "</div>\n";
    $db_aux->close();
    $geoloc->close();
    return;
}
// Multiple Database Server selector
$conn = $dbo->connect();
$database_servers = Databases::get_list($conn);
$dbo->close();
//
if (is_array($_SESSION["server"]) && $_SESSION["server"][0] != "") {
    $dbo->enable_cache();
    $conn = $dbo->custom_connect($_SESSION["server"][0], $_SESSION["server"][2], $_SESSION["server"][3]);
} else {
    $dbo->enable_cache();
    $conn = $dbo->connect();
}
include_once "{$BASE_path}/base_common.php";
$sensors = $hosts = $ossim_servers = array();
$sensors = Av_sensor::get_basic_list($conn, array(), TRUE);
list($hosts, $host_ids) = Asset_host::get_basic_list($conn, array(), TRUE);
$entities = Session::get_all_entities($conn);
$rep_activities = Reputation::get_reputation_activities($conn, "ORDER BY descr", $db_memcache);
$rep_severities = array("ANY", "High", "Medium", "Low");
//
// added default home host/lan to SESSION[ip_addr]
//
if ($_GET["addhomeips"] == "src" || $_GET["addhomeips"] == "dst") {
    $_nets = Asset_net::get_all($conn, TRUE);
    // adding all not external lans
    $local_ips = array();
    $total_ips = 0;
    foreach ($_nets as $current_net) {
        $cirds = explode(",", $current_net['ips']);
        foreach ($cirds as $cidr) {
            if (!$current_net['external'] && preg_match("/(.*)\\.(.*)\\.(.*)\\.(.*)\\/(.*)/", $cidr, $fields)) {
Example #6
0
$result = '';
$db = new ossim_db();
$dbconn = $db->connect();
$_SESSION['_user'] = '******';
switch ($option) {
    case 'get_ctx':
        if (preg_match("/^([a-f\\d]{32})#\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\$/i", $asset, $found)) {
            // host_id#IP
            $result = Asset_host::get_ctx_by_id($dbconn, $found[1]);
        } else {
            if (preg_match("/^([a-f\\d]{32})#\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\/\\d{1,2}\$/i", $asset, $found)) {
                // net_id#CIDR
                $result = Asset_net::get_ctx_by_id($dbconn, $found[1]);
            } else {
                $filters = array('where' => 'hostname = "' . $asset . '" OR fqdns LIKE "%' . $asset . '%"');
                $_hosts_data = Asset_host::get_basic_list($dbconn, $filters);
                $hosts_list = $_hosts_data[1];
                $total = count($hosts_list);
                if ($total > 0) {
                    $host_id = key($hosts_list);
                    $result = $hosts_list[$host_id]['ctx'];
                } else {
                    $result = '';
                }
            }
        }
        break;
    case 'get_sensor_ip':
        $result = Av_sensor::get_ip_by_id($dbconn, $asset);
        break;
    case 'get_system_uuid':
Example #7
0
    list($host_id, $host_ip) = explode("#", $host_id_ip);
    ossim_valid($host_ip, OSS_IP_ADDR, 'illegal:' . _("Host IP"));
    ossim_valid($host_id, OSS_HEX, 'illegal:' . _("Host ID"));
} else {
    // only IP
    ossim_valid($host_id_ip, OSS_NULLABLE, OSS_IP_ADDR, 'illegal:' . _("Host IP"));
}
if (ossim_error()) {
    die(ossim_error());
}
$results = array();
//Check if it is allowed
$allowed = Vulnerabilities::is_allowed_credential($dbconn, $name, $login);
if ($allowed) {
    //Autocomplete data
    $_hosts_data = Asset_host::get_basic_list($dbconn);
    $_hosts = $_hosts_data[1];
    foreach ($_hosts as $_host_id => $_host_detail) {
        // get host IPs
        $hIPs = array();
        $hIPs = explode(",", trim($_host_detail['ips']));
        foreach ($hIPs as $hIP) {
            $hIP = trim($hIP);
            $hosts .= '{ txt:"' . $_host_detail['name'] . ' (' . $hIP . ')", id: "' . $_host_id . '#' . $hIP . '" },';
        }
    }
}
//Check credentials
if ($host_id_ip != "") {
    $results = Vulnerabilities::check_credential($dbconn, $host_id_ip, $name, $login);
}
Example #8
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>";
}