def start_proxy(port): options = Options(listen_port=port, ) config = ProxyConfig(options=options, ) server = ProxyServer(config) print('Intercepting Proxy listening on {0}'.format(port)) m = TestInterceptor(options, server) m.addons.add(core.Core()) m.addons.add(Counter()) m.run()
def __init__(self, host, port, options): self.options = options # Used to stored captured requests self.storage = RequestStorage( base_dir=options.pop('request_storage_base_dir', None)) # Used to modify requests/responses passing through the server # Deprecated. Will be superceded by request/response interceptors. self.modifier = RequestModifier() # The scope of requests we're interested in capturing. self.scopes = [] self.request_interceptor = None self.response_interceptor = None try: self._event_loop = asyncio.get_event_loop() if self._event_loop.is_closed(): # The event loop may be closed if the server had previously # been shutdown and then spun up again self._event_loop = asyncio.new_event_loop() asyncio.set_event_loop(self._event_loop) except: self._event_loop = asyncio.new_event_loop() asyncio.set_event_loop(self._event_loop) # mitmproxy specific options mitmproxy_opts = Options( listen_host=host, listen_port=port, ) # Create an instance of the mitmproxy server self._master = Master(mitmproxy_opts) self._master.server = ProxyServer(ProxyConfig(mitmproxy_opts)) self._master.addons.add(*addons.default_addons()) self._master.addons.add(SendToLogger()) self._master.addons.add(MitmProxyRequestHandler(self)) # Update the options now all addons have been added mitmproxy_opts.update( confdir=DEFAULT_CONFDIR, ssl_insecure=options.get('verify_ssl', True), upstream_cert=DEFAULT_UPSTREAM_CERT, stream_websockets=DEFAULT_STREAM_WEBSOCKETS, **self._get_upstream_proxy_args(), ) # Options that are prefixed mitm_ are passed through to mitmproxy mitmproxy_opts.update( **{k[5:]: v for k, v in options.items() if k.startswith('mitm_')})
def main(): process_1 = Process(target=main_server, args=(q, )) process_1.daemon = True process_1.start() options = Options(listen_host=getConfig('proxy_host'), listen_port=int(getConfig('proxy_port')), http2=True) proxy = ProxyMaster(options, with_termlog=False, with_dumper=False) r_e = RequestEvent(q) proxy.addons.add(r_e) proxy.start_run()
def start_mitm(self): asyncio.set_event_loop(asyncio.new_event_loop()) print('[*] Starting mitmproxy on 127.0.0.1:8080') options = Options(listen_host='127.0.0.1', listen_port=8080, http2=True) m = DumpMaster(options, with_termlog=False, with_dumper=False) config = ProxyConfig(options) m.server = ProxyServer(config) addon = MitmAddon(self.ext_id) m.addons.add(addon) # run mitmproxy in backgroud loop = asyncio.get_event_loop() t = threading.Thread( target=loop_in_thread, args=(loop,m) ) t.start() return m
def __init__(self, mode: ProxyMode, port: int): mode = (f'{mode.value}:https://dummy-upstream' if mode == ProxyMode.REVERSE else mode.value) opts = Options(mode=mode, listen_port=port) super().__init__(opts) self.view = View() self.addons.add( *default_addons(), VaultFlows(), self.view, ProxyEventsAddon(), ) self.server = ProxyServer(ProxyConfig(opts))
def install_cert(): log.warning('Installing mitmproxy certificate...') # Init dummy config to generate the certificate ProxyConfig(Options()) crtPath = Path.home().joinpath('.mitmproxy', 'mitmproxy-ca-cert.cer') log.debug(f'certificate path: "{crtPath}"') if error_code := subprocess.call( f'certutil -addstore -user Root "{crtPath}"', shell=True): log.error( f'Certificate could not be installed: {hex(error_code)} - {str(FormatMessage(error_code)).strip()}' ) # noinspection PyProtectedMember,PyUnresolvedReferences os._exit(1)
def generate_proxy_options(config) -> Options: return Options(listen_host=config.get('host'), listen_port=config.get('port'), http2=True, mode='regular')
def response(self, flow: mitmproxy.http.HTTPFlow): if flow.request.host == 'qcc-static.qichacha.com' or flow.request.host == 'apph5.qichacha.com': print(flow.request.path) flow.response.set_content(flow.response.content.replace(b'debugger', b'')) print('debugger' in flow.response.content) # see source mitmproxy/master.py for details def loop_in_thread(loop, m): asyncio.set_event_loop(loop) # This is the key. m.run_loop(loop.run_forever) if __name__ == "__main__": options = Options(listen_host='0.0.0.0', listen_port=8080, http2=False) m = DumpMaster(options, with_termlog=False, with_dumper=False) config = ProxyConfig(options) m.server = ProxyServer(config) m.addons.add(AntiDebugger()) loop = asyncio.get_event_loop() t = threading.Thread(target=loop_in_thread, args=(loop,m) ) t.start() print('启动代理完成,监听端口8080,设置完代理后,访问mitm.it安装代理证书') t.join() m.shutdown()
select = config.select if not select: select = menu() if str(select) == '1': print('此程序仅设置Internet局域网代理 可能会被拦截,请允许.') print('不要启动加速器或者其它代理程序.') qq = config.QQ if not qq: qq = input_num('输入一个QQ号进行绑定:') print('正在设置代理..') enable_proxy() options = Options(listen_host="0.0.0.0", listen_port=config.proxy_port, http2=True) m = DumpMaster(options, with_termlog=False, with_dumper=False) m.server = ProxyServer(ProxyConfig(options)) m.addons.add(Addon()) try: loop = asyncio.get_event_loop() try: loop.add_signal_handler( signal.SIGINT, getattr(m, "prompt_for_exit", m.shutdown)) loop.add_signal_handler(signal.SIGTERM, m.shutdown) except NotImplementedError: pass async def wakeup():
def capture(): from mitmproxy.options import Options from mitmproxy.proxy.config import ProxyConfig from mitmproxy.proxy.server import ProxyServer from mitmproxy.tools.dump import DumpMaster flag = True print( "开始通过抓包模式捕获链接\n注意:必须等程序运行结束或者Ctrl+C退出,不要直接关闭,否则会上不了网\n可以用解压出来的关闭代理bat脚本恢复,或者 设置 - 网络和Internet - 代理 - 使用代理服务器 - 关闭" ) while flag: try: i = input("确定使用抓包模式吗?请打开抽卡记录页面后输入yes确认执行:") if i == "yes": flag = False except KeyboardInterrupt: print("取消抓包模式") pressAnyKeyToExit() except Exception as e: print(traceback.format_exc()) continue try: options = Options(listen_host="0.0.0.0", listen_port=8889, http2=True) config = ProxyConfig(options) global m m = DumpMaster(options, with_termlog=False, with_dumper=False) m.server = ProxyServer(config) m.addons.add(Addon()) loop = asyncio.get_event_loop() try: loop.add_signal_handler(signal.SIGINT, getattr(m, "prompt_for_exit", m.shutdown)) loop.add_signal_handler(signal.SIGTERM, m.shutdown) except NotImplementedError: pass async def wakeup(): while True: await asyncio.sleep(0.2) asyncio.ensure_future(wakeup()) print("设置代理", end="...", flush=True) enableProxy() print("成功", flush=True) print("正在捕获链接,请在抽卡记录页翻页一次", end="...", flush=True) m.run() print("成功", flush=True) print("清除代理", end="...", flush=True) disableProxy() print("成功", flush=True) return url except KeyboardInterrupt: print("中止抓包") print("清除代理", end="...", flush=True) disableProxy() print("成功", flush=True) pressAnyKeyToExit() except TypeError: pass except Exception as e: print("抓包模块出错:\n", traceback.format_exc())