aboutsummaryrefslogtreecommitdiffstats
path: root/mitmproxy/addons/clientplayback.py
blob: 6a3cc5fb908a32d90fa2d63f336e715e1d1a9e79 (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
import queue
import threading
import time
import typing

import mitmproxy.types
from mitmproxy import command
from mitmproxy import connections
from mitmproxy import controller
from mitmproxy import ctx
from mitmproxy import exceptions
from mitmproxy import flow
from mitmproxy import http
from mitmproxy import io
from mitmproxy import log
from mitmproxy import options
from mitmproxy.coretypes import basethread
from mitmproxy.net import server_spec, tls
from mitmproxy.net.http import http1
from mitmproxy.utils import human


class RequestReplayThread(basethread.BaseThread):
    daemon = True

    def __init__(
            self,
            opts: options.Options,
            channel: controller.Channel,
            queue: queue.Queue,
    ) -> None:
        self.options = opts
        self.channel = channel
        self.queue = queue
        self.inflight = threading.Event()
        super().__init__("RequestReplayThread")

    def run(self):
        while True:
            f = self.queue.get()
            self.inflight.set()
            self.replay(f)
            self.inflight.clear()

    def replay(self, f):  # pragma: no cover
        f.live = True
        r = f.request
        bsl = human.parse_size(self.options.body_size_limit)
        first_line_format_backup = r.first_line_format
        server = None
        try:
            f.response = None

            # If we have a channel, run script hooks.
            request_reply = self.channel.ask("request", f)
            if isinstance(request_reply, http.HTTPResponse):
                f.response = request_reply

            if not f.response:
                # In all modes, we directly connect to the server displayed
                if self.options.mode.startswith("upstream:"):
                    server_address = server_spec.parse_with_mode(self.options.mode)[1].address
                    server = connections.ServerConnection(server_address)
                    server.connect()
                    if r.scheme == "https":
                        connect_request = http.make_connect_request((r.data.host, r.port))
                        server.wfile.write(http1.assemble_request(connect_request))
                        server.wfile.flush()
                        resp = http1.read_response(
                            server.rfile,
                            connect_request,
                            body_size_limit=bsl
                        )
                        if resp.status_code != 200:
                            raise exceptions.ReplayException(
                                "Upstream server refuses CONNECT request"
                            )
                        server.establish_tls(
                            sni=f.server_conn.sni,
                            **tls.client_arguments_from_options(self.options)
                        )
                        r.first_line_format = "relative"
                    else:
                        r.first_line_format = "absolute"
                else:
                    server_address = (r.host, r.port)
                    server = connections.ServerConnection(server_address)
                    server.connect()
                    if r.scheme == "https":
                        server.establish_tls(
                            sni=f.server_conn.sni,
                            **tls.client_arguments_from_options(self.options)
                        )
                    r.first_line_format = "relative"

                server.wfile.write(http1.assemble_request(r))
                server.wfile.flush()
                r.timestamp_start = r.timestamp_end = time.time()

                if f.server_conn:
                    f.server_conn.close()
                f.server_conn = server

                f.response = http.HTTPResponse.wrap(
                    http1.read_response(server.rfile, r, body_size_limit=bsl)
                )
            response_reply = self.channel.ask("response", f)
            if response_reply == exceptions.Kill:
                raise exceptions.Kill()
        except (exceptions.ReplayException, exceptions.NetlibException) as e:
            f.error = flow.Error(str(e))
            self.channel.ask("error", f)
        except exceptions.Kill:
            self.channel.tell("log", log.LogEntry("Connection killed", "info"))
        except Exception as e:
            self.channel.tell("log", log.LogEntry(repr(e), "error"))
        finally:
            r.first_line_format = first_line_format_backup
            f.live = False
            if server and server.connected():
                server.finish()
                server.close()


class ClientPlayback:
    def __init__(self):
        self.q = queue.Queue()
        self.thread: RequestReplayThread = None

    def check(self, f: flow.Flow):
        if f.live:
            return "Can't replay live flow."
        if f.intercepted:
            return "Can't replay intercepted flow."
        if isinstance(f, http.HTTPFlow):
            if not f.request:
                return "Can't replay flow with missing request."
            if f.request.raw_content is None:
                return "Can't replay flow with missing content."
        else:
            return "Can only replay HTTP flows."

    def load(self, loader):
        loader.add_option(
            "client_replay", typing.Sequence[str], [],
            "Replay client requests from a saved file."
        )

    def running(self):
        self.thread = RequestReplayThread(
            ctx.options,
            ctx.master.channel,
            self.q,
        )
        self.thread.start()

    def configure(self, updated):
        if "client_replay" in updated and ctx.options.client_replay:
            try:
                flows = io.read_flows_from_paths(ctx.options.client_replay)
            except exceptions.FlowReadException as e:
                raise exceptions.OptionsError(str(e))
            self.start_replay(flows)

    @command.command("replay.client.count")
    def count(self) -> int:
        """
            Approximate number of flows queued for replay.
        """
        inflight = 1 if self.thread and self.thread.inflight.is_set() else 0
        return self.q.qsize() + inflight

    @command.command("replay.client.stop")
    def stop_replay(self) -> None:
        """
            Clear the replay queue.
        """
        with self.q.mutex:
            lst = list(self.q.queue)
            self.q.queue.clear()
            for f in lst:
                f.revert()
            ctx.master.addons.trigger("update", lst)
        ctx.log.alert("Client replay queue cleared.")

    @command.command("replay.client")
    def start_replay(self, flows: typing.Sequence[flow.Flow]) -> None:
        """
            Add flows to the replay queue, skipping flows that can't be replayed.
        """
        lst = []
        for f in flows:
            hf = typing.cast(http.HTTPFlow, f)

            err = self.check(hf)
            if err:
                ctx.log.warn(err)
                continue

            lst.append(hf)
            # Prepare the flow for replay
            hf.backup()
            hf.request.is_replay = True
            hf.response = None
            hf.error = None
            # https://github.com/mitmproxy/mitmproxy/issues/2197
            if hf.request.http_version == "HTTP/2.0":
                hf.request.http_version = "HTTP/1.1"
                host = hf.request.headers.pop(":authority", None)
                if host is not None:
                    hf.request.headers.insert(0, "host", host)
            self.q.put(hf)
        ctx.master.addons.trigger("update", lst)

    @command.command("replay.client.file")
    def load_file(self, path: mitmproxy.types.Path) -> None:
        """
            Load flows from file, and add them to the replay queue.
        """
        try:
            flows = io.read_flows_from_paths([path])
        except exceptions.FlowReadException as e:
            raise exceptions.CommandError(str(e))
        self.start_replay(flows)