Ejemplo n.º 1
0
    def export_ca_cert(self, nickname, create_pkcs12=False):
        """create_pkcs12 tells us whether we should create a PKCS#12 file
           of the CA or not. If we are running on a replica then we won't
           have the private key to make a PKCS#12 file so we don't need to
           do that step."""
        cacert_fname = paths.IPA_CA_CRT
        # export the CA cert for use with other apps
        ipautil.backup_file(cacert_fname)
        root_nicknames = self.find_root_cert(nickname)[:-1]
        with open(cacert_fname, "w") as f:
            os.fchmod(f.fileno(), stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
            for root in root_nicknames:
                result = self.run_certutil(["-L", "-n", root, "-a"],
                                           capture_output=True)
                f.write(result.output)

        if create_pkcs12:
            ipautil.backup_file(self.pk12_fname)
            self.nssdb.run_pk12util([
                "-o",
                self.pk12_fname,
                "-n",
                self.cacert_name,
                "-k",
                self.passwd_fname,
                "-w",
                self.passwd_fname,
            ])
            self.set_perms(self.pk12_fname)
Ejemplo n.º 2
0
    def export_ca_cert(self, nickname, create_pkcs12=False):
        """create_pkcs12 tells us whether we should create a PKCS#12 file
           of the CA or not. If we are running on a replica then we won't
           have the private key to make a PKCS#12 file so we don't need to
           do that step."""
        cacert_fname = paths.IPA_CA_CRT
        # export the CA cert for use with other apps
        ipautil.backup_file(cacert_fname)
        root_nicknames = self.find_root_cert(nickname)[:-1]
        with open(cacert_fname, "w") as f:
            os.fchmod(f.fileno(), stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
            for root in root_nicknames:
                result = self.run_certutil(["-L", "-n", root, "-a"],
                                           capture_output=True)
                f.write(result.output)

        if create_pkcs12:
            ipautil.backup_file(self.pk12_fname)
            self.nssdb.run_pk12util([
                "-o", self.pk12_fname,
                "-n", self.cacert_name,
                "-k", self.passwd_fname,
                "-w", self.passwd_fname,
            ])
            self.set_perms(self.pk12_fname)
Ejemplo n.º 3
0
 def create_passwd_file(self, passwd=None):
     ipautil.backup_file(self.passwd_fname)
     with open(self.passwd_fname, "w") as f:
         self.set_perms(f)
         if passwd is not None:
             f.write("%s\n" % passwd)
         else:
             f.write(ipautil.ipa_generate_password())
Ejemplo n.º 4
0
 def create_passwd_file(self, passwd=None):
     ipautil.backup_file(self.passwd_fname)
     with open(self.passwd_fname, "w") as f:
         self.set_perms(f)
         if passwd is not None:
             f.write("%s\n" % passwd)
         else:
             f.write(ipautil.ipa_generate_password())
Ejemplo n.º 5
0
 def create_passwd_file(self, passwd=None):
     ipautil.backup_file(self.passwd_fname)
     f = open(self.passwd_fname, "w")
     if passwd is not None:
         f.write("%s\n" % passwd)
     else:
         f.write(self.gen_password())
     f.close()
     self.set_perms(self.passwd_fname)
Ejemplo n.º 6
0
 def create_passwd_file(self, passwd=None):
     ipautil.backup_file(self.passwd_fname)
     f = open(self.passwd_fname, "w")
     if passwd is not None:
         f.write("%s\n" % passwd)
     else:
         f.write(self.gen_password())
     f.close()
     self.set_perms(self.passwd_fname)
Ejemplo n.º 7
0
    def create_db(self, user=None, group=None, mode=None, backup=False):
        """Create cert DB

        :param user: User owner the secdir
        :param group: Group owner of the secdir
        :param mode: Mode of the secdir
        :param backup: Backup the sedir files
        """
        dirmode = 0o750
        filemode = 0o640
        pwdfilemode = 0o640
        if mode is not None:
            dirmode = mode
            filemode = mode & 0o666
            pwdfilemode = mode & 0o660

        uid = -1
        gid = -1
        if user is not None:
            uid = pwd.getpwnam(user).pw_uid
        if group is not None:
            gid = grp.getgrnam(group).gr_gid

        if backup:
            for filename in NSS_FILES:
                path = os.path.join(self.secdir, filename)
                ipautil.backup_file(path)

        if not os.path.exists(self.secdir):
            os.makedirs(self.secdir, dirmode)

        if not os.path.exists(self.pwd_file):
            # Create the password file for this db
            with io.open(os.open(self.pwd_file, os.O_CREAT | os.O_WRONLY,
                                 pwdfilemode),
                         'w',
                         closefd=True) as f:
                f.write(ipautil.ipa_generate_password())
                f.flush()

        self.run_certutil(["-N", "-f", self.pwd_file])

        # Finally fix up perms
        os.chown(self.secdir, uid, gid)
        os.chmod(self.secdir, dirmode)
        tasks.restore_context(self.secdir)
        for filename in NSS_FILES:
            path = os.path.join(self.secdir, filename)
            if os.path.exists(path):
                if uid != -1 or gid != -1:
                    os.chown(path, uid, gid)
                if path == self.pwd_file:
                    new_mode = pwdfilemode
                else:
                    new_mode = filemode
                os.chmod(path, new_mode)
                tasks.restore_context(path)
Ejemplo n.º 8
0
 def create_pin_file(self):
     """
     This is the format of Directory Server pin files.
     """
     ipautil.backup_file(self.pin_fname)
     with open(self.pin_fname, "w") as pinfile:
         self.set_perms(pinfile)
         pinfile.write("Internal (Software) Token:")
         with open(self.passwd_fname) as pwdfile:
             pinfile.write(pwdfile.read())
Ejemplo n.º 9
0
 def create_pin_file(self):
     """
     This is the format of Directory Server pin files.
     """
     ipautil.backup_file(self.pin_fname)
     with open(self.pin_fname, "w") as pinfile:
         self.set_perms(pinfile)
         pinfile.write("Internal (Software) Token:")
         with open(self.passwd_fname) as pwdfile:
             pinfile.write(pwdfile.read())
Ejemplo n.º 10
0
    def create_db(self, user=None, group=None, mode=None, backup=False):
        """Create cert DB

        :param user: User owner the secdir
        :param group: Group owner of the secdir
        :param mode: Mode of the secdir
        :param backup: Backup the sedir files
        """
        dirmode = 0o750
        filemode = 0o640
        pwdfilemode = 0o640
        if mode is not None:
            dirmode = mode
            filemode = mode & 0o666
            pwdfilemode = mode & 0o660

        uid = -1
        gid = -1
        if user is not None:
            uid = pwd.getpwnam(user).pw_uid
        if group is not None:
            gid = grp.getgrnam(group).gr_gid

        if backup:
            for filename in NSS_FILES:
                path = os.path.join(self.secdir, filename)
                ipautil.backup_file(path)

        if not os.path.exists(self.secdir):
            os.makedirs(self.secdir, dirmode)

        if not os.path.exists(self.pwd_file):
            # Create the password file for this db
            with io.open(os.open(self.pwd_file,
                                 os.O_CREAT | os.O_WRONLY,
                                 pwdfilemode), 'w', closefd=True) as f:
                f.write(ipautil.ipa_generate_password())
                f.flush()

        self.run_certutil(["-N", "-f", self.pwd_file])

        # Finally fix up perms
        os.chown(self.secdir, uid, gid)
        os.chmod(self.secdir, dirmode)
        for filename in NSS_FILES:
            path = os.path.join(self.secdir, filename)
            if os.path.exists(path):
                os.chown(path, uid, gid)
                if path == self.pwd_file:
                    new_mode = pwdfilemode
                else:
                    new_mode = filemode
                os.chmod(path, new_mode)
Ejemplo n.º 11
0
 def create_pin_file(self):
     """
     This is the format of Directory Server pin files.
     """
     ipautil.backup_file(self.pin_fname)
     f = open(self.pin_fname, "w")
     f.write("Internal (Software) Token:")
     pwdfile = open(self.passwd_fname)
     f.write(pwdfile.read())
     f.close()
     pwdfile.close()
     self.set_perms(self.pin_fname)
Ejemplo n.º 12
0
 def create_password_conf(self):
     """
     This is the format of mod_nss pin files.
     """
     ipautil.backup_file(self.pwd_conf)
     f = open(self.pwd_conf, "w")
     f.write("internal:")
     pwdfile = open(self.passwd_fname)
     f.write(pwdfile.read())
     f.close()
     pwdfile.close()
     self.set_perms(self.pwd_conf, uid=constants.HTTPD_USER)
Ejemplo n.º 13
0
 def create_pin_file(self):
     """
     This is the format of Directory Server pin files.
     """
     ipautil.backup_file(self.pin_fname)
     f = open(self.pin_fname, "w")
     f.write("Internal (Software) Token:")
     pwdfile = open(self.passwd_fname)
     f.write(pwdfile.read())
     f.close()
     pwdfile.close()
     self.set_perms(self.pin_fname)
Ejemplo n.º 14
0
 def create_password_conf(self):
     """
     This is the format of mod_nss pin files.
     """
     ipautil.backup_file(self.pwd_conf)
     f = open(self.pwd_conf, "w")
     f.write("internal:")
     pwdfile = open(self.passwd_fname)
     f.write(pwdfile.read())
     f.close()
     pwdfile.close()
     self.set_perms(self.pwd_conf, uid=constants.HTTPD_USER)
Ejemplo n.º 15
0
 def create_password_conf(self):
     """
     This is the format of mod_nss pin files.
     """
     ipautil.backup_file(self.pwd_conf)
     f = open(self.pwd_conf, "w")
     f.write("internal:")
     pwdfile = open(self.passwd_fname)
     f.write(pwdfile.read())
     f.close()
     pwdfile.close()
     # TODO: replace explicit uid by a platform-specific one
     self.set_perms(self.pwd_conf, uid="apache")
Ejemplo n.º 16
0
 def create_password_conf(self):
     """
     This is the format of mod_nss pin files.
     """
     ipautil.backup_file(self.pwd_conf)
     f = open(self.pwd_conf, "w")
     f.write("internal:")
     pwdfile = open(self.passwd_fname)
     f.write(pwdfile.read())
     f.close()
     pwdfile.close()
     # TODO: replace explicit uid by a platform-specific one
     self.set_perms(self.pwd_conf, uid="apache")
Ejemplo n.º 17
0
    def ldif2db(self, instance, backend, online=True):
        '''
        Restore a LDIF backup of the data in this instance.

        If executed online create a task and wait for it to complete.
        '''
        self.log.info('Restoring from %s in %s' % (backend, instance))

        now = time.localtime()
        cn = time.strftime('import_%Y_%m_%d_%H_%M_%S')
        dn = DN(('cn', cn), ('cn', 'import'), ('cn', 'tasks'), ('cn', 'config'))

        ldifdir = paths.SLAPD_INSTANCE_LDIF_DIR_TEMPLATE % instance
        ldifname = '%s-%s.ldif' % (instance, backend)
        ldiffile = os.path.join(ldifdir, ldifname)
        srcldiffile = os.path.join(self.dir, ldifname)

        if not os.path.exists(ldifdir):
            pent = pwd.getpwnam(DS_USER)
            os.mkdir(ldifdir, 0770)
            os.chown(ldifdir, pent.pw_uid, pent.pw_gid)

        ipautil.backup_file(ldiffile)
        with open(ldiffile, 'wb') as out_file:
            ldif_writer = ldif.LDIFWriter(out_file)
            with open(srcldiffile, 'rb') as in_file:
                ldif_parser = RemoveRUVParser(in_file, ldif_writer, self.log)
                ldif_parser.parse()

        if online:
            conn = self.get_connection()
            ent = conn.make_entry(
                dn,
                {
                    'objectClass': ['top', 'extensibleObject'],
                    'cn': [cn],
                    'nsFilename': [ldiffile],
                    'nsUseOneFile': ['true'],
                }
            )
            ent['nsInstance'] = [backend]

            try:
                conn.add_entry(ent)
            except Exception, e:
                self.log.error("Unable to bind to LDAP server: %s" % e)
                return

            self.log.info("Waiting for LDIF to finish")
            wait_for_task(conn, dn)
Ejemplo n.º 18
0
    def ldif2db(self, instance, backend, online=True):
        '''
        Restore a LDIF backup of the data in this instance.

        If executed online create a task and wait for it to complete.
        '''
        self.log.info('Restoring from %s in %s' % (backend, instance))

        now = time.localtime()
        cn = time.strftime('import_%Y_%m_%d_%H_%M_%S')
        dn = DN(('cn', cn), ('cn', 'import'), ('cn', 'tasks'),
                ('cn', 'config'))

        ldifdir = paths.SLAPD_INSTANCE_LDIF_DIR_TEMPLATE % instance
        ldifname = '%s-%s.ldif' % (instance, backend)
        ldiffile = os.path.join(ldifdir, ldifname)
        srcldiffile = os.path.join(self.dir, ldifname)

        if not os.path.exists(ldifdir):
            pent = pwd.getpwnam(DS_USER)
            os.mkdir(ldifdir, 0770)
            os.chown(ldifdir, pent.pw_uid, pent.pw_gid)

        ipautil.backup_file(ldiffile)
        with open(ldiffile, 'wb') as out_file:
            ldif_writer = ldif.LDIFWriter(out_file)
            with open(srcldiffile, 'rb') as in_file:
                ldif_parser = RemoveRUVParser(in_file, ldif_writer, self.log)
                ldif_parser.parse()

        if online:
            conn = self.get_connection()
            ent = conn.make_entry(
                dn, {
                    'objectClass': ['top', 'extensibleObject'],
                    'cn': [cn],
                    'nsFilename': [ldiffile],
                    'nsUseOneFile': ['true'],
                })
            ent['nsInstance'] = [backend]

            try:
                conn.add_entry(ent)
            except Exception, e:
                self.log.error("Unable to bind to LDAP server: %s" % e)
                return

            self.log.info("Waiting for LDIF to finish")
            wait_for_task(conn, dn)
Ejemplo n.º 19
0
    def create_cert_db(self):
        database = certs.NSS_DIR
        pwd_file = os.path.join(database, 'pwdfile.txt')

        for p in NSS_FILES:
            nss_path = os.path.join(database, p)
            ipautil.backup_file(nss_path)

        # Create the password file for this db
        hex_str = binascii.hexlify(os.urandom(10))
        f = os.open(pwd_file, os.O_CREAT | os.O_RDWR)
        os.write(f, hex_str)
        os.close(f)

        ipautil.run([paths.CERTUTIL, "-d", database, "-f", pwd_file, "-N"])

        self.fix_cert_db_perms()
Ejemplo n.º 20
0
    def create_cert_db(self):
        database = certs.NSS_DIR
        pwd_file = os.path.join(database, 'pwdfile.txt')

        for p in NSS_FILES:
            nss_path = os.path.join(database, p)
            ipautil.backup_file(nss_path)

        # Create the password file for this db
        hex_str = binascii.hexlify(os.urandom(10))
        f = os.open(pwd_file, os.O_CREAT | os.O_RDWR)
        os.write(f, hex_str)
        os.close(f)

        ipautil.run([paths.CERTUTIL, "-d", database, "-f", pwd_file, "-N"])

        self.fix_cert_db_perms()
Ejemplo n.º 21
0
    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()
Ejemplo n.º 22
0
    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()
Ejemplo n.º 23
0
    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()
Ejemplo n.º 24
0
    def cert_restore_prepare(self):
        cainstance.CAInstance().stop_tracking_certificates()
        httpinstance.HTTPInstance().stop_tracking_certificates()
        try:
            dsinstance.DsInstance().stop_tracking_certificates(
                ipaldap.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()
Ejemplo n.º 25
0
    def create_password_conf(self):
        """
        This is the format of mod_nss pin files.
        """
        pwd_conf = paths.HTTPD_PASSWORD_CONF
        ipautil.backup_file(pwd_conf)

        passwd_fname = os.path.join(paths.HTTPD_ALIAS_DIR, 'pwdfile.txt')
        with open(passwd_fname, 'r') as pwdfile:
            password = pwdfile.read()

        with open(pwd_conf, "w") as f:
            f.write("internal:")
            f.write(password)
            f.write("\nNSS FIPS 140-2 Certificate DB:")
            f.write(password)
            # make sure other processes can access the file contents ASAP
            f.flush()
        pent = pwd.getpwnam(constants.HTTPD_USER)
        os.chown(pwd_conf, pent.pw_uid, pent.pw_gid)
        os.chmod(pwd_conf, 0o400)
Ejemplo n.º 26
0
    def create_password_conf(self):
        """
        This is the format of mod_nss pin files.
        """
        pwd_conf = paths.HTTPD_PASSWORD_CONF
        ipautil.backup_file(pwd_conf)

        passwd_fname = os.path.join(paths.HTTPD_ALIAS_DIR, 'pwdfile.txt')
        with open(passwd_fname, 'r') as pwdfile:
            password = pwdfile.read()

        with open(pwd_conf, "w") as f:
            f.write("internal:")
            f.write(password)
            f.write("\nNSS FIPS 140-2 Certificate DB:")
            f.write(password)
            # make sure other processes can access the file contents ASAP
            f.flush()
        pent = pwd.getpwnam(constants.HTTPD_USER)
        os.chown(pwd_conf, pent.pw_uid, pent.pw_gid)
        os.chmod(pwd_conf, 0o400)
Ejemplo n.º 27
0
 def create_certdbs(self):
     ipautil.backup_file(self.certdb_fname)
     ipautil.backup_file(self.keydb_fname)
     ipautil.backup_file(self.secmod_fname)
     self.run_certutil(["-N",
                        "-f", self.passwd_fname])
     self.set_perms(self.passwd_fname, write=True)
Ejemplo n.º 28
0
 def export_ca_cert(self, nickname, create_pkcs12=False):
     """create_pkcs12 tells us whether we should create a PKCS#12 file
        of the CA or not. If we are running on a replica then we won't
        have the private key to make a PKCS#12 file so we don't need to
        do that step."""
     # export the CA cert for use with other apps
     ipautil.backup_file(self.cacert_fname)
     root_nicknames = self.find_root_cert(nickname)
     fd = open(self.cacert_fname, "w")
     for root in root_nicknames:
         (cert, stderr, returncode) = self.run_certutil(["-L", "-n", root, "-a"])
         fd.write(cert)
     fd.close()
     os.chmod(self.cacert_fname, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
     if create_pkcs12:
         ipautil.backup_file(self.pk12_fname)
         ipautil.run(["/usr/bin/pk12util", "-d", self.secdir,
                      "-o", self.pk12_fname,
                      "-n", self.cacert_name,
                      "-w", self.passwd_fname,
                      "-k", self.passwd_fname])
         self.set_perms(self.pk12_fname)
Ejemplo n.º 29
0
 def export_ca_cert(self, nickname, create_pkcs12=False):
     """create_pkcs12 tells us whether we should create a PKCS#12 file
        of the CA or not. If we are running on a replica then we won't
        have the private key to make a PKCS#12 file so we don't need to
        do that step."""
     # export the CA cert for use with other apps
     ipautil.backup_file(self.cacert_fname)
     root_nicknames = self.find_root_cert(nickname)
     fd = open(self.cacert_fname, "w")
     for root in root_nicknames:
         (cert, stderr,
          returncode) = self.run_certutil(["-L", "-n", root, "-a"])
         fd.write(cert)
     fd.close()
     os.chmod(self.cacert_fname, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
     if create_pkcs12:
         ipautil.backup_file(self.pk12_fname)
         ipautil.run([
             "/usr/bin/pk12util", "-d", self.secdir, "-o", self.pk12_fname,
             "-n", self.cacert_name, "-w", self.passwd_fname, "-k",
             self.passwd_fname
         ])
         self.set_perms(self.pk12_fname)
Ejemplo n.º 30
0
def create_ipa_nssdb():
    db = NSSDatabase(paths.IPA_NSSDB_DIR)
    pwdfile = os.path.join(db.secdir, 'pwdfile.txt')

    ipautil.backup_file(pwdfile)
    ipautil.backup_file(os.path.join(db.secdir, 'cert8.db'))
    ipautil.backup_file(os.path.join(db.secdir, 'key3.db'))
    ipautil.backup_file(os.path.join(db.secdir, 'secmod.db'))

    with open(pwdfile, 'w') as f:
        f.write(ipautil.ipa_generate_password(pwd_len=40))
    os.chmod(pwdfile, 0o600)

    db.create_db(pwdfile)
    os.chmod(os.path.join(db.secdir, 'cert8.db'), 0o644)
    os.chmod(os.path.join(db.secdir, 'key3.db'), 0o644)
    os.chmod(os.path.join(db.secdir, 'secmod.db'), 0o644)
Ejemplo n.º 31
0
def create_ipa_nssdb():
    db = NSSDatabase(paths.IPA_NSSDB_DIR)
    pwdfile = os.path.join(db.secdir, 'pwdfile.txt')

    ipautil.backup_file(pwdfile)
    ipautil.backup_file(os.path.join(db.secdir, 'cert8.db'))
    ipautil.backup_file(os.path.join(db.secdir, 'key3.db'))
    ipautil.backup_file(os.path.join(db.secdir, 'secmod.db'))

    with open(pwdfile, 'w') as f:
        f.write(ipautil.ipa_generate_password(pwd_len=40))
    os.chmod(pwdfile, 0o600)

    db.create_db(pwdfile)
    os.chmod(os.path.join(db.secdir, 'cert8.db'), 0o644)
    os.chmod(os.path.join(db.secdir, 'key3.db'), 0o644)
    os.chmod(os.path.join(db.secdir, 'secmod.db'), 0o644)
Ejemplo n.º 32
0
    def create_db(self, user=None, group=None, mode=None, backup=False):
        """Create cert DB

        :param user: User owner the secdir
        :param group: Group owner of the secdir
        :param mode: Mode of the secdir
        :param backup: Backup the sedir files
        """
        if mode is not None:
            dirmode = mode
            filemode = mode & 0o666
            pwdfilemode = mode & 0o660
        else:
            dirmode = 0o750
            filemode = 0o640
            pwdfilemode = 0o640

        uid = -1
        gid = -1
        if user is not None:
            uid = pwd.getpwnam(user).pw_uid
        if group is not None:
            gid = grp.getgrnam(group).gr_gid

        if backup:
            for filename in self.backup_filenames:
                ipautil.backup_file(filename)

        if not os.path.exists(self.secdir):
            os.makedirs(self.secdir, dirmode)

        if not os.path.exists(self.pwd_file):
            # Create the password file for this db
            with io.open(os.open(self.pwd_file,
                                 os.O_CREAT | os.O_WRONLY,
                                 pwdfilemode), 'w', closefd=True) as f:
                f.write(ipautil.ipa_generate_password())
                f.flush()

        # In case dbtype is auto, let certutil decide which type of DB
        # to create.
        if self.dbtype == 'auto':
            dbdir = self.secdir
        else:
            dbdir = '{}:{}'.format(self.dbtype, self.secdir)
        args = [
            paths.CERTUTIL,
            '-d', dbdir,
            '-N',
            '-f', self.pwd_file,
            # -@ in case it's an old db and it must be migrated
            '-@', self.pwd_file,
        ]
        ipautil.run(args, stdin=None, cwd=self.secdir)
        self._set_filenames(self._detect_dbtype())
        if self.filenames is None:
            # something went wrong...
            raise ValueError(
                "Failed to create NSSDB at '{}'".format(self.secdir)
            )

        # Finally fix up perms
        os.chown(self.secdir, uid, gid)
        os.chmod(self.secdir, dirmode)
        tasks.restore_context(self.secdir, force=True)
        for filename in self.filenames:
            if os.path.exists(filename):
                os.chown(filename, uid, gid)
                if filename == self.pwd_file:
                    new_mode = pwdfilemode
                else:
                    new_mode = filemode
                os.chmod(filename, new_mode)
                tasks.restore_context(filename, force=True)
Ejemplo n.º 33
0
    def ldif2db(self, instance, backend, online=True):
        '''
        Restore a LDIF backup of the data in this instance.

        If executed online create a task and wait for it to complete.
        '''
        self.log.info('Restoring from %s in %s' % (backend, instance))

        cn = time.strftime('import_%Y_%m_%d_%H_%M_%S')
        dn = DN(('cn', cn), ('cn', 'import'), ('cn', 'tasks'), ('cn', 'config'))

        ldifdir = paths.SLAPD_INSTANCE_LDIF_DIR_TEMPLATE % instance
        ldifname = '%s-%s.ldif' % (instance, backend)
        ldiffile = os.path.join(ldifdir, ldifname)
        srcldiffile = os.path.join(self.dir, ldifname)

        if not os.path.exists(ldifdir):
            pent = pwd.getpwnam(constants.DS_USER)
            os.mkdir(ldifdir)
            os.chmod(ldifdir, 0o770)
            os.chown(ldifdir, pent.pw_uid, pent.pw_gid)

        ipautil.backup_file(ldiffile)
        with open(ldiffile, 'wb') as out_file:
            ldif_writer = ldif.LDIFWriter(out_file)
            with open(srcldiffile, 'rb') as in_file:
                ldif_parser = RemoveRUVParser(in_file, ldif_writer, self.log)
                ldif_parser.parse()

        # Make sure the modified ldiffile is owned by DS_USER
        pent = pwd.getpwnam(constants.DS_USER)
        os.chown(ldiffile, pent.pw_uid, pent.pw_gid)

        if online:
            conn = self.get_connection()
            ent = conn.make_entry(
                dn,
                {
                    'objectClass': ['top', 'extensibleObject'],
                    'cn': [cn],
                    'nsFilename': [ldiffile],
                    'nsUseOneFile': ['true'],
                }
            )
            ent['nsInstance'] = [backend]

            try:
                conn.add_entry(ent)
            except Exception as e:
                self.log.error("Unable to bind to LDAP server: %s" % e)
                return

            self.log.info("Waiting for LDIF to finish")
            wait_for_task(conn, dn)
        else:
            try:
                os.makedirs(paths.VAR_LOG_DIRSRV_INSTANCE_TEMPLATE % instance)
            except OSError as e:
                pass

            args = [paths.LDIF2DB,
                    '-Z', instance,
                    '-i', ldiffile,
                    '-n', backend]
            result = run(args, raiseonerr=False)
            if result.returncode != 0:
                self.log.critical("ldif2db failed: %s" % result.error_log)
Ejemplo n.º 34
0
 def create_certdbs(self):
     ipautil.backup_file(self.certdb_fname)
     ipautil.backup_file(self.keydb_fname)
     ipautil.backup_file(self.secmod_fname)
     self.nssdb.create_db(self.passwd_fname)
     self.set_perms(self.passwd_fname, write=True)
Ejemplo n.º 35
0
 def create_certdbs(self):
     ipautil.backup_file(self.certdb_fname)
     ipautil.backup_file(self.keydb_fname)
     ipautil.backup_file(self.secmod_fname)
     self.run_certutil(["-N", "-f", self.passwd_fname])
     self.set_perms(self.passwd_fname, write=True)
Ejemplo n.º 36
0
    def create_db(self, user=None, group=None, mode=None, backup=False):
        """Create cert DB

        :param user: User owner the secdir
        :param group: Group owner of the secdir
        :param mode: Mode of the secdir
        :param backup: Backup the sedir files
        """
        if mode is not None:
            dirmode = mode
            filemode = mode & 0o666
            pwdfilemode = mode & 0o660
        else:
            dirmode = 0o750
            filemode = 0o640
            pwdfilemode = 0o640

        uid = -1
        gid = -1
        if user is not None:
            uid = pwd.getpwnam(user).pw_uid
        if group is not None:
            gid = grp.getgrnam(group).gr_gid

        if backup:
            for filename in self.backup_filenames:
                ipautil.backup_file(filename)

        if not os.path.exists(self.secdir):
            os.makedirs(self.secdir, dirmode)

        if not os.path.exists(self.pwd_file):
            # Create the password file for this db
            with io.open(os.open(self.pwd_file,
                                 os.O_CREAT | os.O_WRONLY,
                                 pwdfilemode), 'w', closefd=True) as f:
                f.write(ipautil.ipa_generate_password())
                # flush and sync tempfile inode
                f.flush()
                os.fsync(f.fileno())

        # In case dbtype is auto, let certutil decide which type of DB
        # to create.
        if self.dbtype == 'auto':
            dbdir = self.secdir
        else:
            dbdir = '{}:{}'.format(self.dbtype, self.secdir)
        args = [
            paths.CERTUTIL,
            '-d', dbdir,
            '-N',
            '-f', self.pwd_file,
            # -@ in case it's an old db and it must be migrated
            '-@', self.pwd_file,
        ]
        ipautil.run(args, stdin=None, cwd=self.secdir)
        self._set_filenames(self._detect_dbtype())
        if self.filenames is None:
            # something went wrong...
            raise ValueError(
                "Failed to create NSSDB at '{}'".format(self.secdir)
            )

        # Finally fix up perms
        os.chown(self.secdir, uid, gid)
        os.chmod(self.secdir, dirmode)
        tasks.restore_context(self.secdir, force=True)
        for filename in self.filenames:
            if os.path.exists(filename):
                os.chown(filename, uid, gid)
                if filename == self.pwd_file:
                    new_mode = pwdfilemode
                else:
                    new_mode = filemode
                os.chmod(filename, new_mode)
                tasks.restore_context(filename, force=True)
Ejemplo n.º 37
0
    def ldif2db(self, instance, backend, online=True):
        '''
        Restore a LDIF backup of the data in this instance.

        If executed online create a task and wait for it to complete.
        '''
        logger.info('Restoring from %s in %s', backend, instance)

        cn = time.strftime('import_%Y_%m_%d_%H_%M_%S')
        dn = DN(('cn', cn), ('cn', 'import'), ('cn', 'tasks'), ('cn', 'config'))

        ldifdir = paths.SLAPD_INSTANCE_LDIF_DIR_TEMPLATE % instance
        ldifname = '%s-%s.ldif' % (instance, backend)
        ldiffile = os.path.join(ldifdir, ldifname)
        srcldiffile = os.path.join(self.dir, ldifname)

        if not os.path.exists(ldifdir):
            pent = pwd.getpwnam(constants.DS_USER)
            os.mkdir(ldifdir)
            os.chmod(ldifdir, 0o770)
            os.chown(ldifdir, pent.pw_uid, pent.pw_gid)

        ipautil.backup_file(ldiffile)
        with open(ldiffile, 'w') as out_file:
            ldif_writer = ldif.LDIFWriter(out_file)
            with open(srcldiffile, 'rb') as in_file:
                ldif_parser = RemoveRUVParser(in_file, ldif_writer)
                ldif_parser.parse()

        # Make sure the modified ldiffile is owned by DS_USER
        pent = pwd.getpwnam(constants.DS_USER)
        os.chown(ldiffile, pent.pw_uid, pent.pw_gid)

        if online:
            conn = self.get_connection()
            ent = conn.make_entry(
                dn,
                {
                    'objectClass': ['top', 'extensibleObject'],
                    'cn': [cn],
                    'nsFilename': [ldiffile],
                    'nsUseOneFile': ['true'],
                }
            )
            ent['nsInstance'] = [backend]

            try:
                conn.add_entry(ent)
            except Exception as e:
                logger.error("Unable to bind to LDAP server: %s", e)
                return

            logger.info("Waiting for LDIF to finish")
            wait_for_task(conn, dn)
        else:
            try:
                os.makedirs(paths.VAR_LOG_DIRSRV_INSTANCE_TEMPLATE % instance)
            except OSError as e:
                pass

            args = [paths.LDIF2DB,
                    '-Z', instance,
                    '-i', ldiffile,
                    '-n', backend]
            result = run(args, raiseonerr=False)
            if result.returncode != 0:
                logger.critical("ldif2db failed: %s", result.error_log)
Ejemplo n.º 38
0
 def create_certdbs(self):
     ipautil.backup_file(self.certdb_fname)
     ipautil.backup_file(self.keydb_fname)
     ipautil.backup_file(self.secmod_fname)
     self.nssdb.create_db(self.passwd_fname)
     self.set_perms(self.passwd_fname, write=True)