models.py 38.2 KB
Newer Older
1
# -*- coding: utf-8 -*-
2

3
from itertools import islice, chain
4
import logging
5
from netaddr import IPSet, EUI
6

7 8
from django.contrib.auth.models import User
from django.db import models
9
from django.forms import ValidationError
10
from django.utils.translation import ugettext_lazy as _
11
from firewall.fields import (MACAddressField, val_alfanum, val_reverse_domain,
12
                             val_ipv6_template,
13
                             val_domain, val_ipv4, val_ipv6, val_mx,
14
                             ipv4_2_ipv6, IPNetworkField, IPAddressField)
15 16
from django.core.validators import MinValueValidator, MaxValueValidator
import django.conf
17
from django.db.models.signals import post_save, post_delete
18 19
import random

Bach Dániel committed
20
from firewall.tasks.local_tasks import reloadtask
21
from acl.models import AclBase
22
logger = logging.getLogger(__name__)
23
settings = django.conf.settings.FIREWALL_SETTINGS
24 25


26 27
class Rule(models.Model):

28 29 30
    """
    A rule of a packet filter, changing the behavior of a host, vlan or
    firewall.
31

32 33
    Some rules accept or deny packets matching some criteria.
    Others set address translation or other free-form iptables parameters.
34 35
    """
    CHOICES_type = (('host', 'host'), ('firewall', 'firewall'),
36
                   ('vlan', 'vlan'))
37 38 39 40
    CHOICES_proto = (('tcp', 'tcp'), ('udp', 'udp'), ('icmp', 'icmp'))
    CHOICES_dir = (('0', 'out'), ('1', 'in'))

    direction = models.CharField(max_length=1, choices=CHOICES_dir,
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
                                 blank=False, verbose_name=_("direction"),
                                 help_text=_("If the rule matches egress "
                                             "or ingress packets."))
    description = models.TextField(blank=True, verbose_name=_('description'),
                                   help_text=_("Why is the rule needed, "
                                               "or how does it work."))
    foreign_network = models.ForeignKey(
        'VlanGroup', verbose_name=_("foreign network"),
        help_text=_("The group of vlans the matching packet goes to "
                    "(direction out) or from (in)."),
        related_name="ForeignRules")
    dport = models.IntegerField(
        blank=True, null=True, verbose_name=_("dest. port"),
        validators=[MinValueValidator(1), MaxValueValidator(65535)],
        help_text=_("Destination port number of packets that match."))
    sport = models.IntegerField(
        blank=True, null=True, verbose_name=_("source port"),
        validators=[MinValueValidator(1), MaxValueValidator(65535)],
        help_text=_("Source port number of packets that match."))
60
    proto = models.CharField(max_length=10, choices=CHOICES_proto,
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
                             blank=True, null=True, verbose_name=_("protocol"),
                             help_text=_("Protocol of packets that match."))
    extra = models.TextField(blank=True, verbose_name=_("extra arguments"),
                             help_text=_("Additional arguments passed "
                                         "literally to the iptables-rule."))
    accept = models.BooleanField(default=False, verbose_name=_("accept"),
                                 help_text=_("Accept the matching packets "
                                             "(or deny if not checked)."))
    owner = models.ForeignKey(User, blank=True, null=True,
                              verbose_name=_("owner"),
                              help_text=_("The user responsible for "
                                          "this rule."))
    nat = models.BooleanField(default=False, verbose_name=_("NAT"),
                              help_text=_("If network address translation "
                                          "shoud be done."))
76
    nat_dport = models.IntegerField(blank=True, null=True,
77 78 79
                                    help_text=_("Rewrite destination port "
                                                "number to this if NAT is "
                                                "needed."),
80 81 82 83 84 85 86 87
                                    validators=[MinValueValidator(1),
                                                MaxValueValidator(65535)])
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name=_("created at"))
    modified_at = models.DateTimeField(
        auto_now=True,
        verbose_name=_("modified at"))
88 89

    vlan = models.ForeignKey('Vlan', related_name="rules", blank=True,
90 91 92
                             null=True, verbose_name=_("vlan"),
                             help_text=_("Vlan the rule applies to "
                                         "(if type is vlan)."))
93
    vlangroup = models.ForeignKey('VlanGroup', related_name="rules",
94 95 96 97
                                  blank=True, null=True, verbose_name=_(
                                      "vlan group"),
                                  help_text=_("Group of vlans the rule "
                                              "applies to (if type is vlan)."))
98
    host = models.ForeignKey('Host', related_name="rules", blank=True,
99 100 101 102 103 104 105 106 107 108 109 110
                             verbose_name=_('host'), null=True,
                             help_text=_("Host the rule applies to "
                                         "(if type is host)."))
    hostgroup = models.ForeignKey(
        'Group', related_name="rules", verbose_name=_("host group"),
        blank=True, null=True, help_text=_("Group of hosts the rule applies "
                                           "to (if type is host)."))
    firewall = models.ForeignKey(
        'Firewall', related_name="rules", verbose_name=_("firewall"),
                                 help_text=_("Firewall the rule applies to "
                                             "(if type is firewall)."),
        blank=True, null=True)
111 112 113 114 115 116

    def __unicode__(self):
        return self.desc()

    def clean(self):
        fields = [self.vlan, self.vlangroup, self.host, self.hostgroup,
117
                  self.firewall]
118 119 120 121 122
        selected_fields = [field for field in fields if field]
        if len(selected_fields) > 1:
            raise ValidationError(_('Only one field can be selected.'))

    def desc(self):
123 124
        """Return a short string representation of the current rule.
        """
125 126 127
        return u'[%(type)s] %(src)s ▸ %(dst)s %(para)s %(desc)s' % {
            'type': self.r_type,
            'src': (unicode(self.foreign_network) if self.direction == '1'
128
                    else self.r_type),
129
            'dst': (self.r_type if self.direction == '1'
130
                    else unicode(self.foreign_network)),
131 132 133 134 135
            'para': ((("proto=%s " % self.proto) if self.proto else '') +
                     (("sport=%s " % self.sport) if self.sport else '') +
                     (("dport=%s " % self.dport) if self.dport else '')),
            'desc': self.description}

136 137 138 139 140 141 142 143 144
    @property
    def r_type(self):
        fields = [self.vlan, self.vlangroup, self.host, self.hostgroup,
                  self.firewall]
        for field in fields:
            if field is not None:
                return field.__class__.__name__.lower()
        return None

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    @models.permalink
    def get_absolute_url(self):
        return ('network.rule', None, {'pk': self.pk})

    class Meta:
        verbose_name = _("rule")
        verbose_name_plural = _("rules")
        ordering = (
            'direction',
            'proto',
            'sport',
            'dport',
            'nat_dport',
            'host',
        )


162
class Vlan(AclBase, models.Model):
163 164 165 166 167 168 169 170 171 172 173 174

    """
    A vlan of the network,

    Networks controlled by this framework are split into separated subnets.
    These networks are izolated by the vlan (virtual lan) technology, which is
    commonly used by managed network switches to partition the network.

    Each vlan network has a unique identifier, a name, a unique IPv4 and IPv6
    range. The gateway also has an IP address in each range.
    """

175 176 177 178
    ACL_LEVELS = (
        ('user', _('user')),
        ('operator', _('operator')),
    )
179 180
    CHOICES_NETWORK_TYPE = (('public', _('public')), ('dmz', _('dmz')),
                            ('portforward', _('portforward')))
181 182 183 184 185 186 187 188 189 190
    vid = models.IntegerField(unique=True,
                              verbose_name=_('VID'),
                              help_text=_('The vlan ID of the subnet.'),
                              validators=[MinValueValidator(1),
                                          MaxValueValidator(4095)])
    name = models.CharField(max_length=20,
                            unique=True,
                            verbose_name=_('Name'),
                            help_text=_('The short name of the subnet.'),
                            validators=[val_alfanum])
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    network4 = IPNetworkField(unique=False,
                              version=4,
                              verbose_name=_('IPv4 address/prefix'),
                              help_text=_(
                                  'The IPv4 address and the prefix length '
                                  'of the gateway.'
                                  'Recommended value is the last '
                                  'valid address of the subnet, '
                                  'for example '
                                  '10.4.255.254/16 for 10.4.0.0/16.'))
    network6 = IPNetworkField(unique=False,
                              version=6,
                              null=True,
                              blank=True,
                              verbose_name=_('IPv6 address/prefix'),
                              help_text=_(
                                  'The IPv6 address and the prefix length '
                                  'of the gateway.'))
209
    snat_ip = models.GenericIPAddressField(protocol='ipv4', blank=True,
210 211 212 213 214 215 216 217
                                           null=True,
                                           verbose_name=_('NAT IP address'),
                                           help_text=_(
                                               'Common IPv4 address used for '
                                               'address translation of '
                                               'connections to the networks '
                                               'selected below '
                                               '(typically to the internet).'))
218
    snat_to = models.ManyToManyField('self', symmetrical=False, blank=True,
219 220 221 222 223 224 225
                                     null=True, verbose_name=_('NAT to'),
                                     help_text=_(
                                         'Connections to these networks '
                                         'should be network address '
                                         'translated, i.e. their source '
                                         'address is rewritten to the value '
                                         'of NAT IP address.'))
226 227 228
    network_type = models.CharField(choices=CHOICES_NETWORK_TYPE,
                                    verbose_name=_('network type'),
                                    max_length=20)
229
    managed = models.BooleanField(default=True, verbose_name=_('managed'))
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    description = models.TextField(blank=True, verbose_name=_('description'),
                                   help_text=_(
                                       'Description of the goals and elements '
                                       'of the vlan network.'))
    comment = models.TextField(blank=True, verbose_name=_('comment'),
                               help_text=_(
                                   'Notes, comments about the network'))
    domain = models.ForeignKey('Domain', verbose_name=_('domain name'),
                               help_text=_('Domain name of the members of '
                                           'this network.'))
    reverse_domain = models.TextField(
        validators=[val_reverse_domain],
        verbose_name=_('reverse domain'),
        help_text=_('Template of the IPv4 reverse domain name that '
                    'should be generated for each host. The template '
                    'should contain four tokens: "%(a)d", "%(b)d", '
                    '"%(c)d", and "%(d)d", representing the four bytes '
                    'of the address, respectively, in decimal notation. '
                    'For example, the template for the standard reverse '
                    'address is: "%(d)d.%(c)d.%(b)d.%(a)d.in-addr.arpa".'),
        default="%(d)d.%(c)d.%(b)d.%(a)d.in-addr.arpa")
251 252 253 254
    ipv6_template = models.TextField(
        validators=[val_ipv6_template],
        verbose_name=_('ipv6 template'),
        default="2001:738:2001:4031:%(b)d:%(c)d:%(d)d:0")
255 256 257 258 259 260 261 262 263 264 265 266 267
    dhcp_pool = models.TextField(blank=True, verbose_name=_('DHCP pool'),
                                 help_text=_(
                                     'The address range of the DHCP pool: '
                                     'empty for no DHCP service, "manual" for '
                                     'no DHCP pool, or the first and last '
                                     'address of the range separated by a '
                                     'space.'))
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created at'))
    owner = models.ForeignKey(User, blank=True, null=True,
                              verbose_name=_('owner'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified at'))
268 269

    def __unicode__(self):
270 271
        return "%s - %s" % ("managed" if self.managed else "unmanaged",
                            self.name)
272

273 274 275 276
    @models.permalink
    def get_absolute_url(self):
        return ('network.vlan', None, {'vid': self.vid})

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    @property
    def net4(self):
        return self.network4.network

    @property
    def ipv4(self):
        return self.network4.ip

    @property
    def prefix4(self):
        return self.network4.prefixlen

    @property
    def net6(self):
        return self.network6.network

    @property
    def ipv6(self):
        return self.network6.ip

    @property
    def prefix6(self):
        return self.network6.prefixlen

301 302 303 304 305 306 307 308 309 310 311 312 313 314
    def get_next_address(self, used_v4):
        try:
            last_address = list(used_v4)[-1]
        except IndexError:
            return []
        next_address = last_address + 1

        if next_address in self.network4.iter_hosts():
            logger.debug("Found unused IPv4 address %s after %s.",
                         next_address, last_address)
            return [next_address]
        else:
            return []

315
    def get_new_address(self):
316
        hosts = self.host_set
317 318 319
        used_v4 = IPSet(hosts.values_list('ipv4', flat=True))
        used_v6 = IPSet(hosts.exclude(ipv6__isnull=True)
                        .values_list('ipv6', flat=True))
320

321 322
        for ipv4 in chain(self.get_next_address(used_v4),
                          islice(self.network4.iter_hosts(), 10000)):
323 324
            ipv4 = str(ipv4)
            if ipv4 not in used_v4:
325
                logger.debug("Found unused IPv4 address %s.", ipv4)
326 327
                ipv6 = None
                if self.network6 is not None:
328
                    ipv6 = ipv4_2_ipv6(self.ipv6_template, ipv4)
329 330 331
                    if ipv6 in used_v6:
                        continue
                    else:
332
                        logger.debug("Found unused IPv6 address %s.", ipv6)
333 334 335
                return {'ipv4': ipv4, 'ipv6': ipv6}
        else:
            raise ValidationError(_("All IP addresses are already in use."))
336

337

338
class VlanGroup(models.Model):
339 340 341 342 343 344
    """
    A group of Vlans.
    """

    name = models.CharField(max_length=20, unique=True, verbose_name=_('name'),
                            help_text=_('The name of the group.'))
345
    vlans = models.ManyToManyField('Vlan', symmetrical=False, blank=True,
346 347 348 349 350 351 352 353 354 355 356
                                   null=True, verbose_name=_('vlans'),
                                   help_text=_('The vlans which are members '
                                               'of the group.'))
    description = models.TextField(blank=True, verbose_name=_('description'),
                                   help_text=_('Description of the group.'))
    owner = models.ForeignKey(User, blank=True, null=True,
                              verbose_name=_('owner'))
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified at'))
357 358 359 360

    def __unicode__(self):
        return self.name

361 362 363 364 365
    @models.permalink
    def get_absolute_url(self):
        return ('network.vlan_group', None, {'pk': self.pk})


366
class Group(models.Model):
367 368 369 370 371 372 373 374 375 376 377 378 379
    """
    A group of hosts.
    """
    name = models.CharField(max_length=20, unique=True, verbose_name=_('name'),
                            help_text=_('The name of the group.'))
    description = models.TextField(blank=True, verbose_name=_('description'),
                                   help_text=_('Description of the group.'))
    owner = models.ForeignKey(User, blank=True, null=True,
                              verbose_name=_('owner'))
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified at'))
380 381 382 383

    def __unicode__(self):
        return self.name

384 385 386 387 388
    @models.permalink
    def get_absolute_url(self):
        return ('network.group', None, {'pk': self.pk})


389
class Host(models.Model):
390 391 392 393
    """
    A host of the network.
    """

394
    hostname = models.CharField(max_length=40,
395 396 397 398 399
                                verbose_name=_('hostname'),
                                help_text=_('The alphanumeric hostname of '
                                            'the host, the first part of '
                                            'the FQDN.'),
                                validators=[val_alfanum])
400
    reverse = models.CharField(max_length=40, validators=[val_domain],
401 402 403 404 405 406 407 408 409
                               verbose_name=_('reverse'),
                               help_text=_('The fully qualified reverse '
                                           'hostname of the host, if '
                                           'different than hostname.domain.'),
                               blank=True, null=True)
    mac = MACAddressField(unique=True, verbose_name=_('MAC address'),
                          help_text=_('The MAC (Ethernet) address of the '
                                      'network interface. For example: '
                                      '99:AA:BB:CC:DD:EE.'))
410 411 412 413 414 415
    ipv4 = IPAddressField(version=4, unique=True,
                          verbose_name=_('IPv4 address'),
                          help_text=_('The real IPv4 address of the '
                                      'host, for example 10.5.1.34.'))
    pub_ipv4 = IPAddressField(
        version=4, blank=True, null=True,
416 417 418
        verbose_name=_('WAN IPv4 address'),
        help_text=_('The public IPv4 address of the host on the wide '
                    'area network, if different.'))
419 420 421 422 423
    ipv6 = IPAddressField(version=6, unique=True,
                          blank=True, null=True,
                          verbose_name=_('IPv6 address'),
                          help_text=_('The global IPv6 address of the host'
                                      ', for example 2001:db:88:200::10.'))
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    shared_ip = models.BooleanField(default=False, verbose_name=_('shared IP'),
                                    help_text=_(
                                        'If the given WAN IPv4 address is '
                                        'used by multiple hosts.'))
    description = models.TextField(blank=True, verbose_name=_('description'),
                                   help_text=_('What is this host for, what '
                                               'kind of machine is it.'))
    comment = models.TextField(blank=True,
                               verbose_name=_('Notes'))
    location = models.TextField(blank=True, verbose_name=_('location'),
                                help_text=_(
                                    'The physical location of the machine.'))
    vlan = models.ForeignKey('Vlan', verbose_name=_('vlan'),
                             help_text=_(
                                 'Vlan network that the host is part of.'))
    owner = models.ForeignKey(User, verbose_name=_('owner'),
                              help_text=_(
                                  'The person responsible for this host.'))
442
    groups = models.ManyToManyField('Group', symmetrical=False, blank=True,
443 444 445 446 447 448 449
                                    null=True, verbose_name=_('groups'),
                                    help_text=_(
                                        'Host groups the machine is part of.'))
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified at'))
450

451 452 453
    class Meta(object):
        unique_together = ('hostname', 'vlan')

454 455 456
    def __unicode__(self):
        return self.hostname

457 458 459 460 461 462 463 464
    @property
    def incoming_rules(self):
        return self.rules.filter(direction='1')

    @property
    def outgoing_rules(self):
        return self.rules.filter(direction='0')

465
    def clean(self):
466 467 468
        if (not self.shared_ip and self.pub_ipv4 and Host.objects.
                exclude(id=self.id).filter(pub_ipv4=self.pub_ipv4)):
            raise ValidationError(_("If shared_ip has been checked, "
469
                                    "pub_ipv4 has to be unique."))
470 471
        if Host.objects.exclude(id=self.id).filter(pub_ipv4=self.ipv4):
            raise ValidationError(_("You can't use another host's NAT'd "
472
                                    "address as your own IPv4."))
473 474 475

    def save(self, *args, **kwargs):
        if not self.id and self.ipv6 == "auto":
476
            self.ipv6 = ipv4_2_ipv6(self.vlan.ipv6_template, self.ipv4)
477
        self.full_clean()
478

479
        super(Host, self).save(*args, **kwargs)
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511

        if self.ipv4 is not None:
            Record.objects.filter(host=self, name=self.hostname,
                                  type='A').update(address=self.ipv4)
            record_count = self.record_set.filter(host=self,
                                                  name=self.hostname,
                                                  address=self.ipv4,
                                                  type='A').count()
            if record_count == 0:
                Record(host=self,
                       name=self.hostname,
                       domain=self.vlan.domain,
                       address=self.ipv4,
                       owner=self.owner,
                       description='host.save()',
                       type='A').save()

        if self.ipv6:
            Record.objects.filter(host=self, name=self.hostname,
                                  type='AAAA').update(address=self.ipv6)
            record_count = self.record_set.filter(host=self,
                                                  name=self.hostname,
                                                  address=self.ipv6,
                                                  type='AAAA').count()
            if record_count == 0:
                Record(host=self,
                       name=self.hostname,
                       domain=self.vlan.domain,
                       address=self.ipv6,
                       owner=self.owner,
                       description='host.save()',
                       type='AAAA').save()
512 513

    def enable_net(self):
514 515
        for i in settings.get('default_host_groups', []):
            self.groups.add(Group.objects.get(name=i))
516

517 518 519 520
    def _get_ports_used(self, proto):
        """
        Gives a list of port numbers used for the public IP address of current
        host for the given protocol.
521

522 523 524 525 526 527 528 529 530
        :param proto: The transport protocol of the generated port (tcp|udp).
        :type proto: str.
        :returns: list -- list of int port numbers used.
        """
        if self.shared_ip:
            ports = Rule.objects.filter(host__pub_ipv4=self.pub_ipv4,
                                        nat=True, proto=proto)
        else:
            ports = self.rules.filter(proto=proto, )
531
        return set(ports.values_list('dport', flat=True))
532 533 534 535 536 537 538 539

    def _get_random_port(self, proto, used_ports=None):
        """
        Get a random unused port for given protocol for current host's public
        IP address.

        :param proto: The transport protocol of the generated port (tcp|udp).
        :type proto: str.
540
        :param used_ports: Optional set of used ports returned by
541 542 543 544 545 546 547 548 549 550 551 552 553
                           _get_ports_used.
        :returns: int -- the generated port number.
        :raises: ValidationError
        """
        if used_ports is None:
            used_ports = self._get_ports_used(proto)

        public = random.randint(1024, 21000)  # pick a random port
        if public in used_ports:  # if it's in use, select smallest free one
            for i in range(1024, 21000) + range(24000, 65535):
                if i not in used_ports:
                    public = i
                    break
554
            else:
555 556
                raise ValidationError(
                    _("All %s ports are already in use.") % proto)
557
        return public
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577

    def add_port(self, proto, public=None, private=None):
        """
        Allow inbound traffic to a port.

        If the host uses a shared IP address, also set up port forwarding.

        :param proto: The transport protocol (tcp|udp).
        :type proto: str.
        :param public: Preferred public port number for forwarding (optional).
        :param private: Port number of host in subject.
        """
        assert proto in ('tcp', 'udp', )
        if public:
            if public in self._get_ports_used(proto):
                raise ValidationError(
                    _("Port %(proto)s %(public)s is already in use.") %
                    {'proto': proto, 'public': public})
        else:
            public = self._get_random_port(proto)
578

579 580 581 582 583 584
        try:
            vgname = settings["default_vlangroup"]
            vg = VlanGroup.objects.get(name=vgname)
        except VlanGroup.DoesNotExist as e:
            logger.error('Host.add_port: default_vlangroup %s missing. %s',
                         vgname, unicode(e))
585
        else:
586 587 588 589 590 591 592 593 594 595 596 597 598
            if self.shared_ip:
                if public < 1024:
                    raise ValidationError(
                        _("Only ports above 1024 can be used."))
                rule = Rule(direction='1', owner=self.owner, dport=public,
                            proto=proto, nat=True, accept=True,
                            nat_dport=private, host=self, foreign_network=vg)
            else:
                rule = Rule(direction='1', owner=self.owner, dport=private,
                            proto=proto, nat=False, accept=True,
                            host=self, foreign_network=vg)
            rule.full_clean()
            rule.save()
599 600

    def del_port(self, proto, private):
601 602 603 604 605 606 607 608 609 610
        """
        Remove rules about inbound traffic to a given port.

        If the host uses a shared IP address, also set up port forwarding.

        :param proto: The transport protocol (tcp|udp).
        :type proto: str.
        :param private: Port number of host in subject.
        """

611 612
        if self.shared_ip:
            self.rules.filter(owner=self.owner, proto=proto, host=self,
613
                              nat_dport=private).delete()
614 615
        else:
            self.rules.filter(owner=self.owner, proto=proto, host=self,
616
                              dport=private).delete()
617

618
    def get_hostname(self, proto, public=True):
619
        """
620
        Get a private or public hostname for host.
621 622 623 624 625

        :param proto: The IP version (ipv4|ipv6).
        :type proto: str.
        """
        assert proto in ('ipv6', 'ipv4', )
626 627
        try:
            if proto == 'ipv6':
628 629
                res = self.record_set.filter(type='AAAA',
                                             address=self.ipv6)
630
            elif proto == 'ipv4':
631
                if self.shared_ip and public:
632
                    res = Record.objects.filter(type='A',
633
                                                address=self.pub_ipv4)
634 635
                    if res.count() < 1:
                        return unicode(self.pub_ipv4)
636
                else:
637 638 639
                    res = self.record_set.filter(type='A',
                                                 address=self.ipv4)
            return unicode(res[0].fqdn)
640
        except:
641
            return None
642 643

    def list_ports(self):
644 645 646
        """
        Return a list of ports with forwarding rules set.
        """
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
        retval = []
        for rule in self.rules.filter(owner=self.owner):
            private = rule.nat_dport if self.shared_ip else rule.dport
            forward = {
                'proto': rule.proto,
                'private': private,
            }
            if self.shared_ip:
                public4 = rule.dport
                public6 = rule.nat_dport
            else:
                public4 = public6 = rule.dport

            if True:      # ipv4
                forward['ipv4'] = {
                    'host': self.get_hostname(proto='ipv4'),
                    'port': public4,
664
                    'pk': rule.pk,
665
                }
666
            if self.ipv6:  # ipv6
667 668 669
                forward['ipv6'] = {
                    'host': self.get_hostname(proto='ipv6'),
                    'port': public6,
670
                    'pk': rule.pk,
671 672 673 674 675
                }
            retval.append(forward)
        return retval

    def get_fqdn(self):
676 677 678
        """
        Get fully qualified host name of host.
        """
679
        return self.get_hostname('ipv4', public=False)
680

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
    def get_public_endpoints(self, port, protocol='tcp'):
        """Get public IPv4 and IPv6 endpoints for local port.

        Optionally the required protocol (e.g. TCP, UDP) can be specified.
        """
        endpoints = {}
        # IPv4
        public_ipv4 = self.pub_ipv4 if self.pub_ipv4 else self.ipv4
        # try get matching port(s) without NAT
        ports = self.incoming_rules.filter(accept=True, dport=port,
                                           nat=False, proto=protocol)
        if ports.exists():
            public_port = ports[0].dport
        else:
            # try get matching port(s) with NAT
            ports = self.incoming_rules.filter(accept=True, nat_dport=port,
                                               nat=True, proto=protocol)
            public_port = ports[0].dport if ports.exists() else None
        endpoints['ipv4'] = ((public_ipv4, public_port) if public_port else
                             None)
        # IPv6
        blocked = self.incoming_rules.filter(accept=False, dport=port,
                                             proto=protocol).exists()
        endpoints['ipv6'] = (self.ipv6, port) if not blocked else None
        return endpoints

707 708 709 710
    @models.permalink
    def get_absolute_url(self):
        return ('network.host', None, {'pk': self.pk})

711 712 713 714 715 716 717 718 719 720 721
    @property
    def eui(self):
        return EUI(self.mac)

    @property
    def hw_vendor(self):
        try:
            return self.eui.oui.registration().org
        except:
            return None

722 723

class Firewall(models.Model):
724 725
    name = models.CharField(max_length=20, unique=True,
                            verbose_name=_('name'))
726 727 728 729

    def __unicode__(self):
        return self.name

730

731
class Domain(models.Model):
732 733 734 735 736 737 738 739 740
    name = models.CharField(max_length=40, validators=[val_domain],
                            verbose_name=_('name'))
    owner = models.ForeignKey(User, verbose_name=_('owner'))
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created_at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified_at'))
    ttl = models.IntegerField(default=600, verbose_name=_('ttl'))
    description = models.TextField(blank=True, verbose_name=_('description'))
741 742 743 744

    def __unicode__(self):
        return self.name

745 746 747 748 749
    @models.permalink
    def get_absolute_url(self):
        return ('network.domain', None, {'pk': self.pk})


750 751
class Record(models.Model):
    CHOICES_type = (('A', 'A'), ('CNAME', 'CNAME'), ('AAAA', 'AAAA'),
752
                   ('MX', 'MX'), ('NS', 'NS'), ('PTR', 'PTR'), ('TXT', 'TXT'))
753
    name = models.CharField(max_length=40, validators=[val_domain],
754 755 756 757 758 759
                            blank=True, null=True, verbose_name=_('name'))
    domain = models.ForeignKey('Domain', verbose_name=_('domain'))
    host = models.ForeignKey('Host', blank=True, null=True,
                             verbose_name=_('host'))
    type = models.CharField(max_length=6, choices=CHOICES_type,
                            verbose_name=_('type'))
760
    address = models.CharField(max_length=200,
761 762 763 764 765 766 767 768
                               verbose_name=_('address'))
    ttl = models.IntegerField(default=600, verbose_name=_('ttl'))
    owner = models.ForeignKey(User, verbose_name=_('owner'))
    description = models.TextField(blank=True, verbose_name=_('description'))
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created_at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified_at'))
769 770 771 772 773

    def __unicode__(self):
        return self.desc()

    def desc(self):
774
        return u' '.join([self.fqdn, self.type, self.address])
775 776 777 778 779

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Record, self).save(*args, **kwargs)

780 781
    def _validate_record(self):
        """Validate a record."""
782 783
        if not self.address:
            raise ValidationError(_("Address must be specified!"))
784 785 786 787 788 789 790 791 792 793 794 795

        try:
            validator = {
                'A': val_ipv4,
                'AAAA': val_ipv6,
                'CNAME': val_domain,
                'MX': val_mx,
                'NS': val_domain,
                'PTR': val_domain,
                'TXT': None,
            }[self.type]
        except KeyError:
796
            raise ValidationError(_("Unknown record type."))
797 798 799
        else:
            if validator:
                validator(self.address)
800

801
    def clean(self):
802 803
        """Validate the Record to be saved.
        """
804 805 806
        if self.name:
            self.name = self.name.rstrip(".")    # remove trailing dots

807
        self._validate_record()
808

809 810
    @property
    def fqdn(self):
811 812 813 814
        if self.name:
            return '%s.%s' % (self.name, self.domain.name)
        else:
            return self.domain.name
815

816 817 818 819
    @models.permalink
    def get_absolute_url(self):
        return ('network.record', None, {'pk': self.pk})

820 821 822 823 824 825
    class Meta:
        ordering = (
            'domain',
            'name',
        )

826

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
class SwitchPort(models.Model):
    untagged_vlan = models.ForeignKey('Vlan',
                                      related_name='untagged_ports',
                                      verbose_name=_('untagged vlan'))
    tagged_vlans = models.ForeignKey('VlanGroup', blank=True, null=True,
                                     related_name='tagged_ports',
                                     verbose_name=_('tagged vlans'))
    description = models.TextField(blank=True, verbose_name=_('description'))
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created_at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified_at'))

    def __unicode__(self):
        devices = ','.join(self.ethernet_devices.values_list('name',
                                                             flat=True))
        tagged_vlans = self.tagged_vlans.name if self.tagged_vlans else ''
        return 'devices=%s untagged=%s tagged=%s' % (devices,
                                                     self.untagged_vlan,
                                                     tagged_vlans)

848 849 850 851
    @models.permalink
    def get_absolute_url(self):
        return ('network.switch_port', None, {'pk': self.pk})

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871

class EthernetDevice(models.Model):
    name = models.CharField(max_length=20,
                            unique=True,
                            verbose_name=_('interface'),
                            help_text=_('The name of network interface the '
                                        'gateway should serve this network '
                                        'on. For example eth2.'))
    switch_port = models.ForeignKey('SwitchPort',
                                    related_name='ethernet_devices',
                                    verbose_name=_('switch port'))
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created_at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified_at'))

    def __unicode__(self):
        return self.name


872
class Blacklist(models.Model):
873 874
    CHOICES_type = (('permban', 'permanent ban'), ('tempban', 'temporary ban'),
                    ('whitelist', 'whitelist'), ('tempwhite', 'tempwhite'))
875
    ipv4 = models.GenericIPAddressField(protocol='ipv4', unique=True)
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    host = models.ForeignKey('Host', blank=True, null=True,
                             verbose_name=_('host'))
    reason = models.TextField(blank=True, verbose_name=_('reason'))
    snort_message = models.TextField(blank=True,
                                     verbose_name=_('short message'))
    type = models.CharField(
        max_length=10,
        choices=CHOICES_type,
        default='tempban',
        verbose_name=_('type')
    )
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created_at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified_at'))
891 892 893 894

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Blacklist, self).save(*args, **kwargs)
895

896 897 898
    def __unicode__(self):
        return self.ipv4

899 900 901 902 903
    @models.permalink
    def get_absolute_url(self):
        return ('network.blacklist', None, {'pk': self.pk})


904
def send_task(sender, instance, created=False, **kwargs):
905
    reloadtask.apply_async(queue='localhost.man', args=[sender.__name__])
906 907


908 909 910 911
for sender in [Host, Rule, Domain, Record, Vlan, Firewall, Group, Blacklist,
               SwitchPort, EthernetDevice]:
    post_save.connect(send_task, sender=sender)
    post_delete.connect(send_task, sender=sender)