def renew(self): ca = cainstance.CAInstance(api.env.realm) if not ca.is_configured(): raise admintool.ScriptError("CA is not configured on this system") self.request_id = self._get_ca_request_id(RENEWAL_CA_NAME) if self.request_id is None: # if external CA renewal was interrupted, the request may have # been left with the "dogtag-ipa-ca-renew-agent-reuse" CA; # look for it too self.request_id = self._get_ca_request_id(RENEWAL_REUSE_CA_NAME) if self.request_id is None: raise admintool.ScriptError( "CA certificate is not tracked by certmonger") logger.debug("Found certmonger request id %r", self.request_id) db = certs.CertDB(api.env.realm, nssdir=paths.PKI_TOMCAT_ALIAS_DIR) cert = db.get_cert_from_db(self.cert_nickname) options = self.options if options.external_cert_files: return self.renew_external_step_2(ca, cert) if options.self_signed is not None: self_signed = options.self_signed else: self_signed = cert.is_self_signed() if self_signed: return self.renew_self_signed(ca) else: return self.renew_external_step_1(ca)
def __init__(self, reg): super().__init__(reg) self.ca = cainstance.CAInstance(api.env.realm, host_name=api.env.host) self.http = httpinstance.HTTPInstance() self.ds = dsinstance.DsInstance() self.serverid = realm_to_serverid(api.env.realm) self.conn = api.Backend.ldap2
def execute(self, **options): ca = cainstance.CAInstance(self.api.env.realm) if not ca.is_configured(): logger.debug("CA is not configured on this host") return False, [] ld = ldapupdate.LDAPUpdate(ldapi=True, sub_dict={ 'SUFFIX': self.api.env.basedn, 'FQDN': self.api.env.host, }) ld.update([paths.CA_TOPOLOGY_ULDIF]) ldap = self.api.Backend.ldap2 ca_replica_dn = DN(('cn', 'replica'), ('cn', 'o=ipaca'), ('cn', 'mapping tree'), ('cn', 'config')) check_interval_attr = 'nsds5replicabinddngroupcheckinterval' default_check_interval = ['60'] try: ca_replica_entry = ldap.get_entry(ca_replica_dn) except errors.NotFound: pass else: if check_interval_attr not in ca_replica_entry: ca_replica_entry[check_interval_attr] = default_check_interval ldap.update_entry(ca_replica_entry) return False, []
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()
def uninstall_check(options): """Check if the host is CRL generation master""" # Skip the checks if the host is not a CA instance ca = cainstance.CAInstance(api.env.realm) if not (api.Command.ca_is_enabled()['result'] and cainstance.is_ca_installed_locally()): return # skip the checks if the host is the last master ipa_config = api.Command.config_show()['result'] ipa_masters = ipa_config.get('ipa_master_server', []) if len(ipa_masters) <= 1: return try: crlgen_enabled = ca.is_crlgen_enabled() except cainstance.InconsistentCRLGenConfigException: # If config is inconsistent, let's be safe and act as if # crl gen was enabled crlgen_enabled = True if crlgen_enabled: print("Deleting this server will leave your installation " "without a CRL generation master.") if (options.unattended and not options.ignore_last_of_role) or \ not (options.unattended or ipautil.user_input( "Are you sure you want to continue with the uninstall " "procedure?", False)): raise ScriptError("Aborting uninstall operation.")
def renew(self): ca = cainstance.CAInstance(api.env.realm) if not ca.is_configured(): raise admintool.ScriptError("CA is not configured on this system") criteria = { 'cert-database': paths.PKI_TOMCAT_ALIAS_DIR, 'cert-nickname': self.cert_nickname, 'ca-name': 'dogtag-ipa-ca-renew-agent', } self.request_id = certmonger.get_request_id(criteria) if self.request_id is None: raise admintool.ScriptError( "CA certificate is not tracked by certmonger") self.log.debug( "Found certmonger request id %r", self.request_id) db = certs.CertDB(api.env.realm, nssdir=paths.PKI_TOMCAT_ALIAS_DIR) cert = db.get_cert_from_db(self.cert_nickname, pem=False) options = self.options if options.external_cert_files: return self.renew_external_step_2(ca, cert) if options.self_signed is not None: self_signed = options.self_signed else: self_signed = x509.is_self_signed(cert, x509.DER) if self_signed: return self.renew_self_signed(ca) else: return self.renew_external_step_1(ca)
def check(self, instance=''): self.service_name = 'pki_tomcatd' ca = cainstance.CAInstance(api.env.realm, host_name=api.env.host) if not ca.is_configured(): return () return super().check()
def install_step_0(standalone, replica_config, options): realm_name = options.realm_name dm_password = options.dm_password host_name = options.host_name subject_base = options.subject if replica_config is not None: # Configure the CA if necessary if standalone: api.Backend.ldap2.disconnect() cainstance.install_replica_ca(replica_config, standalone, ra_p12=getattr(options, 'ra_p12', None)) if standalone and not api.Backend.ldap2.isconnected(): api.Backend.ldap2.connect(bind_dn=DN(('cn', 'Directory Manager')), bind_pw=dm_password) return if options.external_cert_files: external = 2 elif options.external_ca: external = 1 else: external = 0 ca = cainstance.CAInstance(realm_name, certs.NSS_DIR) if standalone: ca.create_ra_agent_db = False if external == 0: ca.configure_instance( host_name, dm_password, dm_password, subject_base=subject_base, ca_signing_algorithm=options.ca_signing_algorithm) elif external == 1: ca.configure_instance( host_name, dm_password, dm_password, csr_file=paths.ROOT_IPA_CSR, subject_base=subject_base, ca_signing_algorithm=options.ca_signing_algorithm, ca_type=options.external_ca_type) else: ca.configure_instance( host_name, dm_password, dm_password, cert_file=external_cert_file.name, cert_chain_file=external_ca_file.name, subject_base=subject_base, ca_signing_algorithm=options.ca_signing_algorithm)
def configure_instance(self, host_name, domain, dm_password, admin_password, ds_port=DEFAULT_DSPORT, pkcs12_info=None, master_host=None, master_replication_port=None, subject_base=None): """Create a KRA instance. To create a clone, pass in pkcs12_info. """ self.fqdn = host_name self.domain = domain self.dm_password = dm_password self.admin_password = admin_password self.ds_port = ds_port self.pkcs12_info = pkcs12_info if self.pkcs12_info is not None: self.clone = True self.master_host = master_host self.master_replication_port = master_replication_port if subject_base is None: self.subject_base = DN(('O', self.realm)) else: self.subject_base = subject_base # Confirm that a KRA does not already exist if self.is_installed(): raise RuntimeError("KRA already installed.") # Confirm that a Dogtag 10 CA instance already exists ca = cainstance.CAInstance(api.env.realm, certs.NSS_DIR, dogtag_constants=dogtag.Dogtag10Constants) if not ca.is_installed(): raise RuntimeError("KRA configuration failed. " "A Dogtag CA must be installed first") self.step("configuring KRA instance", self.__spawn_instance) if not self.clone: self.step("add RA user to KRA agent group", self.__add_ra_user_to_agent_group) self.step("restarting KRA", self.restart_instance) self.step("configure certmonger for renewals", self.configure_certmonger_renewal) self.step("configure certificate renewals", self.configure_renewal) self.step("Configure HTTP to proxy connections", self.http_proxy) self.start_creation(runtime=126)
def initialize(self, framework, config, options=None): super().initialize(framework, config) # deferred import for mock # pylint: disable=import-outside-toplevel from ipaserver.servroles import ADtrustBasedRole, ServiceBasedRole # pylint: enable=import-outside-toplevel installutils.check_server_configuration() if not api.isdone('finalize'): if not api.isdone('bootstrap'): api.bootstrap(in_server=True, context='ipahealthcheck', log=None) if not api.isdone('finalize'): api.finalize() if not api.Backend.ldap2.isconnected(): try: api.Backend.ldap2.connect() except (errors.CCacheError, errors.NetworkError) as e: logger.debug('Failed to connect to LDAP: %s', e) return ca = cainstance.CAInstance(api.env.realm, host_name=api.env.host) self.ca_configured = ca.is_configured() # This package is pulled in when the trust package is installed # and is required to lookup trust users. If this is not installed # then it can be inferred that trust is not enabled. try: # pylint: disable=unused-import,import-outside-toplevel import pysss_nss_idmap # noqa: F401 # pylint: enable=unused-import,import-outside-toplevel except ImportError: return roles = ( ADtrustBasedRole(u"ad_trust_agent_server", u"AD trust agent"), ServiceBasedRole(u"ad_trust_controller_server", u"AD trust controller", component_services=['ADTRUST']), ) role = roles[0].status(api)[0] if role.get('status') == 'enabled': self.trust_agent = True role = roles[1].status(api)[0] if role.get('status') == 'enabled': self.trust_controller = True
def execute(self, **options): ca = cainstance.CAInstance(self.api.env.realm, certs.NSS_DIR) if not ca.is_configured(): self.log.debug("CA is not configured on this host") return False, [] ld = ldapupdate.LDAPUpdate(ldapi=True, sub_dict={ 'SUFFIX': self.api.env.basedn, 'FQDN': self.api.env.host, }) ld.update([paths.CA_TOPOLOGY_ULDIF]) return False, []
def configure_instance(self, realm_name, host_name, dm_password, admin_password, pkcs12_info=None, master_host=None, subject_base=None): """Create a KRA instance. To create a clone, pass in pkcs12_info. """ self.fqdn = host_name self.dm_password = dm_password self.admin_password = admin_password self.pkcs12_info = pkcs12_info if self.pkcs12_info is not None: self.clone = True self.master_host = master_host if subject_base is None: self.subject_base = DN(('O', self.realm)) else: self.subject_base = subject_base self.realm = realm_name self.suffix = ipautil.realm_to_suffix(realm_name) # Confirm that a KRA does not already exist if self.is_installed(): raise RuntimeError("KRA already installed.") # Confirm that a Dogtag 10 CA instance already exists ca = cainstance.CAInstance(api.env.realm, certs.NSS_DIR) if not ca.is_installed(): raise RuntimeError("KRA configuration failed. " "A Dogtag CA must be installed first") self.step("configuring KRA instance", self.__spawn_instance) if not self.clone: self.step("create KRA agent", self.__create_kra_agent) self.step("restarting KRA", self.restart_instance) self.step("configure certmonger for renewals", self.configure_certmonger_renewal) self.step("configure certificate renewals", self.configure_renewal) self.step("configure HTTP to proxy connections", self.http_proxy) self.step("add vault container", self.__add_vault_container) self.step("apply LDAP updates", self.__apply_updates) self.start_creation(runtime=126)
def cert_restore_prepare(self): cainstance.CAInstance().stop_tracking_certificates() httpinstance.HTTPInstance().stop_tracking_certificates() try: dsinstance.DsInstance().stop_tracking_certificates( installutils.realm_to_serverid(api.env.realm)) except OSError: # When IPA is not installed, DS NSS DB does not exist pass for basename in ('cert8.db', 'key3.db', 'secmod.db', 'pwdfile.txt'): filename = os.path.join(paths.IPA_NSSDB_DIR, basename) try: ipautil.backup_file(filename) except OSError as e: self.log.error("Failed to backup %s: %s" % (filename, e)) tasks.remove_ca_certs_from_systemwide_ca_store()
def configure_replica(self, host_name, master_host, dm_password, kra_cert_bundle=None, subject_base=None): """Create a KRA instance. To create a clone, pass in pkcs12_info. """ self.fqdn = host_name self.dm_password = dm_password self.master_host = master_host if subject_base is None: self.subject_base = DN(('O', self.realm)) else: self.subject_base = subject_base self.suffix = ipautil.realm_to_suffix(self.realm) self.pkcs12_info = kra_cert_bundle self.clone = True self.admin_groups = ADMIN_GROUPS # Confirm that a KRA does not already exist if self.is_installed(): raise RuntimeError("KRA already installed.") # Confirm that a Dogtag 10 CA instance already exists ca = cainstance.CAInstance(self.realm, certs.NSS_DIR) if not ca.is_installed(): raise RuntimeError("KRA configuration failed. " "A Dogtag CA must be installed first") self.step("creating installation admin user", self.setup_admin) self.step("configuring KRA instance", self.__spawn_instance) self.step("destroying installation admin user", self.teardown_admin) self.step("restarting KRA", self.restart_instance) self.step("configure certmonger for renewals", self.configure_certmonger_renewal) self.step("configure certificate renewals", self.configure_renewal) self.step("add vault container", self.__add_vault_container) self.step("enabling KRA instance", self.__enable_instance) self.start_creation(runtime=126)
def execute(self, **options): ra_nick = 'ipaCert' ca_enabled = self.api.Command.ca_is_enabled()['result'] if not ca_enabled: return False, [] try: certdb = NSSDatabase(nssdir=paths.HTTPD_ALIAS_DIR) except ValueError as e: logger.warning("Problem opening NSS database in " "%s. Skipping check for existing RA " "agent certificate: %s", paths.HTTPD_ALIAS_DIR, e) return False, [] if not certdb.has_nickname(ra_nick): # Nothign to do return False, [] elif os.path.exists(paths.RA_AGENT_PEM): # even though the certificate file exists, we will overwrite it # as it's probabably something wrong anyway logger.warning( "A certificate with the nickname 'ipaCert' exists in " "the old '%s' NSS database as well as in the new " "PEM file '%s'", paths.HTTPD_ALIAS_DIR, paths.RA_AGENT_PEM) _fd, p12file = tempfile.mkstemp(dir=certdb.secdir) # no password is necessary as we will be saving it in clear anyway certdb.export_pkcs12(ra_nick, p12file, pkcs12_passwd='') # stop tracking the old cert and remove it certmonger.stop_tracking(paths.HTTPD_ALIAS_DIR, nickname=ra_nick) certdb.delete_key_and_cert(ra_nick) if os.path.exists(paths.OLD_KRA_AGENT_PEM): os.remove(paths.OLD_KRA_AGENT_PEM) # get the private key and certificate from the file and start # tracking it in certmonger ca = cainstance.CAInstance() ca.import_ra_cert(p12file) os.remove(p12file) return False, []
def cert_restore_prepare(self): cainstance.CAInstance().stop_tracking_certificates() httpinstance.HTTPInstance().stop_tracking_certificates() try: dsinstance.DsInstance().stop_tracking_certificates( installutils.realm_to_serverid(api.env.realm)) except (OSError, IOError): # When IPA is not installed, DS NSS DB does not exist pass krbinstance.KrbInstance().stop_tracking_certs() for basename in certdb.NSS_FILES: filename = os.path.join(paths.IPA_NSSDB_DIR, basename) try: ipautil.backup_file(filename) except OSError as e: logger.error("Failed to backup %s: %s", filename, e) tasks.remove_ca_certs_from_systemwide_ca_store()
def install_step_0(standalone, replica_config, options): realm_name = options.realm_name dm_password = options.dm_password host_name = options.host_name subject_base = options.subject if replica_config is not None: # Configure the CA if necessary cainstance.install_replica_ca(replica_config, standalone, ra_p12=getattr(options, 'ra_p12', None)) return if options.external_cert_files: external = 2 elif options.external_ca: external = 1 else: external = 0 ca = cainstance.CAInstance(realm_name, certs.NSS_DIR) if standalone: ca.create_ra_agent_db = False if external == 0: ca.configure_instance(host_name, dm_password, dm_password, subject_base=subject_base, ca_signing_algorithm=options.ca_signing_algorithm) elif external == 1: ca.configure_instance(host_name, dm_password, dm_password, csr_file=paths.ROOT_IPA_CSR, subject_base=subject_base, ca_signing_algorithm=options.ca_signing_algorithm, ca_type=options.external_ca_type) else: ca.configure_instance(host_name, dm_password, dm_password, cert_file=external_cert_file.name, cert_chain_file=external_ca_file.name, subject_base=subject_base, ca_signing_algorithm=options.ca_signing_algorithm)
def run(self): api.bootstrap(in_server=True, confdir=paths.ETC_IPA) api.finalize() try: api.Backend.ldap2.connect() except NetworkError as e: logger.debug("Unable to connect to the local instance: %s", e) raise RuntimeError("IPA must be running, please run ipactl start") ca = cainstance.CAInstance(api.env.realm) try: action = self.args[0] if action == 'enable': self.enable(ca) elif action == 'disable': self.disable(ca) elif action == 'status': self.status(ca) finally: api.Backend.ldap2.disconnect() return 0
def run_with_args(api): """ Run the certupdate procedure with the given API object. :param api: API object with ldap2/rpcclient backend connected (such that Commands can be invoked) """ server = urlsplit(api.env.jsonrpc_uri).hostname ldap = ipaldap.LDAPClient.from_hostname_secure(server) try: result = api.Command.ca_is_enabled(version=u'2.107') ca_enabled = result['result'] except (errors.CommandError, errors.NetworkError): result = api.Command.env(server=True, version=u'2.0') ca_enabled = result['result']['enable_ra'] ldap.gssapi_bind() certs = certstore.get_ca_certs(ldap, api.env.basedn, api.env.realm, ca_enabled) if ca_enabled: lwcas = api.Command.ca_find()['result'] else: lwcas = [] if is_ipa_configured(): # look up CA servers before service restarts resp = api.Command.server_role_find( role_servrole=u'CA server', status='enabled', ) ca_servers = [server['server_server'] for server in resp['result']] update_server(certs) # pylint: disable=import-error,ipa-forbidden-import from ipaserver.install import cainstance, custodiainstance # pylint: enable=import-error,ipa-forbidden-import # Add LWCA tracking requests. Only execute if *this server* # has CA installed (ca_enabled indicates CA-ful topology). if cainstance.CAInstance().is_configured(): try: cainstance.add_lightweight_ca_tracking_requests(lwcas) except Exception: logger.exception( "Failed to add lightweight CA tracking requests") try: update_server_ra_config( cainstance, custodiainstance, api.env.enable_ra, api.env.ca_host, ca_servers, ) except Exception: logger.exception("Failed to update RA config") # update_server_ra_config possibly updated default.conf; # restart httpd to pick up changes. if services.knownservices.httpd.is_running(): services.knownservices.httpd.restart() update_client(certs)
def run(self): """Execute the tests""" api.Backend.ldap2.connect() self.serverid = installutils.realm_to_serverid(api.env.realm) self.ca = cainstance.CAInstance(api.env.realm, host_name=api.env.host) self.http = httpinstance.HTTPInstance() self.ds = dsinstance.DsInstance() self.conn = api.Backend.ldap2 logger.info("Check CA status") self.check_ca_status() logger.info("Check tracking") self.check_tracking() logger.info("Check NSS trust") self.check_trust() logger.info("Check dates") self.check_dates() logger.info("Checking certificates in CS.cfg") self.check_cs_cfg() logger.info("Comparing certificates to requests in LDAP") self.compare_requests() logger.info("Checking RA certificate") self.check_ra_cert() logger.info("Checking authorities") self.check_ipa_to_cs_authorities() self.check_cs_to_ipa_authorities() logger.info("Checking host keytab") self.check_hostkeytab() logger.info("Validating certificates") self.validate_certs() logger.info("Checking renewal master") self.check_renewal_master() logger.info("End-to-end cert API test") self.cert_api_test() logger.info("Checking permissions and ownership") self.check_permissions() if self.conn is not None and self.conn.isconnected(): self.conn.disconnect() if self.failures: logger.info("Failures:") for f in self.failures: logger.info(f) else: logger.info("All checks passed") if self.warnings: logger.info("Warnings:") for f in self.warnings: logger.info(f) return self.failures != []
def install_step_1(standalone, replica_config, options, custodia): if replica_config is not None and not replica_config.setup_ca: return realm_name = options.realm_name host_name = options.host_name subject_base = options._subject_base basedn = ipautil.realm_to_suffix(realm_name) ca = cainstance.CAInstance(realm=realm_name, host_name=host_name, custodia=custodia) ca.stop('pki-tomcat') # This is done within stopped_service context, which restarts CA ca.enable_client_auth_to_db() # Lightweight CA key retrieval is configured in step 1 instead # of CAInstance.configure_instance (which is invoked from step # 0) because kadmin_addprinc fails until krb5.conf is installed # by krb.create_instance. # ca.setup_lightweight_ca_key_retrieval() serverid = ipaldap.realm_to_serverid(realm_name) if standalone and replica_config is None: dirname = dsinstance.config_dirname(serverid) # Store the new IPA CA cert chain in DS NSS database and LDAP cadb = certs.CertDB(realm_name, nssdir=paths.PKI_TOMCAT_ALIAS_DIR, subject_base=subject_base) dsdb = certs.CertDB(realm_name, nssdir=dirname, subject_base=subject_base) cacert = cadb.get_cert_from_db('caSigningCert cert-pki-ca') nickname = certdb.get_ca_nickname(realm_name) trust_flags = certdb.IPA_CA_TRUST_FLAGS dsdb.add_cert(cacert, nickname, trust_flags) certstore.put_ca_cert_nss(api.Backend.ldap2, api.env.basedn, cacert, nickname, trust_flags, config_ipa=True, config_compat=True) # Store DS CA cert in Dogtag NSS database trust_flags = dict(reversed(dsdb.list_certs())) server_certs = dsdb.find_server_certs() trust_chain = dsdb.find_root_cert(server_certs[0][0])[:-1] nickname = trust_chain[-1] cert = dsdb.get_cert_from_db(nickname) cadb.add_cert(cert, nickname, trust_flags[nickname]) installutils.restart_dirsrv() ca.start('pki-tomcat') if standalone or replica_config is not None: # We need to restart apache as we drop a new config file in there services.knownservices.httpd.restart(capture_output=True) if standalone: # Install CA DNS records if bindinstance.dns_container_exists(basedn): bind = bindinstance.BindInstance() bind.update_system_records()
def install_step_0(standalone, replica_config, options, custodia): realm_name = options.realm_name dm_password = options.dm_password host_name = options.host_name ca_subject = options._ca_subject subject_base = options._subject_base external_ca_profile = None if replica_config is None: ca_signing_algorithm = options.ca_signing_algorithm if options.external_ca: ca_type = options.external_ca_type external_ca_profile = options.external_ca_profile csr_file = paths.ROOT_IPA_CSR else: ca_type = None csr_file = None if options.external_cert_files: cert_file = external_cert_file.name cert_chain_file = external_ca_file.name else: cert_file = None cert_chain_file = None pkcs12_info = None master_host = None master_replication_port = None ra_p12 = None ra_only = False promote = False else: cafile = os.path.join(replica_config.dir, 'cacert.p12') custodia.get_ca_keys(cafile, replica_config.dirman_password) ca_signing_algorithm = None ca_type = None csr_file = None cert_file = None cert_chain_file = None pkcs12_info = (cafile, ) master_host = replica_config.ca_host_name master_replication_port = replica_config.ca_ds_port ra_p12 = os.path.join(replica_config.dir, 'ra.p12') ra_only = not replica_config.setup_ca promote = True # if upgrading from CA-less to CA-ful, need to rewrite # certmap.conf and subject_base configuration # set_subject_base_in_config(subject_base) sysupgrade.set_upgrade_state('certmap.conf', 'subject_base', str(subject_base)) dsinstance.write_certmap_conf(realm_name, ca_subject) # use secure ldaps when installing a replica or upgrading to CA-ful # In both cases, 389-DS is already configured to have a trusted cert. use_ldaps = standalone or replica_config is not None ca = cainstance.CAInstance(realm=realm_name, host_name=host_name, custodia=custodia) ca.configure_instance( host_name, dm_password, dm_password, subject_base=subject_base, ca_subject=ca_subject, ca_signing_algorithm=ca_signing_algorithm, ca_type=ca_type, external_ca_profile=external_ca_profile, csr_file=csr_file, cert_file=cert_file, cert_chain_file=cert_chain_file, pkcs12_info=pkcs12_info, master_host=master_host, master_replication_port=master_replication_port, ra_p12=ra_p12, ra_only=ra_only, promote=promote, use_ldaps=use_ldaps, pki_config_override=options.pki_config_override, )
def run_with_args(api): """ Run the certupdate procedure with the given API object. :param api: API object with ldap2/rpcclient backend connected (such that Commands can be invoked) """ server = urlsplit(api.env.jsonrpc_uri).hostname ldap = ipaldap.LDAPClient.from_hostname_secure(server) tmpdir = tempfile.mkdtemp(prefix="tmp-") ccache_name = os.path.join(tmpdir, 'ccache') old_krb5ccname = os.environ.get('KRB5CCNAME') try: principal = str('host/%s@%s' % (api.env.host, api.env.realm)) kinit_keytab(principal, paths.KRB5_KEYTAB, ccache_name) os.environ['KRB5CCNAME'] = ccache_name try: result = api.Command.ca_is_enabled(version=u'2.107') ca_enabled = result['result'] except (errors.CommandError, errors.NetworkError): result = api.Command.env(server=True, version=u'2.0') ca_enabled = result['result']['enable_ra'] ldap.gssapi_bind() certs = certstore.get_ca_certs(ldap, api.env.basedn, api.env.realm, ca_enabled) if ca_enabled: lwcas = api.Command.ca_find()['result'] else: lwcas = [] finally: if old_krb5ccname is None: del os.environ['KRB5CCNAME'] else: os.environ['KRB5CCNAME'] = old_krb5ccname shutil.rmtree(tmpdir) server_fstore = sysrestore.FileStore(paths.SYSRESTORE) if server_fstore.has_files(): # look up CA servers before service restarts resp = api.Command.server_role_find( role_servrole=u'CA server', status='enabled', ) ca_servers = [server['server_server'] for server in resp['result']] update_server(certs) # pylint: disable=import-error,ipa-forbidden-import from ipaserver.install import cainstance, custodiainstance # pylint: enable=import-error,ipa-forbidden-import # Add LWCA tracking requests. Only execute if *this server* # has CA installed (ca_enabled indicates CA-ful topology). if cainstance.CAInstance().is_configured(): try: cainstance.add_lightweight_ca_tracking_requests(lwcas) except Exception: logger.exception( "Failed to add lightweight CA tracking requests") try: update_server_ra_config( cainstance, custodiainstance, api.env.enable_ra, api.env.ca_host, ca_servers, ) except Exception: logger.exception("Failed to update RA config") # update_server_ra_config possibly updated default.conf; # restart httpd to pick up changes. if services.knownservices.httpd.is_running(): services.knownservices.httpd.restart() update_client(certs)
def execute(self, **options): ca = cainstance.CAInstance(self.api.env.realm, certs.NSS_DIR) if not ca.is_configured(): self.debug("CA is not configured on this host") return False, [] ldap = self.api.Backend.ldap2 base_dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), self.api.env.basedn) dn = DN(('cn', 'CA'), ('cn', self.api.env.host), base_dn) filter = '(&(cn=CA)(ipaConfigString=caRenewalMaster))' try: entries = ldap.get_entries(base_dn=base_dn, filter=filter, attrs_list=[]) except errors.NotFound: pass else: self.debug("found CA renewal master %s", entries[0].dn[1].value) master = False updates = [] for entry in entries: if entry.dn == dn: master = True continue updates.append({ 'dn': entry.dn, 'updates': [ dict(action='remove', attr='ipaConfigString', value='caRenewalMaster') ], }) if master: return False, updates else: return False, [] criteria = { 'cert-database': paths.HTTPD_ALIAS_DIR, 'cert-nickname': 'ipaCert', } request_id = certmonger.get_request_id(criteria) if request_id is not None: self.debug("found certmonger request for ipaCert") ca_name = certmonger.get_request_value(request_id, 'ca-name') if ca_name is None: self.warning( "certmonger request for ipaCert is missing ca_name, " "assuming local CA is renewal slave") return False, [] ca_name = ca_name.strip() if ca_name == 'dogtag-ipa-renew-agent': pass elif ca_name == 'dogtag-ipa-retrieve-agent-submit': return False, [] elif ca_name == 'dogtag-ipa-ca-renew-agent': return False, [] else: self.warning( "certmonger request for ipaCert has unknown ca_name '%s', " "assuming local CA is renewal slave", ca_name) return False, [] else: self.debug("certmonger request for ipaCert not found") config = installutils.get_directive(paths.CA_CS_CFG_PATH, 'subsystem.select', '=') if config == 'New': pass elif config == 'Clone': return False, [] else: self.warning( "CS.cfg has unknown subsystem.select value '%s', " "assuming local CA is renewal slave", config) return (False, False, []) update = { 'dn': dn, 'updates': [ dict(action='add', attr='ipaConfigString', value='caRenewalMaster') ], } return False, [update]
def install(installer): options = installer fstore = installer._fstore sstore = installer._sstore dirsrv_pkcs12_info = installer._dirsrv_pkcs12_info http_pkcs12_info = installer._http_pkcs12_info pkinit_pkcs12_info = installer._pkinit_pkcs12_info http_ca_cert = installer._ca_cert realm_name = options.realm_name domain_name = options.domain_name dm_password = options.dm_password master_password = options.master_password admin_password = options.admin_password host_name = options.host_name ip_addresses = options.ip_addresses setup_ca = options.setup_ca # Installation has started. No IPA sysrestore items are restored in case of # failure to enable root cause investigation installer._installation_cleanup = False if installer.interactive: print("") print("The following operations may take some minutes to complete.") print("Please wait until the prompt is returned.") print("") # set hostname (transient and static) if user instructed us to do so if options._host_name_overridden: tasks.backup_hostname(fstore, sstore) tasks.set_hostname(host_name) if installer._update_hosts_file: update_hosts_file(ip_addresses, host_name, fstore) http_instance = httpinstance.HTTPInstance() http_instance.create_cert_db() # Create DS user/group if it doesn't exist yet dsinstance.create_ds_user() # Create a directory server instance if not options.external_cert_files: # Configure ntpd if not options.no_ntp: ipaclient.ntpconf.force_ntpd(sstore) ntp = ntpinstance.NTPInstance(fstore) if not ntp.is_configured(): ntp.create_instance() if options.dirsrv_cert_files: ds = dsinstance.DsInstance(fstore=fstore, domainlevel=options.domainlevel, config_ldif=options.dirsrv_config_file) installer._ds = ds ds.create_instance(realm_name, host_name, domain_name, dm_password, dirsrv_pkcs12_info, idstart=options.idstart, idmax=options.idmax, subject_base=options.subject, hbac_allow=not options.no_hbac_allow) else: ds = dsinstance.DsInstance(fstore=fstore, domainlevel=options.domainlevel, config_ldif=options.dirsrv_config_file) installer._ds = ds ds.create_instance(realm_name, host_name, domain_name, dm_password, idstart=options.idstart, idmax=options.idmax, subject_base=options.subject, hbac_allow=not options.no_hbac_allow) ntpinstance.ntp_ldap_enable(host_name, ds.suffix, realm_name) else: api.Backend.ldap2.connect() ds = dsinstance.DsInstance(fstore=fstore, domainlevel=options.domainlevel) installer._ds = ds ds.init_info(realm_name, host_name, domain_name, dm_password, options.subject, 1101, 1100, None) if setup_ca: if not options.external_cert_files and options.external_ca: # stage 1 of external CA installation options.realm_name = realm_name options.domain_name = domain_name options.master_password = master_password options.dm_password = dm_password options.admin_password = admin_password options.host_name = host_name options.reverse_zones = dns.reverse_zones cache_vars = { n: options.__dict__[n] for o, n in installer.knobs() if n in options.__dict__ } write_cache(cache_vars) ca.install_step_0(False, None, options) # Now put the CA cert where other instances exepct it ca_instance = cainstance.CAInstance(realm_name, certs.NSS_DIR) ca_instance.publish_ca_cert(CACERT) else: # Put the CA cert where other instances expect it x509.write_certificate(http_ca_cert, CACERT) os.chmod(CACERT, 0o444) # we now need to enable ssl on the ds ds.enable_ssl() krb = krbinstance.KrbInstance(fstore) if options.pkinit_cert_files: krb.create_instance(realm_name, host_name, domain_name, dm_password, master_password, setup_pkinit=not options.no_pkinit, pkcs12_info=pkinit_pkcs12_info, subject_base=options.subject) else: krb.create_instance(realm_name, host_name, domain_name, dm_password, master_password, setup_pkinit=not options.no_pkinit, subject_base=options.subject) # restart DS to enable ipa-pwd-extop plugin print("Restarting directory server to enable password extension plugin") ds.restart() if setup_ca: ca.install_step_1(False, None, options) # The DS instance is created before the keytab, add the SSL cert we # generated ds.add_cert_to_service() memcache = memcacheinstance.MemcacheInstance() memcache.create_instance('MEMCACHE', host_name, ipautil.realm_to_suffix(realm_name)) otpd = otpdinstance.OtpdInstance() otpd.create_instance('OTPD', host_name, ipautil.realm_to_suffix(realm_name)) custodia = custodiainstance.CustodiaInstance(host_name, realm_name) custodia.create_instance() # Create a HTTP instance http = httpinstance.HTTPInstance(fstore) if options.http_cert_files: http.create_instance(realm_name, host_name, domain_name, pkcs12_info=http_pkcs12_info, subject_base=options.subject, auto_redirect=not options.no_ui_redirect, ca_is_configured=setup_ca) else: http.create_instance(realm_name, host_name, domain_name, subject_base=options.subject, auto_redirect=not options.no_ui_redirect, ca_is_configured=setup_ca) tasks.restore_context(paths.CACHE_IPA_SESSIONS) # Export full CA chain ca_db = certs.CertDB(realm_name) os.chmod(CACERT, 0o644) ca_db.publish_ca_cert(CACERT) set_subject_in_config(realm_name, dm_password, ipautil.realm_to_suffix(realm_name), options.subject) # Apply any LDAP updates. Needs to be done after the configuration file # is created. DS is restarted in the process. service.print_msg("Applying LDAP updates") ds.apply_updates() # Restart krb after configurations have been changed service.print_msg("Restarting the KDC") krb.restart() if options.setup_dns: dns.install(False, False, options) else: # Create a BIND instance bind = bindinstance.BindInstance(fstore) bind.setup(host_name, ip_addresses, realm_name, domain_name, (), 'first', (), zonemgr=options.zonemgr, no_dnssec_validation=options.no_dnssec_validation) bind.create_file_with_system_records() # Set the admin user kerberos password ds.change_admin_password(admin_password) # Call client install script service.print_msg("Configuring client side components") try: args = [ paths.IPA_CLIENT_INSTALL, "--on-master", "--unattended", "--domain", domain_name, "--server", host_name, "--realm", realm_name, "--hostname", host_name ] if options.no_dns_sshfp: args.append("--no-dns-sshfp") if options.ssh_trust_dns: args.append("--ssh-trust-dns") if options.no_ssh: args.append("--no-ssh") if options.no_sshd: args.append("--no-sshd") if options.mkhomedir: args.append("--mkhomedir") run(args, redirect_output=True) print() except Exception: raise ScriptError("Configuration of client side components failed!") # Everything installed properly, activate ipa service. services.knownservices.ipa.enable() print("=======================================" "=======================================") print("Setup complete") print("") print("Next steps:") print("\t1. You must make sure these network ports are open:") print("\t\tTCP Ports:") print("\t\t * 80, 443: HTTP/HTTPS") print("\t\t * 389, 636: LDAP/LDAPS") print("\t\t * 88, 464: kerberos") if options.setup_dns: print("\t\t * 53: bind") print("\t\tUDP Ports:") print("\t\t * 88, 464: kerberos") if options.setup_dns: print("\t\t * 53: bind") if not options.no_ntp: print("\t\t * 123: ntp") print("") print("\t2. You can now obtain a kerberos ticket using the command: " "'kinit admin'") print("\t This ticket will allow you to use the IPA tools (e.g., ipa " "user-add)") print("\t and the web user interface.") if not services.knownservices.ntpd.is_running(): print("\t3. Kerberos requires time synchronization between clients") print("\t and servers for correct operation. You should consider " "enabling ntpd.") print("") if setup_ca: print(("Be sure to back up the CA certificates stored in " + paths.CACERT_P12)) print("These files are required to create replicas. The password for " "these") print("files is the Directory Manager password") else: print( "In order for Firefox autoconfiguration to work you will need to") print("use a SSL signing certificate. See the IPA documentation for " "more details.") if ipautil.file_exists(paths.ROOT_IPA_CACHE): os.remove(paths.ROOT_IPA_CACHE)
def install_step_0(standalone, replica_config, options): realm_name = options.realm_name dm_password = options.dm_password host_name = options.host_name if replica_config is None: subject_base = options.subject ca_signing_algorithm = options.ca_signing_algorithm if options.external_ca: ca_type = options.external_ca_type csr_file = paths.ROOT_IPA_CSR else: ca_type = None csr_file = None if options.external_cert_files: cert_file = external_cert_file.name cert_chain_file = external_ca_file.name else: cert_file = None cert_chain_file = None pkcs12_info = None master_host = None master_replication_port = None ra_p12 = None ra_only = False promote = False else: cafile = os.path.join(replica_config.dir, 'cacert.p12') if options.promote: custodia = custodiainstance.CustodiaInstance( replica_config.host_name, replica_config.realm_name) custodia.get_ca_keys(replica_config.ca_host_name, cafile, replica_config.dirman_password) subject_base = replica_config.subject_base ca_signing_algorithm = None ca_type = None csr_file = None cert_file = None cert_chain_file = None pkcs12_info = (cafile, ) master_host = replica_config.ca_host_name master_replication_port = replica_config.ca_ds_port ra_p12 = os.path.join(replica_config.dir, 'ra.p12') ra_only = not replica_config.setup_ca promote = options.promote ca = cainstance.CAInstance(realm_name, certs.NSS_DIR, host_name=host_name) ca.configure_instance(host_name, dm_password, dm_password, subject_base=subject_base, ca_signing_algorithm=ca_signing_algorithm, ca_type=ca_type, csr_file=csr_file, cert_file=cert_file, cert_chain_file=cert_chain_file, pkcs12_info=pkcs12_info, master_host=master_host, master_replication_port=master_replication_port, ra_p12=ra_p12, ra_only=ra_only, promote=promote, use_ldaps=standalone)
def uninstall(): ca_instance = cainstance.CAInstance(api.env.realm, certs.NSS_DIR) ca_instance.stop_tracking_certificates() if ca_instance.is_configured(): ca_instance.uninstall()
def run(self): if not is_ipa_configured(): print("IPA is not configured.") return 2 if not cainstance.is_ca_installed_locally(): print("CA is not installed on this server.") return 1 try: ipautil.run(['pki-server', 'cert-fix', '--help'], raiseonerr=True) except ipautil.CalledProcessError: print( "The 'pki-server cert-fix' command is not available; " "cannot proceed." ) return 1 api.bootstrap(in_server=True, confdir=paths.ETC_IPA) api.finalize() api.Backend.ldap2.connect() # ensure DS is up subject_base = dsinstance.DsInstance().find_subject_base() if not subject_base: raise RuntimeError("Cannot determine certificate subject base.") ca_subject_dn = ca.lookup_ca_subject(api, subject_base) now = datetime.datetime.now() + datetime.timedelta(weeks=2) certs, extra_certs = expired_certs(now) if not certs and not extra_certs: print("Nothing to do.") return 0 print(msg) print_intentions(certs, extra_certs) response = ipautil.user_input('Enter "yes" to proceed') if response.lower() != 'yes': print("Not proceeding.") return 0 print("Proceeding.") try: run_cert_fix(certs, extra_certs) except ipautil.CalledProcessError: if any(x[0] is IPACertType.LDAPS for x in extra_certs): # The DS cert was expired. This will cause # 'pki-server cert-fix' to fail at the final # restart. Therefore ignore the CalledProcessError # and proceed to installing the IPA-specific certs. pass else: raise # otherwise re-raise replicate_dogtag_certs(subject_base, ca_subject_dn, certs) install_ipa_certs(subject_base, ca_subject_dn, extra_certs) if any(x[0] != 'sslserver' for x in certs) \ or any(x[0] is IPACertType.IPARA for x in extra_certs): # we renewed a "shared" certificate, therefore we must # become the renewal master print("Becoming renewal master.") cainstance.CAInstance().set_renewal_master() ipautil.run(['ipactl', 'restart'], raiseonerr=True) return 0
def configure_instance(self, realm_name, host_name, dm_password, admin_password, pkcs12_info=None, master_host=None, subject_base=None, subject=None, promote=False): """Create a KRA instance. To create a clone, pass in pkcs12_info. """ self.fqdn = host_name self.dm_password = dm_password self.admin_groups = ADMIN_GROUPS self.admin_password = admin_password self.pkcs12_info = pkcs12_info if self.pkcs12_info is not None or promote: self.clone = True self.master_host = master_host self.subject_base = \ subject_base or installutils.default_subject_base(realm_name) self.subject = \ subject or installutils.default_ca_subject_dn(self.subject_base) self.realm = realm_name self.suffix = ipautil.realm_to_suffix(realm_name) # Confirm that a KRA does not already exist if self.is_installed(): raise RuntimeError("KRA already installed.") # Confirm that a Dogtag 10 CA instance already exists ca = cainstance.CAInstance(self.realm) if not ca.is_installed(): raise RuntimeError("KRA configuration failed. " "A Dogtag CA must be installed first") if promote: self.step("creating ACIs for admin", self.add_ipaca_aci) self.step("creating installation admin user", self.setup_admin) self.step("configuring KRA instance", self.__spawn_instance) if not self.clone: self.step("create KRA agent", self.__create_kra_agent) if promote: self.step("destroying installation admin user", self.teardown_admin) self.step("enabling ephemeral requests", self.enable_ephemeral) self.step("restarting KRA", self.restart_instance) self.step("configure certmonger for renewals", self.configure_certmonger_renewal) self.step("configure certificate renewals", self.configure_renewal) self.step("configure HTTP to proxy connections", self.http_proxy) if not self.clone: self.step("add vault container", self.__add_vault_container) self.step("apply LDAP updates", self.__apply_updates) self.step("enabling KRA instance", self.__enable_instance) try: self.start_creation(runtime=120) finally: self.clean_pkispawn_files()
def run(self): if not is_ipa_configured(): print("IPA is not configured.") return 2 if not cainstance.is_ca_installed_locally(): print("CA is not installed on this server.") return 1 try: ipautil.run(['pki-server', 'cert-fix', '--help'], raiseonerr=True) except ipautil.CalledProcessError: print("The 'pki-server cert-fix' command is not available; " "cannot proceed.") return 1 api.bootstrap(in_server=True, confdir=paths.ETC_IPA) api.finalize() if not dsinstance.is_ds_running(realm_to_serverid(api.env.realm)): print("The LDAP server is not running; cannot proceed.") return 1 api.Backend.ldap2.connect() # ensure DS is up subject_base = dsinstance.DsInstance().find_subject_base() if not subject_base: raise RuntimeError("Cannot determine certificate subject base.") ca_subject_dn = ca.lookup_ca_subject(api, subject_base) now = datetime.datetime.now() + datetime.timedelta(weeks=2) certs, extra_certs, non_renewed = expired_certs(now) if not certs and not extra_certs: print("Nothing to do.") return 0 print(msg) print_intentions(certs, extra_certs, non_renewed) response = ipautil.user_input('Enter "yes" to proceed') if response.lower() != 'yes': print("Not proceeding.") return 0 print("Proceeding.") try: fix_certreq_directives(certs) run_cert_fix(certs, extra_certs) except ipautil.CalledProcessError: if any(x[0] is IPACertType.LDAPS for x in extra_certs + non_renewed): # The DS cert was expired. This will cause 'pki-server # cert-fix' to fail at the final restart, and return nonzero. # So this exception *might* be OK to ignore. # # If 'pki-server cert-fix' has written new certificates # corresponding to all the extra_certs, then ignore the # CalledProcessError and proceed to installing the IPA-specific # certs. Otherwise re-raise. if check_renewed_ipa_certs(extra_certs): pass else: raise else: raise # otherwise re-raise replicate_dogtag_certs(subject_base, ca_subject_dn, certs) install_ipa_certs(subject_base, ca_subject_dn, extra_certs) if any(x[0] != 'sslserver' for x in certs) \ or any(x[0] is IPACertType.IPARA for x in extra_certs): # we renewed a "shared" certificate, therefore we must # become the renewal master print("Becoming renewal master.") cainstance.CAInstance().set_renewal_master() print("Restarting IPA") ipautil.run(['ipactl', 'restart'], raiseonerr=True) print(renewal_note) return 0