pythonmitmproxy

How do I modify the JSON Body in a POST request with mitmproxy?


I am working with an app that sends data to a server with a POST request,

POST https://www.somedomain.com//sendImage HTTP/2.0

looking like this:

{
"user": {
    "consent": true,
    "currentNumberIs": 1,
    "images": {
        "data": "BASE64ENCODED IMAGE",
        "docType": "avatar"
    },
    "totalNumberOfImages": 1
}

}

I want to replace the data part of this Json, but only if the docType is avatar. Trying to use a python script for that, that I found here and edited:

def response(flow: http.HTTPFlow) -> None:
 if "somedomain.com" in flow.request.pretty_url:
    request_data = json.loads(flow.request.get_text())
    if request_data["user"]["images"]["docType"] == "avatar":
        data = json.loads(flow.response.get_text())
        data["user"]["images"]["data"] = "NEWDATA"
        flow.response.text = json.dumps(data)

Launched mitmproxy with -s script.py, but according to the web console, the specific request does not trigger the script at all. Which kinda limits the scope to debug.

Would glady appreciate any help.


Solution

  • As @nneonneo mentioned in the comments, I would first recommend to make extensive use of mitmproxy.ctx.log() to make sure that your event hook is triggered properly. Second, if I understand things correctly, you intend to modify the request and not the response? If you want to modify request contents before they are sent to the server, you need to use the request hook and not the response hook:

    def request(flow: http.HTTPFlow) -> None:
        # this is executed after we have received the request 
        # from the client, but before it is sent to the server.
    
    def response(flow: http.HTTPFlow) -> None:
        # this is executed after we have sent the request 
        # to the server and received the response at the proxy.
    

    Finally, you currently read from flow.request.text and then later assign to flow.response.text. I don't know your specific use case, but usually that should be flow.request.text as well.