Search code examples
pythonmitmproxy

How to write a mitmproxy addon that avoids any network request?


I tried mitmproxy in the last couple of days as a test tool and works excellent. However, while I'm able to write add-ons that intercept requests (even changing their URL, like my example below), I couldn't avoid that the request is actually dispatched in the network.

One way or another, always the request is performed using the network.

So, how can I modify my add-on in a way that, giving a request, it returns a fixed response, avoiding any networking request?

class Interceptor:
    def request(self, flow: http.HTTPFlow):
        if http.method() == "GET":
            flow.request.url = "http://google.com"

    def response(self, flow: http.HTTPFlow):
        return http.HTTPResponse.make(status_code=200,b"Rambo 5")

Solution

  • The request hook will be executed when mitmproxy has received the request, the response hook will be executed once we have fetched the response from the server. Long story short, everything in the response hook is too late.

    Instead, you need to assign flow.response in the request hook.