예제 #1
0
 $arrResults = array();
 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('', '');
        if (!$rs) {
            ?>
  
            <script type="text/javascript">
                parent.show_error("<?php 
            echo $conn_snort->ErrorMsg();
            ?>
");								
            </script>
            <?php 
            exit;
        }
        while (!$rs->EOF) {
            $ip = $rs->fields['ip'];
            $ctx = $rs->fields['ctx'];
            $ids = Asset_host::get_id_by_ips($conn_aux, $ip, $ctx);
            if (empty($hosts_in_db[$ip][$ctx]) && empty($ids)) {
                if ($mode == 'insert') {
                    try {
                        $id = Util::uuid();
                        $hostname = Asset_host::get_autodetected_name($ip);
                        $ips = array();
                        $ips[$ip] = array('ip' => $ip, 'mac' => NULL);
                        $sensors = array($rs->fields['sensor_id']);
                        $conn_aux = $db->connect();
                        $host = new Asset_host($conn_aux, $id);
                        Util::disable_perm_triggers($conn_aux, TRUE);
                        $host->set_name($hostname);
                        $host->set_ctx($ctx);
                        $host->set_ips($ips);
                        $host->set_sensors($sensors);
예제 #3
0
파일: index.php 프로젝트: jackpf/ossim-arc
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>";
    }
}
예제 #4
0
    <td width="128" style='background-color:#FFFFE3;border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px;border: 1px solid #F0E68C;'>
        <?php 
echo _("Info");
?>
    </td></tr>
    <?php 
$tp = intval(count($vulns) / $maxpag);
$tp += count($vulns) % $maxpag == 0 ? 0 : 1;
$to = $pag * $maxpag;
$from = $to - $maxpag;
$ips_to_show = array();
$i = 1;
foreach ($vulns as $ctx_ip => $value) {
    if ($i > $from && $i <= $to) {
        list($ctx, $ip) = explode("#", $ctx_ip);
        $host_id = key(Asset_host::get_id_by_ips($dbconn, $ip, $ctx));
        if (valid_hex32($host_id)) {
            $name = Asset_host::get_name_by_id($dbconn, $host_id);
        } else {
            $name = $ip;
        }
        $ips_to_show[] = $ctx_ip . "|" . $name;
        ?>
            <tr>
                <td style="text-align:center"><?php 
        echo $ip;
        ?>
</td>
                <td style="text-align:center"><?php 
        echo $name;
        ?>
예제 #5
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>";
}
예제 #6
0
                $result = 'Impossible to save the host';
            }
        } else {
            $result = 'The host already exists.';
        }
        break;
    case 'update_aliases':
        list($hostip, $ctx, $aliases) = explode('|', base64_decode($asset));
        $hostid = key(Asset_host::get_id_by_ips($dbconn, $hostip, $ctx));
        if (Asset_host::is_in_db($dbconn, $hostid)) {
            try {
                $asset = new Asset_host($dbconn, $hostid);
                $asset->load_from_db($dbconn);
                $asset->set_fqdns($aliases);
                $asset->save_in_db($dbconn);
                $result = 'Host aliases updated';
            } catch (Exception $e) {
                $result = 'Impossible to save the host aliases';
            }
        }
        break;
    case "get_host_id":
        list($hostip, $ctx) = explode('|', base64_decode($asset));
        $result = key(Asset_host::get_id_by_ips($dbconn, $hostip, $ctx));
        break;
    default:
        $db->close();
        die("The option isn't correct\n");
}
$db->close();
echo "{$result}\n";
예제 #7
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;
}
예제 #8
0
function scan2html($conn, $scan)
{
    $count = 0;
    $text_hostname = "<div>" . _('A valid hostname satisfy the following rules (according RFC 1123)') . ":</div>\n                    <div>\n                        <ul>\n                            <li>" . _("A hostname can start or end with a letter or a number [a-zA-z0-9]") . "</li>\n                            <li>" . _("A hostname <strong>MUST NOT</strong> contain any '.' (dot)") . "</li>\n                            <li>" . _("A hostname <strong>MUST NOT</strong> start or end with a '-' (dash)") . "</li>\n                            <li>" . _("A hostname can be up to 63 characters") . "</li>\n                        </ul>\n                    </div>";
    $text_fqdn = "<div>" . _('If FQDN contains any dot, only the first label will be used') . "</div>";
    $text_mac = "<div>" . _('Place the pointer over the MAC address to show MAC vendor') . "</div>";
    $text_services = "<div>" . _('Place the pointer over the service name to show more information') . "</div>";
    $text_os = "<div>" . _('Place the pointer over the OS to show more information') . "</div>";
    $html = '';
    $s_ctx = $scan['sensor']['ctx'];
    foreach ($scan['scanned_ips'] as $ip => $host) {
        $w_msg = '';
        $w_html = '';
        $external_ctxs = Session::get_external_ctxs($conn);
        //Checking forwarded hosts
        if (empty($external_ctxs[$s_ctx])) {
            $can_i_modify_elem = TRUE;
            $md_check = "<input id='icheckbox" . $count . "' type='checkbox' checked='checked' class='mc' value='" . $ip . "' name='ip_" . $count . "'/>";
        } else {
            $can_i_modify_elem = FALSE;
            $md_check = "<input id='icheckbox" . $count . "' type='checkbox' disabled='disabled' class='mc' name='ip_" . $count . "'/>";
        }
        $host_name = $host['hostname'];
        $fqdn = $host['fqdn'];
        $ids = Asset_host::get_id_by_ips($conn, $ip, $s_ctx);
        $id = key($ids);
        //Host already exists
        if (!empty($id)) {
            $host_object = Asset_host::get_object($conn, $id);
            if (is_object($host_object) && !empty($host_object)) {
                $host_name = $host_object->get_name();
                $h_fqdn = $host_object->get_fqdns();
                $fqdn = !empty($fqdn) ? $fqdn : $h_fqdn;
            }
        }
        //FQDN
        if (!empty($fqdn)) {
            $fqdn_check = "<input id='fcheckbox" . $count . "' type='checkbox' class='fqdn' value='" . $ip . "' name='fqdn_" . $count . "'/>";
        } else {
            $fqdn = '-';
            $fqdn_check = "<input id='fcheckbox" . $count . "' type='checkbox' disabled='disabled' class='fqdn' value='" . $ip . "' name='fqdn_" . $count . "'/>";
        }
        //Devices types
        $devices_types = count($host['device_types']) > 0 ? implode(', ', $host['device_types']) : '-';
        //MAC
        $mac = !empty($host['mac']) != '' ? "<a class='more_info' title='" . $host['mac_vendor'] . "'>" . $host['mac'] . "</a>" : '-';
        //Operating System
        $os = !empty($host['os']) != '' ? Properties::get_os_pixmap($host['os']) . ' ' . $host['os'] : '-';
        //Services
        $services = array();
        if (is_array($host['services'])) {
            foreach ($host['services'] as $port_and_proto => $s_data) {
                $service_name = $s_data['service'] != 'unknown' ? $s_data['service'] : $port_and_proto;
                $version = $s_data['version'];
                if (preg_match('/^cpe:\\/a/', $s_data['version'])) {
                    $version = Software::get_info($conn, $s_data['version']);
                }
                $version = !empty($version) && !preg_match("/^cpe/", $version) ? $version : $s_data['service'];
                $title = $port_and_proto . " (" . $version . ')';
                $html_data = "<a class='more_info' title='{$title}'>{$service_name}</a>";
                $services[] = $html_data;
            }
        }
        $services = implode(', ', $services);
        if ($can_i_modify_elem == FALSE) {
            $w_msg = _('The properties of this asset can only be modified at the USM') . ": <strong>" . $external_ctxs[$s_ctx] . '</strong>';
        }
        if (!empty($w_msg)) {
            $w_html = "<a class='more_info' title='" . $w_msg . "'>\n                            <img src='../pixmaps/warning.png' border='0'/>\n                       </a>";
        }
        $html .= "\n            <tr>\n                <td class='td_chk_hosts'>" . $md_check . "</td>\n\n                <td class='td_ip' id='ip" . $count . "'>{$w_html} " . $host['ip'] . "</td>\n\n                <td class='td_hostname' id='hostname" . $count . "'>" . $host_name . "</td>\n\n                <td class='td_fqdn' id='fqdn" . $count . "'>" . $fqdn . "</td>\n\n                <td class='td_device_types' id='device_types" . $count . "'>" . ucwords($devices_types) . "</td>\n\n                <td class='td_mac' id='mac" . $count . "'>" . $mac . "</td>\n\n                <td class='td_os' id='os" . $count . "'>" . $os . "</td>\n\n                <td class='td_services' id='services" . $count . "'>" . $services . "</td>\n\n                <td class='td_chk_fqdns'>" . $fqdn_check . "</td>\n\n            </tr>";
        $count++;
    }
    ?>
   	
	<form method="POST" action="scan_form.php" name="scan_form" id="scan_form">		
		<input type="hidden" name="ips" value='<?php 
    echo $count;
    ?>
'/>
		
		<div class='results_title'><?php 
    echo _('Scan Results');
    ?>
</div>
		
		<table class='table_data' id='t_sresults'>
		    <thead>
               
    			</tr>				
    				<th class="th_chk_hosts">    				    
    				    <input type='checkbox' name='chk_all_hosts' id='chk_all_hosts' checked="checked" value="1"/>    			
    				</th>
    				
    				<th class="th_ip"><?php 
    echo _('Host');
    ?>
</th>
    				<th class="th_hostname"><?php 
    echo _('Hostname');
    ?>
                        <a class="more_info" title="<?php 
    echo $text_hostname;
    ?>
">
                            <img src="../pixmaps/helptip_icon.gif" border="0" align="absmiddle"/>
                        </a>
                    </th>
                    <th class="th_fqdn"><?php 
    echo _('FQDN');
    ?>
</th>
                    <th class="th_devices_types"><?php 
    echo _('Device types');
    ?>
</th>
    				<th class="th_mac"><?php 
    echo _('Mac');
    ?>
                        <a class="more_info" title="<?php 
    echo $text_mac;
    ?>
">
                            <img src="../pixmaps/helptip_icon.gif" border="0" align="absmiddle"/>
                        </a>
                    </th>
    				<th class="th_os"><?php 
    echo _('OS');
    ?>
                        <a class="more_info" title="<?php 
    echo $text_os;
    ?>
">
                            <img src="../pixmaps/helptip_icon.gif" border="0" align="absmiddle"/>
                        </a>
                    </th>
    				<th class="th_services"><?php 
    echo _('Services');
    ?>
                        <a class="more_info" title="<?php 
    echo $text_services;
    ?>
">
                            <img src="../pixmaps/helptip_icon.gif" border="0" align="absmiddle"/>
                        </a>
                    </th>
    				
    			    <th class="th_chk_fqdns">                        
                        <input type='checkbox' name='chk_all_fqdns' id='chk_all_fqdns' value="1"/>                        
                        <span><?php 
    echo _('FQDN as Hostname');
    ?>
</span>
                        <a class="more_info" title="<?php 
    echo $text_fqdn;
    ?>
">
                            <img src="../pixmaps/helptip_icon.gif" border="0" align="absmiddle"/>
                        </a>                
                    </th>
                </tr>
            </thead>
            <tbody>
    			<?php 
    echo $html;
    ?>
    	
            </tbody>
        </table> 
        
        <div style='text-align:center; padding: 10px 0px;'>
			<input type="button" style='margin-left: 10px;' class="av_b_secondary" onclick="document.location.href='index.php?clearscan=1'" value='<?php 
    echo _('Clear scan result');
    ?>
'/>
			<input type='submit' name='send' id='send' value="<?php 
    echo _('Update database values');
    ?>
"/>
        </div>            		
	</form>
	
	<script type='text/javascript'>	

		$(".more_info").tipTip({maxWidth: "auto"});
		
		$("#chk_all_hosts").click(function(){    	    		
    		if ($(this).prop("checked"))
    		{
        		$(".mc:not(:disabled)").prop("checked", true);
    		}
    		else
    		{
        		$(".mc:not(:disabled)").prop("checked", false);
    		}    		
		});	
		
		$(".mc:not(:disabled)").click(function(){     		
    		
    		if($('.mc:checked').length == 0) 
    		{
        		$("#chk_all_hosts").prop("checked", false);
    		}    			
		});	
		
				
		if ($(".fqdn:not(:disabled)").length > 0)
		{
    		$("#chk_all_fqdns").click(function(){    	    		
        		if ($(this).prop("checked"))
        		{
            		$(".fqdn:not(:disabled)").prop("checked", true);
        		}
        		else
        		{
            		$(".fqdn:not(:disabled)").prop("checked", false);
        		}    		
    		});	
		}
		else
		{
    		$("#chk_all_fqdns").prop("disabled", true);
		}
		
		
		$(".mc:not(:disabled)").click(function(){     		
    		
    		if($('.fqdn:checked').length == 0) 
    		{
        		$("#chk_all_fqdns").prop("checked", false);
    		}    			
		});	
		
		
		/***************************************************
        *********************** Token *********************
        ***************************************************/
        
        Token.add_to_forms();
	</script>
	<?php 
}
예제 #9
0
//Database connection
$db = new ossim_db();
$conn = $db->connect();
if ($edition_type == 'single') {
    // Single edition
    $id = GET('id');
    $_ip = GET('ip');
    $_ctx = GET('ctx');
    //Getting host by IP and CTX
    if (empty($id) && !empty($_ctx) && !empty($_ip)) {
        $entity_type = Session::get_entity_type($conn, $_ctx);
        $entity_type = strtolower($entity_type);
        //Sometimes CTX is an engine instead of context
        $_ctx = $entity_type == 'context' ? $_ctx : Session::get_default_ctx();
        if (Asset_host_ips::valid_ip($_ip) && valid_hex32($_ctx)) {
            $aux_ids = Asset_host::get_id_by_ips($conn, $_ip, $_ctx);
            $aux_id = key($aux_ids);
            if (Asset_host::is_in_db($conn, $aux_id)) {
                $id = $aux_id;
            }
        } else {
            unset($_ip);
            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;
        }
예제 #10
0
function submit_scan($vuln_op, $sched_id, $sname, $notify_email, $schedule_type, $ROYEAR, $ROMONTH, $ROday, $time_hour, $time_min, $dayofweek, $dayofmonth, $timeout, $SVRid, $sid, $tarSel, $ip_list, $ip_exceptions_list, $ip_start, $ip_end, $named_list, $cidr, $subnet, $system, $cred_type, $credid, $acc, $domain, $accpass, $acctype, $passtype, $passstore, $wpolicies, $wfpolicies, $upolicies, $custadd_type, $cust_plugins, $is_enabled, $hosts_alive, $scan_locally, $nthweekday, $semail, $not_resolve, $time_interval, $biyear, $bimonth, $biday, $ssh_credential = "", $smb_credential = "")
{
    global $wdaysMap, $daysMap, $allowscan, $uroles, $username, $schedOptions, $adminmail, $mailfrom, $dbk, $dbconn;
    // credentials
    $credentials = $ssh_credential . "|" . $smb_credential;
    $btime_hour = $time_hour;
    // save local time
    $btime_min = $time_min;
    $bbiyear = $biyear;
    $bbimonth = $bimonth;
    $bbiday = $biday;
    $tz = Util::get_timezone();
    if ($schedule_type == "O") {
        // date and time for run once
        if (empty($ROYEAR)) {
            $ROYEAR = gmdate("Y");
        }
        if (empty($ROMONTH)) {
            $ROMONTH = gmdate("m");
        }
        if (empty($ROday)) {
            $ROday = gmdate("d");
        }
        list($_y, $_m, $_d, $_h, $_u, $_s, $_time) = Util::get_utc_from_date($dbconn, "{$ROYEAR}-{$ROMONTH}-{$ROday} {$time_hour}:{$time_min}:00", $tz);
        $ROYEAR = $_y;
        $ROMONTH = $_m;
        $ROday = $_d;
        $time_hour = $_h;
        $time_min = $_u;
    } else {
        if ($schedule_type == "D" || $schedule_type == "W" || $schedule_type == "M" || $schedule_type == "NW") {
            // date and time for Daily, Day of Week, Day of month, Nth weekday of month
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, "{$biyear}-{$bimonth}-{$biday} {$time_hour}:{$time_min}:00", $tz);
            $biyear = $b_y;
            $bimonth = $b_m;
            $biday = $b_d;
            $time_hour = $b_h;
            $time_min = $b_u;
        }
    }
    if ($not_resolve == "1") {
        $resolve_names = 0;
    } else {
        $resolve_names = 1;
    }
    $notify_email = str_replace(";", ",", $notify_email);
    $requested_run = "";
    $jobType = "M";
    $recurring = False;
    $targets = array();
    $time_value = "";
    $profile_desc = getProfileName($sid);
    $target_list = "";
    $need_authorized = "";
    $request = "";
    $plugs_list = "NULL";
    $fk_name = "NULL";
    $target_list = "NULL";
    $tmp_target_list = "";
    $jobs_names = array();
    $sjobs_names = array();
    $I3crID = "";
    if ($hosts_alive == "1") {
        // option: Only scan hosts that are alive
        $I3crID = "1";
    } else {
        $I3crID = "0";
    }
    // if ( $custadd_type == "" ) { $custadd_type = "N"; }
    // if ( $custadd_type != "N" && $cust_plugins != "" ) {
    // $plugs_list="";
    // $vals=preg_split( "/\s+|\r\n|,|;/", $cust_plugins );
    // foreach($vals as $v) {
    // $v=trim($v);
    // if ( strlen($v)>0 ) {
    // $plugs_list .= $v . "\n";
    // }
    // }
    // $plugs_list = "'".$plugs_list."'";
    // }
    if ($schedule_type != "N") {
        // current datetime in UTC
        $arrTime = explode(":", gmdate('Y:m:d:w:H:i:s'));
        $year = $arrTime[0];
        $mon = $arrTime[1];
        $mday = $arrTime[2];
        $wday = $arrTime[3];
        $hour = $arrTime[4];
        $min = $arrTime[5];
        $sec = $arrTime[6];
        $timenow = $hour . $min . $sec;
        $run_wday = $wdaysMap[$dayofweek];
        $run_time = sprintf("%02d%02d%02d", $time_hour, $time_min, "00");
        $run_mday = $dayofmonth;
        $time_value = "{$time_hour}:{$time_min}:00";
        $ndays = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
        $begin_in_seconds = mktime($bihour, $bimin, 0, $bimonth, $biday, $biyear);
        // selected datetime by user in UTC
        $current_in_seconds = mktime($hour, $min, 0, $mon, $mday, $year);
        // current datetime in UTC
        if (strlen($bimonth) == 1) {
            $bimonth = "0" . $bimonth;
        }
        if (strlen($biday) == 1) {
            $biday = "0" . $biday;
        }
    }
    switch ($schedule_type) {
        case "N":
            $requested_run = gmdate("YmdHis");
            $sched_message = "No reccurring Jobs Necessary";
            break;
        case "O":
            $requested_run = sprintf("%04d%02d%02d%06d", $ROYEAR, $ROMONTH, $ROday, $run_time);
            //error_log("O-> $requested_run\n" ,3,"/tmp/sched.log");
            $sched_message = "No reccurring Jobs Necessary";
            $recurring = True;
            $reccur_type = "Run Once";
            break;
        case "D":
            if ($begin_in_seconds > $current_in_seconds) {
                $next_day = $biyear . $bimonth . $biday;
                // selected date by user
            } else {
                if ($run_time > $timenow) {
                    $next_day = $year . $mon . $mday;
                } else {
                    $next_day = gmdate("Ymd", strtotime("+1 day GMT", gmdate("U")));
                }
                // next day
            }
            $requested_run = sprintf("%08d%06d", $next_day, $run_time);
            //error_log("D-> $requested_run\n" ,3,"/tmp/sched.log");
            $recurring = True;
            $sched_message = "Schedule Reccurring";
            $reccur_type = "Daily";
            break;
        case "W":
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                $wday = date("w", mktime(0, 0, 0, $bimonth, $biday, $biyear));
                // make week day for begin day
                if ($run_wday == $wday) {
                    $next_day = $biyear . $bimonth . $biday;
                    // selected date by user
                } else {
                    $next_day = gmdate("Ymd", strtotime("next " . $ndays[$run_wday] . " GMT", mktime(0, 0, 0, $bimonth, $biday, $biyear)));
                }
            } else {
                if ($run_wday == $wday && $run_time > $timenow || $run_wday > $wday) {
                    $next_day = $year . $mon . $mday;
                } else {
                    $next_day = gmdate("Ymd", strtotime("next " . $ndays[$run_wday] . " GMT", gmdate("U")));
                }
                // next week
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})/", $next_day, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " {$btime_hour}:{$btime_min}:00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            //error_log("W-> $requested_run\n" ,3,"/tmp/sched.log");
            $recurring = True;
            $sched_message = "Schedule Reccurring";
            $reccur_type = "Weekly";
            break;
        case "M":
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                if ($run_mday >= $biday) {
                    $next_day = $biyear . $bimonth . ($run_mday < 10 ? "0" : "") . $run_mday;
                    // this month
                } else {
                    $next_day = sprintf("%06d%02d", gmdate("Ym", strtotime("next month GMT", mktime(0, 0, 0, $bimonth, $biday, $biyear))), $run_mday);
                }
            } else {
                if ($run_mday > $mday || $run_mday == $mday && $run_time > $timenow) {
                    $next_day = $year . $mon . ($run_mday < 10 ? "0" : "") . $run_mday;
                    // this month
                } else {
                    $next_day = sprintf("%06d%02d", gmdate("Ym", strtotime("next month GMT", gmdate("U"))), $run_mday);
                }
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})/", $next_day, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " {$btime_hour}:{$btime_min}:00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            //error_log("M-> $requested_run $begin_in_seconds $current_in_seconds\n" ,3,"/tmp/sched.log");
            $recurring = True;
            $sched_message = "Schedule Reccurring";
            $reccur_type = "Montly";
            break;
        case "NW":
            if ($begin_in_seconds > $current_in_seconds) {
                // if it is a future date
                $array_time = array('month' => $bbimonth, 'day' => $bbiday, 'year' => $bbiyear);
                $requested_run = weekday_month(strtolower($daysMap[$dayofweek]), $nthweekday, $btime_hour, $btime_min, $array_time);
            } else {
                $requested_run = weekday_month(strtolower($daysMap[$dayofweek]), $nthweekday, $btime_hour, $btime_min);
            }
            preg_match("/(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/", $requested_run, $found);
            list($b_y, $b_m, $b_d, $b_h, $b_u, $b_s, $b_time) = Util::get_utc_from_date($dbconn, $found[1] . "-" . $found[2] . "-" . $found[3] . " " . $found[4] . ":" . $found[5] . ":00", $tz);
            $requested_run = sprintf("%04d%02d%02d%02d%02d%02d", $b_y, $b_m, $b_d, $b_h, $b_u, "00");
            //error_log("NW-> $requested_run\n" ,3,"/tmp/sched.log");
            $dayofmonth = $nthweekday;
            $recurring = True;
            $sched_message = "Schedule Reccurring";
            $reccur_type = "Nth weekday of the month";
            break;
        default:
            break;
    }
    $insert_time = gmdate("YmdHis");
    if (!empty($_SESSION["_vuln_targets"]) && count($_SESSION["_vuln_targets"]) > 0) {
        $arr_ctx = array();
        $sgr = array();
        foreach ($_SESSION["_vuln_targets"] as $target_selected => $server_id) {
            $sgr[$server_id][] = $target_selected;
            if (preg_match("/^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\/\\d{1,2}\$/i", $target_selected)) {
                $related_ctxs = array_values(Asset_net::get_id_by_ips($dbconn, $target_selected));
                if (is_array($related_ctxs) && count($related_ctxs) > 0) {
                    $arr_ctx[$target_selected] = key(array_shift($related_ctxs));
                }
            } else {
                if (preg_match("/^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\$/i", $target_selected)) {
                    $related_ctxs = array_values(Asset_host::get_id_by_ips($dbconn, $target_selected));
                    if (is_array($related_ctxs) && count($related_ctxs) > 0) {
                        $arr_ctx[$target_selected] = key(array_shift($related_ctxs));
                        // to assign a ctx for a IP
                    }
                } else {
                    if (valid_hostname($target_selected) || valid_fqdns($target_selected)) {
                        $filters = array('where' => "hostname like '{$target_selected}' OR fqdns like '{$target_selected}'");
                        $_hosts_data = Asset_host::get_basic_list($dbconn, $filters);
                        $host_list = $_hosts_data[1];
                        if (count($host_list) > 0) {
                            $first_host = array_shift($host_list);
                            $hips = explode(",", $first_host['ips']);
                            foreach ($hips as $hip) {
                                $hip = trim($hip);
                                $arr_ctx[$hip] = $first_host['ctx'];
                            }
                        }
                    }
                }
            }
        }
        ossim_clean_error();
        unset($_SESSION["_vuln_targets"]);
        // clean scan targets
        $query = array();
        $IP_ctx = array();
        foreach ($arr_ctx as $aip => $actx) {
            $IP_ctx[] = $actx . "#" . $aip;
        }
        if ($vuln_op == "editrecurring" && $sched_id > 0) {
            $query[] = "DELETE FROM vuln_job_schedule WHERE id='{$sched_id}'";
            $i = 1;
            foreach ($sgr as $notify_sensor => $targets) {
                $target_list = implode("\n", $targets);
                $target_list .= "\n" . implode("\n", $ip_exceptions_list);
                $query[] = "INSERT INTO vuln_job_schedule ( name, username, fk_name, job_TYPE, schedule_type, day_of_week, day_of_month, \n                            time, email, meth_TARGET, meth_CRED, meth_VSET, meth_CUSTOM, meth_CPLUGINS, meth_Wfile, \n                            meth_Ucheck, meth_TIMEOUT, next_CHECK, createdate, enabled, resolve_names, time_interval, IP_ctx, credentials) VALUES ( '{$sname}', '{$username}', '" . Session::get_session_user() . "', '{$jobType}',\n                            '{$schedule_type}', '{$dayofweek}', '{$dayofmonth}', '{$time_value}', '{$notify_sensor}', '{$target_list}',\n                            {$I3crID}, '{$sid}', '{$custadd_type}', {$plugs_list}, {$semail}, '{$scan_locally}',\n                            '{$timeout}', '{$requested_run}', '{$insert_time}', '1', '{$resolve_names}' ,'{$time_interval}', '" . implode("\n", $IP_ctx) . "', '{$credentials}') ";
                $sjobs_names[] = $sname . $i;
                $i++;
            }
        } elseif ($recurring) {
            $i = 1;
            foreach ($sgr as $notify_sensor => $targets) {
                $target_list = implode("\n", $targets);
                $target_list .= "\n" . implode("\n", $ip_exceptions_list);
                $query[] = "INSERT INTO vuln_job_schedule ( name, username, fk_name, job_TYPE, schedule_type, day_of_week, day_of_month, \n                                time, email, meth_TARGET, meth_CRED, meth_VSET, meth_CUSTOM, meth_CPLUGINS, meth_Wfile, \n                                meth_Ucheck, meth_TIMEOUT, scan_ASSIGNED, next_CHECK, createdate, enabled, resolve_names, time_interval, IP_ctx, credentials) VALUES ( '{$sname}', '{$username}', '" . Session::get_session_user() . "', '{$jobType}',\n                                '{$schedule_type}', '{$dayofweek}', '{$dayofmonth}', '{$time_value}', '{$notify_sensor}', '{$target_list}',\n                                {$I3crID}, '{$sid}', '{$custadd_type}', {$plugs_list}, {$semail}, '{$scan_locally}',\n                                '{$timeout}', '{$SVRid}', '{$requested_run}', '{$insert_time}', '1', '{$resolve_names}' , '{$time_interval}', '" . implode("\n", $IP_ctx) . "', '{$credentials}') ";
                $sjobs_names[] = $sname . $i;
                $i++;
            }
        } else {
            $i = 1;
            foreach ($sgr as $notify_sensor => $targets) {
                $target_list = implode("\n", $targets);
                $target_list .= "\n" . implode("\n", $ip_exceptions_list);
                $query[] = "INSERT INTO vuln_jobs ( name, username, fk_name, job_TYPE, meth_SCHED, meth_TARGET,  meth_CRED,\n                        meth_VSET, meth_CUSTOM, meth_CPLUGINS, meth_Wfile, meth_TIMEOUT, scan_ASSIGNED,\n                        scan_SUBMIT, scan_next, scan_PRIORITY, status, notify, authorized, author_uname, resolve_names, credentials ) VALUES ( '{$sname}',\n                        '{$username}', '" . Session::get_session_user() . "', '{$jobType}', '{$schedule_type}', '{$target_list}', {$I3crID}, '{$sid}', '{$custadd_type}', {$plugs_list},\n                         {$semail}, '{$timeout}', '{$SVRid}', '{$insert_time}', '{$requested_run}', '3',\n                        'S', '{$notify_sensor}', '{$scan_locally}', '" . implode("\n", $IP_ctx) . "', '{$resolve_names}' , '{$credentials}') ";
                // echo "$query1";
                // die();
                $jobs_names[] = $sname . $i;
                $i++;
            }
        }
        $query_insert_time = gen_strtotime($insert_time, "");
        foreach ($query as $sql) {
            $error_updating = false;
            $error_inserting = false;
            if ($dbconn->execute($sql) === false) {
                echo _("Error creating scan job") . ": " . $dbconn->ErrorMsg();
                if ($vuln_op == "editrecurring") {
                    $error_updating = true;
                } else {
                    $error_creating = true;
                }
            } else {
                $config_nt = array('content' => "", 'options' => array('type' => "nf_success", 'cancel_button' => false), 'style' => 'width: 40%; margin: 20px auto; text-align: center;');
                if ($vuln_op == "editrecurring" && !$error_updating) {
                    $config_nt["content"] = _("Successfully Updated Recurring Job");
                    $nt = new Notification('nt_1', $config_nt);
                    $nt->show();
                } elseif (!$error_creating) {
                    $config_nt["content"] = _("Successfully Submitted Job");
                    $nt = new Notification('nt_1', $config_nt);
                    $nt->show();
                    //logAccess( "Submitted Job [ $jid ] $request" );
                    foreach ($jobs_names as $job_name) {
                        $infolog = array($job_name);
                        Log_action::log(66, $infolog);
                    }
                    foreach ($sjobs_names as $job_name) {
                        $infolog = array($job_name);
                        Log_action::log(67, $infolog);
                    }
                } else {
                    echo "<br><center>" . _("Failed Job Creation") . "</center>";
                }
                ?>
                <script type="text/javascript">
                //<![CDATA[                    
                document.location.href='<?php 
                echo Menu::get_menu_url(AV_MAIN_PATH . '/vulnmeter/manage_jobs.php', 'environment', 'vulnerabilities', 'scan_jobs');
                ?>
'; 
                //]]>
                </script>
                <?php 
            }
        }
    }
    // count($_SESSION["_vuln_targets"])>0
    echo "</b></center>";
}
예제 #11
0
/****************************************************
 ******************** Host Data *********************
 ****************************************************/
//Flags
$is_new_host = TRUE;
//Database connection
$db = new ossim_db();
$conn = $db->connect();
$msg = GET('msg');
$id = GET('id');
$_aux_ip = $_GET['ip'];
$_aux_ctx = $_GET['ctx'];
//Getting host by IP and CTX
if (empty($id) && !empty($_aux_ctx) && !empty($_aux_ip)) {
    if (Asset_host_ips::valid_ip($_aux_ip) && valid_hex32($_aux_ctx)) {
        $aux_ids = Asset_host::get_id_by_ips($conn, $_GET['ip'], $_GET['ctx']);
        $aux_id = key($aux_ids);
        if (Asset_host::is_in_db($conn, $aux_id)) {
            $id = $aux_id;
        }
    } else {
        unset($_aux_ip);
        unset($_aux_ctx);
    }
}
if (!empty($id)) {
    ossim_valid($id, OSS_HEX, 'illegal:' . _('Host ID'));
    if (ossim_error()) {
        echo ossim_error(_('Error! Host not found'));
        exit;
    }
예제 #12
0
 $conn = $db->connect();
 //Validating icon format and size
 $icon = '';
 if (is_uploaded_file($_FILES['icon']['tmp_name'])) {
     $icon = file_get_contents($_FILES['icon']['tmp_name']);
 }
 if ($icon != '') {
     $image = @imagecreatefromstring($icon);
     if (!$image || imagesx($image) > 16 || imagesy($image) > 16) {
         $validation_errors['icon'] = _('Image format is not allowed. Allowed only 16x16 PNG images');
     }
 }
 //Validating IPs
 $aux_ips = explode(',', $ips_string);
 foreach ($aux_ips as $ip) {
     $host_ids = Asset_host::get_id_by_ips($conn, $ip, $ctx);
     unset($host_ids[$id]);
     if (!empty($host_ids)) {
         $validation_errors['ip'] = _('Error! IP not allowed.') . " IP {$ip} " . _('already exists for this entity');
         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) {
             $validation_errors['ip'] = _("Error! IP {$ip} not allowed.  Check your asset filter");
             break;
         }
     }
 }
 //Validating Sensors
 if (is_array($sensors) && !empty($sensors)) {