aboutsummaryrefslogtreecommitdiffstats
path: root/libmproxy/protocol/primitives.py
blob: 77dc936d81edea13d5fdeb38035d0a7b3c69ee6a (plain)
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
from __future__ import absolute_import
import copy
import netlib.tcp
from .. import stateobject, utils, version
from ..proxy.connection import ClientConnection, ServerConnection


KILL = 0  # const for killed requests


class Error(stateobject.StateObject):
    """
        An Error.

        This is distinct from an protocol error response (say, a HTTP code 500),
        which is represented by a normal HTTPResponse object. This class is
        responsible for indicating errors that fall outside of normal protocol
        communications, like interrupted connections, timeouts, protocol errors.

        Exposes the following attributes:

            flow: Flow object
            msg: Message describing the error
            timestamp: Seconds since the epoch
    """
    def __init__(self, msg, timestamp=None):
        """
        @type msg: str
        @type timestamp: float
        """
        self.flow = None  # will usually be set by the flow backref mixin
        self.msg = msg
        self.timestamp = timestamp or utils.timestamp()

    _stateobject_attributes = dict(
        msg=str,
        timestamp=float
    )

    def __str__(self):
        return self.msg

    @classmethod
    def from_state(cls, state):
        # the default implementation assumes an empty constructor. Override
        # accordingly.
        f = cls(None)
        f.load_state(state)
        return f

    def copy(self):
        c = copy.copy(self)
        return c


class Flow(stateobject.StateObject):
    """
    A Flow is a collection of objects representing a single transaction.
    This class is usually subclassed for each protocol, e.g. HTTPFlow.
    """
    def __init__(self, conntype, client_conn, server_conn, live=None):
        self.conntype = conntype
        self.client_conn = client_conn
        """@type: ClientConnection"""
        self.server_conn = server_conn
        """@type: ServerConnection"""
        self.live = live
        """@type: LiveConnection"""

        self.error = None
        """@type: Error"""
        self._backup = None

    _stateobject_attributes = dict(
        error=Error,
        client_conn=ClientConnection,
        server_conn=ServerConnection,
        conntype=str
    )

    def get_state(self):
        d = super(Flow, self).get_state()
        d.update(version=version.IVERSION)
        return d

    def __eq__(self, other):
        return self is other

    def copy(self):
        f = copy.copy(self)

        f.client_conn = self.client_conn.copy()
        f.server_conn = self.server_conn.copy()

        if self.error:
            f.error = self.error.copy()
        return f

    def modified(self):
        """
            Has this Flow been modified?
        """
        if self._backup:
            return self._backup != self.get_state()
        else:
            return False

    def backup(self, force=False):
        """
            Save a backup of this Flow, which can be reverted to using a
            call to .revert().
        """
        if not self._backup:
            self._backup = self.get_state()

    def revert(self):
        """
            Revert to the last backed up state.
        """
        if self._backup:
            self.load_state(self._backup)
            self._backup = None


class ProtocolHandler(object):
    """
    A ProtocolHandler implements an application-layer protocol, e.g. HTTP.
    See: libmproxy.protocol.http.HTTPHandler
    """
    def __init__(self, c):
        self.c = c
        """@type: libmproxy.proxy.server.ConnectionHandler"""
        self.live = LiveConnection(c)
        """@type: LiveConnection"""

    def handle_messages(self):
        """
        This method gets called if a client connection has been made. Depending
        on the proxy settings, a server connection might already exist as well.
        """
        raise NotImplementedError  # pragma: nocover

    def handle_server_reconnect(self, state):
        """
        This method gets called if a server connection needs to reconnect and
        there's a state associated with the server connection (e.g. a
        previously-sent CONNECT request or a SOCKS proxy request). This method
        gets called after the connection has been restablished but before SSL is
        established.
        """
        raise NotImplementedError  # pragma: nocover

    def handle_error(self, error):
        """
        This method gets called should there be an uncaught exception during the
        connection. This might happen outside of handle_messages, e.g. if the
        initial SSL handshake fails in transparent mode.
        """
        raise error  # pragma: nocover


class LiveConnection(object):
    """
    This facade allows interested parties (FlowMaster, inline scripts) to
    interface with a live connection, without exposing the internals
    of the ConnectionHandler.
    """
    def __init__(self, c):
        self.c = c
        """@type: libmproxy.proxy.server.ConnectionHandler"""
        self._backup_server_conn = None
        """@type: libmproxy.proxy.connection.ServerConnection"""

    def change_server(self, address, ssl=None, force=False, persistent_change=False):
        """
        Change the server connection to the specified address.
        @returns:
        True, if a new connection has been established,
        False, if an existing connection has been used
        """
        address = netlib.tcp.Address.wrap(address)

        ssl_mismatch = (ssl is not None and ssl != self.c.server_conn.ssl_established)
        address_mismatch = (address != self.c.server_conn.address)

        if persistent_change:
            self._backup_server_conn = None

        if ssl_mismatch or address_mismatch or force:

            self.c.log(
                "Change server connection: %s:%s -> %s:%s [persistent: %s]" % (
                    self.c.server_conn.address.host,
                    self.c.server_conn.address.port,
                    address.host,
                    address.port,
                    persistent_change
                ),
                "debug"
            )

            if not self._backup_server_conn and not persistent_change:
                self._backup_server_conn = self.c.server_conn
                self.c.server_conn = None
            else:
                # This is at least the second temporary change. We can kill the
                # current connection.
                self.c.del_server_connection()

            self.c.set_server_address(address)
            self.c.establish_server_connection(ask=False)
            if ssl:
                self.c.establish_ssl(server=True)
            return True
        return False

    def restore_server(self):
        # TODO: Similar to _backup_server_conn, introduce _cache_server_conn,
        # which keeps the changed connection open This may be beneficial if a
        # user is rewriting all requests from http to https or similar.
        if not self._backup_server_conn:
            return

        self.c.log("Restore original server connection: %s:%s -> %s:%s" % (
            self.c.server_conn.address.host,
            self.c.server_conn.address.port,
            self._backup_server_conn.address.host,
            self._backup_server_conn.address.port
        ), "debug")

        self.c.del_server_connection()
        self.c.server_conn = self._backup_server_conn
        self._backup_server_conn = None