コード例 #1
0
ファイル: resolver.py プロジェクト: rb12345/LinOTP
def setupResolvers(config=None, cache_dir="/tmp"):
    """
    hook at the server start to initialize the resolvers classes

    :param config: the linotp config
    :param cache_dir: the cache directory, which could be used in each resolver

    :return: -nothing-
    """

    glo = getGlobalObject()
    resolver_classes = copy.deepcopy(glo.getResolverClasses())

    # resolver classes is a dict with aliases as key and the resolver classes
    # as values - as we require only unique classes we put them in a set.
    # On server startup  we call the setup once for each resolver class.

    for resolver_cls in set(resolver_classes.values()):
        if hasattr(resolver_cls, 'setup'):
            try:
                resolver_cls.setup(config=config, cache_dir=cache_dir)
            except Exception as exx:
                log.exception("failed to call setup of %r; %r", resolver_cls,
                              exx)

    return
コード例 #2
0
ファイル: resolver.py プロジェクト: eespinosa/Elm
def setupResolvers(config=None, cache_dir="/tmp"):
    """
    hook for the server start -
        initialize the resolvers
    """
    glo = getGlobalObject()

    resolver_clazzes = copy.deepcopy(glo.getResolverClasses())
    for resolver_clazz in resolver_clazzes.values():
        if hasattr(resolver_clazz, 'setup'):
            try:
                resolver_clazz.setup(config=config, cache_dir=cache_dir)
            except Exception as exx:
                log.error("failed to call setup of %r" % resolver_clazz)

    return
コード例 #3
0
def setupResolvers(config=None, cache_dir="/tmp"):
    """
    hook for the server start -
        initialize the resolvers
    """
    glo = getGlobalObject()

    resolver_clazzes = copy.deepcopy(glo.getResolverClasses())
    for resolver_clazz in resolver_clazzes.values():
        if hasattr(resolver_clazz, 'setup'):
            try:
                resolver_clazz.setup(config=config, cache_dir=cache_dir)
            except Exception as exx:
                log.error("failed to call setup of %r" % resolver_clazz)

    return
コード例 #4
0
ファイル: resolver.py プロジェクト: chocolim/LinOTP
def initResolvers():
    """
    hook for the request start -
        create  a deep copy of the dict with the global resolver classes
    """
    try:
        glo = getGlobalObject()

        resolver_clazzes = copy.deepcopy(glo.getResolverClasses())
        resolver_types = copy.deepcopy(glo.getResolverTypes())

        context['resolver_clazzes'] = resolver_clazzes
        context['resolver_types'] = resolver_types
        # dict of all resolvers, which are instatiated during the request
        context['resolvers_loaded'] = {}

    except Exception as exx:
        log.exception("Failed to initialize resolver in context %r" % exx)
    return
コード例 #5
0
ファイル: resolver.py プロジェクト: rb12345/LinOTP
def initResolvers():
    """
    hook for the request start -
        create  a deep copy of the dict with the global resolver classes
    """
    try:
        glo = getGlobalObject()

        resolver_classes = copy.deepcopy(glo.getResolverClasses())
        resolver_types = copy.deepcopy(glo.getResolverTypes())

        context['resolver_classes'] = resolver_classes
        context['resolver_types'] = resolver_types
        # dict of all resolvers, which are instatiated during the request
        context['resolvers_loaded'] = {}

    except Exception as exx:
        log.exception("Failed to initialize resolver in context %r" % exx)
    return
コード例 #6
0
def initResolvers():
    """
    hook for the request start -
        create  a deep copy of the dict with the global resolver classes
    """
    try:
        glo = getGlobalObject()

        resolver_clazzes = copy.deepcopy(glo.getResolverClasses())
        setattr(context, 'resolver_clazzes', resolver_clazzes)

        resolver_types = copy.deepcopy(glo.getResolverTypes())
        setattr(context, 'resolver_types', resolver_types)

        ## dict of all resolvers, which are instatiated during the request
        setattr(context, 'resolvers_loaded', {})

    except Exception as exx:
        log.error("Failed to initialize resolver in context %r" % exx)
    return
コード例 #7
0
ファイル: resolver.py プロジェクト: eespinosa/Elm
def get_resolver_class(resolver_type):
    '''
    return the class object for a resolver type
    :param resolver_type: string specifying the resolver
                          fully qualified or abreviated
    :return: resolver object class
    '''
    ret = None

    # ## this patch is a bit hacky:
    # the normal request has a request context, where it retrieves
    # the resolver info from and preserves the loaded resolvers for reusage
    # But in case of a authentication request (by a redirect from a 401)
    # the caller is no std request and the context object is missing :-(
    # The solution is, to deal with local references, either to the
    # global context or to local data

    try:
        resolver_clazzes = context.resolver_clazzes
        resolver_types = context.resolver_types
    except Exception as exx:
        glo = getGlobalObject()
        resolver_clazzes = copy.deepcopy(glo.getResolverClasses())
        resolver_types = copy.deepcopy(glo.getResolverTypes())

    parts = resolver_type.split('.')
    # resolver is fully qualified
    if len(parts) > 1:
        if resolver_type in resolver_clazzes:
            ret = resolver_clazzes.get(resolver_type)

    # resolver is in abreviated form, we have to do a reverse lookup
    elif resolver_type in resolver_types.values():
        for k, v in resolver_types.iteritems():
            if v == resolver_type:
                ret = resolver_clazzes.get(k, None)
                break
    if ret is None:
        pass
    return ret
コード例 #8
0
def get_resolver_class(resolver_type):
    '''
    return the class object for a resolver type
    :param resolver_type: string specifying the resolver
                          fully qualified or abreviated
    :return: resolver object class
    '''
    ret = None

    ### this patch is a bit hacky:
    ## the normal request has a request context, where it retrieves
    ## the resolver info from and preserves the loaded resolvers for reusage
    ## But in case of a authentication request (by a redirect from a 401)
    ## the caller is no std request and the context object is missing :-(
    ## The solution is, to deal with local references, either to the
    ## global context or to local data

    try:
        resolver_clazzes = context.resolver_clazzes
        resolver_types = context.resolver_types
    except Exception as exx:
        glo = getGlobalObject()
        resolver_clazzes = copy.deepcopy(glo.getResolverClasses())
        resolver_types = copy.deepcopy(glo.getResolverTypes())

    parts = resolver_type.split('.')
    ## resolver is fully qualified
    if len(parts) > 1:
        if resolver_type in resolver_clazzes:
            ret = resolver_clazzes.get(resolver_type)

    ## resolver is in abreviated form, we have to do a reverse lookup
    elif resolver_type in resolver_types.values():
        for k, v in resolver_types.iteritems():
            if v == resolver_type:
                ret = resolver_clazzes.get(k, None)
                break
    if ret is None:
        pass
    return ret
コード例 #9
0
    def __call__(self, environ, start_response):
        '''Invoke the Controller'''
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        path = ""
        glo = getGlobalObject()
        sep = glo.security_provider

        try:
            hsm = sep.getSecurityModule()
            c.hsm = hsm

            if environ:
                path = environ.get("PATH_INFO", "") or ""

            log.debug("request %r" % path)
            ret = WSGIController.__call__(self, environ, start_response)
            log.debug("reply %r" % ret)

        finally:
            meta.Session.remove()
            ## free the lock on the scurityPovider if any
            sep.dropSecurityModule()
            closeResolvers()

            ## hint for the garbage collector to make the dishes
            data_objects = [
                "resolvers_loaded", "resolver_types", "resolver_clazzes",
                "linotpConfig", "audit", "hsm"
            ]
            for data_obj in data_objects:
                if hasattr(c, data_obj):
                    data = getattr(c, data_obj)
                    del data

            log.debug("request %r done!" % path)

        return ret
コード例 #10
0
ファイル: resolver.py プロジェクト: rb12345/LinOTP
def get_resolver_class(cls_identifier):
    '''
    return the class object for a resolver type
    :param resolver_type: string specifying the resolver
                          fully qualified or abreviated
    :return: resolver object class
    '''

    # ## this patch is a bit hacky:
    # the normal request has a request context, where it retrieves
    # the resolver info from and preserves the loaded resolvers for reusage
    # But in case of a authentication request (by a redirect from a 401)
    # the caller is no std request and the context object is missing :-(
    # The solution is, to deal with local references, either to the
    # global context or to local data

    resolver_classes = context.get('resolver_classes')
    if resolver_classes is None:
        glo = getGlobalObject()
        resolver_classes = copy.deepcopy(glo.getResolverClasses())

    return resolver_classes.get(cls_identifier)
コード例 #11
0
ファイル: base.py プロジェクト: richarddlmay/LinOTP
    def __call__(self, environ, start_response):
        '''Invoke the Controller'''
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        path = ""
        glo = getGlobalObject()
        sep = glo.security_provider

        try:
            hsm = sep.getSecurityModule()
            c.hsm = hsm

            if environ:
                path = environ.get("PATH_INFO", "") or ""

            log.debug("request %r" % path)
            ret = WSGIController.__call__(self, environ, start_response)
            log.debug("reply %r" % ret)

        finally:
            meta.Session.remove()
            ## free the lock on the scurityPovider if any
            sep.dropSecurityModule()
            closeResolvers()


            ## hint for the garbage collector to make the dishes
            data_objects = ["resolvers_loaded", "resolver_types",
                            "resolver_clazzes", "linotpConfig", "audit", "hsm"]
            for data_obj in data_objects:
                if hasattr(c, data_obj):
                    data = getattr(c, data_obj)
                    del data

            log.debug("request %r done!" % path)

        return ret
コード例 #12
0
ファイル: resolver.py プロジェクト: MuhamadYULIANTO/LinOTP
def get_resolver_class(cls_identifier):
    '''
    return the class object for a resolver type
    :param resolver_type: string specifying the resolver
                          fully qualified or abreviated
    :return: resolver object class
    '''

    # ## this patch is a bit hacky:
    # the normal request has a request context, where it retrieves
    # the resolver info from and preserves the loaded resolvers for reusage
    # But in case of a authentication request (by a redirect from a 401)
    # the caller is no std request and the context object is missing :-(
    # The solution is, to deal with local references, either to the
    # global context or to local data

    resolver_classes = context.get('resolver_classes')
    if resolver_classes is None:
        glo = getGlobalObject()
        resolver_classes = copy.deepcopy(glo.getResolverClasses())

    return resolver_classes.get(cls_identifier)
コード例 #13
0
    def authenticate(self, environ, identity):
        log.debug("Authentication through repoze.")
        username = None
        realm = None
        options = {}
        realmbox = "False"

        authenticate = True
        if isSelfTest():
            authenticate = False

        try:
            if isSelfTest():
                if ('login' not in identity
                        and 'repoze.who.plugins.auth_tkt.userid' in identity):
                    u = identity.get('repoze.who.plugins.auth_tkt.userid')
                    identity['login'] = u
                    identity['password'] = u

            username = identity['login']
            realm = identity['realm']
            password = identity['password']
            options.update(identity)
            realmbox = options.get("realmbox", "False")

        except KeyError as e:
            log.exception("Keyerror in repoze identity: %r." % e)
            return None

        # convert string to boolean
        realm_mbox = False
        if realmbox.lower() == 'true':
            realm_mbox = True

        # check username/realm, password
        with request_context_safety():
            linotp_config = getLinotpConfig()
            request_context['Config'] = linotp_config

            # add the cache manager to the context
            glo = getGlobalObject()
            cache_manager = glo.cache_manager
            request_context['CacheManager'] = cache_manager

            # and also add the hsm - enables us to do otp validation :-)
            sep = glo.security_provider
            hsm = sep.getSecurityModule()
            request_context['hsm'] = hsm

            # initialize the base context
            # - copied for the dumb repoze middleware

            cache_dir = config.get("app_conf", {}).get("cache_dir", None)
            setupResolvers(config=linotp_config, cache_dir=cache_dir)
            resolver_context = initResolvers()
            request_context.update(resolver_context)

            # prepare the request local user cache
            if 'UserLookup' not in request_context:
                request_context['UserLookup'] = {}

            user = get_authenticated_user(username,
                                          realm,
                                          password,
                                          realm_box=realm_mbox,
                                          authenticate=authenticate,
                                          options=options)

        if not user:
            return None

        authUser = "******" % (user.login, user.realm)
        return authUser
コード例 #14
0
ファイル: base.py プロジェクト: jimmytuc/LinOTP
    def __init__(self, *args, **kw):
        """
        base controller constructor

        :param *args: generic argument array
        :param **kw: generic argument dict
        :return: None

        """
        self.sep = None
        self.set_language(request.headers)
        self.base_auth_user = ''

        self.parent = super(WSGIController, self)
        self.parent.__init__(*args, **kw)

        # make the OpenID SQL Instance globally available
        openid_sql = config.get('openid_sql', None)
        if openid_sql is None:
            try:
                openid_storage = SQLStorage()
                config['openid_sql'] = openid_storage
            except Exception as exx:
                config['openid_sql'] = exx
                log.error("Failed to configure openid_sql: %r" % exx)

        first_run = False
        app_setup_done = config.get('app_setup_done', False)
        if app_setup_done is False:
            try:
                setup_app(config)
                config['app_setup_done'] = True
                first_run = True
            except Exception as exx:
                config['app_setup_done'] = False
                log.error("Failed to serve request: %r" % exx)
                raise exx

        # set the decryption device before loading linotp config,
        # so it contains the decrypted values as well
        glo = getGlobalObject()
        self.sep = glo.security_provider

        try:
            hsm = self.sep.getSecurityModule()
            self.hsm = hsm
            c.hsm = hsm
        except Exception as exx:
            log.exception('failed to assign hsm device: %r' % exx)
            raise exx

        l_config = initLinotpConfig()

        # initialize the elliptic curve secret + public key for the qr token
        linotpQrTokenSecretKey = l_config.get('QrTokenSecretKey', False)
        if not linotpQrTokenSecretKey:
            init_qrtoken_secret_key(l_config)

        resolver_setup_done = config.get('resolver_setup_done', False)
        if resolver_setup_done is False:
            try:
                cache_dir = config.get("app_conf", {}).get("cache_dir", None)
                setupResolvers(config=l_config, cache_dir=cache_dir)
                config['resolver_setup_done'] = True
            except Exception as exx:
                config['resolver_setup_done'] = False
                log.error("Failed to setup resolver: %r" % exx)
                raise exx

        # TODO: verify merge dropped
        # initResolvers()

        # if we are in the setup cycle, we check for the linotpLicenseFile
        if first_run:
            if "linotpLicenseFile" in config and 'license' not in l_config:
                license_str = ''
                filename = config.get("linotpLicenseFile", '')
                try:
                    with open(filename) as f:
                        license_str = f.read()
                except IOError:
                    log.error("linotpLicenseFile: %s" % filename)

                if not license_str:
                    log.error("empty license file: %s" % filename)
                else:
                    with request_context_safety():
                        request_context['translate'] = translate

                        import linotp.lib.support
                        res, msg = linotp.lib.support.setSupportLicense(license_str)
                        if res is False:
                            log.error("failed to load license: %s: %s"
                                      % (license_str, msg))

                        else:
                            log.info("license successfully loaded")

        return
コード例 #15
0
ファイル: base.py プロジェクト: super-rain/LinOTP
    def __init__(self, *args, **kw):
        """
        base controller constructor

        :param *args: generic argument array
        :param **kw: generic argument dict
        :return: None

        """
        self.sep = None
        self.set_language(request.headers)
        self.base_auth_user = ''

        self.parent = super(WSGIController, self)
        self.parent.__init__(*args, **kw)

        # make the OpenID SQL Instance globally available
        openid_sql = config.get('openid_sql', None)
        if openid_sql is None:
            try:
                openid_storage = SQLStorage()
                config['openid_sql'] = openid_storage
            except Exception as exx:
                config['openid_sql'] = exx
                log.error("Failed to configure openid_sql: %r" % exx)

        first_run = False
        app_setup_done = config.get('app_setup_done', False)
        if app_setup_done is False:
            try:
                setup_app(config)
                config['app_setup_done'] = True
                first_run = True
            except Exception as exx:
                config['app_setup_done'] = False
                log.error("Failed to serve request: %r" % exx)
                raise exx

        # set the decryption device before loading linotp config,
        # so it contains the decrypted values as well
        glo = getGlobalObject()
        self.sep = glo.security_provider

        try:
            hsm = self.sep.getSecurityModule()
            self.hsm = hsm
            c.hsm = hsm
        except Exception as exx:
            log.exception('failed to assign hsm device: %r' % exx)
            raise exx

        l_config = initLinotpConfig()

        # initialize the elliptic curve secret + public key for the qrtoken
        secret_key = l_config.get('SecretKey.Partition.0', False)

        if not secret_key:
            init_key_partition(l_config, partition=0)

        resolver_setup_done = config.get('resolver_setup_done', False)
        if resolver_setup_done is False:
            try:
                cache_dir = config.get("app_conf", {}).get("cache_dir", None)
                setupResolvers(config=l_config, cache_dir=cache_dir)
                config['resolver_setup_done'] = True
            except Exception as exx:
                config['resolver_setup_done'] = False
                log.error("Failed to setup resolver: %r", exx)
                raise exx

        # TODO: verify merge dropped
        # initResolvers()

        # if we are in the setup cycle, we check for the linotpLicenseFile
        if first_run:
            if "linotpLicenseFile" in config and 'license' not in l_config:
                license_str = ''
                filename = config.get("linotpLicenseFile", '')
                try:
                    with open(filename) as f:
                        license_str = f.read()
                except IOError:
                    log.error("could not open licence file: %s", filename)

                if not license_str:
                    log.error("empty license file: %s", filename)
                else:
                    with request_context_safety():
                        request_context['translate'] = translate

                        import linotp.lib.support
                        res, msg = linotp.lib.support.setSupportLicense(
                            license_str)
                        if res is False:
                            log.error("failed to load license: %s: %s",
                                      license_str, msg)

                        else:
                            log.info("license successfully loaded")

        return
コード例 #16
0
ファイル: repoze_auth.py プロジェクト: tdautc19841202/LinOTP
    def authenticate(self, environ, identity):
        log.info("[authenticate] entering repoze authenticate function.")
        # log.debug( identity )
        username = None
        realm = None
        options = {}
        realmbox = "False"

        authenticate = True
        if isSelfTest():
            authenticate = False

        try:
            if isSelfTest():
                if ('login' not in identity
                        and 'repoze.who.plugins.auth_tkt.userid' in identity):
                    u = identity.get('repoze.who.plugins.auth_tkt.userid')
                    identity['login'] = u
                    identity['password'] = u

            username = identity['login']
            realm = identity['realm']
            password = identity['password']
            options.update(identity)
            realmbox = options.get("realmbox", "False")

        except KeyError as e:
            log.exception("[authenticate] Keyerror in identity: %r." % e)
            return None

        # convert string to boolean
        realm_mbox = False
        if realmbox.lower() == 'true':
            realm_mbox = True

        # check username/realm, password
        with request_context_safety():
            linotp_config = getLinotpConfig()
            request_context['Config'] = linotp_config

            # add the cache manager to the context
            glo = getGlobalObject()
            cache_manager = glo.cache_manager
            request_context['CacheManager'] = cache_manager

            # and also add the hsm - enables us to do otp validation :-)
            sep = glo.security_provider
            hsm = sep.getSecurityModule()
            request_context['hsm'] = hsm

            resolver_context = initResolvers()
            request_context.update(resolver_context)

            user = get_authenticated_user(username,
                                          realm,
                                          password,
                                          realm_box=realm_mbox,
                                          authenticate=authenticate,
                                          options=options)

        if not user:
            return None

        authUser = "******" % (user.login, user.realm)
        return authUser
コード例 #17
0
ファイル: base.py プロジェクト: zhao07/LinOTP
    def __init__(self, *args, **kw):
        """
        base controller constructor

        :param *args: generic argument array
        :param **kw: generic argument dict
        :return: None

        """
        self.sep = None

        self.parent = super(WSGIController, self)
        self.parent.__init__(*args, **kw)

        # make the OpenID SQL Instance globally available
        openid_sql = config.get('openid_sql', None)
        if openid_sql is None:
            try:
                openid_storage = SQLStorage()
                config['openid_sql'] = openid_storage
            except Exception as exx:
                config['openid_sql'] = exx
                log.error("Failed to configure openid_sql: %r" % exx)

        app_setup_done = config.get('app_setup_done', False)
        if app_setup_done is False:
            try:
                setup_app(config)
                config['app_setup_done'] = True
            except Exception as exx:
                config['app_setup_done'] = False
                log.error("Failed to serve request: %r" % exx)
                raise exx

        # set the decryption device before loading linotp config,
        # so it contains the decrypted values as well
        glo = getGlobalObject()
        self.sep = glo.security_provider

        try:
            hsm = self.sep.getSecurityModule()
            c.hsm = hsm
        except Exception as exx:
            log.error('failed to assign hsm device: %r' % exx)
            raise exx

        l_config = initLinotpConfig()

        resolver_setup_done = config.get('resolver_setup_done', False)
        if resolver_setup_done is False:
            try:
                cache_dir = config.get("app_conf", {}).get("cache_dir", None)
                setupResolvers(config=l_config, cache_dir=cache_dir)
                config['resolver_setup_done'] = True
            except Exception as exx:
                config['resolver_setup_done'] = False
                log.error("Failed to setup resolver: %r" % exx)
                raise exx

        initResolvers()

        return
コード例 #18
0
ファイル: base.py プロジェクト: MuhamadYULIANTO/LinOTP
    def __init__(self, *args, **kw):
        """
        base controller constructor

        :param *args: generic argument array
        :param **kw: generic argument dict
        :return: None

        """
        self.sep = None
        self.set_language(request.headers)
        self.base_auth_user = ''

        self.parent = super(WSGIController, self)
        self.parent.__init__(*args, **kw)

        # make the OpenID SQL Instance globally available
        openid_sql = config.get('openid_sql', None)
        if openid_sql is None:
            try:
                openid_storage = SQLStorage()
                config['openid_sql'] = openid_storage
            except Exception as exx:
                config['openid_sql'] = exx
                log.error("Failed to configure openid_sql: %r" % exx)

        app_setup_done = config.get('app_setup_done', False)
        if app_setup_done is False:
            try:
                setup_app(config)
                config['app_setup_done'] = True
            except Exception as exx:
                config['app_setup_done'] = False
                log.error("Failed to serve request: %r" % exx)
                raise exx

        # set the decryption device before loading linotp config,
        # so it contains the decrypted values as well
        glo = getGlobalObject()
        self.sep = glo.security_provider

        try:
            hsm = self.sep.getSecurityModule()
            self.hsm = hsm
            c.hsm = hsm
        except Exception as exx:
            log.exception('failed to assign hsm device: %r' % exx)
            raise exx

        l_config = initLinotpConfig()

        # initialize the elliptic curve secret + public key for the qr token
        linotpQrTokenSecretKey = l_config.get('QrTokenSecretKey', False)
        if not linotpQrTokenSecretKey:
            init_qrtoken_secret_key(l_config)

        resolver_setup_done = config.get('resolver_setup_done', False)
        if resolver_setup_done is False:
            try:
                cache_dir = config.get("app_conf", {}).get("cache_dir", None)
                setupResolvers(config=l_config, cache_dir=cache_dir)
                config['resolver_setup_done'] = True
            except Exception as exx:
                config['resolver_setup_done'] = False
                log.error("Failed to setup resolver: %r" % exx)
                raise exx

        return