-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
next_layer.py
419 lines (370 loc) · 15.7 KB
/
next_layer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
"""
This addon determines the next protocol layer in our proxy stack.
Whenever a protocol layer in the proxy wants to pass a connection to a child layer and isn't sure which protocol comes
next, it calls the `next_layer` hook, which ends up here.
For example, if mitmproxy runs as a regular proxy, we first need to determine if
new clients start with a TLS handshake right away (Secure Web Proxy) or send a plaintext HTTP CONNECT request.
This addon here peeks at the incoming bytes and then makes a decision based on proxy mode, mitmproxy options, etc.
For a typical HTTPS request, this addon is called a couple of times: First to determine that we start with an HTTP layer
which processes the `CONNECT` request, a second time to determine that the client then starts negotiating TLS, and a
third time when we check if the protocol within that TLS stream is actually HTTP or something else.
Sometimes it's useful to hardcode specific logic in next_layer when one wants to do fancy things.
In that case it's not necessary to modify mitmproxy's source, adding a custom addon with a next_layer event hook
that sets nextlayer.layer works just as well.
"""
from __future__ import annotations
import logging
import re
import struct
import sys
from collections.abc import Iterable
from collections.abc import Sequence
from typing import Any
from typing import cast
from mitmproxy import ctx
from mitmproxy import dns
from mitmproxy import exceptions
from mitmproxy.net.tls import starts_like_dtls_record
from mitmproxy.net.tls import starts_like_tls_record
from mitmproxy.proxy import layer
from mitmproxy.proxy import layers
from mitmproxy.proxy import mode_specs
from mitmproxy.proxy import tunnel
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.layer import Layer
from mitmproxy.proxy.layers import ClientQuicLayer
from mitmproxy.proxy.layers import ClientTLSLayer
from mitmproxy.proxy.layers import DNSLayer
from mitmproxy.proxy.layers import HttpLayer
from mitmproxy.proxy.layers import modes
from mitmproxy.proxy.layers import RawQuicLayer
from mitmproxy.proxy.layers import ServerQuicLayer
from mitmproxy.proxy.layers import ServerTLSLayer
from mitmproxy.proxy.layers import TCPLayer
from mitmproxy.proxy.layers import UDPLayer
from mitmproxy.proxy.layers.http import HTTPMode
from mitmproxy.proxy.layers.quic import quic_parse_client_hello
from mitmproxy.proxy.layers.tls import dtls_parse_client_hello
from mitmproxy.proxy.layers.tls import HTTP1_ALPNS
from mitmproxy.proxy.layers.tls import HTTP_ALPNS
from mitmproxy.proxy.layers.tls import parse_client_hello
from mitmproxy.tls import ClientHello
if sys.version_info < (3, 11):
from typing_extensions import assert_never
else:
from typing import assert_never
logger = logging.getLogger(__name__)
def stack_match(
context: Context, layers: Sequence[type[Layer] | tuple[type[Layer], ...]]
) -> bool:
if len(context.layers) != len(layers):
return False
return all(
expected is Any or isinstance(actual, expected)
for actual, expected in zip(context.layers, layers)
)
class NeedsMoreData(Exception):
"""Signal that the decision on which layer to put next needs to be deferred within the NextLayer addon."""
class NextLayer:
ignore_hosts: Sequence[re.Pattern] = ()
allow_hosts: Sequence[re.Pattern] = ()
tcp_hosts: Sequence[re.Pattern] = ()
udp_hosts: Sequence[re.Pattern] = ()
def configure(self, updated):
if "tcp_hosts" in updated:
self.tcp_hosts = [
re.compile(x, re.IGNORECASE) for x in ctx.options.tcp_hosts
]
if "udp_hosts" in updated:
self.udp_hosts = [
re.compile(x, re.IGNORECASE) for x in ctx.options.udp_hosts
]
if "allow_hosts" in updated or "ignore_hosts" in updated:
if ctx.options.allow_hosts and ctx.options.ignore_hosts:
raise exceptions.OptionsError(
"The allow_hosts and ignore_hosts options are mutually exclusive."
)
self.ignore_hosts = [
re.compile(x, re.IGNORECASE) for x in ctx.options.ignore_hosts
]
self.allow_hosts = [
re.compile(x, re.IGNORECASE) for x in ctx.options.allow_hosts
]
def next_layer(self, nextlayer: layer.NextLayer):
if nextlayer.layer:
return # do not override something another addon has set.
try:
nextlayer.layer = self._next_layer(
nextlayer.context,
nextlayer.data_client(),
nextlayer.data_server(),
)
except NeedsMoreData:
logger.info(
f"Deferring layer decision, not enough data: {nextlayer.data_client().hex()}"
)
def _next_layer(
self, context: Context, data_client: bytes, data_server: bytes
) -> Layer | None:
assert context.layers
def s(*layers):
return stack_match(context, layers)
tcp_based = context.client.transport_protocol == "tcp"
udp_based = context.client.transport_protocol == "udp"
# 1) check for --ignore/--allow
if self._ignore_connection(context, data_client, data_server):
return (
layers.TCPLayer(context, ignore=True)
if tcp_based
else layers.UDPLayer(context, ignore=True)
)
# 2) Handle proxy modes with well-defined next protocol
# 2a) Reverse proxy: derive from spec
if s(modes.ReverseProxy):
return self._setup_reverse_proxy(context, data_client)
# 2b) Explicit HTTP proxies
if s((modes.HttpProxy, modes.HttpUpstreamProxy)):
return self._setup_explicit_http_proxy(context, data_client)
# 3) Handle security protocols
# 3a) TLS/DTLS
is_tls_or_dtls = (
tcp_based
and starts_like_tls_record(data_client)
or udp_based
and starts_like_dtls_record(data_client)
)
if is_tls_or_dtls:
server_tls = ServerTLSLayer(context)
server_tls.child_layer = ClientTLSLayer(context)
return server_tls
# 3b) QUIC
if udp_based and _starts_like_quic(data_client):
server_quic = ServerQuicLayer(context)
server_quic.child_layer = ClientQuicLayer(context)
return server_quic
# 4) Check for --tcp/--udp
if tcp_based and self._is_destination_in_hosts(context, self.tcp_hosts):
return layers.TCPLayer(context)
if udp_based and self._is_destination_in_hosts(context, self.udp_hosts):
return layers.UDPLayer(context)
# 5) Handle application protocol
# 5a) Is it DNS?
if udp_based:
try:
# TODO: DNS over TCP
dns.Message.unpack(data_client) # TODO: perf
except struct.error:
pass
else:
return layers.DNSLayer(context)
# 5b) We have no other specialized layers for UDP, so we fall back to raw forwarding.
if udp_based:
return layers.UDPLayer(context)
# 5b) Check for raw tcp mode.
very_likely_http = context.client.alpn in HTTP_ALPNS
probably_no_http = not very_likely_http and (
# the first three bytes should be the HTTP verb, so A-Za-z is expected.
len(data_client) < 3
or not data_client[:3].isalpha()
# a server greeting would be uncharacteristic.
or data_server
)
if ctx.options.rawtcp and probably_no_http:
return layers.TCPLayer(context)
# 5c) Assume HTTP by default.
return layers.HttpLayer(context, HTTPMode.transparent)
def _ignore_connection(
self,
context: Context,
data_client: bytes,
data_server: bytes,
) -> bool | None:
"""
Returns:
True, if the connection should be ignored.
False, if it should not be ignored.
Raises:
NeedsMoreData, if we need to wait for more input data.
"""
if not ctx.options.ignore_hosts and not ctx.options.allow_hosts:
return False
# Special handling for wireguard mode: if the hostname is "10.0.0.53", do not ignore the connection
if isinstance(
context.client.proxy_mode, mode_specs.WireGuardMode
) and context.server.address == ("10.0.0.53", 53):
return False
hostnames: list[str] = []
if context.server.peername and (peername := context.server.peername[0]):
hostnames.append(peername)
if context.server.address and (server_address := context.server.address[0]):
hostnames.append(server_address)
# If we already have a destination address, we can also check for HTTP Host headers.
# But we do need the destination, otherwise we don't know where this connection is going to.
if host_header := self._get_host_header(context, data_client, data_server):
hostnames.append(host_header)
if (
client_hello := self._get_client_hello(context, data_client)
) and client_hello.sni:
hostnames.append(client_hello.sni)
if not hostnames:
return False
if ctx.options.ignore_hosts:
return any(
re.search(rex, host, re.IGNORECASE)
for host in hostnames
for rex in ctx.options.ignore_hosts
)
elif ctx.options.allow_hosts:
return not any(
re.search(rex, host, re.IGNORECASE)
for host in hostnames
for rex in ctx.options.allow_hosts
)
else: # pragma: no cover
raise AssertionError()
@staticmethod
def _get_host_header(
context: Context,
data_client: bytes,
data_server: bytes,
) -> str | None:
"""
Try to read a host header from data_client.
Returns:
The host header value, or None, if no host header was found.
Raises:
NeedsMoreData, if the HTTP request is incomplete.
"""
if context.client.transport_protocol != "tcp" or data_server:
return None
host_header_expected = context.client.alpn in HTTP1_ALPNS or re.match(
rb"[A-Z]{3,}.+HTTP/", data_client, re.IGNORECASE
)
if host_header_expected:
if m := re.search(rb"\r\n(?:Host: (.+))?\r\n", data_client, re.IGNORECASE):
if host := m.group(1):
return host.decode("utf-8", "surrogateescape")
else:
return None # \r\n\r\n - header end came first.
else:
raise NeedsMoreData
else:
return None
@staticmethod
def _get_client_hello(context: Context, data_client: bytes) -> ClientHello | None:
"""
Try to read a TLS/DTLS/QUIC ClientHello from data_client.
Returns:
A complete ClientHello, or None, if no ClientHello was found.
Raises:
NeedsMoreData, if the ClientHello is incomplete.
"""
match context.client.transport_protocol:
case "tcp":
if starts_like_tls_record(data_client):
try:
ch = parse_client_hello(data_client)
except ValueError:
pass
else:
if ch is None:
raise NeedsMoreData
return ch
return None
case "udp":
try:
return quic_parse_client_hello(data_client)
except ValueError:
pass
try:
ch = dtls_parse_client_hello(data_client)
except ValueError:
pass
else:
if ch is None:
raise NeedsMoreData
return ch
return None
case _: # pragma: no cover
assert_never(context.client.transport_protocol)
@staticmethod
def _setup_reverse_proxy(context: Context, data_client: bytes) -> Layer:
spec = cast(mode_specs.ReverseMode, context.client.proxy_mode)
stack = tunnel.LayerStack()
match spec.scheme:
case "http":
if starts_like_tls_record(data_client):
stack /= ClientTLSLayer(context)
stack /= HttpLayer(context, HTTPMode.transparent)
case "https":
stack /= ServerTLSLayer(context)
if starts_like_tls_record(data_client):
stack /= ClientTLSLayer(context)
stack /= HttpLayer(context, HTTPMode.transparent)
case "tcp":
if starts_like_tls_record(data_client):
stack /= ClientTLSLayer(context)
stack /= TCPLayer(context)
case "tls":
stack /= ServerTLSLayer(context)
if starts_like_tls_record(data_client):
stack /= ClientTLSLayer(context)
stack /= TCPLayer(context)
case "udp":
if starts_like_dtls_record(data_client):
stack /= ClientTLSLayer(context)
stack /= UDPLayer(context)
case "dtls":
stack /= ServerTLSLayer(context)
if starts_like_dtls_record(data_client):
stack /= ClientTLSLayer(context)
stack /= UDPLayer(context)
case "dns":
# TODO: DNS-over-TLS / DNS-over-DTLS
# is_tls_or_dtls = (
# context.client.transport_protocol == "tcp" and starts_like_tls_record(data_client)
# or
# context.client.transport_protocol == "udp" and starts_like_dtls_record(data_client)
# )
# if is_tls_or_dtls:
# stack /= ClientTLSLayer(context)
stack /= DNSLayer(context)
case "http3":
stack /= ServerQuicLayer(context)
stack /= ClientQuicLayer(context)
stack /= HttpLayer(context, HTTPMode.transparent)
case "quic":
stack /= ServerQuicLayer(context)
stack /= ClientQuicLayer(context)
stack /= RawQuicLayer(context)
case _: # pragma: no cover
assert_never(spec.scheme)
return stack[0]
@staticmethod
def _setup_explicit_http_proxy(context: Context, data_client: bytes) -> Layer:
stack = tunnel.LayerStack()
if context.client.transport_protocol == "udp":
stack /= layers.ClientQuicLayer(context)
elif starts_like_tls_record(data_client):
stack /= layers.ClientTLSLayer(context)
if isinstance(context.layers[0], modes.HttpUpstreamProxy):
stack /= layers.HttpLayer(context, HTTPMode.upstream)
else:
stack /= layers.HttpLayer(context, HTTPMode.regular)
return stack[0]
@staticmethod
def _is_destination_in_hosts(context: Context, hosts: Iterable[re.Pattern]) -> bool:
return any(
(context.server.address and rex.search(context.server.address[0]))
or (context.client.sni and rex.search(context.client.sni))
for rex in hosts
)
def _starts_like_quic(data_client: bytes) -> bool:
# FIXME: handle clienthellos distributed over multiple packets?
# FIXME: perf
try:
quic_parse_client_hello(data_client)
except ValueError:
return False
else:
return True