Skip to content

hypnguyen1209/offensive-claude / skills/exploit-development

exploit-development

Verified

Use when turning a memory-corruption bug into a working PoC — stack/ROP, glibc heap & FSOP, format strings, browser/JIT type confusion & UAF, Linux/Windows kernel LPE against ASLR/DEP/CFG/CET/V8-Sandbox

scripts/exploit_context.py

View on GitHub
#!/usr/bin/env python3
"""exploit_context.py - cached target fingerprint + the gate that forbids blocked techniques.

Two jobs:
  1. CACHE the target's exploitation-relevant context ONCE (checksec mitigations, libc, arch) so an
     autopilot/PoC loop reuses it instead of re-running recon on every attempt (raptor idea B).
  2. GATE technique choice: given the target's mitigations (and, when present, the empirical
     mitigation map from feasibility_profile.py), answer "is this technique blocked here?" so
     /exploit never wastes effort on a primitive the target actually prevents (raptor idea J).

The checksec call needs a Linux binary, so `build()` takes an injectable `runner` (defaults to
safe_subprocess.run) - the cache, parsing, and block-verdict logic are all stdlib and testable
without a target. Mitigation->technique blocking is a CONSERVATIVE static map: a technique is
"blocked" only when a mitigation provably prevents it as stated (e.g. NX blocks shellcode on a
non-exec stack). When the empirical map marks a technique blocked, that wins (it is artefact-grade).

Pure stdlib. CLI:
  exploit_context.py build  --target ./bin [--out exploit-context.json]
  exploit_context.py check  --context exploit-context.json <technique>   # exit 0 allowed, 3 blocked
  exploit_context.py show   --context exploit-context.json
"""
from __future__ import annotations

import argparse
import json
import os
import re
import sys
from dataclasses import dataclass, field, asdict
from typing import Callable, Optional

# Mitigation -> techniques it BLOCKS (conservative; only provably-prevented pairs).
TECHNIQUE_BLOCKS = {
    "nx":          {"ret2shellcode", "stack_shellcode", "exec_stack", "exec_heap"},
    "canary":      {"naive_stack_overflow", "seh_overwrite_naive"},
    "pie":         {"fixed_address_rop", "fixed_address_jmp", "static_got_overwrite"},
    "full_relro":  {"got_overwrite"},
    "partial_relro": set(),
    "fortify":     {"unbounded_strcpy_overflow"},
    "aslr":        {"hardcoded_libc_address"},
    "cfg":         {"indirect_call_hijack_unguarded"},
    "cet":         {"backward_edge_rop_unsafe", "ret2libc_naive"},
}
# A technique is allowed unless a present mitigation blocks it OR the empirical map says blocked.
_KNOWN_TECHNIQUES = set().union(*TECHNIQUE_BLOCKS.values())


@dataclass
class ExploitContext:
    target: str = ""
    arch: str = ""
    libc: str = ""
    mitigations: dict = field(default_factory=dict)      # {nx:bool, canary:bool, pie:bool, ...}
    empirical_mitigation_map: dict = field(default_factory=dict)  # from feasibility_profile.py
    built_at: str = ""
    undetermined: bool = False    # True when hardening could not be determined -> gate fails CLOSED

    def to_dict(self) -> dict:
        return asdict(self)

    @classmethod
    def load(cls, path: str) -> "ExploitContext":
        with open(path, "r", encoding="utf-8") as fh:
            d = json.load(fh)
        if not isinstance(d, dict):
            raise ValueError("exploit-context must be a JSON object")
        known = {f for f in cls.__dataclass_fields__}  # type: ignore[attr-defined]
        obj = cls(**{k: v for k, v in d.items() if k in known})
        if not isinstance(obj.mitigations, dict):           # crafted/non-dict -> fail closed, no crash
            obj.mitigations, obj.undetermined = {}, True
        if not isinstance(obj.empirical_mitigation_map, dict):
            obj.empirical_mitigation_map = {}
        return obj

    def save(self, path: str) -> None:
        os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
        tmp = f"{path}.tmp{os.getpid()}"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(self.to_dict(), fh, indent=2)
        os.replace(tmp, path)

    # --------------------------------------------------------------- the gate
    def static_blocked(self) -> set:
        blocked = set()
        mits = self.mitigations if isinstance(self.mitigations, dict) else {}
        for mit, techs in TECHNIQUE_BLOCKS.items():
            if mits.get(mit) is True:
                blocked |= techs
        return blocked

    def empirical_blocked(self) -> set:
        """Techniques the empirical matrix marked blocked (artefact-grade, overrides static).
        Normalizes a string value (a bare str must become {str}, NOT a per-char set) and case."""
        m = self.empirical_mitigation_map if isinstance(self.empirical_mitigation_map, dict) else {}
        b = m.get("blocked_techniques")
        if isinstance(b, str):
            b = [b]
        if not isinstance(b, (list, set, tuple)):
            return set()
        return {str(t).strip().lower() for t in b if str(t).strip()}

    def is_blocked(self, technique: str) -> bool:
        t = (technique or "").strip().lower()
        if t in self.static_blocked() or t in self.empirical_blocked():
            return True
        return bool(self.undetermined) and t in _KNOWN_TECHNIQUES  # unknown hardening -> fail closed

    def assert_allowed(self, technique: str) -> tuple:
        """(allowed: bool, reason). /exploit must not use a technique this returns False for."""
        t = (technique or "").strip().lower()
        if t in self.empirical_blocked():
            return False, f"technique {t!r} is blocked by the EMPIRICAL mitigation map (artefact-grade)"
        if t in self.static_blocked():
            mits = sorted(m for m, techs in TECHNIQUE_BLOCKS.items()
                          if t in techs and isinstance(self.mitigations, dict)
                          and self.mitigations.get(m) is True)
            return False, f"technique {t!r} is blocked by mitigation(s): {', '.join(mits)}"
        if self.undetermined and t in _KNOWN_TECHNIQUES:
            return False, (f"technique {t!r} is a mitigation-blockable class but target hardening is "
                           "UNDETERMINED - refusing it (fail-closed; build on the real target first)")
        return True, f"technique {t!r} not blocked by known mitigations (still verify empirically)"


# ------------------------------------------------------------------- checksec parsing
def parse_checksec(text: str) -> dict:
    """Parse `pwn checksec` / checksec.sh output into a mitigations dict. Permissive on wording."""
    t = (text or "").lower()
    mit = {}

    def present(label, *needles):
        for n in needles:
            m = re.search(re.escape(n) + r"\s*[:=]?\s*(\S+)", t)
            if m:
                val = m.group(1)
                mit[label] = not any(neg in val for neg in ("no", "disabl", "off", "false"))
                return
        # fall back to a bare keyword presence (e.g. "NX enabled")
        if any(n in t for n in needles):
            mit[label] = "no " + needles[0] not in t and "no-" + needles[0] not in t

    # NX / stack canary / PIE / RELRO / FORTIFY
    if "nx enabled" in t or "nx:" in t:
        mit["nx"] = "nx disabled" not in t and "nx unknown" not in t
    if "no canary found" in t:
        mit["canary"] = False
    elif "canary found" in t or "stack canary" in t:
        mit["canary"] = True
    if "no pie" in t or "pie disabled" in t:
        mit["pie"] = False
    elif "pie enabled" in t or re.search(r"\bpie\b", t):
        mit["pie"] = "no pie" not in t
    if "full relro" in t:
        mit["full_relro"] = True
        mit["partial_relro"] = False
    elif "partial relro" in t:
        mit["partial_relro"] = True
        mit["full_relro"] = False
    elif "no relro" in t:
        mit["full_relro"] = False
        mit["partial_relro"] = False
    mfort = re.search(r"fortify(?:_source| source)?\s*[:=]?\s*(\w+)", t)
    if mfort:
        v = mfort.group(1)
        mit["fortify"] = not any(neg in v for neg in ("no", "disabl", "off", "false"))
    elif "fortified" in t:
        mit["fortify"] = True
    elif "fortify" in t:                       # bare "No FORTIFY" with no value token
        mit["fortify"] = "no fortify" not in t
    return mit


# ------------------------------------------------------------------- build (Linux; runner injectable)
def build(target: str, *, runner: Optional[Callable] = None, now: str = "") -> ExploitContext:
    """Fingerprint the target once. `runner` runs checksec; defaults to safe_subprocess.run.
    Inject a fake runner in tests; on Linux the default shells out to `pwn checksec`."""
    ctx = ExploitContext(target=target, built_at=now)
    out = ""
    try:
        if runner is None:
            sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                            "..", "..", "coding-mastery", "scripts", "_lib"))
            import safe_subprocess
            res = safe_subprocess.run(["pwn", "checksec", "--file", target], allow_binaries=["pwn"])
            out = (res.stdout or "") + "\n" + (res.stderr or "")
        else:
            out = runner(target) or ""
    except Exception as exc:        # fingerprinting failed -> hardening UNDETERMINED, fail closed
        ctx.mitigations = {}
        ctx.undetermined = True
        ctx.libc = f"(checksec unavailable: {exc})"
        return ctx
    ctx.mitigations = parse_checksec(out)
    if not ctx.mitigations:         # parsed nothing -> can't claim "all clear"; fail closed
        ctx.undetermined = True
    return ctx


# ------------------------------------------------------------------- CLI
def main(argv=None) -> int:
    p = argparse.ArgumentParser(description="Cached exploit context + blocked-technique gate.")
    sub = p.add_subparsers(dest="cmd", required=True)
    b = sub.add_parser("build"); b.add_argument("--target", required=True); b.add_argument("--out", default="exploit-context.json")
    c = sub.add_parser("check"); c.add_argument("--context", required=True); c.add_argument("technique")
    s = sub.add_parser("show"); s.add_argument("--context", required=True)
    args = p.parse_args(argv)
    try:
        if args.cmd == "build":
            ctx = build(args.target)
            ctx.save(args.out)
            print(f"context for {args.target}: mitigations={ctx.mitigations} -> {args.out}")
            return 0
        if args.cmd == "check":
            ctx = ExploitContext.load(args.context)
            ok, why = ctx.assert_allowed(args.technique)
            print(("ALLOWED: " if ok else "BLOCKED: ") + why)
            return 0 if ok else 3
        if args.cmd == "show":
            print(json.dumps(ExploitContext.load(args.context).to_dict(), indent=2))
            return 0
    except (OSError, ValueError, TypeError, AttributeError, json.JSONDecodeError) as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 2
    return 2


if __name__ == "__main__":
    raise SystemExit(main())
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall