# Intruder

An attack takes one request, marks where values go, and sends variations
of it built from payload sets, to see which response differs. It is a
research object of its vault: bound by the vault scope and by quotas
enforced in the backend, readable and exportable under the redaction
policies, and runnable by an agent through MCP within stricter quotas.

Design background: `design/intruder.md`. Payload sets read the shared
collections of [Payload collections](payloads.md).

## Model

**Attack** (`attacks`, cascades from the vault)

| Field | Notes |
|---|---|
| `name` | Defaults to `METHOD host/path`. |
| `scheme`, `host`, `port` | The endpoint requests go to, unless the request target is an absolute URL. |
| `template` | The raw request with positions marked (below). |
| `positions` | Parsed on save: `{name, start, end, char_start, char_end, base}`; byte offsets into the clean request and character offsets for editors. |
| `strategy` | `sniper`, `battering_ram`, `pitchfork`, `cluster_bomb`. |
| `payload_sets` | `[{position?, source, processing}]`, stored as given. |
| `matchers`, `options` | Stored as given, options with their defaults. |
| `status` | `draft`, `running`, `paused`, `completed`, `cancelled`, `failed`. |
| `total`, `sent`, `errors`, `matched` | `total` is exact; the counters count stored results. |
| `next_index` | Where a paused attack resumes. |
| `actor` | `user` (REST) or `agent` (MCP), set by the backend. |
| `source_flow_id` | The history flow the template came from (plain id). |
| `error` | Why it failed, or why it was paused by a stop or restart. |

**Result** (`attack_results`, cascades from the attack; unique per
`(attack_id, idx)`): the request index, `payloads` (`[{position, value,
captured}]`), the request sent (method, URL, headers, body), status code
(0 = none), response headers and body (capture body limit), length
(response body bytes), time, matched matcher ids, error, `sent` (false
when refused before sending) and attempts.

Migration: `e4b7d1a9c3f6_intruder_attacks` (after `c6d2a8f4e1b9`). It
also adds the flow source `INTRUDER` for results saved to history.

## Templates and positions

A position is the text between two `§`: `GET /item?id=§42§ HTTP/1.1`.
The marked text is the base value, sent whenever the strategy leaves the
position alone; `§§` is a pure insertion point. Positions are named by
order: `1`, `2`, ... (at most 32).

A literal `§` is `\§`. Backslashes are literal, except in a run that
ends at a `§`: there `\\` is one backslash and an odd one left over
escapes the `§`. Templates built by the backend (from a flow, or marked
with suggestions) are always escaped this way.

The rendered request is parsed as HTTP/1.x (CRLF or LF line endings,
body kept byte for byte). With `update_content_length` (default on),
Content-Length is replaced by the real body length. No client headers
are added (no User-Agent, Accept or Accept-Encoding): only a Host header
when the template has none, and Content-Length for a body.

**Auto** suggests query values, form fields of
`application/x-www-form-urlencoded` bodies, JSON scalars (strings
without quotes, numbers, booleans, null) and cookie values.

## Strategies

| Strategy | Requests | Order |
|---|---|---|
| `sniper` | sum of the set sizes of the positions | position 1 through its set, then 2, ...; the others keep their base |
| `battering_ram` | size of the one set | the same payload in every position |
| `pitchfork` | the smallest set size | item i of every set together |
| `cluster_bomb` | product of the set sizes | every combination; position 1 changes fastest |

Strategies are lazy generators that can start at any index in constant
time; nothing is materialised. Each set names the position it feeds;
a set without `position` is shared by every position without its own. A
battering ram uses the shared set, or else position 1's.

## Payload sets

Sources:

| `kind` | Fields | Values |
|---|---|---|
| `collection` | `collection_id` | A collection of the vault or the global library, read page by page; another vault's collection is `not_found`. |
| `list` | `values` | At most 10,000 values, 1,000,000 characters together. |
| `numbers` | `start`, `stop`, `step` (not 0), `format` | Inclusive range in either direction, Python format spec (`d`, `04d`, `x`, `08b`). |
| `null` | `count` | Empty payloads. |

Processing steps (`processing`, at most 16, in order, applied to the
payload, never the template): `prefix`/`suffix` (`value`), `replace`
(`find`, `replace`, `regex`; literal replacement, bounded regex),
`url_encode` (`all`), `url_decode`, `base64_encode`, `base64_decode`,
`hex_encode`, `hex_decode`, `case` (`upper`, `lower`), `hash` (`md5`,
`sha1`, `sha256`, `sha512`). A value that cannot be processed (invalid
base64, bytes that are not UTF-8, longer than 65,536 characters) is a
result with an error; it is not sent.

## Matchers

| `kind` | Fields | Matches when |
|---|---|---|
| `status` | `values` | the status is one of them |
| `length` | `min`, `max` | the response body length is within |
| `text` | `part` (`headers`, `body`, `any`), `mode` (`literal`, `regex`), `value`, `case_sensitive` | the text occurs |
| `time` | `above_ms` | the response took longer |

Each takes `negate` and an `id` (default `m1`, `m2`, ...). Bounds are
those of intercept rules: 512 characters per value, regex compiled on
save, 64 KiB window, 50 ms per search (a timeout is no match). The body
is matched with content codings removed.

## Options and quotas

| Option | Range | Default |
|---|---|---|
| `concurrency` | 1-20 | 4 |
| `rate` (requests/s) | 0.5-50 | 10 |
| `jitter_ms` | 0-10,000 | 0 |
| `timeout` (s, per attempt) | 1-120 | 30 |
| `retries` (network errors) | 0-5 | 1 |
| `follow_redirects` | up to 5 hops, each checked | off |
| `update_content_length` | | on |
| `auth_failures` | 0 to 1,000 | 20 |
| `session_profile_id` | a [session account](session-profiles.md) of the vault | none |

`auth_failures` pauses the attack when that many answers in a row are
401, 407, 419 or 440, the answers that say the session is not (or no
longer) accepted; 403 does not count, since a probe is often forbidden
on purpose. The attack is paused with the reason, and the requests not
sent yet wait: renew the session in the template or its account, then
resume. 0 never pauses.

`session_profile_id` (**Sign in as** in the attack options) signs every
request in as one of the vault's session accounts: its headers and the
cookies of its jar that match the request replace the template's own,
like a Repeater send. Results keep the template's request, without the
account's values. When `auth_failures` pauses an attack that signs in,
the account is also marked expired.

Quotas (`app/core/intruder/limits.py`): 100,000 requests per attack; 2
running attacks per vault; 100 requests/s across the workstation; 1,000
attacks per vault. An attack an agent starts: 10,000 requests and 10
requests/s. Quotas are checked before start (`estimate` reports the
same `problems`).

## Execution

- Every request is checked before it is sent: the destination host and
  the Host header host must be in the vault scope (re-read with every
  result write). A payload that moves either out of scope gives an error
  result and nothing is sent. With `follow_redirects`, every hop is
  checked the same way.
- Upstream certificates follow the `proxy.tls` policy, like replay; a
  verification failure is recorded with the proxy's message and never
  retried. Connections are pooled per attack.
- Network errors are retried up to `retries` times, each retry paced
  like a new request; an HTTP response is never retried.
- Rate: one token bucket per attack (even pacing, no burst) and one for
  the workstation. Concurrency: a semaphore per attack. Jitter delays
  each request by a random 0..`jitter_ms`.
- Responses keep at most the capture body limit and reserve the shared
  capture memory budget until they are written. Results are written in
  batches every 250 ms or 200 results.
- Pause stops issuing at once; requests in flight finish and are
  written; `next_index` is the first request not issued. Resume
  continues there. Cancel abandons requests in flight and keeps the
  results. Deleting an attack (or its vault) stops it.
- When the workstation stops, running attacks are marked `paused` at
  their first request not finished. On start, attacks a crash left
  `running` are marked `paused` at their first missing result, with the
  reason in `error`. Nothing resumes on its own; a resumed attack skips
  results already stored.

## REST

Paths are below `/api/v1/vaults/{vault_id}`.

| Route | Body / query | Response |
|---|---|---|
| `GET /attacks` | `status` | `[AttackSummary]`, newest first |
| `POST /attacks` | `AttackCreate` | `201 AttackRead` |
| `POST /attacks/positions` | `{template}` | `{text, positions, suggestions [{kind, key, start, end, value}], auto}` |
| `GET /attacks/{id}` | | `AttackRead` |
| `PATCH /attacks/{id}` | `name` any time; configuration of a draft only (409) | `AttackRead` |
| `DELETE /attacks/{id}` | | `204` |
| `POST /attacks/{id}/estimate` | | `Estimate` |
| `POST /attacks/{id}/start`, `pause`, `resume`, `cancel` | | `AttackRead` |
| `GET /attacks/{id}/results` | `after`, `sort` (`index`, `status`, `length`, `time`), `order`, `limit` (1-1000), `status` (repeat; 0 = none), `matched`, `error`, `search` | `{attack_id, items, next_cursor}` |
| `GET /attacks/{id}/results/export` | `format` (`csv`, `jsonl`), the filters, `reveal` | file |
| `GET /attacks/{id}/results/{index}` | | `ResultDetail` |
| `POST /attacks/{id}/results/{index}/save` | | `201 FlowDetail` (`source: intruder`) |

`AttackCreate`: `{template, scheme, host, port}` or `{flow_id}` (the
flow's request as an escaped HTTP/1.1 template, pseudo-headers dropped;
a truncated or non-UTF-8 body is refused), plus `name`, `auto_mark`,
`strategy`, `payload_sets`, `matchers`, `options`.

```json
{"scheme": "https", "host": "shop.test", "port": 443, "strategy": "sniper",
 "template": "GET /item?id=§1§ HTTP/1.1\r\nHost: shop.test\r\n\r\n",
 "payload_sets": [{"source": {"kind": "numbers", "start": 1, "stop": 500}, "processing": [{"op": "prefix", "value": "0"}]}],
 "matchers": [{"kind": "status", "values": [200]}, {"kind": "text", "value": "admin", "id": "admin"}],
 "options": {"concurrency": 4, "rate": 10}}
```

`AttackRead` adds to the summary `template`, `positions`,
`payload_sets`, `matchers`, `options`. The summary carries `rate`
(achieved requests/s while running) and `active` (a run still has
requests in flight or results to write).

`Estimate`: `{total, strategy, positions [{name, base, set, count}],
sets [{key, kind, count, steps, collection_id, collection_name}],
warnings, problems, can_start, seconds, quota {max_requests, max_rate,
agent}}`. Start answers `422` with `details.problems` when there are any,
`409` with `details.limit` when the vault runs two attacks, and
`out_of_scope` when the endpoint host is out of scope.

Result summary: `{index, payloads, method, url, status_code, length,
duration_ms, matched, error, sent, attempts}`. The detail adds request
and response headers and bodies (shared `MessageBody`), sizes, flags,
`mime_type`, `observed_at`.

Exports follow the export redaction policy (`redact` by default, `ask`
needs `reveal=true|false`, `409` without it, `403` for `reveal=true`
under `redact`, `X-Phantom-Redacted`). CSV columns: `index`,
`payload_<position>`..., `method`, `url`, `status_code`, `length`,
`duration_ms`, `matched`, `error`, `sent`, `attempts`.

`GET/PUT /api/v1/settings/intruder` `{agents: allowed | preview}`: user
only (refused for agent calls and requests with MCP transport headers).

## Events

| Event | Data |
|---|---|
| `attack.updated` | `{action, attack}`: `created`, `updated`, `started`, `resumed`, `paused`, `cancelled`, `completed`, `failed`, `deleted` with the summary; `progress` (at most every 0.5 s) with `{id, vault_id, status, total, sent, errors, matched, rate}` |
| `attack.results` | `{attack_id, added, sent, errors, matched, last_index}` per write |

Events never carry payloads, templates or responses.

## MCP

| Tool | REST equivalent |
|---|---|
| `attack_create` | `POST /attacks` |
| `attack_estimate` | `POST .../estimate` (agent quota) |
| `attack_start`, `attack_pause`, `attack_cancel` | `.../start`, `pause`, `cancel` |
| `attack_get` | `GET /attacks/{id}` |
| `attack_results`, `attack_result_get` | `GET .../results`, `.../results/{index}` |

Agents get the agent quotas whoever created the attack. With
`intruder.agents = preview`, `attack_start` is refused
(`permission_denied`); create, estimate, pause, cancel and reads work.
Resume, delete and saving to history are user actions. For an attack an
agent created or started, every request to the workstation's own API
or MCP endpoint on this machine (loopback, its interface addresses or a
name resolving to them) is refused, after resolving dot segments and
percent-encoding.

Outputs follow the MCP redaction policy: the template and position base
values are redacted as text, payload sets and matchers as data; result
URLs, errors, headers and bodies like a flow (bodies before clipping). A
payload taken from a collection item lifted from captured traffic is
masked whole wherever it appears. A template or payload that contains a
redaction placeholder is refused; pass `flow_id` to use the stored
request.

## Interface

Intruder is a Proxy tool next to Repeater (`components/proxy/intruder/`).

- **Entry points:** "Send to Intruder" in the History row menu, the
  Intruder button of the request panel (both create a draft from the
  flow with `flow_id` and Auto marking) and of Repeater (the tab's raw
  request, escaped, to the endpoint the tab resolves to). The vault's
  attacks are listed in the Proxy sidebar with a status dot and progress;
  "Blank attack" starts one from scratch. Right click an attack in the
  sidebar (or Shift+F10 on it) to open it, rename it in place (F2),
  duplicate it as a draft, pause, resume or cancel it, copy its link
  (`[[attack:<id>]]`), attach it to the agent conversation, or delete it
  after a confirmation in the row (Delete).
- **Setup (drafts):** the endpoint and the template, with positions
  highlighted in the accent colour. Select text and press `§` (or Add §)
  to mark it; Auto replaces the marks with the backend's suggestions;
  Clear removes them. The strategy is a segmented control with a one-line
  explanation; sniper and battering ram get one shared payload set,
  pitchfork and cluster bomb one per position. Each set picks a
  collection (searchable, with counts), an inline list, a number range or
  empty payloads, plus processing steps as chips (add, edit, reorder,
  remove). Matchers are written as sentences in the rule style; options
  are clamped to the backend ranges. Changes save after a short pause and
  the backend estimate (total, time, warnings, problems, quota) follows
  every save; Start stays disabled with the reasons while the estimate
  says it cannot start. An attack that ran is read-only, with "New draft
  from this".
- **Run:** Start, Pause, Resume (enabled once requests in flight are
  written), Cancel and Delete (confirmed in place) in the header, with
  sent of total, rate, errors and matched over a progress bar, live from
  `attack.updated`.
- **Results:** a windowed table (index, payloads, status, length, time,
  matched, error) sorted and filtered on the backend (status codes,
  matched only, errors only, payload search) and reloaded at most once a
  second on `attack.results`. The selected result shows its request and
  response in the shared message viewer with the payload values marked.
  The row menu opens the result in Repeater, compares it with the base
  request in the Comparer, saves it to history, adds its payloads to a
  collection, or opens "Record finding" prefilled. Export offers CSV or
  JSON lines of the filtered results, masked always and as captured only
  when the export policy allows it; it is probed first, so policy and
  limit errors show as a toast.
- **Settings > Privacy > Agents and Intruder:** `intruder.agents`
  (`allowed` or `preview`), saved at once.
