示例#1
0
def _run_proxy(event, namespace, service, listen_host, listen_port, verbose):
    # Run mitmproxy as a reverse-proxy to the Kubernetes ApiServer under the
    # subpath /api/v1/namespaces/{namespace}/services/{service}/proxy. See
    # https://k8s.io/docs/tasks/administer-cluster/access-cluster-services.
    client = kubernetes.config.new_client_from_config()
    prefix = f"/api/v1/namespaces/{namespace}/services/{service}/proxy"
    options = Options(listen_host=listen_host,
                      listen_port=listen_port,
                      mode=f"reverse:{client.configuration.host}")
    master = DumpMaster(options, with_termlog=verbose, with_dumper=verbose)
    options.keep_host_header = True
    options.ssl_insecure = True
    with NamedTemporaryFile() as cert_file:
        # If Kubernetes client has a client-certificate set up, then configure
        # mitmproxy to use it. Kubernetes stores the cert and key in separate
        # files, while mitmproxy expects a single file. So append the two file
        # contents into a new file and pass it to mitmproxy.
        if client.configuration.cert_file and client.configuration.key_file:
            with open(client.configuration.cert_file, "rb") as f:
                cert_file.write(f.read())
            with open(client.configuration.key_file, "rb") as f:
                cert_file.write(f.read())
            cert_file.flush()
            options.client_certs = cert_file.name
        master.server = ProxyServer(ProxyConfig(options))
        master.addons.add(_Addon(client, prefix))
        event.set()  # Port is bound by this time, unblock parent process.
        master.run()
示例#2
0
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
    import asyncio
    import signal

    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())
        m.run()
    except KeyboardInterrupt:
        pressAnyKeyExitWithDisableProxy()
    except TypeError:
        pass
    except Exception as e:
        print("抓包模块出错:", e)
示例#3
0
def _run_proxy(event, namespace, service, listen_host, listen_port, verbose):
    # Run mitmproxy as a reverse-proxy to the Kubernetes ApiServer under the
    # subpath /api/v1/namespaces/{namespace}/services/{service}/proxy. See
    # https://k8s.io/docs/tasks/administer-cluster/access-cluster-services.
    client = kubernetes.config.new_client_from_config()
    prefix = f"/api/v1/namespaces/{namespace}/services/{service}/proxy"
    options = Options(listen_host=listen_host,
                      listen_port=listen_port,
                      mode=f"reverse:{client.configuration.host}")
    master = DumpMaster(options, with_termlog=verbose, with_dumper=verbose)
    options.keep_host_header = True
    options.ssl_insecure = True
    master.server = ProxyServer(ProxyConfig(options))
    master.addons.add(_Addon(client, prefix))
    event.set()  # Port is bound by this time, unblock parent process.
    master.run()
示例#4
0
    def __init__(self, options: moptions.Options) -> None:
        self.options = options

        self.certstore: certs.CertStore
        self.check_filter: typing.Optional[HostMatcher] = None
        self.check_tcp: typing.Optional[HostMatcher] = None
        self.upstream_server: typing.Optional[server_spec.ServerSpec] = None
        self.configure(options, set(options.keys()))
        options.changed.connect(self.configure)
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()
示例#6
0
    def __init__(self, options: moptions.Options) -> None:
        self.options = options

        self.check_ignore: HostMatcher = None
        self.check_tcp: HostMatcher = None
        self.certstore: certs.CertStore = None
        self.upstream_server: typing.Optional[server_spec.ServerSpec] = None
        self.configure(options, set(options.keys()))
        options.changed.connect(self.configure)
示例#7
0
    def __init__(self, options: moptions.Options) -> None:
        self.options = options

        self.check_ignore = None  # type: HostMatcher
        self.check_tcp = None  # type: HostMatcher
        self.certstore = None  # type: certs.CertStore
        self.client_certs = None  # type: str
        self.openssl_verification_mode_server = None  # type: int
        self.configure(options, set(options.keys()))
        options.changed.connect(self.configure)
示例#8
0
def start_proxy(port):
    options = Options(listen_port=port, )
    # options.body_size_limit='3m'
    config = ProxyConfig(options=options,
                         #    cacert = os.path.expanduser('./mitmproxy.pem'),
                         )
    server = ProxyServer(config)
    print('Intercepting Proxy listening on {0}'.format(port))
    m = TestInterceptor(options, server)
    m.run()
示例#9
0
    def __init__(self, options: moptions.Options) -> None:
        self.options = options

        self.check_ignore = None
        self.check_tcp = None
        self.certstore = None
        self.clientcerts = None
        self.openssl_verification_mode_server = None
        self.configure(options, set(options.keys()))
        options.changed.connect(self.configure)
示例#10
0
    def __init__(self):
        options = Options(
            listen_port=config.port,
            ignore_hosts=[
                ''.join([
                    r'^(?![0-9.]+:)',  # https://docs.mitmproxy.org/stable/howto-ignoredomains/
                    EpicAddon.hosts,  # Allow epic hosts
                    OriginAddon.hosts,  # Allow origin hosts
                ])
            ])
        options.add_option("body_size_limit", int, 0,
                           "")  # Fix for weird bug that crashes mitmproxy

        super().__init__(options)

        self.server = ProxyServer(ProxyConfig(options))
        self.addons.add(EpicAddon())
        self.addons.add(OriginAddon())

        log.info(f'Successfully initialized mitmproxy on port {config.port}')
示例#11
0
 def test_output(self, outfile, expected_out, expected_err, capfd):
     t = termlog.TermLog(outfile=outfile)
     with taddons.context(options=Options(verbosity=2)) as tctx:
         tctx.configure(t)
         t.log(log.LogEntry("one", "info"))
         t.log(log.LogEntry("two", "debug"))
         t.log(log.LogEntry("three", "warn"))
         t.log(log.LogEntry("four", "error"))
     out, err = capfd.readouterr()
     assert out.strip().splitlines() == expected_out
     assert err.strip().splitlines() == expected_err
示例#12
0
    def __init__(self, options: moptions.Options) -> None:
        self.options = options

        self.authenticator = None
        self.check_ignore = None
        self.check_tcp = None
        self.certstore = None
        self.clientcerts = None
        self.openssl_verification_mode_server = None
        self.configure(options, set(options.keys()))
        options.changed.connect(self.configure)
示例#13
0
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()
示例#14
0
    def __init__(self, host, port, addons):

        self.options = Options(listen_host=str(host),
                               listen_port=int(port),
                               http2=True)

        self.mitm = DumpMaster(self.options,
                               with_termlog=False,
                               with_dumper=False)

        self.addons = addons
        self.config_server()
示例#15
0
 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
示例#16
0
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)
示例#17
0
    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))
示例#18
0
    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_')})
示例#19
0
    server = DumpMaster(options, with_termlog=False, with_dumper=False)
    server.server = ProxyServer(ProxyConfig(options))
    return server  # type: master.Master


def run_console(options):
    server = ConsoleMaster(options)
    server.server = ProxyServer(ProxyConfig(options))
    return server  # type: master.Master


from mitmproxy.http import HTTPFlow

if __name__ == "__main__":
    ops = Options(listen_host='0.0.0.0',
                  listen_port=8080,
                  http2=True,
                  ssl_insecure=True)
    master = run_web(ops)
    #ArkInterceptor.tBuilder = troopBuilder.init()
    master.addons.add(ArkEssential())
    # master.addons.add(CharsEssential())
    # master.addons.add(BattleEssential())
    # master.addons.add(allChars())
    # master.addons.add(graduateChars())
    # master.addons.add(unlockSkins())
    # mc = moreChars()
    # mc.addChars(["char_400_weedy"]*12)
    # master.addons.add(mc)
    # master.addons.add(fakeGacha())
    # master.addons.add(userInfo.init("月云影静","0000",120,0))
    # master.addons.add(userData.init(999,999,666,233,101))
示例#20
0
    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():
示例#21
0
        # flow.response.headers["count"] = str(self.num)
        RED = "\033[34m"  # mode 31 = red forground
        GREEN = "\033[35m"
        # print(flow.response.headers)
        RESET = "\033[0m"  # mode 0  = reset


# 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__":
    # try:
    options = Options(listen_host="0.0.0.0", listen_port=8080, http2=True)
    m = DumpMaster(options, with_termlog=False, with_dumper=False)
    config = ProxyConfig(options)
    m.server = ProxyServer(config)
    colorama.init()

    m.addons.add(Addon())

    loop = asyncio.get_event_loop()
    t = threading.Thread(target=loop_in_thread, args=(loop, m))
    t.start()

    print("hello")

    # Other servers might be started too.
    time.sleep(3000)
示例#22
0
    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()

示例#23
0
 def generate_proxy_options(config) -> Options:
     return Options(listen_host=config.get('host'),
                    listen_port=config.get('port'),
                    http2=True,
                    mode='regular')
示例#24
0
 #                 newname = input("请输入新的名字!(不支持中文!)\nPlease Input your new name!")
 #                 with open(localsave + "\\" + "settings" + "\\" + "account_name.txt", "w+", encoding="utf-8") as f:
 #                     f.write(newname)
 #                 print("修改新名字成功,新名字为:" + newname + "\n Set new name successfully!New name is" + newname)
 #     else:
 #         print("看起来这是您第一次启动游戏。请按照向导设置您的游戏属性!\nSeems this is the first time you run the game,please follow the "
 #               "guide to set your game!")
 #         newname = input("请输入您游戏内的名字!(不支持中文!)\nPlease Input your new name!")
 #         #先得创建文件夹
 #         os.mkdir(localsave + "\\" + "settings")
 #         with open(localsave + "\\" + "settings" + "\\" + "account_name.txt", "w+", encoding="utf-8") as f:
 #             f.write(newname)
 #         print("设置名字成功,您游戏内的名字为:" + newname + "\n Set the name successfully, your new name is" + newname)
 options = Options(listen_host='0.0.0.0',
                   listen_port=serverport,
                   http2=True,
                   confdir="./certs",
                   mode="reverse:http://127.0.0.1:5555")
 m = DumpMaster(options, with_termlog=False, with_dumper=False)
 config = ProxyConfig(options)
 m.server = ProxyServer(config)
 m.addons.add(Addon())
 block_addon = m.addons.get("block")
 m.addons.remove(block_addon)
 m.addons.add(MyBlock())
 print("服务器已经运行!请配置您的serverip为127.0.0.1。您也可以在局域网内做自建服务器。")
 print("Server is running, Port = " + str(serverport) +
       ", Please configure your serverip to 127.0.0.1(A default "
       "config)")
 print("================================================================")
 # print("正在启动游戏……如果游戏没有成功启动,请手动启动RebornEvolve.exe!\nRunning game...If the game failed to run,please run "
示例#25
0
 def __init__(self, **options):
     opts = Options(**options)
     server = ProxyServer(ProxyConfig(opts))
     super().__init__(opts, server)
示例#26
0
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())