Commit 3ae7502b by Őry Máté

remote firewall loading

parent d655afda
...@@ -4,6 +4,7 @@ from django.contrib import admin ...@@ -4,6 +4,7 @@ from django.contrib import admin
admin.autodiscover() admin.autodiscover()
import one.views import one.views
import firewall.views
urlpatterns = patterns('', urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
...@@ -14,4 +15,5 @@ urlpatterns = patterns('', ...@@ -14,4 +15,5 @@ urlpatterns = patterns('',
url(r'^vm/new/(?P<template>\d+)/$', 'one.views.vm_new', name='vm_new'), url(r'^vm/new/(?P<template>\d+)/$', 'one.views.vm_new', name='vm_new'),
url(r'^vm/show/(?P<iid>\d+)/$', 'one.views.vm_show', name='vm_show'), url(r'^vm/show/(?P<iid>\d+)/$', 'one.views.vm_show', name='vm_show'),
url(r'^vm/delete/(?P<iid>\d+)/$', 'one.views.vm_delete', name='vm_delete'), url(r'^vm/delete/(?P<iid>\d+)/$', 'one.views.vm_delete', name='vm_delete'),
url(r'^reload/$', 'firewall.views.reload_firewall', name='reload_firewall'),
) )
from django.core.exceptions import ValidationError
from django.forms import fields
from django.db import models
from django.utils.translation import ugettext_lazy as _
from south.modelsinspector import add_introspection_rules
import re
mac_re = re.compile(r'^([0-9a-fA-F]{2}([:-]?|$)){6}$')
alfanum_re = re.compile(r'^[A-Za-z0-9_-]+$')
domain_re = re.compile(r'^([A-Za-z0-9_-]\.?)+$')
ipv4_re = re.compile('^[0-9]+\.([0-9]+)\.([0-9]+)\.([0-9]+)$')
class MACAddressFormField(fields.RegexField):
default_error_messages = {
'invalid': _(u'Enter a valid MAC address.'),
}
def __init__(self, *args, **kwargs):
super(MACAddressFormField, self).__init__(mac_re, *args, **kwargs)
class MACAddressField(models.Field):
empty_strings_allowed = False
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 17
super(MACAddressField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return "CharField"
def formfield(self, **kwargs):
defaults = {'form_class': MACAddressFormField}
defaults.update(kwargs)
return super(MACAddressField, self).formfield(**defaults)
add_introspection_rules([], ["firewall\.fields\.MACAddressField"])
def val_alfanum(value):
if not alfanum_re.search(value):
raise ValidationError(u'%s - csak betut, kotojelet, alahuzast, szamot tartalmazhat!' % value)
def val_domain(value):
if not domain_re.search(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))
...@@ -6,12 +6,12 @@ ...@@ -6,12 +6,12 @@
#setup_environ(settings) #setup_environ(settings)
from django.contrib import auth from django.contrib import auth
from teszt.firewall import models from firewall import models
import os import os
import subprocess import subprocess
import re import re
DNS_SERVER = "152.66.243.71" DNS_SERVER = "152.66.243.60"
class firewall: class firewall:
...@@ -246,11 +246,10 @@ class firewall: ...@@ -246,11 +246,10 @@ class firewall:
def reload(self): def reload(self):
if self.IPV6: if self.IPV6:
process = subprocess.Popen(['/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:
print "\n".join(self.SZABALYOK)+"\n"+"\n".join(self.SZABALYOK_NAT)+"\n" process = subprocess.Popen(['/usr/bin/ssh', 'fw2', '/usr/bin/sudo', '/sbin/iptables-restore', '-c'], shell=False, stdin=subprocess.PIPE)
process = subprocess.Popen(['/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")
...@@ -258,40 +257,42 @@ class firewall: ...@@ -258,40 +257,42 @@ class firewall:
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:::\n") DNS.append("=cloud.ik.bme.hu:152.66.243.98:600::\n")
for i_vlan in vlans: for i_vlan in vlans:
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"):
m = regex.search(i_vlan.net4) DNS.append("Z%s.%s.in-addr.arpa:dns1.ik.bme.hu:ez.miez::::::600\n" % (m.group(2), m.group(1)))
DNS.append("Z%s.%s.in-addr.arpa:dns1.ik.bme.hu:ez.miez:\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:::\n" % (m.group(2), m.group(1))) DNS.append("Z%s:dns1.ik.bme.hu:ez.miez::::::600\n" % i_vlan.domain)
DNS.append("Z%s:dns1.ik.bme.hu:ez.miez:\n" % i_vlan.domain) DNS.append("&%s::dns1.ik.bme.hu:600::\n" % i_vlan.domain)
DNS.append("&%s::dns1.ik.bme.hu:::\n" % i_vlan.domain) if(i_vlan.name == "WAR"):
DNS.append("Zdns1.%s.%s.%s.in-addr.arpa:dns1.ik.bme.hu:ez.miez::::::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 else i_host.ipv4 ) ipv4 = ( i_host.pub_ipv4 if i_host.pub_ipv4 else i_host.ipv4 )
DNS.append("=%s.%s:%s:::\n" % (i_host.hostname, i_vlan.domain, ipv4)) m2 = regex.search(ipv4)
try: DNS.append("=%s.%s:%s:600::\n" % (i_host.hostname, i_vlan.domain, ipv4))
process = subprocess.Popen(['/usr/bin/ssh', 'tinydns@%s' % DNS_SERVER], shell=False, stdin=subprocess.PIPE) 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))
# print "\n".join(DNS)+"\n"
process.communicate("\n".join(DNS)+"\n") process = subprocess.Popen(['/usr/bin/ssh', 'tinydns@%s' % DNS_SERVER], shell=False, stdin=subprocess.PIPE)
except: process.communicate("\n".join(DNS)+"\n")
return
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]+$')
try: DHCP = []
f = open('/tools/dhcp3/dhcpd.conf.generated','w')
except: #/tools/dhcp3/dhcpd.conf.generated
return
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"):
f.write (''' 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;
...@@ -317,7 +318,7 @@ def dhcp(): ...@@ -317,7 +318,7 @@ def dhcp():
}) })
for i_host in i_vlan.host_set.all(): for i_host in i_vlan.host_set.all():
f.write (''' DHCP.append ('''
host %(hostname)s { host %(hostname)s {
hardware ethernet %(mac)s; hardware ethernet %(mac)s;
fixed-address %(ipv4)s; fixed-address %(ipv4)s;
...@@ -326,9 +327,10 @@ def dhcp(): ...@@ -326,9 +327,10 @@ def dhcp():
'mac': i_host.mac, 'mac': i_host.mac,
'ipv4': i_host.ipv4, 'ipv4': i_host.ipv4,
}) })
f.write("\n")
f.close() 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)
os.system("sudo /etc/init.d/isc-dhcp-server restart") # print "\n".join(DHCP)+"\n"
process.communicate("\n".join(DHCP)+"\n")
#ipt_filter() #ipt_filter()
#ipt_nat() #ipt_nat()
......
from django.forms import fields
from django.db import models
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.db import models
from django.forms import fields
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError from firewall.fields import *
from south.modelsinspector import add_introspection_rules from south.modelsinspector import add_introspection_rules
import re
mac_re = re.compile(r'^([0-9a-fA-F]{2}([:-]?|$)){6}$')
alfanum_re = re.compile(r'^[A-Za-z0-9_-]+$')
domain_re = re.compile(r'^([A-Za-z0-9_-]\.?)+$')
class MACAddressFormField(fields.RegexField):
default_error_messages = {
'invalid': _(u'Enter a valid MAC address.'),
}
def __init__(self, *args, **kwargs):
super(MACAddressFormField, self).__init__(mac_re, *args, **kwargs)
class MACAddressField(models.Field):
empty_strings_allowed = False
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 17
super(MACAddressField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return "CharField"
def formfield(self, **kwargs):
defaults = {'form_class': MACAddressFormField}
defaults.update(kwargs)
return super(MACAddressField, self).formfield(**defaults)
add_introspection_rules([], ["^firewall\.models\.MACAddressField"])
def val_alfanum(value):
if not alfanum_re.search(value):
raise ValidationError(u'%s - csak betut, kotojelet, alahuzast, szamot tartalmazhat!' % value)
def val_domain(value):
if not domain_re.search(value):
raise ValidationError(u'%s - helytelen domain' % value)
class Rule(models.Model): class Rule(models.Model):
# DIRECTION_CH=(('TOHOST', 1), ('FROMHOST', 0)) # DIRECTION_CH=(('TOHOST', 1), ('FROMHOST', 0))
...@@ -49,7 +12,7 @@ class Rule(models.Model): ...@@ -49,7 +12,7 @@ class Rule(models.Model):
vlan = models.ForeignKey('Vlan') vlan = models.ForeignKey('Vlan')
extra = models.TextField(blank=True); extra = models.TextField(blank=True);
action = models.BooleanField(default=False) action = models.BooleanField(default=False)
# owner = models.ForeignKey(User) owner = models.ForeignKey(User, blank=True, null=True)
def __unicode__(self): def __unicode__(self):
return self.description return self.description
...@@ -88,7 +51,7 @@ class Host(models.Model): ...@@ -88,7 +51,7 @@ class Host(models.Model):
mac = MACAddressField(unique=True) mac = MACAddressField(unique=True)
ipv4 = models.GenericIPAddressField(protocol='ipv4', unique=True) ipv4 = models.GenericIPAddressField(protocol='ipv4', unique=True)
pub_ipv4 = models.GenericIPAddressField(protocol='ipv4', unique=True, blank=True, null=True) pub_ipv4 = models.GenericIPAddressField(protocol='ipv4', unique=True, blank=True, null=True)
ipv6 = models.GenericIPAddressField(protocol='ipv6', unique=True) ipv6 = models.GenericIPAddressField(protocol='ipv6', unique=True, blank=True)
description = models.TextField(blank=True) description = models.TextField(blank=True)
comment = models.TextField(blank=True) comment = models.TextField(blank=True)
location = models.TextField(blank=True) location = models.TextField(blank=True)
...@@ -98,6 +61,10 @@ class Host(models.Model): ...@@ -98,6 +61,10 @@ class Host(models.Model):
rules = models.ManyToManyField('Rule', symmetrical=False, blank=True, null=True) rules = models.ManyToManyField('Rule', symmetrical=False, blank=True, null=True)
def __unicode__(self): def __unicode__(self):
return self.hostname return self.hostname
def save(self, *args, **kwargs):
if not self.id and not self.ipv6:
self.ipv6 = ipv4_2_ipv6(self.ipv4)
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():
......
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from django.http import HttpResponse from django.http import HttpResponse
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from teszt.firewall.models import * from firewall.models import *
from teszt.firewall.fw import * from firewall.fw import *
def reload_firewall(request): def reload_firewall(request):
if request.user.is_authenticated(): if request.user.is_authenticated():
......
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