Exemple #1
0
def _get_realms_():
    realms = {}
    if getRealmBox():
        realms = getRealms()
    else:
        def_realm = getDefaultRealm()
        if getDefaultRealm():
            realms = getRealms(def_realm)
    return realms
Exemple #2
0
def _get_realms_():
    realms = {}
    if getRealmBox():
        realms = getRealms()
    else:
        def_realm = getDefaultRealm()
        if getDefaultRealm():
            realms = getRealms(def_realm)
    return realms
Exemple #3
0
    def exists(self):
        """
        check if a user exists in the given realm
        """
        if self._exists in [True, False]:
            return self._exists

        self._exists = False

        realms = getRealms(self.realm)
        if not realms:
            return self._exists

        found = []
        for realm_name, definition in realms.items():
            resolvers = definition.get('useridresolver', [])
            for realm_resolver in resolvers:
                log.debug("checking in %r" % realm_resolver)
                y = getResolverObject(realm_resolver)
                if y:
                    log.debug("checking in module %r" % y)
                    uid = y.getUserId(self.login)
                    found.append((self.login, realm_name, uid, realm_resolver))
                    log.debug("type of uid: %s" % type(uid))
                    log.debug("type of realm_resolver: %s" % type(realm_resolver))
                else:
                    log.error("module %r not found!" % (realm_resolver))

        if found:
            self._exists = True
            (self.login, self.realm, self.uid, self.resolver) = found[0]
        return self._exists
Exemple #4
0
def getUserRealms(user, allRealms=None, defaultRealm=None):
    '''
    Returns the realms, a user belongs to.
    If the user has no realm but only a useridresolver, than all realms, containing this
    resolver are returned.
    This function is used for the policy module
    '''
    if not allRealms:
        allRealms = getRealms()

    if not defaultRealm:
        defRealm = getDefaultRealm().lower()
    else:
        defRealm = defaultRealm.lower()

    Realms = []
    if user.realm == "" and user.resolver_config_identifier == "":
        defRealm = getDefaultRealm().lower()
        Realms.append(defRealm)
        user.realm = defRealm
    elif user.realm != "":
        Realms.append(user.realm.lower())
    else:
        # we got a resolver and will get all realms the resolver belongs to.
        for key, v in allRealms.items():
            log.debug("[getUserRealms] evaluating realm %r: %r " % (key, v))
            for reso in v['useridresolver']:
                resotype, resoname = reso.rsplit('.', 1)
                log.debug("[getUserRealms] found resolver %r of type %r" % (resoname, resotype))
                if resoname == user.resolver_config_identifier:
                    Realms.append(key.lower())
                    log.debug("[getUserRealms] added realm %r to Realms due to resolver %r" % (key, user.resolver_config_identifier))

    return Realms
Exemple #5
0
    def login(self):
        log.debug("[login] selfservice login screen")
        identity = request.environ.get('repoze.who.identity')
        if identity is not None:
            # After login We always redirect to the start page
            redirect("/")

        res = {}
        try:
            c.defaultRealm = getDefaultRealm()
            res = getRealms()

            c.realmArray = []
            #log.debug("[login] %s" % str(res) )
            for (k, v) in res.items():
                c.realmArray.append(k)

            c.realmbox = getRealmBox()
            log.debug("[login] displaying realmbox: %i" % int(c.realmbox))

            Session.commit()
            response.status = '%i Logout from LinOTP selfservice' % LOGIN_CODE
            return render('/selfservice/login.mako')

        except Exception as e:
            log.exception('[login] failed %r' % e)
            Session.rollback()
            return sendError(response, e)

        finally:
            Session.close()
Exemple #6
0
    def exists(self):
        """
        check if a user exists in the given realm
        """
        if self._exists in [True, False]:
            return self._exists

        self._exists = False

        realms = getRealms(self.realm)
        if not realms:
            return self._exists

        found = []
        for realm_name, definition in realms.items():
            resolvers = definition.get('useridresolver', [])
            for realm_resolver in resolvers:
                log.debug("checking in %r", realm_resolver)
                y = getResolverObject(realm_resolver)
                if y:
                    log.debug("checking in module %r" % y)
                    uid = y.getUserId(self.login)
                    found.append((self.login, realm_name, uid, realm_resolver))
                    log.debug("type of uid: %s", type(uid))
                    log.debug("type of realm_resolver: %s",
                              type(realm_resolver))
                else:
                    log.error("module %r not found!", realm_resolver)

        if found:
            self._exists = True
            (self.login, self.realm, self.uid, self.resolver) = found[0]
        return self._exists
Exemple #7
0
def setRealm(realm, resolvers):

    realm = realm.lower().strip()
    realm = realm.replace(" ", "-")

    nameExp = "^[A-Za-z0-9_\-\.]*$"
    res = re.match(nameExp, realm)
    if res is None:
        e = Exception("non conformant characters in realm name:"
                      " %s (not in %s)" % (realm, nameExp))
        raise e

    ret = storeConfig("useridresolver.group.%s" % realm, resolvers)
    if ret == False:
        return ret

    createDBRealm(realm)

    ## if this is the first one, make it the default
    realms = getRealms()
    if 1 == len(realms):
        for name in realms:
            setDefaultRealm(name)

    return True
Exemple #8
0
def getUserRealms(user):
    '''
    Returns the realms, a user belongs to.
    If the user has no realm but only a useridresolver, than all realms, containing this
    resolver are returned.
    This function is used for the policy module
    '''
    allRealms = getRealms()
    Realms = []
    if user.realm == "" and user.conf == "":
        defRealm = getDefaultRealm().lower()
        Realms.append(defRealm)
        user.realm = defRealm
    elif user.realm != "":
        Realms.append(user.realm.lower())
    else:
        # we got a resolver and will get all realms the resolver belongs to.
        for key, v in allRealms.items():
            log.debug("[getUserRealms] evaluating realm %r: %r " % (key, v))
            for reso in v['useridresolver']:
                resotype, resoname = reso.rsplit('.', 1)
                log.debug("[getUserRealms] found resolver %r of type %r" % (resoname, resotype))
                if resoname == user.conf:
                    Realms.append(key.lower())
                    log.debug("[getUserRealms] added realm %r to Realms due to resolver %r" % (key, user.conf))

    return Realms
Exemple #9
0
    def _get_resolvers_of_user(login=login, realm=realm):

        if not login:
            return []

        log.info("cache miss %r@%r", login, realm)
        Resolvers = []
        resolvers_of_realm = getRealms(realm).\
                                       get(realm, {}).\
                                       get('useridresolver', [])

        log.debug("check if user %r is in resolver %r",
                  login, resolvers_of_realm)

        # Search for user in each resolver in the realm_
        for resolver_spec in resolvers_of_realm:
            log.debug("checking in %r", resolver_spec)

            login_, uid, _user_info = lookup_user_in_resolver(login,
                                                              None,
                                                              resolver_spec)
            if login_ and uid:
                Resolvers.append(resolver_spec)

        return Resolvers
Exemple #10
0
    def login(self):
        log.debug("[login] selfservice login screen")
        identity = request.environ.get('repoze.who.identity')
        if identity is not None:
            # After login We always redirect to the start page
            redirect("/")

        res = {}
        try:
            c.defaultRealm = getDefaultRealm()
            res = getRealms()

            c.realmArray = []
            #log.debug("[login] %s" % str(res) )
            for (k, v) in res.items():
                c.realmArray.append(k)

            c.realmbox = getRealmBox()
            log.debug("[login] displaying realmbox: %i" % int(c.realmbox))

            Session.commit()
            response.status = '%i Logout from LinOTP selfservice' % LOGIN_CODE
            return render('/selfservice/login.mako')

        except Exception as e:
            log.exception('[login] failed %r' % e)
            Session.rollback()
            return sendError(response, e)

        finally:
            Session.close()
Exemple #11
0
def setRealm(realm, resolvers):

    realm = realm.lower().strip()
    realm = realm.replace(" ", "-")

    nameExp = "^[A-Za-z0-9_\-\.]*$"
    res = re.match(nameExp, realm)
    if res is None:
        e = Exception("non conformant characters in realm name:"
                      " %s (not in %s)" % (realm, nameExp))
        raise e

    ret = storeConfig("useridresolver.group.%s" % realm, resolvers)
    if ret == False:
        return ret

    createDBRealm(realm)

    # if this is the first one, make it the default
    realms = getRealms()
    if 1 == len(realms):
        for name in realms:
            setDefaultRealm(name)

    return True
Exemple #12
0
    def get_uid_resolver(self, resolvers=None):
        """
        generator to get the uid and resolver info of the user

        :param resolvers: provide the resolver, where to check for the user
        :return: the tuple of uid and resolver
        """

        uid = None
        resolvers_list = []

        # if the resolver is not provided, we make a lookup for all resolvers
        # in the user realm

        if not resolvers:
            if self.realm:
                realms = getRealms()
                if self.realm.lower() in realms:
                    resolvers_list = realms.get(self.realm.lower(), {}).\
                                       get('useridresolver', [])
        else:
            resolvers_list = []
            for search_resolver in resolvers:
                fq_resolver = User.get_fq_resolver(search_resolver)
                if fq_resolver:
                    resolvers_list.append(fq_resolver)

        if not resolvers_list:
            return

        for resolver_spec in resolvers_list:
            try:
                y = getResolverObject(resolver_spec)
                uid = y.getUserId(self.login)
                if not uid:
                    uid = None
                    continue

                # we add the gathered resolver info to our self for later usage

                # 1. to the resolver uid list

                self.resolverUid[resolver_spec] = uid

                # 2. the resolver spec list

                resId = y.getResolverId()
                resCId = resolver_spec
                __, conf = parse_resolver_spec(resolver_spec)
                self.resolverConf[resolver_spec] = (resId, resCId, conf)

                # remember that we identified the user
                self.exist = True

                yield uid, resolver_spec

            except Exception as exx:
                log.exception("Error while accessing resolver %r", exx)
Exemple #13
0
    def login(self):
        """Checks a user's credentials and issues them a JWT access
        token if their credentials are valid. We're using cookies to
        store the access token plus a double-submit token for CSRF
        protection, which makes it easy to refresh access tokens
        transparently if they are nearing expiry.

        """

        username = self.request_params.get("username")
        password = self.request_params.get("password")

        # Search for the user in the admin realm and check the
        # given password.

        admin_realm_name = current_app.config["ADMIN_REALM_NAME"]
        admin_realm = getRealms(admin_realm_name)
        admin_resolvers = admin_realm[admin_realm_name]["useridresolver"]

        for resolver_specification in admin_resolvers:

            resolver = getResolverObject(resolver_specification)

            uid = resolver.getUserId(username)
            if not uid:
                continue

            if not resolver.checkPass(uid, password):
                continue

            response = sendResult(
                None,
                True,
                opt={"message": f"Login successful for {username}"},
            )

            access_token = create_access_token(identity={
                "username":
                username,
                "realm":
                current_app.config["ADMIN_REALM_NAME"],
                "resolver":
                resolver_specification,
            }, )

            set_access_cookies(response, access_token)

            return response

        response = sendResult(
            None,
            False,
            opt={"message": "Bad username or password"},
        )
        response.status_code = 401
        return response
Exemple #14
0
    def _get_realm_condition(self, valid_realms, filterRealm):
        """
        create the condition for only getting certain realms!
        """
        rcondition = None
        if "*" in valid_realms:
            log.debug("[TokenIterator::init] wildcard for realm '*' found."
                      " Tokens of all realms will be displayed")
            return rcondition

        if len(valid_realms) > 0:
            log.debug(
                "[TokenIterator::init] adding filter condition"
                " for realm %r",
                valid_realms,
            )

            # get all matching realms
            token_ids = self._get_tokens_in_realm(valid_realms)
            rcondition = and_(Token.LinOtpTokenId.in_(token_ids))
            return rcondition

        if ("''" in filterRealm or '""' in filterRealm
                or "/:no realm:/" in filterRealm):
            log.debug("[TokenIterator::init] search for all tokens, which are"
                      " in no realm")

            # get all tokenrealm ids
            token_id_tuples = db.session.query(TokenRealm.token_id).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            # define the token id not condition
            rcondition = and_(not_(Token.LinOtpTokenId.in_(token_ids)))
            return rcondition

        if filterRealm:
            # get all matching realms
            search_realms = set()

            realms = getRealms()
            for realm in realms:
                for frealm in filterRealm:
                    if fnmatch.fnmatch(realm, frealm):
                        search_realms.add(realm)

            search_realms = list(search_realms)

            # define the token id condition
            token_ids = self._get_tokens_in_realm(search_realms)
            rcondition = and_(Token.LinOtpTokenId.in_(token_ids))
            return rcondition

        return rcondition
Exemple #15
0
def getAllUserRealms(user):
    results = [];
    realms = getRealms();

    # get a list of realms the user is present in
    for key, v in realms.items():
        resolvers = getResolversOfUser(User(user.login, v['realmname'], ""))
        if (resolvers):
            results.append(v['realmname'])

    return results;
Exemple #16
0
    def _get_realm_condition(self, valid_realms, filterRealm):
        """
         create the condition for only getting certain realms!
        """
        rcondition = None
        if '*' in valid_realms:
            log.debug("[TokenIterator::init] wildcard for realm '*' found."
                      " Tokens of all realms will be displayed")
            return rcondition

        if len(valid_realms) > 0:
            log.debug("[TokenIterator::init] adding filter condition"
                      " for realm %r" % valid_realms)

            # get all matching realms
            token_ids = self._get_tokens_in_realm(valid_realms)
            rcondition = and_(Token.LinOtpTokenId.in_(token_ids))
            return rcondition

        if ("''" in filterRealm or '""' in filterRealm or
              "/:no realm:/" in filterRealm):
            log.debug("[TokenIterator::init] search for all tokens, which are"
                      " in no realm")

            # get all tokenrealm ids
            token_id_tuples = Session.query(TokenRealm.token_id).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            ## define the token id not condition
            rcondition = and_(not_(Token.LinOtpTokenId.in_(token_ids)))
            return rcondition

        if filterRealm:
            # get all matching realms
            search_realms = set()

            realms = getRealms()
            for realm in realms:
                for frealm in filterRealm:
                    if fnmatch.fnmatch(realm, frealm):
                        search_realms.add(realm)

            search_realms = list(search_realms)

            # define the token id condition
            token_ids = self._get_tokens_in_realm(search_realms)
            rcondition = and_(Token.LinOtpTokenId.in_(token_ids))
            return rcondition

        return rcondition
Exemple #17
0
def getResolvers(user):
    '''
    get the list of the Resolvers within a users.realm
    or from the resolver conf, if given in the user object

    :note:  It ignores the user.login attribute!

    :param user: User with realm or resolver conf
    :type  user: User object
    '''
    Resolver = []

    realms = getRealms();

    if user.resolver_config_identifier != "":
        resolver_spec = find_resolver_spec_for_config_identifier(realms,
                                                user.resolver_config_identifier)
        if resolver_spec is not None:
            Resolver.append(resolver_spec)
    else:
        if user.realm != "":
            if user.realm.lower() in realms:
                Resolver = realms[user.realm.lower()]["useridresolver"]
            else:
                resDict = {}
                if user.realm.endswith('*') and len(user.realm) > 1:
                    pattern = user.realm[:-1]
                    for r in realms:
                        if r.startswith(pattern):
                            for idres in realms[r]["useridresolver"]:
                                resDict[idres] = idres
                    for k in resDict:
                        Resolver.append(k)


                elif user.realm.endswith('*') and len(user.realm) == 1:
                    for r in realms:
                        for idres in realms[r]["useridresolver"]:
                            resDict[idres] = idres
                    for k in resDict:
                        Resolver.append(k)

        else:
            for k in realms:
                r = realms[k]
                if r.has_key("default"):
                    Resolver = r["useridresolver"]

    return Resolver
Exemple #18
0
def getResolvers(user):
    '''
    get the list of the Resolvers within a users.realm
    or from the resolver conf, if given in the user object

    :note:  It ignores the user.login attribute!

    :param user: User with realm or resolver conf
    :type  user: User object
    '''
    Resolver = []

    realms = getRealms();

    if user.conf != "":
        reso = getConf(realms, user.conf)
        if len(reso) > 0:
            Resolver.append(reso)
    else:
        if user.realm != "":
            if user.realm.lower() in realms:
                Resolver = realms[user.realm.lower()]["useridresolver"]
            else:
                resDict = {}
                if user.realm.endswith('*') and len(user.realm) > 1:
                    pattern = user.realm[:-1]
                    for r in realms:
                        if r.startswith(pattern):
                            for idres in realms[r]["useridresolver"]:
                                resDict[idres] = idres
                    for k in resDict:
                        Resolver.append(k)


                elif user.realm.endswith('*') and len(user.realm) == 1:
                    for r in realms:
                        for idres in realms[r]["useridresolver"]:
                            resDict[idres] = idres
                    for k in resDict:
                        Resolver.append(k)

        else:
            for k in realms:
                r = realms[k]
                if r.has_key("default"):
                    Resolver = r["useridresolver"]

    return Resolver
Exemple #19
0
def getResolvers(user):
    '''
    get the list of the Resolvers within a users.realm
    or from the resolver conf, if given in the user object

    :note:  It ignores the user.login attribute!

    :param user: User with realm or resolver conf
    :type  user: User object
    '''
    Resolver = []

    realms = getRealms()

    if user.resolver_config_identifier != "":
        resolver_spec = find_resolver_spec_for_config_identifier(realms,
                                                user.resolver_config_identifier)
        if resolver_spec is not None:
            Resolver.append(resolver_spec)
    else:
        if user.realm != "":
            if user.realm.lower() in realms:
                Resolver = realms[user.realm.lower()]["useridresolver"]
            else:
                resDict = {}
                if user.realm.endswith('*') and len(user.realm) > 1:
                    pattern = user.realm[:-1]
                    for r in realms:
                        if r.startswith(pattern):
                            for idres in realms[r]["useridresolver"]:
                                resDict[idres] = idres
                    for k in resDict:
                        Resolver.append(k)

                elif user.realm.endswith('*') and len(user.realm) == 1:
                    for r in realms:
                        for idres in realms[r]["useridresolver"]:
                            resDict[idres] = idres
                    for k in resDict:
                        Resolver.append(k)

        else:
            for k in realms:
                r = realms[k]
                if "default" in r:
                    Resolver = r["useridresolver"]

    return Resolver
Exemple #20
0
    def _convert_realms_to_resolvers(self, valid_realms):
        """
        it's easier and more efficient to look for the resolver definition in
        one realm, than to follow the join on database level
        """
        resolvers = set()
        realms = getRealms()
        if '*' in valid_realms:
            search_realms = realms.keys()
        else:
            search_realms = valid_realms

        for realm in search_realms:
            resolvers.update(realms.get(realm, {}).get('useridresolver', []))

        return list(resolvers)
Exemple #21
0
def get_admin_resolvers():
    """ """
    admin_realm_name = current_app.config["ADMIN_REALM_NAME"].lower()

    admin_realm_definition = getRealms(admin_realm_name).get(
        admin_realm_name, {}
    )

    if not admin_realm_definition:
        return []

    admin_resolvers = set()
    for resolver_spec in admin_realm_definition["useridresolver"]:
        admin_resolvers.add(resolver_spec.rpartition(".")[2])

    return list(admin_resolvers)
Exemple #22
0
    def _convert_realms_to_resolvers(self, valid_realms):
        """
        it's easier and more efficient to look for the resolver definition in
        one realm, than to follow the join on database level
        """
        resolvers = set()
        realms = getRealms()
        if '*' in valid_realms:
            search_realms = realms.keys()
        else:
            search_realms = valid_realms

        for realm in search_realms:
            resolvers.update(realms.get(realm, {}).get('useridresolver', []))

        return list(resolvers)
Exemple #23
0
def getResolvers(user):
    """
    get the list of the Resolvers within a users.realm
    or from the resolver conf, if given in the user object

    :note:  It ignores the user.login attribute!

    :param user: User with realm or resolver conf
    :type  user: User object
    """
    Resolver = []

    realms = getRealms()

    if user.conf != "":
        reso = getConf(realms, user.conf)
        if len(reso) > 0:
            Resolver.append(reso)
    else:
        if user.realm != "":
            if user.realm.lower() in realms:
                Resolver = realms[user.realm.lower()]["useridresolver"]
            else:
                resDict = {}
                if user.realm.endswith("*") and len(user.realm) > 1:
                    pattern = user.realm[:-1]
                    for r in realms:
                        if r.startswith(pattern):
                            for idres in realms[r]["useridresolver"]:
                                resDict[idres] = idres
                    for k in resDict:
                        Resolver.append(k)

                elif user.realm.endswith("*") and len(user.realm) == 1:
                    for r in realms:
                        for idres in realms[r]["useridresolver"]:
                            resDict[idres] = idres
                    for k in resDict:
                        Resolver.append(k)

        else:
            for k in realms:
                r = realms[k]
                if r.has_key("default"):
                    Resolver = r["useridresolver"]

    return Resolver
Exemple #24
0
    def getRealms(self):
        """
        return all realms in which the user is located

        :return: list of realms
        """

        if not self.exists():
            return [self.realm or getDefaultRealm()]

        realms = set()

        for realm, realm_definition in getRealms().items():
            if self.resolver in realm_definition['useridresolver']:
                realms.add(realm)

        return realms
Exemple #25
0
    def login(self):
        '''
        render the selfservice login page
        '''

        c.title = _("LinOTP Self Service Login")

        # ------------------------------------------------------------------ --

        # prepare the realms and put the default realm on the top

        defaultRealm = getDefaultRealm()
        realmArray = [defaultRealm]

        for realm in getRealms():
            if realm != defaultRealm:
                realmArray.append(realm)

        # ------------------------------------------------------------------ --

        # prepare the global context c for the rendering context

        c.defaultRealm = defaultRealm
        c.realmArray = realmArray

        c.realmbox = getRealmBox()

        context = get_pre_context(c.audit['client'])

        mfa_login = context['mfa_login']
        mfa_3_fields = context['mfa_3_fields']

        c.otp = False
        c.mfa_3_fields = False
        if mfa_login and mfa_3_fields:
            c.mfa_3_fields = True

        response = Response(render('/selfservice/login.mako'))

        if request.cookies.get('user_selfservice'):
            remove_auth_cookie(request.cookies.get('user_selfservice'))
            response.delete_cookie('user_selfservice')

        return response
Exemple #26
0
    def login(self):
        """
        render the selfservice login page
        """

        c.title = _("LinOTP Self Service Login")

        # ------------------------------------------------------------------ --

        # prepare the realms and put the default realm on the top

        defaultRealm = getDefaultRealm()
        realmArray = [defaultRealm]

        for realm in getRealms():
            if realm != defaultRealm:
                realmArray.append(realm)

        # ------------------------------------------------------------------ --

        # prepare the global context c for the rendering context

        c.defaultRealm = defaultRealm
        c.realmArray = realmArray

        c.realmbox = getRealmBox()

        context = get_pre_context(g.audit["client"])

        mfa_login = bool(context["settings"]["mfa_login"])
        mfa_3_fields = bool(context["settings"]["mfa_3_fields"])
        c.mfa_login = mfa_login
        c.mfa_3_fields = mfa_login and mfa_3_fields

        response = Response(render("/selfservice/login.mako"))

        if request.cookies.get("user_selfservice"):
            remove_auth_cookie(request.cookies.get("user_selfservice"))
            response.delete_cookie("user_selfservice")

        return response
Exemple #27
0
    def getUserObject(login, realm=None, check_if_exist=False):

        f_realm = realm
        f_login = login

        if not realm:
            if '@' in login:
                realms = getRealms()
                lo, rea = login.rsplit('@', 1)
                if rea.lower() in realms:
                    f_realm = rea.lower()
                    f_login = lo
                else:
                    f_realm = getDefaultRealm()
                    f_login = login

        f_user = User(f_login, realm=f_realm)
        if check_if_exist:
            _uid, _resolver = f_user.get_uid_resolver()

        return f_user
Exemple #28
0
    def getUserObject(login, realm=None, check_if_exist=False):

        f_realm = realm
        f_login = login

        if not realm:
            if '@' in login:
                realms = getRealms()
                lo, rea = login.rsplit('@', 1)
                if rea.lower() in realms:
                    f_realm = rea.lower()
                    f_login = lo
                else:
                    f_realm = getDefaultRealm()
                    f_login = login

        f_user = User(f_login, realm=f_realm)
        if check_if_exist:
            _uid, _resolver = f_user.get_uid_resolver()

        return f_user
Exemple #29
0
    def get_uid_resolver(self, resolvers=None):
        uid = None
        resolver = None
        resolvers_list = []

        if not resolvers:
            if self.realm:
                realms = getRealms()
                if self.realm.lower() in realms:
                    resolvers_list = realms.get(self.realm.lower(), {}).\
                                       get('useridresolver', [])
        else:
            resolvers_list = []
            for search_resolver in resolvers:
                fq_resolver = User.get_fq_resolver(search_resolver)
                if fq_resolver:
                    resolvers_list.append(fq_resolver)

        if not resolvers_list:
            return None, None

        for resolver in resolvers_list:
            try:
                y = getResolverObject(resolver)
                uid = y.getUserId(self.login)
                if not uid:
                    uid = None
                    continue
                self.resolverUid[resolver] = uid
                self.exist = True
                break

            except Exception as exx:
                log.exception("Error while accessing resolver %r", exx)

        return (uid, resolver)
Exemple #30
0
    def get_uid_resolver(self, resolvers=None):
        uid = None
        resolver_spec = None
        resolver_specs = []

        if not resolvers:
            if self.realm:
                realms = getRealms()
                if self.realm.lower() in realms:
                    resolver_specs = realms.get(self.realm.lower(), {}).\
                                       get('useridresolver', [])
        else:
            resolver_specs = []
            for search_resolver in resolvers:
                fq_resolver = User.get_fq_resolver(search_resolver)
                if fq_resolver:
                    resolver_specs.append(fq_resolver)

        if not resolver_specs:
            return None, None

        for resolver_spec in resolver_specs:
            try:
                y = getResolverObject(resolver_spec)
                uid = y.getUserId(self.login)
                if not uid:
                    uid = None
                    continue
                self.resolverUid[resolver_spec] = uid
                self.exist = True
                break

            except Exception as exx:
                log.exception("Error while accessing resolver %r", exx)

        return (uid, resolver_spec)
Exemple #31
0
def getResolversOfUser(user, use_default_realm=True, allRealms=None, defaultRealm=None):
    '''
    This returns the list of the Resolvers of a user in a given realm.
    Usually this should only return one resolver

    input:
        user.login, user.realm

    returns:
        array of resolvers, the user was found in
    '''

    login = user.login
    realm = user.realm

    if not defaultRealm:
        defaultRealm = getDefaultRealm()

    Resolvers = user.getResolvers()

    if len(Resolvers) > 0:
        return Resolvers

    if not login:
        return Resolvers

    if realm is None or realm == "":
        if use_default_realm:
            realm = defaultRealm

    if not allRealms:
        allRealms = getRealms()

    realms = allRealms

    if user.resolver_config_identifier != "":
        resolver_spec = find_resolver_spec_for_config_identifier(realms,
                                                user.resolver_config_identifier)
        if resolver_spec is not None:
            Resolvers.append(resolver_spec)
    else:
        Realm_resolvers = getResolvers(User("", realm, ""))

        log.debug("[getResolversOfUser] check if user %r is in resolver %r"
                   % (login, Realm_resolvers))
        # Search for user in each resolver in the realm_
        for resolver_spec in Realm_resolvers:
            log.debug("[getResolversOfUser] checking in %r" % resolver_spec)

            y = getResolverObject(resolver_spec)
            if y is None:
                log.error('[getResolversOfUser] [resolver with spec %r '
                          'not found!]' % (resolver_spec))

            try:
                log.debug("[getResolversOfUser] checking in module %r" % y)
                uid = y.getUserId(login)
                log.debug("[getResolversOfUser] type of uid: %s" % type(uid))
                log.debug("[getResolversOfUser] type of resolver_spec: %s" % type(resolver_spec))
                log.debug("[getResolversOfUser] type of login: %s" % type(login))
                if uid not in ["", None]:
                    log.info("[getResolversOfUser] user %r found in resolver %r" % (login, resolver_spec))
                    log.info("[getResolversOfUser] userid resolved to %r " % uid)

                    # Unicode Madness:
                    # This will break as soon as the unicode "uid" is put into a tuple
                    # v = (login, realm_resolver, uid)
                    # log.info("[getResolversOfUser] %s %s %s" % v)
                    resId = y.getResolverId();
                    resCId = resolver_spec
                    Resolvers.append(resolver_spec)
                    __, config_identifier = parse_resolver_spec(resolver_spec)
                    user.addResolverUId(resolver_spec, uid, config_identifier,
                                        resId, resCId)
                else:
                    log.debug("[getResolversOfUser] user %r not found"
                              " in resolver %r" % (login, resolver_spec))
            except Exception as e:
                log.exception('[getResolversOfUser] error searching user in '
                              'resolver with spec %r:%r' % (resolver_spec, e))

            log.debug("[getResolversOfUser] Resolvers: %r" % Resolvers)

    log.debug("[getResolversOfUser] Found the user %r in %r" % (login, Resolvers))
    return Resolvers
Exemple #32
0
    def tokenview_flexi(self):
        '''
        This function is used to fill the flexigrid.
        Unlike the complex /admin/show function, it only returns a
        simple array of the tokens.
        '''
        param = self.request_params

        try:
            c.page = param.get("page")
            c.filter = param.get("query")
            c.qtype = param.get("qtype")
            c.sort = param.get("sortname")
            c.dir = param.get("sortorder")
            c.psize = param.get("rp")

            filter_all = None
            filter_realm = None
            user = User()

            if c.qtype == "loginname":

                # we take by default the given expression as a loginname,
                # especially if it contains a "*" wildcard.
                # it only might be more, a user and a realm, if there
                # is an '@' sign in the loginname and the part after the
                # last '@' sign is matching an existing realm

                user = User(login=c.filter)

                if "*" not in c.filter and "@" in c.filter:

                    login, _ , realm = c.filter.rpartition("@")

                    if realm.lower() in getRealms():
                        user = User(login, realm)
                        if not user.exists():
                            user = User(login=c.filter)

            elif c.qtype == "all":
                filter_all = c.filter

            elif c.qtype == "realm":
                filter_realm = c.filter

            # check admin authorization
            res = checkPolicyPre('admin', 'show', param , user=user)

            filterRealm = res['realms']
            # check if policies are active at all
            # If they are not active, we are allowed to SHOW any tokens.
            pol = getAdminPolicies("show")
            # If there are no admin policies, we are allowed to see all realms
            if not pol['active']:
                filterRealm = ["*"]

            # check if we only want to see ONE realm or see all realms we are allowerd to see.
            if filter_realm:
                if filter_realm in filterRealm or '*' in filterRealm:
                    filterRealm = [filter_realm]

            log.debug("[tokenview_flexi] admin >%s< may display the following realms: %s" % (pol['admin'], pol['realms']))
            log.debug("[tokenview_flexi] page: %s, filter: %s, sort: %s, dir: %s" % (c.page, c.filter, c.sort, c.dir))

            if c.page is None:
                c.page = 1
            if c.psize is None:
                c.psize = 20

            log.debug("[tokenview_flexi] calling TokenIterator for user=%s@%s, filter=%s, filterRealm=%s"
                        % (user.login, user.realm, filter_all, filterRealm))
            c.tokenArray = TokenIterator(user, None, c.page , c.psize, filter_all, c.sort, c.dir, filterRealm=filterRealm)
            c.resultset = c.tokenArray.getResultSetInfo()
            # If we have chosen a page to big!
            lines = []
            for tok in c.tokenArray:
                lines.append(
                    {'id' : tok['LinOtp.TokenSerialnumber'],
                     'cell': [
                            tok['LinOtp.TokenSerialnumber'],
                            tok['LinOtp.Isactive'],
                            tok['User.username'],
                            tok['LinOtp.RealmNames'],
                            tok['LinOtp.TokenType'],
                            tok['LinOtp.FailCount'],
                            tok['LinOtp.TokenDesc'],
                            tok['LinOtp.MaxFail'],
                            tok['LinOtp.OtpLen'],
                            tok['LinOtp.CountWindow'],
                            tok['LinOtp.SyncWindow'],
                            tok['LinOtp.Userid'],
                            tok['LinOtp.IdResClass'].split('.')[-1],
                            ]
                    }
                    )

            # We need to return 'page', 'total', 'rows'
            res = { "page": int(c.page),
                "total": c.resultset['tokens'],
                "rows": lines }

            c.audit['success'] = True

            Session.commit()
            # The flexi handler should support std LinOTP output
            return sendResult(response, res)

        except PolicyException as pe:
            log.exception("[tokenview_flexi] Error during checking policies: %r" % pe)
            Session.rollback()
            return sendError(response, unicode(pe), 1)

        except Exception as e:
            log.exception("[tokenview_flexi] failed: %r" % e)
            Session.rollback()
            return sendError(response, e)

        finally:
            Session.close()
Exemple #33
0
    def __init__(self, user, serial, page=None, psize=None, filter=None,
                 sort=None, sortdir=None, filterRealm=None, user_fields=None,
                 params=None):
        '''
        constructor of Tokeniterator, which gathers all conditions to build
        a sqalchemy query - iterator

        :param user:     User object - user provides as well the searchfield entry
        :type  user:     User class
        :param serial:   serial number of a token
        :type  serial:   string
        :param page:     page number
        :type  page:     int
        :param psize:    how many entries per page
        :type  psize:    int
        :param filter:   additional condition
        :type  filter:   string
        :param sort:     sort field definition
        :type  sort:     string
        :param sortdir:  sort direction: ascending or descending
        :type  sortdir:  string
        :param filterRealm:  restrict the set of token to those in the filterRealm
        :type  filterRealm:  string or list
        :param user_fields:  list of additional fields from the user owner
        :type  user_fields: array
        :param params:  list of additional request parameters - currently not used
        :type  params: dict

        :return: - nothing / None

        '''
        log.debug('[TokenIterator::init] begin. start creating TokenIterator \
        class with parameters: user:%r, serial:%r, page=%r, psize:%r, \
                    filter:%r, sort:%r, sortdir:%r, filterRealm:%r' %
                (user, serial, page, psize, filter, sort, sortdir, filterRealm))

        if params is None:
            params = {}

        self.page = 1
        self.pages = 1
        self.tokens = 0

        self.user_fields = user_fields
        if self.user_fields is None:
            self.user_fields = []

        if type(filterRealm) in (str, unicode):
            filterRealm = filterRealm.split(',')

        if type(filterRealm) in [list]:
            s_realms = []
            for f in filterRealm:
                #  support for multiple realm filtering in the ui
                #  as a coma separated string
                for s_realm in f.split(','):
                    s_realms.append(s_realm.strip())
            filterRealm = s_realms

        #  create a list of all realms, which are allowed to be searched
        #  based on the list of the existing ones
        valid_realms = []
        realms = getRealms().keys()
        if '*' in filterRealm:
            valid_realms.append("*")
        else:
            for realm in realms:
                if realm in filterRealm:
                    realm = linotp.lib.crypt.uencode(realm)
                    valid_realms.append(realm)

        scondition = self._get_serial_condition(serial, filterRealm)
        ucondition = self._get_user_condition(user, valid_realms)
        fcondition = self._get_filter_confition(filter)
        rcondition = self._get_realm_condition(valid_realms, filterRealm)

        #  create the final condition as AND of all conditions
        condTuple = ()
        for conn in (fcondition, ucondition, scondition, rcondition):
            if type(conn).__name__ != 'NoneType':
                condTuple += (conn,)

        condition = and_(*condTuple)

        order = Token.LinOtpTokenDesc

        #   o LinOtp.TokenId: 17943
        #   o LinOtp.TokenInfo: ""
        #   o LinOtp.TokenType: "spass"
        #   o LinOtp.TokenSerialnumber: "spass0000FBA3"
        #   o User.description: "User Name,[email protected],local,"
        #   o LinOtp.IdResClass: "useridresolver.PasswdIdResolver.IdResolver._default_Passwd_"
        #   o User.username: "******"
        #   o LinOtp.TokenDesc: "Always Authenticate"
        #   o User.userid: "1000"
        #   o LinOtp.IdResolver: "/etc/passwd"
        #   o LinOtp.Isactive: true

        if sort == "TokenDesc":
            order = Token.LinOtpTokenDesc
        elif sort == "TokenId":
            order = Token.LinOtpTokenId
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "TokenSerialnumber":
            order = Token.LinOtpTokenSerialnumber
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "IdResClass":
            order = Token.LinOtpIdResClass
        elif sort == "IdResolver":
            order = Token.LinOtpIdResolver
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "FailCount":
            order = Token.LinOtpFailCount
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "Isactive":
            order = Token.LinOtpIsactive

        #  care for the result sort order
        if sortdir is not None and sortdir == "desc":
            order = order.desc()
        else:
            order = order.asc()

        #  care for the result pageing
        if page is None:
            self.toks = Session.query(Token).filter(condition).order_by(order).distinct()
            self.tokens = self.toks.count()

            log.debug("[TokenIterator] DB-Query returned # of objects: %i" % self.tokens)
            self.pagesize = self.tokens
            self.it = iter(self.toks)
            return

        try:
            if psize is None:
                pagesize = int(getFromConfig("pagesize", 50))
            else:
                pagesize = int(psize)
        except:
            pagesize = 20

        try:
            thePage = int (page) - 1
        except:
            thePage = 0
        if thePage < 0:
            thePage = 0

        start = thePage * pagesize
        stop = (thePage + 1) * pagesize

        self.toks = Session.query(Token).filter(condition).order_by(order).distinct()
        self.tokens = self.toks.count()
        log.debug("[TokenIterator::init] DB-Query returned # of objects: %i" % self.tokens)
        self.page = thePage + 1
        fpages = float(self.tokens) / float(pagesize)
        self.pages = int(fpages)
        if fpages - int(fpages) > 0:
            self.pages = self.pages + 1
        self.pagesize = pagesize
        self.toks = self.toks.slice(start, stop)

        self.it = iter(self.toks)

        log.debug('[TokenIterator::init] end. Token iterator created: %r' % \
                  (self.it))

        return
Exemple #34
0
    def create_context(self, request):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        self.request_context = {}
        self.request_context['Config'] = linotp_config
        self.request_context['Policies'] = getPolicies(config=linotp_config)
        self.request_context['translate'] = translate

        request_params = {}

        try:
            request_params.update(request.params)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['Params'] = request_params

        authUser = None
        try:
            authUser = getUserFromRequest(request)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['AuthUser'] = authUser

        requestUser = None
        try:
            requestUser = getUserFromParam(request_params, True)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)
        self.request_context['RequestUser'] = requestUser

        client = None
        try:
            client = get_client(request=request)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['Client'] = client

        self.request_context['audit'] = {}

        defaultRealm = ""
        try:
            defaultRealm = getDefaultRealm(linotp_config)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['defaultRealm'] = defaultRealm

        realms = None
        try:
            realms = getRealms(context=self.request_context)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['Realms'] = realms

        return
Exemple #35
0
    def create_context(self, request, environment):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        request_context['Config'] = linotp_config
        request_context['Policies'] = parse_policies(linotp_config)
        request_context['translate'] = translate
        request_context['CacheManager'] = environment['beaker.cache']
        request_context['Path'] = environment.get("PATH_INFO", "") or ""
        request_context['hsm'] = self.hsm

        request_params = {}

        try:
            request_params.update(request.params)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Params'] = request_params

        initResolvers()

        client = None
        try:
            client = get_client(request=request)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Client'] = client

        request_context['Audit'] = Audit
        request_context['audit'] = Audit.initialize(request, client=client)

        authUser = None
        try:
            authUser = getUserFromRequest(request)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['AuthUser'] = authUser
        request_context['UserLookup'] = {}

        requestUser = None
        try:
            requestUser = getUserFromParam(request_params)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)
        request_context['RequestUser'] = requestUser


        defaultRealm = ""
        try:
            defaultRealm = getDefaultRealm(linotp_config)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['defaultRealm'] = defaultRealm

        realms = None
        try:
            realms = getRealms()
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Realms'] = realms

        # ------------------------------------------------------------------ --

        # for the setup of encrypted data, we require the hsm is instatiated
        # and available in the request context

        if not self.secret_key:
            init_key_partition(linotp_config, partition=0)

        # ------------------------------------------------------------------ --

        # copy some system entries from pylons
        syskeys = {
                   "radius.nas_identifier": "LinOTP",
                   "radius.dictfile": "/etc/linotp2/dictionary"
        }

        sysconfig = {}
        for key, default in syskeys.items():
            sysconfig[key] = config.get(key, default)

        request_context['SystemConfig'] = sysconfig
Exemple #36
0
def get_authenticated_user(username, realm, password=None,
                           realm_box=False, authenticate=True,
                           options=None):
    '''
    check the username and password against a userstore.

    remark: the method is called in the context of repoze.who
            during authentication and during auto_enrollToken/auto_assignToken

    :param username: the user login name
    :param realm: the realm, where the user belongs to
    :param password: the to be checked userstore password
    :param realm_box: take the information, if realmbox is displayed
    :parm authenticate: for the selftest, we skip the authentication

    :return: None or authenticated user object
    '''

    log.info("User %r from realm %r tries to authenticate to selfservice",
             username, realm)

    if type(username) != unicode:
        username = username.decode(ENCODING)

    # ease the handling of options
    if not options:
        options = {}

    users = []
    uid = None

    # if we have an realmbox, we take the user as it is
    # - the realm is always given
    # - appended realms result in error
    if realm_box:
        user = User(username, realm, "")
        users.append(user)

    # else if no realm box is given
    #   and realm is not empty:
    #    - create the user from the values (as we are in auto_assign, etc)
    #   and the realm is empty! (s. login.mako
    #    - the user either appends his realm
    #    - or will get the realm appended
    #
    else:
        if realm:
            user = User(username, realm, "")
            users.append(user)
        else:
            def_realm = options.get('defaultRealm', getDefaultRealm())
            if def_realm:
                user = User(username, def_realm, "")
                users.append(user)
            if '@' in username:
                u_name, u_realm = username.rsplit('@', 1)
                user = User(u_name, u_realm, "")
                users.append(user)

    # Authenticate user
    auth_user = None

    for user in users:
        resolvers = []

        username = user.login
        realm = user.realm

        realm_info = getRealms(user.realm)
        if realm_info and realm in realm_info:
            resolvers = realm_info.get(user.realm).get('useridresolver', [])

        found_uid = None
        for resolver_spec in resolvers:

            y = getResolverObject(resolver_spec)
            if y is None:
                log.error("[getResolversOfUser] [ module %r not found!]",
                          resolver_spec)
                continue

            uid = y.getUserId(user.login)
            if not uid:
                log.debug("user %r not in resolver %r.",
                          username, resolver_spec)
                continue

            if found_uid and uid != found_uid:
                    raise Exception('user login %r : missmatch for userid: '
                                    '%r:%r', user.login, found_uid, uid)

            if authenticate:
                if y.checkPass(uid, password):
                    log.debug("Successfully authenticated user %r.", username)
                else:
                    log.info("user %r failed to authenticate.", username)
                    if found_uid:
                        raise Exception('previous authenticated user mismatch'
                                        ' - password missmatch!')
                    continue

            # add the fully qualified resolver to the resolver list
            user.resolvers_list.append(resolver_spec)

            if not found_uid:
                found_uid = uid

            auth_user = user

    if not auth_user:
        log.error("Error while trying to verify the username: %s", username)

    return auth_user
Exemple #37
0
def getResolversOfUser(user, use_default_realm=True, allRealms=None,
                       defaultRealm=None):
    '''
    This returns the list of the Resolvers of a user in a given realm.
    Usually this should only return one resolver

    input:
        user.login, user.realm

    returns:
        array of resolvers, the user was found in
    '''

    login = user.login
    realm = user.realm

    if not defaultRealm:
        defaultRealm = getDefaultRealm()

    Resolvers = user.getResolvers()

    if len(Resolvers) > 0:
        return Resolvers

    if not login:
        return Resolvers

    if realm is None or realm == "":
        if use_default_realm:
            realm = defaultRealm

    if not allRealms:
        allRealms = getRealms()

    realms = allRealms

    if user.resolver_config_identifier != "":
        resolver_spec = find_resolver_spec_for_config_identifier(realms,
                                                user.resolver_config_identifier)
        if resolver_spec is not None:
            Resolvers.append(resolver_spec)
    else:
        Realm_resolvers = getResolvers(User("", realm, ""))

        log.debug("[getResolversOfUser] check if user %r is in resolver %r",
                  login, Realm_resolvers)
        # Search for user in each resolver in the realm_
        for resolver_spec in Realm_resolvers:
            log.debug("[getResolversOfUser] checking in %r", resolver_spec)

            y = getResolverObject(resolver_spec)
            if y is None:
                log.error('[getResolversOfUser] [resolver with spec %r '
                          'not found!]', resolver_spec)

            try:
                log.debug("[getResolversOfUser] checking in module %r", y)
                uid = y.getUserId(login)
                log.debug("[getResolversOfUser] type of uid: %s", type(uid))
                log.debug("[getResolversOfUser] type of resolver_spec: %s",
                           type(resolver_spec))
                log.debug("[getResolversOfUser] type of login: %s",
                          type(login))

                if uid not in ["", None]:
                    log.info("[getResolversOfUser] user %r found in resolver "
                             "%r", login, resolver_spec)
                    log.info("[getResolversOfUser] userid resolved to %r ",
                             uid)

                    # Unicode Madness:
                    # This will break as soon as the unicode "uid" is put into
                    # a tuple
                    # v = (login, realm_resolver, uid)
                    # log.info("[getResolversOfUser] %s %s %s" % v)
                    resId = y.getResolverId()
                    resCId = resolver_spec
                    Resolvers.append(resolver_spec)
                    __, config_identifier = parse_resolver_spec(resolver_spec)
                    user.addResolverUId(resolver_spec, uid, config_identifier,
                                        resId, resCId)
                else:
                    log.debug("[getResolversOfUser] user %r not found"
                              " in resolver %r", login, resolver_spec)
            except Exception as exx:
                log.exception('[getResolversOfUser] error searching user in '
                              'resolver with spec %r:%r', resolver_spec, exx)

            log.debug("[getResolversOfUser] Resolvers: %r", Resolvers)

    log.debug("[getResolversOfUser] Found the user %r in %r", login, Resolvers)
    return Resolvers
Exemple #38
0
    def create_context(self, request):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        request_context['Config'] = linotp_config
        request_context['Policies'] = getPolicies()
        request_context['translate'] = translate

        initResolvers()

        request_params = {}

        try:
            request_params.update(request.params)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['Params'] = request_params

        authUser = None
        try:
            authUser = getUserFromRequest(request)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['AuthUser'] = authUser

        requestUser = None
        try:
            requestUser = getUserFromParam(request_params, True)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)
        request_context['RequestUser'] = requestUser

        client = None
        try:
            client = get_client(request=request)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['Client'] = client

        request_context['Audit'] = Audit
        request_context['audit'] = Audit.initialize(request,
                                                         client=client)

        defaultRealm = ""
        try:
            defaultRealm = getDefaultRealm(linotp_config)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['defaultRealm'] = defaultRealm

        realms = None
        try:
            realms = getRealms()
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['Realms'] = realms

        request_context['hsm'] = None
        if hasattr(self, "hsm"):
            request_context['hsm'] = self.hsm

        # copy some system entries from pylons
        syskeys = {
                   "radius.nas_identifier": "LinOTP",
                   "radius.dictfile": "/etc/linotp2/dictionary"
        }

        sysconfig = {}
        for key, default in syskeys.items():
            try:
                sysconfig[key] = config.get(key, default)
            except:
                log.info('no sytem config entry %s' % key)

        request_context['SystemConfig'] = sysconfig
Exemple #39
0
def user_list_compare(policy_conditions, login):
    """
    check if login name matches list of user policy conditions

    :param policy_condition: the condition described in the policy
    :param login: the to be compared user - either User obj or string
    :return: booleans
    """
    conditions = [x.strip() for x in policy_conditions.split(',')]

    if isinstance(login, User):
        user = login
    elif isinstance(login, str) or isinstance(login, unicode):
        if '@' in login:
            usr, _sep, realm = login.rpartition('@')
            user = User(usr, realm)
        else:
            user = User(login)
    else:
        raise Exception("unsupported type of login")

    matched = False

    domain_comp = UserDomainCompare()
    attr_comp = AttributeCompare()

    for condition in conditions:

        if not condition:
            continue

        its_a_not_condition = False

        # we preserve the kind of match:
        # in case of a 'non condition' match, we must return immeaditly
        # and return a False to break out of the loop of conditions

        if condition[0] in ['-', '!']:
            condition = condition[1:]
            its_a_not_condition = True

        if '#' in condition:

            if ((isinstance(login, str) or isinstance(login, unicode)) and
               '@' in login):

                usr, _sep, realm = login.rpartition('@')

                if realm in getRealms():
                    c_user = User(usr, realm)
                else:
                    c_user = User(login)

            else:
                c_user = user

            identified = attr_comp.compare(c_user, condition)

        elif '@' in condition:  # domain condition requires a domain compare

            #
            # we support fake users, where login is of type string
            # and who have an '@' in it - we rely on that real users
            # are identified up front and then login will of type User

            if ((isinstance(login, str) or isinstance(login, unicode)) and
               '@' in login):
                u_login, _, r_login = login.rpartition('@')
                c_user = User(u_login, r_login)
            else:
                c_user = user
            identified = domain_comp.compare(c_user, condition)

        elif ':' in condition:  # resolver condition - by user exists check

            #
            # special treatment of literal user definition with an @ in login:
            # we can split last part and check if it is an existing realm. If
            # not we treat the user login as literal only

            if ((isinstance(login, str) or isinstance(login, unicode)) and
               '@' in login):

                usr, _sep, realm = login.rpartition('@')

                if realm in getRealms():
                    c_user = User(usr, realm)
                else:
                    c_user = User(login)

            else:
                c_user = user

            identified = domain_comp.exists(c_user, condition)

        else:  # simple user condition with string compare and wild cards

            identified = domain_comp.compare(user, condition)

        if identified:
            matched = True

            if its_a_not_condition:  # early exit on a not condition
                return False

    return matched
Exemple #40
0
def get_authenticated_user(username, realm, password=None,
                           realm_box=False, authenticate=True,
                           options=None):
    '''
    check the username and password against a userstore.

    remark: the method is called in the context of repoze.who
            during authentication and during auto_enrollToken/auto_assignToken

    :param username: the user login name
    :param realm: the realm, where the user belongs to
    :param password: the to be checked userstore password
    :param realm_box: take the information, if realmbox is displayed
    :parm authenticate: for the selftest, we skip the authentication

    :return: None or authenticated user object
    '''

    log.info("User %r from realm %r tries to authenticate to selfservice",
             username, realm)

    if type(username) != unicode:
        username = username.decode(ENCODING)

    # ease the handling of options
    if not options:
        options = {}

    users = []
    uid = None

    # if we have an realmbox, we take the user as it is
    # - the realm is always given
    # - appended realms result in error
    if realm_box:
        user = User(username, realm, "")
        users.append(user)

    # else if no realm box is given
    #   and realm is not empty:
    #    - create the user from the values (as we are in auto_assign, etc)
    #   and the realm is empty! (s. login.mako
    #    - the user either appends his realm
    #    - or will get the realm appended
    #
    else:
        if realm:
            user = User(username, realm, "")
            users.append(user)
        else:
            def_realm = options.get('defaultRealm', getDefaultRealm())
            if def_realm:
                user = User(username, def_realm, "")
                users.append(user)
            if '@' in username:
                u_name, u_realm = username.rsplit('@', 1)
                user = User(u_name, u_realm, "")
                users.append(user)

    # Authenticate user
    auth_user = None

    for user in users:
        resolvers = []

        username = user.login
        realm = user.realm

        realm_info = getRealms(user.realm)
        if realm_info and realm in realm_info:
            resolvers = realm_info.get(user.realm).get('useridresolver', [])

        found_uid = None
        for resolver_spec in resolvers:

            y = getResolverObject(resolver_spec)
            if y is None:
                log.error("[getResolversOfUser] [ module %r not found!]",
                          resolver_spec)
                continue

            uid = y.getUserId(user.login)
            if not uid:
                log.debug("user %r not in resolver %r.",
                          username, resolver_spec)
                continue

            if found_uid and uid != found_uid:
                    raise Exception('user login %r : missmatch for userid: '
                                    '%r:%r', user.login, found_uid, uid)

            if authenticate:
                if y.checkPass(uid, password):
                    log.debug("Successfully authenticated user %r.", username)
                else:
                    log.info("user %r failed to authenticate.", username)
                    if found_uid:
                        raise Exception('previous authenticated user mismatch'
                                        ' - password missmatch!')
                    continue

            # add the fully qualified resolver to the resolver list
            user.resolvers_list.append(resolver_spec)

            if not found_uid:
                found_uid = uid

            auth_user = user

    if not auth_user:
        log.error("Error while trying to verify the username: %s", username)

    return auth_user
Exemple #41
0
    def __init__(self, user, serial, page=None, psize=None, filter=None,
                 sort=None, sortdir=None, filterRealm=None, user_fields=None,
                 params=None):
        '''
        constructor of Tokeniterator, which gathers all conditions to build
        a sqalchemy query - iterator

        :param user:     User object - user provides as well the searchfield
                                       entry
        :type  user:     User class
        :param serial:   serial number of a token
        :type  serial:   string
        :param page:     page number
        :type  page:     int
        :param psize:    how many entries per page
        :type  psize:    int
        :param filter:   additional condition
        :type  filter:   string
        :param sort:     sort field definition
        :type  sort:     string
        :param sortdir:  sort direction: ascending or descending
        :type  sortdir:  string
        :param filterRealm:  restrict the set of token to those in
                             the filterRealm
        :type  filterRealm:  string or list
        :param user_fields:  list of additional fields from the user owner
        :type  user_fields: array
        :param params:  list of additional request parameters
                        - currently not used
        :type  params: dict

        :return: - nothing / None

        '''
        log.debug('[TokenIterator::init] begin. start creating TokenIterator \
        class with parameters: user:%r, serial:%r, page=%r, psize:%r, \
                    filter:%r, sort:%r, sortdir:%r, filterRealm:%r' %
                (user, serial, page, psize, filter, sort, sortdir,
                 filterRealm))

        if params is None:
            params = {}

        self.page = 1
        self.pages = 1
        self.tokens = 0
        self.user_fields = user_fields
        if self.user_fields == None:
            self.user_fields = []

        condition = None
        ucondition = None
        scondition = None
        r_condition = None

        if type(filterRealm) in (str, unicode):
            filterRealm = filterRealm.split(',')

        if type(filterRealm) in [list]:
            s_realms = []
            for f in filterRealm:
                #  support for multiple realm filtering in the ui
                #  as a coma separated string
                for s_realm in f.split(','):
                    s_realms.append(s_realm.strip())
            filterRealm = s_realms

        #  create a list of all realms, which are allowed to be searched
        #  based on the list of the existing ones
        valid_realms = []
        realms = getRealms().keys()
        if '*' in filterRealm:
            valid_realms.append("*")
        else:
            for realm in realms:
                if realm in filterRealm:
                    realm = linotp.lib.crypt.uencode(realm)
                    valid_realms.append(realm)

        if serial is not None:
            #  check if the requested serial is in the realms of
            # the admin (filterRealm)
            log.debug('[TokenIterator::init] start search for serial: >%r<'
                       % (serial))

            allowed = False
            if filterRealm == ['*']:
                allowed = True
            else:
                realms = getTokenRealms(serial)
                for realm in realms:
                    if realm in filterRealm:
                        allowed = True

            if allowed == True:
                if '*' in serial:
                    serial = serial.replace('*', '%')
                    scondition = and_(Token.LinOtpTokenSerialnumber.like(serial))
                else:
                    scondition = and_(Token.LinOtpTokenSerialnumber == serial)

        if user.isEmpty() == False and user is not None:
            log.debug('[TokenIterator::init] start search for username: >%r<'
                      % (user))

            if user.login is not None and (user.login) > 0 :
                loginUser = user.login.lower()
                loginUser = loginUser.replace('"', '')
                loginUser = loginUser.replace("'", '')

                searchType = "any"

                #  search for a 'blank' user
                if len(loginUser) == 0 and len(user.login) > 0:
                    searchType = "blank"
                elif loginUser == "/:no user:/" or loginUser == "/:none:/":
                    searchType = "blank"
                elif loginUser == "/:no user info:/":
                    searchType = "wildcard"
                elif "*" in loginUser or "." in loginUser:
                    searchType = "wildcard"
                else:
                    #  no blank and no wildcard search
                    searchType = "exact"

                if searchType == "blank":
                    log.debug('[TokenIterator::init] search for empty user:'******' >%r<' % (user.login))
                    ucondition = and_(or_(Token.LinOtpUserid == u'',
                                          Token.LinOtpUserid == None))

                if searchType == "exact":
                    log.debug('[TokenIterator::init] search for exact user:'******' %r' % (user))
                    serials = []
                    users = []

                    #  if search for a realmuser 'user@realm' we can take the
                    #  realm from the argument
                    if len(user.realm) > 0:
                        users.append(user)
                    else:
                        for realm in valid_realms:
                            users.append(User(user.login, realm))

                    # resolve the realm with wildcard:
                    # identify all users and add these to the userlist
                    userlist = []
                    for usr in users:
                        urealm = usr.realm
                        if urealm == '*':
                            # if the realm is set to *, the getUserId
                            # triggers the identification of all resolvers,
                            # where the user might reside: tigger the user
                            # resolver lookup
                            (uid, resolver, resolverClass) = getUserId(usr)
                            userlist.extend(usr.getUserPerConf())
                        else:
                            userlist.append(usr)

                    for usr in userlist:
                        try:
                            tokens = getTokens4UserOrSerial(user=usr, _class=False)
                            for tok in tokens:
                                serials.append(tok.LinOtpTokenSerialnumber)
                        except UserError as ex:
                            #  we get an exception if the user is not found
                            log.debug('[TokenIterator::init] no exact user: %r'
                                      % (user))
                            log.debug('[TokenIterator::init] %r' % ex)

                    if len(serials) > 0:
                        #  if tokens found, search for their serials
                        ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
                    else:
                        #  if no token is found, block search for user
                        #  and return nothing
                        ucondition = and_(or_(Token.LinOtpUserid == u'',
                                              Token.LinOtpUserid == None))

                #  handle case, when nothing found in former cases
                if searchType == "wildcard":
                    log.debug('[TokenIterator::init] wildcard search: %r' % (user))
                    serials = []
                    users = getAllTokenUsers()
                    logRe = None
                    lU = loginUser.replace('*', '.*')
                    # lU = lU.replace('..', '.')
                    logRe = re.compile(lU)

                    for ser in users:
                        userInfo = users.get(ser)
                        tokenUser = userInfo.get('username').lower()
                        try:
                            if logRe.match(u'' + tokenUser) is not None:
                                serials.append(ser)
                        except Exception as e:
                            log.error('error no express %r ' % e)

                    #  to prevent warning, we check is serials are found
                    #  SAWarning: The IN-predicate on
                    #  "Token.LinOtpTokenSerialnumber" was invoked with an
                    #  empty sequence. This results in a contradiction, which
                    #  nonetheless can be expensive to evaluate.  Consider
                    #  alternative strategies for improved performance.
                    if len(serials) > 0:
                        ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
                    else:
                        ucondition = and_(or_(Token.LinOtpUserid == u'',
                                              Token.LinOtpUserid == None))

        if filter is None:
            condition = None
        elif filter in ['/:active:/', '/:enabled:/',
                        '/:token is active:/', '/:token is enabled:/' ]:
            condition = and_(Token.LinOtpIsactive == True)
        elif filter in ['/:inactive:/', '/:disabled:/',
                        '/:token is inactive:/', '/:token is disabled:/']:
            condition = and_(Token.LinOtpIsactive == False)
        else:
            #  search in other colums
            filter = linotp.lib.crypt.uencode(filter)
            condition = or_(Token.LinOtpTokenDesc.contains(filter),
                            Token.LinOtpIdResClass.contains(filter),
                            Token.LinOtpTokenSerialnumber.contains(filter),
                            Token.LinOtpUserid.contains(filter),
                            Token.LinOtpTokenType.contains(filter))

        ###################################################################
        #   The condition for only getting certain realms!
        if '*' in valid_realms:
            log.debug("[TokenIterator::init] wildcard for realm '*' found."
                      " Tokens of all realms will be displayed")
        elif len(valid_realms) > 0:
            log.debug("[TokenIterator::init] adding filter condition"
                      " for realm %r" % valid_realms)

            #  get all matching realms
            realm_id_tuples = Session.query(Realm.id).\
                                filter(Realm.name.in_(valid_realms)).all()
            realm_ids = set()
            for realm_tuple in realm_id_tuples:
                realm_ids.add(realm_tuple[0])
            #  get all tokenrealm ids
            token_id_tuples = Session.query(TokenRealm.token_id).\
                        filter(TokenRealm.realm_id.in_(realm_ids)).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            #  define the token id condition
            r_condition = and_(Token.LinOtpTokenId.in_(token_ids))

        elif ("''" in filterRealm or '""' in filterRealm or
              "/:no realm:/" in filterRealm):
            log.debug("[TokenIterator::init] search for all tokens, which are"
                      " in no realm")

            #  get all tokenrealm ids
            token_id_tuples = Session.query(TokenRealm.token_id).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            #  define the token id not condition
            r_condition = and_(not_(Token.LinOtpTokenId.in_(token_ids)))

        #  create the final condition as AND of all conditions
        condTuple = ()
        for conn in (condition, ucondition, scondition, r_condition):
            if type(conn).__name__ != 'NoneType':
                condTuple += (conn,)

        condition = and_(*condTuple)

        order = Token.LinOtpTokenDesc

        if sort == "TokenDesc":
            order = Token.LinOtpTokenDesc
        elif sort == "TokenId":
            order = Token.LinOtpTokenId
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "TokenSerialnumber":
            order = Token.LinOtpTokenSerialnumber
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "IdResClass":
            order = Token.LinOtpIdResClass
        elif sort == "IdResolver":
            order = Token.LinOtpIdResolver
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "FailCount":
            order = Token.LinOtpFailCount
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "Isactive":
            order = Token.LinOtpIsactive

        #  care for the result sort order
        if sortdir is not None and sortdir == "desc":
            order = order.desc()
        else:
            order = order.asc()

        #  care for the result pageing
        if page is None:
            self.toks = Session.query(Token).filter(condition).order_by(order).distinct()
            self.tokens = self.toks.count()

            log.debug("[TokenIterator] DB-Query returned # of objects:"
                      " %i" % self.tokens)
            self.pagesize = self.tokens
            self.it = iter(self.toks)
            return

        try:
            if psize is None:
                pagesize = int(getFromConfig("pagesize", 50))
            else:
                pagesize = int(psize)
        except:
            pagesize = 20

        try:
            thePage = int (page) - 1
        except:
            thePage = 0
        if thePage < 0:
            thePage = 0

        start = thePage * pagesize
        stop = (thePage + 1) * pagesize

        self.toks = Session.query(Token).filter(condition).\
                                         order_by(order).distinct()
        self.tokens = self.toks.count()
        log.debug("[TokenIterator::init] DB-Query returned # of objects:"
                  " %i" % self.tokens)
        self.page = thePage + 1
        fpages = float(self.tokens) / float(pagesize)
        self.pages = int(fpages)
        if fpages - int(fpages) > 0:
            self.pages = self.pages + 1
        self.pagesize = pagesize
        self.toks = self.toks.slice(start, stop)

        self.it = iter(self.toks)

        log.debug('[TokenIterator::init] end. Token iterator created: %r' % \
                  (self.it))

        return
Exemple #42
0
    def __init__(self,
                 user,
                 serial,
                 page=None,
                 psize=None,
                 filter=None,
                 sort=None,
                 sortdir=None,
                 filterRealm=None,
                 user_fields=None,
                 params=None):
        '''
        constructor of Tokeniterator, which gathers all conditions to build
        a sqalchemy query - iterator

        :param user:     User object - user provides as well the searchfield entry
        :type  user:     User class
        :param serial:   serial number of a token
        :type  serial:   string
        :param page:     page number
        :type  page:     int
        :param psize:    how many entries per page
        :type  psize:    int
        :param filter:   additional condition
        :type  filter:   string
        :param sort:     sort field definition
        :type  sort:     string
        :param sortdir:  sort direction: ascending or descending
        :type  sortdir:  string
        :param filterRealm:  restrict the set of token to those in the filterRealm
        :type  filterRealm:  string or list
        :param user_fields:  list of additional fields from the user owner
        :type  user_fields: array
        :param params:  list of additional request parameters - currently not used
        :type  params: dict

        :return: - nothing / None

        '''
        log.debug(
            '[TokenIterator::init] begin. start creating TokenIterator \
        class with parameters: user:%r, serial:%r, page=%r, psize:%r, \
                    filter:%r, sort:%r, sortdir:%r, filterRealm:%r' %
            (user, serial, page, psize, filter, sort, sortdir, filterRealm))

        if params is None:
            params = {}

        self.page = 1
        self.pages = 1
        self.tokens = 0

        self.user_fields = user_fields
        if self.user_fields is None:
            self.user_fields = []

        if type(filterRealm) in (str, unicode):
            filterRealm = filterRealm.split(',')

        if type(filterRealm) in [list]:
            s_realms = []
            for f in filterRealm:
                #  support for multiple realm filtering in the ui
                #  as a coma separated string
                for s_realm in f.split(','):
                    s_realms.append(s_realm.strip())
            filterRealm = s_realms

        #  create a list of all realms, which are allowed to be searched
        #  based on the list of the existing ones
        valid_realms = []
        realms = getRealms().keys()
        if '*' in filterRealm:
            valid_realms.append("*")
        else:
            for realm in realms:
                if realm in filterRealm:
                    realm = linotp.lib.crypt.uencode(realm)
                    valid_realms.append(realm)

        scondition = self._get_serial_condition(serial, filterRealm)
        ucondition = self._get_user_condition(user, valid_realms)
        fcondition = self._get_filter_confition(filter)
        rcondition = self._get_realm_condition(valid_realms, filterRealm)

        #  create the final condition as AND of all conditions
        condTuple = ()
        for conn in (fcondition, ucondition, scondition, rcondition):
            if type(conn).__name__ != 'NoneType':
                condTuple += (conn, )

        condition = and_(*condTuple)

        order = Token.LinOtpTokenDesc

        #   o LinOtp.TokenId: 17943
        #   o LinOtp.TokenInfo: ""
        #   o LinOtp.TokenType: "spass"
        #   o LinOtp.TokenSerialnumber: "spass0000FBA3"
        #   o User.description: "User Name,[email protected],local,"
        #   o LinOtp.IdResClass: "useridresolver.PasswdIdResolver.IdResolver._default_Passwd_"
        #   o User.username: "******"
        #   o LinOtp.TokenDesc: "Always Authenticate"
        #   o User.userid: "1000"
        #   o LinOtp.IdResolver: "/etc/passwd"
        #   o LinOtp.Isactive: true

        if sort == "TokenDesc":
            order = Token.LinOtpTokenDesc
        elif sort == "TokenId":
            order = Token.LinOtpTokenId
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "TokenSerialnumber":
            order = Token.LinOtpTokenSerialnumber
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "IdResClass":
            order = Token.LinOtpIdResClass
        elif sort == "IdResolver":
            order = Token.LinOtpIdResolver
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "FailCount":
            order = Token.LinOtpFailCount
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "Isactive":
            order = Token.LinOtpIsactive

        #  care for the result sort order
        if sortdir is not None and sortdir == "desc":
            order = order.desc()
        else:
            order = order.asc()

        #  care for the result pageing
        if page is None:
            self.toks = Session.query(Token).filter(condition).order_by(
                order).distinct()
            self.tokens = self.toks.count()

            log.debug("[TokenIterator] DB-Query returned # of objects: %i" %
                      self.tokens)
            self.pagesize = self.tokens
            self.it = iter(self.toks)
            return

        try:
            if psize is None:
                pagesize = int(getFromConfig("pagesize", 50))
            else:
                pagesize = int(psize)
        except:
            pagesize = 20

        try:
            thePage = int(page) - 1
        except:
            thePage = 0
        if thePage < 0:
            thePage = 0

        start = thePage * pagesize
        stop = (thePage + 1) * pagesize

        self.toks = Session.query(Token).filter(condition).order_by(
            order).distinct()
        self.tokens = self.toks.count()
        log.debug("[TokenIterator::init] DB-Query returned # of objects: %i" %
                  self.tokens)
        self.page = thePage + 1
        fpages = float(self.tokens) / float(pagesize)
        self.pages = int(fpages)
        if fpages - int(fpages) > 0:
            self.pages = self.pages + 1
        self.pagesize = pagesize
        self.toks = self.toks.slice(start, stop)

        self.it = iter(self.toks)

        log.debug('[TokenIterator::init] end. Token iterator created: %r' % \
                  (self.it))

        return
Exemple #43
0
    def create_context(self, request, environment):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        request_context['Config'] = linotp_config
        request_context['Policies'] = parse_policies(linotp_config)
        request_context['translate'] = translate
        request_context['CacheManager'] = environment['beaker.cache']

        initResolvers()

        request_params = {}

        try:
            request_params.update(request.params)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Params'] = request_params

        authUser = None
        try:
            authUser = getUserFromRequest(request)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['AuthUser'] = authUser
        request_context['UserLookup'] = {}

        requestUser = None
        try:
            requestUser = getUserFromParam(request_params)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)
        request_context['RequestUser'] = requestUser

        client = None
        try:
            client = get_client(request=request)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Client'] = client

        request_context['Audit'] = Audit
        request_context['audit'] = Audit.initialize(request, client=client)

        defaultRealm = ""
        try:
            defaultRealm = getDefaultRealm(linotp_config)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['defaultRealm'] = defaultRealm

        realms = None
        try:
            realms = getRealms()
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Realms'] = realms

        request_context['hsm'] = None
        if hasattr(self, "hsm"):
            request_context['hsm'] = self.hsm

        # copy some system entries from pylons
        syskeys = {
            "radius.nas_identifier": "LinOTP",
            "radius.dictfile": "/etc/linotp2/dictionary"
        }

        sysconfig = {}
        for key, default in syskeys.items():
            sysconfig[key] = config.get(key, default)

        request_context['SystemConfig'] = sysconfig
Exemple #44
0
    def tokenview_flexi(self):
        '''
        This function is used to fill the flexigrid.
        Unlike the complex /admin/show function, it only returns a
        simple array of the tokens.
        '''
        param = self.request_params

        try:
            c.page = param.get("page")
            c.filter = param.get("query")
            c.qtype = param.get("qtype")
            c.sort = param.get("sortname")
            c.dir = param.get("sortorder")
            c.psize = param.get("rp")

            filter_all = None
            filter_realm = None
            user = User()

            if c.qtype == "loginname":

                # we take by default the given expression as a loginname,
                # especially if it contains a "*" wildcard.
                # it only might be more, a user and a realm, if there
                # is an '@' sign in the loginname and the part after the
                # last '@' sign is matching an existing realm

                user = User(login=c.filter)

                if "*" not in c.filter and "@" in c.filter:

                    login, _, realm = c.filter.rpartition("@")

                    if realm.lower() in getRealms():
                        user = User(login, realm)
                        if not user.exists():
                            user = User(login=c.filter)

            elif c.qtype == "all":
                filter_all = c.filter

            elif c.qtype == "realm":
                filter_realm = c.filter

            # check admin authorization
            res = checkPolicyPre('admin', 'show', param, user=user)

            filterRealm = res['realms']
            # check if policies are active at all
            # If they are not active, we are allowed to SHOW any tokens.
            pol = getAdminPolicies("show")
            # If there are no admin policies, we are allowed to see all realms
            if not pol['active']:
                filterRealm = ["*"]

            # check if we only want to see ONE realm or see all realms we are allowerd to see.
            if filter_realm:
                if filter_realm in filterRealm or '*' in filterRealm:
                    filterRealm = [filter_realm]

            log.debug(
                "[tokenview_flexi] admin >%s< may display the following realms: %s"
                % (pol['admin'], pol['realms']))
            log.debug(
                "[tokenview_flexi] page: %s, filter: %s, sort: %s, dir: %s" %
                (c.page, c.filter, c.sort, c.dir))

            if c.page is None:
                c.page = 1
            if c.psize is None:
                c.psize = 20

            log.debug(
                "[tokenview_flexi] calling TokenIterator for user=%s@%s, filter=%s, filterRealm=%s"
                % (user.login, user.realm, filter_all, filterRealm))
            c.tokenArray = TokenIterator(user,
                                         None,
                                         c.page,
                                         c.psize,
                                         filter_all,
                                         c.sort,
                                         c.dir,
                                         filterRealm=filterRealm)
            c.resultset = c.tokenArray.getResultSetInfo()
            # If we have chosen a page to big!
            lines = []
            for tok in c.tokenArray:
                uid = tok['LinOtp.Userid']
                uid = uid.decode('utf-8') if isinstance(uid, bytes) else uid
                lines.append({
                    'id':
                    tok['LinOtp.TokenSerialnumber'],
                    'cell': [
                        tok['LinOtp.TokenSerialnumber'],
                        tok['LinOtp.Isactive'],
                        tok['User.username'],
                        tok['LinOtp.RealmNames'],
                        tok['LinOtp.TokenType'],
                        tok['LinOtp.FailCount'],
                        tok['LinOtp.TokenDesc'],
                        tok['LinOtp.MaxFail'],
                        tok['LinOtp.OtpLen'],
                        tok['LinOtp.CountWindow'],
                        tok['LinOtp.SyncWindow'],
                        uid,
                        tok['LinOtp.IdResClass'].split('.')[-1],
                    ]
                })

            # We need to return 'page', 'total', 'rows'
            res = {
                "page": int(c.page),
                "total": c.resultset['tokens'],
                "rows": lines
            }

            c.audit['success'] = True

            Session.commit()
            # The flexi handler should support std LinOTP output
            return sendResult(response, res)

        except PolicyException as pe:
            log.exception(
                "[tokenview_flexi] Error during checking policies: %r" % pe)
            Session.rollback()
            return sendError(response, str(pe), 1)

        except Exception as e:
            log.exception("[tokenview_flexi] failed: %r" % e)
            Session.rollback()
            return sendError(response, e)

        finally:
            Session.close()
Exemple #45
0
    def __init__(self, user, serial, page=None, psize=None, filter=None,
                 sort=None, sortdir=None, filterRealm=None, user_fields=None,
                 params=None):
        '''
        constructor of Tokeniterator, which gathers all conditions to build
        a sqalchemy query - iterator

        :param user:     User object - user provides as well the searchfield
                                       entry
        :type  user:     User class
        :param serial:   serial number of a token
        :type  serial:   string
        :param page:     page number
        :type  page:     int
        :param psize:    how many entries per page
        :type  psize:    int
        :param filter:   additional condition
        :type  filter:   string
        :param sort:     sort field definition
        :type  sort:     string
        :param sortdir:  sort direction: ascending or descending
        :type  sortdir:  string
        :param filterRealm:  restrict the set of token to those in
                             the filterRealm
        :type  filterRealm:  string or list
        :param user_fields:  list of additional fields from the user owner
        :type  user_fields: array
        :param params:  list of additional request parameters
                        - currently not used
        :type  params: dict

        :return: - nothing / None

        '''
        log.debug('[TokenIterator::init] begin. start creating TokenIterator \
        class with parameters: user:%r, serial:%r, page=%r, psize:%r, \
                    filter:%r, sort:%r, sortdir:%r, filterRealm:%r' %
                (user, serial, page, psize, filter, sort, sortdir,
                 filterRealm))

        if params is None:
            params = {}

        self.page = 1
        self.pages = 1
        self.tokens = 0
        self.user_fields = user_fields
        if self.user_fields == None:
            self.user_fields = []

        condition = None
        ucondition = None
        scondition = None
        r_condition = None

        if type(filterRealm) in (str, unicode):
            filterRealm = filterRealm.split(',')

        if type(filterRealm) in [list]:
            s_realms = []
            for f in filterRealm:
                #  support for multiple realm filtering in the ui
                #  as a coma separated string
                for s_realm in f.split(','):
                    s_realms.append(s_realm.strip())
            filterRealm = s_realms

        #  create a list of all realms, which are allowed to be searched
        #  based on the list of the existing ones
        valid_realms = []
        realms = getRealms().keys()
        if '*' in filterRealm:
            valid_realms.append("*")
        else:
            for realm in realms:
                if realm in filterRealm:
                    realm = linotp.lib.crypt.uencode(realm)
                    valid_realms.append(realm)

        if serial is not None:
            #  check if the requested serial is in the realms of
            # the admin (filterRealm)
            log.debug('[TokenIterator::init] start search for serial: >%r<'
                       % (serial))

            allowed = False
            if filterRealm == ['*']:
                allowed = True
            else:
                realms = getTokenRealms(serial)
                for realm in realms:
                    if realm in filterRealm:
                        allowed = True

            if allowed == True:
                if '*' in serial:
                    serial = serial.replace('*', '%')
                    scondition = and_(Token.LinOtpTokenSerialnumber.like(serial))
                else:
                    scondition = and_(Token.LinOtpTokenSerialnumber == serial)

        if user.isEmpty() == False and user is not None:
            log.debug('[TokenIterator::init] start search for username: >%r<'
                      % (user))

            if user.login is not None and (user.login) > 0 :
                loginUser = user.login.lower()
                loginUser = loginUser.replace('"', '')
                loginUser = loginUser.replace("'", '')

                searchType = "any"

                #  search for a 'blank' user
                if len(loginUser) == 0 and len(user.login) > 0:
                    searchType = "blank"
                elif loginUser == "/:no user:/" or loginUser == "/:none:/":
                    searchType = "blank"
                elif loginUser == "/:no user info:/":
                    searchType = "wildcard"
                elif "*" in loginUser or "." in loginUser:
                    searchType = "wildcard"
                else:
                    #  no blank and no wildcard search
                    searchType = "exact"

                if searchType == "blank":
                    log.debug('[TokenIterator::init] search for empty user:'******' >%r<' % (user.login))
                    ucondition = and_(or_(Token.LinOtpUserid == u'',
                                          Token.LinOtpUserid == None))

                if searchType == "exact":
                    log.debug('[TokenIterator::init] search for exact user:'******' %r' % (user))
                    serials = []
                    users = []

                    #  if search for a realmuser 'user@realm' we can take the
                    #  realm from the argument
                    if len(user.realm) > 0:
                        users.append(user)
                    else:
                        for realm in valid_realms:
                            users.append(User(user.login, realm))

                    # resolve the realm with wildcard:
                    # identify all users and add these to the userlist
                    userlist = []
                    for usr in users:
                        urealm = usr.realm
                        if urealm == '*':
                            # if the realm is set to *, the getUserId
                            # triggers the identification of all resolvers,
                            # where the user might reside: tigger the user
                            # resolver lookup
                            (uid, resolver, resolverClass) = getUserId(usr)
                            userlist.extend(usr.getUserPerConf())
                        else:
                            userlist.append(usr)

                    for usr in userlist:
                        try:
                            tokens = getTokens4UserOrSerial(user=usr, _class=False)
                            for tok in tokens:
                                serials.append(tok.LinOtpTokenSerialnumber)
                        except UserError as ex:
                            #  we get an exception if the user is not found
                            log.debug('[TokenIterator::init] no exact user: %r'
                                      % (user))
                            log.debug('[TokenIterator::init] %r' % ex)
                    if len(serials) > 0:
                        # if tokens found, search for their serials
                        ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
                    else:
                        # if no token is found, block search for user
                        # and return nothing
                        ucondition = and_(Token.LinOtpTokenSerialnumber == u'')

                #  handle case, when nothing found in former cases
                if searchType == "wildcard":
                    log.debug('[TokenIterator::init] wildcard search: %r' % (user))
                    serials = []
                    users = getAllTokenUsers()
                    logRe = None
                    lU = loginUser.replace('*', '.*')
                    # lU = lU.replace('..', '.')
                    logRe = re.compile(lU)

                    for ser in users:
                        userInfo = users.get(ser)
                        tokenUser = userInfo.get('username').lower()
                        try:
                            if logRe.match(u'' + tokenUser) is not None:
                                serials.append(ser)
                        except Exception as e:
                            log.error('error no express %r ' % e)

                    #  to prevent warning, we check is serials are found
                    #  SAWarning: The IN-predicate on
                    #  "Token.LinOtpTokenSerialnumber" was invoked with an
                    #  empty sequence. This results in a contradiction, which
                    #  nonetheless can be expensive to evaluate.  Consider
                    #  alternative strategies for improved performance.
                    if len(serials) > 0:
                        ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
                    else:
                        ucondition = and_(Token.LinOtpTokenSerialnumber == u'')

        if filter is None:
            condition = None
        elif filter in ['/:active:/', '/:enabled:/',
                        '/:token is active:/', '/:token is enabled:/' ]:
            condition = and_(Token.LinOtpIsactive == True)
        elif filter in ['/:inactive:/', '/:disabled:/',
                        '/:token is inactive:/', '/:token is disabled:/']:
            condition = and_(Token.LinOtpIsactive == False)
        else:
            #  search in other colums
            filter = linotp.lib.crypt.uencode(filter)
            condition = or_(Token.LinOtpTokenDesc.contains(filter),
                            Token.LinOtpIdResClass.contains(filter),
                            Token.LinOtpTokenSerialnumber.contains(filter),
                            Token.LinOtpUserid.contains(filter),
                            Token.LinOtpTokenType.contains(filter))

        ###################################################################
        #   The condition for only getting certain realms!
        if '*' in valid_realms:
            log.debug("[TokenIterator::init] wildcard for realm '*' found."
                      " Tokens of all realms will be displayed")
        elif len(valid_realms) > 0:
            log.debug("[TokenIterator::init] adding filter condition"
                      " for realm %r" % valid_realms)

            #  get all matching realms
            realm_id_tuples = Session.query(Realm.id).\
                                filter(Realm.name.in_(valid_realms)).all()
            realm_ids = set()
            for realm_tuple in realm_id_tuples:
                realm_ids.add(realm_tuple[0])
            #  get all tokenrealm ids
            token_id_tuples = Session.query(TokenRealm.token_id).\
                        filter(TokenRealm.realm_id.in_(realm_ids)).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            #  define the token id condition
            r_condition = and_(Token.LinOtpTokenId.in_(token_ids))

        elif ("''" in filterRealm or '""' in filterRealm or
              "/:no realm:/" in filterRealm):
            log.debug("[TokenIterator::init] search for all tokens, which are"
                      " in no realm")

            #  get all tokenrealm ids
            token_id_tuples = Session.query(TokenRealm.token_id).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            #  define the token id not condition
            r_condition = and_(not_(Token.LinOtpTokenId.in_(token_ids)))

        #  create the final condition as AND of all conditions
        condTuple = ()
        for conn in (condition, ucondition, scondition, r_condition):
            if type(conn).__name__ != 'NoneType':
                condTuple += (conn,)

        condition = and_(*condTuple)

        order = Token.LinOtpTokenDesc

        if sort == "TokenDesc":
            order = Token.LinOtpTokenDesc
        elif sort == "TokenId":
            order = Token.LinOtpTokenId
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "TokenSerialnumber":
            order = Token.LinOtpTokenSerialnumber
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "IdResClass":
            order = Token.LinOtpIdResClass
        elif sort == "IdResolver":
            order = Token.LinOtpIdResolver
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "FailCount":
            order = Token.LinOtpFailCount
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "Isactive":
            order = Token.LinOtpIsactive

        #  care for the result sort order
        if sortdir is not None and sortdir == "desc":
            order = order.desc()
        else:
            order = order.asc()

        #  care for the result pageing
        if page is None:
            self.toks = Session.query(Token).filter(condition).order_by(order).distinct()
            self.tokens = self.toks.count()

            log.debug("[TokenIterator] DB-Query returned # of objects:"
                      " %i" % self.tokens)
            self.pagesize = self.tokens
            self.it = iter(self.toks)
            return

        try:
            if psize is None:
                pagesize = int(getFromConfig("pagesize", 50))
            else:
                pagesize = int(psize)
        except:
            pagesize = 20

        try:
            thePage = int (page) - 1
        except:
            thePage = 0
        if thePage < 0:
            thePage = 0

        start = thePage * pagesize
        stop = (thePage + 1) * pagesize

        self.toks = Session.query(Token).filter(condition).\
                                         order_by(order).distinct()
        self.tokens = self.toks.count()
        log.debug("[TokenIterator::init] DB-Query returned # of objects:"
                  " %i" % self.tokens)
        self.page = thePage + 1
        fpages = float(self.tokens) / float(pagesize)
        self.pages = int(fpages)
        if fpages - int(fpages) > 0:
            self.pages = self.pages + 1
        self.pagesize = pagesize
        self.toks = self.toks.slice(start, stop)

        self.it = iter(self.toks)

        log.debug('[TokenIterator::init] end. Token iterator created: %r' % \
                  (self.it))

        return
Exemple #46
0
    def create_context(self, request, environment):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        # make the request id available in the request context
        request_context['RequestId'] = environment['REQUEST_ID']

        # a request local cache to get the user info from the resolver
        request_context['UserLookup'] = {}

        # a request local cache to get the resolver from user and realm
        request_context['UserRealmLookup'] = {}

        request_context['Config'] = linotp_config
        request_context['Policies'] = parse_policies(linotp_config)
        request_context['translate'] = translate
        request_context['CacheManager'] = environment['beaker.cache']

        routes = environment.get('pylons.routes_dict', {})
        path = "/%s/%s" % (routes['controller'], routes['action'])
        request_context['Path'] = path

        request_context['hsm'] = self.hsm

        initResolvers()

        client = None
        try:
            client = get_client(request=request)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Client'] = client

        request_context['Audit'] = Audit
        request_context['audit'] = Audit.initialize(request, client=client)

        authUser = None
        try:
            authUser = getUserFromRequest(request)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['AuthUser'] = authUser
        request_context['UserLookup'] = {}

        # ------------------------------------------------------------------ --
        # get the current resolvers

        resolvers = []
        try:
            resolvers = getResolverList(config=linotp_config)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Resolvers'] = resolvers

        # ------------------------------------------------------------------ --
        # get the current realms

        realms = {}
        try:
            realms = getRealms()
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Realms'] = realms

        # ------------------------------------------------------------------ --

        defaultRealm = ""
        try:
            defaultRealm = getDefaultRealm(linotp_config)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['defaultRealm'] = defaultRealm

        # ------------------------------------------------------------------ --
        # load the requesting user

        from linotp.useridresolver.UserIdResolver import (
            ResolverNotAvailable)

        requestUser = None
        try:
            requestUser = getUserFromParam(self.request_params)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r", exx)
        except (ResolverNotAvailable, NoResolverFound) as exx:
            log.error("Failed to connect to server %r", exx)

        request_context['RequestUser'] = requestUser

        # ------------------------------------------------------------------ --
        # load the providers

        from linotp.provider import Provider_types
        from linotp.provider import getProvider

        provider = {}
        for provider_type in Provider_types.keys():
            provider[provider_type] = getProvider(provider_type)

        request_context['Provider'] = provider

        # ------------------------------------------------------------------ --

        # for the setup of encrypted data, we require the hsm is instatiated
        # and available in the request context

        if not self.secret_key:
            init_key_partition(linotp_config, partition=0)

        # ------------------------------------------------------------------ --

        # copy some system entries from pylons
        syskeys = {
            "radius.nas_identifier": "LinOTP",
            "radius.dictfile": "/etc/linotp2/dictionary"
        }

        sysconfig = {}
        for key, default in syskeys.items():
            sysconfig[key] = config.get(key, default)

        request_context['SystemConfig'] = sysconfig
Exemple #47
0
    def _get_user_condition(self, user, valid_realms):

        ucondition = None

        if not user or user.is_empty or not user.login:
            return ucondition

        loginUser = user.login.lower()
        loginUser = loginUser.replace('"', '')
        loginUser = loginUser.replace("'", '')

        searchType = "any"
        ## search for a 'blank' user
        if len(loginUser) == 0 and len(user.login) > 0:
            searchType = "blank"
        elif loginUser == "/:no user:/" or loginUser == "/:none:/":
            searchType = "blank"
        elif loginUser == "/:no user info:/":
            searchType = "wildcard"
        elif "*" in loginUser:
            searchType = "wildcard"
        else:
            ## no blank and no wildcard search
            searchType = "exact"

        if searchType == "blank":
            ucondition = and_(or_(Token.LinOtpUserid == u'',
                                  Token.LinOtpUserid is None))

        if searchType == "exact":
            serials = []
            users = []

            # if search for a realmuser 'user@realm' we can take the
            # realm from the argument
            if len(user.realm) > 0:
                users.append(user)
            else:
                # otherwise we add all users which are possible combinations
                # from loginname and entry of the valid realms.
                # In case of a '*' wildcard in the list, we take all available
                # realms
                if '*' in valid_realms:
                    valid_realm_list = getRealms().keys()
                else:
                    valid_realm_list = valid_realms

                for realm in valid_realm_list:
                    users.append(User(user.login, realm))

            # resolve the realm with wildcard:
            # identify all users and add these to the userlist
            userlist = []
            for usr in users:
                urealm = usr.realm
                if urealm == '*':
                    # if the realm is set to *, the getUserId
                    # triggers the identification of all resolvers, where the
                    # user might reside: trigger the user resolver lookup
                    for realm in getRealms().keys():
                        if realm in valid_realms or '*' in valid_realms:
                            usr.realm = realm
                            try:
                                (_uid, _resolver, _resolverClass) = getUserId(usr)
                            except UserError as exx:
                                log.info('User %r not found in realm %r',
                                         usr, realm)
                                continue
                            userlist.extend(usr.getUserPerConf())
                else:
                    userlist.append(usr)

            for usr in userlist:
                try:
                    tokens = getTokens4UserOrSerial(user=usr, _class=False)
                    for tok in tokens:
                        serials.append(tok.LinOtpTokenSerialnumber)
                except UserError as ex:
                    ## we get an exception if the user is not found
                    log.debug('[TokenIterator::init] no exact user: %r'
                              % (user))
                    log.debug('[TokenIterator::init] %r' % ex)

            if len(serials) > 0:
                # if tokens found, search for their serials
                ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
            else:
                # if no token is found, block search for user
                # and return nothing
                ucondition = and_(Token.LinOtpTokenSerialnumber == u'')

        ## handle case, when nothing found in former cases
        if searchType == "wildcard":

            serials = _user_expression_match(loginUser, token_owner_iterator())

            # to prevent warning, we check is serials are found
            # SAWarning: The IN-predicate on
            # "Token.LinOtpTokenSerialnumber" was invoked with an
            # empty sequence. This results in a contradiction, which
            # nonetheless can be expensive to evaluate.  Consider
            # alternative strategies for improved performance.

            if len(serials) > 0:
                ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
            else:
                ucondition = and_(Token.LinOtpTokenSerialnumber == u'')
        return ucondition
Exemple #48
0
    def _get_user_condition(self, user, valid_realms):

        ucondition = None

        if not user or user.is_empty or not user.login:
            return ucondition

        loginUser = user.login.lower()
        loginUser = loginUser.replace('"', '')
        loginUser = loginUser.replace("'", '')

        searchType = "any"
        ## search for a 'blank' user
        if len(loginUser) == 0 and len(user.login) > 0:
            searchType = "blank"
        elif loginUser == "/:no user:/" or loginUser == "/:none:/":
            searchType = "blank"
        elif loginUser == "/:no user info:/":
            searchType = "wildcard"
        elif "*" in loginUser:
            searchType = "wildcard"
        else:
            ## no blank and no wildcard search
            searchType = "exact"

        if searchType == "blank":
            ucondition = and_(or_(Token.LinOtpUserid == u'',
                                  Token.LinOtpUserid is None))

        if searchType == "exact":
            serials = []
            users = []

            # if search for a realmuser 'user@realm' we can take the
            # realm from the argument
            if len(user.realm) > 0:
                users.append(user)
            else:
                # otherwise we add all users which are possible combinations
                # from loginname and entry of the valid realms.
                # In case of a '*' wildcard in the list, we take all available
                # realms
                if '*' in valid_realms:
                    valid_realm_list = getRealms().keys()
                else:
                    valid_realm_list = valid_realms

                for realm in valid_realm_list:
                    users.append(User(user.login, realm))

            # resolve the realm with wildcard:
            # identify all users and add these to the userlist
            userlist = []
            for usr in users:
                urealm = usr.realm
                if urealm == '*':
                    # if the realm is set to *, the getUserId
                    # triggers the identification of all resolvers, where the
                    # user might reside: trigger the user resolver lookup
                    for realm in getRealms().keys():
                        if realm in valid_realms or '*' in valid_realms:
                            usr.realm = realm
                            try:
                                (_uid, _resolver, _resolverClass) = getUserId(usr)
                            except UserError as exx:
                                log.info('User %r not found in realm %r',
                                         usr, realm)
                                continue
                            userlist.extend(usr.getUserPerConf())
                else:
                    userlist.append(usr)

            for usr in userlist:
                try:
                    tokens = getTokens4UserOrSerial(user=usr, _class=False)
                    for tok in tokens:
                        serials.append(tok.LinOtpTokenSerialnumber)
                except UserError as ex:
                    ## we get an exception if the user is not found
                    log.debug('[TokenIterator::init] no exact user: %r'
                              % (user))
                    log.debug('[TokenIterator::init] %r' % ex)

            if len(serials) > 0:
                # if tokens found, search for their serials
                ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
            else:
                # if no token is found, block search for user
                # and return nothing
                ucondition = and_(Token.LinOtpTokenSerialnumber == u'')

        ## handle case, when nothing found in former cases
        if searchType == "wildcard":

            serials = _user_expression_match(loginUser, token_owner_iterator())

            # to prevent warning, we check is serials are found
            # SAWarning: The IN-predicate on
            # "Token.LinOtpTokenSerialnumber" was invoked with an
            # empty sequence. This results in a contradiction, which
            # nonetheless can be expensive to evaluate.  Consider
            # alternative strategies for improved performance.

            if len(serials) > 0:
                ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
            else:
                ucondition = and_(Token.LinOtpTokenSerialnumber == u'')
        return ucondition
Exemple #49
0
def getUserId(user):
    """
    getUserId (userObject)

    return (uid,resId,resIdC)
    """

    uid = ''
    loginUser = u''
    loginUser = user.login;

    resolvers = '';
    realms = getRealms();

    # Get the first resolver they're present in, because UID is independent of realm.
    for key, v in realms.items():
        resolvers = getResolversOfUser(User(user.login, v['realmname'], ""))
        if (resolvers):
            break;

    for reso in resolvers:
        resId = ""
        resIdC = ""
        conf = ""
        uid = user.getResolverUId(reso)
        if uid != '':
            (resId, resIdC, conf) = user.getResolverConf(reso)
            break

        (package, module, class_, conf) = splitResolver(reso)

        if len(user.conf) > 0:
            if conf.lower() != user.conf.lower():
                continue

        ## try to load the UserIdResolver Class
        try:
            module = package + "." + module
            log.debug("[getUserId] Getting resolver class: [%r] [%r]"
                       % (module, class_))
            y = getResolverObject(reso)
            log.debug("[getUserId] Getting UserID for user %r"
                        % loginUser)
            uid = y.getUserId(loginUser)
            log.debug("[getUserId] Got UserId for user %r: %r"
                        % (loginUser, uid))

            log.debug("[getUserId] Retrieving ResolverID...")
            resId = y.getResolverId()

            resIdC = reso
            log.debug("[getUserId] Got ResolverID: %r, Loginuser: %r, "
                      "Uid: %r ]" % (resId, loginUser, uid))

            if uid != "":
                break;

        except Exception as e:
            log.error("[getUserId] module %r: %r ]" % (module, e))
            continue

    if (uid == ''):
        log.warning("[getUserId] No uid found for the user >%r< in realm %r"
                    % (loginUser, user.realm))
        raise UserError(u"getUserId failed: no user >%s< found!"
                         % unicode(loginUser), id=1205)

    log.debug("[getUserId] we are done!")
    return (unicode(uid), unicode(resId), unicode(resIdC))
Exemple #50
0
def getResolversOfUser(user):
    '''
    This returns the list of the Resolvers of a user in a given realm.
    Usually this should only return one resolver

    input:
        user.login, user.realm

    returns:
        array of resolvers, the user was found in
    '''

    login = user.login
    realm = user.realm

    Resolvers = user.getResolvers()

    if len(Resolvers) > 0:
        return Resolvers

    if realm is None or realm == "":
        realm = getDefaultRealm()

    #if realm is None or realm=="" or login is None or login == "":
    #    log.error("[getResolversOfUser] You need to specify the name ( %s) and the realm (%s) of a user with conf %s" % (login, realm, user.conf))

    realms = getRealms();

    if user.conf != "":
        reso = getConf(realms, user.conf)
        if len(reso) > 0:
            Resolvers.append(reso)
    else:
        Realm_resolvers = getResolvers(User("", realm, ""))

        log.debug("[getResolversOfUser] check if user %r is in resolver %r"
                   % (login, Realm_resolvers))
        # Search for user in each resolver in the realm_
        for realm_resolver in Realm_resolvers:
            log.debug("[getResolversOfUser] checking in %r" % realm_resolver)

            (package, module, class_, conf) = splitResolver(realm_resolver)
            module = package + "." + module

            y = getResolverObject(realm_resolver)
            if y is None:
                log.error("[getResolversOfUser] [ module %r not found!]"
                                                                    % (module))

            try:
                log.debug("[getResolversOfUser] checking in module %r" % y)
                uid = y.getUserId(login)
                log.debug("[getResolversOfUser] type of uid: %s" % type(uid))
                log.debug("[getResolversOfUser] type of realm_resolver: %s" % type(realm_resolver))
                log.debug("[getResolversOfUser] type of login: %s" % type(login))
                if uid not in ["", None]:
                    log.debug("[getResolversOfUser] user %r found in resolver %r" % (login, realm_resolver))
                    log.debug("[getResolversOfUser] userid resolved to %r " % uid)

                    ## Unicode Madness:
                    ## This will break as soon as the unicode "uid" is put into a tuple
                    ## v = (login, realm_resolver, uid)
                    ## log.info("[getResolversOfUser] %s %s %s" % v)
                    resId = y.getResolverId();
                    resCId = realm_resolver
                    Resolvers.append(realm_resolver)
                    user.addResolverUId(realm_resolver, uid, conf, resId, resCId)
                else:
                    log.debug("[getResolversOfUser] user %r not found"
                              " in resolver %r" % (login, realm_resolver))
            except Exception as e:
                log.error("[getResolversOfUser] error searching user in"
                          " module %r:%r" % (module, e))
                log.error("[getResolversOfUser] %s" % traceback.format_exc())

            log.debug("[getResolversOfUser] Resolvers: %r" % Resolvers)

    log.debug("[getResolversOfUser] Found the user %r in %r" % (login, Resolvers))
    return Resolvers