Search code examples
pythonconcurrencyproxymitmproxylibmproxy

Mitmproxy load and unload scripts with python


I'm a running a proxy as suggested in Mitmproxy github examples:

from libmproxy import proxy, flow

class MitmProxy(flow.FlowMaster):
    def run(self):
        try:
            flow.FlowMaster.run(self)
        except KeyboardInterrupt:
            self.shutdown()

  
    def handle_request(self, r):
        f = flow.FlowMaster.handle_request(self, r)

        if f:
            r.reply()
        return f

    def handle_response(self, r):
        f = flow.FlowMaster.handle_response(self, r)
 
        if f:
            r.reply()
        return f



config = proxy.ProxyConfig(
    cacert = os.path.expanduser("~/.ssl/mitmproxy.pem")
)
state = flow.State()
server = proxy.ProxyServer(config, 8083)
m = MitmProxy(server, state)
try:
    m.run()
except Exception, e:
    print e.message
    m.shutdown()

I want to handle each request/response without blocking the others, for that i need to use the concurrent decorator and scripts

my question is: how do i load and unload scripts to the proxy running in this configuration?


Solution

  • You can use concurrent mode with script loading.
    Here is an example for this kind of usage

    I preferred to implement the mitmproxy logic in the flow level.
    You can use this code

    def handle_response(self, r):
        reply = f.response.reply
            f.response.reply = controller.DummyReply()
            if hasattr(reply, "q"):
                f.response.reply.q = reply.q
            def run(): 
                pass
            threading.Thread(target=run)