예제 #1
0
def test_path_exception():
    # Trigger the internal path find with a "bad location" and
    # make sure that we get the exception
    p = Paths()
    try:
        p._get_defaults_loc(search_paths=[])
        assert (False)
    except IOError:
        assert (True)
예제 #2
0
    def __init__(self, instance, serverid=None):
        self._instance = instance
        self._contents = []

        if serverid:
            # Get the dse.ldif from the instance name
            prefix = os.environ.get('PREFIX', ""),
            if serverid.startswith("slapd-"):
                serverid = serverid.replace("slapd-", "", 1)
            self.path = "{}/etc/dirsrv/slapd-{}/dse.ldif".format(
                prefix[0], serverid)
        else:
            ds_paths = Paths(self._instance.serverid, self._instance)
            self.path = os.path.join(ds_paths.config_dir, 'dse.ldif')

        with open(self.path, 'r') as file_dse:
            processed_line = ""
            for line in file_dse.readlines():
                if not line.startswith(' '):
                    if processed_line:
                        self._contents.append(processed_line)

                    if line.startswith('dn:'):
                        processed_line = line.lower()
                    else:
                        processed_line = line
                else:
                    processed_line = processed_line[:-1] + line[1:]
def get_ds_version():
    """
    Return version of ns-slapd installed on this system. This is determined by the defaults.inf
    file, so is correct for the built and installed ns-slapd binary. This function works without
    root permissions.

    returns a string of the form: 1.3.4.8
    """
    p = Paths()
    return p.version
예제 #4
0
def get_user_is_ds_owner():
    # Check if we have permission to administer the DS instance. This is required
    # for some tasks such as installing, killing, or editing configs for the
    # instance.
    cur_uid = os.getuid()
    if cur_uid == 0:
        # We are root, we have permission
        return True
    cur_username = pwd.getpwuid(cur_uid)[0]
    p = Paths()
    if cur_username == p.user:
        # We are the same user, all good
        return True
    return False
예제 #5
0
def get_instance_list():
    # List all server instances
    paths = Paths()
    conf_dir = os.path.join(paths.sysconf_dir, 'dirsrv')
    insts = []
    try:
        for inst in os.listdir(conf_dir):
            if inst.startswith('slapd-') and not inst.endswith('.removed'):
                insts.append(inst)
    except OSError as e:
        log.error("Failed to check directory: {} - {}".format(conf_dir, str(e)))
    except IOError as e:
        log.error(e)
        log.error("Perhaps you need to be a different user?")
    insts.sort()
    return insts
예제 #6
0
import ldap
import pytest
import time
import shutil
import uuid
from lib389.idm.user import nsUserAccounts, UserAccounts
from lib389.idm.account import Accounts
from lib389.idm.domain import Domain
from lib389.topologies import topology_st as topology
from lib389.backend import Backends
from lib389.paths import Paths
from lib389.utils import ds_is_older
from lib389._constants import *
from lib389.plugins import EntryUUIDPlugin

default_paths = Paths()

pytestmark = pytest.mark.tier1

DATADIR1 = os.path.join(os.path.dirname(__file__), '../../data/entryuuid/')
IMPORT_UUID_A = "973e1bbf-ba9c-45d4-b01b-ff7371fd9008"
UUID_BETWEEN = "eeeeeeee-0000-0000-0000-000000000000"
IMPORT_UUID_B = "f6df8fe9-6b30-46aa-aa13-f0bf755371e8"
UUID_MIN = "00000000-0000-0000-0000-000000000000"
UUID_MAX = "ffffffff-ffff-ffff-ffff-ffffffffffff"


def _entryuuid_import_and_search(topology):
    # 1
    ldif_dir = topology.standalone.get_ldif_dir()
    target_ldif = os.path.join(ldif_dir,
예제 #7
0
import subprocess
import logging
import pytest
import shutil
import glob
import os

from lib389.paths import Paths
from enum import Enum

pkgs = ['389-ds-base', 'nss', 'nspr', 'openldap', 'cyrus-sasl']
p = Paths()


class FIPSState(Enum):
    ENABLED = 'enabled'
    DISABLED = 'disabled'
    NOT_AVAILABLE = 'not_available'

    def __unicode__(self):
        return self.value

    def __str__(self):
        return self.value


def get_rpm_version(pkg):
    try:
        result = subprocess.check_output(
            ['rpm', '-q', '--queryformat', '%{VERSION}-%{RELEASE}', pkg])
    except:
예제 #8
0
import pytest
import os
from lib389.backend import Backend, Backends
from lib389.idm.user import UserAccounts
from lib389.replica import Changelog, ReplicationManager, Replicas
from lib389.utils import *
from lib389._constants import *
from lib389.cli_base import FakeArgs
from lib389.topologies import topology_m2, topology_m3
from lib389.cli_ctl.health import health_check_run
from lib389.paths import Paths

CMD_OUTPUT = 'No issues found.'
JSON_OUTPUT = '[]'

ds_paths = Paths()
log = logging.getLogger(__name__)


def run_healthcheck_and_flush_log(topology, instance, searched_code, json, searched_code2=None):
    args = FakeArgs()
    args.instance = instance.serverid
    args.verbose = instance.verbose
    args.list_errors = False
    args.list_checks = False
    args.check = ['replication', 'backends:userroot:cl_trimming']
    args.dry_run = False

    if json:
        log.info('Use healthcheck with --json option')
        args.json = json
예제 #9
0
def test_path_noread():
    p = Paths()
    assert (p._defaults_cached is False)
    p._read_defaults()
    assert (p._defaults_cached is True)
예제 #10
0
def test_paths():
    # Make the paths object.
    p = Paths()
    # Get a value!
    v = p.version
예제 #11
0
def test_repeated_ldap_add(topology_st):
    """Prevent revealing the entry info to whom has no access rights.

    :id: 76d278bd-3e51-4579-951a-753e6703b4df
    :setup: Standalone instance
    :steps:
        1.  Disable accesslog logbuffering
        2.  Bind as "cn=Directory Manager"
        3.  Add a organisational unit as BOU
        4.  Add a bind user as uid=buser123,ou=BOU,dc=example,dc=com
        5.  Add a test user as uid=tuser0,ou=People,dc=example,dc=com
        6.  Delete aci in dc=example,dc=com
        7.  Bind as Directory Manager, acquire an access log path and instance dir
        8.  Bind as uid=buser123,ou=BOU,dc=example,dc=com who has no right to read the entry
        9.  Bind as uid=bogus,ou=people,dc=bogus,bogus who does not exist
        10. Bind as uid=buser123,ou=BOU,dc=example,dc=com,bogus with wrong password
        11. Adding aci for uid=buser123,ou=BOU,dc=example,dc=com to ou=BOU,dc=example,dc=com.
        12. Bind as uid=buser123,ou=BOU,dc=example,dc=com now who has right to read the entry
    :expectedresults:
        1.  Operation should be successful
        2.  Operation should be successful
        3.  Operation should be successful
        4.  Operation should be successful
        5.  Operation should be successful
        6.  Operation should be successful
        7.  Operation should be successful
        8.  Bind operation should be successful with no search result
        9.  Bind operation should Fail
        10. Bind operation should Fail
        11. Operation should be successful
        12. Bind operation should be successful with search result
    """
    log.info(
        'Testing Bug 1347760 - Information disclosure via repeated use of LDAP ADD operation, etc.'
    )

    log.info('Disabling accesslog logbuffering')
    topology_st.standalone.modify_s(
        CONFIG_DN,
        [(ldap.MOD_REPLACE, 'nsslapd-accesslog-logbuffering', b'off')])

    log.info('Bind as {%s,%s}' % (DN_DM, PASSWORD))
    topology_st.standalone.simple_bind_s(DN_DM, PASSWORD)

    log.info('Adding ou=%s a bind user belongs to.' % BOU)
    topology_st.standalone.add_s(
        Entry((BINDOU, {
            'objectclass': 'top organizationalunit'.split(),
            'ou': BOU
        })))

    log.info('Adding a bind user.')
    topology_st.standalone.add_s(
        Entry((BINDDN, {
            'objectclass':
            "top person organizationalPerson inetOrgPerson".split(),
            'cn':
            'bind user',
            'sn':
            'user',
            'userPassword':
            BINDPW
        })))

    log.info('Adding a test user.')
    topology_st.standalone.add_s(
        Entry((TESTDN, {
            'objectclass':
            "top person organizationalPerson inetOrgPerson".split(),
            'cn':
            'test user',
            'sn':
            'user',
            'userPassword':
            TESTPW
        })))

    log.info('Deleting aci in %s.' % DEFAULT_SUFFIX)
    topology_st.standalone.modify_s(DEFAULT_SUFFIX,
                                    [(ldap.MOD_DELETE, 'aci', None)])

    log.info(
        'While binding as DM, acquire an access log path and instance dir')
    ds_paths = Paths(serverid=topology_st.standalone.serverid,
                     instance=topology_st.standalone)
    file_path = ds_paths.access_log
    inst_dir = ds_paths.inst_dir

    log.info(
        'Bind case 1. the bind user has no rights to read the entry itself, bind should be successful.'
    )
    log.info('Bind as {%s,%s} who has no access rights.' % (BINDDN, BINDPW))
    try:
        topology_st.standalone.simple_bind_s(BINDDN, BINDPW)
    except ldap.LDAPError as e:
        log.info('Desc {}'.format(get_ldap_error_msg(e, 'desc')))
        assert False

    file_obj = open(file_path, "r")
    log.info('Access log path: %s' % file_path)

    log.info(
        'Bind case 2-1. the bind user does not exist, bind should fail with error %s'
        % ldap.INVALID_CREDENTIALS.__name__)
    log.info('Bind as {%s,%s} who does not exist.' % (BOGUSDN, 'bogus'))
    try:
        topology_st.standalone.simple_bind_s(BOGUSDN, 'bogus')
    except ldap.LDAPError as e:
        log.info("Exception (expected): %s" % type(e).__name__)
        log.info('Desc {}'.format(get_ldap_error_msg(e, 'desc')))
        assert isinstance(e, ldap.INVALID_CREDENTIALS)
        regex = re.compile('No such entry')
        cause = pattern_accesslog(file_obj, regex)
        if cause is None:
            log.fatal('Cause not found - %s' % cause)
            assert False
        else:
            log.info('Cause found - %s' % cause)
    time.sleep(1)

    log.info(
        'Bind case 2-2. the bind user\'s suffix does not exist, bind should fail with error %s'
        % ldap.INVALID_CREDENTIALS.__name__)
    log.info('Bind as {%s,%s} who does not exist.' % (BOGUSSUFFIX, 'bogus'))
    with pytest.raises(ldap.INVALID_CREDENTIALS):
        topology_st.standalone.simple_bind_s(BOGUSSUFFIX, 'bogus')
    regex = re.compile('No suffix for bind')
    cause = pattern_accesslog(file_obj, regex)
    if cause is None:
        log.fatal('Cause not found - %s' % cause)
        assert False
    else:
        log.info('Cause found - %s' % cause)
    time.sleep(1)

    log.info(
        'Bind case 2-3. the bind user\'s password is wrong, bind should fail with error %s'
        % ldap.INVALID_CREDENTIALS.__name__)
    log.info('Bind as {%s,%s} who does not exist.' % (BINDDN, 'bogus'))
    try:
        topology_st.standalone.simple_bind_s(BINDDN, 'bogus')
    except ldap.LDAPError as e:
        log.info("Exception (expected): %s" % type(e).__name__)
        log.info('Desc {}'.format(get_ldap_error_msg(e, 'desc')))
        assert isinstance(e, ldap.INVALID_CREDENTIALS)
        regex = re.compile('Invalid credentials')
        cause = pattern_accesslog(file_obj, regex)
        if cause is None:
            log.fatal('Cause not found - %s' % cause)
            assert False
        else:
            log.info('Cause found - %s' % cause)
    time.sleep(1)

    log.info('Adding aci for %s to %s.' % (BINDDN, BINDOU))
    acival = '(targetattr="*")(version 3.0; acl "%s"; allow(all) userdn = "ldap:///%s";)' % (
        BUID, BINDDN)
    log.info('aci: %s' % acival)
    log.info('Bind as {%s,%s}' % (DN_DM, PASSWORD))
    topology_st.standalone.simple_bind_s(DN_DM, PASSWORD)
    topology_st.standalone.modify_s(
        BINDOU, [(ldap.MOD_ADD, 'aci', ensure_bytes(acival))])
    time.sleep(1)

    log.info(
        'Bind case 3. the bind user has the right to read the entry itself, bind should be successful.'
    )
    log.info('Bind as {%s,%s} which should be ok.\n' % (BINDDN, BINDPW))
    topology_st.standalone.simple_bind_s(BINDDN, BINDPW)

    log.info(
        'The following operations are against the subtree the bind user %s has no rights.'
        % BINDDN)
    # Search
    exists = True
    rc = ldap.SUCCESS
    log.info(
        'Search case 1. the bind user has no rights to read the search entry, it should return no search results with %s'
        % rc)
    check_op_result(topology_st.standalone, 'search', TESTDN, None, exists, rc)

    exists = False
    rc = ldap.SUCCESS
    log.info(
        'Search case 2-1. the search entry does not exist, the search should return no search results with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'search', BOGUSDN, None, exists,
                    rc)

    exists = False
    rc = ldap.SUCCESS
    log.info(
        'Search case 2-2. the search entry does not exist, the search should return no search results with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'search', BOGUSDN2, None, exists,
                    rc)

    # Add
    exists = True
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Add case 1. the bind user has no rights AND the adding entry exists, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'add', TESTDN, None, exists, rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Add case 2-1. the bind user has no rights AND the adding entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'add', BOGUSDN, None, exists, rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Add case 2-2. the bind user has no rights AND the adding entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'add', BOGUSDN2, None, exists, rc)

    # Modify
    exists = True
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Modify case 1. the bind user has no rights AND the modifying entry exists, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modify', TESTDN, None, exists, rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Modify case 2-1. the bind user has no rights AND the modifying entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modify', BOGUSDN, None, exists,
                    rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Modify case 2-2. the bind user has no rights AND the modifying entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modify', BOGUSDN2, None, exists,
                    rc)

    # Modrdn
    exists = True
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Modrdn case 1. the bind user has no rights AND the renaming entry exists, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modrdn', TESTDN, None, exists, rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Modrdn case 2-1. the bind user has no rights AND the renaming entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modrdn', BOGUSDN, None, exists,
                    rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Modrdn case 2-2. the bind user has no rights AND the renaming entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modrdn', BOGUSDN2, None, exists,
                    rc)

    exists = True
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Modrdn case 3. the bind user has no rights AND the node moving an entry to exists, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modrdn', TESTDN, GROUPOU, exists,
                    rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Modrdn case 4-1. the bind user has no rights AND the node moving an entry to does not, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modrdn', TESTDN, BOGUSOU, exists,
                    rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Modrdn case 4-2. the bind user has no rights AND the node moving an entry to does not, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modrdn', TESTDN, BOGUSOU, exists,
                    rc)

    # Delete
    exists = True
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Delete case 1. the bind user has no rights AND the deleting entry exists, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'delete', TESTDN, None, exists, rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Delete case 2-1. the bind user has no rights AND the deleting entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'delete', BOGUSDN, None, exists,
                    rc)

    exists = False
    rc = ldap.INSUFFICIENT_ACCESS
    log.info(
        'Delete case 2-2. the bind user has no rights AND the deleting entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'delete', BOGUSDN2, None, exists,
                    rc)

    log.info('EXTRA: Check no regressions')
    log.info('Adding aci for %s to %s.' % (BINDDN, DEFAULT_SUFFIX))
    acival = '(targetattr="*")(version 3.0; acl "%s-all"; allow(all) userdn = "ldap:///%s";)' % (
        BUID, BINDDN)
    log.info('Bind as {%s,%s}' % (DN_DM, PASSWORD))
    topology_st.standalone.simple_bind_s(DN_DM, PASSWORD)
    topology_st.standalone.modify_s(
        DEFAULT_SUFFIX, [(ldap.MOD_ADD, 'aci', ensure_bytes(acival))])
    time.sleep(1)

    log.info('Bind as {%s,%s}.' % (BINDDN, BINDPW))
    try:
        topology_st.standalone.simple_bind_s(BINDDN, BINDPW)
    except ldap.LDAPError as e:
        log.info('Desc {}'.format(get_ldap_error_msg(e, 'desc')))
        assert False
    time.sleep(1)

    exists = False
    rc = ldap.NO_SUCH_OBJECT
    log.info(
        'Search case. the search entry does not exist, the search should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'search', BOGUSDN2, None, exists,
                    rc)
    file_obj.close()

    exists = True
    rc = ldap.ALREADY_EXISTS
    log.info(
        'Add case. the adding entry already exists, it should fail with %s' %
        rc.__name__)
    check_op_result(topology_st.standalone, 'add', TESTDN, None, exists, rc)

    exists = False
    rc = ldap.NO_SUCH_OBJECT
    log.info(
        'Modify case. the modifying entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modify', BOGUSDN, None, exists,
                    rc)

    exists = False
    rc = ldap.NO_SUCH_OBJECT
    log.info(
        'Modrdn case 1. the renaming entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modrdn', BOGUSDN, None, exists,
                    rc)

    exists = False
    rc = ldap.NO_SUCH_OBJECT
    log.info(
        'Modrdn case 2. the node moving an entry to does not, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'modrdn', TESTDN, BOGUSOU, exists,
                    rc)

    exists = False
    rc = ldap.NO_SUCH_OBJECT
    log.info(
        'Delete case. the deleting entry does not exist, it should fail with %s'
        % rc.__name__)
    check_op_result(topology_st.standalone, 'delete', BOGUSDN, None, exists,
                    rc)

    log.info('Inactivate %s' % BINDDN)
    if ds_paths.version < '1.3':
        nsinactivate = '%s/ns-inactivate.pl' % inst_dir
        cli_cmd = [nsinactivate, '-D', DN_DM, '-w', PASSWORD, '-I', BINDDN]
    else:
        dsidm = '%s/dsidm' % ds_paths.sbin_dir
        cli_cmd = [
            dsidm, SERVERID_STANDALONE, '-b', DEFAULT_SUFFIX, 'account',
            'lock', BINDDN
        ]
    log.info(cli_cmd)
    p = Popen(cli_cmd)
    assert (p.wait() == 0)

    log.info('Bind as {%s,%s} which should fail with %s.' %
             (BINDDN, BUID, ldap.UNWILLING_TO_PERFORM.__name__))
    try:
        topology_st.standalone.simple_bind_s(BINDDN, BUID)
    except ldap.LDAPError as e:
        log.info("Exception (expected): %s" % type(e).__name__)
        log.info('Desc {}'.format(get_ldap_error_msg(e, 'desc')))
        assert isinstance(e, ldap.UNWILLING_TO_PERFORM)

    log.info('Bind as {%s,%s} which should fail with %s.' %
             (BINDDN, 'bogus', ldap.UNWILLING_TO_PERFORM.__name__))
    try:
        topology_st.standalone.simple_bind_s(BINDDN, 'bogus')
    except ldap.LDAPError as e:
        log.info("Exception (expected): %s" % type(e).__name__)
        log.info('Desc {}'.format(get_ldap_error_msg(e, 'desc')))
        assert isinstance(e, ldap.UNWILLING_TO_PERFORM)

    log.info('SUCCESS')