def addInterface(self, ctx, form, data): wanDevices = self.sysconf.WANDevices devices = [] for i in xrange(20): n = "ppp%s" % i if not (n in wanDevices.keys()): devices.append(n) this = devices[0] if data['defaultRoute']: defaults = ['defaultroute'] else: defaults = [] if data['defaultDNS']: defaults.append('usepeerdns') seg = { 'pppd': defaults, 'username': data['username'], 'password': data['password'], 'link': data['link'], 'plugins': 'pppoe' } wanDevices[this] = seg self.sysconf.WANDevices = wanDevices if data['localOnly']: self.sysconf.LocalRoute = this WebUtils.system('/usr/local/tcs/tums/configurator --quagga') if os.path.exists('/etc/debian_version'): WebUtils.system('/etc/init.d/quagga restart') WebUtils.system('/usr/local/tcs/tums/configurator --debnet') else: WebUtils.system('/etc/init.d/zebra restart') WebUtils.system('/usr/local/tcs/tums/configurator --net') WebUtils.system('ln -s /etc/init.d/net.lo /etc/init.d/net.%s' % this) WebUtils.system('rc-update -a net.%s boot' % this) return url.root.child('PPP')
def reloadSamba(self): WebUtils.system(Settings.BaseDir + '/configurator --samba') WebUtils.system("/etc/init.d/samba restart")
for vacFile in vacFiles: try: os.remove(vacFile) except: pass try: LDAP.modifyElement(l, 'uid='+self.avatarId.username+','+dc, oldRecord, newRecord) if Settings.sambaDN and self.avatarId.domains[0]==Settings.defaultDomain: WebUtils.system('/etc/init.d/nscd restart') return url.root.child('Settings').child('Completed') except Exception, e: print e, " in last mod" return url.root.child('Settings').child('Failed') return WebUtils.system(Settings.BaseDir+'/ntlmgen/ntlm.pl %s' % (data['userPassword'])).addBoth(gotNTHash) def render_content(self, ctx, data): notice = "" if self.returns=='Completed': notice = tags.img(src='/images/modsuccess.png') keyName = "You do not have any support files associated with your username" for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (self.avatarId.username, self.avatarId.dom) in i and "key" in i: keyName = [ tags.a(href='/packs/%s.%s-vpn.zip' % ( self.avatarId.username, self.avatarId.dom ))["Download Client Settings"], tags.br,
def reloadGuard(result): return WebUtils.system( Settings.BaseDir + '/configurator --cfilter; /etc/init.d/dansguardian restart').addBoth( lambda _: result)
def locateChild(self, ctx, segs): if segs[0] == "Sync": return WebUtils.system('/usr/local/tcs/tums/configurator --ha').addBoth(lambda _: url.root.child('HA')), () return PageHelpers.DefaultAthena.locateChild(self, ctx, segs)
def next(_): print "Added shorewall, going to ARP check" return WebUtils.system( "arp -n | grep %s | awk '{print $3}'" % host).addBoth(done)
def returnAction(self, data): def ret(_): return url.root.child('SSH') return WebUtils.system(Settings.BaseDir + '/configurator --ssh').addBoth(ret)
except Exception, e: print e, " in vacation" return url.root.child('Settings').child('Failed') if not data['vacation'] or not data['vacen']: for vacFile in vacFiles: try: os.remove(vacFile) except: pass try: LDAP.modifyElement(l, 'uid=' + self.avatarId.username + ',' + dc, oldRecord, newRecord) if Settings.sambaDN and self.avatarId.domains[ 0] == Settings.defaultDomain: WebUtils.system('/etc/init.d/nscd restart') return url.root.child('Settings').child('Completed') except Exception, e: print e, " in last mod" return url.root.child('Settings').child('Failed') def render_content(self, ctx, data): notice = "" if self.returns == 'Completed': notice = tags.img(src='/images/modsuccess.png') return ctx.tag[tags.div( id="rightBlock")[notice, tags.directive('form userSettings')]]
def submitForm(self, ctx, form, data): print data l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o=' + Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass) dc = "%s,%s,o=%s" % (Settings.LDAPPeople, LDAP.domainToDC( self.avatarId.domains[0]), Settings.LDAPBase) oldRecord = LDAP.getUsers(l, dc, 'uid=' + self.avatarId.username)[0] newRecord = copy.deepcopy(oldRecord) if data['mailForwardingAddress']: fA = [] for le in data['mailForwardingAddress'].split('\n'): ad = le.replace(' ', '').replace('\r', '') if ad: fA.append(ad) newRecord['mailForwardingAddress'] = [le.encode() for le in fA] elif newRecord.get('mailForwardingAddress', False): del newRecord['mailForwardingAddress'] if data['userPassword']: newRecord['userPassword'] = [ "{SHA}" + LDAP.hashPassword(data['userPassword']) ] if Settings.sambaDN and self.avatarId.domains[ 0] == Settings.defaultDomain: (LM, NT) = tuple( os.popen(Settings.BaseDir + '/ntlmgen/ntlm.pl %s' % (data['userPassword'])).read().strip( '\n').split()) newRecord['sambaNTPassword'] = [NT] newRecord['sambaLMPassword'] = [LM] vacFiles = [ "/var/spool/mail/vacation/%s@%s.db" % (self.avatarId.username, self.avatarId.domains[0]), "/var/spool/mail/vacation/%s@%s.log" % (self.avatarId.username, self.avatarId.domains[0]), "/var/spool/mail/vacation/%s@%s.txt" % (self.avatarId.username, self.avatarId.domains[0]) ] if data['vacation']: # Write a vacation note. try: if data['vacen']: l1 = open( "/var/spool/mail/vacation/%s@%s.db" % (self.avatarId.username, self.avatarId.domains[0]), 'w') l2 = open( "/var/spool/mail/vacation/%s@%s.log" % (self.avatarId.username, self.avatarId.domains[0]), 'w') l3 = open( "/var/spool/mail/vacation/%s@%s.txt" % (self.avatarId.username, self.avatarId.domains[0]), 'w') l1.write('') l2.write('') else: l3 = open( "/var/spool/mail/vacation/DISABLED%s@%s.txt" % (self.avatarId.username, self.avatarId.domains[0]), 'w') l3.write(data['vacation']) if os.path.exists('/etc/debian_version'): WebUtils.system( 'chown www-data:root /var/spool/mail/vacation/*; chmod a+r /var/spool/mail/vacation/*' ) else: WebUtils.system( 'chown apache:root /var/spool/mail/vacation/*; chmod a+r /var/spool/mail/vacation/*' ) except Exception, e: print e, " in vacation" return url.root.child('Settings').child('Failed')
class editPage(Base.Page): addSlash = True userData = {} def __init__(self, avatarId=None, db=None, cid=None, domain=None, returns=None, *a, **ka): PageHelpers.DefaultPage.__init__(self, avatarId, db, *a, **ka) self.avatarId = avatarId self.cid = cid self.domain = domain self.returns = returns if domain: self.lc = LDAP.LDAPConnector(self.domain, self.sysconf) def form_editForm(self, data): domains = [] if self.avatarId.isAdmin: for i in self.flatFil: thisdom = i.split('dm=')[-1].split(',')[0] if not thisdom in domains: domains.append(thisdom) # Form population userData = self.lc.getUser(self.cid) devList = [] #extList = [] rouList = [] UserExtForm = [] fkeyForm = [] if Settings.sambaDN and self.domain == Settings.defaultDomain and PBXUtils.enabled( ): includeList = [] includeList = self.sysconf.PBXExtensions.get( userData['uid'][0], {'extensions': []})['extensions'] devIncList = self.sysconf.PBXExtensions.get( userData['uid'][0], {'devices': []})['devices'] extList = PBXUtils.getAvaExtenNumSelect(True, includeList) #for ext in PBXUtils.getAvailibleExtensions(): # extList.append((str(ext), str(ext))) for dev in PBXUtils.getAllAvaExtDeviceEndPoints(devIncList): devList.append((str(dev), str(dev))) queueList = [ (queue, queue) for queue in self.sysconf.PBX.get('queues', {}).keys() ] rouList = self.sysconf.PBXRouters.keys() extensionWidget = formal.widgetFactory(formal.SelectChoice, options=extList) deviceWidget = formal.widgetFactory(formal.SelectChoice, options=devList) #queueWidget = formal.widgetFactory(formal.SelectChoice, options = queueList) userExtensions = PBXUtils.getExtensionSelect() queueOptions = formal.widgetFactory(formal.SelectChoice, options=[(1, "Level 1 Member"), (2, "Level 2 Member"), (3, "Level 3 Member") ]) queues = [] for queue in self.sysconf.PBX.get('queues', {}).keys()[0:-1]: queues.append( formal.Field('queue%s' % queue, formal.Integer(), queueOptions, label="Queue %s" % queue)) try: queue = self.sysconf.PBX.get('queues', {}).keys()[-1] except: queue = None if queue: queues.append( formal.Field( 'queue%s' % queue, formal.Integer(), queueOptions, label="Queue %s" % queue, description= "Each extension may be part of many queues, each queue membersip has a specific weighting. The weighting determines the order in which calls may be seeded. Level 2 members only get calls seeded to them once Level 1 has been saturated etc." )) fKeyOptions = formal.widgetFactory(formal.SelectChoice, options=userExtensions) fKeys = [] maxKeys = 54 for i in range(maxKeys): fKeys.append( formal.Field('fkeys%s' % i, formal.String(), fKeyOptions, label="Key %s" % i)) fKeys.append( formal.Field( 'fkeys%s' % maxKeys, formal.String(), fKeyOptions, label="Key %s" % maxKeys, description= "Select the extensions for the function keys above")) userExtFormContent = [ formal.Field('userExtEnabled', formal.Boolean(), label=self.text.userFormLabelExtEnabled), formal.Field('userExtOutbound', formal.Sequence(formal.String()), formal.widgetFactory(formal.CheckboxMultiChoice, options=[(i, i) for i in rouList]), label=self.text.userFormLabelOutbound, description=self.text.userFormDescOutbound), #formal.Field('userExtQueues', formal.Sequence(formal.String()), # formal.widgetFactory(formal.CheckboxMultiChoice, # options = queueList), # label = self.text.userFormLabelQueues, # description = self.text.userFormDescQueues), ] userExtFormContent.extend(queues) userExtFormContent.extend([ formal.Field( 'userLowBW', formal.Boolean(), label="Low Bandwidth", description= 'Indicates that the devices(if applicable) should use a low bandwidth codec' ), formal.Field( 'userExtTimeout', formal.Integer(), label="Timeout", description= "How many seconds should we wait before giving up on this extension, note that setting this to 0 will force the extension to use the default timeout" ), formal.Field( 'userExtqTimeout', formal.Integer(), label="Queue Timeout", description= "How many seconds should we wait before giving up on this queue member, 0 will indicate to use the default" ), formal.Field('userExtCallerID', formal.String(), label=self.text.userFormLabelCallID), formal.Field('userExtNumber0', formal.String(), extensionWidget, label=self.text.userFormLabelExtNumber), formal.Field('userExtNumber1', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber2', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber3', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber4', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber5', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber6', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber7', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber8', formal.String(), extensionWidget, label=""), formal.Field('userExtNumber9', formal.String(), extensionWidget, label=""), tags.div(_class="userLine")[tags.a( href="#", onclick="addExten();")[self.text.userFormLabelAddExt]], #formal.Field('userExtFwdUA', formal.String(), label = self.text.userFormLabelRedNoAnswer, # description = self.text.userFormDescRedNoAnswer), formal.Field('userExtDev0', formal.String(), deviceWidget, label=self.text.userFormLabelDev), formal.Field('userExtDev1', formal.String(), deviceWidget, label=""), formal.Field('userExtDev2', formal.String(), deviceWidget, label=""), formal.Field('userExtDev3', formal.String(), deviceWidget, label=""), formal.Field('userExtDev4', formal.String(), deviceWidget, label=""), formal.Field('userExtDev5', formal.String(), deviceWidget, label=""), formal.Field('userExtDev6', formal.String(), deviceWidget, label=""), formal.Field('userExtDev7', formal.String(), deviceWidget, label=""), formal.Field('userExtDev8', formal.String(), deviceWidget, label=""), formal.Field('userExtDev9', formal.String(), deviceWidget, label=""), tags.div(_class="userLine")[tags.a( href="#", onclick="addExtDev();")[self.text.userFormLabelAddDev]], formal.Field('userExtVoiceMail', formal.Boolean(), label=self.text.userFormLabelVoiceMail), formal.Field('userExtVoiceMailPin', formal.String(), label=self.text.userFormLabelVoiceMailPin), ]) UserExtForm = formal.Group('userExtension')[userExtFormContent] fkeyForm = formal.Group('userFKeys')[fKeys] form = formal.Form( self.submitForm )[formal.Group('userSettings')[tags.div(_class="field")[ tags.label[self.text.userFormLabelEmailAddress], tags.div(id="emailAd", _class="inputs")["%s@%s" % (self.cid, self.domain)]], formal.Field('uid', formal .String(required=True, validators=Base .UserNameValidators), label=self.text. userFormLabelUsername), formal.Field('givenName', formal.String( required=True), label=self.text. userFormLabelName), formal.Field('sn', formal.String(), label=self.text. userFormLabelSurname), formal.Field('userPassword', formal.String(), formal.CheckedPassword, label=self.text. userFormLabelPass), ], formal.Group('mailSettings') [formal.Field('mailForwardingAddress0', formal.String(), label=self. text.userFormLabelForward), formal.Field('mailForwardingAddress1', formal.String(), label=""), formal.Field('mailForwardingAddress2', formal.String(), label=""), formal.Field('mailForwardingAddress3', formal.String(), label=""), formal.Field('mailForwardingAddress4', formal.String(), label=""), formal.Field('mailForwardingAddress5', formal.String(), label=""), formal.Field('mailForwardingAddress6', formal.String(), label=""), formal.Field('mailForwardingAddress7', formal.String(), label=""), formal.Field('mailForwardingAddress8', formal.String(), label=""), formal.Field('mailForwardingAddress9', formal.String(), label=""), tags.div( _class="userLine")[tags.a(href="#", onclick="addForward();" )[self.text.userFormLabelAddline]], formal.Field('mailAlternateAddress0', formal.String(), label=self.text.userFormLabelAlias), formal.Field('mailAlternateAddress1', formal.String(), label=""), formal.Field('mailAlternateAddress2', formal.String(), label=""), formal.Field('mailAlternateAddress3', formal.String(), label=""), formal.Field('mailAlternateAddress4', formal.String(), label=""), formal.Field('mailAlternateAddress5', formal.String(), label=""), formal.Field('mailAlternateAddress6', formal.String(), label=""), formal.Field('mailAlternateAddress7', formal.String(), label=""), formal.Field('mailAlternateAddress8', formal.String(), label=""), formal.Field('mailAlternateAddress9', formal.String(), label=""), tags.div( _class="userLine")[tags.a(href="#", onclick="addAlias();" )[self.text.userFormLabelAddline]], formal.Field('vacen', formal.Boolean(), label=self.text.userFormLabelVacationActive, description=self.text.userFormTextVacationNote), formal.Field('vacation', formal.String(), formal.TextArea, label=self.text.userFormLabelVacation), formal.Field('vacvalidity', formal.Date(), label="Valid until", description= "Disable the vacation note automatically on this date" )], formal.Group('userPermissions')[ formal.Field('employeeType', formal.Boolean(), label=self.text.userFormLabelWeb), formal.Field('accountStatus', formal.Boolean(), label=self.text.userFormLabelEmail), formal.Field('tumsAdmin', formal.Boolean(), label=self.text.userFormLabelAdmin), formal.Field('tumsUser', formal.Sequence(formal.String()), formal.widgetFactory(formal.CheckboxMultiChoice, [( i, i) for i in domains]), label=self.text.userFormLabelDomainAdmin), formal.Field('tumsReports', formal.Boolean(), label=self.text.userFormLabelReports), formal.Field('copyto', formal.String(), label=self.text.userFormLabelCopy, description=self.text.userFormTextCopy)], formal.Group('userAccess')[ formal.Field('vpnEnabled', formal.Boolean(), label=self.text.userFormLabelVPN, description=self.text.userFormTextVPN), formal.Field('ftpEnabled', formal.Boolean(), label=self.text.userFormLabelFTP, description=self.text.userFormTextFTP), formal.Field('ftpGlobal', formal.Boolean(), label=self.text.userFormLabelGlobalFTP, description=self.text.userFormTextGlobal)], UserExtForm, fkeyForm] form.addAction(self.submitForm) tData = copy.deepcopy(userData) tData['userSettings.uid'] = tData['uid'][0] tData['userSettings.givenName'] = tData.get('givenName', [""])[0] tData['userSettings.sn'] = tData.get('sn', [""])[0] if tData.get('loginShell'): if '/bin/bash' in tData['loginShell']: tData['userAccess.ftpEnabled'] = True if self.sysconf.FTP.get('globals'): if tData['uid'][0] in self.sysconf.FTP['globals']: tData['userAccess.ftpGlobal'] = True tData['userSettings.userPassword'] = '' # Strip password address = "%s@%s" % (tData['uid'][0], self.domain) for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (self.cid, self.domain) in i and "key" in i: tData['userAccess.vpnEnabled'] = True if self.sysconf.Mail.get('copys', []): for addr, dest in self.sysconf.Mail['copys']: if addr == address: tData['userPermissions.copyto'] = dest if userData.get('accountStatus', False): tData['userPermissions.accountStatus'] = True else: tData['userPermissions.accountStatus'] = False if userData.get('mailForwardingAddress', False): for cnt, address in enumerate(userData['mailForwardingAddress']): tData['mailSettings.mailForwardingAddress%s' % cnt] = address if userData.get('mailAlternateAddress', False): for cnt, address in enumerate(userData['mailAlternateAddress']): tData['mailSettings.mailAlternateAddress%s' % cnt] = address emp = userData.get('employeeType', [False]) if 'squid' in emp: tData['userPermissions.employeeType'] = True else: tData['userPermissions.employeeType'] = False if 'tumsAdmin' in emp: tData['userPermissions.tumsAdmin'] = True else: tData['userPermissions.tumsAdmin'] = False if 'tumsReports' in emp: tData['userPermissions.tumsReports'] = True else: tData['userPermissions.tumsReports'] = False if emp[0]: for i in emp: if 'tumsUser[' in i: tData['userPermissions.tumsUser'] = i.split('[')[-1].split( ']')[0].split(',') try: vac = open( "/var/spool/mail/vacation/%s@%s.txt" % (self.cid, self.domain), 'r') tData['mailSettings.vacation'] = vac.read() tData['mailSettings.vacen'] = True except: pass # No vacation note try: vac = open( "/var/spool/mail/vacation/DISABLED%s@%s.txt" % (self.cid, self.domain), 'r') tData['mailSettings.vacation'] = vac.read() tData['mailSettings.vacen'] = False except: pass # No disabled note either. if os.path.exists('/var/spool/mail/vacation/%s@%s.validity' % (self.cid, self.domain)): n = open('/var/spool/mail/vacation/%s@%s.validity' % (self.cid, self.domain)).read().strip('\n') d = datetime.date(*[int(i) for i in n.split('-')]) tData['mailSettings.vacvalidity'] = d #Populate Userextension Data if PBXUtils.enabled(): ext = self.sysconf.PBXExtensions.get( tData['uid'][0], { 'enabled': False, 'lowbw': False, 'outbound': [], 'callerID': "", 'voiceMail': False, 'voiceMailPin': '', 'fkeys': [], 'extensions': [], 'devices': [], 'queues': {} }) tData['userExtension.userExtEnabled'] = ext['enabled'] tData['userExtension.userExtOutbound'] = ext['outbound'] tData['userExtension.userExtTimeout'] = ext.get('timeout', 0) tData['userExtension.userExtqTimeout'] = ext.get('qtimeout', 0) #tData['userExtension.userExtQueues'] = ext.get('queues', []) queueSettings = ext.get('queues', {}) if type(queueSettings) == list: n = {} for queue in queueSettings: n[queue] = 1 queueSettings = n for queue in self.sysconf.PBX.get('queues', {}).keys(): tData['userExtension.queue%s' % queue] = queueSettings.get( queue, None) tData['userExtension.userExtCallerID'] = ext['callerID'] tData['userExtension.userExtVoiceMail'] = ext['voiceMail'] tData['userExtension.userExtVoiceMailPin'] = ext['voiceMailPin'] tData['userExtension.userLowBW'] = ext.get('lowbw', False) for i in range(0, 9): try: tData['userExtension.userExtNumber%s' % i] = ext['extensions'][i] except: pass try: tData['userExtension.userExtDev%s' % i] = ext['devices'][i] except: pass for i in range(54): try: tData['userFKeys.fkeys%s' % i] = ext['fkeys'][i] except: pass form.data = tData return form def commitUserExtensions(self, form, data): def cAscii(val): if type(val) == str: return val.encode('ascii', 'replace') return val if Settings.sambaDN and self.domain == Settings.defaultDomain and PBXUtils.enabled( ): user = data['userSettings.uid'].encode('ascii', 'replace').lower() ext = self.sysconf.PBXExtensions.get( user, { 'enabled': False, 'lowbw': False, 'outbound': [], 'callerID': "", 'voiceMail': False, 'voiceMailPin': '', 'fkeys': [], 'extensions': [], 'devices': [], 'queues': {} }) ext['enabled'] = data['userExtension.userExtEnabled'] if data['userExtension.userExtOutbound']: ext['outbound'] = [ cAscii(i) for i in data['userExtension.userExtOutbound'] ] #if data['userExtension.userExtQueues']: # ext['queues'] = [ # cAscii(i) # for i in data['userExtension.userExtQueues'] # ] #else: # ext['queues'] = [] userQueues = {} for queue in self.sysconf.PBX.get('queues', {}).keys(): penalty = data.get("userExtension.queue%s" % queue, None) if penalty: userQueues[queue.encode('ascii', 'replace')] = penalty ext['queues'] = userQueues if data['userExtension.userExtCallerID']: ext['callerID'] = cAscii(data['userExtension.userExtCallerID']) else: ext['callerID'] = cAscii(data['userExtension.userExtNumber0']) if data['userExtension.userExtTimeout'] > 0: ext['timeout'] = cAscii(data['userExtension.userExtTimeout']) else: if 'timeout' in ext: del ext['timeout'] if data['userExtension.userExtqTimeout'] > 0: ext['qtimeout'] = cAscii(data['userExtension.userExtqTimeout']) else: if 'qtimeout' in ext: del ext['qtimeout'] oldFullCID = self.sysconf.PBXExtensions.get( user, {'fullcallerID': ""}) ext['lowbw'] = data['userExtension.userLowBW'] ext['fullcallerID'] = """"%s" <%s>""" % (data['cn'][0].encode( 'ascii', 'replace'), ext['callerID']) ext['voiceMail'] = data['userExtension.userExtVoiceMail'] if data['userExtension.userExtVoiceMailPin']: ext['voiceMailPin'] = data[ 'userExtension.userExtVoiceMailPin'].encode( 'ascii', 'replace') else: ext['voiceMailPin'] = '' ext['extensions'] = [] ext['devices'] = [] oldDev = self.sysconf.PBXExtensions.get(user, {'devices': []})['devices'] for i in range(0, 9): if data['userExtension.userExtNumber%s' % i]: ext['extensions'].append( cAscii(data['userExtension.userExtNumber%s' % i])) if data['userExtension.userExtDev%s' % i]: ext['devices'].append( cAscii(data['userExtension.userExtDev%s' % i])) restartPhone = False fkeys = [] for i in range(54): fkeys.append(data['userFKeys.fkeys%s' % i]) if 'fkeys' in ext: if ext['fkeys'] != fkeys: restartPhone = True ext['fkeys'] = fkeys for k, devname in enumerate(oldDev): if k < len(ext['devices']): if devname != ext['devices'][k]: restartPhone = True if oldFullCID != ext['fullcallerID']: restartPhone = True if restartPhone: for devname in ext['devices']: dev = devname.split('/') if dev[0] == 'Phone': Asterisk.restartSnom(dev[1]) EXT = self.sysconf.PBXExtensions EXT[user] = ext self.sysconf.PBXExtensions = EXT return True def submitForm(self, ctx, form, data): oldRecord, newRecord = self.lc.modifyUser(self.cid, data) dc = "%s,%s,o=%s" % (Settings.LDAPPeople, LDAP.domainToDC( self.domain), Settings.LDAPBase) user = data['userSettings.uid'].encode('ascii', 'replace').lower() moveUser = False if user != self.cid: moveUser = True vacFiles = [ "/var/spool/mail/vacation/%s@%s.db" % (user, self.domain), "/var/spool/mail/vacation/%s@%s.log" % (user, self.domain), "/var/spool/mail/vacation/%s@%s.txt" % (user, self.domain) ] runLater = [] vpnCurrent = False for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (user, self.domain) in i and "key" in i: vpnCurrent = True if data['userAccess.vpnEnabled'] and vpnCurrent == False: vdata = { 'name': "%s.%s" % (user, self.domain), 'mail': "%s@%s" % (user, self.domain), 'ip': None, 'mailKey': True } v = VPN.Page() v.text = self.text v.newCert(None, None, vdata) elif not data['userAccess.vpnEnabled'] and vpnCurrent == True: runLater.append( 'cd /etc/openvpn/easy-rsa/; source /etc/openvpn/easy-rsa/vars; /etc/openvpn/easy-rsa/revoke-full %s; rm /etc/openvpn/keys/%s.*' % ("%s.%s" % (user, self.domain), "%s.%s" % (user, self.domain))) address = "%s@%s" % (user, self.domain) mailConf = self.sysconf.Mail if data['userPermissions.copyto']: if mailConf.get('copys', []): newCopys = [] for addr, dest in mailConf['copys']: if addr != address: newCopys.append((addr, dest)) newCopys.append((address, data['userPermissions.copyto'])) mailConf['copys'] = newCopys else: mailConf['copys'] = [(address, data['userPermissions.copyto'])] else: if mailConf.get('copys', []): newCopys = [] for addr, dest in mailConf['copys']: if addr != address: newCopys.append((addr, dest)) mailConf['copys'] = newCopys self.sysconf.Mail = mailConf if data['mailSettings.vacation']: # Write a vacation note. try: if data['mailSettings.vacen']: l1 = open( "/var/spool/mail/vacation/%s@%s.db" % (user, self.domain), 'w') l2 = open( "/var/spool/mail/vacation/%s@%s.log" % (user, self.domain), 'w') l3 = open( "/var/spool/mail/vacation/%s@%s.txt" % (user, self.domain), 'w') l1.write('') l2.write('') else: l3 = open( "/var/spool/mail/vacation/DISABLED%s@%s.txt" % (user, self.domain), 'w') l3.write(data['mailSettings.vacation'].encode("utf-8")) # Update permissions runLater.append( 'chown www-data:root /var/spool/mail/vacation/*; chmod a+rw /var/spool/mail/vacation/*' ) except Exception, e: print "Error ", e, " in vacation" if not data['mailSettings.vacation'] or not data[ 'mailSettings.vacen']: # if vacation is disabled or blank. for vacFile in vacFiles: if os.path.exists(vacFile): os.remove(vacFile) if data['mailSettings.vacen']: try: os.remove("/var/spool/mail/vacation/DISABLED%s@%s.txt" % (user, self.domain)) except: pass if data['mailSettings.vacvalidity']: d = data['mailSettings.vacvalidity'] n = open( '/var/spool/mail/vacation/%s@%s.validity' % (self.cid, self.domain), 'wt') n.write(str(d)) n.close() # Send this to Thebe (Unless this call is Thebe invoked..) if self.handler: try: ser = WebUtils.serialiseUser(newRecord, self.domain) mail = "%s@%s" % (user, self.domain) self.handler.sendMessage(self.handler.master.hiveName, "user:%s:%s" % (mail, ser)) except: pass if moveUser: runLater.append( 'mv /var/spool/mail/%s\@%s /var/spool/mail/%s\@%s' % (self.cid, self.domain, user, self.domain)) if Settings.sambaDN and self.domain == Settings.defaultDomain: if moveUser: runLater.append('mv /home/%s /home/%s' % (self.cid, user)) runLater.append( 'mv /var/lib/samba/profiles/%s /var/lib/samba/profiles/%s' % (self.cid, user)) runLater.append('/etc/init.d/nscd restart') runLater.append( '/usr/local/tcs/tums/configurator --exim; /etc/init.d/exim4 restart' ) runLater.append( '/usr/local/tcs/tums/configurator --ftp; /etc/init.d/vsftpd restart' ) defs = [] #Process UserExtsions if self.commitUserExtensions(form, data): defs.append(restartAsterisk()) def ReturnPage(_): return url.root.child('Users').child('Edit').child( self.domain).child(user).child('Completed') for cmd in runLater: defs.append(WebUtils.system(cmd)) return defer.DeferredList(defs).addCallback(ReturnPage)
def testAddress(self, addr): def eximbt(res): print res return unicode(res) return WebUtils.system("exim -bt %s" % addr.encode('ascii')).addCallback(eximbt)
def restartAsterisk(): return WebUtils.system(Settings.BaseDir + "/configurator --debzaptel; " + Settings.BaseDir + '/configurator --pbx; /etc/init.d/asterisk reload')
def formValidated(newRecord, oldRecord): l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o='+Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass) dc = "%s,%s,o=%s" % (Settings.LDAPPeople, LDAP.domainToDC(self.domain), Settings.LDAPBase) moveUser = False if newRecord['uid'][0].lower() != oldRecord['uid'][0].lower(): # Rename first l.rename_s('uid='+self.cid+','+dc, 'uid='+newRecord['uid'][0]) self.cid = newRecord['uid'][0] newRecord['mail'] = ['%s@%s' % (newRecord['uid'][0], self.domain)] newRecord['mailMessageStore'] = ['/var/spool/mail/%s@%s' % (newRecord['uid'][0], self.domain)] if Settings.sambaDN and self.domain==Settings.defaultDomain: newRecord['homeDirectory'] = ['/home/%s' % newRecord['uid'][0]] moveUser = True vacFiles = [ "/var/spool/mail/vacation/%s@%s.db" % (self.cid, self.domain), "/var/spool/mail/vacation/%s@%s.log" % (self.cid, self.domain), "/var/spool/mail/vacation/%s@%s.txt" % (self.cid, self.domain) ] vpnCurrent = False for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (self.cid, self.domain) in i and "key" in i: vpnCurrent = True if data['userAccess.vpnEnabled'] and vpnCurrent == False: vdata = { 'name': "%s.%s" % (self.cid, self.domain), 'mail': "%s@%s" % (self.cid, self.domain), 'ip':None, 'mailKey':True } v = VPN.Page() v.text = self.text v.newCert(None, None, vdata) elif not data['userAccess.vpnEnabled'] and vpnCurrent == True: WebUtils.system('cd /etc/openvpn/easy-rsa/; source /etc/openvpn/easy-rsa/vars; /etc/openvpn/easy-rsa/revoke-full %s; rm /etc/openvpn/keys/%s.*' % ( "%s.%s" % (self.cid, self.domain), "%s.%s" % (self.cid, self.domain) )) address = "%s@%s" % (newRecord['uid'][0].lower(), self.domain) mailConf = self.sysconf.Mail if data['userPermissions.copyto']: if mailConf.get('copys', []): newCopys = [] for addr, dest in mailConf['copys']: if addr != address: newCopys.append((addr, dest)) newCopys.append((address, data['userPermissions.copyto'])) mailConf['copys'] = newCopys else: mailConf['copys'] = [(address, data['userPermissions.copyto'])] else: if mailConf.get('copys', []): newCopys = [] for addr, dest in mailConf['copys']: if addr != address: newCopys.append((addr, dest)) mailConf['copys'] = newCopys self.sysconf.Mail = mailConf if data['mailSettings.vacation']: # Write a vacation note. try: if data['mailSettings.vacen']: l1 = open("/var/spool/mail/vacation/%s@%s.db" % (self.cid, self.domain), 'w') l2 = open("/var/spool/mail/vacation/%s@%s.log" % (self.cid, self.domain), 'w') l3 = open("/var/spool/mail/vacation/%s@%s.txt" % (self.cid, self.domain), 'w') l1.write('') l2.write('') else: l3 = open("/var/spool/mail/vacation/DISABLED%s@%s.txt" % (self.cid, self.domain), 'w') l3.write(data['mailSettings.vacation'].encode("utf-8")) # Update permissions WebUtils.system('chown www-data:root /var/spool/mail/vacation/*; chmod a+rw /var/spool/mail/vacation/*') except Exception, e: print "Error ", e, " in vacation"
class editPage(Base.Page): addSlash = True userData = {} def __init__(self, avatarId=None, db=None, cid=None, domain = None, returns=None, *a, **ka): PageHelpers.DefaultPage.__init__(self, avatarId, db, *a, **ka) self.avatarId = avatarId self.cid = cid self.domain = domain self.returns = returns def form_editForm(self, data): domains = [] if self.avatarId.isAdmin: for i in self.flatFil: thisdom = i.split('dm=')[-1].split(',')[0] if not thisdom in domains: domains.append(thisdom) # Form population l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o='+Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass) dc = "%s,%s,o=%s" % (Settings.LDAPPeople, LDAP.domainToDC(self.domain), Settings.LDAPBase) userData = LDAP.getUsers(l, dc, 'uid='+self.cid) if not userData: l.unbind_s() return "Error" form = formal.Form(self.submitForm)[ formal.Group('userSettings')[ tags.div(_class="field")[ tags.label[self.text.userFormLabelEmailAddress], tags.div(id="emailAd", _class="inputs")[ "%s@%s"% (self.cid, self.domain) ] ], formal.Field('uid', formal.String(required=True), label = self.text.userFormLabelUsername), formal.Field('givenName', formal.String(required=True), label = self.text.userFormLabelName), formal.Field('sn', formal.String(), label = self.text.userFormLabelSurname), formal.Field('userPassword', formal.String(), formal.CheckedPassword, label= self.text.userFormLabelPass), ], formal.Group('mailSettings')[ formal.Field('mailForwardingAddress0', formal.String(), label=self.text.userFormLabelForward), formal.Field('mailForwardingAddress1', formal.String(), label=""), formal.Field('mailForwardingAddress2', formal.String(), label=""), formal.Field('mailForwardingAddress3', formal.String(), label=""), formal.Field('mailForwardingAddress4', formal.String(), label=""), formal.Field('mailForwardingAddress5', formal.String(), label=""), formal.Field('mailForwardingAddress6', formal.String(), label=""), formal.Field('mailForwardingAddress7', formal.String(), label=""), formal.Field('mailForwardingAddress8', formal.String(), label=""), formal.Field('mailForwardingAddress9', formal.String(), label=""), tags.div(_class="userLine")[tags.a(href="#", onclick="addForward();")[self.text.userFormLabelAddline]], formal.Field('mailAlternateAddress0', formal.String(), label=self.text.userFormLabelAlias), formal.Field('mailAlternateAddress1', formal.String(), label=""), formal.Field('mailAlternateAddress2', formal.String(), label=""), formal.Field('mailAlternateAddress3', formal.String(), label=""), formal.Field('mailAlternateAddress4', formal.String(), label=""), formal.Field('mailAlternateAddress5', formal.String(), label=""), formal.Field('mailAlternateAddress6', formal.String(), label=""), formal.Field('mailAlternateAddress7', formal.String(), label=""), formal.Field('mailAlternateAddress8', formal.String(), label=""), formal.Field('mailAlternateAddress9', formal.String(), label=""), tags.div(_class="userLine")[tags.a(href="#", onclick="addAlias();")[self.text.userFormLabelAddline]], formal.Field('vacen', formal.Boolean(), label = self.text.userFormLabelVacationActive, description=self.text.userFormTextVacationNote), formal.Field('vacation', formal.String(), formal.TextArea, label=self.text.userFormLabelVacation), ], formal.Group('userPermissions')[ formal.Field('employeeType', formal.Boolean(), label = self.text.userFormLabelWeb), formal.Field('accountStatus', formal.Boolean(), label = self.text.userFormLabelEmail), formal.Field('tumsAdmin', formal.Boolean(), label = self.text.userFormLabelAdmin), formal.Field('tumsUser', formal.Sequence(formal.String()), formal.widgetFactory(formal.CheckboxMultiChoice, [(i,i) for i in domains]), label = self.text.userFormLabelDomainAdmin), formal.Field('tumsReports', formal.Boolean(), label = self.text.userFormLabelReports), formal.Field('copyto', formal.String(), label = self.text.userFormLabelCopy, description = self.text.userFormTextCopy) ], formal.Group('userAccess')[ formal.Field('vpnEnabled', formal.Boolean(), label = self.text.userFormLabelVPN, description = self.text.userFormTextVPN), formal.Field('ftpEnabled', formal.Boolean(), label = self.text.userFormLabelFTP, description = self.text.userFormTextFTP), formal.Field('ftpGlobal', formal.Boolean(), label = self.text.userFormLabelGlobalFTP, description = self.text.userFormTextGlobal) ] ] form.addAction(self.submitForm) tData = copy.deepcopy(userData[0]) tData['userSettings.uid'] = tData['uid'][0] tData['userSettings.givenName'] = tData.get('givenName', [""])[0] tData['userSettings.sn'] = tData.get('sn', [""])[0] if tData.get('loginShell'): if '/bin/bash' in tData['loginShell']: tData['userAccess.ftpEnabled'] = True if self.sysconf.FTP.get('globals'): if tData['uid'][0] in self.sysconf.FTP['globals']: tData['userAccess.ftpGlobal'] = True tData['userSettings.userPassword'] = '' # Strip password address = "%s@%s" % (tData['uid'][0], self.domain) for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (self.cid, self.domain) in i and "key" in i: tData['userAccess.vpnEnabled'] = True if self.sysconf.Mail.get('copys', []): for addr, dest in self.sysconf.Mail['copys']: if addr == address: tData['userPermissions.copyto'] = dest if userData[0].get('accountStatus', False): tData['userPermissions.accountStatus'] = True else: tData['userPermissions.accountStatus'] = False if userData[0].get('mailForwardingAddress', False): for cnt,address in enumerate(userData[0]['mailForwardingAddress']): tData['mailSettings.mailForwardingAddress%s' % cnt] = address if userData[0].get('mailAlternateAddress', False): for cnt,address in enumerate(userData[0]['mailAlternateAddress']): tData['mailSettings.mailAlternateAddress%s' % cnt] = address emp = userData[0].get('employeeType', [False]) if 'squid' in emp: tData['userPermissions.employeeType'] = True else: tData['userPermissions.employeeType'] = False if 'tumsAdmin' in emp: tData['userPermissions.tumsAdmin'] = True else: tData['userPermissions.tumsAdmin'] = False if 'tumsReports' in emp: tData['userPermissions.tumsReports'] = True else: tData['userPermissions.tumsReports'] = False if emp[0]: for i in emp: if 'tumsUser[' in i: tData['userPermissions.tumsUser'] = i.split('[')[-1].split(']')[0].split(',') try: vac = open("/var/spool/mail/vacation/%s@%s.txt" % (self.cid, self.domain), 'r') tData['mailSettings.vacation'] = vac.read() tData['mailSettings.vacen'] = True except: pass # No vacation note try: vac = open("/var/spool/mail/vacation/DISABLED%s@%s.txt" % (self.cid, self.domain), 'r') tData['mailSettings.vacation'] = vac.read() tData['mailSettings.vacen'] = False except: pass # No disabled note either. form.data = tData l.unbind_s() return form def validateFormData(self, dc, data, newRecord): newRecord['uid'] = [data['userSettings.uid'].encode("utf-8").lower()] sn = data['userSettings.sn'] or u"" if sn: newRecord['sn'] = [sn.encode("utf-8")] else: newRecord['sn'] = [" "] shell = '/bin/false' if data['userAccess.ftpEnabled']: shell = '/bin/bash' if Settings.sambaDN and self.domain==Settings.defaultDomain: newRecord['loginShell'] = [shell] uid = data['userSettings.uid'].encode("utf-8").lower() if data['userAccess.ftpGlobal']: ftp = self.sysconf.FTP if ftp.get('globals', None): if uid not in ftp['globals']: ftp['globals'].append(uid) else: ftp['globals'] = [uid] self.sysconf.FTP = ftp else: ftp = self.sysconf.FTP newGlobals = [] globals = ftp.get('globals', []) for id in globals: if id != uid: newGlobals.append(id) ftp['globals'] = newGlobals self.sysconf.FTP = ftp # Disable password change date if data.get('sambaPwdMustChange'): del data['sambaPwdMustChange'] if data.get('sambaPwdLastSet'): data['sambaPwdLastSet'] = [str(int(time.time()))] if data['userSettings.givenName']: newRecord['givenName'] = [data['userSettings.givenName'].encode("utf-8")] else: newRecord['givenName'] = [data['userSettings.uid'].encode("utf-8").capitalize()] newRecord['cn'] = ["%s %s" % (newRecord['givenName'][0], sn.encode("utf-8"))] newRecord['employeeType'] = [] if data['userPermissions.employeeType']: newRecord['employeeType'].append('squid') if data.get('userPermissions.tumsAdmin', None): newRecord['employeeType'].append('tumsAdmin') elif data.get('userPermissions.tumsUser', None): tuenc = 'tumsUser[%s]' % ','.join(data['userPermissions.tumsUser']) newRecord['employeeType'].append(tuenc.encode()) if data.get('userPermissions.tumsReports', None): newRecord['employeeType'].append('tumsReports') if data['userPermissions.accountStatus']: newRecord['accountStatus'] = [ 'active' ] elif newRecord.get('accountStatus',False): del newRecord['accountStatus'] mFA = [] for i in xrange(10): if data['mailSettings.mailForwardingAddress%s' % i]: ad = data['mailSettings.mailForwardingAddress%s' % i].replace(' ', '').replace('\r','') if ad: mFA.append(ad) if mFA: newRecord['mailForwardingAddress'] = [ le.encode() for le in mFA ] else: try: del newRecord['mailForwardingAddress'] except: pass mAA = [] for i in xrange(10): if data['mailSettings.mailAlternateAddress%s' % i]: ad = data['mailSettings.mailAlternateAddress%s' % i].replace(' ', '').replace('\r','') if ad: mAA.append(ad) if mAA: newRecord['mailAlternateAddress'] = [ le.encode().strip('\r') for le in mAA ] else: try: del newRecord['mailAlternateAddress'] except: pass if data['userSettings.userPassword']: newRecord['userPassword'] = ["{SHA}"+LDAP.hashPassword(data['userSettings.userPassword'])] if Settings.sambaDN and self.domain==Settings.defaultDomain: newRecord['sambaLMPassword'] = Utils.createLMHash(data['userSettings.userPassword']) newRecord['sambaNTPassword'] = Utils.createNTHash(data['userSettings.userPassword']) return newRecord def submitForm(self, ctx, form, data): l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o='+Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass) dc = "%s,%s,o=%s" % (Settings.LDAPPeople, LDAP.domainToDC(self.domain), Settings.LDAPBase) oldRecord = LDAP.getUsers(l, dc, 'uid='+self.cid)[0] newRecord = copy.deepcopy(oldRecord) l.unbind_s() def failed(e): print 'Submmit on edit failed', e l.unbind_s() return url.root.child('Users').child('Edit').child(self.domain).child(self.cid).child('Failed') def formValidated(newRecord, oldRecord): l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o='+Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass) dc = "%s,%s,o=%s" % (Settings.LDAPPeople, LDAP.domainToDC(self.domain), Settings.LDAPBase) moveUser = False if newRecord['uid'][0].lower() != oldRecord['uid'][0].lower(): # Rename first l.rename_s('uid='+self.cid+','+dc, 'uid='+newRecord['uid'][0]) self.cid = newRecord['uid'][0] newRecord['mail'] = ['%s@%s' % (newRecord['uid'][0], self.domain)] newRecord['mailMessageStore'] = ['/var/spool/mail/%s@%s' % (newRecord['uid'][0], self.domain)] if Settings.sambaDN and self.domain==Settings.defaultDomain: newRecord['homeDirectory'] = ['/home/%s' % newRecord['uid'][0]] moveUser = True vacFiles = [ "/var/spool/mail/vacation/%s@%s.db" % (self.cid, self.domain), "/var/spool/mail/vacation/%s@%s.log" % (self.cid, self.domain), "/var/spool/mail/vacation/%s@%s.txt" % (self.cid, self.domain) ] vpnCurrent = False for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (self.cid, self.domain) in i and "key" in i: vpnCurrent = True if data['userAccess.vpnEnabled'] and vpnCurrent == False: vdata = { 'name': "%s.%s" % (self.cid, self.domain), 'mail': "%s@%s" % (self.cid, self.domain), 'ip':None, 'mailKey':True } v = VPN.Page() v.text = self.text v.newCert(None, None, vdata) elif not data['userAccess.vpnEnabled'] and vpnCurrent == True: WebUtils.system('cd /etc/openvpn/easy-rsa/; source /etc/openvpn/easy-rsa/vars; /etc/openvpn/easy-rsa/revoke-full %s; rm /etc/openvpn/keys/%s.*' % ( "%s.%s" % (self.cid, self.domain), "%s.%s" % (self.cid, self.domain) )) address = "%s@%s" % (newRecord['uid'][0].lower(), self.domain) mailConf = self.sysconf.Mail if data['userPermissions.copyto']: if mailConf.get('copys', []): newCopys = [] for addr, dest in mailConf['copys']: if addr != address: newCopys.append((addr, dest)) newCopys.append((address, data['userPermissions.copyto'])) mailConf['copys'] = newCopys else: mailConf['copys'] = [(address, data['userPermissions.copyto'])] else: if mailConf.get('copys', []): newCopys = [] for addr, dest in mailConf['copys']: if addr != address: newCopys.append((addr, dest)) mailConf['copys'] = newCopys self.sysconf.Mail = mailConf if data['mailSettings.vacation']: # Write a vacation note. try: if data['mailSettings.vacen']: l1 = open("/var/spool/mail/vacation/%s@%s.db" % (self.cid, self.domain), 'w') l2 = open("/var/spool/mail/vacation/%s@%s.log" % (self.cid, self.domain), 'w') l3 = open("/var/spool/mail/vacation/%s@%s.txt" % (self.cid, self.domain), 'w') l1.write('') l2.write('') else: l3 = open("/var/spool/mail/vacation/DISABLED%s@%s.txt" % (self.cid, self.domain), 'w') l3.write(data['mailSettings.vacation'].encode("utf-8")) # Update permissions WebUtils.system('chown www-data:root /var/spool/mail/vacation/*; chmod a+rw /var/spool/mail/vacation/*') except Exception, e: print "Error ", e, " in vacation" if not data['mailSettings.vacation'] or not data['mailSettings.vacen']: # if vacation is disabled or blank. for vacFile in vacFiles: try: os.remove(vacFile) except: pass if data['mailSettings.vacen']: try: os.remove("/var/spool/mail/vacation/DISABLED%s@%s.txt" % (self.cid, self.domain)) except: pass # Send this to Thebe (Unless this call is Thebe invoked..) if self.handler: try: ser = WebUtils.serialiseUser(newRecord, self.domain) mail = "%s@%s" % (self.cid, self.domain) self.handler.sendMessage(self.handler.master.hiveName, "user:%s:%s" % (mail, ser)) except: pass # Check if there are any LDAP changes to worry about change = False for k,v in newRecord.items(): if v != oldRecord.get(k, []): print k,v, oldRecord.get(k, []) change = True break # Now update LDAP tree if there were changes if change: try: l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o='+Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass) LDAP.modifyElement(l, 'uid='+self.cid+','+dc, oldRecord, newRecord) except Exception, e: print e, " LDAP issue in modify" l.unbind_s() return url.root.child('Users').child('Edit').child(self.domain).child(self.cid).child('Failed') l.unbind_s() try: if moveUser: WebUtils.system('mv /var/spool/mail/%s\@%s /var/spool/mail/%s\@%s' % ( oldRecord['uid'][0], self.domain, newRecord['uid'][0], self.domain )) if Settings.sambaDN and self.domain==Settings.defaultDomain: if moveUser: WebUtils.system('mv /home/%s /home/%s' % (oldRecord['uid'][0], newRecord['uid'][0])) WebUtils.system('mv /var/lib/samba/profiles/%s /var/lib/samba/profiles/%s' % (oldRecord['uid'][0], newRecord['uid'][0])) WebUtils.system('/etc/init.d/nscd restart') WebUtils.system('/usr/local/tcs/tums/configurator --exim; /etc/init.d/exim4 restart') WebUtils.system('/usr/local/tcs/tums/configurator --ftp; /etc/init.d/vsftpd restart') print "Complete" return url.root.child('Users').child('Edit').child(self.domain).child(self.cid).child('Completed') except Exception, e: print e, " after LDAP change in User" return url.root.child('Users').child('Edit').child(self.domain).child(self.cid).child('Failed')
def get_openvpn_settings(*sysconf): """ Get settings out of openvpn """ def callCompleted(status, routes): nr = [] for ro in routes.split('\n'): if ro.strip('\n'): nr.append(ro.strip()) routes = nr del nr try: confFile = open('/etc/openvpn/vpn.conf', 'rt') except: confFile = [""] activeRoutes = [] conf = {'mtu': '1400'} rc = status vpnstat = "" for i in rc.split('\n'): if vpnInit in i: vpnstat = i if "openvpn" in vpnstat: conf['openvpn'] = True for i in confFile: line = i.strip('\n') if "route" in line: # Activate a route and add it to the list if not there route = line.split('"')[1].split() tr = "%s %s" % (route[1], route[2]) activeRoutes.append(tr.strip()) if not tr in routes: routes.append(tr.strip()) if "server-bridge" in line: ips = line.split() conf['iprange1'] = ips[3] conf['iprange2'] = ips[4] if "dhcp-option" in line: sp = line.replace('"', '').split() conf[sp[2]] = sp[3] if "proto" in line: if "tcp" in line: conf['tcp'] = True conf['routes'] = activeRoutes return conf, routes def getRc(routes): rc = WebUtils.system(Settings.BaseDir + '/syscripts/rcStatus.py') return rc.addBoth(callCompleted, routes) return WebUtils.system( "route -n | grep -E \"(eth|tun|tap)\" | grep -v \"G\" | awk '{print $1 \" \" $3}'" ).addBoth(getRc)
def submitForm(self, ctx, form, data): name = data['name'] WebUtils.system('smbldap-useradd -w %s$; smbpasswd -a -m %s$' % (name, name)) return url.root.child('Computers')
def locateChild(self, ctx, segments): req = inevow.IRequest(ctx) headers = req.received_headers print headers, req.client # Lets play find the host! host = headers.get('x-forwarded-for', req.client.host) detail = req.args if segments[0] == "login": if not detail.get('username'): return Portal(self.host, self.url, "Username not provided"), () if not detail.get('password'): return Portal(self.host, self.url, "Password not provided"), () user = detail['username'][0] passw = detail['password'][0] def returnAuth(res): # Trace back our topology and find our closest interface to this host iface, zone, network, routed = Utils.traceTopology( self.sysconf, host) ipserv = self.sysconf.EthernetDevices[iface]['ip'].split( '/')[0] print res, user, passw, ipserv, iface, zone, network, routed, host if res: print "Ok bitch" # Add our record to the zone def done(mac): print "User has this MAC", mac l = open('/tmp/caportal/%s' % host, 'wt') l.write("%s|%s|%s" % (time.time(), mac.strip('\n'), user)) l.close() os.chmod('/tmp/caportal/%s' % host, 0777) print "Resturning person to ", segments #return url.URL.fromString('http://%s' % ('/'.join(segments[1:]))) return RefreshTo(url='http://%s' % ('/'.join(segments[1:]))) def next(_): print "Added shorewall, going to ARP check" return WebUtils.system( "arp -n | grep %s | awk '{print $3}'" % host).addBoth(done) return WebUtils.system( 'shorewall add %s:%s c%s' % (iface, host, zone)).addBoth(next), () print "Invalid authentication from", user, ":", repr(res) return Portal(self.host, self.url, "Invalid username or password."), () #return url.URL.fromString('http://%s:9682/myvulani/%s' % (ipserv, '/'.join(segments[1:]))), () # Check for active directory def gotADAuth(res): return returnAuth("OK" in res) if self.sysconf.ProxyConfig.get('adauth', None): if self.sysconf.ProxyConfig.get('addom', None): basedn = str.join(',', [ "dc=" + str(dfrag) for dfrag in self.sysconf.ProxyConfig.get( 'addom', str).split('.') ]) adInfo = { 'basedn': basedn, 'ldapuser': self.sysconf.ProxyConfig.get('adldapuser', ""), 'ldappass': self.sysconf.ProxyConfig.get('adldappass', ""), 'adserver': self.sysconf.ProxyConfig.get('adserver', "") } cmd = "/usr/lib/squid/ldap_auth -R -b \"%(basedn)s\" -D \"%(ldapuser)s\" -w \"%(ldappass)s\" -f sAMAccountName=%%s -h %(adserver)s -p389" % adInfo else: cmd = "/usr/lib/squid/msnt_auth" return WebUtils.system("echo %s %s | %s" % (user, passw, cmd)).addBoth(gotADAuth) else: auth = self.radauth.authenticateUser(user, passw) return returnAuth(auth) if not self.url: return Portal(None, segments), () return Portal(self.host, self.url), ()
def submitForm(self, ctx, form, data): if data['ipAlias']: aliases = data['ipAlias'].encode().replace(' ', '').split(';') else: aliases = [] if data['ip']: ip = data['ip'].strip().encode() else: ip = "" if data['dhcp']: type = "dhcp" else: type = "static" if data['netmask']: network = data['netmask'].strip().encode() elif data['ip']: # make a foney /24 network if we don't know wtf is going on network = '.'.join(ip.split('.')[:3]) + '.0/24' else: # ok we're just boned, save and carry on network = "" iFaces = copy.deepcopy(self.sysconf.EthernetDevices) thisIf = iFaces[self.iface] thisIf['dhcpserver'] = data['dhcpserver'] thisIf['type'] = type thisIf['ip'] = ip thisIf['network'] = network thisIf['aliases'] = aliases if data.get('ipv6', False): thisIf['ipv6'] = data['ipv6'].encode() thisIf['ipv6adv'] = data['ipv6adv'] iFaces[self.iface] = thisIf self.sysconf.EthernetDevices = iFaces if os.path.exists('/etc/debian_version'): WebUtils.system(Settings.BaseDir + '/configurator --debnet') else: WebUtils.system(Settings.BaseDir + '/configurator --net') WebUtils.system('/etc/init.d/net.%s restart' % self.iface) # Perform shorewall configuration shoreWall = copy.deepcopy(self.sysconf.Shorewall) shoreWall['zones'][ data['firewallZone']]['policy'] = data['firewallPolicy'] # check the interface isn't there ifaceZone = shoreWall['zones'][data['firewallZone']]['interfaces'] # Primary LAN interface should be defined with LAN Primary dhcp = "" if self.iface == self.sysconf.LANPrimary: dhcp = "dhcp" for cnt, iface in enumerate(ifaceZone): if self.iface in iface: del shoreWall['zones'][data['firewallZone']]['interfaces'][cnt] shoreWall['zones'][data['firewallZone']]['interfaces'].append( '%s detect %s' % (self.iface, dhcp)) # Delete interface from other zones for zone in shoreWall['zones']: if zone != data['firewallZone']: ifaceDefs = [] for i in shoreWall['zones'][zone]['interfaces']: if self.iface not in i: ifaceDefs.append(i) shoreWall['zones'][zone]['interfaces'] = ifaceDefs self.sysconf.Shorewall = shoreWall WebUtils.system(Settings.BaseDir + '/configurator --shorewall') WebUtils.system('shorewall restart') return url.root.child('Network')
def locateChild(self, ctx, segs): if segs[0]=="DelQos": index = int(segs[1]) conf = self.sysconf.Shorewall try: del conf['qos'][index] except: print "Unable to delete ", index self.sysconf.Shorewall = conf WebUtils.system('/usr/local/tcs/tums/configurator --shorewall') return url.root.child('Firewall'), () if segs[0]=="Delete": if segs[1] == 'Zone': Utils.log.msg('%s deleted firewall zone %s' % (self.avatarId.username, segs[2])) k = self.sysconf.Shorewall if segs[2] in k.get('zones', {}): del k['zones'][segs[2]] self.sysconf.Shorewall = k elif segs[1] == "AIP": Utils.log.msg('%s deleted firewall rule %s' % (self.avatarId.username, segs[2])) k = self.sysconf.Shorewall del k['rules'][int(segs[2])] self.sysconf.Shorewall = k elif segs[1] == "NAT": Utils.log.msg('%s deleted firewall nat rule %s' % (self.avatarId.username, segs[2])) src = segs[2] runum = int(segs[3]) k = self.sysconf.Shorewall del k['masq'][src][runum] self.sysconf.Shorewall = k elif segs[1] == "SNAT": Utils.log.msg('%s deleted firewall snat rule %s' % (self.avatarId.username, segs[2])) # convert rule number runum = int(segs[2]) k = self.sysconf.Shorewall # Delete the offending rule del k['snat'][runum] # Save the config self.sysconf.Shorewall = k else: Utils.log.msg('%s deleted firewall rule (2) %s' % (self.avatarId.username, segs[1])) self.rules.deleteRule(segs[1], int(segs[2])) return url.root.child('Firewall'), () if segs[0] == "Swap": # Swap two rules k = self.sysconf.Shorewall Utils.log.msg('%s swapped firewall rules %s and %s' % (self.avatarId.username, repr(k['rules'][int(segs[1])]), repr(k['rules'][int(segs[2])])) ) trule = k['rules'][int(segs[1])] k['rules'][int(segs[1])] = k['rules'][int(segs[2])] k['rules'][int(segs[2])] = trule self.sysconf.Shorewall = k return url.root.child('Firewall'), () if segs[0]=="Restart": self.restartShorewall() return url.root.child('Firewall'), () return rend.Page.locateChild(self, ctx, segs)
def getRc(routes): rc = WebUtils.system(Settings.BaseDir + '/syscripts/rcStatus.py') return rc.addBoth(callCompleted, routes)
def reloadSquid(_, result): # Call configurator to reconfigure squid d = WebUtils.system('/usr/sbin/squid -k reconfigure > /dev/null 2>&1') return d.addCallback(lambda _: result)
def set_openvpn(sysconf, data, callback): """ Reconfigura the standard VPN""" defs = [] if data['openvpn']: # Enable vpn defs.append(WebUtils.system('update-rc.d %s defaults' % vpnInit)) else: defs.append(WebUtils.system('update-rc.d %s defaults' % vpnInit)) # Allow it in the firewall fw = sysconf.Shorewall if not fw['zones'].get('loc', False): # No loc zone, so make one fw['zones']['loc'] = {'policy': 'ACCEPT', 'interfaces': [], 'log': ''} # Add the openvpn interface to the loc zone if 'tap0' not in fw['zones']['loc']['interfaces']: fw['zones']['loc']['interfaces'].append('tap0') sysconf.Shorewall = fw # Save the config options servIp = '.'.join(data['iprange1'].split('.') [:3]) + '.1' # Take the IP network and /24 server is .1 # Allow through Exim m = sysconf.Mail servRange = '.'.join(data['iprange1'].split('.')[:3]) + '.0/24' if m.get('relay-from'): m['relay-from'].append(servRange) else: m['relay-from'] = [servRange] sysconf.Mail = m ip1 = data['iprange1'] # Make sure people don't put the IP range on top of the server address:( i1segs = ip1.split('.') if int(i1segs[-1]) == 1: i1segs[-1] = "2" ip1 = '.'.join(i1segs) ip2 = data['iprange2'] if data['tcp']: proto = "tcp" else: proto = "udp" confData = """dev tap0 proto %s port 1194 ifconfig-pool-persist /etc/openvpn/vpn_pool client-config-dir /etc/openvpn/vpn-ccd/ keepalive 10 120 client-to-client tls-timeout 300 comp-lzo verb 3 persist-key persist-tun status /var/log/vpn-status.log ca /etc/openvpn/keys/ca.crt cert /etc/openvpn/keys/vpn.crt key /etc/openvpn/keys/vpn.key dh /etc/openvpn/keys/dh1024.pem crl-verify /etc/openvpn/keys/crl.pem server-bridge %s 255.255.255.0 %s %s ifconfig %s 255.255.255.0 """ % (proto, servIp, ip1, ip2, servIp) if data['routes']: for ro in data['routes']: confData += 'push "route %s"\n' % (ro, ) for i in ['DNS', 'WINS', 'DOMAIN']: if data[i]: confData += 'push "dhcp-option %s %s"\n' % (i, data[i]) confFile = open('/etc/openvpn/vpn.conf', 'wt') confFile.write(confData) confFile.close() def Continue(_): def returnB(_): return WebUtils.system( '/usr/local/tcs/tums/configurator --shorewall; shorewall restart' ).addBoth(callback) if data['openvpn']: return WebUtils.system('/etc/init.d/%s restart' % vpnInit).addBoth(returnB) else: return WebUtils.system('/etc/init.d/%s stop' % vpnInit).addBoth(returnB) return defer.DeferredList(defs).addBoth(Continue)
def flushObject(self, name): def flushDb(ret): return self.db[4].deleteFile(name) return WebUtils.system('rm -rf /var/lib/samba/updates/%s' % sha.sha(name).hexdigest()).addBoth(flushDb)
def returnB(_): return WebUtils.system( '/usr/local/tcs/tums/configurator --shorewall; shorewall restart' ).addBoth(callback)
def submitKey(self, ctx, f, data): # Generate an SSH key return WebUtils.system('rm /root/.ssh/identity; rm /root/.ssh/identity.pub; ssh-keygen -b 1024 -t rsa -N "" -C v2 -f /root/.ssh/identity').addBoth( lambda _: url.root.child('HA') )
def revoke_certificate(name): c = 'cd /etc/openvpn/easy-rsa/; source /etc/openvpn/easy-rsa/vars;' c += '/etc/openvpn/easy-rsa/revoke-full %s; rm /etc/openvpn/keys/%s.*' % ( name, name) return WebUtils.system(c)
def reloadAndReturn(self): return WebUtils.system( '/usr/local/tcs/tums/configurator --nut; /etc/init.d/nut restart' ).addBoth(lambda _: url.root.child('UPS'))
def returnB(_): return WebUtils.system('/etc/init.d/openvpn restart').addBoth(callback)
def submitForm(self, ctx, form, data): print data l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o='+Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass) dc = "%s,%s,o=%s" % (Settings.LDAPPeople, LDAP.domainToDC(self.avatarId.domains[0]), Settings.LDAPBase) oldRecord = LDAP.getUsers(l, dc, 'uid='+self.avatarId.username)[0] newRecord = copy.deepcopy(oldRecord) if data['mailForwardingAddress']: fA = [] for le in data['mailForwardingAddress'].split('\n'): ad = le.replace(' ', '').replace('\r','') if ad: fA.append(ad) newRecord['mailForwardingAddress'] = [ le.encode() for le in fA ] elif newRecord.get('mailForwardingAddress', False): del newRecord['mailForwardingAddress'] def gotNTHash(res): (LM, NT) = tuple(res.strip('\n').split()) if data['userPassword']: newRecord['userPassword'] = ["{SHA}"+LDAP.hashPassword(data['userPassword'])] if Settings.sambaDN and self.avatarId.domains[0]==Settings.defaultDomain: newRecord['sambaNTPassword'] = [NT] newRecord['sambaLMPassword'] = [LM] vacFiles = [ "/var/spool/mail/vacation/%s@%s.db" % (self.avatarId.username, self.avatarId.domains[0]), "/var/spool/mail/vacation/%s@%s.log" % (self.avatarId.username, self.avatarId.domains[0]), "/var/spool/mail/vacation/%s@%s.txt" % (self.avatarId.username, self.avatarId.domains[0]) ] if data['vacation']: # Write a vacation note. try: if data['vacen']: l1 = open("/var/spool/mail/vacation/%s@%s.db" % (self.avatarId.username, self.avatarId.domains[0]), 'w') l2 = open("/var/spool/mail/vacation/%s@%s.log" % (self.avatarId.username, self.avatarId.domains[0]), 'w') l3 = open("/var/spool/mail/vacation/%s@%s.txt" % (self.avatarId.username, self.avatarId.domains[0]), 'w') l1.write('') l2.write('') else: l3 = open("/var/spool/mail/vacation/DISABLED%s@%s.txt" % (self.avatarId.username, self.avatarId.domains[0]), 'w') l3.write(data['vacation'].encode('utf-8')) WebUtils.system('chown www-data:root /var/spool/mail/vacation/*; chmod a+r /var/spool/mail/vacation/*') except Exception, e: print e, " in vacation" return url.root.child('Settings').child('Failed') if not data['vacation'] or not data['vacen']: for vacFile in vacFiles: try: os.remove(vacFile) except: pass try: LDAP.modifyElement(l, 'uid='+self.avatarId.username+','+dc, oldRecord, newRecord) if Settings.sambaDN and self.avatarId.domains[0]==Settings.defaultDomain: WebUtils.system('/etc/init.d/nscd restart') return url.root.child('Settings').child('Completed') except Exception, e: print e, " in last mod" return url.root.child('Settings').child('Failed')
def submitForm(self, ctx, form, data): if data['ipAlias']: aliases = data['ipAlias'].encode("ascii", "replace").replace(' ', '').split(',') else: aliases = [] if data['ip']: ip = data['ip'].strip().encode("ascii", "replace") else: ip = "" if data['dhcp']: type = "dhcp" else: type = "static" if data['netmask']: network = data['netmask'].strip().encode("ascii", "replace") elif data['ip']: # make a foney /24 network if we don't know wtf is going on network = '.'.join(ip.split('.')[:3]) + '.0/24' else: # ok we're just boned, save and carry on network = "" iFaces = copy.deepcopy(self.sysconf.EthernetDevices) thisIf = iFaces.get(self.iface, {}) thisIf['dhcpserver'] = data['dhcpserver'] thisIf['type'] = type thisIf['ip'] = ip # set the defualt route routes = thisIf.get('routes', []) rDict = dict(routes) if data['gateway']: fGateway = data['gateway'].encode("ascii", "replace") # Remove any other default routes because one is set here for dev, conf in self.sysconf.EthernetDevices.items(): if dev == self.iface: # Skip configured interface here continue oldRoutes = conf.get('routes', []) newRoutes = [] skip = True for dst, gw in oldRoutes: if dst == "default": skip = False continue newRoutes.append((dst, gw)) if not skip: iFaces[dev]['routes'] = newRoutes else: fGateway = "" if fGateway: rDict['default'] = fGateway elif rDict.get('default'): del rDict['default'] newRoutes = [i for i in rDict.items()] if newRoutes: thisIf['routes'] = newRoutes elif thisIf.get('routes'): del thisIf['routes'] # Continue config thisIf['network'] = network thisIf['aliases'] = aliases if (data['mtu'] > 1200) and (data['mtu'] < 1501): thisIf['mtu'] = data['mtu'] if data.get('ipv6', False): thisIf['ipv6'] = data['ipv6'].encode("ascii", "replace") thisIf['ipv6adv'] = data['ipv6adv'] iFaces[self.iface] = thisIf self.sysconf.EthernetDevices = iFaces lp = self.sysconf.LANPrimary newLP = lp if data['interior']: if self.iface not in lp: newLP.append(self.iface) self.sysconf.LANPrimary = newLP else: if self.iface in lp: newLP = [] for k in lp: if k != self.iface: newLP.append(k) self.sysconf.LANPrimary = newLP # Perform shorewall configuration shoreWall = copy.deepcopy(self.sysconf.Shorewall) shoreWall['zones'][ data['firewallZone']]['policy'] = data['firewallPolicy'] # check the interface isn't there ifaceZone = shoreWall['zones'][data['firewallZone']]['interfaces'] for cnt, iface in enumerate(ifaceZone): if self.iface in iface: del shoreWall['zones'][data['firewallZone']]['interfaces'][cnt] shoreWall['zones'][data['firewallZone']]['interfaces'].append( '%s detect dhcp,routeback' % (self.iface)) # Delete interface from other zones for zone in shoreWall['zones']: if zone != data['firewallZone']: ifaceDefs = [] for i in shoreWall['zones'][zone]['interfaces']: if self.iface not in i: ifaceDefs.append(i) shoreWall['zones'][zone]['interfaces'] = ifaceDefs self.sysconf.Shorewall = shoreWall # Clear old aliases out of system oldAliases = self.sysconf.EthernetDevices.get(self.iface, {}).get('aliases', []) for addr in oldAliases: if addr not in aliases: WebUtils.system('ip addr del %s dev %s' % (i, self.iface)) WebUtils.restartNetworking(data['dhcpserver']) return url.root.child('Network')