def doGrubCfg(startconf, group, kopts): grubcfg = constants.LINBOGRUBDIR + '/' + group + '.cfg' rc, content = readTextfile(grubcfg) if rc == True and not constants.MANAGEDSTR in content: printScript(' > Keeping pxe configuration.') return True # get grub partition name of cache cache = getStartconfOption(startconf, 'LINBO', 'Cache') partnr = getStartconfPartnr(startconf, cache) systemtype = getStartconfOption(startconf, 'LINBO', 'SystemType') cacheroot = getGrubPart(cache, systemtype) cachelabel = getStartconfPartlabel(startconf, partnr) # if cache is not defined provide a forced netboot cfg if cacheroot == None: netboottpl = constants.LINBOTPLDIR + '/grub.cfg.forced_netboot' printScript(' > Creating minimal pxe configuration. start.conf is incomplete!') rc = os.system('cp ' + netboottpl + ' ' + grubcfg) return else: printScript(' > Creating pxe configuration.') # create gobal part for group cfg globaltpl = constants.LINBOTPLDIR + '/grub.cfg.global' rc, content = readTextfile(globaltpl) if rc == False: return rc replace_list = [('@@group@@', group), ('@@cachelabel@@', cachelabel), ('@@cacheroot@@', cacheroot), ('@@kopts@@', kopts)] for item in replace_list: content = content.replace(item[0], item[1]) rc = writeTextfile(grubcfg, content, 'w') # get os infos from group's start.conf oslists = getStartconfOsValues(startconf) if oslists == None: return False # write os parts to grub cfg ostpl = constants.LINBOTPLDIR + '/grub.cfg.os' for oslist in oslists: osname, partition, kernel, initrd, kappend, osnr = oslist osroot = getGrubPart(partition, systemtype) ostype = getGrubOstype(osname) partnr = getStartconfPartnr(startconf, partition) oslabel = getStartconfPartlabel(startconf, partnr) rc, content = readTextfile(ostpl) if rc == False: return rc replace_list = [('@@group@@', group), ('@@cachelabel@@', cachelabel), ('@@cacheroot@@', cacheroot), ('@@osname@@', osname), ('@@osnr@@', osnr), ('@@ostype@@', ostype), ('@@oslabel@@', oslabel), ('@@osroot@@', osroot), ('@@partnr@@', partnr), ('@@kernel@@', kernel), ('@@initrd@@', initrd), ('@@kopts@@', kopts), ('@@append@@', kappend)] for item in replace_list: content = content.replace(item[0], item[1]) rc = writeTextfile(grubcfg, content, 'a') if rc == False: return rc
printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # fixing resolv.conf msg = 'Fixing resolv.conf ' printScript(msg, '', False, False, True) try: resconf = '/etc/resolv.conf' now = str(datetime.datetime.now()).split('.')[0] header = '# created by linuxmuster-setup ' + now + '\n' search = 'search ' + domainname + '\n' ns1 = 'nameserver ' + serverip + '\n' ns2 = 'nameserver ' + firewallip filedata = header + search + ns1 + ns2 os.unlink(resconf) rc = writeTextfile(resconf, filedata, 'w') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # exchange smb.conf msg = 'Exchanging smb.conf ' printScript(msg, '', False, False, True) try: os.system('mv ' + smbconf + ' ' + smbconf + '.orig') os.system('mv ' + smbconf + '.setup ' + smbconf) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)
def main(): # helper files for mailserver setup msg = '* Creating helper files ' printScript(msg, '', False, False, True) try: # add binduser password to setup.ini rc, content = readTextfile(setupini) content = content + 'binduserpw = ' + binduserpw rc = writeTextfile(setuptmp, content, 'w') # create setup helper script content = '#!/bin/bash\nmkdir -p ' + constants.SSLDIR content = content + '\nmv /tmp/*.pem ' + constants.SSLDIR content = content + '\nchmod 640 ' + constants.SSLDIR + '/*.key.pem' content = content + '\nln -sf ' + constants.SSLDIR + '/cacert.pem /etc/ssl/certs/cacert.pem' content = content + '\napt-get update\napt-get -y install linuxmuster-mail' content = content + '\nlinuxmuster-mail.py -c ' + setuptmp content = content + '\nsystemctl start linuxmuster-mail.service' rc = writeTextfile(setuphelper, content, 'w') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # open ssh connection if mailip != serverip: msg = '* Establishing ssh connection to mailserver ' printScript(msg, '', False, False, True) ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(mailip, 22, 'root', adminpw) try: ftp = ssh.open_sftp() printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # uploading data & certs msg = '* Uploading files to mailserver ' printScript(msg, '', False, False, True) for item in [setuptmp, setuphelper, mailcert, mailkey]: if not ftp.put(item, '/tmp/' + os.path.basename(item)): printScript(' ' + os.path.basename(item) + ' failed!', '', True, True, False, len(msg)) sys.exit(1) ftp.chmod(setuphelper, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP) printScript(' Success!', '', True, True, False, len(msg)) # start mailserver setup per ssh msg = '* Starting mailserver setup ' printScript(msg, '', False, False, True) try: stdin, stdout, stderr = ssh.exec_command(setuphelper) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # close ssh connection ftp.close() ssh.close() # local mailserver setup else: msg = '* Starting mailserver setup ' printScript(msg, '', False, False, True) try: subProc('apt update && apt -y install linuxmuster-mail', logfile) subProc('linuxmuster-mail.py -s -c ' + setuptmp, logfile) subProc('systemctl start linuxmuster-mail.service', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) os.unlink(setuptmp) # add mail dns entry msg = '* Creating dns entry ' printScript(msg, '', False, False, True) try: sambaTool('dns add localhost ' + domainname + ' mail A ' + mailip) sambaTool('dns add localhost ' + domainname + ' mail MX "' + mailip + ' 10"') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)
def main(): # helper files for opsiserver setup msg = '* Creating helper files ' printScript(msg, '', False, False, True) try: # create settings file for opsi setup rc, content = readTextfile(setupini) content = content.replace('[setup]\n', '') content = content.replace('\n\n', '\n') content = content.replace(' = ', '="') content = content.replace('\n', '"\n') content = content + '\nadmin="Administrator"' rc = writeTextfile(setuptmp, content, 'w') # create setup helper script content = '#!/bin/bash\nmkdir -p ' + constants.SSLDIR content = content + '\nmv /tmp/*.pem ' + constants.SSLDIR content = content + '\nchmod 640 ' + constants.SSLDIR + '/*.key.pem' content = content + '\nln -sf ' + constants.SSLDIR + '/cacert.pem /etc/ssl/certs/cacert.pem' content = content + '\nmv /tmp/settings ' + constants.OPSILMNDIR content = content + '\n' + constants.OPSISETUP + ' --first | tee /tmp/linuxmuster-opsi.log\n' rc = writeTextfile(setuphelper, content, 'w') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # open ssh connection msg = '* Establishing ssh connection to opsiserver ' printScript(msg, '', False, False, True) ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(opsiip, 22, 'root', adminpw) try: ftp = ssh.open_sftp() printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # uploading data & certs msg = '* Uploading files to opsiserver ' printScript(msg, '', False, False, True) for item in [setuptmp, setuphelper, opsicert, opsikey]: if not ftp.put(item, '/tmp/' + os.path.basename(item)): printScript(' ' + os.path.basename(item) + ' failed!', '', True, True, False, len(msg)) sys.exit(1) ftp.chmod(setuphelper, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP) ftp.close() ssh.close() printScript(' Success!', '', True, True, False, len(msg)) # start opsiserver setup per ssh msg = '* Starting opsiserver setup ' printScript(msg, '', False, False, True) try: sshcmd = 'ssh -oNumberOfPasswordPrompts=0 -oStrictHostKeyChecking=no -p 22 ' + opsiip setupcmd = sshcmd + ' ' + setuphelper subProc(setupcmd, logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # close ssh connection os.unlink(setuptmp)
def main(): # get setup various values serverip = setup.get('setup', 'serverip') bitmask = setup.get('setup', 'bitmask') firewallip = setup.get('setup', 'firewallip') servername = setup.get('setup', 'servername') domainname = setup.get('setup', 'domainname') basedn = setup.get('setup', 'basedn') opsiip = setup.get('setup', 'opsiip') dockerip = setup.get('setup', 'dockerip') network = setup.get('setup', 'network') adminpw = setup.get('setup', 'adminpw') # get timezone rc, timezone = readTextfile('/etc/timezone') timezone = timezone.replace('\n', '') # get binduser password rc, binduserpw = readTextfile(constants.BINDUSERSECRET) # firewall config files now = datetime.datetime.now().strftime('%Y%m%d%H%M%S') fwconftmp = constants.FWCONFLOCAL fwconfbak = fwconftmp.replace('.xml', '-' + now + '.xml') fwconftpl = constants.FWOSCONFTPL # dummy ip addresses if not isValidHostIpv4(opsiip): opsiip = serverip.split('.')[0] + '.' + serverip.split( '.')[1] + '.' + serverip.split('.')[2] + '.2' if not isValidHostIpv4(dockerip): dockerip = serverip.split('.')[0] + '.' + serverip.split( '.')[1] + '.' + serverip.split('.')[2] + '.3' # get current config rc = getFwConfig(firewallip, constants.ROOTPW) if not rc: sys.exit(1) # backup config msg = '* Backing up ' printScript(msg, '', False, False, True) try: shutil.copy(fwconftmp, fwconfbak) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # get root password hash msg = '* Reading current config ' printScript(msg, '', False, False, True) try: rc, content = readTextfile(fwconftmp) soup = BeautifulSoup(content, 'lxml') # save interface configuration wanconfig = str(soup.findAll('wan')[0]) lanconfig = str(soup.findAll('lan')[0]) # save gateway configuration try: gwconfig = str(soup.findAll('gateways')[0]) except: gwconfig = '' # save dnsserver configuration try: dnsconfig = str(soup.findAll('dnsserver')[0]) except: dnsconfig = '' # save opt1 configuration if present try: opt1config = str(soup.findAll('opt1')[0]) except: opt1config = '' printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # get base64 encoded certs msg = '* Reading certificates & ssh key ' printScript(msg, '', False, False, True) try: rc, cacertb64 = readTextfile(constants.CACERTB64) rc, fwcertb64 = readTextfile(constants.SSLDIR + '/firewall.cert.pem.b64') rc, fwkeyb64 = readTextfile(constants.SSLDIR + '/firewall.key.pem.b64') rc, authorizedkey = readTextfile(constants.SSHPUBKEYB64) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # create new firewall configuration msg = '* Creating xml configuration file ' printScript(msg, '', False, False, True) try: # create password hash for new firewall password hashedpw = bcrypt.hashpw(str.encode(adminpw), bcrypt.gensalt(10)) fwrootpw_hashed = hashedpw.decode() apikey = randomPassword(80) apisecret = randomPassword(80) hashedpw = bcrypt.hashpw(str.encode(apisecret), bcrypt.gensalt(10)) apisecret_hashed = hashedpw.decode() # read template rc, content = readTextfile(fwconftpl) # replace placeholders with values content = content.replace('@@servername@@', servername) content = content.replace('@@domainname@@', domainname) content = content.replace('@@basedn@@', basedn) content = content.replace('@@wanconfig@@', wanconfig) content = content.replace('@@dnsconfig@@', dnsconfig) content = content.replace('@@gwconfig@@', gwconfig) content = content.replace('@@lanconfig@@', lanconfig) content = content.replace('@@opt1config@@', opt1config) content = content.replace('@@serverip@@', serverip) content = content.replace('@@firewallip@@', firewallip) content = content.replace('@@network@@', network) content = content.replace('@@bitmask@@', bitmask) content = content.replace('@@opsiip@@', opsiip) content = content.replace('@@dockerip@@', dockerip) content = content.replace('@@fwrootpw_hashed@@', fwrootpw_hashed) content = content.replace('@@authorizedkey@@', authorizedkey) content = content.replace('@@apikey@@', apikey) content = content.replace('@@apisecret_hashed@@', apisecret_hashed) content = content.replace('@@binduserpw@@', binduserpw) content = content.replace('@@timezone@@', timezone) content = content.replace('@@cacertb64@@', cacertb64) content = content.replace('@@fwcertb64@@', fwcertb64) content = content.replace('@@fwkeyb64@@', fwkeyb64) # write new configfile rc = writeTextfile(fwconftmp, content, 'w') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # create api credentials ini file msg = '* Saving api credentials ' printScript(msg, '', False, False, True) try: rc = modIni(constants.FWAPIKEYS, 'api', 'key', apikey) rc = modIni(constants.FWAPIKEYS, 'api', 'secret', apisecret) os.system('chmod 400 ' + constants.FWAPIKEYS) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # upload new configfile rc = putFwConfig(firewallip, constants.ROOTPW) if not rc: sys.exit(1) # remove temporary files #os.unlink(fwconftmp) # reboot firewall rc = sshExec(firewallip, 'configctl firmware reboot', adminpw) if not rc: sys.exit(1)
except Exception as error: printScript(error, '', True, True, False, len(msg)) sys.exit(1) # create dns-admin account msg = 'Creating samba account for dns-admin ' printScript(msg, '', False, False, True) try: dnspw = randomPassword(16) desc = 'Unprivileged user for DNS updates via DHCP server' sambaTool( 'user create dns-admin ' + dnspw + ' --description="' + desc + '"', logfile) sambaTool('user setexpiry dns-admin --noexpiry', logfile) sambaTool('group addmembers DnsAdmins dns-admin', logfile) rc, writeTextfile(constants.DNSADMINSECRET, dnspw, 'w') os.system('chgrp dhcpd ' + constants.DNSADMINSECRET) os.system('chmod 440 ' + constants.DNSADMINSECRET) printScript(' Success!', '', True, True, False, len(msg)) except Exception as error: printScript(error, '', True, True, False, len(msg)) sys.exit(1) # add firewall as dns forwarder # smb.conf msg = 'Add firewall as dns forwarder ' printScript(msg, '', False, False, True) try: modIni('/etc/samba/smb.conf', 'global', 'dns forwarder', firewallip) subProc('echo "nameserver ' + firewallip + '" >> /etc/resolv.conf', logfile)
def main(): # get setup various values serverip = setup.get('setup', 'serverip') bitmask = setup.get('setup', 'bitmask') firewallip = setup.get('setup', 'firewallip') servername = setup.get('setup', 'servername') domainname = setup.get('setup', 'domainname') basedn = setup.get('setup', 'basedn') opsiip = setup.get('setup', 'opsiip') dockerip = setup.get('setup', 'dockerip') network = setup.get('setup', 'network') adminpw = setup.get('setup', 'adminpw') # get timezone rc, timezone = readTextfile('/etc/timezone') timezone = timezone.replace('\n', '') # get binduser password rc, binduserpw = readTextfile(constants.BINDUSERSECRET) # firewall config files now = datetime.datetime.now().strftime('%Y%m%d%H%M%S') fwconftmp = constants.FWCONFLOCAL fwconfbak = fwconftmp.replace('.xml', '-' + now + '.xml') fwconftpl = constants.FWOSCONFTPL # dummy ip addresses if not isValidHostIpv4(opsiip): opsiip = serverip.split('.')[0] + '.' + serverip.split( '.')[1] + '.' + serverip.split('.')[2] + '.2' if not isValidHostIpv4(dockerip): dockerip = serverip.split('.')[0] + '.' + serverip.split( '.')[1] + '.' + serverip.split('.')[2] + '.3' # get current config rc = getFwConfig(firewallip, constants.ROOTPW) if not rc: sys.exit(1) # backup config msg = '* Backing up ' printScript(msg, '', False, False, True) try: shutil.copy(fwconftmp, fwconfbak) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # get root password hash msg = '* Reading current config ' printScript(msg, '', False, False, True) try: rc, content = readTextfile(fwconftmp) soup = BeautifulSoup(content, 'lxml') # save certain configuration values for later use sysctl = str(soup.findAll('sysctl')[0]) # get already configured interfaces for item in soup.findAll('interfaces'): if '<lan>' in str(item): interfaces = str(item) # save language information try: language = str(soup.findAll('language')[0]) except: language = '' # second try get language from locale settings if language == '': try: lang = os.environ['LANG'].split('.')[0] except: lang = 'en_US' language = '<language>' + lang + '</language>' # save gateway configuration try: gwconfig = str(soup.findAll('gateways')[0]) gwconfig = gwconfig.replace('<gateways>', '').replace('</gateways>', '') except: gwconfig = '' # save dnsserver configuration try: dnsconfig = str(soup.findAll('dnsserver')[0]) except: dnsconfig = '' # add server as dnsserver dnsserver = '<dnsserver>' + serverip + '</dnsserver>' if dnsconfig == '': dnsconfig = dnsserver else: dnsconfig = dnsserver + '\n ' + dnsconfig # save opt1 configuration if present try: opt1config = str(soup.findAll('opt1')[0]) except: opt1config = '' printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # get base64 encoded certs msg = '* Reading certificates & ssh key ' printScript(msg, '', False, False, True) try: rc, cacertb64 = readTextfile(constants.CACERTB64) rc, fwcertb64 = readTextfile(constants.SSLDIR + '/firewall.cert.pem.b64') rc, fwkeyb64 = readTextfile(constants.SSLDIR + '/firewall.key.pem.b64') rc, authorizedkey = readTextfile(constants.SSHPUBKEYB64) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # create list of first ten network ips for aliascontent (NoProxy group in firewall) aliascontent = '' netpre = network.split('.')[0] + '.' + network.split( '.')[1] + '.' + network.split('.')[2] + '.' c = 0 max = 10 while c < max: c = c + 1 aliasip = netpre + str(c) if aliascontent == '': aliascontent = aliasip else: aliascontent = aliascontent + ' ' + aliasip # add server ips if not already collected for aliasip in [serverip, opsiip, dockerip]: if not aliasip in aliascontent: aliascontent = aliascontent + '\n' + aliasip # create new firewall configuration msg = '* Creating xml configuration file ' printScript(msg, '', False, False, True) try: # create password hash for new firewall password hashedpw = bcrypt.hashpw(str.encode(adminpw), bcrypt.gensalt(10)) fwrootpw_hashed = hashedpw.decode() apikey = randomPassword(80) apisecret = randomPassword(80) hashedpw = bcrypt.hashpw(str.encode(apisecret), bcrypt.gensalt(10)) apisecret_hashed = hashedpw.decode() # read template rc, content = readTextfile(fwconftpl) # replace placeholders with values content = content.replace('@@sysctl@@', sysctl) content = content.replace('@@servername@@', servername) content = content.replace('@@domainname@@', domainname) content = content.replace('@@basedn@@', basedn) content = content.replace('@@interfaces@@', interfaces) content = content.replace('@@dnsconfig@@', dnsconfig) content = content.replace('@@gwconfig@@', gwconfig) content = content.replace('@@serverip@@', serverip) content = content.replace('@@dockerip@@', dockerip) content = content.replace('@@firewallip@@', firewallip) content = content.replace('@@network@@', network) content = content.replace('@@bitmask@@', bitmask) content = content.replace('@@aliascontent@@', aliascontent) content = content.replace('@@gw_lan@@', constants.GW_LAN) content = content.replace('@@fwrootpw_hashed@@', fwrootpw_hashed) content = content.replace('@@authorizedkey@@', authorizedkey) content = content.replace('@@apikey@@', apikey) content = content.replace('@@apisecret_hashed@@', apisecret_hashed) content = content.replace('@@binduserpw@@', binduserpw) content = content.replace('@@language@@', language) content = content.replace('@@timezone@@', timezone) content = content.replace('@@cacertb64@@', cacertb64) content = content.replace('@@fwcertb64@@', fwcertb64) content = content.replace('@@fwkeyb64@@', fwkeyb64) # write new configfile rc = writeTextfile(fwconftmp, content, 'w') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # create api credentials ini file msg = '* Saving api credentials ' printScript(msg, '', False, False, True) try: rc = modIni(constants.FWAPIKEYS, 'api', 'key', apikey) rc = modIni(constants.FWAPIKEYS, 'api', 'secret', apisecret) os.system('chmod 400 ' + constants.FWAPIKEYS) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # upload new configfile rc = putFwConfig(firewallip, constants.ROOTPW) if not rc: sys.exit(1) # remove temporary files #os.unlink(fwconftmp) # reboot firewall rc = sshExec(firewallip, 'configctl firmware reboot', adminpw) if not rc: sys.exit(1)
sys.exit(1) # set serverip in default start.conf msg = 'Providing server ip to linbo start.conf files ' # default start.conf conffiles = [constants.LINBODIR + '/start.conf'] # collect example start.conf files for item in os.listdir(constants.LINBODIR + '/examples'): if not item.startswith('start.conf.'): continue conffiles.append(constants.LINBODIR + '/examples/' + item) printScript(msg, '', False, False, True) try: for startconf in conffiles: rc, content = readTextfile(startconf) rc = writeTextfile(startconf, content.replace('10.16.1.1', serverip), 'w') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # bittorrent service msg = 'Activating bittorrent tracker ' printScript(msg, '', False, False, True) try: defaultconf = '/etc/default/bittorrent' rc, content = readTextfile(defaultconf) content = re.sub(r'\nSTART_BTTRACK=.*\n', '\nSTART_BTTRACK=1\n', content, re.IGNORECASE) content = re.sub(r'\n[#]*ALLOWED_DIR=.*\n', '\nALLOWED_DIR=' + constants.LINBODIR + '\n', content,
# docker if isValidHostIpv4(dockerip): device_array.append(('docker', dockerip)) # iterate printScript('Creating device entries for:') for item in device_array: hostname = item[0] ip = item[1] msg = '* ' + hostname + ' ' printScript(msg, '', False, False, True) # get mac address if ip == serverip: h = iter(hex(getnode())[2:].zfill(12)) mac = ":".join(i + next(h) for i in h) else: mac = getMacFromArp(ip) if mac == '': mac = getRandomMac(devices) # create devices.csv entry devices = addServerDevice(hostname, mac, ip, devices) if rc == False: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) else: printScript(' ' + ip + ' ' + mac, '', True, True, False, len(msg)) # finally write devices.csv if not writeTextfile(constants.WIMPORTDATA, devices, 'w'): sys.exit(1)
try: subProc('systemctl restart apparmor.service', logfile) printScript(' Success!', '', True, True, False, len(msg)) except Exception as error: printScript(error, '', True, True, False, len(msg)) sys.exit(1) # write schoolname to sophomorix school.conf msg = 'Writing school name to school.conf ' printScript(msg, '', False, False, True) try: schoolname = getSetupValue('schoolname') rc, content = readTextfile(constants.SCHOOLCONF) # need to use regex because sophomorix config files do not do not comply with the ini file standard content = re.sub(r'SCHOOL_LONGNAME=.*\n', 'SCHOOL_LONGNAME=' + schoolname + '\n', content) rc = writeTextfile(constants.SCHOOLCONF, content, 'w') printScript(' Success!', '', True, True, False, len(msg)) except Exception as error: printScript(error, '', True, True, False, len(msg)) sys.exit(1) # import devices msg = 'Starting device import ' printScript(msg, '', False, False, True) try: subProc('linuxmuster-import-devices', logfile) printScript(' Success!', '', True, True, False, len(msg)) except Exception as error: printScript(error, '', True, True, False, len(msg)) sys.exit(1)
def main(): # get various setup values msg = 'Reading setup data ' printScript(msg, '', False, False, True) try: serverip = getSetupValue('serverip') bitmask = getSetupValue('bitmask') firewallip = getSetupValue('firewallip') servername = getSetupValue('servername') domainname = getSetupValue('domainname') basedn = getSetupValue('basedn') opsiip = getSetupValue('opsiip') dockerip = getSetupValue('dockerip') network = getSetupValue('network') adminpw = getSetupValue('adminpw') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # get timezone rc, timezone = readTextfile('/etc/timezone') timezone = timezone.replace('\n', '') # get binduser password rc, binduserpw = readTextfile(constants.BINDUSERSECRET) # get firewall root password provided by linuxmuster-opnsense-reset pwfile = '/tmp/linuxmuster-opnsense-reset' if os.path.isfile(pwfile): # firewall reset after setup, given password is current password rc, rolloutpw = readTextfile(pwfile) productionpw = rolloutpw os.unlink(pwfile) else: # initial setup, rollout root password is standardized rolloutpw = constants.ROOTPW # new root production password provided by setup productionpw = adminpw # create and save radius secret msg = 'Calculating radius secret ' printScript(msg, '', False, False, True) try: radiussecret = randomPassword(16) with open(constants.RADIUSSECRET, 'w') as secret: secret.write(radiussecret) subProc('chmod 400 ' + constants.RADIUSSECRET, logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # firewall config files now = datetime.datetime.now().strftime('%Y%m%d%H%M%S') fwconftmp = constants.FWCONFLOCAL fwconfbak = fwconftmp.replace('.xml', '-' + now + '.xml') fwconftpl = constants.FWOSCONFTPL # dummy ip addresses if not isValidHostIpv4(opsiip): opsiip = serverip.split('.')[0] + '.' + serverip.split('.')[1] + '.' + serverip.split('.')[2] + '.2' if not isValidHostIpv4(dockerip): dockerip = serverip.split('.')[0] + '.' + serverip.split('.')[1] + '.' + serverip.split('.')[2] + '.3' # get current config rc = getFwConfig(firewallip, rolloutpw) if not rc: sys.exit(1) # backup config msg = '* Backing up ' printScript(msg, '', False, False, True) try: shutil.copy(fwconftmp, fwconfbak) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # get root password hash msg = '* Reading current config ' printScript(msg, '', False, False, True) try: rc, content = readTextfile(fwconftmp) soup = BeautifulSoup(content, 'lxml') # save certain configuration values for later use sysctl = str(soup.findAll('sysctl')[0]) # get already configured interfaces for item in soup.findAll('interfaces'): if '<lan>' in str(item): interfaces = str(item) # save language information try: language = str(soup.findAll('language')[0]) except: language = '' # second try get language from locale settings if language == '': try: lang = os.environ['LANG'].split('.')[0] except: lang = 'en_US' language = '<language>' + lang + '</language>' # save gateway configuration try: gwconfig = str(soup.findAll('gateways')[0]) gwconfig = gwconfig.replace('<gateways>', '').replace('</gateways>', '') except: gwconfig = '' # save dnsserver configuration try: dnsconfig = str(soup.findAll('dnsserver')[0]) except: dnsconfig = '' # add server as dnsserver dnsserver = '<dnsserver>' + serverip + '</dnsserver>' if dnsconfig == '': dnsconfig = dnsserver else: dnsconfig = dnsserver + '\n ' + dnsconfig # save opt1 configuration if present try: opt1config = str(soup.findAll('opt1')[0]) except: opt1config = '' printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # get base64 encoded certs msg = '* Reading certificates & ssh key ' printScript(msg, '', False, False, True) try: rc, cacertb64 = readTextfile(constants.CACERTB64) rc, fwcertb64 = readTextfile(constants.SSLDIR + '/firewall.cert.pem.b64') rc, fwkeyb64 = readTextfile(constants.SSLDIR + '/firewall.key.pem.b64') rc, authorizedkey = readTextfile(constants.SSHPUBKEYB64) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # create list of first ten network ips for aliascontent (NoProxy group in firewall) aliascontent = '' netpre = network.split('.')[0] + '.' + network.split('.')[1] + '.' + network.split('.')[2] + '.' c = 0 max = 10 while c < max: c = c + 1 aliasip = netpre + str(c) if aliascontent == '': aliascontent = aliasip else: aliascontent = aliascontent + ' ' + aliasip # add server ips if not already collected for aliasip in [serverip, opsiip, dockerip]: if not aliasip in aliascontent: aliascontent = aliascontent + '\n' + aliasip # create new firewall configuration msg = '* Creating xml configuration file ' printScript(msg, '', False, False, True) try: # create password hash for new firewall password hashedpw = bcrypt.hashpw(str.encode(productionpw), bcrypt.gensalt(10)) fwrootpw_hashed = hashedpw.decode() apikey = randomPassword(80) apisecret = randomPassword(80) hashedpw = bcrypt.hashpw(str.encode(apisecret), bcrypt.gensalt(10)) apisecret_hashed = hashedpw.decode() # read template rc, content = readTextfile(fwconftpl) # replace placeholders with values content = content.replace('@@sysctl@@', sysctl) content = content.replace('@@servername@@', servername) content = content.replace('@@domainname@@', domainname) content = content.replace('@@basedn@@', basedn) content = content.replace('@@interfaces@@', interfaces) content = content.replace('@@dnsconfig@@', dnsconfig) content = content.replace('@@gwconfig@@', gwconfig) content = content.replace('@@serverip@@', serverip) content = content.replace('@@dockerip@@', dockerip) content = content.replace('@@firewallip@@', firewallip) content = content.replace('@@network@@', network) content = content.replace('@@bitmask@@', bitmask) content = content.replace('@@aliascontent@@', aliascontent) content = content.replace('@@gw_lan@@', constants.GW_LAN) content = content.replace('@@fwrootpw_hashed@@', fwrootpw_hashed) content = content.replace('@@authorizedkey@@', authorizedkey) content = content.replace('@@apikey@@', apikey) content = content.replace('@@apisecret_hashed@@', apisecret_hashed) content = content.replace('@@binduserpw@@', binduserpw) content = content.replace('@@radiussecret@@', radiussecret) content = content.replace('@@language@@', language) content = content.replace('@@timezone@@', timezone) content = content.replace('@@cacertb64@@', cacertb64) content = content.replace('@@fwcertb64@@', fwcertb64) content = content.replace('@@fwkeyb64@@', fwkeyb64) # write new configfile rc = writeTextfile(fwconftmp, content, 'w') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # create api credentials ini file msg = '* Saving api credentials ' printScript(msg, '', False, False, True) try: rc = modIni(constants.FWAPIKEYS, 'api', 'key', apikey) rc = modIni(constants.FWAPIKEYS, 'api', 'secret', apisecret) os.system('chmod 400 ' + constants.FWAPIKEYS) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # upload config files # upload modified main config.xml rc = putFwConfig(firewallip, rolloutpw) if not rc: sys.exit(1) # upload modified auth config file for web-proxy sso (#83) printScript('Creating web proxy sso auth config file') subProc(constants.FWSHAREDIR + '/create-auth-config.py', logfile) conftmp = '/tmp/' + os.path.basename(constants.FWAUTHCFG) if not os.path.isfile(conftmp): sys.exit(1) rc, content = readTextfile(conftmp) fwpath = content.split('\n')[0].partition(' ')[2] rc = putSftp(firewallip, conftmp, fwpath, productionpw) if not rc: sys.exit(1) # remove temporary files os.unlink(conftmp) # reboot firewall printScript('Installing extensions and rebooting firewall') fwsetup_local = constants.FWSHAREDIR + '/fwsetup.sh' fwsetup_remote = '/tmp/fwsetup.sh' rc = putSftp(firewallip, fwsetup_local, fwsetup_remote, productionpw) rc = sshExec(firewallip, 'chmod +x ' + fwsetup_remote, productionpw) rc = sshExec(firewallip, fwsetup_remote, productionpw) if not rc: sys.exit(1)
# get setup values printScript('Reading setup values.') servername = getSetupValue('servername') domainname = getSetupValue('domainname') realm = getSetupValue('realm') rc, bindpw = readTextfile(constants.BINDUSERSECRET) if not rc: sys.exit(1) # read config template printScript('Reading config template.') rc, content = readTextfile(constants.FWAUTHCFG) if not rc: sys.exit(1) # replace placeholders content = content.replace('@@servername@@', servername) content = content.replace('@@domainname@@', domainname) content = content.replace('@@realm@@', realm) content = content.replace('@@bindpw@@', bindpw) # write outfile outfile = '/tmp/' + os.path.basename(constants.FWAUTHCFG) printScript('Writing ' + outfile + '.') rc = writeTextfile(outfile, content, 'w') if not rc: printScript('Error writing file.') sys.exit(1) else: printScript('Finished successfully.')
appendcfg = hostcfg else: appendcfg = groupcfg # read template rc, content = readTextfile(cfgtemplate) # replace placeholders content = content.replace('@@normal@@', normal) content = content.replace('@@serverip@@', serverip) content = content.replace('@@iface@@', iface) content = content.replace('@@hostip@@', ip) content = content.replace('@@mac@@', mac) content = content.replace('@@domainname@@', domainname) content = content.replace('@@group@@', group) content = content.replace('@@hostname@@', hostname) # write file rc = writeTextfile(cfgout, content, 'w') # append host/group specific cfg rc, content = readTextfile(appendcfg) rc = writeTextfile(cfgout, content, 'a') # create image file if systemtype == 'bios' or systemtype == 'bios64': cmd = 'grub-mkimage -p /boot/grub -d /usr/lib/grub/' + platform + ' -O ' + imgtype + ' -o ' + img + ' -c ' + cfgout + ' ' + modules else: cmd = 'grub-mkstandalone -d /usr/lib/grub/' + platform + ' -O ' + imgtype + ' -o ' + img + ' --modules="' + modules + '" --install-modules="' + modules + '" /boot/grub/grub.cfg="' + cfgout + '"' os.system(cmd) os.unlink(cfgout) # set filename option in workstations file and dhcpd.conf if setfilename == True: print('Setting filename option in DHCP ...')
content = content.replace('@@lanif@@', lanif) content = content.replace('@@opt1if@@', opt1if) content = content.replace('@@serverip@@', serverip) content = content.replace('@@firewallip@@', firewallip) content = content.replace('@@bitmask@@', bitmask) content = content.replace('@@opsiip@@', opsiip) content = content.replace('@@dockerip@@', dockerip) content = content.replace('@@fwrootpw@@', fwrootpw) content = content.replace('@@authorizedkey@@', authorizedkey) content = content.replace('@@binduserpw@@', binduserpw) content = content.replace('@@timezone@@', timezone) content = content.replace('@@cacertb64@@', cacertb64) content = content.replace('@@fwcertb64@@', fwcertb64) content = content.replace('@@fwkeyb64@@', fwkeyb64) # write new configfile rc = writeTextfile(fwconftmp, content, 'w') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # upload new configfile msg = '* Uploading configuration file ' printScript(msg, '', False, False, True) try: ftp.put(fwconftmp, fwconf) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)
except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # bittorrent service msg = 'Activating bittorrent tracker ' printScript(msg, '', False, False, True) try: defaultconf = '/etc/default/bittorrent' rc, content = readTextfile(defaultconf) content = re.sub(r'\nSTART_BTTRACK=.*\n', '\nSTART_BTTRACK=1\n', content, re.IGNORECASE) content = re.sub(r'\n[#]*ALLOWED_DIR=.*\n', '\nALLOWED_DIR=' + constants.LINBODIR + '\n', content, re.IGNORECASE) writeTextfile(defaultconf, content, 'w') subProc('service bittorrent stop', logfile) subProc('service bittorrent start', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # linbo-bittorrent service msg = 'Activating linbo-bittorrent service ' printScript(msg, '', False, False, True) try: defaultconf = '/etc/default/linbo-bittorrent' rc, content = readTextfile(defaultconf) content = re.sub(r'\nSTART_BITTORRENT=.*\n', '\nSTART_BITTORRENT=1\n', content, re.IGNORECASE)