Пример #1
0
# Authors:
#   Jason Gerard DeRose <*****@*****.**>
#   Rob Crittenden <*****@*****.**>
#
# Copyright (C) 2008  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
XML-RPC client plugin.
"""

from ipalib import api

if 'in_server' in api.env and api.env.in_server is False:
    from ipalib.rpc import xmlclient
    api.register(xmlclient)
Пример #2
0
   ipa ping
   ------------------------------------------
   IPA server version 2.1.9. API version 2.20
   ------------------------------------------

 Ping an IPA server verbosely:
   ipa -v ping
   ipa: INFO: trying https://ipa.example.com/ipa/xml
   ipa: INFO: Forwarding 'ping' to server u'https://ipa.example.com/ipa/xml'
   -----------------------------------------------------
   IPA server version 2.1.9. API version 2.20
   -----------------------------------------------------
""")


class ping(Command):
    __doc__ = _('Ping a remote server.')

    has_output = (output.summary, )

    def execute(self):
        """
        A possible enhancement would be to take an argument and echo it
        back but a fixed value works for now.
        """
        return dict(summary=u'IPA server version %s. API version %s' %
                    (VERSION, API_VERSION))


api.register(ping)
Пример #3
0
        ng_container = DN(api.env.container_netgroup, api.env.basedn)
        for member in list(entry_attrs.get('memberofindirect', [])):
            memberdn = DN(member)
            if not memberdn.endswith(ng_container):
                continue

            filter = ldap.make_filter({'objectclass': 'mepmanagedentry'})
            try:
                ldap.find_entries(filter=filter, base_dn=memberdn,
                                  scope=ldap.SCOPE_BASE, attrs_list=[''])
            except errors.NotFound:
                pass
            else:
                entry_attrs['memberofindirect'].remove(member)

api.register(host)


class host_add(LDAPCreate):
    __doc__ = _('Add a new host.')

    has_output_params = LDAPCreate.has_output_params + host_output_params
    msg_summary = _('Added host "%(value)s"')
    member_attributes = ['managedby']
    takes_options = LDAPCreate.takes_options + (
        Flag('force',
            label=_('Force'),
            doc=_('force host name even if not in DNS'),
        ),
        Flag('no_reverse',
            doc=_('skip reverse DNS detection'),
import docopt  # sudo dnf install python-docopt

from ipalib import parameters
from ipalib import api, errors
from ipalib.cli import cli_plugins
from ipapython import ipautil, ipaldap
from ipapython.dn import DN
from ipalib.rpc import json_encode_binary

argv = list(sys.argv[1:])
del sys.argv[1:]

api.bootstrap_with_global_options(context='cli')
api.load_plugins()
for cls in cli_plugins:
    api.register(cls)
api.finalize()

try:
    from ipalib.plugins.permission import DNOrURL
except ImportError:

    class DNOrURL(object):
        pass


def shell_quote(string):
    if re.match('^[-._~a-zA-Z0-9]+$', string):
        return string
    else:
        return ipautil.shell_quote(string)
Пример #5
0
                              "services to update, truncated: %s",
                              len(entries), truncated)

            error = False
            for entry in entries:
                entry['objectclass'] = (entry['objectclass'] +
                                        ['ipakrbprincipal'])
                entry['ipakrbprincipalalias'] = entry['krbprincipalname']
                try:
                    ldap.update_entry(entry)
                except (errors.EmptyModlist, errors.NotFound):
                    pass
                except errors.ExecutionError, e:
                    root_logger.debug("update_service_principalalias: cannot "
                                      "update service: %s", e)
                    error = True

            if error:
                # exit loop to avoid infinite cycles
                root_logger.error("update_service_principalalias: error(s)"
                                  "detected during service update")
                return False, []
            elif not truncated:
                # all affected entries updated, exit the loop
                root_logger.debug("update_service_principalalias: all affected"
                                  " services updated")
                return False, []
        return False, []

api.register(update_service_principalalias)
Пример #6
0

#-------------------------------------------------------------------------------

from ipalib.request import context

class session_logout(Command):
    '''
    RPC command used to log the current user out of their session.
    '''

    def execute(self, *args, **options):
        session_data = getattr(context, 'session_data', None)
        if session_data is None:
            self.debug('session logout command: no session_data found')
        else:
            session_id = session_data.get('session_id')
            self.debug('session logout command: session_id=%s', session_id)

            # Notifiy registered listeners
            session_mgr.auth_mgr.logout(session_data)

        return dict(result=None)

api.register(session_logout)

#-------------------------------------------------------------------------------


session_mgr = MemcacheSessionManager()
Пример #7
0
        if keys[-1].endswith('.'):
            keys[-1] = keys[-1][:-1]
        dn = super(sudocmd, self).get_dn(*keys, **options)
        try:
            self.backend.get_entry(dn, [''])
        except errors.NotFound:
            try:
                (dn, entry_attrs) = self.backend.find_entry_by_attr(
                    'sudocmd', keys[-1], self.object_class, [''],
                    self.container_dn)
            except errors.NotFound:
                pass
        return dn


api.register(sudocmd)


class sudocmd_add(LDAPCreate):
    __doc__ = _('Create new Sudo Command.')

    msg_summary = _('Added Sudo Command "%(value)s"')


api.register(sudocmd_add)


class sudocmd_del(LDAPDelete):
    __doc__ = _('Delete Sudo Command.')

    msg_summary = _('Deleted Sudo Command "%(value)s"')
Пример #8
0
                self.log.debug("Updated")
            except Exception, e:
                self.log.error("Error caught updating replica: %s", str(e))

        else:
            attrlist_normalized = attrlist.lower().split()
            missing = [
                a for a in values if a.lower() not in attrlist_normalized
            ]

            if missing:
                self.log.debug("%s needs updating (missing: %s)", attribute,
                               ', '.join(missing))
                current = replica.toDict()

                replica.setValue(attribute,
                                 '%s %s' % (attrlist, ' '.join(missing)))

                try:
                    repl.conn.updateEntry(replica.dn, current,
                                          replica.toDict())
                    self.log.debug("Updated %s", attribute)
                except Exception, e:
                    self.log.error("Error caught updating %s: %s", attribute,
                                   str(e))
            else:
                self.log.debug("%s: No update necessary" % attribute)


api.register(update_replica_attribute_lists)
Пример #9
0
        DeprecatedParam('sourcehost_hostgroup?'),
        Str(
            'memberservice_hbacsvc?',
            label=_('Services'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str(
            'memberservice_hbacsvcgroup?',
            label=_('Service Groups'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        external_host_param,
    )


api.register(hbacrule)


class hbacrule_add(LDAPCreate):
    __doc__ = _('Create a new HBAC rule.')

    msg_summary = _('Added HBAC rule "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
                     **options):
        assert isinstance(dn, DN)
        # HBAC rules are enabled by default
        entry_attrs['ipaenabledflag'] = 'TRUE'
        return dn

Пример #10
0
        ]

        for entry in entries:
            # test for mixed configuration
            if any(attr in entry for attr in new_attributes):
                root_logger.critical("Mixed old and new style configuration "
                                     "for plugin %s. Plugin will not work. "
                                     "Skipping plugin migration, please fix it "
                                     "manually",
                                     entry.dn)
                continue
            root_logger.debug("Configuration of plugin %s will be migrated "
                             "to new style", entry.dn)
            try:
                # detect which configuration was used
                arg0 = entry.get('nsslapd-pluginarg0')
                if '=' in arg0:
                    update = self.__objectclass_style(entry)
                else:
                    update = self.__subtree_style(entry)
            except ValueError as e:
                root_logger.error("Unable to migrate configuration of "
                                  "plugin %s (%s)",
                                  entry.dn, e)

            update_list.append(update)

        return False, update_list

api.register(update_uniqueness_plugins_to_new_syntax)
Пример #11
0
    Includes default nfs:None only if no nfs: PAC present in ipakrbauthzdata.
    """

    order = MIDDLE

    def execute(self, **options):
        ldap = self.obj.backend

        try:
            dn = DN('cn=ipaConfig', 'cn=etc', api.env.basedn)
            entry = ldap.get_entry(dn, ['ipakrbauthzdata'])
            pacs = entry.get('ipakrbauthzdata', [])
        except errors.NotFound:
            self.log.warning('Error retrieving: %s' % str(dn))
            return (False, False, [])

        nfs_pac_set = any(pac.startswith('nfs:') for pac in pacs)

        if not nfs_pac_set:
            self.log.debug('Adding nfs:NONE to default PAC types')

            updated_pacs = pacs + [u'nfs:NONE']
            entry['ipakrbauthzdata'] = updated_pacs
            ldap.update_entry(entry)
        else:
            self.log.debug('PAC for nfs is already set, not adding nfs:NONE.')

        return (False, False, [])

api.register(update_pacs)
Пример #12
0
            self.obj.handle_not_found(*keys)

        if 'ipanttrusteddomainsid' in options:
            # Validate SID as the one of trusted domains
            self.obj.validate_trusted_domain_sid(options['ipanttrusteddomainsid'])

        old_base_id = int(old_attrs.get('ipabaseid', [0])[0])
        old_range_size = int(old_attrs.get('ipaidrangesize', [0])[0])
        new_base_id = entry_attrs.get('ipabaseid')
        if new_base_id is not None:
            new_base_id = int(new_base_id)
        new_range_size = entry_attrs.get('ipaidrangesize')
        if new_range_size is not None:
            new_range_size = int(new_range_size)
        self.obj.check_ids_in_modified_range(old_base_id, old_range_size,
                                             new_base_id, new_range_size)

        return dn

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        self.obj.handle_iparangetype(entry_attrs, options)
        return dn

api.register(idrange)
api.register(idrange_add)
api.register(idrange_mod)
api.register(idrange_del)
api.register(idrange_find)
api.register(idrange_show)
Пример #13
0
    object_name_plural = _('automount locations')
    object_class = ['nscontainer']
    default_attributes = ['cn']
    label = _('Automount Locations')
    label_singular = _('Automount Location')

    takes_params = (Str(
        'cn',
        cli_name='location',
        label=_('Location'),
        doc=_('Automount location name.'),
        primary_key=True,
    ), )


api.register(automountlocation)


class automountlocation_add(LDAPCreate):
    __doc__ = _('Create a new automount location.')

    msg_summary = _('Added automount location "%(value)s"')

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        # create auto.master for the new location
        self.api.Command['automountmap_add'](keys[-1], u'auto.master')

        # add additional pre-created maps and keys
        # IMPORTANT: add pre-created maps/keys to DEFAULT_MAPS/DEFAULT_KEYS
        # so that they do not cause conflicts during import operation
Пример #14
0
        ),
        Str('targetgroup?',
            cli_name='targetgroup',
            label=_('Target group'),
            doc=_('Group to apply ACI to'),
            flags=('virtual_attribute',),
        ),
        Flag('selfaci?',
             cli_name='self',
             label=_('Target your own entry (self)'),
             doc=_('Apply ACI to your own entry (self)'),
             flags=('virtual_attribute',),
        ),
    )

api.register(aci)

class aci_add(crud.Create):
    """
    Create new ACI.
    """
    NO_CLI = True
    msg_summary = _('Created ACI "%(value)s"')

    takes_options = (
        _prefix_option,
        Flag('test?',
             doc=_('Test the ACI syntax but don\'t write anything'),
             default=False,
        ),
    )
Пример #15
0
            raise errors.NotFound(reason=_('manager %(manager)s not found') % dict(manager=manager[m]))

        return manager

    def _convert_manager(self, entry_attrs, **options):
        """
        Convert a manager dn into a userid
        """
        if options.get('raw', False):
             return

        if 'manager' in entry_attrs:
            for m in xrange(len(entry_attrs['manager'])):
                entry_attrs['manager'][m] = self.get_primary_key_from_dn(entry_attrs['manager'][m])

api.register(user)


class user_add(LDAPCreate):
    __doc__ = _('Add a new user.')

    msg_summary = _('Added user "%(value)s"')

    has_output_params = LDAPCreate.has_output_params + user_output_params

    takes_options = LDAPCreate.takes_options + (
        Flag('noprivate',
            cli_name='noprivate',
            doc=_('Don\'t create user private group'),
        ),
    )
Пример #16
0
        else:
            keys = self.__find_keys(variables)
        ret = dict(
            result=dict(
                (key, self.env[key]) for key in keys
            ),
            count=len(keys),
            total=len(self.env),
        )
        if len(keys) > 1:
            ret['summary'] = self.msg_summary % ret
        else:
            ret['summary'] = None
        return ret

api.register(env)


class plugins(LocalOrRemote):
    __doc__ = _('Show all loaded plugins.')

    msg_summary = ngettext(
        '%(count)d plugin loaded', '%(count)d plugins loaded', 0
    )

    takes_options = LocalOrRemote.takes_options + (
        Flag('all',
            cli_name='all',
            doc=_('retrieve and print all attributes from the server. Affects command output.'),
            exclude='webui',
            flags=['no_output'],
Пример #17
0
        Returns the entry

        :param principal: The login name or principal of the user
        :param password: the new password
        :param current_password: the existing password, if applicable
        """
        ldap = self.api.Backend.ldap2

        (dn, entry_attrs) = ldap.find_entry_by_attr(
            'krbprincipalname', principal, 'posixaccount', [''],
            DN(api.env.container_user, api.env.basedn)
        )

        if principal == getattr(context, 'principal') and \
            current_password == MAGIC_VALUE:
            # No cheating
            self.log.warn('User attempted to change password using magic value')
            raise errors.ACIError(info=_('Invalid credentials'))

        if current_password == MAGIC_VALUE:
            ldap.modify_password(dn, password)
        else:
            ldap.modify_password(dn, password, current_password)

        return dict(
            result=True,
            value=principal,
        )

api.register(passwd)
Пример #18
0
            except errors.NotFound, e:
                result = None
                error = e
            if result:
                result['result']['trusttype'] = [
                    trust_type_string(result['result']['ipanttrusttype'][0])
                ]
                result['result']['trustdirection'] = [
                    trust_direction_string(
                        result['result']['ipanttrustdirection'][0])
                ]
                break
        if error or not result:
            self.obj.handle_not_found(*keys)

        return result

    def pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        if 'trust_show_type' in options:
            return make_trust_dn(self.env, options['trust_show_type'], dn)
        return dn


api.register(trust)
api.register(trust_add)
api.register(trust_mod)
api.register(trust_del)
api.register(trust_find)
api.register(trust_show)
Пример #19
0
                os.remove(cert_name)
            except:
                pass

        try:
            subject = x509.get_subject(cert)

            serial = x509.get_serial_number(cert)
        except NSPRError, e:
            self.log.error('Unable to decode certificate in entry: %s' % str(e))
            raise errors.CertificateOperationError(
                error=_('Unable to decode certificate in entry: %s') % str(e))

        # To make it look like dogtag return just the base64 data.
        cert = cert.replace('\n','')
        cert = cert.replace('\r','')
        s = cert.find('-----BEGIN CERTIFICATE-----')
        e = cert.find('-----END CERTIFICATE-----')
        s = s + 27
        cert = cert[s:e]

        cmd_result = {}
        cmd_result['serial_number'] = unicode(serial) # convert long to decimal unicode string
        cmd_result['serial_number_hex'] = u'0x%X' % serial
        cmd_result['certificate']   = unicode(cert)
        cmd_result['subject']       = unicode(subject)

        return cmd_result

api.register(ra)
Пример #20
0
            'Should not be deleted.',
        ]

        # First, see if trusts are enabled on the server
        if not self.api.Command.adtrust_is_enabled()['result']:
            self.log.info('AD Trusts are not enabled on this server')
            return False, []

        # Second, make sure the Default Trust View does not exist yet
        try:
            ldap.get_entry(default_trust_view_dn)
        except errors.NotFound:
            pass
        else:
            self.log.info('Default Trust View already present on this server')
            return False, []

        # We have a server with AD trust support without Default Trust View.
        # Create the Default Trust View entry.

        update = {
            'dn': default_trust_view_dn,
            'default': default_trust_view_entry
        }

        return False, [update]


api.register(update_default_range)
api.register(update_default_trust_view)
Пример #21
0
                                          options)

        return dict(result=migrated, failed=failed, enabled=True, compat=True)

    def output_for_cli(self, textui, result, ldapuri, bindpw, **options):
        textui.print_name(self.name)
        if not result['enabled']:
            textui.print_plain(self.migration_disabled_msg)
            return 1
        if not result['compat']:
            textui.print_plain(
                "The compat plug-in is enabled. This can increase the memory requirements during migration. Disable the compat plug-in with \'ipa-compat-manage disable\' or re-run this script with \'--with-compat\' option."
            )
            return 1
        textui.print_plain('Migrated:')
        textui.print_entry1(result['result'],
                            attr_order=self.migrate_order,
                            one_value_per_line=False)
        for ldap_obj_name in self.migrate_order:
            textui.print_plain('Failed %s:' % ldap_obj_name)
            textui.print_entry1(
                result['failed'][ldap_obj_name],
                attr_order=self.migrate_order,
                one_value_per_line=True,
            )
        textui.print_plain('-' * len(self.name))
        textui.print_plain(unicode(self.pwd_migration_msg))


api.register(migrate_ds)
Пример #22
0
        json_dict = dict(
            (a, getattr(self, a)) for a in json_friendly_attributes
        )
        json_dict['primary_key'] = self.primary_key.name

        json_dict['methods'] = [m for m in self.methods]
        return json_dict

    def postprocess_result(self, result):
        try:
            # do not include prefix in result
            del result['aciprefix']
        except KeyError:
            pass

api.register(delegation)


class delegation_add(crud.Create):
    __doc__ = _('Add a new delegation.')

    msg_summary = _('Added delegation "%(value)s"')
    has_output_params = output_params

    def execute(self, aciname, **kw):
        if not 'permissions' in kw:
            kw['permissions'] = (u'write',)
        kw['aciprefix'] = ACI_PREFIX
        result = api.Command['aci_add'](aciname, **kw)['result']
        self.obj.postprocess_result(result)
Пример #23
0
        StrEnum(
            'astaccountencryption?',
            cli_name='default_encryption',
            label=_('encryption Default'),
            doc=_(' '),
            values=(
                u'yes',
                u'no',
            ),
        ),
        #ipaautoastextension
        #ipaautoasttemplate
    )


api.register(astsite)


class astsite_add(LDAPCreate):
    __doc__ = _('Create new Asterisk Site')


api.register(astsite_add)


class astsite_del(LDAPDelete):
    __doc__ = _('Delete Asterisk Site')


api.register(astsite_del)
Пример #24
0
    object_name_plural = _('automount locations')
    object_class = ['nscontainer']
    default_attributes = ['cn']
    label = _('Automount Locations')
    label_singular = _('Automount Location')

    takes_params = (
        Str('cn',
            cli_name='location',
            label=_('Location'),
            doc=_('Automount location name.'),
            primary_key=True,
        ),
    )

api.register(automountlocation)


class automountlocation_add(LDAPCreate):
    __doc__ = _('Create a new automount location.')

    msg_summary = _('Added automount location "%(value)s"')

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        # create auto.master for the new location
        self.api.Command['automountmap_add'](keys[-1], u'auto.master')

        # add additional pre-created maps and keys
        # IMPORTANT: add pre-created maps/keys to DEFAULT_MAPS/DEFAULT_KEYS
        # so that they do not cause conflicts during import operation
Пример #25
0
                remaining_values = entry.get('dnaremainingvalues', [''])[0]
                try:
                    remaining_values = int(remaining_values)
                except ValueError:
                    root_logger.warning(
                        "default_range: could not parse "
                        "remaining values from '%s'", remaining_values)
                    continue
                else:
                    remaining_values_sum += remaining_values

                masters.add(hostname)

            if remaining_values_sum > DEFAULT_ID_RANGE_SIZE:
                msg = [
                    'could not verify default ID range size',
                    'Please use the following command to set correct ID range size',
                    '  $ ipa range-mod %s --range-size=RANGE_SIZE' %
                    id_range_name,
                    'RANGE_SIZE may be computed from --idstart and --idmax options '
                    'used during IPA server installation:',
                    '  RANGE_SIZE = (--idmax) - (--idstart) + 1'
                ]

                root_logger.error("default_range: %s", "\n".join(msg))

        return (False, True, [updates])


api.register(update_default_range)
Пример #26
0
        ),
        Str('add_domain?',
            _domain_name_validator,
            normalizer=_domain_name_normalizer,
            cli_name='add_domain',
            label=_('Add domain'),
        ),
        Str('del_domain?',
            _domain_name_validator,
            normalizer=_domain_name_normalizer,
            cli_name='del_domain',
            label=_('Delete domain'),
        ),
    )

api.register(realmdomains)


class realmdomains_mod(LDAPUpdate):
    __doc__ = _('Modify realm domains.')

    takes_options = LDAPUpdate.takes_options + (
        Flag('force',
            label=_('Force'),
            doc=_('Force adding domain even if not in DNS'),
        ),
    )

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        associateddomain = entry_attrs.get('associateddomain')
Пример #27
0
                self.api.env.container_privilege,
                self.api.env.basedn)

        ldap = self.api.Backend.ldap2
        try:
            ldap.get_entry(passsync_privilege_dn, [''])
        except errors.NotFound:
            root_logger.debug("PassSync privilege not found, this is a new update")
            sysupgrade.set_upgrade_state('winsync', 'passsync_privilege_updated', False)
        else:
            root_logger.debug("PassSync privilege found, skip updating PassSync")
            sysupgrade.set_upgrade_state('winsync', 'passsync_privilege_updated', True)

        return False, []

api.register(update_passync_privilege_check)

class update_passync_privilege_update(Updater):
    """
        Add PassSync user as a member of PassSync privilege, if it exists
    """

    def execute(self, **options):
        update_done = sysupgrade.get_upgrade_state('winsync', 'passsync_privilege_updated')
        if update_done:
            root_logger.debug("PassSync privilege update not needed")
            return False, []

        root_logger.debug("Add PassSync user as a member of PassSync privilege")
        ldap = self.api.Backend.ldap2
        passsync_dn = DN(('uid','passsync'), ('cn', 'sysaccounts'), ('cn', 'etc'),
Пример #28
0
    def validate_ipakrbauthzdata(self, entry):
        new_value = entry.get('ipakrbauthzdata', [])

        if not new_value:
            return

        if not isinstance(new_value, (list, tuple)):
            new_value = set([new_value])
        else:
            new_value = set(new_value)

        if u'NONE' in new_value and len(new_value) > 1:
            raise errors.ValidationError(name='ipakrbauthzdata',
                error=_('NONE value cannot be combined with other PAC types'))

api.register(service)


class service_add(LDAPCreate):
    __doc__ = _('Add a new IPA new service.')

    msg_summary = _('Added service "%(value)s"')
    member_attributes = ['managedby']
    has_output_params = LDAPCreate.has_output_params + output_params
    takes_options = LDAPCreate.takes_options + (
        Flag('force',
            label=_('Force'),
            doc=_('force principal name even if not in DNS'),
        ),
    )
Пример #29
0
        )
        json_dict = dict(
            (a, getattr(self, a)) for a in json_friendly_attributes)
        json_dict['primary_key'] = self.primary_key.name
        json_dict['methods'] = [m for m in self.methods]
        return json_dict

    def postprocess_result(self, result):
        try:
            # do not include prefix in result
            del result['aciprefix']
        except KeyError:
            pass


api.register(selfservice)


class selfservice_add(crud.Create):
    __doc__ = _('Add a new self-service permission.')

    msg_summary = _('Added selfservice "%(value)s"')
    has_output_params = output_params

    def execute(self, aciname, **kw):
        if not 'permissions' in kw:
            kw['permissions'] = (u'write', )
        kw['selfaci'] = True
        kw['aciprefix'] = ACI_PREFIX
        result = api.Command['aci_add'](aciname, **kw)['result']
        self.obj.postprocess_result(result)
Пример #30
0
                raise errors.NotFound(reason=_('HBAC rule %(rule)s not found') % dict(rule=seealso))

        return seealso

    def _convert_seealso(self, ldap, entry_attrs, **options):
        """
        Convert an HBAC rule dn into a name
        """
        if options.get('raw', False):
            return

        if 'seealso' in entry_attrs:
            (hbac_dn, hbac_attrs) = ldap.get_entry(entry_attrs['seealso'][0], ['cn'])
            entry_attrs['seealso'] = hbac_attrs['cn'][0]

api.register(selinuxusermap)


class selinuxusermap_add(LDAPCreate):
    __doc__ = _('Create a new SELinux User Map.')

    msg_summary = _('Added SELinux User Map "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        # rules are enabled by default
        entry_attrs['ipaenabledflag'] = 'TRUE'
        validate_selinuxuser_inlist(ldap, entry_attrs['ipaselinuxuser'])

        # hbacrule is not allowed when usercat or hostcat is set
        is_to_be_set = lambda x: x in entry_attrs and entry_attrs[x] != None
Пример #31
0
import base64

class update_upload_cacrt(PostUpdate):
    """
    Upload public CA certificate to LDAP
    """
    order=MIDDLE

    def execute(self, **options):
        ldap = self.obj.backend
        (cdn, ipa_config) = ldap.get_ipa_config()
        subject_base = ipa_config.get('ipacertificatesubjectbase', [None])[0]
        dirname = config_dirname(realm_to_serverid(api.env.realm))
        certdb = certs.CertDB(api.env.realm, nssdir=dirname, subject_base=subject_base)

        dercert = certdb.get_cert_from_db(certdb.cacert_name, pem=False)

        updates = {}
        dn = DN(('cn', 'CACert'), ('cn', 'ipa'), ('cn','etc'), api.env.basedn)

        cacrt_entry = ['objectclass:nsContainer',
                       'objectclass:pkiCA',
                       'cn:CAcert',
                       'cACertificate;binary:%s' % dercert,
                      ]
        updates[dn] = {'dn': dn, 'default': cacrt_entry}

        return (False, True, [updates])

api.register(update_upload_cacrt)
Пример #32
0
            minvalue=1,
        ),
        Int('krbmaxrenewableage?',
            cli_name='maxrenew',
            label=_('Max renew'),
            doc=_('Maximum renewable age (seconds)'),
            minvalue=1,
        ),
    )

    def get_dn(self, *keys, **kwargs):
        if keys[-1] is not None:
            return self.api.Object.user.get_dn(*keys, **kwargs)
        return self.container_dn

api.register(krbtpolicy)


class krbtpolicy_mod(LDAPUpdate):
    __doc__ = _('Modify Kerberos ticket policy.')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        # disable all flag
        #  ticket policies are attached to objects with unrelated attributes
        if options.get('all'):
            options['all'] = False
        return dn

api.register(krbtpolicy_mod)
Пример #33
0
        """
        super(DSRestart, self).start(wait=False)

    def create_instance(self):
        self.step("stopping directory server", self.stop)
        self.step("starting directory server", self.start)
        self.start_creation(start_message="Restarting Directory server "
                            "to apply updates", show_service_name=False)

class update(Object):
    """
    Generic object used to register all updates into a single namespace.
    """
    backend_name = 'ldap2'

api.register(update)

class PreUpdate(Updater):
    """
    Base class for updates that run prior to file processing.
    """
    updatetype = PRE_UPDATE
    order = MIDDLE

    def __init__(self):
        super(PreUpdate, self).__init__()

class PostUpdate(Updater):
    """
    Base class for updates that run after file processing.
    """
Пример #34
0
    def default_realm(self):
        """
        Return the realm from the default credential cache.

        This will return something like 'EXAMPLE.COM'.  If no credential cache
        exists for the invoking user, None is returned.

        This cannot return anything meaningful if used in the server as a
        request is processed.
        """
        return krbV.default_context().default_realm.decode(ENCODING)

    def get_principal(self, ccname):
        """
        Return the principal from credential cache file at ``ccname``.

        This will return something like '*****@*****.**'.
        """
        return self.__get_principal(ccname).name.decode(ENCODING)

    def get_realm(self, ccname):
        """
        Return the realm from credential cache file at ``ccname``.

        This will return something like 'EXAMPLE.COM'.
        """
        return self.__get_principal(ccname).realm.decode(ENCODING)


api.register(krb)
Пример #35
0
            # If no principal name is set yet we need to try to add
            # one.
            if 'krbprincipalname' not in attrs_list:
                service = "host/%s@%s" % (hostname, api.env.realm)
                api.Command['host_mod'](hostname, krbprincipalname=service)
                self.log.info('No principal set, setting to %s', service)

            # It exists, can we write the password attributes?
            allowed = ldap.can_write(dn, 'krblastpwdchange')
            if not allowed:
                raise errors.ACIError(info=_("Insufficient 'write' privilege "
                    "to the 'krbLastPwdChange' attribute of entry '%s'.") % dn)

            # Reload the attrs_list and dn so that we return update values
            kw = {'fqdn': hostname, 'all': True}
            attrs_list = api.Command['host_show'](**kw)['result']
            dn = attrs_list['dn']

        except errors.NotFound:
            attrs_list = api.Command['host_add'](hostname,
                                                 force=True)['result']
            dn = attrs_list['dn']

        config = api.Command['config_show']()['result']
        attrs_list['ipacertificatesubjectbase'] =\
            config['ipacertificatesubjectbase']

        return (dn, attrs_list)

api.register(join)
Пример #36
0
                textui.print_plain("Hostname %s" % (fqdn))
                details = result['result']['details'][fqdn].items()
                details.sort(key=lambda x: x[0])
                textui.print_keyval(details)
        else:
            # print list of hostnames
            textui.print_plain(" ".join(fqdns))


if __name__ == '__main__':
    from ipalib import create_api
    api = create_api()
else:
    from ipalib import api

api.register(aii)
api.register(aii_find)

if __name__ == '__main__':
    api.finalize()

    from ipalib import cli
    textui = cli.textui()

    args = [unicode('somehost'), unicode('somesubdomain.somedomain')]
    options = {
        'install': True,
    }

    result = api.Command.aii(*args, **options)
    api.Command.aii.output_for_cli(textui, result, *args, **options)
Пример #37
0
            replica[attribute] = [template % " ".join(values)]

            try:
                repl.conn.update_entry(replica)
                self.log.debug("Updated")
            except Exception as e:
                self.log.error("Error caught updating replica: %s", str(e))

        else:
            attrlist_normalized = attrlist.lower().split()
            missing = [a for a in values
                if a.lower() not in attrlist_normalized]

            if missing:
                self.log.debug("%s needs updating (missing: %s)", attribute,
                    ', '.join(missing))

                replica[attribute] = [
                    '%s %s' % (attrlist, ' '.join(missing))]

                try:
                    repl.conn.update_entry(replica)
                    self.log.debug("Updated %s", attribute)
                except Exception as e:
                    self.log.error("Error caught updating %s: %s",
                        attribute, str(e))
            else:
                self.log.debug("%s: No update necessary" % attribute)

api.register(update_replica_attribute_lists)
Пример #38
0
        ),
        StrEnum(
            'ipakrbauthzdata*',
            cli_name='pac_type',
            label=_('Default PAC types'),
            doc=_('Default types of PAC supported for services'),
            values=(u'MS-PAC', u'PAD'),
            csv=True,
        ),
    )

    def get_dn(self, *keys, **kwargs):
        return DN(('cn', 'ipaconfig'), ('cn', 'etc'))


api.register(config)


class config_mod(LDAPUpdate):
    __doc__ = _('Modify configuration options.')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
                     **options):
        assert isinstance(dn, DN)
        if 'ipadefaultprimarygroup' in entry_attrs:
            group = entry_attrs['ipadefaultprimarygroup']
            try:
                api.Object['group'].get_dn_if_exists(group)
            except errors.NotFound:
                raise errors.NotFound(message=_("The group doesn't exist"))
        kw = {}
Пример #39
0
            raise errors.NotFound(reason=_('manager %(manager)s not found') % dict(manager=manager[m]))

        return manager

    def _convert_manager(self, entry_attrs, **options):
        """
        Convert a manager dn into a userid
        """
        if options.get('raw', False):
             return

        if 'manager' in entry_attrs:
            for m in xrange(len(entry_attrs['manager'])):
                entry_attrs['manager'][m] = self.get_primary_key_from_dn(entry_attrs['manager'][m])

api.register(user)


class user_add(LDAPCreate):
    __doc__ = _('Add a new user.')

    msg_summary = _('Added user "%(value)s"')

    has_output_params = LDAPCreate.has_output_params + user_output_params

    takes_options = LDAPCreate.takes_options + (
        Flag('noprivate',
            cli_name='noprivate',
            doc=_('Don\'t create user private group'),
        ),
    )
Пример #40
0
        if not new_value:
            return

        if not isinstance(new_value, (list, tuple)):
            new_value = set([new_value])
        else:
            new_value = set(new_value)

        if u'NONE' in new_value and len(new_value) > 1:
            raise errors.ValidationError(
                name='ipakrbauthzdata',
                error=_('NONE value cannot be combined with other PAC types'))


api.register(service)


class service_add(LDAPCreate):
    __doc__ = _('Add a new IPA new service.')

    msg_summary = _('Added service "%(value)s"')
    member_attributes = ['managedby']
    has_output_params = LDAPCreate.has_output_params + output_params
    takes_options = LDAPCreate.takes_options + (Flag(
        'force',
        label=_('Force'),
        doc=_('force principal name even if not in DNS'),
    ), )

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
Пример #41
0
            ldap.get_entry(passsync_privilege_dn, [''])
        except errors.NotFound:
            root_logger.debug(
                "PassSync privilege not found, this is a new update")
            sysupgrade.set_upgrade_state('winsync',
                                         'passsync_privilege_updated', False)
        else:
            root_logger.debug(
                "PassSync privilege found, skip updating PassSync")
            sysupgrade.set_upgrade_state('winsync',
                                         'passsync_privilege_updated', True)

        return False, []


api.register(update_passync_privilege_check)


class update_passync_privilege_update(Updater):
    """
        Add PassSync user as a member of PassSync privilege, if it exists
    """
    def execute(self, **options):
        update_done = sysupgrade.get_upgrade_state(
            'winsync', 'passsync_privilege_updated')
        if update_done:
            root_logger.debug("PassSync privilege update not needed")
            return False, []

        root_logger.debug(
            "Add PassSync user as a member of PassSync privilege")
Пример #42
0
        """
        ng_container = DN(api.env.container_netgroup, api.env.basedn)
        for member in list(entry_attrs.get('memberofindirect', [])):
            memberdn = DN(member)
            if not memberdn.endswith(ng_container):
                continue

            filter = ldap.make_filter({'objectclass': 'mepmanagedentry'})
            try:
                ldap.get_entries(memberdn, ldap.SCOPE_BASE, filter, [''])
            except errors.NotFound:
                pass
            else:
                entry_attrs['memberofindirect'].remove(member)

api.register(host)


class host_add(LDAPCreate):
    __doc__ = _('Add a new host.')

    has_output_params = LDAPCreate.has_output_params + host_output_params
    msg_summary = _('Added host "%(value)s"')
    member_attributes = ['managedby']
    takes_options = LDAPCreate.takes_options + (
        Flag('force',
            label=_('Force'),
            doc=_('force host name even if not in DNS'),
        ),
        Flag('no_reverse',
            doc=_('skip reverse DNS detection'),
Пример #43
0
        # Success? Then add it to the service entry.
        if 'certificate' in result:
            if not principal.startswith('host/'):
                skw = {"usercertificate": str(result.get('certificate'))}
                api.Command['service_mod'](principal, **skw)
            else:
                hostname = get_host_from_principal(principal)
                skw = {"usercertificate": str(result.get('certificate'))}
                api.Command['host_mod'](hostname, **skw)

        return dict(
            result=result
        )

api.register(cert_request)


class cert_status(VirtualCommand):
    __doc__ = _('Check the status of a certificate signing request.')

    takes_args = (
        Str('request_id',
            label=_('Request id'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
    )
    has_output_params = (
        Str('cert_request_status',
            label=_('Request status'),
        ),
Пример #44
0

#-------------------------------------------------------------------------------

from ipalib.request import context


class session_logout(Command):
    '''
    RPC command used to log the current user out of their session.
    '''
    def execute(self, *args, **options):
        session_data = getattr(context, 'session_data', None)
        if session_data is None:
            self.debug('session logout command: no session_data found')
        else:
            session_id = session_data.get('session_id')
            self.debug('session logout command: session_id=%s', session_id)

            # Notifiy registered listeners
            session_mgr.auth_mgr.logout(session_data)

        return dict(result=None)


api.register(session_logout)

#-------------------------------------------------------------------------------

session_mgr = MemcacheSessionManager()
Пример #45
0
class update_pacs(Updater):
    """
    Includes default nfs:None only if no nfs: PAC present in ipakrbauthzdata.
    """
    def execute(self, **options):
        ldap = self.api.Backend.ldap2

        try:
            dn = DN('cn=ipaConfig', 'cn=etc', self.api.env.basedn)
            entry = ldap.get_entry(dn, ['ipakrbauthzdata'])
            pacs = entry.get('ipakrbauthzdata', [])
        except errors.NotFound:
            self.log.warning('Error retrieving: %s' % str(dn))
            return False, []

        nfs_pac_set = any(pac.startswith('nfs:') for pac in pacs)

        if not nfs_pac_set:
            self.log.debug('Adding nfs:NONE to default PAC types')

            updated_pacs = pacs + [u'nfs:NONE']
            entry['ipakrbauthzdata'] = updated_pacs
            ldap.update_entry(entry)
        else:
            self.log.debug('PAC for nfs is already set, not adding nfs:NONE.')

        return False, []


api.register(update_pacs)
Пример #46
0
            cli_name="targetgroup",
            label=_("Target group"),
            doc=_("Group to apply ACI to"),
            flags=("virtual_attribute",),
        ),
        Flag(
            "selfaci?",
            cli_name="self",
            label=_("Target your own entry (self)"),
            doc=_("Apply ACI to your own entry (self)"),
            flags=("virtual_attribute",),
        ),
    )


api.register(aci)


class aci_add(crud.Create):
    """
    Create new ACI.
    """

    NO_CLI = True
    msg_summary = _('Created ACI "%(value)s"')

    takes_options = (
        _prefix_option,
        Flag("test?", doc=_("Test the ACI syntax but don't write anything"), default=False),
    )
Пример #47
0
        hgdn = DN(dn)
        for member in list(entry_attrs.get('memberof', [])):
            ngdn = DN(member)
            if ngdn['cn'] != hgdn['cn']:
                continue

            filter = ldap.make_filter({'objectclass': 'mepmanagedentry'})
            try:
                ldap.find_entries(filter=filter, base_dn=ngdn,
                                  scope=ldap.SCOPE_BASE, attrs_list=[''])
            except errors.NotFound:
                pass
            else:
                entry_attrs['memberof'].remove(member)

api.register(hostgroup)


class hostgroup_add(LDAPCreate):
    __doc__ = _('Add a new hostgroup.')

    msg_summary = _('Added hostgroup "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        try:
            # check duplicity with hostgroups first to provide proper error
            api.Object['hostgroup'].get_dn_if_exists(keys[-1])
            self.obj.handle_duplicate_entry(*keys)
        except errors.NotFound:
            pass
Пример #48
0
            dict(attr='description', value='Default Trust View for AD users. '
                 'Should not be deleted.'),
        ]

        # First, see if trusts are enabled on the server
        if not self.api.Command.adtrust_is_enabled()['result']:
            self.log.info('AD Trusts are not enabled on this server')
            return False, []

        # Second, make sure the Default Trust View does not exist yet
        try:
            ldap.get_entry(default_trust_view_dn)
        except errors.NotFound:
            pass
        else:
            self.log.info('Default Trust View already present on this server')
            return False, []

        # We have a server with AD trust support without Default Trust View.
        # Create the Default Trust View entry.

        update = {
            'dn': default_trust_view_dn,
            'default': default_trust_view_entry
        }

        return False, [update]

api.register(update_default_range)
api.register(update_default_trust_view)
Пример #49
0
        if len(update_list) > 0:
            restart = True
            update_list.sort(reverse=True, key=lambda x: x['dn'])

        return (restart, update_list)

class update_managed_post_first(Updater, GenerateUpdateMixin):
    """
    Update managed entries
    """

    def execute(self, **options):
        # Never need to restart with the pre-update changes
        (ignore, update_list) = self.generate_update(False)

        return False, update_list

api.register(update_managed_post_first)

class update_managed_post(Updater, GenerateUpdateMixin):
    """
    Update managed entries
    """

    def execute(self, **options):
        (restart, update_list) = self.generate_update(True)

        return restart, update_list

api.register(update_managed_post)
Пример #50
0
                update['idnsallowtransfer'] = u'none;'

            old_policy = util.get_dns_forward_zone_update_policy(
                self.api.env.realm, ('A', 'AAAA'))
            if zone.get('idnsupdatepolicy', [''])[0] == old_policy:
                update['idnsupdatepolicy'] = util.get_dns_forward_zone_update_policy(\
                        self.api.env.realm)

            if update:
                # FIXME: https://fedorahosted.org/freeipa/ticket/4722
                self.api.Command.dnszone_mod(zone[u'idnsname'][0].make_absolute(),
                                        **update)

        return False, []

api.register(update_dnszones)


class update_dns_limits(Updater):
    """
    bind-dyndb-ldap persistent search queries LDAP for all DNS records.
    The LDAP connection must have no size or time limits to work
    properly. This plugin updates limits of the existing DNS service
    principal to match there requirements.
    """
    limit_attributes = ['nsTimeLimit', 'nsSizeLimit', 'nsIdleTimeout', 'nsLookThroughLimit']
    limit_value = '-1'

    def execute(self, **options):
        ldap = self.api.Backend.ldap2
Пример #51
0
            label=_('User category'),
            doc=_('User category the rule applies to'),
            values=(u'all', ),
        ),
        StrEnum(
            'hostcategory?',
            cli_name='hostcat',
            label=_('Host category'),
            doc=_('Host category the rule applies to'),
            values=(u'all', ),
        ),
        external_host_param,
    )


api.register(netgroup)


class netgroup_add(LDAPCreate):
    __doc__ = _('Add a new netgroup.')

    has_output_params = LDAPCreate.has_output_params + output_params
    msg_summary = _('Added netgroup "%(value)s"')

    msg_collision = _(u'hostgroup with name "%s" already exists. ' \
                      u'Hostgroups and netgroups share a common namespace')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
                     **options):
        assert isinstance(dn, DN)
        entry_attrs.setdefault('nisdomainname', self.api.env.domain)
Пример #52
0
            label=_('Default SELinux user'),
            doc=_('Default SELinux user when no match is found in SELinux map rule'),
        ),
        StrEnum('ipakrbauthzdata*',
            cli_name='pac_type',
            label=_('Default PAC types'),
            doc=_('Default types of PAC supported for services'),
            values=(u'MS-PAC', u'PAD'),
            csv=True,
        ),
    )

    def get_dn(self, *keys, **kwargs):
        return DN(('cn', 'ipaconfig'), ('cn', 'etc'))

api.register(config)


class config_mod(LDAPUpdate):
    __doc__ = _('Modify configuration options.')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        if 'ipadefaultprimarygroup' in entry_attrs:
            group=entry_attrs['ipadefaultprimarygroup']
            try:
                api.Object['group'].get_dn_if_exists(group)
            except errors.NotFound:
                raise errors.NotFound(message=_("The group doesn't exist"))
        kw = {}
        if 'ipausersearchfields' in entry_attrs:
Пример #53
0
                for entry in res:
                    updates.update(entry)
                ld.update_from_dict(updates)
            elif res:
                result.extend(res)

        self.destroy_context()

        return result

    def run(self, method, **kw):
        """
        Execute the update plugin.
        """
        return self.Updater[method](**kw)  #pylint: disable=E1101

    def restart(self, dm_password, live_run):
        dsrestart = DSRestart()
        socket_name = '/var/run/slapd-%s.socket' % \
            api.env.realm.replace('.','-')
        if live_run:
            self.destroy_context()
            dsrestart.create_instance()
            wait_for_open_socket(socket_name)
            self.create_context(dm_password)
        else:
            self.log.warn("Test mode, skipping restart")


api.register(updateclient)
Пример #54
0
        return seealso

    def _convert_seealso(self, ldap, entry_attrs, **options):
        """
        Convert an HBAC rule dn into a name
        """
        if options.get('raw', False):
            return

        if 'seealso' in entry_attrs:
            (hbac_dn, hbac_attrs) = ldap.get_entry(entry_attrs['seealso'][0],
                                                   ['cn'])
            entry_attrs['seealso'] = hbac_attrs['cn'][0]


api.register(selinuxusermap)


class selinuxusermap_add(LDAPCreate):
    __doc__ = _('Create a new SELinux User Map.')

    msg_summary = _('Added SELinux User Map "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
                     **options):
        assert isinstance(dn, DN)
        # rules are enabled by default
        entry_attrs['ipaenabledflag'] = 'TRUE'
        validate_selinuxuser_inlist(ldap, entry_attrs['ipaselinuxuser'])

        # hbacrule is not allowed when usercat or hostcat is set
Пример #55
0
    def check_order_uniqueness(self, *keys, **options):
        if 'sudoorder' in options:
            entries = self.methods.find(
                sudoorder=options['sudoorder']
            )['result']
            if len(entries) > 0:
                rule_name = entries[0]['cn'][0]
                raise errors.ValidationError(
                    name='order',
                    error=self.order_not_unique_msg % {
                        'order': options['sudoorder'],
                        'rule': rule_name,
                    }
                )

api.register(sudorule)


class sudorule_add(LDAPCreate):
    __doc__ = _('Create new Sudo Rule.')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        self.obj.check_order_uniqueness(*keys, **options)
        # Sudo Rules are enabled by default
        entry_attrs['ipaenabledflag'] = 'TRUE'
        return dn

    msg_summary = _('Added Sudo Rule "%(value)s"')

api.register(sudorule_add)
Пример #56
0
            # If no principal name is set yet we need to try to add
            # one.
            if 'krbprincipalname' not in attrs_list:
                service = "host/%s@%s" % (hostname, api.env.realm)
                api.Command['host_mod'](hostname, krbprincipalname=service)

            # It exists, can we write the password attributes?
            allowed = ldap.can_write(dn, 'krblastpwdchange')
            if not allowed:
                raise errors.ACIError(info=_(
                    "Insufficient 'write' privilege to the 'krbLastPwdChange' attribute of entry '%s'."
                ) % dn)

            kw = {'fqdn': hostname, 'all': True}
            attrs_list = api.Command['host_show'](**kw)['result']
            dn = attrs_list['dn']
        except errors.NotFound:
            attrs_list = api.Command['host_add'](hostname,
                                                 force=True)['result']
            dn = attrs_list['dn']

        config = api.Command['config_show']()['result']
        attrs_list['ipacertificatesubjectbase'] = config[
            'ipacertificatesubjectbase']

        return (dn, attrs_list)


api.register(join)