models.py 72.9 KB
Newer Older
1
# -*- mode: python; coding: utf-8 -*-
lhark's avatar
lhark committed
2
3
4
5
# Re2o est un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
Gabriel Detraz's avatar
Gabriel Detraz committed
6
# Copyright © 2016-2018  Gabriel Détraz
lhark's avatar
lhark committed
7
8
# Copyright © 2017  Goulven Kermarec
# Copyright © 2017  Augustin Lemesle
Gabriel Detraz's avatar
Gabriel Detraz committed
9
# Copyright © 2018  Charlie Jacomme
lhark's avatar
lhark committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Maël Kervella's avatar
Maël Kervella committed
24
25
26
"""machines.models
The models definitions for the Machines app
"""
lhark's avatar
lhark committed
27

28
29
from __future__ import unicode_literals

erdnaxe's avatar
erdnaxe committed
30
31
import base64
import hashlib
Gabriel Detraz's avatar
Gabriel Detraz committed
32
import re
erdnaxe's avatar
erdnaxe committed
33
from datetime import timedelta
34
from ipaddress import IPv6Address
35
from itertools import chain
Gabriel Detraz's avatar
Gabriel Detraz committed
36

erdnaxe's avatar
erdnaxe committed
37
from django.core.validators import MaxValueValidator, MinValueValidator
Dalahro's avatar
Dalahro committed
38
from django.db import models
39
from django.db.models import Q
Gabriel Detraz's avatar
Gabriel Detraz committed
40
from django.db.models.signals import post_save, post_delete
41
from django.dispatch import receiver
chirac's avatar
chirac committed
42
from django.forms import ValidationError
43
from django.utils import timezone
erdnaxe's avatar
erdnaxe committed
44
from django.utils.functional import cached_property
45
from django.utils.translation import ugettext_lazy as _
46
from macaddress.fields import MACAddressField, default_dialect
erdnaxe's avatar
erdnaxe committed
47
from netaddr import mac_bare, EUI, IPSet, IPRange, IPNetwork, IPAddress
Dalahro's avatar
Dalahro committed
48

erdnaxe's avatar
erdnaxe committed
49
50
import preferences.models
import users.models
51
from re2o.field_permissions import FieldPermissionModelMixin
Maël Kervella's avatar
Maël Kervella committed
52
from re2o.mixins import AclMixin, RevMixin
53

54

55
class Machine(RevMixin, FieldPermissionModelMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
56
57
    """ Class définissant une machine, object parent user, objets fils
    interfaces"""
detraz's avatar
detraz committed
58
    user = models.ForeignKey('users.User', on_delete=models.CASCADE)
Gabriel Detraz's avatar
Gabriel Detraz committed
59
60
    name = models.CharField(
        max_length=255,
61
        help_text=_("Optional"),
Gabriel Detraz's avatar
Gabriel Detraz committed
62
63
64
        blank=True,
        null=True
    )
65
    active = models.BooleanField(default=True)
Dalahro's avatar
Dalahro committed
66

67
68
    class Meta:
        permissions = (
69
            ("view_machine", _("Can view a machine object")),
Maël Kervella's avatar
Maël Kervella committed
70
            ("change_machine_user",
71
             _("Can change the user of a machine")),
72
        )
73
74
        verbose_name = _("machine")
        verbose_name_plural = _("machines")
75

Maël Kervella's avatar
Maël Kervella committed
76
77
    @classmethod
    def get_instance(cls, machineid, *_args, **_kwargs):
78
79
80
81
        """Get the Machine instance with machineid.
        :param userid: The id
        :return: The user
        """
Maël Kervella's avatar
Maël Kervella committed
82
        return cls.objects.get(pk=machineid)
83

84
85
86
    def linked_objects(self):
        """Return linked objects : machine and domain.
        Usefull in history display"""
Maël Kervella's avatar
Maël Kervella committed
87
88
89
90
91
92
        return chain(
            self.interface_set.all(),
            Domain.objects.filter(
                interface_parent__in=self.interface_set.all()
            )
        )
93

94
    @staticmethod
Maël Kervella's avatar
Maël Kervella committed
95
    def can_change_user(user_request, *_args, **_kwargs):
96
97
98
99
100
101
102
103
104
105
        """Checks if an user is allowed to change the user who owns a
        Machine.

        Args:
            user_request: The user requesting to change owner.

        Returns:
            A tuple with a boolean stating if edition is allowed and an
            explanation message.
        """
Maël Kervella's avatar
Maël Kervella committed
106
        return (user_request.has_perm('machines.change_machine_user'),
107
                _("You don't have the right to change the machine's user."))
108

Maël Kervella's avatar
Maël Kervella committed
109
110
    @staticmethod
    def can_view_all(user_request, *_args, **_kwargs):
111
112
113
114
115
        """Vérifie qu'on peut bien afficher l'ensemble des machines,
        droit particulier correspondant
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
        if not user_request.has_perm('machines.view_machine'):
116
            return False, _("You don't have the right to view all the"
erdnaxe's avatar
erdnaxe committed
117
                            " machines.")
118
119
        return True, None

Maël Kervella's avatar
Maël Kervella committed
120
121
    @staticmethod
    def can_create(user_request, userid, *_args, **_kwargs):
122
123
124
125
126
        """Vérifie qu'un user qui fait la requète peut bien créer la machine
        et n'a pas atteint son quota, et crée bien une machine à lui
        :param user_request: Utilisateur qui fait la requête
        :param userid: id de l'user dont on va créer une machine
        :return: soit True, soit False avec la raison de l'échec"""
Maël Kervella's avatar
Maël Kervella committed
127
        try:
128
            user = users.models.User.objects.get(pk=userid)
Maël Kervella's avatar
Maël Kervella committed
129
        except users.models.User.DoesNotExist:
130
            return False, _("Nonexistent user.")
Maël Kervella's avatar
Maël Kervella committed
131
        max_lambdauser_interfaces = (preferences.models.OptionalMachine
erdnaxe's avatar
erdnaxe committed
132
133
134
            .get_cached_value(
            'max_lambdauser_interfaces'
        ))
135
        if not user_request.has_perm('machines.add_machine'):
Maël Kervella's avatar
Maël Kervella committed
136
137
            if not (preferences.models.OptionalMachine
                    .get_cached_value('create_machine')):
138
                return False, (_("You don't have the right to add a machine."))
Maël Kervella's avatar
Maël Kervella committed
139
            if user != user_request:
140
141
                return False, (_("You don't have the right to add a machine"
                                 " to another user."))
Maël Kervella's avatar
Maël Kervella committed
142
            if user.user_interfaces().count() >= max_lambdauser_interfaces:
143
144
145
                return False, (_("You reached the maximum number of interfaces"
                                 " that you are allowed to create yourself"
                                 " (%s)." % max_lambdauser_interfaces))
Maël Kervella's avatar
Maël Kervella committed
146
147
        return True, None

148
    def can_edit(self, user_request, *args, **kwargs):
149
150
151
152
153
        """Vérifie qu'on peut bien éditer cette instance particulière (soit
        machine de soi, soit droit particulier
        :param self: instance machine à éditer
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison le cas échéant"""
154
        if self.user != user_request:
Maël Kervella's avatar
Maël Kervella committed
155
156
157
158
159
160
            if (not user_request.has_perm('machines.change_interface') or
                    not self.user.can_edit(
                        self.user,
                        user_request,
                        *args,
                        **kwargs
161
162
163
                    )[0]):
                return False, (_("You don't have the right to edit a machine"
                                 " of another user."))
164
165
        return True, None

166
    def can_delete(self, user_request, *args, **kwargs):
167
168
169
170
171
        """Vérifie qu'on peut bien supprimer cette instance particulière (soit
        machine de soi, soit droit particulier
        :param self: instance machine à supprimer
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
172
        if self.user != user_request:
Maël Kervella's avatar
Maël Kervella committed
173
174
175
176
177
178
            if (not user_request.has_perm('machines.change_interface') or
                    not self.user.can_edit(
                        self.user,
                        user_request,
                        *args,
                        **kwargs
179
180
                    )[0]):
                return False, _("You don't have the right to delete a machine"
erdnaxe's avatar
erdnaxe committed
181
                                " of another user.")
182
183
        return True, None

Maël Kervella's avatar
Maël Kervella committed
184
    def can_view(self, user_request, *_args, **_kwargs):
185
186
187
188
189
        """Vérifie qu'on peut bien voir cette instance particulière (soit
        machine de soi, soit droit particulier
        :param self: instance machine à éditer
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
Maël Kervella's avatar
Maël Kervella committed
190
191
        if (not user_request.has_perm('machines.view_machine') and
                self.user != user_request):
192
            return False, _("You don't have the right to view other machines"
erdnaxe's avatar
erdnaxe committed
193
                            " than yours.")
LEVY-FALK Hugo's avatar
LEVY-FALK Hugo committed
194
        return True, None
Maël Kervella's avatar
Maël Kervella committed
195

196
197
198
199
    @cached_property
    def short_name(self):
        """Par defaut, renvoie le nom de la première interface
        de cette machine"""
200
201
202
203
204
        interfaces_set = self.interface_set.first()
        if interfaces_set:
            return str(interfaces_set.domain.name)
        else:
            return "None"
205

Gabriel Detraz's avatar
Gabriel Detraz committed
206
207
208
209
210
211
    @cached_property
    def complete_name(self):
        """Par defaut, renvoie le nom de la première interface
        de cette machine"""
        return str(self.interface_set.first())

212
213
214
215
216
217
    @cached_property
    def all_short_names(self):
        """Renvoie de manière unique, le nom des interfaces de cette
        machine"""
        return Domain.objects.filter(
            interface_parent__machine=self
erdnaxe's avatar
erdnaxe committed
218
        ).values_list('name', flat=True).distinct()
219

220
221
222
223
224
    @cached_property
    def get_name(self):
        """Return a name : user provided name or first interface name"""
        return self.name or self.short_name

225
226
227
228
229
    @cached_property
    def all_complete_names(self):
        """Renvoie tous les tls complets de la machine"""
        return [str(domain) for domain in Domain.objects.filter(
            Q(cname__interface_parent__machine=self) | Q(interface_parent__machine=self)
erdnaxe's avatar
erdnaxe committed
230
        )]
231

232
233
234
    def __init__(self, *args, **kwargs):
        super(Machine, self).__init__(*args, **kwargs)
        self.field_permissions = {
Maël Kervella's avatar
Maël Kervella committed
235
            'user': self.can_change_user,
236
237
        }

Dalahro's avatar
Dalahro committed
238
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
239
240
        return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name)

241

242
class MachineType(RevMixin, AclMixin, models.Model):
243
    """ Type de machine, relié à un type d'ip, affecté aux interfaces"""
chirac's avatar
chirac committed
244
    type = models.CharField(max_length=255)
Gabriel Detraz's avatar
Gabriel Detraz committed
245
246
247
248
249
250
    ip_type = models.ForeignKey(
        'IpType',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
chirac's avatar
chirac committed
251

252
253
    class Meta:
        permissions = (
254
255
            ("view_machinetype", _("Can view a machine type object")),
            ("use_all_machinetype", _("Can use all machine types")),
256
        )
257
258
        verbose_name = _("machine type")
        verbose_name_plural = _("machine types")
259

260
    def all_interfaces(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
261
262
        """ Renvoie toutes les interfaces (cartes réseaux) de type
        machinetype"""
263
264
        return Interface.objects.filter(type=self)

Maël Kervella's avatar
Maël Kervella committed
265
266
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
267
268
269
270
271
272
273
274
        """Check if an user can use every MachineType.

        Args:
            user_request: The user requesting edition.
        Returns:
            A tuple with a boolean stating if user can acces and an explanation
            message is acces is not allowed.
        """
275
        if not user_request.has_perm('machines.use_all_machinetype'):
276
277
            return False, (_("You don't have the right to use all machine"
                             " types."))
278
279
        return True, None

chirac's avatar
chirac committed
280
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
281
282
        return self.type

chirac's avatar
chirac committed
283

284
class IpType(RevMixin, AclMixin, models.Model):
285
    """ Type d'ip, définissant un range d'ip, affecté aux machine types"""
Dalahro's avatar
Dalahro committed
286
    type = models.CharField(max_length=255)
287
    extension = models.ForeignKey('Extension', on_delete=models.PROTECT)
288
    need_infra = models.BooleanField(default=False)
289
290
    domaine_ip_start = models.GenericIPAddressField(protocol='IPv4')
    domaine_ip_stop = models.GenericIPAddressField(protocol='IPv4')
291
292
293
294
    domaine_ip_network = models.GenericIPAddressField(
        protocol='IPv4',
        null=True,
        blank=True,
295
        help_text=_("Network containing the domain's IPv4 range (optional)")
296
297
298
299
300
301
302
    )
    domaine_ip_netmask = models.IntegerField(
        default=24,
        validators=[
            MaxValueValidator(31),
            MinValueValidator(8)
        ],
303
        help_text=_("Netmask for the domain's IPv4 range")
304
    )
305
    reverse_v4 = models.BooleanField(
erdnaxe's avatar
erdnaxe committed
306
307
        default=False,
        help_text=_("Enable reverse DNS for IPv4"),
308
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
309
310
311
312
313
    prefix_v6 = models.GenericIPAddressField(
        protocol='IPv6',
        null=True,
        blank=True
    )
314
315
316
317
318
319
    prefix_v6_length = models.IntegerField(
        default=64,
        validators=[
            MaxValueValidator(128),
            MinValueValidator(0)
        ]
erdnaxe's avatar
erdnaxe committed
320
    )
321
    reverse_v6 = models.BooleanField(
erdnaxe's avatar
erdnaxe committed
322
323
        default=False,
        help_text=_("Enable reverse DNS for IPv6"),
324
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
325
326
327
328
329
330
331
332
333
334
335
    vlan = models.ForeignKey(
        'Vlan',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
    ouverture_ports = models.ForeignKey(
        'OuverturePortList',
        blank=True,
        null=True
    )
Dalahro's avatar
Dalahro committed
336

337
338
    class Meta:
        permissions = (
339
340
            ("view_iptype", _("Can view an IP type object")),
            ("use_all_iptype", _("Can use all IP types")),
341
        )
342
        verbose_name = _("IP type")
erdnaxe's avatar
erdnaxe committed
343
        verbose_name_plural = "IP types"
344

345
    @cached_property
346
    def ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
347
348
        """ Renvoie un objet IPRange à partir de l'objet IpType"""
        return IPRange(self.domaine_ip_start, end=self.domaine_ip_stop)
349
350
351

    @cached_property
    def ip_set(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
352
        """ Renvoie une IPSet à partir de l'iptype"""
353
        return IPSet(self.ip_range)
354
355
356

    @cached_property
    def ip_set_as_str(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
357
        """ Renvoie une liste des ip en string"""
358
359
        return [str(x) for x in self.ip_set]

360
361
362
363
364
    @cached_property
    def ip_set_cidrs_as_str(self):
        """Renvoie la liste des cidrs du range en str"""
        return [str(ip_range) for ip_range in self.ip_set.iter_cidrs()]

365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
    @cached_property
    def ip_set_full_info(self):
        """Iter sur les range cidr, et renvoie network, broacast , etc"""
        return [
            {
                'network': str(ip_set.network),
                'netmask': str(ip_set.netmask),
                'netmask_cidr': str(ip_set.prefixlen),
                'broadcast': str(ip_set.broadcast),
                'vlan': str(self.vlan),
                'vlan_id': self.vlan.vlan_id
            } for ip_set in self.ip_set.iter_cidrs()
        ]

    @cached_property
    def ip6_set_full_info(self):
        if self.prefix_v6:
            return {
erdnaxe's avatar
erdnaxe committed
383
384
385
                'network': str(self.prefix_v6),
                'netmask': 'ffff:ffff:ffff:ffff::',
                'netmask_cidr': str(self.prefix_v6_length),
386
                'vlan': str(self.vlan),
387
                'vlan_id': self.vlan.vlan_id
388
389
390
391
            }
        else:
            return None

392
393
394
395
396
397
398
399
400
401
402
403
    @cached_property
    def ip_network(self):
        """Renvoie le network parent du range start-stop, si spécifié
        Différent de ip_set_cidrs ou iP_set, car lui est supérieur ou égal"""
        if self.domaine_ip_network:
            return IPNetwork(str(self.domaine_ip_network) + '/' + str(self.domaine_ip_netmask))
        return None

    @cached_property
    def ip_net_full_info(self):
        """Renvoie les infos du network contenant du range"""
        return {
erdnaxe's avatar
erdnaxe committed
404
405
406
407
            'network': str(self.ip_network.network),
            'netmask': str(self.ip_network.netmask),
            'broadcast': str(self.ip_network.broadcast),
            'netmask_cidr': str(self.ip_network.prefixlen),
408
409
        }

Gabriel Detraz's avatar
Gabriel Detraz committed
410
411
412
413
414
    @cached_property
    def complete_prefixv6(self):
        """Return the complete prefix v6 as cidr"""
        return str(self.prefix_v6) + "/" + str(self.prefix_v6_length)

415
    def ip_objects(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
416
        """ Renvoie tous les objets ipv4 relié à ce type"""
417
418
419
        return IpList.objects.filter(ip_type=self)

    def free_ip(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
420
        """ Renvoie toutes les ip libres associées au type donné (self)"""
Gabriel Detraz's avatar
Gabriel Detraz committed
421
422
423
        return IpList.objects.filter(
            interface__isnull=True
        ).filter(ip_type=self)
424
425

    def gen_ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
426
427
428
        """ Cree les IpList associées au type self. Parcours pédestrement et
        crée les ip une par une. Si elles existent déjà, met à jour le type
        associé à l'ip"""
429
        # Creation du range d'ip dans les objets iplist
chirac's avatar
chirac committed
430
        ip_obj = [IpList(ip_type=self, ipv4=str(ip)) for ip in self.ip_range]
Gabriel Detraz's avatar
Gabriel Detraz committed
431
        listes_ip = IpList.objects.filter(
chirac's avatar
chirac committed
432
            ipv4__in=[str(ip) for ip in self.ip_range]
Gabriel Detraz's avatar
Gabriel Detraz committed
433
        )
434
435
436
437
438
439
        # Si il n'y a pas d'ip, on les crée
        if not listes_ip:
            IpList.objects.bulk_create(ip_obj)
        # Sinon on update l'ip_type
        else:
            listes_ip.update(ip_type=self)
440
        return
441
442

    def del_ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
443
444
        """ Methode dépréciée, IpList est en mode cascade et supprimé
        automatiquement"""
445
        if Interface.objects.filter(ipv4__in=self.ip_objects()):
446
447
448
            raise ValidationError(_("One or several IP addresses from the"
                                    " range are affected, impossible to delete"
                                    " the range."))
449
450
451
        for ip in self.ip_objects():
            ip.delete()

452
453
454
455
456
    def check_replace_prefixv6(self):
        """Remplace les prefixv6 des interfaces liées à ce type d'ip"""
        if not self.prefix_v6:
            return
        else:
Maël Kervella's avatar
Maël Kervella committed
457
            for ipv6 in Ipv6List.objects.filter(
erdnaxe's avatar
erdnaxe committed
458
459
460
                    interface__in=Interface.objects.filter(
                        type__in=MachineType.objects.filter(ip_type=self)
                    )
461
            ):
462
463
                ipv6.check_and_replace_prefix(prefix=self.prefix_v6)

Charlie Jacomme's avatar
Charlie Jacomme committed
464
465
    def get_associated_ptr_records(self):
        from re2o.utils import all_active_assigned_interfaces
466
467
468
469
470
471
        if self.reverse_v4:
            return (all_active_assigned_interfaces()
                    .filter(type__ip_type=self)
                    .filter(ipv4__isnull=False))
        else:
            return None
Charlie Jacomme's avatar
Charlie Jacomme committed
472
473
474

    def get_associated_ptr_v6_records(self):
        from re2o.utils import all_active_interfaces
475
476
477
478
479
        if self.reverse_v6:
            return (all_active_interfaces(full=True)
                    .filter(type__ip_type=self))
        else:
            return None
Charlie Jacomme's avatar
Charlie Jacomme committed
480

481
    def clean(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
482
483
484
485
486
        """ Nettoyage. Vérifie :
        - Que ip_stop est après ip_start
        - Qu'on ne crée pas plus gros qu'un /16
        - Que le range crée ne recoupe pas un range existant
        - Formate l'ipv6 donnée en /64"""
487
        if IPAddress(self.domaine_ip_start) > IPAddress(self.domaine_ip_stop):
488
            raise ValidationError(_("Range end must be after range start..."))
489
490
        # On ne crée pas plus grand qu'un /16
        if self.ip_range.size > 65536:
491
492
            raise ValidationError(_("The range is too large, you can't create"
                                    " a larger one than a /16."))
493
        # On check que les / ne se recoupent pas
494
        for element in IpType.objects.all().exclude(pk=self.pk):
495
            if not self.ip_set.isdisjoint(element.ip_set):
496
497
                raise ValidationError(_("The specified range is not disjoint"
                                        " from existing ranges."))
498
499
500
        # On formate le prefix v6
        if self.prefix_v6:
            self.prefix_v6 = str(IPNetwork(self.prefix_v6 + '/64').network)
501
502
503
        # On vérifie qu'un domaine network/netmask contiens bien le domaine ip start-stop
        if self.domaine_ip_network:
            if not self.domaine_ip_start in self.ip_network or not self.domaine_ip_stop in self.ip_network:
504
505
506
                raise ValidationError(_("If you specify a domain network or"
                                        " netmask, it must contain the"
                                        " domain's IP range."))
507
508
509
510
511
512
        return

    def save(self, *args, **kwargs):
        self.clean()
        super(IpType, self).save(*args, **kwargs)

Maël Kervella's avatar
Maël Kervella committed
513
514
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
Maël Kervella's avatar
Maël Kervella committed
515
516
        """Superdroit qui permet d'utiliser toutes les extensions sans
        restrictions
517
518
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
519
        return user_request.has_perm('machines.use_all_iptype'), None
520

Dalahro's avatar
Dalahro committed
521
522
    def __str__(self):
        return self.type
chirac's avatar
chirac committed
523

Gabriel Detraz's avatar
Gabriel Detraz committed
524

525
class Vlan(RevMixin, AclMixin, models.Model):
526
527
528
    """ Un vlan : vlan_id et nom
    On limite le vlan id entre 0 et 4096, comme défini par la norme"""
    vlan_id = models.PositiveIntegerField(validators=[MaxValueValidator(4095)])
529
530
    name = models.CharField(max_length=256)
    comment = models.CharField(max_length=256, blank=True)
531
532
533
534
    #Réglages supplémentaires
    arp_protect = models.BooleanField(default=False)
    dhcp_snooping = models.BooleanField(default=False)
    dhcpv6_snooping = models.BooleanField(default=False)
Gabriel Detraz's avatar
Gabriel Detraz committed
535
536
537
538
539
540
541
542
543
    igmp = models.BooleanField(
        default=False,
        help_text="Gestion multicast v4"
    )
    mld = models.BooleanField(
        default=False,
        help_text="Gestion multicast v6"
    )

544
545
    class Meta:
        permissions = (
546
            ("view_vlan", _("Can view a VLAN object")),
547
        )
548
549
        verbose_name = _("VLAN")
        verbose_name_plural = _("VLANs")
550

551
552
553
    def __str__(self):
        return self.name

Gabriel Detraz's avatar
Gabriel Detraz committed
554

555
class Nas(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
556
    """ Les nas. Associé à un machine_type.
Gabriel Detraz's avatar
Gabriel Detraz committed
557
558
    Permet aussi de régler le port_access_mode (802.1X ou mac-address) pour
    le radius. Champ autocapture de la mac à true ou false"""
559
560
561
562
563
564
    default_mode = '802.1X'
    AUTH = (
        ('802.1X', '802.1X'),
        ('Mac-address', 'Mac-address'),
    )

565
    name = models.CharField(max_length=255, unique=True)
Gabriel Detraz's avatar
Gabriel Detraz committed
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
    nas_type = models.ForeignKey(
        'MachineType',
        on_delete=models.PROTECT,
        related_name='nas_type'
    )
    machine_type = models.ForeignKey(
        'MachineType',
        on_delete=models.PROTECT,
        related_name='machinetype_on_nas'
    )
    port_access_mode = models.CharField(
        choices=AUTH,
        default=default_mode,
        max_length=32
    )
581
    autocapture_mac = models.BooleanField(default=False)
582

583
584
    class Meta:
        permissions = (
585
            ("view_nas", _("Can view a NAS device object")),
586
        )
587
588
        verbose_name = _("NAS device")
        verbose_name_plural = _("NAS devices")
589

590
591
592
    def __str__(self):
        return self.name

Gabriel Detraz's avatar
Gabriel Detraz committed
593

594
class SOA(RevMixin, AclMixin, models.Model):
595
596
597
598
599
    """
    Un enregistrement SOA associé à une extension
    Les valeurs par défault viennent des recommandations RIPE :
    https://www.ripe.net/publications/docs/ripe-203
    """
600
    name = models.CharField(max_length=255)
601
    mail = models.EmailField(
602
        help_text=_("Contact email address for the zone")
603
604
    )
    refresh = models.PositiveIntegerField(
Maël Kervella's avatar
Maël Kervella committed
605
        default=86400,  # 24 hours
606
607
        help_text=_("Seconds before the secondary DNS have to ask the primary"
                    " DNS serial to detect a modification")
608
609
    )
    retry = models.PositiveIntegerField(
Maël Kervella's avatar
Maël Kervella committed
610
        default=7200,  # 2 hours
611
612
        help_text=_("Seconds before the secondary DNS ask the serial again in"
                    " case of a primary DNS timeout")
613
614
    )
    expire = models.PositiveIntegerField(
Maël Kervella's avatar
Maël Kervella committed
615
        default=3600000,  # 1000 hours
616
617
        help_text=_("Seconds before the secondary DNS stop answering requests"
                    " in case of primary DNS timeout")
618
619
620
    )
    ttl = models.PositiveIntegerField(
        default=172800,  # 2 days
621
        help_text=_("Time to Live")
622
623
    )

624
625
    class Meta:
        permissions = (
626
            ("view_soa", _("Can view an SOA record object")),
627
        )
628
629
        verbose_name = _("SOA record")
        verbose_name_plural = _("SOA records")
630

631
632
633
634
635
636
637
638
639
640
641
642
643
    def __str__(self):
        return str(self.name)

    @cached_property
    def dns_soa_param(self):
        """
        Renvoie la partie de l'enregistrement SOA correspondant aux champs :
            <refresh>   ; refresh
            <retry>     ; retry
            <expire>    ; expire
            <ttl>       ; TTL
        """
        return (
644
645
646
647
            '    {refresh}; refresh\n'
            '    {retry}; retry\n'
            '    {expire}; expire\n'
            '    {ttl}; TTL'
648
        ).format(
649
650
651
652
            refresh=str(self.refresh).ljust(12),
            retry=str(self.retry).ljust(12),
            expire=str(self.expire).ljust(12),
            ttl=str(self.ttl).ljust(12)
653
654
655
656
657
658
        )

    @cached_property
    def dns_soa_mail(self):
        """ Renvoie le mail dans l'enregistrement SOA """
        mail_fields = str(self.mail).split('@')
659
        return mail_fields[0].replace('.', '\\.') + '.' + mail_fields[1] + '.'
660
661
662
663
664
665
666

    @classmethod
    def new_default_soa(cls):
        """ Fonction pour créer un SOA par défaut, utile pour les nouvelles
        extensions .
        /!\ Ne jamais supprimer ou renommer cette fonction car elle est
        utilisée dans les migrations de la BDD. """
Maël Kervella's avatar
Maël Kervella committed
667
        return cls.objects.get_or_create(
668
            name=_("SOA to edit"),
Maël Kervella's avatar
Maël Kervella committed
669
670
            mail="postmaser@example.com"
        )[0].pk
671
672


673
class Extension(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
674
675
    """ Extension dns type example.org. Précise si tout le monde peut
    l'utiliser, associé à un origin (ip d'origine)"""
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
676
677
678
    name = models.CharField(
        max_length=255,
        unique=True,
679
        help_text=_("Zone name, must begin with a dot (.example.org)")
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
680
    )
681
    need_infra = models.BooleanField(default=False)
Gabriel Detraz's avatar
Gabriel Detraz committed
682
    origin = models.ForeignKey(
Gabriel Detraz's avatar
Gabriel Detraz committed
683
684
685
        'IpList',
        on_delete=models.PROTECT,
        blank=True,
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
686
        null=True,
687
        help_text=_("A record associated with the zone")
Gabriel Detraz's avatar
Gabriel Detraz committed
688
    )
689
690
691
    origin_v6 = models.GenericIPAddressField(
        protocol='IPv6',
        null=True,
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
692
        blank=True,
693
        help_text=_("AAAA record associated with the zone")
694
    )
695
696
    soa = models.ForeignKey(
        'SOA',
697
        on_delete=models.CASCADE
698
    )
699
700
701
702
    dnssec = models.BooleanField(
        default=False,
        help_text=_("Should the zone be signed with DNSSEC")
    )
703

704
705
    class Meta:
        permissions = (
706
707
            ("view_extension", _("Can view an extension object")),
            ("use_all_extension", _("Can use all extensions")),
708
        )
709
710
        verbose_name = _("DNS extension")
        verbose_name_plural = _("DNS extensions")
711

712
713
    @cached_property
    def dns_entry(self):
714
715
716
        """ Une entrée DNS A et AAAA sur origin (zone self)"""
        entry = ""
        if self.origin:
717
            entry += "@               IN  A       " + str(self.origin)
718
719
720
        if self.origin_v6:
            if entry:
                entry += "\n"
721
            entry += "@               IN  AAAA    " + str(self.origin_v6)
722
        return entry
723

724
    def get_associated_sshfp_records(self):
725
726
727
        from re2o.utils import all_active_assigned_interfaces
        return (all_active_assigned_interfaces()
                .filter(type__ip_type__extension=self)
728
                .filter(machine__id__in=SshFp.objects.values('machine')))
729

730
    def get_associated_a_records(self):
731
732
        from re2o.utils import all_active_assigned_interfaces
        return (all_active_assigned_interfaces()
Maël Kervella's avatar
Maël Kervella committed
733
                .filter(type__ip_type__extension=self)
734
                .filter(ipv4__isnull=False))
735
736

    def get_associated_aaaa_records(self):
737
738
739
        from re2o.utils import all_active_interfaces
        return (all_active_interfaces(full=True)
                .filter(type__ip_type__extension=self))
740
741

    def get_associated_cname_records(self):
742
        from re2o.utils import all_active_assigned_interfaces
Maël Kervella's avatar
Maël Kervella committed
743
744
        return (Domain.objects
                .filter(extension=self)
Charlie Jacomme's avatar
Charlie Jacomme committed
745
                .filter(cname__interface_parent__in=all_active_assigned_interfaces())
Maël Kervella's avatar
Maël Kervella committed
746
                .prefetch_related('cname'))
747

Gabriel Detraz's avatar
Gabriel Detraz committed
748
749
750
    def get_associated_dname_records(self):
        return (DName.objects.filter(alias=self))

Maël Kervella's avatar
Maël Kervella committed
751
752
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
Maël Kervella's avatar
Maël Kervella committed
753
754
        """Superdroit qui permet d'utiliser toutes les extensions sans
        restrictions
Gabriel Detraz's avatar
Gabriel Detraz committed
755
756
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
757
        return user_request.has_perm('machines.use_all_extension'), None
Gabriel Detraz's avatar
Gabriel Detraz committed
758

759
760
    def __str__(self):
        return self.name
chirac's avatar
chirac committed
761

Gabriel Detraz's avatar
Gabriel Detraz committed
762
    def clean(self, *args, **kwargs):
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
763
        if self.name and self.name[0] != '.':
764
            raise ValidationError(_("An extension must begin with a dot."))
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
765
766
        super(Extension, self).clean(*args, **kwargs)

Gabriel Detraz's avatar
Gabriel Detraz committed
767

768
class Mx(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
769
770
    """ Entrées des MX. Enregistre la zone (extension) associée et la
    priorité
Gabriel Detraz's avatar
Gabriel Detraz committed
771
    Todo : pouvoir associer un MX à une interface """
772
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
773
774
    priority = models.PositiveIntegerField()
    name = models.ForeignKey('Domain', on_delete=models.PROTECT)
775

776
777
    class Meta:
        permissions = (
778
            ("view_mx", _("Can view an MX record object")),
779
        )
780
781
        verbose_name = _("MX record")
        verbose_name_plural = _("MX records")
782

783
784
    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
785
786
        """Renvoie l'entrée DNS complète pour un MX à mettre dans les
        fichiers de zones"""
Maël Kervella's avatar
Maël Kervella committed
787
788
        return "@               IN  MX  {prior} {name}".format(
            prior=str(self.priority).ljust(3),
Maël Kervella's avatar
Maël Kervella committed
789
            name=str(self.name)
Maël Kervella's avatar
Maël Kervella committed
790
        )
791

792
793
794
    def __str__(self):
        return str(self.zone) + ' ' + str(self.priority) + ' ' + str(self.name)

Gabriel Detraz's avatar
Gabriel Detraz committed
795

796
class Ns(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
797
    """Liste des enregistrements name servers par zone considéérée"""
798
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
799
    ns = models.ForeignKey('Domain', on_delete=models.PROTECT)
800

801
802
    class Meta:
        permissions = (
803
            ("view_ns", _("Can view an NS record object")),
804
        )
805
806
        verbose_name = _("NS record")
        verbose_name_plural = _("NS records")
807

808
809
    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
810
        """Renvoie un enregistrement NS complet pour les filezones"""
811
        return "@               IN  NS      " + str(self.ns)
812

813
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
814
        return str(self.zone) + ' ' + str(self.ns)
815

Gabriel Detraz's avatar
Gabriel Detraz committed
816

817
class Txt(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
818
    """ Un enregistrement TXT associé à une extension"""
Gabriel Detraz's avatar
Gabriel Detraz committed
819
820
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
    field1 = models.CharField(max_length=255)
821
    field2 = models.TextField(max_length=2047)
Gabriel Detraz's avatar
Gabriel Detraz committed
822

823
824
    class Meta:
        permissions = (
825
            ("view_txt", _("Can view a TXT record object")),
826
        )
827
828
        verbose_name = _("TXT record")
        verbose_name_plural = _("TXT records")
829

Gabriel Detraz's avatar
Gabriel Detraz committed
830
    def __str__(self):
erdnaxe's avatar
erdnaxe committed
831
832
        return str(self.zone) + " : " + str(self.field1) + " " + \
               str(self.field2)
Gabriel Detraz's avatar
Gabriel Detraz committed
833
834
835

    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
836
        """Renvoie l'enregistrement TXT complet pour le fichier de zone"""
837
        return str(self.field1).ljust(15) + " IN  TXT     " + str(self.field2)
Gabriel Detraz's avatar
Gabriel Detraz committed
838

Gabriel Detraz's avatar
Gabriel Detraz committed
839

Charlie Jacomme's avatar
Charlie Jacomme committed
840
class DName(RevMixin, AclMixin, models.Model):
Maël Kervella's avatar
Maël Kervella committed
841
    """A DNAME entry for the DNS."""
Charlie Jacomme's avatar
Charlie Jacomme committed
842
843
844
845
846
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
    alias = models.CharField(max_length=255)

    class Meta:
        permissions = (
847
            ("view_dname", _("Can view a DNAME record object")),
Charlie Jacomme's avatar
Charlie Jacomme committed
848
        )
849
850
        verbose_name = _("DNAME record")
        verbose_name_plural = _("DNAME records")
Charlie Jacomme's avatar
Charlie Jacomme committed
851
852
853
854
855
856

    def __str__(self):
        return str(self.zone) + " : " + str(self.alias)

    @cached_property
    def dns_entry(self):
Maël Kervella's avatar
Maël Kervella committed
857
        """Returns the DNAME record for the DNS zone file."""
chirac's avatar
chirac committed
858
        return str(self.alias).ljust(15) + " IN  DNAME   " + str(self.zone)
Charlie Jacomme's avatar
Charlie Jacomme committed
859
860


861
class Srv(RevMixin, AclMixin, models.Model):
Maël Kervella's avatar
Maël Kervella committed
862
    """ A SRV record """
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
863
864
865
    TCP = 'TCP'
    UDP = 'UDP'

Maël Kervella's avatar
Maël Kervella committed
866
    service = models.CharField(max_length=31)
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
867
868
869
870
871
    protocole = models.CharField(
        max_length=3,
        choices=(
            (TCP, 'TCP'),
            (UDP, 'UDP'),
872
        ),
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
873
874
875
876
877
        default=TCP,
    )
    extension = models.ForeignKey('Extension', on_delete=models.PROTECT)
    ttl = models.PositiveIntegerField(
        default=172800,  # 2 days
878
        help_text=_("Time to Live")
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
879
880
    )
    priority = models.PositiveIntegerField(
881
        default=0,
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
882
        validators=[MaxValueValidator(65535)],
883
884
885
        help_text=_("Priority of the target server (positive integer value,"
                    " the lower it is, the more the server will be used if"
                    " available)")
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
886
887
    )
    weight = models.PositiveIntegerField(
888
        default=0,
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
889
        validators=[MaxValueValidator(65535)],
890
        help_text=_("Relative weight for records with the same priority"
erdnaxe's avatar
erdnaxe committed
891
                    " (integer value between 0 and 65535)")
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
892
893
894
    )
    port = models.PositiveIntegerField(
        validators=[MaxValueValidator(65535)],
895
        help_text=_("TCP/UDP port")
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
896
897
898
899
    )
    target = models.ForeignKey(
        'Domain',
        on_delete=models.PROTECT,
900
        help_text=_("Target server")
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
901
902
    )

903
904
    class Meta:
        permissions = (
905
            ("view_srv", _("Can view an SRV record object")),
906
        )
907
908
        verbose_name = _("SRV record")
        verbose_name_plural = _("SRV records")
909

Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
910
    def __str__(self):
erdnaxe's avatar
erdnaxe committed
911
912
913
        return str(self.service) + ' ' + str(self.protocole) + ' ' + \
               str(self.extension) + ' ' + str(self.priority) + \
               ' ' + str(self.weight) + str(self.port) + str(self.target)
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
914
915
916
917

    @cached_property
    def dns_entry(self):
        """Renvoie l'enregistrement SRV complet pour le fichier de zone"""
erdnaxe's avatar
erdnaxe committed
918
919
920
921
        return str(self.service) + '._' + str(self.protocole).lower() + \
               str(self.extension) + '. ' + str(self.ttl) + ' IN SRV ' + \
               str(self.priority) + ' ' + str(self.weight) + ' ' + \
               str(self.port) + ' ' + str(self.target) + '.'
Gabriel Detraz's avatar
Fix #52    
Gabriel Detraz committed
922
923


924
925