コード例 #1
0
ファイル: storage_test.py プロジェクト: zero804/389-ds-base
def user_config(topo, field_value):
    """
    Will set storage schema and create user.
    """
    Config(topo.standalone).replace("passwordStorageScheme", field_value)
    user = UserAccounts(topo.standalone, DEFAULT_SUFFIX).create_test_user()
    user.set('userpassword', 'ItsMeAnuj')
    return user
コード例 #2
0
def change_passwd(topo):
    log.info(
        'Reset user password as the user, then re-bind as Directory Manager')
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    user = users.get('test entry')
    user.rebind(USER_PW)
    user.reset_password(USER_PW)
    topo.standalone.simple_bind(DN_DM, PASSWORD)
コード例 #3
0
def test_referral_during_tot(topology_m2):

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

    users = UserAccounts(master2, DEFAULT_SUFFIX)

    u = users.create(properties=TEST_USER_PROPERTIES)
    u.set('userPassword', 'password')

    binddn = u.dn
    bindpw = 'password'

    # Create a bunch of entries on master1
    ldif_dir = master1.get_ldif_dir()
    import_ldif = ldif_dir + '/ref_during_tot_import.ldif'
    dbgen(master1, 10000, import_ldif, DEFAULT_SUFFIX)

    master1.stop()
    master1.ldif2db(bename=None,
                    excludeSuffixes=None,
                    encrypt=False,
                    suffixes=[DEFAULT_SUFFIX],
                    import_file=import_ldif)
    master1.start()
    # Recreate the user on m1 also, so that if the init finishes first ew don't lose the user on m2
    users = UserAccounts(master1, DEFAULT_SUFFIX)
    u = users.create(properties=TEST_USER_PROPERTIES)
    u.set('userPassword', 'password')
    # Now export them to master2
    master1.agreement.init(DEFAULT_SUFFIX, HOST_MASTER_2, PORT_MASTER_2)

    # While that's happening try to bind as a user to master 2
    # This should trigger the referral code.
    referred = False
    for i in range(0, 100):
        conn = ldap.initialize(master2.toLDAPURL())
        conn.set_option(ldap.OPT_REFERRALS, False)
        try:
            conn.simple_bind_s(binddn, bindpw)
            conn.unbind_s()
        except ldap.REFERRAL:
            referred = True
            break
    # Means we never go a referral, should not happen!
    assert referred
コード例 #4
0
def test_dna_interval_with_different_values(topology_st, dna_plugin,
                                            attr_value):
    """Test the dna interval with different values

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

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

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

        # Check that instance did not crashed
        assert topology_st.standalone.status()
コード例 #5
0
def test_check_jpeg_attr_state(topo, attr_name, attr_value, oper_type,
                               exp_values, oper_attr):
    """Modify user's jpegphoto attribute and check if jpegphoto attribute is added/modified/deleted
    and operational attributes vucsn, adcsn and vdcsn are present.

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

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

    tuser.set(attr_name, attr_value, eval(oper_type))
    log.info('Check if list of jpeg attributes are present for a given entry')
    assert sorted([i.decode() for i in tuser.get_attr_vals(attr_name)
                   ]) == sorted(exp_values)
    log.info('Checking if operational attributes are present for cn')
    _check_user_oper_attrs(topo, tuser, attr_name, attr_value, oper_type,
                           exp_values, oper_attr)
コード例 #6
0
def test_export_import_plaintext(topo, enable_user_attr_encryption):
    """Configure attribute encryption, store some data, check that we can export the plain text

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

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

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

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

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

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

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

    log.info("Check that the attribute is imported properly")
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    user = users.get('testuser')
    assert user.present("telephoneNumber")
コード例 #7
0
ファイル: misc_test.py プロジェクト: tbordaz/389-ds-base
def test_memberurl_needs_to_be_normalized(topo, clean, aci_of_user):
    """Non-regression test for BUG 326000: MemberURL needs to be normalized

    :id: a5d172e6-7db8-11e8-aca7-8c16451d917b
    :setup: Standalone Instance
    :steps:
        1. Add test entry
        2. Add ACI
        3. User should follow ACI role
    :expectedresults:
        1. Entry should be added
        2. Operation should  succeed
        3. Operation should  succeed
    """
    ou_ou = OrganizationalUnit(topo.standalone,
                               "ou=PEOPLE,{}".format(DEFAULT_SUFFIX))
    ou_ou.set(
        'aci', '(targetattr= *)'
        '(version 3.0; acl "tester"; allow(all) '
        'groupdn = "ldap:///cn =DYNGROUP,ou=PEOPLE, {}";)'.format(
            DEFAULT_SUFFIX))

    groups = Groups(topo.standalone, DEFAULT_SUFFIX, rdn='ou=PEOPLE')
    groups.create(
        properties={
            "cn":
            "DYNGROUP",
            "description":
            "DYNGROUP",
            'objectClass':
            'groupOfURLS',
            'memberURL':
            "ldap:///ou=PEOPLE,{}??sub?"
            "(uid=test_user_2)".format(DEFAULT_SUFFIX)
        })

    uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    for demo1 in [(1, "Entry to test rights on."), (2, "Member of DYNGROUP")]:
        user = uas.create_test_user(uid=demo1[0], gid=demo1[0])
        user.replace_many(('description', demo1[1]), ('userPassword', PW_DM))

    ##with normal aci
    conn = UserAccount(topo.standalone, uas.list()[1].dn).bind(PW_DM)
    harry = UserAccount(conn, uas.list()[1].dn)
    harry.add('sn', 'FRED')

    ##with abnomal aci
    dygrp = Group(topo.standalone, DYNGROUP)
    dygrp.remove(
        'memberurl',
        "ldap:///ou=PEOPLE,{}??sub?(uid=test_user_2)".format(DEFAULT_SUFFIX))
    dygrp.add(
        'memberurl',
        "ldap:///ou=PEOPLE,{}??sub?(uid=tesT_UsEr_2)".format(DEFAULT_SUFFIX))
    harry.add('sn', 'Not FRED')

    for i in uas.list():
        i.delete()
コード例 #8
0
def test_create(topology):
    """Test to create a replica agreement and initialize the consumer.
    Test on a unknown suffix
    """

    topology.supplier.log.info("\n\n##############\n## CREATE\n##############\n")
    properties = {RA_NAME: ('meTo_%s:%d' % (topology.consumer.host,
                                            topology.consumer.port)),
                  RA_BINDDN: defaultProperties[REPLICATION_BIND_DN],
                  RA_BINDPW: defaultProperties[REPLICATION_BIND_PW],
                  RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD],
                  RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]}
    repl_agreement = topology.supplier.agreement.create(
        suffix=SUFFIX, host=topology.consumer.host,
        port=topology.consumer.port, properties=properties)
    topology.supplier.log.debug("%s created" % repl_agreement)
    topology.supplier.agreement.init(SUFFIX, HOST_CONSUMER, PORT_CONSUMER)
    topology.supplier.waitForReplInit(repl_agreement)

    supplier_users = UserAccounts(topology.supplier, SUFFIX)
    consumer_users = UserAccounts(topology.consumer, SUFFIX)

    testuser = supplier_users.create(properties=TEST_USER_PROPERTIES)
    testuser_dn = testuser.dn

    # Add a test entry
    # Check replication is working
    loop = 0
    while loop <= 10:
        try:
            consumer_users.get(dn=testuser_dn)
            break
        except ldap.NO_SUCH_OBJECT:
            time.sleep(1)
            loop += 1
    assert loop <= 10

    # Check that with an invalid suffix it raises NoSuchEntryError
    with pytest.raises(NoSuchEntryError):
        properties = {RA_NAME: r'meAgainTo_%s:%d' %
                      (topology.consumer.host, topology.consumer.port)}
        topology.supplier.agreement.create(suffix="ou=dummy",
                                           host=topology.consumer.host,
                                           port=topology.consumer.port,
                                           properties=properties)
コード例 #9
0
    def _remove_users():
        topo = topology_st.standalone
        users = UserAccounts(topo, DEFAULT_SUFFIX)
        entries = users.list()
        assert len(entries) > 0

        log.info("Removing all added users")
        for entry in entries:
            delete_obj(entry)
コード例 #10
0
def test_audit_log_rotate_and_check_string(
        topology_st, clean_access_logs, set_audit_log_config_values_to_rotate):
    """Version string should be logged only once at the top of audit log
    after it is rotated.

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

    :setup: Standalone instance

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

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

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

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

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

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

    standalone.stop()

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

        log.info('Check that DS string is present only once')
        for line in f.readlines():
            if search_ds in line:
                count += 1
        assert count == 1
コード例 #11
0
def test_account_locking(topology):
    """Test the eduperson schema works

    :id: f2f15449-a822-4ec6-b4ea-bd6db6240a6c

    :setup: Standalone instance

    :steps:
        1. Add a common user
        2. Extend the user with eduPerson objectClass
        3. Add attributes in eduPerson

    :expectedresults:
        1. User should be added with its properties
        2. User should be extended with eduPerson as the objectClass
        3. eduPerson should be added
    """

    if DEBUGGING:
        # Add debugging steps(if any)...
        pass

    users = UserAccounts(topology.standalone, DEFAULT_SUFFIX)

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

    # Extend the user with eduPerson
    testuser.add('objectClass', 'eduPerson')

    # now add eduPerson attrs
    testuser.add('eduPersonAffiliation', 'value')  # From 2002
    testuser.add('eduPersonNickName', 'value')  # From 2002
    testuser.add('eduPersonOrgDN',
                 'ou=People,%s' % DEFAULT_SUFFIX)  # From 2002
    testuser.add('eduPersonOrgUnitDN',
                 'ou=People,%s' % DEFAULT_SUFFIX)  # From 2002
    testuser.add('eduPersonPrimaryAffiliation', 'value')  # From 2002
    testuser.add('eduPersonPrincipalName', 'value')  # From 2002
    testuser.add('eduPersonEntitlement', 'value')  # From 2002
    testuser.add('eduPersonPrimaryOrgUnitDN',
                 'ou=People,%s' % DEFAULT_SUFFIX)  # From 2002
    testuser.add('eduPersonScopedAffiliation', 'value')  # From 2003
    testuser.add('eduPersonTargetedID', 'value')  # From 2003
    testuser.add('eduPersonAssurance', 'value')  # From 2008
    testuser.add('eduPersonPrincipalNamePrior', 'value')  # From 2012
    testuser.add('eduPersonUniqueId', 'value')  # From 2013
    testuser.add('eduPersonOrcid', 'value')  # From 2016

    log.info('Test PASSED')
コード例 #12
0
def test_export_data_from_source_host(topology_st):
    """Prepare export file for migration using a single instance of Directory Server

    :id: 47f97d87-60f7-4f80-a72b-e7daa1de0061
    :setup: Standalone
    :steps:
        1. Add a test user with employeeNumber and telephoneNumber
        2. Add a test user with escaped DN
        3. Create export file
        4. Check if values of searched attributes are present in exported file
    :expectedresults:
        1. Success
        2. Success
        3. Success
        4. Success
    """

    standalone = topology_st.standalone
    output_file = os.path.join(topology_st.standalone.ds_paths.ldif_dir,
                               "migration_export.ldif")

    log.info("Add a test user")
    users = UserAccounts(standalone, DEFAULT_SUFFIX)
    test_user = users.create(properties=TEST_USER_PROPERTIES)
    test_user.add('employeeNumber', '1000')
    test_user.add('telephoneNumber', '1234567890')

    assert test_user.present('employeeNumber', value='1000')
    assert test_user.present('telephoneNumber', value='1234567890')

    log.info("Creating user with escaped DN")
    users.create(
        properties={
            'uid': '\\#\\,\\+"\\\\>:\\=\\<\\<\\>\\;/',
            'cn': 'tuser2',
            'sn': 'user',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/tuser2',
        })

    log.info("Exporting LDIF offline...")
    standalone.stop()
    standalone.db2ldif(bename=DEFAULT_BENAME,
                       suffixes=[DEFAULT_SUFFIX],
                       excludeSuffixes=None,
                       encrypt=None,
                       repl_data=None,
                       outputfile=output_file)
    standalone.start()

    log.info("Check that value of attribute is present in the exported file")
    with open(output_file, 'r') as ldif_file:
        ldif = ldif_file.read()
        assert 'employeeNumber: 1000' in ldif
        assert 'telephoneNumber: 1234567890' in ldif
        assert 'uid: \\#\\,\\+"\\\\>:\\=\\<\\<\\>\\;/' in ldif
コード例 #13
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)

    # 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)
コード例 #14
0
def test_pwdAdmin_bypass(topology_st, password_policy):
    """Test that password administrators/root DN can
    bypass password syntax/policy

    :id: 743bfe33-a1f7-482b-8807-efeb7aa57348
    :setup: Standalone instance, Password Admin entry,
        Password policy configured as below:
        nsslapd-pwpolicy-local: on
        passwordCheckSyntax: on
        passwordMinCategories: 1
        passwordMinTokenLength: 2
        passwordExp: on
        passwordMinDigits: 1
        passwordMinSpecials: 1
    :steps:
        1: Add users with invalid passwords
    :expectedresults:
        1: Users should be added successfully.
    """

    #
    # Now activate a password administator, bind as root dn to do the config
    # update, then rebind as the password admin
    #
    log.info('test_pwdAdmin: Activate the Password Administator...')

    # Extract our fixture data.

    (admin_group, admin1_user, admin2_user) = password_policy

    # Set the password admin

    topology_st.standalone.config.set('passwordAdminDN', admin1_user.dn)

    #
    # Get our test entry
    #

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

    #
    # Start adding entries with invalid passwords, delete the entry after each pass.
    #
    for passwd in INVALID_PWDS:
        u1 = admin_users.create(
            properties={
                'uid': 'example',
                'cn': 'example',
                'sn': 'example',
                'uidNumber': '1000',
                'gidNumber': '2000',
                'homeDirectory': '/home/example',
                'userPassword': passwd
            })
        u1.delete()
コード例 #15
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["supplier1"]
    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["supplier2"].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)
コード例 #16
0
def test_check_desc_attr_state(topo, attr_name, attr_value, oper_type, exp_values, oper_attr):
    """Modify user's description attribute and check if description attribute is
    added/modified/deleted and operational attributes vucsn, adcsn and vdcsn are present.

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

    test_entry = 'state1test'
    log.info('Add user: {}'.format(test_entry))
    users = UserAccounts(topo.ms['supplier1'], DEFAULT_SUFFIX)
    try:
        tuser = users.get(test_entry)
    except ldap.NO_SUCH_OBJECT:
        USER_PROPERTIES.update(dict.fromkeys(['uid', 'cn'], test_entry))
        tuser = users.create(properties=USER_PROPERTIES)
    tuser.set(attr_name, attr_value, eval(oper_type))
    log.info('Check if list of description attrs present for: {}'.format(test_entry))
    assert sorted([i.decode() for i in tuser.get_attr_vals(attr_name)]) == sorted(exp_values)

    log.info('Checking for operational attributes')
    _check_user_oper_attrs(topo, tuser, attr_name, attr_value, oper_type, exp_values, oper_attr)
コード例 #17
0
def _cleanupentris(request, topo_m4):
    users = UserAccounts(topo_m4.ms["master1"], DEFAULT_SUFFIX)
    for i in range(10): users.create_test_user(uid=i)

    def fin():
        try:
            for i in users.list():
                i.delete()
        except: pass
    request.addfinalizer(fin)
コード例 #18
0
ファイル: accpol_test.py プロジェクト: vashirov/389-ds-base
def del_users(topology_st, suffix, subtree, userid, nousrs):
    """Delete users from default test instance with given suffix, subtree, userid and nousrs"""

    log.info('del_users: Pass all of these as parameters suffix, subtree, userid and nousrs')
    users = UserAccounts(topology_st.standalone, suffix, rdn=subtree)
    while (nousrs > 0):
        usrrdn = '{}{}'.format(userid, nousrs)
        userdn = users.get(usrrdn)
        userdn.delete()
        nousrs = nousrs - 1
コード例 #19
0
def pwd_setup(topo):
    ous = OrganizationalUnits(topo.standalone, DEFAULT_SUFFIX)
    ou = ous.get('people')
    ou.add('aci', USER_ACI)

    topo.standalone.config.replace_many(('passwordCheckSyntax', 'on'),
                                        ('passwordMinLength', '4'),
                                        ('passwordMinCategories', '1'))
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    return users.create(properties=user_properties)
コード例 #20
0
def resetPasswd(inst):
    """Reset the user password for the next test"""

    # First, bind as the ROOT DN so we can set the password
    inst.simple_bind_s(DN_DM, PASSWORD)

    # Now set the password
    users = UserAccounts(inst, DEFAULT_SUFFIX)
    user = users.get(USER_RDN)
    user.reset_password(PASSWORD)
コード例 #21
0
def do_setup(topology_st, request):
    """Create a user and make sure ou=pople exists
    """
    sys.stdout = io.StringIO()

    users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
    users.ensure_state(properties=TEST_USER_PROPERTIES)

    ou = OrganizationalUnits(topology_st.standalone, DEFAULT_SUFFIX)
    ou.ensure_state(properties={'ou': 'people'})
コード例 #22
0
ファイル: config_test.py プロジェクト: zero804/389-ds-base
def test_require_internal_index(topo):
    """Test nsslapd-ignore-virtual-attrs configuration attribute

    :id: 22b94f30-59e3-4f27-89a1-c4f4be036f7f
    :setup: Standalone instance
    :steps:
        1. Set "nsslapd-require-internalop-index" to "on"
        2. Enable RI plugin, and configure it to use an attribute that is not indexed
        3. Create a user and add it a group
        4. Deleting user should be rejected as the RI plugin issues an
        unindexed internal search
    :expectedresults:
        1. Success
        2. Success
        3. Success
        4. Success
    """
    # Set the config
    be_insts = Backends(topo.standalone).list()
    for be in be_insts:
        if be.get_attr_val_utf8_l('nsslapd-suffix') == DEFAULT_SUFFIX:
            be.set('nsslapd-require-index', 'off')
            be.set('nsslapd-require-internalop-index', 'on')

    # Configure RI plugin
    rip = ReferentialIntegrityPlugin(topo.standalone)
    rip.set('referint-membership-attr', 'description')
    rip.enable()

    # Create a bunch of users
    db_cfg = DatabaseConfig(topo.standalone)
    db_cfg.set([('nsslapd-idlistscanlimit', '100')])
    users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
    for i in range(102, 202):
        users.create_test_user(uid=i)

    # Create user and group
    user = users.create(properties={
        'uid': 'indexuser',
        'cn' : 'indexuser',
        'sn' : 'user',
        'uidNumber' : '1010',
        'gidNumber' : '2010',
        'homeDirectory' : '/home/indexuser'
    })
    groups = Groups(topo.standalone, DEFAULT_SUFFIX)
    group = groups.create(properties={'cn': 'group',
                                      'member': user.dn})

    # Restart the server
    topo.standalone.restart()

    # Deletion of user should be rejected
    with pytest.raises(ldap.UNWILLING_TO_PERFORM):
        user.delete()
コード例 #23
0
def test_lockout_bypass(topology_st):
    """Check basic password lockout functionality

    :id: 2482a992-1719-495c-b75b-78fe5c48c873
    :setup: Standalone instance
    :steps:
        1. Set passwordMaxFailure to 1
        2. Set passwordLockDuration to 7
        3. Set passwordLockout to 'on'
        4. Create a user
        5. Set a userPassword attribute
        6. Bind as the user with a bad credentials
        7. Bind as the user with a bad credentials
        8. Bind as the user with a good credentials
    :expectedresults:
        1. passwordMaxFailure should be successfully set
        2. passwordLockDuration should be successfully set
        3. passwordLockout should be successfully set
        4. User should be created
        5. userPassword should be successfully set
        6. Should throw an invalid credentials error
        7. Should throw a constraint violation error
        8. Should throw a constraint violation error
    """

    inst = topology_st.standalone

    # Configure the lock policy
    inst.config.set('passwordMaxFailure', '1')
    inst.config.set('passwordLockoutDuration', '99999')
    inst.config.set('passwordLockout', 'on')

    # Create the account
    users = UserAccounts(inst, DEFAULT_SUFFIX)
    testuser = users.create(properties=TEST_USER_PROPERTIES)
    testuser.set('userPassword', GOOD_PASSWORD)

    conn = testuser.bind(GOOD_PASSWORD)
    assert conn != None
    conn.unbind_s()

    # Bind with bad creds twice
    # This is the failure.
    with pytest.raises(ldap.INVALID_CREDENTIALS):
        conn = testuser.bind(BAD_PASSWORD)
    # Now we should not be able to ATTEMPT the bind. It doesn't matter that
    # we disclose that we have hit the rate limit here, what matters is that
    # it exists.
    with pytest.raises(ldap.CONSTRAINT_VIOLATION):
        conn = testuser.bind(BAD_PASSWORD)

    # now bind with good creds
    # Should be error 19 still.
    with pytest.raises(ldap.CONSTRAINT_VIOLATION):
        conn = testuser.bind(GOOD_PASSWORD)
コード例 #24
0
ファイル: entryusn_test.py プロジェクト: vashirov/389-ds-base
def test_entryusn_after_repl_delete(topology_m2):
    """Verify that entryUSN is incremented on 1 after delete operation which creates a tombstone

    :id: 1704cf65-41bc-4347-bdaf-20fc2431b218
    :setup: An instance with replication, Users, USN enabled
    :steps:
        1. Try to delete a user
        2. Check the tombstone has the incremented USN
        3. Try to delete ou=People with users
        4. Check the entry has a not incremented entryUSN
    :expectedresults:
        1. Success
        2. Success
        3. Should fail with Not Allowed On Non-leaf error
        4. Success
    """

    inst = topology_m2.ms["supplier1"]
    plugin = USNPlugin(inst)
    plugin.enable()
    inst.restart()
    users = UserAccounts(inst, DEFAULT_SUFFIX)

    try:
        user_1 = users.create_test_user()
        user_rdn = user_1.rdn
        tombstones = Tombstones(inst, DEFAULT_SUFFIX)

        user_1.replace('description', 'update_ts')
        user_usn = user_1.get_attr_val_int('entryusn')

        user_1.delete()
        time.sleep(1)  # Gives a little time for tombstone creation to complete

        ts = tombstones.get(user_rdn)
        ts_usn = ts.get_attr_val_int('entryusn')

        assert (user_usn + 1) == ts_usn

        user_1 = users.create_test_user()
        org = OrganizationalUnit(inst, f"ou=People,{DEFAULT_SUFFIX}")
        org.replace('description', 'update_ts')
        ou_usn_before = org.get_attr_val_int('entryusn')
        try:
            org.delete()
        except ldap.NOT_ALLOWED_ON_NONLEAF:
            pass
        ou_usn_after = org.get_attr_val_int('entryusn')
        assert ou_usn_before == ou_usn_after

    finally:
        try:
            user_1.delete()
        except ldap.NO_SUCH_OBJECT:
            pass
コード例 #25
0
def _create_user(topo, uid, ou):
    user = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=ou).create(properties={
        'uid': uid,
        'cn': uid,
        'sn': uid,
        'mail': f'{uid}@example.com',
        'homeDirectory': f'/home/{uid}',
        'uidNumber': '1000',
        'gidNumber': '1000'
    })
    return user
コード例 #26
0
def test_users_and_groups(topology):
    """
    Ensure that user and group management works as expected.
    """
    if DEBUGGING:
        # Add debugging steps(if any)...
        pass

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

    # No user should exist

    assert(len(users.list()) == 0)

    # Create a user

    users.create(properties=TEST_USER_PROPERTIES)

    assert(len(users.list()) == 1)

    testuser = users.get('testuser')

    # Set password
    testuser.set('userPassword', 'password')
    # bind

    conn = testuser.bind('password')
    conn.unbind_s()

    # create group
    group_properties = {
        'cn' : 'group1',
        'description' : 'testgroup'
    }

    group = groups.create(properties=group_properties)

    # user shouldn't be a member
    assert(not group.is_member(testuser.dn))

    # add user as member
    group.add_member(testuser.dn)
    # check they are a member
    assert(group.is_member(testuser.dn))
    # remove user from group
    group.remove_member(testuser.dn)
    # check they are not a member
    assert(not group.is_member(testuser.dn))

    group.delete()
    testuser.delete()

    log.info('Test PASSED')
コード例 #27
0
def add_member(server, cn, subtree):
    dn = subtree
    users = UserAccounts(server, dn, rdn=None)
    users.create(properties={'uid': 'test_%s' % cn,
                             'cn': "%s" % cn,
                             'sn': 'SN',
                             'description': 'member',
                             'uidNumber': '1000',
                             'gidNumber': '2000',
                             'homeDirectory': '/home/testuser'
                             })
コード例 #28
0
def test_replica_backup_and_restore(topo_m4):
    """
    Test Backup and restore
    :id: 5ad1b85c-e765-11e8-9668-8c16451d917b
    :setup: standalone
    :steps:
        1. Add entries
        2. Take backup db2ldif on master1
        3. Delete entries on master1
        4. Restore entries ldif2db
        5. Check entries
    :expected results:
        1. Should success
        2. Should success
        3. Should success
        4. Should success
        5. Should success
    """
    # Testing bug #830335: Taking a replica backup and Restore on M1 after deleting few entries from M1 nad M2
    repl = ReplicationManager(DEFAULT_SUFFIX)
    users = UserAccounts(topo_m4.ms["master3"], DEFAULT_SUFFIX)
    for i in range(20, 25):
        users.create_test_user(uid=i)
        time.sleep(1)
    repl.wait_for_replication(topo_m4.ms["master1"], topo_m4.ms["master2"])
    repl.test_replication(topo_m4.ms["master1"], topo_m4.ms["master2"], 30)
    topo_m4.ms["master1"].stop()
    topo_m4.ms["master1"].db2ldif(
        bename=DEFAULT_BENAME,
        suffixes=[DEFAULT_SUFFIX],
        excludeSuffixes=[],
        encrypt=False,
        repl_data=True,
        outputfile="/tmp/output_file",
    )
    topo_m4.ms["master1"].start()
    for i in users.list():
        topo_m4.ms["master1"].delete_s(i.dn)
    repl.wait_for_replication(topo_m4.ms["master1"], topo_m4.ms["master2"])
    repl.test_replication(topo_m4.ms["master1"], topo_m4.ms["master2"], 30)
    topo_m4.ms["master1"].stop()
    topo_m4.ms["master1"].ldif2db(
        bename=None,
        excludeSuffixes=None,
        encrypt=False,
        suffixes=[DEFAULT_SUFFIX],
        import_file="/tmp/output_file",
    )
    topo_m4.ms["master1"].start()
    for i in range(20, 25):
        users.create_test_user(uid=i)
        time.sleep(1)
    repl.wait_for_replication(topo_m4.ms["master1"], topo_m4.ms["master2"])
    repl.test_replication(topo_m4.ms["master1"], topo_m4.ms["master2"], 30)
コード例 #29
0
def test_pwdAdmin_no_admin(topology_st, password_policy):
    """Test that password administrators/root DN can
    bypass password syntax/policy

    :id: 74347798-7cc7-4ce7-ad5c-06387ffde02c
    :setup: Standalone instance, Password Admin entry,
        Password policy configured as below:
        nsslapd-pwpolicy-local: on
        passwordCheckSyntax: on
        passwordMinCategories: 1
        passwordMinTokenLength: 2
        passwordExp: on
        passwordMinDigits: 1
        passwordMinSpecials: 1
    :steps:
        1: Create a user
        2: Attempt to set passwords on the user that are invalid
    :expectedresults:
        1: Success
        2: The passwords should NOT be set
    """
    (admin_group, admin1_user, admin2_user) = password_policy

    # Remove password admin

    # Can't use pytest.raises. because this may or may not exist
    try:
        topology_st.standalone.config.remove_all('passwordAdminDN')
    except ldap.NO_SUCH_ATTRIBUTE:
        pass

    #
    # Add the entry for the next round of testing (modify password)
    #
    admin_conn = admin1_user.bind(ADMIN_PWD)
    admin_users = UserAccounts(admin_conn, DEFAULT_SUFFIX)

    u2 = admin_users.create(
        properties={
            'uid': 'example',
            'cn': 'example',
            'sn': 'example',
            'uidNumber': '1000',
            'gidNumber': '2000',
            'homeDirectory': '/home/example',
            'userPassword': ADMIN_PWD
        })

    #
    # Make invalid password updates that should fail
    #
    for passwd in INVALID_PWDS:
        with pytest.raises(ldap.CONSTRAINT_VIOLATION):
            u2.replace('userPassword', passwd)
コード例 #30
0
ファイル: misc_test.py プロジェクト: tbordaz/389-ds-base
def test_only_allow_some_targetattr_two(topo, clean, aci_of_user, request):
    """Misc Test 6 only allow some targetattr (2/2)"

    :id: a188239c-7db8-11e8-903e-8c16451d917b
    :setup: Standalone Instance
    :steps:
        1. Add test entry
        2. Add ACI
        3. User should follow ACI role
    :expectedresults:
        1. Entry should be added
        2. Operation should  succeed
        3. Operation should  succeed
    """
    uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=None)
    for i in range(5):
        user = uas.create_test_user(uid=i, gid=i)
        user.replace_many(('mail', '*****@*****.**'), ('cn', 'Anuj'),
                          ('userPassword', PW_DM))

    user1 = uas.create_test_user()
    user1.replace_many(('mail', '*****@*****.**'),
                       ('userPassword', PW_DM))

    Domain(topo.standalone, DEFAULT_SUFFIX).\
        replace("aci", '(target="ldap:///{}") (targetattr="mail||objectClass")'
                       '(targetfilter="cn=Anuj") (version 3.0; acl "{}"; '
                       'allow (compare,read,search) '
                       '(userdn = "ldap:///anyone"); )'.format(DEFAULT_SUFFIX, request.node.name))

    conn = UserAccount(topo.standalone, user.dn).bind(PW_DM)
    # aci will allow only mail targetattr but only for cn=Anuj
    account = Accounts(conn, DEFAULT_SUFFIX)
    assert len(account.filter('(mail=*)')) == 5
    assert not account.filter('(cn=*)')

    for i in account.filter('(mail=*)'):
        assert i.get_attr_val_utf8('mail') == '*****@*****.**'

    conn = Anonymous(topo.standalone).bind()
    # aci will allow only mail targetattr but only for cn=Anuj
    account = Accounts(conn, DEFAULT_SUFFIX)
    assert len(account.filter('(mail=*)')) == 5
    assert not account.filter('(cn=*)')

    for i in account.filter('(mail=*)'):
        assert i.get_attr_val_utf8('mail') == '*****@*****.**'

    # with root no blockage
    assert len(Accounts(topo.standalone,
                        DEFAULT_SUFFIX).filter('(mail=*)')) == 6

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