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/feasibility_profile.py

View on GitHub
#!/usr/bin/env python3
"""feasibility_profile.py - empirical mitigation matrix for a confirmed memory-corruption bug.

Static reasoning ("NX is on, so no shellcode") is weaker than rebuilding the crash witness under
several mitigation profiles and recording which still fire. This produces an `empirical_mitigation_map`
(raptor idea J) that `exploit_context.py` consumes so /exploit is FORBIDDEN from using a technique the
target actually blocks. It is the most defensible part of the crash->exploitability pipeline.

The build+replay step needs a Linux toolchain (gcc/clang) and runs in the devcontainer; it is exposed
through an injectable `runner` so the matrix orchestration and the blocked-technique derivation are
pure stdlib and testable without compiling anything. The blocked-technique map is reused from
exploit_context.TECHNIQUE_BLOCKS (single source of truth).

CLI:
  feasibility_profile.py run --build 'gcc {cflags} -o w witness.c' --witness './w poc' \
       [--context exploit-context.json]      # Linux: builds under each profile, writes the map
  feasibility_profile.py map --results results.json [--context exploit-context.json]   # offline
"""
from __future__ import annotations

import argparse
import json
import os
import sys
from typing import Callable, Optional

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import exploit_context as ec  # noqa: E402

# Each profile: a CFLAGS set and the mitigations it turns ON. permissive < distro < hardened.
PROFILES = [
    {"name": "permissive",
     "cflags": "-O0 -g -fno-stack-protector -z execstack -no-pie -Wl,-z,norelro",
     "mitigations": {"nx": False, "canary": False, "pie": False, "full_relro": False, "fortify": False}},
    {"name": "distro",
     "cflags": "-O2 -g -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fPIE -pie -Wl,-z,relro",
     "mitigations": {"nx": True, "canary": True, "pie": True, "partial_relro": True, "fortify": True}},
    {"name": "hardened",
     "cflags": "-O2 -g -D_FORTIFY_SOURCE=3 -fstack-protector-all -fPIE -pie "
               "-Wl,-z,relro,-z,now -fcf-protection=full",
     "mitigations": {"nx": True, "canary": True, "pie": True, "full_relro": True, "fortify": True, "cet": True}},
    {"name": "asan",
     "cflags": "-O1 -g -fsanitize=address -fno-omit-frame-pointer",
     "mitigations": {"asan": True}},
]
_STRICTNESS = {"permissive": 0, "distro": 1, "hardened": 2}
_PROFILE_BY_NAME = {p["name"]: p for p in PROFILES}


def blocked_from_mitigations(mitigations: dict) -> set:
    blocked = set()
    for mit, techs in ec.TECHNIQUE_BLOCKS.items():
        if mitigations.get(mit) is True:
            blocked |= techs
    return blocked


def to_map(results: list) -> dict:
    """Turn per-profile {name, fires} results into an empirical_mitigation_map. The realistic
    exploitation context is the STRICTEST standard profile under which the bug still fires; the
    techniques that profile's mitigations block are off-limits.

    Fail-SAFE (block more, never fewer):
      - fires=None (build/run failed) is NOT the same as fires=False (proven not to fire). A stricter
        profile that was never proven safe MIGHT still apply, so its mitigations are folded in.
      - duplicate-named records aggregate toward 'fired' (any True wins) so a stricter firing record
        is never overwritten by a later False.
      - non-dict / non-string-named records are skipped (no crash)."""
    seen = {}
    for r in results:
        if not isinstance(r, dict):
            continue
        name = r.get("name")
        if not isinstance(name, str):       # skip unhashable/garbage names (no TypeError)
            continue
        s = seen.setdefault(name, {"true": False, "false": False, "none": False, "note": ""})
        f = r.get("fires")
        if f is True:
            s["true"] = True
        elif f is False:
            s["false"] = True
        else:
            s["none"] = True
        if r.get("note"):
            s["note"] = r["note"]
    agg = {n: (True if s["true"] else (False if s["false"] else None)) for n, s in seen.items()}

    fires_under = [n for n, f in agg.items() if f is True]
    std_firing = [n for n in fires_under if n in _STRICTNESS]
    unproven_std = [n for n in agg if n in _STRICTNESS and agg[n] is None]
    proven_false = [_STRICTNESS[n] for n in agg if n in _STRICTNESS and agg[n] is False]

    def _fold(base_mits, base_strict):
        # Fold a stricter-but-unproven profile's mitigations ONLY if no PROVEN-False profile sits
        # between the base and it: a proven-False intermediate means the bug already dies under that
        # (weaker) mitigation set, so a stricter profile can't newly fire -> folding it over-blocks.
        mits = dict(base_mits)
        for n in unproven_std:
            ns = _STRICTNESS[n]
            if ns <= base_strict:
                continue
            if any(base_strict < pf <= ns for pf in proven_false):
                continue
            mits.update({k: True for k, v in _PROFILE_BY_NAME[n]["mitigations"].items() if v})
        return mits

    if std_firing:
        target = max(std_firing, key=lambda n: _STRICTNESS[n])
        mits = _fold(_PROFILE_BY_NAME[target]["mitigations"], _STRICTNESS[target])
    else:
        target = "distro"                    # bug reproduced under no standard profile -> conservative
        mits = _fold(_PROFILE_BY_NAME["distro"]["mitigations"], _STRICTNESS["distro"])

    return {
        "profiles": [{"name": n, "fires": agg[n], "note": seen[n]["note"]} for n in agg],
        "fires_under": fires_under,
        "target_profile": target,
        "blocked_techniques": sorted(blocked_from_mitigations(mits)),
        "asan_caught": agg.get("asan") is True,
    }


def run_matrix(build_template: str, witness: str, *, runner: Optional[Callable] = None) -> list:
    """Build + replay the witness under each profile. `runner(profile)->{fires,note}` is injectable;
    the default compiles with the profile's cflags and runs the witness via safe_subprocess (Linux)."""
    results = []
    for prof in PROFILES:
        if runner is not None:
            r = runner(prof)
            results.append({"name": prof["name"], "fires": r.get("fires"),
                            "note": r.get("note", ""), "mitigations": prof["mitigations"]})
            continue
        results.append(_default_run(prof, build_template, witness))
    return results


def _default_run(prof: dict, build_template: str, witness: str) -> dict:
    """Linux build+replay via safe_subprocess. fires=True if the witness crashes (signal / asan)."""
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                        "..", "..", "coding-mastery", "scripts", "_lib"))
        import safe_subprocess
        build_cmd = build_template.replace("{cflags}", prof["cflags"])
        b = safe_subprocess.run(["sh", "-c", build_cmd], allow_binaries=["sh"], timeout=120)
        if not b.ok:
            return {"name": prof["name"], "fires": None, "note": f"build failed: {b.stderr[:200]}",
                    "mitigations": prof["mitigations"]}
        r = safe_subprocess.run(["sh", "-c", witness], allow_binaries=["sh"], timeout=60)
        crashed = (r.returncode is not None and r.returncode < 0) or \
                  ("AddressSanitizer" in r.stderr) or ("runtime error" in r.stderr)
        return {"name": prof["name"], "fires": bool(crashed),
                "note": f"rc={r.returncode}", "mitigations": prof["mitigations"]}
    except Exception as exc:
        return {"name": prof["name"], "fires": None, "note": f"error: {exc}",
                "mitigations": prof["mitigations"]}


def merge_into_context(context_path: str, emap: dict) -> None:
    ctx = ec.ExploitContext.load(context_path) if os.path.isfile(context_path) else ec.ExploitContext()
    ctx.empirical_mitigation_map = emap
    ctx.save(context_path)


def main(argv=None) -> int:
    p = argparse.ArgumentParser(description="Empirical mitigation matrix for a memory-corruption bug.")
    sub = p.add_subparsers(dest="cmd", required=True)
    r = sub.add_parser("run")
    r.add_argument("--build", required=True, help="build template with a {cflags} placeholder")
    r.add_argument("--witness", required=True, help="command that triggers the crash")
    r.add_argument("--context", help="merge the map into this exploit-context.json")
    r.add_argument("--out", help="also write the raw map JSON here")
    m = sub.add_parser("map")
    m.add_argument("--results", required=True, help="per-profile results JSON list")
    m.add_argument("--context")
    m.add_argument("--out")
    args = p.parse_args(argv)
    try:
        if args.cmd == "run":
            results = run_matrix(args.build, args.witness)
        else:
            with open(args.results, "r", encoding="utf-8") as fh:
                results = json.load(fh)
            if not isinstance(results, list):
                raise ValueError("results must be a JSON list")
        emap = to_map(results)
        if args.context:
            merge_into_context(args.context, emap)
        if args.out:
            with open(args.out, "w", encoding="utf-8") as fh:
                json.dump(emap, fh, indent=2)
        print(json.dumps(emap, indent=2))
        return 0
    except (OSError, ValueError, TypeError, json.JSONDecodeError) as exc:
        print(f"error: {exc}", file=sys.stderr)
        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