Mitmproxy: Capture HTTP request / response headers?

I’m following the code from the following question (reproduced below):

def response(flow):
    print("")
    print("="*50)
    print(flow.request.method + " " + flow.request.path + " " + flow.request.http_version)

    print("-"*25 + " request headers " + "-"*25)
    for k, v in flow.request.headers.items():
        print("%-30s: %s" % (k.upper(), v))

    print("-"*25 + " response headers " + "-"*25)
    for k, v in flow.response.headers.items():
        print("%-30s: %s" % (k.upper(), v))

    print("-"*25 + " body (first 100 bytes) " + "-"*25)
    print(flow.request.content[0:100])

I have trouble understanding where, when using mitmproxy, you find the flow variable. How do you connect mitmproxy such that you could receive that flow of requests?

Answer

I was wrong. It looks like you pass in the script with the -s flag Something like:

mitmproxy -s myscript.py

Basically you pass in the file name and mitmproxy will load it and call the request() function, passing in the flow variable you mentioned.

I think reading these two pages might help. Note that they have different kinds of add-ons. I think the simple classless request() function you have would make it a ‘script’ type.

https://docs.mitmproxy.org/stable/addons-overview/

https://docs.mitmproxy.org/stable/addons-scripting/

There are also more examples in the docs. Also, I’ve found this GitHub repo to be helpful for examples:

https://github.com/KevCui/mitm-scripts