Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(actions): refuse caller-supplied XML in the PAN-OS user-id client (#1003)

Beenu Aroraeb39c98f2a77
diff --git a/services/actions/app/clients/panos_client.py b/services/actions/app/clients/panos_client.py
index 9c201ae9b..3c8e33ea9 100644
--- a/services/actions/app/clients/panos_client.py
+++ b/services/actions/app/clients/panos_client.py
@@ -33,6 +33,9 @@ management network) and avoids those.
from __future__ import annotations
+import html
+import ipaddress
+import re
from typing import Any
import httpx
@@ -40,6 +43,77 @@ import structlog
logger = structlog.get_logger()
+#: PAN-OS accepts a tag name of up to 127 characters. Restricting it to this
+#: set is narrower than the firewall allows and deliberately so: a tag is
+#: chosen by an operator from a small vocabulary their DAG already matches,
+#: not composed from event data, so nothing legitimate needs a character that
+#: carries meaning in XML.
+_TAG_PATTERN = re.compile(r"\A[A-Za-z0-9._-]{1,127}\Z")
+
+
+class PanOsAddressError(ValueError):
+ """The value offered as an address is not one.
+
+ Raised rather than escaped. An escaped non-address would be sent to the
+ firewall as a literal, where it silently matches nothing — so a block that
+ never applied would report success. Refusing names the problem at the
+ point it can still be fixed.
+ """
+
+
+def _validated_address(value: str) -> str:
+ """Return ``value`` if it is an address PAN-OS registers, else raise.
+
+ Accepts the three forms the user-id API takes: a single address, a CIDR
+ network, and a hyphenated range. Everything else is refused.
+
+ This is the primary control, with escaping below as defence in depth.
+ Escaping alone would stop the injection and still hand the firewall a
+ string that is not an address; validation means the only values that reach
+ the XML are ones that cannot contain a character worth escaping.
+ """
+ candidate = (value or "").strip()
+ if not candidate:
+ raise PanOsAddressError("no address supplied")
+
+ try:
+ ipaddress.ip_address(candidate)
+ return candidate
+ except ValueError:
+ pass
+
+ try:
+ # strict=False so an operator may pass 10.0.0.1/24 and mean the
+ # network; PAN-OS resolves it the same way.
+ ipaddress.ip_network(candidate, strict=False)
+ return candidate
+ except ValueError:
+ pass
+
+ start, separator, end = candidate.partition("-")
+ if separator:
+ try:
+ first = ipaddress.ip_address(start.strip())
+ last = ipaddress.ip_address(end.strip())
+ except ValueError:
+ pass
+ else:
+ # Compared as integers: `ip_address` returns an IPv4Address or an
+ # IPv6Address, and the two are not orderable against each other,
+ # so `first <= last` is only well-typed once the versions match —
+ # which a type checker cannot infer from the guard.
+ if first.version == last.version and int(first) <= int(last):
+ return candidate
+
+ raise PanOsAddressError(f"{value!r} is not an IP address, CIDR network or address range; refusing to send it to the firewall")
+
+
+def _validated_tag(value: str) -> str:
+ candidate = (value or "").strip()
+ if not _TAG_PATTERN.match(candidate):
+ raise PanOsAddressError(f"{value!r} is not a valid PAN-OS tag name; expected 1-127 characters from [A-Za-z0-9._-]")
+ return candidate
+
class PanOsClient:
"""Thin async wrapper over the PAN-OS XML API used by AiSOC."""
@@ -65,23 +139,34 @@ class PanOsClient:
decide to silently release the block. Operators who want a
TTL on the block should set it at the AiSOC playbook
layer where it's auditable.
+
+ ``ip`` and ``tag`` arrive from ``ActionRequest.parameters`` and were
+ interpolated raw. A value closing the attribute could append further
+ payloads to the same message, so a *block* emitted well-formed XML
+ containing an ``unregister`` of any address the caller chose — the
+ containment action releasing a block instead of applying one
+ (GHSA-w754-prh8-m56j). Both are validated, then escaped.
"""
+ address = html.escape(_validated_address(ip), quote=True)
+ member = html.escape(_validated_tag(tag), quote=True)
return (
f"<uid-message>"
f"<version>2.0</version><type>update</type>"
f"<payload><register>"
- f'<entry ip="{ip}" persistent="1">'
- f"<tag><member>{tag}</member></tag>"
+ f'<entry ip="{address}" persistent="1">'
+ f"<tag><member>{member}</member></tag>"
f"</entry></register></payload></uid-message>"
)
def _xml_unregister(self, ip: str, tag: str) -> str:
+ address = html.escape(_validated_address(ip), quote=True)
+ member = html.escape(_validated_tag(tag), quote=True)
return (
f"<uid-message>"
f"<version>2.0</version><type>update</type>"
f"<payload><unregister>"
- f'<entry ip="{ip}">'
- f"<tag><member>{tag}</member></tag>"
+ f'<entry ip="{address}">'
+ f"<tag><member>{member}</member></tag>"
f"</entry></unregister></payload></uid-message>"
)
diff --git a/services/actions/tests/test_panos_xml_injection.py b/services/actions/tests/test_panos_xml_injection.py
new file mode 100644
index 000000000..45387f318
--- /dev/null
+++ b/services/actions/tests/test_panos_xml_injection.py
@@ -0,0 +1,139 @@
+"""GHSA-w754-prh8-m56j: the PAN-OS client must not let a caller write XML.
+
+`_xml_register` and `_xml_unregister` interpolated `ip` and `tag` straight
+into a user-id message with f-strings. Both values arrive from
+`ActionRequest.parameters`, so a value that closed the `ip` attribute could
+append further `<payload>` elements to the same message.
+
+The consequence is worse than it first sounds, and is why this is graded high
+rather than medium: the injected payload is *valid* PAN-OS, so calling
+`block_ip` produced well-formed XML containing an `unregister` for whatever
+address the caller chose. The containment action released a block instead of
+applying one, and the firewall reported success.
+
+The fix validates before it escapes. Escaping alone stops the injection and
+still hands the firewall a string that is not an address, where it matches
+nothing — so a block that never applied would report success, trading a loud
+failure for a silent one.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.clients.panos_client import PanOsClient
+
+try: # pragma: no cover - the pre-fix module has no such symbol
+ from app.clients.panos_client import PanOsAddressError
+except ImportError: # the vulnerable tree, where the impact test must still run
+ PanOsAddressError = ValueError # type: ignore[assignment,misc]
+
+#: Verbatim from the advisory. It closes the `ip` attribute, ends the
+#: register payload, opens an unregister payload for an unrelated host, and
+#: reopens a register so the message still parses.
+REPORTED_PAYLOAD = (
+ '"><tag><member>x</member></tag></entry></register></payload>'
+ '<payload><unregister><entry ip="192.168.1.1">'
+ "<tag><member>aisoc-blocked</member></tag></entry></unregister></payload>"
+ '<payload><register><entry ip="127.0.0.2'
+)
+
+#: The same break-out through the tag, which the advisory's fix suggestion
+#: also covers and which is reachable by the same route.
+TAG_PAYLOAD = '</member></tag></entry></register></payload><payload><unregister><entry ip="10.0.0.1"><tag><member>aisoc-blocked'
+
+
+def client() -> PanOsClient:
+ """A client with no transport — these assertions are about the payload."""
+ return PanOsClient.__new__(PanOsClient)
+
+
+class TestTheReportedInjectionIsRefused:
+ def test_the_address_payload_cannot_reach_the_firewall(self, client: PanOsClient) -> None:
+ with pytest.raises(PanOsAddressError):
+ client._xml_register(REPORTED_PAYLOAD, "aisoc-blocked")
+
+ def test_the_tag_payload_cannot_reach_the_firewall(self, client: PanOsClient) -> None:
+ with pytest.raises(PanOsAddressError):
+ client._xml_register("10.0.0.1", TAG_PAYLOAD)
+
+ def test_unregister_is_refused_the_same_way(self, client: PanOsClient) -> None:
+ """Both builders shared the defect, so both need the assertion."""
+ with pytest.raises(PanOsAddressError):
+ client._xml_unregister(REPORTED_PAYLOAD, "aisoc-blocked")
+
+ @pytest.mark.parametrize("hostile", [REPORTED_PAYLOAD, '10.0.0.1"/><unregister>', "10.0.0.1</member>"])
+ def test_a_block_never_emits_an_unregister(self, client: PanOsClient, hostile: str) -> None:
+ """The impact, asserted without naming the fix.
+
+ Deliberately does not require `PanOsAddressError`: a test that only
+ asserts a new exception type fails against the vulnerable tree with
+ `ImportError`, which proves the symbol is absent rather than that the
+ defect is detected. Refusing and returning safe XML are both passes
+ here, so this assertion is meaningful against any version of the
+ module — and against the pre-fix one it fails on the payload, which
+ is the point.
+ """
+ try:
+ built = client._xml_register(hostile, "aisoc-blocked")
+ except ValueError:
+ return # refused before building: the shipped behaviour
+ assert "<unregister>" not in built, f"block_ip({hostile!r}) built a message telling the firewall to RELEASE a block"
+
+
+class TestLegitimateInputStillWorks:
+ """A fix that refused real addresses would be reverted, so pin them.
+
+ PAN-OS registers three forms and all three are in use; validating only
+ `ip_address()` would break CIDR and range blocks.
+ """
+
+ @pytest.mark.parametrize(
+ "address",
+ ["10.0.0.1", "192.168.1.254", "2001:db8::1", "10.0.0.0/24", "2001:db8::/32", "10.0.0.1-10.0.0.9"],
+ )
+ def test_accepted_address_forms(self, client: PanOsClient, address: str) -> None:
+ message = client._xml_register(address, "aisoc-blocked")
+ assert message.startswith("<uid-message>") and message.endswith("</uid-message>")
+ assert message.count("<payload>") == 1 and message.count("</payload>") == 1
+ assert "<unregister>" not in message
+ assert address in message
+
+ def test_a_host_bit_in_a_network_is_accepted(self, client: PanOsClient) -> None:
+ """`10.0.0.1/24` means the network to an operator, and to PAN-OS."""
+ assert client._xml_register("10.0.0.1/24", "aisoc-blocked")
+
+ @pytest.mark.parametrize("tag", ["aisoc-blocked", "SOC_Quarantine", "tier1.block", "a" * 127])
+ def test_accepted_tag_forms(self, client: PanOsClient, tag: str) -> None:
+ assert f"<member>{tag}</member>" in client._xml_register("10.0.0.1", tag)
+
+
+class TestRefusalRatherThanEscaping:
+ """A non-address must raise, not be escaped into the message.
+
+ An escaped non-address is syntactically safe and semantically wrong: the
+ firewall matches nothing and answers success, so a block that never
+ applied reports as applied. That is a worse outcome than an error.
+ """
+
+ @pytest.mark.parametrize(
+ "value",
+ ["", " ", "not-an-ip", "10.0.0.999", "10.0.0.1 10.0.0.2", "10.0.0.9-10.0.0.1", "example.com"],
+ )
+ def test_non_addresses_raise(self, client: PanOsClient, value: str) -> None:
+ with pytest.raises(PanOsAddressError):
+ client._xml_register(value, "aisoc-blocked")
+
+ @pytest.mark.parametrize("tag", ["", " ", "tag with space", "tag<x", "a" * 128, "tag&amp;"])
+ def test_invalid_tags_raise(self, client: PanOsClient, tag: str) -> None:
+ with pytest.raises(PanOsAddressError):
+ client._xml_register("10.0.0.1", tag)
+
+ def test_a_reversed_range_is_refused(self, client: PanOsClient) -> None:
+ """Ordering is checked, not just parseability of both halves."""
+ with pytest.raises(PanOsAddressError):
+ client._xml_register("10.0.0.9-10.0.0.1", "aisoc-blocked")
+
+ def test_mixed_family_range_is_refused(self, client: PanOsClient) -> None:
+ with pytest.raises(PanOsAddressError):
+ client._xml_register("10.0.0.1-2001:db8::1", "aisoc-blocked")
diff --git a/services/agents/app/investigator/report_writer_agent.py b/services/agents/app/investigator/report_writer_agent.py
index 4d22a923c..db6221f55 100644
--- a/services/agents/app/investigator/report_writer_agent.py
+++ b/services/agents/app/investigator/report_writer_agent.py
@@ -9,6 +9,7 @@ Responsibilities:
from __future__ import annotations
+import html
import time
from datetime import datetime
from typing import Any
@@ -130,9 +131,13 @@ def _md_to_html(md: str, case_id: str) -> str:
body = markdown.markdown(md, extensions=["tables", "fenced_code"])
except ImportError:
- # Fallback: wrap in <pre>
- body = f"<pre>{md}</pre>"
+ # Escaped, because a raw `<pre>` wrap leaks HTML through unchanged and
+ # this report carries model output and connector-supplied entity names.
+ # `orchestrator/report.py` already reached this conclusion and says so
+ # in a comment; this copy did the thing that comment warns against.
+ body = f"<pre>{html.escape(md)}</pre>"
+ case_id = html.escape(str(case_id), quote=True)
ts = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
return f"""<!DOCTYPE html>
<html lang="en">
diff --git a/services/agents/tests/test_report_html_escaping.py b/services/agents/tests/test_report_html_escaping.py
new file mode 100644
index 000000000..d64446575
--- /dev/null
+++ b/services/agents/tests/test_report_html_escaping.py
@@ -0,0 +1,85 @@
+"""The incident report's fallback renderer must not emit untrusted HTML.
+
+`_md_to_html` uses the `markdown` package when it is importable and wraps the
+source in `<pre>` when it is not. The fallback interpolated the Markdown raw,
+and the title interpolated the case id raw.
+
+Found while fixing GHSA-w754-prh8-m56j, by looking for the same shape
+elsewhere. What makes it worth a test rather than a quiet fix is that the
+sibling renderer in `app/orchestrator/report.py` already escapes here, and its
+comment says why in as many words: "a raw `<pre>` wrap would leak HTML through
+unchanged". One copy of the lesson was written down and the other copy did the
+thing it warns about.
+
+The content is not trustworthy: the Markdown is model output and the report
+embeds connector-supplied entity names, so a hostname or filename carried in
+from an alert reaches an analyst's browser.
+"""
+
+from __future__ import annotations
+
+import builtins
+import re
+
+import pytest
+from app.investigator.report_writer_agent import _md_to_html
+
+SCRIPT = "<script>alert('xss')</script>"
+IMG = "<img src=x onerror=alert(1)>"
+
+
+def without_markdown(monkeypatch: pytest.MonkeyPatch):
+ """Force the `<pre>` fallback.
+
+ The defect is only reachable when `markdown` is absent, which is the
+ branch a slim image takes — so a test that did not force it would
+ exercise the safe path and pass against the vulnerable code.
+ """
+ real_import = builtins.__import__
+
+ def _refuse_markdown(name: str, *args, **kwargs):
+ if name == "markdown":
+ raise ImportError("forced for this test")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _refuse_markdown)
+
+
+def _title_of(document: str) -> str:
+ found = re.search(r"<title>(.*?)</title>", document, re.S)
+ assert found, "the report has no title element"
+ return found.group(1)
+
+
+class TestTheFallbackRendererEscapes:
+ def test_markdown_body_cannot_carry_an_element(self, without_markdown) -> None:
+ document = _md_to_html(SCRIPT, "case-1")
+ assert "<script>alert" not in document
+ assert "&lt;script&gt;" in document
+
+ def test_the_case_id_cannot_carry_an_element(self, without_markdown) -> None:
+ """The title took the case id raw.
+
+ Asserted structurally rather than by substring: `html.escape` encodes
+ the angle brackets but leaves `onerror=alert(1)` as literal text, so a
+ substring check passes on escaped output and proves nothing.
+ """
+ title = _title_of(_md_to_html("# ok", IMG))
+ assert not re.search(r"<(img|script)", title)
+
+ def test_the_document_stays_a_single_document(self, without_markdown) -> None:
+ """A payload closing `</html>` and opening another would not show up
+ in either assertion above."""
+ document = _md_to_html("</body></html><html><body>grafted", "</title></head><body>grafted")
+ assert document.count("<html") == 1
+ assert document.count("</html>") == 1
+
+
+class TestTheMarkdownPathIsUnchanged:
+ def test_ordinary_markdown_still_renders(self) -> None:
+ """The fix must not reach the `markdown` path, which handles its own
+ escaping — double-escaping there would corrupt every real report."""
+ document = _md_to_html("# Heading\n\nSome **bold** text.", "case-1")
+ assert "Heading" in document
+ assert "&amp;lt;" not in document