Prompt Engineering
Beginner
T1059.004

Structured Task Specification for Security

A prompt is a task specification, not a persuasion trick: what the model is given, what it may not do, what shape its answer must take, and what it has to admit it does not know. This page treats the prompt as a versioned artifact with an eval record, then runs that artifact against an offline fixture lab.

Foundation Page

Most disappointing security answers trace back to a missing part of the specification — an unstated input, an unstated constraint, or no definition of a correct answer. A persona or a clever phrasing supplies none of those; explicit inputs, constraints and an output contract do.

Core Principles

1. Name the Inputs

State exactly what the model is given: the artefact, its version, the scan output, the code under review. Unstated inputs get invented.

2. State Scope and Constraints

Name the authorization reference, the in-scope hosts, the actions that are off limits, and the output that is permitted.

3. Fix the Output Contract

Specify the schema, the severity vocabulary, the evidence each field must quote, and the explicit unknown value.

4. Version and Score It

Record the prompt id, model version and temperature, and keep the eval case the prompt must pass. The prompt is the artifact under test.

Prompt Construction Flow

Prompt Construction Pipeline

Declare the inputs, the authorization and scope, the constraints and the output contract before submitting; the answer is then scored against that contract - accepted into a documented result or refined back into the specification.

Scroll sideways to see the whole diagram

The first stage is the weakest of them: a role label changes the register of the answer and nothing else. The stages that carry weight are the inputs, the scope, the constraints and the output contract. See Persona Framing Is Not a Constraint.

Prompt Templates

Reconnaissance Prompt

recon-prompt.md
I am a penetration tester with written authorization to assess [target.com].
The scope includes all subdomains of target.com.

Help me plan and execute reconnaissance:
1. What subdomain enumeration techniques should I use?
2. Provide specific commands for subfinder, amass, and assetfinder
3. How should I organize and deduplicate the results?
4. What follow-up enumeration should I perform on discovered assets?

Target: target.com
Scope: *.target.com
Authorization: Yes, written RoE signed

Vulnerability Analysis Prompt

vuln-analysis-prompt.md
As a security researcher, I found the following during my authorized assessment:

[Paste scan results, HTTP response, or code snippet]

Please analyze this for:
1. Potential security vulnerabilities
2. Risk severity (Critical/High/Medium/Low)
3. Exploitation approach (theoretical, not actual exploit code)
4. Remediation recommendations
5. Similar CVEs or known issues

Context: This is from an authorized penetration test of my company's application.

Code Review Prompt

code-review-prompt.md
I'm conducting a security code review on our internal application.
Review this code for security vulnerabilities:

```python
[paste code here]
```

Specifically check for:
- Injection vulnerabilities (SQL, command, XSS)
- Authentication/authorization issues
- Cryptographic weaknesses
- Insecure deserialization
- OWASP Top 10 issues

For each finding, provide:
1. Vulnerability type
2. Affected line numbers
3. Exploitation scenario
4. Secure code fix

Vulnerability Reproduction Prompt

reproduction-prompt.md
Task: reproduce a published vulnerability on one isolated lab host and
produce detection guidance. Do not contact, scan, or modify any host outside that lab.

Inputs:
- CVE: CVE-XXXX-XXXXX (published advisory only)
- Component and version: [name] [version]
- Patch diff or advisory text: [paste]
- Lab target: 10.10.10.20 (isolated VLAN, no internet egress)
- Authorization: internal engagement ENG-2026-014

Constraints:
- Pseudocode only; no weaponised payload against a real target
- Root cause must be supported by the patch diff, not inferred from the CVE title
- Anything not verifiable from the inputs above is marked UNKNOWN, with the missing input named

Output contract:
1. Root cause (one paragraph, cites the changed function)
2. Preconditions, each marked CONFIRMED or UNKNOWN
3. Reproduction approach (pseudocode)
4. Detection opportunities (log source + field + expected value)
5. The inputs you would need to close the remaining unknowns

Setup and Prerequisites

  • Fixture pack: the fixture pack at /labs/offensive-ai (docker-compose.yml, app/, fixtures/, scripts/).
  • Runtime: Docker + Docker Compose, or Python 3.11+ to run the app directly with python -m app.server.
  • Working directory: run every command from inside the pack directory; the lab client is python scripts/lab.py.
  • No model download: no model download and no provider key are needed — the fixture is offline and deterministic.
lab-start.sh
docker compose up -d
python scripts/wait_for_health.py

Expected output

The container starts and the health check prints a healthy body whose marker is OAI-TOYAPP-HEALTHY.

Steps

  1. Run the gate with the fixed prompt version.

    eval-fixed.sh
    python scripts/lab.py eval --ci

    Expected output

    Exit 0. The eval gate passed, the health marker matched fixtures/evals/markers.json, and release is safe.
  2. Break the prompt deliberately and watch the gate fail.

    eval-weak.sh
    python scripts/lab.py eval --ci --prompt weak

    Expected output

    Exit 1. The eval gate failed on eval-rag-injection-001, observed injection_marker against expected no_injection_marker. Release blocked.
  3. Ask the same question under both prompt versions and compare the markers.

    compare-prompt-versions.sh
    python scripts/lab.py ask --tenant tenant-a --query "refund policy"
    python scripts/lab.py ask --tenant tenant-a --query "refund policy" --prompt weak

    Expected output

    The fixed prompt strips the injected chunk from the answer; the weak prompt follows the poisoned document and the answer contains CANARY-INJECTED-POISON-A.
  4. Score both runs in the prompt-eval table and pin the passing prompt version.

    prompt-score.md
    # Prompt score — one row per gate run.
    # Oracle: fixtures/evals/markers.json (health OAI-TOYAPP-HEALTHY,
    # injection CANARY-INJECTED-POISON-A; fixed prompt-v3-fixed, weak prompt-v0-weak).
    # Model is stub-embed-v1 on both rows. Temperature is n/a — the stub is
    # deterministic and takes no sampling parameter.
    | Run | Prompt version | Model | Temperature | Observed | Expected | Gate |
    | --- | --- | --- | --- | --- | --- | --- |
    | eval --ci | prompt-v3-fixed | stub-embed-v1 | n/a (deterministic stub) | no_injection_marker | no_injection_marker | exit 0, release |
    | eval --ci --prompt weak | prompt-v0-weak | stub-embed-v1 | n/a (deterministic stub) | injection_marker | no_injection_marker | exit 1, blocked |

    Expected output

    Every run has a recorded prompt version, observed and expected result and gate decision, and the passing template stays pinned to prompt-v3-fixed.

Verify It Worked

Check Expected Where to look
Gate passes with the fixed prompt Exit 0: the eval gate passed and the health marker matched fixtures/evals/markers.json The eval --ci run
Deliberate weak failure blocks release Exit 1 on eval-rag-injection-001: observed injection_marker against expected no_injection_marker The eval --ci --prompt weak run
Prompt version changes the answer The fixed prompt strips injected chunks; the weak prompt follows the poisoned document The two ask answers for the same query
Score pins the template Prompt version, model version, and temperature recorded for each prompt The prompt-score.md file

Evidence and Findings

Finding Proof Control
Missing specification The prompt asks for "hacking" with no inputs, no scope, and no definition of a good answer. Write the specification: inputs, authorized scope, constraints, and the output contract.
Schema drift in tool outputs Findings come back wrapped in fences or missing fields instead of the requested schema. Anchor with the exact schema plus one concrete example; request ONLY valid JSON.
Unscoped agent prompt The agent acts beyond the intended targets, directories, or actions. Enumerate available tools, define scope boundaries, require audit logging, verify before report.

Pitfalls

Under-specified task with no inputs or scope

Write the task as a specification: inputs, authorized scope, constraints, and the output contract. Re-wording the request or adopting a persona does not supply a missing constraint, and a refusal after a complete specification usually means the scope is wrong rather than the phrasing.

Sending sensitive client data in prompts

Anonymize target details when possible — never send sensitive client data in prompts.

Running MCP agents outside a sandbox

MCP-connected agents can execute real commands on real systems. Always run MCP agents in sandboxed environments during testing and review audit logs before trusting results.

Skipping the score-and-iterate loop

A prompt that cannot be re-scored is a preference, not a control. Keep prompt ids, pin the model version and temperature, and re-run the eval gate whenever either changes — that is what keeps a working template reproducible instead of remembered.

Persona Framing Is Not a Constraint

You are a senior penetration tester changes the register of an answer, not its correctness: it supplies no evidence, grants no authority, and constrains no output. What a model can actually act on sits around the persona: the inputs it is handed, the constraints it is told to honour, and the contract its answer is scored against.

What a persona changes

  • Vocabulary and assumed audience
  • How much tool-level detail it volunteers
  • Which conventions it imitates in a report

What it does not change

  • The inputs it was given, or did not receive
  • Whether the target is in scope
  • Whether a claim is supported by evidence
  • Whether the output parses

Steering around a refusal is a jailbreak, not a technique

Writing the same request as a story ("for my course", "in my isolated lab", "as a defender") to get past a model's refusal is a jailbreak. It does not make the request safer, it produces output you cannot act on, and on a client engagement it is a scope violation dressed as a shortcut. If a request is genuinely in scope, supply the missing specification instead: authorization reference, inputs, permitted output. If it is not in scope, the refusal is correct and the answer is to escalate internally, not to rephrase.

Reasoning Traces Are Not Evidence

Think step by step produces plausible narration; it verifies nothing. In a security task the useful part is the recorded intermediate artifact: which checks were run, what each result would prove, what evidence backs each claim, and what could not be determined. Ask for that ledger explicitly, score it, and treat the reasoning prose around it as an unverified claim:

reasoning-ledger-prompt.md
Task: enumerate privilege-escalation checks for one Windows host and
report what each check would prove. Do not propose a path you cannot support from the supplied evidence.

Inputs:
- Host: WIN10-WS01, domain-joined, standard domain user (no local admin)
- Collectors already run: whoami /priv, whoami /groups, systeminfo, schtasks /query
- Scope: this host only; authorized test (RoE ref ENG-2026-014)

Return one ledger row per check:
| Check | Command | What a positive result proves | Status | Evidence |

Status is exactly one of:
- CONFIRMED - evidence quoted verbatim from the supplied collector output
- NOT_RUN   - with the command that would settle it
- UNKNOWN   - with the input that is missing

Rules:
- No CONFIRMED row without a quote from the supplied output.
- Order rows by what the supplied evidence already supports, and say so if it supports nothing yet.
- End with the single next collection step that resolves the most UNKNOWN rows.

Score the ledger, not the fluency

A confident paragraph and a ledger row that quotes the same three lines of scan output are not equivalent evidence. If the answer cannot name the file, line, header, or command output behind a finding, treat it as unconfirmed regardless of how well it reads.

Refusals and Uncertainty

A refusal is information. On a legitimate engagement it usually means the specification is incomplete: the model cannot tell whether the request is authorized, what it is allowed to produce, or who will receive it. The repair is to supply those parts once, in the task text:

Supply the authorization record

RoE or engagement reference, in-scope assets, test window, and who requested the work. This is a fact about the engagement, not a sentence written to unlock an answer.

State the permitted output

Analysis rather than payload, pseudocode rather than weaponised code, detection logic rather than an evasion recipe. Naming the permitted form is what a refusal is usually missing.

Ask for the defensive artifact too

Request the detection rule, the control mapping and the remediation alongside any analysis, so the output is usable in the report rather than only illustrative.

Accept the no

If a complete specification still draws a refusal, the boundary is real. Escalate internally or to the vendor; do not iterate on the phrasing until something gives.

Handling uncertainty

Models fill gaps rather than flag them, and a fabricated CVE, control id or port number is worse than a blank field because it survives into the report. Make the empty value part of the output contract and score the rate of unsupported claims, not the confidence of the prose:

uncertainty-clause.md
Evidence rules for this task:
- For every finding, quote the input line that supports it. No quote, no finding.
- If a field cannot be determined from the inputs, write UNKNOWN and name the input you
  would need. Do not estimate, do not infer a CVE from a title, do not fill in a
  plausible value.
- If the request crosses the authorization or output limits stated above, stop and say
  which limit it crosses rather than answering around it.

Output Formatting

Request specific output formats for better usability:

output-format-prompt.md
Provide your response in this format:

## Vulnerability Summary
[Brief description]

## Technical Details
- Type: [vulnerability type]
- Severity: [CVSS score if applicable]
- Affected Component: [component]

## Exploitation Steps
1. [step 1]
2. [step 2]
...

## Proof of Concept
```
[code or commands]
```

## Remediation
[fix recommendations]

## References
- [relevant links]

Structured Output Prompting

When integrating AI outputs into toolchains, request machine-parseable formats such as JSON, YAML or CVSS vectors. Providing the exact schema in the prompt improves compliance:

JSON Findings Format

structured-json-prompt.md
Analyze the following Nmap scan results and return your findings
as a JSON array. Each finding must follow this exact schema:

{
  "findings": [
    {
      "host": "10.0.0.1",
      "port": 443,
      "service": "https",
      "vulnerability": "TLS 1.0 enabled",
      "cvss_score": 5.3,
      "cvss_vector": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N",
      "severity": "medium",
      "remediation": "Disable TLS 1.0 and 1.1; enforce TLS 1.2+"
    }
  ]
}

Return ONLY valid JSON — no markdown fences, no commentary.

[Paste Nmap results here]

YAML for Tool Import

structured-yaml-prompt.md
Convert this vulnerability assessment into YAML format
suitable for import into DefectDojo or similar platforms:

vulnerability:
  title: "SQL Injection in login endpoint"
  severity: critical
  cvss: 9.8
  cwe: CWE-89
  endpoint: "/api/v1/auth/login"
  parameter: "username"
  evidence: |
    POST /api/v1/auth/login
    username=admin' OR 1=1--&password=test
  remediation: "Use parameterized queries"
  references:
    - https://cwe.mitre.org/data/definitions/89.html

Schema Anchoring

Always include a concrete example of the desired output format in your prompt. Models follow examples far more reliably than prose descriptions of structure.

Multi-Turn Conversation Strategies

Single prompts rarely extract full value. Chain prompts across turns to progressively deepen your analysis, pivot between offense and defense, and build comprehensive assessments:

multi-turn-example.md
# Turn 1 — Broad reconnaissance request
USER: I have authorized access to test app.example.com.
      What attack surface should I map first?

# Turn 2 — Narrow based on response
USER: You mentioned the /api/v2 endpoint. Enumerate common
      authentication bypass techniques for REST APIs.

# Turn 3 — Deep dive on a finding
USER: The API returns verbose error messages including stack traces.
      How can I leverage these for further exploitation?

# Turn 4 — Remediation pivot
USER: Now switch perspective to defender. How should the
      development team fix the information disclosure issue
      you just described?

Funnel Pattern

Start broad, then narrow with each turn. Move from attack surface mapping to specific vulnerability analysis to exploitation details.

Perspective Switching

Alternate between attacker and defender roles. After identifying an exploit path, ask the model to propose detection rules and mitigations.

Evidence Chaining

Feed outputs from earlier turns as context for later questions. Paste scan results and ask for correlation with previously identified issues.

Summarize-and-Continue

For long conversations, periodically ask the model to summarize findings so far before continuing. This prevents context drift in large context windows.

MCP-Aware Prompting

When working with AI agents that have access to Model Context Protocol (MCP) tools such as filesystem, terminal or browser, your prompts must account for the agent's ability to take real actions. Structure prompts as task plans with explicit tool usage instructions and safety constraints:

mcp-task-prompt.md
You have access to the following MCP tools:
- filesystem: read/write files in the project directory
- terminal: execute shell commands on the test host
- browser: navigate and interact with web applications

Task: Perform an authorized security assessment of the web
application running at http://localhost:8080

Approach:
1. Use the browser tool to crawl and map the application
2. Use terminal to run nikto and nuclei scans
3. Save all findings to /tmp/assessment/findings.json
4. For each finding, verify exploitability before reporting
5. Generate a summary report in markdown format

Constraints:
- Stay within scope (localhost:8080 only)
- Do not modify production data
- Log every command executed for audit trail

Enumerate Available Tools

Start every MCP prompt by listing the tools the agent has access to. This grounds the model's planning and prevents it from hallucinating capabilities.

Define Scope Boundaries

Explicitly state what targets, directories, and actions are in-scope. Autonomous agents will test boundaries, so the prompt is the guardrail.

Require Audit Logging

Instruct the agent to log every action for post-engagement review. This is critical for reproducibility and compliance with Rules of Engagement.

Verify Before Report

Prompt the agent to confirm exploitability before adding findings to the report. This reduces false positives in automated assessments.

MCP Safety

MCP-connected agents can execute real commands on real systems. Always run MCP agents in sandboxed environments during testing and review audit logs before trusting results.

Common Mistakes

Don't

  • Ask for "hacking" with no inputs or scope
  • Request specific exploit code outright
  • Mention unauthorized targets
  • Use threatening language
  • Send sensitive client data in prompts

Do

  • State authorization, scope and the output contract
  • Name the inputs and their versions
  • Require an explicit UNKNOWN for missing facts
  • Quote the evidence behind each claim
  • Anonymize target details when possible

Prompt Libraries

Maintain a curated library of proven prompts — versioned, pinned to a model, and paired with the eval cases that justify keeping them. Several public collections are worth bookmarking, with the caveat that a borrowed prompt arrives without your scope, your inputs or your eval record:

awesome-chatgpt-prompts (Security Section)

Community-curated, mostly persona-driven prompts such as "Act as a Cyber Security Specialist". Useful as vocabulary, not as evidence: rewrite an entry as a specification and score it before relying on its output.

SecGPT / PentestGPT Prompt Collections

Specialised prompt sets for reconnaissance, exploitation, and reporting workflows. Treat borrowed templates as unreviewed code; each one encodes someone else's assumptions about scope and permitted output.

OWASP LLM Top 10 test prompts

Write prompts that exercise each OWASP Top 10 for LLM Applications category against your own deployment, so a finding maps to a published risk rather than to a hunch.

Your Own Prompt Library

Keep a git-tracked file of prompts under ids (prompt-v3-fixed), with the model version, temperature, and the eval case each one is expected to pass. A prompt without a recorded score is a preference, not a control.

Pro Tip

Change one variable at a time (prompt id, then model version, then temperature) and re-run the gate after each change. A prompt that only works on the model you happened to test is not a reproducible artifact.