mitmproxy

DirWangK發表於2024-06-30

分享mitmproxy指令碼,但還是推薦直接使用mitmproxy、mitmdump、mitmweb

py

import json
import logging
import os

from mitmproxy.options import Options

from mitmproxy.http import HTTPFlow

from mitmproxy.tools.dump import DumpMaster


from mitmproxy import ctx

from mitmproxy.addons.proxyserver import Proxyserver
# from mitmproxy.proxy.mode_servers import WireGuardServerInstance
# from mitmproxy.proxy.mode_specs import WireGuardMode
import asyncio


class MyAddon(object):
    def __init__(self):
        pass

    def request(self, flow: HTTPFlow):
        print('[-]call MyAddon request')

        # print(flow.request.pretty_url)
        # json_hd = json.dumps(dict(flow.request.headers), indent=2)
        # print(json_hd)

    def response(self, flow: HTTPFlow):
        print('[-]call MyAddon response')
        # print(flow.response.raw_content)
        # flow.response.content = b'helloword!'


class MyWg:
    def running(self):
        fpath='wg_client.conf'
        if os.path.exists(fpath):
            print('[+]wireguard client config path:%s'%(fpath))
            return
        proxyserver: Proxyserver = ctx.master.addons.get("proxyserver")
        if proxyserver:
            sv=proxyserver.servers
            if sv:
                for k,v in sv._instances.items():
                    # print('instances key:',type(k),k)
                    # print('instances value:',type(v),v)
                    if k.type_name=='wireguard':
                        '''
                        WireGuardServerInstance.client_conf
                        '''
                        
                        
                        with open(fpath,'w',encoding='utf8') as f:
                            f.write(v.client_conf())
                            print('[-]save client_conf to:%s'%fpath)







async def do_main(options: Options, flow_detail=4, proxy_debug=True):
    '''
    Args:
        flow_detail:(The original default value is: 1)
                The display detail level for flows in mitmdump: 0 (quiet) to 4 (very verbose).
                0: no output
                1: shortened request URL with response status code
                2: full request URL with response status code and HTTP headers
                3: 2 + truncated response content, content of WebSocket and TCP messages (content_view_lines_cutoff: {CONTENT_VIEW_LINES_CUTOFF})
                4: 3 + nothing is truncated
        proxy_debug:(The original default value is: False)
                Enable debug logs in the proxy core.

    '''
    m = DumpMaster(
        options,
        with_dumper=True,
    )
    '''
            sc = script.Script(
                tdata.path("mitmproxy/data/addonscripts/error.py"),
                True,
            )
            tctx.master.addons.add(sc)
    '''
	#log 
    logging.getLogger('mitmproxy.addonmanager').setLevel(logging.INFO)
	logging.getLogger('mitmproxy.proxy.mode_servers').setLevel(logging.INFO)
	
    # Add your own custom plugins 
    # m.addons.add(MyAddon(),MyWg())
   
    m.addons.add(MyWg())

    # save flile path
    ctx.options.save_stream_file='save.flow'

    # The display detail level for flows in mitmdump
    ctx.options.flow_detail = flow_detail
    ctx.options.ssl_insecure = True

    # Enable debug logs in the proxy core.
    ctx.options.proxy_debug = proxy_debug

    try:
        print('starting mitmproxy')
        await m.run()
    except KeyboardInterrupt:
        m.shutdown()


if __name__ == "__main__":
    
    options = Options(
        # listen_host='127.0.0.1',
        # listen_port=8080,
        mode=['wireguard:./wg_key.conf@51821'],
    )
    
    loop = asyncio.new_event_loop()
    proxy_debug=False
    flow_detail=4
    loop.run_until_complete(do_main(options,flow_detail,proxy_debug))