Example #1
0
    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)
Example #2
0
    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)
Example #3
0
 def _convert_provider_to_endpoints(self,
                                    entry_attrs,
                                    provider=None,
                                    elements=None):
     """
     Converts provider options to auth-uri and token-uri
     """
     if provider:
         if provider not in self.idp_providers:
             raise errors.ValidationError(name='provider',
                                          error=_('unknown provider'))
         # For each string in the template check if a variable
         # is required, it is provided as an option
         points = deepcopy(self.idp_providers[provider])
         r = string.Template.pattern
         for (k, v) in points.items():
             # build list of variables to be replaced
             subs = list(
                 chain.from_iterable(
                     (filter(None, s) for s in r.findall(v))))
             if subs:
                 for s in subs:
                     if s not in elements:
                         raise errors.ValidationError(
                             name=self.options[s].cli_name,
                             error=_('value is missing'))
                 points[k] = template_str(v, elements)
         entry_attrs.update(points)
Example #4
0
    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, 0o440)
        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)
        args = [
            paths.SETUP_DS_PL,
            "--silent",
            "--logfile",
            "-",
            "-f",
            inf_fd.name,
        ]
        root_logger.debug("calling setup-ds.pl")
        try:
            ipautil.run(args)
            root_logger.debug("completed creating DS instance")
        except ipautil.CalledProcessError as e:
            raise RuntimeError("failed to create DS instance %s" % e)

        # check for open port 389 from now on
        self.open_ports.append(389)

        inf_fd.close()
        os.remove(paths.DIRSRV_BOOT_LDIF)
Example #5
0
def named_test_template(host):
    # create bind instance to get a substitution dict
    bind = bindinstance.BindInstance()
    bind.setup_templating(
        fqdn=host.hostname,
        realm_name=host.domain.realm,
        domain_name=host.domain.name,
    )
    sub_dict = bind.sub_dict.copy()
    sub_dict.update(BINDKEYS_FILE="/etc/named.iscdlv.key")
    return template_str(OLD_NAMED_TEMPLATE, sub_dict)
Example #6
0
    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)
        logger.debug("%s", 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, 0o440)
        os.chown(target_fname, pent.pw_uid, pent.pw_gid)

        inf_txt = ipautil.template_str(INF_TEMPLATE, self.sub_dict)
        logger.debug("writing inf template")
        inf_fd = ipautil.write_tmp_file(inf_txt)
        inf_txt = re.sub(r"RootDNPwd=.*\n", "", inf_txt)
        logger.debug("%s", inf_txt)
        args = [
            paths.SETUP_DS_PL, "--silent",
            "--logfile", "-",
            "-f", inf_fd.name,
        ]
        logger.debug("calling setup-ds.pl")
        try:
            ipautil.run(args)
            logger.debug("completed creating DS instance")
        except ipautil.CalledProcessError as e:
            raise RuntimeError("failed to create DS instance %s" % e)

        # check for open port 389 from now on
        self.open_ports.append(389)

        inf_fd.close()
        os.remove(paths.DIRSRV_BOOT_LDIF)
Example #7
0
def config_ntp(ntp_servers, fstore=None, sysstore=None):
    path_step_tickers = paths.NTP_STEP_TICKERS
    path_ntp_conf = paths.NTP_CONF
    path_ntp_sysconfig = paths.SYSCONFIG_NTPD
    sub_dict = {}
    sub_dict["SERVERS_BLOCK"] = "\n".join("server %s" % s for s in ntp_servers)
    sub_dict["TICKER_SERVERS_BLOCK"] = "\n".join(ntp_servers)

    nc = ipautil.template_str(ntp_conf, sub_dict)
    config_step_tickers = False

    if os.path.exists(path_step_tickers):
        config_step_tickers = True
        ns = ipautil.template_str(ntp_step_tickers, sub_dict)
        __backup_config(path_step_tickers, fstore)
        __write_config(path_step_tickers, ns)
        tasks.restore_context(path_step_tickers)

    if sysstore:
        module = 'ntp'
        sysstore.backup_state(module, "enabled",
                              services.knownservices.ntpd.is_enabled())
        if config_step_tickers:
            sysstore.backup_state(module, "step-tickers", True)

    __backup_config(path_ntp_conf, fstore)
    __write_config(path_ntp_conf, nc)
    tasks.restore_context(path_ntp_conf)

    __backup_config(path_ntp_sysconfig, fstore)
    __write_config(path_ntp_sysconfig, ntp_sysconfig)
    tasks.restore_context(path_ntp_sysconfig)

    # Set the ntpd to start on boot
    services.knownservices.ntpd.enable()

    # Restart ntpd
    services.knownservices.ntpd.restart()
Example #8
0
def config_ntp(ntp_servers, fstore = None, sysstore = None):
    path_step_tickers = paths.NTP_STEP_TICKERS
    path_ntp_conf = paths.NTP_CONF
    path_ntp_sysconfig = paths.SYSCONFIG_NTPD
    sub_dict = {}
    sub_dict["SERVERS_BLOCK"] = "\n".join("server %s" % s for s in ntp_servers)
    sub_dict["TICKER_SERVERS_BLOCK"] = "\n".join(ntp_servers)

    nc = ipautil.template_str(ntp_conf, sub_dict)
    config_step_tickers = False


    if os.path.exists(path_step_tickers):
        config_step_tickers = True
        ns = ipautil.template_str(ntp_step_tickers, sub_dict)
        __backup_config(path_step_tickers, fstore)
        __write_config(path_step_tickers, ns)
        tasks.restore_context(path_step_tickers)

    if sysstore:
        module = 'ntp'
        sysstore.backup_state(module, "enabled", services.knownservices.ntpd.is_enabled())
        if config_step_tickers:
            sysstore.backup_state(module, "step-tickers", True)

    __backup_config(path_ntp_conf, fstore)
    __write_config(path_ntp_conf, nc)
    tasks.restore_context(path_ntp_conf)

    __backup_config(path_ntp_sysconfig, fstore)
    __write_config(path_ntp_sysconfig, ntp_sysconfig)
    tasks.restore_context(path_ntp_sysconfig)

    # Set the ntpd to start on boot
    services.knownservices.ntpd.enable()

    # Restart ntpd
    services.knownservices.ntpd.restart()
Example #9
0
    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)
Example #10
0
def configure_smb_conf(fstore, statestore, options, domains):
    sub_dict = {
        "samba_keytab": paths.SAMBA_KEYTAB,
        "realm": api.env.realm,
        "machine_name": options.netbiosname,
    }

    # First domain in the list is ours, pull our domain name from there
    sub_dict["netbios_name"] = domains[0]["netbios_name"]

    # Construct elements of smb.conf by pre-rendering idmap configuration
    template = [smb_conf_template]
    for dom in domains:
        template.extend([ipautil.template_str(idmap_conf_domain_snippet, dom)])

    # Add default homes share so that users can log into Samba
    if not options.no_homes:
        template.extend([homes_conf_snippet])

    fstore.backup_file(paths.SMB_CONF)
    with open(paths.SMB_CONF, "w") as f:
        f.write(ipautil.template_str("\n".join(template), sub_dict))
    tasks.restore_context(paths.SMB_CONF)
Example #11
0
def config_ntp(server_fqdn, fstore = None, sysstore = None):
    path_step_tickers = "/etc/ntp/step-tickers"
    path_ntp_conf = "/etc/ntp.conf"
    path_ntp_sysconfig = "/etc/sysconfig/ntpd"
    sub_dict = { }
    sub_dict["SERVER"] = server_fqdn

    nc = ipautil.template_str(ntp_conf, sub_dict)
    config_step_tickers = False


    if os.path.exists(path_step_tickers):
        config_step_tickers = True
        ns = ipautil.template_str(ntp_step_tickers, sub_dict)
        __backup_config(path_step_tickers, fstore)
        __write_config(path_step_tickers, ns)
        ipaservices.restore_context(path_step_tickers)

    if sysstore:
        module = 'ntp'
        sysstore.backup_state(module, "enabled", ipaservices.knownservices.ntpd.is_enabled())
        if config_step_tickers:
            sysstore.backup_state(module, "step-tickers", True)

    __backup_config(path_ntp_conf, fstore)
    __write_config(path_ntp_conf, nc)
    ipaservices.restore_context(path_ntp_conf)

    __backup_config(path_ntp_sysconfig, fstore)
    __write_config(path_ntp_sysconfig, ntp_sysconfig)
    ipaservices.restore_context(path_ntp_sysconfig)

    # Set the ntpd to start on boot
    ipaservices.knownservices.ntpd.enable()

    # Restart ntpd
    ipaservices.knownservices.ntpd.restart()
Example #12
0
def config_ntp(server_fqdn, fstore=None, sysstore=None):
    path_step_tickers = "/etc/ntp/step-tickers"
    path_ntp_conf = "/etc/ntp.conf"
    path_ntp_sysconfig = "/etc/sysconfig/ntpd"
    sub_dict = {}
    sub_dict["SERVER"] = server_fqdn

    nc = ipautil.template_str(ntp_conf, sub_dict)
    config_step_tickers = False

    if os.path.exists(path_step_tickers):
        config_step_tickers = True
        ns = ipautil.template_str(ntp_step_tickers, sub_dict)
        __backup_config(path_step_tickers, fstore)
        __write_config(path_step_tickers, ns)
        ipaservices.restore_context(path_step_tickers)

    if sysstore:
        module = 'ntp'
        sysstore.backup_state(module, "enabled",
                              ipaservices.knownservices.ntpd.is_enabled())
        if config_step_tickers:
            sysstore.backup_state(module, "step-tickers", True)

    __backup_config(path_ntp_conf, fstore)
    __write_config(path_ntp_conf, nc)
    ipaservices.restore_context(path_ntp_conf)

    __backup_config(path_ntp_sysconfig, fstore)
    __write_config(path_ntp_sysconfig, ntp_sysconfig)
    ipaservices.restore_context(path_ntp_sysconfig)

    # Set the ntpd to start on boot
    ipaservices.knownservices.ntpd.enable()

    # Restart ntpd
    ipaservices.knownservices.ntpd.restart()
    def update_permission(self, ldap, obj, name, template, anonymous_read_aci):
        """Update the given permission and the corresponding ACI"""
        assert name.startswith('System:')

        dn = self.api.Object[permission].get_dn(name)
        permission_plugin = self.api.Object[permission]

        try:
            attrs_list = list(permission_plugin.default_attributes)
            attrs_list.remove('memberindirect')
            entry = ldap.get_entry(dn, attrs_list)
            is_new = False
        except errors.NotFound:
            entry = ldap.make_entry(dn)
            is_new = True

        self.update_entry(obj, entry, template,
                          anonymous_read_aci, is_new=is_new)

        remove_legacy = False
        if 'replaces' in template:
            sub_dict = {
                'SUFFIX': str(self.api.env.basedn),
                'REALM': str(self.api.env.realm),
            }
            legacy_acistrs = [ipautil.template_str(r, sub_dict)
                              for r in template['replaces']]

            legacy_aci = ACI(legacy_acistrs[0])
            prefix, sep, legacy_name = legacy_aci.name.partition(':')
            assert prefix == 'permission' and sep

            legacy_dn = permission_plugin.get_dn(legacy_name)
            try:
                legacy_entry = ldap.get_entry(legacy_dn,
                                              ['ipapermissiontype', 'cn'])
            except errors.NotFound:
                logger.debug("Legacy permission %s not found", legacy_name)
            else:
                if 'ipapermissiontype' not in legacy_entry:
                    if is_new:
                        _acientry, acistr = (
                            permission_plugin._get_aci_entry_and_string(
                                legacy_entry, notfound_ok=True))
                        try:
                            included, excluded = self.get_upgrade_attr_lists(
                                acistr, legacy_acistrs)
                        except IncompatibleACIModification:
                            logger.error(
                                "Permission '%s' has been modified from its "
                                "default; not updating it to '%s'.",
                                legacy_name, name)
                            return
                        else:
                            logger.debug("Merging attributes from legacy "
                                         "permission '%s'", legacy_name)
                            logger.debug("Included attrs: %s",
                                         ', '.join(sorted(included)))
                            logger.debug("Excluded attrs: %s",
                                         ', '.join(sorted(excluded)))
                            entry['ipapermincludedattr'] = list(included)
                            entry['ipapermexcludedattr'] = list(excluded)
                            remove_legacy = True
                    else:
                        logger.debug("Ignoring attributes in legacy "
                                     "permission '%s' because '%s' exists",
                                     legacy_name, name)
                        remove_legacy = True
                else:
                    logger.debug("Ignoring V2 permission named '%s'",
                                 legacy_name)

        update_aci = True
        logger.debug('Updating managed permission: %s', name)
        if is_new:
            ldap.add_entry(entry)
        else:
            try:
                ldap.update_entry(entry)
            except errors.EmptyModlist:
                logger.debug('No changes to permission: %s', name)
                update_aci = False

        if update_aci:
            logger.debug('Updating ACI for managed permission: %s', name)
            permission_plugin.update_aci(entry)

        if remove_legacy:
            logger.debug("Removing legacy permission '%s'", legacy_name)
            self.api.Command[permission_del](unicode(legacy_name))

        for name in template.get('replaces_system', ()):
            name = unicode(name)
            try:
                entry = ldap.get_entry(permission_plugin.get_dn(name),
                                       ['ipapermissiontype'])
            except errors.NotFound:
                logger.debug("Legacy permission '%s' not found", name)
            else:
                flags = entry.get('ipapermissiontype', [])
                if list(flags) == ['SYSTEM']:
                    logger.debug("Removing legacy permission '%s'", name)
                    self.api.Command[permission_del](name, force=True)
                else:
                    logger.debug("Ignoring V2 permission '%s'", name)
Example #14
0
 def _template_str(self, s):
     try:
         return ipautil.template_str(s, self.sub_dict)
     except KeyError as e:
         raise BadSyntax("Unknown template keyword %s" % e)
    def update_permission(self, ldap, obj, name, template, anonymous_read_aci):
        """Update the given permission and the corresponding ACI"""
        assert name.startswith('System:')

        dn = self.api.Object[permission].get_dn(name)
        permission_plugin = self.api.Object[permission]

        try:
            attrs_list = list(permission_plugin.default_attributes)
            attrs_list.remove('memberindirect')
            entry = ldap.get_entry(dn, attrs_list)
            is_new = False
        except errors.NotFound:
            entry = ldap.make_entry(dn)
            is_new = True

        self.update_entry(obj, entry, template,
                          anonymous_read_aci, is_new=is_new)

        remove_legacy = False
        if 'replaces' in template:
            sub_dict = {
                'SUFFIX': str(self.api.env.basedn),
                'REALM': str(self.api.env.realm),
            }
            legacy_acistrs = [ipautil.template_str(r, sub_dict)
                              for r in template['replaces']]

            legacy_aci = ACI(legacy_acistrs[0])
            prefix, sep, legacy_name = legacy_aci.name.partition(':')
            assert prefix == 'permission' and sep

            legacy_dn = permission_plugin.get_dn(legacy_name)
            try:
                legacy_entry = ldap.get_entry(legacy_dn,
                                              ['ipapermissiontype', 'cn'])
            except errors.NotFound:
                logger.debug("Legacy permission %s not found", legacy_name)
            else:
                if 'ipapermissiontype' not in legacy_entry:
                    if is_new:
                        _acientry, acistr = (
                            permission_plugin._get_aci_entry_and_string(
                                legacy_entry, notfound_ok=True))
                        try:
                            included, excluded = self.get_upgrade_attr_lists(
                                acistr, legacy_acistrs)
                        except IncompatibleACIModification:
                            logger.error(
                                "Permission '%s' has been modified from its "
                                "default; not updating it to '%s'.",
                                legacy_name, name)
                            return
                        else:
                            logger.debug("Merging attributes from legacy "
                                         "permission '%s'", legacy_name)
                            logger.debug("Included attrs: %s",
                                         ', '.join(sorted(included)))
                            logger.debug("Excluded attrs: %s",
                                         ', '.join(sorted(excluded)))
                            entry['ipapermincludedattr'] = list(included)
                            entry['ipapermexcludedattr'] = list(excluded)
                            remove_legacy = True
                    else:
                        logger.debug("Ignoring attributes in legacy "
                                     "permission '%s' because '%s' exists",
                                     legacy_name, name)
                        remove_legacy = True
                else:
                    logger.debug("Ignoring V2 permission named '%s'",
                                 legacy_name)

        update_aci = True
        logger.debug('Updating managed permission: %s', name)
        if is_new:
            ldap.add_entry(entry)
        else:
            try:
                ldap.update_entry(entry)
            except errors.EmptyModlist:
                logger.debug('No changes to permission: %s', name)
                update_aci = False

        if update_aci:
            logger.debug('Updating ACI for managed permission: %s', name)
            permission_plugin.update_aci(entry)

        if remove_legacy:
            logger.debug("Removing legacy permission '%s'", legacy_name)
            self.api.Command[permission_del](unicode(legacy_name))

        for name in template.get('replaces_system', ()):
            name = unicode(name)
            try:
                entry = ldap.get_entry(permission_plugin.get_dn(name),
                                       ['ipapermissiontype'])
            except errors.NotFound:
                logger.debug("Legacy permission '%s' not found", name)
            else:
                flags = entry.get('ipapermissiontype', [])
                if list(flags) == ['SYSTEM']:
                    logger.debug("Removing legacy permission '%s'", name)
                    self.api.Command[permission_del](name, force=True)
                else:
                    logger.debug("Ignoring V2 permission '%s'", name)
Example #16
0
 def _template_str(self, s):
     try:
         return ipautil.template_str(s, self.sub_dict)
     except KeyError as e:
         raise BadSyntax("Unknown template keyword %s" % e)