An interactive, SSL/TLS-capable intercepting proxy for HTTP/1, HTTP/2, and WebSockets.
npx @tessl/cli install tessl/pypi-mitmproxy@12.1.00
# mitmproxy
1
2
A comprehensive HTTP/HTTPS/WebSocket proxy toolkit providing interactive proxy capabilities with real-time traffic interception, analysis, and modification. mitmproxy supports HTTP/1, HTTP/2, HTTP/3, and WebSocket protocols with full SSL/TLS capabilities, making it an essential tool for debugging, testing, and security analysis of web applications and APIs.
3
4
## Package Information
5
6
- **Package Name**: mitmproxy
7
- **Language**: Python
8
- **Installation**: `pip install mitmproxy`
9
- **Python Requirements**: Python 3.12+
10
11
## Core Imports
12
13
For HTTP flow handling:
14
15
```python
16
from mitmproxy import http
17
from mitmproxy.http import HTTPFlow, Request, Response, Headers
18
```
19
20
For flow management:
21
22
```python
23
from mitmproxy import flow
24
from mitmproxy.flow import Flow, Error
25
```
26
27
For connection handling:
28
29
```python
30
from mitmproxy import connection
31
from mitmproxy.connection import Client, Server, ConnectionState
32
```
33
34
## Basic Usage
35
36
### Running mitmproxy Tools
37
38
mitmproxy provides three main command-line interfaces:
39
40
```bash
41
# Interactive console interface
42
mitmproxy
43
44
# Command-line dump tool
45
mitmdump
46
47
# Web-based interface
48
mitmweb
49
```
50
51
### Basic HTTP Flow Interception
52
53
```python
54
from mitmproxy import http
55
56
def request(flow: http.HTTPFlow) -> None:
57
"""Intercept and modify HTTP requests."""
58
# Log all requests
59
print(f"Request: {flow.request.method} {flow.request.url}")
60
61
# Modify request headers
62
flow.request.headers["X-Custom-Header"] = "Modified"
63
64
# Block specific requests
65
if "example.com" in flow.request.url:
66
flow.response = http.Response.make(403, b"Blocked")
67
68
def response(flow: http.HTTPFlow) -> None:
69
"""Intercept and modify HTTP responses."""
70
# Log responses
71
print(f"Response: {flow.response.status_code} for {flow.request.url}")
72
73
# Modify response content
74
if flow.response.headers.get("content-type", "").startswith("application/json"):
75
# Parse and modify JSON responses
76
data = flow.response.json()
77
data["intercepted"] = True
78
flow.response.set_text(json.dumps(data))
79
```
80
81
### Working with Flows Programmatically
82
83
```python
84
from mitmproxy import io, http
85
86
# Read flows from file
87
with open("flows.mitm", "rb") as f:
88
reader = io.FlowReader(f)
89
for flow in reader.stream():
90
if isinstance(flow, http.HTTPFlow):
91
print(f"{flow.request.method} {flow.request.url}")
92
93
# Write flows to file
94
flows = [] # List of flows to save
95
with open("output.mitm", "wb") as f:
96
writer = io.FlowWriter(f)
97
for flow in flows:
98
writer.add(flow)
99
```
100
101
## Architecture
102
103
mitmproxy uses an event-driven architecture built around several key components:
104
105
- **Master**: Central orchestrator managing the proxy server and addon system
106
- **Flow Types**: Protocol-specific flow representations (HTTP, TCP, UDP, WebSocket)
107
- **Addon System**: Extensible plugin architecture for custom functionality
108
- **Connection Management**: Client/server connection abstraction and state tracking
109
- **Certificate Management**: Dynamic SSL/TLS certificate generation and validation
110
111
The addon system provides hooks at every stage of the proxy lifecycle, enabling comprehensive traffic analysis, modification, and custom protocol handling.
112
113
## Capabilities
114
115
### HTTP Flow Management
116
117
Core HTTP proxy functionality including request/response interception, modification, and analysis. Supports HTTP/1, HTTP/2, and HTTP/3 protocols with comprehensive header and content manipulation.
118
119
```python { .api }
120
class HTTPFlow(Flow):
121
request: Request
122
response: Optional[Response]
123
error: Optional[Error]
124
125
class Request:
126
def __init__(self, host: str, port: int, method: bytes, scheme: bytes, authority: bytes, path: bytes, http_version: bytes, headers: Headers, content: bytes, trailers: Optional[Headers], timestamp_start: float, timestamp_end: Optional[float]) -> None: ...
127
128
class Response:
129
def __init__(self, http_version: bytes, status_code: int, reason: bytes, headers: Headers, content: bytes, trailers: Optional[Headers], timestamp_start: float, timestamp_end: float) -> None: ...
130
```
131
132
[HTTP Flow Management](./http-flows.md)
133
134
### Connection Management
135
136
Client and server connection handling with support for transparent proxying, upstream proxies, and complex network topologies. Includes TLS/SSL certificate management and protocol detection.
137
138
```python { .api }
139
class Client(Connection):
140
address: Optional[Address]
141
tls_established: bool
142
certificate_list: Sequence[x509.Certificate]
143
alpn: Optional[bytes]
144
cipher: Optional[str]
145
146
class Server(Connection):
147
address: Optional[Address]
148
tls_established: bool
149
certificate_list: Sequence[x509.Certificate]
150
alpn: Optional[bytes]
151
cipher: Optional[str]
152
```
153
154
[Connection Management](./connections.md)
155
156
### Multi-Protocol Support
157
158
TCP, UDP, and WebSocket flow handling beyond HTTP, enabling comprehensive network traffic analysis and modification for various protocol types.
159
160
```python { .api }
161
class TCPFlow(Flow):
162
messages: List[TCPMessage]
163
164
class UDPFlow(Flow):
165
messages: List[UDPMessage]
166
167
class WebSocketMessage:
168
type: int
169
content: bytes
170
from_client: bool
171
timestamp: float
172
```
173
174
[Multi-Protocol Support](./protocols.md)
175
176
### Flow I/O and Persistence
177
178
Reading and writing flows to files for replay, analysis, and testing. Supports filtering and format conversion for various use cases.
179
180
```python { .api }
181
class FlowReader:
182
def __init__(self, fo: BinaryIO) -> None: ...
183
def stream(self) -> Iterator[Flow]: ...
184
185
class FlowWriter:
186
def __init__(self, fo: BinaryIO) -> None: ...
187
def add(self, flow: Flow) -> None: ...
188
189
def read_flows_from_paths(paths: Sequence[str]) -> Iterator[Flow]: ...
190
```
191
192
[Flow I/O](./flow-io.md)
193
194
### Configuration and Options
195
196
Comprehensive configuration system with type-safe options for proxy behavior, TLS settings, network configuration, and addon parameters.
197
198
```python { .api }
199
class Options:
200
def __init__(self, **kwargs) -> None: ...
201
def set(self, key: str, value: Any) -> None: ...
202
def get(self, key: str) -> Any: ...
203
204
# Key configuration constants
205
CONF_DIR: str = "~/.mitmproxy"
206
CONF_BASENAME: str = "mitmproxy"
207
KEY_SIZE: int = 2048
208
```
209
210
[Configuration](./configuration.md)
211
212
### Addon Development
213
214
Extensible addon system for custom functionality with lifecycle hooks, event handling, and access to all proxy components. Includes built-in addons for common use cases.
215
216
```python { .api }
217
def default_addons() -> List[Any]: ...
218
219
# Decorator for concurrent addon execution
220
def concurrent(func: Callable) -> Callable: ...
221
222
# Context access for addons
223
import mitmproxy.ctx as ctx
224
```
225
226
[Addon Development](./addons.md)
227
228
### Content Processing
229
230
Flexible content viewing, transformation, and analysis with support for various data formats and encoding schemes. Includes syntax highlighting and interactive content exploration.
231
232
```python { .api }
233
class Contentview:
234
name: str
235
content_types: List[str]
236
237
def add(view: Contentview) -> None: ...
238
239
# Encoding utilities
240
def encode(data: bytes, encoding: str) -> bytes: ...
241
def decode(data: bytes, encoding: str) -> bytes: ...
242
```
243
244
[Content Processing](./content.md)
245
246
### Command System
247
248
Type-safe command framework for interactive control and automation. Supports complex command composition and validation with built-in commands for all major operations.
249
250
```python { .api }
251
class CommandManager:
252
def execute(self, cmdstr: str) -> Any: ...
253
def call(self, path: str, *args: Any) -> Any: ...
254
255
# Type system for commands
256
class TypeManager:
257
def command(self, name: str) -> Callable: ...
258
```
259
260
[Command System](./commands.md)
261
262
## Entry Points
263
264
mitmproxy provides three main entry points:
265
266
- `mitmproxy.tools.main:mitmproxy` - Interactive console interface with full-screen TUI
267
- `mitmproxy.tools.main:mitmdump` - Command-line interface for scripted operations
268
- `mitmproxy.tools.main:mitmweb` - Web-based interface accessible via browser
269
270
Each entry point provides the same core functionality with different user interfaces optimized for specific use cases.