Search code examples
pythonpython-3.xmitmproxy

Change images in HTTPResponse with mitmproxy


For a school project we setup mitmproxy on Kali Linux. Finally, we were able to install mitmproxy and we can now intercept HTTPS packages of client devices, which browse websites as WLAN clients of our Raspberry Pi. One of our goals is to change images in HTTPS packages and we really would like to achieve this in our project. And here comes the point, I do not get this working with Python 3 inline scripts. This is what I am currently at.

#!/usr/bin/python3
# modify_response.py
import sys
import os
from io import StringIO
from mitmproxy.net.http import encoding
from mitmproxy.net.http import headers
from mitmproxy.net import http
from PIL.Image import core as _imaging

def response(flow):
    flow.response.headers["newheader"] = "response-flow"

    if flow.response.headers.get("content-type", "").startswith("image"):
        decoded_response = decode(flow.response)
        with decoded(flow.respnse):
        print('OK')
        os.system('"./script2.py" "Decoded response: {}"'.format(decoded_response))
        try:
            img = cStringIO.StringIO(open('6868132.png', 'rb').read())
            flow.response.content = img.getvalue()
        except:
            os.system('"./script2.py" "Error occured"')

Unfortunately, it seems that the if conditions is not true even with requests where the value of the header named "content-type" starts with "image".

I am referencing this website here https://sunu.in/manipulating-http-traffic-with-mitmproxy/ as I'd like to achieve the same thing they did there. But they probably used quite an old version of mitmproxy and we're using 2.0.2 (if I'm not mistaken).

I am quite new to Python and spent some hours doing online tutorials in order I can understand what my code does. Can you please help me with changing images in HTTPResponse?


Solution

  • I posted the same question in the mitmproxy forum and have received an answer there. The answer supplied contained the python scripting lines I was looking for:

    def response(flow):
        if flow.response.headers.get("content-type", "").startswith("image"):
            img = open("file.png", "rb").read()
            flow.response.content = img
            flow.response.headers["content-type"] = "image/png"