Exemplo n.º 1
0
    def tokeninfo(self):
        """
        this returns the contents of /admin/show?serial=xyz in a html format
        """
        param = request.params

        try:
            serial = getParam(param, "serial", required)

            filterRealm = ""
            # check admin authorization
            res = checkPolicyPre("admin", "show", param)

            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 not pol["active"]:
                filterRealm = ["*"]

            log.info("[tokeninfo] admin >%s< may display the following realms: %s" % (res["admin"], filterRealm))
            log.info("[tokeninfo] displaying tokens: serial: %s", serial)

            toks = TokenIterator(User("", "", ""), serial, filterRealm=filterRealm)

            ### now row by row
            lines = []
            for tok in toks:
                lines.append(tok)
            if len(lines) > 0:

                c.tokeninfo = lines[0]
            else:
                c.tokeninfo = {}

            for k in c.tokeninfo:
                if "LinOtp.TokenInfo" == k:
                    try:
                        # Try to convert string to Dictionary
                        c.tokeninfo["LinOtp.TokenInfo"] = json.loads(c.tokeninfo["LinOtp.TokenInfo"])
                    except:
                        pass

            return render("/manage/tokeninfo.mako")

        except PolicyException as pe:
            log.error("[tokeninfo] Error during checking policies: %r" % pe)
            log.error("[tokeninfo] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, unicode(pe), 1)

        except Exception as e:
            log.error("[tokeninfo] failed! %r" % e)
            log.error("[tokeninfo] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, e)

        finally:
            Session.close()
            log.debug("[tokeninfo] done")
Exemplo n.º 2
0
    def activeUsers(self):
        """
        method:
            monitoring/activeUsers

        description:
            for each realm, display the resolvers and
            the number of users which have at least one assigned active token
            per resolver
            the 'total' gives the number of all users, which are in an allowed
            realm and own an active token
            users are conted per resolver (not per realm), so if resolver is in
            multiple realms and one user ons tokens in 2 realms, the user will
            be counted only once

        arguments:
            * realms - optional: takes realms, only information on these realms
                will be displayed
        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')

            monit_handl = MonitorHandler()

            policies = getAdminPolicies('activeUsers', scope='monitoring')

            realm_whitelist = []
            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handl.active_users_per_realm(a_realm)

            result['Realms'] = realm_info
            result['total'] = monit_handl.active_users_total(realms)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[resolvers] done')
Exemplo n.º 3
0
    def tokeninfo(self):
        '''
        this returns the contents of /admin/show?serial=xyz in a html format
        '''
        param = request.params

        try:
            serial = getParam(param, 'serial', required)

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

            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 not pol['active']:
                filterRealm = ["*"]

            log.info("[tokeninfo] admin >%s< may display the following realms: %s" % (res['admin'], filterRealm))
            log.info("[tokeninfo] displaying tokens: serial: %s", serial)

            toks = TokenIterator(User("", "", ""), serial, filterRealm=filterRealm)

            ### now row by row
            lines = []
            for tok in toks:
                lines.append(tok)
            if len(lines) > 0:

                c.tokeninfo = lines[0]
            else:
                c.tokeninfo = {}

            for k in c.tokeninfo:
                if "LinOtp.TokenInfo" == k:
                    try:
                        # Try to convert string to Dictionary
                        c.tokeninfo['LinOtp.TokenInfo'] = json.loads(c.tokeninfo['LinOtp.TokenInfo'])
                    except:
                        pass

            return render('/manage/tokeninfo.mako')

        except PolicyException as pe:
            log.error("[tokeninfo] Error during checking policies: %r" % pe)
            log.error("[tokeninfo] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, unicode(pe), 1)

        except Exception as e:
            log.error("[tokeninfo] failed! %r" % e)
            log.error("[tokeninfo] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, e)

        finally:
            Session.close()
            log.debug('[tokeninfo] done')
Exemplo n.º 4
0
    def activeUsers(self):
        """
        method:
            monitoring/activeUsers

        description:
            for each realm, display the resolvers and
            the number of users which have at least one assigned active token
            per resolver
            the 'total' gives the number of all users, which are in an allowed
            realm and own an active token
            users are conted per resolver (not per realm), so if resolver is in
            multiple realms and one user ons tokens in 2 realms, the user will
            be counted only once

        arguments:
            * realms - optional: takes realms, only information on these realms
                will be displayed
        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')

            monit_handl = MonitorHandler()

            policies = getAdminPolicies('activeUsers', scope='monitoring')

            realm_whitelist = []
            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handl.active_users_per_realm(
                    a_realm)

            result['Realms'] = realm_info
            result['total'] = monit_handl.active_users_total(realms)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemplo n.º 5
0
    def userinfo(self):
        """
        method:
            monitoring/userinfo

        description:
            for each realm, display the resolvers and the number of users
            per resolver

        arguments:
            * realms - optional: takes a realm, only information on this realm
                will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        """
        result = {}
        try:
            request_realms = self.request_params.get("realms", "").split(",")

            monit_handler = MonitorHandler()

            policies = getAdminPolicies("userinfo", scope="monitoring")

            realm_whitelist = []
            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            if "/:no realm:/" in realms:
                realms.remove("/:no realm:/")

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handler.resolverinfo(a_realm)

            result["Realms"] = realm_info

            db.session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemplo n.º 6
0
    def delete_all(self):
        """
        method:
            reporting/delete_all

        description:
            delete the reporting database table

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            if '*' in status:
                status.remove('*')
                status.extend(['active', 'inactive', 'assigned', 'unassigned',
                               'active&assigned', 'active&unassigned',
                               'inactive&assigned', 'inactive&unassigned',
                               'total'])

            result = delete(realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[delete_all] done')
Exemplo n.º 7
0
    def activeUsers(self):
        """
        method:
            monitoring/activeUsers

        description:
            for each realm, display the resolvers and
            the number of users which have at least one assigned active token
            per resolver
            the 'total' gives the number of all users, which are in an allowed
            realm and own an active token
            users are conted per resolver (not per realm), so if resolver is in
            multiple realms and one user ons tokens in 2 realms, the user will
            be counted only once

        arguments:
            * realms - optional: takes realms, only information on these realms
                will be displayed
        """
        result = {}
        try:
            request_realms = self.request_params.get("realms", "").split(",")

            monit_handl = MonitorHandler()

            policies = getAdminPolicies("activeUsers", scope="monitoring")

            realm_whitelist = []
            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handl.active_users_per_realm(
                    a_realm
                )

            result["Realms"] = realm_info
            result["total"] = monit_handl.active_users_total(realms)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemplo n.º 8
0
    def show(self):
        """
        method:
            reporting/show

        description:
            show entries from the reporting database table

        arguments:
        * date - optional: only show entries which are newer than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries are shown
        * realms - optional: takes realms, only the reporting entries
                from this realm are shown
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'
        * sortby  - optional: sort the output by column
        * sortdir - optional: asc/desc
        * page    - optional: reqeuest a certain page
        * pagesize - optional: limit the number of returned tokens
        * outform - optional: if set to "csv", the output will be a .csv file

        returns: a json result with:
            { "head": [],
            "data": [ [row1]
            , [row2]
            , [row3] .. ]
            }
        in case of csv:
        first line: header of columns
        other lines: column values


        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = self.request_params
            page = param.get('page')
            sort = param.get('sortby')
            sortdir = param.get('sortdir')
            psize = param.get('pagesize')
            output_format = param.get('outform', 'json')
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', [])
            border_day = param.get('date')

            if border_day:
                # this may throw ValueError if date is in wrong format
                datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('show', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            reports = ReportingIterator(realms=realms, status=status, date=None,
                                        page=page, psize=psize, sort=sort,
                                        sortdir=sortdir)
            info = reports.getResultSetInfo()

            c.audit['success'] = True
            Session.commit()

            if output_format == 'csv':
                response.content_type = "application/force-download"
                response.headers['Content-disposition'] = \
                    'attachment; filename=linotp-reports.csv'
                return sendCSVIterator(reports.iterate_reports())
            else:
                response.content_type = 'application/json'
                return sendResultIterator(reports.iterate_reports(), opt=info)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemplo n.º 9
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()
Exemplo n.º 10
0
    def show(self):
        """
        method:
            reporting/show

        description:
            show entries from the reporting database table

        arguments:
        * date - optional: only show entries which are newer than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries are shown
        * realms - optional: takes realms, only the reporting entries
                from this realm are shown
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'
        * sortby  - optional: sort the output by column
        * sortdir - optional: asc/desc
        * page    - optional: reqeuest a certain page
        * pagesize - optional: limit the number of returned tokens
        * outform - optional: if set to "csv", the output will be a .csv file

        returns: a json result with:
            { "head": [],
            "data": [ [row1]
            , [row2]
            , [row3] .. ]
            }
        in case of csv:
        first line: header of columns
        other lines: column values


        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = request.params
            page = param.get('page')
            sort = param.get('sortby')
            sortdir = param.get('sortdir')
            psize = param.get('pagesize')
            output_format = param.get('outform', 'json')
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', [])
            border_day = param.get('date')

            if border_day:
                # this may throw ValueError if date is in wrong format
                datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('show', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            reports = ReportingIterator(realms=realms,
                                        status=status,
                                        date=None,
                                        page=page,
                                        psize=psize,
                                        sort=sort,
                                        sortdir=sortdir)
            info = reports.getResultSetInfo()

            c.audit['success'] = True
            Session.commit()

            if output_format == 'csv':
                response.content_type = "application/force-download"
                response.headers['Content-disposition'] = \
                    'attachment; filename=linotp-reports.csv'
                return sendCSVIterator(reports.iterate_reports())
            else:
                response.content_type = 'application/json'
                return sendResultIterator(reports.iterate_reports(), opt=info)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemplo n.º 11
0
    def delete_before(self):
        """
        method:
            reporting/delete_before

        description:
            delete all entries from reporting database with respect to the
            arguments
            date must be given in format: 'yyyy-mm-dd'

        arguments:
        * date - optional: only delete entries which are older than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries get deleted
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:

            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            param = request.params
            border_day = param.get('date')

            # this may throw ValueError if date is in wrong format
            datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('delete_before', scope='reporting')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            result = delete(date=border_day, realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemplo n.º 12
0
    def delete_before(self):
        """
        method:
            reporting/delete_before

        description:
            delete all entries from reporting database with respect to the
            arguments
            date must be given in format: 'yyyy-mm-dd'

        arguments:
        * date - optional: only delete entries which are older than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries get deleted
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            request_realms = self.request_params.get('realms', '').split(',')
            status = self.request_params.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            border_day = self.request_params.get('date')

            # this may throw ValueError if date is in wrong format
            datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('delete_before', scope='reporting')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            result = delete(date=border_day, realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemplo n.º 13
0
    def userinfo(self):
        """
        method:
            monitoring/userinfo

        description:
            for each realm, display the resolvers and the number of users
            per resolver

        arguments:
            * realms - optional: takes a realm, only information on this realm
                will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler()

            policies = getAdminPolicies('userinfo', scope='monitoring')

            realm_whitelist = []
            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handler.resolverinfo(a_realm)

            result[_('Realms')] = realm_info

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[resolvers] done')
Exemplo n.º 14
0
    def delete_all(self):
        """
        method:
            reporting/delete_all

        description:
            delete entries from the reporting database table

        arguments:
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            request_realms = self.request_params.get("realms", "").split(",")
            status = self.request_params.get("status", ["total"])
            if status != ["total"]:
                status = status.split(",")

            realm_whitelist = []
            policies = getAdminPolicies("delete_all", scope="reporting.access")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            if "*" in status:
                status.remove("*")
                status.extend([
                    "active",
                    "inactive",
                    "assigned",
                    "unassigned",
                    "active&assigned",
                    "active&unassigned",
                    "inactive&assigned",
                    "inactive&unassigned",
                    "total",
                ])

            result = delete(realms=realms, status=status)
            db.session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemplo n.º 15
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 = request.params

        try:
            #serial  = getParam(param,"serial",optional)
            c.page = getParam(param, "page", optional)
            c.filter = getParam(param, "query", optional)
            c.qtype = getParam(param, "qtype", optional)
            c.sort = getParam(param, "sortname", optional)
            c.dir = getParam(param, "sortorder", optional)
            c.psize = getParam(param, "rp", optional)

            filter_all = None
            filter_realm = None
            user = User()

            if c.qtype == "loginname":
                if "@" in c.filter:
                    (login, realm) = c.filter.split("@")
                    user = User(login, realm)
                else:
                    user = User(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:
                # Arrange the table more helpfully.
                lines.append({
                    'id':
                    tok['LinOtp.TokenSerialnumber'],
                    'cell': [
                        tok['LinOtp.TokenSerialnumber'],
                        tok['LinOtp.TokenType'],
                        tok['LinOtp.TokenDesc'],
                        tok['LinOtp.Isactive'],
                        tok['User.username'],
                        tok['LinOtp.Userid'],
                        tok['LinOtp.FailCount'],
                        tok['LinOtp.MaxFail'],
                        tok['LinOtp.OtpLen'],
                        tok['LinOtp.CountWindow'],
                        tok['LinOtp.SyncWindow'],
                    ]
                })

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

            c.audit['success'] = True

            Session.commit()
            return json.dumps(res, indent=3)

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

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

        finally:
            Session.close()
            log.debug("[tokenview_flexi] done")
Exemplo n.º 16
0
    def userinfo(self):
        """
        method:
            monitoring/userinfo

        description:
            for each realm, display the resolvers and the number of users
            per resolver

        arguments:
            * realms - optional: takes a realm, only information on this realm
                will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler()

            policies = getAdminPolicies('userinfo', scope='monitoring')

            realm_whitelist = []
            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            if '/:no realm:/' in realms:
                realms.remove('/:no realm:/')

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handler.resolverinfo(a_realm)

            result['Realms'] = realm_info

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemplo n.º 17
0
    def maximum(self):
        """
        method:
            reporting/maximum

        description:
            return the maximum of tokens in a given realm with given status

        arguments:
            * realms - required: takes realms, only the reporting entries for
                this realms will be displayed
            * status - optional: (default is 'active')
                takes assigned/unassigned/active/ etc.
                and shows max of lines in database with this characteristic

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned

        :return:
        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            for realm in realms:
                for stat in status:
                    result[realm] = get_max(realm, stat)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[maximum] done')
Exemplo n.º 18
0
    def maximum(self):
        """
        method:
            reporting/maximum

        description:
            return the maximum of tokens in a given realm with given status

        arguments:
            * realms - required: takes realms, only the reporting entries for
                this realms will be displayed
            * status - optional: (default is 'active')
                takes assigned/unassigned/active/ etc.
                and shows max of lines in database with this characteristic

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned

        :return:
        """
        result = {}
        try:
            # ------------------------------------------------------------- --
            start = datetime(year=1970, month=1, day=1)

            _now = datetime.utcnow()
            end = datetime(year=_now.year, month=_now.month,
                           day=_now.day) + timedelta(days=1)
            # ------------------------------------------------------------- --

            request_realms = self.request_params.get("realms", "").split(",")
            status = self.request_params.get("status", ["total"])
            if status != ["total"]:
                status = status.split(",")

            realm_whitelist = []
            policies = getAdminPolicies("maximum", scope="reporting.access")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            for realm in realms:
                result[realm] = {}
                for stat in status:
                    result[realm][stat] = get_max_token_count_in_period(
                        realm, status=stat, start=start, end=end)
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)

        finally:
            db.session.close()
Exemplo n.º 19
0
    def show(self):
        """
        method:
            reporting/show

        description:
            show entries from the reporting database table

        arguments:
        * date - optional: only show entries which are newer than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries are shown
        * realms - optional: takes realms, only the reporting entries
                from this realm are shown
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'
        * sortby  - optional: sort the output by column
        * sortdir - optional: asc/desc
        * page    - optional: reqeuest a certain page
        * pagesize - optional: limit the number of returned tokens
        * outform - optional: if set to "csv", the output will be a .csv file

        returns: a json result with:
            { "head": [],
            "data": [ [row1]
            , [row2]
            , [row3] .. ]
            }
        in case of csv:
        first line: header of columns
        other lines: column values


        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = self.request_params
            page = param.get("page")
            sort = param.get("sortby")
            sortdir = param.get("sortdir")
            psize = param.get("pagesize")
            output_format = param.get("outform", "json")
            request_realms = param.get("realms", "").split(",")
            status = param.get("status", [])

            start_day = None
            if "date" in param:
                start_day = convert_to_datetime(param.get("date"), TIME_FMTS)

            realm_whitelist = []
            policies = getAdminPolicies("show", scope="reporting.access")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            reports = ReportingIterator(
                realms=realms,
                status=status,
                date=start_day,
                page=page,
                psize=psize,
                sort=sort,
                sortdir=sortdir,
            )
            info = reports.getResultSetInfo()

            g.audit["success"] = True
            db.session.commit()

            if output_format == "csv":
                headers = Headers()
                headers.add(
                    "Content-Disposition",
                    "attachment",
                    filename="linotp-reports.csv",
                )
                return Response(
                    stream_with_context(
                        sendCSVIterator(reports.iterate_reports())),
                    mimetype="text/csv",
                    headers=headers,
                )
            else:
                return Response(
                    stream_with_context(
                        sendResultIterator(reports.iterate_reports(),
                                           opt=info)),
                    mimetype="application/json",
                )

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except ValueError as value_error:
            log.error(value_error)
            db.session.rollback()
            return sendError(response, value_error, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemplo n.º 20
0
    def delete_before(self):
        """
        method:
            reporting/delete_before

        description:
            delete all entries from reporting database with respect to the
            arguments
            date must be given in format: 'yyyy-mm-dd'

        arguments:
        * date - optional: only delete entries which are older than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries get deleted
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            request_realms = self.request_params.get("realms", "").split(",")
            status = self.request_params.get("status", ["total"])
            if status != ["total"]:
                status = status.split(",")

            border_day = self.request_params.get("date")

            # this may throw ValueError if date is in wrong format
            datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies("delete_before", scope="reporting")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            result = delete(date=border_day, realms=realms, status=status)
            db.session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except ValueError as value_error:
            log.error(value_error)
            db.session.rollback()
            return sendError(response, value_error, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemplo n.º 21
0
    def tokens(self):
        """
        method:
            monitoring/tokens

        description:

            Displays the number of tokens (with status) per realm
            (one token might be in multiple realms).
            The Summary gives the sum of all tokens in all given realms and
            might be smaller than the summ of all tokens
            as tokens which have two realms are only counted once!

        arguments:
            * status - optional: takes assigned or unassigned, give the number
                of tokens with this characteristic

            * realms - optional: takes realms, only the number of tokens in
                these realms will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned
        """
        result = {}
        try:
            # extract and strip the list of requested statuses + default
            # statuses and ignore empty values.

            status_params = self.request_params.get("status", "").split(",")
            status = list(
                set(
                    ["total", "total users"]
                    + [s.strip() for s in status_params if s.strip()]
                )
            )

            request_realms = self.request_params.get("realms", "").split(",")

            monit_handler = MonitorHandler()
            realm_whitelist = []

            policies = getAdminPolicies("tokens", scope="monitoring")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                token_count = monit_handler.token_count([a_realm], status)
                realm_info[a_realm] = token_count

            result["Summary"] = monit_handler.token_count(realms, status)
            result["Realms"] = realm_info

            db.session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemplo n.º 22
0
    def show(self):
        """
        method:
            reporting/show

        description:
            show entries from the reporting database table

        arguments:
        * date - optional: only show entries which are newer than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries are shown
        * realms - optional: takes realms, only the reporting entries
                from this realm are shown
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }


        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', [])

            param = request.params
            border_day = param.get('date')

            if border_day:
                # this may throw ValueError if date is in wrong format
                datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('show', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            reports = ReportingIterator(realms=realms, status=status, date=None,
                                        page=None, psize=None, sort=None,
                                        sortdir=None)

            c.audit['success'] = True

            # put in the result
            result = {}

            # now row by row
            lines = []
            for rep in reports:
                # CKO:
                log.debug("tokenline: %s" % rep)
                lines.append(rep)

            result["data"] = lines
            result["resultset"] = reports.getResultSetInfo()

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[delete_before] done')
Exemplo n.º 23
0
    def period(self):
        """
        method:
            reporting/period

        description:
            return the maximum of tokens in a given realm with given status
            for a given period

        arguments:
            * realms - required: takes realms, only the reporting entries for
                this realms will be displayed
            * status - optional: (default is 'active')
                takes assigned/unassigned/active/ etc.
                and shows max of lines in database with this characteristic
            * from - optional: (default is 1970-1-1)
                    the start day for the reporting max lookup
            * to - optional: (default is tomorow 0:0:0)
                    the end day for the reporting max lookup

        returns:
            a json result with:
            {
            "status": "true",
            "value": {
                realms: [ {}, {}],
                period: {
                    'from':
                    'to':
                }
            }
            with a realm entry {} as:
            {
            'realm': 'realmname',
            'tokencount': {
                'active': nn,

                }
            }

        exception:
            if an error occurs an exception is serialized and returned

        :return:
        """
        result = {}
        try:
            request_realms = self.request_params.get("realms", "").split(",")
            status = self.request_params.get("status", ["total"])
            if status != ["total"]:
                status = status.split(",")

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

            # handle start and stop
            # for backward compatibility start and stop are optional

            # if start is not given, we use the unix time start 1.1.1970

            start = datetime(year=1970, month=1, day=1)
            if "from" in self.request_params:
                start_str = self.request_params.get("from")
                start = convert_to_datetime(start_str, TIME_FMTS)

            # if end is not defined, we use tomorrow at 0:0:0

            _now = datetime.utcnow()
            end = datetime(year=_now.year, month=_now.month,
                           day=_now.day) + timedelta(days=1)
            if "to" in self.request_params:
                end_str = self.request_params.get("to")
                end = convert_to_datetime(end_str, TIME_FMTS)

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

            realm_whitelist = []
            policies = getAdminPolicies("period", scope="reporting.access")
            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = request_context["Realms"].keys()

            realms = match_realms(request_realms, realm_whitelist)

            result["realms"] = []
            for realm in realms:
                result_realm = {"name": realm}
                max_token_counts = {}
                for stat in status:

                    # search for the max token in the period [start : end]

                    max_token_stat = get_max_token_count_in_period(realm,
                                                                   status=stat,
                                                                   start=start,
                                                                   end=end)

                    # if none is found (-1) we search for the last entry
                    # before the period start

                    if max_token_stat == -1:
                        max_token_stat = get_last_token_count_before_date(
                            realm, status=stat, before_date=start)

                    max_token_counts[stat] = max_token_stat

                result_realm["maxtokencount"] = max_token_counts
                result["realms"].append(result_realm)

            result["period"] = {
                "from": start.isoformat(),
                "to": end.isoformat(),
            }

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemplo n.º 24
0
    def tokens(self):
        """
        method:
            monitoring/tokens

        description:

            Displays the number of tokens (with status) per realm
            (one token might be in multiple realms).
            The Summary gives the sum of all tokens in all given realms and
            might be smaller than the summ of all tokens
            as tokens which have two realms are only counted once!

        arguments:
            * status - optional: takes assigned or unassigned, give the number
                of tokens with this characteristic

            * realms - optional: takes realms, only the number of tokens in
                these realms will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned
        """
        result = {}
        try:
            param = request.params

            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')
                status.append('total')
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler()
            realm_whitelist = []

            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                token_count = monit_handler.token_count([a_realm], status)
                realm_info[a_realm] = token_count

            result['Summary'] = monit_handler.token_count(realms, status)
            result['Realms'] = realm_info

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemplo n.º 25
0
    def delete_before(self):
        """
        method:
            reporting/delete_before

        description:
            delete all entries from reporting database which are older than date
            date must be given in format: 'yyyy-mm-dd'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:

            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            param = request.params
            border_day = param.get('date')

            # this may throw ValueError if date is in wrong format
            datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            result = delete(date=border_day, realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[tokens] done')
Exemplo n.º 26
0
    def tokens(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:
            page = param.get("page", 1)
            qfilter = param.get("query")
            qtype = param.get("qtype", 'all')
            sort = param.get("sortname", )
            direction = param.get("sortorder", "desc")
            psize = param.get("rp", 20)

            filter_all = None
            filter_realm = None
            user = User()

            if 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=qfilter)

                if "*" not in qfilter and "@" in qfilter:

                    login, _, realm = qfilter.rpartition("@")

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

            elif qtype == "all":
                filter_all = qfilter

            elif qtype == "realm":
                filter_realm = qfilter

            # 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]

            tokenArray = TokenIterator(
                user, None, page, psize, filter_all, sort,
                direction, filterRealm=filterRealm)

            resultset = tokenArray.getResultSetInfo()
            # If we have chosen a page to big!
            lines = []
            for tok in 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(page),
                "total": resultset['tokens'],
                "rows": lines
            }

            c.audit['success'] = True
            Session.commit()
            return sendResult(response, res)

        except PolicyException as pex:
            log.exception("Error during checking policies")
            Session.rollback()
            return sendError(response, pex, 1)

        except Exception as exx:
            log.exception("tokens lookup failed!")
            Session.rollback()
            return sendError(response, exx)

        finally:
            Session.close()
Exemplo n.º 27
0
    def users(self):
        '''
        This function is used to fill the flexigrid.
        Unlike the complex /admin/userlist function, it only returns a
        simple array of the tokens.
        '''
        param = self.request_params

        try:

            page = param.get("page", 1)
            qfilter = param.get("query", '*') or '*'
            qtype = param.get("qtype", 'username')
            sort = param.get("sortname", 'username')
            direction = param.get("sortorder", 'asc')
            psize = param.get("rp", 20)

            user = getUserFromParam(param)

            realms = get_realms_from_params(
                param, getAdminPolicies('userlist', scope='admin'))

            uniqueUsers = {}
            for realm in realms:

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

                # check admin authorization: checkPolicyPre('admin',...

                # admin policies are special as they are acl which define
                # - for user (policy entry)
                # - the actions (policy entry)
                # - in the realm (policy entry)
                # is allowed. while the user.login is not evaluated, the
                # user.realm is.
                #
                # the admin policies are acls and are defined in contradiction
                # to the other policy scopes where actions are either defiend
                # for user or realm!!

                # so we have to check for every user.realm

                if isinstance(user, User):
                    user.realm = realm

                checkPolicyPre('admin', 'userlist', param=param, user=user)

                users_list = getUserList(
                    {qtype: qfilter, 'realm': realm}, user)

                # now create a unique list of users with the unique key of
                # userid + useridresolver

                for u in users_list:
                    pkey = u['userid'] + ':' + u['useridresolver']
                    user_realms = uniqueUsers.get(pkey, {}).get('realms', [])
                    user_realms.append(realm)
                    u['realms'] = user_realms
                    uniqueUsers[pkey] = u

            userNum = len(uniqueUsers)

            lines = []
            for u in uniqueUsers.values():
                # shorten the useridresolver, to get a better display value
                resolver_display = ""
                if "useridresolver" in u:
                    if len(u['useridresolver'].split(".")) > 3:
                        resolver_display = u['useridresolver'].split(
                            ".")[3] + " (" + u['useridresolver'].split(".")[1] + ")"
                    else:
                        resolver_display = u['useridresolver']
                lines.append(
                    {'id': u['username'],
                        'cell': [
                            (u['username']) if u.has_key('username') else (""),
                            (resolver_display),
                            (u['surname']) if u.has_key('surname') else (""),
                            (u['givenname']) if u.has_key(
                                'givenname') else (""),
                            (u['email']) if u.has_key('email') else (""),
                            (u['mobile']) if u.has_key('mobile') else (""),
                            (u['phone']) if u.has_key('phone') else (""),
                            (u['userid']) if u.has_key('userid') else (""),
                            (u['realms']),
                    ]
                    }
                )

            # sorting
            reverse = False
            sortnames = {
                'username': 0,
                'useridresolver': 1,
                'surname': 2,
                'givenname': 3,
                'email': 4,
                'mobile': 5,
                'phone': 6,
                'userid': 7
            }
            if direction == "desc":
                reverse = True

            lines = sorted(lines,
                           key=lambda user: user['cell'][sortnames[sort]],
                           reverse=reverse,
                           cmp=unicode_compare)

            # end: sorting

            # reducing the page
            if page and psize:
                page = int(page)
                psize = int(psize)
                start = psize * (page - 1)
                end = start + psize
                lines = lines[start:end]

            # We need to return 'page', 'total', 'rows'
            res = {
                "page": int(page),
                "total": userNum,
                "rows": lines
            }

            c.audit['success'] = True

            Session.commit()
            return sendResult(response, res)

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

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

        finally:
            Session.close()
Exemplo n.º 28
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 = request.params

        try:
            # serial  = getParam(param,"serial",optional)
            c.page = getParam(param, "page", optional)
            c.filter = getParam(param, "query", optional)
            c.qtype = getParam(param, "qtype", optional)
            c.sort = getParam(param, "sortname", optional)
            c.dir = getParam(param, "sortorder", optional)
            c.psize = getParam(param, "rp", optional)

            filter_all = None
            filter_realm = None
            user = User()

            if c.qtype == "loginname":
                if "@" in c.filter:
                    (login, realm) = c.filter.split("@")
                    user = User(login, realm)
                else:
                    user = User(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.IdResolver"],
                        ],
                    }
                )

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

            c.audit["success"] = True

            Session.commit()
            return json.dumps(res, indent=3)

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

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

        finally:
            Session.close()
            log.debug("[tokenview_flexi] done")
Exemplo n.º 29
0
    def maximum(self):
        """
        method:
            reporting/maximum

        description:
            return the maximum of tokens in a given realm with given status

        arguments:
            * realms - required: takes realms, only the reporting entries for
                this realms will be displayed
            * status - optional: (default is 'active')
                takes assigned/unassigned/active/ etc.
                and shows max of lines in database with this characteristic

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned

        :return:
        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('maximum', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            for realm in realms:
                result[realm] = {}
                for stat in status:
                    result[realm][stat] = get_max(realm, stat)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemplo n.º 30
0
    def tokens(self):
        """
        method:
            monitoring/tokens

        description:

            Displays the number of tokens (with status) per realm
            (one token might be in multiple realms).
            The Summary gives the sum of all tokens in all given realms and
            might be smaller than the summ of all tokens
            as tokens which have two realms are only counted once!

        arguments:
            * status - optional: takes assigned or unassigned, give the number
                of tokens with this characteristic

            * realms - optional: takes realms, only the number of tokens in
                these realms will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned
        """
        result = {}
        try:
            param = request.params

            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')
                status.append('total')
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler()
            realm_whitelist = []

            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                token_count = monit_handler.token_count([a_realm],
                                                        status)
                realm_info[a_realm] = token_count

            result[_('Summary')] = monit_handler.token_count(realms, status)
            result[_('Realms')] = realm_info

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[tokens] done')
Exemplo n.º 31
0
    def delete_all(self):
        """
        method:
            reporting/delete_all

        description:
            delete entries from the reporting database table

        arguments:
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('delete_all', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            if '*' in status:
                status.remove('*')
                status.extend([
                    'active', 'inactive', 'assigned', 'unassigned',
                    'active&assigned', 'active&unassigned',
                    'inactive&assigned', 'inactive&unassigned', 'total'
                ])

            result = delete(realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemplo n.º 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:
                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()
Exemplo n.º 33
0
    def delete_all(self):
        """
        method:
            reporting/delete_all

        description:
            delete entries from the reporting database table

        arguments:
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            request_realms = self.request_params.get('realms', '').split(',')
            status = self.request_params.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('delete_all', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            if '*' in status:
                status.remove('*')
                status.extend(['active', 'inactive', 'assigned', 'unassigned',
                               'active&assigned', 'active&unassigned',
                               'inactive&assigned', 'inactive&unassigned',
                               'total'])

            result = delete(realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()