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

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.

20
from string import ascii_letters
21
from itertools import islice, ifilter, chain
22
from math import ceil
23
import logging
24
import random
25

26 27
from django.contrib.auth.models import User
from django.db import models
28
from django.forms import ValidationError
29
from django.utils.translation import ugettext_lazy as _
30
from firewall.fields import (MACAddressField, val_alfanum, val_reverse_domain,
31
                             val_ipv6_template, val_domain, val_ipv4,
32
                             val_domain_wildcard,
33
                             val_ipv6, val_mx,
34
                             IPNetworkField, IPAddressField)
35
from django.core.validators import MinValueValidator, MaxValueValidator
36
from django.core.urlresolvers import reverse
37
import django.conf
38
from django.db.models.signals import post_save, post_delete
39
from celery.exceptions import TimeoutError
40
from netaddr import IPSet, EUI, IPNetwork, IPAddress, ipv6_full
41

42
from common.models import method_cache, WorkerNotFound, HumanSortField
Bach Dániel committed
43
from firewall.tasks.local_tasks import reloadtask
44
from firewall.tasks.remote_tasks import get_dhcp_clients
45
from .iptables import IptRule
46
from acl.models import AclBase
47 48


49
logger = logging.getLogger(__name__)
50
settings = django.conf.settings.FIREWALL_SETTINGS
51 52


53 54
class Rule(models.Model):

55 56 57
    """
    A rule of a packet filter, changing the behavior of a host, vlan or
    firewall.
58

59 60
    Some rules accept or deny packets matching some criteria.
    Others set address translation or other free-form iptables parameters.
61 62
    """
    CHOICES_type = (('host', 'host'), ('firewall', 'firewall'),
Bach Dániel committed
63
                    ('vlan', 'vlan'))
64
    CHOICES_proto = (('tcp', 'tcp'), ('udp', 'udp'), ('icmp', 'icmp'))
65 66 67
    CHOICES_dir = (('out', _('out')), ('in', _('in')))
    CHOICES_action = (('accept', _('accept')), ('drop', _('drop')),
                      ('ignore', _('ignore')))
68

69
    direction = models.CharField(max_length=3, choices=CHOICES_dir,
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
                                 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."))
89 90
    weight = models.IntegerField(
        verbose_name=_("weight"),
91
        validators=[MinValueValidator(1), MaxValueValidator(65535)],
92 93
        help_text=_("Rule weight"),
        default=30000)
94
    proto = models.CharField(max_length=10, choices=CHOICES_proto,
95 96 97 98 99
                             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."))
100 101 102 103
    action = models.CharField(max_length=10, choices=CHOICES_action,
                              default='drop', verbose_name=_('action'),
                              help_text=_("Accept, drop or ignore the "
                                          "matching packets."))
104 105 106 107
    owner = models.ForeignKey(User, blank=True, null=True,
                              verbose_name=_("owner"),
                              help_text=_("The user responsible for "
                                          "this rule."))
108

109 110
    nat = models.BooleanField(default=False, verbose_name=_("NAT"),
                              help_text=_("If network address translation "
111
                                          "should be done."))
112 113 114 115 116 117 118 119 120
    nat_external_port = models.IntegerField(
        blank=True, null=True,
        help_text=_("Rewrite destination port number to this if NAT is "
                    "needed."),
        validators=[MinValueValidator(1), MaxValueValidator(65535)])
    nat_external_ipv4 = IPAddressField(
        version=4, blank=True, null=True,
        verbose_name=_('external IPv4 address'))

121 122 123 124 125 126
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name=_("created at"))
    modified_at = models.DateTimeField(
        auto_now=True,
        verbose_name=_("modified at"))
127 128

    vlan = models.ForeignKey('Vlan', related_name="rules", blank=True,
129 130 131
                             null=True, verbose_name=_("vlan"),
                             help_text=_("Vlan the rule applies to "
                                         "(if type is vlan)."))
132
    vlangroup = models.ForeignKey('VlanGroup', related_name="rules",
133 134 135 136
                                  blank=True, null=True, verbose_name=_(
                                      "vlan group"),
                                  help_text=_("Group of vlans the rule "
                                              "applies to (if type is vlan)."))
137
    host = models.ForeignKey('Host', related_name="rules", blank=True,
138 139 140 141 142 143 144 145 146 147 148 149
                             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)
150 151 152 153 154 155

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

    def clean(self):
        fields = [self.vlan, self.vlangroup, self.host, self.hostgroup,
156
                  self.firewall]
157 158 159 160
        selected_fields = [field for field in fields if field]
        if len(selected_fields) > 1:
            raise ValidationError(_('Only one field can be selected.'))

161 162 163 164 165 166 167 168 169 170 171
    def get_external_ipv4(self):
        return (self.nat_external_ipv4
                if self.nat_external_ipv4 else self.host.get_external_ipv4())

    def get_external_port(self, proto='ipv4'):
        assert proto in ('ipv4', 'ipv6')
        if proto == 'ipv4' and self.nat_external_port:
            return self.nat_external_port
        else:
            return self.dport

172
    def desc(self):
173 174
        """Return a short string representation of the current rule.
        """
175 176
        return u'[%(type)s] %(src)s ▸ %(dst)s %(para)s %(desc)s' % {
            'type': self.r_type,
177
            'src': (unicode(self.foreign_network) if self.direction == 'in'
178
                    else self.r_type),
179
            'dst': (self.r_type if self.direction == 'out'
180
                    else unicode(self.foreign_network)),
181 182 183 184 185
            '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}

186 187 188 189 190 191 192 193 194
    @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

195
    def get_absolute_url(self):
196
        return reverse('network.rule', kwargs={'pk': self.pk})
197

198 199 200 201 202 203 204 205 206 207 208 209
    def get_chain_name(self, local, remote):
        if local:  # host or vlan
            if self.direction == 'in':
                # remote -> local
                return '%s_%s' % (remote.name, local.name)
            else:
                # local -> remote
                return '%s_%s' % (local.name, remote.name)
            # firewall rule
        elif self.firewall_id:
            return 'INPUT' if self.direction == 'in' else 'OUTPUT'

210 211
    def get_ipt_rules(self, host=None):
        # action
212
        action = 'LOG_ACC' if self.action == 'accept' else 'LOG_DROP'
213

214 215 216
        # 'chain_name': rule dict
        retval = {}

217 218 219 220 221
        # src and dst addresses
        src = None
        dst = None

        if host:
222
            ip = (host.ipv4, host.ipv6_with_host_prefixlen)
223 224 225 226
            if self.direction == 'in':
                dst = ip
            else:
                src = ip
227 228 229
            vlan = host.vlan
        elif self.vlan_id:
            vlan = self.vlan
230
        else:
231
            vlan = None
232

233 234 235
        if vlan and not vlan.managed:
            return retval

236 237
        # process foreign vlans
        for foreign_vlan in self.foreign_network.vlans.all():
238 239 240
            if not foreign_vlan.managed:
                continue

241
            r = IptRule(priority=self.weight, action=action,
242
                        proto=self.proto, extra=self.extra,
243
                        comment='Rule #%s' % self.pk,
244
                        src=src, dst=dst, dport=self.dport, sport=self.sport)
245
            chain_name = self.get_chain_name(local=vlan, remote=foreign_vlan)
246 247 248 249
            retval[chain_name] = r

        return retval

250 251 252 253 254 255 256
    @classmethod
    def portforwards(cls, host=None):
        qs = cls.objects.filter(dport__isnull=False, direction='in')
        if host is not None:
            qs = qs.filter(host=host)
        return qs

257 258 259 260 261 262 263 264
    class Meta:
        verbose_name = _("rule")
        verbose_name_plural = _("rules")
        ordering = (
            'direction',
            'proto',
            'sport',
            'dport',
265
            'nat_external_port',
266 267 268 269
            'host',
        )


270
class Vlan(AclBase, models.Model):
271 272 273 274 275 276 277 278 279 280 281 282

    """
    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.
    """

283 284 285 286
    ACL_LEVELS = (
        ('user', _('user')),
        ('operator', _('operator')),
    )
287
    CHOICES_NETWORK_TYPE = (('public', _('public')),
288
                            ('portforward', _('portforward')))
289 290 291 292 293 294 295 296 297 298
    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])
299 300 301 302 303
    network4 = IPNetworkField(unique=False,
                              version=4,
                              verbose_name=_('IPv4 address/prefix'),
                              help_text=_(
                                  'The IPv4 address and the prefix length '
304
                                  'of the gateway. '
305 306 307 308
                                  'Recommended value is the last '
                                  'valid address of the subnet, '
                                  'for example '
                                  '10.4.255.254/16 for 10.4.0.0/16.'))
309 310 311 312 313 314
    host_ipv6_prefixlen = models.IntegerField(
        verbose_name=_('IPv6 prefixlen/host'),
        help_text=_('The prefix length of the subnet assigned to a host. '
                    'For example /112 = 65536 addresses/host.'),
        default=112,
        validators=[MinValueValidator(1), MaxValueValidator(128)])
315 316 317 318 319 320 321 322
    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.'))
323
    snat_ip = models.GenericIPAddressField(protocol='ipv4', blank=True,
324 325 326 327 328 329 330 331
                                           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).'))
332
    snat_to = models.ManyToManyField('self', symmetrical=False, blank=True,
333
                                     verbose_name=_('NAT to'),
334 335 336 337 338 339
                                     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.'))
340 341
    network_type = models.CharField(choices=CHOICES_NETWORK_TYPE,
                                    verbose_name=_('network type'),
342
                                    default='portforward',
343
                                    max_length=20)
344
    managed = models.BooleanField(default=True, verbose_name=_('managed'))
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
    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")
366
    ipv6_template = models.TextField(
367 368 369 370 371 372 373 374 375 376 377
        blank=True,
        help_text=_('Template for translating IPv4 addresses to IPv6. '
                    'Automatically generated hosts in dual-stack networks '
                    'will get this address. The template '
                    'can contain four tokens: "%(a)d", "%(b)d", '
                    '"%(c)d", and "%(d)d", representing the four bytes '
                    'of the IPv4 address, respectively, in decimal notation. '
                    'Moreover you can use any standard printf format '
                    'specification like %(a)02x to get the first byte as two '
                    'hexadecimal digits. Usual choices for mapping '
                    '198.51.100.0/24 to 2001:0DB8:1:1::/64 would be '
378
                    '"2001:db8:1:1:%(d)d::" and "2001:db8:1:1:%(d)02x00::".'),
379
        validators=[val_ipv6_template], verbose_name=_('ipv6 template'))
380 381 382 383 384 385 386 387 388 389 390 391 392
    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'))
393

394 395 396 397 398
    class Meta:
        verbose_name = _("vlan")
        verbose_name_plural = _("vlans")
        ordering = ('vid', )

399 400 401 402 403 404 405 406 407 408 409 410 411
    def clean(self):
        super(Vlan, self).clean()
        if self.ipv6_template:
            if not self.network6:
                raise ValidationError(
                    _("You cannot specify an IPv6 template if there is no "
                      "IPv6 network set."))
            for i in (self.network4[1], self.network4[-1]):
                i6 = self.convert_ipv4_to_ipv6(i)
                if i6 not in self.network6:
                    raise ValidationError(
                        _("%(ip6)s (translated from %(ip4)s) is outside of "
                          "the IPv6 network.") % {"ip4": i, "ip6": i6})
412 413 414 415 416 417 418
        if self.network6:
            tpl, prefixlen = self._magic_ipv6_template(self.network4,
                                                       self.network6)
            if not self.ipv6_template:
                self.ipv6_template = tpl
            if not self.host_ipv6_prefixlen:
                self.host_ipv6_prefixlen = prefixlen
419

420 421 422 423
    @staticmethod
    def _host_bytes(prefixlen, maxbytes):
        return int(ceil((maxbytes - prefixlen / 8.0)))

Őry Máté committed
424 425 426 427 428 429 430 431 432 433 434
    @staticmethod
    def _append_hexa(s, v, lasthalf):
        if lasthalf:  # can use last half word
            assert s[-1] == "0" or s[-1].endswith("00")
            if s[-1].endswith("00"):
                s[-1] = s[-1][:-2]
            s[-1] += "%({})02x".format(v)
            s[-1].lstrip("0")
        else:
            s.append("%({})02x00".format(v))

435 436
    @classmethod
    def _magic_ipv6_template(cls, network4, network6, verbose=None):
437 438 439 440 441 442 443 444 445 446 447 448 449
        """Offer a sensible ipv6_template value.

        Based on prefix lengths the method magically selects verbose (decimal)
        format:
        >>> Vlan._magic_ipv6_template(IPNetwork("198.51.100.0/24"),
        ...                           IPNetwork("2001:0DB8:1:1::/64"))
        ('2001:db8:1:1:%(d)d::', 80)

        However you can explicitly select non-verbose, i.e. hexa format:
        >>> Vlan._magic_ipv6_template(IPNetwork("198.51.100.0/24"),
        ...                           IPNetwork("2001:0DB8:1:1::/64"), False)
        ('2001:db8:1:1:%(d)02x00::', 72)
        """
450 451
        host4_bytes = cls._host_bytes(network4.prefixlen, 4)
        host6_bytes = cls._host_bytes(network6.prefixlen, 16)
Őry Máté committed
452 453 454
        if host4_bytes > host6_bytes:
            raise ValidationError(
                _("IPv6 network is too small to map IPv4 addresses to it."))
455 456 457 458 459 460 461 462 463 464 465 466
        letters = ascii_letters[4-host4_bytes:4]
        remove = host6_bytes // 2
        ipstr = network6.network.format(ipv6_full)
        s = ipstr.split(":")[0:-remove]
        if verbose is None:  # use verbose format if net6 much wider
            verbose = 2 * (host4_bytes + 1) < host6_bytes
        if verbose:
            for i in letters:
                s.append("%({})d".format(i))
        else:
            remain = host6_bytes
            for i in letters:
467
                cls._append_hexa(s, i, remain % 2 == 1)
468 469 470
                remain -= 1
        if host6_bytes > host4_bytes:
            s.append(":")
471 472 473 474 475 476 477 478
        tpl = ":".join(s)
        # compute prefix length
        mask = int(IPAddress(tpl % {"a": 1, "b": 1, "c": 1, "d": 1}))
        prefixlen = 128
        while mask % 2 == 0:
            mask /= 2
            prefixlen -= 1
        return (tpl, prefixlen)
479

480
    def __unicode__(self):
481 482
        return "%s - %s" % ("managed" if self.managed else "unmanaged",
                            self.name)
483

484
    def get_absolute_url(self):
485
        return reverse('network.vlan', kwargs={'vid': self.vid})
486

487 488 489 490 491 492
    def get_random_addresses(self, used_v4, buffer_size=100, max_hosts=10000):
        addresses = islice(self.network4.iter_hosts(), max_hosts)
        unused_addresses = list(islice(
            ifilter(lambda x: x not in used_v4, addresses), buffer_size))
        random.shuffle(unused_addresses)
        return unused_addresses
493

494
    def get_new_address(self):
495
        hosts = self.host_set
496 497 498
        used_v4 = IPSet(hosts.values_list('ipv4', flat=True))
        used_v6 = IPSet(hosts.exclude(ipv6__isnull=True)
                        .values_list('ipv6', flat=True))
499

500 501 502 503
        for ipv4 in self.get_random_addresses(used_v4):
            logger.debug("Found unused IPv4 address %s.", ipv4)
            ipv6 = None
            if self.network6 is not None:
504
                ipv6 = self.convert_ipv4_to_ipv6(ipv4)
505 506 507 508 509
                if ipv6 in used_v6:
                    continue
                else:
                    logger.debug("Found unused IPv6 address %s.", ipv6)
            return {'ipv4': ipv4, 'ipv6': ipv6}
510 511
        else:
            raise ValidationError(_("All IP addresses are already in use."))
512

513 514
    def convert_ipv4_to_ipv6(self, ipv4):
        """Convert IPv4 address string to IPv6 address string."""
515 516
        if isinstance(ipv4, basestring):
            ipv4 = IPAddress(ipv4, 4)
517 518 519
        nums = {ascii_letters[i]: int(ipv4.words[i]) for i in range(4)}
        return IPAddress(self.ipv6_template % nums)

520 521 522 523 524 525 526
    def get_dhcp_clients(self):
        macs = set(i.mac for i in self.host_set.all())
        return [{"mac": k, "ip": v["ip"], "hostname": v["hostname"]}
                for k, v in chain(*(fw.get_dhcp_clients().iteritems()
                                    for fw in Firewall.objects.all() if fw))
                if v["interface"] == self.name and EUI(k) not in macs]

527

528
class VlanGroup(models.Model):
529 530 531 532 533 534
    """
    A group of Vlans.
    """

    name = models.CharField(max_length=20, unique=True, verbose_name=_('name'),
                            help_text=_('The name of the group.'))
535
    vlans = models.ManyToManyField('Vlan', symmetrical=False, blank=True,
536
                                   verbose_name=_('vlans'),
537 538 539 540 541 542 543 544 545 546
                                   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'))
547

548 549 550 551 552
    class Meta:
        verbose_name = _("vlan group")
        verbose_name_plural = _("vlan groups")
        ordering = ('id', )

553 554 555
    def __unicode__(self):
        return self.name

556
    def get_absolute_url(self):
557
        return reverse('network.vlan_group', kwargs={'pk': self.pk})
558 559


560
class Group(models.Model):
561 562 563 564 565 566 567 568 569 570 571 572 573
    """
    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'))
574

575 576 577 578 579
    class Meta:
        verbose_name = _("host group")
        verbose_name_plural = _("host groups")
        ordering = ('id', )

580 581 582
    def __unicode__(self):
        return self.name

583
    def get_absolute_url(self):
584
        return reverse('network.group', kwargs={'pk': self.pk})
585 586


587
class Host(models.Model):
588 589 590 591
    """
    A host of the network.
    """

592
    hostname = models.CharField(max_length=40,
593 594 595 596 597
                                verbose_name=_('hostname'),
                                help_text=_('The alphanumeric hostname of '
                                            'the host, the first part of '
                                            'the FQDN.'),
                                validators=[val_alfanum])
598
    normalized_hostname = HumanSortField(monitor='hostname', max_length=80)
599
    reverse = models.CharField(max_length=40, validators=[val_domain],
600 601 602 603 604 605 606 607 608
                               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.'))
609 610 611 612
    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.'))
613
    external_ipv4 = IPAddressField(
614
        version=4, blank=True, null=True,
615 616 617
        verbose_name=_('WAN IPv4 address'),
        help_text=_('The public IPv4 address of the host on the wide '
                    'area network, if different.'))
618 619 620 621 622
    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.'))
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    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.'))
641
    groups = models.ManyToManyField('Group', symmetrical=False, blank=True,
642
                                    verbose_name=_('groups'),
643 644 645 646 647 648
                                    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'))
649

650 651
    class Meta(object):
        unique_together = ('hostname', 'vlan')
652
        ordering = ('normalized_hostname', 'vlan')
653

654 655 656
    def __unicode__(self):
        return self.hostname

657 658
    @property
    def incoming_rules(self):
659
        return self.rules.filter(direction='in')
660

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
    @staticmethod
    def create_ipnetwork(ip, prefixlen):
        try:
            net = IPNetwork(ip)
            net.prefixlen = prefixlen
        except TypeError:
            return None
        else:
            return net

    @property
    def ipv4_with_vlan_prefixlen(self):
        return Host.create_ipnetwork(
            self.ipv4, self.vlan.network4.prefixlen)

    @property
    def ipv6_with_vlan_prefixlen(self):
        return Host.create_ipnetwork(
            self.ipv6, self.vlan.network6.prefixlen)

681
    @property
682 683 684
    def ipv6_with_host_prefixlen(self):
        return Host.create_ipnetwork(
            self.ipv6, self.vlan.host_ipv6_prefixlen)
685 686 687 688 689 690 691

    def get_external_ipv4(self):
        return self.external_ipv4 if self.external_ipv4 else self.ipv4

    @property
    def behind_nat(self):
        return self.vlan.network_type != 'public'
692

693
    def clean(self):
694 695 696
        if (self.external_ipv4 and not self.shared_ip and self.behind_nat
                and Host.objects.exclude(id=self.id).filter(
                    external_ipv4=self.external_ipv4)):
697
            raise ValidationError(_("If shared_ip has been checked, "
698 699
                                    "external_ipv4 has to be unique."))
        if Host.objects.exclude(id=self.id).filter(external_ipv4=self.ipv4):
700
            raise ValidationError(_("You can't use another host's NAT'd "
701
                                    "address as your own IPv4."))
702 703 704

    def save(self, *args, **kwargs):
        if not self.id and self.ipv6 == "auto":
705
            self.ipv6 = self.vlan.convert_ipv4_to_ipv6(self.ipv4)
706
        self.full_clean()
707

708
        super(Host, self).save(*args, **kwargs)
709

Bach Dániel committed
710
        # IPv4
711
        if self.ipv4 is not None:
Bach Dániel committed
712 713 714 715
            if not self.shared_ip and self.external_ipv4:  # DMZ
                ipv4 = self.external_ipv4
            else:
                ipv4 = self.ipv4
Bach Dániel committed
716 717 718
            # update existing records
            affected_records = Record.objects.filter(
                host=self, name=self.hostname,
Bach Dániel committed
719
                type='A').update(address=ipv4)
Bach Dániel committed
720 721
            # create new record
            if affected_records == 0:
722 723 724 725 726
                Record(host=self,
                       name=self.hostname,
                       domain=self.vlan.domain,
                       address=self.ipv4,
                       owner=self.owner,
Bach Dániel committed
727
                       description='created by host.save()',
728 729
                       type='A').save()

Bach Dániel committed
730 731 732 733 734 735 736 737
        # IPv6
        if self.ipv6 is not None:
            # update existing records
            affected_records = Record.objects.filter(
                host=self, name=self.hostname,
                type='AAAA').update(address=self.ipv6)
            # create new record
            if affected_records == 0:
738 739 740 741 742
                Record(host=self,
                       name=self.hostname,
                       domain=self.vlan.domain,
                       address=self.ipv6,
                       owner=self.owner,
Bach Dániel committed
743
                       description='created by host.save()',
744
                       type='AAAA').save()
745

Bach Dániel committed
746 747 748 749
    def get_network_config(self):
        interface = {'addresses': []}

        if self.ipv4 and self.vlan.network4:
750
            interface['addresses'].append(str(self.ipv4_with_vlan_prefixlen))
Bach Dániel committed
751 752 753
            interface['gw4'] = str(self.vlan.network4.ip)

        if self.ipv6 and self.vlan.network6:
754
            interface['addresses'].append(str(self.ipv6_with_vlan_prefixlen))
Bach Dániel committed
755 756 757 758
            interface['gw6'] = str(self.vlan.network6.ip)

        return interface

759
    def enable_net(self):
760 761
        for i in settings.get('default_host_groups', []):
            self.groups.add(Group.objects.get(name=i))
762

763 764 765 766
    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.
767

768 769 770 771
        :param proto: The transport protocol of the generated port (tcp|udp).
        :type proto: str.
        :returns: list -- list of int port numbers used.
        """
772 773 774 775 776
        if self.behind_nat:
            ports = Rule.objects.filter(
                host__external_ipv4=self.external_ipv4,
                nat=True,
                proto=proto).values_list('nat_external_port', flat=True)
777
        else:
778 779 780
            ports = self.rules.filter(proto=proto).values_list(
                'dport', flat=True)
        return set(ports)
781 782 783 784 785 786 787 788

    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.
789
        :param used_ports: Optional set of used ports returned by
790 791 792 793 794 795 796 797 798 799 800 801 802
                           _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
803
            else:
804 805
                raise ValidationError(
                    _("All %s ports are already in use.") % proto)
806
        return public
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826

    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)
827

828 829 830 831 832 833
        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))
834
        else:
835
            rule = Rule(direction='in', owner=self.owner, dport=private,
836
                        proto=proto, nat=False, action='accept',
837 838 839 840
                        host=self, foreign_network=vg)
            if self.behind_nat:
                rule.nat_external_port = public
                rule.nat = True
841 842
            rule.full_clean()
            rule.save()
843 844

    def del_port(self, proto, private):
845 846 847 848 849 850 851 852 853 854
        """
        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.
        """

855
        self.rules.filter(proto=proto, dport=private).delete()
856

857
    def get_hostname(self, proto, public=True):
858
        """
859
        Get a private or public hostname for host.
860 861 862 863 864

        :param proto: The IP version (ipv4|ipv6).
        :type proto: str.
        """
        assert proto in ('ipv6', 'ipv4', )
Bach Dániel committed
865 866
        if self.reverse:
            return self.reverse
867 868
        try:
            if proto == 'ipv6':
869 870
                res = self.record_set.filter(type='AAAA',
                                             address=self.ipv6)
871
            elif proto == 'ipv4':
872 873 874
                if self.behind_nat and public:
                    res = Record.objects.filter(
                        type='A', address=self.get_external_ipv4())
875
                    if res.count() < 1:
876
                        return unicode(self.get_external_ipv4())
877
                else:
878 879 880
                    res = self.record_set.filter(type='A',
                                                 address=self.ipv4)
            return unicode(res[0].fqdn)
881
        except:
882
            return None
883 884

    def list_ports(self):
885 886 887
        """
        Return a list of ports with forwarding rules set.
        """
888
        retval = []
889
        for rule in Rule.portforwards(host=self):
890 891
            forward = {
                'proto': rule.proto,
892
                'private': rule.dport,
893 894 895 896 897
            }

            if True:      # ipv4
                forward['ipv4'] = {
                    'host': self.get_hostname(proto='ipv4'),
898
                    'port': rule.get_external_port(proto='ipv4'),
899
                    'pk': rule.pk,
900
                }
901
            if self.ipv6:  # ipv6
902 903
                forward['ipv6'] = {
                    'host': self.get_hostname(proto='ipv6'),
904
                    'port': rule.get_external_port(proto='ipv6'),
905
                    'pk': rule.pk,
906 907 908 909 910
                }
            retval.append(forward)
        return retval

    def get_fqdn(self):
911 912 913
        """
        Get fully qualified host name of host.
        """
914
        return self.get_hostname('ipv4', public=False)
915

916 917 918 919 920 921 922
    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
923
        ports = self.incoming_rules.filter(action='accept', dport=port,
924 925 926 927 928
                                           proto=protocol)
        public_port = (ports[0].get_external_port(proto='ipv4')
                       if ports.exists() else None)
        endpoints['ipv4'] = ((self.get_external_ipv4(), public_port)
                             if public_port else
929 930
                             None)
        # IPv6
931
        endpoints['ipv6'] = (self.ipv6, port) if public_port else None
932 933
        return endpoints

934
    def get_absolute_url(self):
935
        return reverse('network.host', kwargs={'pk': self.pk})
936

937 938 939 940 941 942 943 944 945 946 947
    @property
    def eui(self):
        return EUI(self.mac)

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

948 949

class Firewall(models.Model):
950 951
    name = models.CharField(max_length=20, unique=True,
                            verbose_name=_('name'))
952

953 954 955 956 957
    class Meta:
        verbose_name = _("firewall")
        verbose_name_plural = _("firewalls")
        ordering = ('id', )

958 959 960
    def __unicode__(self):
        return self.name

961
    @method_cache(30)
962
    def get_remote_queue_name(self, queue_id="firewall"):
963 964 965 966 967 968 969 970 971 972 973 974
        """Returns the name of the remote celery queue for this node.

        Throws Exception if there is no worker on the queue.
        The result may include dead queues because of caching.
        """
        from .tasks.remote_tasks import check_queue

        if check_queue(self.name, queue_id, None):
            return self.name + "." + queue_id
        else:
            raise WorkerNotFound()

975 976 977 978 979 980
    @method_cache(20)
    def get_dhcp_clients(self):
        try:
            return get_dhcp_clients.apply_async(
                queue=self.get_remote_queue_name(), expires=60).get(timeout=2)
        except TimeoutError:
981 982 983 984 985 986
            logger.info("get_dhcp_clients task timed out")
        except IOError:
            logger.exception("get_dhcp_clients failed. "
                             "maybe syslog isn't readble by firewall worker")
        except:
            logger.exception("get_dhcp_clients failed")
Őry Máté committed
987
        return {}
988

Kálmán Viktor committed
989
    def get_absolute_url(self):
990
        return reverse('network.firewall', kwargs={'pk': self.pk})
Kálmán Viktor committed
991

992

993
class Domain(models.Model):
994 995 996 997 998 999 1000 1001 1002
    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'))
1003

1004 1005 1006 1007 1008
    class Meta:
        verbose_name = _("domain")
        verbose_name_plural = _("domains")
        ordering = ('id', )

1009 1010 1011
    def __unicode__(self):
        return self.name

1012
    def get_absolute_url(self):
1013
        return reverse('network.domain', kwargs={'pk': self.pk})
1014 1015


1016 1017
class Record(models.Model):
    CHOICES_type = (('A', 'A'), ('CNAME', 'CNAME'), ('AAAA', 'AAAA'),
Bach Dániel committed
1018
                    ('MX', 'MX'), ('NS', 'NS'), ('PTR', 'PTR'), ('TXT', 'TXT'))
1019
    name = models.CharField(max_length=40, validators=[val_domain_wildcard],
1020 1021 1022 1023 1024 1025
                            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'))
1026
    address = models.CharField(max_length=400,
1027 1028 1029 1030 1031 1032 1033 1034
                               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'))
1035 1036 1037 1038 1039

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

    def desc(self):
1040
        return u' '.join([self.fqdn, self.type, self.address])
1041 1042 1043 1044 1045

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

1046 1047
    def _validate_record(self):
        """Validate a record."""
1048 1049
        if not self.address:
            raise ValidationError(_("Address must be specified!"))
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061

        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:
1062
            raise ValidationError(_("Unknown record type."))
1063 1064 1065
        else:
            if validator:
                validator(self.address)
1066

1067
    def clean(self):
1068 1069
        """Validate the Record to be saved.
        """
1070 1071 1072
        if self.name:
            self.name = self.name.rstrip(".")    # remove trailing dots

1073
        self._validate_record()
1074

1075 1076
    @property
    def fqdn(self):
1077 1078 1079 1080
        if self.name:
            return '%s.%s' % (self.name, self.domain.name)
        else:
            return self.domain.name
1081

1082
    def get_absolute_url(self):
1083
        return reverse('network.record', kwargs={'pk': self.pk})
1084

1085
    class Meta:
1086 1087
        verbose_name = _("record")
        verbose_name_plural = _("records")
1088 1089 1090 1091 1092
        ordering = (
            'domain',
            'name',
        )

1093

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
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'))

1107 1108 1109 1110 1111
    class Meta:
        verbose_name = _("switch port")
        verbose_name_plural = _("switch ports")
        ordering = ('id', )

1112 1113 1114 1115 1116 1117 1118 1119
    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)

1120
    def get_absolute_url(self):
1121
        return reverse('network.switch_port', kwargs={'pk': self.pk})
1122

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

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'))

1139 1140 1141 1142 1143
    class Meta:
        verbose_name = _("ethernet device")
        verbose_name_plural = _("ethernet devices")
        ordering = ('id', )

1144 1145 1146 1147
    def __unicode__(self):
        return self.name


1148
class BlacklistItem(models.Model):
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    ipv4 = models.GenericIPAddressField(
        protocol='ipv4', unique=True, verbose_name=("IPv4 address"))
    host = models.ForeignKey(
        'Host', blank=True, null=True, verbose_name=_('host'))
    reason = models.TextField(
        blank=True, null=True, verbose_name=_('reason'))
    snort_message = models.TextField(
        blank=True, null=True, verbose_name=_('short message'))

    whitelisted = models.BooleanField(
        default=False, verbose_name=_("whitelisted"))
1160 1161 1162 1163
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('created_at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       verbose_name=_('modified_at'))
1164 1165
    expires_at = models.DateTimeField(blank=True, null=True, default=None,
                                      verbose_name=_('expires at'))
1166 1167 1168

    def save(self, *args, **kwargs):
        self.full_clean()
1169
        super(BlacklistItem, self).save(*args, **kwargs)
1170

1171 1172 1173
    def __unicode__(self):
        return self.ipv4

1174 1175
    class Meta(object):
        verbose_name = _('blacklist item')
1176 1177
        verbose_name_plural = _('blacklist items')
        ordering = ('id', )
1178

1179
    def get_absolute_url(self):
1180
        return reverse('network.blacklist', kwargs={'pk': self.pk})
1181 1182


1183
def send_task(sender, instance, created=False, **kwargs):
1184
    reloadtask.apply_async(queue='localhost.man', args=[sender.__name__])
1185 1186


1187 1188
for sender in [Host, Rule, Domain, Record, Vlan, Firewall, Group,
               BlacklistItem, SwitchPort, EthernetDevice]:
1189 1190
    post_save.connect(send_task, sender=sender)
    post_delete.connect(send_task, sender=sender)