Beispiel #1
0
def use_api_as_principal(principal, keytab):
    with ipautil.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)
            # Finalize API when TGT obtained using host keytab exists
            if not api.isdone("finalize"):
                api.finalize()

            # Now we have a TGT, connect to IPA
            try:
                if api.Backend.rpcclient.isconnected():
                    api.Backend.rpcclient.disconnect()
                api.Backend.rpcclient.connect()

                yield
            except gssapi.exceptions.GSSError as e:
                raise Exception(
                    "Unable to bind to IPA server. Error initializing "
                    "principal %s in %s: %s" % (principal, keytab, str(e)))
        finally:
            if api.Backend.rpcclient.isconnected():
                api.Backend.rpcclient.disconnect()
            setattr(context, "principal", old_principal)
Beispiel #2
0
    def run(self):
        kwargs = {}

        transformed_cls = self._transform(self.configurable_class)
        for owner_cls, name in transformed_cls.knobs():
            value = getattr(self.options, name, None)
            if value is not None:
                kwargs[name] = value

        if (issubclass(self.configurable_class, common.Interactive) and
                not self.options.unattended):
            kwargs['interactive'] = True

        try:
            cfgr = transformed_cls(**kwargs)
        except core.KnobValueError as e:
            knob_cls = getattr(transformed_cls, e.name)
            try:
                index = self.positional_arguments.index(e.name)
            except IndexError:
                cli_name = knob_cls.cli_name or e.name.replace('_', '-')
                desc = "option --{0}".format(cli_name)
            else:
                desc = "argument {0}".format(index + 1)
            self.option_parser.error("{0}: {1}".format(desc, e))
        except RuntimeError as e:
            self.option_parser.error(str(e))

        signal.signal(signal.SIGTERM, self.__signal_handler)

        # Use private ccache
        with private_ccache():
            super(ConfigureTool, self).run()

            cfgr.run()
Beispiel #3
0
def change_principal(user, password, client=None, path=None,
                     canonicalize=False, enterprise=False):

    if path:
        ccache_name = path
    else:
        ccache_name = os.path.join('/tmp', str(uuid.uuid4()))

    if client is None:
        client = api


    client.Backend.rpcclient.disconnect()

    try:
        with private_ccache(ccache_name):
            kinit_password(user, password, ccache_name,
                           canonicalize=canonicalize, enterprise=enterprise)
            client.Backend.rpcclient.connect()

            try:
                yield
            finally:
                client.Backend.rpcclient.disconnect()
    finally:
        client.Backend.rpcclient.connect()
Beispiel #4
0
def install(api, replica_config, options, custodia):
    if replica_config is None:
        if not options.setup_kra:
            return
        realm_name = api.env.realm
        dm_password = options.dm_password
        host_name = api.env.host
        subject_base = dsinstance.DsInstance().find_subject_base()

        pkcs12_info = None
        master_host = None
        promote = False
    else:
        if not replica_config.setup_kra:
            return
        krafile = os.path.join(replica_config.dir, 'kracert.p12')
        with ipautil.private_ccache():
            ccache = os.environ['KRB5CCNAME']
            kinit_keytab(
                'host/{env.host}@{env.realm}'.format(env=api.env),
                paths.KRB5_KEYTAB,
                ccache)
            custodia.get_kra_keys(
                krafile,
                replica_config.dirman_password)

        realm_name = replica_config.realm_name
        dm_password = replica_config.dirman_password
        host_name = replica_config.host_name
        subject_base = replica_config.subject_base

        pkcs12_info = (krafile,)
        master_host = replica_config.kra_host_name
        promote = True

    ca_subject = ca.lookup_ca_subject(api, subject_base)

    kra = krainstance.KRAInstance(realm_name)
    kra.configure_instance(
        realm_name, host_name, dm_password, dm_password,
        subject_base=subject_base,
        ca_subject=ca_subject,
        pkcs12_info=pkcs12_info,
        master_host=master_host,
        promote=promote,
        pki_config_override=options.pki_config_override,
    )

    _service.print_msg("Restarting the directory server")
    ds = dsinstance.DsInstance()
    ds.restart()
    kra.enable_client_auth_to_db()

    # Restart apache for new proxy config file
    services.knownservices.httpd.restart(capture_output=True)
    # Restarted named to restore bind-dyndb-ldap operation, see
    # https://pagure.io/freeipa/issue/5813
    named = services.knownservices.named  # alias for current named
    if named.is_running():
        named.restart(capture_output=True)
Beispiel #5
0
def install(api, replica_config, options):
    if replica_config is None:
        if not options.setup_kra:
            return
        realm_name = api.env.realm
        dm_password = options.dm_password
        host_name = api.env.host
        subject_base = dsinstance.DsInstance().find_subject_base()

        pkcs12_info = None
        master_host = None
        promote = False
    else:
        if not replica_config.setup_kra:
            return
        krafile = os.path.join(replica_config.dir, 'kracert.p12')
        if options.promote:
            with ipautil.private_ccache():
                ccache = os.environ['KRB5CCNAME']
                kinit_keytab('host/{env.host}@{env.realm}'.format(env=api.env),
                             paths.KRB5_KEYTAB, ccache)
                custodia = custodiainstance.CustodiaInstance(
                    replica_config.host_name, replica_config.realm_name)
                custodia.get_kra_keys(replica_config.kra_host_name, krafile,
                                      replica_config.dirman_password)
        else:
            cafile = os.path.join(replica_config.dir, 'cacert.p12')
            if not os.path.isfile(cafile):
                raise RuntimeError(
                    "Unable to clone KRA."
                    "  cacert.p12 file not found in replica file")
            shutil.copy(cafile, krafile)

        realm_name = replica_config.realm_name
        dm_password = replica_config.dirman_password
        host_name = replica_config.host_name
        subject_base = replica_config.subject_base

        pkcs12_info = (krafile, )
        master_host = replica_config.kra_host_name
        promote = options.promote

    kra = krainstance.KRAInstance(realm_name)
    kra.configure_instance(realm_name,
                           host_name,
                           dm_password,
                           dm_password,
                           subject_base=subject_base,
                           pkcs12_info=pkcs12_info,
                           master_host=master_host,
                           promote=promote)

    _service.print_msg("Restarting the directory server")
    ds = dsinstance.DsInstance()
    ds.restart()
    kra.enable_client_auth_to_db()

    # Restart apache for new proxy config file
    services.knownservices.httpd.restart(capture_output=True)
Beispiel #6
0
def install(api, replica_config, options, custodia):
    if replica_config is None:
        if not options.setup_kra:
            return
        realm_name = api.env.realm
        dm_password = options.dm_password
        host_name = api.env.host
        subject_base = dsinstance.DsInstance().find_subject_base()

        pkcs12_info = None
        master_host = None
        promote = False
    else:
        if not replica_config.setup_kra:
            return
        krafile = os.path.join(replica_config.dir, 'kracert.p12')
        with ipautil.private_ccache():
            ccache = os.environ['KRB5CCNAME']
            kinit_keytab(
                'host/{env.host}@{env.realm}'.format(env=api.env),
                paths.KRB5_KEYTAB,
                ccache)
            custodia.get_kra_keys(
                krafile,
                replica_config.dirman_password)

        realm_name = replica_config.realm_name
        dm_password = replica_config.dirman_password
        host_name = replica_config.host_name
        subject_base = replica_config.subject_base

        pkcs12_info = (krafile,)
        master_host = replica_config.kra_host_name
        promote = True

    kra = krainstance.KRAInstance(realm_name)
    kra.configure_instance(
        realm_name, host_name, dm_password, dm_password,
        subject_base=subject_base,
        pkcs12_info=pkcs12_info,
        master_host=master_host,
        promote=promote,
        pki_config_override=options.pki_config_override,
    )

    _service.print_msg("Restarting the directory server")
    ds = dsinstance.DsInstance()
    ds.restart()
    kra.enable_client_auth_to_db()

    # Restart apache for new proxy config file
    services.knownservices.httpd.restart(capture_output=True)
    # Restarted named-pkcs11 to restore bind-dyndb-ldap operation, see
    # https://pagure.io/freeipa/issue/5813
    named = services.knownservices.named  # alias for named-pkcs11
    if named.is_running():
        named.restart(capture_output=True)
Beispiel #7
0
def change_principal(principal,
                     password=None,
                     client=None,
                     path=None,
                     canonicalize=False,
                     enterprise=False,
                     keytab=None):
    """Temporarily change the kerberos principal

    Most of the test cases run with the admin ipa user which is granted
    all access and exceptions from rules on some occasions.

    When the test needs to test for an application of some kind
    of a restriction it needs to authenticate as a different principal
    with required set of rights to the operation.

    The context manager changes the principal identity in two ways:

    * using password
    * using keytab

    If the context manager is to be used with a keytab, the keytab
    option must be its absolute path.

    The context manager can be used to authenticate with enterprise
    principals and aliases when given respective options.
    """

    if path:
        ccache_name = path
    else:
        ccache_name = os.path.join('/tmp', str(uuid.uuid4()))

    if client is None:
        client = api

    client.Backend.rpcclient.disconnect()

    try:
        with private_ccache(ccache_name):
            if keytab:
                kinit_keytab(principal, keytab, ccache_name)
            else:
                kinit_password(principal,
                               password,
                               ccache_name,
                               canonicalize=canonicalize,
                               enterprise=enterprise)
            client.Backend.rpcclient.connect()

            try:
                yield
            finally:
                client.Backend.rpcclient.disconnect()
    finally:
        client.Backend.rpcclient.connect()
Beispiel #8
0
    def run(self):
        cfgr = self.init_configurator()

        signal.signal(signal.SIGTERM, self.__signal_handler)

        if self.use_private_ccache:
            with private_ccache():
                super(ConfigureTool, self).run()
                return cfgr.run()
        else:
            super(ConfigureTool, self).run()
            return cfgr.run()
Beispiel #9
0
    def run(self):
        cfgr = self.init_configurator()

        signal.signal(signal.SIGTERM, self.__signal_handler)

        if self.use_private_ccache:
            with private_ccache():
                super(ConfigureTool, self).run()
                return cfgr.run()
        else:
            super(ConfigureTool, self).run()
            return cfgr.run()
Beispiel #10
0
def change_principal(principal, password=None, client=None, path=None,
                     canonicalize=False, enterprise=False, keytab=None):
    """Temporarily change the kerberos principal

    Most of the test cases run with the admin ipa user which is granted
    all access and exceptions from rules on some occasions.

    When the test needs to test for an application of some kind
    of a restriction it needs to authenticate as a different principal
    with required set of rights to the operation.

    The context manager changes the principal identity in two ways:

    * using password
    * using keytab

    If the context manager is to be used with a keytab, the keytab
    option must be its absolute path.

    The context manager can be used to authenticate with enterprise
    principals and aliases when given respective options.
    """

    if path:
        ccache_name = path
    else:
        ccache_name = os.path.join('/tmp', str(uuid.uuid4()))

    if client is None:
        client = api


    client.Backend.rpcclient.disconnect()

    try:
        with private_ccache(ccache_name):
            if keytab:
                kinit_keytab(principal, keytab, ccache_name)
            else:
                kinit_password(principal, password, ccache_name,
                               canonicalize=canonicalize,
                               enterprise=enterprise)
            client.Backend.rpcclient.connect()

            try:
                yield
            finally:
                client.Backend.rpcclient.disconnect()
    finally:
        client.Backend.rpcclient.connect()
Beispiel #11
0
def get_thread_ldap_connection():
    if not hasattr(ldapcache, 'connection'):
        conn = ipaldap.LDAPClient(
            ldap_uri=APP.config['LDAP_SERVER'],
            cacert=APP.config['LDAP_CACERT'],
        )
        with private_ccache() as ccache:
            kinit_keytab(
                principal='%s@%s' %
                (APP.config['KRB5_PRINCIPAL'], APP.config['KRB5_REALM']),
                keytab=APP.config['KRB5_KEYTAB'],
                ccache_name=ccache,
            )
            conn.gssapi_bind()

        ldapcache.connection = conn
    return ldapcache.connection
Beispiel #12
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)
Beispiel #13
0
    def run(self):
        kwargs = {}

        transformed_cls = self._transform(self.configurable_class)
        knob_classes = {n: getattr(c, n) for c, n in transformed_cls.knobs()}
        for name in knob_classes:
            value = getattr(self.options, name, None)
            if value is not None:
                kwargs[name] = value

        if (issubclass(self.configurable_class, common.Interactive)
                and not self.options.unattended):
            kwargs['interactive'] = True

        try:
            cfgr = transformed_cls(**kwargs)
        except core.KnobValueError as e:
            knob_cls = knob_classes[e.name]
            try:
                if self.positional_arguments is None:
                    raise ValueError
                index = self.positional_arguments.index(e.name)
            except ValueError:
                cli_name = knob_cls.cli_name or e.name.replace('_', '-')
                desc = "option --{0}".format(cli_name)
            else:
                desc = "argument {0}".format(index + 1)
            self.option_parser.error("{0}: {1}".format(desc, e))
        except RuntimeError as e:
            self.option_parser.error(str(e))

        signal.signal(signal.SIGTERM, self.__signal_handler)

        if self.use_private_ccache:
            with private_ccache():
                super(ConfigureTool, self).run()
                cfgr.run()
        else:
            super(ConfigureTool, self).run()
            cfgr.run()
Beispiel #14
0
def install(api, replica_config, options):
    if replica_config is None:
        if not options.setup_kra:
            return
        realm_name = api.env.realm
        dm_password = options.dm_password
        host_name = api.env.host
        subject_base = dsinstance.DsInstance().find_subject_base()

        pkcs12_info = None
        master_host = None
        promote = False
    else:
        if not replica_config.setup_kra:
            return
        krafile = os.path.join(replica_config.dir, 'kracert.p12')
        if options.promote:
            with ipautil.private_ccache():
                ccache = os.environ['KRB5CCNAME']
                kinit_keytab(
                    'host/{env.host}@{env.realm}'.format(env=api.env),
                    paths.KRB5_KEYTAB,
                    ccache)
                custodia = custodiainstance.CustodiaInstance(
                    replica_config.host_name,
                    replica_config.realm_name)
                custodia.get_kra_keys(
                    replica_config.kra_host_name,
                    krafile,
                    replica_config.dirman_password)
        else:
            cafile = os.path.join(replica_config.dir, 'cacert.p12')
            if not ipautil.file_exists(cafile):
                raise RuntimeError(
                    "Unable to clone KRA."
                    "  cacert.p12 file not found in replica file")
            shutil.copy(cafile, krafile)

        realm_name = replica_config.realm_name
        dm_password = replica_config.dirman_password
        host_name = replica_config.host_name
        subject_base = replica_config.subject_base

        pkcs12_info = (krafile,)
        master_host = replica_config.kra_host_name
        promote = options.promote

    kra = krainstance.KRAInstance(realm_name)
    kra.configure_instance(realm_name, host_name, dm_password, dm_password,
                           subject_base=subject_base,
                           pkcs12_info=pkcs12_info,
                           master_host=master_host,
                           promote=promote)

    _service.print_msg("Restarting the directory server")
    ds = dsinstance.DsInstance()
    ds.restart()
    kra.enable_client_auth_to_db(paths.KRA_CS_CFG_PATH)

    # Restart apache for new proxy config file
    services.knownservices.httpd.restart(capture_output=True)
 def test_anonymous_pkinit(self):
     with ipautil.private_ccache() as anon_ccache:
         try:
             ipautil.run([paths.KINIT, '-n', '-c', anon_ccache])
         except ipautil.CalledProcessError:
             raise RuntimeError("Failed to configure anonymous PKINIT")