Exemple #1
0
def uninstall():
    ca_instance = cainstance.CAInstance(api.env.realm)
    ca_instance.stop_tracking_certificates()
    ipautil.remove_file(paths.RA_AGENT_PEM)
    ipautil.remove_file(paths.RA_AGENT_KEY)
    if ca_instance.is_configured():
        ca_instance.uninstall()
Exemple #2
0
    def uninstall(self):
        if self.is_configured():
            self.print_msg("Unconfiguring %s" % self.service_name)

        running = self.restore_state("running")
        enabled = self.restore_state("enabled")

        try:
            self.stop()
        except Exception:
            pass

        for f in [paths.KRB5KDC_KDC_CONF, paths.KRB5_CONF]:
            try:
                self.fstore.restore_file(f)
            except ValueError as error:
                logger.debug("%s", error)

        # disabled by default, by ldap_configure()
        if enabled:
            self.enable()

        # stop tracking and remove certificates
        self.stop_tracking_certs()
        ipautil.remove_file(paths.CACERT_PEM)
        self.delete_pkinit_cert()

        if running:
            self.restart()

        self.kpasswd = KpasswdInstance()
        self.kpasswd.uninstall()
    def uninstall(self):
        if self.is_configured():
            self.print_msg("Unconfiguring %s" % self.service_name)

        # Just eat states
        self.restore_state("running")
        self.restore_state("enabled")
        self.restore_state("configured")

        # stop and disable service (IPA service, we do not need it anymore)
        self.stop()
        self.disable()

        for f in [paths.SYSCONFIG_NAMED]:
            try:
                self.fstore.restore_file(f)
            except ValueError as error:
                logger.debug('%s', error)

        # remove softhsm pin, to make sure new installation will generate
        # new token database
        # do not delete *so pin*, user can need it to get token data
        ipautil.remove_file(paths.DNSSEC_SOFTHSM_PIN)
        ipautil.remove_file(paths.DNSSEC_SOFTHSM2_CONF)

        try:
            shutil.rmtree(paths.DNSSEC_TOKENS_DIR)
        except OSError as e:
            if e.errno != errno.ENOENT:
                logger.exception("Failed to remove %s",
                                 paths.DNSSEC_TOKENS_DIR)

        ipautil.remove_keytab(self.keytab)
Exemple #4
0
 def remove_httpd_ccaches(self):
     # Clean up existing ccaches
     # Make sure that empty env is passed to avoid passing KRB5CCNAME from
     # current env
     ipautil.remove_file(paths.HTTP_CCACHE)
     for f in os.listdir(paths.IPA_CCACHES):
         os.remove(os.path.join(paths.IPA_CCACHES, f))
Exemple #5
0
 def uninstall(self):
     super(CustodiaInstance, self).uninstall()
     keystore = IPAKEMKeys({
         'server_keys': self.server_keys,
         'ldap_uri': self.ldap_uri
     })
     keystore.remove_server_keys_file()
     ipautil.remove_file(self.config_file)
     sysupgrade.set_upgrade_state('custodia', 'installed', False)
Exemple #6
0
 def remove_httpd_ccaches(self):
     # Clean up existing ccaches
     # Make sure that empty env is passed to avoid passing KRB5CCNAME from
     # current env
     ipautil.remove_file(paths.HTTP_CCACHE)
     shutil.rmtree(paths.IPA_CCACHES)
     ipautil.run(
         [paths.SYSTEMD_TMPFILES, '--create', '--prefix', paths.IPA_CCACHES]
     )
Exemple #7
0
    def uninstall(self):
        if self.is_configured():
            self.print_msg("Unconfiguring %s" % self.service_name)

        # Call restore_state so that we do not leave mess in the statestore
        # Otherwise this does nothing
        self.restore_state("running")
        self.restore_state("enabled")

        winbind = services.service("winbind", api)
        # Always try to stop and disable smb service, since we do not leave
        # working configuration after uninstall
        try:
            self.stop()
            self.disable()
            winbind.stop()
            winbind.disable()
        except Exception:
            pass

        # Since we do not guarantee restoring back to working samba state,
        # we should not restore smb.conf

        # Restore the state of affected selinux booleans
        boolean_states = {
            name: self.restore_state(name)
            for name in constants.SELINUX_BOOLEAN_ADTRUST
        }
        try:
            tasks.set_selinux_booleans(boolean_states)
        except ipapython.errors.SetseboolError as e:
            self.print_msg('WARNING: ' + str(e))

        # Remove samba's credentials cache
        ipautil.remove_ccache(ccache_path=paths.KRB5CC_SAMBA)

        # Remove samba's configuration file
        ipautil.remove_file(self.smb_conf)

        # Remove samba's persistent and temporary tdb files
        # in /var/lib/samba and /var/lib/samba/private
        for smbpath in (paths.SAMBA_DIR,
                        os.path.join(paths.SAMBA_DIR, "private"),
                        os.path.join(paths.SAMBA_DIR, "lock")):
            if os.path.isdir(smbpath):
                tdb_files = [
                    os.path.join(smbpath, tdb_file)
                    for tdb_file in os.listdir(smbpath)
                    if tdb_file.endswith(".tdb")
                ]
                for tdb_file in tdb_files:
                    ipautil.remove_file(tdb_file)

        # Remove our keys from samba's keytab
        self.clean_samba_keytab()
Exemple #8
0
    def check(self):
        ccache_dir = tempfile.mkdtemp()
        ccache_name = os.path.join(ccache_dir, 'ccache')

        try:
            try:
                host_princ = str('host/%s@%s' % (api.env.host, api.env.realm))
                kinit_keytab(host_princ, paths.KRB5_KEYTAB, ccache_name)
            except gssapi.exceptions.GSSError as e:
                yield Result(self,
                             constants.ERROR,
                             msg='Failed to obtain host TGT: %s' % e)
        finally:
            ipautil.remove_file(ccache_name)
            os.rmdir(ccache_dir)
Exemple #9
0
def remove_file(filename):
    """Remove a file and log any exceptions raised.
    """
    warnings.warn("Use 'ipapython.ipautil.remove_file'",
                  DeprecationWarning,
                  stacklevel=2)
    return ipautil.remove_file(filename)
Exemple #10
0
    def uninstall(self):
        if self.is_configured():
            self.print_msg("Unconfiguring %s" % self.service_name)

        running = self.restore_state("running")
        enabled = self.restore_state("enabled")
        named_regular_running = self.restore_state("named-regular-running")
        named_regular_enabled = self.restore_state("named-regular-enabled")

        self.dns_backup.clear_records(self.api.Backend.ldap2.isconnected())

        try:
            self.fstore.restore_file(paths.NAMED_CONF)
        except ValueError as error:
            logger.debug('%s', error)

        try:
            tasks.unconfigure_dns_resolver(fstore=self.fstore)
        except Exception:
            logger.exception("Failed to unconfigure DNS resolver")

        ipautil.rmtree(paths.BIND_LDAP_DNS_IPA_WORKDIR)

        # disabled by default, by ldap_configure()
        if enabled:
            self.enable()
        else:
            self.disable()

        if running:
            self.restart()
        else:
            self.stop()

        self.named_regular.unmask()
        if named_regular_enabled:
            self.named_regular.enable()

        if named_regular_running:
            self.named_regular.start()

        ipautil.remove_file(paths.NAMED_CUSTOM_CONFIG)
        ipautil.remove_keytab(self.keytab)
        ipautil.remove_ccache(run_as=self.service_user)
Exemple #11
0
    def uninstall(self):
        if self.is_configured():
            self.print_msg("Unconfiguring %s" % self.service_name)

        self.dns_backup.clear_records(self.api.Backend.ldap2.isconnected())

        try:
            self.fstore.restore_file(paths.NAMED_CONF)
        except ValueError as error:
            logger.debug('%s', error)

        try:
            tasks.unconfigure_dns_resolver(fstore=self.fstore)
        except Exception:
            logger.exception("Failed to unconfigure DNS resolver")

        ipautil.rmtree(paths.BIND_LDAP_DNS_IPA_WORKDIR)

        self.disable()
        self.stop()

        self.named_conflict.unmask()

        ipautil.remove_file(paths.NAMED_CONF_BAK)
        ipautil.remove_file(paths.NAMED_CUSTOM_CONF)
        ipautil.remove_file(paths.NAMED_CUSTOM_OPTIONS_CONF)
        ipautil.remove_keytab(self.keytab)
        ipautil.remove_ccache(run_as=self.service_user)
Exemple #12
0
def uninstall(installer):
    fstore = installer._fstore
    sstore = installer._sstore

    rv = 0

    print("Shutting down all IPA services")
    try:
        services.knownservices.ipa.stop()
    except Exception:
        # Fallback to direct ipactl stop only if system command fails
        try:
            run([paths.IPACTL, "stop"], raiseonerr=False)
        except Exception:
            pass

    restore_time_sync(sstore, fstore)

    kra.uninstall()

    ca.uninstall()

    dns.uninstall()

    httpinstance.HTTPInstance(fstore).uninstall()
    krbinstance.KrbInstance(fstore).uninstall()
    dsinstance.DsInstance(fstore=fstore).uninstall()
    if _server_trust_ad_installed:
        adtrustinstance.ADTRUSTInstance(fstore).uninstall()
    # realm isn't used, but IPAKEMKeys parses /etc/ipa/default.conf
    # otherwise, see https://pagure.io/freeipa/issue/7474 .
    custodiainstance.CustodiaInstance(realm='REALM.INVALID').uninstall()
    otpdinstance.OtpdInstance().uninstall()
    tasks.restore_hostname(fstore, sstore)
    fstore.restore_all_files()
    try:
        os.remove(paths.ROOT_IPA_CACHE)
    except Exception:
        pass
    try:
        os.remove(paths.ROOT_IPA_CSR)
    except Exception:
        pass

    # ipa-client-install removes /etc/ipa/default.conf

    sstore._load()

    timeconf.restore_forced_timeservices(sstore)

    # Clean up group_exists (unused since IPA 2.2, not being set since 4.1)
    sstore.restore_state("install", "group_exists")

    services.knownservices.ipa.disable()

    # remove upgrade state file
    sysupgrade.remove_upgrade_file()

    tasks.restore_pkcs11_modules(fstore)

    if fstore.has_files():
        logger.error('Some files have not been restored, see '
                     '%s/sysrestore.index', SYSRESTORE_DIR_PATH)
    has_state = False
    for module in IPA_MODULES:  # from installutils
        if sstore.has_state(module):
            logger.error('Some installation state for %s has not been '
                         'restored, see %s/sysrestore.state',
                         module, SYSRESTORE_DIR_PATH)
            has_state = True
            rv = 1

    if has_state:
        logger.error('Some installation state has not been restored.\n'
                     'This may cause re-installation to fail.\n'
                     'It should be safe to remove %s/sysrestore.state '
                     'but it may\n'
                     'mean your system hasn\'t be restored to its '
                     'pre-installation state.', SYSRESTORE_DIR_PATH)
    else:
        # sysrestore.state has no state left, remove it
        sysrestore = os.path.join(SYSRESTORE_DIR_PATH, 'sysrestore.state')
        ipautil.remove_file(sysrestore)

    # Note that this name will be wrong after the first uninstall.
    dirname = dsinstance.config_dirname(
        ipaldap.realm_to_serverid(api.env.realm))
    dirs = [dirname, paths.PKI_TOMCAT_ALIAS_DIR, paths.HTTPD_ALIAS_DIR]
    ids = certmonger.check_state(dirs)
    if ids:
        logger.error('Some certificates may still be tracked by '
                     'certmonger.\n'
                     'This will cause re-installation to fail.\n'
                     'Start the certmonger service and list the '
                     'certificates being tracked\n'
                     ' # getcert list\n'
                     'These may be untracked by executing\n'
                     ' # getcert stop-tracking -i <request_id>\n'
                     'for each id in: %s', ', '.join(ids))

    # Remove the cert renewal lock file
    try:
        os.remove(paths.IPA_RENEWAL_LOCK)
    except OSError as e:
        if e.errno != errno.ENOENT:
            logger.warning("Failed to remove file %s: %s",
                           paths.IPA_RENEWAL_LOCK, e)

    print("Removing IPA client configuration")
    try:
        result = run([paths.IPA_CLIENT_INSTALL, "--on-master",
                      "--unattended", "--uninstall"],
                     raiseonerr=False, redirect_output=True)
        if result.returncode not in [0, 2]:
            raise RuntimeError("Failed to configure the client")
    except Exception:
        rv = 1
        print("Uninstall of client side components failed!")

    sys.exit(rv)
Exemple #13
0
def uninstall(fstore, statestore, options):
    # Shut down Samba services and disable them
    smb = services.service("smb", api)
    winbind = services.service("winbind", api)
    for svc in (smb, winbind):
        if svc.is_running():
            svc.stop()
        svc.disable()

    # Restore the state of affected selinux booleans
    boolean_states = {}
    for usecase in constants.SELINUX_BOOLEAN_SMBSERVICE:
        for name in usecase:
            boolean_states[name] = statestore.restore_state("selinux", name)

    if boolean_states:
        set_selinux_booleans(boolean_states, statestore, backup=False)

    # Remove samba's credentials cache
    ipautil.remove_ccache(ccache_path=paths.KRB5CC_SAMBA)

    # Remove samba's configuration file
    if fstore.has_file(paths.SMB_CONF):
        ipautil.remove_file(paths.SMB_CONF)
        fstore.restore_file(paths.SMB_CONF)

    # Remove samba's persistent and temporary tdb files
    # in /var/lib/samba and /var/lib/samba/private
    for smbpath in (paths.SAMBA_DIR, os.path.join(paths.SAMBA_DIR, "private"),
                    os.path.join(paths.SAMBA_DIR, "lock")):
        tdb_files = [
            os.path.join(smbpath, tdb_file) for tdb_file in os.listdir(smbpath)
            if tdb_file.endswith(".tdb")
        ]
        for tdb_file in tdb_files:
            ipautil.remove_file(tdb_file)

    # Remove our keys from samba's keytab
    if os.path.exists(paths.SAMBA_KEYTAB):
        try:
            ipautil.run([
                paths.IPA_RMKEYTAB,
                "--principal",
                api.env.smb_princ,
                "-k",
                paths.SAMBA_KEYTAB,
            ])
        except ipautil.CalledProcessError as e:
            if e.returncode != 5:
                logger.critical("Failed to remove old key for %s",
                                api.env.smb_princ)

    with use_api_as_principal(api.env.host_princ, paths.KRB5_KEYTAB):
        try:
            api.Command.service_del(api.env.smb_princ)
        except errors.VersionError as e:
            print("This client is incompatible: " + str(e))
        except errors.NotFound:
            logger.debug("No SMB service principal exists, OK to proceed")
        except errors.PublicError as e:
            logger.error(
                "Cannot connect to the server due to "
                "a generic error: %s",
                e,
            )
Exemple #14
0
    def check(self):
        validate = []
        ca_pw_fname = None

        if self.ca.is_configured():
            try:
                ca_passwd = get_dogtag_cert_password()
            except IOError as e:
                yield Result(
                    self,
                    constants.ERROR,
                    error=str(e),
                    msg='Unable to read CA NSSDB token password: {error}')
                return
            else:
                with tempfile.NamedTemporaryFile(mode='w',
                                                 delete=False) as ca_pw_file:
                    ca_pw_file.write(ca_passwd)
                    ca_pw_fname = ca_pw_file.name

                validate.append((
                    paths.PKI_TOMCAT_ALIAS_DIR,
                    'Server-Cert cert-pki-ca',
                    ca_pw_fname,
                ), )

        validate.append((
            dsinstance.config_dirname(self.serverid),
            self.ds.get_server_cert_nickname(self.serverid),
            os.path.join(dsinstance.config_dirname(self.serverid),
                         'pwdfile.txt'),
        ))

        # Wrap in try/except to ensure the temporary password file is
        # removed
        try:
            for (dbdir, nickname, pinfile) in validate:
                # detect the database type so we have the right prefix
                db = certdb.NSSDatabase(dbdir)

                key = os.path.normpath(dbdir) + ':' + nickname
                try:
                    response = self.validate_nss(dbdir, db.dbtype, pinfile,
                                                 nickname)
                except ipautil.CalledProcessError as e:
                    logger.debug('Validation of NSS certificate failed %s', e)
                    yield Result(
                        self,
                        constants.ERROR,
                        key=key,
                        dbdir=dbdir,
                        nickname=nickname,
                        reason=response.output_error,
                        msg='Validation of {nickname} in {dbdir} failed: '
                        '{reason}')
                else:
                    if 'certificate is valid' not in \
                            response.raw_output.decode('utf-8'):
                        yield Result(
                            self,
                            constants.ERROR,
                            key=key,
                            dbdir=dbdir,
                            nickname=nickname,
                            reason="%s: %s" %
                            (response.raw_output.decode('utf-8'),
                             response.error_log),
                            msg='Validation of {nickname} in {dbdir} failed: '
                            '{reason}')
                    else:
                        yield Result(self,
                                     constants.SUCCESS,
                                     dbdir=dbdir,
                                     nickname=nickname,
                                     key=key)
        finally:
            if ca_pw_fname:
                ipautil.remove_file(ca_pw_fname)
Exemple #15
0
 def delete_pkinit_cert(self):
     ipautil.remove_file(paths.KDC_CERT)
     ipautil.remove_file(paths.KDC_KEY)
Exemple #16
0
    def uninstall(self):
        if self.is_configured():
            self.print_msg("Unconfiguring web server")

        running = self.restore_state("running")
        enabled = self.restore_state("enabled")

        # Restore oddjobd to its original state
        oddjobd = services.service('oddjobd', api)

        if not self.sstore.restore_state('oddjobd', 'running'):
            try:
                oddjobd.stop()
            except Exception:
                pass

        if not self.sstore.restore_state('oddjobd', 'enabled'):
            try:
                oddjobd.disable()
            except Exception:
                pass

        self.stop_tracking_certificates()

        helper = self.restore_state('certmonger_ipa_helper')
        if helper:
            bus = dbus.SystemBus()
            obj = bus.get_object('org.fedorahosted.certmonger',
                                 '/org/fedorahosted/certmonger')
            iface = dbus.Interface(obj, 'org.fedorahosted.certmonger')
            path = iface.find_ca_by_nickname('IPA')
            if path:
                ca_obj = bus.get_object('org.fedorahosted.certmonger', path)
                ca_iface = dbus.Interface(ca_obj,
                                          'org.freedesktop.DBus.Properties')
                ca_iface.Set('org.fedorahosted.certmonger.ca',
                             'external-helper', helper)

        for f in [
                paths.HTTPD_IPA_CONF, paths.HTTPD_SSL_CONF,
                paths.HTTPD_SSL_SITE_CONF, paths.HTTPD_NSS_CONF
        ]:
            try:
                self.fstore.restore_file(f)
            except ValueError as error:
                logger.debug("%s", error)

        # Remove the configuration files we create
        ipautil.remove_keytab(self.keytab)
        remove_files = [
            paths.HTTP_CCACHE,
            paths.HTTPD_CERT_FILE,
            paths.HTTPD_KEY_FILE,
            paths.HTTPD_PASSWD_FILE_FMT.format(host=api.env.host),
            paths.HTTPD_IPA_REWRITE_CONF,
            paths.HTTPD_IPA_CONF,
            paths.HTTPD_IPA_PKI_PROXY_CONF,
            paths.HTTPD_IPA_KDCPROXY_CONF_SYMLINK,
            paths.HTTPD_IPA_KDCPROXY_CONF,
            paths.GSSPROXY_CONF,
            paths.GSSAPI_SESSION_KEY,
            paths.HTTPD_PASSWORD_CONF,
            paths.SYSTEMD_SYSTEM_HTTPD_IPA_CONF,
        ]
        # NSS DB backups
        remove_files.extend(
            glob.glob(os.path.join(paths.HTTPD_ALIAS_DIR, '*.ipasave')))
        if paths.HTTPD_IPA_WSGI_MODULES_CONF is not None:
            remove_files.append(paths.HTTPD_IPA_WSGI_MODULES_CONF)

        for filename in remove_files:
            ipautil.remove_file(filename)

        try:
            os.rmdir(paths.SYSTEMD_SYSTEM_HTTPD_D_DIR)
        except OSError as e:
            if e.errno not in {errno.ENOENT, errno.ENOTEMPTY}:
                logger.error("Failed to remove directory %s",
                             paths.SYSTEMD_SYSTEM_HTTPD_D_DIR)

        # Restore SELinux boolean states
        boolean_states = {
            name: self.restore_state(name)
            for name in constants.SELINUX_BOOLEAN_HTTPD
        }
        try:
            tasks.set_selinux_booleans(boolean_states)
        except ipapython.errors.SetseboolError as e:
            self.print_msg('WARNING: ' + str(e))

        if running:
            self.restart()

        # disabled by default, by ldap_configure()
        if enabled:
            self.enable()