Example #1
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')
Example #2
0
    def storageEncryption(self):
        """
        check if hsm/enckey encrypts value before storing it to config db
        :return: true if a new value gets encryptet before beeing stored in db
        """
        try:
            if hasattr(c, "hsm") is False or isinstance(c.hsm, dict) is False:
                raise HSMException("no hsm defined in execution context!")

            hsm = c.hsm.get("obj")
            if hsm is None or hsm.isReady() is False:
                raise HSMException("hsm not ready!")

            hsm_class = str(type(hsm))
            enc_type = hsm_class.split(".")[-1]
            enc_type = enc_type.strip("'>")
            enc_name = hsm.name
            res = {"cryptmodul_type": enc_type, "cryptmodul_name": enc_name}

            monit_handler = MonitorHandler()
            res["encryption"] = monit_handler.check_encryption()

            return sendResult(response, res, 1)

        except Exception as exception:
            log.error(exception)
            return sendError(response, exception)
Example #3
0
    def storageEncryption(self):
        """
        check if hsm/enckey encrypts value before storing it to config db
        :return: true if a new value gets encryptet before beeing stored in db
        """
        try:
            if hasattr(c, 'hsm') == False or isinstance(c.hsm, dict) == False:
                raise HSMException('no hsm defined in execution context!')

            hsm = c.hsm.get('obj')
            if hsm is None or hsm.isReady() == False:
                raise HSMException('hsm not ready!')

            hsm_class = str(type(hsm))
            enc_type = hsm_class.split('.')[-1]
            enc_type = enc_type.strip("'>")
            enc_name = hsm.name
            res = {'cryptmodul_type': enc_type, 'cryptmodul_name': enc_name}

            monit_handler = MonitorHandler()
            res['encryption'] = monit_handler.check_encryption()

            return sendResult(response, res, 1)

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

        finally:
            Session.close()
            log.debug('[encryption] done')
Example #4
0
def token_reporting(event, tokenrealms):
    """
    log token events into reporting table

    :param event: the event that happened, e.g. init token, delete token
    :param tokenrealms: the realm on which the event happened
    :return: nothing
    """
    realms = tokenrealms
    if not tokenrealms or len(tokenrealms) == 0:
        realms = ['/:no realm:/']
    elif not isinstance(tokenrealms, (list, tuple)):
        realms = [tokenrealms]

    for realm in realms:
        action = check_token_reporting(realm)
        mh = MonitorHandler()
        counters = mh.token_count(realm, action[:])
        for key, val in counters.items():
            report = Reporting(
                event=event, realm=realm, parameter=key, count=val)
            try:
                Session.add(report)
            except Exception as exce:
                log.exception('[save]Error during saving Report: %r' % exce)
Example #5
0
def token_reporting(event, tokenrealms):
    """
    log token events into reporting table

    :param event: the event that happened, e.g. init token, delete token
    :param tokenrealms: the realm on which the event happened
    :return: nothing
    """
    realms = tokenrealms
    if not tokenrealms or len(tokenrealms) == 0:
        realms = ['/:no realm:/']
    elif not isinstance(tokenrealms, (list, tuple)):
        realms = [tokenrealms]

    for realm in realms:
        action = check_token_reporting(realm)
        mh = MonitorHandler()
        counters = mh.token_count(realm, action[:])
        for key, val in counters.items():
            report = Reporting(event=event,
                               realm=realm,
                               parameter=key,
                               count=val)
            try:
                Session.add(report)
            except Exception as exce:
                log.exception('Error during saving report. Exception was: '
                              '%r' % exce)
Example #6
0
    def storageEncryption(self):
        """
        check if hsm/enckey encrypts value before storing it to config db
        :return: true if a new value gets encryptet before beeing stored in db
        """
        try:
            if hasattr(c, 'hsm') is False or isinstance(c.hsm, dict) is False:
                raise HSMException('no hsm defined in execution context!')

            hsm = c.hsm.get('obj')
            if hsm is None or hsm.isReady() is False:
                raise HSMException('hsm not ready!')

            hsm_class = str(type(hsm))
            enc_type = hsm_class.split('.')[-1]
            enc_type = enc_type.strip("'>")
            enc_name = hsm.name
            res = {'cryptmodul_type': enc_type, 'cryptmodul_name': enc_name}

            monit_handler = MonitorHandler()
            res['encryption'] = monit_handler.check_encryption()

            return sendResult(response, res, 1)

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

        finally:
            Session.close()
Example #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:
            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()
Example #8
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)
Example #9
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)
Example #10
0
    def license(self):
        """
        license
        return the support status, which is community support by default
        or the support subscription info, which could be the old license
        :return: json result with license info
        """
        res = {}
        try:
            try:
                license_info, license_sig = getSupportLicenseInfo()
            except InvalidLicenseException as err:
                if err.type != 'UNLICENSED':
                    raise err
                opt = {'valid': False,
                       'message': "%r" % err
                       }
                return sendResult(response, {}, 1, opt=opt)

            # Add Extra info
            # if needed; use details = None ... for no details!)...
            license_ok, license_msg = verifyLicenseInfo(license_info,
                                                        license_sig)
            if not license_ok:
                details = {'valid': license_ok,
                           'message': license_msg
                           }
            else:
                details = {'valid': license_ok}

                res['token-num'] = int(license_info.get('token-num', 0))

                # get all active tokens from all realms (including norealm)
                monit_handler = MonitorHandler()
                active_tokencount = monit_handler.get_active_tokencount()
                res['token-active'] = active_tokencount

                res['token-left'] = res['token-num'] - active_tokencount

            return sendResult(response, res, 1, opt=details)

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

        finally:
            Session.close()
            log.debug('[license] done')
Example #11
0
    def encryption(self):
        """
        check if hsm encrypts value before storing it to config db
        :return:
        """
        try:
            monit_handler = MonitorHandler(context=self.request_context)
            res = {'encryption': monit_handler.check_encryption()}

            return sendResult(response, res, 1)

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

        finally:
            Session.close()
            log.debug('[__after__] done')
Example #12
0
    def encryption(self):
        """
        check if hsm encrypts value before storing it to config db
        :return:
        """
        try:
            monit_handler = MonitorHandler(context=self.request_context)
            res = {'encryption': monit_handler.check_encryption()}

            return sendResult(response, res, 1)

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

        finally:
            Session.close()
            log.debug('[__after__] done')
Example #13
0
    def license(self):
        """
        license
        return the support status, which is community support by default
        or the support subscription info, which could be the old license
        :return: json result with license info
        """
        res = {}
        try:
            try:
                license_info, license_sig = getSupportLicenseInfo()
            except InvalidLicenseException as err:
                if err.type != 'UNLICENSED':
                    raise err
                opt = {'valid': False, 'message': "%r" % err}
                return sendResult(response, {}, 1, opt=opt)

            # Add Extra info
            # if needed; use details = None ... for no details!)...
            license_ok, license_msg = verifyLicenseInfo(
                license_info, license_sig)
            if not license_ok:
                res = {'valid': license_ok, 'message': license_msg}
            else:
                details = {'valid': license_ok}

                res['token-num'] = int(license_info.get('token-num', 0))

                # get all active tokens from all realms (including norealm)
                monit_handler = MonitorHandler()
                active_tokencount = monit_handler.get_active_tokencount()
                res['token-active'] = active_tokencount

                res['token-left'] = res['token-num'] - active_tokencount

            return sendResult(response, res, 1)

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

        finally:
            Session.close()
            log.debug('[license] done')
Example #14
0
    def config(self):
        """
        check if Config- Database exists

        touches DB and checks if date of last read is new
        :return:
            a json result with:
            { "head": [],
            "value": {"sync": "True"}
            }

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

            monit_handler = MonitorHandler()
            result = monit_handler.get_sync_status()

            # useful counts:
            counts = monit_handler.get_config_info()

            result.update(counts)

            ldap = 13 * result['ldapresolver']
            sql = 12 * result['sqlresolver']
            policies = 7 * result['policies']
            realms = result['realms']
            passwd = result['passwdresolver']
            total = result['total']

            result['netto'] = total - ldap - sql - passwd - policies - realms

            return sendResult(response, result)

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

        finally:
            Session.close()
            log.debug('[config] done')
Example #15
0
    def config(self):
        """
        check if Config- Database exists

        touches DB and checks if date of last read is new
        :return:
            a json result with:
            { "head": [],
            "value": {"sync": "True"}
            }

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

            monit_handler = MonitorHandler()
            result = monit_handler.get_sync_status()

            # useful counts:
            counts = monit_handler.get_config_info()

            result.update(counts)

            ldap = 13 * result['ldapresolver']
            sql = 12 * result['sqlresolver']
            policies = 7 * result['policies']
            realms = result['realms']
            passwd = result['passwdresolver']
            total = result['total']

            result['netto'] = total - ldap - sql - passwd - policies - realms

            return sendResult(response, result)

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

        finally:
            Session.close()
            log.debug('[config] done')
Example #16
0
    def config(self):
        """
        check if Config- Database exists

        touches DB and checks if date of last read is new
        :return:
            a json result with:
            { "head": [],
            "value": {"sync": "True"}
            }

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

            monit_handler = MonitorHandler()
            result = monit_handler.get_sync_status()

            # useful counts:
            counts = monit_handler.get_config_info()

            result.update(counts)

            ldap = 13 * result["ldapresolver"]
            sql = 12 * result["sqlresolver"]
            policies = 7 * result["policies"]
            realms = result["realms"]
            passwd = result["passwdresolver"]
            total = result["total"]

            result["netto"] = total - ldap - sql - passwd - policies - realms

            return sendResult(response, result)

        except Exception as exception:
            log.error(exception)
            return sendError(response, exception)
Example #17
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()
            realm_whitelist = monit_handler.get_allowed_realms(action='userinfo')

            # by default we show all allowed realms
            realms = realm_whitelist

            # support for empty realms or no realms by realm = *
            if '*' in request_realms:
                realms.append('/:no realm:/')
            # other cases, we iterate through the realm list
            elif len(request_realms) > 0 and not (request_realms == ['']):
                realms = []
                invalid_realms = []
                for search_realm in request_realms:
                    search_realm = search_realm.strip()
                    if search_realm in realm_whitelist:
                        realms.append(search_realm)
                    elif search_realm == '/:no realm:/':
                        realms.append(search_realm)
                    else:
                        invalid_realms.append(search_realm)
                if not realms and invalid_realms:
                    raise PolicyException(_('You do not have the rights to '
                                            'monitor these realms: %r. '
                                            'Check the policies!')
                                          % invalid_realms)

            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')
Example #18
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')
Example #19
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()
Example #20
0
    def tokens(self):
        """
        method:
            monitoring/tokens

        description:
            displays the number of the available tokens per realm

        arguments:
            * status - optional: takes assigned or unassigned, give the number
                of tokens with this characteristic
            * realms - optional: takes a realm, only the number of tokens in
                this realm 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')
            # do NOT initialize status  with ''
            if status:
                status = status.split(',')
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler(context=self.request_context)
            realm_whitelist = monit_handler.get_allowed_realms()

            # by default we show all allowed realms
            realms = realm_whitelist

            # support for empty realms or no realms by realm = *
            if '*' in request_realms:
                realms = realm_whitelist
                realms.append('/:no realm:/')
            # other cases, we iterate through the realm list
            elif len(request_realms) > 0 and not (request_realms == ['']):
                realms = []
                invalid_realms = []
                for search_realm in request_realms:
                    search_realm = search_realm.strip()
                    if search_realm in realm_whitelist:
                        realms.append(search_realm)
                    elif search_realm == '/:no realm:/':
                        realms.append(search_realm)
                    else:
                        invalid_realms.append(search_realm)
                if not realms and invalid_realms:
                    raise PolicyException(_('You do not have the rights to '
                                            'monitor these realms: %r. '
                                            'Check the policies!')
                                          % invalid_realms)

            # if there was realm or no argument given:
            totals = {}
            realm_info = {}
            for a_realm in realms:
                realm_dict = {}

                token_count = monit_handler.token_per_realm_count(a_realm,
                                                                  status)
                for key in token_count.keys():
                    realm_dict[key] = token_count[key]
                    totals[key] = totals.get(key, 0) + token_count[key]

                realm_info[a_realm] = realm_dict

            result[_('Summary')] = totals
            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')
Example #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:
            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()
Example #22
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)
Example #23
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')
Example #24
0
    def tokens(self):
        """
        method:
            monitoring/tokens

        description:
            displays the number of the available tokens per realm

        arguments:
            * status - optional: takes assigned or unassigned, give the number
                of tokens with this characteristic
            * realms - optional: takes a realm, only the number of tokens in
                this realm 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')
            # do NOT initialize status  with ''
            if status:
                status = status.split(',')
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler(context=self.request_context)
            realm_whitelist = monit_handler.get_allowed_realms()

            # by default we show all allowed realms
            realms = realm_whitelist

            # support for empty realms or no realms by realm = *
            if '*' in request_realms:
                realms = realm_whitelist
                realms.append('/:no realm:/')
            # other cases, we iterate through the realm list
            elif len(request_realms) > 0 and not (request_realms == ['']):
                realms = []
                invalid_realms = []
                for search_realm in request_realms:
                    search_realm = search_realm.strip()
                    if search_realm in realm_whitelist:
                        realms.append(search_realm)
                    elif search_realm == '/:no realm:/':
                        realms.append(search_realm)
                    else:
                        invalid_realms.append(search_realm)
                if not realms and invalid_realms:
                    raise PolicyException(
                        _('You do not have the rights to '
                          'monitor these realms: %r. '
                          'Check the policies!') % invalid_realms)

            # if there was realm or no argument given:
            totals = {}
            realm_info = {}
            for a_realm in realms:
                realm_dict = {}

                token_count = monit_handler.token_per_realm_count(
                    a_realm, status)
                for key in token_count.keys():
                    realm_dict[key] = token_count[key]
                    totals[key] = totals.get(key, 0) + token_count[key]

                realm_info[a_realm] = realm_dict

            result[_('Summary')] = totals
            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')