← MITM proxy
MITM·Guide
All tools

MITM Proxy

An interception proxy that runs in the page: SSL 3.0 through TLS 1.3, HTTP/1.1 and HTTP/2 are handled here, and the local agent only carries the TCP connections. It shows every request an app makes (headers, bodies, timings), lets you send one again with changes (Repeater) or many times with payloads (Intruder), and exports the traffic as HAR.

The proxy's settings live on the Settings page, under MITM proxy: the address and port it listens on, the transparent listeners (443 and 80), the certificate authority (download it, or make a new one) and the pass-through list. They are kept in this browser's localStorage by the MitmConfig class, so the proxy page and the Settings page share them and see each other's changes.

Contents

  1. How interception works
  2. The libraries, as modules
  3. ByteStream (lib/byte-stream.js)
  4. Tls13 (lib/crypto/tls/tls13.js)
  5. Http1, Hpack, Http2Connection (lib/http.js)
  6. MitmProxy (lib/mitm-proxy.js)
  7. CraftedRequest and Intruder (lib/http-craft.js)
  8. MitmConfig (lib/mitm-config.js)
  9. Certificates: CertificateAuthority (lib/x509.js)

1How interception works

A client reaches the proxy in one of three ways: as an explicit proxy (the device's Wi-Fi proxy setting; HTTPS arrives as CONNECT host:443), through the transparent TLS listener on 443 (the DNS Server sends the app's names to this computer; the server name comes from the TLS ClientHello's SNI), or through the transparent HTTP listener on 80 (the server comes from the Host header).

For TLS, the proxy reads the ClientHello without consuming it. A host on the pass-through list is relayed untouched (a tunnel), as is an SSL 2.0 client (recognised, but not intercepted — our SSL 2.0 support is client-only). Otherwise the proxy intercepts SSL 3.0, TLS 1.0, 1.1, 1.2 and 1.3: it answers the handshake itself with a certificate for that name, made on the spot and signed by its own certificate authority, and opens its own TLS connection to the real server. The leaf is an ECDSA certificate for TLS 1.3 and the ECDHE_ECDSA suites, or a minted RSA certificate for the RSA-key-exchange and ECDHE_RSA suites that older clients ask for (both chain to the same CA). Apps that don't trust the CA, or that pin their server's certificate, abort the handshake with an alert: the page lists them under TLS and connection events, with a button to pass the host through.

Upstream, the proxy prefers TLS 1.3 and falls back to TLS 1.2 or older when the server can't do 1.3, so it reaches any server. The agent only carries the plain TCP; all of the TLS, both facing the client and facing the server, runs in the page.

Each side speaks the protocol it chose with ALPN: an app on HTTP/2 can be served while the server is reached over HTTP/1.1, and the reverse. Bodies are kept up to 2 MB per request.

2The libraries, as modules

Everything below is in lib/, as JavaScript modules with no user interface: a page (or a test, or a worker) imports the classes it uses, and each module imports its own dependencies. The pages are served over http, so a <script type="module"> works anywhere.

import { Agent } from "../lib/agent.js";
import { MitmProxy } from "../lib/mitm-proxy.js";
import { MitmConfig } from "../lib/mitm-config.js";
import { CraftedRequest, Intruder } from "../lib/http-craft.js";

3ByteStream (lib/byte-stream.js)

import { ByteStream } from "../lib/byte-stream.js"; (no dependencies) turns anything that delivers chunks, such as an agent socket or a TLS connection, into a stream that protocol readers can ask for exactly the bytes they need.

MethodWhat it does
new ByteStream(source)A stream over { ondata, onclose, send(bytes) → Promise, close() }; the stream sets ondata and onclose itself (an agent socket has this shape).
stream.read(count)Exactly count bytes; rejects if the stream ends first.
stream.some()Whatever is buffered (at least one byte), or null at the end.
stream.unshift(bytes), stream.buffered()Puts bytes back in front (after peeking at them); the number of bytes waiting.
stream.write(bytes), stream.close(), stream.closed, stream.oncloseWriting, closing, and the end of the stream (onclose(reason) once).
ByteStream.concat(...arrays)One Uint8Array with all of them in order.

4Tls13 (lib/crypto/tls/tls13.js)

import { Tls13, TlsAlert, TlsConnection } from "../lib/crypto/tls/tls13.js"; is TLS 1.3 (RFC 8446) over a ByteStream, with WebCrypto, both as a server and as a client (it imports lib/byte-stream.js, and lib/asn1.js to encode ECDSA signatures). It supports TLS_AES_128_GCM_SHA256 (the cipher suite every TLS 1.3 peer must support), X25519 and P-256 key exchange (with a HelloRetryRequest when needed), ECDSA P-256 server certificates, ALPN and KeyUpdate; not resumption, 0-RTT, client certificates or TLS 1.2. The client accepts any server certificate, as an interception proxy does.

The other SSL/TLS versions live beside it in lib/crypto/tls/: ssl3.js, tls10.js, tls11.js and tls12.js (client and server), ssl2.js (client, detect-only), and a Tls dispatcher in tls.js that peeks the ClientHello and negotiates the version. They mirror this API, do TLS in the browser over the agent’s plain TCP (the agent speaks no TLS), and support legacy and weak suites (RC4, 3DES, CBC, SSL 3.0) on purpose, for analysis. The proxy uses this Tls dispatcher: it intercepts SSL 3.0 through TLS 1.3 facing the client, and negotiates up to TLS 1.3 (with a ≤ 1.2 fallback) facing the server.

MethodWhat it does
Tls13.peekHello(stream){ sni, alpn, versions, tls13 } from the first ClientHello, which is put back; null when the stream isn't TLS.
Tls13.server(stream, { certFor(sni), alpn(offered) })Answers a handshake and resolves with a TlsConnection. certFor returns { chain: [der…], key } (an ECDSA P-256 CryptoKey); alpn picks a protocol or returns null.
Tls13.client(stream, { sni, alpn })Makes a handshake; the TlsConnection's peerChain has the server's certificates, clientCertRequested says whether it asked for one.
TlsConnectionondata(bytes), onclose(reason), write(bytes), close() (close_notify), closed, and alpn, sni, cipher, group, version. new ByteStream({ set ondata(f), set onclose(f), send, close }) makes it a stream again.
TlsAlert, Tls13.ALERTThe error a failed handshake throws (alert, alertName, sent), and the alert names by code.
Tls13.hkdfExtract(salt, keyMaterial), Tls13.hkdfExpandLabel(secret, label, context, length)The key schedule's building blocks (HKDF with SHA-256); they reproduce the secrets of RFC 8448's traces.
import { ByteStream } from "../lib/byte-stream.js";
import { Tls13 } from "../lib/crypto/tls/tls13.js";

const raw = new ByteStream(await agent.tcpConnect("example.com", 443));
const tls = await Tls13.client(raw, { sni: "example.com", alpn: ["http/1.1"] });
tls.ondata = (bytes) => console.log(new TextDecoder().decode(bytes));
await tls.write(new TextEncoder().encode("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"));

5Http1, Hpack, Http2Connection (lib/http.js)

import { HttpHeaders, Http1, Hpack, HpackDecoder, Http2Connection } from "../lib/http.js"; reads and writes HTTP/1.1 (RFC 9112), HPACK (RFC 7541) and HTTP/2 (RFC 9113) over ByteStreams. It imports lib/byte-stream.js and lib/hpack-huffman.js (HpackHuffman: the Huffman code table of RFC 7541 Appendix B, CODES[byte], LENGTHS[byte], END_OF_STRING). Headers are lists of [name, value] pairs.

MethodWhat it does
HttpHeaders.get(headers, name)The first value of a header, in any case, or null.
Http1.readHead(stream, isRequest)A request head { method, target, version, headers, raw } or response head { version, status, reason, headers, raw }; null at a clean end.
Http1.readBody(stream, head, { isRequest, requestMethod }, onChunk)The body (chunked, Content-Length, or until the end), piece by piece; resolves with the trailers.
Http1.headBytes(firstLine, headers), Http1.chunk(bytes), Http1.lastChunk(trailers)Writing heads and chunked bodies.
new HpackDecoder(), decoder.decode(block)A decoder that keeps its dynamic table between header blocks (one per connection).
Hpack.encode(headers), Hpack.huffmanDecode(bytes), Hpack.STATIC_TABLEA header block of literals; Huffman decoding; the 61 static entries.
new Http2Connection(stream, role)An HTTP/2 connection, "server" or "client": request(headers, end), onstream(stream), onclose, close(), closed. Settings, flow control, PING, GOAWAY and CONTINUATION are handled; server push is refused.
Http2Streamlisten({ headers, info, data, trailers, end, reset }), sendHeaders(headers, end), sendData(bytes, end), reset(code), headers, ended.
import { HttpHeaders, HpackDecoder, Http2Connection } from "../lib/http.js";

const decoder = new HpackDecoder();
decoder.decode(bytesOfHeaderBlock);   // [[":method", "GET"], [":path", "/"], …]

const h2 = new Http2Connection(tlsStream, "client");
const request = h2.request([[":method", "GET"], [":scheme", "https"], [":authority", "example.com"], [":path", "/"]], true);
request.listen({ headers: (headers) => console.log(HttpHeaders.get(headers, ":status")), data: (bytes) => {}, end: () => h2.close() });

6MitmProxy (lib/mitm-proxy.js)

import { MitmProxy } from "../lib/mitm-proxy.js"; is the proxy engine, with no user interface: it takes an agent connection and callbacks and reports each request as a flow. It imports lib/byte-stream.js, lib/crypto/tls/tls13.js, lib/http.js and lib/x509.js.

MethodWhat it does
new MitmProxy({ agent, ca, passThrough, onflow, onevent })A proxy. agent has tcpListen(host, port) and tcpConnect(host, port, timeout) (an Agent from lib/agent.js, or a fake for tests); ca is a CertificateAuthority (or { certificateDer, privateKey, keyId }; not needed to only send requests); passThrough(host) says which hosts not to intercept; onflow(flow) is called each time a request changes, onevent(event) for connection events (kind "info", "warn", "error" or "reject").
proxy.listen(kind, host, port)"proxy" (explicit: CONNECT and absolute URLs), "tls" (transparent, by SNI) or "http" (transparent, by Host); resolves with the address.
proxy.send(request, { http2, client, timeout })Sends a request made here ({ scheme, host, port, method, path, headers, body, hostHeader }) and resolves with its finished flow.
proxy.certFor(host)The ECDSA certificate chain and key the proxy shows for a host (for TLS 1.3 and the ECDHE_ECDSA suites; one leaf key, one certificate per host).
proxy.rsaCertFor(host)Its RSA certificate chain and key (for the RSA-key-exchange and ECDHE_RSA suites older clients ask for; one 2048-bit leaf key, one certificate per host). Both leaves chain to the same CA.
proxy.stop()Closes the listeners and the connections to servers.
flow{ id, time, client, proto, scheme, host, port, method, path, reqHeaders, reqBody, status, resHeaders, resBody, resTrailers, upstreamProto, upstreamTls, state, error, ms, ttfb, reqSize, resSize }; state is "pending", "done", "error" or "tunnel".
import { Agent } from "../lib/agent.js";
import { MitmProxy } from "../lib/mitm-proxy.js";
import { MitmConfig } from "../lib/mitm-config.js";

const proxy = new MitmProxy({
	agent: await Agent.connectSaved(),
	ca: await MitmConfig.authority(),
	passThrough: MitmConfig.passThroughMatcher(),
	onflow: (flow) => console.log(flow.method, flow.host + flow.path, flow.status || flow.state),
	onevent: (event) => console.log(event.kind, event.text),
});
await proxy.listen("proxy", "0.0.0.0", 8080);

7CraftedRequest and Intruder (lib/http-craft.js)

import { CraftedRequest, Intruder } from "../lib/http-craft.js"; (no dependencies) is the Repeater's and the Intruder's non-visual part: requests written as HTTP/1.1 text, and attacks that fill marked positions (§value§) with payloads.

MethodWhat it does
CraftedRequest.parseTarget(text), CraftedRequest.targetText(target)"https://host:port", "host:port" or "host" ↔ { scheme, host, port }.
CraftedRequest.parse(text){ method, path, version, headers, body }, or { error } saying which line is wrong.
CraftedRequest.build(text, target, fixLength)A request for proxy.send(); fixLength sets Content-Length to the body's size.
CraftedRequest.fromFlow(flow){ target, text }: a captured request as editable text.
Intruder.positions(template), Intruder.fill(parts, values), Intruder.clearMarks(text), Intruder.autoMark(text), Intruder.MARKThe marked positions and their original values; a template filled in; marks removed; query parameters, cookies, form and JSON fields marked automatically; the mark (§).
Intruder.total(type, count, sets), Intruder.attack(type, originals, sets)How many requests, and a generator of their values, for "sniper", "ram" (battering ram), "pitchfork" and "cluster" (cluster bomb).
Intruder.listPayloads(text), Intruder.numberPayloads({ from, to, step, width, hex })Payload sets: one per line, or a range of numbers (at most Intruder.CAP, 1,000,000).
Intruder.process(payload, { prefix, suffix, encode }), Intruder.ENCODINGSA payload with prefix and suffix, encoded: none, url, urlall, base64, hex, html.
Intruder.matcher(query)A test for "text" or "/regex/flags" (to flag responses); null when empty or invalid.
import { CraftedRequest, Intruder } from "../lib/http-craft.js";

const template = Intruder.positions(Intruder.autoMark("GET /item?id=7 HTTP/1.1\nHost: shop.test\n\n"));
for (const attempt of Intruder.attack("sniper", template.originals, [["1", "2", "' OR 1=1"]])) {
	const request = CraftedRequest.build(Intruder.fill(template.parts, attempt.values), "https://shop.test", true);
	const flow = await proxy.send(request);
}

8MitmConfig (lib/mitm-config.js)

import { MitmConfig } from "../lib/mitm-config.js"; keeps the proxy's settings in localStorage (keys mitm.v1, mitm.passthrough, mitm.ca.v1) and makes the certificate authority on first use. It imports lib/x509.js, lib/base64.js, lib/bytes.js and lib/pem.js. The MITM Proxy page and the Settings page both use it; every method is static.

MethodWhat it does
MitmConfig.options(), MitmConfig.setOptions(changes), MitmConfig.DEFAULTS{ bind, port, transparent }; defaults 0.0.0.0, 8080, not transparent.
MitmConfig.passThroughText(), MitmConfig.setPassThroughText(text), MitmConfig.addPassThrough(host)The pass-through list, one host per line; *.example.com covers a domain.
MitmConfig.passThroughMatcher()A test (host) → bool for the current list.
MitmConfig.authority(), MitmConfig.newAuthority()The CA, a CertificateAuthority with two more fields, created and stored, loaded or made (ECDSA P-256, 10 years; the key is stored as a JWK and imported as non-extractable); a new one replacing it.
MitmConfig.authorityInfo(authority), MitmConfig.authorityPem(authority){ subject, notAfter, sha256, stored } for display; the certificate as PEM.
MitmConfig.onChange(handler), MitmConfig.STORAGE_KEYShandler(what) when another tab changes "options", "passthrough", "ca" (or "all"); the storage keys.
import { MitmConfig } from "../lib/mitm-config.js";

const authority = await MitmConfig.authority();
console.log(MitmConfig.authorityInfo(authority).sha256, MitmConfig.options().port);

9Certificates: CertificateAuthority (lib/x509.js)

The certificates are made by lib/x509.js (import { CertificateAuthority, X509Certificate } from "../lib/x509.js";, the same library the Certificates tool reads with; see its guide), with WebCrypto ECDSA P-256 keys and SHA-256 signatures, encoded with Der (lib/asn1.js). For old clients the CA also issues leaves that carry an RSA public key (issueServerCertificateForRsa, from an RsaKey in lib/crypto/rsa.js); the CA key stays ECDSA, so an RSA leaf under an ECDSA CA is a valid mixed chain.

MethodWhat it does
CertificateAuthority.create(commonName, { organization, validityDays })A self-signed CA (Basic Constraints CA and Key Usage keyCertSign + cRLSign, both critical; a Subject Key Identifier), valid from a day ago for 3650 days by default: a CertificateAuthority with certificateDer, privateKey, publicKey, jwk, keyId.
new CertificateAuthority({ certificateDer, privateKey, keyId })An authority stored earlier, with its key imported again.
authority.issueServerCertificate(host, leafKeyPair, { validityDays })A server certificate for a host name or IPv4 address (CN and a dNSName or iPAddress alternative name, digitalSignature, serverAuth, key identifiers), 365 days by default: iOS refuses longer ones from a user-installed CA. Resolves with the DER.
import { CertificateAuthority } from "../lib/x509.js";
import { Pem } from "../lib/pem.js";

const authority = await CertificateAuthority.create("My Test CA", { organization: "Example" });
const leafKey = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
const der = await authority.issueServerCertificate("api.example.com", leafKey);
console.log(Pem.encode("CERTIFICATE", der));   // openssl verify -CAfile ca.pem leaf.pem: OK