mitmproxy/libmproxy/protocol/base.py

196 lines
6.5 KiB
Python
Raw Normal View History

from __future__ import (absolute_import, print_function, division)
2015-09-10 23:39:33 +00:00
import sys
import six
2015-07-25 11:31:55 +00:00
from netlib import tcp
2015-08-30 13:27:29 +00:00
from ..models import ServerConnection
from ..exceptions import ProtocolException
2015-09-17 00:13:28 +00:00
from netlib.exceptions import TcpException
2015-07-25 11:31:55 +00:00
2015-07-25 12:48:50 +00:00
2015-07-25 11:31:55 +00:00
class _LayerCodeCompletion(object):
"""
Dummy class that provides type hinting in PyCharm, which simplifies development a lot.
"""
2015-09-03 16:55:38 +00:00
def __init__(self, **mixin_args): # pragma: nocover
super(_LayerCodeCompletion, self).__init__(**mixin_args)
2015-07-25 11:31:55 +00:00
if True:
return
self.config = None
2015-08-31 15:05:52 +00:00
"""@type: libmproxy.proxy.ProxyConfig"""
2015-07-25 11:31:55 +00:00
self.client_conn = None
2015-08-31 15:05:52 +00:00
"""@type: libmproxy.models.ClientConnection"""
self.server_conn = None
"""@type: libmproxy.models.ServerConnection"""
2015-07-25 11:31:55 +00:00
self.channel = None
"""@type: libmproxy.controller.Channel"""
2015-09-03 16:55:38 +00:00
self.ctx = None
"""@type: libmproxy.protocol.Layer"""
2015-07-25 11:31:55 +00:00
class Layer(_LayerCodeCompletion):
2015-09-03 16:55:38 +00:00
"""
Base class for all layers. All other protocol layers should inherit from this class.
"""
def __init__(self, ctx, **mixin_args):
2015-07-25 11:31:55 +00:00
"""
2015-09-03 16:55:38 +00:00
Each layer usually passes itself to its child layers as a context. Properties of the
context are transparently mapped to the layer, so that the following works:
.. code-block:: python
root_layer = Layer(None)
root_layer.client_conn = 42
sub_layer = Layer(root_layer)
print(sub_layer.client_conn) # 42
The root layer is passed a :py:class:`libmproxy.proxy.RootContext` object,
which provides access to :py:attr:`.client_conn <libmproxy.proxy.RootContext.client_conn>`,
:py:attr:`.next_layer <libmproxy.proxy.RootContext.next_layer>` and other basic attributes.
2015-07-25 11:31:55 +00:00
Args:
2015-09-03 16:55:38 +00:00
ctx: The (read-only) parent layer / context.
2015-07-25 11:31:55 +00:00
"""
self.ctx = ctx
2015-09-03 16:55:38 +00:00
"""
The parent layer.
2015-07-25 11:31:55 +00:00
2015-09-03 16:55:38 +00:00
:type: :py:class:`Layer`
2015-07-25 11:31:55 +00:00
"""
2015-09-03 16:55:38 +00:00
super(Layer, self).__init__(**mixin_args)
def __call__(self):
"""Logic of the layer.
Returns:
Once the protocol has finished without exceptions.
2015-07-25 11:31:55 +00:00
Raises:
2015-09-03 16:55:38 +00:00
~libmproxy.exceptions.ProtocolException: if an exception occurs. No other exceptions must be raised.
2015-07-25 11:31:55 +00:00
"""
2015-08-30 13:59:50 +00:00
raise NotImplementedError()
2015-07-25 11:31:55 +00:00
def __getattr__(self, name):
"""
2015-09-03 16:55:38 +00:00
Attributes not present on the current layer are looked up on the context.
2015-07-25 11:31:55 +00:00
"""
return getattr(self.ctx, name)
2015-08-14 08:41:11 +00:00
@property
def layers(self):
2015-09-03 16:55:38 +00:00
"""
List of all layers, including the current layer (``[self, self.ctx, self.ctx.ctx, ...]``)
"""
2015-08-14 08:41:11 +00:00
return [self] + self.ctx.layers
def __repr__(self):
2015-08-15 14:26:12 +00:00
return type(self).__name__
2015-08-14 08:41:11 +00:00
2015-07-25 11:31:55 +00:00
class ServerConnectionMixin(object):
"""
Mixin that provides a layer with the capabilities to manage a server connection.
2015-09-03 16:55:38 +00:00
The server address can be passed in the constructor or set by calling :py:meth:`set_server`.
Subclasses are responsible for calling :py:meth:`disconnect` before returning.
Recommended Usage:
.. code-block:: python
class MyLayer(Layer, ServerConnectionMixin):
def __call__(self):
try:
# Do something.
finally:
if self.server_conn:
self.disconnect()
2015-07-25 11:31:55 +00:00
"""
2016-01-18 08:55:46 +00:00
def __init__(self, server_address=None):
2015-08-15 14:26:12 +00:00
super(ServerConnectionMixin, self).__init__()
self.server_conn = ServerConnection(server_address, (self.config.host, 0))
2015-09-03 15:01:25 +00:00
self.__check_self_connect()
2015-08-18 13:59:44 +00:00
2015-09-03 15:01:25 +00:00
def __check_self_connect(self):
"""
We try to protect the proxy from _accidentally_ connecting to itself,
e.g. because of a failed transparent lookup or an invalid configuration.
"""
address = self.server_conn.address
if address:
self_connect = (
address.port == self.config.port and
address.host in ("localhost", "127.0.0.1", "::1")
)
if self_connect:
raise ProtocolException(
"Invalid server address: {}\r\n"
"The proxy shall not connect to itself.".format(repr(address))
)
2015-09-03 16:25:36 +00:00
def set_server(self, address, server_tls=None, sni=None):
2015-09-03 16:55:38 +00:00
"""
Sets a new server address. If there is an existing connection, it will be closed.
Raises:
~libmproxy.exceptions.ProtocolException:
if ``server_tls`` is ``True``, but there was no TLS layer on the
protocol stack which could have processed this.
"""
2015-09-03 16:25:36 +00:00
if self.server_conn:
self.disconnect()
self.log("Set new server address: " + repr(address), "debug")
self.server_conn.address = address
self.__check_self_connect()
if server_tls:
raise ProtocolException(
"Cannot upgrade to TLS, no TLS layer on the protocol stack."
)
2015-07-25 11:31:55 +00:00
2015-09-03 15:01:25 +00:00
def disconnect(self):
2015-07-25 11:31:55 +00:00
"""
Deletes (and closes) an existing server connection.
2015-09-03 16:55:38 +00:00
Must not be called if there is no existing connection.
2015-07-25 11:31:55 +00:00
"""
2015-08-16 21:25:02 +00:00
self.log("serverdisconnect", "debug", [repr(self.server_conn.address)])
2015-09-03 15:01:25 +00:00
address = self.server_conn.address
2016-01-18 08:55:46 +00:00
source_address = self.server_conn.source_address
2015-07-25 11:31:55 +00:00
self.server_conn.finish()
self.server_conn.close()
2015-08-31 15:05:52 +00:00
self.channel.tell("serverdisconnect", self.server_conn)
self.server_conn = ServerConnection(address, source_address)
2015-07-25 11:31:55 +00:00
2015-08-18 13:59:44 +00:00
def connect(self):
2015-09-03 16:55:38 +00:00
"""
Establishes a server connection.
Must not be called if there is an existing connection.
Raises:
~libmproxy.exceptions.ProtocolException: if the connection could not be established.
"""
2015-08-16 21:25:02 +00:00
if not self.server_conn.address:
2015-08-14 08:41:11 +00:00
raise ProtocolException("Cannot connect to server, no server address given.")
2015-08-16 21:25:02 +00:00
self.log("serverconnect", "debug", [repr(self.server_conn.address)])
2015-08-31 15:05:52 +00:00
self.channel.ask("serverconnect", self.server_conn)
2015-07-25 11:31:55 +00:00
try:
self.server_conn.connect()
2015-09-17 00:13:28 +00:00
except TcpException as e:
2015-09-10 23:39:33 +00:00
six.reraise(
ProtocolException,
ProtocolException(
"Server connection to {} failed: {}".format(
repr(self.server_conn.address), str(e)
)
),
2015-09-10 23:39:33 +00:00
sys.exc_info()[2]
)
2015-08-30 13:27:29 +00:00
class Kill(Exception):
"""
2015-09-03 16:55:38 +00:00
Signal that both client and server connection(s) should be killed immediately.
2015-08-30 13:27:29 +00:00
"""