Commit 40c3495c by x

firewall: code formatting

parent 114e301a
......@@ -42,5 +42,5 @@ def val_domain(value):
raise ValidationError(u'%s - helytelen domain' % value)
def ipv4_2_ipv6(ipv4):
m = ipv4_re.match(ipv4)
return "2001:738:2001:4031:%s:%s:%s:0" % (m.group(1), m.group(2), m.group(3))
m = ipv4_re.match(ipv4)
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 firewall import models
import os
......@@ -15,274 +8,273 @@ DNS_SERVER = "152.66.243.60"
class firewall:
IPV6=False
SZABALYOK = None
SZABALYOK_NAT = []
vlans = None
dmz = None
pub = None
hosts = None
fw = None
def dportsport(self, rule, repl=True):
retval = " "
if(rule.proto == "tcp" or rule.proto == "udp"):
retval = "-p %s " % rule.proto
if(rule.sport):
retval += " --sport %s " % rule.sport
if(rule.dport):
retval += " --dport %s " % ( rule.nat_dport if (repl and rule.nat and rule.direction == '1') else rule.dport )
elif(rule.proto == "icmp"):
retval = "-p %s " % rule.proto
return retval
def iptables(self, s):
self.SZABALYOK.append(s)
def iptablesnat(self, s):
self.SZABALYOK_NAT.append(s)
def host2vlan(self, host, rule):
if(self.IPV6):
ipaddr = host.ipv6 + "/112"
else:
ipaddr = host.ipv4
dport_sport = self.dportsport(rule)
for vlan in rule.vlan.all():
if(rule.accept):
if(rule.direction == '0' and vlan.name == "PUB"):
if(rule.dport == 25):
self.iptables("-A PUB_OUT -s %s %s -p tcp --dport 25 -j LOG_ACC" % (ipaddr, rule.extra))
break
action = "PUB_OUT"
else:
action = "LOG_ACC"
else:
action = "LOG_DROP"
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));
else:
self.iptables("-A %s_%s -s %s %s %s -g %s" % (host.vlan, vlan, ipaddr, dport_sport, rule.extra, action));
def fw2vlan(self, rule):
dport_sport = self.dportsport(rule)
for vlan in rule.vlan.all():
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"));
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"));
def vlan2vlan(self, l_vlan, rule):
dport_sport = self.dportsport(rule)
for vlan in rule.vlan.all():
if(rule.accept):
if((rule.direction == '0') and vlan.name == "PUB"):
action = "PUB_OUT"
else:
action = "LOG_ACC"
else:
action = "LOG_DROP"
if(rule.direction == '1'): #HOSTHOZ megy
self.iptables("-A %s_%s %s %s -g %s" % (vlan, l_vlan, dport_sport, rule.extra, action));
else:
self.iptables("-A %s_%s %s %s -g %s" % (l_vlan, vlan, dport_sport, rule.extra, action));
def prerun(self):
self.iptables("*filter")
self.iptables(":INPUT DROP [88:6448]")
self.iptables(":FORWARD DROP [0:0]")
self.iptables(":OUTPUT DROP [50:6936]")
#inicialize logging
self.iptables("-N LOG_DROP")
#windows port scan are silently dropped
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 -j LOG --log-level 7 --log-prefix \"[ipt][drop]\"")
self.iptables("-A LOG_DROP -j DROP")
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 ACCEPT")
if not self.IPV6:
#The chain which test is a packet has a valid public destination IP
#(RFC-3330) packages passing this chain has valid destination IP addressed
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 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 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 127.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
#(RFC-3330) packages passing this chain has valid destination IP addressed
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 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 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 127.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
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 -j r_pub_dIP")
self.iptables("-N PUB_OUT")
if not self.IPV6:
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 ESTABLISHED,RELATED -j ACCEPT")
self.iptables("-A FORWARD -p icmp --icmp-type echo-request -g LOG_ACC")
if not self.IPV6:
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 -i lo -j ACCEPT")
if not self.IPV6:
self.iptables("-A INPUT -j r_pub_sIP")
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 -o lo -j ACCEPT")
self.iptables("-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT")
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 445 -j LOG_ACC")
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 udp --dport 445 -j LOG_DROP")
self.iptables("-A PUB_OUT -g LOG_ACC")
self.iptables("-A FORWARD -g LOG_DROP")
self.iptables("-A INPUT -g LOG_DROP")
self.iptables("-A OUTPUT -g LOG_DROP")
self.iptables("COMMIT")
def ipt_nat(self):
self.iptablesnat("*nat")
self.iptablesnat(":PREROUTING ACCEPT [0:0]")
self.iptablesnat(":INPUT ACCEPT [0:0]")
self.iptablesnat(":OUTPUT ACCEPT [1:708]")
self.iptablesnat(":POSTROUTING ACCEPT [1:708]")
#portforward
for host in self.hosts.exclude(pub_ipv4=None):
for rule in host.rules.filter(nat=True, direction='1'):
dport_sport = self.dportsport(rule, False)
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))
#sajat publikus ipvel rendelkezo gepek szabalyai
for host in self.hosts.exclude(shared_ip=True):
if(host.pub_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))
#alapertelmezett nat szabalyok a vlanokra
for s_vlan in self.vlans:
if(s_vlan.snat_ip):
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))
#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 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("COMMIT")
def ipt_filter(self):
regexp = re.compile('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+')
regexp_icmp = re.compile('icmp');
#futas elotti dolgok
self.prerun()
#tuzfal sajat szabalyai
for f in self.fw:
for rule in f.rules.all():
self.fw2vlan(rule)
#zonak kozotti lancokra ugras
for s_vlan in self.vlans:
for d_vlan in self.vlans:
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))
#hosztok szabalyai
for i_vlan in self.vlans:
for i_host in i_vlan.host_set.all():
for group in i_host.groups.all():
for rule in group.rules.all():
self.host2vlan(i_host, rule)
for rule in i_host.rules.all():
self.host2vlan(i_host, rule)
#vlanok kozotti kommunikacio engedelyezese
for s_vlan in self.vlans:
for rule in s_vlan.rules.all():
self.vlan2vlan(s_vlan, rule)
#zonak kozotti lancokat zarja le
for s_vlan in self.vlans:
for d_vlan in self.vlans:
self.iptables("-A %s_%s -g LOG_DROP" % (s_vlan, d_vlan))
#futas utani dolgok
self.postrun()
if self.IPV6:
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]
#####
def __init__(self, IPV6=False):
self.SZABALYOK=[]
self.SZABALYOK_NAT=[]
self.IPV6 = IPV6
self.vlans = models.Vlan.objects.all()
self.hosts = models.Host.objects.all()
self.dmz = models.Vlan.objects.get(name="DMZ")
self.pub = models.Vlan.objects.get(name="PUB")
self.fw = models.Firewall.objects.all()
self.ipt_filter()
if not self.IPV6:
self.ipt_nat()
def reload(self):
if self.IPV6:
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")
else:
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")
def show(self):
if self.IPV6:
return "\n".join(self.SZABALYOK)+"\n"
else:
return "\n".join(self.SZABALYOK)+"\n"+"\n".join(self.SZABALYOK_NAT)+"\n"
IPV6=False
SZABALYOK = None
SZABALYOK_NAT = []
vlans = None
dmz = None
pub = None
hosts = None
fw = None
def dportsport(self, rule, repl=True):
retval = " "
if(rule.proto == "tcp" or rule.proto == "udp"):
retval = "-p %s " % rule.proto
if(rule.sport):
retval += " --sport %s " % rule.sport
if(rule.dport):
retval += " --dport %s " % ( rule.nat_dport if (repl and rule.nat and rule.direction == '1') else rule.dport )
elif(rule.proto == "icmp"):
retval = "-p %s " % rule.proto
return retval
def iptables(self, s):
self.SZABALYOK.append(s)
def iptablesnat(self, s):
self.SZABALYOK_NAT.append(s)
def host2vlan(self, host, rule):
if(self.IPV6):
ipaddr = host.ipv6 + "/112"
else:
ipaddr = host.ipv4
dport_sport = self.dportsport(rule)
for vlan in rule.vlan.all():
if(rule.accept):
if(rule.direction == '0' and vlan.name == "PUB"):
if(rule.dport == 25):
self.iptables("-A PUB_OUT -s %s %s -p tcp --dport 25 -j LOG_ACC" % (ipaddr, rule.extra))
break
action = "PUB_OUT"
else:
action = "LOG_ACC"
else:
action = "LOG_DROP"
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))
else:
self.iptables("-A %s_%s -s %s %s %s -g %s" % (host.vlan, vlan, ipaddr, dport_sport, rule.extra, action))
def fw2vlan(self, rule):
dport_sport = self.dportsport(rule)
for vlan in rule.vlan.all():
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"))
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"))
def vlan2vlan(self, l_vlan, rule):
dport_sport = self.dportsport(rule)
for vlan in rule.vlan.all():
if(rule.accept):
if((rule.direction == '0') and vlan.name == "PUB"):
action = "PUB_OUT"
else:
action = "LOG_ACC"
else:
action = "LOG_DROP"
if(rule.direction == '1'): # HOSTHOZ megy
self.iptables("-A %s_%s %s %s -g %s" % (vlan, l_vlan, dport_sport, rule.extra, action))
else:
self.iptables("-A %s_%s %s %s -g %s" % (l_vlan, vlan, dport_sport, rule.extra, action))
def prerun(self):
self.iptables("*filter")
self.iptables(":INPUT DROP [88:6448]")
self.iptables(":FORWARD DROP [0:0]")
self.iptables(":OUTPUT DROP [50:6936]")
# inicialize logging
self.iptables("-N LOG_DROP")
# windows port scan are silently dropped
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 -j LOG --log-level 7 --log-prefix \"[ipt][drop]\"")
self.iptables("-A LOG_DROP -j DROP")
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 ACCEPT")
if not self.IPV6:
# The chain which test is a packet has a valid public destination IP
# (RFC-3330) packages passing this chain has valid destination IP addressed
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 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 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 127.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
# (RFC-3330) packages passing this chain has valid destination IP addressed
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 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 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 127.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
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 -j r_pub_dIP")
self.iptables("-N PUB_OUT")
if not self.IPV6:
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 ESTABLISHED,RELATED -j ACCEPT")
self.iptables("-A FORWARD -p icmp --icmp-type echo-request -g LOG_ACC")
if not self.IPV6:
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 -i lo -j ACCEPT")
if not self.IPV6:
self.iptables("-A INPUT -j r_pub_sIP")
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 -o lo -j ACCEPT")
self.iptables("-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT")
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 445 -j LOG_ACC")
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 udp --dport 445 -j LOG_DROP")
self.iptables("-A PUB_OUT -g LOG_ACC")
self.iptables("-A FORWARD -g LOG_DROP")
self.iptables("-A INPUT -g LOG_DROP")
self.iptables("-A OUTPUT -g LOG_DROP")
self.iptables("COMMIT")
def ipt_nat(self):
self.iptablesnat("*nat")
self.iptablesnat(":PREROUTING ACCEPT [0:0]")
self.iptablesnat(":INPUT ACCEPT [0:0]")
self.iptablesnat(":OUTPUT ACCEPT [1:708]")
self.iptablesnat(":POSTROUTING ACCEPT [1:708]")
# portforward
for host in self.hosts.exclude(pub_ipv4=None):
for rule in host.rules.filter(nat=True, direction='1'):
dport_sport = self.dportsport(rule, False)
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))
# sajat publikus ipvel rendelkezo gepek szabalyai
for host in self.hosts.exclude(shared_ip=True):
if(host.pub_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))
# alapertelmezett nat szabalyok a vlanokra
for s_vlan in self.vlans:
if(s_vlan.snat_ip):
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))
# 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 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("COMMIT")
def ipt_filter(self):
regexp = re.compile('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+')
regexp_icmp = re.compile('icmp')
# futas elotti dolgok
self.prerun()
# tuzfal sajat szabalyai
for f in self.fw:
for rule in f.rules.all():
self.fw2vlan(rule)
# zonak kozotti lancokra ugras
for s_vlan in self.vlans:
for d_vlan in self.vlans:
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))
# hosztok szabalyai
for i_vlan in self.vlans:
for i_host in i_vlan.host_set.all():
for group in i_host.groups.all():
for rule in group.rules.all():
self.host2vlan(i_host, rule)
for rule in i_host.rules.all():
self.host2vlan(i_host, rule)
# vlanok kozotti kommunikacio engedelyezese
for s_vlan in self.vlans:
for rule in s_vlan.rules.all():
self.vlan2vlan(s_vlan, rule)
# zonak kozotti lancokat zarja le
for s_vlan in self.vlans:
for d_vlan in self.vlans:
self.iptables("-A %s_%s -g LOG_DROP" % (s_vlan, d_vlan))
# futas utani dolgok
self.postrun()
if self.IPV6:
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]
def __init__(self, IPV6=False):
self.SZABALYOK=[]
self.SZABALYOK_NAT=[]
self.IPV6 = IPV6
self.vlans = models.Vlan.objects.all()
self.hosts = models.Host.objects.all()
self.dmz = models.Vlan.objects.get(name="DMZ")
self.pub = models.Vlan.objects.get(name="PUB")
self.fw = models.Firewall.objects.all()
self.ipt_filter()
if not self.IPV6:
self.ipt_nat()
def reload(self):
if self.IPV6:
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")
else:
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")
def show(self):
if self.IPV6:
return "\n".join(self.SZABALYOK)+"\n"
else:
return "\n".join(self.SZABALYOK)+"\n"+"\n".join(self.SZABALYOK_NAT)+"\n"
def ipv6_to_octal(ipv6):
......@@ -319,140 +311,119 @@ def ipv6_to_arpa(ipv6):
def dns():
vlans = models.Vlan.objects.all()
regex = re.compile(r'^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$')
DNS = []
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")
#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" % (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" % (62, 243, 66, 152, "r.cloud.ik.bme.hu"))
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("&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::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::ns.bme.hu:600::\n") #ns
for i_vlan in vlans:
m = regex.search(i_vlan.net4)
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("&%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("&%s::dns1.ik.bme.hu:600::\n" % i_vlan.domain)
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("&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():
ipv4 = ( i_host.pub_ipv4 if i_host.pub_ipv4 and not i_host.shared_ip else i_host.ipv4 )
m2 = regex.search(ipv4)
#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))
#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))
process = subprocess.Popen(['/usr/bin/ssh', 'tinydns@%s' % DNS_SERVER], shell=False, stdin=subprocess.PIPE)
process.communicate("\n".join(DNS)+"\n")
vlans = models.Vlan.objects.all()
regex = re.compile(r'^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$')
DNS = []
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")
# 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" % (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" % (62, 243, 66, 152, "r.cloud.ik.bme.hu"))
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("&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 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 rekord
for i_vlan in vlans:
m = regex.search(i_vlan.net4)
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("&%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("&%s::dns1.ik.bme.hu:600::\n" % i_vlan.domain)
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("&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():
ipv4 = ( i_host.pub_ipv4 if i_host.pub_ipv4 and not i_host.shared_ip else i_host.ipv4 )
m2 = regex.search(ipv4)
# 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))
# 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))
process = subprocess.Popen(['/usr/bin/ssh', 'tinydns@%s' % DNS_SERVER], shell=False, stdin=subprocess.PIPE)
process.communicate("\n".join(DNS)+"\n")
def prefix_to_mask(prefix):
t = [0,0,0,0]
for i in range(0,4):
if prefix > i*8+7:
t[i] = 255
elif i*8 < prefix and prefix <= (i+1)*8:
t[i] = 256 - (2 ** ((i+1)*8 - prefix))
return ".".join([str(i) for i in t])
t = [0, 0, 0, 0]
for i in range(0, 4):
if prefix > i*8+7:
t[i] = 255
elif i*8 < prefix and prefix <= (i+1)*8:
t[i] = 256 - (2 ** ((i+1)*8 - prefix))
return ".".join([str(i) for i in t])
def dhcp():
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]+$')
DHCP = []
#/tools/dhcp3/dhcpd.conf.generated
for i_vlan in vlans:
if(i_vlan.dhcp_pool):
m = regex.search(i_vlan.dhcp_pool)
if(m or i_vlan.dhcp_pool == "manual"):
DHCP.append ('''
#%(name)s - %(interface)s
subnet %(net)s netmask %(netmask)s {
%(extra)s;
option domain-name "%(domain)s";
option routers %(router)s;
option domain-name-servers %(dnsserver)s;
option ntp-servers %(ntp)s;
next-server %(tftp)s;
authoritative;
filename \"pxelinux.0\";
allow bootp; allow booting;
}''' % {
'net': i_vlan.net4,
'netmask': prefix_to_mask(i_vlan.prefix4),
'domain': i_vlan.domain,
'router': i_vlan.ipv4,
'ntp': i_vlan.ipv4,
'dnsserver': DNS_SERVER,
'extra': "range %s" % i_vlan.dhcp_pool if m else "deny unknown-clients",
'interface': i_vlan.interface,
'name': i_vlan.name,
'tftp': i_vlan.ipv4
})
for i_host in i_vlan.host_set.all():
DHCP.append ('''
host %(hostname)s {
hardware ethernet %(mac)s;
fixed-address %(ipv4)s;
}''' % {
'hostname': i_host.hostname,
'mac': i_host.mac,
'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)
# print "\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()
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]+$')
DHCP = []
# /tools/dhcp3/dhcpd.conf.generated
for i_vlan in vlans:
if(i_vlan.dhcp_pool):
m = regex.search(i_vlan.dhcp_pool)
if(m or i_vlan.dhcp_pool == "manual"):
DHCP.append ('''
# %(name)s - %(interface)s
subnet %(net)s netmask %(netmask)s {
%(extra)s;
option domain-name "%(domain)s";
option routers %(router)s;
option domain-name-servers %(dnsserver)s;
option ntp-servers %(ntp)s;
next-server %(tftp)s;
authoritative;
filename \"pxelinux.0\";
allow bootp; allow booting;
}''' % {
'net': i_vlan.net4,
'netmask': prefix_to_mask(i_vlan.prefix4),
'domain': i_vlan.domain,
'router': i_vlan.ipv4,
'ntp': i_vlan.ipv4,
'dnsserver': DNS_SERVER,
'extra': "range %s" % i_vlan.dhcp_pool if m else "deny unknown-clients",
'interface': i_vlan.interface,
'name': i_vlan.name,
'tftp': i_vlan.ipv4
})
for i_host in i_vlan.host_set.all():
DHCP.append ('''
host %(hostname)s {
hardware ethernet %(mac)s;
fixed-address %(ipv4)s;
}''' % {
'hostname': i_host.hostname,
'mac': i_host.mac,
'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)
# print "\n".join(DHCP)+"\n"
process.communicate("\n".join(DHCP)+"\n")
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)]:
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:
h1.save()
h1.groups.add(models.Group.objects.get(name="netezhet manbol"))
h1.save()
# i = i + 1
except:
print "nemok %s" % name
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:
h1.save()
h1.groups.add(models.Group.objects.get(name="netezhet manbol"))
h1.save()
# i = i + 1
except:
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
from django.core.validators import MinValueValidator, MaxValueValidator
class Rule(models.Model):
CHOICES_type = (('host', 'host'), ('firewall', 'firewall'), ('vlan', 'vlan'))
CHOICES_proto = (('tcp', 'tcp'), ('udp', 'udp'), ('icmp', 'icmp'))
CHOICES_dir = (('0', 'out'), ('1', 'in'))
direction = models.CharField(max_length=1, choices=CHOICES_dir, blank=False)
description = models.TextField(blank=True)
vlan = models.ManyToManyField('Vlan', symmetrical=False, blank=True, null=True)
dport = 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)
extra = models.TextField(blank=True)
accept = models.BooleanField(default=False)
owner = models.ForeignKey(User, blank=True, null=True)
r_type = models.CharField(max_length=10, choices=CHOICES_type)
nat = models.BooleanField(default=False)
nat_dport = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), MaxValueValidator(65535)])
def __unicode__(self):
CHOICES_type = (('host', 'host'), ('firewall', 'firewall'), ('vlan', 'vlan'))
CHOICES_proto = (('tcp', 'tcp'), ('udp', 'udp'), ('icmp', 'icmp'))
CHOICES_dir = (('0', 'out'), ('1', 'in'))
direction = models.CharField(max_length=1, choices=CHOICES_dir, blank=False)
description = models.TextField(blank=True)
vlan = models.ManyToManyField('Vlan', symmetrical=False, blank=True, null=True)
dport = 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)
extra = models.TextField(blank=True)
accept = models.BooleanField(default=False)
owner = models.ForeignKey(User, blank=True, null=True)
r_type = models.CharField(max_length=10, choices=CHOICES_type)
nat = models.BooleanField(default=False)
nat_dport = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), MaxValueValidator(65535)])
def __unicode__(self):
return self.desc()
def color_desc(self):
para = '</span>'
if(self.dport):
para = "dport=%s %s" % (self.dport, para)
if(self.sport):
para = "sport=%s %s" % (self.sport, para)
if(self.proto):
para = "proto=%s %s" % (self.proto, 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
color_desc.allow_tags = True
def desc(self):
para = u""
if(self.dport):
para = "dport=%s %s" % (self.dport, para)
if(self.sport):
para = "sport=%s %s" % (self.sport, para)
if(self.proto):
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
def vlan_l(self):
retval = []
for vl in self.vlan.all():
retval.append(vl.name)
return u', '.join(retval)
def color_desc(self):
para = '</span>'
if(self.dport):
para = "dport=%s %s" % (self.dport, para)
if(self.sport):
para = "sport=%s %s" % (self.sport, para)
if(self.proto):
para = "proto=%s %s" % (self.proto, 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
color_desc.allow_tags = True
def desc(self):
para = u""
if(self.dport):
para = "dport=%s %s" % (self.dport, para)
if(self.sport):
para = "sport=%s %s" % (self.sport, para)
if(self.proto):
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
def vlan_l(self):
retval = []
for vl in self.vlan.all():
retval.append(vl.name)
return u', '.join(retval)
class Vlan(models.Model):
vid = models.IntegerField(unique=True)
......@@ -76,19 +76,19 @@ class Vlan(models.Model):
def __unicode__(self):
return self.name
def net_ipv6(self):
return self.net6 + "/" + unicode(self.prefix6)
return self.net6 + "/" + unicode(self.prefix6)
def net_ipv4(self):
return self.net4 + "/" + unicode(self.prefix4)
return self.net4 + "/" + unicode(self.prefix4)
def rules_l(self):
retval = []
for rl in self.rules.all():
retval.append(unicode(rl))
return ', '.join(retval)
retval = []
for rl in self.rules.all():
retval.append(unicode(rl))
return ', '.join(retval)
def snat_to_l(self):
retval = []
for rl in self.snat_to.all():
retval.append(unicode(rl))
return ', '.join(retval)
retval = []
for rl in self.snat_to.all():
retval.append(unicode(rl))
return ', '.join(retval)
class Group(models.Model):
name = models.CharField(max_length=20, unique=True)
......@@ -117,55 +117,55 @@ class Host(models.Model):
def save(self, *args, **kwargs):
if not self.id and not self.ipv6:
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):
raise ValidationError("Ha a shared_ip be van pipalva, akkor egyedinek kell lennie a pub_ipv4-nek!")
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!")
if Host.objects.exclude(id=self.id).filter(pub_ipv4=self.ipv4):
raise ValidationError("Egy masik host natolt cimet nem hasznalhatod sajat ipv4-nek")
super(Host, self).save(*args, **kwargs)
def groups_l(self):
retval = []
for grp in self.groups.all():
retval.append(grp.name)
return ', '.join(retval)
retval = []
for grp in self.groups.all():
retval.append(grp.name)
return ', '.join(retval)
def rules_l(self):
retval = []
for rl in self.rules.all():
retval.append(unicode(rl.color_desc()))
return '<br>'.join(retval)
retval = []
for rl in self.rules.all():
retval.append(unicode(rl.color_desc()))
return '<br>'.join(retval)
rules_l.allow_tags = True
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):
proto = "tcp" if (proto == "tcp") else "udp"
proto = "tcp" if (proto == "tcp") else "udp"
if public < 1024:
raise ValidationError("Csak az 1024 feletti portok hasznalhatok")
for host in Host.objects.filter(pub_ipv4=self.pub_ipv4):
if host.rules.filter(nat=True, proto=proto, dport=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.full_clean()
rule.save()
rule.vlan.add(Vlan.objects.get(name="PUB"))
rule.vlan.add(Vlan.objects.get(name="HOT"))
rule.vlan.add(Vlan.objects.get(name="LAB"))
rule.vlan.add(Vlan.objects.get(name="DMZ"))
rule.vlan.add(Vlan.objects.get(name="VM-NET"))
rule.vlan.add(Vlan.objects.get(name="WAR"))
rule.vlan.add(Vlan.objects.get(name="OFF2"))
self.rules.add(rule)
raise ValidationError("Csak az 1024 feletti portok hasznalhatok")
for host in Host.objects.filter(pub_ipv4=self.pub_ipv4):
if host.rules.filter(nat=True, proto=proto, dport=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.full_clean()
rule.save()
rule.vlan.add(Vlan.objects.get(name="PUB"))
rule.vlan.add(Vlan.objects.get(name="HOT"))
rule.vlan.add(Vlan.objects.get(name="LAB"))
rule.vlan.add(Vlan.objects.get(name="DMZ"))
rule.vlan.add(Vlan.objects.get(name="VM-NET"))
rule.vlan.add(Vlan.objects.get(name="WAR"))
rule.vlan.add(Vlan.objects.get(name="OFF2"))
self.rules.add(rule)
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):
retval = []
for rule in self.rules.filter(owner=self.owner, nat=True):
retval.append({'proto': rule.proto, 'public': rule.dport, 'private': rule.nat_dport})
return retval
retval = []
for rule in self.rules.filter(owner=self.owner, nat=True):
retval.append({'proto': rule.proto, 'public': rule.dport, 'private': rule.nat_dport})
return retval
def del_rules(self):
self.rules.filter(owner=self.owner).delete()
self.rules.filter(owner=self.owner).delete()
class Firewall(models.Model):
name = models.CharField(max_length=20, unique=True)
......
......@@ -6,43 +6,43 @@ from firewall.fw import *
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():
print "megszereztem"
ReloadTask.delay()
else:
print "nem szereztem meg"
if acquire_lock():
print "megszereztem"
ReloadTask.delay()
else:
print "nem szereztem meg"
class ReloadTask(Task):
def run(self, **kwargs):
acquire_lock = lambda: cache.add("reload_lock1", "true", 90)
release_lock = lambda: cache.delete("reload_lock1")
if not acquire_lock():
print "mar folyamatban van egy reload"
return
print "indul"
time.sleep(10)
try:
print "ipv4"
ipv4 = firewall()
ipv4.reload()
# print ipv4.show()
print "ipv6"
ipv6 = firewall(True)
ipv6.reload()
print "dns"
dns()
print "dhcp"
dhcp()
print "vege"
except:
raise
print "nem sikerult :("
print "leall"
release_lock()
def run(self, **kwargs):
acquire_lock = lambda: cache.add("reload_lock1", "true", 90)
release_lock = lambda: cache.delete("reload_lock1")
if not acquire_lock():
print "mar folyamatban van egy reload"
return
print "indul"
time.sleep(10)
try:
print "ipv4"
ipv4 = firewall()
ipv4.reload()
# print ipv4.show()
print "ipv6"
ipv6 = firewall(True)
ipv6.reload()
print "dns"
dns()
print "dhcp"
dhcp()
print "vege"
except:
raise
print "nem sikerult :("
print "leall"
release_lock()
......@@ -15,63 +15,63 @@ import sys
def reload_firewall(request):
if request.user.is_authenticated():
if(request.user.is_superuser):
html = u"Be vagy jelentkezve es admin is vagy, kedves %s!" % request.user.username
html += "<br> 10 masodperc mulva ujratoltodik"
ReloadTask.delay()
else:
html = u"Be vagy jelentkezve, csak nem vagy admin, kedves %s!" % request.user.username
else:
html = u"Nem vagy bejelentkezve, kedves ismeretlen!"
return HttpResponse(html)
if request.user.is_authenticated():
if(request.user.is_superuser):
html = u"Be vagy jelentkezve es admin is vagy, kedves %s!" % request.user.username
html += "<br> 10 masodperc mulva ujratoltodik"
ReloadTask.delay()
else:
html = u"Be vagy jelentkezve, csak nem vagy admin, kedves %s!" % request.user.username
else:
html = u"Nem vagy bejelentkezve, kedves ismeretlen!"
return HttpResponse(html)
@csrf_exempt
def firewall_api(request):
if request.method == 'POST':
try:
data=json.loads(base64.b64decode(request.POST["data"]))
command = request.POST["command"]
if(data["password"] != "bdmegintelrontottaanetet"):
raise Exception("rossz jelszo")
if request.method == 'POST':
try:
data=json.loads(base64.b64decode(request.POST["data"]))
command = request.POST["command"]
if(data["password"] != "bdmegintelrontottaanetet"):
raise Exception("rossz jelszo")
if(not(data["vlan"] == "vm-net" or data["vlan"] == "war")):
raise Exception("csak vm-net es war-re mukodik")
if(not(data["vlan"] == "vm-net" or data["vlan"] == "war")):
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"):
data["owner"] = "opennebula"
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.full_clean()
host.save()
if(command == "create"):
data["owner"] = "opennebula"
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.full_clean()
host.save()
host.enable_net()
host.enable_net()
for p in data["portforward"]:
host.add_port(proto=p["proto"], public=int(p["public_port"]), private=int(p["private_port"]))
for p in data["portforward"]:
host.add_port(proto=p["proto"], public=int(p["public_port"]), private=int(p["private_port"]))
elif(command == "destroy"):
data["owner"] = "opennebula"
print data["hostname"]
owner = auth.models.User.objects.get(username=data["owner"])
host = models.Host.objects.get(hostname=data["hostname"], owner=owner)
elif(command == "destroy"):
data["owner"] = "opennebula"
print data["hostname"]
owner = auth.models.User.objects.get(username=data["owner"])
host = models.Host.objects.get(hostname=data["hostname"], owner=owner)
host.del_rules()
host.delete()
else:
raise Exception("rossz parancs")
host.del_rules()
host.delete()
else:
raise Exception("rossz parancs")
reload_firewall_lock()
except (ValidationError, IntegrityError, AttributeError, Exception) as e:
return HttpResponse(u"rosszul hasznalod! :(\n%s\n" % e);
except:
# raise
return HttpResponse(u"rosszul hasznalod! :(\n");
return HttpResponse(u"ok");
reload_firewall_lock()
except (ValidationError, IntegrityError, AttributeError, Exception) as e:
return HttpResponse(u"rosszul hasznalod! :(\n%s\n" % e);
except:
# raise
return HttpResponse(u"rosszul hasznalod! :(\n");
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