mitmproxy load script using API (Python)

2.1k views Asked by At

Good day,

I am trying to implement the mitmproxy into a bigger application. For that, I need to be able to load those so called inline scripts in my code and not via command line. I could not find any helpful information about that in the documentation.

I am using mitmproxy version 0.17 and Python 2.7.

I know there is a newer version available, but that one didnt worked using the code examples.

This is the base code I have:

from mitmproxy import controller, proxy
from mitmproxy.proxy.server import ProxyServer


class ProxyMaster(controller.Master):
    def __init__(self, server):
        controller.Master.__init__(self, server)

    def run(self):
        try:
            return controller.Master.run(self)
        except KeyboardInterrupt:
            self.shutdown()

    def handle_request(self, flow):
        flow.reply()

    def handle_response(self, flow):
        flow.reply()


config = proxy.ProxyConfig(port=8080)
server = ProxyServer(config)
m = ProxyMaster(server)
m.run()

How could I run this proxy using inline scripts?

Thanks in advance

1

There are 1 answers

0
AudioBubble On BEST ANSWER

I figured myself out a really ugly workaround.

Instead of using controller.Master I had to use flow.FlowMaster as the controller.Master lib does not seem to be able to handle inline scripts.

For some reason just loading the files did not work, they get triggered immediately, but not by running their matching hooks.

Instead of using the hooks which are not working, I am loading the matching functions as you can see in handle_response (try/except is missing and threading could be useful)

from mitmproxy import flow, proxy
from mitmproxy.proxy.server import ProxyServer
import imp


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

    def handle_request(self, flow):
        flow.reply()

    def handle_response(self, flow):
        for inline_script in self.scripts:
            script_file = imp.load_source("response", inline_script.filename)
            script_file.response(self, flow)

        flow.reply()


proxy_config = proxy.ProxyConfig(port=8080)
server = ProxyServer(proxy_config)
state = flow.State()
m = ProxyMaster(server, state)

m.load_script("upsidedowninternet.py")
m.load_script("add_header.py")

m.run()

Any ideas about doing it the right way are appreciated.