# Proxy

Phantom's intercepting proxy is the entry point of most research
sessions. It is a forward HTTP and HTTPS proxy that runs inside the
backend, decrypts HTTPS with per-host certificates signed by a local CA,
and records every exchange into the active vault's HTTP history. From
there, History, Intercept, Repeater, Intruder, Comparer and agents all
work from the same captured requests.

This page covers running the proxy, setting up a browser, the listener
and its settings, how the proxy is built, and its security model. What is
stored for each request and how it is shown is in [HTTP history](./history.md).
Protocol-level behaviour and the full Intercept reference are in
[Protocol support](./protocols.md).

## Start capturing

The backend creates the proxy at startup but does not start the listener
on its own.

1. Open the **Proxy** page and press **Start**. The proxy listens on
   `127.0.0.1:8080` by default and captures into the active vault.
2. Download the CA certificate with **Download phantom-ca.pem** in the
   proxy settings, or from `http://127.0.0.1:8000/api/v1/proxy/ca.pem`
   (Docker: `http://127.0.0.1:3000/api/v1/proxy/ca.pem`). With the
   browser already going through the proxy, `http://phantom/` shows the
   same download. The CA is created on first use and also lives as
   `ca.pem` in the CA directory (`~/.ph-proxy` by default).

   The proxy's own address (`127.0.0.1:8080`) is not a website: opened in
   a browser it answers with that page and never forwards the request, so
   it cannot loop back into itself.
3. Trust it in the browser you test with:
   - **Firefox:** Settings > Privacy & Security > Certificates > View
     Certificates > Authorities > Import, then check "Trust this CA to
     identify websites".
   - **Chrome / Edge:** Settings > Privacy and security > Security >
     Manage certificates > Trusted Root Certification Authorities > Import.
   - **Windows, system-wide**, from an elevated prompt:

     ```powershell
     certutil -addstore Root phantom-ca.pem
     ```
4. Set the browser's HTTP and HTTPS proxy to the address shown in the
   proxy status, `127.0.0.1:8080` by default.
5. Check the CA: open `http://phantom/` in that browser. The page fetches
   `https://phantom/ca-check`, which the proxy answers itself with a
   certificate for `phantom` signed by its CA: the line turns green when
   the browser trusts the CA, and says so when it does not yet (reload
   after trusting it). Nothing is forwarded or captured. Outside the
   proxy, the page only explains how to run the check.

We recommend a dedicated browser profile used only for testing: it is the
safest place to trust the CA.

The CA is a 2048-bit RSA certificate with the common name `PhProxy CA`,
valid for ten years. Per-host certificates are valid for one year.

**Proxy › Settings › CA certificate** shows the CA's SHA-256 fingerprint
(compare it with what your browser lists) and its validity. It warns
when the CA should be replaced: when it was made by an older version
without a Subject Key Identifier, which strict clients such as Python
3.13 and later refuse, or when it expires within 30 days.
**Regenerate CA…** creates a new one after a confirmation. Sites are
signed by the new CA from the next connection on, so download it and
trust it again in every browser, and remove the old one from their
stores. Only you can regenerate the CA; agents cannot.

## Control the proxy

| Action | REST | Notes |
|---|---|---|
| Start | `POST /api/v1/proxy/start` with `{"vault_id": N}` | Binds the listener and captures into vault `N` |
| Stop | `POST /api/v1/proxy/stop` | Closes the listener and keeps the history |
| Switch vault | `PUT /api/v1/proxy/vault` | Sends future traffic to another vault without a restart |
| Status | `GET /api/v1/proxy/status` | `running`, the address to configure (`host`, `port`), the bind address (`bind_host`, `bind_port`), `vault_id`, `ca_cert_url`, the last bind `error`, `intercepting` and the number of `held` messages |
| CA | `GET /api/v1/proxy/ca.pem` | The public CA certificate as `phantom-ca.pem` |
| CA status | `GET /api/v1/proxy/ca` | `fingerprint`, `not_before`, `not_after`, `has_key_identifier`, and `renew` (why to replace it, or null) |
| Regenerate CA | `POST /api/v1/proxy/ca/regenerate` | Creates a new CA (user only) |

The same operations are available to agents through MCP tools, under the
`testing` grant.

### Listener settings

`GET /api/v1/proxy/settings` returns the bind `host` and `port`, the
offered `interfaces` (`127.0.0.1`, `::1` when IPv6 is available,
`0.0.0.0`, then the machine's network addresses), `configurable` and
`exposed`. `PUT /api/v1/proxy/settings` with `{"host", "port"}` accepts
only an offered address. If the proxy is running it moves to the new
address: held messages are forwarded first, and if the new address cannot
be bound the previous listener is restored and nothing is saved. The value
is stored under the `proxy.listen` setting and takes precedence over
`PROXY_HOST` and `PROXY_PORT` on the next start.

In Docker, `PROXY_ADVERTISE_HOST` fixes the bind address: `configurable`
is false and `PUT /proxy/settings` is rejected. The container binds
`0.0.0.0:8080`, the compose file publishes it only on the host's
`127.0.0.1`, and the status reports the advertised address.

### Upstream TLS

Upstream certificates are verified by default, for the proxy, replay and
scans. `GET` and `PUT /api/v1/proxy/tls` read and replace the shared
policy (`insecure_hosts`, `allow_insecure`, `ca_bundle`), saved under
`proxy.tls`. The running proxy applies a change to new upstream
connections at once. See [Upstream TLS verification](./protocols.md#upstream-tls-verification).

### Intercept

Intercept holds requests and responses so you can edit, forward or drop
them. Its switch is separate from starting the proxy, it can be limited to
in-scope hosts, filter rules narrow what is held, and a message nobody
decides on is forwarded unchanged after a timeout. Stopping or moving the
listener forwards held messages first. The full reference is in
[Intercept](./protocols.md#intercept).

### Configuration

Settings in `backend/app/config.py`, read from the environment:

| Setting | Default | Meaning |
|---|---|---|
| `PROXY_HOST` | `127.0.0.1` | Bind interface |
| `PROXY_PORT` | `8080` | Bind port |
| `PROXY_BODY_LIMIT` | `524288` (512 KiB) | Default stored bytes per body (overridden by `max_body_bytes` in `proxy.capture`); also the largest body editable in Intercept |
| `PROXY_INTERCEPT_TIMEOUT` | `300` s | Hold time before a message is forwarded unchanged |
| `PROXY_CA_DIR` | `~/.ph-proxy` | CA certificate and key directory |
| `PROXY_ADVERTISE_HOST` / `PROXY_ADVERTISE_PORT` | unset | Address users should configure when it differs from the bind address |

## Standalone relay

For debugging the proxy itself, the repository can run it without the
workstation. From the repository root:

```bash
make proxy
```

This listens on `127.0.0.1:8080` with the default CA directory and
verified upstream TLS. It has no vault, no capture and no Intercept: it
relays traffic and logs one line per request, for example:

```
GET http://example.com/ -> 200
CONNECT example.com:443 -> MITM tunnel established
GET /search?q=test (via example.com) -> HTTP/1.1 200 OK
```

## How it is built

```
Browser
   |  HTTP proxy 127.0.0.1:8080
   v
ProxyServer (aiohttp web.Server, raw handler)
   |
ProxyHandler
  |-- absolute-form HTTP --> aiohttp ClientSession --> upstream
  |-- CONNECT -------------> MITM TLS (CertManager) --> UpstreamConnection (TLS)
  |                          HTTP/1.x relayed and parsed by the handler
  |-- WebSocket upgrade ---> transport.tunnel
  |
  |-- Interceptor: hold request / response   -> InterceptRuntime
  '-- FlowSink: CapturedExchange when done   -> ProxyRuntime -> ProxyFlow
```

`backend/app/core/proxy/` knows nothing about the database, vaults or the
API. The runtime (`backend/app/runtime/proxy_runtime.py`) connects it to
storage and the event bus:

- The handler passes each finished exchange to `ProxyRuntime.submit()`,
  which queues it without blocking (queue limit 10,000; when the queue is
  full the flow is dropped and a warning is logged).
- A background writer stores up to 100 flows per batch, flags each one
  `in_scope` against the vault's scope rules and emits `proxy.flow` for
  that vault. Status changes are emitted as `proxy.status`.
- Events go over the WebSocket at `/api/v1/ws`. Vault events reach clients
  subscribed to that vault; `proxy.status` and the `intercept.*` events go
  to every client.

| Module in `core/proxy/` | Purpose |
|---|---|
| `capture.py` | `BodyBuffer` (size-capped body copy), `CapturedExchange` and the non-blocking `FlowSink` contract |
| `ca_store.py` | Loads or creates the root CA; writes the key atomically with restrictive permissions |
| `certs.py` | `CertManager`: per-host certificates and TLS contexts on the fly |
| `config.py`, `constants.py` | `ProxySettings`, buffer sizes, timeouts, body, decode and hold limits |
| `content.py` | Removes content codings for display only, with bounded decoders |
| `framing.py` | HTTP/1.x framing inside a tunnel and for messages edited in Intercept |
| `handler/` | `ProxyHandler`, split by concern: dispatch, plain HTTP, CONNECT, tunnel relay, holds, WebSocket capture, capture hooks |
| `intercept.py`, `intercept_rules.py` | Held messages, decisions and the filter rules that decide what is held |
| `interfaces.py` | Local addresses the listener may bind to, and whether an address is exposed |
| `server.py` | `ProxyServer` lifecycle for embedding, and `run()` for the standalone relay |
| `upstream.py`, `transport/` | Upstream TLS connections, response streaming, WebSocket relay |

The upstream certificate policy lives in `backend/app/core/tls/`, because
replay and the scan client use it too.

## Security

- **Loopback by default.** The proxy binds `127.0.0.1` unless you choose
  another address.
- **Exposure.** Binding to `0.0.0.0`, `::` or a LAN address makes the
  proxy reachable by other machines, and the interface warns (`exposed`
  in the listener settings). It never becomes an open proxy: other
  machines must authenticate with the user `phantom` and a password
  created the first time you choose such an address and kept after
  (`proxy_user`, `proxy_password` in the listener settings, shown in the
  Listener card with a copy button); without it they get `407 Proxy
  Authentication Required`. Your own browser on this machine never needs
  it. Agents never see the password. The local Docker setup fixes the
  address and asks for none, since it publishes the port on loopback
  only; `PROXY_REQUIRE_AUTH=true` makes it ask on every address.
- **CA private key.** `ca-key.pem` stays in the CA directory. The API
  serves only `ca.pem` and no endpoint exports the key. On Linux and macOS
  the key is written atomically with mode 0600 in a 0700 directory, and
  older files with wider permissions are tightened when loaded. On Windows
  the files inherit the ACL of the CA directory, which under the user
  profile grants access to the user, SYSTEM and Administrators; keep a
  custom `PROXY_CA_DIR` inside the profile.
- **The key is not encrypted at rest.** Encrypting it with a key the same
  process holds would not stop anyone who can read the CA directory.
  Anyone who can read the key can impersonate any site to a browser that
  trusts the CA, so protect the directory and do not trust the CA in your
  everyday browser profile. Storing the key in the OS keychain is on the
  roadmap.
- **Upstream TLS failures are never bypassed silently.** The client
  receives `502` with the reason and the flow or scan log records
  `Upstream TLS verification failed: ...`. Exceptions are explicit
  configuration only; use them for targets you are authorised to test.
- **Older CAs.** CAs created by early versions have no Subject Key
  Identifier. Browsers accept them, but strict verifiers (Python 3.13+
  clients, OpenSSL 3 `X509_STRICT`) reject their leaf certificates with
  "Missing Subject Key Identifier". Delete the CA directory to regenerate
  it, then import the new `ca.pem`.
- **Captured data is sensitive.** History stores cookies, tokens and
  bodies as captured. Views mask secrets, but the database holds them in
  plain form. Clearing a vault's history or deleting the vault removes its
  flows.
