2014-11-15 02:34:39 +00:00
|
|
|
"""
|
2015-01-02 00:41:40 +00:00
|
|
|
This inline script utilizes harparser.HAR from
|
|
|
|
https://github.com/JustusW/harparser to generate a HAR log object.
|
2014-11-15 02:34:39 +00:00
|
|
|
"""
|
2016-03-20 18:56:22 +00:00
|
|
|
import six
|
2016-06-14 01:17:09 +00:00
|
|
|
import sys
|
2016-06-14 16:47:10 +00:00
|
|
|
import pytz
|
2015-01-02 00:41:40 +00:00
|
|
|
from harparser import HAR
|
2014-11-15 21:39:15 +00:00
|
|
|
|
2015-01-02 00:41:40 +00:00
|
|
|
from datetime import datetime
|
2014-11-15 02:34:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
class _HARLog(HAR.log):
|
2015-01-02 00:41:40 +00:00
|
|
|
# The attributes need to be registered here for them to actually be
|
|
|
|
# available later via self. This is due to HAREncodable linking __getattr__
|
|
|
|
# to __getitem__. Anything that is set only in __init__ will just be added
|
|
|
|
# as key/value pair to self.__classes__.
|
2014-11-15 19:11:25 +00:00
|
|
|
__page_list__ = []
|
|
|
|
__page_count__ = 0
|
|
|
|
__page_ref__ = {}
|
|
|
|
|
2016-03-03 21:32:33 +00:00
|
|
|
def __init__(self, page_list=[]):
|
2014-11-15 19:11:25 +00:00
|
|
|
self.__page_list__ = page_list
|
|
|
|
self.__page_count__ = 0
|
|
|
|
self.__page_ref__ = {}
|
|
|
|
|
2014-11-15 02:34:39 +00:00
|
|
|
HAR.log.__init__(self, {"version": "1.2",
|
|
|
|
"creator": {"name": "MITMPROXY HARExtractor",
|
|
|
|
"version": "0.1",
|
|
|
|
"comment": ""},
|
|
|
|
"pages": [],
|
|
|
|
"entries": []})
|
|
|
|
|
|
|
|
def reset(self):
|
2014-11-15 21:04:52 +00:00
|
|
|
self.__init__(self.__page_list__)
|
2014-11-15 02:34:39 +00:00
|
|
|
|
|
|
|
def add(self, obj):
|
|
|
|
if isinstance(obj, HAR.pages):
|
|
|
|
self['pages'].append(obj)
|
|
|
|
if isinstance(obj, HAR.entries):
|
|
|
|
self['entries'].append(obj)
|
|
|
|
|
2014-11-15 19:11:25 +00:00
|
|
|
def create_page_id(self):
|
|
|
|
self.__page_count__ += 1
|
|
|
|
return "autopage_%s" % str(self.__page_count__)
|
|
|
|
|
|
|
|
def set_page_ref(self, page, ref):
|
|
|
|
self.__page_ref__[page] = ref
|
|
|
|
|
|
|
|
def get_page_ref(self, page):
|
|
|
|
return self.__page_ref__.get(page, None)
|
|
|
|
|
|
|
|
def get_page_list(self):
|
|
|
|
return self.__page_list__
|
|
|
|
|
2014-11-15 02:34:39 +00:00
|
|
|
|
2016-06-14 01:17:09 +00:00
|
|
|
def start(context):
|
2014-11-15 02:34:39 +00:00
|
|
|
"""
|
2015-01-02 00:41:40 +00:00
|
|
|
On start we create a HARLog instance. You will have to adapt this to
|
|
|
|
suit your actual needs of HAR generation. As it will probably be
|
|
|
|
necessary to cluster logs by IPs or reset them from time to time.
|
2014-11-15 02:34:39 +00:00
|
|
|
"""
|
2016-07-07 08:21:15 +00:00
|
|
|
if sys.version_info >= (3, 0):
|
|
|
|
raise RuntimeError(
|
|
|
|
"har_extractor.py does not work on Python 3. "
|
|
|
|
"Please check out https://github.com/mitmproxy/mitmproxy/issues/1320 "
|
|
|
|
"if you want to help making this work again."
|
|
|
|
)
|
2014-11-15 21:37:32 +00:00
|
|
|
context.dump_file = None
|
2016-06-14 01:17:09 +00:00
|
|
|
if len(sys.argv) > 1:
|
|
|
|
context.dump_file = sys.argv[1]
|
2014-11-15 21:37:32 +00:00
|
|
|
else:
|
2015-01-02 00:41:40 +00:00
|
|
|
raise ValueError(
|
|
|
|
'Usage: -s "har_extractor.py filename" '
|
|
|
|
'(- will output to stdout, filenames ending with .zhar '
|
|
|
|
'will result in compressed har)'
|
|
|
|
)
|
2016-03-03 21:32:33 +00:00
|
|
|
context.HARLog = _HARLog()
|
2014-11-15 21:37:32 +00:00
|
|
|
context.seen_server = set()
|
2014-11-15 02:34:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
def response(context, flow):
|
|
|
|
"""
|
2015-01-02 00:41:40 +00:00
|
|
|
Called when a server response has been received. At the time of this
|
|
|
|
message both a request and a response are present and completely done.
|
2014-11-15 02:34:39 +00:00
|
|
|
"""
|
2014-11-15 21:37:32 +00:00
|
|
|
# Values are converted from float seconds to int milliseconds later.
|
|
|
|
ssl_time = -.001
|
2014-11-15 19:11:25 +00:00
|
|
|
connect_time = -.001
|
2014-11-15 21:37:32 +00:00
|
|
|
if flow.server_conn not in context.seen_server:
|
2015-01-02 00:41:40 +00:00
|
|
|
# Calculate the connect_time for this server_conn. Afterwards add it to
|
|
|
|
# seen list, in order to avoid the connect_time being present in entries
|
|
|
|
# that use an existing connection.
|
2016-03-02 05:55:15 +00:00
|
|
|
connect_time = (flow.server_conn.timestamp_tcp_setup -
|
|
|
|
flow.server_conn.timestamp_start)
|
2014-11-15 21:37:32 +00:00
|
|
|
context.seen_server.add(flow.server_conn)
|
2014-11-15 02:34:39 +00:00
|
|
|
|
2014-11-15 21:37:32 +00:00
|
|
|
if flow.server_conn.timestamp_ssl_setup is not None:
|
2015-01-02 00:41:40 +00:00
|
|
|
# Get the ssl_time for this server_conn as the difference between
|
|
|
|
# the start of the successful tcp setup and the successful ssl
|
2016-03-02 05:55:15 +00:00
|
|
|
# setup. If no ssl setup has been made it is left as -1 since it
|
2015-01-02 00:41:40 +00:00
|
|
|
# doesn't apply to this connection.
|
2016-03-02 05:55:15 +00:00
|
|
|
ssl_time = (flow.server_conn.timestamp_ssl_setup -
|
|
|
|
flow.server_conn.timestamp_tcp_setup)
|
2014-11-15 17:38:59 +00:00
|
|
|
|
2015-01-02 00:41:40 +00:00
|
|
|
# Calculate the raw timings from the different timestamps present in the
|
|
|
|
# request and response object. For lack of a way to measure it dns timings
|
|
|
|
# can not be calculated. The same goes for HAR blocked: MITMProxy will open
|
|
|
|
# a server connection as soon as it receives the host and port from the
|
|
|
|
# client connection. So the time spent waiting is actually spent waiting
|
|
|
|
# between request.timestamp_end and response.timestamp_start thus it
|
|
|
|
# correlates to HAR wait instead.
|
|
|
|
timings_raw = {
|
|
|
|
'send': flow.request.timestamp_end - flow.request.timestamp_start,
|
|
|
|
'wait': flow.response.timestamp_start - flow.request.timestamp_end,
|
|
|
|
'receive': flow.response.timestamp_end - flow.response.timestamp_start,
|
|
|
|
'connect': connect_time,
|
|
|
|
'ssl': ssl_time
|
|
|
|
}
|
|
|
|
|
|
|
|
# HAR timings are integers in ms, so we have to re-encode the raw timings to
|
|
|
|
# that format.
|
2016-03-20 18:56:22 +00:00
|
|
|
timings = dict([(k, int(1000 * v)) for k, v in six.iteritems(timings_raw)])
|
2014-11-15 17:38:59 +00:00
|
|
|
|
2016-03-02 05:55:15 +00:00
|
|
|
# The full_time is the sum of all timings.
|
|
|
|
# Timings set to -1 will be ignored as per spec.
|
|
|
|
full_time = sum(v for v in timings.values() if v > -1)
|
2014-11-15 02:34:39 +00:00
|
|
|
|
2016-03-01 14:50:18 +00:00
|
|
|
started_date_time = datetime.utcfromtimestamp(
|
2016-06-14 16:47:10 +00:00
|
|
|
flow.request.timestamp_start).replace(tzinfo=pytz.timezone("UTC")).isoformat()
|
2016-03-01 14:50:18 +00:00
|
|
|
|
2016-03-02 05:55:15 +00:00
|
|
|
request_query_string = [{"name": k, "value": v}
|
|
|
|
for k, v in flow.request.query or {}]
|
2014-11-15 17:38:59 +00:00
|
|
|
|
|
|
|
response_body_size = len(flow.response.content)
|
2014-11-15 20:14:50 +00:00
|
|
|
response_body_decoded_size = len(flow.response.get_decoded_content())
|
2014-11-15 17:38:59 +00:00
|
|
|
response_body_compression = response_body_decoded_size - response_body_size
|
2016-03-02 05:55:15 +00:00
|
|
|
|
|
|
|
entry = HAR.entries({
|
|
|
|
"startedDateTime": started_date_time,
|
|
|
|
"time": full_time,
|
|
|
|
"request": {
|
|
|
|
"method": flow.request.method,
|
|
|
|
"url": flow.request.url,
|
|
|
|
"httpVersion": flow.request.http_version,
|
|
|
|
"cookies": format_cookies(flow.request.cookies),
|
|
|
|
"headers": format_headers(flow.request.headers),
|
|
|
|
"queryString": request_query_string,
|
|
|
|
"headersSize": len(str(flow.request.headers)),
|
|
|
|
"bodySize": len(flow.request.content),
|
|
|
|
},
|
|
|
|
"response": {
|
|
|
|
"status": flow.response.status_code,
|
2016-04-02 20:54:46 +00:00
|
|
|
"statusText": flow.response.reason,
|
2016-03-02 05:55:15 +00:00
|
|
|
"httpVersion": flow.response.http_version,
|
|
|
|
"cookies": format_cookies(flow.response.cookies),
|
|
|
|
"headers": format_headers(flow.response.headers),
|
|
|
|
"content": {
|
|
|
|
"size": response_body_size,
|
|
|
|
"compression": response_body_compression,
|
|
|
|
"mimeType": flow.response.headers.get('Content-Type', '')
|
2015-05-30 00:03:28 +00:00
|
|
|
},
|
2016-03-02 05:55:15 +00:00
|
|
|
"redirectURL": flow.response.headers.get('Location', ''),
|
|
|
|
"headersSize": len(str(flow.response.headers)),
|
|
|
|
"bodySize": response_body_size,
|
|
|
|
},
|
|
|
|
"cache": {},
|
|
|
|
"timings": timings,
|
|
|
|
})
|
|
|
|
|
|
|
|
# If the current url is in the page list of context.HARLog or
|
|
|
|
# does not have a referrer, we add it as a new pages object.
|
2016-05-29 08:23:39 +00:00
|
|
|
is_new_page = (
|
|
|
|
flow.request.url in context.HARLog.get_page_list() or
|
|
|
|
flow.request.headers.get('Referer') is None
|
|
|
|
)
|
|
|
|
if is_new_page:
|
2014-11-15 19:11:25 +00:00
|
|
|
page_id = context.HARLog.create_page_id()
|
2015-01-02 00:41:40 +00:00
|
|
|
context.HARLog.add(
|
|
|
|
HAR.pages({
|
|
|
|
"startedDateTime": entry['startedDateTime'],
|
|
|
|
"id": page_id,
|
|
|
|
"title": flow.request.url,
|
2016-06-14 16:47:10 +00:00
|
|
|
"pageTimings": {}
|
2015-01-02 00:41:40 +00:00
|
|
|
})
|
|
|
|
)
|
2014-11-15 19:11:25 +00:00
|
|
|
context.HARLog.set_page_ref(flow.request.url, page_id)
|
2014-11-15 02:34:39 +00:00
|
|
|
entry['pageref'] = page_id
|
|
|
|
|
2015-01-02 00:41:40 +00:00
|
|
|
# Lookup the referer in the page_ref of context.HARLog to point this entries
|
|
|
|
# pageref attribute to the right pages object, then set it as a new
|
|
|
|
# reference to build a reference tree.
|
2015-09-05 18:45:58 +00:00
|
|
|
elif context.HARLog.get_page_ref(flow.request.headers.get('Referer')) is not None:
|
2015-01-02 00:41:40 +00:00
|
|
|
entry['pageref'] = context.HARLog.get_page_ref(
|
2015-09-05 18:45:58 +00:00
|
|
|
flow.request.headers['Referer']
|
2015-01-02 00:41:40 +00:00
|
|
|
)
|
|
|
|
context.HARLog.set_page_ref(
|
2015-09-05 18:45:58 +00:00
|
|
|
flow.request.headers['Referer'], entry['pageref']
|
2015-01-02 00:41:40 +00:00
|
|
|
)
|
2014-11-15 02:34:39 +00:00
|
|
|
|
2014-11-15 19:11:25 +00:00
|
|
|
context.HARLog.add(entry)
|
2014-11-15 02:34:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
def done(context):
|
|
|
|
"""
|
|
|
|
Called once on script shutdown, after any other events.
|
|
|
|
"""
|
2016-03-03 21:32:49 +00:00
|
|
|
import pprint
|
2014-11-15 02:34:39 +00:00
|
|
|
import json
|
|
|
|
|
2014-11-15 19:11:25 +00:00
|
|
|
json_dump = context.HARLog.json()
|
|
|
|
compressed_json_dump = context.HARLog.compress()
|
2014-11-15 17:38:59 +00:00
|
|
|
|
2014-11-15 21:37:32 +00:00
|
|
|
if context.dump_file == '-':
|
2015-01-02 00:41:40 +00:00
|
|
|
context.log(pprint.pformat(json.loads(json_dump)))
|
2014-11-15 21:37:32 +00:00
|
|
|
elif context.dump_file.endswith('.zhar'):
|
|
|
|
file(context.dump_file, "w").write(compressed_json_dump)
|
|
|
|
else:
|
|
|
|
file(context.dump_file, "w").write(json_dump)
|
2015-01-02 00:41:40 +00:00
|
|
|
context.log(
|
|
|
|
"HAR log finished with %s bytes (%s bytes compressed)" % (
|
|
|
|
len(json_dump), len(compressed_json_dump)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
context.log(
|
|
|
|
"Compression rate is %s%%" % str(
|
|
|
|
100. * len(compressed_json_dump) / len(json_dump)
|
|
|
|
)
|
|
|
|
)
|
2014-11-15 02:34:39 +00:00
|
|
|
|
|
|
|
|
2016-03-02 05:55:15 +00:00
|
|
|
def format_cookies(obj):
|
|
|
|
if obj:
|
|
|
|
return [{"name": k.strip(), "value": v[0]} for k, v in obj.items()]
|
|
|
|
return ""
|
|
|
|
|
|
|
|
|
|
|
|
def format_headers(obj):
|
|
|
|
if obj:
|
|
|
|
return [{"name": k, "value": v} for k, v in obj.fields]
|
|
|
|
return ""
|
|
|
|
|
|
|
|
|
2014-11-15 17:41:51 +00:00
|
|
|
def print_attributes(obj, filter_string=None, hide_privates=False):
|
2014-11-15 17:38:59 +00:00
|
|
|
"""
|
2015-01-02 00:41:40 +00:00
|
|
|
Useful helper method to quickly get all attributes of an object and its
|
|
|
|
values.
|
2014-11-15 17:38:59 +00:00
|
|
|
"""
|
2014-11-15 02:34:39 +00:00
|
|
|
for attr in dir(obj):
|
2014-11-15 17:41:51 +00:00
|
|
|
if hide_privates and "__" in attr:
|
|
|
|
continue
|
|
|
|
if filter_string is not None and filter_string not in attr:
|
2014-11-15 02:34:39 +00:00
|
|
|
continue
|
|
|
|
value = getattr(obj, attr)
|
2015-05-30 03:17:48 +00:00
|
|
|
print("%s.%s" % ('obj', attr), value, type(value))
|