GreyDGL/PentestGPT
Supervisor/Executor pentest loop over Claude Code or Codex, with SQLite state and verbatim, receipt-checked evidence.
Overview
PentestGPT is the research project behind the USENIX Security 2024 paper. At this commit the repository holds two separate programs. pentestgpt_agent/ is the maintained autonomous framework: a small, deterministic loop that drives Claude Code or Codex through an assessment of one or more explicitly allowed targets. pentestgpt_legacy/ is the modernized version of the original paper tool: an interactive, human-driven assistant. It runs three LLM sessions (reasoning, generation, parsing) over a pentesting task tree, and the operator pastes tool output back in.
The autonomous framework is notable for what it leaves out. It has no tool catalog, no RAG, no parallel scheduler and no “judge” model. Two LLM roles do the work. The Supervisor picks or proposes one typed task. The Executor performs that one task. Plain Python code owns everything else: scope checks, dependencies, leases, retries, evidence provenance and state transitions. The models get full shell and filesystem access through the provider CLI. PentestGPT treats the surrounding container or VM as the only isolation boundary.
The most distinctive idea is evidence grounding. An Executor result counts as done only if its quoted evidence is an exact, contiguous slice of a command or tool output that the runtime itself captured. Paraphrased, truncated or unmatched evidence is downgraded to progress, so it can never complete a task.
Architecture
flowchart LR
CLI["pentestgpt-agent CLI"] --> TRIAL["run_trial"]
TRIAL --> LOOP["PentestLoop"]
LOOP --> SUP["Supervisor episode"]
SUP --> PLAN["compile_plan (scope, deps)"]
PLAN --> MEM["MemoryKernel (SQLite)"]
LOOP --> EXE["Executor episode"]
EXE --> RUN["EpisodeRunner"]
RUN --> UA["unified-agent: Claude Code / Codex"]
RUN --> TR["TraceStore (events.jsonl)"]
TR --> EXEC["compile_execution (evidence)"]
EXEC --> MEM
MEM --> AUD["audit_run"]
| Component | Path | Role |
|---|---|---|
| Trial entry point | pentestgpt_agent/src/pentestgpt_agent/trial.py |
CLI args, config validation, role construction, resume identity, run summary |
| Loop | pentestgpt_agent/src/pentestgpt_agent/loop.py |
One Supervisor decision, then one leased task, until finish, failure or decision cap |
| Roles and contracts | pentestgpt_agent/src/pentestgpt_agent/agents.py |
Supervisor/Executor instructions, JSON schemas, per-kind turn budgets, state projection |
| Plan compiler | pentestgpt_agent/src/pentestgpt_agent/plan.py |
Task kinds, scope check, dependency/cycle checks, finish preconditions |
| Execution compiler | pentestgpt_agent/src/pentestgpt_agent/execution.py |
Matches the quoted evidence against captured receipts; degrades done to progress |
| Memory kernel | pentestgpt_agent/src/pentestgpt_agent/memory.py |
SQLite runs, tasks, attempts, observations, transitions |
| Traces | pentestgpt_agent/src/pentestgpt_agent/trace.py |
Per-episode input.json, events.jsonl, output.json; receipt classification |
| Auditor | pentestgpt_agent/src/pentestgpt_agent/audit.py |
After-the-fact consistency check of a run directory |
| Legacy client | pentestgpt_legacy/ |
Interactive three-session assistant with a multi-provider model registry |
How a request flows
Take pentestgpt-agent --goal "..." --target http://10.0.0.5:8080:
- Validate and build.
run_trialrefuses an empty target list, checks backend (claudeorcodex), effort and the decision and turn limits. It then writes atrial-config.jsonidentity, or compares against it on--resume(trial.py)._build_rolescreates both roles onUnifiedAgentwithSandboxPolicy.FULL_ACCESS(trial.py). - Open the run.
PentestLoop.runopens or resumes the SQLite run, recovers an active lease if one exists, and enforcesmax_decisions(default 20) (loop.py). - Plan.
_supervisor_planstarts a fresh Supervisor episode. If an earlier episode for the same revision exists on disk, it reuses that recorded output instead of calling the model again. Either way the decision goes throughcompile_plan, and on rejection the error is fed back for one retry (loop.py). - Compile the plan.
compile_planrejects stale revisions, more than one new task, out-of-scope targets, unknown basis IDs, missing dependencies and cycles. It also rejects anEXPLOITtask without a completedTESTon the same target, and afinishwhile work is still open (plan.py). - Lease.
MemoryKernel.commit_planruns in aBEGIN IMMEDIATEtransaction. It inserts the task, marks it ready or blocked, creates an attempt and advances the revision (memory.py). - Execute.
_drive_leaseruns the Executor with the task, its basis observations and a turn budget for its kind.EpisodeRunner.runstreams every provider event into the trace journal (loop.py, trace.py). - Ground and commit.
compile_executionchecks that the trace belongs to this run, task, attempt and revision. It then resolves the quoted evidence against captured receipts and decides the final outcome (execution.py). Failures go through_settle_trace. An attempt is retried only if it was a no-action failure, meaning no command, file change or tool call was recorded (loop.py). - Finish. The loop repeats until the Supervisor finishes, citing observations from completed tasks, or a limit is hit.
run_trialwritessummary.jsonwith tasks, observations, transitions, token usage and the provider-reported cost.
Key components
Task kinds as a control surface
Tasks are one of DISCOVER, ENUMERATE, TEST, EXPLOIT, VERIFY or RECOVER. Each kind has its own Executor turn budget, from 4 for VERIFY to 9 for EXPLOIT (agents.py). The kind is checked in code as well as in the prompt. An EXPLOIT must cite the newest completed TEST observation on the exact same target string. A TEST task whose text contains exploitation phrases is rejected (plan.py). This is an escalation ladder enforced by state, not just by instructions.
Scope check
_target_is_allowed accepts a task target that either equals an allowed non-URL target exactly, or is a URL with the same scheme, host and port whose path starts with an allowed URL’s path. It canonicalizes and rejects encoded or traversal path segments (plan.py). The check applies to the task’s target field. It does not limit which hosts the Executor’s shell actually contacts. The Supervisor prompt asks the model to stay in bounds (agents.py), but no network-level allowlist backs it up.
Evidence grounding
Only some trace events count as receipts. A command_run with an integer exit code is eligible, including non-zero exits, because negative results are valid evidence. A non-error tool_result is eligible too. The StructuredOutput call is not (trace.py). When the quote matches no receipt, compile_execution falls back to the last eligible receipt but commits only progress. A quote cut to the 4,000-character suffix, or one that cannot be resolved, also downgrades done to progress. With no eligible receipt at all, the result is rejected. The project calls these records “observations”. CONTEXT.md states plainly that structured findings, meaning severity-rated claims built on an evidence chain, are not implemented yet (CONTEXT.md).
Memory kernel and traces
MemoryKernel creates five SQLite tables: runs, transitions, attempts, observations and tasks (memory.py). Every revision has exactly one transition row. Episodes always start fresh (resume = None), so provider conversation history is never memory. Each role sees a bounded projection of SQLite state instead. Traces are diagnostic only, and they contain raw target output. failure_detail also recognizes Claude’s own safety refusals and records them as a separate provider_safety_block failure (trace.py).
Legacy interactive client
PentestGPT.__init__ builds three LLMClients, by default Claude Opus for reasoning and generation and Claude Haiku for parsing, from a curated registry. That registry covers OpenAI, Anthropic, Gemini, DeepSeek, xAI, Qwen, Moonshot and local Ollama (pentest_gpt.py). The client executes nothing itself. The human runs the tools and pastes the results in.
Extending it
- Models. The autonomous loop supports only the
claudeandcodexbackends of the externalunified-agentpackage.--modelis passed through unchecked, and both roles share one model. Other providers are available only in the legacy client, throughpentestgpt_legacy/llm/registry.py. - Tools. The framework registers no tools of its own. Anything installed in the environment, plus the provider’s MCP servers and skills, is available to both roles.
unified_agent/tools.pycan serve Python functions to both backends over a stdio MCP server, but the agent does not use it. - Policy changes. Scope, task-kind rules and finish conditions live in
compile_plan. Evidence rules live incompile_execution. The prompt and schema hashes are part of the resume identity, so editing them invalidates in-flight runs on purpose.
Running it
- Local.
make install, thenmake run TARGET=.... This callsuv run pentestgpt-agent --goal ... --target ... --backend ...insidepentestgpt_agent/(Makefile). TheclaudeorcodexCLI must be installed and logged in. - Docker. The image bundles both CLIs and keeps their logins in named volumes.
make docker-runis a stub at this commit: it prints that the framework is not in the image yet and exits (Makefile). - Audit.
pentestgpt-agent-auditre-checks a finished run directory against its traces. - Legacy.
pentestgpt-legacy, with API keys for whichever providers you enable.
Strengths and caveats
- Strength: deterministic authority. The models propose and plain code decides. Plan and execution compilers, a revisioned SQLite log and no-replay rules make runs auditable and resumable. This design is rare in the category.
- Strength: evidence cannot be invented. A task completes only when its quoted evidence matches captured output exactly, so a model cannot write
doneand paraphrase its way there. - Strength: small surface. About 4,000 lines of framework code, with a large test suite next to it.
- Caveat: full access, no in-process sandbox. Both roles get
FULL_ACCESSto the shell and filesystem. The scope check covers the planned target string, not the traffic. You have to supply a disposable, network-restricted environment yourself, and nothing in the repo provisions one. - Caveat: no human approval gate. No step requires an operator to confirm anything during a run. The safeguards are the decision cap, the attempt cap, task-kind rules and the provider’s own safety layer.
- Caveat: no findings or report yet. Output is a set of verbatim observations plus
summary.json. There is no severity, deduplication or report generation. - Caveat: README drift. The README documents a
pentestgpt --target ... --modecommand, session listing and a fixed multi-stage pipeline. None of these exist at this commit. The real entry points arepentestgpt-agentandpentestgpt-legacy.
Sources: code at e8b1bb7, verified Q&A.
How it answers the Open-source AI pentest and offensive-security agents questions
Each answer was drafted by a code-reading agent at commit e8b1bb7. Its citations were checked mechanically. Compare with the other open-source ai pentest and offensive-security agents →
How is the agent loop and planning implemented?
answeredThe autonomous loop uses two deterministic LLM roles — Supervisor and Executor — with no speculative backlog, always-on judge, or parallel scheduler. The Supervisor receives a bounded projection of the run state (open tasks, four recent closed tasks, required dependency context, selected observations, aggregate history, and recent diagnostics) and proposes at most one new task or selects one existing ready task, or signals finish. Its typed decision goes through compile_plan() (plan.py:157) which validates target scope, task kind rules (e.g. EXPLOIT requires a completed TEST on the same target), dependency cycles, basis-ID existence, and finish preconditions — all in pure deterministic code with no model involvement. Once validated, MemoryKernel.commit_plan() (memory.py:431) atomically inserts the new task, transitions the selected task to ACTIVE, creates an Attempt record, and advances the revision counter. The Executor then receives exactly one leased task with explicit kind, turn budget, basis observations, and optional retry diagnostic. Its output goes through compile_execution() (execution.py:271) which verifies that the evidence_excerpt is an exact contiguous substring of one eligible command/tool output receipt, CRLF-normalized only. No model reviews the model's own output. The loop in PentestLoop.run() (loop.py:44) runs decision cycles until the run completes, a max_decisions cap (default 20) is reached, or a non-recoverable error occurs. Each episode is a fresh provider session (resume = null); provider conversation history is not memory. The legacy client (pentestgpt_legacy/) is a human-driven interactive session using three model roles (reasoning, generation, parsing) with no autonomous loop.
How are security tools integrated and executed?
answeredPentestGPT does not define its own security tools. Instead, both the Supervisor and Executor receive every tool exposed by the LLM provider (Claude Code or Codex) with SandboxPolicy.FULL_ACCESS. The provider supplies shell execution, file read/write, MCP servers, and any installed skill commands. The framework's unified_agent package provides a ToolRegistry (tools.py:40) for registering custom Python functions that are served to both backends via a shared stdio MCP server (tool_server.py:1), launched as python -m unified_agent.tool_server pkg.mod:REGISTRY. Both backends see the same tool as mcp__<server>__<tool>. However, the pentestgpt_agent product itself registers zero custom tools — it relies entirely on the provider's native capabilities. The Supervisor and Executor system prompts instruct the model to use shell commands bounded with path, timeout, and output limits (agents.py:45-97). The prompts explicitly warn that tool-call timeout metadata is not an OS bound and tell the Executor to wrap network commands with OS timeout including kill-after. All tool events are captured into the trace journal (trace.py:370-400) as normalized tool_call, tool_result, command_run, command_started, and file_changed records for audit. The legacy client (pentestgpt_legacy/) is a human-driven interactive session where the user pastes security-tool output and the model summarizes it — it does not execute tools on behalf of the model.
How are scope, authorization and dangerous actions controlled?
answeredScope control is enforced through multiple deterministic layers with no human-in-the-loop approval during the run. The RunSpec (memory.py:37-43) stores allowed_targets as a tuple of URL strings from the CLI --target argument. The compile_plan() function (plan.py:157) calls _target_is_allowed() (plan.py:148) which uses a two-stage check: first by _url_contains() — comparing canonicalized scheme, hostname, port, and path prefix — then by exact non-URL string match. A task whose target does not exactly match an allowed target is rejected with PlanValidationError. The Supervisor's system prompt (agents.py:24) instructs: "Every new task target must byte-for-byte copy one supplied allowed target. Ports, schemes, vhosts, URLs, and paths belong only in the objective; never decorate the target field." There is no rate-limiting module, network isolation, or sandboxing inside the framework — SandboxPolicy.FULL_ACCESS is used for both roles (trial.py:73). The deployment container/VM itself is the security boundary, as documented. The max_decisions cap (default 20, CLI-configurable up to 1000) stops the loop after a bounded number of cycles. The max_attempts_per_task (default 2) prevents infinite retries on a single task. The executor's turn budget is per-task-kind (agents.py:209-216: DISCOVER=5, ENUMERATE=6, TEST=5, EXPLOIT=9, VERIFY=4, RECOVER=6). Task kind is a hard boundary: TEST tasks are validated to not contain exploit phrases like "capture the flag" or "reverse shell" (plan.py:201-203). The legacy client has no automated scoping; it relies on the human user to stay in bounds.
How are findings validated and reported?
answeredThere is no structured findings subsystem in this codebase. The CONTEXT.md explicitly states: "Structured findings are not implemented yet" (CONTEXT.md:51-52). Instead, the framework produces canonical observations: each is an exact contiguous substring from exactly one eligible command or tool output receipt, stored as ObservationRecord in SQLite with full identity provenance (run, task, attempt, trace episode, evidence sequence). The compile_execution() function (execution.py:271) enforces evidence grounding through multiple resolution strategies: exact substring match (_exact_receipt_slice), ordered line-span widening (_ordered_exact_line_span), unique line-envelope recovery (_exact_unique_line_envelope), cross-receipt projection (_supported_single_receipt_projection), and prior-observation reuse for no-action retries. Evidence that is truncated to 4,000 characters, widened, projected, or unresolved degrades done outcomes to progress — it can never complete a task. False-positive prevention is structural: the Executor must quote evidence verbatim, the compile step validates it against the trace receipts, and oversize or paraphrased evidence can only produce progress. Duplicates are prevented by basis-ID uniqueness (plan.py:205-206) and by requiring every new task ID to be unique (plan.py:179-180). The audit_run() function (audit.py:158) provides an after-the-fact auditor that checks all observations are grounded to real trace events, all observation identities match, and all basis producers are dependency tasks. The audit validates a held-out oracle flag against canonical observations. The legacy client (pentestgpt_legacy/) logs model reasoning to files but has no structured validation.
How is engagement state and knowledge kept across a long run?
answeredAll canonical state lives in SQLite, managed by MemoryKernel (memory.py:140). The database stores five tables: runs (goal, status, revision, allowed_targets), tasks (id, kind, target, objective, done_when, basis_ids, depends_on, status), attempts (id, task_id, status, revision, trace_episode_id, summary, failure_kind/message), observations (exact evidence quote with full identity provenance), and transitions (append-only revision log with kind, detail, and timestamp). WAL mode with synchronous=FULL ensures durability without concurrency overhead. There is no knowledge graph, vector store, or RAG layer. Each RunSnapshot (memory.py:46-57) is a full materialized view projected from the SQLite state on every read. The Supervisor receives a bounded projection of this state — not the full history — limited to open tasks, four recent closed tasks, required dependency/basis context, the six most recent observations, and four recent diagnostic attempts (agents.py:360-471). The Executor receives only its one task, its explicit basis (up to 8 observations), up to two same-task prior observations, and one retry diagnostic. Provider conversation history is not preserved between episodes — every episode uses resume = null. The TraceStore (trace.py:65) persists diagnostic episode traces as filesystem journals (input.json, events.jsonl, output.json per episode) but traces are not memory — they are diagnostic only. For resumption, the trial stores an identity hash (trial-config.json) of the full configuration; --resume requires an exact match including goal, targets, provider, model, effort, prompt/schema hashes, sandbox policy, and unified-agent version (trial.py:147-152). The legacy client (pentestgpt_legacy/) stores conversation history in an in-memory dictionary per model role (pentest_gpt.py:72-99) and saves transcripts to files on exit.
Which models are supported and how are cost and context managed?
answeredThe autonomous framework (pentestgpt_agent/) supports exactly two backends: claude and codex (trial.py:119). Both use the external unified-agent package which provides normalized task invocation, structured-output, and event streaming. The agent model name is passed as a CLI string (--model) with no registry validation — it is forwarded to the backend SDK directly. Both roles share the same model. Supported reasoning efforts include low|medium|high|xhigh for both backends, plus max for Claude and none|minimal for Codex (trial.py:123-130). The Supervisor gets a max of 4 provider turns, the Executor gets 12 by default (both configurable up to 100). Each Executor turn budget varies by task kind (agents.py:209-216). Provider costs and token usage are aggregated from episode traces into the trial summary (trial.py:206-275) as cost_usd and usage breakdown (input, cached-input, output, reasoning-output tokens). There are no per-role model selection or local-model hooks in the autonomous framework; the Claude auto-memory and nonessential traffic features are explicitly disabled via environment variables (trial.py:58-65).
The legacy client (pentestgpt_legacy/) supports a much wider model range through its own provider clients. The registry (llm/registry.py) lists models from OpenAI (GPT-5.5, GPT-5.4, o3, o4-mini), Anthropic (Claude Opus 4.8, Sonnet 4.6, Haiku 4.5), Google Gemini (3.1 Pro, 3.5 Flash, 3 Pro), DeepSeek (v4 Flash, v4 Pro), xAI Grok (4.3), Alibaba Qwen (3.7 Max, 3.5 Flash), Moonshot Kimi (K2.6), plus dynamic ollama:<model> for local models. It uses three separate LLMClient roles (reasoning, generation, parsing) with different models per role, auto-detecting defaults from configured providers (config.py:40-44). Context windows range from 128K to 1M tokens. All OpenAI-compatible providers share the same OpenAICompatibleProvider class via per-provider base URLs.