Ejemplo n.º 1
0
 def validate_trusted_domain_sid(self, sid):
     if not _dcerpc_bindings_installed:
         raise errors.NotFound(reason=_(
             'Cannot perform SID validation without Samba 4 support installed. '
             'Make sure you have installed server-trust-ad sub-package of IPA on the server'
         ))
     domain_validator = ipaserver.dcerpc.DomainValidator(self.api)
     if not domain_validator.is_configured():
         raise errors.NotFound(reason=_(
             'Cross-realm trusts are not configured. '
             'Make sure you have run ipa-adtrust-install on the IPA server first'
         ))
     if not domain_validator.is_trusted_sid_valid(sid):
         raise errors.ValidationError(
             name='domain SID',
             error=_(
                 'SID is not recognized as a valid SID for a trusted domain'
             ))
Ejemplo n.º 2
0
 def get_entry(self,
               dn,
               attrs_list=None,
               time_limit=None,
               size_limit=None,
               get_effective_rights=False):
     if self.results is None:
         raise errors.NotFound(reason='test')
     return self.results
Ejemplo n.º 3
0
 def _retrieve(self, commandfull_name, name, **kwargs):
     cmd = self.api.Command[commandfull_name]
     try:
         return (cmd, cmd.output[name])
     except KeyError:
         raise errors.NotFound(reason=_("%(pkey)s: %(oname)s not found") % {
             'pkey': name,
             'oname': self.name,
         })
Ejemplo n.º 4
0
 def test_rebuild_membership_with_invalid_hosts_in_hosts(
         self, automember_hostgroup):
     """ Try to rebuild membership with invalid host in --hosts """
     command = automember_hostgroup.make_rebuild_command(
         hosts=fqdn_does_not_exist)
     with raises_exact(
             errors.NotFound(reason=u'%s: host not found' %
                             fqdn_does_not_exist)):
         command()
Ejemplo n.º 5
0
 def handle_not_found(self, *keys):
     pkey = keys[-1]
     key = pkey.split(self.rdn_separator)[0]
     info = self.rdn_separator.join(pkey.split(self.rdn_separator)[1:])
     raise errors.NotFound(
         reason=self.object_not_found_msg % {
             'key': key, 'info': info,
         }
     )
Ejemplo n.º 6
0
 def dn_exists(self, grouptype, groupname, *keys):
     ldap = self.api.Backend.ldap2
     dn = self.api.Object[grouptype].get_dn(groupname)
     try:
         (gdn, entry_attrs) = ldap.get_entry(dn, [])
     except errors.NotFound:
         raise errors.NotFound(reason=_(u'Group: %s not found!') %
                               groupname)
     return gdn
Ejemplo n.º 7
0
 def test_delete_detached_managed(self, managed_group, user):
     """ Delete a previously managed group that is now detached
     and verify it's really gone """
     managed_group.delete()
     command = managed_group.make_retrieve_command()
     with raises_exact(errors.NotFound(
             reason=u'%s: group not found' % managed_group.cn)):
         command()
     user.ensure_missing()
Ejemplo n.º 8
0
 def test_delete_with_nonexistent_hostgroup(self, automember_hostgroup,
                                            hostgroup1):
     """ Try to delete a rule with non-existent group """
     hostgroup1.ensure_missing()
     command = automember_hostgroup.make_delete_command()
     with raises_exact(
             errors.NotFound(reason=u'%s: Automember rule not found' %
                             hostgroup1.cn)):
         command()
Ejemplo n.º 9
0
def ca_enabled_check(_api):
    """Raise NotFound if CA is not enabled.

    This function is defined in multiple plugins to avoid circular imports
    (cert depends on certprofile, so we cannot import cert here).

    """
    if not _api.Command.ca_is_enabled()['result']:
        raise errors.NotFound(reason=_('CA is not configured'))
Ejemplo n.º 10
0
 def _retrieve(self, full_name, **kwargs):
     self.__make_topics()
     try:
         return self.__topics_by_key[full_name]
     except KeyError:
         raise errors.NotFound(reason=_("%(pkey)s: %(oname)s not found") % {
             'pkey': full_name,
             'oname': self.name,
         })
Ejemplo n.º 11
0
 def test_add_nonexistent_location_to_server(self, server):
     nonexistent_loc = DNSName(u'nonexistent-location')
     command = server.make_update_command(
         updates=dict(ipalocation_location=nonexistent_loc, ))
     with raises_exact(
             errors.NotFound(
                 reason=u"{location}: location not found".format(
                     location=nonexistent_loc))):
         command()
Ejemplo n.º 12
0
 def test_rebuild_membership_with_invalid_user_in_users(
         self, automember_group):
     """ Try to rebuild membership with invalid user in --users """
     command = automember_group.make_rebuild_command(
         users=user_does_not_exist)
     with raises_exact(
             errors.NotFound(reason=u'%s: user not found' %
                             user_does_not_exist)):
         command()
Ejemplo n.º 13
0
def resolve_anchor_to_object_name(ldap, obj_type, anchor):
    """
    Resolves IPA Anchor UUID to the actual common object name (uid for users,
    cn for groups).

    Takes options:
        ldap - the backend
        anchor - the anchor, e.g.
                 ':IPA:ipa.example.com:2cb604ea-39a5-11e4-a37e-001a4a22216f'
    """

    if anchor.startswith(IPA_ANCHOR_PREFIX):

        # Prepare search parameters
        accounts_dn = DN(api.env.container_accounts, api.env.basedn)

        # Anchor of the form :IPA:<domain>:<uuid>
        # Strip the IPA prefix and the domain prefix
        uuid = anchor.rpartition(':')[-1].strip()

        # Set the object type-specific search attributes
        objectclass, name_attr = {
            'user': ('posixaccount', 'uid'),
            'group': ('ipausergroup', 'cn'),
        }[obj_type]

        entry = ldap.find_entry_by_attr(attr='ipaUniqueID',
                                        value=uuid,
                                        object_class=objectclass,
                                        attrs_list=[name_attr],
                                        base_dn=accounts_dn)

        # Return the name of the object, which is either cn for
        # groups or uid for users
        return entry.single_value[name_attr]

    elif anchor.startswith(SID_ANCHOR_PREFIX):

        # Parse the SID out from the anchor
        sid = anchor[len(SID_ANCHOR_PREFIX):].strip()

        if _dcerpc_bindings_installed:
            domain_validator = ipaserver.dcerpc.DomainValidator(api)
            if domain_validator.is_configured():
                name = domain_validator.get_trusted_domain_object_from_sid(sid)

                # We need to verify that the object type is correct
                type_correct = verify_trusted_domain_object_type(
                    domain_validator, obj_type, name)

                if type_correct:
                    return name

    # No acceptable object was found
    raise errors.NotFound(
        reason=_("Anchor '%(anchor)s' could not be resolved.") %
        dict(anchor=anchor))
Ejemplo n.º 14
0
 def test_rename_nonexistent(self, idp, renamedidp):
     """ Try to rename a non-existent idp """
     idp.ensure_missing()
     command = idp.make_update_command(updates=dict(setattr='cn=%s' %
                                                    renamedidp.cn))
     with raises_exact(
             errors.NotFound(
                 reason='%s: Identity Provider server not found' % idp.cn)):
         command()
Ejemplo n.º 15
0
 def test_update_nonexistent(self, idp):
     """ Try to update a non-existent idp """
     idp.ensure_missing()
     command = idp.make_update_command(updates=dict(
         ipaidpclientid='idpclient2'))
     with raises_exact(
             errors.NotFound(
                 reason='%s: Identity Provider server not found' % idp.cn)):
         command()
Ejemplo n.º 16
0
 def test_update_nonexistent(self, hostgroup):
     """ Try to update non-existent hostgroup """
     hostgroup.ensure_missing()
     command = hostgroup.make_update_command(
         dict(description=u'Updated hostgroup 1')
     )
     with raises_exact(errors.NotFound(
             reason=u'%s: host group not found' % hostgroup.cn)):
         command()
Ejemplo n.º 17
0
def validate_selinuxuser_inlist(ldap, user):
    """
    Ensure the user is in the list of allowed SELinux users.

    Returns nothing if the user is found, raises an exception otherwise.
    """
    config = ldap.get_ipa_config()[1]
    item = config.get('ipaselinuxusermaporder', [])
    if len(item) != 1:
        raise errors.NotFound(reason=_('SELinux user map list not '
                                       'found in configuration'))
    userlist = item[0].split('$')
    if user not in userlist:
        raise errors.NotFound(reason=_('SELinux user %(user)s not found in '
                                       'ordering list (in config)') %
                              dict(user=user))

    return
Ejemplo n.º 18
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')
Ejemplo n.º 19
0
 def test_assign_nonexistent_manager(self, user, user2):
     """ Try to assign user a non-existent manager """
     user.ensure_exists()
     user2.ensure_missing()
     command = user.make_update_command(
         updates=dict(manager=user2.uid)
     )
     with raises_exact(errors.NotFound(
             reason=u'manager %s not found' % user2.uid)):
         command()
Ejemplo n.º 20
0
 def get_entries(self,
                 base_dn,
                 scope=SCOPE_SUBTREE,
                 filter=None,
                 attrs_list=None,
                 get_effective_rights=False,
                 **kwargs):
     if self.results is None:
         raise errors.NotFound(reason='test')
     return self.results
Ejemplo n.º 21
0
    def test_preserved_manager(self, user, user3):
        user.ensure_exists()
        user3.make_preserved_user()

        command = user.make_update_command(updates=dict(manager=user3.uid))
        with raises_exact(
                errors.NotFound(reason=u'manager %s not found' % user3.uid)):
            command()

        user3.delete()
Ejemplo n.º 22
0
 def dn_exists(self, otype, oname):
     ldap = self.api.Backend.ldap2
     dn = self.api.Object[otype].get_dn(oname)
     try:
         entry = ldap.get_entry(dn, [])
     except errors.NotFound:
         raise errors.NotFound(
             reason=_(u'%(otype)s "%(oname)s" not found') %
             dict(otype=otype, oname=oname))
     return entry.dn
Ejemplo n.º 23
0
 def test_create_without_upg(self):
     """ Try to create user without User's Primary GID """
     testuser = UserTracker(
         name=u'tuser1', givenname=u'Test', sn=u'Tuser1',
         noprivate=True
     )
     command = testuser.make_create_command()
     with raises_exact(errors.NotFound(
             reason=u'Default group for new users is not POSIX')):
         command()
Ejemplo n.º 24
0
    def pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)

        entry_attrs['cn'] = keys[-1]
        if not automember_container_exists(self.api.Backend.ldap2):
            raise errors.NotFound(
                reason=_('Auto Membership is not configured'))
        entry_attrs['automembertargetgroup'] = self.obj.dn_exists(
            options['type'], keys[-1])
        return dn
Ejemplo n.º 25
0
    def _retrieve(self, name, **kwargs):
        try:
            return self.api.Object[name]
        except KeyError:
            pass

        raise errors.NotFound(reason=_("%(pkey)s: %(oname)s not found") % {
            'pkey': name,
            'oname': self.name,
        })
Ejemplo n.º 26
0
 def check_attr(self, attr):
     """
     Verify that the user supplied key is a valid attribute in the schema
     """
     ldap = self.api.Backend.ldap2
     obj = ldap.schema.get_obj(_ldap.schema.AttributeType, attr)
     if obj is not None:
         return obj
     else:
         raise errors.NotFound(reason=_('%s is not a valid attribute.') % attr)
Ejemplo n.º 27
0
    def execute(self, *args, **options):
        # Deferred import, ipaclient.csrgen is expensive to load.
        # see https://pagure.io/freeipa/issue/7484
        from ipaclient import csrgen
        from ipaclient import csrgen_ffi

        if 'out' in options:
            util.check_writable_file(options['out'])

        principal = options.get('principal')
        profile_id = options.get('profile_id')
        if profile_id is None:
            profile_id = dogtag.DEFAULT_PROFILE
        public_key_info = options.get('public_key_info')
        public_key_info = base64.b64decode(public_key_info)

        if self.api.env.in_server:
            backend = self.api.Backend.ldap2
        else:
            backend = self.api.Backend.rpcclient
        if not backend.isconnected():
            backend.connect()

        try:
            if principal.is_host:
                principal_obj = api.Command.host_show(principal.hostname,
                                                      all=True)
            elif principal.is_service:
                principal_obj = api.Command.service_show(unicode(principal),
                                                         all=True)
            elif principal.is_user:
                principal_obj = api.Command.user_show(principal.username,
                                                      all=True)
        except errors.NotFound:
            raise errors.NotFound(
                reason=_("The principal for this request doesn't exist."))
        principal_obj = principal_obj['result']
        config = api.Command.config_show()['result']

        generator = csrgen.CSRGenerator(csrgen.FileRuleProvider())

        csr_config = generator.csr_config(principal_obj, config, profile_id)
        request_info = base64.b64encode(
            csrgen_ffi.build_requestinfo(csr_config.encode('utf8'),
                                         public_key_info))

        result = {}
        if 'out' in options:
            with open(options['out'], 'wb') as f:
                f.write(request_info)
        else:
            result = dict(request_info=request_info)

        return dict(result=result)
Ejemplo n.º 28
0
    def test_staged_manager(self, user, stageduser):
        user.ensure_exists()
        stageduser.ensure_exists()

        command = user.make_update_command(
            updates=dict(manager=stageduser.uid))
        with raises_exact(errors.NotFound(
                reason=u'manager %s not found' % stageduser.uid)):
            command()
        user.delete()
        stageduser.delete()
Ejemplo n.º 29
0
 def __read_mapfile(self, filename):
     try:
         fp = open(filename, 'r')
         map = fp.readlines()
         fp.close()
     except IOError, e:
         if e.errno == 2:
             raise errors.NotFound(reason=_('File %(file)s not found') %
                                   {'file': filename})
         else:
             raise
Ejemplo n.º 30
0
    def get_dn(self, *keys, **kwargs):
        # all commands except for create send pk in keys, too
        # create cannot due to validation in frontend.py
        ldap = self.backend
        if len(keys) == self.num_parents:
            try:
                pkey = kwargs[self.primary_key.name]
            except KeyError:
                raise ValueError('Not enough keys and pkey not in kwargs')
            parent_keys = keys
        else:
            pkey = keys[-1]
            parent_keys = keys[:-1]

        parent_dn = self.api.Object[self.parent_object].get_dn(*parent_keys)
        dn = self.backend.make_dn_from_attr(self.primary_key.name, pkey,
                                            parent_dn)
        # If we're doing an add then just return the dn we created, there
        # is no need to check for it.
        if kwargs.get('add_operation', False):
            return dn
        # We had an older mechanism where description consisted of
        # 'automountkey automountinformation' so we could support multiple
        # direct maps. This made showing keys nearly impossible since it
        # required automountinfo to show, which if you had you didn't need
        # to look at the key. We still support existing entries but now
        # only create this type of dn when the key is /-
        #
        # First we look with the information given, then try to search for
        # the right entry.
        try:
            (dn, entry_attrs) = ldap.get_entry(dn, ['*'],
                                               normalize=self.normalize_dn)
        except errors.NotFound:
            if kwargs.get('automountinformation', False):
                sfilter = '(&(automountkey=%s)(automountinformation=%s))' % \
                    (kwargs['automountkey'], kwargs['automountinformation'])
            else:
                sfilter = '(automountkey=%s)' % kwargs['automountkey']
            basedn = DN(('automountmapname', parent_keys[1]),
                        ('cn', parent_keys[0]), self.container_dn)
            attrs_list = ['*']
            (entries, truncated) = ldap.find_entries(sfilter, attrs_list,
                                                     basedn,
                                                     _ldap.SCOPE_ONELEVEL)
            if len(entries) > 1:
                raise errors.NotFound(reason=_(
                    'More than one entry with key %(key)s found, use --info to select specific entry.'
                ) % dict(key=pkey))
            if truncated:
                raise errors.LimitsExceeded()
            dn = entries[0][0]

        return dn