Change images in HTTPResponse

Hi there
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?

Here you go :slight_smile:

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"
1 Like

Hi

Thank you very very much for this! This were indeed the correct lines of code to replace images in HTTPReponse with a specific one we defnied. Thanks to you quick response, we were able to fulfill all goals of our school project. I’ll get a deeper look into Python in the future, but you saved me quite a lot of time I wouldn’t have had.

Cheers
Paul

2 Likes