Esempio n. 1
0
    def writeConfig(self, *a):
        # make sure slapd is stopped
        os.system('/etc/init.d/slapd stop')
        # Back up ldap.. Who knows.. someone just might postprep a live box :(
        os.system('slapcat > /usr/local/tcs/tums/backups/ldap-%s.ldif' % int(time.time()))

        # Kill the ldap database because 1.2rc3 came with cruf in it for some reason
        if os.path.exists('/etc/debian_version'): # check for debian base
            os.system('rm /var/lib/ldap/*')
        else:
            os.system('rm /var/lib/openldap-data/*')

        # Start SLAPd 
        os.system('/etc/init.d/slapd start')
        # Make sure it's started...
        lk = os.popen('/etc/init.d/slapd status').read()
        if "stopped" in lk:
            print "slapd isn't running, and I can't start it :-(."
            print "the LDAP service is probably broken."
            return
        # Generate a shiny new tree
        os.system('/usr/local/tcs/tums/genLDAP.py')
        # Import the new tree
        os.system('/etc/init.d/slapd stop')
        os.system('slapadd < /usr/local/tcs/tums/template.ldif') # ldapadd is f****d on Debian
        os.system('/etc/init.d/slapd start')
        # Restart slapd for safe measure
        os.system('/etc/init.d/slapd restart')
        os.system('/etc/init.d/samba restart')

        # Populate the LDAP tree with SMB goodness
        os.system('smbldap-populate')
        # Sprinkle on a bit of joy and sugar
        os.system('/usr/local/tcs/tums/ldapConfig')
        # Secure it with a password
        if os.path.exists('/etc/debian_version'):
            os.system('smbpasswd -w `cat /etc/ldap/slapd.conf | grep rootpw | awk \'{print $2}\'`')        
        else:
            os.system('smbpasswd -w `cat /etc/openldap/slapd.conf | grep rootpw | awk \'{print $2}\'`')
        # And then switch it off again
        os.system('/etc/init.d/samba stop')

        os.system('/usr/local/tcs/tums/syscripts/vpn.sh')

        # Clear samba cache
        os.system('rm /var/cache/samba/wins.dat')
        os.system('rm /var/cache/samba/gencache.tdb')
        os.system('rm /var/cache/samba/browse.dat')

        os.system('rm /etc/bind/pri/*.jnl')

        os.system('/root/tcs/vpn.sh')
        if os.path.exists('/etc/debian_version'):
            os.system('openssl req -x509 -newkey rsa:1024 -keyout /etc/exim4/exim.key -out /etc/exim4/exim.cert -days 9999 -nodes')
        else:
            os.system('openssl req -x509 -newkey rsa:1024 -keyout /etc/exim/exim.key -out /etc/exim/exim.cert -days 9999 -nodes')

        os.system('sensors-detect')

        os.system('ntpdate -su %s' % config.NTP)

        if not os.path.exists('/etc/debian_version'):
            os.system('/etc/init.d/clock save')
        
        # Recreate openssh-server keys if it's gentoo
        if not os.path.exists('/etc/debian_version'):
            os.system('rm /etc/ssh/ssh*key*')
            os.system('rm /root/.ssh/known_hosts')

        runlevels =  [
            ('apache2',  'default'),
            ('slapd',  'default'),
            ('mysql',  'default'),
            ('exim',  'default'),
            ('clamd', 'default'),
            ('courier-imapd',  'default'),
            ('courier-authlib',  'default'),
            ('courier-pop3d',  'default'),
            ('ddclient', 'default'),
            ('shorewall', 'default'),
            ('spamd', 'default'),
            ('squid', 'default'),
            ('smartd', 'default'),
            ('sysklogd', 'default'),
            ('ulogd', 'default'),
            ('xinetd', 'default'),
            ('cupsd', 'default'),
            ('netmount', 'default'),
            ('ntp-client', 'default'),
            ('ntpd', 'default'),
            ('gpm', 'default'),
            ('samba', 'default'),
            ('nscd', 'default'),
            ('named', 'default'),
            ('dhcpd', 'default'),
            ('tums', 'default'),
            ('quagga', 'default'),
            ('zebra', 'default')
        ]

        if os.path.exists('/etc/debian_version'):
            for run, level in runlevels:
                # apply modifications for debian
                level = level.replace('default', 'defaults')
                run = run.replace('dhcpd', 'dhcp3-server').replace('exim', 'exim4')
                run = run.replace('courier-authlib', 'courier-authdaemon')
                os.system('update-rc.d %s %s > /dev/null 2>&1' % (run, level))

            # Do defaults fixes (bloody irritating...)
            spamd = """ENABLED=1
OPTIONS="--create-prefs --max-children 5 --helper-home-dir"
PIDFILE="/var/run/spamd.pid"
NICE="--nicelevel 15"""
            Utils.writeConf('/etc/default/spamassassin', spamd, '#')

            shorewall = """startup=1\n"""
            Utils.writeConf('/etc/default/shorewall', shorewall, '#')

            os.system('update-rc.d -f fprobe remove > /dev/null 2>&1')

        else:
            for inter in config.EthernetDevices:
                runlevels.append(("net."+inter, 'boot'))

            for inter in config.WANDevices:
                runlevels.append(("net."+inter, 'boot'))

            for run,level in runlevels:
                os.system('rc-update add %s %s' % (run, level))

        os.system('chmod +x /usr/local/tcs/tums/existat.py')
        os.system('chmod +x /usr/local/tcs/tums/existat-render.py')

        print "Creating admin account"
        self.createAdmin()
Esempio n. 2
0
File: TUMS.py Progetto: calston/tums
    def writeConfig(self, *a):
        host = config.ExternalName
        user = ''.join(host.split('.'))

        debianinitd = """#!/bin/sh -e 
#### BEGIN INIT INFO
# Provides:          tums
# Required-Start:    $syslog $time $local_fs $remote_fs
# Required-Stop:     $syslog $time $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      S 0 1 6
# Short-Description: User management system
# Description:       Debian init script for TUMS providing administrative features to Vulani.
### END INIT INFO
#
# Author:       Colin Alston <*****@*****.**>
#

. /lib/lsb/init-functions

case "$1" in
    start)
        log_daemon_msg "Starting Tums" "tums"
        export PYTHONPATH='/usr/local/tcs/tums'
        start-stop-daemon --start --pidfile /var/run/tums.pid --exec /usr/local/tcs/tums/tums
        start-stop-daemon --start --pidfile /var/run/tums-fc.pid --exec /usr/local/tcs/tums/tums-fc
        start-stop-daemon --start --pidfile /var/run/tums-proxy.pid --exec /usr/local/tcs/tums/proxy.py
        /usr/local/tcs/exilog-tums/exilog_agent.pl > /dev/null 2>&1
        log_end_msg 0
    ;;

    stop)
        log_daemon_msg "Stopping Tums" "tums"
        start-stop-daemon --stop --pidfile /var/run/tums.pid > /dev/null 2>&1
        start-stop-daemon --stop --pidfile /var/run/tums-fc.pid > /dev/null 2>&1
        start-stop-daemon --stop --pidfile /var/run/tums-proxy.pid > /dev/null 2>&1
        killall -r exilog > /dev/null 2>&1
        log_end_msg 0 
    ;;

    force-reload|restart)
        log_daemon_msg "Restarting tums" "tums"
        start-stop-daemon --stop --pidfile /var/run/tums.pid > /dev/null 2>&1
        start-stop-daemon --stop --pidfile /var/run/tums-fc.pid > /dev/null 2>&1
        start-stop-daemon --stop --pidfile /var/run/tums-proxy.pid > /dev/null 2>&1
        sleep 2
        export PYTHONPATH='/usr/local/tcs/tums'
        killall -r exilog > /dev/null 2>&1
        /usr/local/tcs/exilog-tums/exilog_agent.pl > /dev/null 2>&1
        start-stop-daemon --start --pidfile /var/run/tums.pid --exec /usr/local/tcs/tums/tums
        start-stop-daemon --start --pidfile /var/run/tums-fc.pid --exec /usr/local/tcs/tums/tums-fc
        start-stop-daemon --start --pidfile /var/run/tums-proxy.pid --exec /usr/local/tcs/tums/proxy.py
        log_end_msg 0
    ;;\nesac\n"""

        host = config.ExternalName
        user = ''.join(host.split('.'))

        password = sha.sha(user).hexdigest()
        pwdhash = sha.sha(password).hexdigest()
        userD = {user:pwdhash}
        secret = password

        settings = ""

        settings += "LDAPPass = '******'\n" % config.LDAPPassword
        settings += "LDAPBase = '%s'\n" % config.LDAPBase
        settings += "LDAPOrganisation = '%s'\n" % config.CompanyName
        settings += "defaultDomain = '%s'\n" % config.Domain
        settings += "SMBDomain = '%s'\n" % config.SambaDomain
        settings += 'users = %s\n' % repr(userD)
        settings += 'secret = %s\n' % repr(secret)
        
        updateServer = 'https://thebe.thusa.co.za:9680/'

        staticSettings = """LDAPPersonIdentifier = 'mail'
LDAPServer = '127.0.0.1'
LDAPManager = 'cn=Manager'
LDAPPeople = 'ou=People'
BaseDir = '/usr/local/tcs/tums'
sambaDN = True
port = 9682
Mailer='exim'
updateServer = '%s'
packageServer = 'http://updates.thusa.co.za/'
installDirectory = '/usr/local/tcs/tums'
capabilities = {'ipv6':True}
hiveAddress = "thebe.thusa.co.za"
thebePort='9680'\n""" % (
        updateServer
    )

        settings += staticSettings
        Utils.writeConf('/etc/init.d/tums', debianinitd, None)

        os.system('chmod +x /etc/init.d/tums')
        Utils.writeConf('/usr/local/tcs/tums/Settings.py', settings, None)
        try: 
            ts = open('/usr/local/tcs/tums/tcsstore.dat')
        except:
            ts = open('/usr/local/tcs/tums/tcsstore.dat', 'wt')
            ts.write('V1.5\n')
        ts.close()

        os.system('mkdir -p /usr/local/tcs/tums/images/graphs > /dev/null 2>&1')

        # Fix existat
        os.system('chmod a+x /usr/local/tcs/tums/existat*')

        os.system('echo "GRANT ALL ON exilog.* to exilog@localhost identified by \'exilogpw\';" | mysql  >/dev/null 2>&1 ')
Esempio n. 3
0
    def writeConfig(self):
        areSets = False
        # Write cron.d jobs
        for set in config.Backup.keys():
            areSets = True
            t = config.Backup[set].get('time')

            if t:
                self.time = time.strptime(str(t), "%H:%M:%S")

                cron = "%s %s  * * *      root    /usr/local/tcs/tums/backup.py %s\n" % (
                    self.time.tm_min, self.time.tm_hour, set)
                file = '/etc/cron.d/backup%s' % set

                # write to cron file using Utils.writeConf
                Utils.writeConf(file, cron, '#')
        if not areSets:
            # Term here if there are no backups to look at
            return

        # Maintain cron jobs
        jobs = [cron for cron in os.listdir('/etc/cron.d') if 'backup' in cron]
        for i in jobs:
            if i:
                if not i.lstrip('backup') and not int(
                        i.lstrip('backup')) in config.Backup.keys():
                    os.remove('/etc/cron.d/%s' % i)

        # Create logfile directory
        if not os.path.isdir('/var/log/backup'):
            os.makedirs('/var/log/backup')

        # Write logrotate conf
        if not os.path.exists('/etc/logrotate.d/backup'):
            content = """/var/log/backup/*.log {
            daily
            rotate 30
            missingok
            notifempty
            compress
            nocreate
            }"""

            file = '/etc/logrotate.d/backup'

            Utils.writeConf(file, content, '#')
            if not os.path.exists('/var/log/backup/'):
                os.mkdir('/var/log/backup')

        # Create a store for each type
        types = {'usb': [], 'smb': []}

        # Map types to their handler functions
        handlers = {
            'usb': self.usbDir,
            'smb': self.smbDir,
        }

        # reprocess the configuration
        for set, conf in config.Backup.items():
            cnf = conf
            types[str(cnf['type'])].append(cnf)

        # Call the handler functions with the stores
        for k, v in types.items():
            if v:
                v.sort()
                handlers[k](v)
Esempio n. 4
0
File: Exim.py Progetto: calston/tums
    def writeConfig(self, *a):
        # VERY IMPORTANT NOTICE! 
        #
        #  All lines are lead by 8 spaces. These spaces are stripped out at the end.
        #  If you have less than 8 spaces before any new line written to the config
        #  then it will be broken
        #  This is done to make the source semi readable 
        # 
        # END OF IMPORTANT NOTICE

        # Setup local delivery domains
        locals = "\n".join(config.LocalDomains)

        # A list of servers we redeliver or hub mail to
        serverhosts = ['127.0.0.1']

        # Configure hubbed hosts and relay domains
        relayDoms = config.Mail.get('relay', [])
        hubs = ""
        mailReroute = ""
        for dom, dest in config.Mail.get('hubbed', []):
            if dest not in serverhosts:
                serverhosts.append(dest)
            if "@" in dom:
                mailReroute += "%s       %s        byname\n" % (dom,dest)
                dom = dom.split('@')[-1]
            else:
                hubs += "%s        %s        byname\n" % (dom, dest)

            if dom not in relayDoms:
                relayDoms.append(dom)

        # Branch configuration 
        branches = config.Mail.get('branchtopology', {})
        branchMap = {}
        for r in config.Mail.get('branches', []):

            # if the items in branches are not lists, we assume an old datastructure
            if not isinstance(r, list):
                branchMap[r] = None
                continue

            svr, relay = r


            branchMap[svr] = None

            if relay:
                branchMap[svr] = relay.replace(' ', '').replace(';', ',').replace(':', ',').split(',')

        branchReroute = ""
        for branch, addrs in branches.items():
            for addr in addrs:
                # Extend relay domains to handle this remote server too
                dom = addr.split('@')[-1]
                if dom not in relayDoms:
                    relayDoms.append(dom)

                if branchMap[branch]:
                    relay = ':'.join(branchMap[branch])
                else:
                    relay = branch
                
                if relay not in serverhosts:
                    serverhosts.append(relay)

                # Add the address to mail reroute
                branchReroute += "%s       %s        byname\n" % (
                    addr,
                    relay
                )
                
        # Setup our relay list
        relays = "\n".join(relayDoms)

        # Initialise blacklists
        blacklistSender = ""
        blacklistHost = ""
        blacklistDom  = ""
        
        for b in config.Mail.get('blacklist', []):
            if "@" in b:
                blacklistSender += b + '\n'
            else:
                try:
                    int(b.split('.')[0])
                    blacklistHost += b + '\n'
                except:
                    blacklistDom += b + '\n'

        whitelistSender = ""
        whitelistHost = ""
        whitelistDom = ""
        for w in config.Mail.get('whitelist', []):
            if "@" in w:
                whitelistSender += w + "\n"
            else:
                try:
                    int(w.split('.')[0])
                    whitelistHost += w + '\n'
                except:
                    whitelistDom += w + '\n'

        catchall = ""
        for c in config.Mail.get('catchall', []):
            catchall += c + "\n"

        # System filters
        copyTo = "#System Filter\nif error_message then finish endif\n\n"

        if config.Mail.get('copytoall', None):
            copyTo += "if first_delivery then\n"
            copyTo += "    unseen deliver %s errors_to postmaster@%s\n" % (config.Mail['copytoall'], config.Domain)
            copyTo += "endif\n\n"

        for addr, dest in config.Mail.get('copys', []):
            copyTo += "if $recipients contains %s then\n" % addr
            copyTo += "    unseen deliver %s errors_to postmaster@%s\n" % (dest, config.Domain)
            copyTo += "endif\n\n"

        # Global system filter
        if os.path.exists('/usr/local/tcs/tums/filter.db'):
            filterCont = open('/usr/local/tcs/tums/filter.db').read()
            copyTo += filterCont
            copyTo += "\n"
        
        allowsend = ""
        if config.Mail.get('allowsend', None):
            allowsend = "\n".join(config.Mail['allowsend'])

        if config.Mail.get('disableratelimit', None):
            rateLimit = ""
        else:
            rateLimit = """
        # System-wide rate limit for dodgey senders
          defer message = Connection limited: Sender rate $sender_rate / $sender_rate_period.
                hosts            = +relay_hosts
                !sender_domains  = +local_domains : +relay_domains
                !senders         = :
                ratelimit = 50 / 1h / strict\n"""

        if config.Mail.get('disablerpfilter', None):
            senderRpFilter = ""
        else:
            senderRpFilter = """
        # Block mail from forged address on the local side. 
          deny message  =  Vulani has rejected this message from $sender_address because it is not local to this site. http://vulani.net/
                !sender_domains  = +local_domains : +relay_domains
                !senders         = :
                !senders         = +acl_allowed_senders
                hosts            = +relay_hosts
                !hosts           = +server_hosts\n"""


        Utils.writeConf('/etc/exim4/sender_whitelist', whitelistSender, '#')
        Utils.writeConf('/etc/exim4/host_whitelist', whitelistHost, '#')
        Utils.writeConf('/etc/exim4/domain_whitelist', whitelistDom, '#')

        Utils.writeConf('/etc/exim4/sender_blacklist', blacklistSender, '#')
        Utils.writeConf('/etc/exim4/host_blacklist', blacklistHost, '#')
        Utils.writeConf('/etc/exim4/domain_blacklist', blacklistDom, '#')

        Utils.writeConf('/etc/exim4/allowed_senders', allowsend, '#')

        Utils.writeConf('/etc/exim4/host_noavscan', "", '#')

        Utils.writeConf('/etc/exim4/local_domains', locals, '#')
        Utils.writeConf('/etc/exim4/relay_domains', relays, '#')
        Utils.writeConf('/etc/exim4/hubbed_hosts', hubs, '#')
        Utils.writeConf('/etc/exim4/mail_reroute', mailReroute, '#')
        Utils.writeConf('/etc/exim4/branch_reroute', branchReroute, '#')
        Utils.writeConf('/etc/exim4/system_filter', copyTo, '#')
        Utils.writeConf('/etc/exim4/catchall_domains', catchall, '#')

        # Get rid of the autogenerated tag so aptitude doesn't break us
        os.system('rm /var/lib/exim4/config.autogenerated > /dev/null 2>&1')
        systemFilter = "system_filter = /etc/exim4/system_filter\n"
 
        if config.Mail.get('noavscan'):
            avScan = ""
            avscanacl = ""
            print "Antivirus scanning disabled!"
        else:
            avScan = "av_scanner = clamd:/var/run/clamav/clamd.sock"
            avscanacl = """            accept condition  = ${if <={$message_size}{250k}{yes}{no}}
            deny message      = This message contains a virus ($malware_name)
                !hosts        = +acl_host_noavscan
                malware       = *\n"""

        primaryDomain = config.Domain
        hostname = config.ExternalName  # Must be externally lookupable(?!?) name
        mailSize = config.Mail.get('mailsize', '')
        localNet = " : ".join([v for k,v in Utils.getLanNetworks(config).items()])
        
        for n in Utils.getLanIP6s(config):
            localNet += ' : %s ' % n.replace(':', '::')

        # fill in allowed hosts (config.Mail.relay-from)
        if config.Mail.get('relay-from'):
            localNet += ' : ' + ' : '.join(config.Mail['relay-from'])
        extensionBlock = ""

        # Blocked file extensions
        if config.Mail.get('blockedfiles', []):
            extensionBlock = "            deny  message     = We do not accept \".$found_extension\" attachments here.\n"
            extensionBlock += "                 demime      = %s\n" % ':'.join(config.Mail['blockedfiles'])

        # Mail rewrite rules
        rewriteRules = ""
        for fromm,too,flags in config.Mail.get('rewrites', []):
            # flags is one of TtFfbcr
            rewriteRules+='        *@%s    $1@%s   %s\n' % (fromm, too, flags)

        # Get any mailman settings
        mm_router, mm_transport, mm_main = self.MailMan()

        # SpamAssassin required score
        spamscore = config.Mail.get('spamscore', 70)

        # Get greylisting ACLS (if greylisting is enabled)
        aclCheckSenderGreylist, aclCheckDataGreylist = self.Greylisting()

        ### Enable tweaked performance
        performanceTweak = ""
        if config.Mail.get('performance', False):
            performanceTweak =  "        # use muliple directories (default false)\n"
            performanceTweak += "        split_spool_directory\n"
            performanceTweak += "        # queue incoming if load high (no default)\n"
            performanceTweak += "        queue_only_load = 4\n"
            performanceTweak += "        # maximum simultaneous queue runners (default 5)\n"
            performanceTweak += "        queue_run_max = 0\n"
            performanceTweak += "        # parallel delivery of one message to a number of remote hosts (default 2)\n"
            performanceTweak += "        remote_max_parallel = 30\n"
            performanceTweak += "        # simultaneous connections from a single host (default 10)\n"
            performanceTweak += "        smtp_accept_max_per_connection = 20\n"
            performanceTweak += "        # maximum number of waiting SMTP connections (default 20)\n"
            performanceTweak += "        smtp_connect_backlog = 50\n"
            performanceTweak += "        # maximum number of simultaneous incoming SMTP calls that Exim will accept (default 20)\n"
            performanceTweak += "        smtp_accept_max = 0\n"

        if config.Mail.get('rbls'):
            RBL = config.Mail.get('rbls')
        else:
            RBL = [
                "dsn.rfc-ignorant.org/$sender_address_domain",
                "zen.spamhaus.org",
                "dnsbl.njabl.org",
                "bhnc.njabl.org",
                "combined.njabl.org",
                "bl.spamcop.net",
                "psbl-mirror.surriel.com",
                "blackholes.mail-abuse.org",
                "dialup.mail-abuse.org"
            ]


        ### Exim main configuration

        eximMain = """
        ######################################################################
        #                    MAIN CONFIGURATION SETTINGS                     #
        ######################################################################
        ldap_default_servers = %(ldap)s
        primary_hostname = %(hostname)s
        %(avScan)s
        spamd_address = 127.0.0.1 783
        %(systemFilter)s
        
        domainlist local_domains = @ : lsearch;/etc/exim4/local_domains
        domainlist relay_domains = lsearch;/etc/exim4/relay_domains
        hostlist   relay_hosts = 127.0.0.1 : %(hostlist)s
        hostlist   server_hosts = %(serverhosts)s
        
        domainlist acl_domain_whitelist = lsearch;/etc/exim4/domain_whitelist
        hostlist acl_host_whitelist = net-iplsearch;/etc/exim4/host_whitelist
        addresslist acl_sender_whitelist = lsearch*@;/etc/exim4/sender_whitelist
        domainlist acl_domain_blacklist = lsearch;/etc/exim4/domain_blacklist
        hostlist acl_host_blacklist = net-iplsearch;/etc/exim4/host_blacklist
        addresslist acl_sender_blacklist = lsearch*@;/etc/exim4/sender_blacklist
        addresslist acl_allowed_senders = /etc/exim4/allowed_senders

        hostlist acl_host_noavscan = net-iplsearch;/etc/exim4/host_noavscan

        acl_smtp_connect = acl_check_host
        acl_smtp_helo = acl_check_helo
        acl_smtp_mail = acl_check_sender
        acl_smtp_rcpt = acl_check_rcpt
        acl_smtp_data = acl_check_data
        acl_smtp_etrn = acl_check_etrn

        qualify_domain = %(domain)s
        trusted_users = mail
        message_size_limit = %(mailSize)s
        helo_allow_chars = _
        host_lookup = *
        smtp_enforce_sync = false 
        helo_accept_junk_hosts = *
        strip_excess_angle_brackets
        strip_trailing_dot
        delay_warning_condition = "\\
                ${if match{$h_precedence:}{(?i)bulk|list|junk}{no}{yes}}"
        #rfc1413_hosts = ${if eq{$interface_port}{SMTP_PORT} {*}{! *}}
        rfc1413_query_timeout = 0s
        sender_unqualified_hosts = %(hostlist)s
        recipient_unqualified_hosts = %(hostlist)s
        ignore_bounce_errors_after = 2d
        timeout_frozen_after = 7d
        recipients_max = 0
        # SSL/TLS cert and key
        tls_certificate = /etc/exim4/exim.cert
        tls_privatekey = /etc/exim4/exim.key
        # Advertise TLS to anyone
        tls_advertise_hosts = *
        smtp_etrn_command = /etc/exim4/etrn_script $domain

        LDAP_AUTH_CHECK_LOGIN = ${lookup ldap { \\
            user="******"cn=Manager,o=%(base)s" pass=%(pass)s ldap:///?dn?sub?(&(accountStatus=active)(mail=${quote_ldap:$1}))}}" \\
            pass="******" ldap:///?mail?sub?(&(accountStatus=active)(mail=${quote_ldap:$1}))}{yes}{no}}
        
        LDAP_AUTH_CHECK_PLAIN = ${lookup ldap { \\
            user="******"cn=Manager,o=%(base)s" pass=%(pass)s ldap:///?dn?sub?(&(accountStatus=active)(mail=${quote_ldap:$2}))}}" \\
            pass="******" ldap:///?mail?sub?(&(accountStatus=active)(mail=${quote_ldap:$2}))}{yes}{no}}
        

%(extra)s
        """ % {
            'ldap':         '127.0.0.1',
            'hostname':     hostname,
            'hostlist':     localNet,
            'serverhosts':  ' : '.join(serverhosts),
            'domain':       primaryDomain,
            'mailSize':     mailSize,
            'extra':        performanceTweak + mm_main,
            'systemFilter': systemFilter,
            'avScan':       avScan,
            'base':config.LDAPBase,
            'pass':config.LDAPPassword
        }

        eximACL="""
        ######################################################################
        #                       ACL CONFIGURATION                            #
        #         Specifies access control lists for incoming SMTP mail      #
        ######################################################################

        begin acl

        ######################################################################
        # Check connecting host (DNSBL's checked in acl_check_rcpt to ensure no reconnect attempt)
        ######################################################################
        acl_check_host:
            deny hosts        = +acl_host_blacklist
            accept

        ######################################################################
        # Check conencting host is not pretending to be the localhost
        ######################################################################
        acl_check_helo:

            accept hosts         = +relay_hosts
        # If the HELO pretend to be this host
            deny condition       = ${if or { \\
                                  {eq {${lc:$sender_helo_name}}{%(hostname)s}} \\
                                  {eq {${lc:$sender_helo_name}}{%(domain)s}} \\
                                  } {true}{false} }
            accept


        ######################################################################
        # Check sender address
        ######################################################################
        acl_check_sender:
            deny message      = sender envelope address $sender_address is locally blacklisted here.
                senders         = +acl_sender_blacklist

            accept


        ######################################################################
        # Check incoming messages
        ######################################################################
        acl_check_rcpt:

        # Accept if source is local SMTP
          accept hosts      = :
        # Deny if illegal characters in email address
          deny local_parts  = ^.*[@%%!/|] : ^\\\\.

%(ratelimit)s

        # Accept mail to postmaster at any local domain without any checks
          accept local_parts = postmaster
                domains    = +local_domains

%(senderRpFilter)s

        # Accept local, authenticated, whitelisted and dnswl'd hosts
          accept hosts      = +relay_hosts
          accept authenticated = *
          accept dnslists   = list.dnswl.org
          accept hosts      = +acl_host_whitelist
          accept domains    = +acl_domain_whitelist
          accept senders    = +acl_sender_whitelist

        # Deny if domain is locally blacklisted
          deny message        = rejected because $sender_domain is locally blacklisted here
                domains             = +acl_domain_blacklist

        # Deny if listed in a DNSBL
          deny message      = rejected because $sender_host_address is in a blacklist \\
                              at $dnslist_domain\\n$dnslist_text
            !senders        = :
            domains         = +local_domains : +relay_domains
            dnslists        = %(rbl)s

        # Accept if this is a local domain
          accept domains    = +local_domains
            endpass
            message         = unknown user
            verify          = recipient

        # Accept if this is a relay domain
          accept domains    = +relay_domains
            endpass
            message         = unrouteable address
            verify          = recipient

%(senderGreylist)s

        # Deny everything else
            deny message    = relay not permitted

        ######################################################################
        # Check contents of email
        ######################################################################
        acl_check_data:
%(dataGreylist)s

        # ClamAV virus scanning
            deny message      = Vulani has rejected this message because it contains a virus: ($malware_name) http://vulani.net
                log_message   = rejected VIRUS ($malware_name) from $sender_address to $recipients
                !hosts        = +acl_host_noavscan
                demime        = *
                malware       = */defer_ok

        # Reject messages that have serious MIME errors. This calls the demime
        # condition again, but will return cached results.
            deny message      = Vulani has rejected this message because it contains a broken MIME container ($demime_reason) http://vulani.net
                log_message   = rejected broken MIME container ($demime_reason) from $sender_address to $recipients
                condition     = ${if >{$demime_errorlevel}{2}{1}{0}}
                demime        = *

        # SpamAssassin Content Filtering
        # Include Spam Score in Header
            warn message      = X-Spam-Score: $spam_score\\n\\
                                X-Spam-Score-Int: $spam_score_int\\n\\
                                X-Spam-Bar: $spam_bar
                condition     = ${if <{$message_size}{250k}{1}{0}}
                !hosts        = +relay_hosts
                spam          = nobody:true/defer_ok

        # Reject spam messages with score over 7, using an extra condition.
            deny message      = Vulani has rejected this message because it scored $spam_score spam points and is considered to be unsolicited http://vulani.net
                log_message   = rejected SPAM score above threshhold in message from $sender_address to $recipients
                !hosts        = +acl_host_noavscan
                condition     = ${if >{$spam_score_int}{70}{1}{0}}
                spam          = nobody:true

%(extblock)s

            accept

        ######################################################################
        # Check ETRN requests
        ######################################################################
        acl_check_etrn:
            accept hosts = 0.0.0.0/0

        """ % {
            'rbl':              ' : '.join(RBL),        # DNS block lists
            'spamlow':          int(spamscore)-20,      # Warn spam score
            'spamhigh':         int(spamscore),         # Drop spam score.
            'senderGreylist':   aclCheckSenderGreylist, # Greylisting configuration
            'dataGreylist':     aclCheckDataGreylist,   #
            'extblock':         extensionBlock,         # Blocked file extensions
            'hostname':         hostname,
            'domain':       primaryDomain,
            'senderRpFilter': senderRpFilter,
            'ratelimit':    rateLimit,
            'avscan':       avscanacl
        }

        # Trigger our disclaimer transport 
        if config.Mail.get('disclaimer'):
            transport = "remote_smtp_filter"
        else:
            transport = "remote_smtp"

        # Set the external router depending on how the relay is set
        if config.SMTPRelay:
            externalRouter = """
        gateway:
            driver = manualroute
            domains = ! +local_domains
            route_list = * %s bydns
            transport = %s
           """ % (config.SMTPRelay, transport)
        else:
            externalRouter = """
        dnslookup:
            driver = dnslookup
            domains = ! +local_domains
            transport = %s
            ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8
            no_more
            """ % transport

        eximRouters = """
        ######################################################################
        #                      ROUTERS CONFIGURATION                         #
        ######################################################################

        begin routers

        etrn_already:
            driver = accept
            transport = bsmtp_for_etrn
            require_files = /var/spool/mail/etrn/$domain
            domains = lsearch;/etc/exim/etrn_domains

        etrn_delay:
            driver = accept
            transport = bsmtp_for_etrn
            condition = ${if >{$message_age}{1800} {yes}{no}}
            domains = lsearch;/etc/exim/etrn_domains

        mail_reroute:
            driver = manualroute
            route_data = ${lookup{$local_part@$domain}lsearch{/etc/exim4/mail_reroute}}
            transport = remote_smtp

        branch_reroute:
            driver = manualroute
            route_data = ${lookup{$local_part@$domain}lsearch{/etc/exim4/branch_reroute}}
            transport = remote_smtp

        hubbed_hosts:
            driver = manualroute
            domains = ! +local_domains
            route_data = ${lookup{$domain}lsearch{/etc/exim/hubbed_hosts}}
            transport = remote_smtp

%(extro)s

        userforward:
            driver = redirect
            domains = +local_domains
            file = /var/spool/mail/forward/${local_part}@${domain}
            no_verify
            no_expn
            check_ancestor
            file_transport = address_file
            pipe_transport = address_pipe
            reply_transport = address_reply

        alias_user_vacation:
            driver = redirect
            domains = +local_domains
            allow_defer
            allow_fail
            data = ${lookup ldap {user="******" pass=%(ldappass)s \\
                   ldap:///?mail?sub?(mailAlternateAddress=${local_part}@${domain})}}
            redirect_router = user_vacation
            retry_use_local_part

        user_vacation:
            driver = accept
            domains = +local_domains
            require_files = /var/spool/mail/vacation/${local_part}@${domain}.txt
            no_verify
            user = apache
            senders = !^.*-request@.* : !^owner-.*@.* : !^postmaster@.* : \\
                      ! ^listmaster@.* : !^mailer-daemon@.* : !^noreply@.* : \\
                      !^.*-bounces@.*
            transport = vacation_reply
            unseen

        ldap_aliases:
            driver = redirect
            domains = +local_domains
            allow_defer
            allow_fail
            data = ${lookup ldap {user="******" pass=%(ldappass)s \\
                   ldap:///?mail?sub?(mailAlternateAddress=${local_part}@${domain})}}
            redirect_router = ldap_forward
            retry_use_local_part

        ldap_forward:
            driver = redirect
            domains = +local_domains
            allow_defer
            allow_fail
            data = ${lookup ldap {user="******" pass=%(ldappass)s \\
                    ldap:///?mailForwardingAddress?sub?\\
                    (&(accountStatus=active)(mail=${local_part}@${domain}))}{$value}fail}
            no_expn
            retry_use_local_part
            no_verify

        ldap_user:
            driver = accept
            domains = +local_domains
            condition =   ${if eq {}{${lookup ldap {user="******" pass=%(ldappass)s \\
                          ldap:///?mail?sub?(&(accountStatus=active)(mail=${local_part}@${domain}))}}}{no}{yes}}
            group = users
            retry_use_local_part
            transport = local_delivery

        catchall:
            domains = lsearch;/etc/exim/catchall_domains
            driver = redirect
            data = catchall@${domain}

%(router)s

        #localuser:
        #    driver = accept
        #    domains = +local_domains
        #    check_local_user
        #    transport = local_delivery
        """ % {
            'router': mm_router,
            'ldapbase': config.LDAPBase,
            'ldappass': config.LDAPPassword,
            'extro': externalRouter,
        }

        ## Prevent bounce of failed hosts? (Maximum send timeout reached)
        hostfailBounce = ""
        if config.Mail.get('hostfailbounce', False):
            hostfailBounce += "    delay_after_cutoff = false\n"

        if config.Mail.get('smtpinterface'):
            hostfailBounce += "    interface = %s\n" % config.Mail.get('smtpinterface')

        eximTransports = """
        ######################################################################
        #                      TRANSPORTS CONFIGURATION                      #
        ######################################################################

        begin transports

        bsmtp_for_etrn:
            driver=appendfile
            file=/var/spool/mail/etrn/$domain
            user=mail
            batch_max=1000
            use_bsmtp

        vacation_reply:
            debug_print = "T: vacation_reply for $local_part@$domain"
            driver = autoreply
            file = /var/spool/mail/vacation/${local_part}@${domain}.txt
            file_expand
            log = /var/spool/mail/vacation/${local_part}@${domain}.log
            once_repeat = 7d
            once = /var/spool/mail/vacation/${local_part}@${domain}.db
            from = ${local_part}@${domain}
            to = $sender_address
            subject = "Re: $h_subject"
            text = "\\
            This is an automated response for $local_part@${domain}:\\n\\
            ====================================================\\n\\n"

        remote_smtp:
            driver = smtp
            %(iface)s

        remote_smtp_filter:
            driver = smtp
            transport_filter = /usr/local/tcs/tums/bin/remime
            %(iface)s

        local_delivery:
            driver = appendfile
            create_directory
            delivery_date_add
            directory = ${lookup ldap {user="******" pass=%(wpass)s \\
                        ldap:///?mailMessageStore?sub?(&(accountStatus=active)\\
                        (mail=${local_part}@${domain}))}}
            directory_mode = 770
            envelope_to_add
            group = mail
            maildir_format
            mode = 660
            return_path_add
            user = mail

        address_pipe:
            driver = pipe
            return_output

        address_file:
            driver = appendfile
            delivery_date_add
            envelope_to_add
            return_path_add

        address_reply:
            driver = autoreply

        %(mm)s\n""" % {
            'iface': hostfailBounce, 
            'basedn': config.LDAPBase, 
            'wpass': config.LDAPPassword, 
            'mm': mm_transport
        }

        eximOther = """
        ######################################################################
        #                      RETRY CONFIGURATION                           #
        ######################################################################

        begin retry
        *        *   senders=:      F,2m,1m
        *        *                  F,2h,15m; G,16h,1h,1.5; F,7d,4h

        ######################################################################
        #                      REWRITE CONFIGURATION                         #
        ######################################################################

        begin rewrite
%(rewrite)s
        ######################################################################
        #                   AUTHENTICATION CONFIGURATION                     #
        ######################################################################

        begin authenticators

        login:
            driver = plaintext
            public_name = LOGIN
            server_prompts = "Username:: : Password::"
            server_advertise_condition = yes
            server_condition = ${if match_ip{$sender_host_address}{+relay_hosts}{yes}{LDAP_AUTH_CHECK_LOGIN}}
            server_set_id = $1
        plain:
            driver = plaintext
            public_name = PLAIN
            server_prompts = :
            server_advertise_condition = yes
            server_condition = ${if match_ip{$sender_host_address}{+relay_hosts}{yes}{LDAP_AUTH_CHECK_PLAIN}}
            server_set_id = $2 
        """ % {
            'base':config.LDAPBase,
            'pass':config.LDAPPassword,
            'rewrite': rewriteRules
        }

        confFile = eximMain + eximACL + eximRouters + eximTransports + eximOther
        os.system('mkdir -p /var/spool/mail/forward/')
        os.system('mkdir -p /var/spool/mail/etrn/')

        # Reprocess the config file
        lp = confFile.split('\n')
        confFile = ""
        for i in lp:
            confFile += i[8:] + '\n'

        confFile = confFile.replace('/etc/exim/', '/etc/exim4/').replace('apache', 'www-data')
        # Patches user names
        confFile = confFile.replace('user=mail', 'user=Debian-exim')
        Utils.writeConf('/etc/exim4/exim4.conf', confFile, '#')
        os.system('chmod a+r /etc/exim4/*')
        os.system('chmod -R a+r /usr/local/tcs/tums/data')
        os.system('chmod a+x /etc/exim4/etrn_script >/dev/null 2>&1')
        os.system('chmod a+rx /var/mail/vacation >/dev/null 2>&1')
        os.system('chown Debian-exim:Debian-exim /var/spool/mail/etrn')
        os.system('mkdir /var/cache/vulani/ >/dev/null 2>&1')

        ### Mailname
        mailname = "%s.%s\n" % ( config.Hostname, config.Domain )
        l = open('/etc/mailname', 'wt')
        l.write(mailname)
        l.close()
Esempio n. 5
0
    def writeConfig(self, *a):
        # conf.d/net
        net = "\n"
        routes = ""
        vlanIfaces = {}
        dhcpIfaces = []
        for interface, defin in config.EthernetDevices.items():
            if interface!="extra":
                net += 'config_%s=(\n' % interface 
                if config.EthernetDevices[interface]['type'].lower() == 'dhcp':
                    net += '    "dhcp"\n'
                if config.EthernetDevices[interface]['type'].lower() == 'manual':
                    net += ' '
                else:
                    net += '    "%s"\n' % (config.EthernetDevices[interface]['ip'])

                if config.EthernetDevices[interface].get('aliases',None):
                    for addr in config.EthernetDevices[interface]['aliases']:
                        net+= '    "%s"\n' % (addr)

                if defin.get('extra', None):
                    net += defin['extra']

                net += ')\n\n'

                if "vlan" in interface:
                    if defin.get('interface', False):
                        if defin['interface'] in vlanIfaces:
                            vlanIfaces[defin['interface']].append(interface.strip('vlan'))
                        else:
                            vlanIfaces[defin['interface']] = [interface.strip('vlan')]

                routes += 'routes_%s=(\n' % interface
                for ro in config.EthernetDevices[interface].get('routes', []):
                    routes += '    "%s via %s"\n' % ro
                routes += ')\n'

                if interface == config.LANPrimary or defin.get('dhcpserver', False):
                    dhcpIfaces.append(interface)

        confddhcp = "DHCPD_IFACE=\"%s\"\n" % ' '.join(dhcpIfaces)
        cdd = open('/etc/conf.d/dhcpd', 'wt')
        cdd.write(confddhcp)
        cdd.close()

        # config tunnel
        cont = []
        l = open('/etc/conf.d/local.start')
        for i in l:
            if i.strip() and not "# TUN" in i:
                cont.append(i)

        l.close()

        if config.Tunnel.get('ipv6', False):
            remote = config.Tunnel['ipv6']['remoteip']
            local = config.Tunnel['ipv6']['localip']
            localv6 = config.Tunnel['ipv6']['localv6']

            cont.append('ip tunnel add ipv6tun mode sit remote %s local %s ttl 255 # TUN' % (remote, local))
            cont.append('ip link set ipv6tun up # TUN')
            cont.append('ip addr add %s dev ipv6tun # TUN' % (localv6))
            cont.append('ip -6 ro add 2003::/3 dev ipv6tun # TUN\n')

        l = open('/etc/conf.d/local.start', "wt")
        l.write('\n'.join(cont))
        l.close()

        for iface, vlans in vlanIfaces.items():
            net+= "vlans_%s=\"%s\"\n" % (iface, ' '.join(vlans))
            net+= "vconfig_%s=( \"set_name_type VLAN_PLUS_VID_NO_PAD\" )\n" % (iface)

        if config.EthernetDevices.get('extra', None):
            net += config.EthernetDevices['extra']
            net += '\n' 

        for wan in config.WANDevices:
            net += "config_%s=(\"ppp\")\n" % wan
            for opt in config.WANDevices[wan]:
                if type(config.WANDevices[wan][opt]) is list:
                    val = "( %s )" % (' '.join(['"%s"' % i for i in config.WANDevices[wan][opt]]))
                else:
                    val = '"%s"' % config.WANDevices[wan][opt]
                net += '%s_%s=%s \n' % (opt, wan, val)

            net += '\n'
        net += routes
        Utils.writeConf('/etc/conf.d/net', net, '#')
Esempio n. 6
0
    def writeConfig(self, *a):
        syslogConfig = """# Vulani Logging setup
auth,authpriv.*                 /var/log/auth.log
*.*;lpr,user,uucp,cron,auth,authpriv,local0,local1,local2,local3,local4,local5,local6.none,local7.none          -/var/log/syslog
cron.*                         /var/log/cron.log
daemon.*                        -/var/log/daemon.log
kern.*                          -/var/log/kern.log
lpr.*                           -/var/log/lpr.log
mail.*                          /var/log/mail.log
user.*                          -/var/log/user.log
uucp.*                          -/var/log/uucp.log
local0,local1,local3,local5.*   -/var/log/localproc.log
local6.*                        -/var/log/imapd.log
local2.*                        -/var/log/ppp.log
local4.*                        -/var/log/slapd.log
local7.*                        -/var/log/dhcpd.log
mail.info                       -/var/log/mail.info
mail.warn                       -/var/log/mail.warn
mail.err                        /var/log/mail.err
*.=debug;\
        auth,authpriv.none;\
        news.none;mail.none     -/var/log/debug
*.=info;*.=notice;*.=warn;\
        auth,authpriv.none;\
        cron,daemon.none;\
        mail,news.none          -/var/log/messages
*.emerg                         *
*.emerg                         /var/log/emergency"""

        Utils.writeConf('/etc/syslog.conf', syslogConfig, '#')

        clamavd = """/var/log/clamav/clamav.log {
     rotate 12
     weekly
     compress
     delaycompress
     create 640  Debian-exim Debian-exim
     postrotate
     /etc/init.d/clamav-daemon reload-log > /dev/null
     endscript
}\n"""
        clamavfc = """/var/log/clamav/freshclam.log {
     rotate 12
     weekly
     compress
     delaycompress
     create 640 Debian-exim Debian-exim
     postrotate
     /etc/init.d/clamav-freshclam reload-log > /dev/null
     endscript
}\n"""
        exim4 = """/var/log/exim4/mainlog /var/log/exim4/rejectlog {
        daily
        missingok
        rotate 10
        compress
        delaycompress
        notifempty
        create 640 Debian-exim adm
}

/var/log/exim4/paniclog {
        weekly
        missingok
        rotate 10
        compress
        delaycompress
        notifempty
        create 640 Debian-exim adm
}\n"""
        squid = """/var/log/squid/*.log {
        daily
        compress
        delaycompress
        rotate 10
        missingok
        nocreate
        sharedscripts 
        postrotate
                test ! -e /var/run/squid.pid || /usr/sbin/squid -k rotate
        endscript
}\n"""

        tums = """/var/log/tums_cache.log {
        daily
        compress
        delaycompress
        rotate 10
        missingok
        create 666 proxy proxy        
}\n"""
        Utils.writeConf('/etc/logrotate.d/clamav-daemon', clamavd, '#')
        Utils.writeConf('/etc/logrotate.d/clamav-freshclam', clamavfc, '#')
        Utils.writeConf('/etc/logrotate.d/exim4-base', exim4, '#')
        Utils.writeConf('/etc/logrotate.d/squid', squid, '#')
        Utils.writeConf('/etc/logrotate.d/tums', tums, '#')
Esempio n. 7
0
    def writeConfig(self, *a):
        print "Performing final %s configuration" % PRODNAME
        print "   Preparing LDAP tree...",

        # make sure slapd is stopped
        os.system('/etc/init.d/slapd stop > /dev/null 2>&1')
        # Back up ldap.. Who knows.. someone just might postprep a live box :(
        os.system('slapcat > /usr/local/tcs/tums/backups/ldap-%s.ldif' % int(time.time()))
        # Kill the ldap database because 1.2rc3 came with cruf in it for some reason
        os.system('rm /var/lib/ldap/* > /dev/null 2>&1')

        # Start SLAPd 
        os.system('/etc/init.d/slapd start > /dev/null 2>&1')
        # Make sure it's started...
        lk = os.popen('/etc/init.d/slapd status').read()
        if "stopped" in lk:
            print "slapd isn't running, and I can't start it :-(."
            print "the LDAP service is probably broken."
            return
        # Generate a shiny new tree
        os.system('/usr/local/tcs/tums/genLDAP.py')
        # Import the new tree
        os.system('/etc/init.d/slapd stop > /dev/null 2>&1')
        os.system('slapadd < /usr/local/tcs/tums/template.ldif > /dev/null 2>&1') # ldapadd is f****d on Debian
        os.system('chown openldap:openldap /var/lib/ldap/*')
        os.system('chmod a+r /var/lib/ldap/*')
        os.system('su - openldap slapindex > /dev/null 2>&1')
        os.system('/etc/init.d/slapd start > /dev/null 2>&1')
        os.system('chown openldap:openldap /var/lib/ldap/*')
        # Restart slapd for safe measure
        os.system('/etc/init.d/slapd restart > /dev/null 2>&1')
        os.system('/etc/init.d/samba restart > /dev/null 2>&1')
        print "Populating...",

        # Populate the LDAP tree with SMB goodness
        os.system('/usr/local/tcs/tums/syscripts/populate > /dev/null 2>&1')
        # Sprinkle on a bit of joy and sugar
        os.system('/usr/local/tcs/tums/ldapConfig > /dev/null 2>&1')
        # Secure it with a password
        os.system('/usr/bin/smbpasswd -w `cat /etc/ldap/slapd.conf | grep rootpw | awk \'{print $2}\'` > /dev/null 2>&1')        
        # And then switch it off again
        os.system('/etc/init.d/samba stop > /dev/null 2>&1')

        # Gratuitous hack persistance
        os.system('/etc/init.d/slapd restart > /dev/null 2>&1')

        # Put the domain tools in place..
        
        print " Done."

        print "   Installing PDC utilities...",

        os.system('tar -zxf /usr/local/tcs/tums/packages/netlogon.tar.gz -C /var/lib/samba/netlogon/')

        print " Done."

        print "   Building security certificates...",
        os.system('/usr/local/tcs/tums/syscripts/vpn.sh > /dev/null 2>&1')
        os.system('mkdir /etc/openvpn/vpn-ccd; chmod -R a+r /etc/openvpn')

        # Clear samba cache
        os.system('rm /var/cache/samba/wins.dat > /dev/null 2>&1')
        os.system('rm /var/cache/samba/gencache.tdb > /dev/null 2>&1')
        os.system('rm /var/cache/samba/browse.dat > /dev/null 2>&1')

        os.system('rm /etc/bind/pri/*.jnl > /dev/null 2>&1')

        #os.system('/root/tcs/vpn.sh > /dev/null 2>&1')
        os.system('/usr/bin/openssl req -x509 -batch -newkey rsa:1024 -keyout /etc/exim4/exim.key -out /etc/exim4/exim.cert -days 9999 -nodes > /dev/null 2>&1')
        print " Done."

        print "   Detecting hardware...",
        os.system('yes yes | sensors-detect > /dev/null 2>&1')
        print " Done. (ignore the 'yes' error)"
        
        print "   Updating system clock...",
        os.system('ntpdate -su %s > /dev/null 2>&1' % config.NTP)
        print " Done."

        print "   Saving settings...",
        
        # Recreate openssh-server keys if it's gentoo
        runlevels =  [
            ('apache2',  'default'),
            ('slapd',  'default'),
            ('mysql',  'default'),
            ('exim',  'default'),
            ('clamd', 'default'),
            ('courier-imapd',  'default'),
            ('courier-authlib',  'default'),
            ('courier-pop3d',  'default'),
            ('ddclient', 'default'),
            ('shorewall', 'default'),
            ('spamd', 'default'),
            ('squid', 'default'),
            ('smartd', 'default'),
            ('sysklogd', 'default'),
            ('ulogd', 'default'),
            ('xinetd', 'default'),
            ('cupsd', 'default'),
            ('netmount', 'default'),
            ('ntp-client', 'default'),
            ('ntpd', 'default'),
            ('gpm', 'default'),
            ('samba', 'default'),
            ('nscd', 'default'),
            ('named', 'default'),
            ('tums', 'default'),
            ('quagga', 'default'),
            ('zebra', 'default')
        ]

        for run, level in runlevels:
            # apply modifications for debian
            level = level.replace('default', 'defaults')
            run = run.replace('dhcpd', 'dhcp3-server').replace('exim', 'exim4')
            run = run.replace('courier-authlib', 'courier-authdaemon')
            os.system('update-rc.d %s %s > /dev/null 2>&1' % (run, level))

        # Do defaults fixes (bloody irritating...)
        spamd = """ENABLED=1
OPTIONS="-s local6 --create-prefs --max-children 5 --helper-home-dir"
PIDFILE="/var/run/spamd.pid"
NICE="--nicelevel 15"
"""
        Utils.writeConf('/etc/default/spamassassin', spamd, '#')

        shorewall = """startup=1\n"""
        Utils.writeConf('/etc/default/shorewall', shorewall, '#')

        os.system('update-rc.d -f fprobe remove > /dev/null 2>&1')
        
        
        # Make sure l2tpns starts earlier
        os.system('update-rc.d -f l2tpns remove > /dev/null 2>&1')
        os.system('update-rc.d l2tpns start 16 2 3 4 5 . stop 16 0 1 6 . > /dev/null 2>&1')

        # Make sure shorewall starts much much later
        os.system('update-rc.d -f shorewall remove > /dev/null 2>&1')
        os.system('update-rc.d shorewall start 90 2 3 4 5 . stop 90 0 1 6 . > /dev/null 2>&1')

        os.system('chmod +x /usr/local/tcs/tums/existat.py')
        os.system('chmod +x /usr/local/tcs/tums/existat-render.py')
        os.system('chmod +x /usr/local/tcs/tums/bin/*')
        os.system('chmod a+r /usr/local/tcs/tums/currentProfile')
        os.system('chmod a+r /usr/local/tcs/tums/profiles')
        os.system('chmod a+r /usr/local/tcs/tums/profiles/*')

        os.system('chmod a+x /var/lib/samba/data')
        os.system('chmod a+rwx /var/lib/samba/data/public')

        os.system('ln -s /usr/local/tcs/tums/vdiag /usr/bin/')
        os.system('ln -s /usr/local/tcs/tums/configurator /usr/bin/')


        print " Done."

        print "   Creating admin account...",
        self.createAdmin()
        print " Done."

        # Upgrade the system to ACL supprt
        print "   Configuring ACL support...",
        os.system("sed -i 's/reiserfs.*notail/reiserfs notail,acl/' /etc/fstab")
        print " Done."

        os.system('/usr/local/tcs/tums/configurator --services > /dev/null')
        os.system('/usr/local/tcs/tums/configurator --apt > /dev/null')
        print "\nInstallation Complete"
Esempio n. 8
0
File: HA.py Progetto: calston/tums
    def writeConfig(self, *a):
        if not config.General.get('ha'):
            # No Xen config
            return 

        haConf = config.General.get('ha')
        nodes = []
        masterName = ""
        for nodeip, v in haConf.items():
            nodes.append(v['name'])
            if v['topology'] == "master":
                masterName = v['name']

        hacf = """logfile /var/log/ha.log
keepalive 1

deadtime 30
initdead 80

bcast  %(lan)s

#   Tell what machines are in the cluster
#   node    nodename ...    -- must match uname -n
node    %(node)s


# Usualy 'crm yes'
#crm respawn 

auto_failback yes
"""     %   { 
                'lan': haConf.get('port', Utils.getLans(config)[0]),
                'node': '   '.join(nodes)
            }

        Utils.writeConf('/etc/heartbeat/ha.cf', hacf, '#')

        auth = "auth 2\n2 sha1 haf%s\n" % masterName

        Utils.writeConf('/etc/heartbeat/authkeys', auth, '#')

        os.system('chmod 0600 /etc/heartbeat/authkeys')
        
        nets = []
        for k,v in config.EthernetDevices.items():
            nets.append('%s/%s' % (v['ip'], k))
        
        conline = "%s   %s  vulani\n" % (masterName, ' '.join(nets))
        Utils.writeConf('/etc/heartbeat/haresources', conline, '#')

        vulaniResource = """#!/bin/sh
#
# Description:  Vulani Master resource.d
#
# Author:       Colin Alston <*****@*****.**>
# Support:      [email protected]
# License:      All rights reserved
# Copyright:    (C) 2008 Thusa Business Support (Pty) Ltd.

exit 0"""
        l = open('/etc/heartbeat/resource.d/vulani', 'wt')
        l.write(vulaniResource)
        l.close()

        os.system('chmod a+x /etc/heartbeat/resource.d/vulani')

        # Before we restart our local HB service, make sure our slaves are OFF
        
        for name, v in haConf.items():
            if v['topology'] == 'slave':
                os.system('ssh root@%s /etc/init.d/heartbeat stop' % name)

        os.system('/etc/init.d/heartbeat restart')
        

        # Reconfigure SSH to not do SHKC 
        # This is required in order for fresh hosts not to block eachother interactivly
        ssh_config = """# SSH client configuration

Host *
    StrictHostKeyChecking no
    SendEnv LANG LC_*
    HashKnownHosts yes
    GSSAPIAuthentication yes
    GSSAPIDelegateCredentials no\n"""
        
        Utils.writeConf('/etc/ssh/ssh_config', ssh_config, '#')


        # Configure master LDAP
        self.configureMasterLDAP()

        # Configure slaves
        for nodeip, v in haConf.items():
            if v['topology'] == 'slave':
                self.configureSlave(nodeip)
                self.sendLDAP(nodeip)
Esempio n. 9
0
File: HA.py Progetto: calston/tums
    def configureMasterLDAP(self):
        
        replicas = []

        haConf = config.General.get('ha')
        for nodeip, v in haConf.items():
            if v['topology'] == 'slave':
                replicas.append("""replica host=%(ip)s
        binddn="cn=Manager, o=%(base)s"
        bindmethod=simple credentials=%(pass)s""" % {
                    'base': config.LDAPBase,
                    'pass': config.LDAPPassword,
                    'ip': nodeip,
                })

        conf = """include         /etc/ldap/schema/core.schema
include         /etc/ldap/schema/cosine.schema
include         /etc/ldap/schema/nis.schema
include         /etc/ldap/schema/inetorgperson.schema
include         /etc/ldap/schema/samba.schema
include         /etc/ldap/schema/thusa.schema

allow bind_v2

pidfile         /var/run/slapd/slapd.pid
argsfile        /var/run/slapd/slapd.args
loglevel        256
modulepath      /usr/lib/ldap
moduleload      back_bdb
tool-threads    1
defaultsearchbase "o=%(base)s"

backend         bdb
database        bdb
suffix          "o=%(base)s"
#checkpoint      128 15

threads         16
idletimeout     0
sizelimit       unlimited

rootdn          "cn=Manager,o=%(base)s"
rootpw          %(pass)s

directory       "/var/lib/ldap"

access to attrs=userPassword
        by self write
        by dn="cn=Manager,o=%(base)s" write
        by * auth

access to *
        by self write
        by dn="cn=Manager,o=%(base)s" write
        by peername.ip=127.0.0.1 read
        by * read
        by * auth


replogfile /var/lib/ldap/replogfile

%(replica)s

index dc eq
index objectClass,givenname,sn,cn,uid pres,eq
index uniqueMember,memberUid pres,eq
index accountStatus,mail pres,eq
index uidNumber,mailAlternateAddress pres,eq
index associatedDomain pres,eq
index sOARecord,aRecord pres,eq
index sambaSID,sambaSIDList,sambaGroupType pres,eq
index gidNumber,displayName,employeeType pres,eq\n""" % {
            'base': config.LDAPBase,
            'pass': config.LDAPPassword, 
            'replica': '\n'.join(replicas)
        }

        Utils.writeConf('/etc/ldap/slapd.conf', conf, '#')

        os.system("sed -i 's/SLURPD_START=auto/SLURPD_START=yes/g' /etc/default/slapd")

        os.system('/etc/init.d/slapd restart')