Armur-Ai/Pentest-Swarm-AI
Go CLI that runs recon, classifier, exploit and report agents over a pheromone-weighted blackboard, with layered scope and cost guards.
Overview
Pentest Swarm AI is a Go program (pentestswarm) aimed mainly at web and API targets. It has two campaign engines:
- The sequential runner (
Runner.Run) is a fixed five-phase pipeline: recon, classify, plan, execute, report. - The swarm runner (
Runner.RunSwarm, the--swarmflag) uses no central planner. Four agents subscribe to a shared in-memory blackboard and react to typed findings. Each finding carries a “pheromone” weight that decays over time, and consumers ignore findings below a threshold.
Most of the work is done by code, not by the model. Recon chooses its tools from the target type, and a Coordinator runs them concurrently as argv subprocesses. The LLM classifies raw tool output, proposes attack paths as command lines, and writes the report. The exploit agent also runs built-in HTTP probes per vulnerability class, and optional oracles confirm a finding with timing, response-difference or out-of-band signals instead of trusting the model.
Of the projects in this category, this one has the most explicit safety layering. An operator authorization gate, a fail-closed scope validator called by every tool adapter, a command-level scan, a binary allowlist, a dial-time egress guard, a cost cap and an assist mode all exist in code. Some of it is thinner than the docs suggest, as described below.
Architecture
flowchart LR
CLI["pentestswarm scan / run"] --> GATE["ensureAuthorized"]
GATE --> SEQ["Runner.Run (5 phases)"]
GATE --> SW["Runner.RunSwarm"]
SW --> BB["Blackboard (memory)"]
SW --> SCH["Scheduler"]
SCH --> RA["recon agent"]
SCH --> CA["classifier agent"]
SCH --> EA["exploit agent"]
SCH --> REP["report agent"]
RA --> COORD["tools.Coordinator"]
EA --> EXE["exploit.Executor"]
EA --> HTTP["session client + oracles"]
COORD --> SCOPE["scope.Validate"]
EXE --> SCOPE
HTTP --> EGR["ScopedDialContext"]
CA --> LLM["llm.Provider + Meter"]
REP --> OUT["md / json / html / sarif"]
| Component | Path | Role |
|---|---|---|
| CLI | cli/ |
Cobra commands (scan, run, chain, poc, mcp, serve, doctor, …) and the authorization gate |
| Engines | internal/engine/runner.go, swarm_runner.go |
Build scope, providers, agents; run the pipeline or the swarm |
| Swarm core | internal/swarm/ |
Agent contract, Scheduler, blackboard (memory and Postgres implementations), swarm agents |
| Agents | internal/agent/{recon,classifier,exploit,report} |
Tool planning, LLM classification, attack-path building, report generation |
| Tools | internal/tools/ |
~40 adapters (nmap, httpx, nuclei, sqlmap, ffuf, …) with per-adapter scope checks |
| Scope | internal/scope/ |
Validate, ValidateCommand, egress dialer |
| Authorization | internal/authz/ |
Terms acceptance receipt and per-run JSONL audit log |
| LLM | internal/llm/ |
Ten providers behind one interface, pricing table and cost Meter |
| PoC | internal/poc/ |
LLM-written Python proof scripts, safety regex scan, optional local runner |
How a request flows
Take pentestswarm scan app.example --scope app.example --swarm:
- Authorize.
ensureAuthorizedasks the operator, once, to type a confirm phrase. It also accepts--authorizedorPENTESTSWARM_AUTHORIZED, or a stored acceptance, and appends a per-run JSONL record.--lab,--demoand--dry-runare exempt. A non-interactive session with no acceptance fails closed (authorize.go). - Scope and providers.
RunSwarmbuilds aScopeDefinitionand one metered provider per role. Explicit per-agent models win; on Together and OpenRouter, cheaper models go to recon and report (swarm_runner.go). A goroutine polls the meter every 3 seconds and stops the run at--budget(swarm_runner.go). - Seed and schedule. Four agents are registered, the board is seeded with
TARGET_REGISTERED, andScheduler.Runstarts one dispatch loop per agent (swarm_runner.go). - Recon. The recon agent fires on the target, picks a fixed tool list from the target type, and runs it through the
Coordinator. Each adapter callsscope.ValidateAndLogbefore it starts its binary (nmap.go). Subdomains, ports and services go back on the board. - Classify. The classifier turns each finding into a
ClassifiedFinding(CVE, CVSS, severity). It lowers the pheromone according to how reliable the producing model is, and lets a corroborator reject or confirm the finding before writing it back (classifier.go). - Exploit. The exploit agent only reacts to CVE, misconfiguration, endpoint and playbook findings above pheromone 0.3 (exploit.go). It runs stored chains deterministically, asks the LLM for attack paths, and runs per-class HTTP sweeps. Every command step goes through
exploit.Executor. - Finish.
CAMPAIGN_COMPLETEis written after the 20-minute time budget, after 60 seconds of idle, or when the cost cap or killswitch fires. The report agent then queries findings above the publish threshold, collapses duplicates, and renders the report (report.go).
Key components
Scheduler and blackboard
An agent declares Name, Trigger (a predicate over finding types and minimum pheromone), MaxConcurrency and Handle (agent.go). Besides the per-agent loops, Scheduler.Run starts three watchers: one for campaign completion, a budget enforcer that writes CAMPAIGN_COMPLETE so a partial report still renders, and a quiescence watcher (scheduler.go). The pheromone model is a real routing mechanism, not decoration: weak classifications decay below the exploit agent’s gate and are never acted on.
The exploit executor
executeWithVars applies these checks in order (executor.go):
ValidateCommand, a regex scan for every IP or domain in the command line.- The binary allowlist, built from the registered adapter names (executor.go).
- Cleanup registration.
- Dry-run.
- A quote-aware parser that rejects shell metacharacters.
- A safe-mode deny-list of destructive words (executor.go).
- In assist mode, a y/N prompt before each step. Only the swarm runner wires this hook in; the sequential runner’s executor never sets it (runner.go).
Commands run with exec.CommandContext (no shell) and a 120-second timeout (executor.go).
Scope, egress and authorization
Validate checks exclusions first, then CIDRs for IPs and exact, wildcard or parent-domain matches for hostnames. An empty scope is rejected (validator.go). An allowed example.com also admits every subdomain (validator.go).
ScopedDialContext refuses out-of-scope dials for Go-native HTTP. Its own comment says tool subprocesses are covered only by the command scan, and that a kernel-level egress jail is a commercial feature (egress.go).
Three gaps show in the code:
- Exclusions and ports are dropped. Both runners give the recon agent and the executor a copy of the scope that keeps only
AllowedDomainsandAllowedCIDRs.--excludeand--allow-portstherefore reach the session egress guard and the oracles, but not the tool-adapter or command checks (swarm_runner.go, runner.go). - The gate covers only CLI commands.
ensureAuthorizedis called from the CLI only. The MCPscan_targettool and theserveAPI start campaigns without it (mcp/tools.go). The API listens on all interfaces, and its API key and CORS origins default to empty and*(server.go, config.go). - Live scope reload is not wired in. A
scope.Watcherfor live reload exists but is never constructed outside its tests.
Findings and verification
Findings carry a Verified flag and a receipt when an external oracle proved them. --verify enables timing, differential and OOB oracles, rate-limited to 5 requests per second and scope-guarded (swarm_runner.go). --verify-poc has the LLM write a Python proof, rejects destructive patterns with regexes (safety.go), and runs it locally. The runner’s own comment says it does not sandbox network egress (runner.go). The report merges findings that share a normalised target, severity and category (report.go). pipeline.CrossValidate (corroboration by two or more tools) is defined but never called.
State and models
The swarm board is always NewMemoryBoard, so a campaign cannot resume after a crash. The Postgres board exists but RunSwarm does not use it. Cross-campaign “memory” is a JSON file of learned patterns, capped at 5,000 entries and recalled by target. There are ten providers, including local Ollama and LM Studio. If a fallback provider is configured, a refusal by the primary model is retried with a stricter system prompt and then sent to the fallback. There is no conversation-level context management in the live engines: each agent call is a fresh, bounded prompt. The BudgetManager summariser lives in an orchestrator package that nothing imports.
Extending it
- Tool: add an adapter implementing
Name/Run/IsAvailable, callscope.ValidateAndLogfirst, and register it inNewCoordinator. That also adds it to the exploit allowlist. - Swarm agent: implement
swarm.Agentand register it inRunSwarm. - Chains and playbooks: YAML under
chains/andplaybooks/(embedded);pentestswarm chainmanages them. - Pheromone tuning:
config/pheromones.yamland--exploration-bias.
Running it
Install via npm, Homebrew, go install or the Docker image, then run pentestswarm run for the TUI launcher or pentestswarm scan <target> --scope <target> --swarm. doctor lists missing tool binaries, and --lab starts bundled vulnerable targets. A provider key is needed unless you use Ollama or LM Studio. Postgres and Redis appear in the deploy compose files, but the scan engines use an in-memory board and cleanup registry, so a local scan runs without them.
Strengths and caveats
- Strength: deterministic tool layer. Recon order, argv construction and output parsing are code, so the LLM cannot invent a shell pipeline in recon, and exploit commands pass an allowlist and a metacharacter parser.
- Strength: layered controls. An authorization receipt, per-adapter scope checks, an egress dialer, a cost cap, safe-mode, dry-run and assist mode are each real code paths.
- Strength: evidence over opinion. Oracle-proven findings are marked as verified, and pheromone gating keeps unconfirmed cheap-model guesses away from the exploit agent.
- Caveat: scope gaps. Exclusions and port limits are lost for tool and command checks. The command scan is regex-based and skips a hard-coded list of hosts. LLM-written PoC scripts have no network guard.
- Caveat: unauthenticated surfaces. MCP and the API start campaigns with no authorization gate, and the API binds all interfaces with no key by default.
- Caveat: dead code next to docs. A scope watcher, cross-validation, the Postgres board and the context summariser exist but are not wired into the engines.
- Caveat: refusal fallback. With a fallback provider configured, refusals are retried on a “less restrictive” model by design.
Sources: code at 40985e3, 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 40985e3. 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 project implements two execution modes: a sequential 5-phase state-machine pipeline (internal/engine/runner.go) and a newer stigmergic swarm (internal/engine/swarm_runner.go + internal/swarm/). The swarm is the primary mode, selected by --swarm CLI flag.
Multi-agent architecture: The swarm has four specialist agents — recon, classifier, exploit, report — each implementing the swarm.Agent interface (internal/swarm/agent.go:19-36). Agents are stateless between Handle calls; all persistent state lives on the blackboard. There is no central planner. Each agent declares a Trigger() predicate (e.g. TARGET_REGISTERED for recon, raw recon findings for classifier, CVE matches for exploit); the scheduler subscribes and dispatches matching findings as they appear (swarm_runner.go:750-775, scheduler.go:296-418).
Planning and decomposition: Planning emerges from pheromone-weighted shared state. Every finding on the blackboard has a PheromoneBase (initial weight 0-1) and a HalfLifeSec decay. Findings decay over time; agents gate on a MinPheromone floor, so stale/unreinforced signals naturally die. The quality tier system (internal/swarm/quality/quality.go:41-53) discounts inferential findings from cheap models by up to 40%, forcing them to earn attention through corroboration. Tool-grounded observations bypass discount entirely.
Turn structure: The Scheduler.runAgent loop (scheduler.go:299-418) subscribes to a channel, pulls findings one by one respecting MaxConcurrency, calls Handle(), commits a cursor for exactly-once delivery, and updates the aggregate and per-agent budgets. Each Handle invocation is a complete turn — the agent reads board state and writes new findings.
Stop conditions: The scheduler terminates on: (1) CAMPAIGN_COMPLETE finding written to the board, (2) context cancellation (SIGINT), (3) per-campaign time budget (default 20 min in swarm_runner.go:914), (4) a $MaxCostUSD cost cap watcher in swarm_runner.go:245-268, (5) quiescence auto-complete after 60 s of no activity (scheduler.go:232-271). Budget exhaustion writes CAMPAIGN_COMPLETE rather than aborting, so the report agent fires on partial findings.
How are security tools integrated and executed?
answeredThe project wraps 33 security tools as Go adapters, listed in internal/tools/coordinator.go:70-109. Each implements the Tool interface (base.go:9-18) with Name(), Run(), and IsAvailable() methods. Tools include: subfinder (subdomain discovery), httpx (HTTP probing), nuclei (template vuln scanning), naabu (port scanning), katana (web crawling), dnsx (DNS), gau (URL history), nmap, sqlmap, ffuf, gobuster, feroxbuster, trufflehog, gitleaks, semgrep, amass, dalfox (XSS), jwt_tool, arjun (parameter discovery), interactsh (OOB callbacks), nikto, wpscan, checkov, cloudsplaining, prowler, pacu, scoutsuite, kube-hunter, droopescan, wafw00f, whatweb, dotdotpwn, crackmapexec, bloodhound, ysoserial, crlfuzz, testssl, gxss.
Execution mechanism: Tools run as subprocesses via executor.go:18-62 which uses os/exec.CommandContext with an augmented PATH from toolpath.AugmentedPATH() so tools installed via go install or pentestswarm install-tools are found regardless of shell PATH. The RunToolCommand wrapper (executor.go:76-112) adds timeouts and parses JSONL output via parseJSONLines into structured findings.
Coordinator: The Coordinator (coordinator.go:55-275) runs tools concurrently via goroutines, supports RunAll (parallel dispatch of every available tool) and RunSelected (by tool name). Results stream per-tool as they complete through a channel. Hooks (OnStart, OnDone, OnSkip) feed into the campaign event stream so missing binaries are surfaced as live warnings.
Additional execution paths: The exploit executor (internal/agent/exploit/executor.go:18-36) runs LLM-generated httpreq commands, scope-validated. A headless browser driver (internal/browser/browser.go:1-61) renders JS SPAs and harvests back-end API calls. An MCP server (internal/mcp/tools.go:16-147) exposes scan_target, quick_recon, explain_finding and campaign_status as tool calls for external AI agents. Output parsing is per-adapter — nuclei templates produce VulnerabilityRecord structs with clean titles, sqlmap extracts injection points for later timing re-proof.
How are scope, authorization and dangerous actions controlled?
answeredSafety is implemented across six independent layers:
1. Scope validation: internal/scope/validator.go:24-38 defines Validate() and ValidateCommand(). The ScopeDefinition (validator.go:15-20) carries AllowedDomains, AllowedCIDRs, ExcludedCIDRs and AllowedPorts. Domain matching supports exact, wildcard (*.example.com), and subdomain suffixes. ValidateCommand() (validator.go:178-203) regex-scans every command string for IPs/domains and rejects any out-of-scope target before execution. ValidateAndLog in audit.go:17-36 wraps validation with mandatory structured logging for audit trails.
2. Egress guard: internal/scope/egress.go:22-36 wraps the Go network dialer so any outbound connection to an out-of-scope host is refused at the TCP layer — a last-line defense beneath request- and command-level checks (labelled SAFE-6). The authenticated HTTP session (swarm_runner.go:498) incorporates this guard.
3. Shell safety: internal/shellsafe/shellsafe.go:14-112 provides a quote-aware command parser that rejects unquoted shell metacharacters (|, >, <, &, ;, `, $()). Commands requiring shell features must explicitly wrap in sh -c "...".
4. Safe mode and executable allowlist: The exploit executor (internal/agent/exploit/executor.go:19-100) enforces safeMode which blocks commands containing destructive tokens (rm, DROP, TRUNCATE, kill, chmod, shutdown). The allowedExecutables set (executor.go:31, populated from coordinator.RegisteredToolNames()) restricts which binaries the LLM can invoke — no arbitrary shell commands.
5. Human-in-the-loop: Assist mode (runner.go:91-95, executor.go:46) prompts the operator y/N before every executed step via ConfirmFunc. Available through --assist on the CLI.
6. Rate limits and budgets: The scheduler enforces per-agent rate limits (scheduler.go:104-111, 355-359), per-agent token budgets (scheduler.go:335-352), per-campaign time budgets (swarm_runner.go:798-820), and per-campaign cost caps (MaxCostUSD at swarm_runner.go:264-268). A quiescence timeout (scheduler.go:232-271) completes the campaign after 60s of inactivity. The scope.enforce_strict: true config (config.example.yaml:155) is documented as always-on and non-disablable.
scope.enforce_strict setting is read by no code, and --exclude/--allow-ports never reach the tool-adapter or command checks (the runners pass a scope rebuilt from allowed domains/CIDRs only; only the egress and oracle guards see the full scope). The operator authorization gate covers CLI campaigns only: the MCP scan_target tool and the serve API start campaigns without it, and the API binds with no key by default.How are findings validated and reported?
answeredFindings flow through a five-stage validation pipeline before appearing in reports.
1. FP filtering: The ClassifierAgent calls FPFilter.Score() (internal/agent/classifier/fp_filter.go:18-62) which applies 6 deterministic rules to score FP probability: generic server banners (+0.6), ports without service ID (+0.4), 4xx-only endpoints (+0.5), version mismatches (+0.7), non-standard ports (+0.3), info-level findings (+0.2). Findings above 0.75 are filtered.
2. Cross-tool corroboration: pipeline/cross_validate.go:20-55 groups findings by (target, attack_category). When 2+ distinct tools hit the same vulnerability, confidence upgrades to High. Single-source findings with no reproduction plan drop to Unverified.
3. LLM classification and active corroboration: The classifier agent (internal/swarm/agents/classifier.go:51-67) triggers on recon findings and publishes CVE_MATCH/MISCONFIGURATION findings. At the handoff to the exploit agent, a Corroborator (internal/swarm/verify/verify.go:126-321) applies a four-step cost-aware policy: (1) frontier-sourced judgments pass unverified, (2) free corroboration from tool-grounded or multi-signal board data promotes findings at zero LLM cost, (3) low-stakes findings pass through to the passive pheromone gate, (4) high-stakes uncorroborated cheap-model judgments trigger exactly one paid strong-model verification, capped per-campaign.
4. External oracles (--verify): For proven findings that carry a ProbeSpec (internal/swarm/verify/probespec.go:37-59), live oracles (verify/oracle.go:30-48) re-prove the vulnerability against the real target with non-LLM signals — OOB callbacks via interactsh, differential response comparison, or timing ladders. A decisive oracle verdict (Proven at 0.95 pheromone floor) is trusted over any model claim. These are only enabled under --verify-oraacles and respect scope/safe-mode.
5. PoC self-verification: The report agent can run generated PoC code against the target and stamp findings VERIFIED only if they fire (swarm_runner.go:576-583). A safety scanner (internal/poc/safety.go:21-54) prevents destructive patterns (rm -rf, DROP TABLE, etc.) from being executed. An optional Jev model (swarm_runner.go:585-588) scores findings by P(true-positive) and drops those below threshold.
Report format: The renderer (internal/agent/report/agent.go:36-106) produces Markdown, JSON, HTML, and SARIF output. Each finding includes CWE/OWASP/ATT&CK taxonomy labels, CVSS score/vector, evidence, reproduction steps, remediation, and a Verified badge with the verifier name when proven by an oracle.
pipeline.CrossValidate has no non-test caller, so cross-tool corroboration is not part of the live pipeline; the report path de-duplicates with collapseDuplicateFindings in internal/swarm/agents/report.go.How is engagement state and knowledge kept across a long run?
answeredState is maintained across three distinct storage systems with different lifetimes.
In-campaign: the blackboard (internal/swarm/blackboard/). The Board interface (board.go:12-54) provides Write, Query, Subscribe, cursor tracking and budget operations. Each Finding (types.go:59-74) carries a PheromoneBase, HalfLifeSec decay, and typed data. Agents subscribe via Predicate (type filter + MinPheromone gate) and receive a channel of matching findings. The board is memory-backed by default (NewMemoryBoard in swarm_runner.go:284), with a Postgres variant selected when a DB pool is available. The scheduler tracks per-agent cursors for exactly-once delivery (board.go:29-34). Pheromone-based decay means stale findings naturally deprioritize without explicit compaction.
Cross-campaign: MemoryStore (internal/memory/store.go:19-26, persist.go:14-69). After a campaign, the engine calls ExtractPatterns and stores learned patterns in a MemoryStore with categories: tech_stack, attack_chain, false_positive, timing. Each entry has Confidence, UsageCount, and LastUsed. On subsequent runs, RecallRelevant matches target keywords against stored patterns (store.go:42-56) and feeds the resulting brief to the recon agent (swarm_runner.go:468-471). The store persists to ~/.pentestswarm/memory.json (capped at 5000 entries, oldest dropped). Duplicates are merged (bump UsageCount, keep higher confidence) rather than appended.
The attack graph (internal/attackgraph/) is built from findings and the campaign objective, with nodes for each vulnerability/host state and edges for exploitability. BuildFromFindings constructs the graph; BestPathToObjective finds the highest-probability chain (agent/report/agent.go:112-140). Edges proven by external oracles are marked "verified" with full certainty.
Resuming engagements: The scheduler's cursor mechanism (board.go:34, scheduler.go:301) means agents resume from their last committed finding ID. An operator can warm-start a swarm by importing a context pack via SeedImported (agents/seed.go:48-100), which writes prior endpoints and findings to the board with standard pheromone so the swarm skips rediscovery. The ctxpack.Load mechanism (swarm_runner.go:459-465) reads a folder of prior pentest reports, tool output, or code.
blackboard.NewMemoryBoard); NewPostgresBoard has no caller, so in-campaign swarm state does not survive a restart.Which models are supported and how are cost and context managed?
answeredSupported providers (from internal/llm/factory.go:100-288): claude (Anthropic), together (Together AI), openai (native or any OpenAI-compatible), gemini (Google), ollama (local), lmstudio (local), orcarouter (OrcaRouter gateway), openrouter (OpenRouter gateway), bedrock (AWS Bedrock), musespark (Meta Muse Spark). All implement the Provider interface (provider.go:11-29) with Complete, Stream, HealthCheck, ModelName, ContextWindow, SupportsToolUse.
Per-role model selection: By default, all agents inherit the orchestrator's provider and key (config.example.yaml:102-122). In swarm mode, per-role routing is applied: on Together AI, all roles get zai-org/GLM-5.3-Flash (swarm_runner.go:55-57); on OpenRouter, bulk roles (recon, report) get deepseek/deepseek-v4.1-flash and reasoning roles (classifier, exploit) get z-ai/glm-5.3-flash (swarm_runner.go:68-75). An explicit --model or per-agent config override wins over defaults (swarm_runner.go:187-193).
Local model support: Ollama and LM Studio providers use local endpoints (factory.go:117-135). The config example shows how to point individual agents at fine-tuned local models (config.example.yaml:107-122 e.g. ArmurAI/recon-agent-qwen2.5-7b). Context window minimum is validated at 32k tokens (factory.go:296-298).
Cost context management: The llm.Meter (swarm_runner.go:167) wraps every provider and aggregates token spend against a pricing table (pricing.go:25-103) covering 20+ model SKUs across all vendors. A live cost-meter goroutine (swarm_runner.go:245-269) polls every 3s, emits spend to the event stream every 15s, and winds the campaign down when MaxCostUSD is exceeded. The BudgetManager (llm/budget.go:8-99) tracks context-window utilization, warns at 80%, and can summarize oldest messages at 70% threshold by asking the LLM to compress them. Per-agent token budgets (board.go:47-53) prevent one chatty agent from burning the campaign's headroom; the scheduler checks AgentBudget before dispatch (scheduler.go:335-352).
Refusal retry: NewProviderWithRetry (prompts/factory.go:23-48) wraps the primary provider with a configurable fallback provider. If a safety filter refuses a legitimate offense-security prompt, a stricter reframe is attempted, then a fallback to a less-restrictive provider.
BudgetManager (summarise at 70%) is only used in internal/agent/orchestrator, a package nothing imports; the live engines send bounded single-shot prompts per agent call, so no context summarisation runs.