pythonlinuxpacket-capturemitmproxytampering

Modifying HTTPS response packet on the fly with mitmproxy


I am trying to implement an mitmproxy addon script, in order to tamper with a particular https packet data - which is by the way decrypted on the fly through mitmproxy's certificate injection.

I am following this Stack Overflow answer to a rather similar question, as well as this tutorial from the mitmproxy docs, but without any success so far.

The packet I'm targeting comes from https://api.example.com/api/v1/user/info.
Now here is the whole python script I wrote so as to tamper with this packet data, based upon the aforementioned sources :

from mitmproxy import ctx

class RespModif:
    def _init_(self):
        self.num = 0

    def response(self, flow):
        ctx.log.info("RespModif triggered")

        if flow.request.url == "https://api.example.com/api/v1/user/info":
            ctx.log.info("RespModif triggered -- In the if statement")   
            self.num = self.num + 1
            ctx.log.info("RespModif -- Proceeded to %d response modifications "
                         "of the targetted URLs" % self.num)

addons = [
    RespModif()
]

Checking out the events log, I'm able to see that the first log information ("RespModif triggered") is being reported onto the log, but the two other log infos (done from inside the if statement) are never reported, which means I think that the if statement does never succeed.

Is there something wrong with my code ?
How can I get the if statement to succeed ?

PS: The target URL is definitely correct, plus I'm using it with a registered account from the client application that is being sniffed with mitmproxy.


Solution

  • Have you tried to use pretty_url attribute ?
    Something like :

    if flow.request.pretty_url == "https://api.example.com/api/v1/user/info":
        ....
    

    pretty_url attribute handles full domain name whereas url only deals with corresponding ip address.
    Also logging the content of pretty_url should allow to see what exact URL is going through and give more visibility as to what the code is actually doing.