Example #1
0
def configure_chrony(ntp_servers, ntp_pool=None,
                     fstore=None, sysstore=None, debug=False):
    """
    This method only configures chrony client with ntp_servers or ntp_pool
    """

    module = "chrony"
    if sysstore:
        sysstore.backup_state(module, "enabled",
                              services.knownservices.chronyd.is_enabled())

    aug = Augeas(flags=Augeas.NO_LOAD | Augeas.NO_MODL_AUTOLOAD,
                 loadpath=paths.USR_SHARE_IPA_DIR)

    try:
        logger.debug("Configuring chrony")
        chrony_conf = os.path.abspath(paths.CHRONY_CONF)
        aug.transform(module, chrony_conf)  # loads chrony lens file
        aug.load()  # loads augeas tree
        # augeas needs to prepend path with '/files'
        path = '/files{path}'.format(path=chrony_conf)

        # remove possible conflicting configuration of servers
        aug.remove('{}/server'.format(path))
        aug.remove('{}/pool'.format(path))
        aug.remove('{}/peer'.format(path))
        if ntp_pool:
            logger.debug("Setting server pool:")
            logger.debug("'%s'", ntp_pool)
            aug.set('{}/pool[last()+1]'.format(path), ntp_pool)
            aug.set('{}/pool[last()]/iburst'.format(path), None)

        if ntp_servers:
            logger.debug("Setting time servers:")
            for server in ntp_servers:
                aug.set('{}/server[last()+1]'.format(path), server)
                aug.set('{}/server[last()]/iburst'.format(path), None)
                logger.debug("'%s'", server)

        # backup oginal conf file
        logger.debug("Backing up '%s'", chrony_conf)
        __backup_config(chrony_conf, fstore)

        logger.debug("Writing configuration to '%s'", chrony_conf)
        aug.save()

        logger.info('Configuration of chrony was changed by installer.')
        configured = True

    except IOError:
        logger.error("Augeas failed to configure file %s", chrony_conf)
        configured = False
    except RuntimeError as e:
        logger.error("Configuration failed with: %s", e)
        configured = False
    finally:
        aug.close()

    tasks.restore_context(chrony_conf)
    return configured
Example #2
0
def configure_chrony(ntp_servers, ntp_pool=None,
                     fstore=None, sysstore=None, debug=False):
    """
    This method only configures chrony client with ntp_servers or ntp_pool
    """

    module = "chrony"
    if sysstore:
        sysstore.backup_state(module, "enabled",
                              services.knownservices.chronyd.is_enabled())

    aug = Augeas(flags=Augeas.NO_LOAD | Augeas.NO_MODL_AUTOLOAD,
                 loadpath=paths.USR_SHARE_IPA_DIR)

    try:
        logger.debug("Configuring chrony")
        chrony_conf = os.path.abspath(paths.CHRONY_CONF)
        aug.transform(module, chrony_conf)  # loads chrony lens file
        aug.load()  # loads augeas tree
        # augeas needs to prepend path with '/files'
        path = '/files{path}'.format(path=chrony_conf)

        # remove possible conflicting configuration of servers
        aug.remove('{}/server'.format(path))
        aug.remove('{}/pool'.format(path))
        aug.remove('{}/peer'.format(path))
        if ntp_pool:
            logger.debug("Setting server pool:")
            logger.debug("'%s'", ntp_pool)
            aug.set('{}/pool[last()+1]'.format(path), ntp_pool)
            aug.set('{}/pool[last()]/iburst'.format(path), None)

        if ntp_servers:
            logger.debug("Setting time servers:")
            for server in ntp_servers:
                aug.set('{}/server[last()+1]'.format(path), server)
                aug.set('{}/server[last()]/iburst'.format(path), None)
                logger.debug("'%s'", server)

        # backup oginal conf file
        logger.debug("Backing up '%s'", chrony_conf)
        __backup_config(chrony_conf, fstore)

        logger.debug("Writing configuration to '%s'", chrony_conf)
        aug.save()

        logger.info('Configuration of chrony was changed by installer.')
        configured = True

    except IOError:
        logger.error("Augeas failed to configure file %s", chrony_conf)
        configured = False
    except RuntimeError as e:
        logger.error("Configuration failed with: %s", e)
        configured = False
    finally:
        aug.close()

    tasks.restore_context(chrony_conf)
    return configured
Example #3
0
def get_configured_ifaces():
    aug = Augeas(flags=Augeas.NO_MODL_AUTOLOAD)
    aug.add_transform('interfaces', '/etc/network/interfaces')
    aug.load()
    base = '/files/etc/network/interfaces'
    for m in aug.match('%s/iface' % base):
        yield aug.get(m)
    aug.close()
Example #4
0
def execute(*args, **kw):
    if conf.has_section('example.org'):
        primary_domain = conf.get('kolab', 'primary_domain')

        if not primary_domain == 'example.org':
            utils.multiline_message(
                _("""
                            Copying the configuration section for 'example.org' over to
                            a section applicable to your domain '%s'.
                        """) % (primary_domain))

            conf.cfg_parser._sections[primary_domain] = \
                    conf.cfg_parser._sections['example.org']
            conf.cfg_parser._sections.pop('example.org')

            fp = open(conf.cli_keywords.config_file, "w+")
            conf.cfg_parser.write(fp)
            fp.close()

    if os.path.isfile('/etc/default/kolab-server'):
        myaugeas = Augeas()
        setting = os.path.join('/files/etc/default/kolab-server', 'START')
        if not myaugeas.get(setting) == 'yes':
            myaugeas.set(setting, 'yes')
            myaugeas.save()
        myaugeas.close()

    if os.path.isfile('/bin/systemctl'):
        if os.path.isfile('/etc/debian_version'):
            subprocess.call(
                ['/bin/systemctl', 'restart', 'kolab-server.service'])
        else:
            subprocess.call(['/bin/systemctl', 'restart', 'kolabd.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'kolabd', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service', 'kolab-server', 'restart'])
    else:
        log.error(_("Could not start the kolab server service."))

    if os.path.isfile('/bin/systemctl'):
        if os.path.isfile('/etc/debian_version'):
            subprocess.call(
                ['/bin/systemctl', 'enable', 'kolab-server.service'])
        else:
            subprocess.call(['/bin/systemctl', 'enable', 'kolabd.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'kolabd', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'kolab-server', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "kolab server service."))
Example #5
0
    def set_api_timeouts(self, timeout):
        # Determine the file to change
        if self.https:
            config_file = self.abiquo_ssl_conf
        else:
            config_file = self.abiquo_conf
        logging.info("Setting Proxy timeouts in %s" % config_file)

        # Set timeout using Augeas
        a = Augeas()
        for loc in a.match("/files%s/VirtualHost/*[arg='/api']" % config_file):
            proxy_pass = a.match("%s/*[self::directive='ProxyPass']" % loc)
            if len(proxy_pass) == 1:
                # Proxy timeout already exists
                logging.info("ProxyPass found")
                arg1 = a.get("%s/arg" % proxy_pass[0])
                arg2 = "timeout=%s" % timeout
                a.set("%s/arg[1]" % proxy_pass[0], arg1)
                a.set("%s/arg[2]" % proxy_pass[0], arg2)

            a.save()
            a.close()
Example #6
0
    def set_api_timeouts(self, timeout):
        # Determine the file to change
        if self.https:
            config_file = self.abiquo_ssl_conf
        else:
            config_file = self.abiquo_conf
        logging.info("Setting Proxy timeouts in %s" % config_file)

        # Set timeout using Augeas
        a = Augeas()
        for loc in a.match("/files%s/VirtualHost/*[arg='/api']" % config_file):
            proxy_pass = a.match("%s/*[self::directive='ProxyPass']" % loc)
            if len(proxy_pass) == 1:
                # Proxy timeout already exists
                logging.info("ProxyPass found")
                arg1 = a.get("%s/arg" % proxy_pass[0])
                arg2 = "timeout=%s" % timeout
                a.set("%s/arg[1]" % proxy_pass[0], arg1)
                a.set("%s/arg[2]" % proxy_pass[0], arg2)

            a.save()
            a.close()
Example #7
0
class AugeasWrapper(object):
    """python-augeas higher-level wrapper.

    Load single augeas lens and configuration file.
    Exposes configuration file as AugeasNode object with dict-like interface.

    AugeasWrapper can be used in with statement in the same way as file does.
    """
    def __init__(self,
                 confpath,
                 lens,
                 root=None,
                 loadpath=None,
                 flags=Augeas.NO_MODL_AUTOLOAD | Augeas.NO_LOAD
                 | Augeas.ENABLE_SPAN):
        """Parse configuration file using given lens.

        Params:
            confpath (str): Absolute path to the configuration file
            lens (str): Name of module containing Augeas lens
            root: passed down to original Augeas
            flags: passed down to original Augeas
            loadpath: passed down to original Augeas
            flags: passed down to original Augeas
        """
        log.debug('loadpath: %s', loadpath)
        log.debug('confpath: %s', confpath)
        self._aug = Augeas(root=root, loadpath=loadpath, flags=flags)

        # /augeas/load/{lens}
        aug_load_path = join(AUGEAS_LOAD_PATH, lens)
        # /augeas/load/{lens}/lens = {lens}.lns
        self._aug.set(join(aug_load_path, 'lens'), '%s.lns' % lens)
        # /augeas/load/{lens}/incl[0] = {confpath}
        self._aug.set(join(aug_load_path, 'incl[0]'), confpath)
        self._aug.load()

        errors = self._aug.match(AUGEAS_ERROR_PATH)
        if errors:
            err_msg = '\n'.join(
                ["{}: {}".format(e, self._aug.get(e)) for e in errors])
            raise RuntimeError(err_msg)

        path = join(AUGEAS_FILES_PATH, confpath)
        paths = self._aug.match(path)
        if len(paths) != 1:
            raise ValueError('path %s did not match exactly once' % path)
        self.tree = AugeasNode(self._aug, path)
        self._loaded = True

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.save()
        self.close()

    def save(self):
        """Save Augeas tree to its original file."""
        assert self._loaded
        try:
            self._aug.save()
        except IOError as exc:
            log.exception(exc)
            for err_path in self._aug.match('//error'):
                log.error('%s: %s', err_path,
                          self._aug.get(os.path.join(err_path, 'message')))
            raise

    def close(self):
        """
        close Augeas library

        After calling close() the object must not be used anymore.
        """
        assert self._loaded
        self._aug.close()
        del self._aug
        self._loaded = False

    def match(self, path):
        """Yield AugeasNodes matching given expression."""
        assert self._loaded
        assert path
        log.debug('tree match %s', path)
        for matched_path in self._aug.match(path):
            yield AugeasNode(self._aug, matched_path)
Example #8
0
class LVMConfig(object):

    def __init__(self, path="/etc/lvm/lvm.conf"):
        self.path = path

        # Augeas loads by default tons of unneeded lenses and configuration
        # files. On my test host, it fails to load, trying to read my 500 MiB
        # /etc/lvm/archive/.
        #
        # These are the standard LVM lens includes:
        # /augeas/load/LVM/incl[1] /etc/lvm/lvm.conf
        # /augeas/load/LVM/incl[2] /etc/lvm/backup/*
        # /augeas/load/LVM/incl[3] /etc/lvm/archive/*.vg
        #
        # We need only the first entry to work with lvm.conf. Using customized
        # load setup, as explained in
        # https://github.com/hercules-team/augeas/wiki/Loading-specific-files
        #
        # Removing the archive and backup entries, we can load augeas in 0.7
        # seconds on my test vm. Removing all other lenses shorten the time to
        # 0.04 seconds.

        log.debug("Loading LVM configuration from %r", path)
        self.aug = Augeas(flags=Augeas.NO_MODL_AUTOLOAD | Augeas.SAVE_BACKUP)
        self.aug.add_transform("lvm.lns", [path])
        self.aug.load()

    # Context manager interface

    def __enter__(self):
        return self

    def __exit__(self, t, v, tb):
        try:
            self.close()
        except Exception as e:
            # Caller succeeded, raise the close error.
            if t is None:
                raise
            # Caller has failed, do not hide the original error.
            log.exception("Error closing %s: %s" % (self, e))

    # Accessing list of strings

    def getlist(self, section, option):
        pat = "/files%s/%s/dict/%s/list/*/str" % (self.path, section, option)
        matches = self.aug.match(pat)
        if not matches:
            return None  # Cannot store/read empty list
        return [self.aug.get(m) for m in matches]

    def setlist(self, section, option, value):
        log.debug("Setting %s/%s to %s", section, option, value)
        opt_path = "/files%s/%s/dict/%s" % (self.path, section, option)
        self.aug.remove(opt_path)
        item_path = opt_path + "/list/%d/str"
        for i, item in enumerate(value, 1):
            self.aug.set(item_path % i, item)

    # Accessing flat values (int, string)

    def getint(self, section, option):
        val = self._get_flat(section, option, "int")
        return int(val) if val is not None else None

    def setint(self, section, option, value):
        self._set_flat(section, option, "int", str(value))

    def getstr(self, section, option):
        return self._get_flat(section, option, "str")

    def setstr(self, section, option, value):
        self._set_flat(section, option, "str", value)

    def _get_flat(self, section, option, opt_type):
        path = self._flat_path(section, option, opt_type)
        return self.aug.get(path)

    def _set_flat(self, section, option, opt_type, value):
        log.debug("Setting %s/%s to %r", section, option, value)
        path = self._flat_path(section, option, opt_type)
        return self.aug.set(path, value)

    def _flat_path(self, section, option, opt_type):
        return "/files%s/%s/dict/%s/%s" % (
            self.path, section, option, opt_type)

    # Removing options

    def remove(self, section, option):
        log.debug("Removing %s/%s", section, option)
        path = "/files%s/%s/dict/%s" % (self.path, section, option)
        self.aug.remove(path)

    # File operations

    def save(self):
        log.info("Saving new LVM configuration to %r, previous configuration "
                 "saved to %r",
                 self.path, self.path + ".augsave")
        self.aug.save()

    def close(self):
        log.debug("Closing LVM configuration %s", self.path)
        self.aug.close()
Example #9
0
def execute(*args, **kw):

    group_filter = conf.get('ldap', 'kolab_group_filter')
    if group_filter == None:
        group_filter = conf.get('ldap', 'group_filter')

    user_filter = conf.get('ldap', 'kolab_user_filter')
    if user_filter == None:
        user_filter = conf.get('ldap', 'user_filter')

    resource_filter = conf.get('ldap', 'resource_filter')

    sharedfolder_filter = conf.get('ldap', 'sharedfolder_filter')

    server_host = utils.parse_ldap_uri(conf.get('ldap', 'ldap_uri'))[1]

    files = {
        "/etc/postfix/ldap/local_recipient_maps.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(|%(kolab_user_filter)s%(kolab_group_filter)s%(resource_filter)s%(sharedfolder_filter)s))
result_attribute = mail
""" % {
            "base_dn": conf.get('ldap', 'base_dn'),
            "server_host": server_host,
            "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
            "kolab_user_filter": user_filter,
            "kolab_group_filter": group_filter,
            "resource_filter": resource_filter,
            "sharedfolder_filter": sharedfolder_filter,
        },
        "/etc/postfix/ldap/mydestination.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(domain_base_dn)s
scope = sub

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = %(domain_filter)s
result_attribute = %(domain_name_attribute)s
""" % {
            "server_host": server_host,
            "domain_base_dn": conf.get('ldap', 'domain_base_dn'),
            "domain_filter": conf.get('ldap', 'domain_filter').replace(
                '*', '%s'),
            "domain_name_attribute": conf.get('ldap', 'domain_name_attribute'),
            "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
        },
        "/etc/postfix/ldap/mailenabled_distgroups.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(group_base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

# This finds the mail enabled distribution group LDAP entry
query_filter = (&(|(mail=%%s)(alias=%%s))(objectClass=kolabgroupofuniquenames)(objectclass=groupofuniquenames)(!(objectclass=groupofurls)))
# From this type of group, get all uniqueMember DNs
special_result_attribute = uniqueMember
# Only from those DNs, get the mail
result_attribute =
leaf_result_attribute = mail
""" % {
            "server_host": server_host,
            "group_base_dn": conf.get('ldap', 'group_base_dn'),
            "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
        },
        "/etc/postfix/ldap/mailenabled_dynamic_distgroups.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(group_base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

# This finds the mail enabled dynamic distribution group LDAP entry
query_filter = (&(|(mail=%%s)(alias=%%s))(objectClass=kolabgroupofuniquenames)(objectClass=groupOfURLs))
# From this type of group, get all memberURL searches/references
special_result_attribute = memberURL
# Only from those DNs, get the mail
result_attribute =
leaf_result_attribute = mail
""" % {
            "server_host": server_host,
            "group_base_dn": conf.get('ldap', 'group_base_dn'),
            "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
        },
        "/etc/postfix/ldap/transport_maps.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mailAlternateAddress=%%s)(alias=%%s)(mail=%%s))(objectclass=kolabinetorgperson))
result_attribute = mail
result_format = lmtp:unix:/var/lib/imap/socket/lmtp
""" % {
            "base_dn": conf.get('ldap', 'base_dn'),
            "server_host": server_host,
            "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
        },
        "/etc/postfix/ldap/virtual_alias_maps.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(objectclass=kolabinetorgperson))
result_attribute = mail
""" % {
            "base_dn": conf.get('ldap', 'base_dn'),
            "server_host": server_host,
            "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
        },
        "/etc/postfix/ldap/virtual_alias_maps_mailforwarding.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(objectclass=mailrecipient)(objectclass=inetorgperson)(mailforwardingaddress=*))
result_attribute = mailForwardingAddress
""" % {
            "base_dn": conf.get('ldap', 'base_dn'),
            "server_host": server_host,
            "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
        },
        "/etc/postfix/ldap/virtual_alias_maps_sharedfolders.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(objectclass=kolabsharedfolder)(kolabFolderType=mail))
result_attribute = kolabtargetfolder
result_format = "shared+%%s"
""" % {
            "base_dn": conf.get('ldap', 'base_dn'),
            "server_host": server_host,
            "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
        },
    }

    if not os.path.isdir('/etc/postfix/ldap'):
        os.mkdir('/etc/postfix/ldap/', 0770)

    for filename in files.keys():
        fp = open(filename, 'w')
        fp.write(files[filename])
        fp.close()

    fp = open('/etc/postfix/transport', 'a')
    fp.write(
        "\n# Shared Folder Delivery for %(domain)s:\nshared@%(domain)s\t\tlmtp:unix:/var/lib/imap/socket/lmtp\n"
        % {'domain': conf.get('kolab', 'primary_domain')})
    fp.close()

    subprocess.call(["postmap", "/etc/postfix/transport"])

    postfix_main_settings = {
        "inet_interfaces": "all",
        "recipient_delimiter": "+",
        "local_recipient_maps":
        "ldap:/etc/postfix/ldap/local_recipient_maps.cf",
        "mydestination": "ldap:/etc/postfix/ldap/mydestination.cf",
        "transport_maps":
        "ldap:/etc/postfix/ldap/transport_maps.cf, hash:/etc/postfix/transport",
        "virtual_alias_maps":
        "$alias_maps, ldap:/etc/postfix/ldap/virtual_alias_maps.cf, ldap:/etc/postfix/ldap/virtual_alias_maps_mailforwarding.cf, ldap:/etc/postfix/ldap/virtual_alias_maps_sharedfolders.cf, ldap:/etc/postfix/ldap/mailenabled_distgroups.cf, ldap:/etc/postfix/ldap/mailenabled_dynamic_distgroups.cf",
        "smtpd_tls_auth_only": "yes",
        "smtpd_tls_security_level": "may",
        "smtp_tls_security_level": "may",
        "smtpd_sasl_auth_enable": "yes",
        "smtpd_sender_login_maps": "$local_recipient_maps",
        "smtpd_data_restrictions":
        "permit_mynetworks, check_policy_service unix:private/recipient_policy_incoming",
        "smtpd_recipient_restrictions":
        "permit_mynetworks, reject_unauth_pipelining, reject_rbl_client zen.spamhaus.org, reject_non_fqdn_recipient, reject_invalid_helo_hostname, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service unix:private/recipient_policy_incoming, permit",
        "smtpd_sender_restrictions":
        "permit_mynetworks, reject_sender_login_mismatch, check_policy_service unix:private/sender_policy_incoming",
        "submission_recipient_restrictions":
        "check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject",
        "submission_sender_restrictions":
        "reject_non_fqdn_sender, check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject",
        "submission_data_restrictions":
        "check_policy_service unix:private/submission_policy",
        "content_filter": "smtp-amavis:[127.0.0.1]:10024"
    }

    if os.path.isfile(
            '/etc/pki/tls/certs/make-dummy-cert'
    ) and not os.path.isfile('/etc/pki/tls/private/localhost.pem'):
        subprocess.call([
            '/etc/pki/tls/certs/make-dummy-cert',
            '/etc/pki/tls/private/localhost.pem'
        ])

    if os.path.isfile('/etc/pki/tls/private/localhost.pem'):
        postfix_main_settings[
            'smtpd_tls_cert_file'] = "/etc/pki/tls/private/localhost.pem"
        postfix_main_settings[
            'smtpd_tls_key_file'] = "/etc/pki/tls/private/localhost.pem"

    if not os.path.isfile('/etc/postfix/main.cf'):
        if os.path.isfile('/usr/share/postfix/main.cf.debian'):
            shutil.copy('/usr/share/postfix/main.cf.debian',
                        '/etc/postfix/main.cf')

    # Copy header checks files
    for hc_file in ['inbound', 'internal', 'submission']:
        if not os.path.isfile("/etc/postfix/header_checks.%s" % (hc_file)):
            if os.path.isfile('/etc/kolab/templates/header_checks.%s' %
                              (hc_file)):
                input_file = '/etc/kolab/templates/header_checks.%s' % (
                    hc_file)
            elif os.path.isfile('/usr/share/kolab/templates/header_checks.%s' %
                                (hc_file)):
                input_file = '/usr/share/kolab/templates/header_checks.%s' % (
                    hc_file)
            elif os.path.isfile(
                    os.path.abspath(
                        os.path.join(__file__, '..', '..', '..', 'share',
                                     'templates',
                                     'header_checks.%s' % (hc_file)))):
                input_file = os.path.abspath(
                    os.path.join(__file__, '..', '..', '..', 'share',
                                 'templates', 'header_checks.%s' % (hc_file)))

            shutil.copy(input_file,
                        "/etc/postfix/header_checks.%s" % (hc_file))
            subprocess.call(
                ["postmap",
                 "/etc/postfix/header_checks.%s" % (hc_file)])

    myaugeas = Augeas()

    setting_base = '/files/etc/postfix/main.cf/'

    for setting_key in postfix_main_settings.keys():
        setting = os.path.join(setting_base, setting_key)
        current_value = myaugeas.get(setting)

        if current_value == None:
            try:
                myaugeas.set(setting, postfix_main_settings[setting_key])
            except:
                insert_paths = myaugeas.match('/files/etc/postfix/main.cf/*')
                insert_path = insert_paths[(len(insert_paths) - 1)]
                myaugeas.insert(insert_path, setting_key, False)

        log.debug(_("Setting key %r to %r") %
                  (setting_key, postfix_main_settings[setting_key]),
                  level=8)
        myaugeas.set(setting, postfix_main_settings[setting_key])

    myaugeas.save()

    postfix_master_settings = {}

    if os.path.exists('/usr/lib/postfix/kolab_smtp_access_policy'):
        postfix_master_settings[
            'kolab_sap_executable_path'] = '/usr/lib/postfix/kolab_smtp_access_policy'
    else:
        postfix_master_settings[
            'kolab_sap_executable_path'] = '/usr/libexec/postfix/kolab_smtp_access_policy'

    template_file = None

    if os.path.isfile('/etc/kolab/templates/master.cf.tpl'):
        template_file = '/etc/kolab/templates/master.cf.tpl'
    elif os.path.isfile('/usr/share/kolab/templates/master.cf.tpl'):
        template_file = '/usr/share/kolab/templates/master.cf.tpl'
    elif os.path.isfile(
            os.path.abspath(
                os.path.join(__file__, '..', '..', '..', 'share', 'templates',
                             'master.cf.tpl'))):
        template_file = os.path.abspath(
            os.path.join(__file__, '..', '..', '..', 'share', 'templates',
                         'master.cf.tpl'))

    if not template_file == None:
        fp = open(template_file, 'r')
        template_definition = fp.read()
        fp.close()

        t = Template(template_definition, searchList=[postfix_master_settings])
        fp = open('/etc/postfix/master.cf', 'w')
        fp.write(t.__str__())
        fp.close()

    else:
        log.error(
            _("Could not write out Postfix configuration file /etc/postfix/master.cf"
              ))
        return

    if os.path.isdir('/etc/postfix/sasl/'):
        fp = open('/etc/postfix/sasl/smtpd.conf', 'w')
        fp.write("pwcheck_method: saslauthd\n")
        fp.write("mech_list: plain login\n")
        fp.close()

    amavisd_settings = {
        'ldap_server': '%(server_host)s',
        'ldap_bind_dn': conf.get('ldap', 'service_bind_dn'),
        'ldap_bind_pw': conf.get('ldap', 'service_bind_pw'),
        'primary_domain': conf.get('kolab', 'primary_domain'),
        'ldap_filter': "(|(mail=%m)(alias=%m))",
        'ldap_base_dn': conf.get('ldap', 'base_dn'),
        'clamdsock': '/var/spool/amavisd/clamd.sock',
    }

    template_file = None

    # On RPM installations, Amavis configuration is contained within a single file.
    amavisconf_paths = [
        "/etc/amavisd.conf", "/etc/amavis/amavisd.conf",
        "/etc/amavisd/amavisd.conf"
    ]

    amavis_conf = ''
    for amavisconf_path in amavisconf_paths:
        if os.path.isfile(amavisconf_path):
            amavis_conf = amavisconf_path
            break

    if os.path.isfile(amavis_conf):
        if os.path.isfile('/etc/kolab/templates/amavisd.conf.tpl'):
            template_file = '/etc/kolab/templates/amavisd.conf.tpl'
        elif os.path.isfile('/usr/share/kolab/templates/amavisd.conf.tpl'):
            template_file = '/usr/share/kolab/templates/amavisd.conf.tpl'
        elif os.path.isfile(
                os.path.abspath(
                    os.path.join(__file__, '..', '..', '..', 'share',
                                 'templates', 'amavisd.conf.tpl'))):
            template_file = os.path.abspath(
                os.path.join(__file__, '..', '..', '..', 'share', 'templates',
                             'amavisd.conf.tpl'))

        if not template_file == None:
            fp = open(template_file, 'r')
            template_definition = fp.read()
            fp.close()

            if os.path.isfile('/etc/clamd.d/amavisd.conf'):
                amavisdconf_content = file('/etc/clamd.d/amavisd.conf')
                for line in amavisdconf_content:
                    if line.startswith('LocalSocket'):
                        amavisd_settings['clamdsock'] = line[len('LocalSocket '
                                                                 ):].strip()

            t = Template(template_definition, searchList=[amavisd_settings])

        fp = None
        fp = open(amavis_conf, 'w')

        if not fp == None:
            fp.write(t.__str__())
            fp.close()

        else:
            log.error(
                _("Could not write out Amavis configuration file amavisd.conf")
            )
            return

    # On APT installations, /etc/amavis/conf.d/ is a directory with many more files.
    #
    # Somebody could work on enhancement request #1080 to configure LDAP lookups,
    # while really it isn't required.
    else:
        log.info(_("Not writing out any configuration for Amavis."))

    # On debian wheezy amavisd-new expects '/etc/mailname' - possibly remediable through
    # the #1080 enhancement mentioned above, but here's a quick fix.
    f = open('/etc/mailname', 'w')
    f.writelines(conf.get('kolab', 'primary_domain'))
    f.close()

    if os.path.isfile('/etc/default/spamassassin'):
        myaugeas = Augeas()
        setting = os.path.join('/files/etc/default/spamassassin', 'ENABLED')
        if not myaugeas.get(setting) == '1':
            myaugeas.set(setting, '1')
            myaugeas.save()
        myaugeas.close()

    if os.path.isfile('/etc/default/wallace'):
        myaugeas = Augeas()
        setting = os.path.join('/files/etc/default/wallace', 'START')
        if not myaugeas.get(setting) == 'yes':
            myaugeas.set(setting, 'yes')
            myaugeas.save()
        myaugeas.close()

    if os.path.isfile('/usr/lib/systemd/system/[email protected]'):
        from ConfigParser import SafeConfigParser
        unitfile = SafeConfigParser()
        unitfile.optionxform = str
        unitfile.read('/usr/lib/systemd/system/[email protected]')
        if not unitfile.has_section('Install'):
            unitfile.add_section('Install')

        if not unitfile.has_option('Install', 'WantedBy'):
            unitfile.set('Install', 'WantedBy', 'multi-user.target')

        with open('/etc/systemd/system/[email protected]', 'wb') as f:
            unitfile.write(f)

    log.info(_("Configuring and refreshing Anti-Virus..."))

    if os.path.isfile('/etc/kolab/templates/freshclam.conf.tpl'):
        shutil.copy('/etc/kolab/templates/freshclam.conf.tpl',
                    '/etc/freshclam.conf')
    elif os.path.isfile('/usr/share/kolab/templates/freshclam.conf.tpl'):
        shutil.copy('/usr/share/kolab/templates/freshclam.conf.tpl',
                    '/etc/freshclam.conf')
    else:
        log.error(_("Could not find a ClamAV update configuration file"))

    if os.path.isfile('/etc/freshclam.conf'):
        subprocess.call(
            ['/usr/bin/freshclam', '--quiet', '--datadir="/var/lib/clamav"'])

    amavisservice = 'amavisd.service'
    clamavservice = '*****@*****.**'

    if os.path.isfile('/usr/lib/systemd/system/amavis.service'):
        amavisservice = 'amavis.service'

    if os.path.isfile('/lib/systemd/system/amavis.service'):
        amavisservice = 'amavis.service'

    if os.path.isfile('/usr/lib/systemd/system/clamd.service'):
        clamavservice = 'clamd.service'

    if os.path.isfile('/lib/systemd/system/clamd.service'):
        clamavservice = 'clamd.service'

    if os.path.isfile('/lib/systemd/system/clamav-daemon.service'):
        clamavservice = 'clamav-daemon.service'

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'restart', 'postfix.service'])
        subprocess.call(['systemctl', 'restart', amavisservice])
        subprocess.call(['systemctl', 'restart', clamavservice])
        subprocess.call(['systemctl', 'restart', 'wallace.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['service', 'postfix', 'restart'])
        subprocess.call(['service', 'amavisd', 'restart'])
        subprocess.call(['service', 'clamd.amavisd', 'restart'])
        subprocess.call(['service', 'wallace', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service', 'postfix', 'restart'])
        subprocess.call(['/usr/sbin/service', 'amavis', 'restart'])
        subprocess.call(['/usr/sbin/service', 'clamav-daemon', 'restart'])
        subprocess.call(['/usr/sbin/service', 'wallace', 'restart'])
    else:
        log.error(
            _("Could not start the postfix, clamav and amavisd services services."
              ))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'enable', 'postfix.service'])
        subprocess.call(['systemctl', 'enable', amavisservice])
        subprocess.call(['systemctl', 'enable', clamavservice])
        subprocess.call(['systemctl', 'enable', 'wallace.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['chkconfig', 'postfix', 'on'])
        subprocess.call(['chkconfig', 'amavisd', 'on'])
        subprocess.call(['chkconfig', 'clamd.amavisd', 'on'])
        subprocess.call(['chkconfig', 'wallace', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'postfix', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'amavis', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'clamav-daemon', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'wallace', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "postfix, clamav and amavisd services."))
Example #10
0
def execute(*args, **kw):
    """
        Apply the necessary settings to /etc/imapd.conf
    """

    imapd_settings = {
        "ldap_servers":
        conf.get('ldap', 'ldap_uri'),
        "ldap_base":
        conf.get('ldap', 'base_dn'),
        "ldap_bind_dn":
        conf.get('ldap', 'service_bind_dn'),
        "ldap_password":
        conf.get('ldap', 'service_bind_pw'),
        "ldap_filter":
        '(|(&(|(uid=%s)(uid=cyrus-murder))(uid=%%U))(&(|(uid=%%U)(mail=%%U@%%d)(mail=%%U@%%r))(objectclass=kolabinetorgperson)))'
        % (conf.get('cyrus-imap', 'admin_login')),
        "ldap_user_attribute":
        conf.get('cyrus-sasl', 'result_attribute'),
        "ldap_group_base":
        conf.get('ldap', 'base_dn'),
        "ldap_group_filter":
        "(&(cn=%u)(objectclass=ldapsubentry)(objectclass=nsroledefinition))",
        "ldap_group_scope":
        "one",
        "ldap_member_base":
        conf.get('ldap', 'user_base_dn'),
        "ldap_member_method":
        "attribute",
        "ldap_member_attribute":
        "nsrole",
        "admins":
        conf.get('cyrus-imap', 'admin_login'),
        "postuser":
        "******",
    }

    template_file = None

    if os.path.isfile('/etc/kolab/templates/imapd.conf.tpl'):
        template_file = '/etc/kolab/templates/imapd.conf.tpl'
    elif os.path.isfile('/usr/share/kolab/templates/imapd.conf.tpl'):
        template_file = '/usr/share/kolab/templates/imapd.conf.tpl'
    elif os.path.isfile(
            os.path.abspath(
                os.path.join(__file__, '..', '..', '..', 'share', 'templates',
                             'imapd.conf.tpl'))):
        template_file = os.path.abspath(
            os.path.join(__file__, '..', '..', '..', 'share', 'templates',
                         'imapd.conf.tpl'))

    if not template_file == None:
        fp = open(template_file, 'r')
        template_definition = fp.read()
        fp.close()

        t = Template(template_definition, searchList=[imapd_settings])
        fp = open('/etc/imapd.conf', 'w')
        fp.write(t.__str__())
        fp.close()

    else:
        log.error(
            _("Could not write out Cyrus IMAP configuration file /etc/imapd.conf"
              ))
        return

    cyrus_settings = {}

    template_file = None

    if os.path.isfile('/etc/kolab/templates/cyrus.conf.tpl'):
        template_file = '/etc/kolab/templates/cyrus.conf.tpl'
    elif os.path.isfile('/usr/share/kolab/templates/cyrus.conf.tpl'):
        template_file = '/usr/share/kolab/templates/cyrus.conf.tpl'
    elif os.path.isfile(
            os.path.abspath(
                os.path.join(__file__, '..', '..', '..', 'share', 'templates',
                             'cyrus.conf.tpl'))):
        template_file = os.path.abspath(
            os.path.join(__file__, '..', '..', '..', 'share', 'templates',
                         'cyrus.conf.tpl'))

    if not template_file == None:
        fp = open(template_file, 'r')
        template_definition = fp.read()
        fp.close()

        t = Template(template_definition, searchList=[cyrus_settings])
        fp = open('/etc/cyrus.conf', 'w')
        fp.write(t.__str__())
        fp.close()

    else:
        log.error(
            _("Could not write out Cyrus IMAP configuration file /etc/cyrus.conf"
              ))
        return

    annotations = [
        "/vendor/kolab/activesync,mailbox,string,backend,value.priv,r",
        "/vendor/kolab/color,mailbox,string,backend,value.shared value.priv,a",
        "/vendor/kolab/displayname,mailbox,string,backend,value.shared value.priv,a",
        "/vendor/kolab/folder-test,mailbox,string,backend,value.shared value.priv,a",
        "/vendor/kolab/folder-type,mailbox,string,backend,value.shared value.priv,a",
        "/vendor/kolab/incidences-for,mailbox,string,backend,value.shared value.priv,a",
        "/vendor/kolab/pxfb-readable-for,mailbox,string,backend,value.shared value.priv,a",
        "/vendor/kolab/uniqueid,mailbox,string,backend,value.shared value.priv,a",
        "/vendor/kolab/h-share-attr-desc,mailbox,string,backend,value.shared value.priv,a",
        "/vendor/horde/share-params,mailbox,string,backend,value.shared value.priv,a",
        "/vendor/x-toltec/test,mailbox,string,backend,value.shared value.priv,a",
    ]

    fp = open('/etc/imapd.annotations.conf', 'w')
    fp.write("\n".join(annotations))
    fp.close()

    if os.path.isfile('/etc/default/kolab-saslauthd'):
        myaugeas = Augeas()
        setting = os.path.join('/files/etc/default/kolab-saslauthd', 'START')

        if not myaugeas.get(setting) == 'yes':
            myaugeas.set(setting, 'yes')
            myaugeas.save()

        myaugeas.close()

    imapservice = 'cyrus-imapd.service'
    if os.path.isfile('/usr/lib/systemd/system/cyrus.service'):
        imapservice = 'cyrus.service'

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'stop', 'saslauthd.service'])
        subprocess.call(['systemctl', 'restart', 'kolab-saslauthd.service'])
        subprocess.call(['systemctl', 'restart', imapservice])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['service', 'saslauthd', 'stop'])
        subprocess.call(['service', 'kolab-saslauthd', 'restart'])
        subprocess.call(['service', 'cyrus-imapd', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service', 'saslauthd', 'stop'])
        subprocess.call(['/usr/sbin/service', 'kolab-saslauthd', 'restart'])
        subprocess.call(['/usr/sbin/service', 'cyrus-imapd', 'restart'])
    else:
        log.error(
            _("Could not start the cyrus-imapd and kolab-saslauthd services."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'disable', 'saslauthd.service'])
        subprocess.call(['systemctl', 'enable', 'kolab-saslauthd.service'])
        subprocess.call(['systemctl', 'enable', imapservice])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['chkconfig', 'saslauthd', 'off'])
        subprocess.call(['chkconfig', 'kolab-saslauthd', 'on'])
        subprocess.call(['chkconfig', 'cyrus-imapd', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'saslauthd', 'disable'])
        subprocess.call(
            ['/usr/sbin/update-rc.d', 'kolab-saslauthd', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'cyrus-imapd', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "cyrus-imapd and kolab-saslauthd services."))
Example #11
0
def execute(*args, **kw):

    group_filter = conf.get('ldap','kolab_group_filter')
    if group_filter == None:
        group_filter = conf.get('ldap','group_filter')

    user_filter = conf.get('ldap','kolab_user_filter')
    if user_filter == None:
        user_filter = conf.get('ldap','user_filter')

    resource_filter = conf.get('ldap', 'resource_filter')

    sharedfolder_filter = conf.get('ldap', 'sharedfolder_filter')

    server_host = utils.parse_ldap_uri(conf.get('ldap', 'ldap_uri'))[1]

    files = {
            "/etc/postfix/ldap/local_recipient_maps.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(|%(kolab_user_filter)s%(kolab_group_filter)s%(resource_filter)s%(sharedfolder_filter)s))
result_attribute = mail
""" % {
                        "base_dn": conf.get('ldap', 'base_dn'),
                        "server_host": server_host,
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                        "kolab_user_filter": user_filter,
                        "kolab_group_filter": group_filter,
                        "resource_filter": resource_filter,
                        "sharedfolder_filter": sharedfolder_filter,
                    },
            "/etc/postfix/ldap/mydestination.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(domain_base_dn)s
scope = sub

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = %(domain_filter)s
result_attribute = %(domain_name_attribute)s
""" % {
                        "server_host": server_host,
                        "domain_base_dn": conf.get('ldap', 'domain_base_dn'),
                        "domain_filter": conf.get('ldap', 'domain_filter').replace('*', '%s'),
                        "domain_name_attribute": conf.get('ldap', 'domain_name_attribute'),
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/mailenabled_distgroups.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(group_base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

# This finds the mail enabled distribution group LDAP entry
query_filter = (&(|(mail=%%s)(alias=%%s))(objectClass=kolabgroupofuniquenames)(objectclass=groupofuniquenames)(!(objectclass=groupofurls)))
# From this type of group, get all uniqueMember DNs
special_result_attribute = uniqueMember
# Only from those DNs, get the mail
result_attribute =
leaf_result_attribute = mail
""" % {
                        "server_host": server_host,
                        "group_base_dn": conf.get('ldap', 'group_base_dn'),
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/mailenabled_dynamic_distgroups.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(group_base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

# This finds the mail enabled dynamic distribution group LDAP entry
query_filter = (&(|(mail=%%s)(alias=%%s))(objectClass=kolabgroupofuniquenames)(objectClass=groupOfURLs))
# From this type of group, get all memberURL searches/references
special_result_attribute = memberURL
# Only from those DNs, get the mail
result_attribute =
leaf_result_attribute = mail
""" % {
                        "server_host": server_host,
                        "group_base_dn": conf.get('ldap', 'group_base_dn'),
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/transport_maps.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mailAlternateAddress=%%s)(alias=%%s)(mail=%%s))(objectclass=kolabinetorgperson))
result_attribute = mail
result_format = lmtp:unix:/var/lib/imap/socket/lmtp
""" % {
                        "base_dn": conf.get('ldap', 'base_dn'),
                        "server_host": server_host,
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/virtual_alias_maps.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(objectclass=kolabinetorgperson))
result_attribute = mail
""" % {
                        "base_dn": conf.get('ldap', 'base_dn'),
                        "server_host": server_host,
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/virtual_alias_maps_mailforwarding.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(objectclass=mailrecipient)(objectclass=inetorgperson)(mailforwardingaddress=*))
result_attribute = mailForwardingAddress
""" % {
                        "base_dn": conf.get('ldap', 'base_dn'),
                        "server_host": server_host,
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/virtual_alias_maps_sharedfolders.cf": """
server_host = %(server_host)s
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(objectclass=kolabsharedfolder)(kolabFolderType=mail))
result_attribute = kolabtargetfolder
result_format = shared+%%s
""" % {
                        "base_dn": conf.get('ldap', 'base_dn'),
                        "server_host": server_host,
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
        }

    if not os.path.isdir('/etc/postfix/ldap'):
        os.mkdir('/etc/postfix/ldap/', 0770)

    for filename in files.keys():
        fp = open(filename, 'w')
        fp.write(files[filename])
        fp.close()

    fp = open('/etc/postfix/transport', 'a')
    fp.write("\n# Shared Folder Delivery for %(domain)s:\nshared@%(domain)s\t\tlmtp:unix:/var/lib/imap/socket/lmtp\n" % {'domain': conf.get('kolab', 'primary_domain')})
    fp.close()

    subprocess.call(["postmap", "/etc/postfix/transport"])

    postfix_main_settings = {
            "inet_interfaces": "all",
            "recipient_delimiter": "+",
            "local_recipient_maps": "ldap:/etc/postfix/ldap/local_recipient_maps.cf",
            "mydestination": "ldap:/etc/postfix/ldap/mydestination.cf",
            "transport_maps": "ldap:/etc/postfix/ldap/transport_maps.cf, hash:/etc/postfix/transport",
            "virtual_alias_maps": "$alias_maps, ldap:/etc/postfix/ldap/virtual_alias_maps.cf, ldap:/etc/postfix/ldap/virtual_alias_maps_mailforwarding.cf, ldap:/etc/postfix/ldap/virtual_alias_maps_sharedfolders.cf, ldap:/etc/postfix/ldap/mailenabled_distgroups.cf, ldap:/etc/postfix/ldap/mailenabled_dynamic_distgroups.cf",
            "smtpd_tls_auth_only": "yes",
            "smtpd_tls_security_level": "may",
            "smtp_tls_security_level": "may",
            "smtpd_sasl_auth_enable": "yes",
            "smtpd_sender_login_maps": "$local_recipient_maps",
            "smtpd_sender_restrictions": "permit_mynetworks, reject_sender_login_mismatch",
            "smtpd_recipient_restrictions": "permit_mynetworks, reject_unauth_pipelining, reject_rbl_client zen.spamhaus.org, reject_non_fqdn_recipient, reject_invalid_helo_hostname, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service unix:private/recipient_policy_incoming, permit",
            "smtpd_sender_restrictions": "permit_mynetworks, check_policy_service unix:private/sender_policy_incoming",
            "submission_recipient_restrictions": "check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject",
            "submission_sender_restrictions": "reject_non_fqdn_sender, check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject",
            "submission_data_restrictions": "check_policy_service unix:private/submission_policy",
            "content_filter": "smtp-amavis:[127.0.0.1]:10024"

        }

    if os.path.isfile('/etc/pki/tls/certs/make-dummy-cert') and not os.path.isfile('/etc/pki/tls/private/localhost.pem'):
        subprocess.call(['/etc/pki/tls/certs/make-dummy-cert', '/etc/pki/tls/private/localhost.pem'])

    if os.path.isfile('/etc/pki/tls/private/localhost.pem'):
        postfix_main_settings['smtpd_tls_cert_file'] = "/etc/pki/tls/private/localhost.pem"
        postfix_main_settings['smtpd_tls_key_file'] = "/etc/pki/tls/private/localhost.pem"

    if not os.path.isfile('/etc/postfix/main.cf'):
        if os.path.isfile('/usr/share/postfix/main.cf.debian'):
            shutil.copy(
                    '/usr/share/postfix/main.cf.debian',
                    '/etc/postfix/main.cf'
                )

    # Copy header checks files
    for hc_file in [ 'inbound', 'internal', 'submission' ]:
        if not os.path.isfile("/etc/postfix/header_checks.%s" % (hc_file)):
            if os.path.isfile('/etc/kolab/templates/header_checks.%s' % (hc_file)):
                input_file = '/etc/kolab/templates/header_checks.%s' % (hc_file)
            elif os.path.isfile('/usr/share/kolab/templates/header_checks.%s' % (hc_file)):
                input_file = '/usr/share/kolab/templates/header_checks.%s' % (hc_file)
            elif os.path.isfile(os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'header_checks.%s' % (hc_file)))):
                input_file = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'header_checks.%s' % (hc_file)))

            shutil.copy(input_file, "/etc/postfix/header_checks.%s" % (hc_file))
            subprocess.call(["postmap", "/etc/postfix/header_checks.%s" % (hc_file)])

    myaugeas = Augeas()

    setting_base = '/files/etc/postfix/main.cf/'

    for setting_key in postfix_main_settings.keys():
        setting = os.path.join(setting_base,setting_key)
        current_value = myaugeas.get(setting)

        if current_value == None:
            try:
                myaugeas.set(setting, postfix_main_settings[setting_key])
            except:
                insert_paths = myaugeas.match('/files/etc/postfix/main.cf/*')
                insert_path = insert_paths[(len(insert_paths)-1)]
                myaugeas.insert(insert_path, setting_key, False)

        log.debug(_("Setting key %r to %r") % (setting_key, postfix_main_settings[setting_key]), level=8)
        myaugeas.set(setting, postfix_main_settings[setting_key])

    myaugeas.save()

    postfix_master_settings = {
        }

    if os.path.exists('/usr/lib/postfix/kolab_smtp_access_policy'):
        postfix_master_settings['kolab_sap_executable_path'] = '/usr/lib/postfix/kolab_smtp_access_policy'
    else:
        postfix_master_settings['kolab_sap_executable_path'] = '/usr/libexec/postfix/kolab_smtp_access_policy'

    template_file = None

    if os.path.isfile('/etc/kolab/templates/master.cf.tpl'):
        template_file = '/etc/kolab/templates/master.cf.tpl'
    elif os.path.isfile('/usr/share/kolab/templates/master.cf.tpl'):
        template_file = '/usr/share/kolab/templates/master.cf.tpl'
    elif os.path.isfile(os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'master.cf.tpl'))):
        template_file = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'master.cf.tpl'))

    if not template_file == None:
        fp = open(template_file, 'r')
        template_definition = fp.read()
        fp.close()

        t = Template(template_definition, searchList=[postfix_master_settings])
        fp = open('/etc/postfix/master.cf', 'w')
        fp.write(t.__str__())
        fp.close()

    else:
        log.error(_("Could not write out Postfix configuration file /etc/postfix/master.cf"))
        return

    if os.path.isdir('/etc/postfix/sasl/'):
        fp = open('/etc/postfix/sasl/smtpd.conf', 'w')
        fp.write("pwcheck_method: saslauthd\n")
        fp.write("mech_list: plain login\n")
        fp.close()

    amavisd_settings = {
            'ldap_server': '%(server_host)s',
            'ldap_bind_dn': conf.get('ldap', 'service_bind_dn'),
            'ldap_bind_pw': conf.get('ldap', 'service_bind_pw'),
            'primary_domain': conf.get('kolab', 'primary_domain'),
            'ldap_filter': "(|(mail=%m)(alias=%m))",
            'ldap_base_dn': conf.get('ldap', 'base_dn'),
        }

    template_file = None

    # On RPM installations, Amavis configuration is contained within a single file.
    if os.path.isfile("/etc/amavisd/amavisd.conf"):
        if os.path.isfile('/etc/kolab/templates/amavisd.conf.tpl'):
            template_file = '/etc/kolab/templates/amavisd.conf.tpl'
        elif os.path.isfile('/usr/share/kolab/templates/amavisd.conf.tpl'):
            template_file = '/usr/share/kolab/templates/amavisd.conf.tpl'
        elif os.path.isfile(os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'amavisd.conf.tpl'))):
            template_file = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'amavisd.conf.tpl'))

        if not template_file == None:
            fp = open(template_file, 'r')
            template_definition = fp.read()
            fp.close()

            t = Template(template_definition, searchList=[amavisd_settings])

        fp = None
        if os.path.isdir('/etc/amavisd'):
            fp = open('/etc/amavisd/amavisd.conf', 'w')
        elif os.path.isdir('/etc/amavis'):
            fp = open('/etc/amavis/amavisd.conf', 'w')
        elif os.path.isfile('/etc/amavisd.conf'):
            fp = open('/etc/amavisd.conf', 'w')

        if not fp == None:
            fp.write(t.__str__())
            fp.close()

        else:
            log.error(_("Could not write out Amavis configuration file amavisd.conf"))
            return

    # On APT installations, /etc/amavis/conf.d/ is a directory with many more files.
    #
    # Somebody could work on enhancement request #1080 to configure LDAP lookups,
    # while really it isn't required.
    else:
        log.info(_("Not writing out any configuration for Amavis."))

    # On debian wheezy amavisd-new expects '/etc/mailname' - possibly remediable through
    # the #1080 enhancement mentioned above, but here's a quick fix.
    f = open('/etc/mailname','w')
    f.writelines(conf.get('kolab', 'primary_domain'))
    f.close()

    if os.path.isfile('/etc/default/spamassassin'):
        myaugeas = Augeas()
        setting = os.path.join('/files/etc/default/spamassassin','ENABLED')
        if not myaugeas.get(setting) == '1':
            myaugeas.set(setting,'1')
            myaugeas.save()
        myaugeas.close()

    if os.path.isfile('/etc/default/wallace'):
        myaugeas = Augeas()
        setting = os.path.join('/files/etc/default/wallace','START')
        if not myaugeas.get(setting) == 'yes':
            myaugeas.set(setting,'yes')
            myaugeas.save()
        myaugeas.close()

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'restart', 'postfix.service'])
        subprocess.call(['systemctl', 'restart', 'amavisd.service'])
        subprocess.call(['systemctl', 'restart', '*****@*****.**'])
        subprocess.call(['systemctl', 'restart', 'wallace.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['service', 'postfix', 'restart'])
        subprocess.call(['service', 'amavisd', 'restart'])
        subprocess.call(['service', 'clamd.amavisd', 'restart'])
        subprocess.call(['service', 'wallace', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','postfix','restart'])
        subprocess.call(['/usr/sbin/service','amavis','restart'])
        subprocess.call(['/usr/sbin/service','clamav-daemon','restart'])
        subprocess.call(['/usr/sbin/service','wallace','restart'])
    else:
        log.error(_("Could not start the postfix, clamav and amavisd services services."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'enable', 'postfix.service'])
        subprocess.call(['systemctl', 'enable', 'amavisd.service'])
        subprocess.call(['systemctl', 'enable', '*****@*****.**'])
        subprocess.call(['systemctl', 'enable', 'wallace.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['chkconfig', 'postfix', 'on'])
        subprocess.call(['chkconfig', 'amavisd', 'on'])
        subprocess.call(['chkconfig', 'clamd.amavisd', 'on'])
        subprocess.call(['chkconfig', 'wallace', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'postfix', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'amavis', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'clamav-daemon', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'wallace', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "postfix, clamav and amavisd services."))
Example #12
0
class TestNode(unittest.TestCase):
    """Tests the Node class"""

    def setUp(self):
        self.tmp = tempfile.mkdtemp()
        self.root = "%s/root" % self.tmp
        shutil.copytree("%s/fakeroot" % os.path.dirname(__file__), self.root)

        self.aug = Augeas(root=self.root, flags=Augeas.NO_MODL_AUTOLOAD)
        self.aug.add_transform("Nsswitch.lns", "/etc/nsswitch.conf")
        self.aug.load()

        class FakeParent:
            def setpath(self):
                return "/files/etc/nsswitch.conf"
        self.parent = FakeParent()

    def tearDown(self):
        shutil.rmtree(self.tmp)
        self.aug.close()

    def test_setpath_self(self):
        """Test setpath generates path for '.' (itself)"""
        n = aug2cmds.Node(self.aug, self.parent, uniqpaths=["."],
                          path="/files/etc/nsswitch.conf/database[1]")
        self.assertEqual(n.setpath(),
                         "/files/etc/nsswitch.conf/database[.='passwd']")

    def test_setpath_subnode(self):
        """Test setpath generates path for a subnode"""
        n = aug2cmds.Node(self.aug, self.parent, uniqpaths=["service"],
                          path="/files/etc/nsswitch.conf/database[1]")
        self.assertEqual(n.setpath(),
                         "/files/etc/nsswitch.conf/database[service='files']")

    def test_setpath_and(self):
        """Test setpath generates path for multiple subpaths"""
        n = aug2cmds.Node(self.aug, self.parent, uniqpaths=[".", "service"],
                          path="/files/etc/nsswitch.conf/database[1]")
        self.assertEqual(n.setpath(),
          "/files/etc/nsswitch.conf/database[.='passwd' and service='files']")

    def test_basename(self):
        """Test basename understands Augeas paths"""
        self.assertEqual(aug2cmds.Node.basename("/files"), "files")
        self.assertEqual(aug2cmds.Node.basename("/files/test"), "test")
        self.assertEqual(aug2cmds.Node.basename("/files/test[foo]"), "test")
        self.assertEqual(aug2cmds.Node.basename(
                           "/files/test[foo/bar]"), "test")

    def test_dirname(self):
        """Test dirname understands Augeas paths"""
        self.assertEqual(aug2cmds.Node.dirname("/files"), "/")
        self.assertEqual(aug2cmds.Node.dirname("/files/test"), "/files")
        self.assertEqual(aug2cmds.Node.dirname("/files/test[foo]"), "/files")
        self.assertEqual(aug2cmds.Node.dirname(
                           "/files/test[foo/bar]"), "/files")

    def test_children_none(self):
        """Test when there are no children"""
        n = aug2cmds.Node(self.aug, self.parent,
                          "/files/etc/nsswitch.conf/#comment[1]", ["."])
        self.assertRaises(StopIteration, next, n.children())

    def test_children(self):
        """Test new Node objects are created for children"""
        n = aug2cmds.Node(self.aug, self.parent,
                          "/files/etc/nsswitch.conf/database[15]", ["."])
        c = n.children()
        sn = c.next()
        self.assertEqual(sn.path,
          "/files/etc/nsswitch.conf/database[15]/service[1]")
        self.assertEqual(sn.setpath(),
          "/files/etc/nsswitch.conf/database[.='aliases']/service[.='files']")

        sn = c.next()
        self.assertEqual(sn.path,
          "/files/etc/nsswitch.conf/database[15]/service[2]")
        self.assertEqual(sn.setpath(),
          "/files/etc/nsswitch.conf/database[.='aliases']/service[.='nisplus']")

        self.assertRaises(StopIteration, next, c)

    def test_value(self):
        """Test value is retrieved"""
        n = aug2cmds.Node(self.aug, self.parent, uniqpaths=["."],
                          path="/files/etc/nsswitch.conf/database[1]")
        self.assertEqual(n.value(), "passwd")

    def test_value_none(self):
        """Test when no value is set"""
        n = aug2cmds.Node(self.aug, self.parent, uniqpaths=["."],
                          path="/files/etc/nsswitch.conf")
        self.assertEqual(n.value(), None)
Example #13
0
def execute(*args, **kw):
    """
        Apply the necessary settings to /etc/imapd.conf
    """

    imapd_settings = {
            "ldap_servers": conf.get('ldap', 'ldap_uri'),
            "ldap_base": conf.get('ldap', 'base_dn'),
            "ldap_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "ldap_password": conf.get('ldap', 'service_bind_pw'),
            "ldap_filter": '(|(&(|(uid=%s)(uid=cyrus-murder))(uid=%%U))(&(|(uid=%%U)(mail=%%U@%%d)(mail=%%U@%%r))(objectclass=kolabinetorgperson)))' % (conf.get('cyrus-imap', 'admin_login')),
            "ldap_user_attribute": conf.get('cyrus-sasl', 'result_attribute'),
            "ldap_group_base": conf.get('ldap', 'base_dn'),
            "ldap_group_filter": "(&(cn=%u)(objectclass=ldapsubentry)(objectclass=nsroledefinition))",
            "ldap_group_scope": "one",
            "ldap_member_base": conf.get('ldap','user_base_dn'),
            "ldap_member_method": "attribute",
            "ldap_member_attribute": "nsrole",
            "admins": conf.get('cyrus-imap', 'admin_login'),
            "postuser": "******",
        }

    template_file = None

    if os.path.isfile('/etc/kolab/templates/imapd.conf.tpl'):
        template_file = '/etc/kolab/templates/imapd.conf.tpl'
    elif os.path.isfile('/usr/share/kolab/templates/imapd.conf.tpl'):
        template_file = '/usr/share/kolab/templates/imapd.conf.tpl'
    elif os.path.isfile(os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'imapd.conf.tpl'))):
        template_file = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'imapd.conf.tpl'))

    if not template_file == None:
        fp = open(template_file, 'r')
        template_definition = fp.read()
        fp.close()

        t = Template(template_definition, searchList=[imapd_settings])
        fp = open('/etc/imapd.conf', 'w')
        fp.write(t.__str__())
        fp.close()

    else:
        log.error(_("Could not write out Cyrus IMAP configuration file /etc/imapd.conf"))
        return

    cyrus_settings = {}

    template_file = None

    if os.path.isfile('/etc/kolab/templates/cyrus.conf.tpl'):
        template_file = '/etc/kolab/templates/cyrus.conf.tpl'
    elif os.path.isfile('/usr/share/kolab/templates/cyrus.conf.tpl'):
        template_file = '/usr/share/kolab/templates/cyrus.conf.tpl'
    elif os.path.isfile(os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'cyrus.conf.tpl'))):
        template_file = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'cyrus.conf.tpl'))

    if not template_file == None:
        fp = open(template_file, 'r')
        template_definition = fp.read()
        fp.close()

        t = Template(template_definition, searchList=[cyrus_settings])
        fp = open('/etc/cyrus.conf', 'w')
        fp.write(t.__str__())
        fp.close()

    else:
        log.error(_("Could not write out Cyrus IMAP configuration file /etc/cyrus.conf"))
        return

    annotations = [
            "/vendor/kolab/activesync,mailbox,string,backend,value.priv,r",
            "/vendor/kolab/color,mailbox,string,backend,value.shared value.priv,a",
            "/vendor/kolab/displayname,mailbox,string,backend,value.shared value.priv,a",
            "/vendor/kolab/folder-test,mailbox,string,backend,value.shared value.priv,a",
            "/vendor/kolab/folder-type,mailbox,string,backend,value.shared value.priv,a",
            "/vendor/kolab/incidences-for,mailbox,string,backend,value.shared value.priv,a",
            "/vendor/kolab/pxfb-readable-for,mailbox,string,backend,value.shared value.priv,a",
            "/vendor/kolab/uniqueid,mailbox,string,backend,value.shared value.priv,a",
            "/vendor/kolab/h-share-attr-desc,mailbox,string,backend,value.shared value.priv,a",
            "/vendor/horde/share-params,mailbox,string,backend,value.shared value.priv,a",
            "/vendor/x-toltec/test,mailbox,string,backend,value.shared value.priv,a",
        ]

    fp = open('/etc/imapd.annotations.conf', 'w')
    fp.write("\n".join(annotations))
    fp.close()

    if os.path.isfile('/etc/default/kolab-saslauthd'):
        myaugeas = Augeas()
        setting = os.path.join('/files/etc/default/kolab-saslauthd','START')

        if not myaugeas.get(setting) == 'yes':
            myaugeas.set(setting,'yes')
            myaugeas.save()

        myaugeas.close()

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'stop', 'saslauthd.service'])
        subprocess.call(['systemctl', 'restart', 'kolab-saslauthd.service'])
        subprocess.call(['systemctl', 'restart', 'cyrus-imapd.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['service', 'saslauthd', 'stop'])
        subprocess.call(['service', 'kolab-saslauthd', 'restart'])
        subprocess.call(['service', 'cyrus-imapd', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','saslauthd','stop'])
        subprocess.call(['/usr/sbin/service','kolab-saslauthd','restart'])
        subprocess.call(['/usr/sbin/service','cyrus-imapd','restart'])
    else:
        log.error(_("Could not start the cyrus-imapd and kolab-saslauthd services."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'disable', 'saslauthd.service'])
        subprocess.call(['systemctl', 'enable', 'kolab-saslauthd.service'])
        subprocess.call(['systemctl', 'enable', 'cyrus-imapd.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['chkconfig', 'saslauthd', 'off'])
        subprocess.call(['chkconfig', 'kolab-saslauthd', 'on'])
        subprocess.call(['chkconfig', 'cyrus-imapd', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'saslauthd', 'disable'])
        subprocess.call(['/usr/sbin/update-rc.d', 'kolab-saslauthd', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'cyrus-imapd', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "cyrus-imapd and kolab-saslauthd services."))