From 9674a0869c2a333f74178e305677259e7ac379c3 Mon Sep 17 00:00:00 2001 From: Ryo Onodera Date: Tue, 31 Mar 2015 16:07:04 +0900 Subject: Make the Websocket's connection header value case-insensitive --- examples/ignore_websocket.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/ignore_websocket.py b/examples/ignore_websocket.py index 48093951..f7a94bdf 100644 --- a/examples/ignore_websocket.py +++ b/examples/ignore_websocket.py @@ -26,7 +26,8 @@ def done(context): @concurrent def response(context, flow): - if flow.response.headers.get_first("Connection", None) == "Upgrade": + value = flow.response.headers.get_first("Connection", None) + if value and value.upper() == "UPGRADE": # We need to send the response manually now... flow.client_conn.send(flow.response.assemble()) # ...and then delegate to tcp passthrough. -- cgit v1.2.3 From 74aff39b28fe368c94f473c7972feaa75683a18a Mon Sep 17 00:00:00 2001 From: Maximilian Hils Date: Wed, 8 Apr 2015 00:21:49 +0200 Subject: add example which uses filt --- examples/README | 1 + examples/filt.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 examples/filt.py (limited to 'examples') diff --git a/examples/README b/examples/README index f24c4de7..4a5c268d 100644 --- a/examples/README +++ b/examples/README @@ -3,6 +3,7 @@ add_header.py Simple script that just adds a header to every request change_upstream_proxy.py Dynamically change the upstream proxy dns_spoofing.py Use mitmproxy in a DNS spoofing scenario. dup_and_replay.py Duplicates each request, changes it, and then replays the modified request. +filt.py Use mitmproxy's filter expressions in your script. iframe_injector.py Inject configurable iframe into pages. modify_form.py Modify all form submissions to add a parameter. modify_querystring.py Modify all query strings to add a parameters. diff --git a/examples/filt.py b/examples/filt.py new file mode 100644 index 00000000..dc241046 --- /dev/null +++ b/examples/filt.py @@ -0,0 +1,15 @@ +# This scripts demonstrates how to use mitmproxy's filter pattern in inline scripts. +# Usage: mitmdump -s "filt.py FILTER" + +from libmproxy import filt + +def start(context, argv): + print argv + if len(argv) != 2: + raise ValueError("Usage: -s 'filt.py FILTER'") + context.filter = filt.parse(argv[1]) + +def response(context, flow): + if flow.match(context.filter): + print("Flow matches filter:") + print(flow) \ No newline at end of file -- cgit v1.2.3 From c0a318566ae0fb5a264bfaa130f3ff3a09ea5bf5 Mon Sep 17 00:00:00 2001 From: Maximilian Hils Date: Sun, 12 Apr 2015 03:47:58 +0200 Subject: add flowwriter example --- examples/flowwriter.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 examples/flowwriter.py (limited to 'examples') diff --git a/examples/flowwriter.py b/examples/flowwriter.py new file mode 100644 index 00000000..2c253fbb --- /dev/null +++ b/examples/flowwriter.py @@ -0,0 +1,17 @@ +from libmproxy.flow import FlowWriter +import random +import sys + +def start(context, argv): + if len(argv) != 2: + raise ValueError('Usage: -s "flowriter.py filename"') + + if argv[1] == "-": + f = sys.stdout + else: + f = open(argv[1], "wb") + context.flow_writer = FlowWriter(f) + +def response(context, flow): + if random.choice([True, False]): + context.flow_writer.add(flow) \ No newline at end of file -- cgit v1.2.3 From ba149d90adc9d041b255bdefc7cb2002cbcf4216 Mon Sep 17 00:00:00 2001 From: Maximilian Hils Date: Sun, 12 Apr 2015 03:50:14 +0200 Subject: spaces, not tabs --- examples/README | 1 + examples/flowwriter.py | 13 ++++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) (limited to 'examples') diff --git a/examples/README b/examples/README index 4a5c268d..adfcd0f2 100644 --- a/examples/README +++ b/examples/README @@ -4,6 +4,7 @@ change_upstream_proxy.py Dynamically change the upstream proxy dns_spoofing.py Use mitmproxy in a DNS spoofing scenario. dup_and_replay.py Duplicates each request, changes it, and then replays the modified request. filt.py Use mitmproxy's filter expressions in your script. +flowwriter.py Only write selected flows into a mitmproxy dumpfile. iframe_injector.py Inject configurable iframe into pages. modify_form.py Modify all form submissions to add a parameter. modify_querystring.py Modify all query strings to add a parameters. diff --git a/examples/flowwriter.py b/examples/flowwriter.py index 2c253fbb..f411ec45 100644 --- a/examples/flowwriter.py +++ b/examples/flowwriter.py @@ -1,17 +1,20 @@ -from libmproxy.flow import FlowWriter import random import sys +from libmproxy.flow import FlowWriter + + def start(context, argv): if len(argv) != 2: raise ValueError('Usage: -s "flowriter.py filename"') if argv[1] == "-": - f = sys.stdout + f = sys.stdout else: - f = open(argv[1], "wb") + f = open(argv[1], "wb") context.flow_writer = FlowWriter(f) + def response(context, flow): - if random.choice([True, False]): - context.flow_writer.add(flow) \ No newline at end of file + if random.choice([True, False]): + context.flow_writer.add(flow) \ No newline at end of file -- cgit v1.2.3 From bea0bd236a60e3e6c80027448e51b7802394304a Mon Sep 17 00:00:00 2001 From: Aldo Cortesi Date: Tue, 14 Apr 2015 11:58:10 +1200 Subject: Housekeeping and cleanups - No output to stdout on load in examples - they muck up the test suite. - Use the odict module directly, rather than aliasing it. The small convenience this gives to scripters is not worth it. - Move the cookie tests from the flow test module to the protocol_http test module. --- examples/filt.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/filt.py b/examples/filt.py index dc241046..cce2a48a 100644 --- a/examples/filt.py +++ b/examples/filt.py @@ -4,7 +4,6 @@ from libmproxy import filt def start(context, argv): - print argv if len(argv) != 2: raise ValueError("Usage: -s 'filt.py FILTER'") context.filter = filt.parse(argv[1]) @@ -12,4 +11,4 @@ def start(context, argv): def response(context, flow): if flow.match(context.filter): print("Flow matches filter:") - print(flow) \ No newline at end of file + print(flow) -- cgit v1.2.3 From a05a70d8168a07c92b2a3ecbbb1958d85532efe3 Mon Sep 17 00:00:00 2001 From: Aldo Cortesi Date: Sat, 30 May 2015 12:03:28 +1200 Subject: Add coding style check, reformat. --- examples/add_header.py | 2 +- examples/change_upstream_proxy.py | 14 +++++-- examples/dns_spoofing.py | 8 ++-- examples/dup_and_replay.py | 2 +- examples/filt.py | 14 ++++--- examples/flowbasic | 3 +- examples/flowwriter.py | 2 +- examples/har_extractor.py | 88 ++++++++++++++++++++++++--------------- examples/iframe_injector.py | 9 +++- examples/ignore_websocket.py | 3 +- examples/mitmproxywrapper.py | 60 ++++++++++++++++++-------- examples/modify_form.py | 5 ++- examples/modify_querystring.py | 2 +- examples/modify_response_body.py | 7 +++- examples/nonblocking.py | 2 +- examples/proxapp.py | 2 +- examples/read_dumpfile | 5 ++- examples/redirect_requests.py | 3 +- examples/stream.py | 2 +- examples/stream_modify.py | 4 +- examples/stub.py | 9 ++++ examples/upsidedownternet.py | 3 +- 22 files changed, 164 insertions(+), 85 deletions(-) (limited to 'examples') diff --git a/examples/add_header.py b/examples/add_header.py index 291741cb..0c0593d1 100644 --- a/examples/add_header.py +++ b/examples/add_header.py @@ -1,2 +1,2 @@ def response(context, flow): - flow.response.headers["newheader"] = ["foo"] \ No newline at end of file + flow.response.headers["newheader"] = ["foo"] diff --git a/examples/change_upstream_proxy.py b/examples/change_upstream_proxy.py index 74a43bd0..7782dd84 100644 --- a/examples/change_upstream_proxy.py +++ b/examples/change_upstream_proxy.py @@ -1,10 +1,13 @@ # This scripts demonstrates how mitmproxy can switch to a second/different upstream proxy # in upstream proxy mode. # -# Usage: mitmdump -U http://default-upstream-proxy.local:8080/ -s "change_upstream_proxy.py host" +# Usage: mitmdump -U http://default-upstream-proxy.local:8080/ -s +# "change_upstream_proxy.py host" from libmproxy.protocol.http import send_connect_request alternative_upstream_proxy = ("localhost", 8082) + + def should_redirect(flow): return flow.request.host == "example.com" @@ -15,7 +18,12 @@ def request(context, flow): # If you want to change the target server, you should modify flow.request.host and flow.request.port # flow.live.change_server should only be used by inline scripts to change the upstream proxy, # unless you are sure that you know what you are doing. - server_changed = flow.live.change_server(alternative_upstream_proxy, persistent_change=True) + server_changed = flow.live.change_server( + alternative_upstream_proxy, + persistent_change=True) if flow.request.scheme == "https" and server_changed: - send_connect_request(flow.live.c.server_conn, flow.request.host, flow.request.port) + send_connect_request( + flow.live.c.server_conn, + flow.request.host, + flow.request.port) flow.live.c.establish_ssl(server=True) diff --git a/examples/dns_spoofing.py b/examples/dns_spoofing.py index cfba7c54..dddf172c 100644 --- a/examples/dns_spoofing.py +++ b/examples/dns_spoofing.py @@ -25,11 +25,13 @@ mitmproxy -p 443 -R https2http://localhost:8000 def request(context, flow): if flow.client_conn.ssl_established: # TLS SNI or Host header - flow.request.host = flow.client_conn.connection.get_servername() or flow.request.pretty_host(hostheader=True) + flow.request.host = flow.client_conn.connection.get_servername( + ) or flow.request.pretty_host(hostheader=True) - # If you use a https2http location as default destination, these attributes need to be corrected as well: + # If you use a https2http location as default destination, these + # attributes need to be corrected as well: flow.request.port = 443 flow.request.scheme = "https" else: # Host header - flow.request.host = flow.request.pretty_host(hostheader=True) \ No newline at end of file + flow.request.host = flow.request.pretty_host(hostheader=True) diff --git a/examples/dup_and_replay.py b/examples/dup_and_replay.py index 3d9279cc..9ba91d3b 100644 --- a/examples/dup_and_replay.py +++ b/examples/dup_and_replay.py @@ -1,4 +1,4 @@ def request(context, flow): f = context.duplicate_flow(flow) f.request.path = "/changed" - context.replay_request(f) \ No newline at end of file + context.replay_request(f) diff --git a/examples/filt.py b/examples/filt.py index cce2a48a..d2daf9a2 100644 --- a/examples/filt.py +++ b/examples/filt.py @@ -3,12 +3,14 @@ from libmproxy import filt + def start(context, argv): - if len(argv) != 2: - raise ValueError("Usage: -s 'filt.py FILTER'") - context.filter = filt.parse(argv[1]) + if len(argv) != 2: + raise ValueError("Usage: -s 'filt.py FILTER'") + context.filter = filt.parse(argv[1]) + def response(context, flow): - if flow.match(context.filter): - print("Flow matches filter:") - print(flow) + if flow.match(context.filter): + print("Flow matches filter:") + print(flow) diff --git a/examples/flowbasic b/examples/flowbasic index c71debc9..083d7663 100755 --- a/examples/flowbasic +++ b/examples/flowbasic @@ -36,7 +36,8 @@ class MyMaster(flow.FlowMaster): config = proxy.ProxyConfig( port=8080, - cadir="~/.mitmproxy/" # use ~/.mitmproxy/mitmproxy-ca.pem as default CA file. + # use ~/.mitmproxy/mitmproxy-ca.pem as default CA file. + cadir="~/.mitmproxy/" ) state = flow.State() server = ProxyServer(config) diff --git a/examples/flowwriter.py b/examples/flowwriter.py index f411ec45..be2f285e 100644 --- a/examples/flowwriter.py +++ b/examples/flowwriter.py @@ -17,4 +17,4 @@ def start(context, argv): def response(context, flow): if random.choice([True, False]): - context.flow_writer.add(flow) \ No newline at end of file + context.flow_writer.add(flow) diff --git a/examples/har_extractor.py b/examples/har_extractor.py index 5c228ece..1a76fa1f 100644 --- a/examples/har_extractor.py +++ b/examples/har_extractor.py @@ -83,7 +83,8 @@ def response(context, flow): # 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. - connect_time = flow.server_conn.timestamp_tcp_setup - flow.server_conn.timestamp_start + connect_time = flow.server_conn.timestamp_tcp_setup - \ + flow.server_conn.timestamp_start context.seen_server.add(flow.server_conn) if flow.server_conn.timestamp_ssl_setup is not None: @@ -91,7 +92,8 @@ def response(context, flow): # the start of the successful tcp setup and the successful ssl # setup. If no ssl setup has been made it is left as -1 since it # doesn't apply to this connection. - ssl_time = flow.server_conn.timestamp_ssl_setup - flow.server_conn.timestamp_tcp_setup + ssl_time = flow.server_conn.timestamp_ssl_setup - \ + flow.server_conn.timestamp_tcp_setup # 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 @@ -110,7 +112,8 @@ def response(context, flow): # HAR timings are integers in ms, so we have to re-encode the raw timings to # that format. - timings = dict([(key, int(1000 * value)) for key, value in timings_raw.iteritems()]) + timings = dict([(key, int(1000 * value)) + for key, value in timings_raw.iteritems()]) # The full_time is the sum of all timings. Timings set to -1 will be ignored # as per spec. @@ -119,20 +122,27 @@ def response(context, flow): if item > -1: full_time += item - started_date_time = datetime.fromtimestamp(flow.request.timestamp_start, tz=utc).isoformat() + started_date_time = datetime.fromtimestamp( + flow.request.timestamp_start, + tz=utc).isoformat() - request_query_string = [{"name": k, "value": v} for k, v in flow.request.get_query()] + request_query_string = [{"name": k, "value": v} + for k, v in flow.request.get_query()] request_http_version = ".".join([str(v) for v in flow.request.httpversion]) # Cookies are shaped as tuples by MITMProxy. - request_cookies = [{"name": k.strip(), "value": v[0]} for k, v in (flow.request.get_cookies() or {}).iteritems()] + request_cookies = [{"name": k.strip(), "value": v[0]} + for k, v in (flow.request.get_cookies() or {}).iteritems()] request_headers = [{"name": k, "value": v} for k, v in flow.request.headers] request_headers_size = len(str(flow.request.headers)) request_body_size = len(flow.request.content) - response_http_version = ".".join([str(v) for v in flow.response.httpversion]) + response_http_version = ".".join( + [str(v) for v in flow.response.httpversion]) # Cookies are shaped as tuples by MITMProxy. - response_cookies = [{"name": k.strip(), "value": v[0]} for k, v in (flow.response.get_cookies() or {}).iteritems()] - response_headers = [{"name": k, "value": v} for k, v in flow.response.headers] + response_cookies = [{"name": k.strip(), "value": v[0]} + for k, v in (flow.response.get_cookies() or {}).iteritems()] + response_headers = [{"name": k, "value": v} + for k, v in flow.response.headers] response_headers_size = len(str(flow.response.headers)) response_body_size = len(flow.response.content) response_body_decoded_size = len(flow.response.get_decoded_content()) @@ -140,33 +150,43 @@ def response(context, flow): response_mime_type = flow.response.headers.get_first('Content-Type', '') response_redirect_url = flow.response.headers.get_first('Location', '') - entry = HAR.entries({"startedDateTime": started_date_time, - "time": full_time, - "request": {"method": flow.request.method, - "url": flow.request.url, - "httpVersion": request_http_version, - "cookies": request_cookies, - "headers": request_headers, - "queryString": request_query_string, - "headersSize": request_headers_size, - "bodySize": request_body_size, }, - "response": {"status": flow.response.code, - "statusText": flow.response.msg, - "httpVersion": response_http_version, - "cookies": response_cookies, - "headers": response_headers, - "content": {"size": response_body_size, - "compression": response_body_compression, - "mimeType": response_mime_type}, - "redirectURL": response_redirect_url, - "headersSize": response_headers_size, - "bodySize": response_body_size, }, - "cache": {}, - "timings": timings, }) + entry = HAR.entries( + { + "startedDateTime": started_date_time, + "time": full_time, + "request": { + "method": flow.request.method, + "url": flow.request.url, + "httpVersion": request_http_version, + "cookies": request_cookies, + "headers": request_headers, + "queryString": request_query_string, + "headersSize": request_headers_size, + "bodySize": request_body_size, + }, + "response": { + "status": flow.response.code, + "statusText": flow.response.msg, + "httpVersion": response_http_version, + "cookies": response_cookies, + "headers": response_headers, + "content": { + "size": response_body_size, + "compression": response_body_compression, + "mimeType": response_mime_type}, + "redirectURL": response_redirect_url, + "headersSize": response_headers_size, + "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. - if flow.request.url in context.HARLog.get_page_list() or flow.request.headers.get('Referer', None) is None: + if flow.request.url in context.HARLog.get_page_list() or flow.request.headers.get( + 'Referer', + None) is None: page_id = context.HARLog.create_page_id() context.HARLog.add( HAR.pages({ @@ -231,4 +251,4 @@ def print_attributes(obj, filter_string=None, hide_privates=False): if filter_string is not None and filter_string not in attr: continue value = getattr(obj, attr) - print "%s.%s" % ('obj', attr), value, type(value) \ No newline at end of file + print "%s.%s" % ('obj', attr), value, type(value) diff --git a/examples/iframe_injector.py b/examples/iframe_injector.py index 72563bed..b2fa2d26 100644 --- a/examples/iframe_injector.py +++ b/examples/iframe_injector.py @@ -16,7 +16,12 @@ def response(context, flow): with decoded(flow.response): # Remove content encoding (gzip, ...) html = BeautifulSoup(flow.response.content) if html.body: - iframe = html.new_tag("iframe", src=context.iframe_url, frameborder=0, height=0, width=0) + iframe = html.new_tag( + "iframe", + src=context.iframe_url, + frameborder=0, + height=0, + width=0) html.body.insert(0, iframe) flow.response.content = str(html) - context.log("Iframe inserted.") \ No newline at end of file + context.log("Iframe inserted.") diff --git a/examples/ignore_websocket.py b/examples/ignore_websocket.py index f7a94bdf..b52f18f8 100644 --- a/examples/ignore_websocket.py +++ b/examples/ignore_websocket.py @@ -24,6 +24,7 @@ def done(context): HTTPRequest._headers_to_strip_off.append("Connection") HTTPRequest._headers_to_strip_off.append("Upgrade") + @concurrent def response(context, flow): value = flow.response.headers.get_first("Connection", None) @@ -32,4 +33,4 @@ def response(context, flow): flow.client_conn.send(flow.response.assemble()) # ...and then delegate to tcp passthrough. TCPHandler(flow.live.c, log=False).handle_messages() - flow.reply(KILL) \ No newline at end of file + flow.reply(KILL) diff --git a/examples/mitmproxywrapper.py b/examples/mitmproxywrapper.py index 2f3750e9..239642d7 100755 --- a/examples/mitmproxywrapper.py +++ b/examples/mitmproxywrapper.py @@ -14,23 +14,29 @@ import contextlib import os import sys + class Wrapper(object): - + def __init__(self, port, extra_arguments=None): self.port = port self.extra_arguments = extra_arguments def run_networksetup_command(self, *arguments): - return subprocess.check_output(['sudo', 'networksetup'] + list(arguments)) + return subprocess.check_output( + ['sudo', 'networksetup'] + list(arguments)) def proxy_state_for_service(self, service): - state = self.run_networksetup_command('-getwebproxy', service).splitlines() + state = self.run_networksetup_command( + '-getwebproxy', + service).splitlines() return dict([re.findall(r'([^:]+): (.*)', line)[0] for line in state]) def enable_proxy_for_service(self, service): print 'Enabling proxy on {}...'.format(service) for subcommand in ['-setwebproxy', '-setsecurewebproxy']: - self.run_networksetup_command(subcommand, service, '127.0.0.1', str(self.port)) + self.run_networksetup_command( + subcommand, service, '127.0.0.1', str( + self.port)) def disable_proxy_for_service(self, service): print 'Disabling proxy on {}...'.format(service) @@ -39,14 +45,20 @@ class Wrapper(object): def interface_name_to_service_name_map(self): order = self.run_networksetup_command('-listnetworkserviceorder') - mapping = re.findall(r'\(\d+\)\s(.*)$\n\(.*Device: (.+)\)$', order, re.MULTILINE) + mapping = re.findall( + r'\(\d+\)\s(.*)$\n\(.*Device: (.+)\)$', + order, + re.MULTILINE) return dict([(b, a) for (a, b) in mapping]) def run_command_with_input(self, command, input): - popen = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + popen = subprocess.Popen( + command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE) (stdout, stderr) = popen.communicate(input) return stdout - + def primary_interace_name(self): scutil_script = 'get State:/Network/Global/IPv4\nd.show\n' stdout = self.run_command_with_input('/usr/sbin/scutil', scutil_script) @@ -54,13 +66,15 @@ class Wrapper(object): return interface def primary_service_name(self): - return self.interface_name_to_service_name_map()[self.primary_interace_name()] + return self.interface_name_to_service_name_map()[ + self.primary_interace_name()] def proxy_enabled_for_service(self, service): return self.proxy_state_for_service(service)['Enabled'] == 'Yes' def toggle_proxy(self): - new_state = not self.proxy_enabled_for_service(self.primary_service_name()) + new_state = not self.proxy_enabled_for_service( + self.primary_service_name()) for service_name in self.connected_service_names(): if self.proxy_enabled_for_service(service_name) and not new_state: self.disable_proxy_for_service(service_name) @@ -74,8 +88,11 @@ class Wrapper(object): service_names = [] for service_id in service_ids: - scutil_script = 'show Setup:/Network/Service/{}\n'.format(service_id) - stdout = self.run_command_with_input('/usr/sbin/scutil', scutil_script) + scutil_script = 'show Setup:/Network/Service/{}\n'.format( + service_id) + stdout = self.run_command_with_input( + '/usr/sbin/scutil', + scutil_script) service_name, = re.findall(r'UserDefinedName\s*:\s*(.+)', stdout) service_names.append(service_name) @@ -102,7 +119,7 @@ class Wrapper(object): for service_name in connected_service_names: if not self.proxy_enabled_for_service(service_name): self.enable_proxy_for_service(service_name) - + yield for service_name in connected_service_names: @@ -119,15 +136,23 @@ class Wrapper(object): def main(cls): parser = argparse.ArgumentParser( description='Helper tool for OS X proxy configuration and mitmproxy.', - epilog='Any additional arguments will be passed on unchanged to mitmproxy.' - ) - parser.add_argument('-t', '--toggle', action='store_true', help='just toggle the proxy configuration') + epilog='Any additional arguments will be passed on unchanged to mitmproxy.') + parser.add_argument( + '-t', + '--toggle', + action='store_true', + help='just toggle the proxy configuration') # parser.add_argument('--honeyproxy', action='store_true', help='run honeyproxy instead of mitmproxy') - parser.add_argument('-p', '--port', type=int, help='override the default port of 8080', default=8080) + parser.add_argument( + '-p', + '--port', + type=int, + help='override the default port of 8080', + default=8080) args, extra_arguments = parser.parse_known_args() wrapper = cls(port=args.port, extra_arguments=extra_arguments) - + if args.toggle: wrapper.toggle_proxy() # elif args.honeyproxy: @@ -139,4 +164,3 @@ class Wrapper(object): if __name__ == '__main__': Wrapper.ensure_superuser() Wrapper.main() - diff --git a/examples/modify_form.py b/examples/modify_form.py index 3d93e392..37ba2fac 100644 --- a/examples/modify_form.py +++ b/examples/modify_form.py @@ -1,6 +1,7 @@ def request(context, flow): - if "application/x-www-form-urlencoded" in flow.request.headers["content-type"]: + if "application/x-www-form-urlencoded" in flow.request.headers[ + "content-type"]: form = flow.request.get_form_urlencoded() form["mitmproxy"] = ["rocks"] - flow.request.set_form_urlencoded(form) \ No newline at end of file + flow.request.set_form_urlencoded(form) diff --git a/examples/modify_querystring.py b/examples/modify_querystring.py index 1dd4807a..7f31a48f 100644 --- a/examples/modify_querystring.py +++ b/examples/modify_querystring.py @@ -3,4 +3,4 @@ def request(context, flow): q = flow.request.get_query() if q: q["mitmproxy"] = ["rocks"] - flow.request.set_query(q) \ No newline at end of file + flow.request.set_query(q) diff --git a/examples/modify_response_body.py b/examples/modify_response_body.py index 4afd0421..68d3d4ab 100644 --- a/examples/modify_response_body.py +++ b/examples/modify_response_body.py @@ -6,10 +6,13 @@ from libmproxy.protocol.http 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. + # 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) \ No newline at end of file + flow.response.content = flow.response.content.replace( + context.old, + context.new) diff --git a/examples/nonblocking.py b/examples/nonblocking.py index 481c0407..f96b7f40 100644 --- a/examples/nonblocking.py +++ b/examples/nonblocking.py @@ -6,4 +6,4 @@ from libmproxy.script import concurrent 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) \ No newline at end of file + print "start request: %s%s" % (flow.request.host, flow.request.path) diff --git a/examples/proxapp.py b/examples/proxapp.py index d777d522..4d8e7b58 100644 --- a/examples/proxapp.py +++ b/examples/proxapp.py @@ -21,4 +21,4 @@ def start(context, argv): # SSL works too, but the magic domain needs to be resolvable from the mitmproxy machine due to mitmproxy's design. # mitmproxy will connect to said domain and use serve its certificate (unless --no-upstream-cert is set) # but won't send any data. - context.app_registry.add(app, "example.com", 443) \ No newline at end of file + context.app_registry.add(app, "example.com", 443) diff --git a/examples/read_dumpfile b/examples/read_dumpfile index f5818483..9da604cc 100644 --- a/examples/read_dumpfile +++ b/examples/read_dumpfile @@ -4,7 +4,8 @@ # from libmproxy import flow -import json, sys +import json +import sys with open("logfile", "rb") as logfile: freader = flow.FlowReader(logfile) @@ -14,5 +15,5 @@ with open("logfile", "rb") as logfile: print(f.request.host) json.dump(f.get_state(), sys.stdout, indent=4) print "" - except flow.FlowReadError, v: + except flow.FlowReadError as v: print "Flow file corrupted. Stopped loading." diff --git a/examples/redirect_requests.py b/examples/redirect_requests.py index d9a3bfc5..48512f1b 100644 --- a/examples/redirect_requests.py +++ b/examples/redirect_requests.py @@ -8,7 +8,8 @@ This example shows two ways to redirect flows to other destinations. def request(context, flow): # pretty_host(hostheader=True) takes the Host: header of the request into account, - # which is useful in transparent mode where we usually only have the IP otherwise. + # which is useful in transparent mode where we usually only have the IP + # otherwise. # Method 1: Answer with a locally generated response if flow.request.pretty_host(hostheader=True).endswith("example.com"): diff --git a/examples/stream.py b/examples/stream.py index 7d5efc1e..3adbe437 100644 --- a/examples/stream.py +++ b/examples/stream.py @@ -2,4 +2,4 @@ def responseheaders(context, flow): """ Enables streaming for all responses. """ - flow.response.stream = True \ No newline at end of file + flow.response.stream = True diff --git a/examples/stream_modify.py b/examples/stream_modify.py index 56d26e6d..e3f1f3cf 100644 --- a/examples/stream_modify.py +++ b/examples/stream_modify.py @@ -11,7 +11,7 @@ Be aware that content replacement isn't trivial: def modify(chunks): """ chunks is a generator that can be used to iterate over all chunks. - Each chunk is a (prefix, content, suffix) tuple. + Each chunk is a (prefix, content, suffix) tuple. For example, in the case of chunked transfer encoding: ("3\r\n","foo","\r\n") """ for prefix, content, suffix in chunks: @@ -19,4 +19,4 @@ def modify(chunks): def responseheaders(context, flow): - flow.response.stream = modify \ No newline at end of file + flow.response.stream = modify diff --git a/examples/stub.py b/examples/stub.py index c5cdad9c..d5502a47 100644 --- a/examples/stub.py +++ b/examples/stub.py @@ -1,12 +1,15 @@ """ This is a script stub, with definitions for all events. """ + + def start(context, argv): """ Called once on script startup, before any other events. """ context.log("start") + def clientconnect(context, conn_handler): """ Called when a client initiates a connection to the proxy. Note that a @@ -14,6 +17,7 @@ def clientconnect(context, conn_handler): """ context.log("clientconnect") + def serverconnect(context, conn_handler): """ Called when the proxy initiates a connection to the target server. Note that a @@ -21,6 +25,7 @@ def serverconnect(context, conn_handler): """ context.log("serverconnect") + def request(context, flow): """ Called when a client request has been received. @@ -36,12 +41,14 @@ def responseheaders(context, flow): """ context.log("responseheaders") + def response(context, flow): """ Called when a server response has been received. """ context.log("response") + def error(context, flow): """ Called when a flow error has occured, e.g. invalid server responses, or @@ -50,12 +57,14 @@ def error(context, flow): """ context.log("error") + def clientdisconnect(context, conn_handler): """ Called when a client disconnects from the proxy. """ context.log("clientdisconnect") + def done(context): """ Called once on script shutdown, after any other events. diff --git a/examples/upsidedownternet.py b/examples/upsidedownternet.py index 738eb11f..a6de97e4 100644 --- a/examples/upsidedownternet.py +++ b/examples/upsidedownternet.py @@ -2,6 +2,7 @@ import cStringIO from PIL import Image from libmproxy.protocol.http import decoded + def response(context, flow): if flow.response.headers.get_first("content-type", "").startswith("image"): with decoded(flow.response): # automatically decode gzipped responses. @@ -13,4 +14,4 @@ def response(context, flow): flow.response.content = s2.getvalue() flow.response.headers["content-type"] = ["image/png"] except: # Unknown image types etc. - pass \ No newline at end of file + pass -- cgit v1.2.3 From 4fe2c069cca07aadf983f54e18dac4de492d5d69 Mon Sep 17 00:00:00 2001 From: Jim Shaver Date: Fri, 29 May 2015 23:17:48 -0400 Subject: Fixed print function to be inline with python 3 --- examples/flowbasic | 2 +- examples/har_extractor.py | 2 +- examples/mitmproxywrapper.py | 6 +++--- examples/nonblocking.py | 4 ++-- examples/read_dumpfile | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) (limited to 'examples') diff --git a/examples/flowbasic b/examples/flowbasic index c71debc9..edd96b0d 100755 --- a/examples/flowbasic +++ b/examples/flowbasic @@ -30,7 +30,7 @@ class MyMaster(flow.FlowMaster): f = flow.FlowMaster.handle_response(self, f) if f: f.reply() - print f + print(f) return f diff --git a/examples/har_extractor.py b/examples/har_extractor.py index 5c228ece..489898a2 100644 --- a/examples/har_extractor.py +++ b/examples/har_extractor.py @@ -231,4 +231,4 @@ def print_attributes(obj, filter_string=None, hide_privates=False): if filter_string is not None and filter_string not in attr: continue value = getattr(obj, attr) - print "%s.%s" % ('obj', attr), value, type(value) \ No newline at end of file + print("%s.%s" % ('obj', attr), value, type(value)) diff --git a/examples/mitmproxywrapper.py b/examples/mitmproxywrapper.py index 2f3750e9..29e3ac16 100755 --- a/examples/mitmproxywrapper.py +++ b/examples/mitmproxywrapper.py @@ -28,12 +28,12 @@ class Wrapper(object): return dict([re.findall(r'([^:]+): (.*)', line)[0] for line in state]) def enable_proxy_for_service(self, service): - print 'Enabling proxy on {}...'.format(service) + print('Enabling proxy on {}...'.format(service)) for subcommand in ['-setwebproxy', '-setsecurewebproxy']: self.run_networksetup_command(subcommand, service, '127.0.0.1', str(self.port)) def disable_proxy_for_service(self, service): - print 'Disabling proxy on {}...'.format(service) + print('Disabling proxy on {}...'.format(service)) for subcommand in ['-setwebproxystate', '-setsecurewebproxystate']: self.run_networksetup_command(subcommand, service, 'Off') @@ -112,7 +112,7 @@ class Wrapper(object): @classmethod def ensure_superuser(cls): if os.getuid() != 0: - print 'Relaunching with sudo...' + print('Relaunching with sudo...') os.execv('/usr/bin/sudo', ['/usr/bin/sudo'] + sys.argv) @classmethod diff --git a/examples/nonblocking.py b/examples/nonblocking.py index 481c0407..7bc9c07b 100644 --- a/examples/nonblocking.py +++ b/examples/nonblocking.py @@ -4,6 +4,6 @@ from libmproxy.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) + 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) \ No newline at end of file + print("start request: %s%s" % (flow.request.host, flow.request.path)) diff --git a/examples/read_dumpfile b/examples/read_dumpfile index f5818483..82bf832d 100644 --- a/examples/read_dumpfile +++ b/examples/read_dumpfile @@ -13,6 +13,6 @@ with open("logfile", "rb") as logfile: print(f) print(f.request.host) json.dump(f.get_state(), sys.stdout, indent=4) - print "" + print("") except flow.FlowReadError, v: - print "Flow file corrupted. Stopped loading." + print("Flow file corrupted. Stopped loading.") -- cgit v1.2.3