示例#1
0
def set_global_policy(inst, basedn, log, args):
    log = log.getChild('set_global_policy')
    pwp_manager = PwPolicyManager(inst)
    attrs = _args_to_attrs(args, pwp_manager.arg_to_attr)
    pwp_manager.set_global_policy(attrs)

    print('Successfully updated global password policy')
示例#2
0
def create_user_policy(inst, basedn, log, args):
    log = log.getChild('create_user_policy')
    pwp_manager = PwPolicyManager(inst)
    attrs = _args_to_attrs(args, pwp_manager.arg_to_attr)
    pwp_manager.create_user_policy(args.DN[0], attrs)

    print('Successfully created user password policy')
def test_entry_has_restrictions(topology_st, password_policy, create_user):
    """Set 'nsslapd-pwpolicy-inherit-global: on' and 'passwordCheckSyntax: on'.
    Make sure that syntax rules work, if set them at both: cn=config and
    ou=people policy container.

    :id: 4bb0f474-17c1-40f7-aab4-4ddc17d019e8
    :setup: Standalone instance, test user,
            password policy entries for a subtree
    :steps:
        1. Bind as test user
        2. Switch 'nsslapd-pwpolicy-inherit-global: on'
        3. Switch 'passwordCheckSyntax: on'
        4. Set 'passwordMinLength: 9' to:
           cn=config and ou=people policy container
        5. Try to add user with a short password (<9)
        6. Try to add user with a long password (>9)
        7. Cleanup - remove temp users bound as DM
    :expectedresults:
        1. Bind should be successful
        2. nsslapd-pwpolicy-inherit-global should be successfully set
        3. passwordCheckSyntax should be successfully set
        4. passwordMinLength should be successfully set
        5. User should be rejected
        6. User should be rejected
        7. Operation should be successful
    """

    log.info('Set {} to {}'.format(ATTR_INHERIT_GLOBAL, 'on'))
    log.info('Set {} to {}'.format(ATTR_CHECK_SYNTAX, 'on'))
    topology_st.standalone.config.set(ATTR_INHERIT_GLOBAL, 'on')
    topology_st.standalone.config.set(ATTR_CHECK_SYNTAX, 'on')

    pwp = PwPolicyManager(topology_st.standalone)
    policy = pwp.get_pwpolicy_entry(OU_PEOPLE)
    policy.set('passwordMinLength', '9')

    # Wait a second for cn=config to apply
    time.sleep(1)
    check_attr_val(topology_st.standalone, ATTR_INHERIT_GLOBAL, 'on')
    check_attr_val(topology_st.standalone, ATTR_CHECK_SYNTAX, 'on')

    log.info('Bind as test user')
    topology_st.standalone.simple_bind_s(BN, PASSWORD)
    users = UserAccounts(topology_st.standalone, OU_PEOPLE, rdn=None)
    user_props = TEST_USER_PROPERTIES.copy()

    log.info('Try to add user with a short password (<9)')
    with pytest.raises(ldap.CONSTRAINT_VIOLATION):
        user_props.update({'cn': 'test0', 'userpassword': '******'})
        user = users.create(properties=user_props)

    log.info('Try to add user with a long password (>9)')
    user_props.update({'cn': 'test1', 'userpassword': '******'})
    user = users.create(properties=user_props)

    log.info('Bind as DM user')
    topology_st.standalone.simple_bind_s(DN_DM, PASSWORD)

    # Remove test user 1
    user.delete()
示例#4
0
def del_local_policy(inst, basedn, log, args):
    log = log.getChild('del_local_policy')
    targetdn = args.DN[0]
    policy_type = _get_policy_type(inst, targetdn)
    pwp_manager = PwPolicyManager(inst)
    pwp_manager.delete_local_policy(targetdn)
    print('Successfully deleted %s' % policy_type.lower())
示例#5
0
def _get_pw_policy(inst, targetdn, log, use_json=None):
    pwp_manager = PwPolicyManager(inst)
    policy_type = _get_policy_type(inst, targetdn)
    attr_list = pwp_manager.get_attr_list()
    if "global" in policy_type.lower():
        targetdn = 'cn=config'
        attr_list.extend(['passwordIsGlobalPolicy', 'nsslapd-pwpolicy_local'])
        attrs = inst.config.get_attrs_vals_utf8(attr_list)
    else:
        policy = pwp_manager.get_pwpolicy_entry(targetdn)
        targetdn = policy.dn
        attrs = policy.get_attrs_vals_utf8(attr_list)

    if use_json:
        print(json.dumps({"type": "entry", "pwp_type": policy_type, "dn": ensure_str(targetdn), "attrs": attrs}))
    else:
        if "global" in policy_type.lower():
            response = "Global Password Policy: cn=config\n------------------------------------\n"
        else:
            response = "Local {} Policy: {}\n------------------------------------\n".format(policy_type, targetdn)
        for key, value in list(attrs.items()):
            if len(value) == 0:
                value = ""
            else:
                value = value[0]
            response += "{}: {}\n".format(key, value)
        print(response)
示例#6
0
def change_pwp_parameter(topo, pwp, operation, to_do):
    """
    Will change password policy parameter
    """
    pwp1 = PwPolicyManager(topo.standalone)
    user = pwp1.get_pwpolicy_entry(f'{pwp},{DEFAULT_SUFFIX}')
    user.replace(operation, to_do)
示例#7
0
def _create_pwp(topo, instance):
    """
    Will  create pwp
    """
    policy_props = {}
    pwp = PwPolicyManager(topo.standalone)
    pwadm_locpol = pwp.create_subtree_policy(instance, policy_props)
    for attribute, value in [
        ('passwordexp', 'off'),
        ('passwordchange', 'off'),
        ('passwordmustchange', 'off'),
        ('passwordchecksyntax', 'off'),
        ('passwordinhistory', '6'),
        ('passwordhistory', 'off'),
        ('passwordlockout', 'off'),
        ('passwordlockoutduration', '3600'),
        ('passwordmaxage', '8640000'),
        ('passwordmaxfailure', '3'),
        ('passwordminage', '0'),
        ('passwordminlength', '6'),
        ('passwordresetfailurecount', '600'),
        ('passwordunlock', 'on'),
        ('passwordStorageScheme', 'CLEAR'),
        ('passwordwarning', '86400')
    ]:
        pwadm_locpol.add(attribute, value)
    return pwadm_locpol
示例#8
0
def create_subtree_policy(inst, basedn, log, args):
    log = log.getChild('create_subtree_policy')
    # Gather the attributes
    pwp_manager = PwPolicyManager(inst)
    attrs = _args_to_attrs(args, pwp_manager.arg_to_attr)
    pwp_manager.create_subtree_policy(args.DN[0], attrs)

    print('Successfully created subtree password policy')
示例#9
0
def _get_policy_type(inst, dn=None):
    pwp_manager = PwPolicyManager(inst)
    if dn is None:
        return "Global Password Policy"
    elif pwp_manager.is_subtree_policy(dn):
        return "Subtree Policy"
    else:
        return "User Policy"
示例#10
0
def add_ldapsubentry(server, parent):
    pwp = PwPolicyManager(server)
    policy_props = {'passwordStorageScheme': 'ssha',
                                'passwordCheckSyntax': 'on',
                                'passwordInHistory': '6',
                                'passwordChange': 'on',
                                'passwordMinAge': '0',
                                'passwordExp': 'off',
                                'passwordMustChange': 'off',}
    log.info('Create password policy for subtree {}'.format(parent))
    pwp.create_subtree_policy(parent, policy_props)
示例#11
0
def set_local_policy(inst, basedn, log, args):
    log = log.getChild('set_local_policy')
    targetdn = args.DN[0]
    pwp_manager = PwPolicyManager(inst)
    attrs = _args_to_attrs(args, pwp_manager.arg_to_attr)
    pwp_entry = pwp_manager.get_pwpolicy_entry(args.DN[0])
    policy_type = _get_policy_type(inst, targetdn)

    modlist = []
    for attr, value in attrs.items():
        modlist.append((attr, value))
    if len(modlist) > 0:
        pwp_entry.replace_many(*modlist)
    else:
        raise ValueError("There are no password policies to set")

    print('Successfully updated %s' % policy_type.lower())
示例#12
0
def _create_local_pwp(topo, instance):
    """
    For a subtree entry create a local policy
    """

    policy_props = {}
    pwp = PwPolicyManager(topo.standalone)
    pwadm_locpol = pwp.create_subtree_policy(instance, policy_props)
    for attribute, value in [
        ('pwdmustchange', 'on'),
        ('passwordTPRMaxUse', '3'),
        ('passwordTPRDelayExpireAt', '1800'),
        ('passwordTPRDelayValidFrom', '5'),
    ]:
        pwadm_locpol.add(attribute, value)
    log.info('Creating local policies for subtree {}'.format(instance))
    return pwadm_locpol
def password_policy(topology_st, create_user):
    """Set global password policy.
    Then, set fine-grained subtree level password policy
    to ou=People with no password syntax.

    Note: do not touch nsslapd-pwpolicy-inherit-global -- off by default
    """

    log.info('Enable fine-grained policy')
    pwp = PwPolicyManager(topology_st.standalone)
    policy_props = {
        'passwordMustChange': 'off',
        'passwordExp': 'off',
        'passwordMinAge': '0',
        'passwordChange': 'off',
        'passwordStorageScheme': 'ssha'
    }
    pwp.create_subtree_policy(OU_PEOPLE, policy_props)
    check_attr_val(topology_st.standalone, ATTR_INHERIT_GLOBAL, 'off')
    check_attr_val(topology_st.standalone, ATTR_CHECK_SYNTAX, 'off')
示例#14
0
def list_policies(inst, basedn, log, args):
    log = log.getChild('list_policies')

    if args.DN is None:
        # list all the password policies for all the backends
        targetdns = []
        backends = Backends(inst).list()
        for backend in backends:
            targetdns.append(backend.get_suffix())
    else:
        targetdns = [args.DN]

    if args.json:
        result = {'type': 'list', 'items': []}
    else:
        result = ""

    for targetdn in targetdns:
        # Verify target dn exists before getting started
        user_entry = Account(inst, targetdn)
        if not user_entry.exists():
            raise ValueError('The target entry dn does not exist')

        # User pwpolicy entry is under the container that is under the parent,
        # so we need to go one level up
        pwp_entries = PwPolicyEntries(inst, targetdn)
        pwp_manager = PwPolicyManager(inst)
        attr_list = list(pwp_manager.arg_to_attr.values())

        for pwp_entry in pwp_entries.list():
            dn_comps = ldap.dn.explode_dn(pwp_entry.get_attr_val_utf8_l('cn'))
            dn_comps.pop(0)
            entrydn = ",".join(dn_comps)
            policy_type = _get_policy_type(inst, entrydn)
            all_attrs = pwp_entry.get_attrs_vals_utf8(attr_list)
            attrs = {k: v for k, v in all_attrs.items() if len(v) > 0}
            if args.json:
                result['items'].append(
                    {
                        "dn": pwp_entry.dn,
                        "targetdn": entrydn,
                        "pwp_type": policy_type,
                        "basedn": pwp_entry.get_basedn(),
                        "attrs": attrs
                    }
                )
            else:
                result += "%s (%s)\n" % (entrydn, policy_type.lower())

    if args.json:
        print(json.dumps(result, indent=4))
    else:
        print(result)
示例#15
0
def test_change_pwd(topology_st, create_user, password_policy,
                    subtree_pwchange, user_pwchange, exception):
    """Verify that 'passwordChange' attr works as expected
    User should have a priority over a subtree.

    :id: 2c884432-2ba1-4662-8e5d-2cd49f77e5fa
    :parametrized: yes
    :setup: Standalone instance, a test user,
            password policy entries for a user and a subtree
    :steps:
        1. Set passwordChange on the user and the subtree
           to various combinations
        2. Bind as test user
        3. Try to change password
        4. Clean up - change the password to default while bound as DM
    :expectedresults:
        1. passwordChange should be successfully set
        2. Bind should be successful
        3. Subtree/User passwordChange - result, accordingly:
           off/on, on/on - success;
           on/off, off/off - UNWILLING_TO_PERFORM
        4. Operation should be successful
    """

    users = UserAccounts(topology_st.standalone, OU_PEOPLE, rdn=None)
    user = users.get(TEST_USER_NAME)

    log.info('Set passwordChange to "{}" - {}'.format(subtree_pwchange,
                                                      OU_PEOPLE))
    pwp = PwPolicyManager(topology_st.standalone)
    subtree_policy = pwp.get_pwpolicy_entry(OU_PEOPLE)
    subtree_policy.set('passwordChange', subtree_pwchange)

    time.sleep(1)

    log.info('Set passwordChange to "{}" - {}'.format(user_pwchange,
                                                      TEST_USER_DN))
    pwp2 = PwPolicyManager(topology_st.standalone)
    user_policy = pwp2.get_pwpolicy_entry(TEST_USER_DN)
    user_policy.set('passwordChange', user_pwchange)
    user_policy.set('passwordExp', 'on')

    time.sleep(1)

    try:
        log.info('Bind as user and modify userPassword')
        user.rebind(TEST_USER_PWD)
        if exception:
            with pytest.raises(exception):
                user.reset_password('new_pass')
        else:
            user.reset_password('new_pass')
    except ldap.LDAPError as e:
        log.error('Failed to change userpassword for {}: error {}'.format(
            TEST_USER_DN, e.args[0]['info']))
        raise e
    finally:
        log.info('Bind as DM')
        topology_st.standalone.simple_bind_s(DN_DM, PASSWORD)
        user.reset_password(TEST_USER_PWD)
示例#16
0
def _get_pw_policy(inst, targetdn, log, use_json=None):
    pwp_manager = PwPolicyManager(inst)
    policy_type = _get_policy_type(inst, targetdn)
    attr_list = list(pwp_manager.arg_to_attr.values())
    if "global" in policy_type.lower():
        targetdn = 'cn=config'
        policydn = targetdn
        basedn = targetdn
        attr_list.extend(['passwordisglobalpolicy', 'nsslapd-pwpolicy_local'])
        all_attrs = inst.config.get_attrs_vals_utf8(attr_list)
        attrs = {k: v for k, v in all_attrs.items() if len(v) > 0}
    else:
        policy = pwp_manager.get_pwpolicy_entry(targetdn)
        basedn = policy.get_basedn()
        policydn = policy.dn
        all_attrs = policy.get_attrs_vals_utf8(attr_list)
        attrs = {k: v for k, v in all_attrs.items() if len(v) > 0}
    if use_json:
        print(json.dumps({
            "dn": ensure_str(policydn),
            "targetdn": targetdn,
            "type": "entry",
            "pwp_type": policy_type,
            "basedn": basedn,
            "attrs": attrs}, indent=4))
    else:
        if "global" in policy_type.lower():
            response = "Global Password Policy: cn=config\n------------------------------------\n"
        else:
            response = "Local {} Policy for \"{}\": {}\n------------------------------------\n".format(policy_type, targetdn, policydn)
        for key, value in list(attrs.items()):
            if len(value) == 0:
                value = ""
            else:
                value = value[0]
            response += "{}: {}\n".format(key, value)
        print(response)
示例#17
0
def password_policy(topology_st, create_user):
    """Set up password policy for subtree and user"""

    pwp = PwPolicyManager(topology_st.standalone)
    policy_props = {}
    log.info('Create password policy for subtree {}'.format(OU_PEOPLE))
    pwp.create_subtree_policy(OU_PEOPLE, policy_props)

    log.info('Create password policy for user {}'.format(TEST_USER_DN))
    pwp.create_user_policy(TEST_USER_DN, policy_props)
示例#18
0
def test_pwd_min_age(topology_st, create_user, password_policy):
    """If we set passwordMinAge to some value, for example to 10, then it
    should not allow the user to change the password within 10 seconds after
    his previous change.

    :id: 85b98516-8c82-45bd-b9ec-90bd1245e09c
    :setup: Standalone instance, a test user,
            password policy entries for a user and a subtree
    :steps:
        1. Set passwordMinAge to 10 on the user pwpolicy entry
        2. Set passwordMinAge to 10 on the subtree pwpolicy entry
        3. Set passwordMinAge to 10 on the cn=config entry
        4. Bind as test user
        5. Try to change the password two times in a row
        6. Wait 12 seconds
        7. Try to change the password
        8. Clean up - change the password to default while bound as DM
    :expectedresults:
        1. passwordMinAge should be successfully set on the user pwpolicy entry
        2. passwordMinAge should be successfully set on the subtree pwpolicy entry
        3. passwordMinAge should be successfully set on the cn=config entry
        4. Bind should be successful
        5. The password should be successfully changed
        6. 12 seconds have passed
        7. Constraint Violation error should be raised
        8. Operation should be successful
    """

    num_seconds = '10'
    users = UserAccounts(topology_st.standalone, OU_PEOPLE, rdn=None)
    user = users.get(TEST_USER_NAME)

    log.info('Set passwordminage to "{}" - {}'.format(num_seconds, OU_PEOPLE))
    pwp = PwPolicyManager(topology_st.standalone)
    subtree_policy = pwp.get_pwpolicy_entry(OU_PEOPLE)
    subtree_policy.set('passwordminage', num_seconds)

    log.info('Set passwordminage to "{}" - {}'.format(num_seconds,
                                                      TEST_USER_DN))
    user_policy = pwp.get_pwpolicy_entry(TEST_USER_DN)
    user_policy.set('passwordminage', num_seconds)

    log.info('Set passwordminage to "{}" - {}'.format(num_seconds, DN_CONFIG))
    topology_st.standalone.config.set('passwordminage', num_seconds)

    time.sleep(1)

    log.info('Bind as user and modify userPassword')
    user.rebind(TEST_USER_PWD)
    user.reset_password('new_pass')

    time.sleep(1)

    log.info(
        'Bind as user and modify userPassword straight away after previous change'
    )
    user.rebind('new_pass')
    with pytest.raises(ldap.CONSTRAINT_VIOLATION):
        user.reset_password('new_new_pass')

    log.info('Wait {} second'.format(int(num_seconds) + 2))
    time.sleep(int(num_seconds) + 2)

    try:
        log.info('Bind as user and modify userPassword')
        user.rebind('new_pass')
        user.reset_password(TEST_USER_PWD)
    except ldap.LDAPError as e:
        log.error('Failed to change userpassword for {}: error {}'.format(
            TEST_USER_DN, e.args[0]['info']))
        raise e
    finally:
        log.info('Bind as DM')
        topology_st.standalone.simple_bind_s(DN_DM, PASSWORD)
        user.reset_password(TEST_USER_PWD)
示例#19
0
def test_ticket49039(topo):
    """Test "password must change" verses "password min age".  Min age should not
    block password update if the password was reset.
    """

    # Setup SSL (for ldappasswd test)
    topo.standalone.enable_tls()

    # Configure password policy
    try:
        policy = PwPolicyManager(topo.standalone)
        policy.set_global_policy(
            properties={
                'nsslapd-pwpolicy-local': 'on',
                'passwordMustChange': 'on',
                'passwordExp': 'on',
                'passwordMaxAge': '86400000',
                'passwordMinAge': '8640000',
                'passwordChange': 'on'
            })
    except ldap.LDAPError as e:
        log.fatal('Failed to set password policy: ' + str(e))

    # Add user, bind, and set password
    try:
        topo.standalone.add_s(
            Entry((USER_DN, {
                'objectclass': 'top extensibleObject'.split(),
                'uid': 'user1',
                'userpassword': PASSWORD
            })))
    except ldap.LDAPError as e:
        log.fatal('Failed to add user: error ' + e.args[0]['desc'])
        assert False

    # Reset password as RootDN
    try:
        topo.standalone.modify_s(
            USER_DN,
            [(ldap.MOD_REPLACE, 'userpassword', ensure_bytes(PASSWORD))])
    except ldap.LDAPError as e:
        log.fatal('Failed to bind: error ' + e.args[0]['desc'])
        assert False

    time.sleep(1)

    # Reset password as user
    try:
        topo.standalone.simple_bind_s(USER_DN, PASSWORD)
    except ldap.LDAPError as e:
        log.fatal('Failed to bind: error ' + e.args[0]['desc'])
        assert False

    try:
        topo.standalone.modify_s(
            USER_DN,
            [(ldap.MOD_REPLACE, 'userpassword', ensure_bytes(PASSWORD))])
    except ldap.LDAPError as e:
        log.fatal('Failed to change password: error ' + e.args[0]['desc'])
        assert False

    ###################################
    # Make sure ldappasswd also works
    ###################################

    # Reset password as RootDN
    try:
        topo.standalone.simple_bind_s(DN_DM, PASSWORD)
    except ldap.LDAPError as e:
        log.fatal('Failed to bind as rootdn: error ' + e.args[0]['desc'])
        assert False

    try:
        topo.standalone.modify_s(
            USER_DN,
            [(ldap.MOD_REPLACE, 'userpassword', ensure_bytes(PASSWORD))])
    except ldap.LDAPError as e:
        log.fatal('Failed to bind: error ' + e.args[0]['desc'])
        assert False

    time.sleep(1)

    # Run ldappasswd as the User.
    os.environ["LDAPTLS_CACERTDIR"] = topo.standalone.get_cert_dir()
    cmd = ('ldappasswd' + ' -h ' + topo.standalone.host + ' -Z -p 38901 -D ' +
           USER_DN + ' -w password -a password -s password2 ' + USER_DN)
    os.system(cmd)
    time.sleep(1)

    try:
        topo.standalone.simple_bind_s(USER_DN, "password2")
    except ldap.LDAPError as e:
        log.fatal('Failed to bind: error ' + e.args[0]['desc'])
        assert False

    log.info('Test Passed')