Esempio n. 1
0
def setup(topo, request):
    """Add schema, and test user
    """
    log.info('Add custom schema...')
    try:
        ATTR_1 = (b"( 1.3.6.1.4.1.409.389.2.189 NAME 'x-department' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'user defined' )")
        ATTR_2 = (b"( 1.3.6.1.4.1.409.389.2.187 NAME 'x-en-ou' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'user defined' )")
        OC = (b"( xPerson-oid NAME 'xPerson' DESC '' SUP person STRUCTURAL MAY ( x-department $ x-en-ou ) X-ORIGIN 'user defined' )")
        topo.standalone.modify_s("cn=schema", [(ldap.MOD_ADD, 'attributeTypes', ATTR_1),
                                               (ldap.MOD_ADD, 'attributeTypes', ATTR_2),
                                               (ldap.MOD_ADD, 'objectClasses', OC)])
    except ldap.LDAPError as e:
        log.fatal('Failed to add custom schema')
        raise e
    time.sleep(1)

    log.info('Add test user...')
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)

    user_properties = {
        'uid': 'test_user',
        'cn': 'test user',
        'sn': 'user',
        'uidNumber': '1000',
        'gidNumber': '2000',
        'homeDirectory': '/home/test_user',
        'seeAlso': 'cn=cosTemplate,dc=example,dc=com'
    }
    user = users.create(properties=user_properties)

    user.add('objectClass', 'xPerson')

    # Setup COS
    log.info("Setup indirect COS...")
    setup_indirect_cos(topo)
Esempio n. 2
0
def test_gecos_directoryString(topology_st):
    """Check that gecos supports directoryString value

    :id: aee422bb-6299-4124-b5cd-d7393dac19d3

    :setup: Standalone instance

    :steps:
        1. Add a common user
        2. replace gecos with a direstoryString value

    :expectedresults:
        1. Success
        2. Success
    """

    users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)

    user_properties = {
        'uid': 'testuser',
        'cn': 'testuser',
        'sn': 'user',
        'uidNumber': '1000',
        'gidNumber': '2000',
        'homeDirectory': '/home/testuser',
    }
    testuser = users.create(properties=user_properties)

    # Add a gecos UTF value
    testuser.replace('gecos', 'Hélène')
Esempio n. 3
0
def add_group_and_perform_user_operations(topology_st):
    topo = topology_st.standalone

    # Add the automember group
    groups = Groups(topo, DEFAULT_SUFFIX)
    group = groups.create(properties={'cn': 'group'})

    ous = OrganizationalUnits(topo, DEFAULT_SUFFIX)
    branch1 = ous.create(properties={'ou': 'branch1'})

    # Add the automember config entry
    am_configs = AutoMembershipDefinitions(topo)
    am_config = am_configs.create(properties={'cn': 'config',
                                              'autoMemberScope': branch1.dn,
                                              'autoMemberFilter': 'objectclass=top',
                                              'autoMemberDefaultGroup': group.dn,
                                              'autoMemberGroupingAttr': 'member:dn'})

    # Add a user that should get added to the group
    users = UserAccounts(topo, DEFAULT_SUFFIX, rdn='ou={}'.format(branch1.rdn))
    test_user = users.create_test_user(uid=777)

    # Check if created user is group member
    assert test_user.dn in group.list_members()

    log.info('Renaming user')
    test_user.rename('uid=new_test_user_777', newsuperior=SUFFIX)

    log.info('Delete the user')
    delete_obj(test_user)

    log.info('Delete automember entry, org. unit and group for the next test')
    delete_obj(am_config)
    delete_obj(branch1)
    delete_obj(group)
Esempio n. 4
0
def create_user(topology_st, request):
    """User for binding operation"""

    log.info('Adding user simplepaged_test')

    users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
    user = users.create(properties={
        'uid': 'simplepaged_test',
        'cn': 'simplepaged_test',
        'sn': 'simplepaged_test',
        'uidNumber': '1234',
        'gidNumber': '1234',
        'homeDirectory': '/home/simplepaged_test',
        'userPassword': TEST_USER_PWD,
    })

    # Now add the ACI so simplepage_test can read the users ...
    ACI_BODY = ensure_bytes('(targetattr= "uid || sn || dn")(version 3.0; acl "Allow read for user"; allow (read,search,compare) userdn = "ldap:///all";)')
    topology_st.standalone.modify_s(DEFAULT_SUFFIX, [(ldap.MOD_REPLACE, 'aci', ACI_BODY)])

    def fin():
        log.info('Deleting user simplepaged_test')
        user.delete()

    request.addfinalizer(fin)

    return user
Esempio n. 5
0
def test_entry_with_lots_100_attributes(topo, test_uer, aci_of_user):
    """Search Test 39 entry with lots (>100) attributes

    :id: fc155f74-6e12-11e8-96ac-8c16451d917b
    :setup: Standalone Instance
    :steps:
        1. Add Entry
        2. Bind with test USER_ANUJ
        3. Try search
        4. Delete Entry,test USER_ANUJ, ACI
    :expectedresults:
        1. Operation should success
        3. Operation should success
        4. Operation should success
        5. Operation should success
    """
    for i in range(100):
        user = UserAccounts(topo.standalone, DEFAULT_SUFFIX,
                            rdn='ou=People').create_test_user(uid=i)
        user.set("userPassword", "password")

    conn = UserAccount(
        topo.standalone,
        "uid=test_user_1,ou=People,{}".format(DEFAULT_SUFFIX)).bind(PW_DM)
    # no aci no blockage
    assert 1 == len(Accounts(conn, DEFAULT_SUFFIX).filter('(cn=Anuj*)'))
    # no aci no blockage
    assert 103 == len(Accounts(conn, DEFAULT_SUFFIX).filter('(uid=*)'))
    conn = Anonymous(topo.standalone).bind()
    # anonymous_search_on_monitor_entry
    assert 103 == len(Accounts(conn, DEFAULT_SUFFIX).filter('(uid=*)'))
Esempio n. 6
0
def test_account_locking(topology):
    """
    Ensure that user and group management works as expected.
    """
    users = UserAccounts(topology.standalone, DEFAULT_SUFFIX)

    user_properties = {
        'uid': 'testuser',
        'cn': 'testuser',
        'sn': 'user',
        'uidNumber': '1000',
        'gidNumber': '2000',
        'homeDirectory': '/home/testuser',
        'userPassword': '******'
    }
    testuser = users.create(properties=user_properties)

    assert (testuser.is_locked() is False)
    testuser.lock()
    assert (testuser.is_locked() is True)

    # Check a bind fails
    with pytest.raises(ldap.UNWILLING_TO_PERFORM):
        conn = testuser.bind('password')
        conn.unbind_s()

    testuser.unlock()
    assert (testuser.is_locked() is False)

    # Check the bind works.
    conn = testuser.bind('password')
    conn.unbind_s()
Esempio n. 7
0
def add_users(topology_st, users_num, suffix):
    """Add users to the default suffix

    Return the list of added user DNs.
    """

    users_list = []
    users = UserAccounts(topology_st.standalone, suffix, rdn=None)

    log.info('Adding %d users' % users_num)
    for num in sample(range(1000), users_num):
        num_ran = int(round(num))
        USER_NAME = 'test%05d' % num_ran

        user = users.create(properties={
            'uid': USER_NAME,
            'sn': USER_NAME,
            'cn': USER_NAME,
            'uidNumber': '%s' % num_ran,
            'gidNumber': '%s' % num_ran,
            'homeDirectory': '/home/%s' % USER_NAME,
            'mail': '*****@*****.**' % USER_NAME,
            'userpassword': '******' % num_ran,
        })
        users_list.append(user)
    return users_list
Esempio n. 8
0
def test_access_log_truncated_search_message(topology_st, clean_access_logs):
    """Tests that the access log message is properly truncated when the message is too long

    :id: 0a9af37d-3311-4a2f-ac0a-9a1c631aaf27
    :setup: Standalone instance
    :steps:
        1. Make a search with a 2048+ characters basedn, filter and attribute list
        2. Check the access log has the message and it's truncated
    :expectedresults:
        1. Operation should be successful
        2. Access log should contain truncated basedn, filter and attribute list
    """

    topo = topology_st.standalone

    large_str_base = "".join("cn=test," for _ in range(512))
    large_str_filter = "".join("(cn=test)" for _ in range(512))
    users = UserAccounts(topo, f'{large_str_base}dc=ending')
    users._list_attrlist = [f'cn{i}' for i in range(512)]
    log.info("Make a search")
    users.filter(f'(|(objectclass=tester){large_str_filter}(cn=ending))')

    log.info('Restart the server to flush the logs')
    topo.restart()

    assert topo.ds_access_log.match(r'.*cn=test,cn=test,.*')
    assert topo.ds_access_log.match(r'.*objectClass=tester.*')
    assert topo.ds_access_log.match(r'.*cn10.*')
    assert not topo.ds_access_log.match(r'.*dc=ending.*')
    assert not topo.ds_access_log.match(r'.*cn=ending.*')
    assert not topo.ds_access_log.match(r'.*cn500.*')
Esempio n. 9
0
def add_user(topology_st, request):
    """Adds a user for binding"""

    log.info('Add the user')

    users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
    user = users.create(properties={
        'uid': USER_RDN,
        'cn': USER_RDN,
        'sn': USER_RDN,
        'uidNumber': '3000',
        'gidNumber': '4000',
        'homeDirectory': '/home/user',
        'description': 'd_e_s_c',
        'userPassword': USER_PASSWD
    })

    def fin():
        """Removes the user entry"""

        log.info('Remove the user entry')
        topology_st.standalone.simple_bind_s(DN_DM, PASSWORD)
        user.delete()

    request.addfinalizer(fin)
Esempio n. 10
0
def test_delete_a_few_entries_in_m4(topo_m4, _cleanupentris):
    """Delete a few entries in Supplier 4 , verify trees.

    :id: 6ea94d78-e764-11e8-987f-8c16451d917b
    :setup: 4 Instances with replication
    :steps:
        1. Delete a few entries in M4 ,
        2. Wait for 60 seconds for them to propagate,
        3. Verify trees
    :expected results:
        1. Should success
        2. Should success
        3. Should success
    """
    # delete a few entries in M4
    # wait for 60 seconds for them to propagate
    # verify trees
    users = UserAccounts(topo_m4.ms["supplier1"], DEFAULT_SUFFIX)
    repl = ReplicationManager(DEFAULT_SUFFIX)
    repl.wait_for_replication(topo_m4.ms["supplier4"], topo_m4.ms["supplier1"])
    for i in users.list():
        i.delete()
    repl.test_replication(topo_m4.ms["supplier4"], topo_m4.ms["supplier1"], 30)
    repl.test_replication(topo_m4.ms["supplier4"], topo_m4.ms["supplier2"], 30)
    repl.test_replication(topo_m4.ms["supplier4"], topo_m4.ms["supplier3"], 30)
Esempio n. 11
0
    def run(self):
        """Start adding users"""

        dm = DirectoryManager(self.inst)
        conn = dm.bind()

        users = UserAccounts(conn, DEFAULT_SUFFIX)

        u_range = list(range(self.num_users))
        random.shuffle(u_range)

        for idx in u_range:
            try:
                users.create(
                    properties={
                        'uid': 'testuser%s' % idx,
                        'cn': 'testuser%s' % idx,
                        'sn': 'user%s' % idx,
                        'uidNumber': '%s' % (1000 + idx),
                        'gidNumber': '%s' % (1000 + idx),
                        'homeDirectory': '/home/testuser%s' % idx
                    })
            # One of the masters was probably put into read only mode - just break out
            except ldap.UNWILLING_TO_PERFORM:
                break
            except ldap.ALREADY_EXISTS:
                pass
        conn.close()
Esempio n. 12
0
def _perform_ldap_operations(topo):
    """Add a test user, modify description, modrdn user and delete it"""

    log.info('Adding user {}'.format(TEST_ENTRY_NAME))
    users = UserAccounts(topo.ms['master1'], DEFAULT_SUFFIX)
    user_properties = {
        'uid': TEST_ENTRY_NAME,
        'cn': TEST_ENTRY_NAME,
        'sn': TEST_ENTRY_NAME,
        'uidNumber': '1001',
        'gidNumber': '2001',
        'userpassword': PASSWORD,
        'description': 'userdesc',
        'homeDirectory': '/home/{}'.format(TEST_ENTRY_NAME)
    }
    tuser = users.create(properties=user_properties)
    tuser.replace('description', 'newdesc')
    log.info('Modify RDN of user {}'.format(tuser.dn))
    try:
        topo.ms['master1'].modrdn_s(tuser.dn, 'uid={}'.format(NEW_RDN_NAME), 0)
    except ldap.LDAPError as e:
        log.fatal('Failed to modrdn entry {}'.format(tuser.dn))
        raise e
    tuser = users.get(NEW_RDN_NAME)
    log.info('Deleting user: {}'.format(tuser.dn))
    tuser.delete()
def create_user(topology_st):
    """User for binding operation"""

    users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
    users.create(
        properties={
            'cn': TEST_USER_NAME,
            'sn': TEST_USER_NAME,
            'userpassword': TEST_USER_PWD,
            'mail': '*****@*****.**' % TEST_USER_NAME,
            'uid': TEST_USER_NAME,
            'uidNumber': '1000',
            'gidNumber': '1000',
            'homeDirectory': '/home/test'
        })

    # Add anonymous access aci
    ACI_TARGET = "(targetattr != \"userpassword || aci\")(target = \"ldap:///%s\")" % (
        DEFAULT_SUFFIX)
    ACI_ALLOW = "(version 3.0; acl \"Anonymous Read access\"; allow (read,search,compare)"
    ACI_SUBJECT = "(userdn=\"ldap:///anyone\");)"
    ANON_ACI = ACI_TARGET + ACI_ALLOW + ACI_SUBJECT
    suffix = Domain(topology_st.standalone, DEFAULT_SUFFIX)
    try:
        suffix.add('aci', ANON_ACI)
    except ldap.TYPE_OR_VALUE_EXISTS:
        pass
Esempio n. 14
0
def test_change_pwd(topology_st, test_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)
Esempio n. 15
0
def test_allow_add_access_to_parent(topo, _add_user, _aci_of_user):

    """Test to Allow add privilege to parent

    :id: 9f099845-9dbc-412f-bdb9-19a5ea729694
    :setup: server
    :steps:
        1. Add test entry
        2. Add ACI that Allow add privilege to parent
        3. Add something using test USER_DELADD
        4. Remove ACI
    :expectedresults:
        1. Entry should be added
        2. ACI should be added
        3. Operation should   succeed
        4. Delete operation for ACI should succeed
    """
    # set aci
    aci_target = f'(targetattr="*")'
    aci_allow = f'(version 3.0; acl "All rights for parent"; allow (add) '
    aci_subject = f'userdn="ldap:///parent";)'

    Domain(topo.standalone, DEFAULT_SUFFIX).add("aci", (aci_target + aci_allow + aci_subject))

    # create connection with USER_WITH_ACI_DELADD
    conn = UserAccount(topo.standalone, USER_WITH_ACI_DELADD).bind(PW_DM)

    # Perform Allow add privilege to parent
    users = UserAccounts(conn, DEFAULT_SUFFIX, rdn='uid=test_user_1000, ou=people')
    user = users.create_test_user(gid=1, uid=1)
    assert user.exists()

    # Delete created user
    UserAccounts(topo.standalone, DEFAULT_SUFFIX).get('test_user_1').delete()
Esempio n. 16
0
def test_allow_delete_access_to_parent(topo, _add_user, _aci_of_user):

    """Test to Allow delete access to parent

    :id: 2dd7f624-68e7-11e8-8591-8c16451d917b
    :setup: server
    :steps:
        1. Add test entry
        2. Add ACI that Allow delete privilege to parent
        3. Delete something using test USER_DELADD
        4. Remove ACI
    :expectedresults:
        1. Entry should be added
        2. ACI should be added
        3. Operation should   succeed
        4. Delete operation for ACI should succeed
    """
    # set aci
    aci_target = f'(targetattr="*")'
    aci_allow = f'(version 3.0; acl "All rights for parent"; allow (add,delete) '
    aci_subject = f'userdn="ldap:///parent";)'

    Domain(topo.standalone, DEFAULT_SUFFIX).add("aci", (aci_target + aci_allow + aci_subject))

    # create connection with USER_WITH_ACI_DELADD
    conn = UserAccount(topo.standalone, USER_WITH_ACI_DELADD).bind(PW_DM)

    # Create a user with parent 'uid=test_user_1000, ou=people, {}'.format(DEFAULT_SUFFIX)
    users = UserAccounts(conn, DEFAULT_SUFFIX, rdn='uid=test_user_1000, ou=people')
    new_user = users.create_test_user(gid=1, uid=1)
    assert new_user.exists()

    # Perform Allow delete access to parent
    new_user.delete()
Esempio n. 17
0
def create_entry(topo_m2, request):
    """Add test entry using UserAccounts"""

    log.info('Adding a test entry user')
    users = UserAccounts(topo_m2.ms["master1"], DEFAULT_SUFFIX)
    tuser = users.ensure_state(properties=TEST_USER_PROPERTIES)
    return tuser
Esempio n. 18
0
def test_require_index(topo):
    """Test nsslapd-ignore-virtual-attrs configuration attribute

    :id: fb6e31f2-acc2-4e75-a195-5c356faeb803
    :setup: Standalone instance
    :steps:
        1. Set "nsslapd-require-index" to "on"
        2. Test an unindexed search is rejected
    :expectedresults:
        1. Success
        2. Success
    """

    # Set the config
    be_insts = Backends(topo.standalone).list()
    for be in be_insts:
        if be.get_attr_val_utf8_l('nsslapd-suffix') == DEFAULT_SUFFIX:
            be.set('nsslapd-require-index', 'on')

    db_cfg = DatabaseConfig(topo.standalone)
    db_cfg.set([('nsslapd-idlistscanlimit', '100')])

    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    for i in range(101):
        users.create_test_user(uid=i)

    # Issue unindexed search,a nd make sure it is rejected
    raw_objects = DSLdapObjects(topo.standalone, basedn=DEFAULT_SUFFIX)
    with pytest.raises(ldap.UNWILLING_TO_PERFORM):
        raw_objects.filter("(description=test*)")
Esempio n. 19
0
def test_pwdAdmin_group(topology_st, password_policy):
    """Test that password admin group can bypass policy.

    :id: 4d62ae34-0f25-486e-b823-afd2b431e9b0
    :setup: Standalone instance, Password Admin entry,
        Password policy configured as below:
            nsslapd-pwpolicy-local: on
            passwordCheckSyntax: on
            passwordMinCategories: 1
            passwordMinTokenLength: 2
            passwordExp: on
            passwordMinDigits: 1
            passwordMinSpecials: 1
    :steps:
        1: Add group to passwordadmin dn
        2: Attempt to set invalid passwords.
    :expectedresults:
        1: Success.
        2: Password should be set.
    """
    (admin_group, admin1_user, admin2_user) = password_policy

    # Update config - set the password admin group
    topology_st.standalone.config.set('passwordAdminDN', admin_group.dn)

    # Bind as admin2, who is in the group.

    admin2_conn = admin2_user.bind(ADMIN_PWD)
    admin2_users = UserAccounts(admin2_conn, DEFAULT_SUFFIX)

    u4 = admin2_users.get('example')

    # Make some invalid password updates, but they should succeed
    for passwd in INVALID_PWDS:
        u4.replace('userPassword', passwd)
Esempio n. 20
0
def test_check_subtype_attr_state(topo, attr_name, attr_value, oper_type,
                                  exp_values, oper_attr):
    """Modify user's roomnumber;office attribute subtype and check if roomnumber;office attribute
    is added/modified/deleted and operational attributes vucsn, adcsn and vdcsn are present.

    :id: 29ab87a4-02d0-11e9-b104-8c16451d917b
    :setup: Replication with two masters.
    :steps: 1. Add user to Master1 without roomnumber;office attribute.
            2. Add roomnumber;office attribute to user.
            3. Check if only one roomnumber;office attribute exist.
            4. Check if operational attribute vucsn exist.
            5. Add second roomnumber;office attribute to user.
            6. Check if two roomnumber;office attributes exist.
            7. Check if operational attribute vucsn exist.
            8. Add third roomnumber;office attribute to user.
            9. Check if three roomnumber;office attributes exist.
            10. Check if operational attribute vucsn exist.
            11. Replace roomnumber;office attribute for the user.
            12. Check if only one roomnumber;office attribute exist.
            13. Check if operational attribute adcsn exist.
            14. Delete roomnumber;office attribute for the user.
            15. Check if no roomnumber;office attribute exist.
            16. Check if no operational attribute vdcsn exist.
    :expectedresults:
            1. Add user to M1 should PASS.
            2. Adding roomnumber;office attribute should PASS
            3. Only one roomnumber;office attribute should be present.
            4. Vucsn attribute should be present.
            5. Adding a new roomnumber;office attribute should PASS
            6. Two roomnumber;office attribute should be present.
            7. Vucsn attribute should be present.
            8. Adding a new roomnumber;office attribute should PASS
            9. Three roomnumber;office attribute should be present.
            10. Vucsn attribute should be present.
            11. Replacing new roomnumber;office attribute should PASS
            12. Only one roomnumber;office attribute should be present.
            13. Adcsn attribute should be present.
            14. Deleting roomnumber;office attribute should PASS
            15. No roomnumber;office attribute should be present.
            16. Vdcsn attribute should be present.
    """

    test_entry = 'roomoffice1usr'
    log.info('Add user: {}'.format(test_entry))
    users = UserAccounts(topo.ms['master1'], DEFAULT_SUFFIX)
    try:
        tuser = users.get(test_entry)
    except ldap.NO_SUCH_OBJECT:
        USER_PROPERTIES.update(dict.fromkeys(['uid', 'cn'], test_entry))
        tuser = users.create(properties=USER_PROPERTIES)

    tuser.set(attr_name, attr_value, eval(oper_type))
    log.info(
        'Check if list of roomnumber;office attributes are present for a given entry'
    )
    assert sorted([i.decode() for i in tuser.get_attr_vals(attr_name)
                   ]) == sorted(exp_values)
    log.info('Checking if operational attributes are present for cn')
    _check_user_oper_attrs(topo, tuser, attr_name, attr_value, oper_type,
                           exp_values, oper_attr)
Esempio n. 21
0
def test_pwdAdmin_modify(topology_st, password_policy):
    """Test that password administrators/root DN can modify
    passwords rather than adding them.

    :id: 85326527-8eeb-401f-9d1b-4ef55dee45a4
    :setup: Standalone instance, Password Admin entry,
        Password policy configured as below:
            nsslapd-pwpolicy-local: on
            passwordCheckSyntax: on
            passwordMinCategories: 1
            passwordMinTokenLength: 2
            passwordExp: on
            passwordMinDigits: 1
            passwordMinSpecials: 1
    :steps:
        1: Retrieve the user
        2: Replace the password with invalid content
    :expectedresults:
        1: Success
        2: The password should be set
    """
    (admin_group, admin1_user, admin2_user) = password_policy

    # Update config - set the password admin
    topology_st.standalone.config.set('passwordAdminDN', admin1_user.dn)

    admin_conn = admin1_user.bind(ADMIN_PWD)
    admin_users = UserAccounts(admin_conn, DEFAULT_SUFFIX)

    u3 = admin_users.get('example')
    #
    # Make the same password updates, but this time they should succeed
    #
    for passwd in INVALID_PWDS:
        u3.replace('userPassword', passwd)
Esempio n. 22
0
def _test_algo(inst, algo_name):
    inst.config.set('passwordStorageScheme', algo_name)

    users = UserAccounts(inst, DEFAULT_SUFFIX)
    user_props = TEST_USER_PROPERTIES.copy()
    user_props.update({
        'uid': 'user',
        'cn': 'buser',
        'userpassword': '******'
    })
    user = users.create(properties=user_props)

    # Make sure when we read the userPassword field, it is the correct ALGO
    pw_field = user.get_attr_val_utf8('userPassword')

    if algo_name != 'CLEAR' and algo_name != 'DEFAULT':
        assert (algo_name[:5].lower() in pw_field.lower())
    # Now make sure a bind works
    assert (_test_bind(user, 'Secret123'))
    # Bind with a wrong shorter password, should fail
    assert (not _test_bind(user, 'Wrong'))
    # Bind with a wrong longer password, should fail
    assert (not _test_bind(user, 'This is even more wrong'))
    # Bind with a wrong exact length password.
    assert (not _test_bind(user, 'Alsowrong'))
    # Bind with a subset password, should fail
    assert (not _test_bind(user, 'Secret'))
    if not algo_name.startswith('CRYPT'):
        # Bind with a subset password that is 1 char shorter, to detect off by 1 in clear
        assert (not _test_bind(user, 'Secret12'))
        # Bind with a superset password, should fail
        assert (not _test_bind(user, 'Secret123456'))

    # Delete the user
    user.delete()
Esempio n. 23
0
def test_password_crypt_asterisk_is_rejected(topology_st):
    """It was reported that {CRYPT}* was allowing all passwords to be
    valid in the bind process. This checks that we should be rejecting
    these as they should represent locked accounts. Similar, {CRYPT}!

    :id: 0b8f1a6a-f3eb-4443-985e-da14d0939dc3
    :setup: Single instance
    :steps: 1. Set a password hash in with CRYPT and the content *
            2. Test a bind
            3. Set a password hash in with CRYPT and the content !
            4. Test a bind
    :expectedresults:
            1. Successfully set the values
            2. The bind fails
            3. Successfully set the values
            4. The bind fails
    """
    topology_st.standalone.config.set('nsslapd-allow-hashed-passwords', 'on')
    topology_st.standalone.config.set('nsslapd-enable-upgrade-hash', 'off')

    users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
    user = users.create_test_user()

    user.set('userPassword', "{CRYPT}*")

    # Attempt to bind with incorrect password.
    with pytest.raises(ldap.INVALID_CREDENTIALS):
        badconn = user.bind('badpassword')

    user.set('userPassword', "{CRYPT}!")
    # Attempt to bind with incorrect password.
    with pytest.raises(ldap.INVALID_CREDENTIALS):
        badconn = user.bind('badpassword')
Esempio n. 24
0
def add_a_group_with_users(request, topo):
    """
    Add a group and users, which are members of this group.
    """
    groups = Groups(topo.standalone, DEFAULT_SUFFIX, rdn=None)
    group = groups.create(properties={'cn': 'test_group'})
    users_list = []
    users_num = 100
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=None)
    for num in range(users_num):
        USER_NAME = f'test_{num}'
        user = users.create(
            properties={
                'uid': USER_NAME,
                'sn': USER_NAME,
                'cn': USER_NAME,
                'uidNumber': f'{num}',
                'gidNumber': f'{num}',
                'homeDirectory': f'/home/{USER_NAME}'
            })
        users_list.append(user)
        group.add_member(user.dn)

    def fin():
        """
        Removes group and users.
        """
        # If the server crashed, start it again to do the cleanup
        if not topo.standalone.status():
            topo.standalone.start()
        for user in users_list:
            user.delete()
        group.delete()

    request.addfinalizer(fin)
Esempio n. 25
0
def test_audit_log_rotate_and_check_string(
        topology_st, clean_access_logs, set_audit_log_config_values_to_rotate):
    """Version string should be logged only once at the top of audit log
    after it is rotated.

    :id: 14dffb22-2f9c-11e9-8a03-54e1ad30572c

    :customerscenario: True

    :setup: Standalone instance

    :steps:
         1. Set nsslapd-auditlog-logging-enabled: on
         2. Set nsslapd-auditlog-maxlogsize: 1
         3. Do modifications to the entry, until audit log file is rotated
         4. Check audit logs

    :expectedresults:
         1. Attribute nsslapd-auditlog-logging-enabled should be set to on
         2. Attribute nsslapd-auditlog-maxlogsize should be set to 1
         3. Audit file should grow till 1MB and then should be rotated
         4. Audit file log should contain version string only once at the top
    """

    standalone = topology_st.standalone
    search_ds = '389-Directory'

    users = UserAccounts(standalone, DEFAULT_SUFFIX)
    user = users.create(
        properties={
            'uid': 'test_audit_log',
            'cn': 'test',
            'sn': 'user',
            'uidNumber': '1000',
            'gidNumber': '1000',
            'homeDirectory': '/home/test',
        })

    log.info('Doing modifications to rotate audit log')
    audit_log = standalone.ds_paths.audit_log
    while len(glob.glob(audit_log + '*')) == 2:
        user.replace('description', 'test' * 100)

    log.info('Doing one more modification just in case')
    user.replace('description', 'test2' * 100)

    standalone.stop()

    count = 0
    with open(audit_log) as f:
        log.info('Check that DS string is present on first line')
        assert search_ds in f.readline()
        f.seek(0)

        log.info('Check that DS string is present only once')
        for line in f.readlines():
            if search_ds in line:
                count += 1
        assert count == 1
def change_passwd(topo):
    log.info(
        'Reset user password as the user, then re-bind as Directory Manager')
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    user = users.get('test entry')
    user.rebind(USER_PW)
    user.reset_password(USER_PW)
    topo.standalone.simple_bind(DN_DM, PASSWORD)
Esempio n. 27
0
def user_config(topo, field_value):
    """
    Will set storage schema and create user.
    """
    Config(topo.standalone).replace("passwordStorageScheme", field_value)
    user = UserAccounts(topo.standalone, DEFAULT_SUFFIX).create_test_user()
    user.set('userpassword', 'ItsMeAnuj')
    return user
Esempio n. 28
0
def test_export_import_plaintext(topo, enable_user_attr_encryption):
    """Configure attribute encryption, store some data, check that we can export the plain text

     :id: b171e215-0456-48a5-245f-c21abc40fc2d
     :setup: Standalone instance
             Enable AES encryption config on employeenumber
             Enable 3DES encryption config on telephoneNumber
             Add a test user with encrypted attributes
     :steps:
          1. Export data as plain text
          2. Check that the attribute is present in the exported file
          3. Check that the encrypted value of attribute is also present in the exported file
          4. Delete the test user entry with encrypted data
          5. Import data as plaintext
          6. Check attribute value of telephoneNumber
     :expectedresults:
          1. This should be successful
          2. This should be successful
          3. This should be successful
          4. This should be successful
          5. This should be successful
          6. This should be successful
     """

    log.info("Export data as plain text")
    export_ldif = os.path.join(topo.standalone.ds_paths.ldif_dir, "export_plaintext.ldif")

    # Offline export
    topo.standalone.stop()
    if not topo.standalone.db2ldif(bename=DEFAULT_BENAME, suffixes=(DEFAULT_SUFFIX,),
                                   excludeSuffixes=None, encrypt=True, repl_data=None, outputfile=export_ldif):
        log.fatal('Failed to run offline db2ldif')
        assert False
    topo.standalone.start()

    log.info("Check that the attribute is present in the exported file")
    log.info("Check that the plain text value of the encrypted attribute is present in the exported file")
    with open(export_ldif, 'r') as ldif_file:
        assert 'telephoneNumber: 1234567890' in ldif_file.read()

    log.info("Delete the test user entry with encrypted data")
    enable_user_attr_encryption.delete()

    log.info("Import data as plain text, which was exported previously")
    import_ldif = os.path.join(topo.standalone.ds_paths.ldif_dir, "export_plaintext.ldif")

    # Offline export
    topo.standalone.stop()
    if not topo.standalone.ldif2db(bename=DEFAULT_BENAME, suffixes=(DEFAULT_SUFFIX,),
                                   excludeSuffixes=None, encrypt=True, import_file=import_ldif):
        log.fatal('Failed to run offline ldif2db')
        assert False
    topo.standalone.start()

    log.info("Check that the attribute is imported properly")
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    user = users.get('testuser')
    assert user.present("telephoneNumber")
Esempio n. 29
0
def test_dna_interval_with_different_values(topology_st, dna_plugin,
                                            attr_value):
    """Test the dna interval with different values

    :id: 1a3f69fd-1d8d-4046-ba68-b6aa7cafbd37
    :customerscenario: True
    :parametrized: yes
    :setup: Standalone Instance
    :steps:
        1. Set dnaInterval value to 0
        2. Set dnaInterval value to 'abc'
        3. Set dnaInterval value to 2000 and dnaMaxValue to 1000
        4. Create user that trigger DNA to assign a value
        5. Try to make an update to entry that triggers DNA again when dnaInerval is greater than dnaMaxValue
    :expectedresults:
        1. Success
        2. Operation should fail with INVALID_SYNTAX
        3. Success
        4. Success
        5. Operation should fail with OPERATIONS_ERROR
    """
    log.info("Make the config changes needed to test dnaInterval")
    if attr_value == '0':
        dna_plugin.replace('dnaInterval', attr_value)
    elif attr_value == 'abc':
        with pytest.raises(ldap.INVALID_SYNTAX):
            dna_plugin.replace('dnaInterval', attr_value)
    else:
        dna_plugin.replace_many(('dnaInterval', attr_value),
                                ('dnaMaxValue', '1000'))
        # Create user3
        users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
        log.info('Adding user3')
        user = users.create(
            properties={
                'sn': 'interval3',
                'cn': 'interval3',
                'uid': 'interval3',
                'uidNumber': '-1',  # Magic regen value
                'gidNumber': '333',
                'givenname': 'interval3',
                'homePhone': '0861234567',
                'carLicense': '131D16674',
                'mail': '*****@*****.**',
                'homeDirectory': '/home/interval3'
            })

        # Verify DNA works
        assert user.get_attr_val_utf8_l('uidNumber') == '10'

        log.info(
            "Make an update and verify it raises error as the new interval value is more than dnaMaxValue"
        )
        with pytest.raises(ldap.OPERATIONS_ERROR):
            user.replace('uidNumber', '-1')

        # Check that instance did not crashed
        assert topology_st.standalone.status()
Esempio n. 30
0
    def _remove_users():
        topo = topology_st.standalone
        users = UserAccounts(topo, DEFAULT_SUFFIX)
        entries = users.list()
        assert len(entries) > 0

        log.info("Removing all added users")
        for entry in entries:
            delete_obj(entry)