Ejemplo n.º 1
0
     } else {
         if (!$rs->EOF) {
             $scan_END = $rs->fields['scantime'];
             $report_key = $rs->fields['report_key'];
         }
     }
     $file_path = "/usr/share/ossim/www/tmp/" . $result->fields["name"] . "_" . $scan_END . ".pdf";
     $file_path = str_replace(" ", "", $file_path);
     $file_name = $result->fields["name"] . "_" . $scan_END . ".pdf";
     $params = array($report_id, $file_path);
     Util::execute_command("/usr/bin/php /usr/share/ossim/scripts/vulnmeter/respdf.php ? > ?", $params);
     if (file_exists($file_path) && filesize($file_path) <= 5242880) {
         $attachments[] = array("path" => $file_path, "name" => $file_name);
     }
 }
 if (!valid_hex32($username)) {
     $body = get_timestamps($dbconn, $username, $result->fields['scan_START'], $result->fields['scan_SUBMIT'], $body);
     $email = get_email($dbconn, $username);
     Util::send_email($dbconn, $email, $subject, $body, $attachments);
 } else {
     // username is a entity
     $entity_data = Acl::get_entity($dbconn, $username, FALSE, FALSE);
     if ($entity_data["admin_user"] != "") {
         $body = get_timestamps($dbconn, $entity_data["admin_user"], $result->fields['scan_START'], $result->fields['scan_SUBMIT'], $body);
         $email = get_email($dbconn, $entity_data["admin_user"]);
         Util::send_email($dbconn, $email, $subject, $body, $attachments);
     } else {
         // doesn't exit pro admin
         $users_list = Acl::get_users_by_entity($dbconn, $username);
         foreach ($users_list as $k => $user_data) {
             if ($user_data['email'] != "") {
Ejemplo n.º 2
0
*
* You should have received a copy of the GNU General Public License
* along with this package; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA  02110-1301  USA
*
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
$m_perms = array('environment-menu', 'environment-menu');
$sm_perms = array('PolicyHosts', 'PolicyNetworks');
Session::logcheck_ajax($m_perms, $sm_perms);
$data['status'] = 'success';
$data['data'] = _('Your changes have been saved');
$message_id = POST('message_id');
if (!valid_hex32($message_id, TRUE)) {
    Util::response_bad_request(_('Error! Message ID not allowed.  Action could not be completed'));
}
try {
    $status = new System_notifications();
    $flags = array('viewed' => 'true');
    $status->set_status_message($message_id, $flags);
} catch (Exception $e) {
    Util::response_bad_request($e->getMessage());
}
echo json_encode($data);
Ejemplo n.º 3
0
function list_results($type, $value, $ctx_filter, $sortby, $sortdir)
{
    global $allres, $offset, $pageSize, $dbconn;
    global $user, $arruser;
    $dbconn->SetFetchMode(ADODB_FETCH_BOTH);
    $filteredView = FALSE;
    $selRadio = array("", "", "", "");
    $query_onlyuser = "";
    $url_filter = "";
    // Deprecated filter
    //if(!empty($arruser)) {$query_onlyuser = "******";}
    $sortby = "t1.results_sent DESC, t1.hostIP DESC";
    $sortdir = "";
    $queryw = "";
    $queryl = "";
    $querys = "SELECT distinct t1.hostIP, HEX(t1.ctx) as ctx, t1.scantime, t1.username, t1.scantype, t1.report_key, t1.report_type as report_type, t1.sid, t3.name as profile\n    FROM vuln_nessus_latest_reports AS t1 LEFT JOIN vuln_nessus_settings AS t3 ON t1.sid = t3.id, vuln_nessus_latest_results AS t5\n    WHERE\n    t1.hostIP      = t5.hostIP\n    AND t1.ctx     = t5.ctx\n    AND t1.deleted = '0' ";
    // set up the SQL query based on the search form input (if any)
    if ($type == "scantime" && $value != "") {
        $selRadio[0] = "CHECKED";
        $q = $value;
        $queryw = " AND t1.scantime LIKE '%{$q}%' {$query_onlyuser} order by {$sortby} {$sortdir}";
        $queryl = " limit {$offset},{$pageSize}";
        $stext = "<b>" . _("Search for Date/Time") . "</b> = '*{$q}*'";
        $url_filter = "&type={$type}&value={$value}";
    } else {
        if ($type == "service" && $value != "") {
            $selRadio[5] = "CHECKED";
            $q = $value;
            $queryw = " AND t5.service LIKE '%{$q}%' {$query_onlyuser} order by {$sortby} {$sortdir}";
            $queryl = " limit {$offset},{$pageSize}";
            $stext = "<b>" . _("Search for Service") . "</b> = '*" . html_entity_decode($q) . "*'";
            $url_filter = "&type={$type}&value={$value}";
        } else {
            if ($type == "freetext" && $value != "") {
                $selRadio[6] = "CHECKED";
                $q = $value;
                $queryw = " AND t5.msg LIKE '%{$q}%' {$query_onlyuser} order by {$sortby} {$sortdir}";
                $queryl = " limit {$offset},{$pageSize}";
                $stext = "<b>" . _("Search for Free Text") . "</b> = '*" . html_entity_decode($q) . "*'";
                $url_filter = "&type={$type}&value={$value}";
            } else {
                if ($type == "hostip" && $value != "") {
                    $selRadio[1] = "CHECKED";
                    $q = strtolower($value);
                    $queryw = " t1.hostIP LIKE '%{$q}%' {$query_onlyuser} order by {$sortby} {$sortdir}";
                    $queryl = " limit {$offset},{$pageSize}";
                    $stext = "<b>" . _("Search for Host-IP") . "</b> = '*{$q}*'";
                    $url_filter = "&type={$type}&value={$value}";
                } else {
                    if ($type == "fk_name" && $value != "") {
                        $selRadio[2] = "CHECKED";
                        $q = strtolower($value);
                        $queryw = " AND t1.fk_name LIKE '%{$q}%' {$query_onlyuser} order by {$sortby} {$sortdir}";
                        $queryl = " limit {$offset},{$pageSize}";
                        $stext = _("Search for Subnet/CIDR") . " = '*{$q}*'";
                        $url_filter = "&type={$type}&value={$value}";
                    } else {
                        if ($type == "username" && $value != "") {
                            $selRadio[3] = "CHECKED";
                            $q = strtolower($value);
                            $queryw = " AND t1.username LIKE '%{$q}%' {$query_onlyuser} order by {$sortby} {$sortdir}";
                            $queryl = " limit {$offset},{$pageSize}";
                            $stext = "<b>" . _("Search for user") . "</b> = '*{$q}*'";
                            $url_filter = "&type={$type}&value={$value}";
                        } else {
                            if ($type == "hn" && $value != "") {
                                if (!empty($ctx_filter)) {
                                    $queryw = " AND t1.ctx=UNHEX('{$ctx_filter}')";
                                }
                                $selRadio[4] = "CHECKED";
                                if (preg_match("/\\//", $value)) {
                                    $ip_range = array();
                                    $ip_range = Cidr::expand_CIDR($value, "SHORT");
                                    $queryw .= " AND (inet_aton(t1.hostIP) >= '" . $ip_range[0] . "' AND inet_aton(t1.hostIP) <='" . $ip_range[1] . "') {$query_onlyuser} order by {$sortby} {$sortdir}";
                                } elseif (preg_match("/\\,/", $value)) {
                                    $q = implode("','", explode(",", $value));
                                    $queryw .= " AND t1.hostIP in ('{$q}') {$query_onlyuser} order by {$sortby} {$sortdir}";
                                    $q = "Others";
                                } else {
                                    $q = $value;
                                    $queryw .= " AND t1.hostIP LIKE '{$q}' {$query_onlyuser} order by {$sortby} {$sortdir}";
                                }
                                $queryl = " limit {$offset},{$pageSize}";
                                if (!preg_match("/\\//", $value)) {
                                    $stext = "<b>" . _("Search for Host") . "</b> = '" . html_entity_decode($q) . "'";
                                } else {
                                    $stext = "<b>" . _("Search for Subnet/CIDR") . "</b> = '{$value}'";
                                }
                                $url_filter = "&type={$type}&value={$value}";
                            } else {
                                $selRadio[4] = "CHECKED";
                                $viewAll = FALSE;
                                $queryw = "{$query_onlyuser} order by {$sortby} {$sortdir}";
                                $queryl = " limit {$offset},{$pageSize}";
                                $stext = "";
                            }
                        }
                    }
                }
            }
        }
    }
    // set up the pager and search fields if viewing all hosts
    $reportCount = 0;
    if (!$filteredView) {
        $dbconn->Execute(str_replace("SELECT distinct", "SELECT SQL_CALC_FOUND_ROWS distinct", $querys) . $queryw);
        $reportCount = $dbconn->GetOne("SELECT FOUND_ROWS() as total");
        $previous = $offset - $pageSize;
        if ($previous < 0) {
            $previous = 0;
        }
        $last = intval($reportCount / $pageSize) * $pageSize;
        if ($last < 0) {
            $last = 0;
        }
        $next = $offset + $pageSize;
        $pageEnd = $offset + $pageSize;
        $value = html_entity_decode($value);
        //echo "<center><table cellspacing='0' cellpadding='0' border='0' width='100%'><tr><td class='headerpr' style='border:0;'>"._("Current Vulnerablities")."</td></tr></table>";
        // output the search form
        echo "<table class='w100 transparent'>";
        echo "<tr><td class='sec_title'>" . _("Asset Vulnerability Details") . "</td></tr>";
        echo "<tr><td style='padding:12px 0px 0px 0px;' class='transparent'>";
        ?>
    <div id='cvleftdiv'>
        <a id="new_scan_button" class="button" href="<?php 
        echo Menu::get_menu_url(AV_MAIN_PATH . '/vulnmeter/sched.php?action=create_scan&hosts_alive=1&scan_locally=1', 'environment', 'vulnerabilities', 'scan_jobs');
        ?>
" style="text-decoration:none;">
        <?php 
        echo _("New Scan Job");
        ?>
        </a>
    </div>
    <div id='cvrightdiv'>

<?php 
        echo '<form name="hostSearch" id="hostSearch" action="index.php" method="GET">
<input type="text" length="25" name="value" id="assets" class="assets" style="margin:0px !important;" value="' . Util::htmlentities($value) . '">';
        // cvfiltertype -> current vulnerabilities filter type
        echo "\n<input type=\"radio\" name=\"type\" value=\"service\" {$selRadio['5']}>" . _("Service") . "\n<input type=\"radio\" name=\"type\" value=\"freetext\" {$selRadio['6']}>" . _("Free text") . "\n<input type=\"radio\" name=\"type\" value=\"hn\" {$selRadio['4']}>" . _("Host/Net") . "\n";
        echo "<input type=\"submit\" name=\"submit\" value=\"" . _("Find") . "\" id=\"current_vulns_find_button\" class=\"av_b_secondary small\" style=\"margin-left:15px;\">";
        echo <<<EOT
</form>
</p>
EOT;
    } else {
        // get the search result count
        $queryc = "SELECT count( report_id ) FROM vuln_nessus_latest_reports WHERE t1.deleted = '0' ";
        $scount = $dbconn->GetOne($queryc . $queryw);
        echo "<p>{$scount} report";
        if ($scount != 1) {
            echo "s";
        } else {
        }
        echo " " . _("found matching search criteria") . " | ";
        echo " <a href='index.php' alt='" . _("View All Reports") . "'>" . _("View All Reports") . "</a></p>";
    }
    echo "<p>";
    echo $stext;
    echo "</p>";
    echo "</div></td></tr></table>";
    $result = array();
    // get the hosts to display
    $result = $dbconn->GetArray($querys . $queryw . $queryl);
    // main query
    //echo $querys.$queryw.$queryl;
    $delete_ids = array();
    if (count($result) > 0) {
        foreach ($result as $rpt) {
            $delete_ids[] = $dreport_id = $rpt["report_id"];
        }
    }
    $_SESSION["_dreport_ids"] = implode(",", $delete_ids);
    //echo "$querys$queryw$queryl";
    if ($result === false) {
        $errMsg[] = _("Error getting results") . ": " . $dbconn->ErrorMsg();
        $error++;
        dispSQLError($errMsg, $error);
    } else {
        $data['vInfo'] = 0;
        $data['vLow'] = 0;
        $data['vMed'] = 0;
        $data['vHigh'] = 0;
        $data['vSerious'] = 0;
        $perms_where = Asset_host::get_perms_where('host.', TRUE);
        if (!empty($perms_where)) {
            $queryt = "SELECT count(lr.result_id) AS total, lr.risk, lr.hostIP, HEX(lr.ctx) AS ctx\n                        FROM vuln_nessus_latest_results lr, host, host_ip hi\n                        WHERE host.id=hi.host_id AND inet6_ntoa(hi.ip)=lr.hostIP {$perms_where} AND falsepositive='N'\n                        GROUP BY risk, hostIP, ctx";
        } else {
            $queryt = "SELECT count(lr.result_id) AS total, risk, lr.hostIP, HEX(lr.ctx) AS ctx\n                        FROM vuln_nessus_latest_results lr\n                        WHERE falsepositive='N'\n                        GROUP BY risk, hostIP, ctx";
        }
        //echo "$queryt<br>";
        $resultt = $dbconn->Execute($queryt);
        while (!$resultt->EOF) {
            $riskcount = $resultt->fields['total'];
            $risk = $resultt->fields['risk'];
            if ($risk == 7) {
                $data['vInfo'] += $riskcount;
            } else {
                if ($risk == 6) {
                    $data['vLow'] += $riskcount;
                } else {
                    if ($risk == 3) {
                        $data['vMed'] += $riskcount;
                    } else {
                        if ($risk == 2) {
                            $data['vHigh'] += $riskcount;
                        } else {
                            if ($risk == 1) {
                                $data['vSerious'] += $riskcount;
                            }
                        }
                    }
                }
            }
            $resultt->MoveNext();
        }
        if ($data['vInfo'] == 0 && $data['vLow'] == 0 && $data['vMed'] == 0 && $data['vHigh'] == 0 && $data['vSerious'] == 0) {
            $tdata[] = array("report_id" => "All", "host_name" => "", "scantime" => "", "username" => "", "scantype" => "", "report_key" => "", "report_type" => "", "sid" => "", "profile" => "", "hlink" => "", "plink" => "", "xlink" => "", "vSerious" => $data['vSerious'], "vHigh" => $data['vHigh'], "vMed" => $data['vMed'], "vLow" => $data['vLow'], "vInfo" => $data['vInfo']);
        } else {
            $tdata[] = array("report_id" => "All", "host_name" => "", "scantime" => "", "username" => "", "scantype" => "", "report_key" => "", "report_type" => "", "sid" => "", "profile" => "", "hlink" => "lr_reshtml.php?ipl=all&disp=html&output=full&scantype=M", "plink" => "lr_respdf.php?ipl=all&scantype=M", "xlink" => "lr_rescsv.php?ipl=all&scantype=M", "dlink" => "", "vSerious" => $data['vSerious'], "vHigh" => $data['vHigh'], "vMed" => $data['vMed'], "vLow" => $data['vLow'], "vInfo" => $data['vInfo']);
        }
        foreach ($result as $data) {
            if (!Session::hostAllowed_by_ip_ctx($dbconn, $data["hostIP"], $data["ctx"])) {
                continue;
            }
            $host_id = key(Asset_host::get_id_by_ips($dbconn, $data["hostIP"], $data["ctx"]));
            if (valid_hex32($host_id)) {
                $data['host_name'] = Asset_host::get_name_by_id($dbconn, $host_id);
            }
            $data['vSerious'] = 0;
            $data['vHigh'] = 0;
            $data['vMed'] = 0;
            $data['vLow'] = 0;
            $data['vInfo'] = 0;
            // query for reports for each IP
            $query_risk = "SELECT distinct risk, port, protocol, app, scriptid, msg, hostIP FROM vuln_nessus_latest_results WHERE hostIP = '" . $data['hostIP'];
            $query_risk .= "' AND username = '******'username'] . "' AND sid =" . $data['sid'] . " AND ctx = UNHEX('" . $data['ctx'] . "') AND falsepositive='N'";
            $result_risk = $dbconn->Execute($query_risk);
            while (!$result_risk->EOF) {
                if ($result_risk->fields["risk"] == 7) {
                    $data['vInfo']++;
                } else {
                    if ($result_risk->fields["risk"] == 6) {
                        $data['vLow']++;
                    } else {
                        if ($result_risk->fields["risk"] == 3) {
                            $data['vMed']++;
                        } else {
                            if ($result_risk->fields["risk"] == 2) {
                                $data['vHigh']++;
                            } else {
                                if ($result_risk->fields["risk"] == 1) {
                                    $data['vSerious']++;
                                }
                            }
                        }
                    }
                }
                $result_risk->MoveNext();
            }
            $data['plink'] = "lr_respdf.php?treport=latest&ipl=" . urlencode($data['hostIP']) . "&ctx=" . $data['ctx'] . "&scantype=" . $data['scantype'];
            $data['hlink'] = "lr_reshtml.php?treport=latest&ipl=" . urlencode($data['hostIP']) . "&ctx=" . $data['ctx'] . "&scantype=" . $data['scantype'];
            $data['xlink'] = "lr_rescsv.php?treport=latest&ipl=" . urlencode($data['hostIP']) . "&ctx=" . $data['ctx'] . "&scantype=" . $data['scantype'];
            if (Session::am_i_admin()) {
                $data['dlink'] = "index.php?delete=" . $data['report_key'] . "&scantime=" . $data['scantime'];
            }
            $list = explode("\n", trim($data['meth_target']));
            if (count($list) == 1) {
                $list[0] = trim($list[0]);
                $data['target'] = resolve_asset($dbconn, $list[0]);
            } elseif (count($list) == 2) {
                $list[0] = trim($list[0]);
                $list[0] = resolve_asset($dbconn, $list[0]);
                $list[1] = trim($list[1]);
                $list[1] = resolve_asset($dbconn, $list[1]);
                $data['target'] = $list[0] . ' ' . $list[1];
            } else {
                $list[0] = trim($list[0]);
                $list[0] = resolve_asset($dbconn, $list[0]);
                $list[count($list) - 1] = trim($list[count($list) - 1]);
                $list[count($list) - 1] = resolve_asset($dbconn, $list[count($list) - 1]);
                $data['target'] = $list[0] . " ... " . $list[count($list) - 1];
            }
            $tdata[] = $data;
        }
        if ($sortdir == "ASC") {
            $sortdir = "DESC";
        } else {
            $sortdir = "ASC";
        }
        $url = $_SERVER['SCRIPT_NAME'] . "?offset={$offset}&sortby=%var%&sortdir={$sortdir}" . $url_filter;
        $fieldMapLinks = array();
        $fieldMapLinks = array(gettext("HTML Results") => array('url' => '%param%', 'param' => 'hlink', 'target' => 'main', 'icon' => 'images/html.png'), gettext("PDF Results") => array('url' => '%param%', 'param' => 'plink', 'target' => '_blank', 'icon' => 'images/pdf.png'), gettext("EXCEL Results") => array('url' => '%param%', 'param' => 'xlink', 'target' => '_blank', 'icon' => 'images/page_white_excel.png'));
        if (Session::am_i_admin()) {
            $fieldMapLinks["DELETE Results"] = array('url' => '%param%', 'param' => 'dlink', 'target' => 'main', 'icon' => 'images/delete.gif');
        }
        $fieldMap = array("Host - IP" => array('var' => 'hostip'), "Date/Time" => array('var' => 'scantime'), "Profile" => array('var' => 'profile'), "Serious" => array('var' => 'vSerious'), "High" => array('var' => 'vHigh'), "Medium" => array('var' => 'vMed'), "Low" => array('var' => 'vLow'), "Info" => array('var' => 'vInfo'), "Links" => $fieldMapLinks);
        // echo "<pre>";
        // var_dump($tdata);
        // echo "</pre>";
        if (count($tdata) > 1) {
            drawTableLatest($fieldMap, $tdata, "Hosts");
        } elseif (Session::menu_perms("environment-menu", "EventsVulnerabilitiesScan")) {
            echo "<br><span class='gray'>" . _("No results found: ") . "</span><a href='" . Menu::get_menu_url(AV_MAIN_PATH . '/vulnmeter/sched.php?action=create_scan&hosts_alive=1&scan_locally=1', 'environment', 'vulnerabilities', 'scan_jobs') . "'>" . _("Click here to run a Vulnerability Scan now") . "</a><br><br>";
        }
    }
    // draw the pager again, if viewing all hosts
    if (!$filteredView && $reportCount > 10) {
        ?>
    <div class="fright tmargin">
        <?php 
        if ($next > $pageSize) {
            ?>
	        <a href="index.php?<?php 
            echo "offset={$previous}{$url_filter}";
            ?>
" class="pager">< <?php 
            echo _("PREVIOUS");
            ?>
 </a>
	    <?php 
        } else {
            ?>
	        <a class='link_paginate_disabled' href="" onclick='return false'>< <?php 
            echo _("PREVIOUS");
            ?>
 </a>
		<?php 
        }
        if ($next <= $last) {
            ?>
            <a class='lmargin' href="index.php?<?php 
            echo "offset={$next}{$url_filter}";
            ?>
">  <?php 
            echo _("NEXT");
            ?>
 ></a>
        <?php 
        } else {
            ?>
            <a class='link_paginate_disabled lmargin' href="" onclick='return false'><?php 
            echo _("NEXT");
            ?>
 ></a>
        <?php 
        }
        ?>
    </div>
<?php 
    } else {
        echo "<p>&nbsp;</p>";
    }
}
Ejemplo n.º 4
0
 while (list($hostIP, $hostctx, $service, $service_num, $service_proto, $app, $risk, $scriptid, $pname, $msg) = $result->fields) {
     $arrResults[$hostIP . "#" . $hostctx][] = array('service' => $service, 'port' => $service_num, 'protocol' => $service_proto, 'application' => $app, 'risk' => $risk, 'scriptid' => $scriptid, 'exception' => $eid, 'msg' => preg_replace('/(<br\\s*?\\/??>)+/i', "\n", $msg), 'pname' => $pname);
     $result->MoveNext();
 }
 //Vulnerability table configs
 $vcols = array(_("Risk"), _("Details"));
 //widths for columns
 $vwidth_array = array(20, 170);
 // 196 total
 $count = 0;
 $oldip = "";
 // iterate through the IP is the results
 foreach ($arrResults as $hostIP_ctx => $scanData) {
     list($hostIP, $hostctx) = explode("#", $hostIP_ctx);
     $host_id = key(Asset_host::get_id_by_ips($dbconn, $hostIP, $hostctx));
     if (valid_hex32($host_id)) {
         $hostname = Asset_host::get_name_by_id($dbconn, $host_id);
     } else {
         $hostname = _('unknown');
     }
     $hostIP = htmlspecialchars_decode($hostIP);
     $hostname = htmlspecialchars_decode($hostname);
     $pdf->SetLink(${"IP_" . $hostIP_ctx}, $pdf->GetY());
     //print out the host cell
     $pdf->SetFillColor(229, 229, 229);
     $pdf->SetFont('', 'B', 10);
     $pdf->Cell(95, 6, $hostIP, 1, 0, 'C', 1);
     $pdf->Cell(95, 6, $hostname, 1, 0, 'C', 1);
     //$pdf->Cell(105, 6, "",1,0,'C');
     $pdf->SetFont('', '');
     $pdf->Ln();
Ejemplo n.º 5
0
            ?>
" <?php 
            echo $selected;
            ?>
><?php 
            echo $template['name'];
            ?>
</option>
										<?php 
        }
        ?>
								</select>
								
								<?php 
        if ($am_i_admin) {
            if ($notemplates == 0 && valid_hex32($templates[0]['id'])) {
                ?>
										<a href="javascript:;" onclick="go_template('edit')">
											<img align="absmiddle" src="../pixmaps/tables/table_edit.png" border="0" class="info" alt="<?php 
                echo _('View template');
                ?>
" title="<?php 
                echo _('View template');
                ?>
"/>
										</a>
										<?php 
            }
            ?>
									<a href="javascript:;" onclick="go_template('new')">
										<img src="../pixmaps/tables/table_row_insert.png" align="absmiddle" alt="<?php 
Ejemplo n.º 6
0
                     $sensor_error = TRUE;
                 }
             }
         }
         $sname[] = $sensor_name;
         $sperm[] = "<img {$sclass} src='../pixmaps/" . (Session::sensorAllowed($sid) ? "tick" : "cross") . ".png' border='0'>";
         $vs[] = "<img {$vsclass} src='../pixmaps/" . (valid_hex32($scan_server) && $sid == $sensor_id ? "tick" : ($has_vuln_scanner ? "tick" : "cross")) . ".png' border='0'>";
         if (!$hosts_alive) {
             // don't do a Nmap scan
             $snmap[] = '<span style="font-size:9px;color:gray">' . _('No selected') . '</span>';
         } else {
             $snmap[] = "<img {$nmsclass} align='absmiddle' src='../pixmaps/" . ($scan_locally || $withnmap && $withnmapforced ? "tick" : ($withnmap ? "tick" : "cross")) . ".png' border='0'>" . ($scan_locally || $withnmap && $withnmapforced ? "<span style='font-size:9px;color:gray'>{$message_pre_scan}</span>" : ($withnmap ? "" : "<span style='font-size:9px;color:gray'>{$message_force_pre_scan}</span>"));
         }
         if ($ttargets[$target]['sensor'] == $sid) {
             $ttargets[$target]['sperm'] = Session::sensorAllowed($sid) ? TRUE : FALSE;
             $ttargets[$target]['vs'] = valid_hex32($scan_server) && $sid == $sensor_id ? TRUE : ($has_vuln_scanner ? TRUE : FALSE);
             if (!$hosts_alive) {
                 $ttargets[$target]['snmap'] = TRUE;
             } else {
                 $ttargets[$target]['snmap'] = $scan_locally || $withnmap && $withnmapforced ? TRUE : ($withnmap ? TRUE : FALSE);
             }
         }
     }
     $snames = implode('<br><br>', $sname);
 } else {
     $snames = '<span style="font-weight:bold;color:#ff0000">' . _('Sensor not found') . '</span>';
 }
 $sperms = implode('<br>', $sperm);
 $vulns = implode('<br>', $vs);
 $nmaps = implode('<br>', $snmap);
 $load = implode('<br><br>', $load);
Ejemplo n.º 7
0
function ip_max_occurrences($target, $date_from, $date_to)
{
    global $NUM_HOSTS;
    global $security_report;
    global $report_type;
    global $geoloc;
    /* ossim framework conf */
    $conf = $GLOBALS['CONF'];
    $report_graph_type = $conf->get_conf('report_graph_type');
    if (!strcmp($target, "ip_src")) {
        if ($report_type == "alarm") {
            $target = "src_ip";
        }
        $title = _("Attacker hosts");
    } elseif (!strcmp($target, "ip_dst")) {
        if ($report_type == "alarm") {
            $target = "dst_ip";
        }
        $title = _("Attacked hosts");
    }
    $list = $security_report->AttackHost($target, $NUM_HOSTS, $report_type, $date_from, $date_to);
    if (!is_array($list) || empty($list)) {
        return 0;
    }
    ?>
    <table class='t_alarms'>
        <thead>
            <tr><td colspan='2' class="headerpr"><?php 
    echo _("Top");
    echo " {$NUM_HOSTS} {$title}";
    ?>
</td></tr>
        </thead>
        
        <tbody>
            <tr>
                <td class='td_container'>
                    <table class="table_data">
                        <thead>                     
                            <tr>
                                <th> <?php 
    echo _("Host");
    ?>
 </th>
                                <th> <?php 
    echo _("Occurrences");
    ?>
 </th>
                            </tr>
                        </thead>
                        
                        <tbody>
                        <?php 
    foreach ($list as $l) {
        $ip = $l[0];
        $occurrences = number_format($l[1], 0, ",", ".");
        $id = $l[2];
        $ctx = $l[3];
        $host_output = Asset_host::get_extended_name($security_report->ossim_conn, $geoloc, $ip, $ctx, $id);
        $hostname = $host_output['name'];
        $icon = $host_output['html_icon'];
        $os = valid_hex32($id) ? Asset_host_properties::get_os_by_host($security_report->ossim_conn, $id) : "";
        $os_pixmap = preg_match("/unknown/", $os) ? '' : $os;
        $bold = $host_output['is_internal'];
        ?>
                            <tr>
                                <td class='td_data <?php 
        if ($bold) {
            echo 'bold';
        }
        ?>
'>                                
                                    <?php 
        echo $icon . ' ' . $hostname . ' ' . $os_pixmap;
        ?>
                                </td>
                                <td class='td_data'><?php 
        echo $occurrences;
        ?>
</td>
                            </tr>
                            <?php 
    }
    ?>
                        </tbody>
                    </table>
                </td>
                
                <td class='td_container'>
                    <?php 
    if ($report_graph_type == "applets") {
        jgraph_attack_graph($target, $NUM_HOSTS);
    } else {
        ?>
                        <img src="graphs/attack_graph.php?target=<?php 
        echo $target;
        ?>
&hosts=<?php 
        echo $NUM_HOSTS;
        ?>
&type=<?php 
        echo $report_type;
        ?>
&date_from=<?php 
        echo urlencode($date_from);
        ?>
&date_to=<?php 
        echo urlencode($date_to);
        ?>
" alt="attack_graph"/>
                        <?php 
    }
    ?>
                </td>                 
            </tr>
        </tbody>
    </table>
    <?php 
    return 1;
}
Ejemplo n.º 8
0
function origdetails()
{
    global $uroles, $user, $sid, $query_risk, $border, $report_id, $scantime, $scantype, $fp, $nfp, $filterip, $enableFP, $enableNotes, $output, $sortby, $dbconn, $arruser;
    global $treport, $ipl, $query_byuser, $ips_inrange, $ctx, $key;
    $colors = array("Serious" => "#FFCDFF", "High" => "#FFDBDB", "Medium" => "#FFF283", "Low" => "#FFFFC0", "Info" => "#FFFFE3");
    $images = array("Serious" => "./images/risk1.gif", "High" => "./images/risk2.gif", "Medium" => "./images/risk3.gif", "Low" => "./images/risk6.gif", "Info" => "./images/risk7.gif");
    $levels = array("Serious" => "1", "High" => "2", "Medium" => "3", "Low" => "6", "Info" => "7");
    $query_host = '';
    if ($filterip) {
        $query_host = " AND hostip='{$filterip}'";
    }
    echo "<center>";
    echo "<form>";
    echo "<table width=\"900\" class=\"noborder\" style=\"background:transparent;\">";
    echo "<tr><td style=\"text-align:left;\" class=\"nobborder\">";
    echo "<input id=\"checkboxFP\" type=\"checkbox\" onclick=\"showFalsePositives()\"> <span style=\"color:black\">" . _("View false positives") . "</span>";
    echo "</td><td class=\"nobborder\" style=\"text-align:center;\">";
    // print the icon legend
    if ($enableFP) {
        echo "<img alt='True' src='images/true.gif' border=0 align='absmiddle'> - " . _("True result") . "&nbsp;&nbsp;";
        echo "<img alt='False' src='images/false.png' border=0 align='absmiddle'> - " . _("False positive result") . "&nbsp;&nbsp;";
    }
    $feed = exists_feed_tables($dbconn);
    echo "<img alt='Info' src='images/info.png' border=0 align='absmiddle'> - " . _("Additional information is available");
    echo "</td></tr></table>";
    echo "</form>";
    echo "<br>";
    $perms_where = Session::get_ctx_where() != "" ? " AND res.ctx in (" . Session::get_ctx_where() . ")" : "";
    if ($ipl == "all") {
        $query = "select distinct res.hostIP, HEX(res.ctx) as ctx\n                    from vuln_nessus_latest_results res\n                    where falsepositive='N' \n                    {$perms_where}\n                    {$query_byuser}";
    } else {
        if (!empty($ipl) && !empty($ctx)) {
            $query = "select distinct res.hostIP, HEX(res.ctx) as ctx\n                    from vuln_nessus_latest_results res\n                    where falsepositive='N' \n                    and res.hostIP='{$ipl}'\n                    and res.ctx=UNHEX('{$ctx}')\n                    {$perms_where}\n                    {$query_byuser}";
        } else {
            if (!empty($scantime) && !empty($key)) {
                $query = "select distinct res.hostIP, HEX(res.ctx) as ctx\n                    from vuln_nessus_latest_results res, vuln_nessus_latest_reports rep\n                    where res.falsepositive='N'\n                    and res.scantime='{$scantime}' \n                    and res.hostIP=rep.hostIP\n                    and res.ctx=rep.ctx\n                    and res.username=rep.username\n                    and res.sid=rep.sid\n                    {$perms_where}\n                    and rep.report_key='{$key}' {$query_byuser}";
            }
        }
    }
    $resultp = $dbconn->execute($query);
    $host_range = array_keys($ips_inrange);
    while (list($hostip, $hostctx) = $resultp->fields) {
        $host_id = key(Asset_host::get_id_by_ips($dbconn, $hostip, $hostctx));
        if (valid_hex32($host_id)) {
            $hostname = Asset_host::get_name_by_id($dbconn, $host_id);
        } else {
            $hostname = _('unknown');
        }
        if (in_array($hostip . ";" . $hostctx, $host_range)) {
            echo "<div class='hostip'>";
            echo "<br><font color='red'><b><a name='{$hostip};{$hostctx}' href='javascript:;' ctx='{$hostctx}' id='{$hostip};{$hostname}' class='HostReportMenu'>{$hostip} - {$hostname}</a></b></font>";
            echo "<br><br><table summary=\"{$hostip} - " . _("Reported Ports") . "\">";
            echo "<tr><th colspan=2>" . _("Reported Ports") . "</th></tr>";
            if (!empty($scantime) && !empty($key)) {
                $query = "select distinct res.port, res.protocol\n                from vuln_nessus_latest_results res, vuln_nessus_latest_reports rep\n                where res.falsepositive='N'\n                and res.scantime='{$scantime}' \n                and res.hostIP=rep.hostIP\n                and res.ctx=rep.ctx\n                and res.username=rep.username\n                and res.sid=rep.sid\n                and res.hostIP='{$hostip}'\n                and res.ctx='{$hostctx}'\n                and rep.report_key='{$key}' {$query_byuser}) as t group by risk";
            } else {
                $query = "select distinct res.port, res.protocol\n                            from vuln_nessus_latest_results res \n                            where hostip='{$hostip}' and ctx=UNHEX('{$hostctx}') {$query_byuser} AND port > '0' ORDER BY port ASC";
            }
            $result1 = $dbconn->execute($query);
            $k = 1;
            $pos = '';
            if (!$result1->fields) {
                print "<tr><td>" . _("No reported ports found") . "</td></tr>";
            } else {
                while (list($port, $proto) = $result1->fields) {
                    if ($k % 2) {
                        echo "<tr><td>{$port}/{$proto}</td>";
                        $pos = "open";
                    } else {
                        echo "<td>{$port}/{$proto}</td></tr>";
                        $pos = "closed";
                    }
                    $k++;
                    $result1->MoveNext();
                }
                // end while
                // close up the table
                if ($pos != "closed") {
                    echo "<td>&nbsp;</td></tr>";
                }
            }
            echo "</table><br/>";
            echo "<table width='900' summary='{$hostip} - risks'><tr>";
            echo "<th>" . _("Vuln Name") . "</th>";
            echo "<th>" . _("VulnID") . "</th>";
            echo "<th>" . _("Service") . "</th>";
            echo "<th>" . _("Severity") . "</th>";
            echo "</tr>";
            if (!empty($scantime) && !empty($key)) {
                if ($feed) {
                    $query = "select res.result_id, res.service, res.risk, res.falsepositive, res.scriptid, v.name, res.msg, rep.sid\n                        from vuln_nessus_latest_results AS res LEFT JOIN vuln_nessus_plugins AS v ON v.id=res.scriptid, vuln_nessus_latest_reports rep\n                        where res.msg<>''\n                        and res.scantime='{$scantime}' \n                        and res.hostIP=rep.hostIP\n                        and res.ctx=rep.ctx\n                        and res.hostIP='{$hostip}'\n                        and res.ctx=UNHEX('{$hostctx}')\n                        and res.username=rep.username\n                        and res.sid=rep.sid\n                        and rep.report_key='{$key}' and rep.sid>=0 {$query_byuser}\n                        UNION DISTINCT\n                        select res.result_id, res.service, res.risk, res.falsepositive, res.scriptid, v.name, res.msg, rep.sid\n                        from vuln_nessus_latest_results AS res LEFT JOIN vuln_nessus_plugins_feed AS v ON v.id=res.scriptid, vuln_nessus_latest_reports rep\n                        where res.msg<>''\n                        and res.scantime='{$scantime}' \n                        and res.hostIP=rep.hostIP\n                        and res.ctx=rep.ctx\n                        and res.hostIP='{$hostip}'\n                        and res.ctx=UNHEX('{$hostctx}')\n                        and res.username=rep.username\n                        and res.sid=rep.sid\n                        and rep.report_key='{$key}' and rep.sid<0 {$query_byuser}\n                        ";
                } else {
                    $query = "select res.result_id, res.service, res.risk, res.falsepositive, res.scriptid, v.name, res.msg, rep.sid\n                        from vuln_nessus_latest_results AS res LEFT JOIN vuln_nessus_plugins AS v ON v.id=res.scriptid, vuln_nessus_latest_reports rep\n                        where res.msg<>''\n                        and res.scantime='{$scantime}' \n                        and res.hostIP=rep.hostIP\n                        and res.ctx=rep.ctx\n                        and res.hostIP='{$hostip}'\n                        and res.ctx=UNHEX('{$hostctx}')\n                        and res.username=rep.username\n                        and res.sid=rep.sid\n                        and rep.report_key='{$key}' {$query_byuser}";
                }
            } else {
                if ($feed) {
                    $query = "select res.result_id, res.service, res.risk, res.falsepositive, res.scriptid, v.name, res.msg, rep.sid\n                    FROM vuln_nessus_latest_results res LEFT JOIN vuln_nessus_plugins AS v ON v.id=res.scriptid, vuln_nessus_latest_reports rep\n                    WHERE\n                    res.hostIP=rep.hostIP\n                    and res.ctx=rep.ctx\n                    and res.username=rep.username\n                    and res.sid=rep.sid\n                    and res.hostIP='{$hostip}'\n                    and res.ctx=UNHEX('{$hostctx}')\n                    {$query_byuser} and msg<>'' and rep.sid>=0\n                    UNION DISTINCT\n                    select res.result_id, res.service, res.risk, res.falsepositive, res.scriptid, v.name, res.msg, rep.sid\n                    FROM vuln_nessus_latest_results res LEFT JOIN vuln_nessus_plugins_feed AS v ON v.id=res.scriptid, vuln_nessus_latest_reports rep\n                    WHERE\n                    res.hostIP=rep.hostIP\n                    and res.ctx=rep.ctx\n                    and res.username=rep.username\n                    and res.sid=rep.sid\n                    and res.hostIP='{$hostip}'\n                    and res.ctx=UNHEX('{$hostctx}')\n                    {$query_byuser} and msg<>'' and rep.sid<0";
                } else {
                    $query = "select res.result_id, res.service, res.risk, res.falsepositive, res.scriptid, v.name, res.msg, rep.sid\n                    FROM vuln_nessus_latest_results res LEFT JOIN vuln_nessus_plugins AS v ON v.id=res.scriptid, vuln_nessus_latest_reports rep\n                    WHERE\n                    res.hostIP=rep.hostIP\n                    and res.ctx=rep.ctx\n                    and res.username=rep.username\n                    and res.sid=rep.sid\n                    and res.hostIP='{$hostip}'\n                    and res.ctx=UNHEX('{$hostctx}')\n                    {$query_byuser} and msg<>''";
                }
            }
            $query .= " group by risk, port, protocol, app, scriptid, msg  order by risk";
            $result1 = $dbconn->execute($query);
            $arrResults = array();
            while (list($result_id, $service, $risk, $falsepositive, $scriptid, $pname, $msg, $sid) = $result1->fields) {
                $tmpport1 = preg_split("/\\(|\\)/", $service);
                if (sizeof($tmpport1) == 1) {
                    $tmpport1[1] = $tmpport1[0];
                }
                $tmpport2 = preg_split("/\\//", $tmpport1[1]);
                $service_num = $tmpport2[0];
                $service_proto = $tmpport2[1];
                $arrResults[] = array($service_num, $service_proto, $service, $risk, $falsepositive, $result_id, $msg, $scriptid, $pname, $sid);
                $result1->MoveNext();
            }
            if (empty($arrResults)) {
                // empty, print out message
                echo "<tr><td colspan='4'>" . _("No vulnerability results matching this reports filtering criteria were found") . ".</td></tr>";
            }
            foreach ($arrResults as $arrkey => $value) {
                list($service_num, $service_proto, $service, $risk, $falsepositive, $resid, $msg, $scriptid, $pname, $sid) = $value;
                $msg = preg_replace("/^[ \t]*/", "", $msg);
                $cves_found = "";
                if (preg_match_all("/CVE\\-\\d+\\-\\d+/i", $msg, $found)) {
                    $cves_found = implode(" ", $found[0]);
                }
                $msg = preg_replace("/[\n\r]/", "<br>", $msg);
                $msg = wordwrap($msg, 100, "<br>", 1);
                $tmprisk = getrisk($risk);
                $msg = preg_replace("/^\\<br\\>/i", "", str_replace("\\r", "", $msg));
                $msg = preg_replace("/(Solution|Summary|Details|Overview|Synopsis|Description|See also|Plugin output|References|Vulnerability Insight|Vulnerability Detection|Impact|Impact Level|Affected Software\\/OS|Fix|Information about this scan)\\s*:/", "<b>\\1:</b>", $msg);
                // output the table cells
                $ancla = $hostip . "_" . $hostctx . "_" . $levels[$tmprisk];
                $pname = $pname != "" ? $pname : _("No name");
                echo "<tr " . ($falsepositive == 'Y' ? "class=\"trsk risk{$risk} fp\"" : "class=\"trsk risk{$risk}\"") . "style=\"background-color:" . $colors[$tmprisk] . ($falsepositive == 'Y' ? ";display:none;" : "") . "\">";
                //echo "<tr>";
                echo "<td width=\"50%\" style=\"padding:3px 0px 3px 0px;\"><b>" . $pname . "</b></td>";
                echo "<td style=\"padding:3px 0px 3px 0px;\">{$scriptid}</td>";
                ?>
    
                <td style="padding:3px;" width="180"><?php 
                echo $service;
                ?>
</td>
                <td style="text-align:center;">
                    <?php 
                echo $tmprisk;
                ?>
&nbsp;&nbsp;<img align="absmiddle" src="<?php 
                echo $images[$tmprisk];
                ?>
" style="border: 1px solid ; width: 25px; height: 10px;">
                </td>
            </tr>
            
            <?php 
                echo "<tr " . ($falsepositive == 'Y' ? "class=\"trsk risk{$risk} fp\"" : "class=\"trsk risk{$risk}\"") . "style=\"background-color:" . $colors[$tmprisk] . ($falsepositive == 'Y' ? ";display:none;" : "") . "\">";
                ?>
                <td style="padding:3px 0px 3px 6px;text-align:left;">
                    <a class="msg" name="<?php 
                echo $resid;
                ?>
"></a>
                    <a name="<?php 
                echo $ancla;
                ?>
"></a>
                        <?php 
                echo $msg;
                ?>
                    <font size="1">
                    <br><br>
                    </font>
    
                    <?php 
                if ($cves_found != '') {
                    ?>
                        <a title="<?php 
                    echo _("Info from cve.mitre.org");
                    ?>
" target="cve_mitre_org" href="http://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=<?php 
                    echo urlencode($cves_found);
                    ?>
"><img src="images/cve_mitre.png" border='0'></a>
                         <!--Add link to popup with Script Info-->
                        <?php 
                }
                if ($scriptid != "0") {
                    ?>
                        <!--Add link to popup with Script Info-->
                        <div lid="<?php 
                    echo $scriptid;
                    ?>
" style="text-decoration:none;display:inline" class="scriptinfo"><img alt="Info" src="images/info.png" border=0></div>
                        <?php 
                }
                $tmpu = array();
                $url = "";
                foreach ($_GET as $kget => $vget) {
                    if ($kget != "pluginid" && $kget != "nfp" && $kget != "fp") {
                        $tmpu[] = Util::htmlentities($kget) . "=" . urlencode($vget);
                    }
                }
                $url = implode("&", $tmpu);
                if ($falsepositive == "Y") {
                    ?>
                        <a href="<?php 
                    echo $_SERVER['SCRIPT_NAME'] . '?' . $url;
                    ?>
&nfp=<?php 
                    echo $resid;
                    ?>
">
                            <img alt="<?php 
                    echo _("Clear false positive");
                    ?>
" src='images/false.png' title='<?php 
                    echo _("Clear false positive");
                    ?>
' border='0' />
                        </a>
                        <?php 
                } else {
                    ?>
                        <a href="<?php 
                    echo $_SERVER['SCRIPT_NAME'] . '?' . $url;
                    ?>
&fp=<?php 
                    echo $resid;
                    ?>
">
                            <img alt="<?php 
                    echo _("Mark as false positive");
                    ?>
" src='images/true.gif' title='<?php 
                    echo _("Mark as false positive");
                    ?>
' border='0' />
                        </a>
                        <?php 
                }
                $pticket = "ref=Vulnerability&title=" . urlencode($pname) . "&priority=1&ip=" . urlencode($hostip) . "&port=" . urlencode($service_num) . "&nessus_id=" . urlencode($scriptid) . "&risk=" . urlencode($tmprisk) . "&type=" . urlencode("Nessus Vulnerability");
                echo "<a title=\"" . _("New ticket") . "\" class=\"greybox\" href=\"../incidents/newincident.php?{$pticket}\"><img style=\"padding-bottom:2px;\" src=\"../pixmaps/script--pencil.png\" border=\"0\" alt=\"i\" width=\"12\"></a>&nbsp;&nbsp;";
                ?>
                </td>
        
                <?php 
                if ($sid < 0) {
                    $plugin_info = $dbconn->execute("SELECT t2.name, t3.name, t1.copyright, t1.summary, t1.version \n                            FROM vuln_nessus_plugins_feed t1\n                            LEFT JOIN vuln_nessus_family_feed t2 on t1.family=t2.id\n                            LEFT JOIN vuln_nessus_category_feed t3 on t1.category=t3.id\n                            WHERE t1.id='{$scriptid}'");
                } else {
                    $plugin_info = $dbconn->execute("SELECT t2.name, t3.name, t1.copyright, t1.summary, t1.version \n                            FROM vuln_nessus_plugins t1\n                            LEFT JOIN vuln_nessus_family t2 on t1.family=t2.id\n                            LEFT JOIN vuln_nessus_category t3 on t1.category=t3.id\n                            WHERE t1.id='{$scriptid}'");
                }
                list($pfamily, $pcategory, $pcopyright, $psummary, $pversion) = $plugin_info->fields;
                ?>
        
                <td colspan="3" valign="top" style="text-align:left;padding:3px;">
                    <?php 
                $plugindetails = '';
                if ($pfamily != '') {
                    $plugindetails .= '<b>Family name:</b> ' . $pfamily . '<br><br>';
                }
                if ($pcategory != '') {
                    $plugindetails .= '<b>Category:</b> ' . $pcategory . '<br><br>';
                }
                if ($pcopyright != '') {
                    $plugindetails .= '<b>Copyright:</b> ' . $pcopyright . '<br><br>';
                }
                if ($psummary != '') {
                    $plugindetails .= '<b>Summary:</b> ' . $psummary . '<br><br>';
                }
                if ($pversion != '') {
                    $plugindetails .= '<b>Version:</b> ' . $pversion . '<br><br>';
                }
                echo $plugindetails;
                ?>
                </td>
            </tr>
            <?php 
                $result1->MoveNext();
            }
            echo "</table>";
            echo "</div>";
        }
        $resultp->MoveNext();
    }
    echo "</center>";
}
Ejemplo n.º 9
0
 $ret = NULL;
 $data['status'] = 'success';
 try {
     $new_agent = Ossec_agent::create($sensor_id, $agent_name, $ip_cidr, $asset_id);
     //If ossec-remoted is not running, we have to restart Ossec Server
     $ossec_status = Ossec_control::execute_action($sensor_id, 'status');
     if ('UP' !== $ossec_status['general_status']['ossec-remoted']) {
         Ossec_control::execute_action($sensor_id, 'restart');
     }
     if (is_array($new_agent) && !empty($new_agent)) {
         $agent_id = $new_agent['id'];
         $agent_info = array('name' => $new_agent['name'], 'ip_cidr' => $new_agent['ip_cidr'], 'status' => $new_agent['status']);
         $agent_actions = Ossec_agent::get_actions($agent_id, $new_agent);
         $data['data'] = _("HIDS agent has been created. To deploy the agent, please choose one of the options under the 'Actions' column") . "###" . $agent_id . "###";
         $a_unique_id = md5($agent_id);
         if (valid_hex32($new_agent['host_id'])) {
             $db = new Ossim_db();
             $conn = $db->connect();
             $asset_name = Asset_host::get_name_by_id($conn, $new_agent['host_id']);
             $db->close();
         } else {
             $asset_name = '-';
         }
         //Normalize status description (See asset list filters)
         if ($new_agent['status']['id'] == 1) {
             $new_agent['status']['descr'] = 'Disconnected';
         }
         $agent_elem = array("DT_RowId" => 'cont_agent_' . $agent_id, "DT_RowData" => array('agent_key' => $a_unique_id, 'asset_id' => $new_agent['host_id'], 'agent_status' => $new_agent['status']), '', $agent_id, $new_agent['name'], $asset_name, $new_agent['ip_cidr'], "-", "-", $new_agent['status']['descr'], $agent_actions);
         $data['data'] .= json_encode(array($agent_elem));
     }
 } catch (Exception $e) {
Ejemplo n.º 10
0
$user = $argv[5];
$autodetect = $argv[6] == '0' || $argv[3] == 'vulnscan' ? FALSE : TRUE;
$rdns = $argv[7] == '0' ? FALSE : TRUE;
$ports = $argv[8];
// When type is custom, specific ports
// Check targets
$target_array = explode(" ", $targets);
foreach ($target_array as $target) {
    ossim_valid($target, OSS_IP_ADDRCIDR, 'illegal:' . _('Target'));
    if (ossim_error()) {
        $error_message[] = "Incorrect asset format in {$target}";
        ossim_set_error(FALSE);
    }
}
// Check remote sensor
if (!valid_hex32($remote_sensor) && $remote_sensor != 'null' && !empty($remote_sensor)) {
    ossim_valid($remote_sensor, OSS_IP_ADDR, 'illegal:' . _('Remote sensor'));
}
if (ossim_error()) {
    $error_message[] = 'Illegal remote sensor';
    ossim_set_error(FALSE);
}
// check timing template
ossim_valid($timing_template, OSS_NULLABLE, OSS_TIMING_TEMPLATE, 'illegal:' . _('Timing Template'));
if (ossim_error()) {
    $error_message[] = 'Illegal timing template';
    ossim_set_error(FALSE);
}
// check scan type
ossim_valid($scan_type, OSS_NULLABLE, OSS_ALPHA, 'illegal:' . _('Scan type'));
if (ossim_error()) {
Ejemplo n.º 11
0
             $db = new ossim_db();
             $conn = $db->connect();
             $num_assets = Filter_list::get_total_selection($conn, 'asset');
             $asset_group = new Asset_group($group_id);
             $asset_group->save_assets_from_search($conn);
             $db->close();
             $data['status'] = 'success';
             $data['data'] = sprintf(_("%s assets have been added to group"), $num_assets);
         } catch (Exception $e) {
             Util::response_bad_request(_('Error! Selected assets could not be added') . ': ' . $e->getMessage());
         }
     }
     break;
 case 'delete_assets':
     $group_id = POST('asset_id');
     if (!valid_hex32($group_id)) {
         Util::response_bad_request(_('Error! Asset group ID not allowed. Selected assets could not be removed'));
     } else {
         try {
             $db = new ossim_db();
             $conn = $db->connect();
             $num_assets = Filter_list::get_total_selection($conn, 'asset');
             $asset_group = new Asset_group($group_id);
             $asset_group->delete_selected_assets($conn);
             $db->close();
             $data['status'] = 'success';
             $data['data'] = sprintf(_("%s assets have been deleted from group"), $num_assets);
         } catch (Exception $e) {
             Util::response_bad_request(_('Error! Selected assets could not be deleted') . ': ' . $e->getMessage());
         }
     }
Ejemplo n.º 12
0
         unset($_ctx);
     }
 }
 if (!empty($id) && Asset_host::is_in_db($conn, $id)) {
     ossim_valid($id, OSS_HEX, 'illegal:' . _('Asset ID'));
     if (ossim_error()) {
         echo ossim_error(_('Error! Asset not found'));
         exit;
     }
     $asset = new Asset_host($conn, $id);
     $asset->load_from_db($conn);
     $is_in_db = 1;
     $is_editable = Asset_host::can_i_modify_ips($conn, $id) ? 'yes' : 'no_ip';
 } else {
     //New asset or asset has been deleted but there are some instances in the system (SIEM, alarms, ...)
     $id = valid_hex32($id) ? $id : Util::uuid();
     $asset = new Asset_host($conn, $id);
     if (isset($_ip) && isset($_ctx)) {
         $asset->set_ctx($_ctx);
         $ext_ips[$_ip] = array('ip' => $_ip, 'mac' => NULL);
         $asset->set_ips($ext_ips);
     }
 }
 //Getting asset data
 $id = $asset->get_id();
 $ctx = $asset->get_ctx();
 $_ips = $asset->get_ips();
 $ips = $_ips->get_ips();
 if (is_array($ips) && !empty($ips)) {
     $ips = array_keys($ips);
 }
Ejemplo n.º 13
0
function tab_discovery()
{
    global $component, $uroles, $editdata, $scheduler, $username, $useremail, $dbconn, $disp, $enScanRequestImmediate, $enScanRequestRecur, $timeout, $smethod, $SVRid, $sid, $ip_list, $ip_exceptions_list, $schedule_type, $ROYEAR, $ROday, $ROMONTH, $time_hour, $time_min, $dayofweek, $dayofmonth, $sname, $user, $entity, $hosts_alive, $scan_locally, $version, $nthweekday, $semail, $not_resolve, $time_interval, $ssh_credential, $smb_credential, $net_id;
    global $pluginOptions, $enComplianceChecks, $profileid;
    $conf = $GLOBALS["CONF"];
    $users = Session::get_users_to_assign($dbconn);
    $entities_to_assign = Session::get_entities_to_assign($dbconn);
    $pre_scan_locally_status = $conf->get_conf("nessus_pre_scan_locally");
    $user_selected = $user;
    $entity_selected = $entity;
    $SVRid_selected = $SVRid;
    $sid_selected = $sid != "" ? $sid : $editdata['meth_VSET'];
    $timeout_selected = $editdata["meth_TIMEOUT"];
    $ip_list_selected = str_replace("\\r\\n", "\n", str_replace(";;", "\n", $ip_list));
    if (count($ip_exceptions_list) > 0) {
        $ip_list_selected .= "\n" . implode("\n", $ip_exceptions_list);
    }
    $ROYEAR_selected = $ROYEAR;
    $ROday_selected = $ROday;
    $ROMONTH_selected = $ROMONTH;
    $time_hour_selected = $time_hour;
    $time_min_selected = $time_min;
    $dayofweek_selected = $dayofweek;
    $dayofmonth_selected = $dayofmonth;
    $sname_selected = $sname;
    if (preg_match("/^[a-f\\d]{32}\$/i", $net_id)) {
        // Autofill new scan job from deployment
        if (Asset_net::is_in_db($dbconn, $net_id)) {
            $sname_selected = Asset_net::get_name_by_id($dbconn, $net_id);
            $schedule_type = "M";
            $ip_list = array();
            $nips = explode(",", Asset_net::get_ips_by_id($dbconn, $net_id));
            foreach ($nips as $nip) {
                $ip_list[] = $net_id . "#" . trim($nip);
            }
        }
    }
    if ($schedule_type != "") {
        $editdata['schedule_type'] = $schedule_type;
    }
    $cquery_like = "";
    if ($component != "") {
        $cquery_like = " AND component='{$component}'";
    }
    $today = date("Ymd");
    $tyear = substr($today, 0, 4);
    $nyear = $tyear + 1;
    $tmonth = substr($today, 4, 2);
    $tday = substr($today, 6, 2);
    #SET VALUES UP IF EDIT SCHEDULER
    if (isset($editdata['notify'])) {
        $enotify = $editdata['notify'];
    } else {
        $enotify = "{$useremail}";
    }
    if (isset($editdata['time'])) {
        list($time_hour, $time_min, $time_sec) = split(':', $editdata['time']);
        $tz = Util::get_timezone();
        $time_hour = $time_hour + $tz;
    }
    $arrTypes = array("N", "O", "D", "W", "M", "NW");
    foreach ($arrTypes as $type) {
        $sTYPE[$type] = "";
    }
    $arrJobTypes = array("C", "M", "R", "S");
    foreach ($arrJobTypes as $type) {
        $sjTYPE[$type] = "";
    }
    if (isset($editdata['schedule_type'])) {
        $sTYPE[$editdata['schedule_type']] = "selected='selected'";
        if ($editdata['schedule_type'] == 'D') {
            $ni = 2;
        } elseif ($editdata['schedule_type'] == 'O') {
            $ni = 3;
        } elseif ($editdata['schedule_type'] == 'W') {
            $ni = 4;
        } elseif ($editdata['schedule_type'] == 'NW') {
            $ni = 6;
        } else {
            $ni = 5;
        }
        $show = "<br><script language=javascript>showLayer('idSched', {$ni});</script>";
    } else {
        if ($enScanRequestImmediate) {
            $sTYPE['N'] = "selected='selected'";
            $show = "<br><script language=javascript>showLayer('idSched', 1);</script>";
        } else {
            $sTYPE['O'] = "selected='selected'";
            $show = "<br><script language=javascript>showLayer('idSched', 3);</script>";
        }
    }
    if ($schedule_type != "") {
        if ($schedule_type == "N") {
            $show .= "<br><script language=javascript>showLayer('idSched', 1);</script>";
        }
        if ($schedule_type == "O") {
            $show .= "<br><script language=javascript>showLayer('idSched', 3);</script>";
        }
        if ($schedule_type == "D") {
            $show .= "<br><script language=javascript>showLayer('idSched', 2);</script>";
        }
        if ($schedule_type == "W") {
            $show .= "<br><script language=javascript>showLayer('idSched', 4);</script>";
        }
        if ($schedule_type == "M") {
            $show .= "<br><script language=javascript>showLayer('idSched', 5);</script>";
        }
        if ($schedule_type == "NW") {
            $show .= "<br><script language=javascript>showLayer('idSched', 6);</script>";
        }
    }
    if (isset($editdata['job_TYPE'])) {
        $sjTYPE[$editdata['job_TYPE']] = "SELECTED";
    } else {
        $sjTYPE['M'] = "SELECTED";
    }
    if (isset($editdata['day_of_month'])) {
        $dayofmonth = $editdata['day_of_month'];
    }
    if (isset($editdata['day_of_week'])) {
        $day[$editdata['day_of_week']] = "SELECTED";
    }
    if ($dayofweek_selected != "") {
        $day[$dayofweek_selected] = "SELECTED";
    }
    if (!$uroles['nessus']) {
        $name = "sr-" . substr($username, 0, 6) . "-" . time();
        $name = $editdata['name'] == "" ? $name : $editdata['name'];
        $nameout = $name . "<input type=hidden style='width:210px' name='sname' value='{$name}'>";
    } else {
        $nameout = "<input type=text style='width:210px' name='sname' value='" . ($sname_selected != "" ? "{$sname_selected}" : "{$editdata['name']}") . "'>";
    }
    $discovery = "<input type=\"hidden\" name=\"save_scan\" value=\"1\">";
    $discovery .= "<input type=\"hidden\" name=\"cred_type\" value=\"N\">";
    $discovery .= "<table width=\"80%\" cellspacing=\"4\">";
    $discovery .= "<tr>";
    $discovery .= "<input type=\"hidden\" name=\"smethod\" value=\"{$smethod}\">";
    $discovery .= "<td width=\"25%\" class='job_option'>" . Util::strong(_("Job Name") . ":") . "</td>";
    $discovery .= "<td style=\"text-align:left;\">{$nameout}</td>";
    $discovery .= "</tr>";
    list($sensor_list, $total) = Av_sensor::get_list($dbconn);
    $discovery .= "<tr>";
    $discovery .= "<td class='job_option'>" . Util::strong(_("Select Server") . ":") . "</td>";
    $discovery .= "<td style='text-align:left;'><select id='SVRid' style='width:212px' name='SVRid'>";
    $discovery .= "<option value='Null'>" . _("First Available Server-Distributed") . "</option>";
    foreach ($sensor_list as $_sensor_id => $sensor_data) {
        if (intval($sensor_data['properties']['has_vuln_scanner']) == 1) {
            $discovery .= "<option value=\"{$_sensor_id}\" ";
            if ($editdata['email'] == $_sensor_id || $editdata['scan_ASSIGNED'] == $_sensor_id) {
                $discovery .= " SELECTED";
            }
            if ($SVRid_selected == $_sensor_id) {
                $discovery .= " SELECTED";
            }
            $discovery .= ">" . strtoupper($sensor_data['name']) . " [" . $sensor_data['ip'] . "] </option>";
        }
    }
    $discovery .= <<<EOT
      </select>
    </td>
  </tr>
  <tr>
EOT;
    $discovery .= "<td class='job_option'>" . Util::strong(_("Profile") . ":") . "</td>";
    $discovery .= "<td style='text-align:left;'><select name='sid'>";
    $query = "";
    if ($username == "admin" || Session::am_i_admin()) {
        $query = "SELECT distinct(t1.id), t1.name, t1.description \n                 FROM vuln_nessus_settings t1 WHERE deleted='0'\n                 ORDER BY t1.name";
    } else {
        if (Session::is_pro()) {
            $users_and_entities = Acl::get_entities_to_assign($dbconn);
            if (Acl::am_i_proadmin()) {
                $users = Acl::get_my_users($dbconn, Session::get_session_user());
                foreach ($users as $us) {
                    $users_and_entities[$us->get_login()] = $us->get_login();
                }
                $owner_list['0'] = '0';
                $owner_list = array_keys($users_and_entities);
                $owner_list = implode("','", $owner_list);
                $query = "SELECT distinct(t1.id), t1.name, t1.description FROM vuln_nessus_settings t1\n                      WHERE deleted = '0' and (name='Default' or owner in ('" . $owner_list . "')) ORDER BY t1.name";
            } else {
                $owner_list['0'] = '0';
                $owner_list[$username] = $username;
                $owner_list = array_keys($users_and_entities);
                $owner_list[] = Session::get_session_user();
                $owner_list = implode("','", $owner_list);
                $user_where = "owner in ('" . $owner_list . "')";
                $query = "SELECT distinct(t1.id), t1.name, t1.description FROM vuln_nessus_settings t1\n                      WHERE deleted = '0' and (name='Default' or {$user_where}) ORDER BY t1.name";
            }
        } else {
            $query = "SELECT distinct(t1.id), t1.name, t1.description FROM vuln_nessus_settings t1\n                     WHERE deleted = '0' and (name='Default' or owner in ('0','{$username}')) ORDER BY t1.name";
        }
    }
    $dbconn->SetFetchMode(ADODB_FETCH_BOTH);
    $result = $dbconn->execute($query);
    $job_profiles = array();
    $id_found = false;
    $ipr = 0;
    while (!$result->EOF) {
        list($sid, $sname, $sdescription) = $result->fields;
        if ($sid_selected == $sid) {
            $id_found = true;
        }
        $job_profiles[$ipr]["sid"] = $sid;
        $job_profiles[$ipr]["sname"] = $sname;
        $job_profiles[$ipr]["sdescription"] = $sdescription;
        $ipr++;
        $result->MoveNext();
    }
    foreach ($job_profiles as $profile_data) {
        $sid = $profile_data["sid"];
        $sname = $profile_data["sname"];
        $sdescription = $profile_data["sdescription"];
        $discovery .= "<option value=\"{$sid}\" ";
        if ($sid_selected == $sid) {
            if ($sdescription != "") {
                $discovery .= "selected>{$sname} - {$sdescription}</option>";
            } else {
                $discovery .= "selected>{$sname}</option>";
            }
        } else {
            if ($sdescription != "") {
                $discovery .= (preg_match("/default/i", $sname) && !$id_found ? 'selected="selected"' : "") . ">{$sname} - {$sdescription}</option>";
            } else {
                $discovery .= (preg_match("/default/i", $sname) && !$id_found ? 'selected="selected"' : "") . ">{$sname}</option>";
            }
        }
    }
    $discovery .= "</select>&nbsp;&nbsp;&nbsp<a href=\"" . Menu::get_menu_url('settings.php', 'environment', 'vulnerabilities', 'scan_jobs') . "\">[" . _("EDIT PROFILES") . "]</a></td>";
    $discovery .= "</tr>";
    $discovery .= "<tr>";
    $discovery .= "<td class='job_option' style='vertical-align: top;'><div>" . Util::strong(_("Schedule Method") . ":") . "</div></td>";
    $discovery .= "<td style='text-align:left'><div><select name='schedule_type' id='scheduleM'>";
    $discovery .= "<option value='N' {$sTYPE['N']}>" . _("Immediately") . "</option>";
    $discovery .= "<option value='O' {$sTYPE['O']}>" . _("Run Once") . "</option>";
    $discovery .= "<option value='D' {$sTYPE['D']}>" . _("Daily") . "</option>";
    $discovery .= "<option value='W' {$sTYPE['W']}>" . _("Day of the Week") . "</option>";
    $discovery .= "<option value='M' {$sTYPE['M']}>" . _("Day of the Month") . "</option>";
    $discovery .= "<option value='NW' {$sTYPE['NW']}>" . _("N<sup>th</sup> weekday of the month") . "</option>";
    $discovery .= "</select></div></tr>";
    $smethods = array("O", "D", "W", "M", "NW");
    $smethodtr_display = in_array($editdata['schedule_type'], $smethods) ? "" : "style='display:none'";
    $discovery .= "<tr {$smethodtr_display} id='smethodtr'><td>&nbsp;</td>";
    $discovery .= <<<EOT
    </td>
    <td><div>
      <div id="idSched1" class="forminput">
      </div>
EOT;
    // div to select start day
    $discovery .= "<div id=\"idSched8\" class=\"forminput\">";
    $discovery .= "<table cellspacing=\"2\" cellpadding=\"0\" width=\"100%\">";
    $discovery .= "<tr><th width='35%'>" . _("Begin in") . "</th><td class='noborder' nowrap='nowrap'>" . gettext("Year") . "&nbsp;<select name='biyear'>";
    $discovery .= "<option value=\"{$tyear}\" selected>{$tyear}</option>";
    $discovery .= "<option value=\"{$nyear}\" >{$nyear}</option>";
    $discovery .= "</select>&nbsp;&nbsp;&nbsp;" . gettext("Month") . "&nbsp;<select name='bimonth'>";
    for ($i = 1; $i <= 12; $i++) {
        $discovery .= "<option value=\"{$i}\" ";
        if ($i == $tmonth) {
            $discovery .= "selected";
        }
        $discovery .= ">{$i}</option>";
    }
    $discovery .= "</select>&nbsp;&nbsp;&nbsp;" . gettext("Day") . "&nbsp;<select name=\"biday\">";
    for ($i = 1; $i <= 31; $i++) {
        $discovery .= "<option value=\"{$i}\" ";
        if ($i == $tday) {
            $discovery .= "selected";
        }
        $discovery .= ">{$i}</option>";
    }
    $discovery .= "</select></td>";
    $discovery .= "</tr>";
    $discovery .= "</table>";
    $discovery .= "</div>";
    $discovery .= <<<EOT
      <div id="idSched3" class="forminput">
        <table cellspacing="2" cellpadding="0" width="100%">
EOT;
    $discovery .= "<tr><th width='35%'>" . _("Day") . "</th><td colspan='6' class='noborder' nowrap='nowrap'>" . gettext("Year") . "&nbsp;<select name='ROYEAR'>";
    $discovery .= "<option value=\"{$tyear}\" " . ($ROYEAR_selected == "" || $ROYEAR_selected == $tyear ? "selected" : "") . ">{$tyear}</option>";
    $discovery .= "<option value=\"{$nyear}\" " . ($ROYEAR_selected == $nyear ? "selected" : "") . ">{$nyear}</option>";
    $discovery .= "</select>&nbsp;&nbsp;&nbsp;" . gettext("Month") . "&nbsp;<select name='ROMONTH'>";
    for ($i = 1; $i <= 12; $i++) {
        $discovery .= "<option value=\"{$i}\" ";
        if ($i == $tmonth && $ROMONTH_selected == "" || $ROMONTH_selected == $i) {
            $discovery .= "selected";
        }
        $discovery .= ">{$i}</option>";
    }
    $discovery .= "</select>&nbsp;&nbsp;&nbsp;" . gettext("Day") . "&nbsp;<select name=\"ROday\">";
    for ($i = 1; $i <= 31; $i++) {
        $discovery .= "<option value=\"{$i}\" ";
        if ($i == $tday && $ROday_selected == "" || $ROday_selected == $i) {
            $discovery .= "selected";
        }
        $discovery .= ">{$i}</option>";
    }
    $discovery .= <<<EOT
            </select></td>
          </tr>
        </table>
      </div>
      <div id="idSched4" class="forminput" > 
        <table width="100%">
          <tr>
EOT;
    $discovery .= "<th align=\"right\" width=\"35%\">" . _("Weekly") . "</th><td colspan=\"2\" class=\"noborder\">";
    $discovery .= "<select name=\"dayofweek\">";
    $discovery .= "<option value=\"Su\" SELECTED >" . gettext("Select week day to run") . "</option>";
    $discovery .= "<option value=\"Su\" {$day['Su']} >" . gettext("Sunday") . "</option>";
    $discovery .= "<option value=\"Mo\" {$day['Mo']} >" . gettext("Monday") . "</option>";
    $discovery .= "<option value=\"Tu\" {$day['Tu']} >" . gettext("Tuesday") . "</option>";
    $discovery .= "<option value=\"We\" {$day['We']} >" . gettext("Wednesday") . "</option>";
    $discovery .= "<option value=\"Th\" {$day['Th']} >" . gettext("Thursday") . "</option>";
    $discovery .= "<option value=\"Fr\" {$day['Fr']} >" . gettext("Friday") . "</option>";
    $discovery .= "<option value=\"Sa\" {$day['Sa']} >" . gettext("Saturday") . "</option>";
    $discovery .= "</select>";
    $discovery .= "</td>";
    $discovery .= <<<EOT
          </tr>
        </table>
      </div>
      <div id="idSched5" class="forminput">
        <table width="100%">
          <tr>
EOT;
    $discovery .= "<th width='35%'>" . gettext("Select Day") . "</td>";
    $discovery .= <<<EOT
            <td colspan="2" class="noborder"><select name="dayofmonth">"
EOT;
    for ($i = 1; $i <= 31; $i++) {
        $discovery .= "<option value=\"{$i}\"";
        if ($dayofmonth == $i && $dayofmonth_selected == "" || $dayofmonth_selected == $i) {
            $discovery .= " selected";
        }
        $discovery .= ">{$i}</option>";
    }
    $discovery .= <<<EOT
            </select></td>
          </tr>
        </table>
      </div>
      <div id="idSched6" class="forminput">
        <table width="100%">
          <tr>
EOT;
    $discovery .= "<th width=\"35%\">" . gettext("Day of week") . "</th><td colspan=\"2\" class=\"noborder\">";
    $discovery .= "<select name=\"nthdayofweek\">";
    $discovery .= "<option value=\"Su\" SELECTED >" . gettext("Select week day to run") . "</option>";
    $discovery .= "<option value=\"Su\" {$day['Su']} >" . gettext("Sunday") . "</option>";
    $discovery .= "<option value=\"Mo\" {$day['Mo']} >" . gettext("Monday") . "</option>";
    $discovery .= "<option value=\"Tu\" {$day['Tu']} >" . gettext("Tuesday") . "</option>";
    $discovery .= "<option value=\"We\" {$day['We']} >" . gettext("Wednesday") . "</option>";
    $discovery .= "<option value=\"Th\" {$day['Th']} >" . gettext("Thursday") . "</option>";
    $discovery .= "<option value=\"Fr\" {$day['Fr']} >" . gettext("Friday") . "</option>";
    $discovery .= "<option value=\"Sa\" {$day['Sa']} >" . gettext("Saturday") . "</option>";
    $discovery .= "</select>";
    $discovery .= "</td>";
    $discovery .= <<<EOT
          </tr>
        </table>
        <br>
        <table width="100%">
          <tr>
EOT;
    $discovery .= "<th align='right'>" . gettext("N<sup>th</sup> weekday") . "</th><td colspan='2' class='noborder'>";
    $discovery .= "<select name='nthweekday'>";
    $discovery .= "<option value='1'>" . gettext("Select nth weekday to run") . "</option>";
    $discovery .= "<option value='1'" . ($dayofmonth == 1 ? " selected" : "") . ">" . gettext("First") . "</option>";
    $discovery .= "<option value='2'" . ($dayofmonth == 2 ? " selected" : "") . ">" . gettext("Second") . "</option>";
    $discovery .= "<option value='3'" . ($dayofmonth == 3 ? " selected" : "") . ">" . gettext("Third") . "</option>";
    $discovery .= "<option value='4'" . ($dayofmonth == 4 ? " selected" : "") . ">" . gettext("Fourth") . "</option>";
    $discovery .= "<option value='5'" . ($dayofmonth == 5 ? " selected" : "") . ">" . gettext("Fifth") . "</option>";
    $discovery .= "<option value='6'" . ($dayofmonth == 6 ? " selected" : "") . ">" . gettext("Sixth") . "</option>";
    $discovery .= "<option value='7'" . ($dayofmonth == 7 ? " selected" : "") . ">" . gettext("Seventh") . "</option>";
    $discovery .= "<option value='8'" . ($dayofmonth == 8 ? " selected" : "") . ">" . gettext("Eighth") . "</option>";
    $discovery .= "<option value='9'" . ($dayofmonth == 9 ? " selected" : "") . ">" . gettext("Ninth") . "</option>";
    $discovery .= "<option value='10'" . ($dayofmonth == 10 ? " selected" : "") . ">" . gettext("Tenth") . "</option>";
    $discovery .= <<<EOT
              </select>
            </td>
          </tr>
        </table>
      </div>
EOT;
    $discovery .= "<div id='idSched7' class='forminput' style=margin-bottom:3px;>";
    $discovery .= "<table width='100%'>";
    $discovery .= "<tr>";
    $discovery .= "<th width='35%'>" . _("Frequency") . "</th>";
    $discovery .= "<td width='100%' style='text-align:center;' class='nobborder'>";
    $discovery .= "<span style='margin-right:5px;'>" . _("Every") . "</span>";
    $discovery .= "<select name='time_interval'>";
    for ($itime = 1; $itime <= 30; $itime++) {
        $discovery .= "<option value='" . $itime . "'" . ($editdata['time_interval'] == $itime ? " selected" : "") . ">" . $itime . "</option>";
    }
    $discovery .= "</select>";
    $discovery .= "<span id='days' style='margin-left:5px'>" . _("day(s)") . "</span><span id='weeks' style='margin-left:5px'>" . _("week(s)") . "</span>";
    $discovery .= "</td>";
    $discovery .= "</tr>";
    $discovery .= "</table>";
    $discovery .= "</div>";
    $discovery .= <<<EOT
      <div id="idSched2" class="forminput">
        <table width="100%">
EOT;
    $discovery .= "<tr>";
    $discovery .= "<th rowspan='2' align='right' width='35%'>" . gettext("Time") . "</td>";
    $discovery .= "<td align='right'>" . gettext("Hour") . "</td>";
    $discovery .= <<<EOT
            <td align="left" class="noborder"><select name="time_hour">
EOT;
    for ($i = 0; $i <= 23; $i++) {
        $discovery .= "<option value=\"{$i}\"";
        if ($time_hour == $i && $time_hour_selected == "" || $time_hour_selected == $i) {
            $discovery .= " selected";
        }
        $discovery .= ">{$i}</option>";
    }
    $discovery .= "</select></td><td align='right'>" . gettext("Minutes") . "</td>\n            <td class='noborder' align='left'><select name='time_min'>";
    for ($i = 0; $i < 60; $i = $i + 15) {
        $discovery .= "<option value=\"{$i}\"";
        if ($time_min == $i && $time_min_selected == "" || $time_min_selected == $i) {
            $discovery .= " selected";
        }
        $discovery .= ">{$i}</option>";
    }
    $discovery .= <<<EOT
            </select></td>
          </tr>
        </table>
      </div>
    </tr>
    
EOT;
    $discovery .= "<tr>";
    $discovery .= "\t\t<td class='madvanced'><a class='section'><img id='advanced_arrow' border='0' align='absmiddle' src='../pixmaps/arrow_green.gif'>" . _("ADVANCED") . "</a></td>";
    $discovery .= "\t\t<td>&nbsp;</td>";
    $discovery .= "</tr>";
    if ($_SESSION["scanner"] == "omp") {
        $credentials = Vulnerabilities::get_credentials($dbconn, 'ssh');
        preg_match("/(.*)\\|(.*)/", $editdata["credentials"], $found);
        $discovery .= "<tr class='advanced'>";
        $discovery .= "<td class='job_option'>" . Util::strong(_("SSH Credential:")) . "</td>";
        $discovery .= "<td style='text-align:left'><select id='ssh_credential' name='ssh_credential'>";
        $discovery .= "<option value=''>--</option>";
        foreach ($credentials as $cred) {
            $login_text = $cred["login"];
            if ($cred["login"] == '0') {
                $login_text = _("All");
            } elseif (valid_hex32($cred["login"])) {
                $login_text = Session::get_entity_name($dbconn, $cred["login"]);
            }
            $selected = $found[1] == $cred["name"] . "#" . $cred["login"] || $cred["name"] . "#" . $cred["login"] == $ssh_credential ? " selected='selected'" : "";
            $discovery .= "<option value='" . $cred["name"] . "#" . $cred["login"] . "' {$selected}>" . $cred["name"] . " (" . $login_text . ")</option>";
        }
        $discovery .= "</select></td>";
        $discovery .= "</tr>";
        $credentials = Vulnerabilities::get_credentials($dbconn, 'smb');
        $discovery .= "<tr class='advanced'>";
        $discovery .= "<td class='job_option'>" . Util::strong(_("SMB Credential:")) . "</td>";
        $discovery .= "<td style='text-align:left'><select id='smb_credential' name='smb_credential'>";
        $discovery .= "<option value=''>--</option>";
        foreach ($credentials as $cred) {
            $login_text = $cred["login"];
            if ($cred["login"] == '0') {
                $login_text = _("All");
            } elseif (valid_hex32($cred["login"])) {
                $login_text = Session::get_entity_name($dbconn, $cred["login"]);
            }
            $selected = $found[2] == $cred["name"] . "#" . $cred["login"] || $cred["name"] . "#" . $cred["login"] == $smb_credential ? " selected='selected'" : "";
            $discovery .= "<option value='" . $cred["name"] . "#" . $cred["login"] . "' {$selected}>" . $cred["name"] . " (" . $login_text . ")</option>";
        }
        $discovery .= "</select></td>";
        $discovery .= "</tr>";
    }
    $discovery .= "<tr class='job_option advanced'>";
    $discovery .= "<td class='job_option'>" . Util::strong(_("Timeout:")) . "</td>";
    $discovery .= "<td style=\"text-align:left;\" nowrap><input type='text' style='width:80px' name='timeout' value='" . ($timeout_selected == "" ? "{$timeout}" : "{$timeout_selected}") . "'>";
    $discovery .= "<font color='black'>&nbsp;&nbsp;&nbsp;" . _("Max scan run time in seconds") . "&nbsp;&nbsp;&nbsp;</font></td>";
    $discovery .= "</tr>";
    $discovery .= "<tr class='advanced'><td class='job_option'>" . Util::strong(_("Send an email notification:"));
    $discovery .= "</td>";
    $discovery .= "<td style=\"text-align:left;\">";
    $discovery .= "<input type=\"radio\" name=\"semail\" value=\"0\"" . (count($editdata) <= 1 && intval($semail) == 0 || intval($editdata['meth_Wfile']) == 0 ? " checked" : "") . "/>" . _("No");
    $discovery .= "<input type=\"radio\" name=\"semail\" value=\"1\"" . (count($editdata) <= 1 && intval($semail) == 1 || intval($editdata['meth_Wfile']) == 1 ? " checked" : "") . "/>" . _("Yes");
    $discovery .= "</td></tr>";
    $discovery .= "<tr class='advanced'>\n\t\t\t\t\t\t<td class='job_option'>" . Util::strong(_("Scan job visible for:")) . "</td>\n\t\t\t\t\t\t<td style='text-align: left'>\n\t\t\t\t\t\t\t<table cellspacing='0' cellpadding='0' class='transparent' style='margin: 5px 0px;'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td class='nobborder'><span style='margin-right:3px'>" . _('User:'******'nobborder'>\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t<select name='user' id='user' onchange=\"switch_user('user');return false;\">";
    $num_users = 0;
    foreach ($users as $k => $v) {
        $login = $v->get_login();
        $selected = $editdata["username"] == $login || $user_selected == $login ? "selected='selected'" : "";
        $options .= "<option value='" . $login . "' {$selected}>{$login}</option>\n";
        $num_users++;
    }
    if ($num_users == 0) {
        $discovery .= "<option value='' style='text-align:center !important;'>- " . _("No users found") . " -</option>";
    } else {
        $discovery .= "<option value='' style='text-align:center !important;'>- " . _("Select one user") . " -</option>\n";
        $discovery .= $options;
    }
    $discovery .= "\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t\t</td>";
    if (!empty($entities_to_assign)) {
        $discovery .= "\t    \t\t\t<td style='text-align:center; border:none; !important'><span style='padding:5px;'>" . _("OR") . "<span></td>\n\t\t\t\t\t\t\t\t\t<td class='nobborder'><span style='margin-right:3px'>" . _("Entity:") . "</span></td>\n\t\t\t\t\t\t\t\t\t<td class='nobborder'>\t\n\t\t\t\t\t\t\t\t\t\t<select name='entity' id='entity' onchange=\"switch_user('entity');return false;\">\n\t\t\t\t\t\t\t\t\t\t\t<option value='' style='text-align:center !important;'>-" . _("Select one entity") . "-</option>";
        foreach ($entities_to_assign as $k => $v) {
            $selected = $editdata["username"] == $k || $entity_selected == $k ? "selected='selected'" : "";
            $discovery .= "<option value='{$k}' {$selected}>{$v}</option>";
        }
        $discovery .= "\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t\t</td>";
    }
    $discovery .= " \t    \t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>";
    $discovery .= "<tr><td valign=\"top\" width=\"15%\" class=\"job_option noborder\"><br>";
    // conditions to exclude IPs
    $condition1 = count($editdata) <= 1 && intval($hosts_alive) == 1 ? TRUE : FALSE;
    $condition2 = preg_match('/' . EXCLUDING_IP2 . '/', trim($editdata["meth_TARGET"]));
    $condition3 = intval($editdata['meth_CRED']) == 1 ? TRUE : FALSE;
    $condition4 = count($ip_exceptions_list) > 0 ? TRUE : FALSE;
    $host_alive_check = $condition1 || $condition2 || $condition3 || $condition4 ? ' checked' : '';
    $host_alive_status = $condition2 || $condition4 ? ' disabled=\\"disabled\\"' : '';
    $discovery .= "<input onclick=\"toggle_scan_locally()\" type=\"checkbox\" id=\"hosts_alive\" name=\"hosts_alive\" value=\"1\"" . $host_alive_check . $host_alive_status . ">" . Util::strong(_("Only scan hosts that are alive")) . "<br>(" . Util::strong(_("greatly speeds up the scanning process")) . ")<br><br>";
    $discovery .= "<input type=\"checkbox\" id=\"scan_locally\" name=\"scan_locally\" value=\"1\"" . ($pre_scan_locally_status == 0 ? " disabled=\"disabled\"" : "") . ($pre_scan_locally_status == 1 && (intval($editdata['authorized']) == 1 || intval($scan_locally) == 1) ? " checked" : "") . ">" . Util::strong(_("Pre-Scan locally")) . "<br>(" . Util::strong(_("do not pre-scan from scanning sensor")) . ")<br><br>";
    $discovery .= "<input type=\"checkbox\" id=\"not_resolve\" name=\"not_resolve\" value=\"1\" " . ($editdata['resolve_names'] === "0" || $not_resolve == "1" ? "checked=\"checked\"" : "") . "/>" . Util::strong(_("Do not resolve names"));
    $discovery .= <<<EOT
        </td>
EOT;
    $discovery .= '     <td class="noborder" valign="top">';
    $discovery .= '         <table width="100%" class="transparent" cellspacing="0" cellpadding="0">';
    $discovery .= '              <tr>';
    $discovery .= '                  <td class="nobborder" style="vertical-align: top;text-align:left;padding:10px 0px 0px 0px;">';
    $discovery .= '                     <table class="transparent" cellspacing="4">';
    $discovery .= '                         <tr>';
    $discovery .= '                             <td class="nobborder" style="text-align:left;"><input class="greyfont" type="text" id="searchBox" value="' . _("Type here to search assets (Hosts/Networks)") . '" /></td>';
    $discovery .= '                         </tr>';
    $discovery .= '                         <tr>';
    $discovery .= '                             <td class="nobborder"><select id="targets" name="targets[]" multiple="multiple">';
    if (!empty($editdata["meth_TARGET"])) {
        $ip_list = explode("\n", trim($editdata["meth_TARGET"]));
    }
    if (!empty($ip_list)) {
        foreach ($ip_list as $asset) {
            if (preg_match("/([a-f\\d]+)#(.*)/i", $asset, $found)) {
                if (Asset_host::is_in_db($dbconn, $found[1])) {
                    $_asset_name = Asset_host::get_name_by_id($dbconn, $found[1]) . " (" . $found[2] . ")";
                } else {
                    $_asset_name = Asset_net::get_name_by_id($dbconn, $found[1]) . " (" . $found[2] . ")";
                }
                $discovery .= '<option value="' . $asset . '">' . $_asset_name . '</option>';
            } else {
                $discovery .= '<option value="' . $asset . '">' . $asset . '</option>';
            }
        }
        foreach ($ip_exceptions_list as $asset) {
            $discovery .= '<option value="' . $asset . '">' . $asset . '</option>';
        }
    }
    $discovery .= '                             </select></td>';
    $discovery .= '                         </tr>';
    $discovery .= '                         <tr>';
    $discovery .= '                             <td class="nobborder" style="text-align:right"><input type="button" value=" [X] " id="delete_target" class="av_b_secondary small"/>';
    $discovery .= '                             <input type="button" style="margin-right:0px;"value="Delete all" id="delete_all" class="av_b_secondary small"/></td>';
    $discovery .= '                         </tr>';
    $discovery .= '                         </table>';
    $discovery .= '                  </td>';
    $discovery .= '                  <td class="nobborder" width="450px;" style="vertical-align: top;padding:0px 0px 0px 5px;">';
    $discovery .= '                    <div id="vtree" style="text-align:left;width:100%;"></div>';
    $discovery .= '                  </td>';
    $discovery .= '              </tr>';
    $discovery .= '         </table>';
    $discovery .= '    </td>';
    $discovery .= '</tr>';
    $discovery .= '</table>';
    $discovery .= '</tr></td></table>';
    $discovery .= $show;
    return $discovery;
}
Ejemplo n.º 14
0
$num_assets = POST('num_assets');
$error_msg = '';
ossim_valid($group_id, OSS_HEX, 'illegal: Group ID');
ossim_valid($num_assets, OSS_DIGIT, OSS_NULLABLE, 'illegal: Num of assets');
if (ossim_error()) {
    die(ossim_error());
}
// Database Object
$db = new ossim_db();
$conn = $db->connect();
$group = Asset_group::get_object($conn, $group_id);
$group->can_i_edit($conn);
// Form is submited: Add to group
if ($num_assets > 0) {
    for ($i = 0; $i < $num_assets; $i++) {
        if (valid_hex32(POST('host' . $i))) {
            $assets[] = POST('host' . $i);
        }
    }
    try {
        $group->add_host($conn, $assets);
    } catch (Exception $e) {
        $error_msg = $e->getMessage();
    }
    if ($error_msg == '') {
        $msg = 'saved';
        ?>
        <script>
        if(typeof(top.frames['main'].force_reload) != 'undefined')
	    {
	        top.frames['main'].force_reload = 'snapshot,alarms,events';
Ejemplo n.º 15
0
        $priority = $incident->get_priority();
        ?>
                        <td><?php 
        echo Incident::get_priority_in_html($priority);
        ?>
</td>
                        <td nowrap='nowrap'><?php 
        echo $incident->get_date();
        ?>
</td>
                        <td nowrap='nowrap'><?php 
        echo $incident->get_life_time();
        ?>
</td>
                            <?php 
        if (preg_match("/pro|demo/i", $version) && valid_hex32($incident->get_in_charge())) {
            $in_charge_name = Acl::get_entity_name($conn, $incident->get_in_charge());
        } else {
            $in_charge_name = $incident->get_in_charge_name($conn);
        }
        ?>
                        <td><?php 
        echo $in_charge_name;
        ?>
</td>
                        <?php 
        $submitter = $incident->get_submitter();
        $submitter_data = explode("/", $submitter);
        ?>
                        <td><?php 
        echo $submitter_data[0];
Ejemplo n.º 16
0
    return $data;
}
function get_network_info($conn, $net_id)
{
    $net = Asset_net::get_object($conn, $net_id);
    //Asset IPs
    $cidrs = $net->get_ips('array');
    //Asset Sensors
    $net_sensors = $net->get_sensors();
    $sensors = $net_sensors->get_sensors();
    $data = array('id' => $net_id, 'name' => $net->get_name(), 'owner' => $net->get_owner(), 'descr' => html_entity_decode($net->get_descr(), ENT_QUOTES, 'UTF-8'), 'cidrs' => $cidrs, 'asset_value' => $net->get_asset_value(), 'icon' => base64_encode($net->get_icon()), 'sensors' => $sensors);
    return $data;
}
// Check Asset Type
$asset_types = array('asset' => 'Asset_host', 'network' => 'Asset_net', 'group' => 'Asset_group');
if (!valid_hex32($asset_id)) {
    Util::response_bad_request(_('Sorry, asset data was not loaded due to a validation error'));
}
try {
    $db = new ossim_db(TRUE);
    $conn = $db->connect();
    if (isset($_POST['asset_id']) && isset($_POST['asset_type'])) {
        if (!array_key_exists($asset_type, $asset_types)) {
            Av_exception::throw_error(Av_exception::USER_ERROR, _('Error! Invalid Asset Type'));
        }
        $class_name = $asset_types[$_POST['asset_type']];
        // Check Asset Permission
        if (method_exists($class_name, 'is_allowed') && !$class_name::is_allowed($conn, $asset_id)) {
            $error = sprintf(_('Error! %s is not allowed'), ucwords($asset_type));
            Av_exception::throw_error(Av_exception::USER_ERROR, $error);
        }
Ejemplo n.º 17
0
function is_map_editable($conn, $id)
{
    //If I am an admin user, return true
    if (Session::am_i_admin()) {
        return TRUE;
    }
    $query = "SELECT perm FROM risk_maps where map = UNHEX(?)";
    $params = array($id);
    $result = $conn->Execute($query, $params);
    if (!$result->EOF) {
        $perm = $result->fields['perm'];
    }
    if ($perm == '') {
        return FALSE;
    }
    $ret = FALSE;
    if (strlen($perm) > 0) {
        // ENTITY
        //If the user is the admin of the entity, then it can edit the map. return true.
        if (valid_hex32($perm) && Session::is_pro()) {
            $aux = Acl::get_entities_managed_by_user($conn, Session::get_session_user());
            if ($aux[0][$perm]) {
                $ret = TRUE;
            }
        } elseif (Session::get_session_user() == $perm) {
            $ret = TRUE;
        }
    }
    return $ret;
}
Ejemplo n.º 18
0
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA  02110-1301  USA
*
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
// Check permissions
Session::useractive();
$cell_id = GET('id');
ossim_valid($cell_id, OSS_ALPHA, OSS_DIGIT . OSS_SCORE, 'illegal: Message Id');
if (ossim_error()) {
    die(ossim_error());
}
list($msg_id, $component_id) = explode("_", $cell_id);
$msg_id = intval($msg_id);
if (!valid_hex32($component_id, true)) {
    die(_("Invalid canonical uuid"));
}
// Call API
try {
    $status = new System_status();
    $status->set_viewed($msg_id, $component_id);
    list($detail) = $status->get_message_detail($msg_id);
} catch (Exception $e) {
    // Do nothing
}
Ejemplo n.º 19
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;
}
Ejemplo n.º 20
0
function select_profile()
{
    global $sid, $username, $dbconn, $version, $nessus_path;
    $args = "";
    if (!Session::am_i_admin()) {
        list($owners, $sqlowners) = Vulnerabilities::get_users_and_entities_filter($dbconn);
        $owners[] = '0';
        $sql_perms .= " OR owner IN('" . implode("', '", $owners) . "')";
        $args = "WHERE name='Default' OR name='Deep' OR name='Ultimate' " . $sql_perms;
    }
    $layouts = array();
    $query = "SELECT id, name, description, owner, type FROM vuln_nessus_settings {$args} ORDER BY name";
    $dbconn->SetFetchMode(ADODB_FETCH_BOTH);
    $result = $dbconn->execute($query);
    echo "<CENTER>";
    echo "<table class=\"transparent\"><tr><td class=\"sec_title\">" . _("Vulnerability Scan Profiles") . "</td></tr></table>";
    echo "<p>";
    echo _("Please select a profile to edit") . ":";
    echo "</p>";
    echo "<table class='table_list'>";
    echo "<tr>";
    echo "<th>" . _("Available for") . "</th>";
    echo "<th>" . _("Profile") . "</th>";
    echo "<th>" . _("Description") . "</th>";
    echo "<th>" . _("Action") . "</th>";
    echo "</tr>";
    $color = 0;
    while (!$result->EOF) {
        $sid = $result->fields[0];
        $sname = $result->fields[1];
        $sdescription = $result->fields[2];
        $sowner = $result->fields[3];
        $stype = $result->fields[4];
        echo "<tr id='profile{$sid}'>";
        if ($sowner == "0") {
            echo "<td>" . _("All") . "</td>";
        } elseif (valid_hex32($sowner)) {
            echo "<td style='padding:0px 2px 0px 2px;'>" . Session::get_entity_name($dbconn, $sowner) . "</td>";
        } else {
            echo "<td>" . Util::htmlentities($sowner) . "</td>";
        }
        echo "<td width='200'>" . Util::htmlentities($sname) . "</td>";
        echo "<td width='450'>" . Util::htmlentities($sdescription) . "</td>";
        echo "<td>";
        if ($sname == "Default" || $sname == "Deep" || $sname == "Ultimate") {
            echo "<img src=\"images/pencil.png\" class=\"tip disabled\" title=\"" . _("{$sname} profile can't be edited, clone it to make changes") . "\" />";
            echo "<img src=\"images/delete.gif\" class=\"tip disabled\" title=\"" . _("{$sname} profile can't be deleted") . "\" />";
        } else {
            if (Vulnerabilities::can_modify_profile($dbconn, $sname, $sowner)) {
                echo "<a href='settings.php?disp=edit&amp;sid={$sid}'><img class='hand' id='edit_" . md5($sname . $sowner) . "' src='images/pencil.png' ></a>";
            } else {
                echo "<img class='disabled' src='images/pencil.png'>";
            }
            if (Vulnerabilities::can_delete_profile($dbconn, $sname, $sowner)) {
                echo "<img class='hand' src='images/delete.gif'  id='delete_" . md5($sname . $sowner) . "' onclick='deleteProfile({$sid})'>";
            } else {
                echo "<img class='disabled' src=\"images/delete.gif\" >";
            }
        }
        echo "</td>";
        echo "</tr>";
        $result->MoveNext();
        $color++;
    }
    echo "</table>";
    echo "<center>";
    echo "<form>";
    echo "<br/>";
    echo "<input type='button' onclick=\"document.location.href='settings.php?disp=new'\" id=\"new_profile\" value=\"" . _("Create New Profile") . "\"/>";
    echo "</form>";
    echo "</p>";
    echo "</center>";
    // end else
}
Ejemplo n.º 21
0
foreach ($dst_groups as $nid => $nname) {
    $aux[] = '<a href="#" data-url="' . Menu::get_menu_url(AV_MAIN_PATH . '/av_asset/common/views/detail.php?asset_id=' . $nid, 'environment', 'assets', 'asset_groups') . '">' . Util::htmlentities($nname) . '</a>';
}
if (empty($aux)) {
    $aux[] = $empty;
}
$dst_groups = implode(', ', $aux) . (count($aux) >= $limitc ? ' [...]' : '');
$dst_output = Asset_host::get_extended_name($_conn, $geoloc, $current_dip, $ctx, $myrow2["dst_host"], $myrow2["dst_net"]);
$dip_aux = $dst_output['name'];
$dst_img = $dst_output['html_icon'];
$dst_loc = preg_match("/data-title\\s*=\\s*'([^\\d]+)'/", $dst_img, $matches) ? $dst_img . ' <a target="_blank" href="' . $gmaps_url . '">' . $matches[1] . '</a>' : '';
$ip_dst_data = (preg_match("/data-title\\s*=\\s*'\\d+/", $dst_img) ? $dst_img . ' ' : ' ') . ($myrow2['dst_host'] != '' ? '<A HREF="#" data-url="' . Menu::get_menu_url(AV_MAIN_PATH . '/av_asset/common/views/detail.php?asset_id=' . $myrow2['dst_host'], 'environment', 'assets', 'assets') . '">' : '<A HREF="#" data-url="' . AV_MAIN_PATH . '/forensics/base_stat_ipaddr.php?ip=' . $current_dip . '&amp;netmask=32">') . $dip_aux . ($current_dip == $dip_aux ? '' : ' [' . $current_dip . ']');
$reptooltip_dst = getreptooltip($idm_data["rep_prio_dst"], $idm_data["rep_rel_dst"], $idm_data["rep_act_dst"], $current_dip);
// Destination Map
$dst_latitude = $dst_longitude = 0;
if (valid_hex32($myrow2['dst_host'])) {
    if ($dst_obj = Asset_host::get_object($_conn, $myrow2['dst_host'])) {
        $coordinates = $dst_obj->get_location();
        if (floatval($coordinates['lat']) != 0) {
            $dst_latitude = floatval($coordinates['lat']);
        }
        if (floatval($coordinates['lon']) != 0) {
            $dst_longitude = floatval($coordinates['lon']);
        }
        if (empty($dst_loc)) {
            $dst_location = Asset_host::get_extended_location($_conn, $geoloc, $current_dip, $myrow2['dst_host']);
            if ($dst_location['country']['code']) {
                $dst_loc = '<img src="../pixmaps/flags/' . $dst_location['country']['code'] . '.png"/> <a target="_blank" href="' . $gmaps_url . '">' . $dst_location['country']['name'] . '</a>';
            }
        }
    }
Ejemplo n.º 22
0
} else {
    $list = $security_report->AttackHost($target, $limit, $type, $date_from, $date_to);
}
$datax = $datay = array();
$gorientation = "h";
foreach ($list as $key => $l) {
    if ($key >= 10) {
        // ponemos un límite de resultados para la gráfica
        //break;
        $gorientation = "v";
    }
    $ip = $l[0];
    $occurrences = number_format($l[1], 0, ",", ".");
    $id = $l[2];
    $ctx = $l[3];
    $hostname = valid_hex32($id) ? Asset_host::get_name_by_id($security_report->ossim_conn, $id) : $ip;
    $datax[] = $hostname ? $hostname : $ip;
    $datay[] = $l[1];
}
require_once 'ossim_conf.inc';
$conf = $GLOBALS["CONF"];
$jpgraph = $conf->get_conf("jpgraph_path");
require_once "{$jpgraph}/jpgraph.php";
require_once "{$jpgraph}/jpgraph_bar.php";
// Setup the graph.
if ($gorientation == "v") {
    $y = 30 + count($list) * 21;
} else {
    $y = 250;
}
$graph = new Graph(400, $y, "auto");
Ejemplo n.º 23
0
    }
    if (count($local_ips) > 0) {
        $local_ips[count($local_ips) - 1][9] = " ";
        // delete last OR
        $_SESSION['ip_addr'] = $_GET['ip_addr'] = $local_ips;
        $_SESSION['ip_addr_cnt'] = $_GET['ip_addr_cnt'] = $total_ips;
    }
    $_SESSION["_hostgroup"] = "";
    //print_r($_SESSION["ip_addr"]);
} elseif ($_GET["addhomeips"] == "-1") {
    if ($_SESSION["_hostgroup"] != "") {
        $_SESSION["_hostgroup"] = "";
        $_SESSION['ip_addr'] = "";
        $_SESSION['ip_addr_cnt'] = "";
    }
} elseif ($_GET["addhomeips"] != "" && valid_hex32($_GET["addhomeips"])) {
    // PENDING CTX
    require_once "base_common.php";
    $_SESSION["_hostgroup"] = $_GET["addhomeips"];
    $ips = array();
    $total_ips = 0;
    $hg = GetOssimHostsFromHostGroups($_SESSION["_hostgroup"]);
    foreach ($hg as $iph) {
        $hips = explode(',', $iph);
        foreach ($hips as $iph) {
            $fields = explode('.', $iph);
            $ips[] = array(' ', 'ip_src', '=', $fields[0], $fields[1], $fields[2], $fields[3], $iph, ' ', 'OR', '');
            $total_ips++;
            $ips[] = array(' ', 'ip_dst', '=', $fields[0], $fields[1], $fields[2], $fields[3], $iph, ' ', 'OR', '');
            $total_ips++;
        }
Ejemplo n.º 24
0
$result = $conn->execute("SET SESSION time_zone='+00:00'");
$result = $conn->execute("SELECT id, title, date, ref, type_id, priority, last_update, in_charge, submitter FROM incident inner join incident_tag on incident_tag.incident_id=incident.id WHERE DATEDIFF(now() , date) > {$mdays} AND STATUS = 'open'");
while (!$result->EOF) {
    if (valid_hex32($result->fields["in_charge"])) {
        $in_charge = Acl::get_entity_name($conn, $result->fields["in_charge"]);
    } else {
        $in_charge = $result->fields["in_charge"];
    }
    $subject = _('Ticket Open: ') . $result->fields["title"];
    $body = '<html>
    <head>
        <title>' . $subject . '</title>
    </head>
    <body>' . '<table width="100%" cellspacing="0" cellpadding="0" style="border:0px;">' . '<tr><td width="75">' . _('Id:') . '</td><td>' . $result->fields["id"] . '</td></tr>' . '<tr><td width="75">' . _('Title:') . '</td><td>' . $result->fields["title"] . '</td></tr>' . '<tr><td width="75">' . _('Date:') . '</td><td>' . $result->fields["date"] . '</td></tr>' . '<tr><td width="75">' . _('Ref:') . '</td><td>' . $result->fields["ref"] . '</td></tr>' . '<tr><td width="75">' . _('Type id:') . '</td><td>' . $result->fields["type_id"] . '</td></tr>' . '<tr><td width="75">' . _('Priority:') . '</td><td>' . $result->fields["priority"] . '</td></tr>' . '<tr><td width="75">' . _('Last update:') . '</td><td>' . $result->fields["last_update"] . '</td></tr>' . '<tr><td width="75">' . _('In charge:') . '</td><td>' . $in_charge . '</td></tr>' . '<tr><td width="75">' . _('Submitter:') . '</td><td>' . $result->fields["submitter"] . '</td></tr>' . '</table>' . '</body>
    </html>';
    if (!valid_hex32($result->fields["in_charge"])) {
        $user_data = Session::get_list($conn, "WHERE login='******'", "", TRUE);
        if (is_object($user_data[0])) {
            if ($user_data[0]->get_email() != '') {
                Util::send_email($conn, $user_data[0]->get_email(), $subject, $body);
            }
        }
    } else {
        // In_charge is a entity
        $entity_data = Acl::get_entity($conn, $result->fields["in_charge"], FALSE, FALSE);
        if ($entity_data["admin_user"] != "") {
            // exists pro admin
            $pro_admin_data = Session::get_list($conn, "WHERE login='******'", "", TRUE);
            if ($pro_admin_data[0]->get_email() != '') {
                Util::send_email($conn, $pro_admin_data[0]->get_email(), $subject, $body);
            }
Ejemplo n.º 25
0
                 $sensor_id = $asset_sensor_id;
                 break;
             }
         }
         $agent_id = NULL;
         $ip_address = $default_ip_address;
     }
     if ($sensor_id === NULL) {
         $deployment_stats[$asset_id]['status'] = 'error';
         $deployment_stats[$asset_id]['data'] = _('Error! No HIDS sensor related to asset');
         continue;
     }
     $d_data = array('asset_id' => $asset_id, 'w_ip' => $ip_address, 'w_user' => $user, 'w_password' => $pass, 'w_domain' => $domain, 'agent_id' => $agent_id);
     $res = Ossec_agent::deploy_windows_agent($sensor_id, $d_data);
     $job_id = $res['job_id'];
     if (valid_hex32($job_id, TRUE) == FALSE) {
         $deployment_stats[$asset_id]['status'] = 'warning';
         $deployment_stats[$asset_id]['data'] = _('Warning! Deployment job cannot be launched');
     } else {
         $total_deployed++;
     }
 }
 if ($total_deployed == $total_windows) {
     $data = array('status' => 'success', 'data' => _('Deployment job/s scheduled successfully.
             <br/>Check out the <span class="bold" id="go_to_mc">Message Center</span> for more details'));
 } else {
     if ($total_deployed == 0) {
         $data = array('status' => 'warning', 'data' => _('Unable to deploy HIDS agents due to an internal error. Please try again'), 'stats' => $deployment_stats);
     } else {
         $total_not_deployed = $total_windows - $total_deployed;
         $data = array('status' => 'warning', 'data' => sprintf(_('Unable to deploy HIDS agents to %s assets.
Ejemplo n.º 26
0
function main_page($viewall, $sortby, $sortdir)
{
    global $uroles, $username, $dbconn, $hosts;
    global $arruser, $user;
    $dbconn->SetFetchMode(ADODB_FETCH_BOTH);
    $tz = Util::get_timezone();
    if ($sortby == "") {
        $sortby = "id";
    }
    if ($sortdir == "") {
        $sortdir = "DESC";
    }
    $sql_order = "order by {$sortby} {$sortdir}";
    if (Session::menu_perms("environment-menu", "EventsVulnerabilitiesScan")) {
        ?>
		<div style="width:50%; position: relative; height: 5px; float:left">
			
			<div style="width:100%; position: absolute; top: -41px;left:0px;">
    			<div style="float:left; height:28px; margin:5px 5px 0px 0px;">
    				<a class="button" href="<?php 
        echo Menu::get_menu_url(AV_MAIN_PATH . '/vulnmeter/sched.php?smethod=schedule&hosts_alive=1&scan_locally=1', 'environment', 'vulnerabilities', 'scan_jobs');
        ?>
">
                            <?php 
        echo _("New Scan Job");
        ?>
    				</a>
    			</div>
    			
    			<div style="float:left;height:28px;margin:5px 5px 0px -2px;">
    				<a class="greybox button av_b_secondary" href="import_nbe.php" title="<?php 
        echo _("Import nbe file");
        ?>
">
    				        <?php 
        echo _("Import nbe file");
        ?>
    				</a>
    			</div>
			</div>		
			
		</div>
		
		<?php 
    }
    if (intval($_GET['page']) != 0) {
        $page = intval($_GET['page']);
    } else {
        $page = 1;
    }
    $pagesize = 10;
    if ($username == "admin") {
        $query = "SELECT count(id) as num FROM vuln_jobs";
    } else {
        $query = "SELECT count(id) as num FROM vuln_jobs where username='******'";
    }
    $result = $dbconn->Execute($query);
    $jobCount = $result->fields["num"];
    $num_pages = ceil($jobCount / $pagesize);
    //echo "num_pages:[".$num_pages."]";
    //echo "jobCount:[".$jobCount."]";
    //echo "page:[".$page."]";
    if (Vulnerabilities::scanner_type() == "omp") {
        // We can display scan status with OMP protocol
        echo Vulnerabilities::get_omp_running_scans($dbconn);
    } else {
        // Nessus
        all_jobs(0, 10, "R");
    }
    ?>

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

   <table style='margin-top:20px;' class='w100 transparent'><tr><td class='sec_title'>{$schedulejobs}</td></tr></table>
   <table summary="Job Schedules" class='w100 table_list'>
EOT;
    if ($sortdir == "ASC") {
        $sortdir = "DESC";
    } else {
        $sortdir = "ASC";
    }
    $arr = array("name" => "Name", "schedule_type" => "Schedule Type", "time" => "Time", "next_CHECK" => "Next Scan", "enabled" => "Status");
    // modified by hsh to return all scan schedules
    if (empty($arruser)) {
        $query = "SELECT t2.name as profile, t1.meth_TARGET, t1.id, t1.name, t1.schedule_type, t1.meth_VSET, t1.meth_TIMEOUT, t1.username, t1.enabled, t1.next_CHECK, t1.email\n              FROM vuln_job_schedule t1 LEFT JOIN vuln_nessus_settings t2 ON t1.meth_VSET=t2.id ";
    } else {
        $query = "SELECT t2.name as profile, t1.meth_TARGET, t1.id, t1.name, t1.schedule_type, t1.meth_VSET, t1.meth_TIMEOUT, t1.username, t1.enabled, t1.next_CHECK, t1.email\n              FROM vuln_job_schedule t1 LEFT JOIN vuln_nessus_settings t2 ON t1.meth_VSET=t2.id WHERE username in ({$user}) ";
    }
    $query .= $sql_order;
    $result = $dbconn->execute($query);
    if ($result->EOF) {
        echo "<tr><td class='empty_results' height='20' style='text-align:center;'>" . _("No Scheduled Jobs") . "</td></tr>";
    }
    if (!$result->EOF) {
        echo "<tr>";
        foreach ($arr as $order_by => $value) {
            echo "<th><a href=\"manage_jobs.php?sortby={$order_by}&sortdir={$sortdir}\">" . _($value) . "</a></th>";
        }
        if (Session::menu_perms("environment-menu", "EventsVulnerabilitiesScan")) {
            echo "<th>" . _("Action") . "</th></tr>";
        }
    }
    $colors = array("#FFFFFF", "#EEEEEE");
    $color = 0;
    while (!$result->EOF) {
        list($profile, $targets, $schedid, $schedname, $schedtype, $sid, $timeout, $user, $schedstatus, $nextscan, $servers) = $result->fields;
        $name = Av_sensor::get_name_by_id($dbconn, $servers);
        $servers = $name != '' ? $name : "unknown";
        $targets_to_resolve = explode("\n", $targets);
        $ttargets = array();
        foreach ($targets_to_resolve as $id_ip) {
            if (preg_match("/^([a-f\\d]{32})#\\d+\\.\\d+\\.\\d+\\.\\d+\\/\\d{1,2}/i", $id_ip, $found) && Asset_net::is_in_db($dbconn, $found[1])) {
                $ttargets[] = preg_replace("/^([a-f\\d]{32})#/i", "", $id_ip) . " (" . Asset_net::get_name_by_id($dbconn, $found[1]) . ")";
            } else {
                if (preg_match("/^([a-f\\d]{32})#\\d+\\.\\d+\\.\\d+\\.\\d+/i", $id_ip, $found) && Asset_host::is_in_db($dbconn, $found[1])) {
                    $ttargets[] = preg_replace("/^([a-f\\d]{32})#/i", "", $id_ip) . " (" . Asset_host::get_name_by_id($dbconn, $found[1]) . ")";
                } else {
                    $ttargets[] = preg_replace("/[a-f\\d]{32}/i", "", $id_ip);
                }
            }
        }
        $targets = implode("<BR/>", $ttargets);
        $tz = intval($tz);
        $nextscan = gmdate("Y-m-d H:i:s", Util::get_utc_unixtime($nextscan) + 3600 * $tz);
        preg_match("/\\d+\\-\\d+\\-\\d+\\s(\\d+:\\d+:\\d+)/", $nextscan, $found);
        $time = $found[1];
        switch ($schedtype) {
            case "N":
                $stt = _("Once (Now)");
                break;
            case "O":
                $stt = _("Once");
                break;
            case "D":
                $stt = _("Daily");
                break;
            case "W":
                $stt = _("Weekly");
                break;
            case "M":
                $stt = _("Monthly");
                break;
            case "Q":
                $stt = _("Quarterly");
                break;
            case "H":
                $stt = _("On Hold");
                break;
            case "NW":
                $stt = _("N<sup>th</sup> weekday of the month");
                break;
            default:
                $stt = "&nbsp;";
                break;
        }
        switch ($schedstatus) {
            case "1":
                $itext = _("Disable Scheduled Job");
                $isrc = "images/stop_task.png";
                $ilink = "manage_jobs.php?disp=setstatus&schedid={$schedid}&enabled=0";
                break;
            default:
                $itext = _("Enable Scheduled Job");
                $isrc = "images/play_task.png";
                $ilink = "manage_jobs.php?disp=setstatus&schedid={$schedid}&enabled=1";
                break;
        }
        if (!Session::menu_perms("environment-menu", "EventsVulnerabilitiesScan")) {
            $ilink = "javascript:return false;";
        }
        if ($schedstatus) {
            $txt_enabled = "<td><a href=\"{$ilink}\"><font color=\"green\">" . _("Enabled") . "</font></a></td>";
        } else {
            $txt_enabled = "<td><a href=\"{$ilink}\"><font color=\"red\">" . _("Disabled") . "</font></a></td>";
        }
        require_once 'classes/Security.inc';
        if (valid_hex32($user)) {
            $user = Session::get_entity_name($dbconn, $user);
        }
        echo "<tr bgcolor=\"" . $colors[$color % 2] . "\">";
        if ($profile == "") {
            $profile = _("Default");
        }
        echo "<td><span class=\"tip\" title=\"<b>" . _("Owner") . ":</b> {$user}<br><b>" . _("Server") . ":</b> {$servers}<br /><b>" . _("Scheduled Job ID") . ":</b> {$schedid}<br><b>" . _("Profile") . ":</b> {$profile}<br><b>" . _("Targets") . ":</b><br>" . $targets . "\">{$schedname}</span></td>";
        ?>
    <td><?php 
        echo $stt;
        ?>
</td>
    <td><?php 
        echo $time;
        ?>
</td>
    <td><?php 
        echo $nextscan;
        ?>
</td>
<?php 
        echo <<<EOT
    {$txt_enabled}
    <td style="padding-top:2px;"><a href="{$ilink}"><img alt="{$itext}" src="{$isrc}" border=0 title="{$itext}"></a>&nbsp;
EOT;
        if (Session::menu_perms("environment-menu", "EventsVulnerabilitiesScan")) {
            echo "<a href='" . Menu::get_menu_url(AV_MAIN_PATH . '/vulnmeter/sched.php?disp=edit_sched&sched_id=' . $schedid, 'environment', 'vulnerabilities', 'scan_jobs') . "'><img src='images/pencil.png' title='" . _("Edit Scheduled") . "'></a>&nbsp;";
            echo "<a href='manage_jobs.php?disp=delete&amp;schedid={$schedid}' onclick='return confirmDelete();'><img src='images/delete.gif' title='" . gettext("Delete Scheduled") . "'></a>";
        }
        echo "</td>";
        echo <<<EOT
</tr>
EOT;
        $result->MoveNext();
        $color++;
    }
    echo <<<EOT
</table>
EOT;
    ?>
<br />
<?php 
    $out = all_jobs(($page - 1) * $pagesize, $pagesize);
    ?>
<table width="100%" align="center" class="transparent" cellspacing="0" cellpadding="0">
    <tr>
        <td class="nobborder" valign="top" style="padding-top:5px;">
            <div class="fright">
                <?php 
    if ($out != 0 && $num_pages != 1) {
        $page_url = "manage_jobs.php";
        if ($page == 1 && $page == $num_pages) {
            echo '<a href="" class="link_paginate_disabled" onclick="return false">< ' . _("PREVIOUS") . '</a>';
            echo '<a class="lmargin link_paginate_disabled" href="" onclick="return false">' . _("NEXT") . ' ></a>';
        } elseif ($page == 1) {
            echo '<a href="" class="link_paginate_disabled" onclick="return false">< ' . _("PREVIOUS") . '</a>';
            echo '<a class="lmargin" href="' . $page_url . '?page=' . ($page + 1) . '">' . _("NEXT") . ' ></a>&nbsp;';
        } elseif ($page == $num_pages) {
            echo '<a href="' . $page_url . '?page=' . ($page - 1) . '">< ' . _("PREVIOUS") . '</a>';
            echo '<a class="lmargin link_paginate_disabled" href="" onclick="return false">' . _("NEXT") . ' ></a>';
        } else {
            echo '<a href="' . $page_url . '?page=' . ($page - 1) . '">< ' . _("PREVIOUS") . '</a><a class="lmargin" href="' . $page_url . '?page=' . ($page + 1) . '">' . _("NEXT") . ' ></a>';
        }
    }
    ?>
            </div>
        </td>
    </tr>
    </table>
<?php 
}
Ejemplo n.º 27
0
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA  02110-1301  USA
*
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
Session::logcheck('configuration-menu', 'AlienVaultInventory');
$sensor_id = GET('sensor_id');
$data['status'] = 'error';
$data['data'] = '';
if (valid_hex32($sensor_id)) {
    $_networks = array();
    $db = new ossim_db();
    $conn = $db->connect();
    $_nets = Asset_net::get_nets_by_sensor($conn, $sensor_id);
    $db->close();
    foreach ($_nets as $_net) {
        $cidrs = explode(',', $_net['ips']);
        foreach ($cidrs as $cidr) {
            $_networks[] = array('txt' => trim($cidr) . ' [' . $_net['name'] . ']', 'id' => trim($cidr));
        }
    }
    $data['status'] = 'OK';
    $data['data'] = $_networks;
}
echo json_encode($data);
Ejemplo n.º 28
0
    return $summary;
}
/****************************************************
 ******************** Import data *******************
 ****************************************************/
$import_type = REQUEST('import_type');
$import_type = empty($import_type) ? 'networks' : $import_type;
if ($_POST['import_assets'] == 1) {
    $data['status'] = 'error';
    $data['data'] = NULL;
    $file_csv = $_SESSION['file_csv'];
    unset($_SESSION['file_csv']);
    $iic = POST('iic');
    $ctx = POST('ctx');
    if (Session::is_pro()) {
        if (!valid_hex32($ctx) || Acl::entityAllowed($ctx) < 1) {
            $data['data'] = empty($ctx) ? _('You must select an entity') : _('Entity not allowed');
            echo json_encode($data);
            exit;
        }
    } else {
        $ctx = Session::get_default_ctx();
    }
    if (!empty($file_csv)) {
        $data['status'] = 'OK';
        $data['data'] = import_assets_from_csv($file_csv, $_POST['iic'], $ctx, $import_type);
        //@unlink($file_csv);
    } else {
        $data['data'] = _('Failed to read data from CSV file. File is missing');
    }
    echo json_encode($data);
Ejemplo n.º 29
0
</th>
							<th><?php 
        echo _("Available for");
        ?>
</th>
							<th><?php 
        echo _("Action");
        ?>
</th>
						</tr>
						
						<?php 
        foreach ($list as $item) {
            if ($item["login"] == '0') {
                $available_for = _("All");
            } elseif (valid_hex32($item["login"])) {
                $available_for = Session::get_entity_name($conn, $item["login"]);
            } else {
                $available_for = $item["login"];
            }
            $credential_id = md5(trim($item["login"]) . trim($item["name"]));
            ?>
							<tr>
								<td id="credential_name_<?php 
            echo $credential_id;
            ?>
"><?php 
            echo $item["name"];
            ?>
</td>
								<td id="credential_type_<?php 
Ejemplo n.º 30
-2
function submit_scan($SVRid, $job_name, $ssh_credential, $smb_credential, $schedule_type, $not_resolve, $user, $entity, $targets, $scheduled_status, $hosts_alive, $sid, $send_email, $timeout, $scan_locally, $dayofweek, $dayofmonth, $ROYEAR, $ROMONTH, $ROday, $time_hour, $time_min, $time_interval, $sched_id, $biyear, $bimonth, $biday, $nthweekday, $tz, $daysMap)
{
    $db = new ossim_db();
    $dbconn = $db->connect();
    $credentials = $ssh_credential . '|' . $smb_credential;
    $username = valid_hex32($entity) ? $entity : $user;
    if (empty($username)) {
        $username = Session::get_session_user();
    }
    $btime_hour = $time_hour;
    // save local time
    $btime_min = $time_min;
    $bbiyear = $biyear;
    $bbimonth = $bimonth;
    $bbiday = $biday;
    if ($schedule_type == 'O') {
        // date and time for run once
        if (empty($ROYEAR)) {
            $ROYEAR = gmdate('Y');
        }
        if (empty($ROMONTH)) {
            $ROMONTH = gmdate('m');
        }
        if (empty($ROday)) {
            $ROday = gmdate('d');
        }
        list($_y, $_m, $_d, $_h, $_u, $_s, $_time) = Util::get_utc_from_date($dbconn, "{$ROYEAR}-{$ROMONTH}-{$ROday} {$time_hour}:{$time_min}:00", $tz);
        $ROYEAR = $_y;
        $ROMONTH = $_m;
        $ROday = $_d;
        $time_hour = $_h;
        $time_min = $_u;
    } else {
        if (in_array($schedule_type, array('D', 'W', 'M', 'NW'))) {
            // date and time for Daily, Day of Week, Day of month, Nth weekday of month
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, "{$biyear}-{$bimonth}-{$biday} {$time_hour}:{$time_min}:00", $tz);
            $biyear = $b_y;
            $bimonth = $b_m;
            $biday = $b_d;
            $time_hour = $b_h;
            $time_min = $b_u;
        }
    }
    $resolve_names = $not_resolve == '1' ? 0 : 1;
    if ($schedule_type != 'N') {
        // current datetime in UTC
        $arrTime = explode(":", gmdate('Y:m:d:w:H:i:s'));
        $year = $arrTime[0];
        $mon = $arrTime[1];
        $mday = $arrTime[2];
        $wday = $arrTime[3];
        $hour = $arrTime[4];
        $min = $arrTime[5];
        $sec = $arrTime[6];
        $timenow = $hour . $min . $sec;
        $run_wday = $daysMap[$dayofweek]['number'];
        $run_time = sprintf('%02d%02d%02d', $time_hour, $time_min, '00');
        $run_mday = $dayofmonth;
        $time_value = "{$time_hour}:{$time_min}:00";
        $ndays = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        $begin_in_seconds = Util::get_utc_unixtime("{$biyear}-{$bimonth}-{$biday} {$time_hour}:{$time_min}:00") - 3600 * $tz;
        $current_in_seconds = gmdate('U');
        // current datetime in UTC
        if (strlen($bimonth) == 1) {
            $bimonth = '0' . $bimonth;
        }
        if (strlen($biday) == 1) {
            $biday = '0' . $biday;
        }
    }
    switch ($schedule_type) {
        case 'N':
            $requested_run = gmdate('YmdHis');
            break;
        case 'O':
            $requested_run = sprintf('%04d%02d%02d%06d', $ROYEAR, $ROMONTH, $ROday, $run_time);
            break;
        case 'D':
            if ($begin_in_seconds > $current_in_seconds) {
                $next_day = $biyear . $bimonth . $biday;
                // selected date by user
            } else {
                if ($run_time > $timenow) {
                    $next_day = $year . $mon . $mday;
                    // today
                } else {
                    $next_day = gmdate("Ymd", strtotime("+1 day GMT", gmdate("U")));
                    // next day
                }
            }
            $requested_run = sprintf("%08d%06d", $next_day, $run_time);
            break;
        case 'W':
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                $wday = date("w", mktime(0, 0, 0, $bimonth, $biday, $biyear));
                // make week day for begin day
                if ($run_wday == $wday) {
                    $next_day = $biyear . $bimonth . $biday;
                    // selected date by user
                } else {
                    $next_day = gmdate("Ymd", strtotime("next " . $ndays[$run_wday] . " GMT", mktime(0, 0, 0, $bimonth, $biday, $biyear)));
                }
            } else {
                if ($run_wday == $wday && $run_time > $timenow) {
                    $next_day = $year . $mon . $mday;
                    // today
                } else {
                    $next_day = gmdate("Ymd", strtotime("next " . $ndays[$run_wday] . " GMT", gmdate("U")));
                    // next week
                }
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})/", $next_day, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " {$btime_hour}:{$btime_min}:00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            break;
        case 'M':
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                if ($run_mday >= $biday) {
                    $next_day = $biyear . $bimonth . ($run_mday < 10 ? "0" : "") . $run_mday;
                    // this month
                } else {
                    $next_day = sprintf("%06d%02d", gmdate("Ym", strtotime("next month GMT", mktime(0, 0, 0, $bimonth, $biday, $biyear))), $run_mday);
                }
            } else {
                if ($run_mday > $mday || $run_mday == $mday && $run_time > $timenow) {
                    $next_day = $year . $mon . ($run_mday < 10 ? "0" : "") . $run_mday;
                    // this month
                } else {
                    $next_day = sprintf("%06d%02d", gmdate("Ym", strtotime("next month GMT", gmdate("U"))), $run_mday);
                }
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})/", $next_day, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " {$btime_hour}:{$btime_min}:00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            break;
        case 'NW':
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                $array_time = array('month' => $bbimonth, 'day' => $bbiday, 'year' => $bbiyear);
                $requested_run = weekday_month(strtolower($daysMap[$dayofweek]['text']), $nthweekday, $btime_hour, $btime_min, $array_time);
            } else {
                $requested_run = weekday_month(strtolower($daysMap[$dayofweek]['text']), $nthweekday, $btime_hour, $btime_min);
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/", $requested_run, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " " . $found[4] . ":" . $found[5] . ":00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            $dayofmonth = $nthweekday;
            break;
        default:
            break;
    }
    $insert_time = gmdate('YmdHis');
    if (!empty($_SESSION['_vuln_targets']) && count($_SESSION['_vuln_targets']) > 0) {
        $sgr = array();
        foreach ($_SESSION['_vuln_targets'] as $target_selected => $server_id) {
            $sgr[$server_id][] = $target_selected;
        }
        ossim_clean_error();
        unset($_SESSION['_vuln_targets']);
        // clean scan targets
        $resolve_names = $not_resolve == '1' ? 0 : 1;
        $queries = array();
        $bbimonth = strlen($bbimonth) == 1 ? '0' . $bbimonth : $bbimonth;
        $bbiday = strlen($bbiday) == 1 ? '0' . $bbiday : $bbiday;
        $qc = 0;
        if ($schedule_type == 'N') {
            foreach ($sgr as $notify_sensor => $target_list) {
                $target_list = implode("\n", $target_list);
                $params = array($job_name, $username, Session::get_session_user(), $schedule_type, $target_list, $hosts_alive, $sid, $send_email, $timeout, $SVRid, $insert_time, $requested_run, '3', 'S', $notify_sensor, $scan_locally, '', $resolve_names, $credentials);
                $queries[$qc]['query'] = 'INSERT INTO vuln_jobs ( name, username, fk_name, meth_SCHED, meth_TARGET,  meth_CRED,
                    meth_VSET, meth_Wfile, meth_TIMEOUT, scan_ASSIGNED,
                    scan_SUBMIT, scan_next, scan_PRIORITY, status, notify, authorized, author_uname, resolve_names, credentials )
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
                $queries[$qc]['params'] = $params;
                $qc++;
            }
        } else {
            $params = array($bbiyear . $bbimonth . $bbiday, $job_name, $username, Session::get_session_user(), $schedule_type, $dayofweek, $dayofmonth, $time_value, implode("\n", $targets), $hosts_alive, $sid, $send_email, $scan_locally, $timeout, $requested_run, $insert_time, strval($scheduled_status), $resolve_names, $time_interval, '', $credentials, $SVRid);
            $queries[$qc]['query'] = 'INSERT INTO vuln_job_schedule ( begin, name, username, fk_name, schedule_type, day_of_week, day_of_month, time, meth_TARGET, meth_CRED, meth_VSET, meth_Wfile,  meth_Ucheck, meth_TIMEOUT, next_CHECK, createdate, enabled, resolve_names, time_interval, IP_ctx, credentials, email)
                                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ';
            $queries[$qc]['params'] = $params;
            $qc++;
        }
        $execute_errors = array();
        foreach ($queries as $id => $sql_data) {
            $rs = $dbconn->execute($sql_data['query'], $sql_data['params']);
            if ($rs === FALSE) {
                $execute_errors[] = $dbconn->ErrorMsg();
            }
        }
        if (empty($execute_errors) && $schedule_type != 'N') {
            // We have to update the vuln_job_assets
            if (intval($sched_id) == 0) {
                $query = ossim_query('SELECT LAST_INSERT_ID() as sched_id');
                $rs = $dbconn->Execute($query);
                if (!$rs) {
                    Av_exception::throw_error(Av_exception::DB_ERROR, $dbconn->ErrorMsg());
                } else {
                    $sched_id = $rs->fields['sched_id'];
                }
            }
            Vulnerabilities::update_vuln_job_assets($dbconn, 'insert', $sched_id, 0);
        }
        $config_nt = array('content' => '', 'options' => array('type' => 'nf_success', 'cancel_button' => FALSE), 'style' => 'width: 40%; margin: 20px auto; text-align: center;');
        $config_nt['content'] = empty($execute_errors) ? _('Successfully Submitted Job') : _('Error creating scan job:') . implode('<br>', $execute_errors);
        $nt = new Notification('nt_1', $config_nt);
        $nt->show();
        $dbconn->close();
    }
}