function make_ctx_filter($alias = 'acid_event')
{
    $where = '';
    $ctxs = Session::get_ctx_where();
    if ($ctxs != '') {
        $where .= " AND {$alias}.ctx in ({$ctxs})";
    }
    return $where;
}
function calc_system_eps($conn)
{
    $perms_where = Session::get_ctx_where() != '' ? " AND entity_id IN (" . Session::get_ctx_where() . ")" : "";
    //
    $sql = "SELECT SUM( stat ) AS eps FROM acl_entities_stats WHERE 1 =1 {$perms_where}";
    if (!($rs =& $conn->Execute($sql))) {
        $eps = 0;
    } else {
        $eps = empty($rs->fields['eps']) ? 0 : $rs->fields['eps'];
    }
    return number_format($eps, 0);
}
Example #3
0
function GetPerms($alias = "acid_event")
{
    $perms_sql = "";
    $domain = Session::get_ctx_where();
    if ($domain != "") {
        $perms_sql .= " AND {$alias}.ctx in ({$domain})";
    }
    // Asset filter
    $host_perms = Session::get_host_where();
    $net_perms = Session::get_net_where();
    if ($host_perms != "") {
        $perms_sql .= " AND ({$alias}.src_host in ({$host_perms}) OR {$alias}.dst_host in ({$host_perms})";
        if ($net_perms != "") {
            $perms_sql .= " OR {$alias}.src_net in ({$net_perms}) OR {$alias}.dst_net in ({$net_perms}))";
        } else {
            $perms_sql .= ")";
        }
    } elseif ($net_perms != "") {
        $perms_sql .= " AND ({$alias}.src_net in ({$net_perms}) OR {$alias}.dst_net in ({$net_perms}))";
    }
    return $perms_sql;
}
Example #4
0
                ${$pp} = "";
            }
        }
        break;
}
$offset = intval($offset);
// latest results table
$roffset = intval($roffset);
// reports table
$sreport = intval($sreport);
// to show reports
//for autocomplete input
$autocomplete_keys = array('hosts_ips', 'nets_cidrs', 'sensors');
$assets = Autocomplete::get_autocomplete($dbconn, $autocomplete_keys);
// ctx permissions
$perms_where = Session::get_ctx_where() != "" ? " AND ctx in (" . Session::get_ctx_where() . ")" : "";
list($arruser, $user) = Vulnerabilities::get_users_and_entities_filter($conn);
// Delete Section
if (!empty($delete) && !empty($scantime)) {
    // a single scan in latest results tables
    $params = array($delete, $scantime);
    $query = "SELECT hostIP, HEX(ctx) as ctx, sid, username FROM vuln_nessus_latest_reports WHERE report_key=? and scantime=? {$perms_where}";
    $result = $dbconn->execute($query, $params);
    if (Session::hostAllowed_by_ip_ctx($dbconn, $result->fields["hostIP"], $result->fields["ctx"])) {
        $dhostIP = $result->fields["hostIP"];
        $dctx = $result->fields["ctx"];
        $dusername = $result->fields["username"];
        $dsid = $result->fields["sid"];
        $query = "DELETE FROM vuln_nessus_latest_reports WHERE report_key=? and scantime=? {$perms_where}";
        $result = $dbconn->execute($query, $params);
        $params = array($dhostIP, $dctx, $dusername, $dsid, $scantime);
Example #5
0
ossim_valid($engine_id, OSS_HEX, '\\-', OSS_NULLABLE, 'illegal:' . _("Engine ID"));
ossim_valid($toggled_dir, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Directive ID"));
ossim_valid($toggled_info, OSS_DIGIT, OSS_NULLABLE, 'illegal:' . _("Directive Option"));
if (ossim_error()) {
    die(ossim_error());
}
if (GET('msg_success') == 1) {
    $msg_success = _("Directive successfully saved");
}
$conf = $GLOBALS["CONF"];
if ($engine_id == "") {
    $engine_id = $conf->get_conf("default_engine_id", false);
}
$found = 0;
// Default engine is not allowed by CTX user perms
if (Session::get_ctx_where() != "" && Session::is_pro() && !Acl::entityAllowed(strtoupper(str_replace("-", "", $engine_id)))) {
    if ($_SESSION['_user_vision']['ctx'] != "") {
        $engine_id = Util::uuid_format($_SESSION['_user_vision']['ctx']);
    }
}
$directive_editor = new Directive_editor($engine_id);
// Default toggle User Contributed
if ($toggled == "") {
    $toggled = "user.xml";
}
if (POST('delete_directive_id') != "") {
    $toggled = POST('file');
    ossim_valid(POST('delete_directive_id'), OSS_DIGIT, 'illegal:' . _("Directive ID"));
    ossim_valid(POST('file'), OSS_ALPHA, OSS_PUNC, 'illegal:' . _("File"));
    if (ossim_error()) {
        die(ossim_error());
Example #6
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>";
}
Example #7
0
function GetPlugins($db)
{
    $plugins = array();
    $temp_sql = "SELECT distinct plugin_id,name FROM ac_acid_event LEFT JOIN alienvault.plugin ON ac_acid_event.plugin_id=plugin.id WHERE cnt>0";
    if (Session::get_ctx_where() != "") {
        $temp_sql .= " AND ac_acid_event.ctx in (" . Session::get_ctx_where() . ")";
    }
    $tmp_result = $db->baseExecute($temp_sql);
    while ($myrow = $tmp_result->baseFetchRow()) {
        $plg = $myrow[1] == "" ? $myrow[0] : $myrow[1];
        $plg = preg_replace("/(ossec)-.*/", "\\1", $plg);
        $plugins[$plg][] = $myrow[0];
    }
    $tmp_result->baseFreeRows();
    return $plugins;
}
    ?>
</th>
            <th width="10%"><?php 
    echo gettext("Service");
    ?>
</th>
            <th width="10%"><?php 
    echo gettext("Severity");
    ?>
</th>
        </tr>

    <?php 
    $risks = array("1", "2", "3", "6", "7");
    foreach ($risks as $risk_value) {
        $perms_where_t1 = Session::get_ctx_where() != "" ? " AND t1.ctx in (" . Session::get_ctx_where() . ")" : "";
        $report1_data = array();
        $query = "SELECT DISTINCT t1.risk, t1.hostIP, HEX(ctx) as ctx, t1.hostname, t1.port, t1.protocol, t1.app, t1.scriptid, t1.msg, t2.name FROM vuln_nessus_results as t1\n                        LEFT JOIN vuln_nessus_plugins as t2 on t2.id=t1.scriptid\n                        WHERE t1.report_id={$freport} and t1.hostIP='{$ip}' and t1.ctx=UNHEX('{$hctx}') {$perms_where_t1} and t1.falsepositive='N' and t1.risk={$risk_value}";
        $dbconn->SetFetchMode(ADODB_FETCH_NUM);
        $result = $dbconn->Execute($query);
        while (list($risk, $hostIP, $ctx, $hostname, $port, $protocol, $app, $scriptid, $msg, $plugin_name) = $result->fields) {
            if (Session::hostAllowed_by_ip_ctx($dbconn, $hostIP, $ctx)) {
                $aux = array();
                $aux["risk"] = $risk;
                $aux["app"] = $app;
                $aux["msg"] = $msg;
                $aux["scriptid"] = $scriptid;
                $aux["port"] = $port;
                $aux["protocol"] = $protocol;
                $aux["plugin_name"] = $plugin_name;
                $report1_data["{$scriptid}|{$port}|{$protocol}|{$msg}"] = $aux;
Example #9
0
function top_siem_events($conn, $limit)
{
    $data = array();
    $perms_sql = "WHERE 1=1";
    $domain = Session::get_ctx_where();
    if ($domain != "") {
        $perms_sql .= " AND ac.ctx in ({$domain})";
    }
    // Asset filter
    $hosts = Session::get_host_where();
    $nets = Session::get_net_where();
    if ($hosts != "") {
        $perms_sql .= " AND (ac.src_host in ({$hosts}) OR ac.dst_host in ({$hosts})";
        if ($nets != "") {
            $perms_sql .= " OR ac.src_net in ({$nets}) OR ac.dst_net in ({$nets}))";
        } else {
            $perms_sql .= ")";
        }
    } elseif ($nets != "") {
        $perms_sql .= " AND (ac.src_net in ({$nets}) OR ac.dst_net in ({$nets}))";
    }
    $query = "SELECT sum(ac.cnt) as num, plugin_sid.name FROM alienvault_siem.ac_acid_event AS ac LEFT JOIN alienvault.plugin_sid ON plugin_sid.plugin_id=ac.plugin_id AND plugin_sid.sid=ac.plugin_sid {$perms_sql} GROUP BY name ORDER BY num DESC LIMIT {$limit}";
    $rs = $conn->Execute($query);
    if (!$rs) {
        echo "error";
        die($conn->ErrorMsg());
    }
    while (!$rs->EOF) {
        $data[Util::signaturefilter($rs->fields["name"])] = $rs->fields["num"];
        $rs->MoveNext();
    }
    return $data;
}
Example #10
0
////////////////////////////////////////////////////////////////
/*
* @param $name, string with the id of the object (ex: a network name or a host
* ip)
* @param $type, enum ('day', 'month', ...)
*/
// Cache some queries
$host_qualification_cache = get_host_qualification($conn);
$net_qualification_cache = get_net_qualification($conn);
////////////////////////////////////////////////////////////////
// Network Groups
////////////////////////////////////////////////////////////////
// If allowed_nets === null, then permit all
$net_group_where = "";
// CTX's filter
$ctxs = Session::get_ctx_where();
if ($ctxs != "") {
    $net_group_where = " AND net_group.ctx in ({$ctxs})";
}
// Asset filter
$nets = Session::get_net_where();
if ($nets != "") {
    $net_group_where .= " AND net.id in ({$nets})";
}
$net_limit = " LIMIT {$from},{$max}";
// We can't join the control_panel table, because new ossim installations
// holds no data there
$sql = "SELECT\n            net_group.name as group_name,\n            net_group.threshold_c as group_threshold_c,\n            net_group.threshold_a as group_threshold_a,\n            net.name as net_name,\n            HEX(net.id) as net_id,\n            net.threshold_c as net_threshold_c,\n            net.threshold_a as net_threshold_a,\n            net.ips as net_address,\n            HEX(net_group.id) as group_id\n        FROM\n            net_group,\n            net,\n            net_group_reference\n        WHERE\n            net_group_reference.net_id = net.id AND\n            net_group_reference.net_group_id = net_group.id {$net_group_where}";
if (!($rs =& $conn->Execute($sql))) {
    die($conn->ErrorMsg());
}
function ProcessCriteria()
{
    global $db, $join_sql, $perms_sql, $where_sql, $criteria_sql, $sql, $debug_mode, $caller, $DBtype;
    /* XXX-SEC */
    global $cs, $timetz;
    $db_aux = new ossim_db();
    $conn_aux = $db_aux->connect();
    /* the JOIN criteria */
    $ip_join_sql = " LEFT JOIN iphdr ON acid_event.sid=iphdr.sid AND acid_event.cid=iphdr.cid ";
    // *************** DEPRECATED: TCP UDP ICMP join *********************
    //$tcp_join_sql = " LEFT JOIN tcphdr ON acid_event.sid=tcphdr.sid AND acid_event.cid=tcphdr.cid ";
    //$udp_join_sql = " LEFT JOIN udphdr ON acid_event.sid=udphdr.sid AND acid_event.cid=udphdr.cid ";
    //$icmp_join_sql = " LEFT JOIN icmphdr ON acid_event.sid=icmphdr.sid AND acid_event.cid=icmphdr.cid ";
    $rawip_join_sql = " LEFT JOIN iphdr ON acid_event.sid=iphdr.sid AND acid_event.cid=iphdr.cid ";
    $sig_join_sql = " LEFT JOIN alienvault.plugin_sid ON acid_event.plugin_id=plugin_sid.plugin_id AND acid_event.plugin_sid=plugin_sid.sid ";
    $sig_join = false;
    //$data_join_sql = " LEFT JOIN extra_data ON acid_event.sid=extra_data.sid AND acid_event.cid=extra_data.cid ";
    $data_join_sql = "";
    $ag_join_sql = " LEFT JOIN acid_ag_alert ON acid_event.sid=acid_ag_alert.ag_sid AND acid_event.cid=acid_ag_alert.ag_cid ";
    //$sig_join_sql = "";
    //SQL_CALC_FOUND_ROWS
    $sql = "SELECT acid_event.*, HEX(acid_event.ctx) AS ctx, HEX(acid_event.src_host) AS src_host, HEX(acid_event.dst_host) AS dst_host, HEX(acid_event.src_net) AS src_net, HEX(acid_event.dst_net) AS dst_net FROM acid_event";
    $where_sql = " WHERE ";
    //$where_sql = "";
    // $criteria_sql = " acid_event.sid > 0";
    // Initially show last 24hours events
    if ($_GET['time_range'] == "") {
        $criteria_sql = " ( timestamp >='" . gmdate("Y-m-d", $timetz) . "' ) ";
    } else {
        $criteria_sql = " 1 ";
    }
    //$criteria_sql = " ( timestamp <= CURDATE() ) ";
    //$criteria_sql = " 1 ";
    $join_sql = "";
    $use_ac = true;
    // Use ac_acid_event or not
    /* ********************** Meta Criteria ******************************************** */
    $sig = $cs->criteria['sig']->criteria;
    $sig_type = $cs->criteria['sig']->sig_type;
    $sig_class = $cs->criteria['sig_class']->criteria;
    $sig_priority = $cs->criteria['sig_priority']->criteria;
    $ag = $cs->criteria['ag']->criteria;
    $sensor = $cs->criteria['sensor']->criteria;
    $sensor_op = $cs->criteria['sensor']->param ? "not in" : "in";
    $plugin = $cs->criteria['plugin']->criteria;
    $plugingroup = $cs->criteria['plugingroup']->criteria;
    $networkgroup = $cs->criteria['networkgroup']->criteria;
    $userdata = $cs->criteria['userdata']->criteria;
    $idm_username = $cs->criteria['idm_username']->criteria;
    $idm_hostname = $cs->criteria['idm_hostname']->criteria;
    $idm_domain = $cs->criteria['idm_domain']->criteria;
    $sourcetype = $cs->criteria['sourcetype']->criteria;
    $category = $cs->criteria['category']->criteria;
    $rep = $cs->criteria['rep']->criteria;
    $time = $cs->criteria['time']->GetUTC();
    $real_time = $cs->criteria['time']->criteria;
    //print_r($time);
    $time_cnt = $cs->criteria['time']->GetFormItemCnt();
    $hostid = $cs->criteria['hostid']->criteria;
    $netid = $cs->criteria['netid']->criteria;
    $ctx = $cs->criteria['ctx']->criteria;
    $device = $cs->criteria['device']->criteria;
    $ip_addr = $cs->criteria['ip_addr']->criteria;
    $ip_addr_cnt = $cs->criteria['ip_addr']->GetFormItemCnt();
    $layer4 = $cs->criteria['layer4']->criteria;
    $ip_field = $cs->criteria['ip_field']->criteria;
    $ip_field_cnt = $cs->criteria['ip_field']->GetFormItemCnt();
    $tcp_port = $cs->criteria['tcp_port']->criteria;
    $tcp_port_cnt = $cs->criteria['tcp_port']->GetFormItemCnt();
    // DEPRECATED tcp flags
    //$tcp_flags = $cs->criteria['tcp_flags']->criteria;
    //$tcp_field = $cs->criteria['tcp_field']->criteria;
    //$tcp_field_cnt = $cs->criteria['tcp_field']->GetFormItemCnt();
    $udp_port = $cs->criteria['udp_port']->criteria;
    $udp_port_cnt = $cs->criteria['udp_port']->GetFormItemCnt();
    // DEPRECATED udp field icmp field
    //$udp_field = $cs->criteria['udp_field']->criteria;
    //$udp_field_cnt = $cs->criteria['udp_field']->GetFormItemCnt();
    //$icmp_field = $cs->criteria['icmp_field']->criteria;
    //$icmp_field_cnt = $cs->criteria['icmp_field']->GetFormItemCnt();
    $rawip_field = $cs->criteria['rawip_field']->criteria;
    $rawip_field_cnt = $cs->criteria['rawip_field']->GetFormItemCnt();
    $data = $cs->criteria['data']->criteria;
    $data_cnt = $cs->criteria['data']->GetFormItemCnt();
    $cs->criteria['data']->data_encode;
    //$data_encode[0] = "ascii"; $data_encode[1] = "hex";
    /* OSSIM */
    $ossim_type = $cs->criteria['ossim_type']->criteria;
    $ossim_priority = $cs->criteria['ossim_priority']->criteria;
    $ossim_reliability = $cs->criteria['ossim_reliability']->criteria;
    $ossim_asset_dst = $cs->criteria['ossim_asset_dst']->criteria;
    $ossim_risk_a = $cs->criteria['ossim_risk_a']->criteria;
    $tmp_meta = "";
    /* Sensor */
    if ($sensor != "" && $sensor != " ") {
        $tmp_meta = $tmp_meta . " AND acid_event.device_id {$sensor_op} ( " . preg_replace("/^\\!/", "", $sensor) . " )";
    } else {
        $cs->criteria['sensor']->Set("");
    }
    /* Device */
    if ($device != "") {
        $_ip = bin2hex(inet_pton($device));
        $tmp_meta .= " AND acid_event.device_id IN (SELECT id FROM device WHERE device_ip=UNHEX('" . $_ip . "'))";
    }
    /* Plugin */
    if ($plugin != "" && $plugin != " ") {
        if (preg_match("/(\\d+)\\-(\\d+)/", $plugin, $match)) {
            $tmp_meta = $tmp_meta . " AND acid_event.plugin_id between " . $match[1] . " and " . $match[2];
        } else {
            $tmp_meta = $tmp_meta . " AND acid_event.plugin_id in (" . $plugin . ")";
        }
    }
    /* Plugin Group */
    if ($plugingroup != "" && $plugingroup != " ") {
        $pg_ids = QueryOssimPluginGroup($plugingroup);
        if ($pg_ids != "") {
            $tmp_meta = $tmp_meta . " AND ({$pg_ids}) ";
        } else {
            $tmp_meta = $tmp_meta . " AND (acid_event.plugin_id=-1 AND acid_event.plugin_sid=-1)";
        }
    }
    /* Network Group */
    if ($networkgroup != "" && $networkgroup != " ") {
        $ng_ids = QueryOssimNetworkGroup($networkgroup);
        if ($ng_ids != "") {
            $tmp_meta = $tmp_meta . " AND ({$ng_ids}) ";
            $use_ac = false;
        }
    }
    /* User Data */
    //echo "User Data:$userdata";
    $rpl = array('EQ' => '=', 'NE' => '!=', 'LT' => '<', 'LOE' => '<=', 'GT' => '>', 'GOE' => '>=');
    if (trim($userdata[2]) != "") {
        $_q = parenthesis_encode(escape_sql($userdata[2], $conn_aux));
        $sql = "SELECT acid_event.*, HEX(acid_event.ctx) AS ctx, HEX(acid_event.src_host) AS src_host, \n                                  HEX(acid_event.dst_host) AS dst_host, HEX(acid_event.src_net) AS src_net, \n                                  HEX(acid_event.dst_net) AS dst_net,extra_data.* \n                           FROM acid_event";
        $data_join_sql .= ",extra_data ";
        $_nq = is_numeric($_q) ? $_q : "'" . $_q . "'";
        $flt = "extra_data." . $userdata[0] . " " . strtr($userdata[1], $rpl) . " " . ($userdata[1] == "like" ? "'%" . $_q . "%'" : $_nq);
        $tmp_meta .= " AND acid_event.id=extra_data.event_id AND ({$flt})";
        $use_ac = FALSE;
    }
    /* IDM */
    if (trim($idm_username[0]) != '' || trim($idm_domain[0]) != '') {
        $data_join_sql .= ",idm_data ";
        $tmp_meta .= " AND acid_event.id=idm_data.event_id";
        $use_ac = FALSE;
    }
    if ($idm_username[0] != '') {
        $_q = parenthesis_encode(escape_sql($idm_username[0], $conn_aux));
        if ($idm_username[1] == "both") {
            $tmpcrit = "idm_data.username='******'";
        } else {
            $tmpcrit = "(idm_data.username='******' AND idm_data.from_src=" . ($idm_username[1] == "src" ? "1" : "0") . ")";
        }
        $tmp_meta .= " AND {$tmpcrit}";
    }
    if ($idm_domain[0] != '') {
        $_q = parenthesis_encode(escape_sql($idm_domain[0], $conn_aux));
        if ($idm_domain[1] == "both") {
            $tmpcrit = "idm_data.domain='" . $_q . "'";
        } else {
            $tmpcrit = "(idm_data.domain='" . $_q . "' AND idm_data.from_src=" . ($idm_domain[1] == "src" ? "1" : "0") . ")";
        }
        $tmp_meta .= " AND {$tmpcrit}";
    }
    if ($idm_hostname[0] != '') {
        $_q = parenthesis_encode(escape_sql($idm_hostname[0], $conn_aux));
        if ($idm_hostname[1] == "both") {
            $tmpcrit = "(acid_event.src_hostname='" . $_q . "' OR acid_event.dst_hostname='" . $_q . "')";
        } else {
            $tmpcrit = "acid_event." . $idm_hostname[1] . "_hostname='" . $_q . "'";
        }
        $tmp_meta .= " AND {$tmpcrit}";
        $use_ac = FALSE;
    }
    /* Reputation */
    $rep_data = trim($rep[0]) != "" || trim($rep[1]) != "" ? true : false;
    if ($rep_data) {
        $data_join_sql .= ",reputation_data";
        $tmp_meta .= " AND acid_event.id=reputation_data.event_id";
        $use_ac = false;
    }
    if (trim($rep[0]) != "") {
        # Activity
        if (intval($rep[0])) {
            $aname = GetActivityName($rep[0], $db);
            $tmpcrit = "(reputation_data.rep_act_src like '%" . str_replace("'", "\\'", $aname) . "%' OR reputation_data.rep_act_dst like '%" . str_replace("'", "\\'", $aname) . "%')";
        } else {
            $tmpcrit = "(reputation_data.rep_act_src!='' OR reputation_data.rep_act_dst!='')";
        }
        $tmp_meta .= " AND {$tmpcrit}";
    }
    if (trim($rep[1]) != "") {
        # Severity
        switch ($rep[1]) {
            case "High":
                $tmpcrit = "(reputation_data.rep_prio_src>6 OR reputation_data.rep_prio_dst>6)";
                break;
            case "Medium":
                $tmpcrit = "(reputation_data.rep_prio_src in (3,4,5,6) OR reputation_data.rep_prio_dst in (3,4,5,6))";
                break;
            case "Low":
                $tmpcrit = "(reputation_data.rep_prio_src in (0,1,2) OR reputation_data.rep_prio_dst in (0,1,2))";
                break;
            default:
                $tmpcrit = "(reputation_data.rep_prio_src>0 OR reputation_data.rep_prio_dst>0)";
        }
        $tmp_meta .= " AND {$tmpcrit}";
    }
    /* Source Type */
    if (trim($sourcetype) != "") {
        $tmp_meta = $tmp_meta . " AND acid_event.plugin_id in (" . GetPluginListBySourceType($sourcetype) . ")";
    }
    /* Category */
    if ($category[0] != 0) {
        $sig_join = true;
        $tmp_meta = $tmp_meta . GetPluginListByCategory($category);
    }
    /* Signature */
    if (isset($sig[0]) && $sig[0] != " " && $sig[0] != "" && (isset($sig[1]) && $sig[1] != "")) {
        if ($sig_type == 1) {
            // sending sig[1]=plugin_id;plugin_sid
            $pidsid = preg_split("/[\\s;]+/", $sig[1]);
            $tmp_meta = $tmp_meta . " AND (acid_event.plugin_id=" . intval($pidsid[0]) . " AND acid_event.plugin_sid=" . intval($pidsid[1]) . ")";
        } else {
            // free string
            $sig_ids = QueryOssimSignature($sig[1], $sig[0], $sig[2]);
            $sig_join = true;
            $tmp_meta = $tmp_meta . " AND ({$sig_ids})";
            //if ($sig_ids != "")
            //  $tmp_meta = $tmp_meta . " AND ($sig_ids) ";
            //else
            //  $tmp_meta = $tmp_meta." AND (plugin_id=-1 AND plugin_sid=-1)";
        }
    } else {
        $cs->criteria['sig']->Set("");
    }
    /*
     * OSSIM Code
     */
    /* OSSIM Type */
    if ($ossim_type[1] != " " && $ossim_type[1] != "" && $ossim_type[1] != "0") {
        $tmp_meta = $tmp_meta . " AND acid_event.ossim_type = '" . $ossim_type[1] . "'";
        $use_ac = false;
    } else {
        if ($ossim_type[1] == "0") {
            $tmp_meta = $tmp_meta . " AND (acid_event.ossim_type is null OR acid_event.ossim_type = '0')";
            $use_ac = false;
        } else {
            $cs->criteria['ossim_type']->Set("");
        }
    }
    /* OSSIM Priority */
    if ($ossim_priority[1] != " " && $ossim_priority[1] != "" && $ossim_priority[1] != "0") {
        $tmp_meta = $tmp_meta . " AND acid_event.ossim_priority  " . $ossim_priority[0] . " '" . $ossim_priority[1] . "'";
        $use_ac = false;
    } else {
        if ($ossim_priority[1] == "0") {
            $use_ac = false;
            $tmp_meta = $ossim_priority[0] == "=" ? $tmp_meta . " AND (acid_event.ossim_priority is null OR acid_event.ossim_priority = '0')" : ($tmp_meta = $tmp_meta . " AND acid_event.ossim_priority  " . $ossim_priority[0] . " '" . $ossim_priority[1] . "'");
        } else {
            $cs->criteria['ossim_priority']->Set("");
        }
    }
    /* OSSIM Reliability */
    if ($ossim_reliability[1] != " " && $ossim_reliability[1] != "" && $ossim_reliability[1] != "0") {
        $tmp_meta = $tmp_meta . " AND acid_event.ossim_reliability " . $ossim_reliability[0] . " '" . $ossim_reliability[1] . "'";
        $use_ac = false;
    } else {
        if ($ossim_reliability[1] == "0") {
            $tmp_meta = $ossim_reliability[0] == "=" ? $tmp_meta . " AND (acid_event.ossim_reliability is null OR acid_event.ossim_reliability = '0')" : $tmp_meta . " AND acid_event.ossim_reliability " . $ossim_reliability[0] . " '" . $ossim_reliability[1] . "'";
            $use_ac = false;
        } else {
            $cs->criteria['ossim_reliability']->Set("");
        }
    }
    /* OSSIM Asset DST */
    if ($ossim_asset_dst[1] != " " && $ossim_asset_dst[1] != "" && $ossim_asset_dst[1] != "0") {
        $tmp_meta = $tmp_meta . " AND acid_event.ossim_asset_dst " . $ossim_asset_dst[0] . " '" . $ossim_asset_dst[1] . "'";
        $use_ac = false;
    } else {
        if ($ossim_asset_dst[1] == "0") {
            $tmp_meta = $ossim_asset_dst[0] == "=" ? $tmp_meta . " AND (acid_event.ossim_asset_dst is null OR acid_event.ossim_asset_dst = '0')" : $tmp_meta . " AND acid_event.ossim_asset_dst " . $ossim_asset_dst[0] . " '" . $ossim_asset_dst[1] . "'";
            $use_ac = false;
        } else {
            $cs->criteria['ossim_asset_dst']->Set("");
        }
    }
    /* OSSIM Risk A */
    if ($ossim_risk_a != " " && $ossim_risk_a != "" && $ossim_risk_a != "0") {
        if ($ossim_risk_a == "low") {
            //$tmp_meta = $tmp_meta." AND ossim_risk_a >= 1 AND ossim_risk_a <= 4 ";
            $tmp_meta = $tmp_meta . " AND acid_event.ossim_risk_a < 1 ";
            $use_ac = false;
        } else {
            if ($ossim_risk_a == "medium") {
                //$tmp_meta = $tmp_meta." AND ossim_risk_a >= 5 AND ossim_risk_a <= 7 ";
                $tmp_meta = $tmp_meta . " AND acid_event.ossim_risk_a = 1 ";
                $use_ac = false;
            } else {
                if ($ossim_risk_a == "high") {
                    //$tmp_meta = $tmp_meta." AND ossim_risk_a >= 8 AND ossim_risk_a <= 10 ";
                    $tmp_meta = $tmp_meta . " AND acid_event.ossim_risk_a > 1 ";
                    $use_ac = false;
                }
            }
        }
    } else {
        $cs->criteria['ossim_risk_a']->Set("");
    }
    /* Date/Time */
    $time_meta = "";
    $real_time_meta = "";
    DateTimeRows2sql($real_time, $time_cnt, $real_time_meta);
    // Time without utc conversion
    if (DateTimeRows2sql($time, $time_cnt, $time_meta) == 0) {
        $cs->criteria['time']->SetFormItemCnt(0);
    }
    $criteria_sql = $criteria_sql . $tmp_meta;
    /* ********************** PERMS ************************ */
    // Allowed CTX's y Asset Filter
    $perms_sql = "";
    $domain = Session::get_ctx_where();
    if ($domain != "") {
        $perms_sql .= " AND acid_event.ctx in ({$domain})";
    }
    // Asset filter
    $host_perms = Session::get_host_where();
    $net_perms = Session::get_net_where();
    if ($host_perms != "") {
        $perms_sql .= " AND (acid_event.src_host in ({$host_perms}) OR acid_event.dst_host in ({$host_perms})";
        if ($net_perms != "") {
            $perms_sql .= " OR acid_event.src_net in ({$net_perms}) OR acid_event.dst_net in ({$net_perms}))";
        } else {
            $perms_sql .= ")";
        }
    } elseif ($net_perms != "") {
        $perms_sql .= " AND (acid_event.src_net in ({$net_perms}) OR acid_event.dst_net in ({$net_perms}))";
    }
    $criteria_sql .= $perms_sql;
    /* Host ID */
    $op = $hostid[3] != '' ? $hostid[3] : 'IN';
    $and_or = $op == 'NOT IN' ? 'AND' : 'OR';
    // src_host, dst_host fields
    if ($hostid[0] != "") {
        $hostwhere = "UNHEX('" . implode("',UNHEX('", explode(",", $hostid[0])) . "')";
        if ($hostid[2] == "both") {
            $criteria_sql .= " AND (acid_event.src_host {$op} ({$hostwhere}) {$and_or} acid_event.dst_host {$op} ({$hostwhere}))";
        } else {
            $criteria_sql .= " AND acid_event." . $hostid[2] . "_host {$op} ({$hostwhere})";
        }
    }
    /* Network ID */
    if ($netid[0] != "") {
        // src_net, dst_net fields
        $netwhere = "UNHEX('" . implode("',UNHEX('", explode(",", $netid[0])) . "')";
        if ($netid[2] == "both") {
            $criteria_sql .= " AND (acid_event.src_net in ({$netwhere}) OR acid_event.dst_net in ({$netwhere}))";
        } else {
            $criteria_sql .= " AND acid_event." . $netid[2] . "_host in ({$netwhere})";
        }
    }
    /* ********************** IP Criteria ********************************************** */
    /* IP Addresses */
    $tmp2 = "";
    for ($i = 0; $i < $ip_addr_cnt; $i++) {
        $tmp = "";
        if (isset($ip_addr[$i][3]) && $ip_addr[$i][1] != " " && $ip_addr[$i][1] != "") {
            if ($ip_addr[$i][3] != "" && $ip_addr[$i][4] != "" && $ip_addr[$i][5] != "" && $ip_addr[$i][6] != "") {
                /* if use illegal 256.256.256.256 address then
                 *  this is the special case where need to search for portscans
                 */
                if ($ip_addr[$i][3] == "256" && $ip_addr[$i][4] == "256" && $ip_addr[$i][5] == "256" && $ip_addr[$i][6] == "256") {
                    $tmp = $tmp . " acid_event." . $ip_addr[$i][1] . " IS NULL" . " ";
                } else {
                    if ($ip_addr[$i][10] == "") {
                        $tmp = $tmp . " acid_event." . $ip_addr[$i][1] . $ip_addr[$i][2] . "unhex('" . baseIP2hex($ip_addr[$i][3] . "." . $ip_addr[$i][4] . "." . $ip_addr[$i][5] . "." . $ip_addr[$i][6]) . "') ";
                    } else {
                        $mask = getIPMask($ip_addr[$i][3] . "." . $ip_addr[$i][4] . "." . $ip_addr[$i][5] . "." . $ip_addr[$i][6], $ip_addr[$i][10]);
                        if ($ip_addr[$i][2] == "!=") {
                            $tmp_op = " NOT ";
                        } else {
                            $tmp_op = "";
                        }
                        $tmp = $tmp . $tmp_op . " acid_event." . $ip_addr[$i][1] . ">= unhex('" . baseIP2hex($mask[0]) . "') AND acid_event." . $ip_addr[$i][1] . "<= unhex('" . baseIP2hex($mask[1]) . "')";
                    }
                }
            }
            /* if have chosen the address type to be both source and destination */
            if (ereg("ip_both", $tmp)) {
                $tmp_src = ereg_replace("ip_both", "ip_src", $tmp);
                $tmp_dst = ereg_replace("ip_both", "ip_dst", $tmp);
                if ($ip_addr[$i][2] == '=') {
                    $tmp = "(" . $tmp_src . ') OR (' . $tmp_dst . ')';
                } else {
                    $tmp = "(" . $tmp_src . ') AND (' . $tmp_dst . ')';
                }
            }
            $aux_op = $ip_addr_cnt > 0 ? $ip_addr[$i][9] == "AND" || $ip_addr[$i][9] == "OR" ? $ip_addr[$i][9] : "AND" : "";
            if ($tmp != "") {
                $tmp = $ip_addr[$i][0] . "(" . $tmp . ")" . $ip_addr[$i][8] . $aux_op;
            }
        } else {
            if (isset($ip_addr[$i][3]) && $ip_addr[$i][3] != "" || $ip_addr[$i][1] != " " && $ip_addr[$i][1] != "") {
                /* IP_addr_type, but MALFORMED IP address */
                if ($ip_addr[$i][1] != " " && $ip_addr[$i][1] != "" && $ip_addr[$i][3] == "" && ($ip_addr[$i][4] != "" || $ip_addr[$i][5] != "" || $ip_addr[$i][6] != "")) {
                    ErrorMessage("<B>" . gettext("Criteria warning:") . "</B> " . gettext("Invalid IP address criteria") . " ' *." . $ip_addr[$i][4] . "." . $ip_addr[$i][5] . "." . $ip_addr[$i][6] . " '");
                }
                /* ADDRESS, but NO IP_addr_type was given */
                if (isset($ip_addr[$i][3]) && $ip_addr[$i][1] == " " && $ip_addr[$i][1] == "") {
                    ErrorMessage("<B>" . gettext("Criteria warning:") . "</B> " . gettext("A IP address of") . " '" . $ip_addr[$i][3] . "." . $ip_addr[$i][4] . "." . $ip_addr[$i][5] . "." . $ip_addr[$i][6] . "' " . gettext("was entered for as a criteria value, but the type of address (e.g. source, destination) was not specified."));
                }
                /* IP_addr_type IS FILLED, but no ADDRESS */
                if ($ip_addr[$i][1] != " " && $ip_addr[$i][1] != "" && $ip_addr[$i][1] != "" && $ip_addr[$i][3] == "") {
                    ErrorMessage("<B>" . gettext("Criteria warning:") . "</B> " . gettext("An IP address of type") . " '" . $ip_addr[$i][1] . "' " . gettext("was selected (at #") . $i . ") " . gettext("indicating that an IP address should be a criteria, but no address on which to match was specified."));
                }
            }
        }
        $tmp2 = $tmp2 . $tmp;
        if ($i > 0 && ($ip_addr[$i - 1][9] != 'OR' && $ip_addr[$i - 1][9] != 'AND') && $ip_addr[$i - 1][3] != "") {
            ErrorMessage("<B>" . gettext("Criteria warning:") . "</B> " . gettext("Multiple IP address criteria entered without a boolean operator (e.g. AND, OR) between IP Criteria") . " #{$i} and #" . ($i + 1) . ".");
        }
    }
    if ($tmp2 != "") {
        BalanceBrackets($tmp2);
        $criteria_sql = $criteria_sql . " AND ( " . $tmp2 . " )";
        $use_ac = false;
    } else {
        $cs->criteria['ip_addr']->SetFormItemCnt(0);
    }
    /* IP Fields */
    if (FieldRows2sql($ip_field, $ip_field_cnt, $criteria_sql) == 0) {
        $cs->criteria['ip_field']->SetFormItemCnt(0);
    } else {
        $use_ac = false;
    }
    /* CTX */
    if ($ctx != "") {
        $criteria_sql .= " AND acid_event.ctx = UNHEX('{$ctx}')";
    }
    /* Layer-4 encapsulation */
    if ($layer4 == "TCP") {
        $criteria_sql = $criteria_sql . " AND acid_event.ip_proto= '6'";
        $use_ac = false;
    } else {
        if ($layer4 == "UDP") {
            $criteria_sql = $criteria_sql . " AND acid_event.ip_proto= '17'";
            $use_ac = false;
        } else {
            if ($layer4 == "ICMP") {
                $criteria_sql = $criteria_sql . " AND acid_event.ip_proto= '1'";
                $use_ac = false;
            } else {
                if ($layer4 == "RawIP") {
                    $criteria_sql = $criteria_sql . " AND acid_event.ip_proto= '255'";
                    $use_ac = false;
                } else {
                    $cs->criteria['layer4']->Set("");
                }
            }
        }
    }
    /* Join the iphdr table if necessary */
    if (!$cs->criteria['ip_field']->isEmpty()) {
        $join_sql = $ip_join_sql . $join_sql;
    }
    /* ********************** TCP Criteria ********************************************** */
    if ($layer4 == "TCP") {
        $proto_tmp = "";
        /* TCP Ports */
        if (FieldRows2sql($tcp_port, $tcp_port_cnt, $proto_tmp) == 0) {
            $cs->criteria['tcp_port']->SetFormItemCnt(0);
        }
        $criteria_sql = $criteria_sql . $proto_tmp;
        $proto_tmp = "";
        // ****************** DEPRECATED: TCP Flags TCP Fields ********************
        /* TCP Flags */
        /*
        if (isset($tcp_flags) && sizeof($tcp_flags) == 8) {
            if ($tcp_flags[0] == "contains" || $tcp_flags[0] == "is") {
                $flag_tmp = $tcp_flags[1] + $tcp_flags[2] + $tcp_flags[3] + $tcp_flags[4] + $tcp_flags[5] + $tcp_flags[6] + $tcp_flags[7] + $tcp_flags[8];
                if ($tcp_flags[0] == "is") $proto_tmp = $proto_tmp . ' AND tcp_flags=' . $flag_tmp;
                else if ($tcp_flags[0] == "contains") $proto_tmp = $proto_tmp . ' AND (tcp_flags & ' . $flag_tmp . ' = ' . $flag_tmp . " )";
                else $proto_tmp = "";
            }
        }
        */
        /* TCP Fields */
        //if (FieldRows2sql($tcp_field, $tcp_field_cnt, $proto_tmp) == 0) $cs->criteria['tcp_field']->SetFormItemCnt(0);
        /* TCP Options
         *  - not implemented
         */
        //if (!$cs->criteria['tcp_port']->isEmpty() || !$cs->criteria['tcp_flags']->isEmpty() || !$cs->criteria['tcp_field']->isEmpty()) {
        //************************************************************************
        if (!$cs->criteria['tcp_port']->isEmpty()) {
            $criteria_sql = $criteria_sql . $proto_tmp;
            // DEPRECATED tcp_join_sql
            //if (!$cs->criteria['tcp_flags']->isEmpty() || !$cs->criteria['tcp_field']->isEmpty()) $join_sql = $tcp_join_sql . $join_sql;
        }
    }
    /* ********************** UDP Criteria ********************************************* */
    if ($layer4 == "UDP") {
        $proto_tmp = "";
        /* UDP Ports */
        if (FieldRows2sql($udp_port, $udp_port_cnt, $proto_tmp) == 0) {
            $cs->criteria['udp_port']->SetFormItemCnt(0);
        }
        $criteria_sql = $criteria_sql . $proto_tmp;
        $proto_tmp = "";
        // ********************** DEPRECATED UDP Fields *************************
        /* UDP Fields */
        //if (FieldRows2sql($udp_field, $udp_field_cnt, $proto_tmp) == 0) $cs->criteria['udp_field']->SetFormItemCnt(0);
        //if (!$cs->criteria['udp_port']->isEmpty() || !$cs->criteria['udp_field']->isEmpty()) {
        // **********************************************************************
        if (!$cs->criteria['udp_port']->isEmpty()) {
            $criteria_sql = $criteria_sql . $proto_tmp;
            // DEPRECATED udp_join_sql
            //if (!$cs->criteria['udp_field']->isEmpty()) $join_sql = $udp_join_sql . $join_sql;
        }
    }
    // DEPRECATED: ICMP
    /* ********************** ICMP Criteria ******************************************** */
    /*
    if ($layer4 == "ICMP") {
        $proto_tmp = "";
        // ICMP Fields
        if (FieldRows2sql($icmp_field, $icmp_field_cnt, $proto_tmp) == 0) $cs->criteria['icmp_field']->SetFormItemCnt(0);
        if (!$cs->criteria['icmp_field']->isEmpty()) {
            $criteria_sql = $criteria_sql . $proto_tmp;
            $join_sql = $icmp_join_sql . $join_sql;
        }
    }
    */
    /* ********************** Packet Scan Criteria ************************************* */
    if ($layer4 == "RawIP") {
        $proto_tmp = "";
        /* RawIP Fields */
        if (FieldRows2sql($rawip_field, $rawip_field_cnt, $proto_tmp) == 0) {
            $cs->criteria['rawip_field']->SetFormItemCnt(0);
        }
        if (!$cs->criteria['rawip_field']->isEmpty()) {
            $criteria_sql = $criteria_sql . $proto_tmp;
            $join_sql = $rawip_join_sql . $join_sql;
        }
    }
    /* ********************** Payload Criteria ***************************************** */
    //$tmp_payload = "";
    if (DataRows2sql($data, $data_cnt, $data_encode, $tmp_payload) == 0) {
        $cs->criteria['data']->SetFormItemCnt(0);
    } else {
        $use_ac = false;
    }
    //echo "<br><br><br>";
    //print_r($data);
    //print_r("data_cnt: [".$data_cnt."]");
    //print_r($cs->criteria['data']->isEmpty());
    //print_r("criteria_ sql: [".$criteria_sql."]");
    //print_r("tmp_payload: [".$tmp_payload."]");
    //print_r($data);
    if (!$cs->criteria['data']->isEmpty()) {
        $sql = "SELECT acid_event.*, HEX(acid_event.ctx) AS ctx, HEX(acid_event.src_host) AS src_host, HEX(acid_event.dst_host) AS dst_host, HEX(acid_event.src_net) AS src_net, HEX(acid_event.dst_net) AS dst_net, extra_data.* FROM acid_event";
        if (!preg_match("/extra_data/", $data_join_sql)) {
            $data_join_sql .= ",extra_data ";
        }
        $criteria_sql = $criteria_sql . $tmp_payload;
        $use_ac = false;
    }
    // special distinct for idm_username
    if (preg_match("/idm_data/", $data_join_sql)) {
        $sql = preg_replace("/^SELECT/", "SELECT DISTINCT", $sql);
    }
    if ($sig_join) {
        $join_sql = $join_sql . $sig_join_sql;
    }
    $join_sql = $join_sql . $data_join_sql;
    $csql[0] = $join_sql;
    // Ready to ac_acid_event
    $criteria1_sql = $criteria_sql . preg_replace("/ \\d\\d:\\d\\d:\\d\\d/", "", str_replace("timestamp", "day", $real_time_meta));
    $criteria1_sql = preg_replace("/AND\\s+\\)/", " )", preg_replace("/OR\\s+\\)/", " )", $criteria1_sql));
    // Ready to ac_acid_event next day
    $criteria2_sql = $criteria_sql . preg_replace("/ \\d\\d:\\d\\d:\\d\\d/", "", str_replace("timestamp", "day", $time_meta));
    $criteria2_sql = preg_replace("/AND\\s+\\)/", " )", preg_replace("/OR\\s+\\)/", " )", $criteria2_sql));
    // to acid_event
    $criteria_sql = $criteria_sql . $time_meta;
    $criteria_sql = preg_replace("/AND\\s+\\)/", " )", preg_replace("/OR\\s+\\)/", " )", $criteria_sql));
    $csql[1] = $criteria_sql;
    $csql[2] = $perms_sql . preg_replace("/ \\d\\d:\\d\\d:\\d\\d/", "", str_replace("timestamp", "day", $time_meta));
    // $real_time_criteria
    $csql[3] = $use_ac;
    // true if we use ac_acid_event instead acid_event
    $csql[4] = $criteria1_sql;
    $csql[5] = $criteria2_sql;
    $db_aux->close();
    //print_r($csql);
    return $csql;
}