Skip to content

hypnguyen1209/offensive-claude / skills/vulnerability-analysis

vulnerability-analysis

Unverified

Use when auditing source code for vulnerabilities — drive CodeQL/Semgrep/Joern to taint untrusted data source-to-sink across injection, memory safety, deserialization/prototype-pollution, secrets/crypto/authz/race, and supply-chain risks

scripts/path_conditions.py

View on GitHub
#!/usr/bin/env python3
"""path_conditions.py - turn a path's branch guards into solver-checkable predicates.

A taint trace tells you a sink is *reachable on paper*; it does not tell you whether the branch
conditions on that path can all be satisfied at once. This tool extracts the comparisons / null
checks crossed on a path into a normalized predicate set, optionally feeds them to Z3, and reports
feasibility as a TRI-STATE:

  feasible = true   - Z3 found a satisfying assignment over the COMPLETE parseable predicate set
                      (model = a concrete trigger input).
  feasible = false  - Z3 proved the predicates UNSAT. Sound even on a subset: if a subset of the
                      constraints already contradicts, the full path can't be taken. Prunes a
                      false-positive path mechanically.
  feasible = null   - UNKNOWN -> fall through to MANUAL analysis. This is the default whenever the
                      tool cannot be sure: no Z3 installed, nothing parseable, or SAT over a subset
                      that had to drop unparseable predicates (calls/casts/derefs/bitmask). A
                      solver/parse limit is ALWAYS null, NEVER false.

This is ADVISORY. It models variables as mathematical integers, so it does NOT model fixed-width
wraparound: an `uint32` overflow guard (`a + b < a`) may be UNSAT over Z3 Ints yet reachable on a
32-bit target. Treat a `false` over arithmetic that could wrap as `null` and confirm by hand. The
`path_profile` records the dominant width seen so a reviewer can spot this.

Pure stdlib for extraction; Z3 (`pip install z3-solver`) is optional and only ever upgrades null.

Input (JSON): a list of guards, or {"guards":[...]} / {"path_conditions":[...]}. Each guard:
  {"expr": "idx < size", "step_index": 3, "negated": false}   # negated => the FALSE branch was taken

CLI:
  path_conditions.py --trace path.json [--width 64] [--no-z3] [--json]
  exit 0 = feasible true/null (path not refuted), 1 = feasible false (path pruned), 2 = error
"""
from __future__ import annotations

import argparse
import json
import re
import sys

_CMP = ["==", "!=", "<=", ">=", "<", ">"]
_IDENT = re.compile(r"^[A-Za-z_]\w*$")
_INT = re.compile(r"^(?:0[xX][0-9a-fA-F]+|\d+)$")
_COMPLEX = re.compile(r"[()\[\]{}*]|->|\.|/|%|\+|&&|\|\||\bcall\b")
_CONSTS = {"null": 0, "nullptr": 0, "none": 0, "true": 1, "false": 0}
_WIDTHS = ["uint8", "int8", "uint16", "int16", "uint32", "int32", "uint64", "int64", "size_t"]


def _operand(tok: str):
    """Return ('var', name) | ('int', value) | None (unparseable)."""
    t = tok.strip()
    low = t.lower()
    if low in _CONSTS:
        return ("int", _CONSTS[low])
    if _INT.match(t):
        try:
            return ("int", int(t, 0))
        except ValueError:
            # e.g. C octal-style "0755": int(t,0) rejects it. Parse as octal if it fits, else
            # treat as unparseable (dropped) - a malformed literal must never abort the whole path.
            if re.fullmatch(r"0[0-7]+", t):
                try:
                    return ("int", int(t, 8))
                except ValueError:
                    return None
            return None
    if _IDENT.match(t):
        return ("var", t)
    return None


def parse_guard(expr: str):
    """Normalize one guard into a predicate dict. parseable=False for anything Z3 can't take here
    (calls, casts, dereferences, arithmetic, bitmask) - those are excluded, not guessed."""
    raw = (expr or "").strip()
    e = raw
    while e.startswith("(") and e.endswith(")"):
        e = e[1:-1].strip()
    pred = {"raw": raw, "parseable": False, "op": None, "lhs": None, "rhs": None,
            "reason": ""}
    # bare null/bool checks: !x  /  x
    if e.startswith("!"):
        inner = _operand(e[1:])
        if inner and inner[0] == "var":
            pred.update(parseable=True, op="==", lhs=inner, rhs=("int", 0))
            return pred
        pred["reason"] = "negation of a non-variable"
        return pred
    # bitmask used as boolean is intentionally NOT modeled over Ints (would be unsound)
    if "&" in e or "|" in e or "^" in e or "<<" in e or ">>" in e:
        pred["reason"] = "bitwise expression - excluded (would be unsound over integers)"
        return pred
    for op in _CMP:                       # longest ops first (<=, >=, ==, != before <, >)
        idx = e.find(op)
        if idx != -1:
            lhs_s, rhs_s = e[:idx], e[idx + len(op):]
            if _COMPLEX.search(lhs_s) or _COMPLEX.search(rhs_s):
                pred["reason"] = "operand is a call/cast/deref/arithmetic expression"
                return pred
            lhs, rhs = _operand(lhs_s), _operand(rhs_s)
            if lhs and rhs and not (lhs[0] == "int" and rhs[0] == "int"):
                pred.update(parseable=True, op=op, lhs=lhs, rhs=rhs)
                return pred
            pred["reason"] = "operand not a simple variable/integer"
            return pred
    # bare truthiness: a lone variable
    bare = _operand(e)
    if bare and bare[0] == "var":
        pred.update(parseable=True, op="!=", lhs=bare, rhs=("int", 0))
        return pred
    pred["reason"] = "no recognized comparison/null/truthiness form"
    return pred


def _load_guards(trace) -> list:
    if isinstance(trace, dict):
        trace = trace.get("guards", trace.get("path_conditions", []))
    if not isinstance(trace, list):
        raise ValueError("trace must be a list of guards (or {guards:[...]})")
    out = []
    for i, g in enumerate(trace):
        if isinstance(g, str):
            out.append({"expr": g, "step_index": i, "negated": False})
        elif isinstance(g, dict):
            out.append({"expr": str(g.get("expr", "")), "step_index": g.get("step_index", i),
                        "negated": bool(g.get("negated", False))})
        else:
            raise ValueError(f"guard #{i} must be a string or object")
    return out


def _path_profile(guards) -> str:
    blob = " ".join(g["expr"] for g in guards).lower()
    # longest token first so 'uint32' wins over its substring 'int32'
    for w in sorted(_WIDTHS, key=len, reverse=True):
        if w in blob:
            return w
    return "unknown"


def _solve(preds, *, use_z3: bool):
    """Return (feasible, model, note). feasible in {True, False, None}."""
    parseable = [p for p in preds if p["parseable"]]
    dropped = len(preds) - len(parseable)
    if not use_z3:
        return None, None, "z3 disabled - feasibility is manual (null)"
    try:
        import z3
    except Exception:
        return None, None, "z3 not installed (pip install z3-solver) - feasibility is manual (null)"
    if not parseable:
        return None, None, "no parseable predicates - feasibility is manual (null)"
    s = z3.Solver()
    varz: dict = {}

    def term(operand):
        kind, val = operand
        if kind == "int":
            return z3.IntVal(val)
        if val not in varz:
            varz[val] = z3.Int(val)
        return varz[val]

    ops = {"==": lambda a, b: a == b, "!=": lambda a, b: a != b,
           "<": lambda a, b: a < b, "<=": lambda a, b: a <= b,
           ">": lambda a, b: a > b, ">=": lambda a, b: a >= b}
    for p in parseable:
        c = ops[p["op"]](term(p["lhs"]), term(p["rhs"]))
        if p.get("negated"):
            c = z3.Not(c)
        s.add(c)
    res = s.check()
    if res == z3.unsat:
        # sound even with dropped predicates: a contradictory subset stays contradictory
        return False, None, f"UNSAT over {len(parseable)} predicate(s) - path pruned" + \
               (f" ({dropped} unparseable excluded)" if dropped else "")
    if res == z3.sat:
        if dropped:
            return None, None, (f"SAT over {len(parseable)} predicate(s) but {dropped} were "
                                "unparseable and excluded - cannot confirm full path (manual)")
        m = s.model()
        model = {str(d): m[d].as_long() if hasattr(m[d], "as_long") else str(m[d]) for d in m.decls()}
        return True, model, f"SAT over all {len(parseable)} predicate(s) - concrete model found"
    return None, None, f"z3 returned {res} - feasibility is manual (null)"


def analyze(trace, *, use_z3: bool = True, width: int = 64) -> dict:
    guards = _load_guards(trace)
    preds = []
    for g in guards:
        p = parse_guard(g["expr"])
        p["step_index"] = g["step_index"]
        p["negated"] = g["negated"]
        preds.append(p)
    feasible, model, note = _solve(preds, use_z3=use_z3)
    return {
        "feasible": feasible,           # True | False | None  (None => manual)
        "model": model,
        "solver": "z3" if (use_z3 and model is not None) else ("z3" if (use_z3 and feasible is False) else None),
        "path_profile": _path_profile(guards),
        "width_assumed": width,
        "note": note,
        "wraparound_caveat": "integers modeled as unbounded; a 'false' over wrapping arithmetic may "
                             "still be reachable on a fixed-width target - confirm by hand",
        "path_conditions": [{"raw": p["raw"], "parseable": p["parseable"], "op": p["op"],
                             "step_index": p["step_index"], "negated": p["negated"],
                             "reason": p["reason"]} for p in preds],
        "parseable_count": sum(1 for p in preds if p["parseable"]),
        "dropped_count": sum(1 for p in preds if not p["parseable"]),
    }


def main(argv=None):
    ap = argparse.ArgumentParser(description="Extract path branch guards -> tri-state feasibility (Z3 optional).")
    ap.add_argument("--trace", required=True, help="JSON guards file")
    ap.add_argument("--width", type=int, default=64)
    ap.add_argument("--no-z3", action="store_true", help="force feasibility=null (no solver)")
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args(argv)
    try:
        with open(args.trace, "r", encoding="utf-8") as fh:
            trace = json.load(fh)
    except (OSError, ValueError, json.JSONDecodeError) as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 2
    try:
        out = analyze(trace, use_z3=not args.no_z3, width=args.width)
    except ValueError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 2
    if args.json:
        print(json.dumps(out, indent=2))
    else:
        fmap = {True: "FEASIBLE(true)", False: "INFEASIBLE(false=path pruned)", None: "UNKNOWN(null=manual)"}
        print(f"feasible: {fmap[out['feasible']]}")
        print(f"profile: {out['path_profile']}  parseable: {out['parseable_count']}  dropped: {out['dropped_count']}")
        print(f"note: {out['note']}")
        if out["model"]:
            print(f"model: {out['model']}")
    return 1 if out["feasible"] is False else 0


if __name__ == "__main__":
    raise SystemExit(main())
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall