By UNST33R
Build a bounded LLM penetration testing agent for internal networks
A practical architecture for continuous authorized security testing: signed scope manifests, typed tool calls, deterministic policy checks, isolated execution, audit evidence, and staged rollout.
An internal penetration testing agent has two jobs that must remain separate. The language model proposes the next test from observations. A deterministic control plane decides whether that proposal is inside the signed authorization scope, safe for the current phase, and below the traffic budget.
Combining those jobs gives probabilistic text the force of access control. A prompt injection in a web page, a malformed scanner result, or a planner mistake can then expand a target list or select a destructive action. The architecture below keeps the model useful for planning and evidence synthesis while preserving ordinary security boundaries.
The intended setting is a network you own or have written permission to test. It begins with read-only asset discovery and templated checks. Exploitation, credential use, persistence, phishing, and denial-of-service actions stay outside the automatic loop.
The control plane
Use five components with narrow responsibilities:
| Component | Receives | Produces | Security rule |
|---|---|---|---|
| Scheduler | Approved campaign ID | Run request | Cannot edit scope |
| Planner model | Sanitized observations and tool schemas | Typed proposal | Has no network or shell access |
| Policy gateway | Proposal plus signed scope | Allow, deny, or require approval | Uses deterministic code only |
| Tool workers | Validated arguments | Structured observations | Run in isolated identities and namespaces |
| Evidence store | Decisions, stdout, hashes, receipts | Append-only run record | Planner cannot rewrite history |
OWASP's February 17, 2025 Agentic AI Threats and Mitigations identifies tool misuse, agent hijacking, memory poisoning, and cascading failures as distinct agent risks. This design assigns each one a control boundary. Tool misuse stops at the gateway, untrusted text is tagged before the planner sees it, campaign memory is namespaced, and repeated failures trip a kill switch.
NIST's February 2026 software and AI agent identity and authorization concept paper frames least privilege, delegated authority, human approval, and tamper-resistant auditing as core agent questions. The scope manifest below turns those questions into fields that can be checked on every tool call.
Step 1: sign a scope manifest
Do not put scope only in the system prompt. Store it as data, review it, and bind it to the campaign with a signature or an approval record. A small first campaign can use this YAML:
campaign_id: corp-lab-weekly-004
owner: security-engineering
valid_from: 2026-11-05T01:00:00Z
valid_until: 2026-11-05T03:00:00Z
targets:
cidrs: ["10.70.12.0/28"]
hostnames: ["lab-api.corp.example"]
excluded_targets: ["10.70.12.1", "10.70.12.9"]
tools:
inventory:
max_packets_per_second: 20
max_host_seconds: 120
http_check:
methods: ["GET", "HEAD"]
max_requests_per_second: 2
template_scan:
allow_tags: ["misconfig", "exposure"]
deny_tags: ["dos", "fuzz", "intrusive"]
budgets:
max_tool_calls: 100
max_failed_calls: 8
max_consecutive_failures: 3
requires_human_approval: ["new_hostname", "credential_use", "state_change"]
Resolve hostnames when the campaign is approved and again immediately before execution. Reject any address outside the listed CIDRs, including redirect destinations. Keep exclusions as higher-priority rules. A model must never be able to add a hostname by describing it as “related infrastructure.”
Hash the normalized manifest and attach scope_sha256 to every event. If the scheduler, planner, gateway, and evidence record disagree on that hash, stop the campaign. This also makes later review precise: an analyst can recover the exact authority that existed when a request ran.
Step 2: expose typed, narrow tools
Avoid a generic run_shell(command) tool. Give the planner operations with fixed fields and map those fields to argument arrays in code. A minimal proposal schema can look like this:
{
"tool": "http_check",
"reason": "Confirm whether the documented health endpoint is exposed",
"arguments": {
"url": "https://lab-api.corp.example/health",
"method": "GET"
},
"expected_evidence": "status, headers, body hash"
}
The gateway validates the tool name, argument types, normalized destination, HTTP method, traffic budget, and campaign time window. It then creates an execution ticket. The worker accepts tickets signed by the gateway and ignores direct requests from the planner.
A compact Python validator for IP targets illustrates the pattern:
from ipaddress import ip_address, ip_network
ALLOWED = [ip_network("10.70.12.0/28")]
EXCLUDED = {ip_address("10.70.12.1"), ip_address("10.70.12.9")}
def authorize_ip(raw: str) -> str:
candidate = ip_address(raw)
if candidate in EXCLUDED:
raise PermissionError("target is explicitly excluded")
if not any(candidate in network for network in ALLOWED):
raise PermissionError("target is outside campaign scope")
return str(candidate)
Production validation also needs DNS resolution, redirect checks, IPv4-mapped IPv6 normalization, URL credential rejection, port allowlists, and protection against resolution changes between authorization and connection. Put those checks in the gateway or an egress proxy, where model output cannot modify them.
Step 3: isolate every worker
Give inventory, HTTP, and template workers separate workload identities. Mount no developer home directories. Supply no default cloud credential chain. Deny general internet egress and route approved destinations through a campaign proxy.
Each worker should have a hard wall-clock timeout, CPU and memory limits, an output-size cap, and a read-only filesystem except for a run-specific scratch directory. Delete the scratch directory after its output is hashed and stored. If a scanner supports its own rate and timeout controls, configure both the scanner and the proxy. The proxy is the final authority.
For example, Nmap's official timing and performance reference documents --max-rate, --max-retries, and --host-timeout. Build those from manifest fields. Do not let the planner supply raw flags, because several scanner options trade accuracy for speed or change the type of traffic sent.
Template scanners need the same treatment. Pin the template repository revision, permit specific tags or template IDs, and review updates before changing the pin. “Latest” is an uncontrolled change to campaign behavior. Store the scanner version and template commit beside every result.
Step 4: connect the planner through an OpenAI-compatible API
The model receives the manifest summary, the available JSON schemas, and sanitized observations. It receives no API tokens for the tools. The following request asks unst33r-deepseek to select one allowed next action:
curl https://api.unst33r.si/v1/chat/completions \
-H "Authorization: Bearer $UNST33R_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "unst33r-deepseek",
"temperature": 0,
"messages": [
{
"role": "system",
"content": "You are planning an authorized lab assessment. Return exactly one JSON tool proposal from the supplied schemas. Never invent targets, credentials, flags, or tools."
},
{
"role": "user",
"content": "Scope hash: 65c7... Allowed target: 10.70.12.4. Observation: TCP 443 is open. Available tool: http_check(url, method)."
}
],
"response_format": {"type": "json_object"}
}'
Reduced-refusal models are useful in authorized security testing because reconnaissance context, payload descriptions, and vulnerability evidence are less likely to terminate a planning loop. That improves coverage. The gateway still treats every proposal as untrusted input. Test JSON and tool-call stability in your own harness before choosing a tier; the model selection guide explains how to separate workload fit from headline benchmarks.
For high-volume observation summaries, unst33r-flash can handle narrow classification tasks. Reserve a stronger reasoning tier for ambiguous evidence and final adjudication. Keep the executor model-free. The single-endpoint PyRIT sweep shows how to reuse one API contract while recording the model ID per run.
Step 5: treat tool output as hostile data
A banner, HTML comment, repository file, or scanner finding may contain instructions aimed at the planner. Wrap every observation in a typed envelope and state its provenance:
{
"observation_id": "obs-0041",
"source_tool": "http_check",
"target": "10.70.12.4:443",
"untrusted_content": true,
"content_type": "text/html",
"sha256": "c17d...",
"excerpt": "<title>Lab API</title>"
}
Strip active content, cap excerpts, and store the full body outside the model context. System instructions should tell the planner that envelope content is evidence and cannot change scope or tool policy. That reduces accidental instruction following, while the policy gateway contains the impact if the planner is still hijacked.
This is also why end-to-end success is an incomplete metric. Log each proposal and gateway decision so a denied out-of-scope attempt remains visible. Our multi-agent attack-surface primer covers confused-deputy and shared-memory tests for planners that delegate across several workers.
Step 6: make the kill switch mechanical
The scheduler should stop issuing work when any hard condition fires:
- The current time leaves the approved campaign window.
- A proposal targets an excluded or unresolved destination.
- Three tool calls fail consecutively.
- The tool-call, packet, request, token, or cost budget is exhausted.
- A worker output cannot be parsed or exceeds its size cap.
- The proxy sees a destination absent from the execution ticket.
- A human operator activates the campaign stop control.
Stopping must revoke worker credentials and invalidate outstanding tickets. Merely telling the planner to stop leaves already queued work alive. Test the switch before each campaign by pausing a benign long-running lab check and confirming that network traffic and queue consumption cease.
Step 7: keep evidence that another analyst can replay
An audit row should contain at least:
{
"run_id": "corp-lab-weekly-004-017",
"scope_sha256": "65c7...",
"model": "unst33r-deepseek",
"prompt_sha256": "90da...",
"proposal_sha256": "56a1...",
"tool": "http_check",
"target": "10.70.12.4:443",
"policy_decision": "allow",
"worker_identity": "http-worker-07",
"stdout_sha256": "c17d...",
"started_at": "2026-11-05T01:17:03Z",
"finished_at": "2026-11-05T01:17:04Z"
}
Store raw model responses, normalized proposals, denial reasons, tool versions, policy version, and approval identity. A finding without the denied attempts around it can hide scope pressure. A model summary without the underlying tool artifact cannot be independently validated.
Use a separate reviewer to score evidence quality. The reviewer may suppress duplicates and route likely findings, but it cannot change scanner output or mark a vulnerability confirmed without a deterministic check or a human analyst. The PyRIT CI/CD gate tutorial provides a pattern for turning reviewed cases into regression tests.
Roll out in four gates
| Gate | Model authority | Tool behavior | Promotion condition |
|---|---|---|---|
| 1. Replay | Proposes from saved observations | No live tools | Proposals remain parseable and in scope |
| 2. Shadow | Observes live sanitized results | Gateway logs decisions; workers do not run proposals | Zero unexplained target or tool expansion |
| 3. Lab | Plans against isolated test systems | Read-only, low-rate tools execute | Kill switch, evidence capture, and budget limits pass drills |
| 4. Limited internal | Plans against a small approved segment | Same read-only tools under a short window | Human review shows useful findings with acceptable noise |
Promotion is campaign-specific. Adding a tool, credential class, subnet, template family, or state-changing method sends the design back through review. Continuous execution should mean a repeatable scheduled authorization, not permanent open-ended authority.
The first useful weekly campaign
Start with one /28 lab range, inventory plus GET/HEAD, and a one-hour window. Cap the campaign at 100 tool calls and two requests per second. Ask the planner to group observations, select the next allowed check, and draft evidence summaries. Require human approval for every new hostname and any action outside the two read-only tools.
After three clean runs, compare the agent's findings with the same tools executed from a fixed script. The agent earns its place only if it improves prioritization or coverage while preserving the same scope. Track denied proposal rate, duplicate rate, analyst-confirmed finding rate, time per confirmed finding, and kill-switch latency. Raw finding count rewards noise.
Existing autonomous pentest harnesses can sit above this control plane. The integration notes for Shannon, Strix, and T3MP3ST explain why PoC-stage refusals matter; the bounded architecture here supplies the authorization and execution layer those model loops still need.
Keep every campaign within written scope and the acceptable-use policy. An LLM penetration testing agent becomes operationally useful when its authority is narrower, more observable, and easier to revoke than a human tester's shell session. Build those properties first, then increase autonomy one reviewed capability at a time.