示例#1
0
 def update_pki_admin_password(self):
     ldap = ldap2(shared_instance=False)
     ldap.connect(bind_dn=DN(('cn', 'directory manager')),
                  bind_pw=self.dirman_password)
     dn = DN('uid=admin', 'ou=people', 'o=ipaca')
     ldap.modify_password(dn, self.dirman_password)
     ldap.disconnect()
示例#2
0
    def ask_for_options(self):
        options = self.options
        super(ReplicaPrepare, self).ask_for_options()

        # get the directory manager password
        self.dirman_password = options.password
        if not options.password:
            self.dirman_password = installutils.read_password(
                "Directory Manager (existing master)",
                confirm=False, validate=False)
            if self.dirman_password is None:
                raise admintool.ScriptError(
                    "Directory Manager password required")

        # Try out the password & get the subject base
        suffix = ipautil.realm_to_suffix(api.env.realm)
        try:
            conn = ldap2(shared_instance=False, base_dn=suffix)
            conn.connect(bind_dn=DN(('cn', 'directory manager')),
                         bind_pw=self.dirman_password)
            dn, entry_attrs = conn.get_ipa_config()
            conn.disconnect()
        except errors.ACIError:
            raise admintool.ScriptError("The password provided is incorrect "
                "for LDAP server %s" % api.env.host)
        except errors.LDAPError:
            raise admintool.ScriptError(
                "Unable to connect to LDAP server %s" % api.env.host)
        except errors.DatabaseError, e:
            raise admintool.ScriptError(e.desc)
示例#3
0
    def run(self):
        api.bootstrap(in_server=True)
        api.finalize()

        conn = ldap2()
        try:
            ccache = krbV.default_context().default_ccache()
            conn.connect(ccache=ccache)
        except (krbV.Krb5Error, errors.ACIError):
            raise admintool.ScriptError(
                "Unable to connect to LDAP! Did you kinit?")

        try:
            # Parse tokens
            for keypkg in self.doc.getKeyPackages():
                try:
                    api.Command.otptoken_add(keypkg.id,
                                             no_qrcode=True,
                                             **keypkg.options)
                except Exception as e:
                    self.log.warn("Error adding token: %s", e)
                else:
                    self.log.info("Added token: %s", keypkg.id)
                    keypkg.remove()
        finally:
            conn.disconnect()

        # Write out the XML file without the tokens that succeeded.
        self.doc.save(self.output)
示例#4
0
    def run(self):
        api.bootstrap(in_server=True)
        api.finalize()

        conn = ldap2(api)
        try:
            ccache = krbV.default_context().default_ccache()
            conn.connect(ccache=ccache)
        except (krbV.Krb5Error, errors.ACIError):
            raise admintool.ScriptError("Unable to connect to LDAP! Did you kinit?")

        try:
            # Parse tokens
            for keypkg in self.doc.getKeyPackages():
                try:
                    api.Command.otptoken_add(keypkg.id, no_qrcode=True, **keypkg.options)
                except Exception as e:
                    self.log.warn("Error adding token: %s", e)
                else:
                    self.log.info("Added token: %s", keypkg.id)
                    keypkg.remove()
        finally:
            conn.disconnect()

        # Write out the XML file without the tokens that succeeded.
        self.doc.save(self.output)
示例#5
0
    def execute(self, ldapuri, bindpw, **options):
        ldap = self.api.Backend.ldap2
        self.normalize_options(options)
        config = ldap.get_ipa_config()

        ds_base_dn = options.get('basedn')
        if ds_base_dn is not None:
            assert isinstance(ds_base_dn, DN)

        # check if migration mode is enabled
        if config.get('ipamigrationenabled', ('FALSE', ))[0] == 'FALSE':
            return dict(result={}, failed={}, enabled=False, compat=True)

        # connect to DS
        ds_ldap = ldap2(self.api, ldap_uri=ldapuri)

        cacert = None
        if options.get('cacertfile') is not None:
            # store CA cert into file
            tmp_ca_cert_f = write_tmp_file(options['cacertfile'])
            cacert = tmp_ca_cert_f.name

            # start TLS connection
            ds_ldap.connect(bind_dn=options['binddn'], bind_pw=bindpw,
                            cacert=cacert)

            tmp_ca_cert_f.close()
        else:
            ds_ldap.connect(bind_dn=options['binddn'], bind_pw=bindpw)

        # check whether the compat plugin is enabled
        if not options.get('compat'):
            try:
                ldap.get_entry(DN(('cn', 'compat'), (api.env.basedn)))
                return dict(result={}, failed={}, enabled=True, compat=False)
            except errors.NotFound:
                pass

        if not ds_base_dn:
            # retrieve base DN from remote LDAP server
            entries, _truncated = ds_ldap.find_entries(
                '', ['namingcontexts', 'defaultnamingcontext'], DN(''),
                ds_ldap.SCOPE_BASE, size_limit=-1, time_limit=0,
            )
            if 'defaultnamingcontext' in entries[0]:
                ds_base_dn = DN(entries[0]['defaultnamingcontext'][0])
                assert isinstance(ds_base_dn, DN)
            else:
                try:
                    ds_base_dn = DN(entries[0]['namingcontexts'][0])
                    assert isinstance(ds_base_dn, DN)
                except (IndexError, KeyError) as e:
                    raise Exception(str(e))

        # migrate!
        (migrated, failed) = self.migrate(
            ldap, config, ds_ldap, ds_base_dn, options
        )

        return dict(result=migrated, failed=failed, enabled=True, compat=True)
示例#6
0
    def execute(self, ldapuri, bindpw, **options):
        ldap = self.api.Backend.ldap2
        self.normalize_options(options)
        config = ldap.get_ipa_config()

        ds_base_dn = options.get('basedn')
        if ds_base_dn is not None:
            assert isinstance(ds_base_dn, DN)

        # check if migration mode is enabled
        if config.get('ipamigrationenabled', ('FALSE', ))[0] == 'FALSE':
            return dict(result={}, failed={}, enabled=False, compat=True)

        # connect to DS
        ds_ldap = ldap2(shared_instance=False, ldap_uri=ldapuri, base_dn='')

        cacert = None
        if options.get('cacertfile') is not None:
            #store CA cert into file
            tmp_ca_cert_f = write_tmp_file(options['cacertfile'])
            cacert = tmp_ca_cert_f.name

            #start TLS connection
            ds_ldap.connect(bind_dn=options['binddn'],
                            bind_pw=bindpw,
                            tls_cacertfile=cacert)

            tmp_ca_cert_f.close()
        else:
            ds_ldap.connect(bind_dn=options['binddn'], bind_pw=bindpw)

        #check whether the compat plugin is enabled
        if not options.get('compat'):
            try:
                ldap.get_entry(DN(('cn', 'compat'), (api.env.basedn)))
                return dict(result={}, failed={}, enabled=True, compat=False)
            except errors.NotFound:
                pass

        if not ds_base_dn:
            # retrieve base DN from remote LDAP server
            entries, truncated = ds_ldap.find_entries(
                '',
                ['namingcontexts', 'defaultnamingcontext'],
                DN(''),
                ds_ldap.SCOPE_BASE,
                size_limit=-1,
                time_limit=0,
            )
            if 'defaultnamingcontext' in entries[0]:
                ds_base_dn = DN(entries[0]['defaultnamingcontext'][0])
                assert isinstance(ds_base_dn, DN)
            else:
                try:
                    ds_base_dn = DN(entries[0]['namingcontexts'][0])
                    assert isinstance(ds_base_dn, DN)
                except (IndexError, KeyError), e:
                    raise StandardError(str(e))
示例#7
0
 def test_GSSAPI(self):
     """
     Test a GSSAPI LDAP bind using ldap2
     """
     self.conn = ldap2(api)
     self.conn.connect(autobind=AUTOBIND_DISABLED)
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')[0]
     assert cert.serial_number is not None
示例#8
0
 def test_GSSAPI(self):
     """
     Test a GSSAPI LDAP bind using ldap2
     """
     self.conn = ldap2(api)
     self.conn.connect(autobind=AUTOBIND_DISABLED)
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')[0]
     assert cert.serial_number is not None
示例#9
0
 def update_pki_admin_password(self):
     ldap = ldap2(api)
     ldap.connect(
         bind_dn=DN(('cn', 'directory manager')),
         bind_pw=self.dirman_password
     )
     dn = DN('uid=admin', 'ou=people', 'o=ipaca')
     ldap.modify_password(dn, self.dirman_password)
     ldap.disconnect()
示例#10
0
    def test_find_orphan_automember_rules(self, hostgroup1):
        """ Remove hostgroup1, find and remove obsolete automember rules. """
        # Remove hostgroup1

        hostgroup1.ensure_missing()

        # Test rebuild (is failing)
        # rebuild fails if 389-ds is older than 1.4.0.22 where unmembering
        # feature was implemented: https://pagure.io/389-ds-base/issue/50077
        if not have_ldap2:
            pytest.skip('server plugin not available')
        ldap = ldap2(api)
        ldap.connect()
        rootdse = ldap.get_entry(DN(''), ['vendorVersion'])
        version = rootdse.single_value.get('vendorVersion')
        # The format of vendorVersion is the following:
        # 389-Directory/1.3.8.4 B2019.037.1535
        # Extract everything between 389-Directory/ and ' B'
        mo = re.search(r'389-Directory/(.*) B', version)
        vendor_version = parse_version(mo.groups()[0])
        expected_failure = vendor_version < parse_version('1.4.0.22')

        try:
            api.Command['automember_rebuild'](type=u'hostgroup')
        except errors.DatabaseError:
            rebuild_failure = True
        else:
            rebuild_failure = False
        if expected_failure != rebuild_failure:
            pytest.fail("unexpected result for automember_rebuild with "
                        "an orphan automember rule")

        # Find obsolete automember rules
        result = api.Command['automember_find_orphans'](type=u'hostgroup')
        assert result['count'] == 1

        # Find and remove obsolete automember rules
        result = api.Command['automember_find_orphans'](type=u'hostgroup',
                                                        remove=True)
        assert result['count'] == 1

        # Find obsolete automember rules
        result = api.Command['automember_find_orphans'](type=u'hostgroup')
        assert result['count'] == 0

        # Test rebuild (may not be failing)
        try:
            api.Command['automember_rebuild'](type=u'hostgroup')
        except errors.DatabaseError:
            assert False

        # Final cleanup of automember rule if it still exists
        with raises_exact(
                errors.NotFound(reason=u'%s: Automember rule not found' %
                                hostgroup1.cn)):
            api.Command['automember_del'](hostgroup1.cn, type=u'hostgroup')
示例#11
0
    def execute(self, ldapuri, bindpw, **options):
        ldap = self.api.Backend.ldap2
        self.normalize_options(options)
        config = ldap.get_ipa_config()[1]

        ds_base_dn = options.get('basedn')
        if ds_base_dn is not None:
            assert isinstance(ds_base_dn, DN)

        # check if migration mode is enabled
        if config.get('ipamigrationenabled', ('FALSE', ))[0] == 'FALSE':
            return dict(result={}, failed={}, enabled=False, compat=True)

        # connect to DS
        ds_ldap = ldap2(shared_instance=False, ldap_uri=ldapuri, base_dn='')

        cacert = None
        if options.get('cacertfile') is not None:
            #store CA cert into file
            tmp_ca_cert_f = write_tmp_file(options['cacertfile'])
            cacert = tmp_ca_cert_f.name

            #start TLS connection
            ds_ldap.connect(bind_dn=options['binddn'], bind_pw=bindpw,
                tls_cacertfile=cacert)

            tmp_ca_cert_f.close()
        else:
            ds_ldap.connect(bind_dn=options['binddn'], bind_pw=bindpw)

        #check whether the compat plugin is enabled
        if not options.get('compat'):
            try:
                (dn,check_compat) = ldap.get_entry(_compat_dn)
                assert isinstance(dn, DN)
                if check_compat is not None and \
                        check_compat.get('nsslapd-pluginenabled', [''])[0].lower() == 'on':
                    return dict(result={}, failed={}, enabled=True, compat=False)
            except errors.NotFound:
                pass

        if not ds_base_dn:
            # retrieve base DN from remote LDAP server
            entries, truncated = ds_ldap.find_entries(
                '', ['namingcontexts', 'defaultnamingcontext'], DN(''),
                ds_ldap.SCOPE_BASE, size_limit=-1, time_limit=0,
            )
            if 'defaultnamingcontext' in entries[0][1]:
                ds_base_dn = DN(entries[0][1]['defaultnamingcontext'][0])
                assert isinstance(ds_base_dn, DN)
            else:
                try:
                    ds_base_dn = DN(entries[0][1]['namingcontexts'][0])
                    assert isinstance(ds_base_dn, DN)
                except (IndexError, KeyError), e:
                    raise StandardError(str(e))
示例#12
0
 def test_anonymous(self):
     """
     Test an anonymous LDAP bind using ldap2
     """
     self.conn = ldap2(api)
     self.conn.connect(autobind=AUTOBIND_DISABLED)
     dn = api.env.basedn
     entry_attrs = self.conn.get_entry(dn, ['associateddomain'])
     domain = entry_attrs.single_value['associateddomain']
     assert domain == api.env.domain
示例#13
0
文件: test_ldap.py 项目: msrb/freeipa
 def test_anonymous(self):
     """
     Test an anonymous LDAP bind using ldap2
     """
     self.conn = ldap2(api, ldap_uri=self.ldapuri)
     self.conn.connect()
     dn = api.env.basedn
     entry_attrs = self.conn.get_entry(dn, ['associateddomain'])
     domain = entry_attrs.single_value['associateddomain']
     assert domain == api.env.domain
示例#14
0
 def test_anonymous(self):
     """
     Test an anonymous LDAP bind using ldap2
     """
     self.conn = ldap2(api)
     self.conn.connect(autobind=AUTOBIND_DISABLED)
     dn = api.env.basedn
     entry_attrs = self.conn.get_entry(dn, ['associateddomain'])
     domain = entry_attrs.single_value['associateddomain']
     assert domain == api.env.domain
示例#15
0
 def test_anonymous(self):
     """
     Test an anonymous LDAP bind using ldap2
     """
     self.conn = ldap2(shared_instance=False, ldap_uri=self.ldapuri)
     self.conn.connect()
     dn = api.env.basedn
     entry_attrs = self.conn.get_entry(dn, ['associateddomain'])
     domain = entry_attrs.single_value['associateddomain']
     assert domain == api.env.domain
示例#16
0
 def test_GSSAPI(self):
     """
     Test a GSSAPI LDAP bind using ldap2
     """
     self.conn = ldap2(api)
     self.conn.connect(autobind=AUTOBIND_DISABLED)
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = x509.load_certificate(cert, x509.DER).serial_number
     assert serial is not None
示例#17
0
 def test_GSSAPI(self):
     """
     Test a GSSAPI LDAP bind using ldap2
     """
     self.conn = ldap2(api)
     self.conn.connect(autobind=AUTOBIND_DISABLED)
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = x509.load_certificate(cert, x509.DER).serial_number
     assert serial is not None
示例#18
0
 def test_GSSAPI(self):
     """
     Test a GSSAPI LDAP bind using ldap2
     """
     self.conn = ldap2(api, ldap_uri=self.ldapuri)
     self.conn.connect()
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = x509.load_certificate(cert, x509.DER).serial
     assert serial is not None
示例#19
0
 def test_GSSAPI(self):
     """
     Test a GSSAPI LDAP bind using ldap2
     """
     self.conn = ldap2(api, ldap_uri=self.ldapuri)
     self.conn.connect()
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = x509.load_certificate(cert, x509.DER).serial
     assert serial is not None
示例#20
0
 def test_autobind(self):
     """
     Test an autobind LDAP bind using ldap2
     """
     ldapuri = 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % api.env.realm.replace('.','-')
     self.conn = ldap2(shared_instance=False, ldap_uri=ldapuri)
     try:
         self.conn.connect(autobind=True)
     except errors.DatabaseError, e:
         if e.desc == 'Inappropriate authentication':
             raise nose.SkipTest("Only executed as root")
示例#21
0
 def test_anonymous(self):
     """
     Test an anonymous LDAP bind using ldap2
     """
     self.conn = ldap2(shared_instance=False, ldap_uri=self.ldapuri)
     self.conn.connect()
     (dn, entry_attrs) = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = unicode(x509.get_serial_number(cert, x509.DER))
     assert serial is not None
示例#22
0
 def test_autobind(self):
     """
     Test an autobind LDAP bind using ldap2
     """
     self.conn = ldap2(api)
     try:
         self.conn.connect(autobind=True)
     except errors.ACIError:
         raise unittest.SkipTest("Only executed as root")
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')[0]
     assert cert.serial_number is not None
示例#23
0
    def ldapentry_setup(self, request):
        self.ldapuri = api.env.ldap_uri
        self.conn = ldap2(api)
        self.conn.connect(autobind=AUTOBIND_DISABLED)

        self.entry = self.conn.make_entry(self.dn1, cn=self.cn1)

        def fin():
            if self.conn and self.conn.isconnected():
                self.conn.disconnect()

        request.addfinalizer(fin)
示例#24
0
 def test_autobind(self):
     """
     Test an autobind LDAP bind using ldap2
     """
     self.conn = ldap2(api)
     try:
         self.conn.connect(autobind=True)
     except errors.ACIError:
         raise nose.SkipTest("Only executed as root")
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')[0]
     assert cert.serial_number is not None
示例#25
0
    def execute(self, ldapuri, bindpw, **options):
        ldap = self.api.Backend.ldap2
        self.normalize_options(options)

        config = ldap.get_ipa_config()[1]

        ds_base_dn = options.get('basedn')
        if ds_base_dn is not None:
            assert isinstance(ds_base_dn, DN)

        # check if migration mode is enabled
        if config.get('ipamigrationenabled', ('FALSE', ))[0] == 'FALSE':
            return dict(result={}, failed={}, enabled=False, compat=True)

        # connect to DS
        ds_ldap = ldap2(shared_instance=False, ldap_uri=ldapuri, base_dn='')
        ds_ldap.connect(bind_dn=options['binddn'], bind_pw=bindpw)

        #check whether the compat plugin is enabled
        if not options.get('compat'):
            try:
                (dn, check_compat) = ldap.get_entry(_compat_dn,
                                                    normalize=False)
                assert isinstance(dn, DN)
                if check_compat is not None and \
                        check_compat.get('nsslapd-pluginenabled', [''])[0].lower() == 'on':
                    return dict(result={},
                                failed={},
                                enabled=True,
                                compat=False)
            except errors.NotFound:
                pass

        if not ds_base_dn:
            # retrieve base DN from remote LDAP server
            (entries, truncated) = ds_ldap.find_entries(
                '',
                ['namingcontexts', 'defaultnamingcontext'],
                DN(''),
                _ldap.SCOPE_BASE,
                size_limit=-1,
                time_limit=0,
            )
            if 'defaultnamingcontext' in entries[0][1]:
                ds_base_dn = DN(entries[0][1]['defaultnamingcontext'][0])
                assert isinstance(ds_base_dn, DN)
            else:
                try:
                    ds_base_dn = DN(entries[0][1]['namingcontexts'][0])
                    assert isinstance(ds_base_dn, DN)
                except (IndexError, KeyError), e:
                    raise StandardError(str(e))
示例#26
0
文件: install.py 项目: cluck/freeipa
def set_subject_in_config(realm_name, dm_password, suffix, subject_base):
        ldapuri = 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % (
            installutils.realm_to_serverid(realm_name)
        )
        try:
            conn = ldap2(shared_instance=False, ldap_uri=ldapuri,
                         base_dn=suffix)
            conn.connect(bind_dn=DN(('cn', 'directory manager')),
                         bind_pw=dm_password)
        except errors.ExecutionError, e:
            root_logger.critical("Could not connect to the Directory Server "
                                 "on %s" % realm_name)
            raise e
示例#27
0
 def test_GSSAPI(self):
     """
     Test a GSSAPI LDAP bind using ldap2
     """
     if not ipautil.file_exists(self.ccache):
         raise nose.SkipTest('Missing ccache %s' % self.ccache)
     self.conn = ldap2(shared_instance=False, ldap_uri=self.ldapuri)
     self.conn.connect(ccache='FILE:%s' % self.ccache)
     (dn, entry_attrs) = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = unicode(x509.get_serial_number(cert, x509.DER))
     assert serial is not None
示例#28
0
 def test_GSSAPI(self):
     """
     Test a GSSAPI LDAP bind using ldap2
     """
     if not ipautil.file_exists(self.ccache):
         raise nose.SkipTest("Missing ccache %s" % self.ccache)
     self.conn = ldap2(api, ldap_uri=self.ldapuri)
     self.conn.connect(ccache="FILE:%s" % self.ccache)
     entry_attrs = self.conn.get_entry(self.dn, ["usercertificate"])
     cert = entry_attrs.get("usercertificate")
     cert = cert[0]
     serial = unicode(x509.get_serial_number(cert, x509.DER))
     assert serial is not None
示例#29
0
 def test_GSSAPI(self):
     """
     Test a GSSAPI LDAP bind using ldap2
     """
     if not ipautil.file_exists(self.ccache):
         raise nose.SkipTest('Missing ccache %s' % self.ccache)
     self.conn = ldap2(shared_instance=False, ldap_uri=self.ldapuri)
     self.conn.connect(ccache='FILE:%s' % self.ccache)
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = unicode(x509.get_serial_number(cert, x509.DER))
     assert serial is not None
示例#30
0
    def execute(self, ldapuri, bindpw, **options):
        ldap = self.api.Backend.ldap2
        self.normalize_options(options)
        config = ldap.get_ipa_config()

        ds_base_dn = options.get("basedn")
        if ds_base_dn is not None:
            assert isinstance(ds_base_dn, DN)

        # check if migration mode is enabled
        if config.get("ipamigrationenabled", ("FALSE",))[0] == "FALSE":
            return dict(result={}, failed={}, enabled=False, compat=True)

        # connect to DS
        ds_ldap = ldap2(self.api, ldap_uri=ldapuri)

        cacert = None
        if options.get("cacertfile") is not None:
            # store CA cert into file
            tmp_ca_cert_f = write_tmp_file(options["cacertfile"])
            cacert = tmp_ca_cert_f.name

            # start TLS connection
            ds_ldap.connect(bind_dn=options["binddn"], bind_pw=bindpw, tls_cacertfile=cacert)

            tmp_ca_cert_f.close()
        else:
            ds_ldap.connect(bind_dn=options["binddn"], bind_pw=bindpw)

        # check whether the compat plugin is enabled
        if not options.get("compat"):
            try:
                ldap.get_entry(DN(("cn", "compat"), (api.env.basedn)))
                return dict(result={}, failed={}, enabled=True, compat=False)
            except errors.NotFound:
                pass

        if not ds_base_dn:
            # retrieve base DN from remote LDAP server
            entries, truncated = ds_ldap.find_entries(
                "", ["namingcontexts", "defaultnamingcontext"], DN(""), ds_ldap.SCOPE_BASE, size_limit=-1, time_limit=0
            )
            if "defaultnamingcontext" in entries[0]:
                ds_base_dn = DN(entries[0]["defaultnamingcontext"][0])
                assert isinstance(ds_base_dn, DN)
            else:
                try:
                    ds_base_dn = DN(entries[0]["namingcontexts"][0])
                    assert isinstance(ds_base_dn, DN)
                except (IndexError, KeyError), e:
                    raise StandardError(str(e))
示例#31
0
    def test_topologyplugin(self):
        supplier = REPL_PLUGIN_NAME_TEMPLATE % 'supplier'
        pluginattrs = {
            u'nsslapd-pluginPath': [u'libtopology'],
            u'nsslapd-pluginVendor': [u'freeipa'],
            u'cn': [u'IPA Topology Configuration'],
            u'nsslapd-plugin-depends-on-named': [supplier, u'ldbm database'],
            u'nsslapd-topo-plugin-shared-replica-root': [u'dc=example,dc=com'],
            u'nsslapd-pluginVersion': [u'1.0'],
            u'nsslapd-topo-plugin-shared-config-base':
            [u'cn=ipa,cn=etc,dc=example,dc=com'],
            u'nsslapd-pluginDescription': [u'ipa-topology-plugin'],
            u'nsslapd-pluginEnabled': [u'on'],
            u'nsslapd-pluginId': [u'ipa-topology-plugin'],
            u'objectClass': [u'top', u'nsSlapdPlugin', u'extensibleObject'],
            u'nsslapd-topo-plugin-startup-delay': [u'20'],
            u'nsslapd-topo-plugin-shared-binddngroup': [
                u'cn=replication managers,cn=sysaccounts,cn=etc,dc=example,dc=com'
            ],
            u'nsslapd-pluginType': [u'object'],
            u'nsslapd-pluginInitfunc': [u'ipa_topo_init']
        }
        variable_attrs = {
            u'nsslapd-topo-plugin-shared-replica-root',
            u'nsslapd-topo-plugin-shared-config-base',
            u'nsslapd-topo-plugin-shared-binddngroup'
        }

        # Now eliminate keys that have domain-dependent values.
        checkvalues = set(pluginattrs.keys()) - variable_attrs
        topoplugindn = DN(('cn', 'IPA Topology Configuration'),
                          ('cn', 'plugins'), ('cn', 'config'))
        pwfile = os.path.join(api.env.dot_ipa, ".dmpw")
        with io.open(pwfile, "r") as f:
            dm_password = f.read().rstrip()
        self.conn = ldap2(api)
        self.conn.connect(bind_dn=DN(('cn', 'directory manager')),
                          bind_pw=dm_password)
        entry = self.conn.get_entry(topoplugindn)
        assert (set(entry.keys()) == set(pluginattrs.keys()))

        # Handle different names for replication plugin
        key = 'nsslapd-plugin-depends-on-named'
        plugin_dependencies = entry[key]
        if supplier not in plugin_dependencies:
            mm = REPL_PLUGIN_NAME_TEMPLATE % 'master'
            pluginattrs[key] = [mm, 'ldbm database']

        for i in checkvalues:
            assert (set(pluginattrs[i]) == set(entry[i]))
示例#32
0
def get_ra_cert():
    api.bootstrap(in_server=True, context='restart', confdir=paths.ETC_IPA)
    api.finalize()

    base_dn = DN(('uid', 'ipara'), ('ou', 'people'), ('o', 'ipaca'))
    conn = ldap2.ldap2(api)
    conn.connect()

    entry = conn.get_entry(base_dn, ['description', 'usercertificate'])
    description = entry['description'][0]
    usercertificate = entry['usercertificate'][0]
    serial_number = description.split(';')[1]

    return int(serial_number), usercertificate
示例#33
0
 def test_autobind(self):
     """
     Test an autobind LDAP bind using ldap2
     """
     self.conn = ldap2(api)
     try:
         self.conn.connect(autobind=True)
     except errors.ACIError:
         raise nose.SkipTest("Only executed as root")
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = x509.load_certificate(cert, x509.DER).serial_number
     assert serial is not None
示例#34
0
 def test_simple(self):
     """
     Test a simple LDAP bind using ldap2
     """
     pwfile = api.env.dot_ipa + os.sep + ".dmpw"
     if ipautil.file_exists(pwfile):
         with open(pwfile, "r") as fp:
             dm_password = fp.read().rstrip()
     else:
         raise nose.SkipTest("No directory manager password in %s" % pwfile)
     self.conn = ldap2(api)
     self.conn.connect(bind_dn=DN(('cn', 'directory manager')), bind_pw=dm_password)
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')[0]
     assert cert.serial_number is not None
示例#35
0
 def test_autobind(self):
     """
     Test an autobind LDAP bind using ldap2
     """
     ldapuri = 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % api.env.realm.replace('.','-')
     self.conn = ldap2(api, ldap_uri=ldapuri)
     try:
         self.conn.connect(autobind=True)
     except errors.ACIError:
         raise nose.SkipTest("Only executed as root")
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = unicode(x509.get_serial_number(cert, x509.DER))
     assert serial is not None
示例#36
0
 def test_autobind(self):
     """
     Test an autobind LDAP bind using ldap2
     """
     ldapuri = 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % api.env.realm.replace('.','-')
     self.conn = ldap2(shared_instance=False, ldap_uri=ldapuri)
     try:
         self.conn.connect(autobind=True)
     except errors.ACIError:
         raise nose.SkipTest("Only executed as root")
     (dn, entry_attrs) = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = unicode(x509.get_serial_number(cert, x509.DER))
     assert serial is not None
示例#37
0
 def test_autobind(self):
     """
     Test an autobind LDAP bind using ldap2
     """
     ldapuri = "ldapi://%%2fvar%%2frun%%2fslapd-%s.socket" % api.env.realm.replace(".", "-")
     self.conn = ldap2(api, ldap_uri=ldapuri)
     try:
         self.conn.connect(autobind=True)
     except errors.ACIError:
         raise nose.SkipTest("Only executed as root")
     entry_attrs = self.conn.get_entry(self.dn, ["usercertificate"])
     cert = entry_attrs.get("usercertificate")
     cert = cert[0]
     serial = unicode(x509.get_serial_number(cert, x509.DER))
     assert serial is not None
示例#38
0
 def test_autobind(self):
     """
     Test an autobind LDAP bind using ldap2
     """
     ldapuri = 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % api.env.realm.replace('.','-')
     self.conn = ldap2(api, ldap_uri=ldapuri)
     try:
         self.conn.connect(autobind=True)
     except errors.ACIError:
         raise nose.SkipTest("Only executed as root")
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = x509.load_certificate(cert, x509.DER).serial
     assert serial is not None
示例#39
0
def set_subject_in_config(realm_name, dm_password, suffix, subject_base):
    ldapuri = 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % (
        installutils.realm_to_serverid(realm_name))
    try:
        conn = ldap2(api, ldap_uri=ldapuri)
        conn.connect(bind_dn=DN(('cn', 'directory manager')),
                     bind_pw=dm_password)
    except errors.ExecutionError as e:
        root_logger.critical("Could not connect to the Directory Server "
                             "on %s" % realm_name)
        raise e
    entry_attrs = conn.get_ipa_config()
    if 'ipacertificatesubjectbase' not in entry_attrs:
        entry_attrs['ipacertificatesubjectbase'] = [str(subject_base)]
        conn.update_entry(entry_attrs)
    conn.disconnect()
示例#40
0
 def test_simple(self):
     """
     Test a simple LDAP bind using ldap2
     """
     pwfile = api.env.dot_ipa + os.sep + ".dmpw"
     if os.path.isfile(pwfile):
         with open(pwfile, "r") as fp:
             dm_password = fp.read().rstrip()
     else:
         pytest.skip("No directory manager password in %s" % pwfile)
     self.conn = ldap2(api)
     self.conn.connect(bind_dn=DN(('cn', 'directory manager')),
                       bind_pw=dm_password)
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')[0]
     assert cert.serial_number is not None
示例#41
0
    def test_use(self, test_smb_svc):
        """
        Try to use the service keytab to regenerate ipaNTHash value
        """
        # Step 1. Extend objectclass to allow ipaNTHash attribute
        # We cannot verify write access to objectclass
        with use_keytab(test_smb_svc.name, self.keytabname) as conn:
            entry = conn.get_entry(test_smb_svc.dn, ['objectclass'])
            entry['objectclass'].extend(['ipaNTUserAttrs'])
            try:
                conn.update_entry(entry)
            except errors.ACIError:
                assert ('No correct ACI to the allow ipaNTUserAttrs '
                        'for SMB service' in "failure")

        # Step 2. With ipaNTUserAttrs in place, we can ask to regenerate
        # ipaNTHash value. We can also verify it is possible to write to
        # ipaNTHash attribute while being an SMB service
        with use_keytab(test_smb_svc.name, self.keytabname) as conn:
            assert conn.can_write(test_smb_svc.dn, 'ipaNTHash') is True
            entry = conn.get_entry(test_smb_svc.dn, ['ipaNTHash'])
            entry['ipanthash'] = b'MagicRegen'
            try:
                conn.update_entry(entry)
            except errors.ACIError:
                assert ("No correct ACI to the ipaNTHash for SMB service"
                        in "failure")
            except errors.EmptyResult:
                assert "No arcfour-hmac in Kerberos keys" in "failure"
            except errors.DatabaseError:
                # Most likely ipaNTHash already existed -- we either get
                # OPERATIONS_ERROR or UNWILLING_TO_PERFORM, both map to
                # the same DatabaseError class.
                assert "LDAP Entry corruption after generation" in "failure"

        # Update succeeded, now we have either MagicRegen (broken) or
        # a real NT hash in the entry. However, we can only retrieve it as
        # a cn=Directory Manager. When bind_dn is None, ldap2.connect() wil
        # default to cn=Directory Manager.
        conn = ldap2(api)
        conn.connect(bind_dn=None,
                     bind_pw=self.dm_password,
                     autobind=ipaldap.AUTOBIND_DISABLED)
        entry = conn.retrieve(test_smb_svc.dn, ['ipaNTHash'])
        ipanthash = entry.single_value.get('ipanthash')
        conn.disconnect()
        assert ipanthash is not b'MagicRegen', 'LDBM backend entry corruption'
示例#42
0
def use_keytab(principal, keytab):
    try:
        tmpdir = tempfile.mkdtemp(prefix = "tmp-")
        ccache_file = 'FILE:%s/ccache' % tmpdir
        krbcontext = krbV.default_context()
        principal = str(principal)
        keytab = krbV.Keytab(name=keytab, context=krbcontext)
        principal = krbV.Principal(name=principal, context=krbcontext)
        os.environ['KRB5CCNAME'] = ccache_file
        ccache = krbV.CCache(name=ccache_file, context=krbcontext, primary_principal=principal)
        ccache.init(principal)
        ccache.init_creds_keytab(keytab=keytab, principal=principal)
        conn = ldap2(shared_instance=False, ldap_uri=api.env.ldap_uri, base_dn=api.env.basedn)
        conn.connect(ccache=ccache)
        conn.disconnect()
    except krbV.Krb5Error, e:
        raise StandardError('Unable to bind to LDAP. Error initializing principal %s in %s: %s' % (principal.name, keytab, str(e)))
示例#43
0
def set_subject_in_config(realm_name, dm_password, suffix, subject_base):
        ldapuri = 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % (
            installutils.realm_to_serverid(realm_name)
        )
        try:
            conn = ldap2(api, ldap_uri=ldapuri)
            conn.connect(bind_dn=DN(('cn', 'directory manager')),
                         bind_pw=dm_password)
        except errors.ExecutionError as e:
            root_logger.critical("Could not connect to the Directory Server "
                                 "on %s" % realm_name)
            raise e
        entry_attrs = conn.get_ipa_config()
        if 'ipacertificatesubjectbase' not in entry_attrs:
            entry_attrs['ipacertificatesubjectbase'] = [str(subject_base)]
            conn.update_entry(entry_attrs)
        conn.disconnect()
示例#44
0
    def __create_kra_agent(self):
        """
        Create KRA agent, assign a certificate, and add the user to
        the appropriate groups for accessing KRA services.
        """

        # get ipaCert certificate
        with certdb.NSSDatabase(paths.HTTPD_ALIAS_DIR) as ipa_nssdb:
            cert_data = ipa_nssdb.get_cert("ipaCert")
        cert = x509.load_certificate(cert_data, x509.DER)

        # connect to KRA database
        server_id = installutils.realm_to_serverid(api.env.realm)
        dogtag_uri = 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % server_id
        conn = ldap2.ldap2(api, ldap_uri=dogtag_uri)
        conn.connect(autobind=True)

        # create ipakra user with ipaCert certificate
        user_dn = DN(('uid', "ipakra"), ('ou', 'people'), self.basedn)
        entry = conn.make_entry(
            user_dn,
            objectClass=[
                'top', 'person', 'organizationalPerson', 'inetOrgPerson',
                'cmsuser'
            ],
            uid=["ipakra"],
            sn=["IPA KRA User"],
            cn=["IPA KRA User"],
            usertype=["undefined"],
            userCertificate=[cert_data],
            description=[
                '2;%s;%s;%s' %
                (cert.serial_number,
                 DN(('CN', 'Certificate Authority'),
                    self.subject_base), DN(
                        ('CN', 'IPA RA'), self.subject_base))
            ])
        conn.add_entry(entry)

        # add ipakra user to Data Recovery Manager Agents group
        group_dn = DN(('cn', 'Data Recovery Manager Agents'), ('ou', 'groups'),
                      self.basedn)
        conn.add_entry_to_group(user_dn, group_dn, 'uniqueMember')

        conn.disconnect()
示例#45
0
def use_keytab(principal, keytab):
    with private_ccache() as ccache_file:
        try:
            old_principal = getattr(context, 'principal', None)
            name = gssapi.Name(principal, gssapi.NameType.kerberos_principal)
            store = {'ccache': ccache_file, 'client_keytab': keytab}
            gssapi.Credentials(name=name, usage='initiate', store=store)
            conn = ldap2(api)
            conn.connect(ccache=ccache_file,
                         autobind=ipaldap.AUTOBIND_DISABLED)
            yield conn
            conn.disconnect()
        except gssapi.exceptions.GSSError as e:
            raise Exception('Unable to bind to LDAP. Error initializing '
                            'principal %s in %s: %s' %
                            (principal, keytab, str(e)))
        finally:
            setattr(context, 'principal', old_principal)
示例#46
0
def use_keytab(principal, keytab):
    try:
        tmpdir = tempfile.mkdtemp(prefix = "tmp-")
        ccache_file = 'FILE:%s/ccache' % tmpdir
        name = gssapi.Name(principal, gssapi.NameType.kerberos_principal)
        store = {'ccache': ccache_file,
                 'client_keytab': keytab}
        os.environ['KRB5CCNAME'] = ccache_file
        gssapi.Credentials(name=name, usage='initiate', store=store)
        conn = ldap2(api)
        conn.connect(autobind=ipaldap.AUTOBIND_DISABLED)
        conn.disconnect()
    except gssapi.exceptions.GSSError as e:
        raise StandardError('Unable to bind to LDAP. Error initializing principal %s in %s: %s' % (principal, keytab, str(e)))
    finally:
        os.environ.pop('KRB5CCNAME', None)
        if tmpdir:
            shutil.rmtree(tmpdir)
示例#47
0
def use_keytab(principal, keytab):
    try:
        tmpdir = tempfile.mkdtemp(prefix = "tmp-")
        ccache_file = 'FILE:%s/ccache' % tmpdir
        name = gssapi.Name(principal, gssapi.NameType.kerberos_principal)
        store = {'ccache': ccache_file,
                 'client_keytab': keytab}
        os.environ['KRB5CCNAME'] = ccache_file
        gssapi.Credentials(name=name, usage='initiate', store=store)
        conn = ldap2(api)
        conn.connect(autobind=ipaldap.AUTOBIND_DISABLED)
        conn.disconnect()
    except gssapi.exceptions.GSSError as e:
        raise Exception('Unable to bind to LDAP. Error initializing principal %s in %s: %s' % (principal, keytab, str(e)))
    finally:
        os.environ.pop('KRB5CCNAME', None)
        if tmpdir:
            shutil.rmtree(tmpdir)
示例#48
0
 def test_simple(self):
     """
     Test a simple LDAP bind using ldap2
     """
     pwfile = api.env.dot_ipa + os.sep + ".dmpw"
     if ipautil.file_exists(pwfile):
         fp = open(pwfile, "r")
         dm_password = fp.read().rstrip()
         fp.close()
     else:
         raise nose.SkipTest("No directory manager password in %s" % pwfile)
     self.conn = ldap2(shared_instance=False, ldap_uri=self.ldapuri)
     self.conn.connect(bind_dn=DN(('cn', 'directory manager')), bind_pw=dm_password)
     (dn, entry_attrs) = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = unicode(x509.get_serial_number(cert, x509.DER))
     assert serial is not None
示例#49
0
 def test_simple(self):
     """
     Test a simple LDAP bind using ldap2
     """
     pwfile = api.env.dot_ipa + os.sep + ".dmpw"
     if ipautil.file_exists(pwfile):
         with open(pwfile, "r") as fp:
             dm_password = fp.read().rstrip()
     else:
         raise nose.SkipTest("No directory manager password in %s" % pwfile)
     self.conn = ldap2(api)
     self.conn.connect(bind_dn=DN(('cn', 'directory manager')),
                       bind_pw=dm_password)
     entry_attrs = self.conn.get_entry(self.dn, ['usercertificate'])
     cert = entry_attrs.get('usercertificate')
     cert = cert[0]
     serial = x509.load_certificate(cert, x509.DER).serial_number
     assert serial is not None
示例#50
0
def wait_automember_rebuild():
    """Wait for an asynchronous automember rebuild to finish

    Lookup the rebuild taskid and then loop until it is finished.

    If no task is found assume that the task is already finished.
    """
    if not have_ldap2:
        raise unittest.SkipTest('server plugin not available')
    ldap = ldap2(api)
    ldap.connect()

    # give the task a chance to start
    time.sleep(1)

    try:
        task_entries, unused = ldap.find_entries(
            base_dn=REBUILD_TASK_CONTAINER,
            filter='(&(!(nstaskexitcode=0))(scope=*))')
    except errors.NotFound:
        # either it's done already or it never started
        return

    # we run these serially so there should be only one at a time
    assert len(task_entries) == 1

    task_dn = task_entries[0].dn

    start_time = time.time()
    while True:
        try:
            task = ldap.get_entry(task_dn)
        except errors.NotFound:
            # not likely but let's hope the task disappered because it's
            # finished
            break

        if 'nstaskexitcode' in task:
            # a non-zero exit code means something broke
            assert task.single_value['nstaskexitcode'] == '0'
            break
        time.sleep(1)
        # same arbitrary wait time as hardcoded in automember plugin
        assert time.time() < (start_time + 60)
示例#51
0
    def __create_kra_agent(self):
        """
        Create KRA agent, assign a certificate, and add the user to
        the appropriate groups for accessing KRA services.
        """

        # get ipaCert certificate
        with certdb.NSSDatabase(paths.HTTPD_ALIAS_DIR) as ipa_nssdb:
            cert_data = ipa_nssdb.get_cert("ipaCert")
        cert = x509.load_certificate(cert_data, x509.DER)

        # connect to KRA database
        server_id = installutils.realm_to_serverid(api.env.realm)
        dogtag_uri = "ldapi://%%2fvar%%2frun%%2fslapd-%s.socket" % server_id
        conn = ldap2.ldap2(api, ldap_uri=dogtag_uri)
        conn.connect(autobind=True)

        # create ipakra user with ipaCert certificate
        user_dn = DN(("uid", "ipakra"), ("ou", "people"), self.basedn)
        entry = conn.make_entry(
            user_dn,
            objectClass=["top", "person", "organizationalPerson", "inetOrgPerson", "cmsuser"],
            uid=["ipakra"],
            sn=["IPA KRA User"],
            cn=["IPA KRA User"],
            usertype=["undefined"],
            userCertificate=[cert_data],
            description=[
                "2;%s;%s;%s"
                % (
                    cert.serial_number,
                    DN(("CN", "Certificate Authority"), self.subject_base),
                    DN(("CN", "IPA RA"), self.subject_base),
                )
            ],
        )
        conn.add_entry(entry)

        # add ipakra user to Data Recovery Manager Agents group
        group_dn = DN(("cn", "Data Recovery Manager Agents"), ("ou", "groups"), self.basedn)
        conn.add_entry_to_group(user_dn, group_dn, "uniqueMember")

        conn.disconnect()
示例#52
0
    def test_topologyplugin(self):
        pluginattrs = {
            u'nsslapd-pluginPath': [u'libtopology'],
            u'nsslapd-pluginVendor': [u'freeipa'],
            u'cn': [u'IPA Topology Configuration'],
            u'nsslapd-plugin-depends-on-named':
                [u'Multimaster Replication Plugin', u'ldbm database'],
            u'nsslapd-topo-plugin-shared-replica-root': [u'dc=example,dc=com'],
            u'nsslapd-pluginVersion': [u'1.0'],
            u'nsslapd-topo-plugin-shared-config-base':
                [u'cn=ipa,cn=etc,dc=example,dc=com'],
            u'nsslapd-pluginDescription': [u'ipa-topology-plugin'],
            u'nsslapd-pluginEnabled': [u'on'],
            u'nsslapd-pluginId': [u'ipa-topology-plugin'],
            u'objectClass': [u'top', u'nsSlapdPlugin', u'extensibleObject'],
            u'nsslapd-topo-plugin-startup-delay': [u'20'],
            u'nsslapd-topo-plugin-shared-binddngroup':
                [u'cn=replication managers,cn=sysaccounts,cn=etc,dc=example,dc=com'],
            u'nsslapd-pluginType': [u'object'],
            u'nsslapd-pluginInitfunc': [u'ipa_topo_init']
        }
        variable_attrs = {u'nsslapd-topo-plugin-shared-replica-root',
                          u'nsslapd-topo-plugin-shared-config-base',
                          u'nsslapd-topo-plugin-shared-binddngroup'}

        # Now eliminate keys that have domain-dependent values.
        checkvalues = set(pluginattrs.keys()) - variable_attrs
        topoplugindn = DN(('cn', 'IPA Topology Configuration'),
                          ('cn', 'plugins'),
                          ('cn', 'config'))
        pwfile = os.path.join(api.env.dot_ipa, ".dmpw")
        if ipautil.file_exists(pwfile):
            with open(pwfile, "r") as f:
                dm_password = f.read().rstrip()
        else:
            raise nose.SkipTest("No directory manager password in %s" % pwfile)
        self.conn = ldap2(api)
        self.conn.connect(bind_dn=DN(('cn', 'directory manager')),
                          bind_pw=dm_password)
        entry = self.conn.get_entry(topoplugindn)
        assert(set(entry.keys()) == set(pluginattrs.keys()))
        for i in checkvalues:
            assert(pluginattrs[i] == entry[i])
示例#53
0
    def ldap_connect(self):
        conn = ldap2(api)

        password = self.options.password
        if not password:
            try:
                conn.connect()
            except (gssapi.exceptions.GSSError, errors.ACIError):
                pass
            else:
                return conn

            password = installutils.read_password(
                "Directory Manager", confirm=False, validate=False)
            if password is None:
                raise admintool.ScriptError(
                    "Directory Manager password required")

        conn.connect(bind_dn=DN(('cn', 'Directory Manager')), bind_pw=password)

        return conn
def set_automember_process_modify_ops(value):
    """Configure the auto member plugin to process modifyOps

    Set the value for the attribute autoMemberProcessModifyOps of the entry
    cn=Auto Membership Plugin,cn=plugins,cn=config.
    :param value: can be either on or off
    """
    if not have_ldap2:
        raise unittest.SkipTest('server plugin not available')
    ldap = ldap2(api)
    ldap.connect()
    plugin_entry = ldap.get_entry(
        DN("cn=Auto Membership Plugin,cn=plugins,cn=config"))
    plugin_entry['autoMemberProcessModifyOps'] = value
    try:
        ldap.update_entry(plugin_entry)
    except errors.EmptyModlist:
        pass
    # Requires a 389-ds restart
    dashed_domain = api.env.realm.replace(".", "-")
    cmd = ['systemctl', 'restart', 'dirsrv@{}'.format(dashed_domain)]
    run(cmd)
示例#55
0
    def ldap_connect(self):
        conn = ldap2()

        password = self.options.password
        if not password:
            try:
                ccache = krbV.default_context().default_ccache()
                conn.connect(ccache=ccache)
            except (krbV.Krb5Error, errors.ACIError):
                pass
            else:
                return conn

            password = installutils.read_password(
                "Directory Manager", confirm=False, validate=False)
            if password is None:
                raise admintool.ScriptError(
                    "Directory Manager password required")

        conn.connect(bind_dn=DN(('cn', 'Directory Manager')), bind_pw=password)

        return conn
示例#56
0
    def __create_kra_agent(self):
        """
        Create KRA agent, assign a certificate, and add the user to
        the appropriate groups for accessing KRA services.
        """

        # get RA agent certificate
        cert = x509.load_certificate_from_file(paths.RA_AGENT_PEM)
        cert_data = cert.public_bytes(x509.Encoding.DER)

        # connect to KRA database
        conn = ldap2.ldap2(api)
        conn.connect(autobind=True)

        # create ipakra user with RA agent certificate
        user_dn = DN(('uid', "ipakra"), ('ou', 'people'), self.basedn)
        entry = conn.make_entry(
            user_dn,
            objectClass=[
                'top', 'person', 'organizationalPerson', 'inetOrgPerson',
                'cmsuser'
            ],
            uid=["ipakra"],
            sn=["IPA KRA User"],
            cn=["IPA KRA User"],
            usertype=["undefined"],
            userCertificate=[cert_data],
            description=[
                '2;%s;%s;%s' % (cert.serial_number, DN(
                    self.subject), DN(('CN', 'IPA RA'), self.subject_base))
            ])
        conn.add_entry(entry)

        # add ipakra user to Data Recovery Manager Agents group
        group_dn = DN(('cn', 'Data Recovery Manager Agents'), ('ou', 'groups'),
                      self.basedn)
        conn.add_entry_to_group(user_dn, group_dn, 'uniqueMember')

        conn.disconnect()
示例#57
0
def set_automember_process_modify_ops(value):
    """Configure the auto member plugin to process modifyOps

    Set the value for the attribute autoMemberProcessModifyOps of the entry
    cn=Auto Membership Plugin,cn=plugins,cn=config.
    :param value: can be either on or off
    """
    if not have_ldap2:
        raise unittest.SkipTest('server plugin not available')
    ldap = ldap2(api)
    ldap.connect()
    plugin_entry = ldap.get_entry(
        DN("cn=Auto Membership Plugin,cn=plugins,cn=config"))
    plugin_entry['autoMemberProcessModifyOps'] = value
    try:
        ldap.update_entry(plugin_entry)
    except errors.EmptyModlist:
        pass
    # Requires a 389-ds restart
    dashed_domain = api.env.realm.replace(".", "-")
    cmd = ['systemctl', 'restart', 'dirsrv@{}'.format(dashed_domain)]
    run(cmd)