Day 2 of 560 minExploit ArchitectHands-on lab

Day 2: Giving the agent scanner tools with least privilege

Taught by Mr Elite Updated

By the end of today you can

  • Design scan tools with a fixed schema and allowlisted flags instead of free-form command strings
  • Validate every argument against scope.yaml in code, not in the prompt
  • Run a scanner in a container with no credentials, dropped capabilities and a limited network
  • Prove with a saved note that malformed and out-of-scope calls are rejected

Warm-up

Answer from memory first, then tap to check. Recalling yesterday is what makes it stick.

Who decides what is in scope, and what is the agent allowed to do with the scope file?

A human decides. The agent reads the scope file and never edits it.

Why do we build commands as argument lists and not as shell strings?

A list is passed to the program as separate arguments, so input cannot add extra commands or flags through shell parsing.

Picture an agent with one tool called run_command that takes a string. It is told in the prompt to scan only the client's staging host. Then a banner on that host says to also check the admin panel on another address, and the agent obliges. Nothing in your prompt was wrong. The tool simply allowed it.

Today we fix that at the tool. The agent gets two narrow tools, scan_host and run_template. Each accepts only values that your code checks against yesterday's scope file. The model can ask for anything it likes, but the tool decides what happens.

The tool is the blast radius

An agent has no powers of its own. It can only do what its tools can do, so the tool set defines the worst case. If a tool accepts any string and runs it, a hijacked agent can do anything your account can do. If a tool accepts a host from a list and one of three scan profiles, the worst case is a quick scan of a host you already approved.

This is why I treat the prompt as a hint and the tool as the law. A prompt says please. Code says no. Anything that matters, such as scope, flags and timeouts, lives in code that the model cannot rewrite.

Fixed schema
A declared list of arguments with types and allowed values. Anything outside it is rejected before a program runs.
Allowlist
A list of permitted values. Anything not on it is refused, which is safer than trying to list bad values.
Blast radius
How much damage a compromised component can do with the permissions it holds.

Quick check

Your prompt says 'only scan hosts in scope'. A tool accepts any hostname string. Where is the scope control actually enforced?

Design rules for a scanner tool

Four rules cover most of it. First, never accept a command string or a free-form flags field. Second, expose named options such as profile=quick, and map each name to a fixed argument list in your code. Third, check every target against scope.yaml with exact matching. Fourth, fail closed: any error or surprise means refuse.

Notice what this removes. The agent cannot add --script, cannot point Nuclei at a template path of its choosing, and cannot smuggle a second host into one string. Each of those is a real route for abuse, and each is closed by leaving the field out of the schema.

Watch me do it: build scan_host

We reuse the scope file from Day 1 as the single authority. I assume your scope.yaml has a list under the key allowed_hosts, for example 127.0.0.1. If your key is named differently, change the one line that reads it. Everything here runs on your own machine against 127.0.0.1 only.

bash
pip install pyyaml
nmap --version
Installs the YAML reader and confirms nmap is on your path.
python
import subprocess, yaml

SCOPE = yaml.safe_load(open("scope.yaml"))
ALLOWED_HOSTS = set(SCOPE["allowed_hosts"])
PROFILES = {
    "quick": ["-F"],
    "service": ["-sV", "--top-ports", "100"],
}

class Refused(Exception):
    pass

def check_host(host):
    if not isinstance(host, str) or host not in ALLOWED_HOSTS:
        raise Refused(f"host not in scope: {host!r}")
    return host

def scan_host(host, profile="quick"):
    host = check_host(host)
    if profile not in PROFILES:
        raise Refused(f"unknown profile: {profile!r}")
    cmd = ["nmap", "-Pn", "--max-retries", "1", *PROFILES[profile], host]
    done = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    return done.stdout

SCAN_HOST_SCHEMA = {
    "name": "scan_host",
    "parameters": {
        "type": "object",
        "properties": {
            "host": {"type": "string"},
            "profile": {"type": "string", "enum": list(PROFILES)},
        },
        "required": ["host"],
        "additionalProperties": False,
    },
}
scan_host takes a host and a profile name. The flags come from your dictionary, the list is passed without a shell, and a timeout stops a hung scan.
python
from agent_tools import scan_host, Refused

calls = [
    {"host": "127.0.0.1", "profile": "quick"},
    {"host": "10.0.0.5"},
    {"host": "127.0.0.1 -sU"},
    {"host": "127.0.0.1", "profile": "-A --script=vuln"},
]
for c in calls:
    try:
        out = scan_host(**c)
        print("OK     ", c, "->", out.splitlines()[0])
    except Refused as e:
        print("REFUSED", c, "->", e)
One valid call, then an out-of-scope host, a host with a smuggled flag, and an abusive profile. Run with: python test_refusals.py > refusals.txt

You should see one OK line starting with a Starting Nmap banner, then three REFUSED lines. The schema block matters too. Setting additionalProperties to false tells the model API not to invent extra arguments, but still keep the Python checks, because the schema is advice and the code is enforcement.

Quick check

Why does the test call with host '127.0.0.1 -sU' fail even though it begins with an in-scope address?

Your turn: write run_template

Now you build the second tool with the same pattern. run_template takes a host, a port and a template name. It must never take a path, a tag expression or a raw URL. Your code maps names to template files you have reviewed and builds the URL itself.

Contain the tool process itself

Validation stops bad requests. Containment limits the damage if a scanner has a bug or a hostile response abuses it. Run each tool in a container with no credentials, no mounted home folder, a read-only filesystem and no extra Linux capabilities. Your API keys should not exist anywhere that process can see.

bash
docker network create scan-net
docker run --rm --network scan-net --cap-drop ALL \
  --read-only --security-opt no-new-privileges \
  --memory 512m -v "$PWD/templates:/t:ro" \
  projectdiscovery/nuclei:latest -version
A locked-down Nuclei run. The templates folder is mounted read-only, the network holds only what you attach to it, and no environment variables are passed.

You should see a Nuclei version banner, then the container is removed. Later you attach only the target container to scan-net, so the scanner cannot reach your other services or the internet. If Docker reports a permission error, check that your user can run docker, and note that the first pull needs internet access.

Lab: coding agent blast radius

The scanner tools are one case of a general problem. The lab shows the same idea in a different setting, so you see that least privilege applies to every agent you deploy.

Your turn

Coding Agent Blast Radius

A coding agent works on a failing test while an issue it reads carries a hidden instruction, and its permissions currently allow everything. This is the same blast radius question as our scanner tools, seen from the security engineer's chair, so we use it right after writing our own limits.

Open the lab in a new tab

What to try

What to notice

  • Which permissions were never needed for the task at all
  • Whether your fix depends on the agent behaving well or on the permission simply not existing
  • How the same pattern maps to scan_host: named options in, everything else refused

If it did not work

Leaving a free-form extra_args field 'for flexibility'

Delete it. Add a new named profile in code when you need a new behaviour, after you have reviewed it.

Checking scope in the system prompt and trusting the model to obey

Call check_host inside every tool. Test with a deliberately out-of-scope call and confirm it prints REFUSED.

Running the tool container with your home folder mounted or API keys in the environment

Run docker inspect on the container and confirm no sensitive mounts or environment variables appear.

Using shell=True or an f-string command because it was quicker to write

Search your code for shell=True and replace every hit with an argument list.

Recap

  • An agent's tools define its blast radius, so design the tools first
  • Accept named options, never command strings or free-form flags
  • Enforce scope in code with exact matching against scope.yaml
  • Schemas guide the model, but only code validation is a control
  • Run scanners in containers with no credentials, dropped capabilities and a limited network
  • Test your refusals on purpose and keep the evidence

Cheat sheet

additionalProperties: false
Schema setting that rejects arguments you did not declare
PROFILES dict
Maps a safe name to a fixed flag list, so flags never come from the agent
check_host()
Exact match against allowed_hosts, raises Refused otherwise
subprocess.run([...], timeout=120)
List arguments, no shell, bounded runtime
--cap-drop ALL --read-only
Docker flags that remove Linux capabilities and make the filesystem read-only
--security-opt no-new-privileges
Stops processes in the container gaining extra privileges

Before the next day

Mission: Two strict scan tools with proof of rejection

Finish scan_host and run_template in agent_tools.py, both validating against the Day 1 scope.yaml. Then prove they fail closed. Tomorrow we feed hostile output into these tools, so they need to hold up first.

About 30 min

You are done when: agent_tools.py with both tools and schemas, plus refusals.txt showing three rejected calls and one accepted call.

Want more? Run both tools inside the locked-down Docker container from today and record the docker run command you used, then confirm the container cannot reach a host outside scan-net.

Quiz

4 questions. Your score is saved with your progress.

1. An agent is hijacked mid-scan. Which design limits the damage most?

2. Why map profile names to flag lists in your own dictionary?

3. Your schema says port is an integer, yet your code also checks the range. Why keep both?

4. What is the main point of running the scanner container with no credentials and a limited network?

Finish the day

Mark the day complete to save your progress.

Go to Day 3

Next: On Day 3 we send hostile data back through these tools, using scanner output, banners and fetched pages, and show how an injection arrives. The strict tools you built today are what we will defend them with.

Tell someone you are doing this:WhatsAppXLinkedIn

Your notes

Private to this device. Write what you want to remember from today.