def __init__(self, avatarId = None, deleter = lambda _:None, post_delete = lambda _: None, *a, **k): formal.ResourceMixin.__init__(self, *a, **k) rend.Page.__init__(self, *a, **k) self.avatarId = avatarId self.sysconf = confparse.Config() self.deleter = deleter self.post_delete = post_delete
def writeConfig(self, *a): Strings = "CompanyName ExternalName Hostname Domain SambaDomain LDAPBase LDAPPassword WANPrimary " Strings += "ThusaDNSUsername ThusaDNSPassword ThusaDNSAddress NTP SMTPRelay LocalRoute" Dicts = "EthernetDevices WANDevices Shorewall SambaConfig SambaShares ProxyConfig Mail Shaping DHCP Failover Tunnel BGP FTP RADIUS General" Lists = "LANPrimary ForwardingNameservers TCSAliases LocalDomains ShorewallBalance ShorewallSourceRoutes" Lists += " ProxyAllowedHosts ProxyAllowedDestinations ProxyAllowedDomains ProxyBlockedDomains ShaperRules" newConf = self.checkType(Strings, str, "string (\"\")", "") newConf += self.checkType(Lists, list, "list ([])", []) newConf += self.checkType(Dicts, dict, "dictionary ({})", {}) conf = newConf # Rewrite the config file (format will be nasty) l = open('/usr/local/tcs/tums/config.py', 'wt') #l = open('config.py', 'wt') l.write(conf) l.close() os.system( 'cat /usr/local/tcs/tums/runningProfile | xargs --replace=% cp /usr/local/tcs/tums/config.py /usr/local/tcs/tums/profiles/%' ) self.thisUpgrade() # Permissions checks os.system('chmod a+x /usr/local/tcs/tums/syscripts/*') # Ditch stupid logrotate files os.system('rm /etc/logrotate.d/*.ucf-dist >/dev/null 2>&1') # Update our cron script os.system('/usr/local/tcs/tums/configurator -f /etc/cron.d/tums') # patches to configuration file c = confparse.Config() g = c.General if not g.get('diskalert', None): g['diskalert'] = { '/': 90, '/var': 90, } c.General = g lp = c.LANPrimary if not isinstance(lp, list): c.LANPrimary = [lp] else: lp = lp[0] eth = c.EthernetDevices if not eth[lp].get('dhcpserver'): eth[lp]['dhcpserver'] = True c.EthernetDevices = eth # Write our special proxy errors os.system( 'cp -a /usr/local/tcs/tums/packages/squid/* /usr/share/squid/errors/English/' ) os.system('chmod a+r /usr/share/squid/errors/English/*')
def __init__(self, host=None, url=[], error=None, *a): self.radauth = Auth.RadiusLDAPAuthenticator() rend.Page.__init__(self, *a) self.host = host self.url = url self.error = error self.sysconf = confparse.Config()
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 __init__(self, avatarId = None, db = None, *a, **k): mods = athena.jsDeps.mapping mods[self.moduleName] = Settings.BaseDir+'/scripts/'+self.moduleScript athena.LivePage.__init__(self, jsModules = athena.JSPackage(mods)) self.avatarId = avatarId self.db = db self.lockStatus, self.lockTime, self.lockUser = isLocked() self.sysconf = confparse.Config() self.render_userBar = render_userBar
def __init__(self): self.config = confparse.Config() self.lanNetwork = '.'.join(self.config.EthernetDevices[ self.config.LANPrimary]['ip'].split('.')[:2]) + '.' self.db = Database.AggregatorDatabase() self.portCache = {} self.lastSeen = [] self.sourcesSeen = {} reactor.callLater(60, self.persistFlows) print "[NetFlowCollector] Working with LAN: ", self.lanNetwork
def locateChild(self, ctx, segments): sysconf = confparse.Config() req = inevow.IRequest(ctx) host = req.received_headers.get('x-forwarded-for', req.client.host) # Trace back our topology and find our closest interface to this host iface, zone, network, routed = Utils.traceTopology(sysconf, host) ipserv = sysconf.EthernetDevices[iface]['ip'].split('/')[0] return url.URL.fromString('http://%s:9682/myvulani/%s' % (ipserv, '/'.join(segments))), ()
def __init__(self, handler, tstat): self.loops = {} self.tstat = tstat self.handler = handler self.alerts = {} self.lastClam = "" self.sysconf = confparse.Config() self.thivechecker = None self.iftraf = {} # Running totals self.ifdisp = {} # Last value
def __init__(self, avatarId = None, db = None, *a, **k): formal.ResourceMixin.__init__(self, *a, **k) rend.Page.__init__(self, *a, **k) self.avatarId = avatarId self.db = db self.sysconf = confparse.Config() try: self.text = db[2] self.handler = db[3] except: print "Failed to get i18l module"
def upgradeRules(): """Upgrades the configuration rules, runs on instantiation of the firewall interface""" rulesParser = Rules() config = confparse.Config() #List of rules to automatically remove removeList = [ 'Ping/ACCEPT all all', 'AllowICMPs all all', 'ACCEPT all all udp 33434:33463', ] """ Parse Rules.read() split AIP to rules PROXY to redirect FORWARD to dnat """ curRules = config.Shorewall.get('rules', []) shw = config.Shorewall #Temp firewall rules parsedRules = rulesParser.read() def copyRules(parsedRulesIn, outPut, ruleNameFilter=None): if ruleNameFilter: newOut = [] for k, curRule in enumerate(outPut): if curRule[1].split()[0] == ruleNameFilter: newOut.append(curRule) outPut = newOut for rule in parsedRulesIn: try: if rule[-1] in parsedRules[ 'UPGRADERULETAG'] or not ruleNameFilter: ruleData = curRules[rule[ -1]] #This should only run for PROXY FORWARD and DNAT if the rule was marked as an upgrade else: continue except: print "Bad Rule: %s" % str(rule) continue if ruleData[1] not in removeList: outPut.append(ruleData) return outPut shw["rules"] = copyRules(parsedRules['AIP'], []) shw["redirect"] = copyRules(parsedRules['PROXY'], config.Shorewall.get('redirect', []), "REDIRECT") shw["dnat"] = copyRules(parsedRules['FORWARD'], config.Shorewall.get('dnat', []), "DNAT") config.Shorewall = shw #Overwrite the config
def test_duplicates(self): c = confparse.Config() eth = c.EthernetDevices.items() routeStack = None for dev, configs in eth: for dst, gw in configs.get('routes', []): if dst == "default": assert (routeStack == None) routeStack = dev return True
def __init__(self, avatarId = None, db = None, *a, **k): formal.ResourceMixin.__init__(self, *a, **k) rend.Fragment.__init__(self, *a, **k) self.avatarId = avatarId self.db = db self.sysconf = confparse.Config() self.render_userBar = render_userBar self.lockStatus, self.lockTime, self.lockUser = isLocked() try: self.text = db[2] self.handler = db[3] except: print "Failed to get i18l module"
def __init__(self): self.config = confparse.Config() self.lanNetworks = [ i for k, i in Utils.getLanNetworks(self.config).items() ] #self.lanNetwork = '.'.join(self.config.EthernetDevices[self.config.LANPrimary]['ip'].split('.')[:2]) + '.' self.db = Database.AggregatorDatabase() self.portCache = {} # Cache for service lookups self.lastSeen = [] self.sourcesSeen = {} self.itime = 60 # 60 is good self.rtime = 5 * 60 # 5*60 is good reactor.callLater(self.itime, self.persistFlows) print "[NetFlowCollector] Working with LANs: ", self.lanNetworks
def thive_setOption(self, messageId, params, data): """ Called when we get a setOption command params : [BaseParameter, Configurator command, Init.d script] data: Base parameter set handler (executed in-line) - should act on configBase """ conf = confparse.Config() configBase = getattr(conf, params[0]) exec data # Persist the operation setattr(conf, params[0], configBase) self.sendMessage(self.master.hiveName, 'OK', messageId)
def render_root(self, ctx, data): req = inevow.IRequest(ctx) host = req.client.host # Pull out our config - requests to here should be minimised to reduce disk thrash sysconf = confparse.Config() authority = sysconf.General.get('infoserv', {}).get('authorized', []) bsvr = [] # branch server container for k in sysconf.Mail.get('branches', []): if isinstance(k, list): bsvr.append(k[0]) else: bsvr.append(k) authority.extend(bsvr) if host in authority: return ctx.tag[self.allowed(host)] else: return ctx.tag[self.denied(host)]
def __init__(self, avatarId, db, day=None, month=None, year=None, entry=None, view=None, index=0, *a, **kw): self.DB = db[5]['telDB'] if not month: today = datetime.datetime.now() self.month = today.month self.year = today.year self.day = 0 else: self.month = month self.year = year if day: if day > 0: self.day = day else: self.day = 0 self.view = view self.entry = entry self.sysconf = confparse.Config() self.updateNames() try: self.index = int(index) except: self.index = 0 Reports.Page.__init__(self, avatarId, db, *a, **kw)
def __init__(self, *a, **kw): super(ClusterFragment, self).__init__(*a, **kw) self.sysconf = confparse.Config()
def __init__(self, avatarId): super(calendarFragment, self).__init__() self.sysconf = confparse.Config() self.db = Database.CalendarDatabase() self.avatarId = avatarId
class Rules: rules = confparse.Config() parsedRules = {} def deleteRule(self, type, num): rules = "/etc/shorewall/rules" fi = open(rules) ri = fi.read().split('\n') rules = self.rules.Shorewall ri = copy.deepcopy(rules.get('rules', [])) fi.close() self.read() ro = [] thisRule = self.parsedRules[type][num] if type == "AIP": for l in ri: if "ACCEPT" in l[1] and thisRule[0] in l[1] and thisRule[ 1] in l[1]: pass else: ro.append([l[0], l[1]]) elif type == "APORT": for l in ri: rS = l[1].split() if len(rS) > 4 and rS[0] == "ACCEPT" and rS[1] == thisRule[ 0] and rS[3] == thisRule[1] and rS[4] == thisRule[ 2] and thisRule[3] in l[1]: pass else: ro.append([l[0], l[1]]) elif type == "FORWARD": for l in ri: if "DNAT" in l[1] and thisRule[0] in l[1] and thisRule[1] in l[ 1] and thisRule[2] in l[1] and thisRule[3] in l[1]: pass else: ro.append([l[0], l[1]]) elif type == "PROXY": for l in ri: if "REDIRECT" in l[1] and thisRule[0] in l[1] and thisRule[ 1] in l[1] and thisRule[2] in l[1] and thisRule[ 3] in l[1] and thisRule[4] in l[1]: pass else: ro.append([l[0], l[1]]) else: return if ro: # some protection from blanking the rules rules['rules'] = ro self.rules.Shorewall = rules def buildRule(self, type, *cont): if type == "AIP": rule = "ACCEPT %s:%s all" % (cont[0], cont[1]) elif type == "APORT": rule = "ACCEPT %s all %s %s" % (cont[0], cont[1], cont[2]) if cont[3]: rule += " - %s" % cont[3] elif type == "PROXY": rule = "REDIRECT loc%s %s %s %s - %s" % ( cont[0] or "", # Optional ip exclusion (source) cont[1], # destination port cont[2], # protocol cont[3], # catch port cont[4], # exclusion destination range ) elif type == "FORWARD": if cont[3].strip(): dstport = ":%s" % cont[3].strip() else: dstport = "" rule = "DNAT net loc:%s %s %s - %s" % ( cont[0] + dstport, cont[1], cont[2] or "-", cont[4] or " ", ) else: return None return rule def addRule(self, type, scont): rules = self.rules.Shorewall # ['rules'] if not scont: return if not rules.get('rules', []): rules['rules'] = [] rules['rules'].append([1, scont.encode()]) self.rules.Shorewall = copy.deepcopy(rules) def read(self): parsedRules = {'AIP': [], 'APORT': [], 'FORWARD': [], 'PROXY': []} for l in self.rules.Shorewall.get('rules', []): line = l[1] if line and l[0]: thisRule = line.split() type = thisRule[0] if type == "ACCEPT": if ":" in thisRule[1]: ip = thisRule[1].split(':')[-1] net = thisRule[1].split(':')[0] parsedRules['AIP'].append([net, ip]) else: if len(thisRule) > 4: # Enough parameters net = thisRule[1] dest = thisRule[2] proto = thisRule[3] port = thisRule[4] if len(thisRule) > 6: dest = thisRule[6] else: dest = "" parsedRules['APORT'].append( [net, proto, port, dest]) if type == "DNAT": if len(thisRule) > 5: destip = thisRule[2].split(':', 1)[-1] proto = thisRule[3] port = thisRule[4].strip('-') or "ANY" if len(thisRule) > 6: sourceip = thisRule[6] else: sourceip = "" parsedRules['FORWARD'].append( [destip, proto, port, sourceip]) if type == "REDIRECT": if ":" in thisRule[1]: source = thisRule[1].split(':')[-1] else: source = "" srcport = thisRule[4] dstport = thisRule[2] proto = thisRule[3] dest = thisRule[6] parsedRules['PROXY'].append( [source, srcport, dstport, proto, dest]) self.parsedRules = parsedRules return parsedRules
def parseNet(): """ Returns our configurator network information """ conf = confparse.Config() return conf.EthernetDevices
def __init__(self, *a, **kw): super(liveGraphFragment, self).__init__(*a, **kw) self.sysconf = confparse.Config()
def getUsername(ip): # Get the username for a specific IP at an instantaneous time # This does NOT give back stats if ip == "0.0.0.0": return "0.0.0.0" # Cache if os.path.exists('/tmp/ncache'): cache = open('/tmp/ncache') for i in cache: if ip in i: l = i.strip('\n').split(':') now = time.time() then = float(l[2]) if now < (then + 3600): return l[1] # Quickest, check CAPORTAL if os.path.exists('/tmp/caportal/%s' % ip): # We do have this l = open('/tmp/caportal/%s' % ip).read().split('|') if '@' in l[-1]: n = l[-1] else: import Settings n = '%s@%s' % (l[-1], Settings.defaultDomain) updateNCache(ip, n) return n sysconf = confparse.Config() if sysconf.DHCP.get('leases', {}).get(ip): return sysconf.DHCP.get('leases', {}).get(ip)[0] def parseNmb(lookup): l = lookup.strip('\n').strip() name = ip if l: name = l updateNCache(ip, l) return name def checkMail(mail): l = mail.strip('\n').strip() name = None if l: now = time.time() then = logToEpoch(' '.join(l.split()[:3])) if now < (then + 3600): # We can use the email address, yay n = l.split('user='******',')[0] return n return system( "nmblookup -A %s | grep '<00>' | grep -v '<GROUP>' | awk '{print $1}'" % ip).addBoth(parseNmb) def parseSamba(sessions): name = None for i in sessions.split('\n'): if ip in i: l = i.split('\\') name = l[1] updateNCache(ip, name) # immediate return return name # Find mail return system( "grep '@.*%s' /var/log/mail.log | grep 'LOGIN,' | tail -n 1" % ip).addBoth(checkMail) # Try samba return system('net status sessions parseable').addBoth(parseSamba)
def __init__(self, *a, **k): rend.Page.__init__(self, *a, **k) self.sysconf = confparse.Config()
def __init__(self): self.sysconf = confparse.Config()
def serialiseUser(detail, dom): vacation = "" vacEnable = False user, domain = detail['uid'][0], dom try: vac = open("/var/spool/mail/vacation/%s@%s.txt" % (user, domain), 'r') vacation = vac.read() vacEnable = True except: pass # No vacation note try: vac = open( "/var/spool/mail/vacation/DISABLED%s@%s.txt" % (user, domain), 'r') vacation = vac.read() except: pass # No disabled note either. serStruct = { 'domain': dom, 'name': detail['uid'][0], 'uid': detail.get('uidNumber', [1000])[0], 'gid': detail.get('gidNumber', [1000])[0], 'cn': detail.get('cn', [''])[0], 'sn': detail.get('sn', [''])[0], 'giveName': detail.get('givenName', [''])[0], 'emp': '+'.join(detail.get('employeeType', [])), # Can have multiple values here. 'password': detail.get('userPassword', [''])[0], 'mail': detail.get('mail', [''])[0], 'active': detail.get('accountStatus', [''])[0], 'pgSid': detail.get('sambaPrimaryGroupSID', [''])[0], 'samSid': detail.get('sambaSID', [''])[0], 'ntPass': detail.get('sambaNTPassword', [''])[0], 'lmPass': detail.get('sambaLMPassword', [''])[0], 'mailForward': '+'.join(detail.get('mailForwardingAddress', [])), 'mailAlias': '+'.join(detail.get('mailAlternateAddress', [])), 'vacation': vacation, 'vacEnable': vacEnable } # Construct our flags. flags = [] # Order is important from here on thisFlag = False for i in os.listdir('/etc/openvpn/keys/'): if "%s.%s" % (serStruct['name'], dom) in i and "key" in i: thisFlag = True flags.append(thisFlag) # FTP Enabled thisFlag = False if detail.get('loginShell'): if '/bin/bash' in detail['loginShell'][0]: thisFlag = True flags.append(thisFlag) # We need a config parser sysconf = confparse.Config() thisFlag = False # FTP Global if sysconf.FTP.get('globals'): if serStruct['name'] in sysconf.FTP['globals']: thisFlag = True flags.append(thisFlag) address = "%s@%s" % (serStruct['name'], dom) copyto = "" if sysconf.Mail.get('copys', []): for addr, dest in sysconf.Mail['copys']: if addr == address: copyto = dest flagSer = "" for i in flags: flagSer += i and '-' or '_' flagSer += "+" + copyto serStruct['flags'] = flagSer x = "" for k, v in serStruct.items(): x += "%s:%s`" % (k, v) return x
def __init__(self, *a, **kw): athena.LiveFragment.__init__(self, *a, **kw) self.sysconf = confparse.Config()
class Rules: rules = confparse.Config() parsedRules = {} def deleteRule(self, type, num): #XXX XXX XXX Remove # Pick the dataset to add this rule to if type == "FORWARD": rarea = 'dnat' elif type == "PROXY": rarea = 'redirect' else: rarea = 'rules' rules = self.rules.Shorewall ri = copy.deepcopy(rules.get(rarea, [])) del ri[num] rules[rarea] = ri self.rules.Shorewall = rules def buildRule(self, type, *cont): if type == "AIP": rule = "ACCEPT %s:%s all" % (cont[0], cont[1]) elif type == "APORT": rule = "ACCEPT %s all %s %s" % (cont[0], cont[1], cont[2]) if cont[3]: rule += " - %s" % cont[3] elif type == "PROXY": rule = "REDIRECT %s%s %s %s %s - %s" % ( cont[0], cont[1] or "", # Optional ip exclusion (source) cont[2], # destination port cont[3], # protocol cont[4], # catch port cont[5], # exclusion destination range ) elif type == "FORWARD": if cont[3].strip(): dstport = ":%s" % cont[3].strip() else: dstport = "" if cont[7].strip(): source = ":%s" % cont[7].strip() else: source = "" rule = "DNAT %s%s %s:%s %s %s - %s" % ( cont[5], source, cont[6], cont[0] + dstport, cont[1], cont[2] or "-", cont[4] or " ", ) else: return None return rule def addRule(self, type, scont): rules = self.rules.Shorewall # ['rules'] if not scont: return # Pick the dataset to add this rule to if type == "FORWARD": rarea = 'dnat' elif type == "PROXY": rarea = 'redirect' else: rarea = 'rules' if not rules.get(rarea, []): rules[rarea] = [] rules[rarea].append([1, scont.encode('ascii', 'replace')]) self.rules.Shorewall = copy.deepcopy(rules) def read(self): def parseRule(rule): # pad and split each of these, making sure we have sufficient params or nones src = rule[1] + ':Any:Any:' src = src.split(':') srczone = src[0].replace('all', 'Any') srcip = src[1] srcport = src[2] dst = rule[2] + ':Any:Any:' dst = dst.split(':') dstzone = dst[0].replace('all', 'Any') dstip = dst[1] #dstport = dst[2] myrule = ['Any' for i in range(4)] for i, v in enumerate(rule[3:]): myrule[i] = v if myrule[2] != "Any": srcport = myrule[2] if myrule[3] != "Any": dstip = myrule[3] return [ type, srczone, srcip, srcport, dstzone, dstip, myrule[0], myrule[1], rulecnt ] def parseForward(rule): destz = rule[1].split(':', 1)[0] if ':' in rule[1]: source = rule[1].split(':', 1)[-1] else: source = "Any" tzone = rule[2].split(':', 1)[0] destip = rule[2].split(':', 1)[-1] proto = rule[3] port = rule[4].strip('-') or "ANY" if len(rule) > 6: sourceip = rule[6] else: sourceip = "" return [ destz, source, destip, tzone, proto, port, sourceip, rulecnt ] def parseRedirect(rule): if ":" in rule[1]: source = rule[1].split(':')[-1] zone = rule[1].split(':')[0] else: source = "" zone = rule[1] srcport = rule[4] dstport = rule[2] proto = rule[3] if len(rule) > 6: dest = rule[6] else: dest = "-" return [zone, source, srcport, dstport, proto, dest, rulecnt] parsedRules = { 'AIP': [], 'APORT': [], 'FORWARD': [], 'PROXY': [], 'UPGRADERULETAG': [], #Stop Repeating rule problem } rulecnt = 0 for l in self.rules.Shorewall.get('rules', []): line = l[1] if line and l[0]: thisRule = line.split() type = thisRule[0] if type == "ACCEPT" or type == "REJECT": parsedRules['AIP'].append(parseRule(thisRule)) #Here for legacy reasons (You never know) if type == "DNAT": parsedRules['FORWARD'].append(parseForward(thisRule)) parsedRules['UPGRADERULETAG'].append(rulecnt) if type == "REDIRECT": parsedRules['PROXY'].append(parseRedirect(thisRule)) parsedRules['UPGRADERULETAG'].append(rulecnt) # increase rule count rulecnt += 1 rulecnt = 0 for l in self.rules.Shorewall.get('dnat', []): line = l[1] if line and l[0]: thisRule = line.split() type = thisRule[0] if type == "DNAT": parsedRules['FORWARD'].append(parseForward(thisRule)) # increase rule count rulecnt += 1 rulecnt = 0 for l in self.rules.Shorewall.get('redirect', []): line = l[1] if line and l[0]: thisRule = line.split() type = thisRule[0] if type == "REDIRECT": parsedRules['PROXY'].append(parseRedirect(thisRule)) # increase rule count rulecnt += 1 self.parsedRules = parsedRules return parsedRules
def __init__(self, db, file=None, *a, **kw): self.db = db self.file = file self.sysconf = confparse.Config() rend.Page.__init__(self, *a, **kw)
# import sqlalchemy as sa from sasync.database import AccessBroker, transact from datetime import datetime as dt import sha, time, datetime, os from twisted.internet import defer, reactor from Core import confparse import Settings from axiom.store import Store from axiom.item import Item from axiom.attributes import bytes, boolean, reference, integer, timestamp, AND from axiom.errors import ItemNotFound from axiom.upgrade import registerAttributeCopyingUpgrader, registerUpgrader conf = confparse.Config() class CalendarEntry(Item): typeName = 'db_caldate' schemaVersion = 1 # The FQ name of the entry owner (ie, [email protected]) owner = bytes() # All the bits of the date (easier to process chunks like this than a timestamp object) day = integer() month = integer() year = integer() # Start time
class Rules: rules = confparse.Config() parsedRules = {} def deleteRule(self, type, num): rules = "/etc/shorewall/rules" fi = open(rules) ri = fi.read().split('\n') rules = self.rules.Shorewall ri = copy.deepcopy(rules.get('rules', [])) fi.close() self.read() ro = [] thisRule = self.parsedRules[type][num] if type == "AIP": for l in ri: if "ACCEPT" in l[1] and thisRule[0] in l[1] and thisRule[ 1] in l[1]: pass else: ro.append([l[0], l[1]]) elif type == "APORT": for l in ri: rS = l[1].split() if len(rS) > 4 and rS[0] == "ACCEPT" and rS[1] == thisRule[ 0] and rS[3] == thisRule[1] and rS[4] == thisRule[ 2] and thisRule[3] in l[1]: pass else: ro.append([l[0], l[1]]) elif type == "FORWARD": for l in ri: if "DNAT" in l[1] and thisRule[0] in l[1] and thisRule[1] in l[ 1] and thisRule[2] in l[1] and thisRule[3] in l[1]: pass else: ro.append([l[0], l[1]]) elif type == "PROXY": for l in ri: if "REDIRECT" in l[1] and thisRule[0] in l[1] and thisRule[ 1] in l[1] and thisRule[2] in l[1] and thisRule[ 3] in l[1] and thisRule[4] in l[1]: pass else: ro.append([l[0], l[1]]) else: return if ro: # some protection from blanking the rules rules['rules'] = ro self.rules.Shorewall = rules def buildRule(self, type, *cont): if type == "AIP": rule = "ACCEPT %s:%s all" % (cont[0], cont[1]) elif type == "APORT": rule = "ACCEPT %s all %s %s" % (cont[0], cont[1], cont[2]) if cont[3]: rule += " - %s" % cont[3] elif type == "PROXY": rule = "REDIRECT %s%s %s %s %s - %s" % ( cont[0], cont[1] or "", # Optional ip exclusion (source) cont[2], # destination port cont[3], # protocol cont[4], # catch port cont[5], # exclusion destination range ) elif type == "FORWARD": if cont[3].strip(): dstport = ":%s" % cont[3].strip() else: dstport = "" if cont[7].strip(): source = ":%s" % cont[7].strip() else: source = "" rule = "DNAT %s%s %s:%s %s %s - %s" % ( cont[5], source, cont[6], cont[0] + dstport, cont[1], cont[2] or "-", cont[4] or " ", ) else: return None return rule def addRule(self, type, scont): rules = self.rules.Shorewall # ['rules'] if not scont: return if not rules.get('rules', []): rules['rules'] = [] rules['rules'].append([1, scont.encode()]) self.rules.Shorewall = copy.deepcopy(rules) def read(self): parsedRules = {'AIP': [], 'APORT': [], 'FORWARD': [], 'PROXY': []} rulecnt = 0 for l in self.rules.Shorewall.get('rules', []): line = l[1] if line and l[0]: thisRule = line.split() type = thisRule[0] if type == "ACCEPT" or type == "REJECT": # pad and split each of these, making sure we have sufficient params or nones src = thisRule[1] + ':Any:Any:' src = src.split(':') srczone = src[0].replace('all', 'Any') srcip = src[1] srcport = src[2] dst = thisRule[2] + ':Any:Any:' dst = dst.split(':') dstzone = dst[0].replace('all', 'Any') dstip = dst[1] #dstport = dst[2] myrule = ['Any' for i in range(4)] for i, v in enumerate(thisRule[3:]): myrule[i] = v if myrule[2] != "Any": srcport = myrule[2] if myrule[3] != "Any": dstip = myrule[3] thisRule = [ type, srczone, srcip, srcport, dstzone, dstip, myrule[0], myrule[1], rulecnt ] parsedRules['AIP'].append(thisRule) if type == "DNAT": destz = thisRule[1].split(':', 1)[0] if ':' in thisRule[1]: source = thisRule[1].split(':', 1)[-1] else: source = "Any" tzone = thisRule[2].split(':', 1)[0] destip = thisRule[2].split(':', 1)[-1] proto = thisRule[3] port = thisRule[4].strip('-') or "ANY" if len(thisRule) > 6: sourceip = thisRule[6] else: sourceip = "" parsedRules['FORWARD'].append([ destz, source, destip, tzone, proto, port, sourceip, rulecnt ]) if type == "REDIRECT": if ":" in thisRule[1]: source = thisRule[1].split(':')[-1] zone = thisRule[1].split(':')[0] else: source = "" zone = thisRule[1] srcport = thisRule[4] dstport = thisRule[2] proto = thisRule[3] if len(thisRule) > 6: dest = thisRule[6] else: dest = "-" parsedRules['PROXY'].append( [zone, source, srcport, dstport, proto, dest, rulecnt]) # increase rule count rulecnt += 1 self.parsedRules = parsedRules return parsedRules