Inline Scripts

mitmproxy has a powerful scripting API that allows you to modify flows on-the-fly or rewrite previously saved flows locally.

The mitmproxy scripting API is event driven - a script is simply a Python module that exposes a set of event methods. Here’s a complete mitmproxy script that adds a new header to every HTTP response before it is returned to the client:

examples/add_header.py
def response(context, flow):
    flow.response.headers["newheader"] = "foo"

The first argument to each event method is an instance of ScriptContext that lets the script interact with the global mitmproxy state. The response event also gets an instance of ScriptContext, which we can use to manipulate the response itself.

We can now run this script using mitmdump or mitmproxy as follows:

>>> mitmdump -s add_header.py

The new header will be added to all responses passing through the proxy.

Examples

mitmproxy comes with a variety of example inline scripts, which demonstrate many basic tasks. We encourage you to either browse them locally or on GitHub.

Events

The context argument passed to each event method is always a ScriptContext instance. It is guaranteed to be the same object for the scripts lifetime and is not shared between multiple inline scripts. You can safely use it to store any form of state you require.

Script Lifecycle Events

start(context, argv)

Called once on startup, before any other events.

Parameters:argv (List[str]) – The inline scripts’ arguments. For example, mitmproxy -s 'example.py --foo 42' sets argv to ["--foo", "42"].
done(context)

Called once on script shutdown, after any other events.

Connection Events

clientconnect(context, root_layer)

Called when a client initiates a connection to the proxy. Note that a connection can correspond to multiple HTTP requests.

Changed in version 0.14.

Parameters:root_layer (Layer) – The root layer (see Protocols for an explanation what the root layer is), which provides transparent access to all attributes of the RootContext. For example, root_layer.client_conn.address gives the remote address of the connecting client.
clientdisconnect(context, root_layer)

Called when a client disconnects from the proxy.

Changed in version 0.14.

Parameters:root_layer (Layer) – see clientconnect()
serverconnect(context, server_conn)

Called before the proxy initiates a connection to the target server. Note that a connection can correspond to multiple HTTP requests.

Parameters:server_conn (ServerConnection) – The server connection object. It is guaranteed to have a non-None address attribute.
serverdisconnect(context, server_conn)

Called when the proxy has closed the server connection.

New in version 0.14.

Parameters:server_conn (ServerConnection) – see serverconnect()

HTTP Events

request(context, flow)

Called when a client request has been received. The flow object is guaranteed to have a non-None request attribute.

Parameters:flow (HTTPFlow) – The flow containing the request which has been received. The object is guaranteed to have a non-None request attribute.
responseheaders(context, flow)

Called when the headers of a server response have been received. This will always be called before the response hook.

Parameters:flow (HTTPFlow) – The flow containing the request and response. The object is guaranteed to have non-None request and response attributes. response.content will be None, as the response body has not been read yet.
response(context, flow)

Called when a server response has been received.

Parameters:flow (HTTPFlow) – The flow containing the request and response. The object is guaranteed to have non-None request and response attributes. response.body will contain the raw response body, unless response streaming has been enabled.
error(context, flow)

Called when a flow error has occurred, e.g. invalid server responses, or interrupted connections. This is distinct from a valid server HTTP error response, which is simply a response with an HTTP error code.

Parameters:flow (HTTPFlow) – The flow containing the error. It is guaranteed to have non-None error attribute.

TCP Events

tcp_message(context, tcp_msg)

Warning

API is subject to change

If the proxy is in TCP mode, this event is called when it receives a TCP payload from the client or server.

The sender and receiver are identifiable. The message is user-modifiable.

Parameters:tcp_msg (TcpMessage) – see examples/tcp_message.py

API

The canonical API documentation is the code, which you can browse here, locally or on GitHub. Use the Source, Luke!

The main classes you will deal with in writing mitmproxy scripts are:

ScriptContext
  • A handle for interacting with mitmproxy’s Flow Master from within scripts.
ClientConnection
  • Describes a client connection.
ServerConnection
  • Describes a server connection.
HTTPFlow
  • A collection of objects representing a single HTTP transaction.
HTTPRequest
  • An HTTP request.
HTTPResponse
  • An HTTP response.
Error
  • A communications error.
netlib.http.Headers
  • A dictionary-like object for managing HTTP headers.
netlib.certutils.SSLCert
  • Exposes information SSL certificates.
mitmproxy.flow.FlowMaster
  • The “heart” of mitmproxy, usually subclassed as mitmproxy.dump.DumpMaster or mitmproxy.console.ConsoleMaster.

Script Context

class mitmproxy.script.ScriptContext(master)[source]

The script context should be used to interact with the global mitmproxy state from within a script.

log(message, level='info')[source]

Logs an event.

By default, only events with level “error” get displayed. This can be controlled with the “-v” switch. How log messages are handled depends on the front-end. mitmdump will print them to stdout, mitmproxy sends output to the eventlog for display (“e” keyboard shortcut).

kill_flow(f)[source]

Kills a flow immediately. No further data will be sent to the client or the server.

duplicate_flow(f)[source]

Returns a duplicate of the specified flow. The flow is also injected into the current state, and is ready for editing, replay, etc.

replay_request(f)[source]

Replay the request on the current flow. The response will be added to the flow object.

app_registry
add_contentview(view_obj)[source]
remove_contentview(view_obj)[source]

Running scripts in parallel

We have a single flow primitive, so when a script is blocking, other requests are not processed. While that’s usually a very desirable behaviour, blocking scripts can be run threaded by using the mitmproxy.script.concurrent decorator. If your script does not block, you should avoid the overhead of the decorator.

examples/nonblocking.py
import time
from mitmproxy.script import concurrent


@concurrent  # Remove this and see what happens
def request(context, flow):
    print("handle request: %s%s" % (flow.request.host, flow.request.path))
    time.sleep(5)
    print("start  request: %s%s" % (flow.request.host, flow.request.path))

Make scripts configurable with arguments

Sometimes, you want to pass runtime arguments to the inline script. This can be simply done by surrounding the script call with quotes, e.g. `mitmdump -s 'script.py --foo 42'. The arguments are then exposed in the start event:

examples/modify_response_body.py
# Usage: mitmdump -s "modify_response_body.py mitmproxy bananas"
# (this script works best with --anticache)
from mitmproxy.models import decoded


def start(context, argv):
    if len(argv) != 3:
        raise ValueError('Usage: -s "modify_response_body.py old new"')
    # You may want to use Python's argparse for more sophisticated argument
    # parsing.
    context.old, context.new = argv[1], argv[2]


def response(context, flow):
    with decoded(flow.response):  # automatically decode gzipped responses.
        flow.response.content = flow.response.content.replace(
            context.old,
            context.new)

Running scripts on saved flows

Sometimes, we want to run a script on Flow objects that are already complete. This happens when you start a script, and then load a saved set of flows from a file (see the “scripted data transformation” example here). It also happens when you run a one-shot script on a single flow through the | (pipe) shortcut in mitmproxy.

In this case, there are no client connections, and the events are run in the following order: start, request, responseheaders, response, error, done. If the flow doesn’t have a response or error associated with it, the matching events will be skipped.

Spaces in the script path

By default, spaces are interpreted as a separator between the inline script and its arguments (e.g. -s 'foo.py 42'). Consequently, the script path needs to be wrapped in a separate pair of quotes if it contains spaces: -s '\'./foo bar/baz.py\' 42'.