API

Errors

class mitmproxy.flow.Error(msg: str, timestamp=None) → None[source][source]

An Error.

This is distinct from an protocol error response (say, a HTTP code 500), which is represented by a normal HTTPResponse object. This class is responsible for indicating errors that fall outside of normal protocol communications, like interrupted connections, timeouts, protocol errors.

Exposes the following attributes:

msg: Message describing the error timestamp: Seconds since the epoch
get_state()[source]

Retrieve object state.

set_state(state)[source]

Load object state from data returned by a get_state call.

HTTP

class mitmproxy.http.HTTPRequest(first_line_format, method, scheme, host, port, path, http_version, headers, content, timestamp_start=None, timestamp_end=None, is_replay=False)[source][source]

A mitmproxy HTTP request.

classmethod wrap(request)[source][source]

Wraps an existing mitmproxy.net.http.Request.

anticache()[source]

Modifies this request to remove headers that might produce a cached response. That is, we remove ETags and If-Modified-Since headers.

anticomp()[source]

Modifies this request to remove headers that will compress the resource’s data.

constrain_encoding()[source]

Limits the permissible Accept-Encoding values, based on what we can decode appropriately.

content

The HTTP message body decoded with the content-encoding header (e.g. gzip)

Raises:ValueError, when the content-encoding is invalid and strict is True.

See also: raw_content, text

cookies

The request cookies.

An empty MultiDictView object if the cookie monster ate them all.

decode(strict=True)[source]

Decodes body based on the current Content-Encoding header, then removes the header. If there is no Content-Encoding header, no action is taken.

Raises:ValueError, when the content-encoding is invalid and strict is True.
encode(e)[source]

Encodes body with the encoding e, where e is “gzip”, “deflate”, “identity”, or “br”. Any existing content-encodings are overwritten, the content is not decoded beforehand.

Raises:ValueError, when the specified content-encoding is invalid.
first_line_format

HTTP request form as defined in RFC7230.

origin-form and asterisk-form are subsumed as “relative”.

get_content(strict: bool=True) → bytes[source]

The HTTP message body decoded with the content-encoding header (e.g. gzip)

Raises:ValueError, when the content-encoding is invalid and strict is True.

See also: raw_content, text

get_text(strict: bool=True) → typing.Union[str, NoneType][source]

The HTTP message body decoded with both content-encoding header (e.g. gzip) and content-type header charset.

Raises:ValueError, when either content-encoding or charset is invalid and strict is True.

See also: content, raw_content

headers

Message headers object

Returns:mitmproxy.net.http.Headers
host

Target host. This may be parsed from the raw request (e.g. from a GET http://example.com/ HTTP/1.1 request line) or inferred from the proxy mode (e.g. an IP in transparent mode).

Setting the host attribute also updates the host header, if present.

http_version

Version string, e.g. “HTTP/1.1”

method

HTTP request method, e.g. “GET”.

multipart_form

The multipart form data as an MultiDictView object. An empty multidict.MultiDictView if the content-type indicates non-form data or the content could not be parsed.

Key and value are bytes.

path

HTTP request path, e.g. “/index.html”. Guaranteed to start with a slash, except for OPTIONS requests, which may just be “*”.

path_components

The URL’s path components as a tuple of strings. Components are unquoted.

port

Target port

pretty_host

Similar to host, but using the Host headers as an additional preferred data source. This is useful in transparent mode where host is only an IP address, but may not reflect the actual destination as the Host header could be spoofed.

pretty_url

Like url, but using pretty_host instead of host.

query

The request query string as an MultiDictView object.

raw_content

The raw (encoded) HTTP message body

See also: content, text

replace(pattern, repl, flags=0, count=0)[source]

Replaces a regular expression pattern with repl in the headers, the request path and the body of the request. Encoded content will be decoded before replacement, and re-encoded afterwards.

Returns:The number of replacements made.
scheme

HTTP request scheme, which should be “http” or “https”.

text

The HTTP message body decoded with both content-encoding header (e.g. gzip) and content-type header charset.

Raises:ValueError, when either content-encoding or charset is invalid and strict is True.

See also: content, raw_content

timestamp_end

Last byte timestamp

timestamp_start

First byte timestamp

url

The URL string, constructed from the request’s URL components

urlencoded_form

The URL-encoded form data as an MultiDictView object. An empty multidict.MultiDictView if the content-type indicates non-form data or the content could not be parsed.

Starting with mitmproxy 1.0, key and value are strings.

class mitmproxy.http.HTTPResponse(http_version, status_code, reason, headers, content, timestamp_start=None, timestamp_end=None, is_replay=False)[source][source]

A mitmproxy HTTP response.

classmethod wrap(response)[source][source]

Wraps an existing mitmproxy.net.http.Response.

content

The HTTP message body decoded with the content-encoding header (e.g. gzip)

Raises:ValueError, when the content-encoding is invalid and strict is True.

See also: raw_content, text

cookies

The response cookies. A possibly empty MultiDictView, where the keys are cookie name strings, and values are (value, attr) tuples. Value is a string, and attr is an MultiDictView containing cookie attributes. Within attrs, unary attributes (e.g. HTTPOnly) are indicated by a Null value.

Caveats:
Updating the attr
decode(strict=True)[source]

Decodes body based on the current Content-Encoding header, then removes the header. If there is no Content-Encoding header, no action is taken.

Raises:ValueError, when the content-encoding is invalid and strict is True.
encode(e)[source]

Encodes body with the encoding e, where e is “gzip”, “deflate”, “identity”, or “br”. Any existing content-encodings are overwritten, the content is not decoded beforehand.

Raises:ValueError, when the specified content-encoding is invalid.
get_content(strict: bool=True) → bytes[source]

The HTTP message body decoded with the content-encoding header (e.g. gzip)

Raises:ValueError, when the content-encoding is invalid and strict is True.

See also: raw_content, text

get_text(strict: bool=True) → typing.Union[str, NoneType][source]

The HTTP message body decoded with both content-encoding header (e.g. gzip) and content-type header charset.

Raises:ValueError, when either content-encoding or charset is invalid and strict is True.

See also: content, raw_content

headers

Message headers object

Returns:mitmproxy.net.http.Headers
http_version

Version string, e.g. “HTTP/1.1”

make(status_code: int=200, content: ~AnyStr=b'', headers: typing.Union[typing.Dict[~AnyStr, ~AnyStr], typing.Iterable[typing.Tuple[bytes, bytes]]]=())[source]

Simplified API for creating response objects.

raw_content

The raw (encoded) HTTP message body

See also: content, text

reason

HTTP Reason Phrase, e.g. “Not Found”. This is always None for HTTP2 requests, because HTTP2 responses do not contain a reason phrase.

refresh(now=None)[source]

This fairly complex and heuristic function refreshes a server response for replay.

  • It adjusts date, expires and last-modified headers.
  • It adjusts cookie expiration.
replace(pattern, repl, flags=0, count=0)[source]

Replaces a regular expression pattern with repl in both the headers and the body of the message. Encoded body will be decoded before replacement, and re-encoded afterwards.

Returns:The number of replacements made.
status_code

HTTP Status Code, e.g. 200.

text

The HTTP message body decoded with both content-encoding header (e.g. gzip) and content-type header charset.

Raises:ValueError, when either content-encoding or charset is invalid and strict is True.

See also: content, raw_content

timestamp_end

Last byte timestamp

timestamp_start

First byte timestamp

class mitmproxy.http.HTTPFlow(client_conn, server_conn, live=None, mode='regular')[source][source]

An HTTPFlow is a collection of objects representing a single HTTP transaction.

request = None

HTTPRequest object

response = None

HTTPResponse object

error = None

Error object

Note that it’s possible for a Flow to have both a response and an error object. This might happen, for instance, when a response was received from the server, but there was an error sending it back to the client.

server_conn = None

ServerConnection object

client_conn = None

ClientConnection object

intercepted = None

Is this flow currently being intercepted?

mode = None

What mode was the proxy layer in when receiving this request?

backup(force=False)[source]

Save a backup of this Flow, which can be reverted to using a call to .revert().

intercept()[source]

Intercept this Flow. Processing will stop until resume is called.

kill()[source]

Kill this request.

modified()[source]

Has this Flow been modified?

resume()[source]

Continue with the flow - called after an intercept().

revert()[source]

Revert to the last backed up state.

replace(pattern, repl, *args, **kwargs)[source][source]

Replaces a regular expression pattern with repl in both request and response of the flow. Encoded content will be decoded before replacement, and re-encoded afterwards.

Returns the number of replacements made.

Logging

class mitmproxy.log.Log(master)[source][source]

The central logger, exposed to scripts as mitmproxy.ctx.log.

debug(txt)[source][source]

Log with level debug.

info(txt)[source][source]

Log with level info.

warn(txt)[source][source]

Log with level warn.

error(txt)[source][source]

Log with level error.

class mitmproxy.log.LogEntry(msg, level)[source][source]