Beispiel #1
0
def test_escape():
    """
    Test `prewikka.utils.html.escape()`.
    """
    assert text_type(escape(None)) == ''
    assert text_type(escape('')) == ''
    assert text_type(escape('foo')) == 'foo'
    assert text_type(escape('foo bar')) == 'foo bar'
    assert text_type(escape('<script>alert();</script>')
                     ) == '&lt;script&gt;alert();&lt;/script&gt;'
Beispiel #2
0
    def getUrlLink(self, name, url=None):
        if not name:
            return None

        if not url:
            if name.find("http://") != -1:
                url = name

            elif re.compile("\.[^\s]+\.[^\s+]").search(name):
                url = "http://" + name

            else:
                return name

        return resource.HTMLSource(
            '<a target="%s" href="%s">%s</a>' %
            (env.external_link_target, html.escape(url), html.escape(name)))
Beispiel #3
0
    def buildAlertIdent(self, alert, parent):
        calist = {}

        for alertident in parent["alertident"]:

            # IDMEF draft 14 page 27
            # If the "analyzerid" is not provided, the alert is assumed to have come
            # from the same analyzer that is sending the Alert.

            analyzerid = alertident["analyzerid"]
            if not analyzerid:
                for a in alert["analyzer"]:
                    if a["analyzerid"]:
                        analyzerid = a["analyzerid"]
                        break

            if not analyzerid in calist:
                calist[analyzerid] = []

            calist[analyzerid].append(alertident["alertident"])

        idx = 1
        for analyzerid in calist.keys():

            content = ""
            missing = 0
            for ident in calist[analyzerid]:
                criteria = Criterion("alert.analyzer.analyzerid", "=",
                                     analyzerid) & Criterion(
                                         "alert.messageid", "=", ident)

                results = env.dataprovider.get(criteria)
                if len(results) == 0:
                    missing += 1
                    #content += "<li>" + _("Invalid 'analyzerid:messageid' pair, '%(analyzerid):%(messageid)'") % { "analyzerid": analyzerid, "messageid": ident } + "</li>"
                else:
                    alert = results[0]["alert"]
                    link = url_for(".", analyzerid=analyzerid, messageid=ident)
                    content += '<li><a class="widget-link" title="%s" href="%s">%s</a></li>' % (
                        _("Alert details"), link,
                        html.escape(alert["classification.text"]))

            if missing > 0:
                content += "<li>" + (
                    _("%d linked alerts missing (probably deleted)") %
                    missing) + "</li>"

            self.newTableCol(
                idx,
                resource.HTMLSource(
                    "<ul style='padding: 0px; margin: 0px 0px 0px 10px;'>%s</ul>"
                    % content))
            self.buildAnalyzer(alert["analyzer(-1)"])
            self.newTableRow()

            idx += 1
Beispiel #4
0
    def update(self):
        data = self._get_plugin_infos()

        env.request.web.send_stream(json.dumps(
            {"total": data.maintenance_total}),
                                    event="begin",
                                    sync=True)

        for mod, fromversion, uplist in itertools.chain.from_iterable(
                data.maintenance.values()):
            for upscript in uplist:
                if isinstance(upscript, Exception):
                    continue

                label = _("Applying %(module)s %(script)s...") % {
                    'module': mod.full_module_name,
                    'script': text_type(upscript)
                }
                env.request.web.send_stream(json.dumps({
                    "label":
                    html.escape(label),
                    'module':
                    html.escape(mod.full_module_name),
                    'script':
                    html.escape(text_type(upscript))
                }),
                                            sync=True)

                try:
                    upscript.apply()
                except Exception as e:
                    env.request.web.send_stream(json.dumps({
                        "logs":
                        "\n".join(html.escape(x) for x in upscript.query_logs),
                        "error":
                        html.escape(text_type(e))
                    }),
                                                sync=True)
                else:
                    env.request.web.send_stream(json.dumps({
                        "logs":
                        "\n".join(html.escape(x) for x in upscript.query_logs),
                        "success":
                        True
                    }),
                                                sync=True)

        env.request.web.send_stream(data=json.dumps(
            {"label": _("All updates applied")}),
                                    event="finish",
                                    sync=True)
        env.request.web.send_stream("close", event="close")

        env.db.trigger_plugin_change()
Beispiel #5
0
    def buildAdditionalData(self,
                            alert,
                            ignore=[],
                            ignored={},
                            ip_options=[],
                            tcp_options=[]):
        self.beginSection(_("Additional data"))

        self.beginTable()
        self.newTableCol(0, _("Meaning"), header=True)
        self.newTableCol(0, _("Value"), header=True)

        index = 1
        for ad in alert["additional_data"]:
            value = None
            meaning = ad["meaning"]

            if meaning == "ip_option_code":
                ip_options.append((ad["data"], 0, None))
                ignored[meaning] = ""

            if meaning == "ip_option_data":
                data = ad["data"]
                ip_options[-1] = (ip_options[-1][0], len(data), data)
                ignored[meaning] = ""

            if meaning == "tcp_option_code":
                tcp_options.append((ad["data"], 0, None))
                ignored[meaning] = ""

            if meaning == "tcp_option_data":
                data = ad["data"]
                tcp_options[-1] = (tcp_options[-1][0], len(data), data)
                ignored[meaning] = ""

            if ad["data"] != None:
                value = ad["data"]
                if ad["type"] == "byte-string" and meaning != "payload":
                    value = utils.hexdump(value)

            for field in ignore:
                if meaning != None and meaning == field[0]:
                    ignored[meaning] = value
                    break

            links = []
            for url, text in hookmanager.trigger(
                    "HOOK_ALERTSUMMARY_MEANING_LINK", alert, meaning, value):
                if url:
                    links.append("<a target='%s' href='%s'>%s</a>" % \
                                 (env.external_link_target, html.escape(url), html.escape(text)))

            if links:
                meaning = "<a class='popup_menu_toggle'>%s</a><span class='popup_menu'>%s</span>" % \
                          (html.escape(meaning), "".join(links))

            if not meaning in ignored:
                self.newTableCol(
                    index, resource.HTMLSource(meaning or "Data content"))
                self.newTableCol(index, html.escape(value) if value else None)
                index += 1

        self.endTable()
        self.endSection()
Beispiel #6
0
    def render(self, analyzerid=None, messageid=None):
        MessageSummary.render(self)

        alert = env.dataprovider.get(
            getUriCriteria("alert", analyzerid, messageid))[0]["alert"]

        env.request.dataset["sections"] = []

        self.beginSection(self.getSectionName(alert))

        self.buildTime(alert)

        self.beginTable()
        self.newTableEntry(_("MessageID"), alert["messageid"])
        self.endTable()

        self.beginTable()
        self.buildClassification(alert)
        self.buildImpact(alert)
        self.endTable()

        self.beginSection(_("Actions"))
        for action in alert["assessment.action"]:
            self.buildAction(action)
        self.endSection()

        self.buildCorrelationAlert(alert)
        self.buildToolAlert(alert)
        self.buildReference(alert)

        self.beginSection(_("Analyzer #%d") % (len(alert["analyzer"]) - 1))
        self.buildAnalyzer(alert["analyzer(-1)"])

        self.buildAnalyzerList(alert)
        self.endSection()

        self.endSection()

        self.buildSourceTarget(alert)

        ip = self.buildIpHeaderTable(alert)
        tcp = self.buildTcpHeaderTable(alert)
        udp = self.buildUdpHeaderTable(alert)
        icmp = self.buildIcmpHeaderTable(alert)
        data = self.buildPayloadTable(alert)

        ignored_value = {}
        ip_options = []
        tcp_options = []

        group = ip.field_list + tcp.field_list + udp.field_list + icmp.field_list + data.field_list
        self.buildAdditionalData(alert,
                                 ignore=group,
                                 ignored=ignored_value,
                                 ip_options=ip_options,
                                 tcp_options=tcp_options)

        if len(ignored_value.keys()) > 0:

            def blah(b):
                if b >= 32 and b < 127:
                    return chr(b)
                else:
                    return "."

            self.beginSection(_("Network centric information"))

            self.beginTable(cl="table-borderless")
            ip.render_table(self, "IP", ignored_value)
            self.ipOptionRender(ip_options)

            tcp.render_table(self, "TCP", ignored_value)
            self.tcpOptionRender(tcp_options)

            udp.render_table(self, "UDP", ignored_value)
            icmp.render_table(self, "ICMP", ignored_value)

            if "payload" in ignored_value:
                val = {}

                payload = html.escape(utils.hexdump(
                    ignored_value["payload"])).replace(
                        " ", resource.HTMLSource("&nbsp;"))
                val["payload"] = resource.HTMLSource(
                    "<span class='fixed'>%s</span>" % payload)
                data.render_table(self, _("Payload"), val)

                pset = set(string.printable)
                payload = ''.join((i if i in pset else '.'
                                   for i in ignored_value["payload"]))
                val["payload"] = resource.HTMLSource(
                    "<div style='overflow: auto;'>%s</div>" %
                    html.escape(payload).replace("\n",
                                                 resource.HTMLSource("<br/>")))
                data.render_table(self, _("ASCII Payload"), val)

            self.endTable()
            self.endSection()
    def buildAlertIdent(self, alert, parent):
        calist = {}

        for alertident in parent["alertident"]:

            # IDMEF draft 14 page 27
            # If the "analyzerid" is not provided, the alert is assumed to have come
            # from the same analyzer that is sending the Alert.

            analyzerid = alertident["analyzerid"]
            if not analyzerid:
                for a in alert["analyzer"]:
                    if a["analyzerid"]:
                        analyzerid = a["analyzerid"]
                        break

            calist.setdefault(analyzerid, []).append(alertident["alertident"])

        for idx, (analyzerid, idents) in enumerate(calist.items()):
            content = ""
            results = []
            total = 0
            step = 50
            limit = min(len(idents), 500)

            for i in range(0, limit, step):
                # FIXME #3250, #3251
                # We execute several queries to avoid recursion errors
                criteria = Criterion()
                for ident in idents[i:i+step]:
                    criteria |= self._get_alert_ident_criterion(analyzerid, ident)

                results.append(env.dataprovider.query(["alert.messageid", "alert.classification.text"], criteria))

            for ident, classif in itertools.chain(*results):
                link = url_for(".render", analyzerid=analyzerid, messageid=ident)
                content += '<li><a title="%s" href="%s">%s</a></li>' % (_("Alert details"), link, html.escape(classif))
                total += 1

            missing = limit - total
            if missing > 0:
                content += "<li>" + (_("%d linked alerts missing (probably deleted)") % missing) + "</li>"

            omitted = len(idents) - limit
            if omitted > 0:
                content += "<li>" + (_("%d linked alerts omitted") % omitted) + "</li>"

            self.newTableCol(idx + 1, resource.HTMLSource("<ul style='padding: 0px; margin: 0px 0px 0px 10px;'>%s</ul>" % content))

            linked_alerts = env.dataprovider.get(self._get_alert_ident_criterion(analyzerid, idents[0]))
            if linked_alerts:
                self.buildAnalyzer(linked_alerts[0]["alert.analyzer(-1)"])
            else:
                self.newTableCol(1, None)

            self.newTableRow()
    def buildAdditionalData(self, msg, ptype, ignore=[], ignored={}, ip_options=[], tcp_options=[]):
        self.beginSection(_("Additional data"))

        self.beginTable()
        self.newTableCol(0, _("Meaning"), header=True)
        self.newTableCol(0, _("Value"), header=True)

        index = 1
        for ad in msg["additional_data"]:
            value = None
            meaning = ad["meaning"]

            if meaning == "ip_option_code":
                ip_options.append((ad["data"], 0, None))
                ignored[meaning] = ""

            if meaning == "ip_option_data":
                data = ad["data"]
                ip_options[-1] = (ip_options[-1][0], len(data), data)
                ignored[meaning] = ""

            if meaning == "tcp_option_code":
                tcp_options.append((ad["data"], 0, None))
                ignored[meaning] = ""

            if meaning == "tcp_option_data":
                data = ad["data"]
                tcp_options[-1] = (tcp_options[-1][0], len(data), data)
                ignored[meaning] = ""

            if ad["data"] is not None:
                value = ad["data"]
                if ad["type"] == "byte-string" and meaning != "payload":
                    value = html.escape(utils.hexdump(value)).replace(" ", resource.HTMLSource("&nbsp;"))
                    value = resource.HTMLSource("<span class='fixed'>%s</span>" % value)

            for field in ignore:
                if meaning is not None and meaning == field[0]:
                    ignored[meaning] = value
                    break

            links = resource.HTMLSource()
            for obj in filter(None, hookmanager.trigger("HOOK_%sSUMMARY_MEANING_LINK" % ptype.upper(), msg, meaning, value)):
                links += obj

            if links:
                meaning = resource.HTMLNode("a", meaning, **{
                    "data-toggle": "popover",
                    "data-placement": "bottom",
                    "data-html": "true",
                    "data-content": '<span class="popup-menu">%s</span>' % links,
                    "data-template": POPOVER_HTML,
                })

            if meaning not in ignored:
                self.newTableCol(index, resource.HTMLSource(meaning or "Data content"))
                self.newTableCol(index, html.escape(value) if value is not None else None)
                index += 1

        self.endTable()
        self.endSection()