2014-09-14 00:22:28 +00:00
|
|
|
import os.path
|
2014-12-25 15:10:47 +00:00
|
|
|
import re
|
2014-09-14 00:22:28 +00:00
|
|
|
import tornado.web
|
2014-09-16 21:40:25 +00:00
|
|
|
import tornado.websocket
|
|
|
|
import logging
|
2014-09-17 01:58:56 +00:00
|
|
|
import json
|
2016-02-10 23:14:38 +00:00
|
|
|
import base64
|
2016-02-08 01:10:10 +00:00
|
|
|
|
|
|
|
from netlib.http import CONTENT_MISSING
|
2014-12-26 02:10:24 +00:00
|
|
|
from .. import version, filt
|
2014-09-14 00:22:28 +00:00
|
|
|
|
|
|
|
|
2016-02-08 01:10:10 +00:00
|
|
|
def _strip_content(flow_state):
|
|
|
|
"""
|
|
|
|
Remove flow message content and cert to save transmission space.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
flow_state: The original flow state. Will be left unmodified
|
|
|
|
"""
|
|
|
|
for attr in ("request", "response"):
|
|
|
|
if attr in flow_state:
|
|
|
|
message = flow_state[attr]
|
|
|
|
if message["content"]:
|
|
|
|
message["contentLength"] = len(message["content"])
|
|
|
|
elif message["content"] == CONTENT_MISSING:
|
|
|
|
message["contentLength"] = None
|
|
|
|
else:
|
|
|
|
message["contentLength"] = 0
|
|
|
|
del message["content"]
|
|
|
|
|
|
|
|
if "backup" in flow_state:
|
|
|
|
del flow_state["backup"]
|
|
|
|
flow_state["modified"] = True
|
|
|
|
|
|
|
|
flow_state.get("server_conn", {}).pop("cert", None)
|
|
|
|
|
|
|
|
return flow_state
|
|
|
|
|
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
class APIError(tornado.web.HTTPError):
|
|
|
|
pass
|
|
|
|
|
2014-12-25 15:10:47 +00:00
|
|
|
|
2016-02-10 23:14:38 +00:00
|
|
|
class BasicAuth(object):
|
|
|
|
def set_auth_headers(self):
|
|
|
|
self.set_status(401)
|
|
|
|
self.set_header('WWW-Authenticate', 'Basic realm=MITMWeb')
|
|
|
|
self._transforms = []
|
|
|
|
self.finish()
|
|
|
|
|
|
|
|
def initialize(self, **kwargs):
|
|
|
|
self.wauthenticator = kwargs.get("wauthenticator")
|
|
|
|
|
|
|
|
def prepare(self):
|
|
|
|
if self.wauthenticator:
|
|
|
|
auth_header = self.request.headers.get('Authorization')
|
|
|
|
if auth_header is None or not auth_header.startswith('Basic '):
|
|
|
|
self.set_auth_headers()
|
|
|
|
else:
|
|
|
|
self.auth_decoded = base64.decodestring(auth_header[6:])
|
|
|
|
self.username, self.password = self.auth_decoded.split(':', 2)
|
|
|
|
if not self.wauthenticator.test(self.username, self.password):
|
|
|
|
self.set_auth_headers()
|
|
|
|
raise APIError(401, "Invalid username or password.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class RequestHandler(BasicAuth, tornado.web.RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-25 15:10:47 +00:00
|
|
|
def set_default_headers(self):
|
|
|
|
super(RequestHandler, self).set_default_headers()
|
|
|
|
self.set_header("Server", version.NAMEVERSION)
|
|
|
|
self.set_header("X-Frame-Options", "DENY")
|
|
|
|
self.add_header("X-XSS-Protection", "1; mode=block")
|
|
|
|
self.add_header("X-Content-Type-Options", "nosniff")
|
2015-01-02 00:26:22 +00:00
|
|
|
self.add_header(
|
|
|
|
"Content-Security-Policy",
|
|
|
|
"default-src 'self'; "
|
|
|
|
"connect-src 'self' ws://* ; "
|
|
|
|
"style-src 'self' 'unsafe-inline'"
|
|
|
|
)
|
2014-12-25 15:10:47 +00:00
|
|
|
|
2015-03-22 23:24:56 +00:00
|
|
|
@property
|
|
|
|
def json(self):
|
2015-09-05 18:45:58 +00:00
|
|
|
if not self.request.headers.get("Content-Type").startswith("application/json"):
|
2015-03-22 23:24:56 +00:00
|
|
|
return None
|
2015-10-08 10:43:55 +00:00
|
|
|
return json.loads(self.request.body)
|
2015-03-22 23:24:56 +00:00
|
|
|
|
2014-12-25 15:10:47 +00:00
|
|
|
@property
|
|
|
|
def state(self):
|
|
|
|
return self.application.master.state
|
|
|
|
|
|
|
|
@property
|
|
|
|
def master(self):
|
|
|
|
return self.application.master
|
|
|
|
|
|
|
|
@property
|
|
|
|
def flow(self):
|
|
|
|
flow_id = str(self.path_kwargs["flow_id"])
|
|
|
|
flow = self.state.flows.get(flow_id)
|
|
|
|
if flow:
|
|
|
|
return flow
|
|
|
|
else:
|
|
|
|
raise APIError(400, "Flow not found.")
|
|
|
|
|
|
|
|
def write_error(self, status_code, **kwargs):
|
|
|
|
if "exc_info" in kwargs and isinstance(kwargs["exc_info"][1], APIError):
|
|
|
|
self.finish(kwargs["exc_info"][1].log_message)
|
|
|
|
else:
|
|
|
|
super(RequestHandler, self).write_error(status_code, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
class IndexHandler(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-09-14 00:33:07 +00:00
|
|
|
def get(self):
|
2014-11-28 18:16:47 +00:00
|
|
|
_ = self.xsrf_token # https://github.com/tornadoweb/tornado/issues/645
|
2014-09-14 00:33:07 +00:00
|
|
|
self.render("index.html")
|
|
|
|
|
|
|
|
|
2014-12-26 02:10:24 +00:00
|
|
|
class FiltHelp(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-26 02:10:24 +00:00
|
|
|
def get(self):
|
|
|
|
self.write(dict(
|
|
|
|
commands=filt.help
|
|
|
|
))
|
|
|
|
|
2015-05-30 00:03:28 +00:00
|
|
|
|
2016-02-10 23:14:38 +00:00
|
|
|
class WebSocketEventBroadcaster(BasicAuth, tornado.websocket.WebSocketHandler):
|
2015-05-30 00:03:28 +00:00
|
|
|
# raise an error if inherited class doesn't specify its own instance.
|
|
|
|
connections = None
|
2014-09-16 21:40:25 +00:00
|
|
|
|
|
|
|
def open(self):
|
2014-11-26 03:18:21 +00:00
|
|
|
self.connections.add(self)
|
2014-09-16 21:40:25 +00:00
|
|
|
|
|
|
|
def on_close(self):
|
2014-11-26 03:18:21 +00:00
|
|
|
self.connections.remove(self)
|
2014-09-16 21:40:25 +00:00
|
|
|
|
|
|
|
@classmethod
|
2014-12-09 17:55:16 +00:00
|
|
|
def broadcast(cls, **kwargs):
|
2015-07-13 22:08:36 +00:00
|
|
|
message = json.dumps(kwargs, ensure_ascii=False)
|
|
|
|
|
2014-09-16 21:40:25 +00:00
|
|
|
for conn in cls.connections:
|
|
|
|
try:
|
2014-11-26 03:18:21 +00:00
|
|
|
conn.write_message(message)
|
2014-09-16 21:40:25 +00:00
|
|
|
except:
|
|
|
|
logging.error("Error sending message", exc_info=True)
|
|
|
|
|
|
|
|
|
2014-12-23 19:33:42 +00:00
|
|
|
class ClientConnection(WebSocketEventBroadcaster):
|
|
|
|
connections = set()
|
|
|
|
|
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
class Flows(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-11-26 03:18:21 +00:00
|
|
|
def get(self):
|
|
|
|
self.write(dict(
|
2016-02-08 01:10:10 +00:00
|
|
|
data=[_strip_content(f.get_state()) for f in self.state.flows]
|
2014-12-09 23:47:05 +00:00
|
|
|
))
|
|
|
|
|
2014-12-23 19:33:42 +00:00
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
class ClearAll(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
def post(self):
|
|
|
|
self.state.clear()
|
|
|
|
|
|
|
|
|
|
|
|
class AcceptFlows(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-23 19:33:42 +00:00
|
|
|
def post(self):
|
2014-12-24 00:07:57 +00:00
|
|
|
self.state.flows.accept_all(self.master)
|
|
|
|
|
|
|
|
|
|
|
|
class AcceptFlow(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
def post(self, flow_id):
|
|
|
|
self.flow.accept_intercept(self.master)
|
|
|
|
|
|
|
|
|
|
|
|
class FlowHandler(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
def delete(self, flow_id):
|
|
|
|
self.flow.kill(self.master)
|
|
|
|
self.state.delete_flow(self.flow)
|
2014-12-23 19:33:42 +00:00
|
|
|
|
2015-03-22 23:24:56 +00:00
|
|
|
def put(self, flow_id):
|
|
|
|
flow = self.flow
|
2015-05-01 15:24:44 +00:00
|
|
|
flow.backup()
|
2015-03-22 23:24:56 +00:00
|
|
|
for a, b in self.json.iteritems():
|
|
|
|
|
|
|
|
if a == "request":
|
|
|
|
request = flow.request
|
|
|
|
for k, v in b.iteritems():
|
2015-09-17 13:16:33 +00:00
|
|
|
if k in ["method", "scheme", "host", "path", "http_version"]:
|
2015-03-22 23:24:56 +00:00
|
|
|
setattr(request, k, str(v))
|
|
|
|
elif k == "port":
|
|
|
|
request.port = int(v)
|
2015-03-26 17:17:30 +00:00
|
|
|
elif k == "headers":
|
2016-02-08 03:19:25 +00:00
|
|
|
request.headers.set_state(v)
|
2015-03-22 23:24:56 +00:00
|
|
|
else:
|
|
|
|
print "Warning: Unknown update {}.{}: {}".format(a, k, v)
|
|
|
|
|
|
|
|
elif a == "response":
|
|
|
|
response = flow.response
|
|
|
|
for k, v in b.iteritems():
|
|
|
|
if k == "msg":
|
|
|
|
response.msg = str(v)
|
|
|
|
elif k == "code":
|
2015-09-17 13:16:33 +00:00
|
|
|
response.status_code = int(v)
|
|
|
|
elif k == "http_version":
|
|
|
|
response.http_version = str(v)
|
2015-03-26 17:17:30 +00:00
|
|
|
elif k == "headers":
|
2016-02-08 03:19:25 +00:00
|
|
|
response.headers.set_state(v)
|
2015-03-26 17:17:30 +00:00
|
|
|
else:
|
|
|
|
print "Warning: Unknown update {}.{}: {}".format(a, k, v)
|
2015-03-22 23:24:56 +00:00
|
|
|
else:
|
|
|
|
print "Warning: Unknown update {}: {}".format(a, b)
|
|
|
|
self.state.update_flow(flow)
|
|
|
|
|
2014-12-23 19:33:42 +00:00
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
class DuplicateFlow(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-23 19:33:42 +00:00
|
|
|
def post(self, flow_id):
|
2014-12-24 00:07:57 +00:00
|
|
|
self.master.duplicate_flow(self.flow)
|
2014-12-23 19:33:42 +00:00
|
|
|
|
2014-12-25 15:10:47 +00:00
|
|
|
|
|
|
|
class RevertFlow(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-25 15:10:47 +00:00
|
|
|
def post(self, flow_id):
|
|
|
|
self.state.revert(self.flow)
|
|
|
|
|
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
class ReplayFlow(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
def post(self, flow_id):
|
2015-03-27 17:51:25 +00:00
|
|
|
self.flow.backup()
|
|
|
|
self.flow.response = None
|
|
|
|
self.state.update_flow(self.flow)
|
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
r = self.master.replay_request(self.flow)
|
|
|
|
if r:
|
|
|
|
raise APIError(400, r)
|
|
|
|
|
2014-12-25 15:10:47 +00:00
|
|
|
|
|
|
|
class FlowContent(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-25 15:10:47 +00:00
|
|
|
def get(self, flow_id, message):
|
|
|
|
message = getattr(self.flow, message)
|
|
|
|
|
|
|
|
if not message.content:
|
|
|
|
raise APIError(400, "No content.")
|
|
|
|
|
2015-09-05 18:45:58 +00:00
|
|
|
content_encoding = message.headers.get("Content-Encoding", None)
|
2014-12-25 15:10:47 +00:00
|
|
|
if content_encoding:
|
|
|
|
content_encoding = re.sub(r"[^\w]", "", content_encoding)
|
|
|
|
self.set_header("Content-Encoding", content_encoding)
|
|
|
|
|
2015-09-05 18:45:58 +00:00
|
|
|
original_cd = message.headers.get("Content-Disposition", None)
|
2014-12-25 15:10:47 +00:00
|
|
|
filename = None
|
|
|
|
if original_cd:
|
|
|
|
filename = re.search("filename=([\w\" \.\-\(\)]+)", original_cd)
|
|
|
|
if filename:
|
|
|
|
filename = filename.group(1)
|
|
|
|
if not filename:
|
|
|
|
filename = self.flow.request.path.split("?")[0].split("/")[-1]
|
|
|
|
|
|
|
|
filename = re.sub(r"[^\w\" \.\-\(\)]", "", filename)
|
|
|
|
cd = "attachment; filename={}".format(filename)
|
|
|
|
self.set_header("Content-Disposition", cd)
|
|
|
|
self.set_header("Content-Type", "application/text")
|
|
|
|
self.set_header("X-Content-Type-Options", "nosniff")
|
|
|
|
self.set_header("X-Frame-Options", "DENY")
|
|
|
|
self.write(message.content)
|
|
|
|
|
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
class Events(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-09 23:47:05 +00:00
|
|
|
def get(self):
|
|
|
|
self.write(dict(
|
2014-12-24 00:07:57 +00:00
|
|
|
data=list(self.state.events)
|
2014-12-10 14:25:40 +00:00
|
|
|
))
|
|
|
|
|
|
|
|
|
2014-12-24 00:07:57 +00:00
|
|
|
class Settings(RequestHandler):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2014-12-10 14:25:40 +00:00
|
|
|
def get(self):
|
|
|
|
self.write(dict(
|
|
|
|
data=dict(
|
2014-12-25 01:08:58 +00:00
|
|
|
version=version.VERSION,
|
2014-12-25 01:03:55 +00:00
|
|
|
mode=str(self.master.server.config.mode),
|
2014-12-24 00:07:57 +00:00
|
|
|
intercept=self.state.intercept_txt
|
2014-12-10 14:25:40 +00:00
|
|
|
)
|
2014-11-26 03:18:21 +00:00
|
|
|
))
|
|
|
|
|
2015-03-22 23:24:56 +00:00
|
|
|
def put(self):
|
2014-12-23 19:33:42 +00:00
|
|
|
update = {}
|
2015-03-22 23:24:56 +00:00
|
|
|
for k, v in self.json.iteritems():
|
|
|
|
if k == "intercept":
|
|
|
|
self.state.set_intercept(v)
|
|
|
|
update[k] = v
|
2014-12-23 19:33:42 +00:00
|
|
|
else:
|
2015-05-30 03:17:48 +00:00
|
|
|
print("Warning: Unknown setting {}: {}".format(k, v))
|
2014-12-23 19:33:42 +00:00
|
|
|
|
|
|
|
ClientConnection.broadcast(
|
|
|
|
type="settings",
|
|
|
|
cmd="update",
|
|
|
|
data=update
|
|
|
|
)
|
|
|
|
|
2014-11-26 03:18:21 +00:00
|
|
|
|
2014-12-23 19:33:42 +00:00
|
|
|
class Application(tornado.web.Application):
|
2016-01-27 09:12:18 +00:00
|
|
|
|
2016-02-10 23:14:38 +00:00
|
|
|
def __init__(self, master, debug, wauthenticator):
|
2014-12-23 19:33:42 +00:00
|
|
|
self.master = master
|
2016-02-10 23:14:38 +00:00
|
|
|
self.additional_args = dict(
|
|
|
|
wauthenticator=wauthenticator,
|
|
|
|
)
|
2014-09-14 00:22:28 +00:00
|
|
|
handlers = [
|
2014-09-14 00:33:07 +00:00
|
|
|
(r"/", IndexHandler),
|
2014-12-26 02:10:24 +00:00
|
|
|
(r"/filter-help", FiltHelp),
|
2014-09-16 21:40:25 +00:00
|
|
|
(r"/updates", ClientConnection),
|
2014-12-09 23:47:05 +00:00
|
|
|
(r"/events", Events),
|
2014-11-28 18:16:47 +00:00
|
|
|
(r"/flows", Flows),
|
2014-12-23 19:33:42 +00:00
|
|
|
(r"/flows/accept", AcceptFlows),
|
2014-12-24 00:07:57 +00:00
|
|
|
(r"/flows/(?P<flow_id>[0-9a-f\-]+)", FlowHandler),
|
|
|
|
(r"/flows/(?P<flow_id>[0-9a-f\-]+)/accept", AcceptFlow),
|
|
|
|
(r"/flows/(?P<flow_id>[0-9a-f\-]+)/duplicate", DuplicateFlow),
|
|
|
|
(r"/flows/(?P<flow_id>[0-9a-f\-]+)/replay", ReplayFlow),
|
2014-12-25 15:10:47 +00:00
|
|
|
(r"/flows/(?P<flow_id>[0-9a-f\-]+)/revert", RevertFlow),
|
|
|
|
(r"/flows/(?P<flow_id>[0-9a-f\-]+)/(?P<message>request|response)/content", FlowContent),
|
2014-12-10 14:25:40 +00:00
|
|
|
(r"/settings", Settings),
|
2014-12-24 00:07:57 +00:00
|
|
|
(r"/clear", ClearAll),
|
2014-09-14 00:22:28 +00:00
|
|
|
]
|
2016-02-10 23:14:38 +00:00
|
|
|
for i, handler in enumerate(handlers):
|
|
|
|
handlers[i] += (self.additional_args,)
|
|
|
|
|
2014-09-14 00:22:28 +00:00
|
|
|
settings = dict(
|
|
|
|
template_path=os.path.join(os.path.dirname(__file__), "templates"),
|
|
|
|
static_path=os.path.join(os.path.dirname(__file__), "static"),
|
|
|
|
xsrf_cookies=True,
|
2014-11-28 18:16:47 +00:00
|
|
|
cookie_secret=os.urandom(256),
|
2014-09-14 00:22:28 +00:00
|
|
|
debug=debug,
|
|
|
|
)
|
2015-05-30 03:17:48 +00:00
|
|
|
super(Application, self).__init__(handlers, **settings)
|