mitmproxy/libmproxy/protocol2/root_context.py

71 lines
2.4 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-18 13:59:44 +00:00
from libmproxy.protocol2.layer 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-19 13:23:52 +00:00
from netlib.http.http2 import HTTP2Protocol
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
# TODO: Handle ignore and tcp passthrough
2015-08-19 13:23:52 +00:00
# TLS ClientHello magic, works for SSLv3, TLSv1.0, TLSv1.1, TLSv1.2
# http://www.moserware.com/2009/06/first-few-milliseconds-of-https.html#client-hello
d = top_layer.client_conn.rfile.peek(3)
2015-08-14 08:41:11 +00:00
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-19 13:23:52 +00:00
d = top_layer.client_conn.rfile.peek(3)
is_ascii = (
len(d) == 3 and
2015-08-24 14:52:03 +00:00
all(x in string.ascii_letters for x in d) # better be safe here and don't expect uppercase...
2015-08-19 13:23:52 +00:00
)
2015-08-18 12:15:08 +00:00
2015-08-19 13:23:52 +00:00
d = top_layer.client_conn.rfile.peek(len(HTTP2Protocol.CLIENT_CONNECTION_PREFACE))
is_http2_magic = (d == HTTP2Protocol.CLIENT_CONNECTION_PREFACE)
2015-08-26 04:38:03 +00:00
alpn_proto_negotiated = top_layer.client_conn.get_alpn_proto_negotiated()
2015-08-19 13:23:52 +00:00
is_alpn_h2_negotiated = (
isinstance(top_layer, TlsLayer) and
2015-08-26 04:38:03 +00:00
alpn_proto_negotiated == HTTP2Protocol.ALPN_PROTO_H2
2015-08-19 13:23:52 +00:00
)
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-19 13:23:52 +00:00
elif is_alpn_h2_negotiated or is_http2_magic:
return Http2Layer(top_layer, 'transparent')
elif is_ascii:
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"