Commit 40c3495c by x

firewall: code formatting

parent 114e301a
...@@ -42,5 +42,5 @@ def val_domain(value): ...@@ -42,5 +42,5 @@ def val_domain(value):
raise ValidationError(u'%s - helytelen domain' % value) raise ValidationError(u'%s - helytelen domain' % value)
def ipv4_2_ipv6(ipv4): def ipv4_2_ipv6(ipv4):
m = ipv4_re.match(ipv4) m = ipv4_re.match(ipv4)
return "2001:738:2001:4031:%s:%s:%s:0" % (m.group(1), m.group(2), m.group(3)) return "2001:738:2001:4031:%s:%s:%s:0" % (m.group(1), m.group(2), m.group(3))
#!/usr/bin/env python
#from django.core.management import setup_environ
#from teszt import settings
#setup_environ(settings)
from django.contrib import auth from django.contrib import auth
from firewall import models from firewall import models
import os import os
...@@ -15,274 +8,273 @@ DNS_SERVER = "152.66.243.60" ...@@ -15,274 +8,273 @@ DNS_SERVER = "152.66.243.60"
class firewall: class firewall:
IPV6=False IPV6=False
SZABALYOK = None SZABALYOK = None
SZABALYOK_NAT = [] SZABALYOK_NAT = []
vlans = None vlans = None
dmz = None dmz = None
pub = None pub = None
hosts = None hosts = None
fw = None fw = None
def dportsport(self, rule, repl=True): def dportsport(self, rule, repl=True):
retval = " " retval = " "
if(rule.proto == "tcp" or rule.proto == "udp"): if(rule.proto == "tcp" or rule.proto == "udp"):
retval = "-p %s " % rule.proto retval = "-p %s " % rule.proto
if(rule.sport): if(rule.sport):
retval += " --sport %s " % rule.sport retval += " --sport %s " % rule.sport
if(rule.dport): if(rule.dport):
retval += " --dport %s " % ( rule.nat_dport if (repl and rule.nat and rule.direction == '1') else rule.dport ) retval += " --dport %s " % ( rule.nat_dport if (repl and rule.nat and rule.direction == '1') else rule.dport )
elif(rule.proto == "icmp"): elif(rule.proto == "icmp"):
retval = "-p %s " % rule.proto retval = "-p %s " % rule.proto
return retval return retval
def iptables(self, s): def iptables(self, s):
self.SZABALYOK.append(s) self.SZABALYOK.append(s)
def iptablesnat(self, s): def iptablesnat(self, s):
self.SZABALYOK_NAT.append(s) self.SZABALYOK_NAT.append(s)
def host2vlan(self, host, rule): def host2vlan(self, host, rule):
if(self.IPV6): if(self.IPV6):
ipaddr = host.ipv6 + "/112" ipaddr = host.ipv6 + "/112"
else: else:
ipaddr = host.ipv4 ipaddr = host.ipv4
dport_sport = self.dportsport(rule) dport_sport = self.dportsport(rule)
for vlan in rule.vlan.all(): for vlan in rule.vlan.all():
if(rule.accept): if(rule.accept):
if(rule.direction == '0' and vlan.name == "PUB"): if(rule.direction == '0' and vlan.name == "PUB"):
if(rule.dport == 25): if(rule.dport == 25):
self.iptables("-A PUB_OUT -s %s %s -p tcp --dport 25 -j LOG_ACC" % (ipaddr, rule.extra)) self.iptables("-A PUB_OUT -s %s %s -p tcp --dport 25 -j LOG_ACC" % (ipaddr, rule.extra))
break break
action = "PUB_OUT" action = "PUB_OUT"
else: else:
action = "LOG_ACC" action = "LOG_ACC"
else: else:
action = "LOG_DROP" action = "LOG_DROP"
if(rule.direction == '1'): #HOSTHOZ megy if(rule.direction == '1'): # HOSTHOZ megy
self.iptables("-A %s_%s -d %s %s %s -g %s" % (vlan, host.vlan, ipaddr, dport_sport, rule.extra, action)); self.iptables("-A %s_%s -d %s %s %s -g %s" % (vlan, host.vlan, ipaddr, dport_sport, rule.extra, action))
else: else:
self.iptables("-A %s_%s -s %s %s %s -g %s" % (host.vlan, vlan, ipaddr, dport_sport, rule.extra, action)); self.iptables("-A %s_%s -s %s %s %s -g %s" % (host.vlan, vlan, ipaddr, dport_sport, rule.extra, action))
def fw2vlan(self, rule): def fw2vlan(self, rule):
dport_sport = self.dportsport(rule) dport_sport = self.dportsport(rule)
for vlan in rule.vlan.all(): for vlan in rule.vlan.all():
if(rule.direction == '1'): #HOSTHOZ megy if(rule.direction == '1'): # HOSTHOZ megy
self.iptables("-A INPUT -i %s %s %s -g %s" % (vlan.interface, dport_sport, rule.extra, "LOG_ACC" if rule.accept else "LOG_DROP")); self.iptables("-A INPUT -i %s %s %s -g %s" % (vlan.interface, dport_sport, rule.extra, "LOG_ACC" if rule.accept else "LOG_DROP"))
else: else:
self.iptables("-A OUTPUT -o %s %s %s -g %s" % (vlan.interface, dport_sport, rule.extra, "LOG_ACC" if rule.accept else "LOG_DROP")); self.iptables("-A OUTPUT -o %s %s %s -g %s" % (vlan.interface, dport_sport, rule.extra, "LOG_ACC" if rule.accept else "LOG_DROP"))
def vlan2vlan(self, l_vlan, rule): def vlan2vlan(self, l_vlan, rule):
dport_sport = self.dportsport(rule) dport_sport = self.dportsport(rule)
for vlan in rule.vlan.all(): for vlan in rule.vlan.all():
if(rule.accept): if(rule.accept):
if((rule.direction == '0') and vlan.name == "PUB"): if((rule.direction == '0') and vlan.name == "PUB"):
action = "PUB_OUT" action = "PUB_OUT"
else: else:
action = "LOG_ACC" action = "LOG_ACC"
else: else:
action = "LOG_DROP" action = "LOG_DROP"
if(rule.direction == '1'): #HOSTHOZ megy if(rule.direction == '1'): # HOSTHOZ megy
self.iptables("-A %s_%s %s %s -g %s" % (vlan, l_vlan, dport_sport, rule.extra, action)); self.iptables("-A %s_%s %s %s -g %s" % (vlan, l_vlan, dport_sport, rule.extra, action))
else: else:
self.iptables("-A %s_%s %s %s -g %s" % (l_vlan, vlan, dport_sport, rule.extra, action)); self.iptables("-A %s_%s %s %s -g %s" % (l_vlan, vlan, dport_sport, rule.extra, action))
def prerun(self): def prerun(self):
self.iptables("*filter") self.iptables("*filter")
self.iptables(":INPUT DROP [88:6448]") self.iptables(":INPUT DROP [88:6448]")
self.iptables(":FORWARD DROP [0:0]") self.iptables(":FORWARD DROP [0:0]")
self.iptables(":OUTPUT DROP [50:6936]") self.iptables(":OUTPUT DROP [50:6936]")
#inicialize logging # inicialize logging
self.iptables("-N LOG_DROP") self.iptables("-N LOG_DROP")
#windows port scan are silently dropped # windows port scan are silently dropped
self.iptables("-A LOG_DROP -p tcp --dport 445 -j DROP") self.iptables("-A LOG_DROP -p tcp --dport 445 -j DROP")
self.iptables("-A LOG_DROP -p udp --dport 137 -j DROP") self.iptables("-A LOG_DROP -p udp --dport 137 -j DROP")
self.iptables("-A LOG_DROP -j LOG --log-level 7 --log-prefix \"[ipt][drop]\"") self.iptables("-A LOG_DROP -j LOG --log-level 7 --log-prefix \"[ipt][drop]\"")
self.iptables("-A LOG_DROP -j DROP") self.iptables("-A LOG_DROP -j DROP")
self.iptables("-N LOG_ACC") self.iptables("-N LOG_ACC")
self.iptables("-A LOG_ACC -j LOG --log-level 7 --log-prefix \"[ipt][isok]\"") self.iptables("-A LOG_ACC -j LOG --log-level 7 --log-prefix \"[ipt][isok]\"")
self.iptables("-A LOG_ACC -j ACCEPT") self.iptables("-A LOG_ACC -j ACCEPT")
if not self.IPV6: if not self.IPV6:
#The chain which test is a packet has a valid public destination IP # The chain which test is a packet has a valid public destination IP
#(RFC-3330) packages passing this chain has valid destination IP addressed # (RFC-3330) packages passing this chain has valid destination IP addressed
self.iptables("-N r_pub_dIP") self.iptables("-N r_pub_dIP")
self.iptables("-A r_pub_dIP -d 0.0.0.0/8 -g LOG_DROP") self.iptables("-A r_pub_dIP -d 0.0.0.0/8 -g LOG_DROP")
self.iptables("-A r_pub_dIP -d 169.254.0.0/16 -g LOG_DROP") self.iptables("-A r_pub_dIP -d 169.254.0.0/16 -g LOG_DROP")
self.iptables("-A r_pub_dIP -d 172.16.0.0/12 -g LOG_DROP") self.iptables("-A r_pub_dIP -d 172.16.0.0/12 -g LOG_DROP")
self.iptables("-A r_pub_dIP -d 192.0.2.0/24 -g LOG_DROP") self.iptables("-A r_pub_dIP -d 192.0.2.0/24 -g LOG_DROP")
self.iptables("-A r_pub_dIP -d 192.168.0.0/16 -g LOG_DROP") self.iptables("-A r_pub_dIP -d 192.168.0.0/16 -g LOG_DROP")
self.iptables("-A r_pub_dIP -d 127.0.0.0/8 -g LOG_DROP") self.iptables("-A r_pub_dIP -d 127.0.0.0/8 -g LOG_DROP")
#self.iptables("-A r_pub_dIP -d 10.0.0.0/8 -g LOG_DROP") # self.iptables("-A r_pub_dIP -d 10.0.0.0/8 -g LOG_DROP")
#The chain which test is a packet has a valid public source IP # The chain which test is a packet has a valid public source IP
#(RFC-3330) packages passing this chain has valid destination IP addressed # (RFC-3330) packages passing this chain has valid destination IP addressed
self.iptables("-N r_pub_sIP") self.iptables("-N r_pub_sIP")
self.iptables("-A r_pub_sIP -s 0.0.0.0/8 -g LOG_DROP") self.iptables("-A r_pub_sIP -s 0.0.0.0/8 -g LOG_DROP")
self.iptables("-A r_pub_sIP -s 169.254.0.0/16 -g LOG_DROP") self.iptables("-A r_pub_sIP -s 169.254.0.0/16 -g LOG_DROP")
self.iptables("-A r_pub_sIP -s 172.16.0.0/12 -g LOG_DROP") self.iptables("-A r_pub_sIP -s 172.16.0.0/12 -g LOG_DROP")
self.iptables("-A r_pub_sIP -s 192.0.2.0/24 -g LOG_DROP") self.iptables("-A r_pub_sIP -s 192.0.2.0/24 -g LOG_DROP")
self.iptables("-A r_pub_sIP -s 192.168.0.0/16 -g LOG_DROP") self.iptables("-A r_pub_sIP -s 192.168.0.0/16 -g LOG_DROP")
self.iptables("-A r_pub_sIP -s 127.0.0.0/8 -g LOG_DROP") self.iptables("-A r_pub_sIP -s 127.0.0.0/8 -g LOG_DROP")
#self.iptables("-A r_pub_sIP -s 10.0.0.0/8 -g LOG_DROP") # self.iptables("-A r_pub_sIP -s 10.0.0.0/8 -g LOG_DROP")
#chain which tests if the destination specified by the DMZ host is valid # chain which tests if the destination specified by the DMZ host is valid
self.iptables("-N r_DMZ_dIP") self.iptables("-N r_DMZ_dIP")
self.iptables("-A r_DMZ_dIP -d 10.2.0.0/16 -j RETURN") self.iptables("-A r_DMZ_dIP -d 10.2.0.0/16 -j RETURN")
self.iptables("-A r_DMZ_dIP -j r_pub_dIP") self.iptables("-A r_DMZ_dIP -j r_pub_dIP")
self.iptables("-N PUB_OUT") self.iptables("-N PUB_OUT")
if not self.IPV6: if not self.IPV6:
self.iptables("-A PUB_OUT -j r_pub_dIP") self.iptables("-A PUB_OUT -j r_pub_dIP")
self.iptables("-A FORWARD -m state --state INVALID -g LOG_DROP") self.iptables("-A FORWARD -m state --state INVALID -g LOG_DROP")
self.iptables("-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT") self.iptables("-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT")
self.iptables("-A FORWARD -p icmp --icmp-type echo-request -g LOG_ACC") self.iptables("-A FORWARD -p icmp --icmp-type echo-request -g LOG_ACC")
if not self.IPV6: if not self.IPV6:
self.iptables("-A FORWARD -j r_pub_sIP -o pub") self.iptables("-A FORWARD -j r_pub_sIP -o pub")
self.iptables("-A INPUT -m state --state INVALID -g LOG_DROP") self.iptables("-A INPUT -m state --state INVALID -g LOG_DROP")
self.iptables("-A INPUT -i lo -j ACCEPT") self.iptables("-A INPUT -i lo -j ACCEPT")
if not self.IPV6: if not self.IPV6:
self.iptables("-A INPUT -j r_pub_sIP") self.iptables("-A INPUT -j r_pub_sIP")
self.iptables("-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT") self.iptables("-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT")
self.iptables("-A OUTPUT -m state --state INVALID -g LOG_DROP") self.iptables("-A OUTPUT -m state --state INVALID -g LOG_DROP")
self.iptables("-A OUTPUT -o lo -j ACCEPT") self.iptables("-A OUTPUT -o lo -j ACCEPT")
self.iptables("-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT") self.iptables("-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT")
def postrun(self): def postrun(self):
self.iptables("-A PUB_OUT -s 152.66.243.160/27 -p tcp --dport 25 -j LOG_ACC") self.iptables("-A PUB_OUT -s 152.66.243.160/27 -p tcp --dport 25 -j LOG_ACC")
self.iptables("-A PUB_OUT -s 152.66.243.160/27 -p tcp --dport 445 -j LOG_ACC") self.iptables("-A PUB_OUT -s 152.66.243.160/27 -p tcp --dport 445 -j LOG_ACC")
self.iptables("-A PUB_OUT -p tcp --dport 25 -j LOG_DROP") self.iptables("-A PUB_OUT -p tcp --dport 25 -j LOG_DROP")
self.iptables("-A PUB_OUT -p tcp --dport 445 -j LOG_DROP") self.iptables("-A PUB_OUT -p tcp --dport 445 -j LOG_DROP")
self.iptables("-A PUB_OUT -p udp --dport 445 -j LOG_DROP") self.iptables("-A PUB_OUT -p udp --dport 445 -j LOG_DROP")
self.iptables("-A PUB_OUT -g LOG_ACC") self.iptables("-A PUB_OUT -g LOG_ACC")
self.iptables("-A FORWARD -g LOG_DROP") self.iptables("-A FORWARD -g LOG_DROP")
self.iptables("-A INPUT -g LOG_DROP") self.iptables("-A INPUT -g LOG_DROP")
self.iptables("-A OUTPUT -g LOG_DROP") self.iptables("-A OUTPUT -g LOG_DROP")
self.iptables("COMMIT") self.iptables("COMMIT")
def ipt_nat(self): def ipt_nat(self):
self.iptablesnat("*nat") self.iptablesnat("*nat")
self.iptablesnat(":PREROUTING ACCEPT [0:0]") self.iptablesnat(":PREROUTING ACCEPT [0:0]")
self.iptablesnat(":INPUT ACCEPT [0:0]") self.iptablesnat(":INPUT ACCEPT [0:0]")
self.iptablesnat(":OUTPUT ACCEPT [1:708]") self.iptablesnat(":OUTPUT ACCEPT [1:708]")
self.iptablesnat(":POSTROUTING ACCEPT [1:708]") self.iptablesnat(":POSTROUTING ACCEPT [1:708]")
#portforward # portforward
for host in self.hosts.exclude(pub_ipv4=None): for host in self.hosts.exclude(pub_ipv4=None):
for rule in host.rules.filter(nat=True, direction='1'): for rule in host.rules.filter(nat=True, direction='1'):
dport_sport = self.dportsport(rule, False) dport_sport = self.dportsport(rule, False)
if host.vlan.snat_ip: if host.vlan.snat_ip:
self.iptablesnat("-A PREROUTING -d %s %s %s -j DNAT --to-destination %s:%s" % (host.pub_ipv4, dport_sport, rule.extra, host.ipv4, rule.nat_dport)) self.iptablesnat("-A PREROUTING -d %s %s %s -j DNAT --to-destination %s:%s" % (host.pub_ipv4, dport_sport, rule.extra, host.ipv4, rule.nat_dport))
#sajat publikus ipvel rendelkezo gepek szabalyai # sajat publikus ipvel rendelkezo gepek szabalyai
for host in self.hosts.exclude(shared_ip=True): for host in self.hosts.exclude(shared_ip=True):
if(host.pub_ipv4): if(host.pub_ipv4):
self.iptablesnat("-A PREROUTING -d %s -j DNAT --to-destination %s" % (host.pub_ipv4, host.ipv4)) self.iptablesnat("-A PREROUTING -d %s -j DNAT --to-destination %s" % (host.pub_ipv4, host.ipv4))
self.iptablesnat("-A POSTROUTING -s %s -j SNAT --to-source %s" % (host.ipv4, host.pub_ipv4)) self.iptablesnat("-A POSTROUTING -s %s -j SNAT --to-source %s" % (host.ipv4, host.pub_ipv4))
#alapertelmezett nat szabalyok a vlanokra # alapertelmezett nat szabalyok a vlanokra
for s_vlan in self.vlans: for s_vlan in self.vlans:
if(s_vlan.snat_ip): if(s_vlan.snat_ip):
for d_vlan in s_vlan.snat_to.all(): for d_vlan in s_vlan.snat_to.all():
self.iptablesnat("-A POSTROUTING -s %s -o %s -j SNAT --to-source %s" % (s_vlan.net_ipv4(), d_vlan.interface, s_vlan.snat_ip)) self.iptablesnat("-A POSTROUTING -s %s -o %s -j SNAT --to-source %s" % (s_vlan.net_ipv4(), d_vlan.interface, s_vlan.snat_ip))
#bedrotozott szabalyok # bedrotozott szabalyok
self.iptablesnat("-A POSTROUTING -s 10.5.0.0/16 -o vlan0003 -j SNAT --to-source 10.3.255.254") #man elerheto legyen self.iptablesnat("-A POSTROUTING -s 10.5.0.0/16 -o vlan0003 -j SNAT --to-source 10.3.255.254") # man elerheto legyen
self.iptablesnat("-A POSTROUTING -s 10.5.0.0/16 -o vlan0008 -j SNAT --to-source 10.0.0.247") #wolf halozat a nyomtatashoz self.iptablesnat("-A POSTROUTING -s 10.5.0.0/16 -o vlan0008 -j SNAT --to-source 10.0.0.247") # wolf halozat a nyomtatashoz
self.iptablesnat("-A POSTROUTING -s 10.3.0.0/16 -o vlan0002 -j SNAT --to-source %s" % self.pub.ipv4) #kulonben nemmegy a du self.iptablesnat("-A POSTROUTING -s 10.3.0.0/16 -o vlan0002 -j SNAT --to-source %s" % self.pub.ipv4) # kulonben nemmegy a du
self.iptablesnat("COMMIT") self.iptablesnat("COMMIT")
def ipt_filter(self): def ipt_filter(self):
regexp = re.compile('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+') regexp = re.compile('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+')
regexp_icmp = re.compile('icmp'); regexp_icmp = re.compile('icmp')
#futas elotti dolgok # futas elotti dolgok
self.prerun() self.prerun()
#tuzfal sajat szabalyai # tuzfal sajat szabalyai
for f in self.fw: for f in self.fw:
for rule in f.rules.all(): for rule in f.rules.all():
self.fw2vlan(rule) self.fw2vlan(rule)
#zonak kozotti lancokra ugras # zonak kozotti lancokra ugras
for s_vlan in self.vlans: for s_vlan in self.vlans:
for d_vlan in self.vlans: for d_vlan in self.vlans:
self.iptables("-N %s_%s" % (s_vlan, d_vlan)) self.iptables("-N %s_%s" % (s_vlan, d_vlan))
self.iptables("-A FORWARD -i %s -o %s -g %s_%s" % (s_vlan.interface, d_vlan.interface, s_vlan, d_vlan)) self.iptables("-A FORWARD -i %s -o %s -g %s_%s" % (s_vlan.interface, d_vlan.interface, s_vlan, d_vlan))
#hosztok szabalyai # hosztok szabalyai
for i_vlan in self.vlans: for i_vlan in self.vlans:
for i_host in i_vlan.host_set.all(): for i_host in i_vlan.host_set.all():
for group in i_host.groups.all(): for group in i_host.groups.all():
for rule in group.rules.all(): for rule in group.rules.all():
self.host2vlan(i_host, rule) self.host2vlan(i_host, rule)
for rule in i_host.rules.all(): for rule in i_host.rules.all():
self.host2vlan(i_host, rule) self.host2vlan(i_host, rule)
#vlanok kozotti kommunikacio engedelyezese # vlanok kozotti kommunikacio engedelyezese
for s_vlan in self.vlans: for s_vlan in self.vlans:
for rule in s_vlan.rules.all(): for rule in s_vlan.rules.all():
self.vlan2vlan(s_vlan, rule) self.vlan2vlan(s_vlan, rule)
#zonak kozotti lancokat zarja le # zonak kozotti lancokat zarja le
for s_vlan in self.vlans: for s_vlan in self.vlans:
for d_vlan in self.vlans: for d_vlan in self.vlans:
self.iptables("-A %s_%s -g LOG_DROP" % (s_vlan, d_vlan)) self.iptables("-A %s_%s -g LOG_DROP" % (s_vlan, d_vlan))
#futas utani dolgok # futas utani dolgok
self.postrun() self.postrun()
if self.IPV6: if self.IPV6:
self.SZABALYOK = [x for x in self.SZABALYOK if not regexp.search(x)] self.SZABALYOK = [x for x in self.SZABALYOK if not regexp.search(x)]
self.SZABALYOK = [regexp_icmp.sub('icmpv6', x) for x in self.SZABALYOK] self.SZABALYOK = [regexp_icmp.sub('icmpv6', x) for x in self.SZABALYOK]
#####
def __init__(self, IPV6=False):
def __init__(self, IPV6=False): self.SZABALYOK=[]
self.SZABALYOK=[] self.SZABALYOK_NAT=[]
self.SZABALYOK_NAT=[] self.IPV6 = IPV6
self.IPV6 = IPV6 self.vlans = models.Vlan.objects.all()
self.vlans = models.Vlan.objects.all() self.hosts = models.Host.objects.all()
self.hosts = models.Host.objects.all() self.dmz = models.Vlan.objects.get(name="DMZ")
self.dmz = models.Vlan.objects.get(name="DMZ") self.pub = models.Vlan.objects.get(name="PUB")
self.pub = models.Vlan.objects.get(name="PUB") self.fw = models.Firewall.objects.all()
self.fw = models.Firewall.objects.all() self.ipt_filter()
self.ipt_filter() if not self.IPV6:
if not self.IPV6: self.ipt_nat()
self.ipt_nat()
def reload(self):
def reload(self): if self.IPV6:
if self.IPV6: process = subprocess.Popen(['/usr/bin/ssh', 'fw2', '/usr/bin/sudo', '/sbin/ip6tables-restore', '-c'], shell=False, stdin=subprocess.PIPE)
process = subprocess.Popen(['/usr/bin/ssh', 'fw2', '/usr/bin/sudo', '/sbin/ip6tables-restore', '-c'], shell=False, stdin=subprocess.PIPE) process.communicate("\n".join(self.SZABALYOK)+"\n")
process.communicate("\n".join(self.SZABALYOK)+"\n") else:
else: process = subprocess.Popen(['/usr/bin/ssh', 'fw2', '/usr/bin/sudo', '/sbin/iptables-restore', '-c'], shell=False, stdin=subprocess.PIPE)
process = subprocess.Popen(['/usr/bin/ssh', 'fw2', '/usr/bin/sudo', '/sbin/iptables-restore', '-c'], shell=False, stdin=subprocess.PIPE) process.communicate("\n".join(self.SZABALYOK)+"\n"+"\n".join(self.SZABALYOK_NAT)+"\n")
process.communicate("\n".join(self.SZABALYOK)+"\n"+"\n".join(self.SZABALYOK_NAT)+"\n")
def show(self):
def show(self): if self.IPV6:
if self.IPV6: return "\n".join(self.SZABALYOK)+"\n"
return "\n".join(self.SZABALYOK)+"\n" else:
else: return "\n".join(self.SZABALYOK)+"\n"+"\n".join(self.SZABALYOK_NAT)+"\n"
return "\n".join(self.SZABALYOK)+"\n"+"\n".join(self.SZABALYOK_NAT)+"\n"
def ipv6_to_octal(ipv6): def ipv6_to_octal(ipv6):
...@@ -319,140 +311,119 @@ def ipv6_to_arpa(ipv6): ...@@ -319,140 +311,119 @@ def ipv6_to_arpa(ipv6):
def dns(): def dns():
vlans = models.Vlan.objects.all() vlans = models.Vlan.objects.all()
regex = re.compile(r'^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$') regex = re.compile(r'^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$')
DNS = [] DNS = []
DNS.append("=cloud.ik.bme.hu:152.66.243.98:600::\n") DNS.append("=cloud.ik.bme.hu:152.66.243.98:600::\n")
DNS.append(":cloud.ik.bme.hu:28:\040\001\007\070\040\001\100\061\000\002\000\000\000\007\000\000:600\n") DNS.append(":cloud.ik.bme.hu:28:\040\001\007\070\040\001\100\061\000\002\000\000\000\007\000\000:600\n")
#tarokkknak # tarokkknak
DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s:600::\n" % (75, 243, 66, 152, "se.hpc.iit.bme.hu")) DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s:600::\n" % (75, 243, 66, 152, "se.hpc.iit.bme.hu"))
DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s:600::\n" % (76, 243, 66, 152, "ce.hpc.iit.bme.hu")) DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s:600::\n" % (76, 243, 66, 152, "ce.hpc.iit.bme.hu"))
DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s:600::\n" % (77, 243, 66, 152, "mon.hpc.iit.bme.hu")) DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s:600::\n" % (77, 243, 66, 152, "mon.hpc.iit.bme.hu"))
DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s:600::\n" % (62, 243, 66, 152, "r.cloud.ik.bme.hu")) DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s:600::\n" % (62, 243, 66, 152, "r.cloud.ik.bme.hu"))
DNS.append("=r.cloud.ik.bme.hu:152.66.243.62:600::\n") DNS.append("=r.cloud.ik.bme.hu:152.66.243.62:600::\n")
DNS.append("Z1.3.0.4.1.0.0.2.8.3.7.0.1.0.0.2.ip6.arpa:dns1.ik.bme.hu:support.ik.bme.hu::::::600\n") #soa DNS.append("Z1.3.0.4.1.0.0.2.8.3.7.0.1.0.0.2.ip6.arpa:dns1.ik.bme.hu:support.ik.bme.hu::::::600\n") # soa
DNS.append("&1.3.0.4.1.0.0.2.8.3.7.0.1.0.0.2.ip6.arpa::dns1.ik.bme.hu:600::\n") #ns DNS.append("&1.3.0.4.1.0.0.2.8.3.7.0.1.0.0.2.ip6.arpa::dns1.ik.bme.hu:600::\n") # ns rekord
DNS.append("&1.3.0.4.1.0.0.2.8.3.7.0.1.0.0.2.ip6.arpa::nic.bme.hu:600::\n") #ns DNS.append("&1.3.0.4.1.0.0.2.8.3.7.0.1.0.0.2.ip6.arpa::nic.bme.hu:600::\n") # ns rekord
# DNS.append("&1.3.0.4.1.0.0.2.8.3.7.0.1.0.0.2.ip6.arpa::ns.bme.hu:600::\n") #ns # DNS.append("&1.3.0.4.1.0.0.2.8.3.7.0.1.0.0.2.ip6.arpa::ns.bme.hu:600::\n") # ns rekord
for i_vlan in vlans: for i_vlan in vlans:
m = regex.search(i_vlan.net4) m = regex.search(i_vlan.net4)
if(i_vlan.name != "DMZ" and i_vlan.name != "PUB"): if(i_vlan.name != "DMZ" and i_vlan.name != "PUB"):
DNS.append("Z%s.%s.in-addr.arpa:dns1.ik.bme.hu:support.ik.bme.hu::::::600\n" % (m.group(2), m.group(1))) DNS.append("Z%s.%s.in-addr.arpa:dns1.ik.bme.hu:support.ik.bme.hu::::::600\n" % (m.group(2), m.group(1)))
DNS.append("&%s.%s.in-addr.arpa::dns1.ik.bme.hu:600::\n" % (m.group(2), m.group(1))) DNS.append("&%s.%s.in-addr.arpa::dns1.ik.bme.hu:600::\n" % (m.group(2), m.group(1)))
DNS.append("Z%s:dns1.ik.bme.hu:support.ik.bme.hu::::::600\n" % i_vlan.domain) DNS.append("Z%s:dns1.ik.bme.hu:support.ik.bme.hu::::::600\n" % i_vlan.domain)
DNS.append("&%s::dns1.ik.bme.hu:600::\n" % i_vlan.domain) DNS.append("&%s::dns1.ik.bme.hu:600::\n" % i_vlan.domain)
if(i_vlan.name == "WAR"): if(i_vlan.name == "WAR"):
DNS.append("Zdns1.%s.%s.%s.in-addr.arpa:dns1.ik.bme.hu:support.ik.bme.hu::::::600\n" % (m.group(3), m.group(2), m.group(1))) DNS.append("Zdns1.%s.%s.%s.in-addr.arpa:dns1.ik.bme.hu:support.ik.bme.hu::::::600\n" % (m.group(3), m.group(2), m.group(1)))
DNS.append("&dns1.%s.%s.%s.in-addr.arpa::dns1.ik.bme.hu:600::\n" % (m.group(3), m.group(2), m.group(1))) DNS.append("&dns1.%s.%s.%s.in-addr.arpa::dns1.ik.bme.hu:600::\n" % (m.group(3), m.group(2), m.group(1)))
for i_host in i_vlan.host_set.all(): for i_host in i_vlan.host_set.all():
ipv4 = ( i_host.pub_ipv4 if i_host.pub_ipv4 and not i_host.shared_ip else i_host.ipv4 ) ipv4 = ( i_host.pub_ipv4 if i_host.pub_ipv4 and not i_host.shared_ip else i_host.ipv4 )
m2 = regex.search(ipv4) m2 = regex.search(ipv4)
#ipv4 # ipv4
DNS.append("=%s.%s:%s:600::\n" % (i_host.hostname, i_vlan.domain, ipv4)) DNS.append("=%s.%s:%s:600::\n" % (i_host.hostname, i_vlan.domain, ipv4))
DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s.%s:600::\n" % (m2.group(4), m2.group(3), m2.group(2), m2.group(1), i_host.hostname, i_vlan.domain)) DNS.append("^%s.dns1.%s.%s.%s.in-addr.arpa:%s.%s:600::\n" % (m2.group(4), m2.group(3), m2.group(2), m2.group(1), i_host.hostname, i_vlan.domain))
#ipv6 # ipv6
DNS.append(":%s.%s:28:%s:600\n" % (i_host.hostname, i_vlan.domain, ipv6_to_octal(i_host.ipv6))) DNS.append(":%s.%s:28:%s:600\n" % (i_host.hostname, i_vlan.domain, ipv6_to_octal(i_host.ipv6)))
DNS.append("^%s:%s.%s:600::\n" % (ipv6_to_arpa(i_host.ipv6), i_host.hostname, i_vlan.domain)) DNS.append("^%s:%s.%s:600::\n" % (ipv6_to_arpa(i_host.ipv6), i_host.hostname, i_vlan.domain))
process = subprocess.Popen(['/usr/bin/ssh', 'tinydns@%s' % DNS_SERVER], shell=False, stdin=subprocess.PIPE) process = subprocess.Popen(['/usr/bin/ssh', 'tinydns@%s' % DNS_SERVER], shell=False, stdin=subprocess.PIPE)
process.communicate("\n".join(DNS)+"\n") process.communicate("\n".join(DNS)+"\n")
def prefix_to_mask(prefix): def prefix_to_mask(prefix):
t = [0,0,0,0] t = [0, 0, 0, 0]
for i in range(0,4): for i in range(0, 4):
if prefix > i*8+7: if prefix > i*8+7:
t[i] = 255 t[i] = 255
elif i*8 < prefix and prefix <= (i+1)*8: elif i*8 < prefix and prefix <= (i+1)*8:
t[i] = 256 - (2 ** ((i+1)*8 - prefix)) t[i] = 256 - (2 ** ((i+1)*8 - prefix))
return ".".join([str(i) for i in t]) return ".".join([str(i) for i in t])
def dhcp(): def dhcp():
vlans = models.Vlan.objects.all() vlans = models.Vlan.objects.all()
regex = re.compile(r'^([0-9]+)\.([0-9]+)\.[0-9]+\.[0-9]+\s+([0-9]+)\.([0-9]+)\.[0-9]+\.[0-9]+$') regex = re.compile(r'^([0-9]+)\.([0-9]+)\.[0-9]+\.[0-9]+\s+([0-9]+)\.([0-9]+)\.[0-9]+\.[0-9]+$')
DHCP = [] DHCP = []
#/tools/dhcp3/dhcpd.conf.generated # /tools/dhcp3/dhcpd.conf.generated
for i_vlan in vlans: for i_vlan in vlans:
if(i_vlan.dhcp_pool): if(i_vlan.dhcp_pool):
m = regex.search(i_vlan.dhcp_pool) m = regex.search(i_vlan.dhcp_pool)
if(m or i_vlan.dhcp_pool == "manual"): if(m or i_vlan.dhcp_pool == "manual"):
DHCP.append (''' DHCP.append ('''
#%(name)s - %(interface)s # %(name)s - %(interface)s
subnet %(net)s netmask %(netmask)s { subnet %(net)s netmask %(netmask)s {
%(extra)s; %(extra)s;
option domain-name "%(domain)s"; option domain-name "%(domain)s";
option routers %(router)s; option routers %(router)s;
option domain-name-servers %(dnsserver)s; option domain-name-servers %(dnsserver)s;
option ntp-servers %(ntp)s; option ntp-servers %(ntp)s;
next-server %(tftp)s; next-server %(tftp)s;
authoritative; authoritative;
filename \"pxelinux.0\"; filename \"pxelinux.0\";
allow bootp; allow booting; allow bootp; allow booting;
}''' % { }''' % {
'net': i_vlan.net4, 'net': i_vlan.net4,
'netmask': prefix_to_mask(i_vlan.prefix4), 'netmask': prefix_to_mask(i_vlan.prefix4),
'domain': i_vlan.domain, 'domain': i_vlan.domain,
'router': i_vlan.ipv4, 'router': i_vlan.ipv4,
'ntp': i_vlan.ipv4, 'ntp': i_vlan.ipv4,
'dnsserver': DNS_SERVER, 'dnsserver': DNS_SERVER,
'extra': "range %s" % i_vlan.dhcp_pool if m else "deny unknown-clients", 'extra': "range %s" % i_vlan.dhcp_pool if m else "deny unknown-clients",
'interface': i_vlan.interface, 'interface': i_vlan.interface,
'name': i_vlan.name, 'name': i_vlan.name,
'tftp': i_vlan.ipv4 'tftp': i_vlan.ipv4
}) })
for i_host in i_vlan.host_set.all(): for i_host in i_vlan.host_set.all():
DHCP.append (''' DHCP.append ('''
host %(hostname)s { host %(hostname)s {
hardware ethernet %(mac)s; hardware ethernet %(mac)s;
fixed-address %(ipv4)s; fixed-address %(ipv4)s;
}''' % { }''' % {
'hostname': i_host.hostname, 'hostname': i_host.hostname,
'mac': i_host.mac, 'mac': i_host.mac,
'ipv4': i_host.ipv4, 'ipv4': i_host.ipv4,
}) })
process = subprocess.Popen(['/usr/bin/ssh', 'fw2', 'cat > /tools/dhcp3/dhcpd.conf.generated;sudo /etc/init.d/isc-dhcp-server restart'], shell=False, stdin=subprocess.PIPE) process = subprocess.Popen(['/usr/bin/ssh', 'fw2', 'cat > /tools/dhcp3/dhcpd.conf.generated;sudo /etc/init.d/isc-dhcp-server restart'], shell=False, stdin=subprocess.PIPE)
# print "\n".join(DHCP)+"\n" # print "\n".join(DHCP)+"\n"
process.communicate("\n".join(DHCP)+"\n") process.communicate("\n".join(DHCP)+"\n")
#ipt_filter()
#ipt_nat()
#process = subprocess.Popen(['/usr/bin/sudo', 'iptables-restore'], shell=False, stdin=subprocess.PIPE)
#process.communicate("\n".join(SZABALYOK)+"\n"+"\n".join(SZABALYOK_NAT)+"\n")
#blabla = firewall()
#process = subprocess.Popen(['/usr/bin/sudo', 'ip6tables-restore'], shell=False, stdin=subprocess.PIPE)
#process.communicate("\n".join(SZABALYOK)+"\n")
#dns()
#dhcp()
i=2
''' '''
i=2
for mac, name, ipend in [("18:a9:05:64:19:aa", "mega6", 16), ("00:1e:0b:e9:79:1e", "blade1", 21), ("00:22:64:9c:fd:34", "blade2", 22), ("00:1e:0b:ec:65:46", "blade3", 23), ("b4:b5:2f:61:d2:5a", "cloud-man", 1)]: for mac, name, ipend in [("18:a9:05:64:19:aa", "mega6", 16), ("00:1e:0b:e9:79:1e", "blade1", 21), ("00:22:64:9c:fd:34", "blade2", 22), ("00:1e:0b:ec:65:46", "blade3", 23), ("b4:b5:2f:61:d2:5a", "cloud-man", 1)]:
h1 = models.Host(hostname= name, vlan=models.Vlan.objects.get(vid=3), mac=mac, ipv4="10.3.1.%d" % ipend, ipv6="2001:738:2001:4031:3:1:%d:0" % ipend, owner=auth.models.User.objects.get(username="bd")) h1 = models.Host(hostname= name, vlan=models.Vlan.objects.get(vid=3), mac=mac, ipv4="10.3.1.%d" % ipend, ipv6="2001:738:2001:4031:3:1:%d:0" % ipend, owner=auth.models.User.objects.get(username="bd"))
try: try:
h1.save() h1.save()
h1.groups.add(models.Group.objects.get(name="netezhet manbol")) h1.groups.add(models.Group.objects.get(name="netezhet manbol"))
h1.save() h1.save()
# i = i + 1 # i = i + 1
except: except:
print "nemok %s" % name print "nemok %s" % name
''' '''
#try:
# h1.save()
# h1.groups.add(models.Group.objects.get(name="irodai gep"))
# h1.save()
#except:
# print "nemsikerult"
...@@ -9,51 +9,51 @@ from south.modelsinspector import add_introspection_rules ...@@ -9,51 +9,51 @@ from south.modelsinspector import add_introspection_rules
from django.core.validators import MinValueValidator, MaxValueValidator from django.core.validators import MinValueValidator, MaxValueValidator
class Rule(models.Model): class Rule(models.Model):
CHOICES_type = (('host', 'host'), ('firewall', 'firewall'), ('vlan', 'vlan')) CHOICES_type = (('host', 'host'), ('firewall', 'firewall'), ('vlan', 'vlan'))
CHOICES_proto = (('tcp', 'tcp'), ('udp', 'udp'), ('icmp', 'icmp')) CHOICES_proto = (('tcp', 'tcp'), ('udp', 'udp'), ('icmp', 'icmp'))
CHOICES_dir = (('0', 'out'), ('1', 'in')) CHOICES_dir = (('0', 'out'), ('1', 'in'))
direction = models.CharField(max_length=1, choices=CHOICES_dir, blank=False) direction = models.CharField(max_length=1, choices=CHOICES_dir, blank=False)
description = models.TextField(blank=True) description = models.TextField(blank=True)
vlan = models.ManyToManyField('Vlan', symmetrical=False, blank=True, null=True) vlan = models.ManyToManyField('Vlan', symmetrical=False, blank=True, null=True)
dport = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), MaxValueValidator(65535)]) dport = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), MaxValueValidator(65535)])
sport = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), MaxValueValidator(65535)]) sport = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), MaxValueValidator(65535)])
proto = models.CharField(max_length=10, choices=CHOICES_proto, blank=True, null=True) proto = models.CharField(max_length=10, choices=CHOICES_proto, blank=True, null=True)
extra = models.TextField(blank=True) extra = models.TextField(blank=True)
accept = models.BooleanField(default=False) accept = models.BooleanField(default=False)
owner = models.ForeignKey(User, blank=True, null=True) owner = models.ForeignKey(User, blank=True, null=True)
r_type = models.CharField(max_length=10, choices=CHOICES_type) r_type = models.CharField(max_length=10, choices=CHOICES_type)
nat = models.BooleanField(default=False) nat = models.BooleanField(default=False)
nat_dport = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), MaxValueValidator(65535)]) nat_dport = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), MaxValueValidator(65535)])
def __unicode__(self): def __unicode__(self):
return self.desc() return self.desc()
def color_desc(self): def color_desc(self):
para = '</span>' para = '</span>'
if(self.dport): if(self.dport):
para = "dport=%s %s" % (self.dport, para) para = "dport=%s %s" % (self.dport, para)
if(self.sport): if(self.sport):
para = "sport=%s %s" % (self.sport, para) para = "sport=%s %s" % (self.sport, para)
if(self.proto): if(self.proto):
para = "proto=%s %s" % (self.proto, para) para = "proto=%s %s" % (self.proto, para)
para= u'<span style="color: #00FF00;">' + para para= u'<span style="color: #00FF00;">' + para
return u'<span style="color: #FF0000;">[' + self.r_type + u']</span> ' + (self.vlan_l() + u'<span style="color: #0000FF;"> ▸ </span>' + self.r_type if self.direction=='1' else self.r_type + u'<span style="color: #0000FF;"> ▸ </span>' + self.vlan_l()) + ' ' + para + ' ' +self.description return u'<span style="color: #FF0000;">[' + self.r_type + u']</span> ' + (self.vlan_l() + u'<span style="color: #0000FF;"> ▸ </span>' + self.r_type if self.direction=='1' else self.r_type + u'<span style="color: #0000FF;"> ▸ </span>' + self.vlan_l()) + ' ' + para + ' ' +self.description
color_desc.allow_tags = True color_desc.allow_tags = True
def desc(self): def desc(self):
para = u"" para = u""
if(self.dport): if(self.dport):
para = "dport=%s %s" % (self.dport, para) para = "dport=%s %s" % (self.dport, para)
if(self.sport): if(self.sport):
para = "sport=%s %s" % (self.sport, para) para = "sport=%s %s" % (self.sport, para)
if(self.proto): if(self.proto):
para = "proto=%s %s" % (self.proto, para) para = "proto=%s %s" % (self.proto, para)
return u'[' + self.r_type + u'] ' + (self.vlan_l() + u' ▸ ' + self.r_type if self.direction=='1' else self.r_type + u' ▸ ' + self.vlan_l()) + u' ' + para + u' ' +self.description return u'[' + self.r_type + u'] ' + (self.vlan_l() + u' ▸ ' + self.r_type if self.direction=='1' else self.r_type + u' ▸ ' + self.vlan_l()) + u' ' + para + u' ' +self.description
def vlan_l(self): def vlan_l(self):
retval = [] retval = []
for vl in self.vlan.all(): for vl in self.vlan.all():
retval.append(vl.name) retval.append(vl.name)
return u', '.join(retval) return u', '.join(retval)
class Vlan(models.Model): class Vlan(models.Model):
vid = models.IntegerField(unique=True) vid = models.IntegerField(unique=True)
...@@ -76,19 +76,19 @@ class Vlan(models.Model): ...@@ -76,19 +76,19 @@ class Vlan(models.Model):
def __unicode__(self): def __unicode__(self):
return self.name return self.name
def net_ipv6(self): def net_ipv6(self):
return self.net6 + "/" + unicode(self.prefix6) return self.net6 + "/" + unicode(self.prefix6)
def net_ipv4(self): def net_ipv4(self):
return self.net4 + "/" + unicode(self.prefix4) return self.net4 + "/" + unicode(self.prefix4)
def rules_l(self): def rules_l(self):
retval = [] retval = []
for rl in self.rules.all(): for rl in self.rules.all():
retval.append(unicode(rl)) retval.append(unicode(rl))
return ', '.join(retval) return ', '.join(retval)
def snat_to_l(self): def snat_to_l(self):
retval = [] retval = []
for rl in self.snat_to.all(): for rl in self.snat_to.all():
retval.append(unicode(rl)) retval.append(unicode(rl))
return ', '.join(retval) return ', '.join(retval)
class Group(models.Model): class Group(models.Model):
name = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=20, unique=True)
...@@ -117,55 +117,55 @@ class Host(models.Model): ...@@ -117,55 +117,55 @@ class Host(models.Model):
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
if not self.id and not self.ipv6: if not self.id and not self.ipv6:
self.ipv6 = ipv4_2_ipv6(self.ipv4) self.ipv6 = ipv4_2_ipv6(self.ipv4)
if not self.shared_ip and self.pub_ipv4 and Host.objects.exclude(id=self.id).filter(pub_ipv4=self.pub_ipv4): if not self.shared_ip and self.pub_ipv4 and Host.objects.exclude(id=self.id).filter(pub_ipv4=self.pub_ipv4):
raise ValidationError("Ha a shared_ip be van pipalva, akkor egyedinek kell lennie a pub_ipv4-nek!") raise ValidationError("Ha a shared_ip be van pipalva, akkor egyedinek kell lennie a pub_ipv4-nek!")
if Host.objects.exclude(id=self.id).filter(pub_ipv4=self.ipv4): if Host.objects.exclude(id=self.id).filter(pub_ipv4=self.ipv4):
raise ValidationError("Egy masik host natolt cimet nem hasznalhatod sajat ipv4-nek") raise ValidationError("Egy masik host natolt cimet nem hasznalhatod sajat ipv4-nek")
super(Host, self).save(*args, **kwargs) super(Host, self).save(*args, **kwargs)
def groups_l(self): def groups_l(self):
retval = [] retval = []
for grp in self.groups.all(): for grp in self.groups.all():
retval.append(grp.name) retval.append(grp.name)
return ', '.join(retval) return ', '.join(retval)
def rules_l(self): def rules_l(self):
retval = [] retval = []
for rl in self.rules.all(): for rl in self.rules.all():
retval.append(unicode(rl.color_desc())) retval.append(unicode(rl.color_desc()))
return '<br>'.join(retval) return '<br>'.join(retval)
rules_l.allow_tags = True rules_l.allow_tags = True
def enable_net(self): def enable_net(self):
self.groups.add(Group.objects.get(name="netezhet")) self.groups.add(Group.objects.get(name="netezhet"))
def add_port(self, proto, public, private): def add_port(self, proto, public, private):
proto = "tcp" if (proto == "tcp") else "udp" proto = "tcp" if (proto == "tcp") else "udp"
if public < 1024: if public < 1024:
raise ValidationError("Csak az 1024 feletti portok hasznalhatok") raise ValidationError("Csak az 1024 feletti portok hasznalhatok")
for host in Host.objects.filter(pub_ipv4=self.pub_ipv4): for host in Host.objects.filter(pub_ipv4=self.pub_ipv4):
if host.rules.filter(nat=True, proto=proto, dport=public): if host.rules.filter(nat=True, proto=proto, dport=public):
raise ValidationError("A %s %s port mar hasznalva" % (proto, public)) raise ValidationError("A %s %s port mar hasznalva" % (proto, public))
rule = Rule(direction='1', owner=self.owner, description=u"%s %s %s ▸ %s" % (self.hostname, proto, public, private), dport=public, proto=proto, nat=True, accept=True, r_type="host", nat_dport=private) rule = Rule(direction='1', owner=self.owner, description=u"%s %s %s ▸ %s" % (self.hostname, proto, public, private), dport=public, proto=proto, nat=True, accept=True, r_type="host", nat_dport=private)
rule.full_clean() rule.full_clean()
rule.save() rule.save()
rule.vlan.add(Vlan.objects.get(name="PUB")) rule.vlan.add(Vlan.objects.get(name="PUB"))
rule.vlan.add(Vlan.objects.get(name="HOT")) rule.vlan.add(Vlan.objects.get(name="HOT"))
rule.vlan.add(Vlan.objects.get(name="LAB")) rule.vlan.add(Vlan.objects.get(name="LAB"))
rule.vlan.add(Vlan.objects.get(name="DMZ")) rule.vlan.add(Vlan.objects.get(name="DMZ"))
rule.vlan.add(Vlan.objects.get(name="VM-NET")) rule.vlan.add(Vlan.objects.get(name="VM-NET"))
rule.vlan.add(Vlan.objects.get(name="WAR")) rule.vlan.add(Vlan.objects.get(name="WAR"))
rule.vlan.add(Vlan.objects.get(name="OFF2")) rule.vlan.add(Vlan.objects.get(name="OFF2"))
self.rules.add(rule) self.rules.add(rule)
def del_port(self, proto, public): def del_port(self, proto, public):
self.rules.filter(owner=self.owner, proto=proto, nat=True, dport=public).delete() self.rules.filter(owner=self.owner, proto=proto, nat=True, dport=public).delete()
def list_ports(self): def list_ports(self):
retval = [] retval = []
for rule in self.rules.filter(owner=self.owner, nat=True): for rule in self.rules.filter(owner=self.owner, nat=True):
retval.append({'proto': rule.proto, 'public': rule.dport, 'private': rule.nat_dport}) retval.append({'proto': rule.proto, 'public': rule.dport, 'private': rule.nat_dport})
return retval return retval
def del_rules(self): def del_rules(self):
self.rules.filter(owner=self.owner).delete() self.rules.filter(owner=self.owner).delete()
class Firewall(models.Model): class Firewall(models.Model):
name = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=20, unique=True)
......
...@@ -6,43 +6,43 @@ from firewall.fw import * ...@@ -6,43 +6,43 @@ from firewall.fw import *
def reload_firewall_lock(): def reload_firewall_lock():
acquire_lock = lambda: cache.add("reload_lock1", "true", 9) acquire_lock = lambda: cache.add("reload_lock1", "true", 9)
if acquire_lock(): if acquire_lock():
print "megszereztem" print "megszereztem"
ReloadTask.delay() ReloadTask.delay()
else: else:
print "nem szereztem meg" print "nem szereztem meg"
class ReloadTask(Task): class ReloadTask(Task):
def run(self, **kwargs): def run(self, **kwargs):
acquire_lock = lambda: cache.add("reload_lock1", "true", 90) acquire_lock = lambda: cache.add("reload_lock1", "true", 90)
release_lock = lambda: cache.delete("reload_lock1") release_lock = lambda: cache.delete("reload_lock1")
if not acquire_lock(): if not acquire_lock():
print "mar folyamatban van egy reload" print "mar folyamatban van egy reload"
return return
print "indul" print "indul"
time.sleep(10) time.sleep(10)
try: try:
print "ipv4" print "ipv4"
ipv4 = firewall() ipv4 = firewall()
ipv4.reload() ipv4.reload()
# print ipv4.show() # print ipv4.show()
print "ipv6" print "ipv6"
ipv6 = firewall(True) ipv6 = firewall(True)
ipv6.reload() ipv6.reload()
print "dns" print "dns"
dns() dns()
print "dhcp" print "dhcp"
dhcp() dhcp()
print "vege" print "vege"
except: except:
raise raise
print "nem sikerult :(" print "nem sikerult :("
print "leall" print "leall"
release_lock() release_lock()
...@@ -15,63 +15,63 @@ import sys ...@@ -15,63 +15,63 @@ import sys
def reload_firewall(request): def reload_firewall(request):
if request.user.is_authenticated(): if request.user.is_authenticated():
if(request.user.is_superuser): if(request.user.is_superuser):
html = u"Be vagy jelentkezve es admin is vagy, kedves %s!" % request.user.username html = u"Be vagy jelentkezve es admin is vagy, kedves %s!" % request.user.username
html += "<br> 10 masodperc mulva ujratoltodik" html += "<br> 10 masodperc mulva ujratoltodik"
ReloadTask.delay() ReloadTask.delay()
else: else:
html = u"Be vagy jelentkezve, csak nem vagy admin, kedves %s!" % request.user.username html = u"Be vagy jelentkezve, csak nem vagy admin, kedves %s!" % request.user.username
else: else:
html = u"Nem vagy bejelentkezve, kedves ismeretlen!" html = u"Nem vagy bejelentkezve, kedves ismeretlen!"
return HttpResponse(html) return HttpResponse(html)
@csrf_exempt @csrf_exempt
def firewall_api(request): def firewall_api(request):
if request.method == 'POST': if request.method == 'POST':
try: try:
data=json.loads(base64.b64decode(request.POST["data"])) data=json.loads(base64.b64decode(request.POST["data"]))
command = request.POST["command"] command = request.POST["command"]
if(data["password"] != "bdmegintelrontottaanetet"): if(data["password"] != "bdmegintelrontottaanetet"):
raise Exception("rossz jelszo") raise Exception("rossz jelszo")
if(not(data["vlan"] == "vm-net" or data["vlan"] == "war")): if(not(data["vlan"] == "vm-net" or data["vlan"] == "war")):
raise Exception("csak vm-net es war-re mukodik") raise Exception("csak vm-net es war-re mukodik")
data["hostname"] = re.sub(r' ','_', data["hostname"]) data["hostname"] = re.sub(r' ','_', data["hostname"])
if(command == "create"): if(command == "create"):
data["owner"] = "opennebula" data["owner"] = "opennebula"
owner = auth.models.User.objects.get(username=data["owner"]) owner = auth.models.User.objects.get(username=data["owner"])
host = models.Host(hostname=data["hostname"], vlan=models.Vlan.objects.get(name=data["vlan"]), mac=data["mac"], ipv4=data["ip"], owner=owner, description=data["description"], pub_ipv4=models.Vlan.objects.get(name=data["vlan"]).snat_ip, shared_ip=True) host = models.Host(hostname=data["hostname"], vlan=models.Vlan.objects.get(name=data["vlan"]), mac=data["mac"], ipv4=data["ip"], owner=owner, description=data["description"], pub_ipv4=models.Vlan.objects.get(name=data["vlan"]).snat_ip, shared_ip=True)
host.full_clean() host.full_clean()
host.save() host.save()
host.enable_net() host.enable_net()
for p in data["portforward"]: for p in data["portforward"]:
host.add_port(proto=p["proto"], public=int(p["public_port"]), private=int(p["private_port"])) host.add_port(proto=p["proto"], public=int(p["public_port"]), private=int(p["private_port"]))
elif(command == "destroy"): elif(command == "destroy"):
data["owner"] = "opennebula" data["owner"] = "opennebula"
print data["hostname"] print data["hostname"]
owner = auth.models.User.objects.get(username=data["owner"]) owner = auth.models.User.objects.get(username=data["owner"])
host = models.Host.objects.get(hostname=data["hostname"], owner=owner) host = models.Host.objects.get(hostname=data["hostname"], owner=owner)
host.del_rules() host.del_rules()
host.delete() host.delete()
else: else:
raise Exception("rossz parancs") raise Exception("rossz parancs")
reload_firewall_lock() reload_firewall_lock()
except (ValidationError, IntegrityError, AttributeError, Exception) as e: except (ValidationError, IntegrityError, AttributeError, Exception) as e:
return HttpResponse(u"rosszul hasznalod! :(\n%s\n" % e); return HttpResponse(u"rosszul hasznalod! :(\n%s\n" % e);
except: except:
# raise # raise
return HttpResponse(u"rosszul hasznalod! :(\n"); return HttpResponse(u"rosszul hasznalod! :(\n");
return HttpResponse(u"ok"); return HttpResponse(u"ok");
return HttpResponse(u"ez kerlek egy api lesz!\n"); return HttpResponse(u"ez kerlek egy api lesz!\n");
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment