Esempio n. 1
0
def test_deref_and_access_control(topo):
    """Test that the deref plugin honors access control rules correctly

    The setup mimics a generic IPA DIT with its ACI's.  The userpassword
    attribute should not be returned

    :id: bedb6af2-b765-479d-808c-df0348e0ec95
    :setup: Standalone Instance
    :steps:
        1. Create container entries with aci's
        2. Perform deref search and make sure userpassword is not returned
    :expectedresults:
        1. Success
        2. Success
    """

    topo.standalone.config.set('nsslapd-schemacheck', 'off')
    if DEBUGGING:
        topo.standalone.config.enable_log('audit')
        topo.standalone.config.set('nsslapd-errorlog-level', '128')

    # Accounts
    ou1 = OrganizationalUnits(topo.standalone, DEFAULT_SUFFIX)
    ou1.create(properties={'ou': 'accounts', 'aci': ACCTS_ACI})

    # Users
    ou2 = OrganizationalUnits(topo.standalone, ACCTS_DN)
    ou2.create(properties={'ou': 'users', 'aci': USERS_ACI})

    # Groups
    ou3 = OrganizationalUnits(topo.standalone, ACCTS_DN)
    ou3.create(properties={'ou': 'groups', 'aci': GROUPS_ACIS})

    # Create User
    users = UserAccounts(topo.standalone, USERS_DN, rdn=None)
    user_props = TEST_USER_PROPERTIES.copy()
    user_props.update({
        'uid': 'user',
        'objectclass': ['posixAccount', 'extensibleObject'],
        'userpassword': PASSWORD
    })
    user = users.create(properties=user_props)

    # Create Admin user
    user_props = TEST_USER_PROPERTIES.copy()
    user_props.update({
        'uid':
        'admin',
        'objectclass': ['posixAccount', 'extensibleObject', 'inetuser'],
        'userpassword':
        PASSWORD,
        'memberOf':
        ADMIN_GROUP_DN
    })
    users.create(properties=user_props)

    # Create Admin group
    groups = Groups(topo.standalone, GROUPS_DN, rdn=None)
    group_props = {
        'cn': 'admins',
        'gidNumber': '123',
        'objectclass': ['posixGroup', 'extensibleObject'],
        'member': ADMIN_DN
    }
    groups.create(properties=group_props)

    # Bind as user, then perform deref search on admin user
    user.rebind(PASSWORD)
    result, control_response = topo.standalone.dereference(
        'member:cn,userpassword', base=ADMIN_GROUP_DN, scope=ldap.SCOPE_BASE)

    log.info(
        'Check, that the dereference search result does not have userpassword')
    assert result[0][2][0].entry[0]['attrVals'][0]['type'] != 'userpassword'
Esempio n. 2
0
def test_inconsistencies(topo_tls_ldapi):
    """Check that the report mentions inconsistencies with attributes

    :id: c8fe3e84-b346-4969-8f5d-3462b643a1d2
    :customerscenario: True
    :setup: Two master replication
    :steps:
        1. Add an entry to master and wait for replication
        2. Pause replication between master and replica
        3. Set different description attr values to master and replica
        4. Add telephoneNumber attribute to master and not to replica
        5. Generate the report
        6. Check that attribute values are mentioned in the report
        7. Generate the report with -i option to ignore some attributes
        8. Check that attribute values are mentioned in the report
    :expectedresults:
        1. It should be successful
        2. It should be successful
        3. It should be successful
        4. It should be successful
        5. It should be successful
        6. The attribute values should be mentioned in the report
        7. It should be successful
        8. The attribute values should not be mentioned in the report
    """

    m1 = topo_tls_ldapi.ms["master1"]
    m2 = topo_tls_ldapi.ms["master2"]
    attr_m1 = "m1_inconsistency"
    attr_m2 = "m2_inconsistency"
    attr_first = "first ordered valued"
    attr_second = "second ordered valued"
    attr_m1_only = "123123123"

    try:
        users_m1 = UserAccounts(m1, DEFAULT_SUFFIX)
        users_m2 = UserAccounts(m2, DEFAULT_SUFFIX)
        user_m1 = users_m1.create(properties=TEST_USER_PROPERTIES)
        time.sleep(1)
        user_m2 = users_m2.get(user_m1.rdn)
        topo_tls_ldapi.pause_all_replicas()
        user_m1.set("description", attr_m1)
        user_m2.set("description", attr_m2)
        user_m1.set("telephonenumber", attr_m1_only)
        # Add the same multi-valued attrs, but out of order
        user_m1.set("cn", [attr_first, attr_second])
        user_m2.set("cn", [attr_second, attr_first])
        time.sleep(2)

        for tool_cmd in replcheck_cmd_list(topo_tls_ldapi):
            result = subprocess.check_output(tool_cmd, encoding='utf-8').lower()
            assert attr_m1 in result
            assert attr_m2 in result
            assert attr_m1_only in result
            if ds_is_newer("1.3.9.1", "1.4.1.2"):
                assert attr_first not in result
                assert attr_second not in result
            # Ignore some attributes and check the output
            tool_cmd.extend(['-i', '{},{}'.format('description', 'telephonenumber')])
            result = subprocess.check_output(tool_cmd, encoding='utf-8').lower()
            assert attr_m1 not in result
            assert attr_m2 not in result
            assert attr_m1_only not in result
            if ds_is_newer("1.3.9.1", "1.4.1.2"):
                assert attr_first not in result
                assert attr_second not in result

    finally:
        topo_tls_ldapi.resume_all_replicas()
        user_m1.delete()
Esempio n. 3
0
def test_indirect_template_scale(topology_st):
    """Test that cos templates can be added at a reasonable scale

    :id: 7cbcdf22-1f9c-4222-9e76-685fe374fc20
    :steps:
        1. Enable COS plugin
        2. Create the test user
        3. Add an indirect cos template
        4. Add a cos template
        5. Add the user to the cos template and assert it works.
        6. Add 25,000 templates to the database
        7. Search the user. It should not exceed THRESHOLD.
    :expected results:
        1. It is enabled.
        2. It is created.
        3. Is is created.
        4. It is created.
        5. It is valid.
        6. They are created.
        7. It is fast.
    """

    cos_plugin = ClassOfServicePlugin(topology_st.standalone)
    cos_plugin.enable()

    topology_st.standalone.restart()

    # Now create, the indirect specifier, and a user to template onto.
    users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
    user = users.create(properties=TEST_USER_PROPERTIES)

    cos_inds = CosIndirectDefinitions(topology_st.standalone, DEFAULT_SUFFIX)
    cos_ind = cos_inds.create(properties={
        'cn' : 'cosIndirectDef',
        'cosIndirectSpecifier': 'seeAlso',
        'cosAttribute': [
            'ou merge-schemes',
            'description merge-schemes',
            'postalCode merge-schemes',
            ],
    })

    ous = OrganisationalUnits(topology_st.standalone, DEFAULT_SUFFIX)
    ou_temp = ous.create(properties={'ou': 'templates'})
    cos_temps = OUCosTemplates(topology_st.standalone, ou_temp.dn)

    cos_temp_u = cos_temps.create(properties={
        'ou' : 'ou_temp_u',
        'description' : 'desc_temp_u',
        'postalCode': '0'
    })
    # Edit the user to add the seeAlso ...
    user.set('seeAlso', cos_temp_u.dn)

    # Now create 25,0000 templates, they *don't* need to apply to the user though!
    for i in range(1, 25001):
        cos_temp_u = cos_temps.create(properties={
            'ou' : 'ou_temp_%s' % i,
            'description' : 'desc_temp_%s' % i,
            'postalCode': '%s' % i
        })

        if i % 500 == 0:
            start_time = time.monotonic()
            u_search = users.get('testuser')
            attrs = u_search.get_attr_vals_utf8('postalCode')
            end_time = time.monotonic()
            diff_time = end_time - start_time
            assert diff_time < THRESHOLD

        if i == 10000:
            # Now add our user to this template also.
            user.add('seeAlso', cos_temp_u.dn)

            start_time = time.monotonic()
            attrs_after = u_search.get_attr_vals_utf8('postalCode')
            end_time = time.monotonic()
            diff_time = end_time - start_time
            assert(set(attrs) < set(attrs_after))
            assert diff_time < THRESHOLD
Esempio n. 4
0
def _add_user(request, topo):
    """
    A Function that will create necessary users delete the created user
    """
    ous = OrganizationalUnits(topo.standalone, DEFAULT_SUFFIX)
    ou_ou = ous.create(properties={'ou': 'roledntest'})
    ou_ou.set('aci', [
        f'(target="ldap:///{NESTED_ROLE_TESTER}")(targetattr="*") '
        f'(version 3.0; aci "nested role aci"; allow(all)'
        f'roledn = "ldap:///{ROLE2}";)',
        f'(target="ldap:///{OR_RULE_ACCESS}")(targetattr="*")'
        f'(version 3.0; aci "or role aci"; allow(all) '
        f'roledn = "ldap:///{ROLE1} || ldap:///{ROLE21}";)',
        f'(target="ldap:///{ALL_ACCESS}")(targetattr=*)'
        f'(version 3.0; aci "anyone role aci"; allow(all) '
        f'roledn = "ldap:///anyone";)',
        f'(target="ldap:///{NOT_RULE_ACCESS}")(targetattr=*)'
        f'(version 3.0; aci "not role aci"; allow(all)'
        f'roledn != "ldap:///{ROLE1} || ldap:///{ROLE21}";)'
    ])

    nestedroles = NestedRoles(topo.standalone, OU_ROLE)
    for i in [('role2', [ROLE1, ROLE21]), ('role3', [ROLE2, ROLE31])]:
        nestedroles.create(properties={'cn': i[0], 'nsRoleDN': i[1]})

    managedroles = ManagedRoles(topo.standalone, OU_ROLE)
    for i in ['ROLE1', 'ROLE21', 'ROLE31']:
        managedroles.create(properties={'cn': i})

    filterroles = FilteredRoles(topo.standalone, OU_ROLE)
    filterroles.create(
        properties={
            'cn': 'filterRole',
            'nsRoleFilter': 'sn=Dr Drake',
            'description': 'filter role tester'
        })

    users = UserAccounts(topo.standalone, OU_ROLE, rdn=None)
    for i in [('STEVE_ROLE', ROLE1, 'Has roles 1, 2 and 3.'),
              ('HARRY_ROLE', ROLE21, 'Has roles 21, 2 and 3.'),
              ('MARY_ROLE', ROLE31, 'Has roles 31 and 3.')]:
        users.create(
            properties={
                'uid': i[0],
                'cn': i[0],
                'sn': 'user',
                'uidNumber': '1000',
                'gidNumber': '2000',
                'homeDirectory': '/home/' + i[0],
                'userPassword': PW_DM,
                'nsRoleDN': i[1],
                'Description': i[2]
            })

    for i in [('JOE_ROLE', 'Has filterRole.'), ('NOROLEUSER', 'Has no roles.'),
              ('SCRACHENTRY', 'Entry to test rights on.'),
              ('all access', 'Everyone has acccess (incl anon).'),
              ('not rule access', 'Only accessible to mary.'),
              ('or rule access',
               'Only to steve and harry but nbot mary or anon'),
              ('nested role tester', 'Only accessible to harry and steve.')]:
        users.create(
            properties={
                'uid': i[0],
                'cn': i[0],
                'sn': 'user',
                'uidNumber': '1000',
                'gidNumber': '2000',
                'homeDirectory': '/home/' + i[0],
                'userPassword': PW_DM,
                'Description': i[1]
            })

    # Setting SN for user JOE
    UserAccount(topo.standalone,
                f'uid=JOE_ROLE,ou=roledntest,{DEFAULT_SUFFIX}').set(
                    'sn', 'Dr Drake')

    def fin():
        """
        It will delete the created users
        """
        for i in users.list() + managedroles.list() + nestedroles.list():
            i.delete()

    request.addfinalizer(fin)
Esempio n. 5
0
def test_repl_modrdn(topo_m2):
    """Test that replicated MODRDN does not break replication

    :id: a3e17698-9eb4-41e0-b537-8724b9915fa6
    :setup: Two masters replication setup
    :steps:
        1. Add 3 test OrganizationalUnits A, B and C
        2. Add 1 test user under OU=A
        3. Add same test user under OU=B
        4. Stop Replication
        5. Apply modrdn to M1 - move test user from OU A -> C
        6. Apply modrdn on M2 - move test user from OU B -> C
        7. Start Replication
        8. Check that there should be only one test entry under ou=C on both masters
        9. Check that the replication is working fine both ways M1 <-> M2
    :expectedresults:
        1. This should pass
        2. This should pass
        3. This should pass
        4. This should pass
        5. This should pass
        6. This should pass
        7. This should pass
        8. This should pass
        9. This should pass
    """

    master1 = topo_m2.ms["master1"]
    master2 = topo_m2.ms["master2"]

    repl = ReplicationManager(DEFAULT_SUFFIX)

    log.info(
        "Add test entries - Add 3 OUs and 2 same users under 2 different OUs")
    OUs = OrganizationalUnits(master1, DEFAULT_SUFFIX)
    OU_A = OUs.create(properties={
        'ou': 'A',
        'description': 'A',
    })
    OU_B = OUs.create(properties={
        'ou': 'B',
        'description': 'B',
    })
    OU_C = OUs.create(properties={
        'ou': 'C',
        'description': 'C',
    })

    users = UserAccounts(master1, DEFAULT_SUFFIX, rdn='ou={}'.format(OU_A.rdn))
    tuser_A = users.create(properties=TEST_USER_PROPERTIES)

    users = UserAccounts(master1, DEFAULT_SUFFIX, rdn='ou={}'.format(OU_B.rdn))
    tuser_B = users.create(properties=TEST_USER_PROPERTIES)

    repl.test_replication(master1, master2)
    repl.test_replication(master2, master1)

    log.info("Stop Replication")
    topo_m2.pause_all_replicas()

    log.info("Apply modrdn to M1 - move test user from OU A -> C")
    master1.rename_s(tuser_A.dn,
                     'uid=testuser1',
                     newsuperior=OU_C.dn,
                     delold=1)

    log.info("Apply modrdn on M2 - move test user from OU B -> C")
    master2.rename_s(tuser_B.dn,
                     'uid=testuser1',
                     newsuperior=OU_C.dn,
                     delold=1)

    log.info("Start Replication")
    topo_m2.resume_all_replicas()

    log.info("Wait for sometime for repl to resume")
    repl.test_replication(master1, master2)
    repl.test_replication(master2, master1)

    log.info(
        "Check that there should be only one test entry under ou=C on both masters"
    )
    users = UserAccounts(master1, DEFAULT_SUFFIX, rdn='ou={}'.format(OU_C.rdn))
    assert len(users.list()) == 1

    users = UserAccounts(master2, DEFAULT_SUFFIX, rdn='ou={}'.format(OU_C.rdn))
    assert len(users.list()) == 1

    log.info("Check that the replication is working fine both ways, M1 <-> M2")
    repl.test_replication(master1, master2)
    repl.test_replication(master2, master1)
Esempio n. 6
0
def test_MMR_double_free(topology_m2, topology_setup, timeout=5):
    """Reproduce conditions where a double free occurs and check it does not make
    the server crash

    :id: 91580b1c-ad10-49bc-8aed-402edac59f46 
    :setup: replicated topology - purge delay and purge interval are configured
    :steps:
        1. create an entry on supplier1
        2. modify the entry with description add
        3. check the entry is correctly replicated on supplier2
        4. stop supplier2
        5. delete the entry's description on supplier1
        6. stop supplier1
        7. start supplier2
        8. delete the entry's description on supplier2
        9. add an entry's description on supplier2
        10. wait the purge delay duration
        11. add again an entry's description on supplier2
    :expectedresults:
        1. entry exists on supplier1
        2. modification is effective 
        3. entry exists on supplier2 and modification is effective
        4. supplier2 is stopped
        5. description is removed from entry on supplier1
        6. supplier1 is stopped
        7. supplier2 is started - not synchronized with supplier1
        8. description is removed from entry on supplier2 (same op should be performed too by replication mecanism)
        9. description to entry is added on supplier2
        10. Purge delay has expired - changes are erased 
        11.  description to entry is added again on supplier2
    """
    name = 'test_entry'

    entry_m1 = UserAccounts(topology_m2.ms["supplier1"], DEFAULT_SUFFIX)
    entry = entry_m1.create(
        properties={
            'uid': name,
            'sn': name,
            'cn': name,
            'uidNumber': '1001',
            'gidNumber': '1001',
            'homeDirectory': '/home/test_entry',
            'userPassword': '******'
        })

    log.info('First do an update that is replicated')
    entry.add('description', '5')

    log.info('Check the update in the replicated entry')
    entry_m2 = UserAccounts(topology_m2.ms["supplier2"], DEFAULT_SUFFIX)

    success = 0
    for i in range(0, timeout):
        try:
            entry_repl = entry_m2.get(name)
            out = entry_repl.display_attr('description')
            if len(out) > 0:
                success = 1
                break
        except:
            time.sleep(1)

    assert success

    log.info('Stop M2 so that it will not receive the next update')
    topology_m2.ms["supplier2"].stop(10)

    log.info('Perform a del operation that is not replicated')
    entry.remove('description', '5')

    log.info(
        "Stop M1 so that it will keep del '5' that is unknown from supplier2")
    topology_m2.ms["supplier1"].stop(10)

    log.info('start M2 to do the next updates')
    topology_m2.ms["supplier2"].start()

    log.info("del 'description' by '5'")
    entry_repl.remove('description', '5')

    log.info("add 'description' by '5'")
    entry_repl.add('description', '5')

    log.info(
        'sleep of purge delay so that the next update will purge the CSN_7')
    time.sleep(6)

    log.info("add 'description' by '6' that purge the state info")
    entry_repl.add('description', '6')

    log.info('Restart supplier1')
    topology_m2.ms["supplier1"].start(30)
def test_attr_encryption_backends(topo, enable_user_attr_encryption):
    """Tests Configuration of attribute encryption for single backend
       where more backends are present

    :id: f3ef40e1-17d6-44d8-a3a4-4a25a57e9064
    :setup: Standalone instance
            SSL Enabled
    :steps:
         1. Add two test backends
         2. Configure attribute encryption for telephoneNumber in one test backend
         3. Add a test user in both backends with telephoneNumber
         4. Export ldif from both test backends
         5. Check that telephoneNumber is encrypted in the ldif file of db1
         6. Check that telephoneNumber is not encrypted in the ldif file of db2
         7. Delete both test backends
    :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
         7. This should be successful
    """
    log.info("Add two test backends")
    test_suffix1 = 'dc=test1,dc=com'
    test_db1 = 'test_db1'
    test_suffix2 = 'dc=test2,dc=com'
    test_db2 = 'test_db2'

    # Create backends
    backends = Backends(topo.standalone)
    test_backend1 = backends.create(properties={'cn': test_db1,
                                                'nsslapd-suffix': test_suffix1})
    test_backend2 = backends.create(properties={'cn': test_db2,
                                                'nsslapd-suffix': test_suffix2})

    # Create the top of the tree
    suffix1 = Domain(topo.standalone, test_suffix1)
    test1 = suffix1.create(properties={'dc': 'test1'})
    suffix2 = Domain(topo.standalone, test_suffix2)
    test2 = suffix2.create(properties={'dc': 'test2'})

    log.info("Enables attribute encryption for telephoneNumber in test_backend1")
    backend1_encrypt_attrs = EncryptedAttrs(topo.standalone, basedn='cn=encrypted attributes,{}'.format(test_backend1.dn))
    b1_encrypt = backend1_encrypt_attrs.create(properties={'cn': 'telephoneNumber',
                                                           'nsEncryptionAlgorithm': 'AES'})

    log.info("Add a test user with telephoneNumber in both backends")
    users = UserAccounts(topo.standalone, test1.dn, None)
    test_user = users.create(properties=TEST_USER_PROPERTIES)
    test_user.replace('telephoneNumber', '1234567890')

    users = UserAccounts(topo.standalone, test2.dn, None)
    test_user = users.create(properties=TEST_USER_PROPERTIES)
    test_user.replace('telephoneNumber', '1234567890')

    log.info("Export data as ciphertext from both backends")
    export_db1 = os.path.join(topo.standalone.ds_paths.ldif_dir, "export_db1.ldif")
    export_db2 = os.path.join(topo.standalone.ds_paths.ldif_dir, "export_db2.ldif")

    # Offline export
    topo.standalone.stop()
    if not topo.standalone.db2ldif(bename=test_db1, suffixes=(test_suffix1,),
                                   excludeSuffixes=None, encrypt=False, repl_data=None, outputfile=export_db1):
        log.fatal('Failed to run offline db2ldif')
        assert False

    if not topo.standalone.db2ldif(bename=test_db2, suffixes=(test_suffix2,),
                                   excludeSuffixes=None, encrypt=False, repl_data=None, outputfile=export_db2):
        log.fatal('Failed to run offline db2ldif')
        assert False
    topo.standalone.start()

    log.info("Check that the attribute is present in the exported file in db1")
    log.info("Check that the encrypted value of attribute is not present in the exported file in db1")
    with open(export_db1, 'r') as ldif_file:
        ldif = ldif_file.read()
        assert 'telephoneNumber' in ldif
        assert 'telephoneNumber: 1234567890' not in ldif

    log.info("Check that the attribute is present in the exported file in db2")
    log.info("Check that the value of attribute is also present in the exported file in db2")
    with open(export_db2, 'r') as ldif_file:
        ldif = ldif_file.read()
        assert 'telephoneNumber' in ldif
        assert 'telephoneNumber: 1234567890' in ldif

    log.info("Delete test backends")
    test_backend1.delete()
    test_backend2.delete()
Esempio n. 8
0
def test_managedrole(topo, request):
    """Test Managed Role

    :id: d52a9c00-3bf6-11e9-9b7b-8c16451d917b
    :setup: server
    :steps:
        1. Add test entry
        2. Add ACI
        3. Search managed role entries
    :expectedresults:
        1. Entry should be added
        2. Operation should  succeed
        3. Operation should  succeed
    """
    # Create Managed role entry
    roles = ManagedRoles(topo.standalone, DEFAULT_SUFFIX)
    role = roles.create(properties={"cn": 'ROLE1'})

    # Create user and Assign the role to the entry
    uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=None)
    uas.create(
        properties={
            'uid': 'Fail',
            'cn': 'Fail',
            'sn': 'user',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/' + 'Fail',
            'nsRoleDN': role.dn,
            'userPassword': PW_DM
        })

    # Create user and do not Assign any role to the entry
    uas.create(
        properties={
            'uid': 'Success',
            'cn': 'Success',
            'sn': 'user',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/' + 'Success',
            'userPassword': PW_DM
        })

    # Assert that Manage role entry is created and its searchable
    assert ManagedRoles(topo.standalone, DEFAULT_SUFFIX).list()[0].dn \
           == 'cn=ROLE1,dc=example,dc=com'

    # Set an aci that will deny  ROLE1 manage role
    Domain(topo.standalone, DEFAULT_SUFFIX).\
        add('aci', '(targetattr="*")(version 3.0; aci "role aci";'
                   ' deny(all) roledn="ldap:///{}";)'.format(role.dn),)
    # Add self user modification and anonymous aci
    ANON_ACI = "(targetattr=\"*\")(version 3.0; acl \"Anonymous Read access\"; allow (read,search,compare) userdn = \"ldap:///anyone\";)"
    suffix = Domain(topo.standalone, DEFAULT_SUFFIX)
    suffix.add('aci', ANON_ACI)

    # Crate a connection with cn=Fail which is member of ROLE1
    conn = UserAccount(topo.standalone,
                       "uid=Fail,{}".format(DEFAULT_SUFFIX)).bind(PW_DM)
    # Access denied to ROLE1 members
    assert not ManagedRoles(conn, DEFAULT_SUFFIX).list()

    # Now create a connection with cn=Success which is not a member of ROLE1
    conn = UserAccount(topo.standalone,
                       "uid=Success,{}".format(DEFAULT_SUFFIX)).bind(PW_DM)
    # Access allowed here
    assert ManagedRoles(conn, DEFAULT_SUFFIX).list()

    for i in uas.list():
        i.delete()

    for i in roles.list():
        i.delete()

    def fin():
        topo.standalone.restart()
        try:
            role = ManagedRoles(topo.standalone, DEFAULT_SUFFIX).get('ROLE1')
            role.delete()
        except:
            pass
        topo.standalone.config.set('nsslapd-ignore-virtual-attrs', 'on')

    request.addfinalizer(fin)
Esempio n. 9
0
def test_info_disclosure(request, topo):
    """Test that a search returns 32 when base entry does not exist

    :id: f6dec4c2-65a3-41e4-a4c0-146196863333
    :setup: Standalone Instance
    :steps:
        1. Add aci
        2. Add test user
        3. Bind as user and search for non-existent entry
    :expectedresults:
        1. Success
        2. Success
        3. Error 32 is returned
    """

    ACI_TARGET = "(targetattr = \"*\")(target = \"ldap:///%s\")" % (
        DEFAULT_SUFFIX)
    ACI_ALLOW = "(version 3.0; acl \"Read/Search permission for all users\"; allow (read,search)"
    ACI_SUBJECT = "(userdn=\"ldap:///all\");)"
    ACI = ACI_TARGET + ACI_ALLOW + ACI_SUBJECT

    # Get current ACi's so we can restore them when we are done
    suffix = Domain(topo.standalone, DEFAULT_SUFFIX)
    preserved_acis = suffix.get_attr_vals_utf8('aci')

    def finofaci():
        domain = Domain(topo.standalone, DEFAULT_SUFFIX)
        try:
            domain.remove_all('aci')
            domain.replace_values('aci', preserved_acis)
        except:
            pass

    request.addfinalizer(finofaci)

    # Remove aci's
    suffix.remove_all('aci')

    # Add test user
    USER_DN = "uid=test,ou=people," + DEFAULT_SUFFIX
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    users.create(
        properties={
            'uid': 'test',
            'cn': 'test',
            'sn': 'test',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/test',
            'userPassword': PW_DM
        })

    # bind as user
    conn = UserAccount(topo.standalone, USER_DN).bind(PW_DM)

    # Search fo existing base DN
    test = Domain(conn, DEFAULT_SUFFIX)
    try:
        test.get_attr_vals_utf8_l('dc')
        assert False
    except IndexError:
        pass

    # Search for a non existent bases
    subtree = Domain(conn, "ou=does_not_exist," + DEFAULT_SUFFIX)
    try:
        subtree.get_attr_vals_utf8_l('objectclass')
    except IndexError:
        pass
    subtree = Domain(
        conn, "ou=also does not exist,ou=does_not_exist," + DEFAULT_SUFFIX)
    try:
        subtree.get_attr_vals_utf8_l('objectclass')
    except IndexError:
        pass
    # Try ONE level search instead of BASE
    try:
        Accounts(conn, "ou=does_not_exist," + DEFAULT_SUFFIX).filter(
            "(objectclass=top)", scope=ldap.SCOPE_ONELEVEL)
    except IndexError:
        pass

    # add aci
    suffix.add('aci', ACI)

    # Search for a non existent entry which should raise an exception
    with pytest.raises(ldap.NO_SUCH_OBJECT):
        conn = UserAccount(topo.standalone, USER_DN).bind(PW_DM)
        subtree = Domain(conn, "ou=does_not_exist," + DEFAULT_SUFFIX)
        subtree.get_attr_vals_utf8_l('objectclass')
    with pytest.raises(ldap.NO_SUCH_OBJECT):
        conn = UserAccount(topo.standalone, USER_DN).bind(PW_DM)
        subtree = Domain(
            conn, "ou=also does not exist,ou=does_not_exist," + DEFAULT_SUFFIX)
        subtree.get_attr_vals_utf8_l('objectclass')
    with pytest.raises(ldap.NO_SUCH_OBJECT):
        conn = UserAccount(topo.standalone, USER_DN).bind(PW_DM)
        DN = "ou=also does not exist,ou=does_not_exist," + DEFAULT_SUFFIX
        Accounts(conn, DN).filter("(objectclass=top)",
                                  scope=ldap.SCOPE_ONELEVEL,
                                  strict=True)
Esempio n. 10
0
def test_nsds5replicaenabled_verify(topo_m4):
    """
    Add the attribute nsds5ReplicaEnabled to cn=config
    :id: ba6dd634-e764-11e8-b158-8c16451d917b
    :setup: 4 Instances with replication
    :steps:
        1. Add the attribute nsds5ReplicaEnabled to cn=config
        2. Add data
        3. Delete data
        4. Very the replication
    :expected results:
        1. Should  success
        2. Should  success
        3. Should  success
        4. Should  success
    """
    # Add the attribute nsds5ReplicaEnabled to cn=config
    # Stop M3 and M4 instances, as not required for this test
    repl = ReplicationManager(DEFAULT_SUFFIX)
    for i in ["master3", "master4"]:
        topo_m4.all_insts.get(i).stop()
    # Adding nsds5ReplicaEnabled to M1
    topo_m4.ms["master1"].modify_s(
        topo_m4.ms["master1"].agreement.list(suffix=DEFAULT_SUFFIX)[0].dn,
        [(ldap.MOD_ADD, "nsds5ReplicaEnabled", b"on")],
    )
    topo_m4.ms["master1"].modify_s(
        topo_m4.ms["master1"].agreement.list(suffix=DEFAULT_SUFFIX)[0].dn,
        [(ldap.MOD_REPLACE, "nsds5ReplicaEnabled", b"off")],
    )
    # Adding data to Master1
    users = UserAccounts(topo_m4.ms["master1"], DEFAULT_SUFFIX)
    user_properties = {
        "uid": "test_bug834074",
        "cn": "test_bug834074",
        "sn": "test_bug834074",
        "userpassword": "******",
        "uidNumber": "1000",
        "gidNumber": "2000",
        "homeDirectory": "/home/{}".format("test_bug834074"),
    }
    users.create(properties=user_properties)
    test_user_very = users.get("test_bug834074").dn
    # No replication no data in Master2
    with pytest.raises(Exception):
        repl.wait_for_replication(topo_m4.ms["master1"], topo_m4.ms["master2"])
    # Replication on
    topo_m4.ms["master1"].modify_s(
        topo_m4.ms["master1"].agreement.list(suffix=DEFAULT_SUFFIX)[0].dn,
        [(ldap.MOD_REPLACE, "nsds5ReplicaEnabled", b"on")],
    )
    repl.wait_for_replication(topo_m4.ms["master1"], topo_m4.ms["master2"])
    # Now data is available on master2
    assert len(topo_m4.ms['master2'].search_s(test_user_very,
                                              ldap.SCOPE_SUBTREE,
                                              'objectclass=*')) == 1
    ## Stop replication to master2
    topo_m4.ms["master1"].modify_s(
        topo_m4.ms["master1"].agreement.list(suffix=DEFAULT_SUFFIX)[0].dn,
        [(ldap.MOD_REPLACE, "nsds5ReplicaEnabled", b"off")],
    )
    # Modify some data in master1
    topo_m4.ms["master1"].modrdn_s(test_user_very, 'uid=test_bug834075', 1)
    with pytest.raises(Exception):
        repl.wait_for_replication(topo_m4.ms["master1"], topo_m4.ms["master2"])
        # changes are not replicated in master2
        with pytest.raises(Exception):
            topo_m4.ms['master2'].search_s(
                'uid=test_bug834075,ou=People,{}'.format(DEFAULT_SUFFIX),
                ldap.SCOPE_SUBTREE, 'objectclass=*')
    # Turn on the replication
    topo_m4.ms["master1"].modify_s(
        topo_m4.ms["master1"].agreement.list(suffix=DEFAULT_SUFFIX)[0].dn,
        [(ldap.MOD_REPLACE, "nsds5ReplicaEnabled", b"on")],
    )
    repl.wait_for_replication(topo_m4.ms["master1"], topo_m4.ms["master2"])
    # Now same data is available in master2
    assert len(topo_m4.ms['master2'].search_s(
        'uid=test_bug834075,ou=People,{}'.format(DEFAULT_SUFFIX),
        ldap.SCOPE_SUBTREE, 'objectclass=*')) == 1
    # Turn off the replication from master1 to master2
    topo_m4.ms["master1"].modify_s(
        topo_m4.ms["master1"].agreement.list(suffix=DEFAULT_SUFFIX)[0].dn,
        [(ldap.MOD_REPLACE, "nsds5ReplicaEnabled", b"off")],
    )
    # delete some data in master1
    topo_m4.ms["master1"].delete_s(
        'uid=test_bug834075,ou=People,{}'.format(DEFAULT_SUFFIX))
    with pytest.raises(Exception):
        repl.wait_for_replication(topo_m4.ms["master1"], topo_m4.ms["master2"])
        # deleted data from master1 is still there in master2 as repliaction is off
        assert len(topo_m4.ms['master2'].search_s(
            'uid=test_bug834075,ou=People,{}'.format(DEFAULT_SUFFIX),
            ldap.SCOPE_SUBTREE, 'objectclass=*')) == 1
    topo_m4.ms["master1"].modify_s(
        topo_m4.ms["master1"].agreement.list(suffix=DEFAULT_SUFFIX)[0].dn,
        [(ldap.MOD_REPLACE, "nsds5ReplicaEnabled", b"on")],
    )
    repl.wait_for_replication(topo_m4.ms["master1"], topo_m4.ms["master2"])
    # After repliction is on same is gone from master2 also.
    with pytest.raises(ldap.NO_SUCH_OBJECT):
        topo_m4.ms['master2'].search_s(
            'uid=test_bug834075,ou=People,{}'.format(DEFAULT_SUFFIX),
            ldap.SCOPE_SUBTREE, 'objectclass=*')
    with pytest.raises(ldap.OPERATIONS_ERROR):
        topo_m4.ms["master1"].modify_s(
            topo_m4.ms["master1"].agreement.list(suffix=DEFAULT_SUFFIX)[0].dn,
            [(ldap.MOD_REPLACE, "nsds5ReplicaEnabled", b"invalid")],
        )
    for i in ["master3", "master4"]:
        topo_m4.all_insts.get(i).start()
Esempio n. 11
0
def _add_user(topo):
    """
    This function will create user for the test and in the end entries will be deleted .
    """
    role_aci_body = '(targetattr=*)(version 3.0; aci "role aci"; allow(all)'
    # Creating OUs
    ous = OrganizationalUnits(topo.standalone, DEFAULT_SUFFIX)
    ou_accounting = ous.create(properties={'ou': 'Accounting'})
    ou_accounting.set('aci', [
        f'(target="ldap:///{ROLEDNACCESS}"){role_aci_body} '
        f'userattr = "Description#ROLEDN";)',
        f'(target="ldap:///{USERDNACCESS}"){role_aci_body} '
        f'userattr = "Description#USERDN";)',
        f'(target="ldap:///{GROUPDNACCESS}"){role_aci_body} '
        f'userattr = "Description#GROUPDN";)',
        f'(target="ldap:///{LDAPURLACCESS}"){role_aci_body} '
        f'userattr = "Description#LDAPURL";)',
        f'(target="ldap:///{ATTRNAMEACCESS}"){role_aci_body} '
        f'userattr = "Description#4612";)'
    ])

    ou_inheritance = ous.create(
        properties={
            'ou': 'Inheritance',
            'street': LEVEL_4,
            'seeAlso': LEVEL_3,
            'st': LEVEL_2,
            'description': LEVEL_1,
            'businessCategory': LEVEL_0
        })

    inheritance_aci_body = '(targetattr=*)(version 3.0; aci "Inheritance aci"; allow(all) '
    ou_inheritance.set('aci', [
        f'{inheritance_aci_body} '
        f'userattr = "parent[0].businessCategory#USERDN";)',
        f'{inheritance_aci_body} '
        f'userattr = "parent[0,1].description#USERDN";)',
        f'{inheritance_aci_body} '
        f'userattr = "parent[0,1,2].st#USERDN";)', f'{inheritance_aci_body} '
        f'userattr = "parent[0,1,2,3].seeAlso#USERDN";)',
        f'{inheritance_aci_body} '
        f'userattr = "parent[0,1,2,3,4].street#USERDN";)'
    ])

    # Creating Users
    users = UserAccounts(topo.standalone, OU, rdn=None)

    for i in [['Anuj Borah', 'Sunnyvale', ROLE1, '4612'],
              ['Ananda Borah', 'Santa Clara', ROLE2, 'Its Unknown']]:
        users.create(
            properties={
                'uid': i[0],
                'cn': i[0].split()[0],
                'sn': 'user',
                'uidNumber': '1000',
                'gidNumber': '2000',
                'homeDirectory': '/home/' + i[0].split()[0],
                'userPassword': PW_DM,
                'givenname': i[0].split()[0],
                'l': i[1],
                'mail': "*****@*****.**",
                'telephonenumber': "+1 408 555 4798",
                'facsimiletelephonenumber': "+1 408 555 9751",
                'roomnumber': i[3],
                'Description': i[3],
                'nsRoleDN': i[2]
            })

    for demo1 in [('ROLEDNACCESS', ROLE1), ('USERDNACCESS', CAN),
                  ('GROUPDNACCESS', NSSIMPLEGROUP), ('ATTRNAMEACCESS', '4612'),
                  ('LDAPURLACCESS',
                   f"ldap:///{DEFAULT_SUFFIX}??sub?(l=Sunnyvale)")]:
        users.create(
            properties={
                'uid': demo1[0],
                'cn': demo1[0],
                'sn': 'user',
                'uidNumber': '1000',
                'gidNumber': '2000',
                'homeDirectory': '/home/' + demo1[0],
                'userPassword': PW_DM,
                'Description': demo1[1]
            })

    # Creating roles
    roles = ManagedRoles(topo.standalone, OU)
    for i in ['ROLE1', 'ROLE2']:
        roles.create(properties={"cn": i})

    # Creating Groups
    grps = Groups(topo.standalone, OU, rdn=None)
    for i in [('NSSIMPLEGROUP', CAN), ('NSSIMPLEGROUP1', CANNOT)]:
        grps.create(properties={'cn': i[0], 'ou': 'groups', 'member': i[1]})

    users = UserAccounts(topo.standalone, OU_2, rdn=None)
    for i in ['Grandson', 'Child', 'Parent', 'Grandparent', 'Ancestor']:
        users.create(
            properties={
                'uid': i,
                'cn': i,
                'sn': 'user',
                'uidNumber': '1000',
                'gidNumber': '2000',
                'homeDirectory': '/home/' + i,
                'userPassword': PW_DM
            })

    # Creating Other OUs
    for dn_dn in [(OU_2, 'ANCESTORS'), (ANCESTORS, 'GRANDPARENTS'),
                  (GRANDPARENTS, 'PARENTS'), (PARENTS, 'CHILDREN'),
                  (CHILDREN, 'GRANDSONS')]:
        OrganizationalUnits(topo.standalone,
                            dn_dn[0]).create(properties={'ou': dn_dn[1]})
Esempio n. 12
0
def test_ldapi_authdn_attr_rewrite(topo, request):
    """Test LDAPI Authentication DN mapping feature

    :id: e8d68979-4b3d-4e2d-89ed-f9bad827718c
    :setup: Standalone Instance
    :steps:
        1. Set LDAPI configuration
        2. Create LDAP user
        3. Create OS user
        4. Create entries under cn=config for auto bind subtree and mapping entry
        5. Do an LDAPI ldapsearch as the OS user
        6. OS user was mapped expected LDAP entry
        7. Do search using root & LDAPI
    :expectedresults:
        1. Success
        2. Success
        3. Success
        4. Success
        5. Success
        6. Success
        7. Success
    """

    LINUX_USER = "******"
    LINUX_USER2 = "ldapi_test_lib389_user2"
    LINUX_USER3 = "ldapi_test_lib389_user3"
    LINUX_PWD = "5ecret_137"
    LDAP_ENTRY_DN = "uid=test_ldapi,ou=people,dc=example,dc=com"
    LDAP_ENTRY_DN2 = "uid=test_ldapi2,ou=people,dc=example,dc=com"
    LDAP_ENTRY_DN3 = "uid=test_ldapi3,ou=people,dc=example,dc=com"
    LDAPI_AUTH_CONTAINER = "cn=auto_bind,cn=config"

    def fin():
        # Remove the OS users
        for user in [LINUX_USER, LINUX_USER2, LINUX_USER3]:
            try:
                subprocess.run(['userdel', '-r', user])
            except:
                pass

    request.addfinalizer(fin)

    # Must be root
    if os.geteuid() != 0:
        return

    # Perform config tasks
    topo.standalone.config.set('nsslapd-accesslog-logbuffering', 'off')
    topo.standalone.config.set('nsslapd-ldapiDNMappingBase',
                               'cn=auto_bind,cn=config')
    topo.standalone.config.set('nsslapd-ldapimaptoentries', 'on')
    topo.standalone.config.set('nsslapd-ldapiuidnumbertype', 'uidNumber')
    topo.standalone.config.set('nsslapd-ldapigidnumbertype', 'gidNumber')
    ldapi_socket_raw = topo.standalone.config.get_attr_val_utf8(
        'nsslapd-ldapifilepath')
    ldapi_socket = ldapi_socket_raw.replace('/', '%2F')

    # Create LDAP users
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    user_properties = {
        'uid': 'test_ldapi',
        'cn': 'test_ldapi',
        'sn': 'test_ldapi',
        'uidNumber': '2020',
        'gidNumber': '2020',
        'userpassword': '******',
        'description': 'userdesc',
        'homeDirectory': '/home/test_ldapi'
    }
    users.create(properties=user_properties)

    user_properties = {
        'uid': 'test_ldapi2',
        'cn': 'test_ldapi2',
        'sn': 'test_ldapi2',
        'uidNumber': '2021',
        'gidNumber': '2021',
        'userpassword': '******',
        'description': 'userdesc',
        'homeDirectory': '/home/test_ldapi2'
    }
    users.create(properties=user_properties)

    user_properties = {
        'uid': 'test_ldapi3',
        'cn': 'test_ldapi3',
        'sn': 'test_ldapi3',
        'uidNumber': '2023',
        'gidNumber': '2023',
        'userpassword': '******',
        'description': 'userdesc',
        'homeDirectory': '/home/test_ldapi3'
    }
    users.create(properties=user_properties)

    # Create OS users
    subprocess.run(['useradd', '-u', '5001', '-p', LINUX_PWD, LINUX_USER])
    subprocess.run(['useradd', '-u', '5002', '-p', LINUX_PWD, LINUX_USER2])

    # Create some mapping entries
    ldapi_mapping = LDAPIMapping(topo.standalone, LDAPI_AUTH_CONTAINER)
    ldapi_mapping.create_mapping(name='entry_map1',
                                 username='******',
                                 ldap_dn='uid=dummy1,dc=example,dc=com')
    ldapi_mapping.create_mapping(name='entry_map2',
                                 username=LINUX_USER,
                                 ldap_dn=LDAP_ENTRY_DN)
    ldapi_mapping.create_mapping(name='entry_map3',
                                 username='******',
                                 ldap_dn='uid=dummy3,dc=example,dc=com')

    # Restart server for config to take effect, and clear the access log
    topo.standalone.deleteAccessLogs(restart=True)

    # Bind as OS user using ldapsearch
    ldapsearch_cmd = f'ldapsearch -b \'\' -s base -Y EXTERNAL -H ldapi://{ldapi_socket}'
    os.system(f'su {LINUX_USER} -c "{ldapsearch_cmd}"')

    # Check access log
    assert topo.standalone.ds_access_log.match(
        f'.*AUTOBIND dn="{LDAP_ENTRY_DN}".*')

    # Bind as Root DN just to make sure it still works
    assert os.system(ldapsearch_cmd) == 0
    assert topo.standalone.ds_access_log.match(f'.*AUTOBIND dn="{DN_DM}".*')

    # Create some fixed mapping
    ldapi_fixed_mapping = LDAPIFixedMapping(topo.standalone,
                                            LDAPI_AUTH_CONTAINER)
    ldapi_fixed_mapping.create_mapping("fixed",
                                       "5002",
                                       "5002",
                                       ldap_dn=LDAP_ENTRY_DN2)
    topo.standalone.deleteAccessLogs(restart=True)

    # Bind as OS user using ldapsearch
    os.system(f'su {LINUX_USER2} -c "{ldapsearch_cmd}"')

    # Check access log
    assert topo.standalone.ds_access_log.match(
        f'.*AUTOBIND dn="{LDAP_ENTRY_DN2}".*')

    # Add 3rd user, and test reload task
    subprocess.run(['useradd', '-u', '5003', '-p', LINUX_PWD, LINUX_USER3])
    ldapi_fixed_mapping.create_mapping("reload",
                                       "5003",
                                       "5003",
                                       ldap_dn=LDAP_ENTRY_DN3)

    reload_task = LDAPIMappingReloadTask(topo.standalone).create()
    reload_task.wait(timeout=20)

    os.system(f'su {LINUX_USER3} -c "{ldapsearch_cmd}"')
    assert topo.standalone.ds_access_log.match(
        f'.*AUTOBIND dn="{LDAP_ENTRY_DN3}".*')
Esempio n. 13
0
def test_mentry01(topo, _create_inital):
    """Test Managed Entries basic functionality

    :id: 9b87493b-0493-46f9-8364-6099d0e5d806
    :setup: Standalone Instance
    :steps:
        1. Check the plug-in status
        2. Add Template and definition entry
        3. Add our org units
        4. Add users with PosixAccount ObjectClass and verify creation of User Private Group
        5. Disable the plug-in and check the status
        6. Enable the plug-in and check the status the plug-in is disabled and creation of UPG should fail
        7. Add users with PosixAccount ObjectClass and verify creation of User Private Group
        8. Add users, run ModRDN operation and check the User Private group
        9. Add users, run LDAPMODIFY to change the gidNumber and check the User Private group
        10. Checking whether creation of User Private group fails for existing group entry
        11. Checking whether adding of posixAccount objectClass to existing user creates UPG
        12. Running ModRDN operation and checking the user private groups mepManagedBy attribute
        13. Deleting mepManagedBy attribute and running ModRDN operation to check if it creates a new UPG
        14. Change the RDN of template entry, DSA Unwilling to perform error expected
        15. Change the RDN of cn=Users to cn=TestUsers and check UPG are deleted
    :expected results:
        1. Success
        2. Success
        3. Success
        4. Success
        5. Success
        6. Success
        7. Success
        8. Success
        9. Success
        10. Success
        11. Success
        12. Success
        13. Success
        14. Fail(Unwilling to perform )
        15. Success
    """
    # Check the plug-in status
    mana = ManagedEntriesPlugin(topo.standalone)
    assert mana.status()

    # Add Template and definition entry
    org1 = OrganizationalUnits(
        topo.standalone, DEFAULT_SUFFIX).create(properties={'ou': 'Users'})
    org2 = OrganizationalUnit(topo.standalone, f'ou=Groups,{DEFAULT_SUFFIX}')
    meps = MEPTemplates(topo.standalone, DEFAULT_SUFFIX)
    mep_template1 = meps.create(
        properties={
            'cn':
            'UPG Template1',
            'mepRDNAttr':
            'cn',
            'mepStaticAttr':
            'objectclass: posixGroup',
            'mepMappedAttr':
            'cn: $uid|gidNumber: $gidNumber|description: User private group for $uid'
            .split('|')
        })
    conf_mep = MEPConfigs(topo.standalone)
    conf_mep.create(
        properties={
            'cn': 'UPG Definition2',
            'originScope': org1.dn,
            'originFilter': 'objectclass=posixaccount',
            'managedBase': org2.dn,
            'managedTemplate': mep_template1.dn
        })

    # Add users with PosixAccount ObjectClass and verify creation of User Private Group
    user = UserAccounts(topo.standalone,
                        f'ou=Users,{DEFAULT_SUFFIX}',
                        rdn=None).create_test_user()
    assert user.get_attr_val_utf8(
        'mepManagedEntry') == f'cn=test_user_1000,ou=Groups,{DEFAULT_SUFFIX}'

    # Disable the plug-in and check the status
    mana.disable()
    user.delete()
    topo.standalone.restart()

    # Add users with PosixAccount ObjectClass when the plug-in is disabled and creation of UPG should fail
    user = UserAccounts(topo.standalone,
                        f'ou=Users,{DEFAULT_SUFFIX}',
                        rdn=None).create_test_user()
    assert not user.get_attr_val_utf8('mepManagedEntry')

    # Enable the plug-in and check the status
    mana.enable()
    user.delete()
    topo.standalone.restart()

    # Add users with PosixAccount ObjectClass and verify creation of User Private Group
    user = UserAccounts(topo.standalone,
                        f'ou=Users,{DEFAULT_SUFFIX}',
                        rdn=None).create_test_user()
    assert user.get_attr_val_utf8(
        'mepManagedEntry') == f'cn=test_user_1000,ou=Groups,{DEFAULT_SUFFIX}'

    # Add users, run ModRDN operation and check the User Private group
    # Add users, run LDAPMODIFY to change the gidNumber and check the User Private group
    user.rename(new_rdn='uid=UserNewRDN',
                newsuperior='ou=Users,dc=example,dc=com')
    assert user.get_attr_val_utf8(
        'mepManagedEntry') == f'cn=UserNewRDN,ou=Groups,{DEFAULT_SUFFIX}'
    user.replace('gidNumber', '20209')
    entry = Account(topo.standalone,
                    f'cn=UserNewRDN,ou=Groups,{DEFAULT_SUFFIX}')
    assert entry.get_attr_val_utf8('gidNumber') == '20209'
    user.replace_many(('sn', 'new_modified_sn'), ('gidNumber', '31309'))
    assert entry.get_attr_val_utf8('gidNumber') == '31309'
    user.delete()

    # Checking whether creation of User Private group fails for existing group entry
    Groups(topo.standalone, f'ou=Groups,{DEFAULT_SUFFIX}',
           rdn=None).create(properties={'cn': 'MENTRY_14'})
    user = UserAccounts(topo.standalone,
                        f'ou=Users,{DEFAULT_SUFFIX}',
                        rdn=None).create_test_user()
    with pytest.raises(ldap.NO_SUCH_OBJECT):
        entry.status()
    user.delete()

    # Checking whether adding of posixAccount objectClass to existing user creates UPG
    # Add Users without posixAccount objectClass
    users = WithObjectClass(topo.standalone,
                            f'uid=test_test, ou=Users,{DEFAULT_SUFFIX}')
    user_properties1 = {
        'uid': 'test_test',
        'cn': 'test',
        'sn': 'test',
        'mail': '*****@*****.**',
        'telephoneNumber': '123'
    }
    user = users.create(properties=user_properties1)
    assert not user.get_attr_val_utf8('mepManagedEntry')

    # Add posixAccount objectClass
    user.replace_many(
        ('objectclass', ['top', 'person', 'inetorgperson', 'posixAccount']),
        ('homeDirectory', '/home/ok'), ('uidNumber', '61603'),
        ('gidNumber', '61603'))
    assert not user.get_attr_val_utf8('mepManagedEntry')
    user = UserAccounts(topo.standalone,
                        f'ou=Users,{DEFAULT_SUFFIX}',
                        rdn=None).create_test_user()
    entry = Account(topo.standalone,
                    'cn=test_user_1000,ou=Groups,dc=example,dc=com')

    # Add inetuser objectClass
    user.replace_many(('objectclass', [
        'top', 'account', 'posixaccount', 'inetOrgPerson',
        'organizationalPerson', 'nsMemberOf', 'nsAccount', 'person',
        'mepOriginEntry', 'inetuser'
    ]), ('memberOf', entry.dn))
    assert entry.status()
    user.delete()
    user = UserAccounts(topo.standalone,
                        f'ou=Users,{DEFAULT_SUFFIX}',
                        rdn=None).create_test_user()
    entry = Account(topo.standalone,
                    'cn=test_user_1000,ou=Groups,dc=example,dc=com')

    # Add groupofNames objectClass
    user.replace_many(('objectclass', [
        'top', 'account', 'posixaccount', 'inetOrgPerson',
        'organizationalPerson', 'nsMemberOf', 'nsAccount', 'person',
        'mepOriginEntry', 'groupofNames'
    ]), ('memberOf', user.dn))
    assert entry.status()

    # Running ModRDN operation and checking the user private groups mepManagedBy
    # attribute was also reset because the modrdn on the origin will do a modrdn
    # on checkManagedEntry to match the new rdn value of the origin entry
    checkManagedEntry = UserAccounts(topo.standalone,
                                     f'ou=Groups,{DEFAULT_SUFFIX}',
                                     rdn=None)
    check_entry = checkManagedEntry.create(
        properties={
            'objectclass': ['top', 'extensibleObject'],
            'uid': 'CheckModRDN',
            'uidNumber': '12',
            'gidNumber': '12',
            'homeDirectory': '/home',
            'sn': 'tmp',
            'cn': 'tmp',
        })
    user.replace('mepManagedEntry', check_entry.dn)
    user.rename(new_rdn='uid=UserNewRDN',
                newsuperior='ou=Users,dc=example,dc=com')
    assert user.get_attr_val_utf8_l(
        'mepManagedEntry'
    ) == f'cn=UserNewRDN,ou=Groups,{DEFAULT_SUFFIX}'.lower()

    # Deleting mepManagedBy attribute and running ModRDN operation to check if it creates a new UPG
    user.remove('mepManagedEntry', f'cn=UserNewRDN,ou=Groups,{DEFAULT_SUFFIX}')
    user.rename(new_rdn='uid=UserNewRDN1',
                newsuperior='ou=Users,dc=example,dc=com')
    assert user.get_attr_val_utf8(
        'mepManagedEntry') == f'cn=UserNewRDN1,ou=Groups,{DEFAULT_SUFFIX}'

    # Change the RDN of template entry, DSA Unwilling to perform error expected
    mep = MEPTemplate(topo.standalone, f'cn=UPG Template,{DEFAULT_SUFFIX}')
    with pytest.raises(ldap.UNWILLING_TO_PERFORM):
        mep.rename(new_rdn='cn=UPG Template2', newsuperior='dc=example,dc=com')

    # Change the RDN of cn=Users to cn=TestUsers and check UPG are deleted
    before = user.get_attr_val_utf8('mepManagedEntry')
    user.rename(new_rdn='uid=Anuj', newsuperior='ou=Users,dc=example,dc=com')
    assert user.get_attr_val_utf8('mepManagedEntry') != before
Esempio n. 14
0
def _create_test_entries(topo):
    """
    :param topo:
    :return: Will create users used for this test script .
    """
    users_people = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    for demo1 in LIST_OF_USER:
        users_people.create(properties={
            'uid': demo1,
            'cn': demo1,
            'sn': demo1,
            'uidNumber': str(1000),
            'gidNumber': '2000',
            'homeDirectory': '/home/' + demo1,
            'givenname': demo1,
            'userpassword': PW_DM
        })

    users_people.create(properties={
        'uid': 'bhall',
        'cn': 'Benjamin Hall',
        'sn': 'Hall',
        'uidNumber': str(1000),
        'gidNumber': '2000',
        'homeDirectory': '/home/' + 'bhall',
        'mail': '*****@*****.**',
        'givenname': 'Benjamin',
        'ou': ['Product Development', 'People'],
        'l': 'sunnyvale',
        'telephonenumber': '+1 408 555 6067',
        'roomnumber': '2511',
        'manager': 'uid=trigden, ou=People, dc=example, dc=com',
        'nsRoleDN': 'cn=new managed role, ou=People, dc=example, dc=com',
        'userpassword': PW_DM,
    })

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

    ous = OrganizationalUnits(topo.standalone, ou_ou.dn)
    ous.create(properties={'ou': 'MailSchemeClasses'})

    Schema(topo.standalone).\
        add('attributetypes', "( 9.9.8.4 NAME 'emailclass' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 "
                              "X-ORIGIN 'RFC 2256' )")
    Schema(topo.standalone).\
        add('objectclasses', "( 9.9.8.2 NAME 'mailSchemeUser' DESC "
                             "'User Defined ObjectClass' SUP 'top' MUST "
                             "( objectclass )  MAY (aci $ emailclass) X-ORIGIN 'RFC 2256' )")

    users_people.create(properties={
        'cn': 'Randy Jensen',
        'sn': 'Jensen',
        'givenname': 'Randy',
        'objectclass': 'top account person organizationalPerson inetOrgPerson mailSchemeUser '
                       'mailRecipient posixaccount'.split(),
        'l': 'sunnyvale',
        'uid': 'rjense2',
        'uidNumber': str(1000),
        'gidNumber': str(1000),
        'homeDirectory': '/home/' + 'rjense2',
        'mail': '*****@*****.**',
        'telephonenumber': '+1 408 555 9045',
        'roomnumber': '1984',
        'manager': 'uid=jwalker, ou=People, dc=example,dc=com',
        'nsRoleDN': 'cn=new managed role, ou=People, dc=example, dc=com',
        'emailclass': 'vpemail',
        'mailquota': '600',
        'userpassword': PW_DM,
    })

    users_people.create(properties={
        'cn': 'Bjorn Talbot',
        'sn': 'Talbot',
        'givenname': 'Bjorn',
        'objectclass': 'top account person organizationalPerson inetOrgPerson posixaccount'.split(),
        'ou': ['Product Development', 'People'],
        'l': 'Santa Clara',
        'uid': 'btalbo2',
        'mail': '*****@*****.**',
        'telephonenumber': '+1 408 555 4234',
        'roomnumber': '1205',
        'uidNumber': str(1000),
        'gidNumber': str(1000),
        'homeDirectory': '/home/' + 'btalbo2',
        'manager': 'uid=trigden, ou=People, dc=example,dc=com',
        'nsRoleDN': 'cn=new managed role, ou=People, dc=example, dc=com',
        'userpassword': PW_DM
    })

    users_people.create(properties={
        'objectclass': 'top '
                       'account '
                       'person '
                       'organizationalPerson '
                       'inetOrgPerson '
                       'mailRecipient '
                       'mailSchemeUser '
                       'posixaccount'.split(),
        'cn': 'Matthew Tyler',
        'sn': 'Tyler',
        'givenname': 'Matthew',
        'ou': ['Human Resources', 'People'],
        'l': 'Cupertino',
        'uid': 'mtyler',
        'mail': '*****@*****.**',
        'telephonenumber': '+1 408 555 7907',
        'roomnumber': '2701',
        'uidNumber': str(1000),
        'gidNumber': str(1000),
        'homeDirectory': '/home/' + 'mtyler',
        'manager': 'uid=jwalker, ou=People, dc=example,dc=com',
        'nsRoleDN': 'cn=new managed role, ou=People, dc=example, dc=com',
        'mailquota': '600',
        'userpassword': PW_DM})
Esempio n. 15
0
def test_managedrole(topo):
    """Test Managed Role

    :id: d52a9c00-3bf6-11e9-9b7b-8c16451d917b
    :setup: server
    :steps:
        1. Add test entry
        2. Add ACI
        3. Search managed role entries
    :expectedresults:
        1. Entry should be added
        2. Operation should  succeed
        3. Operation should  succeed
    """
    # Create Managed role entry
    roles = ManagedRoles(topo.standalone, DEFAULT_SUFFIX)
    role = roles.create(properties={"cn": 'ROLE1'})

    # Create user and Assign the role to the entry
    uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=None)
    uas.create(
        properties={
            'uid': 'Fail',
            'cn': 'Fail',
            'sn': 'user',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/' + 'Fail',
            'nsRoleDN': role.dn,
            'userPassword': PW_DM
        })

    # Create user and do not Assign any role to the entry
    uas.create(
        properties={
            'uid': 'Success',
            'cn': 'Success',
            'sn': 'user',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/' + 'Success',
            'userPassword': PW_DM
        })

    # Assert that Manage role entry is created and its searchable
    assert ManagedRoles(topo.standalone, DEFAULT_SUFFIX).list()[0].dn \
           == 'cn=ROLE1,dc=example,dc=com'

    # Set an aci that will deny  ROLE1 manage role
    Domain(topo.standalone, DEFAULT_SUFFIX).\
        add('aci', '(targetattr=*)(version 3.0; aci "role aci";'
                   ' deny(all) roledn="ldap:///{}";)'.format(role.dn),)

    # Crate a connection with cn=Fail which is member of ROLE1
    conn = UserAccount(topo.standalone,
                       "uid=Fail,{}".format(DEFAULT_SUFFIX)).bind(PW_DM)
    # Access denied to ROLE1 members
    assert not ManagedRoles(conn, DEFAULT_SUFFIX).list()

    # Now create a connection with cn=Success which is not a member of ROLE1
    conn = UserAccount(topo.standalone,
                       "uid=Success,{}".format(DEFAULT_SUFFIX)).bind(PW_DM)
    # Access allowed here
    assert ManagedRoles(conn, DEFAULT_SUFFIX).list()

    for i in uas.list():
        i.delete()

    for i in roles.list():
        i.delete()
Esempio n. 16
0
def test_retrocl_exclude_attr_mod(topology_st):
    """ Test exclude attribute feature of the retrocl plugin for mod operation

    :id: f6bef689-685b-4f86-a98d-f7e6b1fcada3

    :setup: Standalone instance

    :steps:
        1. Enable dynamic plugins
        2. Confige retro changelog plugin
        3. Add user1 entry
        4. Ensure entry attrs are in the changelog
        5. Exclude an attr
        6. Modify user1 entry
        7. Ensure excluded attr is not in the changelog

    :expectedresults:
        1. Success
        2. Success
        3. Success
        4. Success
        5. Success
        6. Success
        7. Success
    """

    st = topology_st.standalone

    log.info('Configure retrocl plugin')
    rcl = RetroChangelogPlugin(st)
    rcl.disable()
    rcl.enable()
    rcl.replace('nsslapd-attribute', 'nsuniqueid:targetUniqueId')

    log.info('Restarting instance')
    try:
        st.restart()
    except ldap.LDAPError as e:
        ldap.error('Failed to restart instance ' + e.args[0]['desc'])
        assert False

    users = UserAccounts(st, DEFAULT_SUFFIX)

    log.info('Adding user1')
    try:
        user1 = users.create(
            properties={
                'sn': '1',
                'cn': 'user 1',
                'uid': 'user1',
                'uidNumber': '11',
                'gidNumber': '111',
                'givenname': 'user1',
                'homePhone': '0861234567',
                'carLicense': '131D16674',
                'mail': '*****@*****.**',
                'homeDirectory': '/home/user1',
                'userpassword': USER_PW
            })
    except ldap.ALREADY_EXISTS:
        user1 = UserAccount(st, dn=USER1_DN)
    except ldap.LDAPError as e:
        log.error("Failed to add user1: " + str(e))

    log.info(
        'Verify homePhone and carLicense attrs are in the changelog changestring'
    )
    try:
        retro_changelog_suffix = DSLdapObjects(st, basedn=RETROCL_SUFFIX)
        cllist = retro_changelog_suffix.filter(f'(targetDn={USER1_DN})')
    except ldap.LDAPError as e:
        log.fatal("Changelog search failed, error: " + str(e))
        assert False
    assert len(cllist) > 0
    if cllist[0].present('changes'):
        clstr = str(cllist[0].get_attr_vals_utf8('changes'))
        assert ATTR_HOMEPHONE in clstr
        assert ATTR_CARLICENSE in clstr

    log.info('Excluding attribute ' + ATTR_CARLICENSE)
    args = FakeArgs()
    args.connections = [
        st.host + ':' + str(st.port) + ':' + DN_DM + ':' + PW_DM
    ]
    args.instance = 'standalone1'
    args.basedn = None
    args.binddn = None
    args.starttls = False
    args.pwdfile = None
    args.bindpw = None
    args.prompt = False
    args.exclude_attrs = ATTR_CARLICENSE
    args.func = retrochangelog_add
    dsrc_inst = dsrc_arg_concat(args, None)
    inst = connect_instance(dsrc_inst, False, args)
    result = args.func(inst, None, log, args)
    disconnect_instance(inst)
    assert result is None

    log.info('Restarting instance')
    try:
        st.restart()
    except ldap.LDAPError as e:
        ldap.error('Failed to restart instance ' + e.args[0]['desc'])
        assert False

    log.info('Modify user1 carLicense attribute')
    try:
        user1.replace(ATTR_CARLICENSE, "123WX321")
    except ldap.LDAPError as e:
        log.fatal(
            'test_retrocl_exclude_attr_mod: Failed to update user1 attribute: error '
            + e.message['desc'])
        assert False

    log.info('Verify carLicense attr is not in the changelog changestring')
    try:
        cllist = retro_changelog_suffix.filter(f'(targetDn={USER1_DN})')
        assert len(cllist) > 0
        # There will be 2 entries in the changelog for this user, we are only
        #interested in the second one, the modify operation.
        if cllist[1].present('changes'):
            clstr = str(cllist[1].get_attr_vals_utf8('changes'))
            assert ATTR_CARLICENSE not in clstr
    except ldap.LDAPError as e:
        log.fatal("Changelog search failed, error: " + str(e))
        assert False
Esempio n. 17
0
def test_fetch_bindDnGroup(topo_m2):
    """Check the bindDNGroup is fetched on first replication session

    :id: 5f1b1f59-6744-4260-b091-c82d22130025
    :setup: 2 Master Instances
    :steps:
        1. Create a replication bound user and group, but the user *not* member of the group
        2. Check that replication is working
        3. Some preparation is required because of lib389 magic that already define a replication via group
           - define the group as groupDN for replication and 60sec as fetch interval
           - pause RA in both direction
           - Define the user as bindDn of the RAs
        4. restart servers.
            It sets the fetch time to 0, so next session will refetch the group
        5. Before resuming RA, add user to groupDN (on both side as replication is not working at that time)
        6. trigger an update and check replication is working and
           there is no failure logged on supplier side 'does not have permission to supply replication updates to the replica'
    :expectedresults:
        1. Success
        2. Success
        3. Success
        4. Success
        5. Success
        6. Success
    """

    # If you need any test suite initialization,
    # please, write additional fixture for that (including finalizer).
    # Topology for suites are predefined in lib389/topologies.py.

    # If you need host, port or any other data about instance,
    # Please, use the instance object attributes for that (for example, topo.ms["master1"].serverid)
    M1 = topo_m2.ms['master1']
    M2 = topo_m2.ms['master2']

    # Enable replication log level. Not really necessary
    M1.modify_s('cn=config',
                [(ldap.MOD_REPLACE, 'nsslapd-errorlog-level', b'8192')])
    M2.modify_s('cn=config',
                [(ldap.MOD_REPLACE, 'nsslapd-errorlog-level', b'8192')])

    # Create a group and a user
    PEOPLE = "ou=People,%s" % SUFFIX
    PASSWD = 'password'
    REPL_MGR_BOUND_DN = 'repl_mgr_bound_dn'

    uid = REPL_MGR_BOUND_DN.encode()
    users = UserAccounts(M1, PEOPLE, rdn=None)
    user_props = TEST_USER_PROPERTIES.copy()
    user_props.update({
        'uid': uid,
        'cn': uid,
        'sn': '_%s' % uid,
        'userpassword': PASSWD.encode(),
        'description': b'value creation'
    })
    create_user = users.create(properties=user_props)

    groups_M1 = Groups(M1, DEFAULT_SUFFIX)
    group_properties = {'cn': 'group1', 'description': 'testgroup'}
    group_M1 = groups_M1.create(properties=group_properties)
    group_M2 = Group(M2, group_M1.dn)
    assert (not group_M1.is_member(create_user.dn))

    # Check that M1 and M2 are in sync
    repl = ReplicationManager(DEFAULT_SUFFIX)
    repl.wait_for_replication(M1, M2, timeout=20)

    # Define the group as the replication manager and fetch interval as 60sec
    replicas = Replicas(M1)
    replica = replicas.list()[0]
    replica.apply_mods([
        (ldap.MOD_REPLACE, 'nsDS5ReplicaBindDnGroupCheckInterval', '60'),
        (ldap.MOD_REPLACE, 'nsDS5ReplicaBindDnGroup', group_M1.dn)
    ])

    replicas = Replicas(M2)
    replica = replicas.list()[0]
    replica.apply_mods([
        (ldap.MOD_REPLACE, 'nsDS5ReplicaBindDnGroupCheckInterval', '60'),
        (ldap.MOD_REPLACE, 'nsDS5ReplicaBindDnGroup', group_M1.dn)
    ])

    # Then pause the replication agreement to prevent them trying to acquire
    # while the user is not member of the group
    topo_m2.pause_all_replicas()

    # Define the user as the bindDN of the RAs
    for inst in (M1, M2):
        agmts = Agreements(inst)
        agmt = agmts.list()[0]
        agmt.replace('nsDS5ReplicaBindDN', create_user.dn.encode())
        agmt.replace('nsds5ReplicaCredentials', PASSWD.encode())

    # Key step
    # The restart will fetch the group/members define in the replica
    #
    # The user NOT member of the group replication will not work until bindDNcheckInterval
    #
    # With the fix, the first fetch is not taken into account (fetch time=0)
    # so on the first session, the group will be fetched
    M1.restart()
    M2.restart()

    # Replication being broken here we need to directly do the same update.
    # Sorry not found another solution except total update
    group_M1.add_member(create_user.dn)
    group_M2.add_member(create_user.dn)

    topo_m2.resume_all_replicas()

    # trigger updates to be sure to have a replication session, giving some time
    M1.modify_s(create_user.dn, [(ldap.MOD_ADD, 'description', b'value_1_1')])
    M2.modify_s(create_user.dn, [(ldap.MOD_ADD, 'description', b'value_2_2')])
    time.sleep(10)

    # Check replication is working
    ents = M1.search_s(create_user.dn, ldap.SCOPE_BASE, '(objectclass=*)')
    for ent in ents:
        assert (ent.hasAttr('description'))
        found = 0
        for val in ent.getValues('description'):
            if (val == b'value_1_1'):
                found = found + 1
            elif (val == b'value_2_2'):
                found = found + 1
        assert (found == 2)

    ents = M2.search_s(create_user.dn, ldap.SCOPE_BASE, '(objectclass=*)')
    for ent in ents:
        assert (ent.hasAttr('description'))
        found = 0
        for val in ent.getValues('description'):
            if (val == b'value_1_1'):
                found = found + 1
            elif (val == b'value_2_2'):
                found = found + 1
        assert (found == 2)

    # Check in the logs that the member was detected in the group although
    # at startup it was not member of the group
    regex = re.compile(
        "does not have permission to supply replication updates to the replica."
    )
    errorlog_M1 = open(M1.errlog, "r")
    errorlog_M2 = open(M1.errlog, "r")

    # Find the last restart position
    restart_location_M1 = find_start_location(errorlog_M1, 2)
    assert (restart_location_M1 != -1)
    restart_location_M2 = find_start_location(errorlog_M2, 2)
    assert (restart_location_M2 != -1)

    # Then check there is no failure to authenticate
    count = pattern_errorlog(errorlog_M1,
                             regex,
                             start_location=restart_location_M1)
    assert (count <= 1)
    count = pattern_errorlog(errorlog_M2,
                             regex,
                             start_location=restart_location_M2)
    assert (count <= 1)

    if DEBUGGING:
        # Add debugging steps(if any)...
        pass
Esempio n. 18
0
def test_retrocl_exclude_attr_add(topology_st):
    """ Test exclude attribute feature of the retrocl plugin for add operation

    :id: 3481650f-2070-45ef-9600-2500cfc51559

    :setup: Standalone instance

    :steps:
        1. Enable dynamic plugins
        2. Confige retro changelog plugin
        3. Add an entry
        4. Ensure entry attrs are in the changelog
        5. Exclude an attr
        6. Add another entry
        7. Ensure excluded attr is not in the changelog

    :expectedresults:
        1. Success
        2. Success
        3. Success
        4. Success
        5. Success
        6. Success
        7. Success
    """

    st = topology_st.standalone

    log.info('Configure retrocl plugin')
    rcl = RetroChangelogPlugin(st)
    rcl.disable()
    rcl.enable()
    rcl.replace('nsslapd-attribute', 'nsuniqueid:targetUniqueId')

    log.info('Restarting instance')
    try:
        st.restart()
    except ldap.LDAPError as e:
        ldap.error('Failed to restart instance ' + e.args[0]['desc'])
        assert False

    users = UserAccounts(st, DEFAULT_SUFFIX)

    log.info('Adding user1')
    try:
        users.create(
            properties={
                'sn': '1',
                'cn': 'user 1',
                'uid': 'user1',
                'uidNumber': '11',
                'gidNumber': '111',
                'givenname': 'user1',
                'homePhone': '0861234567',
                'carLicense': '131D16674',
                'mail': '*****@*****.**',
                'homeDirectory': '/home/user1',
                'userpassword': USER_PW
            })
    except ldap.ALREADY_EXISTS:
        pass
    except ldap.LDAPError as e:
        log.error("Failed to add user1: " + str(e))

    log.info(
        'Verify homePhone and carLicense attrs are in the changelog changestring'
    )
    try:
        retro_changelog_suffix = DSLdapObjects(st, basedn=RETROCL_SUFFIX)
        cllist = retro_changelog_suffix.filter(f'(targetDn={USER1_DN})')
    except ldap.LDAPError as e:
        log.fatal("Changelog search failed, error: " + str(e))
        assert False
    assert len(cllist) > 0
    if cllist[0].present('changes'):
        clstr = str(cllist[0].get_attr_vals_utf8('changes'))
        assert ATTR_HOMEPHONE in clstr
        assert ATTR_CARLICENSE in clstr

    log.info('Excluding attribute ' + ATTR_HOMEPHONE)
    args = FakeArgs()
    args.connections = [
        st.host + ':' + str(st.port) + ':' + DN_DM + ':' + PW_DM
    ]
    args.instance = 'standalone1'
    args.basedn = None
    args.binddn = None
    args.starttls = False
    args.pwdfile = None
    args.bindpw = None
    args.prompt = False
    args.exclude_attrs = ATTR_HOMEPHONE
    args.func = retrochangelog_add
    dsrc_inst = dsrc_arg_concat(args, None)
    inst = connect_instance(dsrc_inst, False, args)
    result = args.func(inst, None, log, args)
    disconnect_instance(inst)
    assert result is None

    log.info('Restarting instance')
    try:
        st.restart()
    except ldap.LDAPError as e:
        ldap.error('Failed to restart instance ' + e.args[0]['desc'])
        assert False

    log.info('Adding user2')
    try:
        users.create(
            properties={
                'sn': '2',
                'cn': 'user 2',
                'uid': 'user2',
                'uidNumber': '22',
                'gidNumber': '222',
                'givenname': 'user2',
                'homePhone': '0879088363',
                'carLicense': '04WX11038',
                'mail': '*****@*****.**',
                'homeDirectory': '/home/user2',
                'userpassword': USER_PW
            })
    except ldap.ALREADY_EXISTS:
        pass
    except ldap.LDAPError as e:
        log.error("Failed to add user2: " + str(e))

    log.info('Verify homePhone attr is not in the changelog changestring')
    try:
        cllist = retro_changelog_suffix.filter(f'(targetDn={USER2_DN})')
        assert len(cllist) > 0
        if cllist[0].present('changes'):
            clstr = str(cllist[0].get_attr_vals_utf8('changes'))
            assert ATTR_HOMEPHONE not in clstr
            assert ATTR_CARLICENSE in clstr
    except ldap.LDAPError as e:
        log.fatal("Changelog search failed, error: " + str(e))
        assert False
Esempio n. 19
0
def moddn_setup(topology_m2):
    """Creates
       - a staging DIT
       - a production DIT
       - add accounts in staging DIT
       - enable ACL logging (commented for performance reason)
    """

    m1 = topology_m2.ms["master1"]
    o_roles = OrganizationalRoles(m1, SUFFIX)

    m1.log.info("\n\n######## INITIALIZATION ########\n")

    # entry used to bind with
    m1.log.info("Add {}".format(BIND_DN))
    user = UserAccount(m1, BIND_DN)
    user_props = TEST_USER_PROPERTIES.copy()
    user_props.update({
        'sn': BIND_RDN,
        'cn': BIND_RDN,
        'uid': BIND_RDN,
        'userpassword': BIND_PW
    })
    user.create(properties=user_props, basedn=SUFFIX)

    # Add anonymous read aci
    ACI_TARGET = "(target = \"ldap:///%s\")(targetattr=\"*\")" % (SUFFIX)
    ACI_ALLOW = "(version 3.0; acl \"Anonymous Read access\"; allow (read,search,compare)"
    ACI_SUBJECT = " userdn = \"ldap:///anyone\";)"
    ACI_BODY = ACI_TARGET + ACI_ALLOW + ACI_SUBJECT
    suffix = Domain(m1, SUFFIX)
    suffix.add('aci', ACI_BODY)

    # DIT for staging
    m1.log.info("Add {}".format(STAGING_DN))
    o_roles.create(properties={'cn': STAGING_CN, 'description': "staging DIT"})

    # DIT for production
    m1.log.info("Add {}".format(PRODUCTION_DN))
    o_roles.create(properties={
        'cn': PRODUCTION_CN,
        'description': "production DIT"
    })

    # DIT for production/except
    m1.log.info("Add {}".format(PROD_EXCEPT_DN))
    o_roles_prod = OrganizationalRoles(m1, PRODUCTION_DN)
    o_roles_prod.create(properties={
        'cn': EXCEPT_CN,
        'description': "production except DIT"
    })

    # enable acl error logging
    # mod = [(ldap.MOD_REPLACE, 'nsslapd-errorlog-level', '128')]
    # m1.modify_s(DN_CONFIG, mod)
    # topology_m2.ms["master2"].modify_s(DN_CONFIG, mod)

    # add dummy entries in the staging DIT
    staging_users = UserAccounts(m1, SUFFIX, rdn="cn={}".format(STAGING_CN))
    user_props = TEST_USER_PROPERTIES.copy()
    for cpt in range(MAX_ACCOUNTS):
        name = "{}{}".format(NEW_ACCOUNT, cpt)
        user_props.update({'sn': name, 'cn': name, 'uid': name})
        staging_users.create(properties=user_props)
Esempio n. 20
0
def test_critical_msg_on_empty_range_idl(topology_st):
    """Doing a range index lookup should not report a critical message even if IDL is empty

    :id: a07a2222-0551-44a6-b113-401d23799364
    :setup: Standalone instance
    :steps:
         1. Create an index for internationalISDNNumber. (attribute chosen because it is
         unlikely that previous tests used it)
         2. telephoneNumber being indexed by default create 20 users without telephoneNumber
         3. add a telephoneNumber value and delete it to trigger an empty index database
         4. Do a search that triggers a range lookup on empty telephoneNumber
         5. Check that the critical message is not logged in error logs
    :expectedresults:
         1. This should pass
         2. This should pass
         3. This should pass
         4. This should pass on normal build but could abort a debug build
         4. This should pass
    """
    indexedAttr = 'internationalISDNNumber'

    # Step 1
    from lib389.index import Indexes

    indexes = Indexes(topology_st.standalone)
    indexes.create(properties={
        'cn': indexedAttr,
        'nsSystemIndex': 'false',
        'nsIndexType': 'eq'
    })
    topology_st.standalone.restart()

    # Step 2
    users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
    log.info('Adding 20 users without "%s"' % indexedAttr)
    for i in range(20):
        name = 'user_%d' % i
        last_user = users.create(
            properties={
                'uid': name,
                'sn': name,
                'cn': name,
                'uidNumber': '1000',
                'gidNumber': '1000',
                'homeDirectory': '/home/%s' % name,
                'mail': '*****@*****.**' % name,
                'userpassword': '******' % name,
            })

    # Step 3
    # required update to create the indexAttr (i.e. 'loginShell') database, and then make it empty
    topology_st.standalone.modify_s(last_user.dn,
                                    [(ldap.MOD_ADD, indexedAttr, b'1234')])
    ent = topology_st.standalone.getEntry(
        last_user.dn,
        ldap.SCOPE_BASE,
    )
    assert ent
    assert ent.hasAttr(indexedAttr)
    topology_st.standalone.modify_s(last_user.dn,
                                    [(ldap.MOD_DELETE, indexedAttr, None)])
    ent = topology_st.standalone.getEntry(
        last_user.dn,
        ldap.SCOPE_BASE,
    )
    assert ent
    assert not ent.hasAttr(indexedAttr)

    # Step 4
    # The first component being not indexed the range on second is evaluated
    try:
        ents = topology_st.standalone.search_s(
            DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE,
            '(&(sudoNotAfter=*)(%s>=111))' % indexedAttr)
        assert len(ents) == 0
    except ldap.SERVER_DOWN:
        log.error('Likely testing against a debug version that asserted')
        pass

    # Step 5
    assert not topology_st.standalone.searchErrorsLog(
        'CRIT - list_candidates - NULL idl was recieved from filter_candidates_ext.'
    )
Esempio n. 21
0
def test_user(request, topo):
    for demo in ['Product Development', 'Accounting', 'Product Testing', 'nestedgroup', 'ACLGroup']:
        OrganizationalUnit(topo.standalone, "ou={},{}".format(demo, DEFAULT_SUFFIX)).create(properties={'ou': demo})

    user = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn='ou=Accounting')
    for demo1 in ['Ted Morris', 'David Miller']:
        user.create(properties= {
            'uid': demo1,
            'cn': demo1,
            'sn': 'user',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/' + demo1,
            'userPassword': PW_DM
        })

    # Add anonymous access aci
    ACI_TARGET = "(targetattr=\"*\")(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(topo.standalone, DEFAULT_SUFFIX)
    suffix.add('aci', ANON_ACI)

    uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX, 'ou=nestedgroup')
    for demo1 in ['DEEPUSER_GLOBAL', 'scratchEntry', 'DEEPUSER2_GLOBAL', 'DEEPUSER1_GLOBAL',
                  'DEEPUSER3_GLOBAL', 'GROUPDNATTRSCRATCHENTRY_GLOBAL', 'newChild']:
        uas.create(properties={
            'uid': demo1,
            'cn': demo1,
            'sn': 'user',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/' + demo1,
            'userPassword': PW_DM
        })

    uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX, 'uid=GROUPDNATTRSCRATCHENTRY_GLOBAL,ou=nestedgroup')
    for demo1 in ['c1', 'CHILD1_GLOBAL']:
        uas.create(properties={
            'uid': demo1,
            'cn': demo1,
            'sn': 'user',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/' + demo1,
            'userPassword': PW_DM
        })

    grp = UniqueGroups(topo.standalone, DEFAULT_SUFFIX, rdn='ou=nestedgroup')
    for i in [('ALLGROUPS_GLOBAL', GROUPA_GLOBAL), ('GROUPA_GLOBAL', GROUPB_GLOBAL), ('GROUPB_GLOBAL', GROUPC_GLOBAL),
              ('GROUPC_GLOBAL', GROUPD_GLOBAL), ('GROUPD_GLOBAL', GROUPE_GLOBAL), ('GROUPE_GLOBAL', GROUPF_GLOBAL),
              ('GROUPF_GLOBAL', GROUPG_GLOBAL), ('GROUPG_GLOBAL', GROUPH_GLOBAL), ('GROUPH_GLOBAL', DEEPUSER_GLOBAL)]:
        grp.create(properties={'cn': i[0],
                               'ou': 'groups',
                               'uniquemember': i[1]
                               })

    grp = UniqueGroup(topo.standalone, 'cn=BIG_GLOBAL Group,{}'.format(DEFAULT_SUFFIX))
    grp.create(properties={'cn': 'BIG_GLOBAL Group',
                           'ou': 'groups',
                           'uniquemember': ["uid=Ted Morris,ou=Accounting,{}".format(DEFAULT_SUFFIX),
                                            "uid=David Miller,ou=Accounting,{}".format(DEFAULT_SUFFIX),]
                           })
Esempio n. 22
0
def password_policy(topology_st):
    """Set up password policy
    Create a Password Admin entry;
    Set up password policy attributes in config;
    Add an aci to give everyone full access;
    Test that the setup works
    """

    log.info('test_pwdAdmin_init: Creating Password Administrator entries...')

    users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
    groups = Groups(topology_st.standalone, DEFAULT_SUFFIX)

    # Add Password Admin 1
    admin1_user = users.create(
        properties={
            'uid': 'admin1',
            'cn': 'admin1',
            'sn': 'strator',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/admin1',
            'userPassword': ADMIN_PWD
        })

    # Add Password Admin 2

    admin2_user = users.create(
        properties={
            'uid': 'admin2',
            'cn': 'admin2',
            'sn': 'strator',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/admin2',
            'userPassword': ADMIN_PWD
        })

    # Add Password Admin Group

    admin_group = groups.create(properties={'cn': 'password admin group'})

    admin_group.add_member(admin1_user.dn)
    admin_group.add_member(admin2_user.dn)

    # Configure password policy

    log.info('test_pwdAdmin_init: Configuring password policy...')

    topology_st.standalone.config.replace_many(
        ('nsslapd-pwpolicy-local', 'on'), ('passwordCheckSyntax', 'on'),
        ('passwordMinCategories', '1'), ('passwordMinTokenLength', '2'),
        ('passwordExp', 'on'), ('passwordMinDigits', '1'),
        ('passwordMinSpecials', '1'))

    #
    # Add an aci to allow everyone all access (just makes things easier)
    #
    log.info('Add aci to allow password admin to add/update entries...')

    domain = Domain(topology_st.standalone, DEFAULT_SUFFIX)

    ACI_TARGET = "(target = \"ldap:///%s\")" % SUFFIX
    ACI_TARGETATTR = "(targetattr = *)"
    ACI_ALLOW = "(version 3.0; acl \"Password Admin Access\"; allow (all) "
    ACI_SUBJECT = "(userdn = \"ldap:///anyone\");)"
    ACI_BODY = ACI_TARGET + ACI_TARGETATTR + ACI_ALLOW + ACI_SUBJECT

    domain.add('aci', ACI_BODY)

    #
    # Bind as the future Password Admin
    #
    log.info(
        'test_pwdAdmin_init: Bind as the Password Administrator (before activating)...'
    )
    admin_conn = admin1_user.bind(ADMIN_PWD)

    #
    # Setup our test entry, and test password policy is working
    #

    # Connect up an admin authed users connection.
    admin_users = UserAccounts(admin_conn, DEFAULT_SUFFIX)

    #
    # Start by attempting to add an entry with an invalid password
    #
    log.info(
        'test_pwdAdmin_init: Attempt to add entries with invalid passwords, these adds should fail...'
    )
    for passwd in INVALID_PWDS:
        with pytest.raises(ldap.CONSTRAINT_VIOLATION):
            admin_users.create(
                properties={
                    'uid': 'example',
                    'cn': 'example',
                    'sn': 'example',
                    'uidNumber': '1000',
                    'gidNumber': '2000',
                    'homeDirectory': '/home/example',
                    'userPassword': passwd
                })

    return (admin_group, admin1_user, admin2_user)
Esempio n. 23
0
def test_cleanallruv_repl(topo_m3):
    """Test that cleanallruv could not break replication if anchor csn in ruv originated in deleted replica
    :id: 46faba9a-897e-45b8-98dc-aec7fa8cec9a
    :setup: 3 Masters
    :steps:
        1. Configure error log level to 8192 in all masters
        2. Modify nsslapd-changelogmaxage=30 and nsslapd-changelogtrim-interval=5 for M1 and M2
        3. Add test users to 3 masters
        4. Launch ClearRuv but withForce
        5. Check the users after CleanRUV, because of changelog trimming, it will effect the CLs
    :expectedresults:
        1. Error logs should be configured successfully
        2. Modify should be successful
        3. Test users should be added successfully
        4. ClearRuv should be launched successfully
        5. Users should be present according to the changelog trimming effect
    """

    M1 = topo_m3.ms["master1"]
    M2 = topo_m3.ms["master2"]
    M3 = topo_m3.ms["master3"]

    log.info("Change the error log levels for all masters")
    for s in (M1, M2, M3):
        s.config.replace('nsslapd-errorlog-level', "8192")

    log.info("Get the replication agreements for all 3 masters")
    m1_m2 = M1.agreement.list(suffix=SUFFIX,
                              consumer_host=M2.host,
                              consumer_port=M2.port)
    m1_m3 = M1.agreement.list(suffix=SUFFIX,
                              consumer_host=M3.host,
                              consumer_port=M3.port)
    m3_m1 = M3.agreement.list(suffix=SUFFIX,
                              consumer_host=M1.host,
                              consumer_port=M1.port)

    log.info("Get the changelog enteries for M1 and M2")
    changelog_m1 = Changelog5(M1)
    changelog_m2 = Changelog5(M2)

    log.info(
        "Modify nsslapd-changelogmaxage=30 and nsslapd-changelogtrim-interval=5 for M1 and M2"
    )
    changelog_m1.set_max_age(MAXAGE_STR)
    changelog_m1.set_trim_interval(TRIMINTERVAL_STR)

    log.info("Add test users to 3 masters")
    users_m1 = UserAccounts(M1, DEFAULT_SUFFIX)
    users_m2 = UserAccounts(M2, DEFAULT_SUFFIX)
    users_m3 = UserAccounts(M3, DEFAULT_SUFFIX)
    user_props = TEST_USER_PROPERTIES.copy()

    user_props.update({'uid': "testuser10"})
    user10 = users_m1.create(properties=user_props)

    user_props.update({'uid': "testuser20"})
    user20 = users_m2.create(properties=user_props)

    user_props.update({'uid': "testuser30"})
    user30 = users_m3.create(properties=user_props)

    # ::important:: the testuser31 is the oldest csn in M2,
    # because it will be cleared by changelog trimming
    user_props.update({'uid': "testuser31"})
    user31 = users_m3.create(properties=user_props)

    user_props.update({'uid': "testuser11"})
    user11 = users_m1.create(properties=user_props)

    user_props.update({'uid': "testuser21"})
    user21 = users_m2.create(properties=user_props)
    # this is to trigger changelog trim and interval values
    time.sleep(40)

    # Here M1, M2, M3 should have 11,21,31 and 10,20,30 are CL cleared
    M2.stop()
    M1.agreement.pause(m1_m2[0].dn)
    user_props.update({'uid': "testuser32"})
    user32 = users_m3.create(properties=user_props)

    user_props.update({'uid': "testuser33"})
    user33 = users_m3.create(properties=user_props)

    user_props.update({'uid': "testuser12"})
    user12 = users_m1.create(properties=user_props)

    M3.agreement.pause(m3_m1[0].dn)
    M3.agreement.resume(m3_m1[0].dn)
    time.sleep(40)

    # Here because of changelog trimming testusers 31 and 32 are CL cleared
    # ClearRuv is launched but with Force
    M3.stop()
    M1.tasks.cleanAllRUV(suffix=SUFFIX,
                         replicaid='3',
                         force=True,
                         args={TASK_WAIT: False})

    # here M1 should clear 31
    M2.start()
    M1.agreement.pause(m1_m2[0].dn)
    M1.agreement.resume(m1_m2[0].dn)
    time.sleep(10)

    #Check the users after CleanRUV
    expected_m1_users = [
        user31.dn, user11.dn, user21.dn, user32.dn, user33.dn, user12.dn
    ]
    expected_m2_users = [user31.dn, user11.dn, user21.dn, user12.dn]
    current_m1_users = [user.dn for user in users_m1.list()]
    current_m2_users = [user.dn for user in users_m2.list()]

    assert set(expected_m1_users).issubset(current_m1_users)
    assert set(expected_m2_users).issubset(current_m2_users)
Esempio n. 24
0
def test_operation_with_nsslapd_disk_monitoring_logging_critical_off(topo, setup, reset_logs):
    """
    Verify operation with \"nsslapd-disk-monitoring-logging-critical: off
    :id: 97985a52-fe9e-11e8-9914-8c16451d917b
    :setup: Standalone
    :steps:
        1. Verify that logging is disabled
        2. Verify that rotated logs were removed
        3. Verify that verbose logging was set to default level
        4. Verify that logging is disabled
        5. Verify that rotated logs were removed
    :expectedresults:
        1. Should Success
        2. Should Success
        3. Should Success
        4. Should Success
        5. Should Success
    """
    # Verify that logging is disabled
    try:
        assert topo.standalone.config.set('nsslapd-disk-monitoring', 'on')
        assert topo.standalone.config.set('nsslapd-disk-monitoring-logging-critical', 'off')
        assert topo.standalone.config.set('nsslapd-errorlog-level', '8')
        assert topo.standalone.config.set('nsslapd-accesslog-maxlogsize', '1')
        assert topo.standalone.config.set('nsslapd-accesslog-logrotationtimeunit', 'minute')
        assert topo.standalone.config.set('nsslapd-accesslog-level', '772')
        topo.standalone.restart()
        # Verify that rotated logs were removed
        users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
        for i in range(10):
            user_properties = {
                'uid': 'cn=anuj{}'.format(i),
                'cn': 'cn=anuj{}'.format(i),
                'sn': 'cn=anuj{}'.format(i),
                'userPassword': "******",
                'uidNumber': '1{}'.format(i),
                'gidNumber': '2{}'.format(i),
                'homeDirectory': '/home/{}'.format(i)
            }
            users.create(properties=user_properties)
        for j in range(100):
            for i in [i for i in users.list()]: i.bind('Itsme123')
        assert re.findall(r'access.\d+-\d+',str(os.listdir(topo.standalone.ds_paths.log_dir)))
        topo.standalone.bind_s(DN_DM, PW_DM)
        assert topo.standalone.config.set('nsslapd-accesslog-maxlogsize', '100')
        assert topo.standalone.config.set('nsslapd-accesslog-logrotationtimeunit', 'day')
        assert topo.standalone.config.set('nsslapd-accesslog-level', '256')
        topo.standalone.restart()
        subprocess.call(['dd', 'if=/dev/zero', 'of={}/foo2'.format(topo.standalone.ds_paths.log_dir), 'bs=1M', 'count={}'.format(HALF_THR_FILL_SIZE)])
        # Verify that verbose logging was set to default level
        _witherrorlog(topo, 'temporarily setting error loglevel to the default level', 10)
        assert LOG_DEFAULT == int(re.findall(r'nsslapd-errorlog-level: \d+', str(
            topo.standalone.search_s('cn=config', ldap.SCOPE_SUBTREE, '(objectclass=*)', ['nsslapd-errorlog-level'])))[0].split(' ')[1])
        # Verify that logging is disabled
        _withouterrorlog(topo, "topo.standalone.config.get_attr_val_utf8('nsslapd-accesslog-logging-enabled') != 'off'", 20)
        with open(topo.standalone.errlog, 'r') as study: study = study.read()
        assert 'disabling access and audit logging' in study
        # Verify that rotated logs were removed
        _witherrorlog(topo, 'deleting rotated logs', 10)
        with open(topo.standalone.errlog, 'r') as study:study = study.read()
        assert 'Unable to remove file:' not in study
        assert 'is too far below the threshold' not in study
        for i in [i for i in users.list()]: i.delete()
    finally:
        os.remove('{}/foo2'.format(topo.standalone.ds_paths.log_dir))
Esempio n. 25
0
def test_ignore_virtual_attrs(topo):
    """Test nsslapd-ignore-virtual-attrs configuration attribute

    :id: 9915d71b-2c71-4ac0-91d7-92655d53541b
    :setup: Standalone instance
    :steps:
         1. Check the attribute nsslapd-ignore-virtual-attrs is present in cn=config
         2. Check the default value of attribute nsslapd-ignore-virtual-attrs should be OFF
         3. Set the valid values i.e. on/ON and off/OFF for nsslapd-ignore-virtual-attrs
         4. Set invalid value for attribute nsslapd-ignore-virtual-attrs
         5. Set nsslapd-ignore-virtual-attrs=off
         6. Add cosPointer, cosTemplate and test entry to default suffix, where virtual attribute is postal code
         7. Test if virtual attribute i.e. postal code shown in test entry while nsslapd-ignore-virtual-attrs: off
         8. Set nsslapd-ignore-virtual-attrs=on
         9. Test if virtual attribute i.e. postal code not shown while nsslapd-ignore-virtual-attrs: on
    :expectedresults:
         1. This should be successful
         2. This should be successful
         3. This should be successful
         4. This should fail
         5. This should be successful
         6. This should be successful
         7. Postal code should be present
         8. This should be successful
         9. Postal code should not be present
    """

    log.info("Check the attribute nsslapd-ignore-virtual-attrs is present in cn=config")
    assert topo.standalone.config.present('nsslapd-ignore-virtual-attrs')

    log.info("Check the default value of attribute nsslapd-ignore-virtual-attrs should be OFF")
    assert topo.standalone.config.get_attr_val_utf8('nsslapd-ignore-virtual-attrs') == "off"

    log.info("Set the valid values i.e. on/ON and off/OFF for nsslapd-ignore-virtual-attrs")
    for attribute_value in ['on', 'off', 'ON', 'OFF']:
        topo.standalone.config.set('nsslapd-ignore-virtual-attrs', attribute_value)
        assert topo.standalone.config.present('nsslapd-ignore-virtual-attrs', attribute_value)

    log.info("Set invalid value for attribute nsslapd-ignore-virtual-attrs")
    with pytest.raises(ldap.OPERATIONS_ERROR):
        topo.standalone.config.set('nsslapd-ignore-virtual-attrs', 'invalid_value')

    cos_template_properties = {
        'cn': 'cosTemplateExample',
        'postalcode': '117'
    }
    cos_templates = CosTemplates(topo.standalone, DEFAULT_SUFFIX, 'ou=People')
    test_cos_template = cos_templates.create(properties=cos_template_properties)

    log.info("Add cosPointer, cosTemplate and test entry to default suffix, where virtual attribute is postal code")
    cos_pointer_properties = {
        'cn': 'cosPointer',
        'description': 'cosPointer example',
        'cosTemplateDn': 'cn=cosTemplateExample,ou=People,dc=example,dc=com',
        'cosAttribute': 'postalcode',
    }
    cos_pointer_definitions = CosPointerDefinitions(topo.standalone, DEFAULT_SUFFIX, 'ou=People')
    test_cos_pointer_definition = cos_pointer_definitions.create(properties=cos_pointer_properties)

    test_users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    test_user = test_users.create(properties=TEST_USER_PROPERTIES)

    log.info("Test if virtual attribute i.e. postal code shown in test entry while nsslapd-ignore-virtual-attrs: off")
    assert test_user.present('postalcode', '117')

    log.info("Set nsslapd-ignore-virtual-attrs=on")
    topo.standalone.config.set('nsslapd-ignore-virtual-attrs', 'on')

    log.info("Test if virtual attribute i.e. postal code not shown while nsslapd-ignore-virtual-attrs: on")
    assert not test_user.present('postalcode', '117')
Esempio n. 26
0
def test_operation_with_nsslapd_disk_monitoring_logging_critical_off_below_half_of_the_threshold(topo, setup, reset_logs):
    """
    Verify operation with \"nsslapd-disk-monitoring-logging-critical: off\" below 1/2 of the threshold
    Verify shutdown
    Recovery and setup
    :id: 9d4c7d48-fe9e-11e8-b5d6-8c16451d917b
    :setup: Standalone
    :steps:
        1. Verify that DS goes into shutdown mode
        2. Verifying that DS has been shut down after the grace period
        3. Verify logging enabled
        4. Create rotated logfile
        5. Enable verbose logging
    :expectedresults:
        1. Should Success
        2. Should Success
        3. Should Success
        4. Should Success
        5. Should Success
    """
    assert topo.standalone.config.set('nsslapd-disk-monitoring', 'on')
    assert topo.standalone.config.set('nsslapd-disk-monitoring-logging-critical', 'off')
    topo.standalone.restart()
    # Verify that DS goes into shutdown mode
    if float(THRESHOLD) > FULL_THR_FILL_SIZE:
        FULL_THR_FILL_SIZE_new = FULL_THR_FILL_SIZE + round(float(THRESHOLD) - FULL_THR_FILL_SIZE)
        subprocess.call(['dd', 'if=/dev/zero', 'of={}/foo'.format(topo.standalone.ds_paths.log_dir), 'bs=1M', 'count={}'.format(FULL_THR_FILL_SIZE_new)])
    else:
        subprocess.call(['dd', 'if=/dev/zero', 'of={}/foo'.format(topo.standalone.ds_paths.log_dir), 'bs=1M', 'count={}'.format(FULL_THR_FILL_SIZE)])
    # Increased sleep to avoid failure
    _witherrorlog(topo, 'is too far below the threshold', 100)
    _witherrorlog(topo, 'Signaling slapd for shutdown', 2)
    # Verifying that DS has been shut down after the grace period
    assert topo.standalone.status() == False
    # free_space
    os.remove('{}/foo'.format(topo.standalone.ds_paths.log_dir))
    open('{}/errors'.format(topo.standalone.ds_paths.log_dir), 'w').close()
    # StartSlapd
    topo.standalone.start()
    # verify logging enabled
    assert topo.standalone.config.get_attr_val_utf8('nsslapd-accesslog-logging-enabled') == 'on'
    assert topo.standalone.config.get_attr_val_utf8('nsslapd-errorlog-logging-enabled') == 'on'
    with open(topo.standalone.errlog, 'r') as study: study = study.read()
    assert 'disabling access and audit logging' not in study
    assert topo.standalone.config.set('nsslapd-accesslog-maxlogsize', '1')
    assert topo.standalone.config.set('nsslapd-accesslog-logrotationtimeunit', 'minute')
    assert topo.standalone.config.set('nsslapd-accesslog-level', '772')
    topo.standalone.restart()
    # create rotated logfile
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    for i in range(10):
        user_properties = {
            'uid': 'cn=anuj{}'.format(i),
            'cn': 'cn=anuj{}'.format(i),
            'sn': 'cn=anuj{}'.format(i),
            'userPassword': "******",
            'uidNumber': '1{}'.format(i),
            'gidNumber': '2{}'.format(i),
            'homeDirectory': '/home/{}'.format(i)
        }
        users.create(properties=user_properties)
    for j in range(100):
        for i in [i for i in users.list()]: i.bind('Itsme123')
    assert re.findall(r'access.\d+-\d+',str(os.listdir(topo.standalone.ds_paths.log_dir)))
    topo.standalone.bind_s(DN_DM, PW_DM)
    # enable verbose logging
    assert topo.standalone.config.set('nsslapd-accesslog-maxlogsize', '100')
    assert topo.standalone.config.set('nsslapd-accesslog-logrotationtimeunit', 'day')
    assert topo.standalone.config.set('nsslapd-accesslog-level', '256')
    assert topo.standalone.config.set('nsslapd-errorlog-level', '8')
    topo.standalone.restart()
    for i in [i for i in users.list()]: i.delete()
Esempio n. 27
0
def test_memberof_with_repl(topo):
    """Test that we allowed to enable MemberOf plugin in dedicated consumer

    :id: 60c11636-55a1-4704-9e09-2c6bcc828de4
    :setup: 1 Master - 1 Hub - 1 Consumer
    :steps:
        1. Configure replication to EXCLUDE memberof
        2. Enable memberof plugin
        3. Create users/groups
        4. Make user_0 member of group_0
        5. Checks that user_0 is memberof group_0 on M,H,C
        6. Make group_0 member of group_1 (nest group)
        7. Checks that user_0 is memberof group_0 and group_1 on M,H,C
        8. Check group_0 is memberof group_1 on M,H,C
        9. Remove group_0 from group_1
        10. Check group_0 and user_0 are NOT memberof group_1 on M,H,C
        11. Remove user_0 from group_0
        12. Check user_0 is not memberof group_0 and group_1 on M,H,C
        13. Disable memberof on C
        14. make user_0 member of group_1
        15. Checks that user_0 is memberof group_0 on M,H but not on C
        16. Enable memberof on C
        17. Checks that user_0 is memberof group_0 on M,H but not on C
        18. Run memberof fixup task
        19. Checks that user_0 is memberof group_0 on M,H,C
    :expectedresults:
        1. Configuration should be successful
        2. Plugin should be enabled
        3. Users and groups should be created
        4. user_0 should be member of group_0
        5. user_0 should be memberof group_0 on M,H,C
        6. group_0 should be member of group_1
        7. user_0 should be memberof group_0 and group_1 on M,H,C
        8. group_0 should be memberof group_1 on M,H,C
        9. group_0 from group_1 removal should be successful
        10. group_0 and user_0 should not be memberof group_1 on M,H,C
        11. user_0 from group_0 remove should be successful
        12. user_0 should not be memberof group_0 and group_1 on M,H,C
        13. memberof should be disabled on C
        14. user_0 should be member of group_1
        15. user_0 should be memberof group_0 on M,H and should not on C
        16. Enable memberof on C should be successful
        17. user_0 should be memberof group_0 on M,H should not on C
        18. memberof fixup task should be successful
        19. user_0 should be memberof group_0 on M,H,C
    """

    M1 = topo.ms["master1"]
    H1 = topo.hs["hub1"]
    C1 = topo.cs["consumer1"]

    # Step 1 & 2
    M1.config.enable_log('audit')
    config_memberof(M1)
    M1.restart()

    H1.config.enable_log('audit')
    config_memberof(H1)
    H1.restart()

    C1.config.enable_log('audit')
    config_memberof(C1)
    C1.restart()

    #Declare lists of users and groups
    test_users = []
    test_groups = []

    # Step 3
    #In for loop create users and add them in the user list
    #it creates user_0 to user_9 (range is fun)
    for i in range(10):
        CN = '%s%d' % (USER_CN, i)
        users = UserAccounts(M1, SUFFIX)
        user_props = TEST_USER_PROPERTIES.copy()
        user_props.update({'uid': CN, 'cn': CN, 'sn': '_%s' % CN})
        testuser = users.create(properties=user_props)
        time.sleep(2)
        test_users.append(testuser)

    #In for loop create groups and add them to the group list
    #it creates group_0 to group_2 (range is fun)
    for i in range(3):
        CN = '%s%d' % (GROUP_CN, i)
        groups = Groups(M1, SUFFIX)
        testgroup = groups.create(properties={'cn': CN})
        time.sleep(2)
        test_groups.append(testgroup)

    # Step 4
    #Now start testing by adding differnt user to differn group
    if not ds_is_older('1.3.7'):
        test_groups[0].remove('objectClass', 'nsMemberOf')

    member_dn = test_users[0].dn
    grp0_dn = test_groups[0].dn
    grp1_dn = test_groups[1].dn

    test_groups[0].add_member(member_dn)
    time.sleep(5)

    # Step 5
    for i in [M1, H1, C1]:
        _find_memberof(i, member_dn, grp0_dn)

    # Step 6
    test_groups[1].add_member(test_groups[0].dn)
    time.sleep(5)

    # Step 7
    for i in [grp0_dn, grp1_dn]:
        for inst in [M1, H1, C1]:
            _find_memberof(inst, member_dn, i)

    # Step 8
    for i in [M1, H1, C1]:
        _find_memberof(i, grp0_dn, grp1_dn)

    # Step 9
    test_groups[1].remove_member(test_groups[0].dn)
    time.sleep(5)

    # Step 10
    # For negative testcase, we are using assertionerror
    for inst in [M1, H1, C1]:
        for i in [grp0_dn, member_dn]:
            with pytest.raises(AssertionError):
                _find_memberof(inst, i, grp1_dn)

    # Step 11
    test_groups[0].remove_member(member_dn)
    time.sleep(5)

    # Step 12
    for inst in [M1, H1, C1]:
        for grp in [grp0_dn, grp1_dn]:
            with pytest.raises(AssertionError):
                _find_memberof(inst, member_dn, grp)

    # Step 13
    C1.plugins.disable(name=PLUGIN_MEMBER_OF)
    C1.restart()

    # Step 14
    test_groups[0].add_member(member_dn)
    time.sleep(5)

    # Step 15
    for i in [M1, H1]:
        _find_memberof(i, member_dn, grp0_dn)
    with pytest.raises(AssertionError):
        _find_memberof(C1, member_dn, grp0_dn)

    # Step 16
    memberof = MemberOfPlugin(C1)
    memberof.enable()
    C1.restart()

    # Step 17
    for i in [M1, H1]:
        _find_memberof(i, member_dn, grp0_dn)
    with pytest.raises(AssertionError):
        _find_memberof(C1, member_dn, grp0_dn)

    # Step 18
    memberof.fixup(SUFFIX)
    time.sleep(5)

    # Step 19
    for i in [M1, H1, C1]:
        _find_memberof(i, member_dn, grp0_dn)
Esempio n. 28
0
def test_hide_unhashed_pwd(topology_st):
    """Change userPassword, enable hiding of un-hashed
    password and check the audit logs.

    :id: c4a5d08d-f525-459b-82b9-3f68dae6fc71
    :setup: Standalone instance
    :steps:
        1. Add a test user entry
        2. Set a new password for user and nsslapd-auditlog-logging-enabled to 'on'
        3. Disable nsslapd-auditlog-logging-hide-unhashed-pw
        4. Check the audit logs
        5. Set a new password for user and nsslapd-auditlog-logging-hide-unhashed-pw to 'on'
        6. Check the audit logs
    :expectedresults:
        1. User addition should be successful
        2. New password should be set and audit logs should be enabled
        3. Operation should be successful
        4. Audit logs should show password without hash
        5. Operation should be successful
        6. Audit logs should hide password which is un-hashed
     """

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

    # Enable the audit log
    topology_st.standalone.config.set('nsslapd-auditlog-logging-enabled', 'on')

    # Allow the unhashed password to be written to audit log
    topology_st.standalone.config.set(
        'nsslapd-auditlog-logging-hide-unhashed-pw', 'off')
    topology_st.standalone.config.set('nsslapd-unhashed-pw-switch', 'on')

    # Set new password, and check the audit log
    user.reset_password('mypassword')

    # Check audit log
    time.sleep(1)
    if not topology_st.standalone.searchAuditLog(
            'unhashed#user#password: mypassword'):
        log.fatal('failed to find unhashed password in auditlog')
        assert False

    # Hide unhashed password in audit log
    topology_st.standalone.config.set(
        'nsslapd-auditlog-logging-hide-unhashed-pw', 'on')

    # Modify password, and check the audit log
    user.reset_password('hidepassword')

    # Check audit log
    time.sleep(1)
    if topology_st.standalone.searchAuditLog(
            'unhashed#user#password: hidepassword'):
        log.fatal('Found unhashed password in auditlog')
        assert False

    log.info('Test complete')
Esempio n. 29
0
def test_user_compare(topology):
    """
    Testing compare function

    :id: 26f2dea9-be1e-48ca-bcea-79592823390c

    :setup: Standalone instance

    :steps:
        1. Testing comparison of two different users.
        2. Testing comparison of 'str' object with itself.
        3. Testing comparison of user with similar user (different object id).
        4. Testing comparison of user with group.

    :expectedresults:
        1. Should fail to compare
        2. Should raise value error
        3. Should be the same despite uuid difference
        4. Should fail to compare
    """
    users = UserAccounts(topology.standalone, DEFAULT_SUFFIX)
    groups = Groups(topology.standalone, DEFAULT_SUFFIX)
    # Create 1st user
    user1_properties = {
        'uid': 'testuser1',
        'cn': 'testuser1',
        'sn': 'user',
        'uidNumber': '1000',
        'gidNumber': '2000',
        'homeDirectory': '/home/testuser1'
    }

    users.create(properties=user1_properties)
    testuser1 = users.get('testuser1')
    # Create 2nd user
    user2_properties = {
        'uid': 'testuser2',
        'cn': 'testuser2',
        'sn': 'user',
        'uidNumber': '1001',
        'gidNumber': '2002',
        'homeDirectory': '/home/testuser2'
    }

    users.create(properties=user2_properties)
    testuser2 = users.get('testuser2')
    # create group
    group_properties = {
        'cn' : 'group1',
        'description' : 'testgroup'
    }

    testuser1_copy = users.get("testuser1")
    group = groups.create(properties=group_properties)

    assert UserAccount.compare(testuser1, testuser2) is False

    with pytest.raises(ValueError):
        UserAccount.compare("test_str_object","test_str_object")

    assert UserAccount.compare(testuser1, testuser1_copy)
    assert UserAccount.compare(testuser1, group) is False
Esempio n. 30
0
def test_ri_and_mep_cache_corruption(topology_st):
    """Test RI plugin aborts change after MEP plugin fails.
    This is really testing the entry cache for corruption

    :id: 70d0b96e-b693-4bf7-bbf5-102a66ac5995

    :setup: Standalone instance

    :steps: 1. Enable and configure mep and ri plugins
            2. Add user and add it to a group
            3. Disable MEP plugin and remove MEP group
            4. Delete user
            5. Check that user is still a member of the group

    :expectedresults:
            1. Success
            2. Success
            3. Success
            4. It fails with NO_SUCH_OBJECT
            5. Success

    """
    # Start plugins
    topology_st.standalone.config.set('nsslapd-dynamic-plugins', 'on')
    mep_plugin = ManagedEntriesPlugin(topology_st.standalone)
    mep_plugin.enable()
    ri_plugin = ReferentialIntegrityPlugin(topology_st.standalone)
    ri_plugin.enable()

    # Add our org units
    ous = OrganizationalUnits(topology_st.standalone, DEFAULT_SUFFIX)
    ou_people = ous.create(properties={'ou': 'managed_people'})
    ou_groups = ous.create(properties={'ou': 'managed_groups'})

    # Configure MEP
    mep_templates = MEPTemplates(topology_st.standalone, DEFAULT_SUFFIX)
    mep_template1 = mep_templates.create(
        properties={
            'cn':
            'MEP template',
            'mepRDNAttr':
            'cn',
            'mepStaticAttr':
            'objectclass: posixGroup|objectclass: extensibleObject'.split('|'),
            'mepMappedAttr':
            'cn: $cn|uid: $cn|gidNumber: $uidNumber'.split('|')
        })
    mep_configs = MEPConfigs(topology_st.standalone)
    mep_configs.create(
        properties={
            'cn': 'config',
            'originScope': ou_people.dn,
            'originFilter': 'objectclass=posixAccount',
            'managedBase': ou_groups.dn,
            'managedTemplate': mep_template1.dn
        })

    # Add an entry that meets the MEP scope
    users = UserAccounts(topology_st.standalone,
                         DEFAULT_SUFFIX,
                         rdn='ou={}'.format(ou_people.rdn))
    user = users.create(
        properties={
            'uid': 'test-user1',
            'cn': 'test-user',
            'sn': 'test-user',
            'uidNumber': '10011',
            'gidNumber': '20011',
            'homeDirectory': '/home/test-user1'
        })

    # Add group
    groups = Groups(topology_st.standalone, DEFAULT_SUFFIX)
    user_group = groups.ensure_state(properties={
        'cn': 'group',
        'member': user.dn
    })

    # Check if a managed group entry was created
    mep_group = Group(topology_st.standalone,
                      dn='cn={},{}'.format(user.rdn, ou_groups.dn))
    if not mep_group.exists():
        log.fatal("MEP group was not created for the user")
        assert False

    # Test MEP be txn pre op failure does not corrupt entry cache
    # Should get the same exception for both rename attempts
    with pytest.raises(ldap.UNWILLING_TO_PERFORM):
        mep_group.rename("cn=modrdn group")

    with pytest.raises(ldap.UNWILLING_TO_PERFORM):
        mep_group.rename("cn=modrdn group")

    # Mess with MEP so it fails
    mep_plugin.disable()
    mep_group.delete()
    mep_plugin.enable()

    # Add another group to verify entry cache is not corrupted
    test_group = groups.create(properties={'cn': 'test_group'})

    # Delete user, should fail in MEP be txn post op, and user should still be a member
    with pytest.raises(ldap.NO_SUCH_OBJECT):
        user.delete()

    # Verify membership is intact
    if not user_group.is_member(user.dn):
        log.fatal(
            "Member was incorrectly removed from the group!!  Or so it seems")

        # Restart server and test again in case this was a cache issue
        topology_st.standalone.restart()
        if user_group.is_member(user.dn):
            log.info("The entry cache was corrupted")
            assert False

        assert False

    # Verify test group is still found in entry cache by deleting it
    test_group.delete()

    # Success
    log.info("Test PASSED")