Exemplo n.º 1
0
 def render_content(self, ctx, data):
     rules = self.rules.read()
     classes = self.classes.read()
     print rules
     return ctx.tag[
         Tools.Page.sideMenu(Tools.Page(None, self.db), ctx, data),
         tags.div(id="rightBlockIFrame")[tags.h2[tags.img(
             src="/images/firewall.png"), " Bandwidth Management"], [[
                 tags.fieldset[
                     tags.legend[r[6]], tags.h3["Class Details"],
                     tags.table(cellspacing=0, _class='listing')[tags.thead(
                         background="/images/gradMB.png")[tags.tr[
                             tags.th["Interface"], tags.th["Base Rate"],
                             tags.th["Maximum Rate"],
                             tags.th["Priority"]], ], tags.tbody[
                                 tags.tr[tags.td[r[0]], tags.td[r[2]],
                                         tags.td[r[3]], tags.td[r[4]]], ]],
                     tags.h3["Rules"],
                     tags.table(cellspacing=0, _class='listing')[tags.thead(
                         background="/images/gradMB.png")[tags.tr[
                             tags.th["Source IP"],
                             tags.th["Destination IP"], tags.th["Protocol"],
                             tags.th["Source Port"],
                             tags.th["Destination Port"]], ], tags.tbody[[
                                 tags.tr[tags.td[t[0] or "??"],
                                         tags.td[t[1] or "??"],
                                         tags.td[t[2] or "Any"],
                                         tags.td[t[3] or "Any"],
                                         tags.td[t[4] or "Any"], ]
                                 for t in rules.get(r[1], [])
                             ]]]], tags.br
             ] for r in classes], ]]
Exemplo n.º 2
0
 def returnMailLog(mail):
     if self.offset > 0:
         previousTag = tags.a(
             href=url.root.child("Mail").child(self.offset -
                                               20))["Previous 20"]
     else:
         previousTag = "Previous 20"
     return ctx.tag[
         #tags.div(id="rightBlockIFrame")[
         tags.h3[tags.img(src="/images/maillog.png"),
                 " Mail Logs"], previousTag,
         tags.a(href=url.root.child("Mail").child(self.offset +
                                                  20))["Next 20"],
         tags.br,
         tags.table(cellspacing=0, _class='listing')[tags.thead(
             background="/images/gradMB.png")[tags.tr[
                 tags.th["Date"], tags.th["From"], tags.th["To"],
                 tags.th["Size"], tags.th["Message ID"]]], tags.tbody[[
                     tags.tr[tags.td[time.ctime(m[2])], tags.td[m[5]],
                             tags.td[m[18]],
                             tags.td["%0.3f KB" %
                                     (float(m[11]) / 1024.0)],
                             tags.td[m[1]]] for m in mail
                 ]]], tags.br, previousTag,
         tags.a(href=url.root.child("Mail").child(self.offset +
                                                  20))["Next 20"],
         tags.br, tags.h3["Search Logs"],
         tags.invisible(render=tags.directive('form searchForm'))]
Exemplo n.º 3
0
 def __init__(self, other=None):
     super().__init__()
     self.other = other
     self.header = tags.thead()
     self.body = tags.tbody(border='1px solid black')
     self.tag = tags.table(border='1 px solid black')[self.header, self.body]
     self.functions = [self.setStyle]
Exemplo n.º 4
0
 def returnMailLog(mail):
     return ctx.tag[
             tags.h3[tags.img(src="/images/maillog.png"), " Mail Queue"],
             tags.br,
             tags.table(cellspacing=0, _class='listing')[
                 tags.thead(background="/images/gradMB.png")[
                     tags.tr[
                         tags.th["Date"],
                         tags.th["From"],
                         tags.th["To"],
                         tags.th["Subject"],
                         tags.th["Message ID"]
                     ]
                 ],
                 tags.tbody[
                     [tags.tr[
                             tags.td[time.ctime(m[3])],
                             tags.td[m[2] or ""],
                             tags.td[m[5] or ""],
                             tags.td[m[9] or ""],
                             tags.td[m[1] or ""]
                         ]
                     for m in mail]
                 ]
             ],
     ]
Exemplo n.º 5
0
def dataTable(headings, content, sortable = False, tabid=None):
    """ Produces a tabular listing which is either sortable or not. Sortable expects headings to be a 
        list of tuples, but if it is not a list of tuples the 'string' type will be assumed for every cell """
    if sortable:
        if isinstance(headings[0], tuple):
            header = [ tags.th(colformat=j)[i] for j,i in headings ]
        else:
            header = [ tags.th(colformat='istr')[i] for i in headings ]
        tclass = 'sortable'
    else:
        header = [ tags.th[i] for i in headings ]
        tclass = 'listing'

    if not content: 
        rows = tags.tr[ tags.td(colspan=len(headings))[tags.em["No entries."]]]
    else:
        rows = [tags.tr[ [tags.td[col] for col in row] ]
        for row in content]

    return tags.table(id = tabid, cellspacing=0,  _class=tclass)[
        tags.thead(background="/images/gradMB.png")[
            tags.tr[
                header
            ]
        ],
        tags.tbody[
            rows
        ]
    ]
Exemplo n.º 6
0
    def render_content(self, ctx, data):
        shares = self.sysconf.SambaShares

        return ctx.tag[
            tags.h2[tags.img(src="/images/sharefold.png"), " Shared folders"],
            tags.table(cellspacing="0", _class="listing")[
                tags.thead(background="/images/gradMB.png")[tags.tr[
                    tags.th['Shared Folder'], tags.th['Shared Path'],
                    tags.th['Comment'], tags.th['Writable'], tags.th['Public'],
                    tags.th['Permission'], tags.th[''], ]],
                tags.tbody[[
                    tags.tr[tags.td[share], [
                        tags.td[shares[share].get(i, None) or ""] for i in [
                            'path', 'comment', 'writable', 'public',
                            'valid users'
                        ]
                    ], tags.td[
                        tags.
                        a(href='Delete/%s/' % (share, ),
                          onclick
                          ="return confirm('Are you sure you want to delete this share?');"
                          )[tags.img(src="/images/ex.png")]]]
                    for share in shares.keys() if not share == "global"
                ]]], tags.h3["Add new share"],
            tags.directive('form addShare'), ]
Exemplo n.º 7
0
    def render_content(self, ctx, data):
        try:
            l = open(Settings.BaseDir+'/backup.dat')
        except:
            WebUtils.system('echo > %s/backup.dat' % Settings.BaseDir)
            l = []

        sets = []
        for i in l:
            if i.strip('\n'):
                dta = i.strip('\n').split('|')
                delmsg = "return confirm('%s');" % self.text.backupConfirmDelete
                if dta[6] =="True":
                    dta[6] = dta[7]
                    dta[7] = [
                        tags.img(src="/images/blankblock.png"), "  ",
                        tags.a(href="Delete/%s/" % (dta[0],), onclick = delmsg)[tags.img(src="/images/ex.png")]
                    ]

                else:
                    dta[6] = "No"
                    dta[7] = [
                        tags.a(href="Execute/%s/" % (dta[0],))[tags.img(src="/images/start.png")], "  ", 
                        tags.a(href="Delete/%s/" % (dta[0],), onclick = delmsg)[tags.img(src="/images/ex.png")]
                    ]

                dta[4] = [ [i, tags.br] for i in dta[4].split(';')]
                dta[2] = [ [i, tags.br] for i in dta[2].split(';')]

                del dta[0]
    
                sets.append(dta)
                
        return ctx.tag[
            tags.h2[tags.img(src="/images/netdrive.png"), self.text.backupSet],
            tags.table(cellspacing=0,  _class='listing')[
                tags.thead(background="/images/gradMB.png")[
                    tags.tr[
                        [ tags.th[i] for i in [
                            self.text.backupHeaderDescription, self.text.backupHeaderNotify, 
                            self.text.backupHeaderDevice, self.text.backupHeaderSource, 
                            self.text.backupHeaderDestination, self.text.backupHeaderAutomated, '']]
                    ]
                ],
                tags.tbody[
                [
                    tags.tr[ [tags.td[col] for col in row] ]
                for row in sets],
                ]
            ],
            tags.h3[self.text.backupCreateSet], 
            tags.directive('form addBackup')
        ]
Exemplo n.º 8
0
def dataTable(headings, content):
    return tags.table(cellspacing=0,  _class='listing')[
        tags.thead(background="/images/gradMB.png")[
            tags.tr[
                [ tags.th[i] for i in headings ]
            ]
        ],
        tags.tbody[
        [   
            tags.tr[ [tags.td[col] for col in row] ]
        for row in content],
        ]
    ]
Exemplo n.º 9
0
    def render_content(self, ctx, data):
        keys = [i for i in os.listdir('/etc/openvpn/keys/') if 'key' in i]

        keys.sort()
        for key in ['vpn.key', 'ca.key']:
            try:
                keys.remove(key)
            except:
                pass

        return ctx.tag[
                tags.h2[tags.img(src="/images/vpn.png"), self.text.vpnConfig],
                PageHelpers.TabSwitcher((
                    (self.text.vpnTabWindows, 'panelWindows'),
                    (self.text.vpnTabTCS, 'panelOpenVPN'),
                    (self.text.vpnTabUsers, 'panelVPNUsers')
                )),
                tags.div(id="panelWindows", _class="tabPane")[
                    tags.h3[self.text.vpnHeadingWindows],
                    tags.directive('form winForm'),
                ],
                tags.div(id="panelOpenVPN", _class="tabPane")[
                    tags.h3[self.text.vpnHeadingTCS],
                    tags.directive('form vpnForm'), tags.br,
                ],
                tags.div(id="panelVPNUsers", _class="tabPane")[
                    tags.h3[self.text.vpnHeadingTCSUsers],
                    tags.table(cellspacing=0,  _class='listing')[
                        tags.thead(background="/images/gradMB.png")[
                            tags.tr[
                                tags.th[self.text.vpnCertificateName],
                                tags.th[""],
                            ]
                        ],
                        tags.tbody[
                        [
                            tags.tr[
                                tags.td['.'.join(i.split('.')[:-1])],
                                tags.td[tags.a(href="Revoke/%s/" % '.'.join(i.split('.')[:-1]), onclick="return confirm('%s');" % self.text.vpnConfirmRevoke)[ 
                                    tags.img(src="/images/ex.png")]
                                ]
                            ]
                        for i in keys],
                        ]
                    ], tags.br,
                    tags.h3[self.text.vpnHeadingAddUser],
                    tags.directive('form addUser')
                ],
                PageHelpers.LoadTabSwitcher()
            ]
Exemplo n.º 10
0
 def returnMailLog(mail):
     return ctx.tag[
         tags.h3[tags.img(src="/images/maillog.png"),
                 " Mail Logs"], tags.br,
         tags.table(cellspacing=0, _class='listing')[tags.thead(
             background="/images/gradMB.png")[tags.tr[
                 tags.th["Date"], tags.th["From"], tags.th["To"],
                 tags.th["Size"], tags.th["Message ID"]]], tags.tbody[[
                     tags.tr[tags.td[time.ctime(m[2])], tags.td[m[5]],
                             tags.td[m[18]],
                             tags.td["%0.3f KB" %
                                     (float(m[11]) / 1024.0)],
                             tags.td[m[1]]] for m in mail
                 ]]], tags.br, ]
Exemplo n.º 11
0
 def render_editContent(self, ctx, data):
     if not self.avatarId.checkDomainPermissions(self.domain):
         return ctx.tag[
             "Not Authorised"
         ]
         
     if not self.group:
         l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o='+Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass)
         dc = "%s,o=%s" % (LDAP.domainToDC(self.domain), Settings.LDAPBase)
         groups = LDAP.getGroups(l, dc)
         l.unbind_s() 
         return ctx.tag[
             tags.h3["Groups"], 
             tags.table(cellspacing="0", _class="listing")[
                 tags.thead(background="/images/gradMB.png")[
                     tags.tr[
                         tags.th[self.text.userFormGroupName],
                         tags.th[''],
                     ]
                 ],
                 tags.tbody[
                     [ 
                         tags.tr[
                             tags.td[group[1]], 
                             tags.td[
                                 tags.a(href=url.root.child("Users").child('GroupMod').child(self.domain).child(group[1]))[
                                     self.text.userLinkEditMembership
                                 ]
                             ]
                         ]
                     for group in groups]
                 ]
             ],
             tags.a(href=url.root.child("Users").child('GroupAdd').child(self.domain))[self.text.userLinkCreateGroup]
         ]
     else:
         return ctx.tag[
             tags.h3["%s%s" % (self.text.userHeadingMemberships, self.group)],
             tags.directive('form editForm')
         ]
     return ctx.tag[
         tags.h3[self.text.userErrorUserPlayedWithLink],
     ]
Exemplo n.º 12
0
 def render_content(self, ctx, data):
     drives = self.getMaps()
     return ctx.tag[
         tags.h2[tags.img(src="/images/netdrive.png"), " Network Drives"],
         tags.table(cellspacing=0, width="95%", _class='listing')
         [tags.thead(background="/images/gradMB.png")[tags.tr[
             tags.th["Login Group"],
             tags.th["Drive Letter"], tags.th["Share Path"],
             tags.th[""], ]],
          tags.tbody[[
              tags.
              tr[tags.td[i[0]], tags.td[i[1]], tags.td[i[2]], tags.
                 td[tags.
                    a(href="Delete/%s/" % i[1],
                      onclick=
                      "return confirm('Are you sure you want to delete this drive?');"
                      )[tags.img(src="/images/ex.png")]]] for i in drives
          ], ]], tags.br, tags.h3["Add Network Drive"],
         tags.directive('form addDrive')]
Exemplo n.º 13
0
    def render_content(self, ctx, data):
        leases = self.sysconf.DHCP.get('leases', {})
        statics = []
        for ip, hostmac in leases.items():
            statics.append((ip, hostmac[0], hostmac[1]))

        statics.sort()

        sharenets = []
        for sharenet, defin in self.sysconf.DHCP.get('sharenets', {}).items():
            sharenets.append(
                (sharenet, defin['domain'],
                 self.sysconf.EthernetDevices[sharenet]['ip'],
                 tags.a(href="Delnet/%s/" %
                        sharenet)[tags.img(src="/images/ex.png")]))

        return ctx.tag[
            tags.h3[tags.img(src="/images/netdrive.png"), " DHCP"],
            PageHelpers.TabSwitcher((
                ('DHCP Settings', 'panelSettings'),
                ('Static Leases', 'panelLeases'),
                ('Shared Networks', 'panelAltnet'),
            )),
            tags.div(id="panelLeases", _class="tabPane")[
                tags.table(cellspacing=0, _class='listing')[tags.thead(
                    background="/images/gradMB.png")[tags.tr[
                        tags.th["IP Address"], tags.th["Hostname"],
                        tags.th["MAC Address"], tags.th[""], ]], tags.tbody[[
                            tags.tr[tags.td[i[0]], tags.td[i[1]],
                                    tags.td[i[2]], tags.td[tags.a(
                                        href="Delete/%s/" %
                                        i[0])[tags.img(src="/images/ex.png")]]]
                            for i in statics
                        ], ]], tags.br, tags.h3["Add Static Lease"],
                tags.directive('form addStatic')],
            tags.div(id="panelSettings", _class="tabPane"
                     )[tags.directive('form confDhcp')],
            tags.div(id="panelAltnet", _class="tabPane")[
                PageHelpers.dataTable(
                    ("Interface", "Domain", "Network", ""), sharenets),
                tags.h3["Add DHCP Network"],
                tags.directive('form addNet')],
            PageHelpers.LoadTabSwitcher()]
Exemplo n.º 14
0
    def render_content(self, ctx, data):
        interfaces = Utils.getInterfaces() + self.sysconf.EthernetDevices.keys(
        )
        params = Utils.parseNet()
        d = {}
        vlans = []
        routes = {}
        types = {}
        vali = []
        for i in interfaces:
            if not "vlan" in i:
                if i in d.keys():
                    pass
                if i in params.keys():
                    types[i] = params[i]['type']
                    routes[i] = [params[i].get('network', '')]
                    if params[i]['type'] == 'static':
                        d[i] = params[i]['ip']
                    if params[i]['type'] == 'manual':
                        d[i] = "Manual"
                    else:
                        d[i] = "DHCP"
                else:
                    types[i] = ""
                    routes[i] = ""
                    d[i] = ""
            else:
                vlans.append((i, params[i]['ip'],
                              tags.a(title="Edit Interface %s" % i,
                                     href="Edit/%s" %
                                     i)[tags.img(src="/images/edit.png")]))

        return ctx.tag[
            tags.h3[tags.img(src="/images/netdrive.png"), " Network Setup"],
            PageHelpers.TabSwitcher((('Interface Configuration', 'panelIface'),
                                     ('VLAN Configuration', 'panelVlan'),
                                     ('IPv6 Tunnel', 'panelTunnel'))),
            tags.div(id="panelIface", _class="tabPane")[
                tags.h3["Configured Interfaces"],
                tags.table(cellspacing="0", _class="listing")[tags.thead(
                    background="/images/gradMB.png")[tags.tr[
                        tags.th['Interface'], tags.th['DHCP'], tags.th['IP'],
                        tags.th['Associated Routes'],
                        tags.th[''], ]], tags.tbody[[
                            tags.tr[tags.td[i.replace('eth', 'Port ')],
                                    tags.td[types[i] == 'dhcp'], tags.td[d[i]],
                                    tags.td[[[k, tags.br] for k in routes.
                                             get(i, ["None"])]], tags.
                                    td[tags.a(title="Edit Interface %s" % i,
                                              href="Edit/%s" % i)[tags.img(
                                                  src="/images/edit.png")]], ]
                            for i in d.keys() if not i == "lo"
                        ]]], tags.br, tags.h3["Add interface"],
                tags.directive('form addInterface')],
            tags.div(id="panelVlan", _class="tabPane")[
                tags.h3["Configured VLAN Interfaces"],
                PageHelpers.dataTable(('Interface', 'IP', ''), vlans), tags.br,
                tags.h3["Add VLAN"],
                tags.directive('form addVLAN')],
            tags.div(id="panelTunnel", _class="tabPane")[
                tags.h3["Configure IPv6 Tunnel"],
                tags.directive('form tunnelConf')],
            PageHelpers.LoadTabSwitcher(), ]
Exemplo n.º 15
0
class HTMLTableFragment(HTMLDataRenderer):
	"""A nevow renderer for result tables.
	"""
	rowsPerDivision = 25

	def _getRowFormatter(self):
		"""returns a callable returning a rendered row in HTML (as used for the
		stan xml tag).
		"""
		source = [
			"def formatRow(row, rowAttrs=''):",
			"  res = ['<tr%s>'%rowAttrs]",]
		for index, (name, _, wantsRow) in enumerate(self.formatterSeq):
			if wantsRow:
				source.append("  val = formatters[%d](row)"%index)
			else:
				source.append("  val = formatters[%d](row[%s])"%(index, repr(name)))
			source.extend([
#				"  import code;code.interact(local=locals())",
				"  if val is None:",
				"    val = 'N/A'",
				"  if isinstance(val, basestring):",
				"    serFct = escapeForHTML",
				"  else:",
				"    serFct = flatten",
				"  res.append('<td>%s</td>'%serFct(val))",])
		source.extend([
			"  res.append('</tr>')",
			"  return ''.join(res)"])

		return utils.compileFunction("\n".join(source), "formatRow", {
				"formatters": [p[1] for p in self.formatterSeq],
				"escapeForHTML": common.escapeForHTML,
				"flatten": flat.flatten})

	def render_rowSet(self, ctx, items):
		# slow, use render_tableBody
		return ctx.tag(render=rend.mapping)[self.defaultTds]

	def render_tableBody(self, ctx, data):
		"""returns HTML-rendered table rows in chunks of rowsPerDivision.

		We don't use stan here since we can concat all those tr/td much faster
		ourselves.
		"""
		rowAttrsIterator = itertools.cycle([' class="data"', ' class="data even"'])
		formatRow = self._getRowFormatter()
		rendered = []
		yield T.xml("<tbody>")
		for row in self.table:
			rendered.append(formatRow(row, rowAttrsIterator.next()))
			if len(rendered)>=self.rowsPerDivision:
				yield T.xml("\n".join(rendered))
				yield self.headCellsStan
				rendered = []
		yield T.xml("\n".join(rendered)+"\n</tbody>")

	docFactory = loaders.stan(T.div(class_="tablewrap")[
		T.div(render=T.directive("meta"), class_="warning")["_warning"],
		T.table(class_="results") [
				T.thead(render=T.directive("headCells")),
				T.tbody(render=T.directive("tableBody"))],
			T.invisible(render=T.directive("footnotes")),
		]
	)
Exemplo n.º 16
0
 def __init__(self, other=None):
     self.other = other
     self.header = tags.thead()
     self.body = tags.tbody()
     self.tag = tags.table()[self.header, self.body]
     self.functions = []
Exemplo n.º 17
0
    def render_content(self, ctx, data):
        Utils.log.msg('%s opened Tools/Firewall' % (self.avatarId.username))
        rules = self.rules.read()
        rows = []
        bg = True

        ### Read SNAT rules
        snat = self.sysconf.Shorewall.get('snat', [])
        snatRules = []
        n = 0
        for ru in snat:
            l = ru.split()
            l.append(
                tags.a(
                    href="Delete/SNAT/%s/" % n, 
                    onclick="return confirm('Are you sure you want to delete this SNAT rule?');",
                    title="Delete this SNAT rule."
                )[tags.img(src="/images/ex.png")]
            )
            snatRules.append(l)
            n += 1

        ### Read MASQ rules
        masq = self.sysconf.Shorewall.get('masq', {})
        natRules = []
        for k,mas in masq.items():
            runum = 0 
            for v in mas:
                if type(v) == list:
                    l = [k]
                    l.extend([i.replace('-', 'Any') for i in v])
                    l.append(
                        tags.a(
                            href="Delete/NAT/%s/%s/"%(k, runum), 
                            onclick="return confirm('Are you sure you want to delete this NAT rule?');",
                            title="Delete this NAT rule."
                        )[tags.img(src="/images/ex.png")]
                    )
                    natRules.append(l)
                else:
                    natRules.append([
                        k, 'Any', v, 'Any', 'Any', 'Any', 'Any',
                        tags.a(
                            href="Delete/NAT/%s/%s/"%(k, runum), 
                            onclick="return confirm('Are you sure you want to delete this NAT rule?');",
                            title="Delete this NAT rule."
                        )[tags.img(src="/images/ex.png")]
                    ])
                runum += 1

        securityViolation = None

        ### Read firewall rules table 
        try:
            lastrule = rules['AIP'][0][8]
        except:
            lastrule = 0
        for i,ru in enumerate(rules['AIP']):
            bg = not bg
            this = bg and "#F5F5EB" or "#eee"
            try:
                nextrule = rules['AIP'][i+1][8]
            except:
                nextrule = ru[8]

            # Check for security violations
            print "Port, source", ru[7], ru[2]

            # SSH and Vulani access violation
            if ru[7] in ["22", "9682"]:
                if (ru[2] == "Any") and ((ru[1] in ["net", "Any", "dsl", "ppp", "wan", "net2"]) or (ru[4] == "fw")):
                    securityViolation = "Inbound SSH and/or Vulani administrative access should not be unrestricted! "
                    securityViolation += "Your system security has been seriously compromised. Please remove this "
                    securityViolation += "rule and restrict the source IP or make use of the VPN to administer the server remotely"
                    this = "#ff5555"

            r = [
                tags.tr(style="background: %s" % this)[
                    tags.td(rowspan=2)[ru[0]],
                    tags.td[tags.strong['Source ']],
                    tags.td[ru[1]], # Source zone
                    tags.td[ru[3].replace('-', 'Any')], # Source port
                    tags.td[ru[2]], # Source IP
                    tags.td(rowspan=2)[ru[6].replace('-', 'Any')],
                    tags.td(rowspan=2)[
                        tags.a(
                            href="Swap/%s/%s/" % (ru[8], nextrule),
                            title = "Move this rule down"
                        )[tags.img(src="/images/arrowdown.png")],
                        " ",
                        tags.a(
                            href="Swap/%s/%s/" % (ru[8], lastrule),
                            title = "Move this rule up"
                        )[tags.img(src="/images/arrowup.png")],
                        " ",
                        tags.a(
                            href="Delete/AIP/%s/"%(ru[8]), 
                            onclick="return confirm('Are you sure you want to delete this rule?');",
                            title="Delete this firewall rule."
                        )[tags.img(src="/images/ex.png")]
                    ]
                ],
                tags.tr(style="background: %s" % this)[
                    tags.td[tags.strong['Destination ']], 
                    #tags.td(align='right')[' Zone: '],
                    tags.td[ru[4]], # Zone
                    #tags.td( align='right')[' Port/Type: '],
                    tags.td[ru[7].replace('-', 'Any')], #Port
                    #tags.td( align='right')[' IP: '],
                    tags.td[ru[5]], # IP
                ],
            ]
            rows.append(r)
            lastrule = ru[8] 
        self.largestRule = lastrule
        fwtable = tags.table(cellspacing=0,  _class='listing')[
            tags.thead(background="/images/gradMB.png")[
                tags.tr[
                    tags.th['Rule'],
                    tags.th[''],
                    #tags.th[''],
                    tags.th['Zone'],
                    #tags.th[''],
                    tags.th['Port'],
                    #tags.th[''],
                    tags.th['IP'], 
                    tags.th['Protocol'],
                    tags.th[''],
                ],
            ],
            tags.tbody[
                rows
            ]
        ]

        toss = {
            '16':'Minimize Delay',
            '8':'Maximize Throughput',
            '4':'Maximize Reliability',
            '2':'Minimize Cost',
            '0':'Normal Service'
        }
        qosRules = []
        l = 0
        for port, proto, tos in self.sysconf.Shorewall.get('qos', []):
            qosRules.append([
                port,
                proto,
                toss[tos],
                tags.a(href=url.root.child("Qos").child("Delete").child(l), onclick="return confirm('Are you sure you want to delete this entry?');")[tags.img(src="/images/ex.png")]
            ])
            l += 1

        ### Check if shorewall is broken
        if os.path.exists('/usr/local/tcs/tums/shorewallBroken'):
            check = tags.div(style="color: #F00")[
                tags.br,
                tags.strong[
                    "The firewall configuration appears to be broken, please test the settings to see any errors and correct them"
                ],
                tags.br
            ]
        else:
            check = ""

        if securityViolation:
            secError =  [tags.table(width="70%", style="border:2px solid #ff5555")[tags.tr[
                tags.td[tags.img(src="/images/securityhz.png")],
                tags.td[
                    tags.h1["Security Violation!"],
                    securityViolation
                ]
            ]], tags.br, tags.br]
        else:
            secError = ""
        
        ### Return the page stanza
        return ctx.tag[
                tags.h3[tags.img(src="/images/firewall.png"), " Firewall"],

                check,
                secError,

                tags.img(src="/images/start.png"), " ",
                tags.a(
                    href="Test", 
                    style="font-size:11pt;", 
                    title="Test the firewall. (This may take some time!)"
                )[tags.strong(style="font-family:arial,verdana,helvetica,sans-serif;")["Test Settings"]],
                tags.br,
                tags.img(src="/images/refresh.png"), " ",
                tags.a(
                    href="Restart", 
                    style="font-size:11pt;", 
                    title="Restart the firewall and apply the changes. Changes are only activated after this is clicked."
                )[tags.strong(style="font-family:arial,verdana,helvetica,sans-serif")["Apply Changes"]],

                PageHelpers.TabSwitcher((
                    ('Rules'          , 'panelRules'),
                    #('Allow Ports'       , 'panelAllowPort'),
                    ('NAT',             'panelNATTab'),
                    ('QoS',             'panelQos'),
                    ('Policy',             'panelPolicy'),
                    ('Zones'    ,       'panelZones'),
                    ('Connections',     'panelCurrent'),
                ), id = "firewall"),

                tags.div(id="panelNATTab", _class="tabPane")[
                    PageHelpers.TabSwitcher((
                        ('Forwarding',  'panelForwardPort'), 
                        ('Redirection', 'panelTransparentProxy'), 
                        ('NAT',         'panelNAT'), 
                        ('Source NAT',  'panelSNAT')
                    ), id ="firewallNAT"),

                    tags.div(id="panelForwardPort", _class="tabPane")[
                        tags.h3["Port Forwarding"],
                        PageHelpers.dataTable(['Source Zone', 'Source IP', 'Forward To', 'Destination Zone', 'Protocol', 'Port', 'Destination IP', ''], [
                            r[:-1] + [tags.a(
                                href="Delete/AIP/%s/"%(r[-1]), 
                                title="Delete this port forwarding rule",
                                onclick="return confirm('Are you sure you want to delete this entry?');"
                            )[tags.img(src="/images/ex.png")]]
                        for i,r in enumerate(rules['FORWARD'])]),
                        tags.h3["Add Forwarding Rule"],
                        tags.directive('form forwardPort'),
                    ],

                    tags.div(id="panelTransparentProxy", _class="tabPane")[
                        tags.h3["Destination NAT (Transparent Proxy)"],
                        PageHelpers.dataTable(['Source Zone', 'Source Network', 'Destination Port', 'Source Port', 'Protocol', 'Destination Network', ''], [
                            r[:-1] + [tags.a(
                                href="Delete/AIP/%s/"%(r[-1]), 
                                title="Delete this transparent redirection rule",
                                onclick="return confirm('Are you sure you want to delete this entry?');"
                            )[tags.img(src="/images/ex.png")]]
                        for i,r in enumerate(rules['PROXY'])]),
                        tags.h3["Add DNAT Rule"],
                        tags.directive('form transProxy'),
                    ],

                    tags.div(id="panelNAT", _class="tabPane")[
                        tags.h3["Nework Address Translation (Masquerading)"],
                        PageHelpers.dataTable(
                            ['Destination Interface', 'Destination Network', 'Source Network', 'Source Interface', 'NAT IP', 'Protocol', 'Port', ''],
                            natRules
                        ),
                        tags.h3['Add NAT Rule'],
                        tags.directive('form addNAT')
                    ],

                    tags.div(id="panelSNAT", _class="tabPane")[
                        tags.h3["Source NAT"],
                        PageHelpers.dataTable(
                            ['Source IP', 'External Interface', 'Internal IP', 'Any Interface', 'Use Internal'],
                            snatRules
                        ),
                        tags.h3['Add SNAT Rule'],
                        tags.directive('form addSNAT')
                    ],

                    PageHelpers.LoadTabSwitcher(id="firewallNAT")
                ],

                tags.div(id="panelPolicy", _class="tabPane")[
                    tags.h3["General firewall policy"],
                    tags.directive('form inetPol') 
                ],

                tags.div(id="panelQos", _class="tabPane")[
                    tags.h3[tags.img(src="/images/compress.png"), "QOS"],
                    PageHelpers.dataTable(['Port', 'Protocol', 'Type of service', ''], qosRules),
                    tags.h3["Add Rule"],
                    tags.directive('form addQos'),
                ],

                tags.div(id="panelRules", _class="tabPane")[
                    tags.h3["Firewall Rules"], 
                    #PageHelpers.dataTable(
                    #    [
                    #        'Action', '', 'Protocol',''
                    #    ], 
                        fwtable,
                    #),
                    tags.a(name="addRule")[''],
                    tags.h3["Add rule"],
                    tags.directive('form allowRange'),
                ],

                tags.div(id="panelZones", _class="tabPane")[
                    tags.h3["Zones"],
                    PageHelpers.dataTable(['Zone Name', 'Policy', 'Log target', 'Interfaces', ''], 
                        [
                            [
                                zone, zd['policy'], zd['log'], [[i, tags.br] for i in zd['interfaces']],
                                [
                                    tags.a(
                                        href="Delete/Zone/%s/"%(zone),
                                        title="Delete this firewall zone",
                                        onclick="return confirm('Are you sure you want to delete this zone?');"
                                    )[tags.img(src="/images/ex.png")],
                                    tags.a(href="EditZone/%s/" % zone)[tags.img(src="/images/edit.png")]
                                ]
                            ] 
                        for zone, zd in self.sysconf.Shorewall.get('zones', {}).items()]
                    ),
                    tags.h3['Add Firewall Zone'],
                    tags.directive('form addZone')
                ],
                tags.div(id="panelCurrent", _class="tabPane")[
                    tags.h3["Current Connections"],
                    tags.invisible(render=tags.directive('connections'))
                ],
            PageHelpers.LoadTabSwitcher(id="firewall")
        ]
Exemplo n.º 18
0
Arquivo: VPN.py Projeto: calston/tums
    def render_content(self, ctx, data):
        keys = [i for i in os.listdir('/etc/openvpn/keys/') if '.key' in i]

        keys.sort()
        for key in ['vpn.key', 'ca.key']:
            try:
                keys.remove(key)
            except:
                pass

        # Build a list of tunnels
        types={}
        # reprocess the configuration
        for name, conf in self.sysconf.Tunnel.items():
            if name == "ipv6":
                continue
            cnf = conf
            cnf['name'] = str(name)
            if types.get(str(cnf['type'])):
                types[str(cnf['type'])].append(cnf)
            else:
                types[str(cnf['type'])] = [cnf]
                
        # Check vpn is configured
        if os.path.exists('/etc/openvpn/vpn.conf'):
            userForm = tags.directive('form addUser')
        else:
            userForm = tags.strong["Please configure the VPN in order to add new users"]

        tuns = []
        # Call the handler functions with the stores
        ifs = Utils.getInterfaces()
        for k,v in types.items():
            if v:
                v.sort()
                for c,tun in enumerate(v):
                    status = tags.a(href='Start/%s/' % tun['name'])["Disconnected"]
                    if k == 'openvpn':
                        # Hunt TAP interfaces
                        if 'tap%s' % (c+1) in ifs:
                            status = tags.a(href='Stop/%s/' % tun['name'])["Connected"]

                    tuns.append((
                        status, 
                        tun['name'], 
                        tun['type'], 
                        tun['endpoint'], 
                        tags.a(href="Delete/%s/" % (tun['name']))["Delete"]
                    ))

        return ctx.tag[
                tags.h3[tags.img(src="/images/vpn.png"), self.text.vpnConfig],
                PageHelpers.TabSwitcher((
                    (self.text.vpnTabWindows, 'panelWindows'),
                    (self.text.vpnTabTCS, 'panelOpenVPN'),
                    (self.text.vpnTabUsers, 'panelVPNUsers'),
                    (self.text.vpnTabTun, 'panelTun')
                )),
                tags.div(id="panelWindows", _class="tabPane")[
                    tags.h3[self.text.vpnHeadingWindows],
                    tags.directive('form winForm'),
                ],
                tags.div(id="panelTun", _class="tabPane")[
                    tags.h3["Tunnels"],
                    PageHelpers.dataTable(['Status', 'Name', 'Type', 'Endpoint', ''], tuns),
                    tags.h3["Add tunnel"],
                    tags.directive('form addTun'), tags.br,
                ],
                tags.div(id="panelOpenVPN", _class="tabPane")[
                    tags.h3[self.text.vpnHeadingTCS],
                    tags.directive('form vpnForm'), tags.br,
                ],
                tags.div(id="panelVPNUsers", _class="tabPane")[
                    tags.h3[self.text.vpnHeadingTCSUsers],
                    tags.table(cellspacing=0,  _class='sortable')[
                        tags.thead(background="/images/gradMB.png")[
                            tags.tr[
                                tags.th(colformat="str")[self.text.vpnCertificateName],
                                tags.th[""],
                            ]
                        ],
                        tags.tbody[
                        [
                            tags.tr[
                                tags.td['.'.join(i.split('.')[:-1])],
                                tags.td[
                                    tags.a(
                                        href="Revoke/%s/" % '.'.join(i.split('.')[:-1]), 
                                        onclick="return confirm('%s');" % self.text.vpnConfirmRevoke
                                    )[ 
                                        tags.img(src="/images/ex.png")
                                    ]
                                ]
                            ]
                        for i in keys],
                        ]
                    ], tags.br,
                    tags.h3[self.text.vpnHeadingAddUser],

                    userForm
                ],
                PageHelpers.LoadTabSwitcher()
            ]