omp packages

@mauriciosec/pi-ctf1.1.6

Lightweight CTF framework for Pi with an async Python engine, native pwn MCP, category playbooks, evidence, subagents and goal loop.

mauriciosec Published 7 days ago MIT ~306 downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

pi-ctf: High-Velocity Jeopardy CTF Solving Framework for Pi

License: MIT Platform: Linux Agent: Pi NPM Version

A modular, high-velocity Jeopardy CTF framework developed for @earendil-works/pi-coding-agent.

The framework implements an Autonomous Solve First methodology: prioritizing deterministic triage, exploit generation, and flag capture over artificial reporting barriers, high-token ceremonies, or restrictive validation gates.


Architecture Overview

flowchart TD
    subgraph INTAKE["1. Challenge Ingestion"]
        Target["Challenge Artifacts / Remote Target"] --> TriageAuto["ctf-triage Skill / Mini-Tools"]
    end

    subgraph RUNTIME["2. Pi Extension Engine"]
        TriageAuto --> ExtEngine["Extensions Core"]
        ExtEngine --> FlagDet["flag-detector\n(Verified vs Candidate)"]
        ExtEngine --> Timer["solve-timer\n(Category Metrics)"]
        ExtEngine --> PromptInj["llm-identity-shield\nctf-instructions"]
        ExtEngine --> AntiStag["anti-stagnation\n(Progress Monitor)"]
        ExtEngine --> Checkpoint["handoff-saver\n(work/checkpoint.yaml)"]
        ExtEngine --> McpReg["pwn-mcp\n(Native Server Register)"]
    end

    subgraph PLAYBOOKS["3. Category Playbooks"]
        ExtEngine --> Skills["Dynamic Skill Tool"]
        Skills --> PwnSkill["ctf-pwn"]
        Skills --> RevSkill["ctf-rev"]
        Skills --> WebSkill["ctf-web"]
        Skills --> CryptoSkill["ctf-crypto"]
        Skills --> ForensicsSkill["ctf-forensics"]
        Skills --> MiscSkill["ctf-misc"]
    end

    subgraph EXEC["4. Tooling & Execution Core"]
        McpReg --> MCP["pwn-tools MCP Server\n(19 Native Tools)"]
        PwnSkill --> MCP
        RevSkill --> RevTools["Ghidra / angr / radare2"]
        WebSkill --> WebTools["ctf-web-triage / curl / Z3"]
        CryptoSkill --> CryptoTools["ctf-crypto-triage / SageMath"]
        ExtEngine --> SubAgents["pi-subagents / pi-goal\n(Orchestration & Loop)"]
    end

    subgraph RESOLUTION["5. Flag Capture & Verification"]
        MCP & RevTools & WebTools & CryptoTools --> Exploit["Exploit Execution"]
        Exploit --> FlagDet
        FlagDet --> Output["flags.txt / [VERIFIED] Alert / Stopped Timer"]
    end

Key Capabilities

  • Autonomous Solve First Workflow: Targets the flag immediately upon intake. Bypasses repetitive paperwork and reporting rituals to minimize token overhead and latency.
  • Strict Workspace Isolation: Fully contained project configurations ensure zero configuration bleed into Bug Bounty or external pentesting environments.
  • Native 19-Tool PWN MCP Server: Directly exposes a dedicated Model Context Protocol server featuring pwn_fast_sweep, pwn_intake_bundle, pwn_gdb_batch, pwn_gdb_snapshot, pwn_ropgadget, pwn_one_gadget, pwn_seccomp_dump, pwn_cyclic, and pwn_pwninit. Conforms strictly to MCP JSON-RPC protocol with content array payloads.
  • Instant Triage Mini-Tools: One-shot CLI scripts for PWN, Web, Crypto, and Reversing that determine architectures, binary protections, input vectors, offsets, and skeleton scripts in under 3 seconds.
  • Verified vs Candidate Flag Separation: Differentiates between candidate matches found in static text/fixtures and flags verified through dynamic runtime execution. Prevents premature solve celebrations.
  • Structured Challenge Checkpoints: Generates compact, high-density state checkpoints in work/checkpoint.yaml before context compactions to preserve active hypotheses and rejected paths without token bloat.
  • 7 Dense Category Playbooks: Battle-tested strategies covering Pwn, Reverse Engineering, Cryptography, Web Security, Forensics, Miscellaneous (jails, smart contracts), and Unified Triage.

Detailed Installation Guide

Prerequisites

Ensure the following runtimes and tools are installed on your Linux system:

  • Node.js: Version 22.19.0 or later (required by modern Pi agent runtime).
  • Python: Version 3.10 or later with pip.
  • Pi Coding Agent: @earendil-works/pi-coding-agent version 0.82.0 or later.
  • Git: Version 2.30 or later.

Optional binary analysis dependencies (recommended for PWN and Reverse Engineering tracks):

  • gdb with pwndbg or gef
  • ROPgadget
  • one_gadget
  • seccomp-tools
  • checksec
  • pwninit

Verify system readiness using the included dependency audit utility:

bash tools/scripts/check-deps.sh

Method 1: Install via Pi Package Manager (Recommended)

The package is published and maintained on the global npm registry under the @mauriciosec scope.

Global Installation

Installs the framework globally across your Pi agent runtime:

pi install @mauriciosec/pi-ctf
Project-Local Installation

To scope the suite exclusively to your current challenge directory without modifying global settings:

pi install -l @mauriciosec/pi-ctf

Method 2: Install Directly from GitHub

You can instruct Pi to fetch and link the package straight from the GitHub source repository:

pi install git:github.com/MauricioDuarte100/pi-CTF-package

Method 3: Standalone Workspace (Clone & Run)

For dedicated CTF machines, Docker containers, or isolated lab virtual machines:

  1. Clone the repository:

    git clone https://github.com/MauricioDuarte100/pi-CTF-package.git
    cd pi-CTF-package
    
  2. Install project dependencies:

    npm install
    
  3. Run automated verification tests:

    npm test
    
  4. Launch Pi Agent:

    pi
    

Pi loads the extension bundle through extensions/package.ts. When a project already has an extension with the same filename under .pi/extensions/, the bundle uses that project copy and skips the package copy, preventing duplicate tool registration. It also initializes the pwn-tools MCP server and ingests the behavioral constraints in AGENTS.md.

Pi CTF Engine (lightweight Python setup)

The engine does not use Docker or download tool images. Install the npm package through Pi, then configure Python once from Pi itself (requires uv in WSL2):

/ctf setup
# Optional ELF and PE dependencies (pwntools and pefile):
/ctf setup analysis
/ctf doctor

For subsequent package releases, use the normal update command:

pi update --extensions
pi

The extension starts the manager from the installed npm package. When its source changes, an idle manager is replaced automatically; active runs finish before replacement. For migration from older managers without update support, /ctf restart explicitly stops the owned manager and starts the installed version. This migration command interrupts active legacy runs, so finish those first. No development extension path or second Pi installation is required.

/ctf setup installs locked dependencies into ~/.local/share/pi-ctf-engine/venv, outside the npm package, and can be repeated after dependency updates. It never installs packages implicitly during triage. A shell installer remains available at tools/scripts/ctf-engine-install for development and troubleshooting; CTF_ENGINE_PYTHON can explicitly select an interpreter.

The registry invokes the existing Python scripts through bounded subprocesses and normalizes their JSON reports. It selects additional checks from recorded findings and shares reports between checks, so routes, sinks, and secrets do not trigger three source scans. Repeated identical requests share an active run; completed deterministic results reuse the validated cache.

Category Integrated scripts and checks
Web ctf-web-triage source framework/routes/sinks/secrets; ctf-jwt-tool for discovered tokens; native scoped HTTP and same-origin JavaScript observation
Pwn ctf-pwn-triage static ELF metadata, imports, protections and libc; ctf-pwn-sweep static signals and lifecycle hints; selected static gadgets
Crypto ctf-crypto-triage encoding chains and evidence-activated RSA attacks; repeated-block checks; ctf-crypto-xor for XOR evidence
Reverse ctf-rev-triage runtime, constants, validation strings/functions and directed static decompilation; ctf-pe-triage headers, sections, imports and TLS callbacks
Forensics ctf-pcap-triage in fast mode, ctf-evtx-triage in balanced mode and ctf-memory-triage in balanced mode (including .mem dumps; Volatility runs offline)
Machines Native exact-scope port/service observation, coordinated by the same scheduler

Missing optional dependencies mark their checks unavailable while compatible checks continue. ctf-engine doctor lists the installed capabilities. EVTX needs python-evtx in the engine interpreter, memory needs Volatility 3, and static decompilation needs radare2. The engine does not execute challenge binaries. It passes explicit static modes to Pwn scripts and disables automatic unpacking in Reverse. Gadget enumeration is selected explicitly after Pi maps data-only corruption; it is not enabled by a sink hint alone.

External Web scanners remain blocked even with remote_active permission: this build has no OS-level scoped network barrier for subprocesses. Remote observations use the engine's pinned-address HTTP/TCP implementations. The engine does not claim to restrict direct Pi commands or separately invoked MCP tools.

Open Pi from a separate directory for each challenge and use:

/ctf triage ./challenge.zip
/ctf status <run_id>
/ctf run ./challenge.zip deep
/ctf resume <run_id>
/ctf cancel <run_id>

The same operations are exposed as ctf_triage, ctf_run, ctf_status, ctf_evidence, and ctf_cancel. ctf_run defaults to balanced depth and executes registered category scripts; ctf_triage keeps fast recognition only. ctf_run accepts dry_run: true to inspect selected checks. The Python CLI supports ctf-engine doctor, init, plan, run, status, resume, and cancel.

For example, ctf_run with {"target":"./challenge", "depth":"deep", "dry_run":true} returns initial checks and potential follow-ups with their evidence triggers. To request a specific supported check, include "checks":["pwn.gadgets"] after completing the data-only map. The original files remain intact; legacy adapters use bounded, hash-checked copies under the run directory. Each script report and its stdout/stderr are retained as evidence, including timeout and cancellation logs.

ctf_run and /ctf run return a run_id before file classification and hashing finish. Use ctf_status or /ctf status to read progress. A run is completed when its selected checks finish successfully, partial when an optional check is blocked or unavailable, and failed when a check errors or times out. Individual check statuses remain visible in the result. Unrecognized input with no compatible checks fails explicitly rather than returning an empty successful analysis.

The extension checks the running manager’s source revision and package location before using its Unix socket. Package updates cannot silently reuse an older registry. Managers from a different installation are reported rather than stopped automatically.

Global concurrency defaults to four light checks, two network checks, and eight worker slots. Set CTF_ENGINE_LIGHT, CTF_ENGINE_NETWORK, and CTF_ENGINE_WORKERS before starting Pi to change them. Scripts declare their internal worker use. Progressive selection is bounded by CTF_ENGINE_MAX_EXPANSIONS (default 4) and CTF_ENGINE_MAX_CHECKS (default 64). Script adapters require Linux prlimit to enforce address-space, CPU-time and output-file limits; wall time, process-group cancellation and bounded pipe draining are handled by asyncio. These limits do not provide a filesystem or network sandbox.

Archive extraction is bounded to 1,000 files and 2 GiB of expanded data per request, with nested archive and free-disk checks. CTF_ENGINE_EXTRACT_BYTES adjusts the byte quota (maximum 8 GiB). Originals are preserved.

Each challenge directory contains manifest.json, state.sqlite, artifacts/, and runs/<run_id>/. For a remote host:port or URL, initialization records that exact host and port and pins its resolved addresses. Additional hosts or ports must be added to the manifest explicitly; observed network checks do not follow out-of-scope redirects. The engine supports offline_static and remote_observe for its integrated checks. It never submits flags and labels matches as candidates unless a configured proof supports verification.

When the challenge supplies a trusted SHA-256 digest of its flag, put it in manifest.json as expected_flag_sha256. The engine promotes a matching candidate to VERIFIED and records the digest and evidence references as its reproducible proof. Without a trusted validator, matches remain CANDIDATE even when they appear in a live response or a program output.

The check catalog covers six categories with bounded techniques. It does not generate new exploits or run a generic active network scanner; Pi handles new strategies. Ghidra, SageMath, pwntools, PE tooling, and other optional scripts can be invoked through their existing interfaces when installed separately.


Component Reference

1. Extensions Reference (extensions/)

Extension File Operational Role
flag-detector extensions/flag-detector.ts Intercepts standard and custom flag formats (flag{...}, CTF{...}) from tool output. Records candidates in flags.txt and verifies only when structured proof with evidence is available.
solve-timer extensions/solve-timer.ts Records challenge duration across categories (PWN, Web, Crypto, Rev, Forensics, Misc) and stops only when a verified flag is confirmed.
skill-tool extensions/skill-tool.ts Exposes a dynamic Skill(skill=...) invocation tool enabling the agent to load playbooks into context on demand.
anti-stagnation extensions/anti-stagnation.ts Unified monitor that recognizes legitimate deep work (GDB, symbolic execution, lattice reduction) and only suggests hypothesis re-evaluation after 5 identical consecutive failures without new observations.
handoff-saver extensions/handoff-saver.ts Serializes challenge state to work/checkpoint.yaml before context compactions and injects active hypotheses, proven signals, rejected paths, and artifacts directly into the LLM system prompt via before_agent_start.
scope-gate extensions/scope-gate.ts Enforces authorization boundaries while automatically exempting specified CTF challenge targets.
llm-identity-shield extensions/llm-identity-shield.ts Sanitizes target server responses to neutralize prompt injections and identity extraction probes in AI/LLM challenges.
ctf-instructions extensions/ctf-instructions.ts Injects core CTF guidelines and Pwn Invariant directly into Pi's system prompt so guidelines apply anywhere the package is installed.
pwn-mcp extensions/pwn-mcp.ts Dynamically registers pwn-tools MCP server with deferred exposure by default and direct exposure for fast triage tools (pwn_fast_sweep, pwn_intake_bundle, pwn_checksec) to minimize LLM context bloat.
pi-goal extensions/pi-goal.ts Bridges pi-goal-x to provide structured task trees and an autonomous goal loop (/goal and zero-bureaucracy /goal-direct) with startup diagnostics.
pi-subagents extensions/pi-subagents.ts Integrates @henryqw/pi-subagent for parallel exploration, bounded reconnaissance tasks, and subagent delegation with startup diagnostics.
teamw4llz-banner extensions/teamw4llz-banner.ts Prints the static TeamW4LLZ ANSI banner (assets/teamw4llz-banner.ansi) on interactive startup and via /w4llz.

2. Category Skills Reference (skills/)

  • ctf-triage: Auto-detects challenge format and dispatches appropriate category workflows.
  • ctf-pwn: Exploitation for Linux userland/kernel. Stack overflows, ret2libc, ROP/SROP, format strings, glibc heap (tcache, fastbin, unsorted, largebin, house of force/einherjar), and seccomp bypasses. Enforces the Pwn Invariant (data-only corruption mapping before control flow).
  • ctf-rev: Decompilation and binary disassembly. Covers Ghidra, radare2, angr symbolic execution, .NET/Java/Python/WASM bytecode analysis, and custom VM architectures.
  • ctf-web: Web exploitation techniques including SQLi, NoSQLi, SSTI, SSRF, IDOR, prototype pollution, JWT vulnerabilities, deserialization, race conditions, and GraphQL introspection.
  • ctf-crypto: Cryptanalysis covering RSA (Wiener, Hastad, Boneh-Durfee, ROCA), AES (ECB, CBC padding oracle, GCM), ECC (Smart, Pohlig-Hellman), LLL lattice reductions, PRNG state recovery, and Z3 constraint solving.
  • ctf-forensics: Memory extraction (Volatility 3), network packet analysis (tshark, Wireshark), filesystem carving, EVTX event log hunting, and steganography.
  • ctf-misc: Python sandbox/jail escapes, restricted bash (rbash), esoteric programming languages, Ethereum smart contract audits, and prompt injection challenges.

3. Model Context Protocol (MCP) Server (mcp/)

The Python-based server (mcp/pwn-tools-mcp.py) operates over standard I/O (stdio) and delivers 19 binary analysis functions formatted according to the official MCP specification:

{
  "mcpServers": {
    "pwn-tools": {
      "command": "python3",
      "args": ["mcp/run.py"]
    }
  }
}
Exposed MCP Tools
  • pwn_fast_sweep: Rapid assessment of binary architecture, protections, and symbols (bounded default timeout: 25s, max 35s).
  • pwn_intake_bundle: Deep ELF analysis covering hardening, imported functions, and vulnerabilities.
  • pwn_checksec: Mitigations check (Canary, NX, PIE, RELRO, FORTIFY).
  • pwn_file_info: Metadata including file format, dynamic linker, and strip state.
  • pwn_protocol_trace: Executes target binaries under controlled stdin/stdout conditions.
  • pwn_gdb_batch: Executes scriptable batch commands inside GDB.
  • pwn_gdb_snapshot: Inspects register state, stack frames, and backtraces at explicit addresses.
  • pwn_ropgadget: Automated ROP gadget search via ROPgadget.
  • pwn_one_gadget: libc one-gadget finder via one_gadget.
  • pwn_cyclic & pwn_cyclic_find: De Bruijn pattern generation and crash offset calculation.
  • pwn_seccomp_dump: Syscall filter inspection via seccomp-tools.
  • pwn_pwninit: Automatic binary patching with custom libc and linker via pwninit.
  • pwn_qemu_run: Foreign architecture execution under user-mode QEMU.

4. Diagnostic Utilities (tools/scripts/)

One-shot diagnostic scripts optimized for turn-1 execution:

# PWN: Checksec, sinks, gadgets, cyclic crash offset & pwntools skeleton
python3 tools/scripts/ctf-pwn-triage ./vuln [--remote host:port]

# WEB: Headers, cookies, API routes, JWTs, SSTI/SQLi probes & local sinks
python3 tools/scripts/ctf-web-triage https://target.ctf.site

# CRYPTO: Multi-layer decoders, RSA parameter extraction & canonical attacks
python3 tools/scripts/ctf-crypto-triage ./challenge.py

# REVERSING: Compiler, packers (auto UPX unpack), crypto constants & pseudo-C
python3 tools/scripts/ctf-rev-triage ./binary [--func main]

5. Built-in Terminal Themes (themes/)

The framework packages two custom terminal UI themes developed by TeamW4LLZ, declared directly in package.json under Pi's theme registry:

  • teamw4llz-hacker: Phosphor terminal green palette (#00ff41), deep void background (#03080a), high-contrast syntax highlighting, and amber accent markers.
  • teamw4llz-ice: Cyber ice-blue palette (#9adcff), navy night background (#06070f), sky-blue prompts, and mint bash status accents.

To activate a theme within Pi interactive mode:

/theme teamw4llz-hacker

or

/theme teamw4llz-ice

Directory Structure

pi-CTF-package/
├── extensions/                  # 11 TypeScript agent runtime extensions
│   ├── anti-stagnation.ts       # Unified technical progress monitor
│   ├── ctf-instructions.ts     # Core solve-first prompt injector
│   ├── ctf-lib.ts               # Shared utility library
│   ├── flag-detector.ts         # Verified vs candidate flag interceptor
│   ├── handoff-saver.ts         # Challenge checkpoint serializer & prompt restorer
│   ├── llm-identity-shield.ts   # Prompt injection neutralizer
│   ├── pi-goal.ts               # Autonomous goal loop extension
│   ├── pi-subagents.ts          # Subagent task orchestrator
│   ├── pwn-mcp.ts               # Native Pi MCP registration
│   ├── scope-gate.ts            # Target validation gate
│   ├── skill-tool.ts            # Dynamic Skill() execution tool
│   └── solve-timer.ts           # Stopwatch for verified solve durations
├── mcp/
│   ├── pwn-tools-mcp.py         # 19-tool Python MCP server (MCP JSON-RPC compliant)
│   ├── README.md                # MCP technical specification
│   └── run.py                   # MCP process bootstrap
├── skills/
│   ├── ctf-crypto/SKILL.md      # Cryptanalysis playbook
│   ├── ctf-forensics/SKILL.md   # Memory, disk, network, stego playbook
│   ├── ctf-misc/SKILL.md        # Sandboxes, rbash, smart contracts
│   ├── ctf-pwn/SKILL.md         # Stack, heap, ROP, seccomp playbook
│   ├── ctf-rev/SKILL.md         # Reverse engineering playbook
│   ├── ctf-triage/SKILL.md      # Triage & dispatch playbook
│   └── ctf-web/SKILL.md         # Web exploitation playbook
├── themes/                      # TeamW4LLZ terminal UI themes
│   ├── teamw4llz-hacker.json    # Phosphor green hacker palette
│   └── teamw4llz-ice.json       # Cyan ice cyber palette
├── tools/
│   ├── lib/ctfkit/              # Python support library
│   └── scripts/                 # One-shot triage mini-tools & test suite
├── .mcp.json                    # MCP configuration
├── AGENTS.md                    # Agent behavioral guidance & Pwn Invariant
├── LICENSE                      # MIT License
├── README.md                    # System documentation
└── package.json                 # Package manifest & extension registry

Testing & Quality Assurance

Run the automated test suite to verify Python syntax, Bash syntax, MCP JSON-RPC compliance, and package manifest integrity:

npm test

Maintainers can additionally verify a real npm installation in a disposable consumer directory, including /ctf setup, script execution, evidence retrieval and the complete Pi extension bundle:

python3 tools/scripts/test-package-install.py

The package installation test uses cached dependencies by default. Use --allow-downloads to explicitly permit missing dependency downloads, --previous PATH.tgz to exercise an update between prepared compatible releases, or --pi-cli /absolute/path/to/pi to test a particular installed CLI. It leaves logs in the printed temporary directory and does not alter your normal Pi/npm installation.


License

This project is licensed under the MIT License.