mitmproxy/mitmproxy/contentviews.py

644 lines
18 KiB
Python
Raw Normal View History

2015-09-12 11:49:16 +00:00
"""
Mitmproxy Content Views
=======================
mitmproxy includes a set of content views which can be used to format/decode/highlight data.
While they are currently used for HTTP message bodies only, the may be used in other contexts
in the future, e.g. to decode protobuf messages sent as WebSocket frames.
Thus, the View API is very minimalistic. The only arguments are `data` and `**metadata`,
where `data` is the actual content (as bytes). The contents on metadata depend on the protocol in
use. For HTTP, the message headers are passed as the ``headers`` keyword argument. For HTTP
requests, the query parameters are passed as the ``query`` keyword argument.
2015-09-12 11:49:16 +00:00
"""
2016-06-01 02:06:57 +00:00
from __future__ import absolute_import, print_function, division
import datetime
2015-03-13 12:14:37 +00:00
import json
import logging
2015-09-04 15:07:14 +00:00
import subprocess
2015-09-11 11:37:52 +00:00
import sys
2016-06-01 02:06:57 +00:00
import html2text
2016-06-01 02:06:57 +00:00
import lxml.etree
import lxml.html
import six
2016-06-01 02:06:57 +00:00
from PIL import ExifTags
2016-06-01 02:25:47 +00:00
from PIL import Image
2016-06-20 18:52:00 +00:00
from six import BytesIO
2016-06-01 02:06:57 +00:00
from mitmproxy import exceptions
from mitmproxy.contrib import jsbeautifier
from mitmproxy.contrib.wbxml import ASCommandResponse
from netlib import encoding
from netlib import http
from netlib import multidict
2016-05-31 21:05:57 +00:00
from netlib.http import url
from netlib import strutils
2015-03-13 12:14:37 +00:00
2012-08-18 05:51:34 +00:00
try:
import pyamf
from pyamf import remoting, flex
2016-01-25 18:41:22 +00:00
except ImportError: # pragma no cover
2012-08-18 05:51:34 +00:00
pyamf = None
try:
import cssutils
2016-01-25 18:41:22 +00:00
except ImportError: # pragma no cover
cssutils = None
else:
cssutils.log.setLevel(logging.CRITICAL)
cssutils.ser.prefs.keepComments = True
cssutils.ser.prefs.omitLastSemicolon = False
cssutils.ser.prefs.indentClosingBrace = False
cssutils.ser.prefs.validOnly = False
2015-09-12 11:49:16 +00:00
# Default view cutoff *in lines*
VIEW_CUTOFF = 512
2015-09-04 15:07:14 +00:00
KEY_MAX = 30
def pretty_json(s):
# type: (bytes) -> bytes
try:
2016-06-20 18:52:00 +00:00
p = json.loads(s.decode('utf-8'))
except ValueError:
return None
pretty = json.dumps(p, sort_keys=True, indent=4, ensure_ascii=False)
if isinstance(pretty, six.text_type):
# json.dumps _may_ decide to return unicode, if the JSON object is not ascii.
# From limited testing this is always valid utf8 (otherwise json.loads will fail earlier),
# so we can just re-encode it here.
return pretty.encode("utf8", "strict")
return pretty
2015-09-04 15:07:14 +00:00
def format_dict(d):
"""
2015-09-12 11:49:16 +00:00
Helper function that transforms the given dictionary into a list of
2015-09-04 15:07:14 +00:00
("key", key )
("value", value)
tuples, where key is padded to a uniform width.
"""
max_key_len = max(len(k) for k in d.keys())
max_key_len = min(max_key_len, KEY_MAX)
for key, value in d.items():
key += ":"
key = key.ljust(max_key_len + 2)
2015-09-11 11:37:52 +00:00
yield [
2015-09-04 15:33:21 +00:00
("header", key),
("text", value)
2015-09-11 11:37:52 +00:00
]
2015-09-02 18:56:19 +00:00
2015-09-12 11:49:16 +00:00
def format_text(text):
"""
2015-09-12 11:49:16 +00:00
Helper function that transforms bytes into the view output format.
"""
2015-09-12 11:49:16 +00:00
for line in text.splitlines():
2015-09-11 11:37:52 +00:00
yield [("text", line)]
2015-09-04 15:07:14 +00:00
2015-09-04 15:33:21 +00:00
class View(object):
2015-09-04 15:07:14 +00:00
name = None
prompt = ()
content_types = []
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
2015-09-04 15:33:21 +00:00
"""
2015-09-12 11:49:16 +00:00
Transform raw data into human-readable output.
Args:
data: the data to decode/format as bytes.
metadata: optional keyword-only arguments for metadata. Implementations must not
rely on a given argument being present.
2015-09-04 15:33:21 +00:00
Returns:
2015-09-11 11:37:52 +00:00
A (description, content generator) tuple.
2015-09-12 11:49:16 +00:00
The content generator yields lists of (style, text) tuples, where each list represents
a single line. ``text`` is a unfiltered byte string which may need to be escaped,
depending on the used output.
Caveats:
The content generator must not yield tuples of tuples,
because urwid cannot process that. You have to yield a *list* of tuples per line.
2015-09-04 15:33:21 +00:00
"""
2015-09-04 15:07:14 +00:00
raise NotImplementedError()
class ViewAuto(View):
2012-08-18 05:08:17 +00:00
name = "Auto"
prompt = ("auto", "a")
content_types = []
2015-03-13 12:14:37 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
headers = metadata.get("headers", {})
ctype = headers.get("content-type")
if data and ctype:
2016-05-31 21:05:57 +00:00
ct = http.parse_content_type(ctype) if ctype else None
2015-05-30 00:03:28 +00:00
ct = "%s/%s" % (ct[0], ct[1])
if ct in content_types_map:
2015-09-12 11:49:16 +00:00
return content_types_map[ct][0](data, **metadata)
2016-06-20 18:52:00 +00:00
elif strutils.isXML(data.decode()):
2015-09-12 11:49:16 +00:00
return get("XML")(data, **metadata)
if metadata.get("query"):
return get("Query")(data, **metadata)
2016-06-20 18:52:00 +00:00
if data and strutils.isMostlyBin(data.decode()):
return get("Hex")(data)
if not data:
return "No content", []
2015-09-12 11:49:16 +00:00
return get("Raw")(data)
2015-09-04 15:07:14 +00:00
class ViewRaw(View):
2012-08-18 05:08:17 +00:00
name = "Raw"
prompt = ("raw", "r")
content_types = []
2015-03-13 12:14:37 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
return "Raw", format_text(strutils.bytes_to_escaped_str(data, True))
2015-09-04 15:07:14 +00:00
class ViewHex(View):
2012-08-18 05:08:17 +00:00
name = "Hex"
prompt = ("hex", "e")
content_types = []
2015-03-13 12:14:37 +00:00
2015-09-04 15:07:14 +00:00
@staticmethod
2015-09-12 11:49:16 +00:00
def _format(data):
for offset, hexa, s in strutils.hexdump(data):
2015-09-11 11:37:52 +00:00
yield [
2015-09-04 15:07:14 +00:00
("offset", offset + " "),
("text", hexa + " "),
2015-09-11 11:37:52 +00:00
("text", s)
]
2015-09-04 15:07:14 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
return "Hex", self._format(data)
2012-08-18 05:08:17 +00:00
2015-09-04 15:07:14 +00:00
class ViewXML(View):
2012-08-18 05:08:17 +00:00
name = "XML"
prompt = ("xml", "x")
content_types = ["text/xml"]
2015-03-13 12:14:37 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
2015-03-13 12:14:37 +00:00
parser = lxml.etree.XMLParser(
remove_blank_text=True,
resolve_entities=False,
strip_cdata=False,
recover=False
)
2012-08-18 05:08:17 +00:00
try:
2015-09-12 11:49:16 +00:00
document = lxml.etree.fromstring(data, parser)
2012-08-18 05:08:17 +00:00
except lxml.etree.XMLSyntaxError:
return None
docinfo = document.getroottree().docinfo
prev = []
p = document.getroottree().getroot().getprevious()
while p is not None:
prev.insert(
0,
lxml.etree.tostring(p)
)
p = p.getprevious()
2015-03-13 12:14:37 +00:00
doctype = docinfo.doctype
2012-08-18 05:08:17 +00:00
if prev:
2016-06-20 18:52:00 +00:00
doctype += "\n".join(p.decode() for p in prev).strip()
2012-08-18 05:08:17 +00:00
doctype = doctype.strip()
s = lxml.etree.tostring(
2015-03-13 12:14:37 +00:00
document,
pretty_print=True,
xml_declaration=True,
doctype=doctype or None,
2015-09-04 15:07:14 +00:00
encoding=docinfo.encoding
2015-03-13 12:14:37 +00:00
)
2012-08-18 05:08:17 +00:00
2015-09-12 11:49:16 +00:00
return "XML-like data", format_text(s)
2012-08-18 05:08:17 +00:00
2015-09-04 15:07:14 +00:00
class ViewJSON(View):
2012-08-18 05:08:17 +00:00
name = "JSON"
prompt = ("json", "s")
2012-08-18 05:08:17 +00:00
content_types = ["application/json"]
2015-03-13 12:14:37 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
pj = pretty_json(data)
if pj:
return "JSON", format_text(pj)
2012-08-18 05:08:17 +00:00
2015-09-04 15:33:21 +00:00
class ViewHTML(View):
2012-08-18 05:08:17 +00:00
name = "HTML"
prompt = ("html", "h")
content_types = ["text/html"]
2015-03-13 12:14:37 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
2016-06-20 18:52:00 +00:00
if strutils.isXML(data.decode()):
2015-03-13 12:14:37 +00:00
parser = lxml.etree.HTMLParser(
strip_cdata=True,
remove_blank_text=True
)
2015-09-12 11:49:16 +00:00
d = lxml.html.fromstring(data, parser=parser)
2012-08-18 05:08:17 +00:00
docinfo = d.getroottree().docinfo
2015-03-13 12:14:37 +00:00
s = lxml.etree.tostring(
d,
pretty_print=True,
doctype=docinfo.doctype,
encoding='utf8'
2015-03-13 12:14:37 +00:00
)
2015-09-12 11:49:16 +00:00
return "HTML", format_text(s)
2012-08-18 05:08:17 +00:00
2015-09-04 15:33:21 +00:00
class ViewHTMLOutline(View):
2012-08-18 05:08:17 +00:00
name = "HTML Outline"
prompt = ("html outline", "o")
content_types = ["text/html"]
2015-03-13 12:14:37 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
data = data.decode("utf-8")
2012-08-18 05:08:17 +00:00
h = html2text.HTML2Text(baseurl="")
h.ignore_images = True
h.body_width = 0
2015-09-12 11:49:16 +00:00
outline = h.handle(data)
return "HTML Outline", format_text(outline)
2012-08-18 05:08:17 +00:00
2015-09-04 15:33:21 +00:00
class ViewURLEncoded(View):
2012-08-18 05:08:17 +00:00
name = "URL-encoded"
prompt = ("urlencoded", "u")
content_types = ["application/x-www-form-urlencoded"]
2015-03-13 12:14:37 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
d = url.decode(data)
return "URLEncoded form", format_dict(multidict.MultiDict(d))
2012-08-18 05:08:17 +00:00
2015-09-04 15:33:21 +00:00
class ViewMultipart(View):
2012-08-18 05:08:17 +00:00
name = "Multipart Form"
prompt = ("multipart", "m")
content_types = ["multipart/form-data"]
2015-03-13 12:14:37 +00:00
2015-09-04 15:33:21 +00:00
@staticmethod
def _format(v):
2015-09-11 11:37:52 +00:00
yield [("highlight", "Form data:\n")]
for message in format_dict(multidict.MultiDict(v)):
2015-09-04 15:33:21 +00:00
yield message
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
headers = metadata.get("headers", {})
2016-05-31 21:05:57 +00:00
v = http.multipart.decode(headers, data)
2012-08-18 05:08:17 +00:00
if v:
2015-09-04 15:33:21 +00:00
return "Multipart form", self._format(v)
2012-08-18 05:08:17 +00:00
if pyamf:
class DummyObject(dict):
2016-01-27 09:12:18 +00:00
def __init__(self, alias):
dict.__init__(self)
def __readamf__(self, input):
data = input.readObject()
self["data"] = data
def pyamf_class_loader(s):
for i in pyamf.CLASS_LOADERS:
if i != pyamf_class_loader:
v = i(s)
if v:
return v
return DummyObject
pyamf.register_class_loader(pyamf_class_loader)
2015-09-04 15:33:21 +00:00
class ViewAMF(View):
name = "AMF"
prompt = ("amf", "f")
content_types = ["application/x-amf"]
2016-06-19 08:52:05 +00:00
def unpack(self, b, seen=None):
if seen is None:
seen = set([])
if hasattr(b, "body"):
return self.unpack(b.body, seen)
if isinstance(b, DummyObject):
if id(b) in seen:
return "<recursion>"
else:
seen.add(id(b))
for k, v in b.items():
b[k] = self.unpack(v, seen)
return b
elif isinstance(b, dict):
for k, v in b.items():
b[k] = self.unpack(v, seen)
return b
elif isinstance(b, list):
return [self.unpack(i) for i in b]
elif isinstance(b, datetime.datetime):
return str(b)
elif isinstance(b, flex.ArrayCollection):
return [self.unpack(i, seen) for i in b]
else:
return b
2015-09-12 11:49:16 +00:00
def _format(self, envelope):
for target, message in iter(envelope):
if isinstance(message, pyamf.remoting.Request):
2015-09-11 11:37:52 +00:00
yield [
("header", "Request: "),
("text", str(target)),
2015-09-11 11:37:52 +00:00
]
else:
2015-09-11 11:37:52 +00:00
yield [
("header", "Response: "),
2015-05-30 00:03:28 +00:00
("text", "%s, code %s" % (target, message.status)),
2015-09-11 11:37:52 +00:00
]
s = json.dumps(self.unpack(message), indent=4)
2015-09-12 11:49:16 +00:00
for msg in format_text(s):
2015-09-04 15:33:21 +00:00
yield msg
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
envelope = remoting.decode(data, strict=False)
2015-09-11 11:37:52 +00:00
if envelope:
2015-09-12 11:49:16 +00:00
return "AMF v%s" % envelope.amfVersion, self._format(envelope)
2012-08-18 05:08:17 +00:00
2015-09-04 15:33:21 +00:00
class ViewJavaScript(View):
2012-08-18 05:08:17 +00:00
name = "JavaScript"
prompt = ("javascript", "j")
content_types = [
"application/x-javascript",
"application/javascript",
"text/javascript"
]
2015-03-13 12:14:37 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
2012-08-18 05:08:17 +00:00
opts = jsbeautifier.default_options()
opts.indent_size = 2
2015-09-12 11:49:16 +00:00
res = jsbeautifier.beautify(data, opts)
return "JavaScript", format_text(res)
2015-03-13 12:14:37 +00:00
2015-09-04 15:33:21 +00:00
class ViewCSS(View):
name = "CSS"
prompt = ("css", "c")
content_types = [
"text/css"
]
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
if cssutils:
2015-09-12 11:49:16 +00:00
sheet = cssutils.parseString(data)
beautified = sheet.cssText
else:
2015-09-12 11:49:16 +00:00
beautified = data
2015-09-12 11:49:16 +00:00
return "CSS", format_text(beautified)
2012-08-18 05:08:17 +00:00
2015-09-04 15:33:21 +00:00
class ViewImage(View):
2012-08-18 05:08:17 +00:00
name = "Image"
prompt = ("image", "i")
content_types = [
"image/png",
"image/jpeg",
"image/gif",
"image/vnd.microsoft.icon",
"image/x-icon",
]
2015-03-13 12:14:37 +00:00
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
2012-08-18 05:08:17 +00:00
try:
2016-06-20 18:52:00 +00:00
img = Image.open(BytesIO(data))
2012-08-18 05:08:17 +00:00
except IOError:
return None
parts = [
("Format", str(img.format_description)),
2015-05-30 00:03:28 +00:00
("Size", "%s x %s px" % img.size),
2012-08-18 05:08:17 +00:00
("Mode", str(img.mode)),
]
2012-08-18 05:08:17 +00:00
for i in sorted(img.info.keys()):
if i != "exif":
parts.append(
(str(i), str(img.info[i]))
)
if hasattr(img, "_getexif"):
ex = img._getexif()
if ex:
for i in sorted(ex.keys()):
2016-06-01 02:06:57 +00:00
tag = ExifTags.TAGS.get(i, i)
2012-08-18 05:08:17 +00:00
parts.append(
(str(tag), str(ex[i]))
)
fmt = format_dict(multidict.MultiDict(parts))
2015-05-30 00:03:28 +00:00
return "%s image" % img.format, fmt
2012-08-18 05:08:17 +00:00
2015-03-13 12:14:37 +00:00
2015-09-04 15:33:21 +00:00
class ViewProtobuf(View):
2016-01-27 09:12:18 +00:00
"""Human friendly view of protocol buffers
The view uses the protoc compiler to decode the binary
"""
name = "Protocol Buffer"
prompt = ("protobuf", "p")
content_types = [
"application/x-protobuf",
"application/x-protobuffer",
]
@staticmethod
def is_available():
try:
2015-03-13 12:14:37 +00:00
p = subprocess.Popen(
["protoc", "--version"],
stdout=subprocess.PIPE
)
out, _ = p.communicate()
return out.startswith("libprotoc")
except:
return False
def decode_protobuf(self, content):
# if Popen raises OSError, it will be caught in
# get_content_view and fall back to Raw
p = subprocess.Popen(['protoc', '--decode_raw'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate(input=content)
if out:
return out
else:
return err
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
decoded = self.decode_protobuf(data)
return "Protobuf", format_text(decoded)
2012-08-18 05:08:17 +00:00
2015-03-13 12:14:37 +00:00
class ViewQuery(View):
name = "Query"
prompt = ("query", "q")
content_types = []
def __call__(self, data, **metadata):
query = metadata.get("query")
if query:
return "Query", format_dict(query)
else:
return "Query", format_text("")
2015-09-04 15:33:21 +00:00
class ViewWBXML(View):
2014-05-06 17:27:13 +00:00
name = "WBXML"
prompt = ("wbxml", "w")
content_types = [
"application/vnd.wap.wbxml",
"application/vnd.ms-sync.wbxml"
]
2015-09-12 11:49:16 +00:00
def __call__(self, data, **metadata):
2015-03-13 12:14:37 +00:00
2014-05-06 17:27:13 +00:00
try:
2016-06-01 02:06:57 +00:00
parser = ASCommandResponse.ASCommandResponse(data)
2014-05-06 17:27:13 +00:00
parsedContent = parser.xmlString
2015-09-11 11:37:52 +00:00
if parsedContent:
2015-09-12 11:49:16 +00:00
return "WBXML", format_text(parsedContent)
2014-05-06 17:27:13 +00:00
except:
2015-03-13 12:14:37 +00:00
return None
2014-05-06 17:27:13 +00:00
2015-09-04 15:07:14 +00:00
2015-11-13 21:55:27 +00:00
views = []
2012-08-18 05:08:17 +00:00
content_types_map = {}
2015-11-13 21:55:27 +00:00
view_prompts = []
2015-11-26 13:58:08 +00:00
def get(name):
for i in views:
if i.name == name:
return i
2012-08-18 05:08:17 +00:00
def get_by_shortcut(c):
for i in views:
if i.prompt[1] == c:
return i
2015-11-13 21:55:27 +00:00
def add(view):
# TODO: auto-select a different name (append an integer?)
2015-11-09 16:06:16 +00:00
for i in views:
2015-11-13 21:55:27 +00:00
if i.name == view.name:
2016-06-01 02:06:57 +00:00
raise exceptions.ContentViewException("Duplicate view: " + view.name)
2015-11-09 16:06:16 +00:00
2015-11-13 21:55:27 +00:00
# TODO: the UI should auto-prompt for a replacement shortcut
for prompt in view_prompts:
2015-11-13 21:55:27 +00:00
if prompt[1] == view.prompt[1]:
2016-06-01 02:06:57 +00:00
raise exceptions.ContentViewException("Duplicate view shortcut: " + view.prompt[1])
2015-11-13 21:55:27 +00:00
views.append(view)
for ct in view.content_types:
l = content_types_map.setdefault(ct, [])
l.append(view)
view_prompts.append(view.prompt)
2015-11-09 16:06:16 +00:00
2015-11-13 21:55:27 +00:00
def remove(view):
for ct in view.content_types:
l = content_types_map.setdefault(ct, [])
2015-11-13 21:55:27 +00:00
l.remove(view)
if not len(l):
del content_types_map[ct]
view_prompts.remove(view.prompt)
views.remove(view)
2015-11-13 21:55:27 +00:00
add(ViewAuto())
add(ViewRaw())
add(ViewHex())
add(ViewJSON())
add(ViewXML())
add(ViewWBXML())
add(ViewHTML())
add(ViewHTMLOutline())
add(ViewJavaScript())
add(ViewCSS())
add(ViewURLEncoded())
add(ViewMultipart())
add(ViewImage())
add(ViewQuery())
2015-11-13 21:55:27 +00:00
if pyamf:
add(ViewAMF())
if ViewProtobuf.is_available():
add(ViewProtobuf())
2015-11-09 16:06:16 +00:00
def safe_to_print(lines, encoding="utf8"):
"""
Wraps a content generator so that each text portion is a *safe to print* unicode string.
"""
for line in lines:
clean_line = []
for (style, text) in line:
if isinstance(text, bytes):
text = text.decode(encoding, "replace")
text = strutils.escape_control_characters(text)
clean_line.append((style, text))
yield clean_line
2015-09-12 11:49:16 +00:00
def get_content_view(viewmode, data, **metadata):
"""
2015-09-12 11:49:16 +00:00
Args:
viewmode: the view to use.
data, **metadata: arguments passed to View instance.
2015-09-02 18:56:19 +00:00
Returns:
2015-09-11 11:37:52 +00:00
A (description, content generator) tuple.
In contrast to calling the views directly, text is always safe-to-print unicode.
2015-09-02 18:56:19 +00:00
Raises:
ContentViewException, if the content view threw an error.
"""
msg = []
2015-09-12 11:49:16 +00:00
headers = metadata.get("headers", {})
2015-09-05 18:45:58 +00:00
enc = headers.get("content-encoding")
if enc and enc != "identity":
2015-09-12 11:49:16 +00:00
decoded = encoding.decode(enc, data)
if decoded:
2015-09-12 11:49:16 +00:00
data = decoded
2015-05-30 00:03:28 +00:00
msg.append("[decoded %s]" % enc)
try:
2015-09-12 11:49:16 +00:00
ret = viewmode(data, **metadata)
# Third-party viewers can fail in unexpected ways...
except Exception as e:
six.reraise(
2016-06-01 02:06:57 +00:00
exceptions.ContentViewException,
exceptions.ContentViewException(str(e)),
sys.exc_info()[2]
)
if not ret:
2015-09-12 11:49:16 +00:00
ret = get("Raw")(data, **metadata)
msg.append("Couldn't parse: falling back to Raw")
else:
msg.append(ret[0])
return " ".join(msg), safe_to_print(ret[1])