예제 #1
0
 def getChild(self, name, request):
     if name == "traxis":
         print 'traxis'
         return proxy.ReverseProxyResource('www.yahoo.com', 80, '')
     else:
         print 'else'
         return proxy.ReverseProxyResource('www.google.be', 80, '')
예제 #2
0
 def getChild(self, name, request):
     print "getChild called with name:'%s' and request: %s from host: %s" % (name, request, request.getHost())
     if name == "etb1":
         print "proxy on etb1"
         return proxy.ReverseProxyResource('130.107.98.46', 8085, "/")
     elif  name == "etb2":
         print "proxy on etb2"
         return proxy.ReverseProxyResource('130.107.98.48', 8086, "/")
     else:
         NoResource()
예제 #3
0
    def __init__(self, session, path=""):
        BaseController.__init__(self, path=path, session=session)

        self.putChild2("web", WebController(session))
        self.putGZChild("api", ApiController(session))
        self.putGZChild("ajax", AjaxController(session))
        self.putChild2("file", FileController())
        self.putChild2("grab", grabScreenshot(session))
        if os.path.exists(getPublicPath('mobile')):
            self.putChild2("mobile", MobileController(session))
            self.putChild2("m", static.File(getPublicPath() + "/mobile"))
        for static_val in ('js', 'css', 'static', 'images', 'fonts'):
            self.putChild2(
                static_val,
                static.File(
                    six.ensure_binary(getPublicPath() + '/' + static_val)))
        for static_val in ('modern', 'themes', 'webtv', 'vxg'):
            if os.path.exists(getPublicPath(static_val)):
                self.putChild2(
                    static_val,
                    static.File(
                        six.ensure_binary(getPublicPath() + '/' + static_val)))

        if os.path.exists('/usr/bin/shellinaboxd'):
            if os.path.exists('/etc/vtiversion.info'):
                self.putChild2(
                    "terminal",
                    proxy.ReverseProxyResource(b'127.0.0.1', 4200, b'/'))
            else:
                self.putChild2("terminal",
                               proxy.ReverseProxyResource(b'::1', 4200, b'/'))
        self.putGZChild("ipkg", IpkgController(session))
        self.putChild2("autotimer", ATController(session))
        self.putChild2("epgrefresh", ERController(session))
        self.putChild2("bouqueteditor", BQEController(session))
        self.putChild2("transcoding", TranscodingController())
        self.putChild2("wol", WOLClientController())
        self.putChild2("wolsetup", WOLSetupController(session))
        if PICON_PATH:
            self.setPiconChild(PICON_PATH)
        try:
            from Plugins.Extensions.OpenWebif.controllers.NET import NetController
            self.putChild2("net", NetController(session))
        except:  # nosec # noqa: E722
            pass
        try:
            harddiskmanager.on_partition_list_change.append(
                self.onPartitionChange)
        except:  # nosec # noqa: E722
            pass
예제 #4
0
    def _cb_getFileAlias(self, results, filename, request):
        (dbcontentID, dbfilename, mimetype, date_created, size,
         restricted) = results
        # Return a 404 if the filename in the URL is incorrect. This offers
        # a crude form of access control (stuff we care about can have
        # unguessable names effectively using the filename as a secret).
        if dbfilename.encode('utf-8') != filename:
            log.msg(
                "404: dbfilename.encode('utf-8') != filename: %r != %r"
                % (dbfilename.encode('utf-8'), filename))
            defer.returnValue(fourOhFour)

        stream = yield self.storage.open(dbcontentID)
        if stream is not None:
            # XXX: Brad Crittenden 2007-12-05 bug=174204: When encodings are
            # stored as part of a file's metadata this logic will be replaced.
            encoding, mimetype = guess_librarian_encoding(filename, mimetype)
            file = File(mimetype, encoding, date_created, stream, size)
            # Set our caching headers. Public Librarian files can be
            # cached forever, while private ones mustn't be at all.
            request.setHeader(
                'Cache-Control',
                'max-age=31536000, public'
                if not restricted else 'max-age=0, private')
            defer.returnValue(file)
        elif self.upstreamHost is not None:
            defer.returnValue(
                proxy.ReverseProxyResource(
                    self.upstreamHost, self.upstreamPort, request.path))
        else:
            raise AssertionError(
                "Content %d missing from storage." % dbcontentID)
예제 #5
0
	def __init__(self, session, path=""):
		BaseController.__init__(self, path=path, session=session)

		self.putChild("web", WebController(session))
		self.putGZChild("api", ApiController(session))
		self.putGZChild("ajax", AjaxController(session))
		self.putChild("file", FileController())
		self.putChild("grab", grabScreenshot(session))
		if os.path.exists(getPublicPath('mobile')):
			self.putChild("mobile", MobileController(session))
			self.putChild("m", static.File(getPublicPath() + "/mobile"))
		for static_val in ('js', 'css', 'static', 'images', 'fonts'):
			self.putChild(static_val, static.File(getPublicPath() + '/' + static_val))
		for static_val in ('themes', 'webtv', 'vxg'):
			if os.path.exists(getPublicPath(static_val)):
				self.putChild(static_val, static.File(getPublicPath() + '/' + static_val))

		if os.path.exists('/usr/bin/shellinaboxd'):
			self.putChild("terminal", proxy.ReverseProxyResource('::1', 4200, '/'))
		self.putGZChild("ipkg", IpkgController(session))
		self.putChild("autotimer", ATController(session))
		self.putChild("epgrefresh", ERController(session))
		self.putChild("bouqueteditor", BQEController(session))
		self.putChild("transcoding", TranscodingController())
		self.putChild("wol", WOLClientController())
		self.putChild("wolsetup", WOLSetupController(session))
		if PICON_PATH:
			self.putChild("picon", static.File(PICON_PATH))
		try:
			from NET import NetController
			self.putChild("net", NetController(session))
		except:
			pass
예제 #6
0
    def __init__(self, configs):

        self.proxy_address = configs['proxy_address']
        self.proxy_port = configs['proxy_port']
        self.upstream_host = configs['upstream_host']
        self.upstream_port = configs['upstream_port']
        self.redis_host = configs['redis_host']
        self.redis_port = configs['redis_port']
        self.request_channel = configs['control_pub_queue']
        self.response_channel = configs['control_sub_queue']

        self._start_logging()

        self.module_registry = Registry(configs)
        self.site = server.Site(
            proxy.ReverseProxyResource(self.upstream_host, self.upstream_port,
                                       ''))

        redis_endpoint = TCP4ClientEndpoint(reactor, self.redis_host,
                                            self.redis_port)

        op_factory = RedisOperationFactory(self, redis_endpoint,
                                           self.response_channel)
        self.redis_conn = redis_endpoint.connect(
            HBProxyMgmtRedisSubscriberFactory(self.request_channel,
                                              op_factory))
        self.redis_conn.addCallback(self.subscribe).addCallback(
            self.start_proxy)
예제 #7
0
    def getChild(self, name, request):
        if 'proxy_' in name:
            host, port = name.split('_')[1:]
            b = proxy.ReverseProxyResource(host, int(port), '')
            return b

        return resource.Resource.getChild(self, name, request)
예제 #8
0
파일: proxy.py 프로젝트: tarunsmalviya/smap
 def getChild(self, name, request):
     if name == '':
         return self
     elif name in self.child_proxies:
         host, port, rpath = self.child_proxies[name]
         return proxy.ReverseProxyResource(host, port, rpath + '/data')
     else:
         return NoResource()
예제 #9
0
def main():
    #	site = ClipperzTestSite(proxy.ReverseProxyResource('localhost', 8084, '/java-backend'))
    site = ClipperzTestSite(
        proxy.ReverseProxyResource('localhost', 8084, '/app'))
    #	site = ClipperzTestSite(proxy.ReverseProxyResource('www.clipperz.com', 443, '/'))
    reactor.listenTCP(8888, site)

    reactor.run()
예제 #10
0
    def getChild(self, name, request):
        # Assume an HTTP 1.1 request
        proxy_host = request.requestHeaders.getRawHeaders('Host')
        request.requestHeaders.setRawHeaders('X-Forwarded-Host', proxy_host)

        if (request.uri in ['/json/get_events']
                or request.uri.startswith('/json/events')
                or request.uri.startswith('/api/v1/events')
                or request.uri.startswith('/sockjs')):
            return proxy.ReverseProxyResource('localhost', tornado_port,
                                              '/' + name)

        elif (request.uri.startswith('/webpack')
              or request.uri.startswith('/socket.io')):
            return proxy.ReverseProxyResource('localhost', webpack_port,
                                              '/' + name)

        return proxy.ReverseProxyResource('localhost', django_port, '/' + name)
예제 #11
0
 def proxyRender(self, results):
     #print 'getAddress results: {0}'.format(results)
     if not results:
         self.request.write(
             '<html><body>Unknown Request. Sorry.</body></html>')
         self.request.finish()
     else:
         host = str(results[0][0])  #can't be unicode
         port = results[0][1]
         #print "proxy.ReverseProxyResource(%s, %s)" % (host, port)
         return proxy.ReverseProxyResource(host, port,
                                           "/").render(self.request)
예제 #12
0
    def __init__(self, static):
        Resource.__init__(self)
        self.static = static
        self.putChild('clear_cache', ClearCache())
        self.putChild('clear_attachments', ClearAttachments())
        self.putChild('update_prices', UpdatePrices())
        self.putChild('edit_model', EditModel())
        self.putChild(
            'couch',
            proxy.ReverseProxyResource('127.0.0.1', 5984, '', reactor=reactor))
        self.putChild('findorder', FindOrder())
        self.putChild('storeorder', StoreOrder())
        self.putChild('storemodel', StoreModel())
        self.putChild('mothers', Mothers())
        self.putChild('store_mother', StoreMother())
        self.putChild('tablets', Tablets())
        self.putChild('store_tablet', StoreTablet())
        self.putChild('store_promo', StorePromo())
        self.putChild('procs', Procs())
        self.putChild('store_proc', StoreProc())
        self.putChild('videos', Videos())
        self.putChild('store_video', StoreVideo())
        self.putChild('notebooks', NoteBooks())
        self.putChild('store_note', StoreNote())
        self.putChild('warranty', WarrantyFill())
        self.putChild('show_how', ShowHow())
        self.putChild('edit_how', EditHow())
        self.putChild('comet', AdminComet())
        self.putChild('acceptComet', AcceptComet())
        self.putChild('session', SessionGetter())
        self.putChild('promo', Promo())
        self.putChild('wit_for_mapping', WitForMapping())
        self.putChild('new_for_mapping', NewForMapping())
        self.putChild('store_wit_new_map', StoreWitNewMap())
        self.putChild('delete_wit_new_map', DeleteWitNewMap())

        self.putChild('get_new_descriptions', GetNewDescriptions())
        self.putChild('clone_new_descriptions', CloneNewDescriptipon())
        self.putChild('get_desc_from_new', GetDescFromNew())
        self.putChild('store_new_desc', StoreNewDesc())

        self.putChild('get_soho_descriptions', GetSohoDescriptions())
        self.putChild('store_soho_desc', StoreSohoDesc())

        self.putChild('psus', Psus())
        self.putChild('store_psu', StorePsu())
        self.putChild('evolve', Evolve())

        self.putChild('store_description', StoreDescription())

        self.putChild('addImage', AddImage())
예제 #13
0
    def _getResourceForRequest(self, request):
        """
        Return the resource matching the C{Host} header in C{request}.

        If host is valid, return matching proxy to C{AAAA} DNS entry.
        If host is not valid, return a C{NoResource} instance.
        """
        if request.prepath and request.prepath[0] in self.listStaticNames():
            return self.getStaticEntity(request.prepath[0])
        host = request.getHeader(b"host")
        if not self.isValidHost(host):
            return resource.NoResource()
        # Get reverse proxy resource
        return proxy.ReverseProxyResource(host, request.getHost().port, b"")
예제 #14
0
    def __init__(self, session, path=""):
        BaseController.__init__(self, path=path, session=session)
        piconpath = getPiconPath()

        self.putChild("web", WebController(session))
        self.putChild("api", ApiController(session))
        self.putChild("ajax", AjaxController(session))

        encoder_factory = rest_fs_access.GzipEncodeByFileExtensionFactory(
            extensions=[
                'txt', 'json', 'html', 'xml', 'js', 'conf', 'cfg', 'eit', 'sc',
                'ap'
            ])
        #: gzip compression enabled file controller
        wrapped_fs_controller = EncodingResourceWrapper(
            rest_fs_access.FileController(root='/',
                                          resource_prefix="/file",
                                          session=session), [encoder_factory])
        self.putChild("file", wrapped_fs_controller)
        self.putChild("grab", grabScreenshot(session))
        if os.path.exists(getPublicPath('mobile')):
            self.putChild("mobile", MobileController(session))
            self.putChild("m", static.File(getPublicPath() + "/mobile"))
        self.putChild("js", static.File(getPublicPath() + "/js"))
        self.putChild("css", static.File(getPublicPath() + "/css"))
        self.putChild("static", static.File(getPublicPath() + "/static"))
        self.putChild("images", static.File(getPublicPath() + "/images"))
        self.putChild("fonts", static.File(getPublicPath() + "/fonts"))
        if os.path.exists(getPublicPath('themes')):
            self.putChild("themes", static.File(getPublicPath() + "/themes"))
        if os.path.exists(getPublicPath('webtv')):
            self.putChild("webtv", static.File(getPublicPath() + "/webtv"))
        if os.path.exists(getPublicPath('vxg')):
            self.putChild("vxg", static.File(getPublicPath() + "/vxg"))
        if os.path.exists('/usr/bin/shellinaboxd'):
            self.putChild("terminal",
                          proxy.ReverseProxyResource('::1', 4200, '/'))
        self.putChild("ipkg", IpkgController(session))
        self.putChild("autotimer", ATController(session))
        self.putChild("serienrecorder", SRController(session))
        self.putChild("epgrefresh", ERController(session))
        self.putChild("bouqueteditor", BQEController(session))
        self.putChild("transcoding", TranscodingController())
        self.putChild("wol", WOLClientController())
        self.putChild("wolsetup", WOLSetupController(session))
        if piconpath:
            self.putChild("picon", static.File(piconpath))
예제 #15
0
    def _dostart(self):
        home = HomeResource()
        for k in self.proxy:
            v = self.proxy[k]
            pi = kernel.parse_socket_port_info(v)
            if pi[1] is None:
                logger.warn('反向代理丢失%s的port配置' % k)
                continue
            t = proxy.ReverseProxyResource(pi[0], pi[1], b'')
            home.putChild(k.encode('utf-8'), t)

        cfg = [
            'tcp',
            'port=%d' % self.port,
            'interface=%s' % self.listen
        ]
        cfg = ':'.join(cfg)

        s = server.Site(home)
        endpoints.serverFromString(reactor, cfg).listen(s)
        reactor.run()
예제 #16
0
    def getChild(self, path, request):

        # get username from headers
        # - this should be set on authenticated web sessions
        try:
            user = request.getHeader("x-forwarded-user")
        except:
            user = None

        # check if the request comes from the right user (note: can be forged)
        if user == getpass.getuser():

            # get ood token cookie
            # - cookie name depends on the ood interactive session id ($PWD)
            ood_session_id = os.path.basename(os.getcwd())
            try:
                cookie = request.getCookie(
                    b'_ood_token_' +
                    ood_session_id.encode('utf-8')).decode('utf-8')
            except:
                cookie = None

            # get token from environment
            # - $_ood_token_<session_id> is set in template/before.sh script
            try:
                ood_token = os.environ.get("_ood_token_" +
                                           ood_session_id.replace("-", "_"))
            except:
                ood_token = None

            #return proxy.ReverseProxyResource(self.host, self.port, ('/' + path.decode('utf-8')).encode('utf-8'))

            # check that cookie matches the local token
            if cookie == ood_token and cookie is not None:
                return proxy.ReverseProxyResource(
                    self.host, self.port,
                    ('/' + path.decode('utf-8')).encode('utf-8'))

        request.setResponseCode(403)
        return ForbiddenResource()
예제 #17
0
    def __init__(self, session, path=""):
        BaseController.__init__(self, path=path, session=session)
        piconpath = getPiconPath()

        self.putChild("web", WebController(session))
        self.putChild("api", ApiController(session))
        self.putChild("ajax", AjaxController(session))
        self.putChild("file", FileController())
        self.putChild("grab", grabScreenshot(session))
        if os.path.exists(getPublicPath('mobile')):
            self.putChild("mobile", MobileController(session))
            self.putChild("m", static.File(getPublicPath() + "/mobile"))
        self.putChild("js", static.File(getPublicPath() + "/js"))
        self.putChild("css", static.File(getPublicPath() + "/css"))
        self.putChild("static", static.File(getPublicPath() + "/static"))
        self.putChild("images", static.File(getPublicPath() + "/images"))
        self.putChild("fonts", static.File(getPublicPath() + "/fonts"))
        if os.path.exists(getPublicPath('themes')):
            self.putChild("themes", static.File(getPublicPath() + "/themes"))
        if os.path.exists(getPublicPath('webtv')):
            self.putChild("webtv", static.File(getPublicPath() + "/webtv"))
        if os.path.exists(getPublicPath('vxg')):
            self.putChild("vxg", static.File(getPublicPath() + "/vxg"))
        if os.path.exists('/usr/bin/shellinaboxd'):
            self.putChild("terminal",
                          proxy.ReverseProxyResource('::1', 4200, '/'))
        self.putChild("ipkg", IpkgController(session))
        self.putChild("autotimer", ATController(session))
        self.putChild("serienrecorder", SRController(session))
        self.putChild("epgrefresh", ERController(session))
        self.putChild("bouqueteditor", BQEController(session))
        self.putChild("transcoding", TranscodingController())
        self.putChild("wol", WOLClientController())
        self.putChild("wolsetup", WOLSetupController(session))
        if piconpath:
            self.putChild("picon", static.File(piconpath))
"""
This example demonstrates how to run a reverse proxy.

Run this example with:
    $ python reverse-proxy.py

Then visit http://localhost:8080/ in your web browser.
"""

from twisted.internet import reactor
from twisted.web import proxy, server

site = server.Site(proxy.ReverseProxyResource('www.yahoo.com', 80, ''))
reactor.listenTCP(8080, site)
reactor.run()
예제 #19
0
def setup(ip='127.0.0.1'):
    path = "./web"  # path to static resources (html, js etc..)
    root = static.File(path)     # will be served under '/'
    root.putChild('auth', proxy.ReverseProxyResource(ip, 8889, ''))
    root.putChild('battle', proxy.ReverseProxyResource(ip, 8890, ''))
    return server.Site(root)
예제 #20
0
 def start(self):
     site = server.Site(
         proxy.ReverseProxyResource(self.remote_server, self.remote_port,
                                    b''))
     reactor.listenTCP(self.port, site)
     reactor.run()
예제 #21
0
파일: web.py 프로젝트: webvul/SPF
    def start(self):
        self.loadSites()

        if self.config["ip"] == "0.0.0.0":
            self.config["ip"] = Utils.getIP()

        #define phishing sites
        for key in self.websites:
            self.phishingsites[key] = PhishingSite(
                self.config, key, self.websites[key]['path'], self.logpath,
                "logs/" + self.websites[key]['logfile'], self.db,
                self.websites[key]['redirecturl']).getResource()

        site_length = 0
        for key in self.phishingsites:
            if (len(key) > site_length):
                site_length = len(key)

        # if we are doing port based
        print()
        for key in self.phishingsites:
            for port in range(self.MINPORT, self.MAXPORT):
                try:
                    site = Site(self.phishingsites[key],
                                logPath=self.logpath + "logs/" +
                                self.websites[key]['logfile'] + ".access")
                    #                    site.logRequest = True
                    reactor.listenTCP(port, site)
                    print(
                        "Started website [%s] on [http://%s:%s]" %
                        (('{:<%i}' %
                          (site_length)).format(key), self.config["ip"], port))
                    self.websites[key]['port'] = port
                    break
                except twisted.internet.error.CannotListenError as ex:
                    continue

        # if we are doing virtual hosts
        if (self.config["enable_host_based_vhosts"] == "1"):
            print()

            # GENERATING SSL CERTS ARE CURRENTLY BROKEN
            # TODO: Fix this
            # generate new certificates
            #            domains = ""
            #            cert_path = "/etc/letsencrypt/live/"
            #            first = True
            #            for key in self.phishingsites:
            #                domains += "-d " + key + "." + self.config["phishing_domain"] + " "
            #                if first:
            #                    cert_path += key + "." + self.config["phishing_domain"] + "/"
            #                    first = False
            #
            #            cmd = self.config["certbot_path"] + " certonly --register-unsafely-without-email --non-interactive --agree-tos --standalone --force-renewal " + domains
            #
            #            env = os.environ
            #            print "Generating SSL CERT"
            #            proc = subprocess.Popen(cmd, executable='/bin/bash', env=env, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
            #            result = proc.communicate()[0]
            #            m = re.search(r'.* (\/etc\/letsencrypt\/live\/[^\/]+\/).*fullchain.pem.*', result)
            #            print result
            #
            #            cert_path = m.group(1)

            root = vhost.NameVirtualHost()
            site_length += len("." + self.config["phishing_domain"])
            # add each port based vhost to the nam based vhost
            for key in self.phishingsites:
                root.addHost(
                    key + "." + self.config["phishing_domain"],
                    proxy.ReverseProxyResource('localhost',
                                               self.websites[key]['port'], ''))
                #                print "Created VHOST [%s] -> [https://%s:%s]" % (('{:<%i}' % (site_length)).format(key + "." + self.config["phishing_domain"]), self.config["ip"], str(self.websites[key]['port']))
                print("Created VHOST [%s] -> [http://%s:%s]" %
                      (('{:<%i}' %
                        (site_length)).format(key + "." +
                                              self.config["phishing_domain"]),
                       self.config["ip"], str(self.websites[key]['port'])))
            # add a mapping for the base IP address to map to one of the sites
            if (self.phishingsites):
                root.addHost(
                    self.config["ip"],
                    proxy.ReverseProxyResource(
                        'localhost',
                        int(self.websites[list(
                            self.phishingsites.keys())[0]]['port']), ''))
                try:
                    site = Site(root,
                                logPath=self.logpath + "logs/root.log.access")

                    #                    # ADD SSL CERT
                    #                    sslContext = ssl.DefaultOpenSSLContextFactory(
                    #                        cert_path + 'privkey.pem',
                    #                        cert_path + 'fullchain.pem',
                    #                    )
                    #                    reactor.listenSSL(int(self.config["default_web_ssl_port"]), site, contextFactory=sslContext)
                    reactor.listenTCP(int(self.config["default_web_port"]),
                                      site)
                except twisted.internet.error.CannotListenError as ex:
                    #                    print "ERROR: Could not start web service listener on port [" + int(self.config["default_web_ssl_port"]) + "]!"
                    print(
                        "ERROR: Could not start web service listener on port [80]!"
                    )
                    print(ex)
                    print(
                        "ERROR: Host Based Virtual Hosting will not function!")
            else:
                #                print "ERROR: Could not start web service listener on port [" + int(self.config["default_web_ssl_port"]) + "]!"
                print(
                    "ERROR: Could not start web service listener on port [80]!"
                )
                print("ERROR: Host Based Virtual Hosting will not function!")

        print()
        print("Websites loaded and launched.")
        sys.stdout.flush()
        reactor.run()
예제 #22
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
This example demonstrates how to run a reverse proxy.

Run this example with:
    $ python reverse-proxy.py

Then visit http://localhost:8080/ in your web browser.
"""

from twisted.internet import reactor
from twisted.web import proxy, server

site = server.Site(proxy.ReverseProxyResource('example.com', 80, b''))
reactor.listenTCP(8080, site)
reactor.run()
예제 #23
0
파일: proxy.py 프로젝트: jzh14/Auction
#-*- coding: UTF-8 -*-
import os
import sys
from twisted.internet import reactor
from twisted.web import proxy, server

if len(sys.argv) == 4:
    site = server.Site(
        proxy.ReverseProxyResource(sys.argv[1], int(sys.argv[2]), ''))
    reactor.listenTCP(int(sys.argv[3]), site)
    reactor.run()
else:
    print len(sys.argv)
예제 #24
0
 def getChild(self, path, request):
     request.received_headers[
         'x-forwarded-host'] = request.received_headers['host']
     if path.startswith('live'):
         return proxy.ReverseProxyResource('localhost', 8090, '/live')
     return proxy.ReverseProxyResource('localhost', 8001, '/' + path)
예제 #25
0
class PhishingWebServer():
    def __init__(self, config):
        self.config = config
        self.logpath = os.getcwd() + "/" + self.config[
            "domain_name"] + "_" + self.config["phishing_domain"] + "/"

        #ensure log path exists
        if not os.path.exists(self.logpath):
            os.makedirs(self.logpath)
        if not os.path.exists(self.logpath + "logs/"):
            os.makedirs(self.logpath + "/logs")

        # set up database connection
        self.db = MyDB(sqlite_file=self.logpath)

        self.websites = {}
        self.phishingsites = {}
        self.MINPORT = int(self.config["vhost_port_min"])
        self.MAXPORT = int(self.config["vhost_port_max"])

    def getTemplates(self):
        templates = []
        db_static_templates = self.db.getWebTemplates(ttype="static")
        db_dynamic_templates = self.db.getWebTemplates(ttype="dynamic")
        if (db_static_templates or db_dynamic_templates):
            for template in db_static_templates:
                parts = template.split("[-]")
                template_file = parts[0] + "/CONFIG"
                if Utils.is_readable(template_file) and os.path.isfile(
                        template_file):
                    templates.append(parts[0])
                    print "STATIC = [%s]" % (parts[0])
            for template in db_dynamic_templates:
                parts = template.split("[-]")
                template_file = parts[0] + "/CONFIG"
                if Utils.is_readable(template_file) and os.path.isfile(
                        template_file):
                    templates.append(parts[0])
                    print "DYNAMIC = [%s]" % (parts[0])
        else:
            for f in os.listdir(self.config["web_template_path"]):
                template_file = os.path.join(self.config["web_template_path"],
                                             f) + "/CONFIG"
                if Utils.is_readable(template_file) and os.path.isfile(
                        template_file):
                    templates.append(
                        os.path.join(self.config["web_template_path"], f))
                    print "FIXED = [%s]" % (os.path.join(
                        self.config["web_template_path"], f))
        return templates

    def loadSites(self):

        templates = self.getTemplates()
        print

        # loop over each web template
        for f in templates:
            template_file = f + "/CONFIG"
            if Utils.is_readable(template_file) and os.path.isfile(
                    template_file):
                print "Found the following web sites: [%s]" % template_file
                # read in the VHOST, LOGFILE, and REDIRECTURL
                VHOST = ""
                LOGFILE = ""
                REDIRECTURL = ""
                #PATH = self.config["web_template_path"] + f + "/"
                PATH = f + "/"
                with open(template_file, "r") as myfile:
                    for line in myfile.readlines():
                        match = re.search("VHOST=", line)
                        if match:
                            VHOST = line.replace('"', "")
                            VHOST = VHOST.split("=")
                            VHOST = VHOST[1].lower().strip()
                        match2 = re.search("LOGFILE=", line)
                        if match2:
                            LOGFILE = line.replace('"', "")
                            LOGFILE = LOGFILE.split("=")
                            LOGFILE = LOGFILE[1].strip()
                        match3 = re.search("REDIRECTURL=", line)
                        if match3:
                            REDIRECTURL = line.replace('"', "")
                            REDIRECTURL = REDIRECTURL.replace(r'\n', "\n")
                            REDIRECTURL = REDIRECTURL.split("=")
                            REDIRECTURL = REDIRECTURL[1].strip()
                self.websites[VHOST] = {
                    'path': PATH,
                    'port': 8000,
                    'logfile': LOGFILE,
                    'redirecturl': REDIRECTURL
                }

    def timedLogFormatter(timestamp, request):
        """
        A custom request formatter.  This is whats used when each request line is formatted.

        :param timestamp:
        :param request: A twisted.web.server.Request instance
        """
        #referrer = _escape(request.getHeader(b"referer") or b"-")
        agent = _escape(request.getHeader(b"user-agent") or b"-")
        duration = round(time.time() - request.started, 4)
        line = (u'"%(ip)s" %(duration)ss "%(method)s %(uri)s %(protocol)s" '
                u'%(code)d %(length)s "%(agent)s"' %
                dict(ip=_escape(request.getClientIP() or b"-"),
                     duration=duration,
                     method=_escape(request.method),
                     uri=_escape(request.uri),
                     protocol=_escape(request.clientproto),
                     code=request.code,
                     length=request.sentLength or u"-",
                     agent=agent))
        return line

    def start(self):
        self.loadSites()

        if self.config["ip"] == "0.0.0.0":
            self.config["ip"] = Utils.getIP()

        #define phishing sites
        for key in self.websites:
            self.phishingsites[key] = PhishingSite(
                self.config, key, self.websites[key]['path'], self.logpath,
                "logs/" + self.websites[key]['logfile'], self.db,
                self.websites[key]['redirecturl']).getResource()

        site_length = 0
        for key in self.phishingsites:
            if (len(key) > site_length):
                site_length = len(key)

        # if we are doing port based
        print
        for key in self.phishingsites:
            for port in range(self.MINPORT, self.MAXPORT):
                try:
                    site = Site(self.phishingsites[key],
                                logPath=self.logpath + "logs/" +
                                self.websites[key]['logfile'] + ".access")
                    #                    site.logRequest = True
                    reactor.listenTCP(port, site)
                    print "Started website [%s] on [http://%s:%s]" % (
                        ('{:<%i}' %
                         (site_length)).format(key), self.config["ip"], port)
                    self.websites[key]['port'] = port
                    break
                except twisted.internet.error.CannotListenError, ex:
                    continue

        # if we are doing virtual hosts
        if (self.config["enable_host_based_vhosts"] == "1"):
            print

            root = vhost.NameVirtualHost()
            site_length += len("." + self.config["phishing_domain"])
            # add each port based vhost to the nam based vhost
            for key in self.phishingsites:
                root.addHost(
                    key + "." + self.config["phishing_domain"],
                    proxy.ReverseProxyResource('localhost',
                                               self.websites[key]['port'], ''))
                print "Created VHOST [%s] -> [https://%s:%s]" % (
                    ('{:<%i}' %
                     (site_length)).format(key + "." +
                                           self.config["phishing_domain"]),
                    self.config["ip"], str(self.websites[key]['port']))
                print "Created VHOST [%s] -> [http://%s:%s]" % (
                    ('{:<%i}' %
                     (site_length)).format(key + "." +
                                           self.config["phishing_domain"]),
                    self.config["ip"], str(self.websites[key]['port']))
            # add a mapping for the base IP address to map to one of the sites
            if (self.phishingsites):
                root.addHost(
                    self.config["ip"],
                    proxy.ReverseProxyResource(
                        'localhost',
                        int(self.websites[self.phishingsites.keys()[0]]
                            ['port']), ''))
                try:
                    site = Site(root,
                                logPath=self.logpath + "logs/root.log.access")

                    # ADD SSL CERT
                    sslContext = ssl.DefaultOpenSSLContextFactory(
                        self.config["cert_path"] + 'privkey.pem',
                        self.config["cert_path"] + 'fullchain.pem',
                    )
                    reactor.listenSSL(int(self.config["default_web_ssl_port"]),
                                      site,
                                      contextFactory=sslContext)
                    reactor.listenTCP(int(self.config["default_web_port"]),
                                      site)
                except twisted.internet.error.CannotListenError, ex:
                    print "ERROR: Could not start web service listener on port [" + int(
                        self.config["default_web_ssl_port"]) + "]!"
                    print "ERROR: Could not start web service listener on port [80]!"
                    print ex
                    print "ERROR: Host Based Virtual Hosting will not function!"
            else:
                print "ERROR: Could not start web service listener on port [" + int(
                    self.config["default_web_ssl_port"]) + "]!"
                print "ERROR: Could not start web service listener on port [80]!"
                print "ERROR: Host Based Virtual Hosting will not function!"
예제 #26
0
from twisted.internet import reactor
from twisted.web import proxy, server

site = server.Site(proxy.ReverseProxyResource('127.0.0.1', 8080, b''))
reactor.listenTCP(8666, site)
reactor.run()
예제 #27
0
 def getChild(self, path, request):
     if not request.requestHeaders.hasHeader(b"x-forwarded-for"):
         host = request.getHeader(b"host")
         return proxy.ReverseProxyResource(
             host, request.getHost().port, request.path
         )
예제 #28
0
from twisted.internet import reactor
from twisted.web import proxy, server
from twisted.web.resource import Resource


class AppendingReverseProxyResource(proxy.ReverseProxyResource):
    
    def __init__(self, host, port, prefix, postfix, reactor=reactor):
        super(AppendingReverseProxyResource, self).__init__(self, host, port, prefix, reactor=reactor)
        self.path += postfix
    

siteRoot = Resource()
site = server.Site(siteRoot)
port6001 = proxy.ReverseProxyResource('localhost', 6001, '')
port7000 = proxy.ReverseProxyResource('localhost', 7000, '')
port8000 = proxy.ReverseProxyResource('localhost', 8000, '')

siteRoot.putChild("ui", port8000)
siteRoot.putChild("slave", port7000)
siteRoot.putChild("api", port6001)

reactor.listenTCP(8080, site)
reactor.run()
예제 #29
0
favicon = os.path.join(os.path.dirname(__file__),
                       'skgargpms/static_media/favicon.ico').replace(
                           '\\', '/')
root_resource.putChild('favicon.ico', static.File(favicon))

#Sproutcore Mobile application URL.
root_resource.putChild(
    'mobile',
    static.File(
        os.path.join(os.path.dirname(__file__),
                     'skgargpms/static_media/mobile').replace('\\', '/')))

#Reverse proxy setup - fdesk.ditchyourip.com/clinic_workflow* ---> fdesk.ditchyourip.com:9000/clinic_workflow*
root_resource.putChild(
    'clinic_workflow',
    twisted_proxy.ReverseProxyResource(INTERFACE, 9000, "clinic_workflow"))

http_factory = server.Site(root_resource,
                           logPath=PROJECT_DIR + "/logs/http.log")
tcpServ = internet.TCPServer(STATIC_PORT, http_factory,
                             interface=INTERFACE).setServiceParent(multi)

# Orbited server: For Commetsession -
proxy_factory = proxy.ProxyFactory()
internet.GenericServer(cometsession.Port,
                       factory=proxy_factory,
                       resource=root_resource,
                       childName="tcp",
                       interface=INTERFACE).setServiceParent(multi)

# Stomp server:
예제 #30
0
파일: proxy.py 프로젝트: akshat91/nextbus
from twisted.internet import reactor
from twisted.web import proxy,server

site=server.Site(proxy.ReverseProxyResource('www.google.com',80, ''))
reactor.listenTCP(8080, site)
reactor.run()