def getMacFromArp(ip): mac = '' subProc('ping -c2 ' + ip, logfile) pid = Popen(["arp", "-n", ip], stdout=PIPE) arpout = pid.communicate()[0] mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", str(arpout)).groups()[0] return mac.upper()
def getMacFromArp(ip): mac = '' c = 0 max = 10 while not isValidMac(mac): if c > 0: os.system('sleep 15') subProc('ping -c2 ' + ip, logfile) pid = Popen(["arp", "-n", ip], stdout=PIPE) arpout = pid.communicate()[0] try: mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", str(arpout)).groups()[0] if isValidMac(mac): return mac.upper() except: mac = '' c = c + 1 if c > max: break return mac
printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # create sophomorix admin user msg = 'Calculating random passwords ' printScript(msg, '', False, False, True) try: sophadminpw = randomPassword(16) with open(constants.SOPHADMINSECRET, 'w') as secret: secret.write(sophadminpw) binduserpw = randomPassword(16) with open(constants.BINDUSERSECRET, 'w') as secret: secret.write(binduserpw) subProc('chmod 400 ' + constants.SECRETDIR + '/*', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # samba backup msg = 'Backing up samba ' printScript(msg, '', False, False, True) try: subProc('sophomorix-samba --backup-samba without-users', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)
logfile = constants.LOGDIR + '/setup.' + title + '.log' printScript('', 'begin') printScript(title) # stop services msg = 'Stopping samba services ' printScript(msg, '', False, False, True) #services = ['winbind', 'samba-ad-dc', 'smbd', 'nmbd'] services = [ 'winbind', 'samba-ad-dc', 'smbd', 'nmbd', 'systemd-resolved', 'samba-ad-dc' ] try: for service in services: subProc('systemctl stop ' + service + '.service', logfile) if service == 'samba-ad-dc': continue # disabling not needed samba services subProc('systemctl disable ' + service + '.service', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # read setup ini msg = 'Reading setup data ' printScript(msg, '', False, False, True) setupini = constants.SETUPINI try: setup = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
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)
try: opts, args = getopt.getopt(sys.argv[1:], "c:hsu", ["config=", "help", "skip-fw", "unattended"]) except getopt.GetoptError as err: # print help information and exit: print(err) # will print something like "option -a not recognized" usage() sys.exit(2) # default values unattended = False skipfw = False # open logfile global logfile logfile = constants.SETUPLOG subProc('touch ' + logfile) subProc('chmod 600 ' + logfile) try: l = open(logfile, 'w') orig_out = sys.stdout sys.stdout = tee(sys.stdout, l) sys.stderr = tee(sys.stderr, l) except: fail('Cannot open logfile ' + logfile + ' !') sys.exit() # evaluate options for o, a in opts: if o in ("-u", "--unattended"): unattended = True elif o in ("-s", "--skipfw"):
filedata = filedata.replace('@@serverip@@', serverip) # get target path firstline = filedata.split('\n')[0] target = firstline.partition(' ')[2] # remove target path from shebang line if '#!/bin/sh' in firstline or '#!/bin/bash' in firstline: filedata = filedata.replace(' ' + target, '\n# ' + target) operms = '755' else: operms = '664' # do not overwrite specified configfiles if they exist if (f in do_not_overwrite and os.path.isfile(target)): printScript(' Success!', '', True, True, False, len(msg)) continue # create target directory subProc('mkdir -p ' + os.path.dirname(target), logfile) # backup file if f not in do_not_backup: backupCfg(target) with open(target, 'w') as outfile: outfile.write(setupComment()) outfile.write(filedata) os.system('chmod ' + operms + ' ' + target) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # restart network interface msg = 'Network setup ' printScript(msg, '', False, False, True)
# iface = setup.get('setup', 'iface') # except: # iface = '' # if iface == '' or iface == None: # iface_list, iface = getDefaultIface() # if iface == '': # printScript(' not set!', '', True, True, False, len(msg)) # try: # setup.set('setup', 'iface', iface) # except: # printScript(' failed to set!', '', True, True, False, len(msg)) # sys.exit(1) # printScript(' ' + iface, '', True, True, False, len(msg)) # write inifile finally msg = 'Writing setup ini file ' printScript(msg, '', False, False, True) try: with open(constants.SETUPINI, 'w') as outfile: setup.write(outfile) subProc('chmod 600 ' + constants.SETUPINI, logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # delete temporary ini files for item in [constants.CUSTOMINI, constants.PREPINI]: if os.path.isfile(item): os.unlink(item)
# substring with sha and validation duration shadays = ' -sha256 -days 3650' # ca key password & string cakeypw = randomPassword(16) passin = ' -passin pass:'******'Creating private CA key & certificate ' subj = subjbase + realm + '/subjectAltName=' + realm + '/' printScript(msg, '', False, False, True) try: with open(constants.CAKEYSECRET, 'w') as secret: secret.write(cakeypw) subProc('chmod 400 ' + constants.CAKEYSECRET, logfile) subProc( 'openssl genrsa -out ' + constants.CAKEY + ' -aes128 -passout pass:'******' 2048', logfile) subProc( 'openssl req -batch -x509 ' + subj + ' -new -nodes ' + passin + ' -key ' + constants.CAKEY + shadays + ' -out ' + constants.CACERT, logfile) subProc( 'openssl x509 -in ' + constants.CACERT + ' -inform PEM -out ' + constants.CACERTCRT, logfile) # install crt subProc( 'ln -sf ' + constants.CACERTCRT + ' /usr/local/share/ca-certificates/linuxmuster_cacert.crt', logfile) subProc('update-ca-certificates', logfile)
iface = '' if iface == '' or iface == None: iface_list, iface = getDefaultIface() if iface == '': printScript(' not set!', '', True, True, False, len(msg)) try: setup.set('setup', 'iface', iface) except: printScript(' failed to set!', '', True, True, False, len(msg)) sys.exit(1) printScript(' ' + iface, '', True, True, False, len(msg)) # write inifile finally msg = 'Writing setup ini file ' printScript(msg, '', False, False, True) setupini = constants.SETUPINI try: with open(setupini, 'w') as outfile: setup.write(outfile) subProc('chmod 600 ' + setupini, logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # delete temporary ini files if os.path.isfile(constants.CUSTOMINI): os.unlink(constants.CUSTOMINI) if os.path.isfile(constants.PREPINI): os.unlink(constants.PREPINI)
def main(): # open ssh connection if mailip != serverip: # start mailserver setup per ssh printScript('Remote mailserver setup') sshcmd = 'ssh -q -oStrictHostKeyChecking=accept-new ' + mailip + ' ' try: msg = '* Uploading certificates ' printScript(msg, '', False, False, True) # create remote ssl cert dir subProc(sshcmd + 'mkdir -p ' + constants.SSLDIR, logfile) # upload certs for item in [cacert, mailcert, mailkey]: putSftp(mailip, item, item) # link cacert subProc(sshcmd + 'ln -sf ' + cacert + ' /etc/ssl/certs', logfile) printScript(' Success!', '', True, True, False, len(msg)) msg = '* Uploading setup data ' printScript(msg, '', False, False, True) # create remote dir for setup.ini subProc(sshcmd + 'mkdir -p ' + constants.VARDIR, logfile) # upload setup.ini putSftp(mailip, setuptmp, setupini) printScript(' Success!', '', True, True, False, len(msg)) msg = '* Installing linuxmuster-mail package ' printScript(msg, '', False, False, True) # install linuxmuster-mail pkg subProc(sshcmd + 'apt update', logfile) subProc(sshcmd + 'apt -y install linuxmuster-mail', logfile) # key permissions subProc(sshcmd + 'chmod 640 ' + mailkey, logfile) subProc(sshcmd + 'chgrp docker ' + mailkey, logfile) printScript(' Success!', '', True, True, False, len(msg)) msg = '* Pulling mailserver image ' printScript(msg, '', False, False, True) # pull image subProc(sshcmd + 'docker pull ' + imagename, logfile) printScript(' Success!', '', True, True, False, len(msg)) msg = '* Setting up mailserver container ' printScript(msg, '', False, False, True) # invoke setup script subProc( sshcmd + '/usr/sbin/linuxmuster-mail-setup -f -c ' + setupini, logfile) printScript(' Success!', '', True, True, False, len(msg)) except: msg = 'Remote mailserver setup ' printScript(msg, '', False, False, True) printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # local mailserver setup else: msg = 'Local mailserver setup ' printScript(msg, '', False, False, True) try: subProc('apt update && apt -y install linuxmuster-mail', logfile) subProc('/usr/sbin/linuxmuster-mail-setup -f -c ' + setuptmp, logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # add mail dns entry msg = '* Creating dns entry ' printScript(msg, '', False, False, True) try: sambaTool('dns add localhost ' + domainname + ' mail A ' + mailip, logfile) sambaTool( 'dns add localhost ' + domainname + ' mail MX "' + mailip + ' 10"', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)
adminpw = setup.get('setup', 'adminpw') domainname = setup.get('setup', 'domainname') sambadomain = setup.get('setup', 'sambadomain') firewallip = setup.get('setup', 'firewallip') # get binduser password rc, binduserpw = readTextfile(constants.BINDUSERSECRET) printScript(' Success!', '', True, True, False, len(msg)) except Exception as error: printScript(error, '', True, True, False, len(msg)) sys.exit(1) # samba backup msg = 'Backing up samba ' printScript(msg, '', False, False, True) try: subProc('sophomorix-samba --backup-samba without-users', logfile) printScript(' Success!', '', True, True, False, len(msg)) except Exception as error: printScript(error, '', True, True, False, len(msg)) sys.exit(1) # renew sophomorix configs os.system('rm -f ' + constants.SCHOOLCONF) os.system('rm -f ' + constants.SOPHOSYSDIR + '/sophomorix.conf') subProc('sophomorix-postinst', logfile) # create default-school share schoolname = os.path.basename(constants.DEFAULTSCHOOL) defaultpath = constants.SCHOOLSSHARE + '/' + schoolname shareopts = 'writeable=y guest_ok=n' shareoptsex = ['comment "Share for default-school"', '"hide unreadable" yes', '"msdfs root" no', '"strict allocate" yes', '"valid users" "' + sambadomain + '\\administrator, @' + sambadomain + '\\SCHOOLS"']
# set password policy msg = 'password policy setup ' printScript(msg, '', False, False, True) try: replaceInFile(constants.SCHOOLCONF, 'RANDOM_PWD=yes', 'RANDOM_PWD=no') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # check msg = 'sophomorix-check ' printScript(msg, '', False, False, True) try: subProc('sophomorix-check', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # add msg = 'sophomorix-add ' printScript(msg, '', False, False, True) try: subProc('sophomorix-add', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)
# printScript(' not set!', '', True, True, False, len(msg)) # try: # setup.set('setup', 'iface', iface) # except: # printScript(' failed to set!', '', True, True, False, len(msg)) # sys.exit(1) # printScript(' ' + iface, '', True, True, False, len(msg)) # create global binduser password msg = 'Creating global binduser secret ' printScript(msg, '', False, False, True) try: binduserpw = randomPassword(16) with open(constants.BINDUSERSECRET, 'w') as secret: secret.write(binduserpw) subProc('chmod 400 ' + constants.SECRETDIR + '/*', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # write setup.ini finally msg = 'Writing setup ini file ' printScript(msg, '', False, False, True) try: with open(constants.SETUPINI, 'w') as outfile: setup.write(outfile) subProc('chmod 600 ' + constants.SETUPINI, logfile) # temporary setup.ini for transfering it later to additional vms setup.set('setup', 'binduserpw', binduserpw) setup.set('setup', 'adminpw', '')
opsiip = setup.get('setup', 'opsiip') dockerip = setup.get('setup', 'dockerip') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # variables hostkey_prefix = '/etc/ssh/ssh_host_' crypto_list = ['dsa', 'ecdsa', 'ed25519', 'rsa'] sshdir = '/root/.ssh' rootkey_prefix = sshdir + '/id_' known_hosts = sshdir + '/known_hosts' # delete old ssh keys subProc('rm -f /etc/ssh/*key* ' + sshdir + '/id*', logfile) # create ssh keys printScript('Creating ssh keys:') for a in crypto_list: msg = '* ' + a + ' host key ' printScript(msg, '', False, False, True) try: subProc( 'ssh-keygen -t ' + a + ' -f ' + hostkey_prefix + a + '_key -N ""', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) msg = '* ' + a + ' root key '
if rc == True: printScript(' Success!', '', True, True, False, len(msg)) else: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # write linbo auth data to rsyncd.secrets msg = 'Creating rsync secrets file ' printScript(msg, '', False, False, True) configfile = '/etc/rsyncd.secrets' filedata = setupComment() + '\n' + 'linbo:' + adminpw + '\n' try: with open(configfile, 'w') as outfile: outfile.write(filedata) # set permissions subProc('chmod 600 ' + configfile, logfile) # enable rsync service subProc('systemctl enable rsync.service', logfile) # restart rsync service subProc('service rsync stop', logfile) subProc('service rsync start', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) 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
# try all fstab entries try: for i in mountpoints: # if mountpoint matches change mount options if config.tree.filesystems[c].mountpoint == i: msg = 'Modifying mount options for ' + i + ' ' printScript(msg, '', False, False, True) try: # get mount options from constants config.tree.filesystems[c].options = constants.ROOTMNTOPTS # save fstab config.save() printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) msg = 'Remounting ' + i + ' ' printScript(msg, '', False, False, True) # try to remount filesystem with new options try: subProc('mount -o remount ' + i, logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # next entry c += 1 # break if entries ran out except: break
firstline = filedata.split('\n')[0] target = firstline.partition(' ')[2] # remove target path from shebang line, define target file permissions if '#!/bin/sh' in firstline or '#!/bin/bash' in firstline: filedata = filedata.replace(' ' + target, '\n# ' + target) operms = '755' elif 'sudoers.d' in target: operms = '400' else: operms = '644' # do not overwrite specified configfiles if they exist if (f in do_not_overwrite and os.path.isfile(target)): printScript(' Success!', '', True, True, False, len(msg)) continue # create target directory subProc('mkdir -p ' + os.path.dirname(target), logfile) # backup file if f not in do_not_backup: backupCfg(target) with open(target, 'w') as outfile: outfile.write(setupComment()) outfile.write(filedata) os.system('chmod ' + operms + ' ' + target) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # restart network interface msg = 'Network setup ' printScript(msg, '', False, False, True)
# set comment filedata = setupComment() + filedata # backup original configfile backupCfg(configfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # write changes msg = 'Writing back dhcp configuration ' printScript(msg, '', False, False, True) try: with open(configfile, 'w') as outfile: outfile.write(filedata) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # restart dhcp service msg = 'Restarting dhcp service ' printScript(msg, '', False, False, True) try: subProc('service isc-dhcp-server stop', logfile) subProc('service isc-dhcp-server start', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)
from functions import printScript from functions import subProc title = os.path.basename(__file__).replace('.py', '').split('_')[1] logfile = constants.LOGDIR + '/setup.' + title + '.log' printScript('', 'begin') printScript(title) # disable unwanted services unwanted = ['iscsid', 'dropbear', 'lxcfs'] for item in unwanted: msg = 'Disabling service ' + item + ' ' printScript(msg, '', False, False, True) try: subProc('systemctl stop ' + item + '.service', logfile) subProc('systemctl disable ' + item + '.service', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' not installed!', '', True, True, False, len(msg)) # 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: printScript(' Failed!', '', 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)
adminpw = setup.get('setup', 'adminpw') domainname = setup.get('setup', 'domainname') sambadomain = setup.get('setup', 'sambadomain') firewallip = setup.get('setup', 'firewallip') # get binduser password rc, binduserpw = readTextfile(constants.BINDUSERSECRET) printScript(' Success!', '', True, True, False, len(msg)) except Exception as error: printScript(error, '', True, True, False, len(msg)) sys.exit(1) # samba backup msg = 'Backing up samba ' printScript(msg, '', False, False, True) try: subProc('sophomorix-samba --backup-samba without-users', logfile) printScript(' Success!', '', True, True, False, len(msg)) except Exception as error: printScript(error, '', True, True, False, len(msg)) sys.exit(1) # renew sophomorix configs os.system('rm -f ' + constants.SCHOOLCONF) os.system('rm -f ' + constants.SOPHOSYSDIR + '/sophomorix.conf') subProc('sophomorix-postinst', logfile) # create default-school share schoolname = os.path.basename(constants.DEFAULTSCHOOL) defaultpath = constants.SCHOOLSSHARE + '/' + schoolname shareopts = 'writeable=y guest_ok=n' shareoptsex = [
# printScript(' not set!', '', True, True, False, len(msg)) # try: # setup.set('setup', 'iface', iface) # except: # printScript(' failed to set!', '', True, True, False, len(msg)) # sys.exit(1) # printScript(' ' + iface, '', True, True, False, len(msg)) # create global binduser password msg = 'Creating global binduser secret ' printScript(msg, '', False, False, True) try: binduserpw = randomPassword(16) with open(constants.BINDUSERSECRET, 'w') as secret: secret.write(binduserpw) subProc('chmod 440 ' + constants.BINDUSERSECRET, logfile) subProc('chgrp dhcpd ' + constants.BINDUSERSECRET, logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # write setup.ini finally msg = 'Writing setup ini file ' printScript(msg, '', False, False, True) try: with open(constants.SETUPINI, 'w') as outfile: setup.write(outfile) subProc('chmod 600 ' + constants.SETUPINI, logfile) # temporary setup.ini for transfering it later to additional vms setup.set('setup', 'binduserpw', binduserpw)
defaults = configparser.ConfigParser(inline_comment_prefixes=('#', ';')) defaults.read(constants.DEFAULTSINI) # setup.ini setup = configparser.ConfigParser(inline_comment_prefixes=('#', ';')) setup.read(setupini) # interface to use iface = setup.get('setup', 'iface') serverip = setup.get('setup', 'serverip') firewallip = setup.get('setup', 'firewallip') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # stop network interface subProc('ifconfig ' + iface + ' 0.0.0.0 down', logfile) # templates, whose corresponding configfiles must not be overwritten do_not_overwrite = 'dhcpd.custom.conf' # templates, whose corresponding configfiles must not be backed up do_not_backup = [ 'interfaces.linuxmuster', 'dovecot.linuxmuster.conf', 'smb.conf' ] printScript('Processing config templates:') for f in os.listdir(constants.TPLDIR): source = constants.TPLDIR + '/' + f msg = ' * ' + f + ' ' printScript(msg, '', False, False, True) try: with open(source, 'r') as infile:
logfile = constants.LOGDIR + '/setup.' + title + '.log' printScript('', 'begin') printScript(title) # remove temporary files if os.path.isfile('/tmp/setup.ini'): os.unlink('/tmp/setup.ini') # disable unwanted services unwanted = ['iscsid', 'dropbear', 'lxcfs'] for item in unwanted: msg = 'Disabling service ' + item + ' ' printScript(msg, '', False, False, True) try: subProc('systemctl stop ' + item + '.service', logfile) subProc('systemctl disable ' + item + '.service', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' not installed!', '', True, True, False, len(msg)) # 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: 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)
setup.read(setupini) adminpw = setup.get('setup', 'adminpw') domainname = setup.get('setup', 'domainname') printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # create sophomorix admin user msg = 'Calculating random passwords ' printScript(msg, '', False, False, True) try: binduserpw = randomPassword(16) with open(constants.BINDUSERSECRET, 'w') as secret: secret.write(binduserpw) subProc('chmod 400 ' + constants.SECRETDIR + '/*', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # samba backup msg = 'Backing up samba ' printScript(msg, '', False, False, True) try: subProc('sophomorix-samba --backup-samba without-users', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)
if isValidPassword(adminpw_repeated): break if adminpw == adminpw_repeated: break print('Administrator password: '******'setup', 'adminpw', adminpw) # write INIFILE msg = 'Writing input to setup ini file ' printScript(msg, '', False, False, True) try: with open(constants.SETUPINI, 'w') as INIFILE: setup.write(INIFILE) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1) # set root password msg = 'Setting root password ' printScript(msg, '', False, False, True) try: subProc('echo "root:' + adminpw + '" | chpasswd', logfile) if os.path.isdir('/home/linuxmuster'): subProc('echo "linuxmuster:' + adminpw + '" | chpasswd', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)
#!/usr/bin/python3 # # final tasks # [email protected] # 20170212 # import constants import os import sys from functions import printScript from functions import subProc title = os.path.basename(__file__).replace('.py', '').split('_')[1] logfile = constants.LOGDIR + '/setup.' + title + '.log' printScript('', 'begin') printScript(title) # import devices msg = 'Starting device import ' printScript(msg, '', False, False, True) try: subProc('linuxmuster-import-devices.py', logfile) printScript(' Success!', '', True, True, False, len(msg)) except: printScript(' Failed!', '', True, True, False, len(msg)) sys.exit(1)