Beispiel #1
0
def legacy_getPolicy(param, only_active=False):
    '''
    Function to retrieve the list of policies.

    attributes:

    - name:   (optional) will only return the policy with the name
    - user:   (optional) will only return the policies for this user
    - realm:  (optional) will only return the policies of this realm
    - scope:  (optional) will only return the policies within this scope
    - action: (optional) will only return the policies with this action
         The action can also be something like "otppin" and will
         return policies containing "otppin = 2"

    :return: a dictionary with the policies. The name of the policy being
             the key
    '''
    # log.debug("[getPolicy] params %s" % str(param))
    Policies = {}

    # First we load ALL policies from the Config
    lPolicies = get_copy_of_policies()

    if param.get('name', None):
        # If a named policy was requested, we add
        # the policy if the name does match case insensitiv
        p_name = param['name'].lower()
        for pol_name in lPolicies:
            if pol_name.lower() == p_name:
                Policies[pol_name] = lPolicies[pol_name]
    else:
        Policies = lPolicies

    # Now we need to clean up policies, that are inactive
    if not only_active:
        pol2delete = []
        for polname, policy in Policies.items():
            pol_active = policy.get("active", "True")
            if pol_active == "False":
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    # Now we need to clean up realms, that were not requested
    pol2delete = []
    if param.get('realm', None) is not None:
        # log.debug("[getPolicy] cleanup acccording to realm %s"
        #          % param["realm"])
        for polname, policy in Policies.items():
            delete_it = True
            # log.debug("[getPolicy] evaluating policy %s: %s"
            #          % (polname, str(policy)))
            if policy.get("realm") is not None:
                pol_realms = [
                    p.strip() for p in policy['realm'].lower().split(',')
                ]
                # log.debug("[getPolicy] realms in policy %s: %s"
                #          % (polname, str(pol_realms) ))
                for r in pol_realms:
                    # log.debug("[getPolicy] Realm: %s" % r)
                    if r == param['realm'].lower() or r == '*':
                        # log.debug( "[getPolicy] Setting delete_it to false.
                        # Se we are using policy: %s" % str(polname))
                        delete_it = False
            if delete_it:
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    pol2delete = []
    if param.get('scope', None) is not None:
        # log.debug("[getPolicy] cleanup acccording to scope %s"
        #          % param["scope"])
        for polname, policy in Policies.items():
            if policy['scope'].lower() != param['scope'].lower():
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    pol2delete = []
    if param.get('action', None) is not None:
        # log.debug("[getPolicy] cleanup acccording to action %s"
        #          % param["action"])
        param_action = param['action'].strip().lower()
        for polname, policy in Policies.items():
            delete_it = True
            # log.debug("[getPolicy] evaluating policy %s: %s"
            #          % (polname, str(policy)))
            if policy.get("action") is not None:
                pol_actions = [
                    p.strip()
                    for p in policy.get('action', "").lower().split(',')
                ]
                # log.debug("[getPolicy] actions in policy %s: %s "
                #          % (polname, str(pol_actions) ))
                for policy_action in pol_actions:
                    if policy_action == '*' or policy_action == param_action:
                        # If any action (*) or the exact action we are looking
                        # for matches, then keep the policy
                        # e.g. otppin=1 matches when we search for 'otppin=1'
                        delete_it = False
                    elif policy_action.split('=')[0].strip() == param_action:
                        # If the first part of the action matches then keep the
                        # policy
                        # e.g. otppin=1 matches when we search for 'otppin'
                        delete_it = False
                    else:
                        # No match, delete_it = True
                        pass
            if delete_it:
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    pol2delete = []
    wildcard_match = {}
    exact_user_match = {}
    wildcard_user_match = {}
    if param.get('user', None) is not None:
        # log.debug("cleanup acccording to user %s" % param["user"])
        for polname, policy in Policies.items():
            if policy.get('user'):
                pol_users = [
                    p.strip() for p in policy.get('user').lower().split(',')
                ]
                # log.debug("[getPolicy] users in policy %s: %s"
                #          % (polname, str(pol_users) ))
            else:
                log.error("Empty userlist in policy '%s' not supported!" %
                          polname)
                raise Exception(
                    "Empty userlist in policy '%s' not supported!" % polname)

            delete_it = True

            # first check of wildcard in users
            if '*' in pol_users:
                wildcard_match[polname] = policy
                delete_it = False

            # then check for direct name match
            if delete_it:
                if (param['user'].lower() in pol_users
                        or param['user'] in pol_users):
                    exact_user_match[polname] = policy
                    delete_it = False

            if delete_it:
                # we support the verification of the user,
                # to be in a resolver for the admin and system scope
                local_scope = param.get('scope', '').lower()
                if local_scope in [
                        'admin', 'system', 'monitoring', 'authentication',
                        'reporting.access'
                ]:

                    policy_users = policy.get('user', '').split(',')
                    userObj = User(login=param['user'])

                    if 'realm' in param:
                        userObj.realm = param['realm']
                    else:
                        import linotp.lib.realm
                        userObj.realm = linotp.lib.realm.getDefaultRealm()

                    # we do the extended user defintion comparison
                    res = _filter_admin_user(policy_users, userObj)
                    if res is True:
                        wildcard_user_match[polname] = policy
                        delete_it = False

            if delete_it:
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    # if we got policies and a user is defined on request
    if len(Policies) > 0:
        if exact_user_match:
            Policies = exact_user_match
            log.debug("getting exact user match %r for params %s",
                      exact_user_match, param)

        elif wildcard_user_match:
            Policies = wildcard_user_match
            log.debug("getting wildcard user match %r for params %s",
                      wildcard_user_match, param)

        elif wildcard_match:
            Policies = wildcard_match
            log.debug("getting wildcard user match %r for params %s",
                      wildcard_match, param)

    # only do the realm filtering if action was filtered before
    if 'action' in param:
        Policies = _post_realm_filter(Policies, param)

    log.debug("getting policies %s for params %s" % (Policies, param))
    return Policies
Beispiel #2
0
def _check_policy_impact(scope='',
                         action='',
                         active='True',
                         client='',
                         realm='',
                         time=None,
                         user=None,
                         name='',
                         enforce=False):
    """
    check if applying the policy will lock the user out
    """

    # Currently only system policies are checked
    if scope.lower() not in ['system']:
        return

    reason = ''
    no_system_write_policy = True
    active_system_policy = False

    pol = {
        'scope': scope,
        'action': action,
        'active': active,
        'client': client,
        'realm': realm,
        'user': user,
        'time': time
    }

    #
    # we need a copy of the policies as we want to modify them

    policies = get_copy_of_policies()

    # in case of a policy change exclude this one from comparison
    if name in policies:
        del policies[name]

    # add the new policy and check the constrains
    policies[name] = pol

    for policy in list(policies.values()):

        # do we have a system policy that is active?
        p_scope = policy['scope'].lower()
        p_active = policy['active'].lower()

        if p_scope == 'system' and p_active == 'true':
            active_system_policy = True

            # get the policy actions
            p_actions = []
            for act in policy.get('action', '').split(','):
                p_actions.append(act.strip())

            # check if there is a write in the actions
            if '*' in p_actions or 'write' in p_actions:
                no_system_write_policy = False
                break

    # for any system policy:
    # if no user is defined defined this can as well result in a lockout
    if not user.strip():
        reason = "no user defined for system policy %s!" % name
    # same for empty realm
    if not realm.strip():
        reason = "no realm defined for system policy %s!" % name

    # if there has been no system policy with write option
    # and there are active system policy left
    if no_system_write_policy and active_system_policy:
        reason = "no active system policy with 'write' permission defined!"

    if reason and enforce is False:
        raise PolicyWarning("Warning: potential lockout due to policy "
                            "defintion: %s" % reason)

    # admin policy could as well result in lockout
    return
Beispiel #3
0
def _check_policy_impact(scope='', action='', active='True',
                         client='', realm='', time=None, user=None, name='',
                         enforce=False):
    """
    check if applying the policy will lock the user out
    """

    # Currently only system policies are checked
    if scope.lower() not in ['system']:
        return

    reason = ''
    no_system_write_policy = True
    active_system_policy = False

    pol = {'scope': scope,
           'action': action,
           'active': active,
           'client': client,
           'realm': realm,
           'user': user,
           'time': time
           }

    #
    # we need a copy of the policies as we want to modify them

    policies = get_copy_of_policies()

    # in case of a policy change exclude this one from comparison
    if name in policies:
        del policies[name]

    # add the new policy and check the constrains
    policies[name] = pol

    for policy in policies.values():

        # do we have a system policy that is active?
        p_scope = policy['scope'].lower()
        p_active = policy['active'].lower()

        if p_scope == 'system' and p_active == 'true':
            active_system_policy = True

            # get the policy actions
            p_actions = []
            for act in policy.get('action', '').split(','):
                p_actions.append(act.strip())

            # check if there is a write in the actions
            if '*' in p_actions or 'write' in p_actions:
                no_system_write_policy = False
                break

    # for any system policy:
    # if no user is defined defined this can as well result in a lockout
    if not user.strip():
        reason = "no user defined for system policy %s!" % name
    # same for empty realm
    if not realm.strip():
        reason = "no realm defined for system policy %s!" % name

    # if there has been no system policy with write option
    # and there are active system policy left
    if no_system_write_policy and active_system_policy:
        reason = "no active system policy with 'write' permission defined!"

    if reason and enforce is False:
        raise PolicyWarning("Warning: potential lockout due to policy "
                "defintion: %s" % reason)

    # admin policy could as well result in lockout
    return
Beispiel #4
0
def legacy_getPolicy(param, only_active=True):
    '''
    Function to retrieve the list of policies.

    attributes:

    - name:   (optional) will only return the policy with the name
    - user:   (optional) will only return the policies for this user
    - realm:  (optional) will only return the policies of this realm
    - scope:  (optional) will only return the policies within this scope
    - action: (optional) will only return the policies with this action
         The action can also be something like "otppin" and will
         return policies containing "otppin = 2"

    :return: a dictionary with the policies. The name of the policy being
             the key
    '''
    # log.debug("[getPolicy] params %s" % str(param))
    Policies = {}

    # First we load ALL policies from the Config
    lPolicies = get_copy_of_policies()

    if param.get('name', None):
        # If a named policy was requested, we add
        # the policy if the name does match case insensitiv
        p_name = param['name'].lower()
        for pol_name in lPolicies:
            if pol_name.lower() == p_name:
                Policies[pol_name] = lPolicies[pol_name]
    else:
        Policies = lPolicies

    # Now we need to clean up policies, that are inactive
    if only_active:
        pol2delete = []
        for polname, policy in Policies.items():
            pol_active = policy.get("active", "True")
            if pol_active == "False":
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    # Now we need to clean up realms, that were not requested
    pol2delete = []
    if param.get('realm', None) is not None:
        # log.debug("[getPolicy] cleanup acccording to realm %s"
        #          % param["realm"])
        for polname, policy in Policies.items():
            delete_it = True
            # log.debug("[getPolicy] evaluating policy %s: %s"
            #          % (polname, str(policy)))
            if policy.get("realm") is not None:
                pol_realms = [p.strip()
                              for p in policy['realm'].lower().split(',')]
                # log.debug("[getPolicy] realms in policy %s: %s"
                #          % (polname, str(pol_realms) ))
                for r in pol_realms:
                    # log.debug("[getPolicy] Realm: %s" % r)
                    if r == param['realm'].lower() or r == '*':
                        # log.debug( "[getPolicy] Setting delete_it to false.
                        # Se we are using policy: %s" % str(polname))
                        delete_it = False
            if delete_it:
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    pol2delete = []
    if param.get('scope', None) is not None:
        # log.debug("[getPolicy] cleanup acccording to scope %s"
        #          % param["scope"])
        for polname, policy in Policies.items():
            if policy['scope'].lower() != param['scope'].lower():
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    pol2delete = []
    if param.get('action', None) is not None:
        # log.debug("[getPolicy] cleanup acccording to action %s"
        #          % param["action"])
        param_action = param['action'].strip().lower()
        for polname, policy in Policies.items():
            delete_it = True
            # log.debug("[getPolicy] evaluating policy %s: %s"
            #          % (polname, str(policy)))
            if policy.get("action") is not None:
                pol_actions = [p.strip()
                               for p in policy.get('action', "").
                               lower().split(',')]
                # log.debug("[getPolicy] actions in policy %s: %s "
                #          % (polname, str(pol_actions) ))
                for policy_action in pol_actions:
                    if policy_action == '*' or policy_action == param_action:
                        # If any action (*) or the exact action we are looking
                        # for matches, then keep the policy
                        # e.g. otppin=1 matches when we search for 'otppin=1'
                        delete_it = False
                    elif policy_action.split('=')[0].strip() == param_action:
                        # If the first part of the action matches then keep the
                        # policy
                        # e.g. otppin=1 matches when we search for 'otppin'
                        delete_it = False
                    else:
                        # No match, delete_it = True
                        pass
            if delete_it:
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    pol2delete = []
    wildcard_match = {}
    exact_user_match = {}
    wildcard_user_match = {}
    if param.get('user', None) is not None:
        # log.debug("cleanup acccording to user %s" % param["user"])
        for polname, policy in Policies.items():
            if policy.get('user'):
                pol_users = [p.strip()
                             for p in policy.get('user').lower().split(',')]
                # log.debug("[getPolicy] users in policy %s: %s"
                #          % (polname, str(pol_users) ))
            else:
                log.error("Empty userlist in policy '%s' not supported!"
                          % polname)
                raise Exception("Empty userlist in policy '%s' not supported!"
                                % polname)

            delete_it = True

            # first check of wildcard in users
            if '*' in pol_users:
                wildcard_match[polname] = policy
                delete_it = False

            # then check for direct name match
            if delete_it:
                if (param['user'].lower() in pol_users or
                   param['user'] in pol_users):
                    exact_user_match[polname] = policy
                    delete_it = False

            if delete_it:
                # we support the verification of the user,
                # to be in a resolver for the admin and system scope
                local_scope = param.get('scope', '').lower()
                if local_scope in ['admin', 'system', 'monitoring',
                                   'authentication',
                                   'reporting.access']:

                    policy_users = policy.get('user', '').split(',')
                    userObj = User(login=param['user'])

                    if 'realm' in param:
                        userObj.realm = param['realm']
                    else:
                        import linotp.lib.realm
                        userObj.realm = linotp.lib.realm.getDefaultRealm()

                    # we do the extended user defintion comparison
                    res = _filter_admin_user(policy_users, userObj)
                    if res is True:
                        wildcard_user_match[polname] = policy
                        delete_it = False

            if delete_it:
                pol2delete.append(polname)
        for polname in pol2delete:
            del Policies[polname]

    # if we got policies and a user is defined on request
    if len(Policies) > 0:
        if exact_user_match:
            Policies = exact_user_match
            log.debug("getting exact user match %r for params %s",
                      exact_user_match, param)

        elif wildcard_user_match:
            Policies = wildcard_user_match
            log.debug("getting wildcard user match %r for params %s",
                      wildcard_user_match, param)

        elif wildcard_match:
            Policies = wildcard_match
            log.debug("getting wildcard user match %r for params %s",
                      wildcard_match, param)

    # only do the realm filtering if action was filtered before
    if 'action' in param:
        Policies = _post_realm_filter(Policies, param)

    log.debug("getting policies %s for params %s" % (Policies, param))
    return Policies