0
# Connection Management
1
2
Client and server connection handling with comprehensive support for TLS/SSL, transparent proxying, upstream proxies, and complex network topologies. Provides detailed connection state tracking and certificate management.
3
4
## Capabilities
5
6
### Connection Base Class
7
8
Abstract base class for all connection types providing common connection attributes and state management.
9
10
```python { .api }
11
class Connection:
12
"""
13
Abstract base class for client and server connections.
14
15
Attributes:
16
- id: Unique connection identifier
17
- address: Network address (host, port) or None
18
- state: Current connection state flags
19
- error: Connection error information if failed
20
- tls_established: Whether TLS handshake completed
21
- certificate_list: List of certificates in TLS chain
22
- alpn: Application Layer Protocol Negotiation result
23
- cipher: TLS cipher suite in use
24
- sni: Server Name Indication from TLS handshake
25
- timestamp_start: Connection establishment start time
26
- timestamp_tls_setup: TLS handshake completion time
27
- timestamp_end: Connection termination time
28
"""
29
id: str
30
address: Optional[Address]
31
state: ConnectionState
32
error: Optional[str]
33
tls_established: bool
34
certificate_list: Sequence[x509.Certificate]
35
alpn: Optional[bytes]
36
cipher: Optional[str]
37
sni: Optional[str]
38
timestamp_start: float
39
timestamp_tls_setup: Optional[float]
40
timestamp_end: Optional[float]
41
42
def __str__(self) -> str: ...
43
def __repr__(self) -> str: ...
44
```
45
46
### Client Connection
47
48
Represents the client-side connection from the user agent (browser, application) to the proxy.
49
50
```python { .api }
51
class Client(Connection):
52
"""
53
Client connection from user agent to proxy.
54
55
Inherits all Connection attributes and adds client-specific functionality.
56
Represents the incoming connection that initiated the proxy request.
57
"""
58
def __init__(
59
self,
60
address: Optional[Address],
61
state: ConnectionState = ConnectionState.OPEN,
62
error: Optional[str] = None,
63
tls_established: bool = False,
64
certificate_list: Optional[Sequence[x509.Certificate]] = None,
65
alpn: Optional[bytes] = None,
66
cipher: Optional[str] = None,
67
sni: Optional[str] = None,
68
timestamp_start: float = 0,
69
timestamp_tls_setup: Optional[float] = None,
70
timestamp_end: Optional[float] = None
71
) -> None: ...
72
73
@classmethod
74
def make_dummy(cls, address: Address = ("client", 0)) -> "Client": ...
75
```
76
77
### Server Connection
78
79
Represents the server-side connection from the proxy to the target server.
80
81
```python { .api }
82
class Server(Connection):
83
"""
84
Server connection from proxy to target server.
85
86
Inherits all Connection attributes and adds server-specific functionality.
87
Represents the outgoing connection to fulfill the client request.
88
"""
89
def __init__(
90
self,
91
address: Optional[Address],
92
state: ConnectionState = ConnectionState.OPEN,
93
error: Optional[str] = None,
94
tls_established: bool = False,
95
certificate_list: Optional[Sequence[x509.Certificate]] = None,
96
alpn: Optional[bytes] = None,
97
cipher: Optional[str] = None,
98
sni: Optional[str] = None,
99
timestamp_start: float = 0,
100
timestamp_tls_setup: Optional[float] = None,
101
timestamp_end: Optional[float] = None
102
) -> None: ...
103
104
@classmethod
105
def make_dummy(cls, address: Address = ("server", 0)) -> "Server": ...
106
```
107
108
### Connection State
109
110
Enumeration of connection state flags using bitwise operations for complex state tracking.
111
112
```python { .api }
113
class ConnectionState(Flag):
114
"""
115
Connection state flags supporting bitwise operations.
116
117
States can be combined to represent complex connection conditions.
118
"""
119
CLOSED = 0
120
OPEN = 1
121
CAN_READ = 2
122
CAN_WRITE = 4
123
124
# Convenience combinations
125
ACTIVE = OPEN | CAN_READ | CAN_WRITE # 7
126
127
def __str__(self) -> str: ...
128
def __repr__(self) -> str: ...
129
```
130
131
### Address Type
132
133
Network address representation as a tuple of host and port.
134
135
```python { .api }
136
# Type alias for network addresses
137
Address = Tuple[str, int]
138
139
# Example addresses:
140
# ("192.168.1.1", 8080)
141
# ("example.com", 443)
142
# ("::1", 80) # IPv6
143
```
144
145
## Usage Examples
146
147
### Connection State Monitoring
148
149
```python
150
from mitmproxy import connection
151
from mitmproxy.connection import ConnectionState
152
153
def server_connect(flow):
154
"""Monitor server connection establishment."""
155
server = flow.server_conn
156
157
print(f"Connecting to: {server.address}")
158
print(f"Connection state: {server.state}")
159
160
# Check if connection is ready for I/O
161
if server.state & ConnectionState.CAN_WRITE:
162
print("Server ready for writing")
163
164
if server.state & ConnectionState.CAN_READ:
165
print("Server ready for reading")
166
167
# Log TLS information
168
if server.tls_established:
169
print(f"TLS cipher: {server.cipher}")
170
print(f"ALPN protocol: {server.alpn}")
171
print(f"SNI: {server.sni}")
172
print(f"Certificate count: {len(server.certificate_list)}")
173
174
def client_connect(flow):
175
"""Monitor client connection."""
176
client = flow.client_conn
177
178
print(f"Client connected from: {client.address}")
179
180
# Check for TLS
181
if client.tls_established:
182
print("Client using TLS")
183
if client.sni:
184
print(f"Client SNI: {client.sni}")
185
```
186
187
### Certificate Analysis
188
189
```python
190
from mitmproxy import tls
191
import datetime
192
193
def tls_clienthello(data):
194
"""Analyze client TLS hello."""
195
print(f"Client SNI: {data.context.client.sni}")
196
print(f"Client ALPN: {data.context.client.alpn}")
197
198
def tls_established_server(data):
199
"""Analyze established server TLS connection."""
200
server = data.context.server
201
202
if server.certificate_list:
203
cert = server.certificate_list[0] # First certificate in chain
204
205
print(f"Server certificate subject: {cert.subject}")
206
print(f"Server certificate issuer: {cert.issuer}")
207
print(f"Certificate valid from: {cert.not_valid_before}")
208
print(f"Certificate valid until: {cert.not_valid_after}")
209
210
# Check certificate validity
211
now = datetime.datetime.now(datetime.timezone.utc)
212
if now < cert.not_valid_before:
213
print("WARNING: Certificate not yet valid")
214
elif now > cert.not_valid_after:
215
print("WARNING: Certificate expired")
216
217
# Check for SAN (Subject Alternative Names)
218
try:
219
san = cert.extensions.get_extension_for_oid(
220
x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME
221
)
222
print(f"SAN entries: {[name.value for name in san.value]}")
223
except x509.ExtensionNotFound:
224
print("No SAN extension found")
225
```
226
227
### Connection Error Handling
228
229
```python
230
from mitmproxy import connection
231
232
def server_connect(flow):
233
"""Handle server connection issues."""
234
server = flow.server_conn
235
236
# Monitor connection establishment
237
if server.error:
238
print(f"Server connection error: {server.error}")
239
240
# Could implement retry logic here
241
# or modify the target server
242
243
def error(flow):
244
"""Handle flow errors including connection issues."""
245
if flow.error:
246
error_msg = flow.error.msg
247
248
if "connection" in error_msg.lower():
249
print(f"Connection error: {error_msg}")
250
251
# Log connection details for debugging
252
if flow.server_conn:
253
print(f"Target: {flow.server_conn.address}")
254
print(f"TLS: {flow.server_conn.tls_established}")
255
256
if flow.client_conn:
257
print(f"Client: {flow.client_conn.address}")
258
```
259
260
### Connection Timing Analysis
261
262
```python
263
from mitmproxy import http
264
import time
265
266
def request(flow: http.HTTPFlow):
267
"""Track request timing."""
268
# Store request start time for later analysis
269
flow.metadata["proxy_start"] = time.time()
270
271
def server_connect(flow):
272
"""Track server connection timing."""
273
server = flow.server_conn
274
275
if server.timestamp_start:
276
connect_time = time.time() - server.timestamp_start
277
print(f"Server connection established in {connect_time:.3f}s")
278
279
if server.timestamp_tls_setup and server.timestamp_start:
280
tls_time = server.timestamp_tls_setup - server.timestamp_start
281
print(f"TLS handshake took {tls_time:.3f}s")
282
283
def response(flow: http.HTTPFlow):
284
"""Calculate total request timing."""
285
if "proxy_start" in flow.metadata:
286
total_time = time.time() - flow.metadata["proxy_start"]
287
print(f"Total request time: {total_time:.3f}s")
288
289
# Break down timing components
290
client = flow.client_conn
291
server = flow.server_conn
292
293
if (client.timestamp_start and server.timestamp_start and
294
server.timestamp_end and client.timestamp_end):
295
296
# Calculate various timing metrics
297
client_connect = server.timestamp_start - client.timestamp_start
298
server_connect = (server.timestamp_tls_setup or server.timestamp_start) - server.timestamp_start
299
request_send = flow.request.timestamp_end - flow.request.timestamp_start
300
response_recv = flow.response.timestamp_end - flow.response.timestamp_start
301
302
print(f"Timing breakdown:")
303
print(f" Client connect: {client_connect:.3f}s")
304
print(f" Server connect: {server_connect:.3f}s")
305
print(f" Request send: {request_send:.3f}s")
306
print(f" Response receive: {response_recv:.3f}s")
307
```
308
309
### Advanced Connection Manipulation
310
311
```python
312
from mitmproxy import connection
313
from mitmproxy.connection import Server
314
315
def server_connect(flow):
316
"""Modify server connections dynamically."""
317
# Route requests to different servers based on conditions
318
if "/api/" in flow.request.path:
319
# Route API requests to API server
320
flow.server_conn = Server(("api.internal.com", 443))
321
elif "/static/" in flow.request.path:
322
# Route static content to CDN
323
flow.server_conn = Server(("cdn.example.com", 443))
324
325
# Force TLS for specific connections
326
if flow.request.host == "insecure.example.com":
327
# Upgrade to secure connection
328
new_server = Server(("secure.example.com", 443))
329
new_server.tls_established = True
330
flow.server_conn = new_server
331
332
def client_connect(flow):
333
"""Handle client connection setup."""
334
client = flow.client_conn
335
336
# Log client information
337
print(f"Client {client.address} connected")
338
339
# Could implement IP-based filtering here
340
client_ip = client.address[0]
341
if client_ip in BLOCKED_IPS:
342
# Close connection (implementation specific)
343
client.state = ConnectionState.CLOSED
344
```