mitmproxy/libmproxy/protocol2/root_context.py

63 lines
2.0 KiB
Python
Raw Normal View History

2015-08-14 08:41:11 +00:00
from __future__ import (absolute_import, print_function, division)
2015-08-18 12:15:08 +00:00
import string
2015-08-14 08:41:11 +00:00
2015-08-16 21:25:02 +00:00
from .messages import Kill
2015-08-14 08:41:11 +00:00
from .rawtcp import RawTcpLayer
2015-08-11 18:27:34 +00:00
from .tls import TlsLayer
from .http import Http1Layer, Http2Layer, HttpLayer
2015-08-11 18:27:34 +00:00
2015-08-16 21:25:02 +00:00
2015-08-11 18:27:34 +00:00
class RootContext(object):
"""
The outmost context provided to the root layer.
As a consequence, every layer has .client_conn, .channel, .next_layer() and .config.
"""
def __init__(self, client_conn, config, channel):
self.client_conn = client_conn # Client Connection
self.channel = channel # provides .ask() method to communicate with FlowMaster
self.config = config # Proxy Configuration
def next_layer(self, top_layer):
"""
This function determines the next layer in the protocol stack.
:param top_layer: the current top layer
:return: The next layer.
"""
2015-08-14 08:41:11 +00:00
d = top_layer.client_conn.rfile.peek(3)
# TODO: Handle ignore and tcp passthrough
# TLS ClientHello magic, see http://www.moserware.com/2009/06/first-few-milliseconds-of-https.html#client-hello
is_tls_client_hello = (
len(d) == 3 and
d[0] == '\x16' and
d[1] == '\x03' and
d[2] in ('\x00', '\x01', '\x02', '\x03')
)
2015-08-11 18:27:34 +00:00
2015-08-18 12:15:08 +00:00
is_ascii = all(x in string.ascii_uppercase for x in d)
# TODO: build is_http2_magic check here, maybe this is an easy way to detect h2c
2015-08-11 18:27:34 +00:00
if not d:
2015-08-16 21:25:02 +00:00
return iter([])
2015-08-14 08:41:11 +00:00
if is_tls_client_hello:
2015-08-15 18:20:46 +00:00
return TlsLayer(top_layer, True, True)
2015-08-18 12:15:08 +00:00
elif isinstance(top_layer, TlsLayer) and is_ascii:
if top_layer.client_conn.get_alpn_proto_negotiated() == 'h2':
return Http2Layer(top_layer, 'transparent')
2015-08-18 12:15:08 +00:00
else:
return Http1Layer(top_layer, "transparent")
2015-08-11 18:27:34 +00:00
else:
2015-08-15 18:20:46 +00:00
return RawTcpLayer(top_layer)
2015-08-14 08:41:11 +00:00
@property
def layers(self):
return []
def __repr__(self):
return "RootContext"