Exemple #1
0
    def setup(self):
        # Make sure Unix user/group are active
        users = UsersBackend(self.app)
        users.add_sys_with_home('sparkleshare')
        users.add_group('sparkleshare')
        users.add_to_group('sparkleshare', 'sparkleshare')
        users.change_user_param('sparkleshare', 'shell', '/usr/bin/git-shell')
        if not os.path.exists('/home/sparkleshare'):
            os.makedirs('/home/sparkleshare')

        # Configure SSH
        if not os.path.exists('/home/sparkleshare/.ssh'):
            os.makedirs('/home/sparkleshare/.ssh')
            os.chmod('/home/sparkleshare/.ssh', 0700)
        if not os.path.exists('/home/sparkleshare/.ssh/authorized_keys'):
            open('/home/sparkleshare/.ssh/authorized_keys', 'w').write('')
            os.chmod('/home/sparkleshare/.ssh/authorized_keys', 0600)
        f = open('/etc/ssh/sshd_config', 'r').read()
        if not '# SparkleShare' in f:
            f += '\n'
            f += '# SparkleShare\n'
            f += '# Please do not edit the above comment as it\'s used as a check by Dazzle/Genesis\n'
            f += 'Match User sparkleshare\n'
            f += '    PasswordAuthentication no\n'
            f += '    PubkeyAuthentication yes\n'
            f += '# End of SparkleShare configuration\n'
            open('/etc/ssh/sshd_config', 'w').write(f)
        self.app.get_backend(apis.services.IServiceManager).restart('sshd')
Exemple #2
0
    def setup(self):
        # Make sure Unix user/group are active
        users = UsersBackend(self.app)
        users.add_sys_with_home('sparkleshare')
        users.add_group('sparkleshare')
        users.add_to_group('sparkleshare', 'sparkleshare')
        users.change_user_param('sparkleshare', 'shell', '/usr/bin/git-shell')
        if not os.path.exists('/home/sparkleshare'):
            os.makedirs('/home/sparkleshare')

        # Configure SSH
        if not os.path.exists('/home/sparkleshare/.ssh'):
            os.makedirs('/home/sparkleshare/.ssh')
            os.chmod('/home/sparkleshare/.ssh', 0700)
        if not os.path.exists('/home/sparkleshare/.ssh/authorized_keys'):
            open('/home/sparkleshare/.ssh/authorized_keys', 'w').write('')
            os.chmod('/home/sparkleshare/.ssh/authorized_keys', 0600)
        f = open('/etc/ssh/sshd_config', 'r').read()
        if not '# SparkleShare' in f:
            f += '\n'
            f += '# SparkleShare\n'
            f += '# Please do not edit the above comment as it\'s used as a check by Dazzle/Genesis\n'
            f += 'Match User sparkleshare\n'
            f += '    PasswordAuthentication no\n'
            f += '    PubkeyAuthentication yes\n'
            f += '# End of SparkleShare configuration\n'
            open('/etc/ssh/sshd_config', 'w').write(f)
        self.app.get_backend(apis.services.IServiceManager).restart('sshd')
Exemple #3
0
    def initial_setup(self):
        # Grab frameworks for use later
        config = MailConfig(self.app)
        users = UsersBackend(self.app)
        dbase = apis.databases(self.app).get_interface('SQLite3')
        config.load()

        # Create a SQLite3 database for storing mailbox, alias and
        # domain information
        if 'vmail' in [x['name'] for x in dbase.get_dbs()]:
            dbase.remove('vmail')
        dbase.add('vmail')
        sql = ('CREATE TABLE "alias" ('
            'address varchar(255) NOT NULL default "", '
            'goto text NOT NULL, domain varchar(255) NOT NULL default "", '
            'created datetime NOT NULL default "0000-00-00 00:00:00", '
            'active tinyint(1) NOT NULL default "1", '
            'PRIMARY KEY (address)); '
            'CREATE TABLE "domain" ( '
            'domain varchar(255) NOT NULL default "", '
            'transport varchar(255) default NULL, '
            'backupmx tinyint(1) NOT NULL default "0", '
            'created datetime NOT NULL default "0000-00-00 00:00:00", '
            'active tinyint(1) NOT NULL default "1", '
            'PRIMARY KEY (domain)); '
            'CREATE TABLE "alias_domain" ( '
            'alias_domain varchar(255) NOT NULL default "", '
            'target_domain varchar(255) NOT NULL default "", '
            'created datetime NOT NULL default "0000-00-00 00:00:00", '
            'active tinyint(1) NOT NULL default "1", '
            'PRIMARY KEY (alias_domain)); '
            'CREATE TABLE "mailbox" ( '
            'username varchar(255) NOT NULL default "", '
            'password varchar(255) NOT NULL default "", '
            'name varchar(255) NOT NULL default "", '
            'maildir varchar(255) NOT NULL default "", '
            'quota bigint(20) NOT NULL default "0", '
            'local_part varchar(255) NOT NULL default "", '
            'domain varchar(255) NOT NULL default "", '
            'created datetime NOT NULL default "0000-00-00 00:00:00", '
            'active tinyint(1) NOT NULL default "1", '
            'PRIMARY KEY (username));'
            'CREATE INDEX address ON alias (address);'
            'CREATE INDEX active ON alias_domain (active);'
            'CREATE INDEX target_domain ON alias_domain (target_domain);'
            'CREATE INDEX username ON mailbox (username);'
        )
        dbase.execute('vmail', sql)

        # Add system user and group for handling mail
        users.add_sys_user('vmail')
        users.add_group('vmail')
        users.add_to_group('vmail', 'vmail')
        uid = int(users.get_user('vmail', users.get_all_users()).uid)
        gid = int(users.get_group('vmail', users.get_all_groups()).gid)
        pfgid = int(users.get_group('dovecot', users.get_all_groups()).gid)

        # Create the virtual mail directory
        if not os.path.exists('/var/vmail'):
            os.mkdir('/var/vmail')
        users.change_user_param('vmail', 'home', '/var/vmail')
        users.change_user_param('vmail', 'shell', '/sbin/nologin')
        os.chmod('/var/vmail', 0770)
        os.chown('/var/vmail', uid, gid)

        # Tell Dovecot (MDA) where to find users and passwords
        config.dovecot_authsql = {
            'passdb_0': {
                'driver': 'sql',
                'args': '/etc/dovecot/dovecot-sql.conf.ext'
            },
            'userdb_0': {
                'driver': 'sql',
                'args': '/etc/dovecot/dovecot-sql.conf.ext'
            }
        }

        # Tell Dovecot how to read our SQL
        config.dovecot_dovecotsql['driver'] = 'sqlite'
        config.dovecot_dovecotsql['connect'] = '/var/lib/sqlite3/vmail.db'
        config.dovecot_dovecotsql['default_pass_scheme'] = 'MD5-CRYPT'
        config.dovecot_dovecotsql['password_query'] = (
            'SELECT username as user, password, \'/var/vmail/%d/%n\''
            ' as userdb_home, \'maildir:/var/vmail/%d/%n\' as userdb_mail,'
            ' '+str(uid)+' as userdb_uid, '+str(gid)+' as userdb_gid FROM mailbox '
            'WHERE username = \'%u\' AND active = \'1\'')
        config.dovecot_dovecotsql['user_query'] = (
            'SELECT \'/var/vmail/%d/%n\' as home, '
            '\'maildir:/var/vmail/%d/%n\' as mail, '+str(uid)+' AS uid, '+str(gid)+' AS gid, '
            '\'dirsize:storage=\'|| quota AS quota FROM mailbox '
            'WHERE username = \'%u\' AND active = \'1\'')
        config.dovecot_auth['disable_plaintext_auth'] = 'yes'
        config.dovecot_auth['auth_mechanisms'] = 'plain login'
        rm = ''
        for x in config.dovecot_auth:
            if x.startswith('include') and config.dovecot_auth[x] != 'auth-sql.conf.ext':
                rm = x
        if rm:
            del config.dovecot_auth[rm]
        config.dovecot_auth['include_0'] = 'auth-sql.conf.ext'

        config.dovecot_ssl['ssl_key'] = ''
        config.dovecot_ssl['ssl_cert'] = ''

        # Tell Dovecot where to put its mail and how to save/access it
        config.dovecot_mail['mail_location'] = 'maildir:/var/vmail/%d/%n'
        config.dovecot_mail['mail_uid'] = 'vmail'
        config.dovecot_mail['mail_gid'] = 'vmail'
        config.dovecot_mail['first_valid_uid'] = str(uid)
        config.dovecot_mail['last_valid_uid'] = str(uid)

        # Tell Dovecot to communicate with Postfix (MTA)
        config.dovecot_master['service auth_0'] = {
            'unix_listener auth-userdb_0': {
                'mode': '0600',
                'user': '******',
                'group': 'vmail'
            },
            'unix_listener /var/spool/postfix/private/auth_0': {
                'mode': '0660',
                'user': '******',
                'group': 'postfix'
            }
        }

        # Protect Dovecot configuration folder
        for r, d, f in os.walk('/etc/dovecot'):
            for x in d:
                os.chown(os.path.join(r, x), uid, pfgid)
                st = os.stat(os.path.join(r, x))
                os.chmod(os.path.join(r, x), st.st_mode&~stat.S_IROTH&~stat.S_IWOTH&~stat.S_IXOTH)
            for x in f:
                os.chown(os.path.join(r, x), uid, pfgid)
                st = os.stat(os.path.join(r, x))
                os.chmod(os.path.join(r, x), st.st_mode&~stat.S_IROTH&~stat.S_IWOTH&~stat.S_IXOTH)

        # Tell Postfix (MTA) how to get mailbox, alias and domain info
        # from our SQLite3 database
        f = open('/etc/postfix/sqlite_virtual_alias_domainaliases_maps.cf', 'w')
        f.write('dbpath = /var/lib/sqlite3/vmail.db\n'
            'query = SELECT goto FROM alias,alias_domain\n'
            '  WHERE alias_domain.alias_domain = \'%d\'\n'
            '  AND alias.address = \'%u\' || \'@\' || alias_domain.target_domain\n'
            '  AND alias.active = 1\n')
        f.close()
        f = open('/etc/postfix/sqlite_virtual_alias_maps.cf', 'w')
        f.write('dbpath = /var/lib/sqlite3/vmail.db\n'
            'table = alias\n'
            'select_field = goto\n'
            'where_field = address\n'
            'additional_conditions = and active = \'1\'\n')
        f.close()
        f = open('/etc/postfix/sqlite_virtual_domains_maps.cf', 'w')
        f.write('dbpath = /var/lib/sqlite3/vmail.db\n'
            'table = domain\n'
            'select_field = domain\n'
            'where_field = domain\n'
            'additional_conditions = and backupmx = \'0\' and active = \'1\'\n')
        f.close()
        f = open('/etc/postfix/sqlite_virtual_mailbox_domainaliases_maps.cf', 'w')
        f.write('dbpath = /var/lib/sqlite3/vmail.db\n'
            'query = SELECT maildir FROM mailbox, alias_domain\n'
            '  WHERE alias_domain.alias_domain = \'%d\'\n'
            '  AND mailbox.username = \'%u\' || \'@\' || alias_domain.target_domain )\n'
            '  AND mailbox.active = 1\n')
        f.close()
        f = open('/etc/postfix/sqlite_virtual_mailbox_maps.cf', 'w')
        f.write('dbpath = /var/lib/sqlite3/vmail.db\n'
            'table = mailbox\n'
            'select_field = domain || \'/\' || local_part)\n'
            'where_field = username\n'
            'additional_conditions = and active = \'1\'\n')
        f.close()
        f = open('/etc/postfix/header_checks', 'w')
        f.write('/^Received:/                 IGNORE\n'
            '/^User-Agent:/               IGNORE\n'
            '/^X-Mailer:/                 IGNORE\n'
            '/^X-Originating-IP:/         IGNORE\n'
            '/^x-cr-[a-z]*:/              IGNORE\n'
            '/^Thread-Index:/             IGNORE\n')
        f.close()

        # Configure Postfix
        config.postfix_main = {
            'smtpd_banner': '$myhostname ESMTP $mail_name',
            'biff': 'no',
            'append_dot_mydomain': 'no',
            'readme_directory': 'no',
            'smtpd_sasl_type': 'dovecot',
            'smtpd_sasl_path': 'private/auth',
            'smtpd_sasl_auth_enable': 'yes',
            'broken_sasl_auth_clients': 'yes',
            'smtpd_sasl_security_options': 'noanonymous',
            'smtpd_sasl_local_domain': '',
            'smtpd_sasl_authenticated_header': 'yes',
            'smtp_tls_note_starttls_offer': 'no',
            'smtpd_tls_loglevel': '1',
            'smtpd_tls_received_header': 'yes',
            'smtpd_tls_session_cache_timeout': '3600s',
            'tls_random_source': 'dev:/dev/urandom',
            'smtpd_use_tls': 'no',
            'smtpd_enforce_tls': 'no',
            'smtp_use_tls': 'no',
            'smtp_enforce_tls': 'no',
            'smtpd_tls_security_level': 'may',
            'smtp_tls_security_level': 'may',
            'unknown_local_recipient_reject_code': '450',
            'maximal_queue_lifetime': '7d',
            'minimal_backoff_time': '1800s',
            'maximal_backoff_time': '8000s',
            'smtp_helo_timeout': '60s',
            'smtpd_recipient_limit': '16',
            'smtpd_soft_error_limit': '3',
            'smtpd_hard_error_limit': '12',
            'smtpd_helo_restrictions': 'permit_mynetworks, warn_if_reject reject_non_fqdn_hostname, reject_invalid_hostname, permit',
            'smtpd_sender_restrictions': 'permit_sasl_authenticated, permit_mynetworks, warn_if_reject reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit',
            'smtpd_client_restrictions': 'reject_rbl_client sbl.spamhaus.org, reject_rbl_client blackholes.easynet.nl',
            'smtpd_recipient_restrictions': 'reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, permit',
            'smtpd_data_restrictions': 'reject_unauth_pipelining',
            'smtpd_relay_restrictions': 'reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, permit',
            'smtpd_helo_required': 'yes',
            'smtpd_delay_reject': 'yes',
            'disable_vrfy_command': 'yes',
            'myhostname': self.app.get_backend(IHostnameManager).gethostname().lower(),
            'myorigin': self.app.get_backend(IHostnameManager).gethostname().lower(),
            'mydestination': '',
            'mynetworks': '127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128',
            'mailbox_size_limit': '0',
            'recipient_delimiter': '+',
            'inet_interfaces': 'all',
            'mynetworks_style': 'host',
            'virtual_mailbox_base': '/var/vmail',
            'virtual_mailbox_maps': 'sqlite:/etc/postfix/sqlite_virtual_mailbox_maps.cf, sqlite:/etc/postfix/sqlite_virtual_mailbox_domainaliases_maps.cf',
            'virtual_uid_maps': 'static:'+str(uid),
            'virtual_gid_maps': 'static:'+str(gid),
            'virtual_alias_maps': 'sqlite:/etc/postfix/sqlite_virtual_alias_maps.cf, sqlite:/etc/postfix/sqlite_virtual_alias_domainaliases_maps.cf',
            'virtual_mailbox_domains': 'sqlite:/etc/postfix/sqlite_virtual_domains_maps.cf',
            'virtual_transport': 'dovecot',
            'dovecot_destination_recipient_limit': '1',
            'header_checks': 'regexp:/etc/postfix/header_checks',
            'enable_original_recipient': 'no'
        }
        xs, xss, xd = False, False, False
        for x in config.postfix_master:
            if x[0] == 'smtp':
                x = ['smtp', 'inet', 'n', '-', '-', '-', '-', 'smtpd']
                xs = True
            elif x[0] == 'submission':
                x = ['submission', 'inet', 'n', '-', '-', '-', '-', 'smtpd', '',
                    'syslog_name=postfix/submission', 'smtpd_sasl_auth_enable=yes', 'smtpd_tls_auth_only=yes',
                    'smtpd_client_restrictions=permit_sasl_authenticated,reject_unauth_destination,reject',
                    'smtpd_sasl_security_options=noanonymous,noplaintext',
                    'smtpd_sasl_tls_security_options=noanonymous']
                xss = True
            elif x[0] == 'dovecot':
                x = ['dovecot', 'unix', '-', 'n', 'n', '-', '-', 'pipe',
                    'flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/dovecot-lda -d $(recipient)']
                xd = True
        if not xs:
            config.postfix_master.insert(0, ['smtp', 'inet', 'n', '-', '-', '-', '-', 'smtpd'])
        if not xss:
            config.postfix_master.insert(2, ['submission', 'inet', 'n', '-', '-', '-', '-', 'smtpd', '',
                'syslog_name=postfix/submission', 'smtpd_sasl_auth_enable=yes', 'smtpd_tls_auth_only=yes',
                'smtpd_client_restrictions=permit_sasl_authenticated,reject_unauth_destination,reject',
                'smtpd_sasl_security_options=noanonymous,noplaintext',
                'smtpd_sasl_tls_security_options=noanonymous'])
        if not xd:
            config.postfix_master.append(['dovecot', 'unix', '-', 'n', 'n', '-', '-', 'pipe',
                'flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/dovecot-lda -d $(recipient)'])
        open('/etc/aliases', 'w').write('')

        # Save the configurations and start the services
        config.save(True)
        cfg =  self.app.get_config(self)
        cfg.reinitialize = False
        cfg.save()
Exemple #4
0
    def initial_setup(self):
        # Grab frameworks for use later
        config = MailConfig(self.app)
        users = UsersBackend(self.app)
        dbase = apis.databases(self.app).get_interface('SQLite3')
        config.load()

        # Create a SQLite3 database for storing mailbox, alias and
        # domain information
        if 'vmail' in [x['name'] for x in dbase.get_dbs()]:
            dbase.remove('vmail')
        dbase.add('vmail')
        sql = ('CREATE TABLE "alias" ('
               'address varchar(255) NOT NULL default "", '
               'goto text NOT NULL, domain varchar(255) NOT NULL default "", '
               'created datetime NOT NULL default "0000-00-00 00:00:00", '
               'active tinyint(1) NOT NULL default "1", '
               'PRIMARY KEY (address)); '
               'CREATE TABLE "domain" ( '
               'domain varchar(255) NOT NULL default "", '
               'transport varchar(255) default NULL, '
               'backupmx tinyint(1) NOT NULL default "0", '
               'created datetime NOT NULL default "0000-00-00 00:00:00", '
               'active tinyint(1) NOT NULL default "1", '
               'PRIMARY KEY (domain)); '
               'CREATE TABLE "alias_domain" ( '
               'alias_domain varchar(255) NOT NULL default "", '
               'target_domain varchar(255) NOT NULL default "", '
               'created datetime NOT NULL default "0000-00-00 00:00:00", '
               'active tinyint(1) NOT NULL default "1", '
               'PRIMARY KEY (alias_domain)); '
               'CREATE TABLE "mailbox" ( '
               'username varchar(255) NOT NULL default "", '
               'password varchar(255) NOT NULL default "", '
               'name varchar(255) NOT NULL default "", '
               'maildir varchar(255) NOT NULL default "", '
               'quota bigint(20) NOT NULL default "0", '
               'local_part varchar(255) NOT NULL default "", '
               'domain varchar(255) NOT NULL default "", '
               'created datetime NOT NULL default "0000-00-00 00:00:00", '
               'active tinyint(1) NOT NULL default "1", '
               'PRIMARY KEY (username));'
               'CREATE INDEX address ON alias (address);'
               'CREATE INDEX active ON alias_domain (active);'
               'CREATE INDEX target_domain ON alias_domain (target_domain);'
               'CREATE INDEX username ON mailbox (username);')
        dbase.execute('vmail', sql)

        # Add system user and group for handling mail
        users.add_sys_user('vmail')
        users.add_group('vmail')
        users.add_to_group('vmail', 'vmail')
        uid = int(users.get_user('vmail', users.get_all_users()).uid)
        gid = int(users.get_group('vmail', users.get_all_groups()).gid)
        pfgid = int(users.get_group('dovecot', users.get_all_groups()).gid)

        # Create the virtual mail directory
        if not os.path.exists('/var/vmail'):
            os.mkdir('/var/vmail')
        users.change_user_param('vmail', 'home', '/var/vmail')
        users.change_user_param('vmail', 'shell', '/sbin/nologin')
        os.chmod('/var/vmail', 0770)
        os.chown('/var/vmail', uid, gid)

        # Tell Dovecot (MDA) where to find users and passwords
        config.dovecot_authsql = {
            'passdb_0': {
                'driver': 'sql',
                'args': '/etc/dovecot/dovecot-sql.conf.ext'
            },
            'userdb_0': {
                'driver': 'sql',
                'args': '/etc/dovecot/dovecot-sql.conf.ext'
            }
        }

        # Tell Dovecot how to read our SQL
        config.dovecot_dovecotsql['driver'] = 'sqlite'
        config.dovecot_dovecotsql['connect'] = '/var/lib/sqlite3/vmail.db'
        config.dovecot_dovecotsql['default_pass_scheme'] = 'MD5-CRYPT'
        config.dovecot_dovecotsql['password_query'] = (
            'SELECT username as user, password, \'/var/vmail/%d/%n\''
            ' as userdb_home, \'maildir:/var/vmail/%d/%n\' as userdb_mail,'
            ' ' + str(uid) + ' as userdb_uid, ' + str(gid) +
            ' as userdb_gid FROM mailbox '
            'WHERE username = \'%u\' AND active = \'1\'')
        config.dovecot_dovecotsql['user_query'] = (
            'SELECT \'/var/vmail/%d/%n\' as home, '
            '\'maildir:/var/vmail/%d/%n\' as mail, ' + str(uid) + ' AS uid, ' +
            str(gid) + ' AS gid, '
            '\'dirsize:storage=\'|| quota AS quota FROM mailbox '
            'WHERE username = \'%u\' AND active = \'1\'')
        config.dovecot_auth['disable_plaintext_auth'] = 'yes'
        config.dovecot_auth['auth_mechanisms'] = 'plain login'
        rm = ''
        for x in config.dovecot_auth:
            if x.startswith('include') and config.dovecot_auth[
                    x] != 'auth-sql.conf.ext':
                rm = x
        if rm:
            del config.dovecot_auth[rm]
        config.dovecot_auth['include_0'] = 'auth-sql.conf.ext'

        config.dovecot_ssl['ssl_key'] = ''
        config.dovecot_ssl['ssl_cert'] = ''

        # Tell Dovecot where to put its mail and how to save/access it
        config.dovecot_mail['mail_location'] = 'maildir:/var/vmail/%d/%n'
        config.dovecot_mail['mail_uid'] = 'vmail'
        config.dovecot_mail['mail_gid'] = 'vmail'
        config.dovecot_mail['first_valid_uid'] = str(uid)
        config.dovecot_mail['last_valid_uid'] = str(uid)

        # Tell Dovecot to communicate with Postfix (MTA)
        config.dovecot_master['service auth_0'] = {
            'unix_listener auth-userdb_0': {
                'mode': '0600',
                'user': '******',
                'group': 'vmail'
            },
            'unix_listener /var/spool/postfix/private/auth_0': {
                'mode': '0660',
                'user': '******',
                'group': 'postfix'
            }
        }

        # Protect Dovecot configuration folder
        for r, d, f in os.walk('/etc/dovecot'):
            for x in d:
                os.chown(os.path.join(r, x), uid, pfgid)
                st = os.stat(os.path.join(r, x))
                os.chmod(
                    os.path.join(r, x),
                    st.st_mode & ~stat.S_IROTH & ~stat.S_IWOTH & ~stat.S_IXOTH)
            for x in f:
                os.chown(os.path.join(r, x), uid, pfgid)
                st = os.stat(os.path.join(r, x))
                os.chmod(
                    os.path.join(r, x),
                    st.st_mode & ~stat.S_IROTH & ~stat.S_IWOTH & ~stat.S_IXOTH)

        # Tell Postfix (MTA) how to get mailbox, alias and domain info
        # from our SQLite3 database
        f = open('/etc/postfix/sqlite_virtual_alias_domainaliases_maps.cf',
                 'w')
        f.write(
            'dbpath = /var/lib/sqlite3/vmail.db\n'
            'query = SELECT goto FROM alias,alias_domain\n'
            '  WHERE alias_domain.alias_domain = \'%d\'\n'
            '  AND alias.address = \'%u\' || \'@\' || alias_domain.target_domain\n'
            '  AND alias.active = 1\n')
        f.close()
        f = open('/etc/postfix/sqlite_virtual_alias_maps.cf', 'w')
        f.write('dbpath = /var/lib/sqlite3/vmail.db\n'
                'table = alias\n'
                'select_field = goto\n'
                'where_field = address\n'
                'additional_conditions = and active = \'1\'\n')
        f.close()
        f = open('/etc/postfix/sqlite_virtual_domains_maps.cf', 'w')
        f.write(
            'dbpath = /var/lib/sqlite3/vmail.db\n'
            'table = domain\n'
            'select_field = domain\n'
            'where_field = domain\n'
            'additional_conditions = and backupmx = \'0\' and active = \'1\'\n'
        )
        f.close()
        f = open('/etc/postfix/sqlite_virtual_mailbox_domainaliases_maps.cf',
                 'w')
        f.write(
            'dbpath = /var/lib/sqlite3/vmail.db\n'
            'query = SELECT maildir FROM mailbox, alias_domain\n'
            '  WHERE alias_domain.alias_domain = \'%d\'\n'
            '  AND mailbox.username = \'%u\' || \'@\' || alias_domain.target_domain\n'
            '  AND mailbox.active = 1\n')
        f.close()
        f = open('/etc/postfix/sqlite_virtual_mailbox_maps.cf', 'w')
        f.write('dbpath = /var/lib/sqlite3/vmail.db\n'
                'table = mailbox\n'
                'select_field = domain || \'/\' || local_part\n'
                'where_field = username\n'
                'additional_conditions = and active = \'1\'\n')
        f.close()
        f = open('/etc/postfix/header_checks', 'w')
        f.write('/^Received:/                 IGNORE\n'
                '/^User-Agent:/               IGNORE\n'
                '/^X-Mailer:/                 IGNORE\n'
                '/^X-Originating-IP:/         IGNORE\n'
                '/^x-cr-[a-z]*:/              IGNORE\n'
                '/^Thread-Index:/             IGNORE\n')
        f.close()

        # Configure Postfix
        config.postfix_main = {
            'smtpd_banner':
            '$myhostname ESMTP $mail_name',
            'biff':
            'no',
            'append_dot_mydomain':
            'no',
            'readme_directory':
            'no',
            'smtpd_sasl_type':
            'dovecot',
            'smtpd_sasl_path':
            'private/auth',
            'smtpd_sasl_auth_enable':
            'yes',
            'broken_sasl_auth_clients':
            'yes',
            'smtpd_sasl_security_options':
            'noanonymous',
            'smtpd_sasl_local_domain':
            '',
            'smtpd_sasl_authenticated_header':
            'yes',
            'smtp_tls_note_starttls_offer':
            'no',
            'smtpd_tls_loglevel':
            '1',
            'smtpd_tls_received_header':
            'yes',
            'smtpd_tls_session_cache_timeout':
            '3600s',
            'tls_random_source':
            'dev:/dev/urandom',
            'smtpd_use_tls':
            'no',
            'smtpd_enforce_tls':
            'no',
            'smtp_use_tls':
            'no',
            'smtp_enforce_tls':
            'no',
            'smtpd_tls_security_level':
            'may',
            'smtp_tls_security_level':
            'may',
            'unknown_local_recipient_reject_code':
            '450',
            'maximal_queue_lifetime':
            '7d',
            'minimal_backoff_time':
            '1800s',
            'maximal_backoff_time':
            '8000s',
            'smtp_helo_timeout':
            '60s',
            'smtpd_recipient_limit':
            '16',
            'smtpd_soft_error_limit':
            '3',
            'smtpd_hard_error_limit':
            '12',
            'smtpd_helo_restrictions':
            'permit_mynetworks, warn_if_reject reject_non_fqdn_hostname, reject_invalid_hostname, permit',
            'smtpd_sender_restrictions':
            'permit_sasl_authenticated, permit_mynetworks, warn_if_reject reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit',
            'smtpd_client_restrictions':
            'reject_rbl_client sbl.spamhaus.org, reject_rbl_client blackholes.easynet.nl',
            'smtpd_recipient_restrictions':
            'reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, permit',
            'smtpd_data_restrictions':
            'reject_unauth_pipelining',
            'smtpd_relay_restrictions':
            'reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, permit',
            'smtpd_helo_required':
            'yes',
            'smtpd_delay_reject':
            'yes',
            'disable_vrfy_command':
            'yes',
            'myhostname':
            self.app.get_backend(IHostnameManager).gethostname().lower(),
            'myorigin':
            self.app.get_backend(IHostnameManager).gethostname().lower(),
            'mydestination':
            '',
            'mynetworks':
            '127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128',
            'mailbox_size_limit':
            '0',
            'recipient_delimiter':
            '+',
            'inet_interfaces':
            'all',
            'mynetworks_style':
            'host',
            'virtual_mailbox_base':
            '/var/vmail',
            'virtual_mailbox_maps':
            'sqlite:/etc/postfix/sqlite_virtual_mailbox_maps.cf, sqlite:/etc/postfix/sqlite_virtual_mailbox_domainaliases_maps.cf',
            'virtual_uid_maps':
            'static:' + str(uid),
            'virtual_gid_maps':
            'static:' + str(gid),
            'virtual_alias_maps':
            'sqlite:/etc/postfix/sqlite_virtual_alias_maps.cf, sqlite:/etc/postfix/sqlite_virtual_alias_domainaliases_maps.cf',
            'virtual_mailbox_domains':
            'sqlite:/etc/postfix/sqlite_virtual_domains_maps.cf',
            'virtual_transport':
            'dovecot',
            'dovecot_destination_recipient_limit':
            '1',
            'header_checks':
            'regexp:/etc/postfix/header_checks',
            'enable_original_recipient':
            'no'
        }
        xs, xss, xd = False, False, False
        for x in config.postfix_master:
            if x[0] == 'smtp':
                x = ['smtp', 'inet', 'n', '-', '-', '-', '-', 'smtpd']
                xs = True
            elif x[0] == 'submission':
                x = [
                    'submission', 'inet', 'n', '-', '-', '-', '-', 'smtpd', '',
                    'syslog_name=postfix/submission',
                    'smtpd_sasl_auth_enable=yes', 'smtpd_tls_auth_only=yes',
                    'smtpd_client_restrictions=permit_sasl_authenticated,reject_unauth_destination,reject',
                    'smtpd_sasl_security_options=noanonymous,noplaintext',
                    'smtpd_sasl_tls_security_options=noanonymous'
                ]
                xss = True
            elif x[0] == 'dovecot':
                x = [
                    'dovecot', 'unix', '-', 'n', 'n', '-', '-', 'pipe',
                    'flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/dovecot-lda -d $(recipient)'
                ]
                xd = True
        if not xs:
            config.postfix_master.insert(
                0, ['smtp', 'inet', 'n', '-', '-', '-', '-', 'smtpd'])
        if not xss:
            config.postfix_master.insert(2, [
                'submission', 'inet', 'n', '-', '-', '-', '-', 'smtpd', '',
                'syslog_name=postfix/submission', 'smtpd_sasl_auth_enable=yes',
                'smtpd_tls_auth_only=yes',
                'smtpd_client_restrictions=permit_sasl_authenticated,reject_unauth_destination,reject',
                'smtpd_sasl_security_options=noanonymous,noplaintext',
                'smtpd_sasl_tls_security_options=noanonymous'
            ])
        if not xd:
            config.postfix_master.append([
                'dovecot', 'unix', '-', 'n', 'n', '-', '-', 'pipe',
                'flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/dovecot-lda -d $(recipient)'
            ])
        open('/etc/aliases', 'w').write('')

        # Save the configurations and start the services
        config.save(True)
        cfg = self.app.get_config(self)
        cfg.reinitialize = False
        cfg.save()