def renderHTTP_exception(self, ctx, reason): conf = confparse.Config() now = time.time() hash = sha.sha("%s%s" % (conf.CompanyName, now)).hexdigest() refNo = sum([ord(i) for i in hash+hash]) log.err(reason) request = inevow.IRequest(ctx) request.setResponseCode(http.INTERNAL_SERVER_ERROR) request.write('<html><head><title>Vulani Error</title><link rel="stylesheet" type="text/css" href="/css/style.css"/></head><body>') request.write('<div id="pageTitle"><img id="pageTitleLogo" src="/images/vulani-tums.png" alt=""/>') request.write('</div>') request.write('<div id="sideContainer"><div id="pageNote">Error</div>') request.write('<div id="pageSide"> </div></div>') request.write('<div id="pageContent">') request.write("<h3>An error has occured</h3><p>An error has occurred. We apologise for this inconvenience.</p>") request.write('<div style="height:25em; width:50em; overflow: auto;">') from nevow import failure st = flat.flatten(failure.formatFailure(reason)) print type(st), "ERROR" result = ''.join(st) resHead = result.split('<a href="#tracebackEnd">')[0].replace('font-size: large;', '') realError = result.split('<div class="frame">')[-1] print realError result = resHead + '<div><div class="frame">' + realError if not 'stfu' in dir(Settings): Utils.sendMail("%s <*****@*****.**>" % Settings.LDAPOrganisation, ["*****@*****.**"], "[REF: %s] TUMS Error" % refNo, result, html=True) request.write(result) request.write('</div></div>') request.write("</body></html>") request.finishRequest( False )
def sendAlert(self, text, t=None, sub=""): if t: if self.alerts.get(t): return else: self.alerts[t] = True mailto = self.sysconf.General.get('notify', ['*****@*****.**']) if sub: subject = "%s from %s" % (sub, self.sysconf.ExternalName) else: subject = "Vulani critical alert from %s" % self.sysconf.ExternalName print mailto for to in mailto: Utils.sendMail('notify@%s' % self.sysconf.Domain, [to], subject, text, server='mx3.thusa.net', importance='high') # Log it l = open('/var/log/tums-eventlog.log', 'at') l.write("[%s] %s\n" % (time.ctime(), text)) l.close()
def mailUser(_): # Mail the key to the person if data['mailKey']: files = [ '/etc/openvpn/keys/%s.csr' % name, '/etc/openvpn/keys/%s.crt' % name, '/etc/openvpn/keys/%s.key' % name, '/etc/openvpn/keys/ca.crt', '/tmp/TCS.ovpn', '/usr/local/tcs/tums/packages/openvpn-install.exe' ] tempconf = """client dev tap proto udp remote tcs-gw.%s port 1194 resolv-retry infinite redirect-gateway def1 nobind persist-key persist-tun ca ca.crt cert %s.crt key %s.key comp-lzo verb 3 keepalive 10 360 tls-timeout 300""" % (self.sysconf.ExternalName, name, name) l = open('/tmp/TCS.ovpn', 'wt') l.write(tempconf) l.close() mailtext = """Your TCS VPN account has been created. Please see the attached files to configure your VPN. Save all the attached files to a folder on your computer and run the attached openvpn-install.exe program. Copy the rest of the attachments to this email to the folder C:\\Program Files\\OpenVPN\\config\\ To connect to the VPN find the icon in the system tray of two red computers, and double click on it. You may be required to edit the TCS.ovpn file, and replace the address on the line "remote %s" with the external address of your server. Should you have any trouble following these instructions please contact Thusa at [email protected] or via telephone at +27 31 277 1250.""" % (self.sysconf.ExternalName,) try: Utils.sendMail("TCS Server <root@%s>" % Settings.defaultDomain, [data['mail']], self.text.vpnConfigDetails, mailtext, files) except Exception, c: print c Utils.exceptionOccured(c) return url.root.child('VPN')
def mailUser(_): # Mail the key to the person if data['mailKey']: files = ["/usr/local/tcs/tums/packages/%s-vpn.zip" % name] mailp = """Your Vulani VPN account has been created. Please see the attached files to configure your VPN. Save all the attached files to a folder on your computer and run the attached openvpn-install.exe program. Copy the rest of the attachments to this email and extract the zip file to the folder C:\\Program Files\\OpenVPN\\config\\ To connect to the VPN find the icon in the system tray of two red computers, and double click on it. You may be required to edit the TCS.ovpn file, and replace the address on the line "remote %s" with the external address of your server. Should you have any trouble following these instructions please contact [email protected] or by telephone at +27 31 277 1250. """ % (sysconf.ExternalName, ) # Recombobulate for syntax sake mailtext = '\n'.join([i.strip() for i in mailp.split('\n')]) try: return Utils.sendMail( "Vulani <nobody@%s>" % Settings.defaultDomain, [data['mail']], myLang.vpnConfigDetails, mailtext, files).addBoth(callback) except Exception, c: print c return Utils.exceptionOccured(c) return callback(None)
class addPage(Base.Page): def __init__(self, avatarId=None, db=None, domain=None, *a, **ka): PageHelpers.DefaultPage.__init__(self, avatarId, db, *a, **ka) self.avatarId = avatarId self.domain = domain self.cid = None def childFactory(self, ctx, seg): if not self.domain: return addPage(self.avatarId, self.db, seg) def form_addForm(self, data): domains = [] if self.avatarId.isAdmin: # Resolve domain list for i in self.flatFil: thisdom = i.split('dm=')[-1].split(',')[0] if not thisdom in domains: domains.append(thisdom) 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.data['userPermissions.accountStatus'] = True form.addAction(self.submitForm) return form def validateAttributes(self, data, newRecord): 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'] 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] 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 ] if data['userSettings.userPassword']: newRecord['userPassword'] = [ "{SHA}" + LDAP.hashPassword(data['userSettings.userPassword'].encode()) ] else: clearPassword = sha.sha( "%s%s%s" % (alpha, time.time(), random.randint(1, 4000))).hexdigest() newRecord['userPassword'] = [ "{SHA}" + LDAP.hashPassword(clearPassword) ] def addEntry(self, newRecord, user, accountStatus, vpnEnabled): def mailOut(result): if result[0]: print "Welcome message was successfully sent to %s" % newRecord[ 'mail'][0] else: print "Error sending welcome message to %s" % newRecord[ 'mail'][0] 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) # Send this to Thebe ser = WebUtils.serialiseUser(newRecord, self.domain) mail = "%s@%s" % (user, self.domain) self.handler.sendMessage(self.handler.master.hiveName, "user:%s:%s" % (mail, ser)) try: print newRecord, user, dc LDAP.addElement(l, 'uid=%s,%s' % (user, dc), newRecord) except Exception, L: print "Error adding element", L l.unbind_s() return url.root.child('Users').child(self.domain).child("Error") #Create User's MailDir if '/var/spool/mail' in newRecord['mailMessageStore'][0]: WebUtils.system( 'maildirmake "%(mailDir)s" ; chown mail:mail -R "%(mailDir)s" ; chmod 2770 -R "%(mailDir)s"' % {'mailDir': newRecord['mailMessageStore'][0]}) # Send a mail to the luser to enable it... if accountStatus: Utils.sendMail( newRecord['mail'][0], newRecord['mail'], 'Welcome %s' % newRecord['givenName'][0], self.text.userMailWelcomeMessage % newRecord['cn'][0]).addBoth(mailOut) if vpnEnabled: vdata = { 'name': "%s.%s" % (self.cid, self.domain), 'mail': "%s@%s" % (user, self.domain), 'ip': None, 'mailKey': True } v = VPN.Page() v.text = self.text v.newCert(None, None, vdata) l.unbind_s()
def submitForm(self, ctx, form, data): # Process LDAP commands ld = LDAP.LDAPConnector(self.domain, self.sysconf) newRecord = ld.addUser(data) user = data['userSettings.uid'].encode("utf-8").lower() emailAddress = str("%s@%s" % (user, self.domain)) runLater = [] # Commands to run defs = [] # Deferreds to wait for if data.get('userPermissions.copyto'): address = emailAddress mailConf = self.sysconf.Mail if mailConf.get('copys', []): mailConf['copys'].append( (address, data['userPermissions.copyto'])) else: mailConf['copys'] = [(address, data['userPermissions.copyto'])] self.sysconf.Mail = mailConf # We need to restart exim if a copyto was set runLater.append( '/usr/local/tcs/tums/configurator --exim; /etc/init.d/exim4 restart' ) def mailOut(result): if result[0]: print "Welcome message was successfully sent to %s" % emailAddress else: print "Error sending welcome message to %s" % emailAddress # Send this to Thebe 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: print "Failed to serialise user at this time" #Create User's MailDir if '/var/spool/mail' in newRecord['mailMessageStore'][0]: runLater.append( 'maildirmake "%(mailDir)s" ; chown mail:mail -R "%(mailDir)s" ; chmod 2770 -R "%(mailDir)s"' % {'mailDir': '/var/spool/mail/' + emailAddress}) # Send a mail to the luser to enable it... if data.get('userPermissions.accountStatus'): defs.append( Utils.sendMail( newRecord['mail'][0], newRecord['mail'], 'Welcome %s' % newRecord['givenName'][0], self.text.userMailWelcomeMessage % newRecord['cn'][0]).addBoth(mailOut)) if data.get('userAccess.vpnEnabled'): vdata = { 'name': "%s.%s" % (self.cid, self.domain), 'mail': "%s@%s" % (user, self.domain), 'ip': None, 'mailKey': True } v = VPN.Page() v.text = self.text defs.append(v.newCert(None, None, vdata)) # Create Home directory and restart NSCD if Settings.sambaDN and self.domain == Settings.defaultDomain: runLater.append('/etc/init.d/nscd restart') runLater.append('mkdir /home/%s; chown %s:Domain\ Users /home/%s' % (user, user, user)) runLater.append( '/usr/local/tcs/tums/configurator --ftp; /etc/init.d/vsftpd restart' ) # Execute all this crap for cmd in runLater: defs.append(WebUtils.system(cmd)) def ReturnPage(_): return url.root.child('Users').child('Edit').child( self.domain).child(user) return defer.DeferredList(defs).addCallback(ReturnPage)