models.py 9.25 KB
Newer Older
Őry Máté committed
1 2
# -*- coding: utf8 -*-

Őry Máté committed
3
from django.contrib.auth.models import User
Őry Máté committed
4
from django.db import models
5
from django.forms import fields, ValidationError
Őry Máté committed
6
from django.utils.translation import ugettext_lazy as _
Őry Máté committed
7
from firewall.fields import *
8
from south.modelsinspector import add_introspection_rules
9
from django.core.validators import MinValueValidator, MaxValueValidator
django committed
10 11 12 13 14 15 16
from modeldict import ModelDict

class Setting(models.Model):
    key = models.CharField(max_length=32)
    value = models.CharField(max_length=200)

settings = ModelDict(Setting, key='key', value='value', instances=False)
Őry Máté committed
17 18

class Rule(models.Model):
x committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
    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)])
Őry Máté committed
34 35
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
x committed
36 37

    def __unicode__(self):
root committed
38
        return self.desc()
Őry Máté committed
39

x committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    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)
Őry Máté committed
66 67 68 69

class Vlan(models.Model):
    vid = models.IntegerField(unique=True)
    name = models.CharField(max_length=20, unique=True, validators=[val_alfanum])
70 71
    prefix4 = models.IntegerField(default=16)
    prefix6 = models.IntegerField(default=80)
Őry Máté committed
72 73 74 75 76
    interface = models.CharField(max_length=20, unique=True)
    net4 = models.GenericIPAddressField(protocol='ipv4', unique=True)
    net6 = models.GenericIPAddressField(protocol='ipv6', unique=True)
    ipv4 = models.GenericIPAddressField(protocol='ipv4', unique=True)
    ipv6 = models.GenericIPAddressField(protocol='ipv6', unique=True)
root committed
77 78 79
    snat_ip = models.GenericIPAddressField(protocol='ipv4', blank=True, null=True)
    snat_to = models.ManyToManyField('self', symmetrical=False, blank=True, null=True)
    rules = models.ManyToManyField('Rule', related_name="%(app_label)s_%(class)s_related", symmetrical=False, blank=True, null=True)
Őry Máté committed
80 81 82 83
    description = models.TextField(blank=True)
    comment = models.TextField(blank=True)
    domain = models.TextField(blank=True, validators=[val_domain])
    dhcp_pool = models.TextField(blank=True)
Őry Máté committed
84 85
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
86

Őry Máté committed
87 88 89
    def __unicode__(self):
        return self.name
    def net_ipv6(self):
x committed
90
        return self.net6 + "/" + unicode(self.prefix6)
Őry Máté committed
91
    def net_ipv4(self):
x committed
92
        return self.net4 + "/" + unicode(self.prefix4)
root committed
93
    def rules_l(self):
x committed
94 95 96 97
        retval = []
        for rl in self.rules.all():
            retval.append(unicode(rl))
        return ', '.join(retval)
root committed
98
    def snat_to_l(self):
x committed
99 100 101 102
        retval = []
        for rl in self.snat_to.all():
            retval.append(unicode(rl))
        return ', '.join(retval)
Őry Máté committed
103 104 105 106

class Group(models.Model):
    name = models.CharField(max_length=20, unique=True)
    rules = models.ManyToManyField('Rule', symmetrical=False, blank=True, null=True)
Őry Máté committed
107 108
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
109

Őry Máté committed
110 111 112
    def __unicode__(self):
        return self.name

113 114 115
class Alias(models.Model):
    host = models.ForeignKey('Host')
    alias = models.CharField(max_length=40, unique=True, validators=[val_domain])
Őry Máté committed
116 117 118
    owner = models.ForeignKey(User, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
119 120 121
    class Meta:
        verbose_name_plural = 'aliases'

Őry Máté committed
122
class Host(models.Model):
x committed
123
    hostname = models.CharField(max_length=40, unique=True, validators=[val_alfanum])
124
    reverse = models.CharField(max_length=40, validators=[val_domain], blank=True, null=True)
Őry Máté committed
125 126
    mac = MACAddressField(unique=True)
    ipv4 = models.GenericIPAddressField(protocol='ipv4', unique=True)
127
    pub_ipv4 = models.GenericIPAddressField(protocol='ipv4', blank=True, null=True)
128
    ipv6 = models.GenericIPAddressField(protocol='ipv6', unique=True, blank=True, null=True)
129
    shared_ip = models.BooleanField(default=False)
Őry Máté committed
130 131 132 133 134 135 136
    description = models.TextField(blank=True)
    comment = models.TextField(blank=True)
    location = models.TextField(blank=True)
    vlan = models.ForeignKey('Vlan')
    owner = models.ForeignKey(User)
    groups = models.ManyToManyField('Group', symmetrical=False, blank=True, null=True)
    rules = models.ManyToManyField('Rule', symmetrical=False, blank=True, null=True)
Őry Máté committed
137 138
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
139

Őry Máté committed
140 141
    def __unicode__(self):
        return self.hostname
Őry Máté committed
142
    def save(self, *args, **kwargs):
143
        if not self.id and self.ipv6 == "auto":
Őry Máté committed
144
            self.ipv6 = ipv4_2_ipv6(self.ipv4)
x committed
145 146
        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!")
x committed
147 148
        if Host.objects.exclude(id=self.id).filter(pub_ipv4=self.ipv4):
            raise ValidationError("Egy masik host natolt cimet nem hasznalhatod sajat ipv4-nek")
Őry Máté committed
149
        super(Host, self).save(*args, **kwargs)
Őry Máté committed
150
    def groups_l(self):
x committed
151 152 153 154
        retval = []
        for grp in self.groups.all():
            retval.append(grp.name)
        return ', '.join(retval)
Őry Máté committed
155
    def rules_l(self):
x committed
156 157 158 159
        retval = []
        for rl in self.rules.all():
            retval.append(unicode(rl.color_desc()))
        return '<br>'.join(retval)
Őry Máté committed
160
    rules_l.allow_tags = True
Őry Máté committed
161
    def enable_net(self):
x committed
162
        self.groups.add(Group.objects.get(name="netezhet"))
163

Őry Máté committed
164
    def add_port(self, proto, public, private):
x committed
165
        proto = "tcp" if (proto == "tcp") else "udp"
166
        if public < 1024:
x committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
            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)
182

Őry Máté committed
183
    def del_port(self, proto, public):
x committed
184
        self.rules.filter(owner=self.owner, proto=proto, nat=True, dport=public).delete()
185

Őry Máté committed
186
    def list_ports(self):
x committed
187 188 189 190
        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
191

Őry Máté committed
192
    def del_rules(self):
x committed
193
        self.rules.filter(owner=self.owner).delete()
Őry Máté committed
194 195 196 197

class Firewall(models.Model):
    name = models.CharField(max_length=20, unique=True)
    rules = models.ManyToManyField('Rule', symmetrical=False, blank=True, null=True)
198

Őry Máté committed
199 200
    def __unicode__(self):
        return self.name
Őry Máté committed
201