def writeConfig(self, *a): try: serverIP = Utils.getLanIPs(config)[0] except: # We aren't sure what our IP is.. oh dear serverIP = "127.0.0.1" #Check current hostname is consistent try: l = open('/etc/hostname', 'r') sysHostname = l.read() l.close() if config.Hostname != sysHostname.strip(): #If the hostname is inconsistent then we should redefine the hostname #This will fix problems with debsecan l = open('/etc/hostname', 'wt') l.write(config.Hostname + "\n") l.close() os.system('/bin/hostname -F /etc/hostname') except Exception, _e: print "Warning: Unable to validate or correct hostname, ", str(_e)
def writeConfig(self, *a): if not config.General.get('xen'): # No Xen config return if not config.General['xen'].get('enabled'): # Disabled return self.checkInstall() XenConf = config.General['xen'].get('config', {}) conf = """ # -*- sh -*- # Vulani Xen configuration (network-script 'network-bridge netdev=%(lanPrimary)s') (network-script network-dummy) (vif-script vif-bridge) (dom0-min-mem 196) (dom0-cpus 0) (vnc-listen '%(lanPrimaryIp)s' """ % { 'lanPrimaryIp': Utils.getLanIPs(config)[0], 'lanPrimary': Utils.getLans(config)[0] } # Seek out our latest Xen kernel lines = os.open('ls /boot/ | grep xen-vserver | grep -v ".bak$"') kern = "vmlinuz-2.6.18-6-xen-vserver-686" init = "initrd.img-2.6.18-6-xen-vserver-686" knum = 2 * 6 * 18 * 6 inum = 2 * 6 * 18 * 6 for n in lines.read(): line = n.strip('\n') if not ('vmlinuz' in line or 'initrd' in line): # avoid things that might break this logic continue p = line.split('-') # Make a big number from the version ver = reduce(lambda x, y: x * y, [int(i) for i in p[1].split('.')]) * int(p[2]) # Make sure this is the biggest version if "vmlinuz" in line: if ver > knum: kern = line knum = ver if "initrd" in line: if ver > knum: init = line inum = ver toolconf = """ # Vulani Xen-tools configuration dir = /storage/virtual_machines size = 10Gb memory = 128Mb swap = 128Mb fs = ext3 dist = etch image = sparse dhcp = 1 passwd = 1 kernel = /boot/%(xenKern)s initrd = /boot/%(xenInit)s mirror = http://debian.mirror.ac.za/debian/ """ % { 'xenKern': kern, 'xenInit': init } defaults = """ # Vulani Xen defaults XENDOMAINS_SYSRQ="" XENDOMAINS_USLEEP=100000 XENDOMAINS_CREATE_USLEEP=5000000 XENDOMAINS_MIGRATE="" XENDOMAINS_SAVE=/var/lib/xen/save XENDOMAINS_SHUTDOWN="--halt --wait" XENDOMAINS_SHUTDOWN_ALL="--all --halt --wait" XENDOMAINS_RESTORE=true XENDOMAINS_AUTO=/etc/xen/auto XENDOMAINS_AUTO_ONLY=false XENDOMAINS_STOP_MAXWAIT=300 """ Utils.writeConf('/etc/xend-config.sxp', conf, None) Utils.writeConf('/etc/xen-tools/xen-tools.conf', toolconf, None) Utils.writeConf('/etc/default/xendomains', defaults, None)
def writeConfig(self, *a): try: serverIP = Utils.getLanIPs(config)[0] except: # We aren't sure what our IP is.. oh dear serverIP = "127.0.0.1" # This all needs to happen first hosts = """127.0.0.1 localhost 127.0.1.1 %(host)s.%(domain)s %(host)s # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters ff02::3 ip6-allhosts\n""" % { 'host': config.Hostname, 'domain': config.Domain } l = open('/etc/hosts', 'wt') l.write(hosts) l.close() if config.General.get('sysresolv', []): ns = "" for i in config.General['sysresolv']: ns += 'nameserver %s\n' % i else: if serverIP == "127.0.0.1": ns = "" else: ns = 'nameserver 127.0.0.1\n' resolv = """search %s domain %s %s\n""" % (config.Domain, config.Domain, ns) l = open('/etc/resolv.conf', 'wt') l.write(resolv) l.close() os.system('mkdir -p /etc/bind/pri > /dev/null 2>&1') SOA = """@ 86400 IN SOA %s. postmaster.%s. ( 1 ; Serial 28800 ; Refresh 7200 ; Retry 604800 ; Expire 3600) ; Minimum TTL\n""" zones = "" ipv6addr = "" ipv6listen = "" ipv6query = "" if Utils.getLanIP6s(config): ipv6addr = Utils.getLanIP6s(config) ipv6listen = "listen-on-v6 {\n %s;\n };" % ';'.join( [n.split('/')[0] for n in ipv6addr]) ipv6query = "%s;" % Utils.getV6Network(ipv6addr[0]) TSOA = SOA % ("%s.%s" % (config.Hostname, config.Domain), config.Domain) TSOA += " NS %s.%s.\n" % ( config.Hostname, config.Domain) if not config.General.get('zones', {}).get(config.Domain, None): if not serverIP: serverIP = "127.0.0.1" forward = TSOA + " A %s\n" % serverIP for cname in config.TCSAliases: spaces = ''.join([" " for i in range(20 - len(cname))]) forward += "%s %s CNAME %s\n" % (cname, spaces, config.Hostname) forward += "%s A %s\n" % (config.Hostname, serverIP) if ipv6addr: forward += "%s AAAA %s\n" % ( config.Hostname, ipv6addr[0]) Utils.writeConf('/etc/bind/pri/%s.zone' % (config.Domain, ), forward, ';') zones += """ zone "%s" in { type master; allow-update { 127.0.0.1; }; notify no; file "pri/%s.zone"; };\n\n""" % (config.Domain, config.Domain) if config.General.get('zones', None): for domain, info in config.General['zones'].items(): zones += " zone \"%s\" in {\n" % domain # Get options if info.get('options', None): for opt in info['options']: zones += " %s;\n" % opt else: # Use defaults zones += " type master;\n notify no;\n" if 'type forward' not in info.get('options'): # check updaters if info.get('update', None): zones += " allow-update {\n" for update in info['update']: zones += " %s;\n" % update zones += " };\n" else: # Use default localhost. zones += " allow-update {\n 127.0.0.1;\n };" ns = info.get('ns', []) if len(ns) < 1: print "ERROR!! Domain %s requires at least 1 name server!" % domain sys.exit() # Create zone data zonedata = "" for i in ns: zonedata += " NS %s.\n" % i if info.get('records'): maxRec = max([ len(rec.split()[0]) for rec in info.get('records', []) ]) + 5 else: maxRec = 4 colspace = [maxRec, 8] first = "" for rec in info.get('records', []): if "MX" in rec: host, type, prio, data = rec.split() type = "%s %s" % (type, prio) else: host, type, data = tuple(rec.split()) theseSpaces = [ colspace[c] - len(i) for c, i in enumerate([host, type]) ] recLine = "%s%s%s%s%s\n" % (host, " " * theseSpaces[0], type, " " * theseSpaces[1], data) if type == "NS" or "MX" in rec: first += recLine else: zonedata += recLine if 'type forward' in info.get('options'): zones += " forwarders {\n %s;\n };\n" % info.get( 'forward') if 'type slave' in info.get('options'): uservs = [] for i in info.get('update'): if i != "127.0.0.1": uservs.append(i) zones += " masters {\n %s;\n };\n" % ';'.join( uservs) if 'type master' in info.get('options'): zones += " file \"pri/%s.zone\";\n" % domain # Terminate entry zones += " };\n" l = open('/etc/bind/pri/%s.zone' % domain, 'wt') l.write(SOA % (ns[0], domain)) l.write(first) l.write(zonedata) l.close() reverse = TSOA + "%s PTR %s.%s.\n" % ( serverIP.split('.')[-1], config.Hostname, config.Domain) os.system('chown -R bind:bind /etc/bind/pri ') Utils.writeConf('/etc/bind/pri/reverse.zone', reverse, ';') lanv4Ips = Utils.getLanIPs(config) if lanv4Ips: listenv4 = ';'.join(lanv4Ips) + ';' else: listenv4 = "" options = """options { listen-on { 127.0.0.1; %s }; %s allow-query { %s 127.0.0.1; 0.0.0.0/0; }; forwarders { %s }; directory "/var/bind"; pid-file "/var/run/named/named.pid"; forward first;\n};\n\n""" % (listenv4, ipv6listen, ipv6query, ''.join( [" %s;\n" % i for i in config.ForwardingNameservers])) zones = """zone "." in { type hint; file "named.ca"; }; zone "0.0.127.in-addr.arpa" in { type master; file "pri/127.zone"; notify no; }; zone "localhost" in { type master; file "pri/localhost.zone"; notify no; }; zone "%s.in-addr.arpa" in { type master; file "pri/reverse.zone"; notify no; allow-update { 127.0.0.1; }; }; %s\n""" % ('.'.join([i for i in reversed(serverIP.split('.')[:3])]), zones) # Debian modifications zones = zones.replace('named.ca', 'db.root') zones = zones.replace('pri/localhost.zone', 'db.local') zones = zones.replace('pri/127.zone', 'db.127') options = options.replace('pid-file "/var/run/named/named.pid";', '') options = options.replace('directory "/var/bind";', 'directory "/etc/bind";') # Rechown os.system('chown -R bind:bind /etc/bind/*') bindFile = options + zones Utils.writeConf('/etc/bind/named.conf', bindFile, '//') os.system('rm /etc/bind/pri/*.jnl > /dev/null 2>&1')
def writeConfig(self, *a): path = "/etc/squid/" # Make sure Dansguardian is sorted os.system('mkdir -p /var/log/dansguardian') os.system('touch /var/log/dansguardian/access.log') os.system('chown -R dansguardian:dansguardian /var/log/dansguardian') # Sort out update cache permissions os.system('mkdir -p /var/lib/samba/updates/download') os.system('chown -R proxy:proxy /var/lib/samba/updates') os.system('chmod -R a+rwx /var/lib/samba/updates') os.system('chmod -R a+rwx /usr/local/tcs/tums/uaxeldb') #Fix read permissions for config files os.system('chmod a+r /etc/squid') os.system('chmod a+r /etc/squid/allow_hosts') os.system('chmod a+r /etc/squid/allow_dst') os.system('chmod a+r /etc/squid/allow_domains') allowDest = "" allowHost = "" allowDom = "vulaniblockdomainholder.vulani\n" blockDom = "vulaniblockdomainholder.vulani\n" for h in config.ProxyAllowedDomains: allowDom += "%s\n" % h for h in config.ProxyBlockedDomains: blockDom += "%s\n" % h for h in config.ProxyAllowedDestinations: allowDest += "%s\n" % h for h in config.ProxyAllowedHosts: allowHost += "%s\n" % h l = open(path + 'allow_dst', 'wt') l.write(allowDest) l.close() l = open(path + 'allow_hosts', 'wt') l.write(allowHost) l.close() l = open(path + 'allow_domains', 'wt') l.write(allowDom) l.close() l = open(path + 'denied_domains', 'wt') l.write(blockDom) l.close() adGroupAuth = "" adGroups = [] aclEntries = [ ] #Make sure we don't break the squid config by making reference to undefined acls keep a list of defined acls and only use them if they are in this list if config.ProxyConfig.get('adauth', None): if config.ProxyConfig.get( 'addom', None) and config.ProxyConfig.get( 'adldapuser', None) and config.ProxyConfig.get( 'adldappass', None): basedn = str.join(',', [ "dc=" + str(dfrag) for dfrag in config.ProxyConfig.get( 'addom', str).split('.') ]) adInfo = { 'basedn': basedn, 'ldapuser': config.ProxyConfig['adldapuser'], 'ldappass': config.ProxyConfig['adldappass'], 'adserver': config.ProxyConfig['adserver'] } authentication = "auth_param basic program /usr/lib/squid/ldap_auth -R -b \"%(basedn)s\" -D \"%(ldapuser)s\" -w \"%(ldappass)s\" -f sAMAccountName=%%s -h %(adserver)s -p389" % adInfo if config.ProxyConfig.get('adacls', None): adGroupPaths = [] for adacl in config.ProxyConfig.get('adacls', []): if '=' in adacl[1]: filter = "(memberof=cn=%%a,%s,%s)" % (adacl[1], basedn) if filter not in adGroupPaths: adGroupPaths.append(filter) adGroups.append( "acl vacl_%s external adACLGroup %s" % (adacl[2], adacl[0])) aclEntries.append(adacl[2]) else: print "Invalid AD Group path", adacl[1] if len(adGroupPaths) > 0: if len(adGroupPaths) > 1: adInfo["adGroupFilter"] = "(|%s)" % str.join( "", adGroupPaths) else: adInfo["adGroupFilter"] = adGroupPaths[0] authentication = authentication + "\nexternal_acl_type adACLGroup %%LOGIN /usr/lib/squid/squid_ldap_group -R -b \"%(basedn)s\" -D \"%(ldapuser)s\" -w \"%(ldappass)s\" -f \"(&%(adGroupFilter)s(objectclass=person)(sAMAccountName=%%v))\" -h %(adserver)s -p389" % adInfo else: authentication = "auth_param basic program /usr/lib/squid/msnt_auth" l = open(path + 'msntauth.conf', 'wt') l.write('server %s %s %s\n' % (config.ProxyConfig['adserver'], config.ProxyConfig['adserver'], config.ProxyConfig['addom'])) l.close() os.system('chmod a+r %smsntauth' % path) else: #authentication = "auth_param basic program /usr/libexec/squid/squid_ldap_auth -b "ou=People,%s,o=%s" -f (&(uid=%%s)(employeeType=squid)) localhost #""" % (','.join(["dc=%s"%(i,) for i in config.Domain.split('.')]), config.LDAPBase) authentication = "auth_param basic program /usr/libexec/squid/squid_ldap_auth -b \"o=%s\" -f " % config.LDAPBase # Muchos haxed ldap search authentication += "(&(|(mail=%%s@%s)(mail=%%s))(employeeType=squid)) localhost \n" % config.Domain if config.ProxyConfig.get('contentfilter', None): cfilter = "cache_peer 127.0.0.1 parent 8081 0 no-query login=*:nopassword\n" else: cfilter = "" timeAcls = "" # Do user ACLS here for usrs, aclname in config.ProxyConfig.get('aclusers', []): timeAcls += "acl vacl_%s proxy_auth %s\n" % (aclname, ' '.join( [i.strip() for i in usrs.split(',')])) aclEntries.append(aclname) # Do more destination ACL's here for doms, aclname in config.ProxyConfig.get('domacls', []): timeAcls += "acl vacl_%s dstdomain %s\n" % (aclname, ' '.join( [i.strip() for i in doms.split(',')])) aclEntries.append(aclname) srcacls = "" for i in config.ProxyConfig.get('srcacls', []): src, acl = i if not '/' in src: src_ip = "%s/32" % src else: src_ip = src srcacls += "acl vacl_%s src %s\n" % (acl, src_ip) aclEntries.append(acl) denys = "" allows = "" cnt = 0 if config.ProxyConfig.get('timedaccess', None): for action, days, times, domain, exacl in config.ProxyConfig[ 'timedaccess']: if exacl not in aclEntries: continue cnt += 1 timeAcls += "acl time_acl%s time %s %s\n" % (cnt, days, times) if domain: timeAcls += "acl domain_acl%s dstdomain %s\n" % (cnt, domain) if action: allows += "http_access allow all time_acl%s" % (cnt, ) else: allows += "http_access deny all time_acl%s" % (cnt, ) if domain: allows += " domain_acl%s" % (cnt) if exacl: allows += " vacl_%s" % exacl allows += "\n" bindaddr = "" if config.ProxyConfig.get('bindaddr'): bindaddr = "tcp_outgoing_address %s" % config.ProxyConfig.get( 'bindaddr') routingacls = "" for i in config.ProxyConfig.get('aclgateways', []): gateway, acl = i if acl in aclEntries: routingacls += "tcp_outgoing_address %s vacl_%s\n" % (gateway, acl) for acl, perm in config.ProxyConfig.get('aclperms', []): aclList = [] for e in acl.split(): if e in aclEntries: aclList.append('vacl_' + e) if aclList: if perm == "allow": allows += "http_access allow all %s\n" % str.join( ' ', aclList) else: allows += "http_access deny all %s\n" % str.join( ' ', aclList) # Configure our update accelerator updator = "" redirCache = "" redircacheallow = "" if config.ProxyConfig.get('updates', {}).get('enabled', None): # Allow redir hosts to bypass all Squid auth when we use a captive portal. Also point all to the rewriter if config.ProxyConfig.get('captive'): redirCache = "acl redir_hosts src \"/etc/squid/redir_hosts\"" redircacheallow = "http_access allow redir_hosts" rfi = open('/etc/squid/redir_hosts', 'wt') for iface, net in Utils.getLanNetworks(config).items(): rfi.write(net + '\n') rfi.close() updateConf = config.ProxyConfig['updates'] # Get config options and set some defaults diskspace = updateConf.get('maxspace', 95) speed = updateConf.get('maxspeed', 256) # accelerator.conf accelerator = """#Proxy Settings UPSTREAM_USER= UPSTREAM_PASSWORD= PROXY_PORT=8080 ENABLE_UPDXLRATOR=on UPSTREAM_PROXY= #Accelerator Settings AUTOCHECK_SCHEDULE=daily LOW_DOWNLOAD_PRIORITY=off ENABLE_AUTOCHECK=on PASSIVE_MODE=off FULL_AUTOSYNC=off ENABLE_LOG=on MAX_DISK_USAGE=%s NOT_ACCESSED_LAST=month1 CHILDREN=5 MAX_DOWNLOAD_RATE=%s GREEN_ADDRESS=127.0.0.1\n""" % (diskspace, speed) acc = open('/etc/squid/accelerator.conf', 'wt') acc.write(accelerator) acc.close() # meh os.system('chmod a+r /etc/squid/accelerator.conf') # squid.conf directives updator = "url_rewrite_program /usr/local/tcs/tums/bin/update_cache\n" updator += "url_rewrite_children 20\n" updator += "url_rewrite_access allow redir_cache\n" if config.ProxyConfig.get('captive'): updator += "url_rewrite_access allow redir_hosts\n" updator += "url_rewrite_access deny allow_hosts\n" updator += "url_rewrite_access deny allow_domain\n" updator += "url_rewrite_access deny allow_dst\n" if not config.ProxyConfig.get('captive'): updator += "url_rewrite_access deny all\n" #Allow for someone to specify alternative bound ports asside from the default 8080 #Some installations require explicit binding to port 3128, by no means does this mean #that it should be encouraged ... squidConf_bindPorts = "" if config.ProxyConfig.get('bindports'): bindPorts = str(config.ProxyConfig.get('bindports')) for port in bindPorts.replace(' ', '').split(','): if port == "8080": continue squidConf_bindPorts += "http_port %s transparent\n" % (port) squidconf = """http_port 8080 transparent %(bindPorts)s visible_hostname %(host)s hierarchy_stoplist cgi-bin ? .pl acl QUERY urlpath_regex cgi-bin \\? .pl .asp mail.%(domain)s no_cache deny QUERY cache_mem 32 MB maximum_object_size 1000000 KB cache_dir ufs /var/cache/squid/ 10000 16 256 cache_access_log /var/log/squid/access.log cache_log /var/log/squid/cache.log cache_store_log none pid_filename /var/run/squid.pid #ftp_user [email protected] ignore_expect_100 on hosts_file /etc/hosts %(auth)s auth_param basic children 5 auth_param basic realm Vulani Web Proxy auth_param basic credentialsttl 2 hours refresh_pattern ^ftp: 1440 20%% 10080 refresh_pattern ^gopher: 1440 0%% 1440 refresh_pattern . 0 20%% 4320 refresh_pattern windowsupdate.com/.*\\.(cab|exe) 4320 100%% 43200 reload-into-ims refresh_pattern download.microsoft.com/.*\\.(cab|exe) 4320 100%% 43200 reload-into-ims refresh_pattern akamai.net/.*\\.(cab|exe) 4320 100%% 43200 reload-into-ims strip_query_terms off #acl support.microsoft.com dstdomain support.microsoft.com #reply_header_access Accept-Encoding deny support.microsoft.com #request_header_access Accept-Encoding deny support.microsoft.com acl all src 0.0.0.0/0.0.0.0 acl manager proto cache_object acl localhost src 127.0.0.1/32 acl to_localhost dst 127.0.0.0/8 %(srcacls)s %(adAcls)s acl allow_hosts src "/etc/squid/allow_hosts" acl denied_domains dstdomain "/etc/squid/denied_domains" acl allow_domain dstdomain "/etc/squid/allow_domains" acl allow_dst dst "/etc/squid/allow_dst" acl redir_cache dstdomain .microsoft.com acl redir_cache dstdomain .windowsupdate.com acl redir_cache dstdomain .mirror.ac.za acl redir_cache dstdomain .debian.org acl redir_cache dstdomain .ubuntu.com acl redir_cache dstdomain .avg.com %(redircache)s %(timeacls)s acl password proxy_auth REQUIRED acl SSL_ports port 443 563 acl Safe_ports port 80 # http acl Safe_ports port 21 # ftp acl Safe_ports port 443 563 # https, snews acl Safe_ports port 70 # gopher acl Safe_ports port 210 # wais acl Safe_ports port 1025-65535 # unregistered ports acl Safe_ports port 280 # http-mgmt acl Safe_ports port 488 # gss-http acl Safe_ports port 591 # filemaker acl Safe_ports port 777 # multiling http acl Safe_ports port 901 # SWAT acl purge method PURGE acl CONNECT method CONNECT redirector_access deny localhost http_access allow manager localhost http_access deny manager http_access allow purge localhost http_access deny purge http_access deny !Safe_ports http_access deny CONNECT !SSL_ports http_access deny to_localhost http_access allow all localhost %(allows)s http_access deny denied_domains http_access allow allow_domain http_access allow allow_dst %(denys)s http_access allow allow_hosts %(redircacheallow)s %(passwordAuth)s http_access deny all http_reply_access allow all icp_access allow all cache_mgr postmaster@%(domain)s logfile_rotate 7 append_domain .%(domain)s forwarded_for on cachemgr_passwd %(ldappass)s shutdown cachemgr_passwd %(ldappass)s info stats/objects cachemgr_passwd disable all snmp_access allow localhost coredump_dir /var/log/squid extension_methods REPORT MERGE MKACTIVITY CHECKOUT acl snmpcommunity snmp_community public snmp_port 3401 snmp_access allow snmpcommunity localhost snmp_access deny all\n%(updator)s\n%(bindaddr)s\n%(cfilter)s\n%(routingacls)s""" % { 'redircache': redirCache, 'host': config.Hostname + "." + config.Domain, 'bindPorts': squidConf_bindPorts, 'domain': config.Domain, 'auth': authentication, 'ldappass': config.LDAPPassword, 'timeacls': timeAcls, 'allows': allows, 'denys': denys, 'redircacheallow': redircacheallow, 'updator': updator, 'bindaddr': bindaddr, 'cfilter': cfilter, 'routingacls': routingacls, 'srcacls': srcacls, 'adAcls': str.join('\n', adGroups), 'passwordAuth': len(adGroups) > 0 and config.ProxyConfig.get('adGroupDefaultDeny', False) and ' ' or 'http_access allow all password' } # Apply debian fixes squidconf = squidconf.replace('/usr/libexec/squid/squid_ldap_auth', '/usr/lib/squid/ldap_auth') #squidconf = squidconf.replace('/etc/squid/', '/etc/squid/') os.system('mkdir -p /var/cache/squid > /dev/null 2>&1') os.system('mkdir -p /var/log/squid > /dev/null 2>&1') os.system('chown proxy:proxy /var/cache/squid') os.system('touch /var/log/tums_cache.log') os.system('chown proxy:proxy /var/log/tums_cache.log') os.system('chmod a+rwx /var/log/tums_cache.log') os.system('chown -R proxy:proxy /var/log/squid') os.system('rm -r /var/log/squid3 > /dev/null 2>&1') l = open(path + 'squid.conf', 'wt') l.write(squidconf) l.close() # Configure WPAD script for each LAN range. for ip in Utils.getLanIPs(config): pacfile = """function FindProxyForURL(url, host) { if (shExpMatch(url, "http:*")) return "PROXY %(proxyUrl)s:8080"; if (shExpMatch(url, "https:*")) return "PROXY %(proxyUrl)s:8080"; if (shExpMatch(url, "ftp:*")) return "PROXY %(proxyUrl)s:8080"; return "DIRECT"; }\n""" % { 'proxyUrl': ip } fp = open( '/var/www/localhost/htdocs/wpad-%s.pac' % ip.replace('.', '-'), 'wt') fp.write(pacfile) fp.close() try: default = Utils.getLanIPs(config)[0] os.system( 'cp /var/www/localhost/htdocs/wpad-%s.pac /var/www/localhost/htdocs/wpad.dat' % default.replace('.', '-')) except: pass
def sendLDAP(self, name): os.system('/etc/init.d/slapd stop') os.system('slapcat > /tmp/ldap_tree') # Reconfigre LDAP now for slave replication # Start LDAP back up os.system('/etc/init.d/slapd start') # Send our ldap tree to the remote server os.system('scp /tmp/ldap_tree root@%s:/tmp/' % name) os.system('ssh root@%s /etc/init.d/slapd stop') os.system('ssh root@%s rm /var/lib/ldap/*' % name) os.system('ssh root@%s slapadd < /tmp/ldap_tree' % name) os.system('ssh root@%s chown -R openldap:openldap /var/lib/ldap' % name) 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/thusa.schema include /etc/ldap/schema/samba.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 sizelimit 500 tool-threads 1 defaultsearchbase "o=%(base)s" backend bdb #checkpoint 512 30 database bdb suffix "o=%(base)s" rootdn "cn=Manager,o=%(base)s" rootpw %(pass)s directory "/var/lib/ldap" # Replication updatedn cn=Manager,o=%(base)s updateref ldap://%(master)s 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 index dc eq index objectClass eq index sn eq index cn eq index uid eq index uniqueMember,memberUid pres,eq index accountStatus,mail pres,eq index associatedDomain pres,eq index sOARecord,aRecord pres,eq\n""" % { 'base': config.LDAPBase, 'pass': config.LDAPPassword, 'master': Utils.getLanIPs(config)[0] } l = open('/tmp/slaveLdapConf', 'wt') l.write(conf) l.close() os.system('scp /tmp/slaveLdapConf root@%s:/etc/ldap/slapd.conf' % name) # Start up LDAP os.system('ssh root@%s /etc/init.d/slapd restart' % name) os.system('ssh root@%s /etc/init.d/heartbeat restart' % name)
def writeConfig(self, *a): lans = Utils.getLanNetworks(config) extramain = config.DHCP.get('main','') ips = Utils.getLanIPs(config) myIp = ips[0] rev = '.'.join([i for i in reversed(myIp.split('.')[:3])]) ifaces = [] dhcpconf = """# DHCPD config generated by TUMS Configurator ddns-update-style interim; default-lease-time 21600; max-lease-time 21600; allow booting; allow bootp; authoritative; log-facility local7; zone %(domain)s. { primary 127.0.0.1; } zone %(rev)s.in-addr.arpa. { primary 127.0.0.1; } option local-pac-server code 252 = text; %(extramain)s """ % { 'extramain': extramain, 'domain': config.Domain, 'rev': rev } n = 0 for k,v in lans.items(): myNet = v myIp = config.EthernetDevices[k].get('ip', '/').split('/')[0] dhcpConf = config.DHCP.get(k, {}) if not myIp: # No IP set for this interface (is DHCP itself) continue if not config.EthernetDevices[k].get('dhcpserver'): # Not set to do DHCP continue ifaces.append(k) statics = "" for ip, hostmac in config.DHCP.get('leases',{}).items(): if Utils.matchIP(myNet, ip): # make sure the IP is in this network host, mac = hostmac statics += """ host %s { fixed-address %s; hardware ethernet %s; }\n""" % (host, ip, mac) myNetmask = Utils.cidr2netmask(myNet.split('/')[1]) rangeStart = dhcpConf.get('rangeStart', "100") rangeEnd = dhcpConf.get('rangeEnd', "240") netmask = dhcpConf.get('netmask', myNetmask) netbios = dhcpConf.get('netbios', myIp) nameserver = dhcpConf.get('nameserver', myIp) router = dhcpConf.get('gateway', myIp) myNet = dhcpConf.get('network', Utils.getNetwork(config.EthernetDevices[k]['ip'])) domain = dhcpConf.get('domain', config.Domain) if not '/' in myNet: # AAAAAAAAAAAARGH GOD DAMN DIE IN HELL PAUL VIXIE cdr = Utils.netmask2cidr(netmask) myNet = "%s/%s" % (myNet, cdr) bcast = Utils.getBroadcast(myNet) else: bcast = Utils.getBroadcast(myNet) # allow custom configuration options custom = dhcpConf.get('custom', '') netL = '.'.join(myNet.split('.')[:3]) if not ("." in rangeStart): rangeStart = "%s.%s" % (netL, rangeStart) rangeEnd = "%s.%s" % (netL, rangeEnd) defn = { 'netname': 'DHCP%s' % k.upper(), 'myIp': myIp, 'pacIp': myIp.replace('.', '-'), 'domain': domain, 'network': netL, 'networkF': myNet.split('/')[0], 'static': statics, 'custom': custom, 'netmask': netmask, 'rangeStart': rangeStart, 'rangeEnd': rangeEnd, 'myNetbios': netbios, 'myDns': nameserver, 'myRouter': router, 'extramain': extramain, 'bcast': bcast } dhcpnet = """ shared-network %(netname)s { use-host-decl-names on; option domain-name "%(domain)s"; option domain-name-servers %(myDns)s; option netbios-name-servers %(myNetbios)s; option netbios-node-type 8; option local-pac-server "http://%(myIp)s/wpad-%(pacIp)s.pac"; option ntp-servers %(myIp)s; option time-servers %(myIp)s; option log-servers %(myIp)s; option font-servers %(myIp)s; option pop-server %(myIp)s; option smtp-server %(myIp)s; option x-display-manager %(myIp)s; subnet %(networkF)s netmask %(netmask)s { range dynamic-bootp %(rangeStart)s %(rangeEnd)s; option subnet-mask %(netmask)s; option broadcast-address %(bcast)s; option routers %(myRouter)s; } %(static)s %(custom)s }\n""" % defn dhcpconf += dhcpnet # Check for debianism (goes in /etc/dhcp3) f = open('/etc/dhcp3/dhcpd.conf', 'wt') f.write(dhcpconf) f.close() f = open('/etc/default/dhcp3-server', 'wt') f.write('# On what interfaces should the DHCP server (dhcpd) serve DHCP requests?\n') f.write('# Separate multiple interfaces with spaces, e.g. "eth0 eth1".\n') f.write('INTERFACES="%s"\n' % ' '.join(ifaces)) f.close()