def setUp(self): fqdn = installutils.get_fqdn() pwfile = api.env.dot_ipa + os.sep + ".dmpw" if ipautil.file_exists(pwfile): fp = open(pwfile, "r") self.dm_password = fp.read().rstrip() fp.close() else: raise nose.SkipTest("No directory manager password") self.updater = LDAPUpdate(dm_password=self.dm_password, sub_dict={}, live_run=True) self.ld = ipaldap.IPAdmin(fqdn) self.ld.do_simple_bind(bindpw=self.dm_password) if ipautil.file_exists("0_reset.update"): self.testdir = "./" elif ipautil.file_exists("tests/test_install/0_reset.update"): self.testdir = "./tests/test_install/" else: raise nose.SkipTest("Unable to find test update files") self.container_dn = DN( self.updater._template_str('cn=test, cn=accounts, $SUFFIX')) self.user_dn = DN( self.updater._template_str( 'uid=tuser, cn=test, cn=accounts, $SUFFIX'))
def install_http(config, auto_redirect): # if we have a pkcs12 file, create the cert db from # that. Otherwise the ds setup will create the CA # cert pkcs12_info = make_pkcs12_info(config.dir, "httpcert.p12", "http_pin.txt") memcache = memcacheinstance.MemcacheInstance() memcache.create_instance('MEMCACHE', config.host_name, config.dirman_password, ipautil.realm_to_suffix(config.realm_name)) http = httpinstance.HTTPInstance() http.create_instance( config.realm_name, config.host_name, config.domain_name, config.dirman_password, False, pkcs12_info, auto_redirect=auto_redirect, ca_file=config.dir + "/ca.crt", ca_is_configured=ipautil.file_exists(config.dir + "/cacert.p12")) # Now copy the autoconfiguration files try: if ipautil.file_exists(config.dir + "/preferences.html"): shutil.copy(config.dir + "/preferences.html", paths.PREFERENCES_HTML) if ipautil.file_exists(config.dir + "/configure.jar"): shutil.copy(config.dir + "/configure.jar", paths.CONFIGURE_JAR) except Exception, e: print "error copying files: " + str(e) sys.exit(1)
def setup(self): nss.nss_init_nodb() if ipautil.file_exists("test0.csr"): self.testdir="./" elif ipautil.file_exists("ipatests/test_pkcs10/test0.csr"): self.testdir= "./ipatests/test_pkcs10/" else: raise nose.SkipTest("Unable to find test update files")
def copy_misc_files(self): self.log.info("Copying additional files") self.copy_info_file(CACERT, "ca.crt") preferences_filename = paths.PREFERENCES_HTML if ipautil.file_exists(preferences_filename): self.copy_info_file(preferences_filename, "preferences.html") jar_filename = paths.CONFIGURE_JAR if ipautil.file_exists(jar_filename): self.copy_info_file(jar_filename, "configure.jar") cacert_filename = paths.CACERT_PEM if ipautil.file_exists(cacert_filename): self.copy_info_file(cacert_filename, "cacert.pem") self.copy_info_file(paths.IPA_DEFAULT_CONF, "default.conf")
def copy_ds_certificate(self): options = self.options passwd_fname = os.path.join(self.dir, "dirsrv_pin.txt") with open(passwd_fname, "w") as fd: fd.write("%s\n" % (self.dirsrv_pin or '')) if options.dirsrv_cert_files: logger.info("Copying SSL certificate for the Directory Server") self.copy_info_file(self.dirsrv_pkcs12_file.name, "dscert.p12") else: if ipautil.file_exists(options.ca_file): # Since it is possible that the Directory Manager password # has changed since ipa-server-install, we need to regenerate # the CA PKCS#12 file and update the pki admin user password self.regenerate_ca_file(options.ca_file) self.update_pki_admin_password() self.copy_info_file(options.ca_file, "cacert.p12") else: raise admintool.ScriptError("Root CA PKCS#12 not " "found in %s" % options.ca_file) logger.info("Creating SSL certificate for the Directory Server") self.export_certdb("dscert", passwd_fname) if not options.dirsrv_cert_files: logger.info( "Creating SSL certificate for the dogtag Directory Server") self.export_certdb("dogtagcert", passwd_fname) logger.info("Saving dogtag Directory Server port") port_fname = os.path.join(self.dir, "dogtag_directory_port.txt") with open(port_fname, "w") as fd: fd.write("389\n")
def copy_misc_files(self): logger.info("Copying additional files") cacert_filename = paths.CACERT_PEM if ipautil.file_exists(cacert_filename): self.copy_info_file(cacert_filename, "cacert.pem") self.copy_info_file(paths.IPA_DEFAULT_CONF, "default.conf")
def __del__(self): if self.temporary: shutil.rmtree(self.secdir) else: # clean up if ipautil.file_exists(self.noise_file): os.remove(self.noise_file)
def __create_instance(self): pent = pwd.getpwnam(DS_USER) self.backup_state("serverid", self.serverid) self.fstore.backup_file("/etc/sysconfig/dirsrv") self.sub_dict['BASEDC'] = self.realm.split('.')[0].lower() base_txt = ipautil.template_str(BASE_TEMPLATE, self.sub_dict) root_logger.debug(base_txt) target_fname = '/var/lib/dirsrv/boot.ldif' base_fd = open(target_fname, "w") base_fd.write(base_txt) base_fd.close() # Must be readable for dirsrv os.chmod(target_fname, 0440) os.chown(target_fname, pent.pw_uid, pent.pw_gid) inf_txt = ipautil.template_str(INF_TEMPLATE, self.sub_dict) root_logger.debug("writing inf template") inf_fd = ipautil.write_tmp_file(inf_txt) inf_txt = re.sub(r"RootDNPwd=.*\n", "", inf_txt) root_logger.debug(inf_txt) if ipautil.file_exists("/usr/sbin/setup-ds.pl"): args = ["/usr/sbin/setup-ds.pl", "--silent", "--logfile", "-", "-f", inf_fd.name] root_logger.debug("calling setup-ds.pl") else: args = ["/usr/bin/ds_newinst.pl", inf_fd.name] root_logger.debug("calling ds_newinst.pl") try: ipautil.run(args) root_logger.debug("completed creating ds instance") except ipautil.CalledProcessError, e: root_logger.critical("failed to create ds instance %s" % e)
def copy_misc_files(self): self.log.info("Copying additional files") self.copy_info_file("/etc/ipa/ca.crt", "ca.crt") preferences_filename = "/usr/share/ipa/html/preferences.html" if ipautil.file_exists(preferences_filename): self.copy_info_file(preferences_filename, "preferences.html") self.copy_info_file("/usr/share/ipa/html/krb.js", "krb.js") self.copy_info_file( "/usr/share/ipa/html/kerberosauth.xpi", "kerberosauth.xpi") jar_filename = "/usr/share/ipa/html/configure.jar" if ipautil.file_exists(jar_filename): self.copy_info_file(jar_filename, "configure.jar") cacert_filename = "/var/kerberos/krb5kdc/cacert.pem" if ipautil.file_exists(cacert_filename): self.copy_info_file(cacert_filename, "cacert.pem")
def install_check(options): global dirsrv_pkcs12_info global http_pkcs12_info global pkinit_pkcs12_info global external_cert_file global external_ca_file global http_ca_cert global ds global installation_cleanup # Use private ccache init_private_ccache() ds = None tasks.check_selinux_status() if options.master_password: msg = ("WARNING:\noption '-P/--master-password' is deprecated. " "KDC master password of sufficient strength is autogenerated " "during IPA server installation and should not be set " "manually.") print textwrap.fill(msg, width=79, replace_whitespace=False) installation_cleanup = True print("\nThe log file for this installation can be found in " "/var/log/ipaserver-install.log") if (not options.external_ca and not options.external_cert_files and is_ipa_configured()): installation_cleanup = False sys.exit("IPA server is already configured on this system.\n" "If you want to reinstall the IPA server, please uninstall " "it first using 'ipa-server-install --uninstall'.") client_fstore = sysrestore.FileStore(paths.IPA_CLIENT_SYSRESTORE) if client_fstore.has_files(): installation_cleanup = False sys.exit("IPA client is already configured on this system.\n" "Please uninstall it before configuring the IPA server, " "using 'ipa-client-install --uninstall'") global fstore fstore = sysrestore.FileStore(SYSRESTORE_DIR_PATH) global sstore sstore = sysrestore.StateFile(SYSRESTORE_DIR_PATH) # This will override any settings passed in on the cmdline if ipautil.file_exists(paths.ROOT_IPA_CACHE): if options.dm_password is not None: dm_password = options.dm_password else: dm_password = read_password("Directory Manager", confirm=False) if dm_password is None: sys.exit("Directory Manager password required") try: options._update_loose(read_cache(dm_password)) except Exception, e: sys.exit("Cannot process the cache file: %s" % str(e))
def validate_options(self, needs_root=True): super(KRAInstaller, self).validate_options(needs_root=True) if self.options.unattended and self.options.password is None: self.option_parser.error( "Directory Manager password must be specified using -p" " in unattended mode" ) self.installing_replica = dogtaginstance.is_installing_replica("KRA") if self.installing_replica: if not self.args: self.option_parser.error("A replica file is required.") if len(self.args) > 1: self.option_parser.error("Too many arguments provided") self.replica_file = self.args[0] if not ipautil.file_exists(self.replica_file): self.option_parser.error( "Replica file %s does not exist" % self.replica_file) else: if self.args: self.option_parser.error("Too many parameters provided. " "No replica file is required.")
def test_Backend(self): """ Test using the ldap2 Backend directly (ala ipa-server-install) """ # Create our own api because the one generated for the tests is # a client-only api. Then we register in the commands and objects # we need for the test. myapi = create_api(mode=None) myapi.bootstrap(context='cli', in_server=True, in_tree=True) myapi.register(ldap2) myapi.register(host) myapi.register(service) myapi.register(service_show) myapi.finalize() pwfile = api.env.dot_ipa + os.sep + ".dmpw" if ipautil.file_exists(pwfile): fp = open(pwfile, "r") dm_password = fp.read().rstrip() fp.close() else: raise nose.SkipTest("No directory manager password in %s" % pwfile) myapi.Backend.ldap2.connect(bind_dn=DN(('cn', 'Directory Manager')), bind_pw=dm_password) result = myapi.Command['service_show']('ldap/%s@%s' % (api.env.host, api.env.realm,)) entry_attrs = result['result'] cert = entry_attrs.get('usercertificate') cert = cert[0] serial = unicode(x509.get_serial_number(cert, x509.DER)) assert serial is not None
def next_serial(serial_file=CA_SERIALNO): """ Get the next serial number if we're using an NSS-based self-signed CA. The file is an ini-like file with following properties: lastvalue = the last serial number handed out nextreplica = the serial number the next replica should start with replicainterval = the number to add to nextreplica the next time a replica is created File locking is attempted so we have unique serial numbers. """ fp = None parser = RawConfigParser() if ipautil.file_exists(serial_file): try: fp = open(serial_file, "r+") fcntl.flock(fp.fileno(), fcntl.LOCK_EX) parser.readfp(fp) serial = parser.getint('selfsign', 'lastvalue') cur_serial = serial + 1 except IOError, e: raise RuntimeError("Unable to determine serial number: %s" % str(e)) except MissingSectionHeaderError: fcntl.flock(fp.fileno(), fcntl.LOCK_UN) fp.close() f=open(serial_file,"r") r = f.readline() f.close() cur_serial = int(r) + 1 fp = open(serial_file, "w") fcntl.flock(fp.fileno(), fcntl.LOCK_EX) parser.add_section('selfsign') parser.set('selfsign', 'nextreplica', 500000) parser.set('selfsign', 'replicainterval', 500000)
def test_Backend(self): """ Test using the ldap2 Backend directly (ala ipa-server-install) """ # Create our own api because the one generated for the tests is # a client-only api. Then we register in the commands and objects # we need for the test. myapi = create_api(mode=None) myapi.bootstrap(context='cli', in_server=True, in_tree=True) myapi.register(ldap2) myapi.register(host) myapi.register(service) myapi.register(service_show) myapi.finalize() pwfile = api.env.dot_ipa + os.sep + ".dmpw" if ipautil.file_exists(pwfile): fp = open(pwfile, "r") dm_password = fp.read().rstrip() fp.close() else: raise nose.SkipTest("No directory manager password in %s" % pwfile) myapi.Backend.ldap2.connect(bind_dn=DN(('cn', 'Directory Manager')), bind_pw=dm_password) result = myapi.Command['service_show']('ldap/%s@%s' % ( api.env.host, api.env.realm, )) entry_attrs = result['result'] cert = entry_attrs.get('usercertificate') cert = cert[0] serial = unicode(x509.get_serial_number(cert, x509.DER)) assert serial is not None
def __create_instance(self): pent = pwd.getpwnam(DS_USER) self.backup_state("serverid", self.serverid) self.fstore.backup_file(paths.SYSCONFIG_DIRSRV) self.sub_dict['BASEDC'] = self.realm.split('.')[0].lower() base_txt = ipautil.template_str(BASE_TEMPLATE, self.sub_dict) root_logger.debug(base_txt) target_fname = paths.DIRSRV_BOOT_LDIF base_fd = open(target_fname, "w") base_fd.write(base_txt) base_fd.close() # Must be readable for dirsrv os.chmod(target_fname, 0440) os.chown(target_fname, pent.pw_uid, pent.pw_gid) inf_txt = ipautil.template_str(INF_TEMPLATE, self.sub_dict) root_logger.debug("writing inf template") inf_fd = ipautil.write_tmp_file(inf_txt) inf_txt = re.sub(r"RootDNPwd=.*\n", "", inf_txt) root_logger.debug(inf_txt) if ipautil.file_exists(paths.SETUP_DS_PL): args = [paths.SETUP_DS_PL, "--silent", "--logfile", "-", "-f", inf_fd.name] root_logger.debug("calling setup-ds.pl") else: args = [paths.DS_NEWINST_PL, inf_fd.name] root_logger.debug("calling ds_newinst.pl") try: ipautil.run(args) root_logger.debug("completed creating ds instance") except ipautil.CalledProcessError, e: root_logger.critical("failed to create ds instance %s" % e)
def copy_ds_certificate(self): options = self.options passwd_fname = os.path.join(self.dir, "dirsrv_pin.txt") with open(passwd_fname, "w") as fd: fd.write("%s\n" % (self.dirsrv_pin or '')) if options.dirsrv_cert_files: self.log.info("Copying SSL certificate for the Directory Server") self.copy_info_file(self.dirsrv_pkcs12_file.name, "dscert.p12") else: if ipautil.file_exists(options.ca_file): # Since it is possible that the Directory Manager password # has changed since ipa-server-install, we need to regenerate # the CA PKCS#12 file and update the pki admin user password self.regenerate_ca_file(options.ca_file) self.update_pki_admin_password() self.copy_info_file(options.ca_file, "cacert.p12") else: raise admintool.ScriptError("Root CA PKCS#12 not " "found in %s" % options.ca_file) self.log.info( "Creating SSL certificate for the Directory Server") self.export_certdb("dscert", passwd_fname) if not options.dirsrv_cert_files: self.log.info( "Creating SSL certificate for the dogtag Directory Server") self.export_certdb("dogtagcert", passwd_fname) self.log.info("Saving dogtag Directory Server port") port_fname = os.path.join( self.dir, "dogtag_directory_port.txt") with open(port_fname, "w") as fd: fd.write("%s\n" % str(dogtag.configured_constants().DS_PORT))
def create_keytab(path, principal): try: if ipautil.file_exists(path): os.remove(path) except os.error: root_logger.critical("Failed to remove %s." % path) kadmin("ktadd -k " + path + " " + principal)
def __init__(self, **kwargs): super(Replica, self).__init__(**kwargs) self._top_dir = None self._config = None # pylint: disable=no-member if self.replica_file is None: raise RuntimeError("you must provide a file generated by ipa-replica-prepare") if not ipautil.file_exists(self.replica_file): raise RuntimeError("Replica file %s does not exist" % self.replica_file) if not self.dns.setup_dns: if self.dns.forwarders: raise RuntimeError("You cannot specify a --forwarder option without the " "--setup-dns option") if self.dns.no_forwarders: raise RuntimeError("You cannot specify a --no-forwarders option without the " "--setup-dns option") if self.dns.reverse_zones: raise RuntimeError("You cannot specify a --reverse-zone option without the " "--setup-dns option") if self.dns.no_reverse: raise RuntimeError("You cannot specify a --no-reverse option without the " "--setup-dns option") if self.dns.no_dnssec_validation: raise RuntimeError( "You cannot specify a --no-dnssec-validation option " "without the --setup-dns option" ) elif self.dns.forwarders and self.dns.no_forwarders: raise RuntimeError("You cannot specify a --forwarder option together with " "--no-forwarders") elif not self.dns.forwarders and not self.dns.no_forwarders: raise RuntimeError("You must specify at least one --forwarder option or " "--no-forwarders option") elif self.dns.reverse_zones and self.dns.no_reverse: raise RuntimeError("You cannot specify a --reverse-zone option together with " "--no-reverse") # Automatically disable pkinit w/ dogtag until that is supported self.ca.no_pkinit = True self.external_ca = False self.external_cert_files = None self.no_pkinit = self.ca.no_pkinit self.skip_schema_check = self.ca.skip_schema_check self.setup_dns = self.dns.setup_dns self.forwarders = self.dns.forwarders self.no_forwarders = self.dns.no_forwarders self.reverse_zones = self.dns.reverse_zones self.no_reverse = self.dns.no_reverse self.no_dnssec_validation = self.dns.no_dnssec_validation self.dnssec_master = self.dns.dnssec_master self.disable_dnssec_master = self.dns.disable_dnssec_master self.kasp_db_file = self.dns.kasp_db_file self.force = self.dns.force self.zonemgr = None self.no_host_dns = self.dns.no_host_dns self.no_dns_sshfp = self.dns.no_dns_sshfp self.unattended = not self.interactive
def install(api, replica_config, options): if replica_config is None: 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 ra_only = False promote = False else: krafile = os.path.join(replica_config.dir, 'kracert.p12') if options.promote: 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 ra_only = not replica_config.setup_kra 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, ra_only=ra_only, promote=promote) _service.print_msg("Restarting the directory server") ds = dsinstance.DsInstance() ds.restart() if not ra_only: 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 install(api, replica_config, options): if replica_config is None: 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 ra_only = False promote = False else: krafile = os.path.join(replica_config.dir, 'kracert.p12') if options.promote: 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 ra_only = not replica_config.setup_kra 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, ra_only=ra_only, promote=promote) _service.print_msg("Restarting the directory server") ds = dsinstance.DsInstance() ds.restart() if not ra_only: 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 setUp(self): fqdn = installutils.get_fqdn() pwfile = api.env.dot_ipa + os.sep + ".dmpw" if ipautil.file_exists(pwfile): fp = open(pwfile, "r") self.dm_password = fp.read().rstrip() fp.close() else: raise nose.SkipTest("No directory manager password") self.updater = LDAPUpdate(dm_password=self.dm_password, sub_dict={}) self.ld = ipaldap.IPAdmin(fqdn) self.ld.do_simple_bind(bindpw=self.dm_password) self.testdir = os.path.abspath(os.path.dirname(__file__)) if not ipautil.file_exists(os.path.join(self.testdir, "0_reset.update")): raise nose.SkipTest("Unable to find test update files") self.container_dn = DN(self.updater._template_str('cn=test, cn=accounts, $SUFFIX')) self.user_dn = DN(self.updater._template_str('uid=tuser, cn=test, cn=accounts, $SUFFIX'))
def is_db_configured(): """ Raise an exception if we are testing against lite-server and the developer cert database is configured. """ aliasdir = api.env.dot_ipa + os.sep + 'alias' + os.sep + '.pwd' if (api.env.xmlrpc_uri == u'http://localhost:8888/ipa/xml' and not ipautil.file_exists(aliasdir)): raise nose.SkipTest('developer CA not configured in %s' % aliasdir)
def setup(self): self.tmp_dir = None self.saved_lang = None self.lang = 'xh_ZA' self.domain = 'ipa' self.ipa_i18n_dir = os.path.join(os.path.dirname(__file__), '../../install/po') self.pot_basename = '%s.pot' % self.domain self.po_basename = '%s.po' % self.lang self.mo_basename = '%s.mo' % self.domain self.tmp_dir = tempfile.mkdtemp() self.saved_lang = os.environ['LANG'] self.locale_dir = os.path.join(self.tmp_dir, 'test_locale') self.msg_dir = os.path.join(self.locale_dir, self.lang, 'LC_MESSAGES') if not os.path.exists(self.msg_dir): os.makedirs(self.msg_dir) self.pot_file = os.path.join(self.ipa_i18n_dir, self.pot_basename) self.mo_file = os.path.join(self.msg_dir, self.mo_basename) self.po_file = os.path.join(self.tmp_dir, self.po_basename) result = create_po(self.pot_file, self.po_file, self.mo_file) if result: raise nose.SkipTest( 'Unable to create po file "%s" & mo file "%s" from pot file "%s"' % (self.po_file, self.mo_file, self.pot_file)) if not file_exists(self.po_file): raise nose.SkipTest( 'Test po file unavailable, run "make test" in install/po') if not file_exists(self.mo_file): raise nose.SkipTest( 'Test mo file unavailable, run "make test" in install/po') self.po_file_iterate = po_file_iterate
def uninstall(self): if not self.is_configured(): return self.print_msg("Unconfiguring %s" % self.service_name) running = self.restore_state("running") enabled = self.restore_state("enabled") # stop DNSSEC services before backing up kasp.db try: self.stop() except Exception: pass ods_exporter = services.service('ipa-ods-exporter') try: ods_exporter.stop() except Exception: pass # remove directive from ipa-dnskeysyncd, this server is not DNSSEC # master anymore installutils.set_directive(paths.SYSCONFIG_IPA_DNSKEYSYNCD, 'ISMASTER', None, quotes=False, separator='=') if ipautil.file_exists(paths.OPENDNSSEC_KASP_DB): # force to export data ods_enforcerd = services.knownservices.ods_enforcerd cmd = [paths.IPA_ODS_EXPORTER, 'ipa-full-update'] try: ipautil.run(cmd, runas=ods_enforcerd.get_user_name()) except CalledProcessError: root_logger.debug("OpenDNSSEC database has not been updated") try: shutil.copy(paths.OPENDNSSEC_KASP_DB, paths.IPA_KASP_DB_BACKUP) except IOError as e: root_logger.error( "Unable to backup OpenDNSSEC database: %s", e) else: root_logger.info("OpenDNSSEC database backed up in %s", paths.IPA_KASP_DB_BACKUP) for f in [paths.OPENDNSSEC_CONF_FILE, paths.OPENDNSSEC_KASP_FILE, paths.OPENDNSSEC_KASP_DB, paths.SYSCONFIG_ODS]: try: self.fstore.restore_file(f) except ValueError, error: root_logger.debug(error) pass
def validate_options(self, needs_root=True): super(KRAInstaller, self).validate_options(needs_root=True) if self.options.unattended and self.options.password is None: self.option_parser.error("Directory Manager password must be specified using -p" " in unattended mode") if len(self.args) > 1: self.option_parser.error("Too many arguments provided") elif len(self.args) == 1: self.replica_file = self.args[0] if not ipautil.file_exists(self.replica_file): self.option_parser.error("Replica file %s does not exist" % self.replica_file)
def create_noise_file(self): """ Generate a noise file to be used when creating a key """ if ipautil.file_exists(self.noise_file): os.remove(self.noise_file) f = open(self.noise_file, "w") f.write(self.generate_random()) f.close() return
def setUp(self): # raise an error if the command is missing even if the remote # server is not available. if not ipautil.file_exists(self.command): raise AssertionError( 'Command %r not available' % self.command ) super(cmdline_test, self).setUp() if not server_available: raise nose.SkipTest( 'Server not available: %r' % api.env.xmlrpc_uri )
def export_certdb(self, fname, passwd_fname, is_kdc=False): """Export a cert database :param fname: The file to export to (relative to the info directory) :param passwd_fname: File that holds the cert DB password :param is_kdc: True if we're exporting KDC certs """ options = self.options hostname = self.replica_fqdn subject_base = self.subject_base if is_kdc: nickname = "KDC-Cert" else: nickname = "Server-Cert" try: db = certs.CertDB( api.env.realm, nssdir=self.dir, subject_base=subject_base) db.create_passwd_file() ca_db = certs.CertDB( api.env.realm, host_name=api.env.host, subject_base=subject_base) db.create_from_cacert(ca_db.cacert_fname) db.create_server_cert(nickname, hostname, ca_db) pkcs12_fname = os.path.join(self.dir, fname + ".p12") try: if is_kdc: ca_db.export_pem_p12(pkcs12_fname, passwd_fname, nickname, os.path.join(self.dir, "kdc.pem")) else: db.export_pkcs12(pkcs12_fname, passwd_fname, nickname) except ipautil.CalledProcessError as e: self.log.info("error exporting Server certificate: %s", e) installutils.remove_file(pkcs12_fname) installutils.remove_file(passwd_fname) self.remove_info_file("cert8.db") self.remove_info_file("key3.db") self.remove_info_file("secmod.db") self.remove_info_file("noise.txt") if is_kdc: self.remove_info_file("kdc.pem") orig_filename = passwd_fname + ".orig" if ipautil.file_exists(orig_filename): installutils.remove_file(orig_filename) except errors.CertificateOperationError as e: raise admintool.ScriptError(str(e))
def export_certdb(self, fname, passwd_fname, is_kdc=False): """Export a cert database :param fname: The file to export to (relative to the info directory) :param passwd_fname: File that holds the cert DB password :param is_kdc: True if we're exporting KDC certs """ hostname = self.replica_fqdn subject_base = self.subject_base if is_kdc: nickname = "KDC-Cert" else: nickname = "Server-Cert" try: db = certs.CertDB(api.env.realm, nssdir=self.dir, subject_base=subject_base) db.create_passwd_file() ca_db = certs.CertDB(api.env.realm, host_name=api.env.host, subject_base=subject_base) db.create_from_cacert() db.create_server_cert(nickname, hostname, ca_db) pkcs12_fname = os.path.join(self.dir, fname + ".p12") try: if is_kdc: ca_db.export_pem_p12(pkcs12_fname, passwd_fname, nickname, os.path.join(self.dir, "kdc.pem")) else: db.export_pkcs12(pkcs12_fname, passwd_fname, nickname) except ipautil.CalledProcessError as e: self.log.info("error exporting Server certificate: %s", e) installutils.remove_file(pkcs12_fname) installutils.remove_file(passwd_fname) self.remove_info_file("cert8.db") self.remove_info_file("key3.db") self.remove_info_file("secmod.db") self.remove_info_file("noise.txt") if is_kdc: self.remove_info_file("kdc.pem") orig_filename = passwd_fname + ".orig" if ipautil.file_exists(orig_filename): installutils.remove_file(orig_filename) except errors.CertificateOperationError as e: raise admintool.ScriptError(str(e))
def __setup_ssl(self): fqdn = None if not self.self_signed_ca: fqdn = self.fqdn ca_db = certs.CertDB(self.realm, host_name=fqdn, subject_base=self.subject_base) db = certs.CertDB(self.realm, subject_base=self.subject_base) if self.pkcs12_info: db.create_from_pkcs12(self.pkcs12_info[0], self.pkcs12_info[1], passwd=None) server_certs = db.find_server_certs() if len(server_certs) == 0: raise RuntimeError("Could not find a suitable server cert in import in %s" % self.pkcs12_info[0]) db.create_password_conf() # We only handle one server cert nickname = server_certs[0][0] self.dercert = db.get_cert_from_db(nickname, pem=False) db.track_server_cert(nickname, self.principal, db.passwd_fname, 'restart_httpd') self.__set_mod_nss_nickname(nickname) else: if self.self_signed_ca: db.create_from_cacert(ca_db.cacert_fname) db.create_password_conf() self.dercert = db.create_server_cert("Server-Cert", self.fqdn, ca_db) db.track_server_cert("Server-Cert", self.principal, db.passwd_fname, 'restart_httpd') db.create_signing_cert("Signing-Cert", "Object Signing Cert", ca_db) # Fix the database permissions os.chmod(certs.NSS_DIR + "/cert8.db", 0660) os.chmod(certs.NSS_DIR + "/key3.db", 0660) os.chmod(certs.NSS_DIR + "/secmod.db", 0660) os.chmod(certs.NSS_DIR + "/pwdfile.txt", 0660) pent = pwd.getpwnam("apache") os.chown(certs.NSS_DIR + "/cert8.db", 0, pent.pw_gid ) os.chown(certs.NSS_DIR + "/key3.db", 0, pent.pw_gid ) os.chown(certs.NSS_DIR + "/secmod.db", 0, pent.pw_gid ) os.chown(certs.NSS_DIR + "/pwdfile.txt", 0, pent.pw_gid ) # Fix SELinux permissions on the database ipaservices.restore_context(certs.NSS_DIR + "/cert8.db") ipaservices.restore_context(certs.NSS_DIR + "/key3.db") # In case this got generated as part of the install, reset the # context if ipautil.file_exists(certs.CA_SERIALNO): ipaservices.restore_context(certs.CA_SERIALNO) os.chown(certs.CA_SERIALNO, 0, pent.pw_gid) os.chmod(certs.CA_SERIALNO, 0664)
def test_GSSAPI(self): """ Test a GSSAPI LDAP bind using ldap2 """ if not ipautil.file_exists(self.ccache): raise nose.SkipTest('Missing ccache %s' % self.ccache) self.conn = ldap2(shared_instance=False, ldap_uri=self.ldapuri) self.conn.connect(ccache='FILE:%s' % self.ccache) (dn, entry_attrs) = self.conn.get_entry(self.dn, ['usercertificate']) cert = entry_attrs.get('usercertificate') cert = cert[0] serial = unicode(x509.get_serial_number(cert, x509.DER)) assert serial is not None
def read_replica_info_dogtag_port(config_dir): portfile = config_dir + "/dogtag_directory_port.txt" default_port = dogtag.Dogtag9Constants.DS_PORT if not ipautil.file_exists(portfile): dogtag_master_ds_port = default_port else: with open(portfile) as fd: try: dogtag_master_ds_port = int(fd.read()) except (ValueError, IOError), e: root_logger.debug('Cannot parse dogtag DS port: %s', e) root_logger.debug('Default to %d', default_port) dogtag_master_ds_port = default_port
def test_GSSAPI(self): """ Test a GSSAPI LDAP bind using ldap2 """ if not ipautil.file_exists(self.ccache): raise nose.SkipTest("Missing ccache %s" % self.ccache) self.conn = ldap2(api, ldap_uri=self.ldapuri) self.conn.connect(ccache="FILE:%s" % self.ccache) entry_attrs = self.conn.get_entry(self.dn, ["usercertificate"]) cert = entry_attrs.get("usercertificate") cert = cert[0] serial = unicode(x509.get_serial_number(cert, x509.DER)) assert serial is not None
def setup(self): self.tmp_dir = None self.saved_lang = None self.lang = 'xh_ZA' self.domain = 'ipa' self.pot_basename = '%s.pot' % self.domain self.po_basename = '%s.po' % self.lang self.mo_basename = '%s.mo' % self.domain self.tmp_dir = tempfile.mkdtemp() self.saved_lang = os.environ['LANG'] self.locale_dir = os.path.join(self.tmp_dir, 'test_locale') self.msg_dir = os.path.join(self.locale_dir, self.lang, 'LC_MESSAGES') if not os.path.exists(self.msg_dir): os.makedirs(self.msg_dir) self.pot_file = os.path.join( os.path.dirname(__file__), 'data', self.pot_basename) self.mo_file = os.path.join(self.msg_dir, self.mo_basename) self.po_file = os.path.join(self.tmp_dir, self.po_basename) result = create_po(self.pot_file, self.po_file, self.mo_file) if result: raise nose.SkipTest('Unable to create po file "%s" & mo file "%s" from pot file "%s"' % (self.po_file, self.mo_file, self.pot_file)) if not file_exists(self.po_file): raise nose.SkipTest( 'Test po file unavailable: {}'.format(self.po_file)) if not file_exists(self.mo_file): raise nose.SkipTest( 'Test mo file unavailable: {}'.format(self.mo_file)) self.po_file_iterate = po_file_iterate
def test_GSSAPI(self): """ Test a GSSAPI LDAP bind using ldap2 """ if not ipautil.file_exists(self.ccache): raise nose.SkipTest('Missing ccache %s' % self.ccache) self.conn = ldap2(shared_instance=False, ldap_uri=self.ldapuri) self.conn.connect(ccache='FILE:%s' % self.ccache) entry_attrs = self.conn.get_entry(self.dn, ['usercertificate']) cert = entry_attrs.get('usercertificate') cert = cert[0] serial = unicode(x509.get_serial_number(cert, x509.DER)) assert serial is not None
def install_replica_kra(config, postinstall=False): """ Install a KRA on a replica. There are two modes of doing this controlled: - While the replica is being installed - Post-replica installation config is a ReplicaConfig object Returns a KRA instance """ # note that the cacert.p12 file is regenerated during the # ipa-replica-prepare process and should include all the certs # for the CA and KRA krafile = config.dir + "/cacert.p12" if not ipautil.file_exists(krafile): raise RuntimeError("Unable to clone KRA." " cacert.p12 file not found in replica file") _kra = KRAInstance(config.realm_name, dogtag_constants=dogtag.install_constants) _kra.dm_password = config.dirman_password _kra.subject_base = config.subject_base if _kra.is_installed(): sys.exit("A KRA is already configured on this system.") _kra.configure_instance(config.host_name, config.domain_name, config.dirman_password, config.dirman_password, pkcs12_info=(krafile, ), master_host=config.master_host_name, master_replication_port=config.ca_ds_port, subject_base=config.subject_base) # Restart httpd since we changed it's config and added ipa-pki-proxy.conf if postinstall: services.knownservices.httpd.restart() # The dogtag DS instance needs to be restarted after installation. # The procedure for this is: stop dogtag, stop DS, start DS, start # dogtag service.print_msg("Restarting the directory and KRA servers") _kra.stop(dogtag.install_constants.PKI_INSTANCE_NAME) services.knownservices.dirsrv.restart() _kra.start(dogtag.install_constants.PKI_INSTANCE_NAME) return _kra
def install_replica_kra(config, postinstall=False): """ Install a KRA on a replica. There are two modes of doing this controlled: - While the replica is being installed - Post-replica installation config is a ReplicaConfig object Returns a KRA instance """ # note that the cacert.p12 file is regenerated during the # ipa-replica-prepare process and should include all the certs # for the CA and KRA krafile = config.dir + "/cacert.p12" if not ipautil.file_exists(krafile): raise RuntimeError( "Unable to clone KRA." " cacert.p12 file not found in replica file") _kra = KRAInstance(config.realm_name, dogtag_constants=dogtag.install_constants) _kra.dm_password = config.dirman_password _kra.subject_base = config.subject_base if _kra.is_installed(): sys.exit("A KRA is already configured on this system.") _kra.configure_instance(config.realm_name, config.host_name, config.domain_name, config.dirman_password, config.dirman_password, pkcs12_info=(krafile,), master_host=config.master_host_name, master_replication_port=config.ca_ds_port, subject_base=config.subject_base) # Restart httpd since we changed it's config and added ipa-pki-proxy.conf if postinstall: services.knownservices.httpd.restart() # The dogtag DS instance needs to be restarted after installation. # The procedure for this is: stop dogtag, stop DS, start DS, start # dogtag service.print_msg("Restarting the directory and KRA servers") _kra.stop(dogtag.install_constants.PKI_INSTANCE_NAME) services.knownservices.dirsrv.restart() _kra.start(dogtag.install_constants.PKI_INSTANCE_NAME) return _kra
def setup(self): self.tmp_dir = None self.setup_lang() self.domain = 'ipa' self.pot_basename = '%s.pot' % self.domain self.po_basename = '%s.po' % self.lang self.mo_basename = '%s.mo' % self.domain self.tmp_dir = tempfile.mkdtemp() self.locale_dir = os.path.join(self.tmp_dir, 'test_locale') self.msg_dir = os.path.join(self.locale_dir, self.lang, 'LC_MESSAGES') if not os.path.exists(self.msg_dir): os.makedirs(self.msg_dir) self.pot_file = os.path.join(os.path.dirname(__file__), 'data', self.pot_basename) self.mo_file = os.path.join(self.msg_dir, self.mo_basename) self.po_file = os.path.join(self.tmp_dir, self.po_basename) result = create_po(self.pot_file, self.po_file, self.mo_file) if result: raise nose.SkipTest( 'Unable to create po file "%s" & mo file "%s" from pot file "%s"' % (self.po_file, self.mo_file, self.pot_file)) if not file_exists(self.po_file): raise nose.SkipTest('Test po file unavailable: {}'.format( self.po_file)) if not file_exists(self.mo_file): raise nose.SkipTest('Test mo file unavailable: {}'.format( self.mo_file)) self.po_file_iterate = po_file_iterate
def read_cache(dm_password): """ Returns a dict of cached answers or empty dict if no cache file exists. """ if not ipautil.file_exists(paths.ROOT_IPA_CACHE): return {} top_dir = tempfile.mkdtemp("ipa") fname = "%s/cache" % top_dir try: decrypt_file(paths.ROOT_IPA_CACHE, fname, dm_password, top_dir) except Exception, e: shutil.rmtree(top_dir) raise Exception("Decryption of answer cache in %s failed, please " "check your password." % paths.ROOT_IPA_CACHE)
def read_replica_info_kra_enabled(config_dir): """ Check the replica info to determine if a KRA has been installed on the master """ default_file = config_dir + "/default.conf" if not ipautil.file_exists(default_file): return False else: with open(default_file) as fd: config = SafeConfigParser() config.readfp(fd) enable_kra = config.getboolean("global", "enable_kra") return enable_kra
def setUp(self): fqdn = installutils.get_fqdn() pwfile = api.env.dot_ipa + os.sep + ".dmpw" if ipautil.file_exists(pwfile): fp = open(pwfile, "r") self.dm_password = fp.read().rstrip() fp.close() else: raise nose.SkipTest("No directory manager password") self.updater = LDAPUpdate(dm_password=self.dm_password, sub_dict={}) ldap_uri = ipaldap.get_ldap_uri(fqdn) self.ld = ipaldap.LDAPClient(ldap_uri) self.ld.simple_bind(bind_dn=ipaldap.DIRMAN_DN, bind_password=self.dm_password) self.testdir = os.path.abspath(os.path.dirname(__file__)) if not ipautil.file_exists(os.path.join(self.testdir, "0_reset.update")): raise nose.SkipTest("Unable to find test update files") self.container_dn = DN( self.updater._template_str('cn=test, cn=accounts, $SUFFIX')) self.user_dn = DN( self.updater._template_str( 'uid=tuser, cn=test, cn=accounts, $SUFFIX'))
def validate_options(self, needs_root=True): super(KRAInstaller, self).validate_options(needs_root=True) if self.options.unattended and self.options.password is None: self.option_parser.error( "Directory Manager password must be specified using -p" " in unattended mode") if len(self.args) > 1: self.option_parser.error("Too many arguments provided") elif len(self.args) == 1: self.replica_file = self.args[0] if not ipautil.file_exists(self.replica_file): self.option_parser.error("Replica file %s does not exist" % self.replica_file)
def test_simple(self): """ Test a simple LDAP bind using ldap2 """ pwfile = api.env.dot_ipa + os.sep + ".dmpw" if ipautil.file_exists(pwfile): with open(pwfile, "r") as fp: dm_password = fp.read().rstrip() else: raise nose.SkipTest("No directory manager password in %s" % pwfile) self.conn = ldap2(api) self.conn.connect(bind_dn=DN(('cn', 'directory manager')), bind_pw=dm_password) entry_attrs = self.conn.get_entry(self.dn, ['usercertificate']) cert = entry_attrs.get('usercertificate')[0] assert cert.serial_number is not None
def next_replica(serial_file=CA_SERIALNO): """ Return the starting serial number for a new self-signed replica """ fp = None parser = RawConfigParser() if ipautil.file_exists(serial_file): try: fp = open(serial_file, "r+") fcntl.flock(fp.fileno(), fcntl.LOCK_EX) parser.readfp(fp) serial = parser.getint('selfsign', 'nextreplica') nextreplica = serial + parser.getint('selfsign', 'replicainterval') except IOError, e: raise RuntimeError("Unable to determine serial number: %s" % str(e))
def __init__(self, secdir, password=None, temporary=False): if secdir is None: secdir = tempfile.mkdtemp(prefix="certdb-") if password is None: password = self.generate_random() self.secdir = secdir self.password = password self.temporary = temporary self.noise_file = secdir + "/noise" self.pwd_file = secdir + "/pwd" self.csr_file = secdir + "/csr.txt" f = open(self.pwd_file, "w") f.write(self.password) f.close() if not ipautil.file_exists(secdir + "/secmod.db"): self.run_certutil(["-N", "-f", self.pwd_file])
def test_simple(self): """ Test a simple LDAP bind using ldap2 """ pwfile = api.env.dot_ipa + os.sep + ".dmpw" if ipautil.file_exists(pwfile): fp = open(pwfile, "r") dm_password = fp.read().rstrip() fp.close() else: raise nose.SkipTest("No directory manager password in %s" % pwfile) self.conn = ldap2(shared_instance=False, ldap_uri=self.ldapuri) self.conn.connect(bind_dn=DN(('cn', 'directory manager')), bind_pw=dm_password) (dn, entry_attrs) = self.conn.get_entry(self.dn, ['usercertificate']) cert = entry_attrs.get('usercertificate') cert = cert[0] serial = unicode(x509.get_serial_number(cert, x509.DER)) assert serial is not None
def setUp(self): if 'cert_request' not in api.Command: raise nose.SkipTest('cert_request not registered') if not ipautil.file_exists(api.env.dot_ipa + os.sep + 'alias' + os.sep + '.pwd'): raise nose.SkipTest('developer self-signed CA not configured') super(test_cert, self).setUp() self.reqdir = tempfile.mkdtemp(prefix = "tmp-") self.reqfile = self.reqdir + "/test.csr" self.pwname = self.reqdir + "/pwd" # Create an empty password file fp = open(self.pwname, "w") fp.write("\n") fp.close() # Create our temporary NSS database self.run_certutil(["-N", "-f", self.pwname]) self.subject = DN(('CN', self.host_fqdn), x509.subject_base())
def create_from_cacert(self): cacert_fname = paths.IPA_CA_CRT if ipautil.file_exists(self.certdb_fname): # We already have a cert db, see if it is for the same CA. # If it is we leave things as they are. with open(cacert_fname, "r") as f: newca = f.read() newca, _st = find_cert_from_txt(newca) cacert = self.get_cert_from_db(self.cacert_name) if newca == cacert: return # The CA certificates are different or something went wrong. Start with # a new certificate database. self.create_passwd_file() self.create_certdbs() self.load_cacert(cacert_fname, IPA_CA_TRUST_FLAGS)
def create_from_cacert(self, cacert_fname, passwd=None): if ipautil.file_exists(self.certdb_fname): # We already have a cert db, see if it is for the same CA. # If it is we leave things as they are. f = open(cacert_fname, "r") newca = f.readlines() f.close() newca = "".join(newca) (newca, st) = find_cert_from_txt(newca) cacert = self.get_cert_from_db(self.cacert_name) if cacert != '': (cacert, st) = find_cert_from_txt(cacert) if newca == cacert: return # The CA certificates are different or something went wrong. Start with # a new certificate database. self.create_passwd_file(passwd) self.create_certdbs() self.load_cacert(cacert_fname)
def read_cache(dm_password): """ Returns a dict of cached answers or empty dict if no cache file exists. """ if not ipautil.file_exists(paths.ROOT_IPA_CACHE): return {} top_dir = tempfile.mkdtemp("ipa") fname = "%s/cache" % top_dir try: installutils.decrypt_file(paths.ROOT_IPA_CACHE, fname, dm_password, top_dir) except Exception as e: shutil.rmtree(top_dir) raise Exception("Decryption of answer cache in %s failed, please " "check your password." % paths.ROOT_IPA_CACHE) try: with open(fname, 'rb') as f: try: optdict = pickle.load(f) except Exception as e: raise Exception("Parse error in %s: %s" % (paths.ROOT_IPA_CACHE, str(e))) except IOError as e: raise Exception("Read error in %s: %s" % (paths.ROOT_IPA_CACHE, str(e))) finally: shutil.rmtree(top_dir) # These are the only ones that may be overridden try: del optdict['external_cert_files'] except KeyError: pass return optdict
def __create_instance(self): pent = pwd.getpwnam(DS_USER) self.backup_state("serverid", self.serverid) self.fstore.backup_file("/etc/sysconfig/dirsrv") self.sub_dict['BASEDC'] = self.realm_name.split('.')[0].lower() base_txt = ipautil.template_str(BASE_TEMPLATE, self.sub_dict) root_logger.debug(base_txt) target_fname = '/var/lib/dirsrv/boot.ldif' base_fd = open(target_fname, "w") base_fd.write(base_txt) base_fd.close() # Must be readable for dirsrv os.chmod(target_fname, 0440) os.chown(target_fname, pent.pw_uid, pent.pw_gid) inf_txt = ipautil.template_str(INF_TEMPLATE, self.sub_dict) root_logger.debug("writing inf template") inf_fd = ipautil.write_tmp_file(inf_txt) inf_txt = re.sub(r"RootDNPwd=.*\n", "", inf_txt) root_logger.debug(inf_txt) if ipautil.file_exists("/usr/sbin/setup-ds.pl"): args = [ "/usr/sbin/setup-ds.pl", "--silent", "--logfile", "-", "-f", inf_fd.name ] root_logger.debug("calling setup-ds.pl") else: args = ["/usr/bin/ds_newinst.pl", inf_fd.name] root_logger.debug("calling ds_newinst.pl") try: ipautil.run(args) root_logger.debug("completed creating ds instance") except ipautil.CalledProcessError, e: root_logger.critical("failed to create ds instance %s" % e)