Ce serveur Gitlab sera éteint le 30 juin 2020, pensez à migrer vos projets vers les serveurs gitlab-research.centralesupelec.fr et gitlab-student.centralesupelec.fr !

models.py 72.1 KB
Newer Older
1
# -*- mode: python; coding: utf-8 -*-
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.
#
6
# Copyright © 2016-2018  Gabriel Détraz
7 8
# Copyright © 2017  Goulven Kermarec
# Copyright © 2017  Augustin Lemesle
9
# Copyright © 2018  Charlie Jacomme
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.
24 25 26
"""machines.models
The models definitions for the Machines app
"""
27

28 29
from __future__ import unicode_literals

Gabriel Detraz's avatar
Gabriel Detraz committed
30 31
from datetime import timedelta
import re
32
from ipaddress import IPv6Address
33
from itertools import chain
34
from netaddr import mac_bare, EUI, IPSet, IPRange, IPNetwork, IPAddress
35 36
import hashlib
import base64
Gabriel Detraz's avatar
Gabriel Detraz committed
37

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
42
from django.forms import ValidationError
43
from django.utils.functional import cached_property
44
from django.utils import timezone
45
from django.core.validators import MaxValueValidator, MinValueValidator
46
from django.utils.translation import ugettext_lazy as _
Gabriel Detraz's avatar
Gabriel Detraz committed
47

48
from macaddress.fields import MACAddressField
49

50
from re2o.field_permissions import FieldPermissionModelMixin
51
from re2o.mixins import AclMixin, RevMixin
52

Maël Kervella's avatar
Maël Kervella committed
53 54 55
import users.models
import preferences.models

56

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

69 70
    class Meta:
        permissions = (
71
            ("view_machine", _("Can view a machine object")),
72
            ("change_machine_user",
73
             _("Can change the user of a machine")),
74
        )
75 76
        verbose_name = _("machine")
        verbose_name_plural = _("machines")
77

78 79
    @classmethod
    def get_instance(cls, machineid, *_args, **_kwargs):
80 81 82 83
        """Get the Machine instance with machineid.
        :param userid: The id
        :return: The user
        """
84
        return cls.objects.get(pk=machineid)
85

86 87 88
    def linked_objects(self):
        """Return linked objects : machine and domain.
        Usefull in history display"""
89 90 91 92 93 94
        return chain(
            self.interface_set.all(),
            Domain.objects.filter(
                interface_parent__in=self.interface_set.all()
            )
        )
95

96
    @staticmethod
97
    def can_change_user(user_request, *_args, **_kwargs):
98 99 100 101 102 103 104 105 106 107
        """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.
        """
108
        return (user_request.has_perm('machines.change_machine_user'),
109
                _("You don't have the right to change the machine's user."))
110

111 112
    @staticmethod
    def can_view_all(user_request, *_args, **_kwargs):
113 114 115 116 117
        """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'):
118 119
            return False, _("You don't have the right to view all the"
                             " machines.")
120 121
        return True, None

122 123
    @staticmethod
    def can_create(user_request, userid, *_args, **_kwargs):
124 125 126 127 128
        """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
129
        try:
130
            user = users.models.User.objects.get(pk=userid)
Maël Kervella's avatar
Maël Kervella committed
131
        except users.models.User.DoesNotExist:
132
            return False, _("Nonexistent user.")
133 134 135 136
        max_lambdauser_interfaces = (preferences.models.OptionalMachine
                                     .get_cached_value(
                                         'max_lambdauser_interfaces'
                                     ))
137
        if not user_request.has_perm('machines.add_machine'):
138 139
            if not (preferences.models.OptionalMachine
                    .get_cached_value('create_machine')):
140
                return False, (_("You don't have the right to add a machine."))
Maël Kervella's avatar
Maël Kervella committed
141
            if user != user_request:
142 143
                return False, (_("You don't have the right to add a machine"
                                 " to another user."))
Maël Kervella's avatar
Maël Kervella committed
144
            if user.user_interfaces().count() >= max_lambdauser_interfaces:
145 146 147
                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
148 149
        return True, None

150
    def can_edit(self, user_request, *args, **kwargs):
151 152 153 154 155
        """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"""
156
        if self.user != user_request:
157 158 159 160 161 162
            if (not user_request.has_perm('machines.change_interface') or
                    not self.user.can_edit(
                        self.user,
                        user_request,
                        *args,
                        **kwargs
163 164 165
                    )[0]):
                return False, (_("You don't have the right to edit a machine"
                                 " of another user."))
166 167
        return True, None

168
    def can_delete(self, user_request, *args, **kwargs):
169 170 171 172 173
        """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"""
174
        if self.user != user_request:
175 176 177 178 179 180
            if (not user_request.has_perm('machines.change_interface') or
                    not self.user.can_edit(
                        self.user,
                        user_request,
                        *args,
                        **kwargs
181 182 183
                    )[0]):
                return False, _("You don't have the right to delete a machine"
                                 " of another user.")
184 185
        return True, None

186
    def can_view(self, user_request, *_args, **_kwargs):
187 188 189 190 191
        """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"""
192 193
        if (not user_request.has_perm('machines.view_machine') and
                self.user != user_request):
194 195
            return False, _("You don't have the right to view other machines"
                             " than yours.")
196
        return True, None
197

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    @cached_property
    def short_name(self):
        """Par defaut, renvoie le nom de la première interface
        de cette machine"""
        return str(self.interface_set.first().domain.name)

    @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
            ).values_list('name', flat=True).distinct()

    @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)
            )]

219 220 221
    def __init__(self, *args, **kwargs):
        super(Machine, self).__init__(*args, **kwargs)
        self.field_permissions = {
222
            'user': self.can_change_user,
223 224
        }

225
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
226 227
        return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name)

228

229
class MachineType(RevMixin, AclMixin, models.Model):
230
    """ Type de machine, relié à un type d'ip, affecté aux interfaces"""
231
    type = models.CharField(max_length=255)
Gabriel Detraz's avatar
Gabriel Detraz committed
232 233 234 235 236 237
    ip_type = models.ForeignKey(
        'IpType',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
238

239 240
    class Meta:
        permissions = (
241 242
            ("view_machinetype", _("Can view a machine type object")),
            ("use_all_machinetype", _("Can use all machine types")),
243
        )
244 245
        verbose_name = _("machine type")
        verbose_name_plural = _("machine types")
246

247
    def all_interfaces(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
248 249
        """ Renvoie toutes les interfaces (cartes réseaux) de type
        machinetype"""
250 251
        return Interface.objects.filter(type=self)

252 253
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
254 255 256 257 258 259 260 261
        """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.
        """
262
        if not user_request.has_perm('machines.use_all_machinetype'):
263 264
            return False, (_("You don't have the right to use all machine"
                             " types."))
265 266
        return True, None

267
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
268 269
        return self.type

270

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

324 325
    class Meta:
        permissions = (
326 327
            ("view_iptype", _("Can view an IP type object")),
            ("use_all_iptype", _("Can use all IP types")),
328
        )
329 330
        verbose_name = _("IP type")
        verbose_name_plural = ("IP types")
331

332
    @cached_property
333
    def ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
334 335
        """ Renvoie un objet IPRange à partir de l'objet IpType"""
        return IPRange(self.domaine_ip_start, end=self.domaine_ip_stop)
336 337 338

    @cached_property
    def ip_set(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
339
        """ Renvoie une IPSet à partir de l'iptype"""
340
        return IPSet(self.ip_range)
341 342 343

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

347 348 349 350 351
    @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()]

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    @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 {
                'network' : str(self.prefix_v6),
                'netmask' : 'ffff:ffff:ffff:ffff::',
                'netmask_cidr' : str(self.prefix_v6_length),
                'vlan': str(self.vlan),
                'vlan_id': self.vlan.vlan_id
            }
        else:
            return None

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    @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 {
            '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),
        }

397 398 399 400 401
    @cached_property
    def complete_prefixv6(self):
        """Return the complete prefix v6 as cidr"""
        return str(self.prefix_v6) + "/" + str(self.prefix_v6_length)

402
    def ip_objects(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
403
        """ Renvoie tous les objets ipv4 relié à ce type"""
404 405 406
        return IpList.objects.filter(ip_type=self)

    def free_ip(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
407
        """ Renvoie toutes les ip libres associées au type donné (self)"""
Gabriel Detraz's avatar
Gabriel Detraz committed
408 409 410
        return IpList.objects.filter(
            interface__isnull=True
        ).filter(ip_type=self)
411 412

    def gen_ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
413 414 415
        """ 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"""
416
        # Creation du range d'ip dans les objets iplist
417
        ip_obj = [IpList(ip_type=self, ipv4=str(ip)) for ip in self.ip_range]
Gabriel Detraz's avatar
Gabriel Detraz committed
418
        listes_ip = IpList.objects.filter(
419
            ipv4__in=[str(ip) for ip in self.ip_range]
Gabriel Detraz's avatar
Gabriel Detraz committed
420
        )
421 422 423 424 425 426
        # 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)
427
        return
428 429

    def del_ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
430 431
        """ Methode dépréciée, IpList est en mode cascade et supprimé
        automatiquement"""
432
        if Interface.objects.filter(ipv4__in=self.ip_objects()):
433 434 435
            raise ValidationError(_("One or several IP addresses from the"
                                    " range are affected, impossible to delete"
                                    " the range."))
436 437 438
        for ip in self.ip_objects():
            ip.delete()

439 440 441 442 443
    def check_replace_prefixv6(self):
        """Remplace les prefixv6 des interfaces liées à ce type d'ip"""
        if not self.prefix_v6:
            return
        else:
444
            for ipv6 in Ipv6List.objects.filter(
445 446 447 448
                interface__in=Interface.objects.filter(
                    type__in=MachineType.objects.filter(ip_type=self)
                )
            ):
449 450
                ipv6.check_and_replace_prefix(prefix=self.prefix_v6)

451 452
    def get_associated_ptr_records(self):
        from re2o.utils import all_active_assigned_interfaces
453 454 455 456 457 458
        if self.reverse_v4:
            return (all_active_assigned_interfaces()
                    .filter(type__ip_type=self)
                    .filter(ipv4__isnull=False))
        else:
            return None
459 460 461

    def get_associated_ptr_v6_records(self):
        from re2o.utils import all_active_interfaces
462 463 464 465 466
        if self.reverse_v6:
            return (all_active_interfaces(full=True)
                    .filter(type__ip_type=self))
        else:
            return None
467

468
    def clean(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
469 470 471 472 473
        """ 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"""
474
        if IPAddress(self.domaine_ip_start) > IPAddress(self.domaine_ip_stop):
475
            raise ValidationError(_("Range end must be after range start..."))
476 477
        # On ne crée pas plus grand qu'un /16
        if self.ip_range.size > 65536:
478 479
            raise ValidationError(_("The range is too large, you can't create"
                                    " a larger one than a /16."))
480
        # On check que les / ne se recoupent pas
481
        for element in IpType.objects.all().exclude(pk=self.pk):
482
            if not self.ip_set.isdisjoint(element.ip_set):
483 484
                raise ValidationError(_("The specified range is not disjoint"
                                        " from existing ranges."))
485 486 487
        # On formate le prefix v6
        if self.prefix_v6:
            self.prefix_v6 = str(IPNetwork(self.prefix_v6 + '/64').network)
488 489 490
        # 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:
491 492 493
                raise ValidationError(_("If you specify a domain network or"
                                        " netmask, it must contain the"
                                        " domain's IP range."))
494 495 496 497 498 499
        return

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

500 501
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
502 503
        """Superdroit qui permet d'utiliser toutes les extensions sans
        restrictions
504 505
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
506
        return user_request.has_perm('machines.use_all_iptype'), None
507

508 509
    def __str__(self):
        return self.type
chirac's avatar
chirac committed
510

Gabriel Detraz's avatar
Gabriel Detraz committed
511

512
class Vlan(RevMixin, AclMixin, models.Model):
513 514 515
    """ 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)])
516 517 518
    name = models.CharField(max_length=256)
    comment = models.CharField(max_length=256, blank=True)

519 520
    class Meta:
        permissions = (
521
            ("view_vlan", _("Can view a VLAN object")),
522
        )
523 524
        verbose_name = _("VLAN")
        verbose_name_plural = _("VLANs")
525

526 527 528
    def __str__(self):
        return self.name

Gabriel Detraz's avatar
Gabriel Detraz committed
529

530
class Nas(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
531
    """ Les nas. Associé à un machine_type.
Gabriel Detraz's avatar
Gabriel Detraz committed
532 533
    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"""
534 535 536 537 538 539
    default_mode = '802.1X'
    AUTH = (
        ('802.1X', '802.1X'),
        ('Mac-address', 'Mac-address'),
    )

540
    name = models.CharField(max_length=255, unique=True)
Gabriel Detraz's avatar
Gabriel Detraz committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    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
    )
556
    autocapture_mac = models.BooleanField(default=False)
557

558 559
    class Meta:
        permissions = (
560
            ("view_nas", _("Can view a NAS device object")),
561
        )
562 563
        verbose_name = _("NAS device")
        verbose_name_plural = _("NAS devices")
564

565 566 567
    def __str__(self):
        return self.name

Gabriel Detraz's avatar
Gabriel Detraz committed
568

569
class SOA(RevMixin, AclMixin, models.Model):
570 571 572 573 574
    """
    Un enregistrement SOA associé à une extension
    Les valeurs par défault viennent des recommandations RIPE :
    https://www.ripe.net/publications/docs/ripe-203
    """
575
    name = models.CharField(max_length=255)
576
    mail = models.EmailField(
577
        help_text=_("Contact email address for the zone")
578 579
    )
    refresh = models.PositiveIntegerField(
580
        default=86400,  # 24 hours
581 582
        help_text=_("Seconds before the secondary DNS have to ask the primary"
                    " DNS serial to detect a modification")
583 584
    )
    retry = models.PositiveIntegerField(
585
        default=7200,  # 2 hours
586 587
        help_text=_("Seconds before the secondary DNS ask the serial again in"
                    " case of a primary DNS timeout")
588 589
    )
    expire = models.PositiveIntegerField(
590
        default=3600000,  # 1000 hours
591 592
        help_text=_("Seconds before the secondary DNS stop answering requests"
                    " in case of primary DNS timeout")
593 594 595
    )
    ttl = models.PositiveIntegerField(
        default=172800,  # 2 days
596
        help_text=_("Time to Live")
597 598
    )

599 600
    class Meta:
        permissions = (
601
            ("view_soa", _("Can view an SOA record object")),
602
        )
603 604
        verbose_name = _("SOA record")
        verbose_name_plural = _("SOA records")
605

606 607 608 609 610 611 612 613 614 615 616 617 618
    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 (
619 620 621 622
            '    {refresh}; refresh\n'
            '    {retry}; retry\n'
            '    {expire}; expire\n'
            '    {ttl}; TTL'
623
        ).format(
624 625 626 627
            refresh=str(self.refresh).ljust(12),
            retry=str(self.retry).ljust(12),
            expire=str(self.expire).ljust(12),
            ttl=str(self.ttl).ljust(12)
628 629 630 631 632 633
        )

    @cached_property
    def dns_soa_mail(self):
        """ Renvoie le mail dans l'enregistrement SOA """
        mail_fields = str(self.mail).split('@')
634
        return mail_fields[0].replace('.', '\\.') + '.' + mail_fields[1] + '.'
635 636 637 638 639 640 641

    @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. """
642
        return cls.objects.get_or_create(
643
            name=_("SOA to edit"),
644 645
            mail="postmaser@example.com"
        )[0].pk
646 647


648
class Extension(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
649 650
    """ Extension dns type example.org. Précise si tout le monde peut
    l'utiliser, associé à un origin (ip d'origine)"""
Gabriel Detraz's avatar
Gabriel Detraz committed
651 652 653
    name = models.CharField(
        max_length=255,
        unique=True,
654
        help_text=_("Zone name, must begin with a dot (.example.org)")
Gabriel Detraz's avatar
Gabriel Detraz committed
655
    )
656
    need_infra = models.BooleanField(default=False)
657
    origin = models.ForeignKey(
Gabriel Detraz's avatar
Gabriel Detraz committed
658 659 660
        'IpList',
        on_delete=models.PROTECT,
        blank=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
661
        null=True,
662
        help_text=_("A record associated with the zone")
Gabriel Detraz's avatar
Gabriel Detraz committed
663
    )
664 665 666
    origin_v6 = models.GenericIPAddressField(
        protocol='IPv6',
        null=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
667
        blank=True,
668
        help_text=_("AAAA record associated with the zone")
669
    )
670 671
    soa = models.ForeignKey(
        'SOA',
672
        on_delete=models.CASCADE
673
    )
674

675 676
    class Meta:
        permissions = (
677 678
            ("view_extension", _("Can view an extension object")),
            ("use_all_extension", _("Can use all extensions")),
679
        )
680 681
        verbose_name = _("DNS extension")
        verbose_name_plural = _("DNS extensions")
682

683 684
    @cached_property
    def dns_entry(self):
685 686 687
        """ Une entrée DNS A et AAAA sur origin (zone self)"""
        entry = ""
        if self.origin:
688
            entry += "@               IN  A       " + str(self.origin)
689 690 691
        if self.origin_v6:
            if entry:
                entry += "\n"
692
            entry += "@               IN  AAAA    " + str(self.origin_v6)
693
        return entry
694

695
    def get_associated_sshfp_records(self):
696 697 698
        from re2o.utils import all_active_assigned_interfaces
        return (all_active_assigned_interfaces()
                .filter(type__ip_type__extension=self)
699
                .filter(machine__id__in=SshFp.objects.values('machine')))
700

701
    def get_associated_a_records(self):
702 703
        from re2o.utils import all_active_assigned_interfaces
        return (all_active_assigned_interfaces()
704
                .filter(type__ip_type__extension=self)
705
                .filter(ipv4__isnull=False))
706 707

    def get_associated_aaaa_records(self):
708 709 710
        from re2o.utils import all_active_interfaces
        return (all_active_interfaces(full=True)
                .filter(type__ip_type__extension=self))
711 712

    def get_associated_cname_records(self):
713
        from re2o.utils import all_active_assigned_interfaces
714 715
        return (Domain.objects
                .filter(extension=self)
Charlie Jacomme's avatar
Charlie Jacomme committed
716
                .filter(cname__interface_parent__in=all_active_assigned_interfaces())
717
                .prefetch_related('cname'))
718

719 720
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
721 722
        """Superdroit qui permet d'utiliser toutes les extensions sans
        restrictions
723 724
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
725
        return user_request.has_perm('machines.use_all_extension'), None
726

727 728
    def __str__(self):
        return self.name
chirac's avatar
chirac committed
729

730
    def clean(self, *args, **kwargs):
Gabriel Detraz's avatar
Gabriel Detraz committed
731
        if self.name and self.name[0] != '.':
732
            raise ValidationError(_("An extension must begin with a dot."))
Gabriel Detraz's avatar
Gabriel Detraz committed
733 734
        super(Extension, self).clean(*args, **kwargs)

Gabriel Detraz's avatar
Gabriel Detraz committed
735

736
class Mx(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
737 738
    """ Entrées des MX. Enregistre la zone (extension) associée et la
    priorité
Gabriel Detraz's avatar
Gabriel Detraz committed
739
    Todo : pouvoir associer un MX à une interface """
740
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
741 742
    priority = models.PositiveIntegerField()
    name = models.ForeignKey('Domain', on_delete=models.PROTECT)
743

744 745
    class Meta:
        permissions = (
746
            ("view_mx", _("Can view an MX record object")),
747
        )
748 749
        verbose_name = _("MX record")
        verbose_name_plural = _("MX records")
750

751 752
    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
753 754
        """Renvoie l'entrée DNS complète pour un MX à mettre dans les
        fichiers de zones"""
755 756
        return "@               IN  MX  {prior} {name}".format(
            prior=str(self.priority).ljust(3),
Maël Kervella's avatar
Maël Kervella committed
757
            name=str(self.name)
758
        )
759

760 761 762
    def __str__(self):
        return str(self.zone) + ' ' + str(self.priority) + ' ' + str(self.name)

Gabriel Detraz's avatar
Gabriel Detraz committed
763

764
class Ns(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
765
    """Liste des enregistrements name servers par zone considéérée"""
766
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
767
    ns = models.ForeignKey('Domain', on_delete=models.PROTECT)
768

769 770
    class Meta:
        permissions = (
771
            ("view_ns", _("Can view an NS record object")),
772
        )
773 774
        verbose_name = _("NS record")
        verbose_name_plural = _("NS records")
775

776 777
    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
778
        """Renvoie un enregistrement NS complet pour les filezones"""
779
        return "@               IN  NS      " + str(self.ns)
780

781
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
782
        return str(self.zone) + ' ' + str(self.ns)
783

Gabriel Detraz's avatar
Gabriel Detraz committed
784

785
class Txt(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
786
    """ Un enregistrement TXT associé à une extension"""
Gabriel Detraz's avatar
Gabriel Detraz committed
787 788
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
    field1 = models.CharField(max_length=255)
789
    field2 = models.TextField(max_length=2047)
Gabriel Detraz's avatar
Gabriel Detraz committed
790

791 792
    class Meta:
        permissions = (
793
            ("view_txt", _("Can view a TXT record object")),
794
        )
795 796
        verbose_name = _("TXT record")
        verbose_name_plural = _("TXT records")
797

Gabriel Detraz's avatar
Gabriel Detraz committed
798
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
799 800
        return str(self.zone) + " : " + str(self.field1) + " " +\
            str(self.field2)
Gabriel Detraz's avatar
Gabriel Detraz committed
801 802 803

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

Gabriel Detraz's avatar
Gabriel Detraz committed
807

Charlie Jacomme's avatar
Charlie Jacomme committed
808
class DName(RevMixin, AclMixin, models.Model):
Maël Kervella's avatar
Maël Kervella committed
809
    """A DNAME entry for the DNS."""
Charlie Jacomme's avatar
Charlie Jacomme committed
810 811 812 813 814
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
    alias = models.CharField(max_length=255)

    class Meta:
        permissions = (
815
            ("view_dname", _("Can view a DNAME record object")),
Charlie Jacomme's avatar
Charlie Jacomme committed
816
        )
817 818
        verbose_name = _("DNAME record")
        verbose_name_plural = _("DNAME records")
Charlie Jacomme's avatar
Charlie Jacomme committed
819 820 821 822 823 824

    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
825
        """Returns the DNAME record for the DNS zone file."""
chirac's avatar
chirac committed
826
        return str(self.alias).ljust(15) + " IN  DNAME   " + str(self.zone)
Charlie Jacomme's avatar
Charlie Jacomme committed
827 828


829
class Srv(RevMixin, AclMixin, models.Model):
830
    """ A SRV record """
Gabriel Detraz's avatar
Gabriel Detraz committed
831 832 833
    TCP = 'TCP'
    UDP = 'UDP'

834
    service = models.CharField(max_length=31)
Gabriel Detraz's avatar
Gabriel Detraz committed
835 836 837 838 839
    protocole = models.CharField(
        max_length=3,
        choices=(
            (TCP, 'TCP'),
            (UDP, 'UDP'),
840
        ),
Gabriel Detraz's avatar
Gabriel Detraz committed
841 842 843 844 845
        default=TCP,
    )
    extension = models.ForeignKey('Extension', on_delete=models.PROTECT)
    ttl = models.PositiveIntegerField(
        default=172800,  # 2 days
846
        help_text=_("Time to Live")
Gabriel Detraz's avatar
Gabriel Detraz committed
847 848
    )
    priority = models.PositiveIntegerField(
849
        default=0,
Gabriel Detraz's avatar
Gabriel Detraz committed
850
        validators=[MaxValueValidator(65535)],
851 852 853
        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
Gabriel Detraz committed
854 855
    )
    weight = models.PositiveIntegerField(
856
        default=0,
Gabriel Detraz's avatar
Gabriel Detraz committed
857
        validators=[MaxValueValidator(65535)],
858 859
        help_text=_("Relative weight for records with the same priority"
                     " (integer value between 0 and 65535)")
Gabriel Detraz's avatar
Gabriel Detraz committed
860 861 862
    )
    port = models.PositiveIntegerField(
        validators=[MaxValueValidator(65535)],
863
        help_text=_("TCP/UDP port")
Gabriel Detraz's avatar
Gabriel Detraz committed
864 865 866 867
    )
    target = models.ForeignKey(
        'Domain',
        on_delete=models.PROTECT,
868
        help_text=_("Target server")
Gabriel Detraz's avatar
Gabriel Detraz committed
869 870
    )

871 872
    class Meta:
        permissions = (
873
            ("view_srv", _("Can view an SRV record object")),
874
        )
875 876
        verbose_name = _("SRV record")
        verbose_name_plural = _("SRV records")
877

Gabriel Detraz's avatar
Gabriel Detraz committed
878 879 880 881 882 883 884 885 886 887 888 889 890 891
    def __str__(self):
        return str(self.service) + ' ' + str(self.protocole) + ' ' +\
            str(self.extension) + ' ' + str(self.priority) +\
            ' ' + str(self.weight) + str(self.port) + str(self.target)

    @cached_property
    def dns_entry(self):
        """Renvoie l'enregistrement SRV complet pour le fichier de zone"""
        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) + '.'


892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
class SshFp(RevMixin, AclMixin, models.Model):
    """A fingerprint of an SSH public key"""

    ALGO = (
        ("ssh-rsa", "ssh-rsa"),
        ("ssh-ed25519", "ssh-ed25519"),
        ("ecdsa-sha2-nistp256", "ecdsa-sha2-nistp256"),
        ("ecdsa-sha2-nistp384", "ecdsa-sha2-nistp384"),
        ("ecdsa-sha2-nistp521", "ecdsa-sha2-nistp521"),
    )

    machine = models.ForeignKey('Machine', on_delete=models.CASCADE)
    pub_key_entry = models.TextField(
        help_text="SSH public key",
        max_length=2048
    )
    algo = models.CharField(
        choices=ALGO,
        max_length=32
    )
    comment = models.CharField(
        help_text="Comment",
        max_length=255,
        null=True,
        blank=True
    )

    @cached_property
    def algo_id(self):
        """Return the id of the algorithm for this key"""
        if "ecdsa" in self.algo:
            return 3
        elif "rsa" in self.algo:
            return 1
        else:
            return 2

    @cached_property
    def hash(self):
        """Return the hashess for the pub key with correct id
        cf RFC, 1 is sha1 , 2 sha256"""
        return {
            "1" : hashlib.sha1(base64.b64decode(self.pub_key_entry)).hexdigest(),
            "2" : hashlib.sha256(base64.b64decode(self.pub_key_entry)).hexdigest(),
        }

    class Meta:
        permissions = (
940
            ("view_sshfp", _("Can view an SSHFP record object")),
941
        )
942 943
        verbose_name = _("SSHFP record")
        verbose_name_plural = _("SSHFP records")
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958

    def can_view(self, user_request, *_args, **_kwargs):
        return self.machine.can_view(user_request, *_args, **_kwargs)

    def can_edit(self, user_request, *args, **kwargs):
        return self.machine.can_edit(user_request, *args, **kwargs)

    def can_delete(self, user_request, *args, **kwargs):
        return self.machine.can_delete(user_request, *args, **kwargs)

    def __str__(self):
        return str(self.algo) + ' ' + str(self.comment)



959
class Interface(RevMixin, AclMixin, FieldPermissionModelMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
960 961 962
    """ Une interface. Objet clef de l'application machine :
    - une address mac unique. Possibilité de la rendre unique avec le
    typemachine
Gabriel Detraz's avatar
Gabriel Detraz committed
963 964 965 966
    - une onetoone vers IpList pour attribution ipv4
    - le type parent associé au range ip et à l'extension
    - un objet domain associé contenant son nom
    - la liste des ports oiuvert"""
Gabriel Detraz's avatar
Gabriel Detraz committed
967 968 969 970 971 972
    ipv4 = models.OneToOneField(
        'IpList',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
973
    mac_address = MACAddressField(integer=False)
974
    machine = models.ForeignKey('Machine', on_delete=models.CASCADE)
975
    type = models.ForeignKey('MachineType', on_delete=models.PROTECT)
976
    details = models.CharField(max_length=255, blank=True)
977
    port_lists = models.ManyToManyField('OuverturePortList', blank=True)
chirac's avatar
chirac committed
978

979 980
    class Meta:
        permissions = (
981
            ("view_interface", _("Can view an interface object")),
982
            ("change_interface_machine",
983
             _("Can change the owner of an interface")),
984
        )
985 986
        verbose_name = _("interface")
        verbose_name_plural = _("interfaces")
987

988
    @cached_property
Dalahro's avatar
Dalahro committed
989 990 991 992
    def is_active(self):
        """ Renvoie si une interface doit avoir accès ou non """
        machine = self.machine
        user = self.machine.user
993
        return machine.active and user.has_access()
Dalahro's avatar
Dalahro committed
994

995
    @cached_property
996
    def ipv6_slaac(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
997 998
        """ Renvoie un objet type ipv6 à partir du prefix associé à
        l'iptype parent"""
999
        if self.type.ip_type.prefix_v6:
Gabriel Detraz's avatar
Gabriel Detraz committed
1000 1001 1002
            return EUI(self.mac_address).ipv6(
                IPNetwork(self.type.ip_type.prefix_v6).network
            )
1003 1004 1005
        else:
            return None

1006 1007 1008
    @cached_property
    def gen_ipv6_dhcpv6(self):
        """Cree une ip, à assigner avec dhcpv6 sur une machine"""
1009
        prefix_v6 = self.type.ip_type.prefix_v6.encode().decode('utf-8')
1010 1011
        if not prefix_v6:
            return None
1012 1013 1014 1015
        return IPv6Address(
            IPv6Address(prefix_v6).exploded[:20] +
            IPv6Address(self.id).exploded[20:]
        )
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028

    def sync_ipv6_dhcpv6(self):
        """Affecte une ipv6 dhcpv6 calculée à partir de l'id de la machine"""
        ipv6_dhcpv6 = self.gen_ipv6_dhcpv6
        if not ipv6_dhcpv6:
            return
        ipv6 = Ipv6List.objects.filter(ipv6=str(ipv6_dhcpv6)).first()
        if not ipv6:
            ipv6 = Ipv6List(ipv6=str(ipv6_dhcpv6))
        ipv6.interface = self
        ipv6.save()
        return

1029 1030 1031 1032 1033 1034 1035 1036
    def sync_ipv6_slaac(self):
        """Cree, mets à jour et supprime si il y a lieu l'ipv6 slaac associée
        à la machine
        Sans prefixe ipv6, on return
        Si l'ip slaac n'est pas celle qu'elle devrait être, on maj"""
        ipv6_slaac = self.ipv6_slaac
        if not ipv6_slaac:
            return
1037 1038 1039
        ipv6_object = (Ipv6List.objects
                       .filter(interface=self, slaac_ip=True)
                       .first())
1040 1041 1042 1043 1044 1045
        if not ipv6_object:
            ipv6_object = Ipv6List(interface=self, slaac_ip=True)
        if ipv6_object.ipv6 != str(ipv6_slaac):
            ipv6_object.ipv6 = str(ipv6_slaac)
            ipv6_object.save()

1046 1047
    def sync_ipv6(self):
        """Cree et met à jour l'ensemble des ipv6 en fonction du mode choisi"""
1048 1049
        if (preferences.models.OptionalMachine
                .get_cached_value('ipv6_mode') == 'SLAAC'):
1050
            self.sync_ipv6_slaac()
1051 1052
        elif (preferences.models.OptionalMachine
              .get_cached_value('ipv6_mode') == 'DHCPV6'):
1053 1054 1055 1056
            self.sync_ipv6_dhcpv6()
        else:
            return

1057
    def ipv6(self):
1058
        """ Renvoie le queryset de la liste des ipv6
1059 1060 1061 1062
        On renvoie l'ipv6 slaac que si le mode slaac est activé
        (et non dhcpv6)"""
        if (preferences.models.OptionalMachine
                .get_cached_value('ipv6_mode') == 'SLAAC'):
1063
            return self.ipv6list.all()
1064 1065
        elif (preferences.models.OptionalMachine
              .get_cached_value('ipv6_mode') == 'DHCPV6'):
1066
            return self.ipv6list.filter(slaac_ip=False)
1067 1068
        else:
            return None
1069

1070
    def mac_bare(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1071
        """ Formatage de la mac type mac_bare"""
1072 1073
        return str(EUI(self.mac_address, dialect=mac_bare)).lower()

1074
    def filter_macaddress(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1075 1076
        """ Tente un formatage mac_bare, si échoue, lève une erreur de
        validation"""
1077 1078
        try:
            self.mac_address = str(EUI(self.mac_address))
Gabriel Detraz's avatar
Gabriel Detraz committed
1079
        except:
1080
            raise ValidationError(_("The given MAC address is invalid."))
1081

1082
    def clean(self, *args, **kwargs):
Gabriel Detraz's avatar
Gabriel Detraz committed
1083 1084
        """ Formate l'addresse mac en mac_bare (fonction filter_mac)
        et assigne une ipv4 dans le bon range si inexistante ou incohérente"""
1085 1086 1087 1088 1089 1090 1091
        # If type was an invalid value, django won't create an attribute type
        # but try clean() as we may be able to create it from another value
        # so even if the error as yet been detected at this point, django
        # continues because the error might not prevent us from creating the
        # instance.
        # But in our case, it's impossible to create a type value so we raise
        # the error.
1092
        if not hasattr(self, 'type'):
1093
            raise ValidationError(_("The selected IP type is invalid."))
1094
        self.filter_macaddress()
1095
        self.mac_address = str(EUI(self.mac_address)) or None
1096
        if not self.ipv4 or self.type.ip_type != self.ipv4.ip_type:
1097
            self.assign_ipv4()
1098
        super(Interface, self).clean(*args, **kwargs)
1099 1100 1101 1102 1103 1104 1105

    def assign_ipv4(self):
        """ Assigne une ip à l'interface """
        free_ips = self.type.ip_type.free_ip()
        if free_ips:
            self.ipv4 = free_ips[0]
        else:
1106 1107
            raise ValidationError(_("There is no IP address available in the"
                                    " slash."))
1108 1109 1110
        return

    def unassign_ipv4(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1111
        """ Sans commentaire, désassigne une ipv4"""
1112
        self.ipv4 = None
1113

1114 1115 1116 1117 1118
    def update_type(self):
        """ Lorsque le machinetype est changé de type d'ip, on réassigne"""
        self.clean()
        self.save()

1119
    def save(self, *args, **kwargs):
1120
        self.filter_macaddress()
1121
        # On verifie la cohérence en forçant l'extension par la méthode
1122 1123
        if self.ipv4:
            if self.type.ip_type != self.ipv4.ip_type:
1124 1125
                raise ValidationError(_("The IPv4 address and the machine type"
                                        " don't match."))
1126 1127
        super(Interface, self).save(*args, **kwargs)

1128 1129
    @staticmethod
    def can_create(user_request, machineid, *_args, **_kwargs):
1130 1131 1132 1133 1134
        """Verifie que l'user a les bons droits infra pour créer
        une interface, ou bien que la machine appartient bien à l'user
        :param macineid: Id de la machine parente de l'interface
        :param user_request: instance utilisateur qui fait la requête
        :return: soit True, soit False avec la raison de l'échec"""
1135
        try:
1136
            machine = Machine.objects.get(pk=machineid)
1137
        except Machine.DoesNotExist:
1138
            return False, _("Nonexistent machine.")
1139
        if not user_request.has_perm('machines.add_interface'):
1140 1141
            if not (preferences.models.OptionalMachine
                    .get_cached_value('create_machine')):
1142
                return False, _("You can't add a machine.")
1143 1144 1145 1146
            max_lambdauser_interfaces = (preferences.models.OptionalMachine
                                         .get_cached_value(
                                             'max_lambdauser_interfaces'
                                         ))
1147
            if machine.user != user_request:
1148 1149
                return False, _("You don't have the right to add an interface"
                                " to a machine of another user.")
1150 1151
            if (machine.user.user_interfaces().count() >=
                    max_lambdauser_interfaces):
1152 1153 1154
                return False, (_("You reached the maximum number of interfaces"
                                 " that you are allowed to create yourself"
                                 " (%s)." % max_lambdauser_interfaces))
1155 1156
        return True, None

1157
    @staticmethod
1158 1159 1160
    def can_change_machine(user_request, *_args, **_kwargs):
        """Check if a user can change the machine associated with an
        Interface object """
1161
        return (user_request.has_perm('machines.change_interface_machine'),
1162
                _("Permission required to edit the machine."))
1163

1164
    def can_edit(self, user_request, *args, **kwargs):
1165 1166 1167 1168 1169
        """Verifie que l'user a les bons droits infra pour editer
        cette instance interface, ou qu'elle lui appartient
        :param self: Instance interface à editer
        :param user_request: Utilisateur qui fait la requête
        :return: soit True, soit False avec la raison de l'échec"""
1170
        if self.machine.user != user_request:
1171 1172 1173 1174 1175
            if (not user_request.has_perm('machines.change_interface') or
                    not self.machine.user.can_edit(
                        user_request,
                        *args,
                        **kwargs
1176 1177 1178
                    )[0]):
                return False, _("You don't have the right to edit a machine of"
                                " another user.")
1179 1180
        return True, None

1181
    def can_delete(self, user_request, *args, **kwargs):
1182
        """Verifie que l'user a les bons droits delete object pour del
1183 1184 1185 1186
        cette instance interface, ou qu'elle lui appartient
        :param self: Instance interface à del
        :param user_request: Utilisateur qui fait la requête
        :return: soit True, soit False avec la raison de l'échec"""
1187
        if self.machine.user != user_request:
1188 1189 1190 1191 1192
            if (not user_request.has_perm