Exemplo n.º 1
0
 def _drop_privileges(self):
     """ Drop privileges with
     :class:`cherrypy.process.plugins.DropPrivileges` """
     DropPrivileges(cherrypy.engine,
                    uid=Bcfg2.Options.setup.daemon_uid,
                    gid=Bcfg2.Options.setup.daemon_gid,
                    umask=int(Bcfg2.Options.setup.umask, 8)).subscribe()
Exemplo n.º 2
0
 def _daemonize(self):
     """ Drop privileges with
     :class:`cherrypy.process.plugins.DropPrivileges`, daemonize
     with :class:`cherrypy.process.plugins.Daemonizer`, and write a
     PID file with :class:`cherrypy.process.plugins.PIDFile`. """
     DropPrivileges(cherrypy.engine,
                    uid=self.setup['daemon_uid'],
                    gid=self.setup['daemon_gid'],
                    umask=int(self.setup['umask'], 8)).subscribe()
     Daemonizer(cherrypy.engine).subscribe()
     PIDFile(cherrypy.engine, self.setup['daemon']).subscribe()
     return True
Exemplo n.º 3
0
 def _daemonize(self):
     """ Drop privileges with
     :class:`cherrypy.process.plugins.DropPrivileges`, daemonize
     with :class:`cherrypy.process.plugins.Daemonizer`, and write a
     PID file with :class:`cherrypy.process.plugins.PIDFile`. """
     DropPrivileges(cherrypy.engine,
                    uid=Bcfg2.Options.setup.daemon_uid,
                    gid=Bcfg2.Options.setup.daemon_gid,
                    umask=int(Bcfg2.Options.setup.umask, 8)).subscribe()
     Daemonizer(cherrypy.engine).subscribe()
     PIDFile(cherrypy.engine, Bcfg2.Options.setup.daemon).subscribe()
     return True
Exemplo n.º 4
0
def daemonize(user, group, pidfile=None):
    if os.name == 'posix' and os.getuid() == 0:
        from cherrypy.process.plugins import DropPrivileges
        import grp
        import pwd
        try:
            uid = pwd.getpwnam(user)[2]
            gid = grp.getgrnam(group)[2]
        except KeyError:
            cherrypy.log.error(
                'Cannot find user `{0}` or group `{1}`'.format(user, group),
                'DAEMONIZE',
                logging.FATAL
            )
            raise
        cherrypy.drop_privileges = DropPrivileges(
            cherrypy.engine, uid=uid, gid=gid).subscribe()

    from cherrypy.process.plugins import PIDFile, Daemonizer
    if pidfile:
        PIDFile(cherrypy.engine, pidfile).subscribe()
    Daemonizer(cherrypy.engine).subscribe()
Exemplo n.º 5
0
def configure(cfgfile):
    with open_text(*_CONFIG_SPEC) as fh:
        cfg = salmagundi.config.configure(cfgfile,
                                          fh,
                                          create_properties=False,
                                          converters=_CONVERTERS)
    _logging(cfg)
    _storage_path(cfg)
    _index_url(cfg)
    _project_url(cfg)
    _ssl(cfg)
    host, port = cfg['server', 'host']
    cherrypy.config.update({
        'response.headers.Server': f'{PROG_NAME}/{__version__}',
        'server.socket_host': host,
        'server.socket_port': port,
        'engine.autoreload.on': False,
        'request.show_tracebacks': PYPP_DEBUG,
        'request.show_mismatched_params': PYPP_DEBUG,
    })
    if PYPP_DEBUG:
        cherrypy.engine.signal_handler.handlers['SIGUSR2'] =\
            lambda: cherrypy.engine.restart()
    if cfg['server', 'daemonize']:
        Daemonizer(cherrypy.engine).subscribe()
        cherrypy.engine.signal_handler.handlers['SIGUSR1'] = None
    if os.getuid() == 0:
        uid, gid = _user_group(cfg)
        if uid:
            DropPrivileges(cherrypy.engine, uid=uid, gid=gid).subscribe()
        else:
            cherrypy.log("running as 'root'", 'WARNING')
    if cfg['server', 'pidfile']:
        PIDFile(cherrypy.engine, cfg['server', 'pidfile']).subscribe()
    rv = {opt: cfg['pypackproxy', opt] for opt in cfg.options('pypackproxy')}
    rv['proxies'] = _proxies(cfg)
    rv['user-agent'] = f'{PROG_NAME}/{__version__}'
    return rv
Exemplo n.º 6
0
    def daemonize(self):
        if not _daemon_conf.on:
            return

        if os.name == 'posix' and os.getuid() == 0:
            from cherrypy.process.plugins import DropPrivileges
            import grp, pwd
            try:
                uid = pwd.getpwnam(_daemon_conf.user)[2]
                gid = grp.getgrnam(_daemon_conf.group)[2]
            except KeyError:
                cherrypy.log.error(
                    'Cannot find user "{0}" or group "{1}"'.format(
                        _daemon_conf.user, _daemon_conf.group), 'SERVER',
                    logging.FATAL)
                raise
            cherrypy.drop_privileges = DropPrivileges(cherrypy.engine,
                                                      uid=uid,
                                                      gid=gid).subscribe()

        from cherrypy.process.plugins import PIDFile, Daemonizer
        if _daemon_conf.pid_file:
            PIDFile(cherrypy.engine, _daemon_conf.pid_file).subscribe()
        Daemonizer(cherrypy.engine).subscribe()
Exemplo n.º 7
0
                  help="Temporary directory",
                  type="str")
parser.add_option("-d",
                  "--daemon",
                  dest="daemon",
                  help="Daemonise? any value, false by default",
                  type="str")
(options, args) = parser.parse_args()
if options.port:
    port = options.port
if options.host:
    host = options.host

if daemon:
    from cherrypy.process.plugins import Daemonizer, DropPrivileges, PIDFile
    DropPrivileges(cherrypy.engine, uid=1000, gid=1000).subscribe()
    Daemonizer(cherrypy.engine).subscribe()


class Site(object):
    exposed = True

    def GET(self):
        return open(os.path.join(insiderer_dir, 'static/index.html'),
                    'r').read()

    @cherrypy.tools.json_out()
    def POST(self, **kwargs):
        metadata_files = []
        for key, postfiles in kwargs.items():
            if not isinstance(postfiles, list):
Exemplo n.º 8
0
        format=
        '%(asctime)s : %(levelname)s : %(module)s:%(lineno)d : %(funcName)s(%(threadName)s) : %(message)s',
        level=logging.DEBUG)
    logger.info("running %s", ' '.join(sys.argv))

    program = os.path.basename(sys.argv[0])

    # check and process input arguments
    if len(sys.argv) < 2:
        print globals()['__doc__'] % locals()
        sys.exit(1)

    conf_file = sys.argv[1]
    config_srv = Config(
        **cherrypy.lib.reprconf.Config(conf_file).get('global'))
    config = Config(
        **cherrypy.lib.reprconf.Config(conf_file).get('w2v_server'))

    if config_srv.pid_file:
        PIDFile(cherrypy.engine, config_srv.pid_file).subscribe()
    if config_srv.run_user and config_srv.run_group:
        logging.info("dropping priviledges to %s:%s" %
                     (config_srv.run_user, config_srv.run_group))
        DropPrivileges(cherrypy.engine,
                       gid=config_srv.run_group,
                       uid=config_srv.run_user).subscribe()

    cherrypy.quickstart(Server(config.MODEL_FILE), config=conf_file)

    logger.info("finished running %s", program)
Exemplo n.º 9
0
            cherrypy.server.ssl_certificate_chain = Options().ssl_certificate_chain

    if Options().daemon:
        # Daemon info is logged by CherryPy
        daemon = Daemonizer(cherrypy.engine)
        daemon.subscribe()
    else:
        logger.info('Not running as daemon.')

    # PID is logged by CherryPy
    pid = PIDFile(cherrypy.engine, os.path.join(Options().run_dir, 'cherryblog.pid'))
    pid.subscribe()

    if Options().privileges:
        # Privileges are logged by CherryPy
        privileges = DropPrivileges(cherrypy.engine, uid=Options().uid, gid=Options().gid)
        privileges.subscribe()
    else:
        logger.info('No user privileges specified.')

    cherrypy.quickstart(Application(), config=settings)

###
#
#   Version: 2.2.1
#   Date: 2020-04-25
#   Author: Yves Vindevogel (vindevoy)
#
#   Fixes:
#       - Urgent bug on the type of SSL to use
#
Exemplo n.º 10
0
def serve(**kwargs):
    """
    Spawn a new running Cherrypy process

    usage: blubeberry serve [options]

    options:
      -h, --help                                 show this help message and exit
      -b BINDING, --bind BINDING                 the address and port to bind to.
                                                 [default: 127.0.0.1:8080]
      -e ENVIRONMENT, --environment ENVIRONMENT  apply the given config environment
      -C ENV_VAR_NAME, --env-var ENV_VAR_NAME    add the given config from environment variable name
                                                 [default: BLUEBERRYPY_CONFIG]
      -f                                         start a fastcgi server instead of the default HTTP
                                                 server
      -s                                         start a scgi server instead of the default HTTP
                                                 server
      -d, --daemonize                            run the server as a daemon. [default: False]
      -p, --drop-privilege                       drop privilege to separately specified umask, uid
                                                 and gid. [default: False]
      -P PIDFILE, --pidfile PIDFILE              store the process id in the given file
      -u UID, --uid UID                          setuid to uid [default: www]
      -g GID, --gid GID                          setgid to gid [default: www]
      -m UMASK, --umask UMASK                    set umask [default: 022]

    """

    config = BlueberryPyConfiguration(config_dir=kwargs.get('config_dir'),
                                      env_var_name=kwargs.get('env_var'))

    cpengine = cherrypy.engine

    cpenviron = kwargs.get("environment")
    if cpenviron:
        config = BlueberryPyConfiguration(config_dir=kwargs.get('config_dir'),
                                          env_var_name=kwargs.get('env_var'),
                                          environment=cpenviron)
        cherrypy.config.update({"environment": cpenviron})

    if config.use_email and config.email_config:
        from blueberrypy import email
        email.configure(config.email_config)

    if config.use_logging and config.logging_config:
        from blueberrypy.plugins import LoggingPlugin
        cpengine.logging = LoggingPlugin(cpengine, config=config.logging_config)

    if config.use_redis:
        from blueberrypy.session import RedisSession
        cherrypy.lib.sessions.RedisSession = RedisSession

    if config.use_sqlalchemy:
        from blueberrypy.plugins import SQLAlchemyPlugin
        cpengine.sqlalchemy = SQLAlchemyPlugin(cpengine,
                                               config=config.sqlalchemy_config)
        from blueberrypy.tools import SQLAlchemySessionTool
        cherrypy.tools.orm_session = SQLAlchemySessionTool()

    if config.use_jinja2:
        if config.webassets_env:
            configure_jinja2(assets_env=config.webassets_env,
                             **config.jinja2_config)
        else:
            configure_jinja2(**config.jinja2_config)

    # update global config first, so subsequent command line options can
    # override the settings in the config files
    cherrypy.config.update(config.app_config)

    if kwargs.get("bind"):
        address, port = kwargs.get("bind").strip().split(":")
        cherrypy.server.socket_host = address
        cherrypy.server.socket_port = int(port)

    if kwargs.get("daemonize"):
        cherrypy.config.update({'log.screen': False})
        Daemonizer(cpengine).subscribe()

    if kwargs.get("drop_privilege"):
        cherrypy.config.update({'engine.autoreload_on': False})
        DropPrivileges(cpengine, umask=int(kwargs.get("umask")),
                       uid=kwargs.get("uid") or "www",
                       gid=kwargs.get("gid") or "www").subscribe()

    if kwargs.get("pidfile"):
        PIDFile(cpengine, kwargs.get("pidfile")).subscribe()

    fastcgi, scgi = kwargs.get("fastcgi"), kwargs.get("scgi")
    if fastcgi and scgi:
        cherrypy.log.error("You may only specify one of the fastcgi and "
                           "scgi options.", 'ENGINE')
        sys.exit(1)
    elif fastcgi or scgi:
        # Turn off autoreload when using *cgi.
        cherrypy.config.update({'engine.autoreload_on': False})
        # Turn off the default HTTP server (which is subscribed by default).
        cherrypy.server.unsubscribe()

        addr = cherrypy.server.bind_addr
        if fastcgi:
            f = servers.FlupFCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        elif scgi:
            f = servers.FlupSCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        s = servers.ServerPlugin(cpengine, httpserver=f, bind_addr=addr)
        s.subscribe()

    if hasattr(cpengine, 'signal_handler'):
        cpengine.signal_handler.subscribe()

    # for win32 only
    if hasattr(cpengine, "console_control_handler"):
        cpengine.console_control_handler.subscribe()

    # mount the controllers
    for script_name, section in config.controllers_config.viewitems():
        section = section.copy()
        controller = section.pop("controller")
        if isinstance(controller, cherrypy.dispatch.RoutesDispatcher):
            routes_config = {'/': {"request.dispatch": controller}}
            for path in section.viewkeys():
                if path.strip() == '/':
                    routes_config['/'].update(section['/'])
                else:
                    routes_config[path] = section[path].copy()
            app_config = config.app_config.copy()
            app_config.pop("controllers")
            routes_config.update(app_config)
            cherrypy.tree.mount(None, script_name=script_name,
                                config=routes_config)
        else:
            app_config = config.app_config.copy()
            app_config.pop("controllers")
            controller_config = section.copy()
            controller_config.update(app_config)
            cherrypy.tree.mount(controller(), script_name=script_name,
                                config=controller_config)

    # Add the blueberrypy config files into CP's autoreload monitor
    # Jinja2 templates are monitored by Jinja2 itself and will autoreload if
    # needed
    if config.config_file_paths:
        for path in config.config_file_paths:
            cpengine.autoreload.files.add(path)

    try:
        cpengine.start()
    except:
        sys.exit(1)
    else:
        cpengine.block()
Exemplo n.º 11
0
            
        return data

    
if __name__ == '__main__':
    # Register the SQLAlchemy plugin
    
    # Load configuration
#    from Config.Config import connectUrl, cpconfig, base_url
    from Config.Config import *
    
    from sqlalchemy_plugin.saplugin import SAEnginePlugin
    from cherrypy.process.plugins import DropPrivileges
    
#    dr = DropPrivileges(cherrypy.engine, uid=1000, gid=1000)
    dr = DropPrivileges(cherrypy.engine)
    dr.subscribe()
    
    from cherrypy.process.plugins import Daemonizer
    d = Daemonizer(cherrypy.engine)
    d.subscribe()
    
    connectionString = ConnectionString()
    
#    dr = DropPrivileges(cherrypy.engine, uid=1000, gid=1000)
#    dr.subscribe()
    
#    SAEnginePlugin(cherrypy.engine, connectUrl).subscribe()
    SAEnginePlugin(cherrypy.engine, connectionString).subscribe()
    
    # Register the SQLAlchemy tool
Exemplo n.º 12
0
    def run(self) -> None:
        """ Starts the application """
        #### Command Line Argument Parsing
        parser = argparse.ArgumentParser(description='ARPOC')
        parser.add_argument('-c', '--config-file')
        parser.add_argument('--print-sample-config', action='store_true')
        parser.add_argument('--print-sample-ac', action='store_true')
        parser.add_argument('--add-provider')
        parser.add_argument('--client-id')
        parser.add_argument('--client-secret')
        parser.add_argument('-d', '--daemonize', action='store_true')
        parser.add_argument('--check-ac', action='store_true')

        args = parser.parse_args()

        config.cfg = config.OIDCProxyConfig(config_file=args.config_file)
        self.config = config.cfg

        assert self.config.proxy is not None

        #### Read Configuration
        if args.print_sample_config:
            config.cfg.print_sample_config()
            return

        if args.print_sample_ac:
            arpoc.ac.print_sample_ac()
            return
        self.setup_loggers()

        #### Create secrets dir and change ownership (perm)
        self.create_secrets_dir()

        self.oidc_handler = OidcHandler(self.config)

        if args.add_provider and args.client_id and args.client_secret:
            # read secrets
            secrets = self.read_secrets(self.config.proxy['secrets'])

            provider_cfg = self.config.openid_providers[args.add_provider]
            redirect_uris = provider_cfg.redirect_uris or self.config.proxy[
                'redirect_uris']

            # add secrets
            secret_dict = {
                "client_id": args.client_id,
                "client_secret": args.client_secret,
                "redirect_uris": args.redirect_uris
            }
            secrets[args.add_provider] = secret_dict
            self.oidc_handler._secrets = secrets
            self.oidc_handler.create_client_from_secrets(
                args.add_provider, provider_cfg)
            self.save_secrets()
            return

        #### Read AC Rules
        for acl_dir in self.config.access_control['json_dir']:
            ServiceProxy.ac.load_dir(acl_dir)

        if args.check_ac:
            ServiceProxy.ac.check()
            return

        if args.daemonize:
            daemonizer = Daemonizer(cherrypy.engine)
            daemonizer.subscribe()
            # check if pid file exists
            try:
                with open(self.config.misc.pid_file) as pidfile:
                    pid = int(pidfile.read().strip())
                    try:
                        os.kill(pid, 0)  # check if running
                    except OSError:
                        PIDFile(cherrypy.engine,
                                self.config.misc.pid_file).subscribe()
                        # not running
                    else:
                        # running
                        print("PID File %s exists" % self.config.misc.pid_file)
                        print("Another instance of arpoc seems to be running")
                        return
            except FileNotFoundError:
                PIDFile(cherrypy.engine, self.config.misc.pid_file).subscribe()

        #### Setup OIDC Provider
        cherrypy.engine.subscribe('start', self.setup_oidc_provider, 80)
        cherrypy.engine.subscribe('stop', self.cancel_scheduler, 80)
        cherrypy.engine.subscribe('stop', self.save_secrets, 80)
        #### Setup Cherrypy
        global_conf = {
            'log.screen': False,
            'log.access_file': '',
            'log.error_file': '',
            'server.socket_host': config.cfg.proxy['address'],
            'server.socket_port': config.cfg.proxy['tls_port'],
            'server.ssl_private_key': config.cfg.proxy['keyfile'],
            'server.ssl_certificate': config.cfg.proxy['certfile'],
            'engine.autoreload.on': False
        }
        cherrypy.config.update(global_conf)
        app_conf = {
            '/': {
                'tools.sessions.on': True,
                'request.dispatch': self.get_routes_dispatcher()
            }
        }
        DropPrivileges(cherrypy.engine, uid=self.uid, gid=self.gid).subscribe()

        #### Start Web Server
        cherrypy.tree.mount(None, '/', app_conf)
        if self.config.proxy['plain_port']:
            server2 = cherrypy._cpserver.Server()
            server2.socket_port = self.config.proxy['plain_port']
            server2._socket_host = self.config.proxy['address']
            server2.thread_pool = 30
            server2.subscribe()

        cherrypy.engine.start()
        cherrypy.engine.block()
Exemplo n.º 13
0
 def _daemonize(self):
     DropPrivileges(cherrypy.engine,
                    uid=self.setup['daemon_uid'],
                    gid=self.setup['daemon_gid']).subscribe()
     Daemonizer(cherrypy.engine).subscribe()
     PIDFile(cherrypy.engine, self.setup['daemon']).subscribe()