Пример #1
0
    def run(self, host, port, username=None, password=None):
        if username is not None and password is not None:
            cherrypy.config.update({'tools.auth_digest.on': True,
                                    'tools.auth_digest.realm': 'localhost',
                                    'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain({username: password}),
                                    'tools.auth_digest.key': 'a565c27146791cfb'})

        cherrypy.tree.mount(self, '/')
        cherrypy.tree.mount(StatisticView(),
                            '/statistics',
                            {'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})

        cherrypy.tree.mount(StateView(),
                            '/states',
                            {'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})

        cherrypy.tree.mount(TimerView(),
                            '/timers',
                            {'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})

        cherrypy.tree.mount(SequenceView(),
                            '/sequences',
                            {'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})

        cherrypy.server.socket_host = host
        cherrypy.server.socket_port = port

        cherrypy.engine.start()
        cherrypy.engine.block()
Пример #2
0
def _configure_server(restarting=False):
    global websocket_plugin

    # Configure server error log
    cherrypy.config.update({'log.error_file': 'cherrypy.error.log'})

    # Configure server url
    cherrypy.config.update({'server.socket_host': utils.s2n(autosubliminal.WEBSERVERIP),
                            'server.socket_port': int(autosubliminal.WEBSERVERPORT)
                            })

    # Disable engine plugins (no need for autoreload plugin)
    cherrypy.config.update({'engine.autoreload.on': False})

    # Configure authentication in if a username and password is set by the user
    if autosubliminal.USERNAME and autosubliminal.PASSWORD:
        users = {utils.s2n(autosubliminal.USERNAME): utils.s2n(autosubliminal.PASSWORD)}
        cherrypy.config.update({'tools.auth_digest.on': True,
                                'tools.auth_digest.realm': 'Auto-Subliminal website',
                                'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(users),
                                'tools.auth_digest.key': 'yek.tsegid_htua.lanimilbuS-otuA'  # Can be any random string
                                })

    if not restarting:
        # Enable websocket plugin
        websocket_plugin = WebSocketPlugin(cherrypy.engine)
        websocket_plugin.subscribe()
        cherrypy.tools.websocket = WebSocketTool()
    else:
        # When restarting we need to create a new websocket manager thread (you cannot start the same thread twice!)
        websocket_plugin.manager = WebSocketManager()
        # When restarting we need to clear the httpserver to force the creation of a new one (needed for ip/port change)
        cherrypy.server.httpserver = None
Пример #3
0
def load_config():

    # TODO: handle errors in input!!
    print("*** Loading config from file ***")
    jsonify_quotes(cwd + '/share/config.json')

    j = json.loads(open(cwd + "/share/config.json").read())

    user = {str(j["user"]): str(j["pass"])}

    port = int(j["port"])

    conf = {
        '/': {
            'tools.sessions.on': True,
            #'tools.staticdir.root': cwd,
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': 'localhost',
            'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(user),
            'tools.auth_digest.key': 'a565c27146791cfb'
        },
        '/generator': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': cwd + '/share/public'
        },
    }

    return conf, port
    def testDigest(self):
        self.getPage('/digest/')
        self.assertStatus(401)
        value = None
        for k, v in self.headers:
            if k.lower() == 'www-authenticate':
                if v.startswith('Digest'):
                    value = v
                    break

        if value is None:
            self._handlewebError('Digest authentification scheme was not found')
        value = value[7:]
        items = value.split(', ')
        tokens = {}
        for item in items:
            key, value = item.split('=')
            tokens[key.lower()] = value

        missing_msg = '%s is missing'
        bad_value_msg = "'%s' was expecting '%s' but found '%s'"
        nonce = None
        if 'realm' not in tokens:
            self._handlewebError(missing_msg % 'realm')
        elif tokens['realm'] != '"localhost"':
            self._handlewebError(bad_value_msg % ('realm', '"localhost"', tokens['realm']))
        if 'nonce' not in tokens:
            self._handlewebError(missing_msg % 'nonce')
        else:
            nonce = tokens['nonce'].strip('"')
        if 'algorithm' not in tokens:
            self._handlewebError(missing_msg % 'algorithm')
        elif tokens['algorithm'] != '"MD5"':
            self._handlewebError(bad_value_msg % ('algorithm', '"MD5"', tokens['algorithm']))
        if 'qop' not in tokens:
            self._handlewebError(missing_msg % 'qop')
        elif tokens['qop'] != '"auth"':
            self._handlewebError(bad_value_msg % ('qop', '"auth"', tokens['qop']))
        get_ha1 = auth_digest.get_ha1_dict_plain({'test': 'test'})
        base_auth = 'Digest username="******", realm="wrong realm", nonce="%s", uri="/digest/", algorithm=MD5, response="%s", qop=auth, nc=%s, cnonce="1522e61005789929"'
        auth_header = base_auth % (nonce, '11111111111111111111111111111111', '00000001')
        auth = auth_digest.HttpDigestAuthorization(auth_header, 'GET')
        ha1 = get_ha1(auth.realm, 'test')
        response = auth.request_digest(ha1)
        auth_header = base_auth % (nonce, response, '00000001')
        self.getPage('/digest/', [('Authorization', auth_header)])
        self.assertStatus(401)
        base_auth = 'Digest username="******", realm="localhost", nonce="%s", uri="/digest/", algorithm=MD5, response="%s", qop=auth, nc=%s, cnonce="1522e61005789929"'
        auth_header = base_auth % (nonce, '11111111111111111111111111111111', '00000001')
        auth = auth_digest.HttpDigestAuthorization(auth_header, 'GET')
        ha1 = get_ha1('localhost', 'test')
        response = auth.request_digest(ha1)
        auth_header = base_auth % (nonce, response, '00000001')
        self.getPage('/digest/', [('Authorization', auth_header)])
        self.assertStatus('200 OK')
        self.assertBody("Hello test, you've been authorized.")
    def testDigest(self):
        self.getPage('/digest/')
        self.assertStatus(401)
        value = None
        for k, v in self.headers:
            if k.lower() == 'www-authenticate':
                if v.startswith('Digest'):
                    value = v
                    break

        if value is None:
            self._handlewebError('Digest authentification scheme was not found')
        value = value[7:]
        items = value.split(', ')
        tokens = {}
        for item in items:
            key, value = item.split('=')
            tokens[key.lower()] = value

        missing_msg = '%s is missing'
        bad_value_msg = "'%s' was expecting '%s' but found '%s'"
        nonce = None
        if 'realm' not in tokens:
            self._handlewebError(missing_msg % 'realm')
        elif tokens['realm'] != '"localhost"':
            self._handlewebError(bad_value_msg % ('realm', '"localhost"', tokens['realm']))
        if 'nonce' not in tokens:
            self._handlewebError(missing_msg % 'nonce')
        else:
            nonce = tokens['nonce'].strip('"')
        if 'algorithm' not in tokens:
            self._handlewebError(missing_msg % 'algorithm')
        elif tokens['algorithm'] != '"MD5"':
            self._handlewebError(bad_value_msg % ('algorithm', '"MD5"', tokens['algorithm']))
        if 'qop' not in tokens:
            self._handlewebError(missing_msg % 'qop')
        elif tokens['qop'] != '"auth"':
            self._handlewebError(bad_value_msg % ('qop', '"auth"', tokens['qop']))
        get_ha1 = auth_digest.get_ha1_dict_plain({'test': 'test'})
        base_auth = 'Digest username="******", realm="wrong realm", nonce="%s", uri="/digest/", algorithm=MD5, response="%s", qop=auth, nc=%s, cnonce="1522e61005789929"'
        auth_header = base_auth % (nonce, '11111111111111111111111111111111', '00000001')
        auth = auth_digest.HttpDigestAuthorization(auth_header, 'GET')
        ha1 = get_ha1(auth.realm, 'test')
        response = auth.request_digest(ha1)
        auth_header = base_auth % (nonce, response, '00000001')
        self.getPage('/digest/', [('Authorization', auth_header)])
        self.assertStatus(401)
        base_auth = 'Digest username="******", realm="localhost", nonce="%s", uri="/digest/", algorithm=MD5, response="%s", qop=auth, nc=%s, cnonce="1522e61005789929"'
        auth_header = base_auth % (nonce, '11111111111111111111111111111111', '00000001')
        auth = auth_digest.HttpDigestAuthorization(auth_header, 'GET')
        ha1 = get_ha1('localhost', 'test')
        response = auth.request_digest(ha1)
        auth_header = base_auth % (nonce, response, '00000001')
        self.getPage('/digest/', [('Authorization', auth_header)])
        self.assertStatus('200 OK')
        self.assertBody("Hello test, you've been authorized.")
Пример #6
0
        def authenticate(*args, **kwargs):
            cookie = cherrypy.request.cookie.get(self.cookie_name, None)

            if not (allow_cookie_auth and self.is_valid(cookie)):
                digest_auth(self.realm, get_ha1_dict_plain(self.users_dict),
                            self.secret)

            cookie = cherrypy.response.cookie
            cookie[self.cookie_name] = self.generate_cookie()
            cookie[self.cookie_name]['path'] = '/'
            cookie[self.cookie_name]['version'] = '1'

            return func(*args, **kwargs)
Пример #7
0
        def authenticate(*args, **kwargs):
            cookie = cherrypy.request.cookie.get(self.cookie_name, None)

            if not (allow_cookie_auth and self.is_valid(cookie)):
                digest_auth(self.realm, get_ha1_dict_plain(self.users_dict),
                            self.secret)

            cookie = cherrypy.response.cookie
            cookie[self.cookie_name] = self.generate_cookie()
            cookie[self.cookie_name]['path'] = '/'
            cookie[self.cookie_name]['version'] = '1'

            return func(*args, **kwargs)
Пример #8
0
def get_app_config():
    return {
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.join(config.HERE, 'static'),
        },
        '/': {
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': 'localhost',
            'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(USERS),
            'tools.auth_digest.key': 'a565c27146791cfb'
        }
    }
Пример #9
0
 def __init__(self, username, password):
     self.cp_config = {
         '/': {
             'tools.auth_digest.on':
             True,
             'tools.auth_digest.realm':
             'stracker admin area',
             'tools.auth_digest.get_ha1':
             auth_digest.get_ha1_dict_plain({username: password}),
             'tools.auth_digest.key':
             random.getrandbits(64),
         }
     }
     WwwServer.__init__(self, static_base_dir + "/admin")
Пример #10
0
def _configure_server(restarting=False):
    global websocket_plugin

    # Configure server error log
    cherrypy.config.update({'log.error_file': 'cherrypy.error.log'})

    # Configure server url
    cherrypy.config.update({
        'server.socket_host':
        s2n(autosubliminal.WEBSERVERIP),
        'server.socket_port':
        int(autosubliminal.WEBSERVERPORT)
    })

    # Disable engine plugins (no need for autoreload plugin)
    cherrypy.config.update({'engine.autoreload.on': False})

    # Read and store cherrypy server version (if not set, it returns CherryPy/Unknown because it's not installed)
    server_header = 'CherryPy/%s' % get_library_version('cherrypy')
    cherrypy.config.update({'response.headers.server': server_header})

    # Configure authentication in if a username and password is set by the user
    if autosubliminal.USERNAME and autosubliminal.PASSWORD:
        users = {s2n(autosubliminal.USERNAME): s2n(autosubliminal.PASSWORD)}
        cherrypy.config.update({
            'tools.auth_digest.on':
            True,
            'tools.auth_digest.realm':
            'Auto-Subliminal website',
            'tools.auth_digest.get_ha1':
            auth_digest.get_ha1_dict_plain(users),
            'tools.auth_digest.key':
            'yek.tsegid_htua.lanimilbuS-otuA'  # Can be any random string
        })

    # Configure our custom json_out_handler (Uncomment if it should be used for any @cherrypy.tools.json_out())
    # cherrypy.config.update({'tools.json_out.handler': json_out_handler})

    if not restarting:
        # Enable websocket plugin
        websocket_plugin = WebSocketPlugin(cherrypy.engine)
        websocket_plugin.subscribe()
        cherrypy.tools.websocket = WebSocketTool()
    else:
        # When restarting we need to create a new websocket manager thread (you cannot start the same thread twice!)
        websocket_plugin.manager = WebSocketManager()
        # When restarting we need to clear the httpserver to force the creation of a new one (needed for ip/port change)
        cherrypy.server.httpserver = None
Пример #11
0
def start_server(start_callback, stop_callback):

    config = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': str(get_project_path().absolute())
        },
        '/api': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/json')],
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './webapp'
        }
    }

    cherrypy.engine.subscribe('start', start_callback)
    cherrypy.engine.subscribe('stop', stop_callback)

    app = App()
    app.api = Api()
    app.api.status = ApiStatus()
    app.api.config = ApiConfig()
    app.api.logs = ApiLogs()
    app.api.set_controller_mode = ApiSetControllerMode()
    app.api.activate_zone = ApiActivateZone()
    app.api.run_cycle = ApiRunCycle()
    app.api.stop_sprinkler = ApiStopSprinkler()

    user = {CONFIG.server.user: CONFIG.server.password}

    cherrypy.config.update({'log.screen': False,
                            'log.access_file': '',
                            'log.error_file': '',
                            'tools.auth_digest.on': True,
                            'tools.auth_digest.realm': 'localhost',
                            'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(user),
                            'tools.auth_digest.key': 'b361e37146791cfb',
                            'tools.auth_digest.accept_charset': 'UTF-8'
                            })
    logging.getLogger("cherrypy").propagate = False
    logging.getLogger("cherrypy.error").addHandler(GLOBAL_LOG_HANDLER)

    cherrypy.config.update({'server.socket_host': '0.0.0.0',
                            'server.socket_port': CONFIG.server.port})
    cherrypy.quickstart(app, '/', config)
Пример #12
0
def main():
    USERS = {'USER': '******'}
    cherrypy.config.update({
        'server.socket_host': '::',
        'server.socket_port': 8080,
    })
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': 'localhost',
            'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(USERS),
            'tools.auth_digest.key': '3f80c187d4fbbb054b4f24ab1f3cb231',
            'tools.auth_digest.accept_charset': 'UTF-8',
        },
    }
    webapp = Subscribe()

    cherrypy.quickstart(webapp, '/', conf)
Пример #13
0
def _configure_server(restarting=False):
    global websocket_plugin

    # Configure server error log
    cherrypy.config.update({'log.error_file': 'cherrypy.error.log'})

    # Configure server url
    cherrypy.config.update({'server.socket_host': s2n(autosubliminal.WEBSERVERIP),
                            'server.socket_port': int(autosubliminal.WEBSERVERPORT)
                            })

    # Disable engine plugins (no need for autoreload plugin)
    cherrypy.config.update({'engine.autoreload.on': False})

    # Read and store cherrypy server version (if not set, it returns CherryPy/Unknown because it's not installed)
    server_header = 'CherryPy/%s' % get_library_version('cherrypy')
    cherrypy.config.update({'response.headers.server': server_header})

    # Configure authentication in if a username and password is set by the user
    if autosubliminal.USERNAME and autosubliminal.PASSWORD:
        users = {s2n(autosubliminal.USERNAME): s2n(autosubliminal.PASSWORD)}
        cherrypy.config.update({'tools.auth_digest.on': True,
                                'tools.auth_digest.realm': 'Auto-Subliminal website',
                                'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(users),
                                'tools.auth_digest.key': 'yek.tsegid_htua.lanimilbuS-otuA'  # Can be any random string
                                })

    # Configure our custom json_out_handler (Uncomment if it should be used for any @cherrypy.tools.json_out())
    # cherrypy.config.update({'tools.json_out.handler': json_out_handler})

    if not restarting:
        # Enable websocket plugin
        websocket_plugin = WebSocketPlugin(cherrypy.engine)
        websocket_plugin.subscribe()
        cherrypy.tools.websocket = WebSocketTool()
    else:
        # When restarting we need to create a new websocket manager thread (you cannot start the same thread twice!)
        websocket_plugin.manager = WebSocketManager()
        # When restarting we need to clear the httpserver to force the creation of a new one (needed for ip/port change)
        cherrypy.server.httpserver = None
Пример #14
0
import cherrypy
from cherrypy.lib import auth_digest

USERS = {
	'admin':'Start!123'
}

class SecureApp(object):
	@cherrypy.expose
	def index(self):
		return 'Successfull authentication!'


if __name__ == '__main__':
	conf = {
		'/' : {
			'tools.auth_digest.on' : True,
			'tools.auth_digest.realm' : 'localhost',
			'tools.auth_digest.get_ha1' : auth_digest.get_ha1_dict_plain(USERS),
			'tools.auth_digest.key' : 'a565c27146791cfb',
			'tools.auth_basic.accept_charset' : 'UTF-8',
		}

	}
	cherrypy.quickstart(SecureApp(),'/',conf)
Пример #15
0
def start_server() -> None:
    """Web server initialization

    :return: None
    """

    controller = Controller()

    def stop_callback() -> None:
        controller.stop()
        cleanup_pi()

    app = App()
    app.api = Api()
    app.api.toggle_light = ApiToggleSwitch(controller, Switch.LIGHT)
    app.api.toggle_ir_light = ApiToggleSwitch(controller, Switch.IR_LIGHT)
    app.api.toggle_fan = ApiToggleSwitch(controller, Switch.FAN)
    app.api.status = ApiStatus(controller)

    users: Dict[str, str] = {CONFIG.server.user: CONFIG.server.password} #type: ignore

    auth_config = {
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': 'localhost',
            'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(users),
            'tools.auth_digest.key': 'afa51d97d0948067097fd69cfc10b4da',
            'tools.auth_digest.accept_charset': 'UTF-8',
        }

    api_config = {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/json')],
        }

    app_config = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': str(get_project_path().absolute())
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './webapp'
        },
        '/home': auth_config,
        '/logs': auth_config,
        '/api': { **api_config, **auth_config }
    }

    logging.getLogger("cherrypy").propagate = False
    logging.getLogger("cherrypy.error").addHandler(GLOBAL_LOG_HANDLER)

    global_config = {
        'log.screen': False,
        'log.access_file': '',
        'log.error_file': '',
        'server.socket_host': '0.0.0.0',
        'server.socket_port': CONFIG.server.port #type: ignore
    }
    cherrypy.config.update(global_config)
    cherrypy.engine.subscribe('stop', stop_callback)
    cherrypy.quickstart(app, '/', app_config)
Пример #16
0
        print "Using admin admin login"
        usersDict.update({"admin":"admin"})

    #Create the SSL certificate if you have a valid certificate comment out these lines
    #and set the path to your certificate and key with certPath and keyPath
    currentDir = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
    create_self_signed_cert(currentDir)
    certPath = currentDir + "/" + CERT_FILE
    keyPath = currentDir + "/" + KEY_FILE

    #Add the certificates to the server
    cherrypy.server.ssl_module = 'builtin'
    cherrypy.server.ssl_certificate = certPath
    cherrypy.server.ssl_private_key = keyPath

    # Enable access to static files via the web directory and add basic auth
    currentDir = os.path.abspath(sf.myPath())
    conf = {'/static': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': os.path.join(currentDir, 'static')},
        '/': {
        'tools.auth_digest.on': True,
        'tools.auth_digest.realm': sfConfig['__webaddr'],
        'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(usersDict),
        'tools.auth_digest.key': 'a565c27146791cfb'
    }}

    # Try starting the web server. If it fails due to a database being
    # missing, start a smaller web server just for setting up the DB.
    cherrypy.quickstart(SpiderFootWebUi(sfConfig), script_name=sfConfig['__docroot'], config=conf)
Пример #17
0
    })

    pwm_display_config = {
        '/': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': args.static_dir
        }
    }

    pwm_api_config = {'/': {}}
    if args.user and args.password:
        pwm_api_config['/'] = {
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': 'PWM API',
            'tools.auth_digest.get_ha1':
                auth_digest.get_ha1_dict_plain({args.user: args.password}),
            'tools.auth_digest.key': 'b2fb6f93353cc4c6'
        }

    # Bah! But if I don't do this, RPi.GPIO usually segfaults due to some conflict with CherryPy.
    # If I ever have the time, I may want to look for an alternative PWM library that gives a
    # less shoddy impression.
    time.sleep(1)

    # Override the default handle_SIGHUP, which will restart CherryPy if receiving a SIGUP while
    # running as daemon. Even though I spawn this script through nohup, somehow a SIGHUP still
    # ends up being received when the shutdownpi script is invoked from within. (You don't want
    # to know how much time I've wasted debugging this.)
    cherrypy.engine.signal_handler.handlers['SIGHUP'] = cherrypy.engine.signal_handler.bus.exit
    cherrypy.engine.subscribe('stop', PWM.shutdown)
Пример #18
0
def start_web_server(sfWebUiConfig, sfConfig):
    """Start the web server so you can start looking at results

    Args:
        sfWebUiConfig (dict): web server options
        sfConfig (dict): SpiderFoot config options
    """

    web_host = sfWebUiConfig.get('host', '127.0.0.1')
    web_port = sfWebUiConfig.get('port', 5001)
    web_root = sfWebUiConfig.get('root', '/')

    # Place your whitelisted CORS origins here
    # Example: cors_origins = ['http://example.com']
    cors_origins = []

    cherrypy.config.update({
        'log.screen': False,
        'server.socket_host': web_host,
        'server.socket_port': int(web_port)
    })

    log.info(f"Starting web server at {web_host}:{web_port} ...")

    # Disable auto-reloading of content
    cherrypy.engine.autoreload.unsubscribe()

    sf = SpiderFoot(sfConfig)

    # Enable access to static files via the web directory
    conf = {
        '/query': {
            'tools.encode.text_only': False,
            'tools.encode.add_charset': True,
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'static',
            'tools.staticdir.root': sf.myPath()
        }
    }

    secrets = dict()

    log.info("Check for username and password environment variables")
    if 'SF_USERNAME' in os.environ.keys():
        username = os.environ.get("SF_USERNAME")
        log.info("found username")
    else:
        username = None
    if 'SF_PASSWORD' in os.environ.keys():
        password = os.environ.get("SF_PASSWORD")
        log.info("found password")
    else:
        password = None
    
    # add the username and password to the secrets dictionary. 
    if username == None or password == None:
        log.info("No username/password environment variables defined.") 
    else:
        secrets[username] = password


    passwd_file = sf.dataPath() + '/passwd'
    if os.path.isfile(passwd_file):
        if not os.access(passwd_file, os.R_OK):
            log.error("Could not read passwd file. Permission denied.")
            sys.exit(-1)

        pw = open(passwd_file, 'r')

        for line in pw.readlines():
            if ':' not in line:
                log.error("Incorrect format of passwd file, must be username:password on each line.")
                sys.exit(-1)

            u = line.strip().split(":")[0]
            p = ':'.join(line.strip().split(":")[1:])

            if not u or not p:
                log.error("Incorrect format of passwd file, must be username:password on each line.")
                sys.exit(-1)

            secrets[u] = p

    if secrets:
        log.info("Enabling authentication based on supplied passwd file or environment variables.")
        conf['/'] = {
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': web_host,
            'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(secrets),
            'tools.auth_digest.key': random.SystemRandom().randint(0, 99999999)
        }
    else:
        warn_msg = "\n********************************************************************\n"
        warn_msg += "Warning: passwd file contains no passwords. Authentication disabled.\n"
        warn_msg += "Please consider adding authentication to protect this instance!\n"
        warn_msg += "Refer to https://www.spiderfoot.net/documentation/#security.\n"
        warn_msg += "********************************************************************\n"
        log.warning(warn_msg)

    using_ssl = False
    key_path = sf.dataPath() + '/spiderfoot.key'
    crt_path = sf.dataPath() + '/spiderfoot.crt'
    if os.path.isfile(key_path) and os.path.isfile(crt_path):
        if not os.access(crt_path, os.R_OK):
            log.critical(f"Could not read {crt_path} file. Permission denied.")
            sys.exit(-1)

        if not os.access(key_path, os.R_OK):
            log.critical(f"Could not read {key_path} file. Permission denied.")
            sys.exit(-1)

        log.info("Enabling SSL based on supplied key and certificate file.")
        cherrypy.server.ssl_module = 'builtin'
        cherrypy.server.ssl_certificate = crt_path
        cherrypy.server.ssl_private_key = key_path
        using_ssl = True

    if using_ssl:
        url = "https://"
        cors_origins.append(f"https://{web_host}:{web_port}")
    else:
        url = "http://"
        cors_origins.append(f"http://{web_host}:{web_port}")

    if web_host == "0.0.0.0":  # nosec
        url = f"{url}<IP of this host>"
    else:
        url = f"{url}{web_host}"

    url = f"{url}:{web_port}{web_root}"

    cherrypy_cors.install()
    cherrypy.config.update({
        'cors.expose.on': True,
        'cors.expose.origins': cors_origins,
        'cors.preflight.origins': cors_origins
    })

    print("")
    print("*************************************************************")
    print(" Use SpiderFoot by starting your web browser of choice and ")
    print(f" browse to {url}")
    print("*************************************************************")
    print("")

    cherrypy.quickstart(SpiderFootWebUi(sfWebUiConfig, sfConfig), script_name=web_root, config=conf)
Пример #19
0
    }}

    if os.path.isfile(sf.myPath() + '/passwd'):
        secrets = dict()
        pw = file(sf.myPath() + '/passwd', 'r')
        for line in pw.readlines():
            u, p = line.strip().split(":")
            if None in [u, p]:
                print "Incorrect format of passwd file, must be username:password on each line."
                sys.exit(-1)
            secrets[u] = p

        print "Enabling authentication based on supplied passwd file."
        conf['/'] = {
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': sfConfig['__webaddr'],
            'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(secrets),
            'tools.auth_digest.key': random.randint(0, 99999999)
        }

    if os.path.isfile(sf.myPath() + '/spiderfoot.key') and \
       os.path.isfile(sf.myPath() + '/spiderfoot.crt'):
        print "Enabling SSL based on supplied key and certificate file."
        cherrypy.server.ssl_module = 'builtin'
        cherrypy.server.ssl_certificate = sf.myPath() + '/spiderfoot.crt'
        cherrypy.server.ssl_private_key = sf.myPath() + '/spiderfoot.key'

    # Try starting the web server. If it fails due to a database being
    # missing, start a smaller web server just for setting up the DB.
    cherrypy.quickstart(SpiderFootWebUi(sfConfig), script_name=sfConfig['__docroot'], config=conf)
Пример #20
0
                print(
                    "Incorrect format of passwd file, must be username:password on each line."
                )
                sys.exit(-1)

            secrets[u] = p

        if secrets:
            print("Enabling authentication based on supplied passwd file.")
            conf['/'] = {
                'tools.auth_digest.on':
                True,
                'tools.auth_digest.realm':
                sfConfig['__webaddr'],
                'tools.auth_digest.get_ha1':
                auth_digest.get_ha1_dict_plain(secrets),
                'tools.auth_digest.key':
                random.SystemRandom().randint(0, 99999999)
            }
        else:
            print(
                "Warning: passwd file contains no passwords. Authentication disabled."
            )

    key_path = sf.myPath() + '/spiderfoot.key'
    crt_path = sf.myPath() + '/spiderfoot.crt'
    if os.path.isfile(key_path) and os.path.isfile(crt_path):
        if not os.access(crt_path, os.R_OK):
            print("Could not read spiderfoot.crt file. Permission denied.")
            sys.exit(-1)
Пример #21
0
def start_web_server(sfWebUiConfig, sfConfig):
    """Start the web server so you can start looking at results"""

    web_host = sfWebUiConfig.get('host', '127.0.0.1')
    web_port = sfWebUiConfig.get('port', 5001)
    web_root = sfWebUiConfig.get('root', '/')

    cherrypy.config.update({
        'server.socket_host': web_host,
        'server.socket_port': int(web_port)
    })

    log.info(f"Starting web server at {web_host}:{web_port} ...")

    # Disable auto-reloading of content
    cherrypy.engine.autoreload.unsubscribe()

    sf = SpiderFoot(sfConfig)

    # Enable access to static files via the web directory
    conf = {
        '/query': {
            'tools.encode.text_only': False,
            'tools.encode.add_charset': True,
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'static',
            'tools.staticdir.root': sf.myPath()
        }
    }

    passwd_file = sf.dataPath() + '/passwd'
    if os.path.isfile(passwd_file):
        if not os.access(passwd_file, os.R_OK):
            log.error("Could not read passwd file. Permission denied.")
            sys.exit(-1)

        secrets = dict()

        pw = open(passwd_file, 'r')

        for line in pw.readlines():
            if ':' not in line:
                log.error(
                    "Incorrect format of passwd file, must be username:password on each line."
                )
                sys.exit(-1)

            u = line.strip().split(":")[0]
            p = ':'.join(line.strip().split(":")[1:])

            if not u or not p:
                log.error(
                    "Incorrect format of passwd file, must be username:password on each line."
                )
                sys.exit(-1)

            secrets[u] = p

        if secrets:
            log.info("Enabling authentication based on supplied passwd file.")
            conf['/'] = {
                'tools.auth_digest.on':
                True,
                'tools.auth_digest.realm':
                web_host,
                'tools.auth_digest.get_ha1':
                auth_digest.get_ha1_dict_plain(secrets),
                'tools.auth_digest.key':
                random.SystemRandom().randint(0, 99999999)
            }
        else:
            warn_msg = "\n********************************************************************\n"
            warn_msg += "Warning: passwd file contains no passwords. Authentication disabled.\n"
            warn_msg += "********************************************************************\n"
            log.warning(warn_msg)
    else:
        warn_msg = "\n********************************************************************\n"
        warn_msg += "Please consider adding authentication to protect this instance!\n"
        warn_msg += "Refer to https://www.spiderfoot.net/documentation/#security.\n"
        warn_msg += "********************************************************************\n"
        log.warning(warn_msg)

    if web_host == "0.0.0.0":  # nosec
        url = f"http://<IP of this host>:{web_port}{web_root}"
    else:
        url = f"http://{web_host}:{web_port}{web_root}"

    key_path = sf.dataPath() + '/spiderfoot.key'
    crt_path = sf.dataPath() + '/spiderfoot.crt'
    if os.path.isfile(key_path) and os.path.isfile(crt_path):
        if not os.access(crt_path, os.R_OK):
            log.critical(f"Could not read {crt_path} file. Permission denied.")
            sys.exit(-1)

        if not os.access(key_path, os.R_OK):
            log.critical(f"Could not read {key_path} file. Permission denied.")
            sys.exit(-1)

        log.info("Enabling SSL based on supplied key and certificate file.")
        cherrypy.server.ssl_module = 'builtin'
        cherrypy.server.ssl_certificate = crt_path
        cherrypy.server.ssl_private_key = key_path

        url = url.replace("http://", "https://")

    print("")
    print("*************************************************************")
    print(" Use SpiderFoot by starting your web browser of choice and ")
    print(f" browse to {url}")
    print("*************************************************************")
    print("")

    cherrypy.quickstart(SpiderFootWebUi(sfWebUiConfig, sfConfig),
                        script_name=web_root,
                        config=conf)
Пример #22
0
def start():
    """ Main function for starting HTTP server """
    logger = logging.getLogger("htpc.server")
    logger.debug("Setting up to start cherrypy")

    # Set server ip, port and root
    cherrypy.config.update({"server.socket_host": htpc.HOST, "server.socket_port": htpc.PORT, "log.screen": False})

    # Set server environment to production unless when debugging
    if not htpc.DEBUG:
        cherrypy.config.update({"environment": "production"})

    # Enable SSL
    if htpc.SSLCERT and htpc.SSLKEY:
        cherrypy.config.update(
            {
                "server.ssl_module": "builtin",
                "server.ssl_certificate": htpc.SSLCERT,
                "server.ssl_private_key": htpc.SSLKEY,
            }
        )

    # Daemonize cherrypy if specified
    if htpc.DAEMON:
        if sys.platform == "win32":
            logger.error(
                "You are using Windows - I cannot setup daemon mode. Please use the pythonw executable instead."
            )
            logger.error("More information at http://docs.python.org/2/using/windows.html.")
        else:
            Daemonizer(cherrypy.engine).subscribe()

    # Create PID if specified
    if htpc.PID:
        PIDFile(cherrypy.engine, htpc.PID).subscribe()

    # Set static directories
    webdir = os.path.join(htpc.RUNDIR, htpc.TEMPLATE)
    favicon = os.path.join(webdir, "img/favicon.ico")
    app_config = {
        "/": {
            "tools.staticdir.root": webdir,
            "tools.encode.on": True,
            "tools.encode.encoding": "utf-8",
            "tools.gzip.on": True,
        },
        "/js": {
            "tools.caching.on": True,
            "tools.caching.force": True,
            "tools.caching.delay": 0,
            "tools.expires.on": True,
            "tools.expires.secs": 60 * 60 * 6,
            "tools.staticdir.on": True,
            "tools.staticdir.dir": "js",
        },
        "/css": {
            "tools.caching.on": True,
            "tools.caching.force": True,
            "tools.caching.delay": 0,
            "tools.expires.on": True,
            "tools.expires.secs": 60 * 60 * 6,
            "tools.staticdir.on": True,
            "tools.staticdir.dir": "css",
        },
        "/img": {
            "tools.caching.on": True,
            "tools.caching.force": True,
            "tools.caching.delay": 0,
            "tools.expires.on": True,
            "tools.expires.secs": 60 * 60 * 6,
            "tools.staticdir.on": True,
            "tools.staticdir.dir": "img",
        },
        "/favicon.ico": {
            "tools.caching.on": True,
            "tools.caching.force": True,
            "tools.caching.delay": 0,
            "tools.expires.on": True,
            "tools.expires.secs": 60 * 60 * 6,
            "tools.staticfile.on": True,
            "tools.staticfile.filename": favicon,
        },
    }
    # Require username and password if they are set
    if htpc.USERNAME and htpc.PASSWORD:
        logger.info("Enabling username/password access")
        userpassdict = {htpc.USERNAME: htpc.PASSWORD}
        get_ha1 = get_ha1_dict_plain(userpassdict)
        app_config["/"].update(
            {
                "tools.auth_digest.on": True,
                "tools.auth_digest.realm": "HTPC Manager",
                "tools.auth_digest.get_ha1": get_ha1,
                "tools.auth_digest.key": "a565c27146791cfb",
            }
        )

    # Start the CherryPy server (remove trailing slash from webdir)
    logger.info("Starting up webserver")
    print "******************************************************"
    print "Starting HTPC Manager on port " + str(htpc.PORT) + "."
    print "Start your browser and go to http://localhost:" + str(htpc.PORT) + "/" + htpc.WEBDIR[:-1]
    print "******************************************************"
    cherrypy.quickstart(htpc.ROOT, htpc.WEBDIR[:-1], config=app_config)
Пример #23
0
    def __webServerThread(self):
        """ Sets up the web server. - configures paths and connects them to correct objects. """

        conf = {
            '/': {
                'tools.sessions.on':
                True,
                'tools.staticdir.root':
                os.path.abspath(os.path.join(os.getcwd(), "Web", "public")),
                'tools.__secureheaders.on':
                True,
                'tools.auth_digest.on':
                True,
                'tools.auth_digest.realm':
                'localhost',
                'tools.auth_digest.get_ha1':
                auth_digest.get_ha1_dict_plain(self.authUsers),
                'tools.auth_digest.key':
                self.__setupKey(),
            },
            '/static': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': './static',
            }
        }

        api_conf = {
            '/': {
                'tools.auth_digest.on':
                True,
                'tools.auth_digest.realm':
                'localhost',
                'tools.auth_digest.get_ha1':
                auth_digest.get_ha1_dict_plain(self.authUsers),
                'tools.auth_digest.key':
                self.__setupKey(),
                'tools.__secureheaders.on':
                True,
            },
            '/settings': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            },
            '/systemLog': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            },
            '/twitterFollow': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            },
            '/twitterModifyUser': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            },
            '/twitterPrintTweetWithId': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            },
            '/twitterSaveSettings': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            },
            '/note': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            },
            '/redditSaveSettings': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            },
            '/redditGetAuthorization': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            },
            '/redditGetRefreshToken': {
                'request.dispatch':
                cherrypy.dispatch.MethodDispatcher(),
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Content-Type', 'application/json')],
            }
        }

        api = Web.ServerMethods.APIMethods()
        api.settings = Web.ServerMethods.SettingsList()
        api.twitterFollow = Web.ServerMethods.FollowTwitterUser()
        api.twitterModifyUser = Web.ServerMethods.ModifyTwitterUser()
        api.twitterPrintTweetWithId = Web.ServerMethods.PrintTweetWithId()
        api.twitterSaveSettings = Web.ServerMethods.SaveTwitterSettings()
        api.systemLog = Web.ServerMethods.SystemLog()
        api.note = Web.ServerMethods.PrintNote()
        api.redditSaveSettings = Web.ServerMethods.SaveRedditSettings()
        api.redditGetAuthorization = Web.ServerMethods.GetRedditAuthorization()
        api.redditGetRefreshToken = Web.ServerMethods.GetRedditRefreshTokenWithCode(
        )

        cherrypy.tree.mount(Web.ServerMethods.ServerMethods(),
                            '/',
                            config=conf)
        cherrypy.tree.mount(api, '/api', config=api_conf)

        cherrypy.log.screen = None

        cherrypy.engine.start()
        cherrypy.engine.block()
Пример #24
0
 cherrypy.config.update("server.conf")
 static_path = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
 cherrypy.config.update({
     'tools.staticdir.dir': static_path,
     'tools.staticdir.on': True
 })
 cherrypy.tree.mount(RootServer(my_config), '/')
 cherrypy.tree.mount(
     DTSecuredServer(my_config), '/secured', {
         '/': {
             'tools.auth_digest.on': True,
             'tools.auth_digest.realm': 'localhost',
             'tools.auth_digest.key': 'a565c27146791cfb',
             'tools.auth_digest.accept_charset': 'UTF-8',
             'tools.auth_digest.get_ha1':
             auth_digest.get_ha1_dict_plain(USERS)
         }
     })
 cherrypy.tree.mount(
     APIServer(my_config), '/api', {
         '/': {
             'tools.auth_digest.on': True,
             'tools.auth_digest.realm': 'localhost',
             'tools.auth_digest.key': 'a565c27146791cfb',
             'tools.auth_digest.accept_charset': 'UTF-8',
             'tools.auth_digest.get_ha1':
             auth_digest.get_ha1_dict_plain(USERS)
         }
     })
 # root = RootServer(my_config)
 # root.secure = SecuredServer(my_config)
Пример #25
0
def start_web_server(sfWebUiConfig: dict,
                     sfConfig: dict,
                     loggingQueue=None) -> None:
    """Start the web server so you can start looking at results

    Args:
        sfWebUiConfig (dict): web server options
        sfConfig (dict): SpiderFoot config options
        loggingQueue (Queue): main SpiderFoot logging queue
    """
    log = logging.getLogger(f"spiderfoot.{__name__}")

    web_host = sfWebUiConfig.get('host', '127.0.0.1')
    web_port = sfWebUiConfig.get('port', 5001)
    web_root = sfWebUiConfig.get('root', '/')
    cors_origins = sfWebUiConfig.get('cors_origins', [])

    cherrypy.config.update({
        'log.screen': False,
        'server.socket_host': web_host,
        'server.socket_port': int(web_port)
    })

    log.info(f"Starting web server at {web_host}:{web_port} ...")

    sf = SpiderFoot(sfConfig)

    # Enable access to static files via the web directory
    conf = {
        '/query': {
            'tools.encode.text_only': False,
            'tools.encode.add_charset': True,
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'static',
            'tools.staticdir.root': f"{sf.myPath()}/spiderfoot"
        }
    }

    secrets = dict()
    passwd_file = SpiderFootHelpers.dataPath() + '/passwd'
    if os.path.isfile(passwd_file):
        if not os.access(passwd_file, os.R_OK):
            log.error("Could not read passwd file. Permission denied.")
            sys.exit(-1)

        with open(passwd_file, 'r') as f:
            passwd_data = f.readlines()

        for line in passwd_data:
            if line.strip() == '':
                continue

            if ':' not in line:
                log.error(
                    "Incorrect format of passwd file, must be username:password on each line."
                )
                sys.exit(-1)

            u = line.strip().split(":")[0]
            p = ':'.join(line.strip().split(":")[1:])

            if not u or not p:
                log.error(
                    "Incorrect format of passwd file, must be username:password on each line."
                )
                sys.exit(-1)

            secrets[u] = p

    if secrets:
        log.info("Enabling authentication based on supplied passwd file.")
        conf['/'] = {
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': web_host,
            'tools.auth_digest.get_ha1':
            auth_digest.get_ha1_dict_plain(secrets),
            'tools.auth_digest.key':
            random.SystemRandom().randint(0, 99999999)
        }
    else:
        warn_msg = "\n********************************************************************\n"
        warn_msg += "Warning: passwd file contains no passwords. Authentication disabled.\n"
        warn_msg += "Please consider adding authentication to protect this instance!\n"
        warn_msg += "Refer to https://www.spiderfoot.net/documentation/#security.\n"
        warn_msg += "********************************************************************\n"
        log.warning(warn_msg)

    using_ssl = False
    key_path = SpiderFootHelpers.dataPath() + '/spiderfoot.key'
    crt_path = SpiderFootHelpers.dataPath() + '/spiderfoot.crt'
    if os.path.isfile(key_path) and os.path.isfile(crt_path):
        if not os.access(crt_path, os.R_OK):
            log.critical(f"Could not read {crt_path} file. Permission denied.")
            sys.exit(-1)

        if not os.access(key_path, os.R_OK):
            log.critical(f"Could not read {key_path} file. Permission denied.")
            sys.exit(-1)

        log.info("Enabling SSL based on supplied key and certificate file.")
        cherrypy.server.ssl_module = 'builtin'
        cherrypy.server.ssl_certificate = crt_path
        cherrypy.server.ssl_private_key = key_path
        using_ssl = True

    if using_ssl:
        url = "https://"
    else:
        url = "http://"

    if web_host == "0.0.0.0":  # nosec
        url = f"{url}127.0.0.1:{web_port}"
    else:
        url = f"{url}{web_host}:{web_port}{web_root}"
        cors_origins.append(url)

    cherrypy_cors.install()
    cherrypy.config.update({
        'cors.expose.on': True,
        'cors.expose.origins': cors_origins,
        'cors.preflight.origins': cors_origins
    })

    print("")
    print("*************************************************************")
    print(" Use SpiderFoot by starting your web browser of choice and ")
    print(f" browse to {url}")
    print("*************************************************************")
    print("")

    # Disable auto-reloading of content
    cherrypy.engine.autoreload.unsubscribe()

    cherrypy.quickstart(SpiderFootWebUi(sfWebUiConfig, sfConfig, loggingQueue),
                        script_name=web_root,
                        config=conf)
Пример #26
0
		exec('res')
		if u not in USERS:  return "wrong username"
		elif USERS[u] != upwd : return "wrong password"
		elif npwd1 != npwd2 : return "type two different new password !"
		elif npwd1 == upwd : return "no change ! don't dou wo !!"
		else : 
			ss = '":"'.join([u,USERS[u]])
			USERS[u] = npwd1
			nss = '":"'.join([u,USERS[u]])
			(status, res) = commands.getstatusoutput("perl -p -i -e 's/%s/%s/g' ./demo520.py" %(ss,nss))
			if status == 0 : return "change password success!! remember you new password : [%s] <meta http-equiv='refresh' content='2;url=http://112.74.96.133:9999/index/1'>" %(USERS[u])

#(status, res) = commands.getstatusoutput("cat USER.py")
#exec(res)
USERS = {"antony":"supererror","amumu":"superbeauty.","dada":"chaojiwudishuai","cassie":"1234567","yannis":"henshuai123","trinity":"123123","devin":"1830057868","mimi":"mimi123456","lucy":"20150610","amber":"123456789.","tim":"lxg1578","bingbing":"bing1234","harry":"chaojiwudishuai","guard":"1234567","springwang":"1234567","simon":"1234567","kevin":"1234567","yummy":"1234567","wendy":"1234567","thomasli":"19920527","james":"1234567","kyrie":"1234567","vivianwang":"Vivian123","jeremylin":"1234567","lindazheng":"1234567","leon":"1234567","edwardhou":"1234567","benjaminpeng":"1234567","wade":"1234567","charles":"1234567","colin":"1234567","franck":"1234567"}

conf = {'/': {
		'tools.sessions.on' : True,
		'tools.auth_digest.on': True,
		'tools.auth_digest.realm': "don't be rude , ask antony to sign in ",
		'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(USERS),
		'tools.auth_digest.key': 'a565c27146791cfb'
        },
	'global':{
		'server.socket_host' : '112.74.96.133',
		'server.socket_port' : 9999,
}}	
cherrypy.config.update(conf)

cherrypy.quickstart(HelloWorld(),config=conf)
Пример #27
0
    def run(self):
        logging.info("Starting Web Server...")
        logging.info("Working Dir: "+self.currdir)
        
        users = {}
        with open(os.path.normpath(self.currdir+'/conf/users.conf'),'r') as f:
            for line in f:
                (user,password) = line.split(':')
                #logging.info("...Users...")
                #logging.info("User: "******" Password: "******"Starting HTTPS Server...")
            server1 = cherrypy._cpserver.Server()
            server1.socket_port=443
            server1._socket_host='0.0.0.0'
            server1.thread_pool=10
            server1.ssl_module = 'builtin'
            server1.ssl_certificate = os.path.normpath(self.currdir+'/certs/cert.cer')
            server1.ssl_private_key = os.path.normpath(self.currdir+'/certs/cert.key')
            #server1.ssl_certificate_chain = os.path.normpath(self.currdir+'/cert_bundle.crt')
            server1.subscribe()
        else:
            logging.info("HTTPS DISABLED -- No cert.cer or cert.key found")
    
        logging.info("Starting HTTP Server...")
        server2 = cherrypy._cpserver.Server()
        server2.socket_port=80
        server2._socket_host="0.0.0.0"
        server2.thread_pool=10
        server2.subscribe()

        cherrypy.log.screen = None
        
        #print os.path.normpath(currdir+'/access_log')
        cherrypy.log.access_file = os.path.normpath(self.currdir+'/logs/access_log')
        cherrypy.log.error_file = os.path.normpath(self.currdir+'/logs/error_log')
        
        cherrypy.log.access_log.propagate = False
        cherrypy.log.error_log.propagate = False
        
        cherrypy.engine.autoreload.on = False
        
        cherrypy.engine.start()
        cherrypy.engine.block()
        
        logging.info("Web Server Stopped.")
        return
Пример #28
0
import os
import sys
sys.path.append('./lib/cherrypy')
import cherrypy
from cherrypy.lib import auth_digest

g_auth_users = {'yant': '123456'}

app_conf = {
    '/': {
        'tools.staticdir.root': os.path.abspath('./'),
        'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
    },
    '/web/resources': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': 'resources',
    },
    '/web/upload': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': 'upload',
    },
    '/api': {
        'tools.auth_digest.on': True,
        'tools.auth_digest.realm': '192.168.0.105',
        'tools.auth_digest.get_ha1':
        auth_digest.get_ha1_dict_plain(g_auth_users),
        'tools.auth_digest.key': 'a565c27146791cfb'
    }
}
Пример #29
0
    injector_port = config['frontend'].getint('injector_port')

has_role_injector = 'injector' in config
if has_role_injector:
    injector_fifo = config['injector']['fifo']
    injector_logfile = config['injector']['logfile']

cherrypy.config.update({'server.socket_port': server_port})
cherrypy.config.update({'server.socket_host': server_host})

users = {username: password}
conf = {
    '/data': {
        'tools.auth_digest.on': True,
        'tools.auth_digest.realm': 'localhost',
        'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(users),
        'tools.auth_digest.key': 'iw4jURBej6oPraM3mISaH0xat',
    },
    '/inject': {
        'tools.auth_digest.on': True,
        'tools.auth_digest.realm': 'localhost',
        'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(users),
        'tools.auth_digest.key': 'iw4jURBej6oPraM3mISaH0xat',
    }
}


class Root(object):
    @cherrypy.expose
    def index(self):
        return "Data-over-DAB bridge"
Пример #30
0
def start_web_server(sfConfig):
    """Start the web server so you can start looking at results"""

    sf = SpiderFoot(sfConfig)

    web_host = sfConfig['__webaddr']
    web_port = sfConfig['__webport']

    log.info(f"Starting web server at {web_host}:{web_port} ...")

    cherrypy.config.update({
        'server.socket_host': web_host,
        'server.socket_port': web_port
    })

    # Disable auto-reloading of content
    cherrypy.engine.autoreload.unsubscribe()

    # Enable access to static files via the web directory
    conf = {
        '/query': {
            'tools.encode.text_only': False,
            'tools.encode.add_charset': True,
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'static',
            'tools.staticdir.root': sf.myPath()
        }
    }

    passwd_file = sf.dataPath() + '/passwd'
    if os.path.isfile(passwd_file):
        if not os.access(passwd_file, os.R_OK):
            log.error("Could not read passwd file. Permission denied.")
            sys.exit(-1)

        secrets = dict()

        pw = open(passwd_file, 'r')

        for line in pw.readlines():
            if ':' not in line:
                log.error("Incorrect format of passwd file, must be username:password on each line.")
                sys.exit(-1)

            u = line.strip().split(":")[0]
            p = ':'.join(line.strip().split(":")[1:])

            if not u or not p:
                log.error("Incorrect format of passwd file, must be username:password on each line.")
                sys.exit(-1)

            secrets[u] = p

        if secrets:
            log.info("Enabling authentication based on supplied passwd file.")
            conf['/'] = {
                'tools.auth_digest.on': True,
                'tools.auth_digest.realm': sfConfig['__webaddr'],
                'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(secrets),
                'tools.auth_digest.key': random.SystemRandom().randint(0, 99999999)
            }
        else:
            warn_msg = "\n********************************************************************\n"
            warn_msg += "Warning: passwd file contains no passwords. Authentication disabled.\n"
            warn_msg += "********************************************************************\n"
            log.warning(warn_msg)
    else:
        warn_msg = "\n********************************************************************\n"
        warn_msg += "Please consider adding authentication to protect this instance!\n"
        warn_msg += "Refer to https://www.spiderfoot.net/documentation/#security.\n"
        warn_msg += "********************************************************************\n"
        log.warning(warn_msg)

    key_path = sf.dataPath() + '/spiderfoot.key'
    crt_path = sf.dataPath() + '/spiderfoot.crt'
    if os.path.isfile(key_path) and os.path.isfile(crt_path):
        if not os.access(crt_path, os.R_OK):
            log.critical("Could not read spiderfoot.crt file. Permission denied.")
            sys.exit(-1)

        if not os.access(key_path, os.R_OK):
            log.critical("Could not read spiderfoot.key file. Permission denied.")
            sys.exit(-1)

        log.info("Enabling SSL based on supplied key and certificate file.")
        cherrypy.server.ssl_module = 'builtin'
        cherrypy.server.ssl_certificate = crt_path
        cherrypy.server.ssl_private_key = key_path

    # Try starting the web server. If it fails due to a database being
    # missing, start a smaller web server just for setting up the DB.
    cherrypy.quickstart(SpiderFootWebUi(sfConfig), script_name=sfConfig['__docroot'], config=conf)
Пример #31
0
if __name__ == "__main__":
    with open('credentials.secret', 'r') as fd:
        credentials = json.load(fd)
    config = {
        'global': {
            'server.socket_host': '0.0.0.0',
            'server.socket_port': 8080,
            'server.thread_pool': 8
        },
        '/': {
            'tools.auth_digest.on':
            True,
            'tools.auth_digest.realm':
            'Bradut',
            'tools.auth_digest.get_ha1':
            auth_digest.get_ha1_dict_plain(credentials),
            'tools.auth_digest.key':
            'randomsecret',
            'tools.auth_digest.accept_charset':
            'UTF-8'
        },
    }
    try:
        ctrl = Controller()
        ctrl.start()
        cherrypy.quickstart(Site(), '/', config)
    except KeyboardInterrupt:
        print('Received Keyboard Interrupt')
        comm_sem.acquire()
        comm['shutdown'] = True
        comm_sem.release()
Пример #32
0
        raise SystemExit(err)

    cam = CameraMQTT(IP_broker, PORT_broker, Handler, IP_Catalog, PORT_Catalog,
                     key)
    cam.start()
    cam.Subscribe('MotionDetect')

    userpassdict = {'TakeASmile': key}

    conf = {
        '/': {
            'tools.auth_digest.on':
            True,
            'tools.auth_digest.realm':
            'localhost',
            'tools.auth_digest.get_ha1':
            auth_digest.get_ha1_dict_plain(userpassdict),
            'tools.auth_digest.key':
            'a565c27146791cfb',
            'request.dispatch':
            cherrypy.dispatch.MethodDispatcher(),
            'tool.session.on':
            True
        }
    }
    cherrypy.tree.mount(CameraREST(cam), '/', conf)
    cherrypy.config.update({'server.socket_host': '0.0.0.0'})
    cherrypy.config.update({'server.socket_port': my_port})
    cherrypy.engine.start()
    cherrypy.engine.block()
Пример #33
0
         
    fp = open("configCatalog.json", 'r')
    config = json.loads(fp.read())
    fp.close()
    
    key = config["DigestKey"]
    my_ip = config["IP_catalog"]
    my_port = config["PORT_catalog"]
    
    userpassdict = {'TakeASmile':key}
          
    conf={
        '/':{
                  
                
                'tools.auth_digest.on': True,
                'tools.auth_digest.realm': 'localhost',
                'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(userpassdict),
                'tools.auth_digest.key': 'a565c27146791cfb',
              
                'request.dispatch':cherrypy.dispatch.MethodDispatcher(),
                'tool.session.on':True
         }
    }     
                
    cherrypy.tree.mount(REST_Catalog(),'/',conf)    
    cherrypy.config.update({'server.socket_host': my_ip})
    cherrypy.config.update({'server.socket_port': my_port})
    cherrypy.engine.start()
    cherrypy.engine.block()
Пример #34
0
def start():
    """ Main function for starting HTTP server """
    logger = logging.getLogger('htpc.server')
    logger.debug("Setting up to start cherrypy")

    # Set server ip, port and root
    cherrypy.config.update({
        'server.socket_host': htpc.HOST,
        'server.socket_port': htpc.PORT,
        'log.screen': False
    })

    # Set server environment to production unless when debugging
    if not htpc.DEBUG:
        cherrypy.config.update({
            'environment': 'production'
        })

    # Enable SSL
    if htpc.SSLCERT and htpc.SSLKEY:
        cherrypy.config.update({
            'server.ssl_module': 'builtin',
            'server.ssl_certificate': htpc.SSLCERT,
            'server.ssl_private_key': htpc.SSLKEY
        })

    # Daemonize cherrypy if specified
    if htpc.DAEMON:
        if sys.platform == 'win32':
            logger.error("You are using Windows - I cannot setup daemon mode. Please use the pythonw executable instead.")
            logger.error("More information at http://docs.python.org/2/using/windows.html.")
        else:
            Daemonizer(cherrypy.engine).subscribe()

    # Create PID if specified
    if htpc.PID:
        PIDFile(cherrypy.engine, htpc.PID).subscribe()

    # Set static directories
    webdir = os.path.join(htpc.RUNDIR, htpc.TEMPLATE)
    favicon = os.path.join(webdir, "img/favicon.ico")
    app_config = {
        '/': {
            'tools.staticdir.root': webdir,
            'tools.encode.on': True,
            'tools.encode.encoding': 'utf-8',
            'tools.gzip.on': True
        },
        '/js': {
            'tools.caching.on': True,
            'tools.caching.force': True,
            'tools.caching.delay': 0,
            'tools.expires.on': True,
            'tools.expires.secs': 60 * 60 * 6,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'js'
        },
        '/css': {
            'tools.caching.on': True,
            'tools.caching.force': True,
            'tools.caching.delay': 0,
            'tools.expires.on': True,
            'tools.expires.secs': 60 * 60 * 6,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'css'
        },
        '/img': {
            'tools.caching.on': True,
            'tools.caching.force': True,
            'tools.caching.delay': 0,
            'tools.expires.on': True,
            'tools.expires.secs': 60 * 60 * 6,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'img'
        },
        '/favicon.ico': {
            'tools.caching.on': True,
            'tools.caching.force': True,
            'tools.caching.delay': 0,
            'tools.expires.on': True,
            'tools.expires.secs': 60 * 60 * 6,
            'tools.staticfile.on': True,
            'tools.staticfile.filename': favicon
        },
    }
    # Require username and password if they are set
    if htpc.USERNAME and htpc.PASSWORD:
        logger.info("Enabling username/password access")
        userpassdict = {htpc.USERNAME: htpc.PASSWORD}
        get_ha1 = get_ha1_dict_plain(userpassdict)
        app_config['/'].update({
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': "HTPC Manager",
            'tools.auth_digest.get_ha1': get_ha1,
            'tools.auth_digest.key': 'a565c27146791cfb'
        })

    # Start the CherryPy server (remove trailing slash from webdir)
    logger.info("Starting up webserver")
    print '******************************************************'
    print 'Starting HTPC Manager on port ' + str(htpc.PORT) + '.'
    print 'Start your browser and go to http://localhost:' + str(htpc.PORT)
    print '******************************************************'
    cherrypy.quickstart(htpc.ROOT, htpc.WEBDIR[:-1], config=app_config)