Statistics
| Branch: | Tag: | Revision:

root / flowspec / models.py @ ac2fbadf

History | View | Annotate | Download (19 kB)

1
# -*- coding: utf-8 -*- vim:fileencoding=utf-8:
2
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
3

    
4
# Copyright © 2011-2014 Greek Research and Technology Network (GRNET S.A.)
5
# Copyright © 2011-2014 Leonidas Poulopoulos (@leopoul)
6
# 
7
# Permission to use, copy, modify, and/or distribute this software for any
8
# purpose with or without fee is hereby granted, provided that the above
9
# copyright notice and this permission notice appear in all copies.
10
# 
11
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
12
# TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
13
# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
14
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
15
# DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
16
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
17
# SOFTWARE.
18

    
19
from django.db import models
20
from django.conf import settings
21
from django.contrib.auth.models import User
22
from django.utils.translation import ugettext_lazy as _
23
from utils import proxy as PR
24
from ipaddr import *
25
import datetime
26
import logging
27
from time import sleep
28

    
29
import beanstalkc
30
from utils.randomizer import id_generator as id_gen
31

    
32
from tasks import *
33

    
34
def user_unicode_patch(self):
35
    peer = None
36
    try:
37
        peer = self.get_profile().peer.peer_name
38
    except:
39
        pass
40
    if peer:
41
        return '%s.::.%s' % (self.username, peer)
42
    return self.username
43

    
44
User.__unicode__ = user_unicode_patch
45

    
46

    
47
FORMAT = '%(asctime)s %(levelname)s: %(message)s'
48
logging.basicConfig(format=FORMAT)
49
logger = logging.getLogger(__name__)
50
logger.setLevel(logging.DEBUG)
51

    
52

    
53
FRAGMENT_CODES = (
54
    ("dont-fragment", "Don't fragment"),
55
    ("first-fragment", "First fragment"),
56
    ("is-fragment", "Is fragment"),
57
    ("last-fragment", "Last fragment"),
58
    ("not-a-fragment", "Not a fragment")
59
)
60

    
61
THEN_CHOICES = (
62
    ("accept", "Accept"),
63
    ("discard", "Discard"),
64
    ("community", "Community"),
65
    ("next-term", "Next term"),
66
    ("routing-instance", "Routing Instance"),
67
    ("rate-limit", "Rate limit"),
68
    ("sample", "Sample")                
69
)
70

    
71
MATCH_PROTOCOL = (
72
    ("ah", "ah"),
73
    ("egp", "egp"),
74
    ("esp", "esp"),
75
    ("gre", "gre"),
76
    ("icmp", "icmp"),
77
    ("icmp6", "icmp6"),
78
    ("igmp", "igmp"),
79
    ("ipip", "ipip"),
80
    ("ospf", "ospf"),
81
    ("pim", "pim"),
82
    ("rsvp", "rsvp"),
83
    ("sctp", "sctp"),
84
    ("tcp", "tcp"),
85
    ("udp", "udp"),
86
)
87

    
88
ROUTE_STATES = (
89
    ("ACTIVE", "ACTIVE"),
90
    ("ERROR", "ERROR"),
91
    ("EXPIRED", "EXPIRED"),
92
    ("PENDING", "PENDING"),
93
    ("OUTOFSYNC", "OUTOFSYNC"),
94
    ("INACTIVE", "INACTIVE"),
95
    ("ADMININACTIVE", "ADMININACTIVE"),           
96
)
97

    
98

    
99
def days_offset(): return datetime.date.today() + datetime.timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
100
    
101
class MatchPort(models.Model):
102
    port = models.CharField(max_length=24, unique=True)
103
    def __unicode__(self):
104
        return self.port
105
    class Meta:
106
        db_table = u'match_port'    
107

    
108
class MatchDscp(models.Model):
109
    dscp = models.CharField(max_length=24)
110
    def __unicode__(self):
111
        return self.dscp
112
    class Meta:
113
        db_table = u'match_dscp'
114

    
115
class MatchProtocol(models.Model):
116
    protocol = models.CharField(max_length=24, unique=True)
117
    def __unicode__(self):
118
        return self.protocol
119
    class Meta:
120
        db_table = u'match_protocol'
121

    
122
class FragmentType(models.Model):
123
    fragmenttype = models.CharField(max_length=20, choices=FRAGMENT_CODES, verbose_name="Fragment Type")
124
    
125
    def __unicode__(self):
126
        return "%s" %(self.fragmenttype)
127

    
128

    
129
class ThenAction(models.Model):
130
    action = models.CharField(max_length=60, choices=THEN_CHOICES, verbose_name="Action")
131
    action_value = models.CharField(max_length=255, blank=True, null=True, verbose_name="Action Value")
132
    def __unicode__(self):
133
        ret = "%s:%s" %(self.action, self.action_value)
134
        return ret.rstrip(":")
135
    class Meta:
136
        db_table = u'then_action'
137
        ordering = ['action', 'action_value']
138
        unique_together = ("action", "action_value")
139

    
140
class Route(models.Model):
141
    name = models.SlugField(max_length=128, verbose_name=_("Name"))
142
    applier = models.ForeignKey(User, blank=True, null=True)
143
    source = models.CharField(max_length=32, help_text=_("Network address. Use address/CIDR notation"), verbose_name=_("Source Address"))
144
    sourceport = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchSourcePort", verbose_name=_("Source Port"))
145
    destination = models.CharField(max_length=32, help_text=_("Network address. Use address/CIDR notation"), verbose_name=_("Destination Address"))
146
    destinationport = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchDestinationPort", verbose_name=_("Destination Port"))
147
    port = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchPort", verbose_name=_("Port"))
148
    dscp = models.ManyToManyField(MatchDscp, blank=True, null=True, verbose_name="DSCP")
149
    fragmenttype = models.ManyToManyField(FragmentType, blank=True, null=True, verbose_name="Fragment Type")
150
    icmpcode = models.CharField(max_length=32, blank=True, null=True, verbose_name="ICMP Code")
151
    icmptype = models.CharField(max_length=32, blank=True, null=True, verbose_name="ICMP Type")
152
    packetlength = models.IntegerField(blank=True, null=True, verbose_name="Packet Length")
153
    protocol = models.ManyToManyField(MatchProtocol, blank=True, null=True, verbose_name=_("Protocol"))
154
    tcpflag = models.CharField(max_length=128, blank=True, null=True, verbose_name="TCP flag")
155
    then = models.ManyToManyField(ThenAction, verbose_name=_("Then"))
156
    filed = models.DateTimeField(auto_now_add=True)
157
    last_updated = models.DateTimeField(auto_now=True)
158
    status = models.CharField(max_length=20, choices=ROUTE_STATES, blank=True, null=True, verbose_name=_("Status"), default="PENDING")
159
#    is_online = models.BooleanField(default=False)
160
#    is_active = models.BooleanField(default=False)
161
    expires = models.DateField(default=days_offset, verbose_name=_("Expires"))
162
    response = models.CharField(max_length=512, blank=True, null=True, verbose_name=_("Response"))
163
    comments = models.TextField(null=True, blank=True, verbose_name=_("Comments"))
164

    
165
    
166
    def __unicode__(self):
167
        return self.name
168
    
169
    class Meta:
170
        db_table = u'route'
171
        verbose_name = "Rule"
172
        verbose_name_plural = "Rules"
173
    
174
    def save(self, *args, **kwargs):
175
        if not self.pk:
176
            hash = id_gen()
177
            self.name = "%s_%s" %(self.name, hash)
178
        super(Route, self).save(*args, **kwargs) # Call the "real" save() method.
179

    
180
        
181
    def clean(self, *args, **kwargs):
182
        from django.core.exceptions import ValidationError
183
        if self.destination:
184
            try:
185
                address = IPNetwork(self.destination)
186
                self.destination = address.exploded
187
            except Exception:
188
                raise ValidationError(_('Invalid network address format at Destination Field'))
189
        if self.source:
190
            try:
191
                address = IPNetwork(self.source)
192
                self.source = address.exploded
193
            except Exception:
194
                raise ValidationError(_('Invalid network address format at Source Field'))
195
   
196
    def commit_add(self, *args, **kwargs):
197
        peer = self.applier.get_profile().peer.peer_tag
198
        send_message("[%s] Adding rule %s. Please wait..." %(self.applier.username, self.name), peer)
199
        response = add.delay(self)
200
        logger.info("Got add job id: %s" %response)
201
        
202
    def commit_edit(self, *args, **kwargs):
203
        peer = self.applier.get_profile().peer.peer_tag
204
        send_message("[%s] Editing rule %s. Please wait..." %(self.applier.username, self.name), peer)
205
        response = edit.delay(self)
206
        logger.info("Got edit job id: %s" %response)
207

    
208
    def commit_delete(self, *args, **kwargs):
209
        reason_text = ''
210
        reason = ''
211
        if "reason" in kwargs:
212
            reason = kwargs['reason']
213
            reason_text = "Reason: %s. " %reason
214
        peer = self.applier.get_profile().peer.peer_tag
215
        send_message("[%s] Suspending rule %s. %sPlease wait..." %(self.applier.username, self.name, reason_text), peer)
216
        response = delete.delay(self, reason=reason)
217
        logger.info("Got delete job id: %s" %response)
218

    
219
    def has_expired(self):
220
        today = datetime.date.today()
221
        if today > self.expires:
222
            return True
223
        return False
224
    
225
    def check_sync(self):
226
        if not self.is_synced():
227
            self.status = "OUTOFSYNC"
228
            self.save()
229
    
230
    def is_synced(self):
231
        found = False
232
        get_device = PR.Retriever()
233
        device = get_device.fetch_device()
234
        try:
235
            routes = device.routing_options[0].routes
236
        except Exception as e:
237
            self.status = "EXPIRED"
238
            self.save()
239
            logger.error("No routing options on device. Exception: %s" %e)
240
            return True
241
        for route in routes:
242
            if route.name == self.name:
243
                found = True
244
                logger.info('Found a matching rule name')
245
                devicematch = route.match
246
                try:
247
                    assert(self.destination)
248
                    assert(devicematch['destination'][0])
249
                    if self.destination == devicematch['destination'][0]:
250
                        found = found and True
251
                        logger.info('Found a matching destination')
252
                    else:
253
                        found = False
254
                        logger.info('Destination fields do not match')
255
                except:
256
                    pass
257
                try:
258
                    assert(self.source)
259
                    assert(devicematch['source'][0])
260
                    if self.source == devicematch['source'][0]:
261
                        found = found and True
262
                        logger.info('Found a matching source')
263
                    else:
264
                        found = False
265
                        logger.info('Source fields do not match')
266
                except:
267
                    pass
268
                
269
                try:
270
                    assert(self.fragmenttype.all())
271
                    assert(devicematch['fragment'])
272
                    devitems = devicematch['fragment']
273
                    dbitems = ["%s"%i for i in self.fragmenttype.all()]
274
                    intersect = list(set(devitems).intersection(set(dbitems)))
275
                    if ((len(intersect) == len(dbitems)) and (len(intersect) == len(devitems))):
276
                        found = found and True
277
                        logger.info('Found a matching fragment type')
278
                    else:
279
                        found = False
280
                        logger.info('Fragment type fields do not match')
281
                except:
282
                    pass
283
                
284
                try:
285
                    assert(self.port.all())
286
                    assert(devicematch['port'])
287
                    devitems = devicematch['port']
288
                    dbitems = ["%s"%i for i in self.port.all()]
289
                    intersect = list(set(devitems).intersection(set(dbitems)))
290
                    if ((len(intersect) == len(dbitems)) and (len(intersect) == len(devitems))):
291
                        found = found and True
292
                        logger.info('Found a matching port type')
293
                    else:
294
                        found = False
295
                        logger.info('Port type fields do not match')
296
                except:
297
                    pass
298
                
299
                try:
300
                    assert(self.protocol.all())
301
                    assert(devicematch['protocol'])
302
                    devitems = devicematch['protocol']
303
                    dbitems = ["%s"%i for i in self.protocol.all()]
304
                    intersect = list(set(devitems).intersection(set(dbitems)))
305
                    if ((len(intersect) == len(dbitems)) and (len(intersect) == len(devitems))):
306
                        found = found and True
307
                        logger.info('Found a matching protocol type')
308
                    else:
309
                        found = False
310
                        logger.info('Protocol type fields do not match')
311
                except:
312
                    pass
313

    
314
                try:
315
                    assert(self.destinationport.all())
316
                    assert(devicematch['destination-port'])
317
                    devitems = devicematch['destination-port']
318
                    dbitems = ["%s"%i for i in self.destinationport.all()]
319
                    intersect = list(set(devitems).intersection(set(dbitems)))
320
                    if ((len(intersect) == len(dbitems)) and (len(intersect) == len(devitems))):
321
                        found = found and True
322
                        logger.info('Found a matching destination port type')
323
                    else:
324
                        found = False
325
                        logger.info('Destination port type fields do not match')
326
                except:
327
                    pass
328

    
329
                try:
330
                    assert(self.sourceport.all())
331
                    assert(devicematch['source-port'])
332
                    devitems = devicematch['source-port']
333
                    dbitems = ["%s"%i for i in self.sourceport.all()]
334
                    intersect = list(set(devitems).intersection(set(dbitems)))
335
                    if ((len(intersect) == len(dbitems)) and (len(intersect) == len(devitems))):
336
                        found = found and True
337
                        logger.info('Found a matching source port type')
338
                    else:
339
                        found = False
340
                        logger.info('Source port type fields do not match')
341
                except:
342
                    pass
343
                                
344
                
345
#                try:
346
#                    assert(self.fragmenttype)
347
#                    assert(devicematch['fragment'][0])
348
#                    if self.fragmenttype == devicematch['fragment'][0]:
349
#                        found = found and True
350
#                        logger.info('Found a matching fragment type')
351
#                    else:
352
#                        found = False
353
#                        logger.info('Fragment type fields do not match')
354
#                except:
355
#                    pass
356
                try:
357
                    assert(self.icmpcode)
358
                    assert(devicematch['icmp-code'][0])
359
                    if self.icmpcode == devicematch['icmp-code'][0]:
360
                        found = found and True
361
                        logger.info('Found a matching icmp code')
362
                    else:
363
                        found = False
364
                        logger.info('Icmp code fields do not match')
365
                except:
366
                    pass
367
                try:
368
                    assert(self.icmptype)
369
                    assert(devicematch['icmp-type'][0])
370
                    if self.icmptype == devicematch['icmp-type'][0]:
371
                        found = found and True
372
                        logger.info('Found a matching icmp type')
373
                    else:
374
                        found = False
375
                        logger.info('Icmp type fields do not match')
376
                except:
377
                    pass
378
                if found and self.status != "ACTIVE":
379
                    logger.error('Rule is applied on device but appears as offline')
380
                    self.status = "ACTIVE"
381
                    self.save()
382
                    found = True
383
            if self.status == "ADMININACTIVE" or self.status == "INACTIVE" or self.status == "EXPIRED":
384
                found = True
385
        return found
386

    
387
    def get_then(self):
388
        ret = ''
389
        then_statements = self.then.all()
390
        for statement in then_statements:
391
            if statement.action_value:
392
                ret = "%s %s %s" %(ret, statement.action, statement.action_value)
393
            else: 
394
                ret = "%s %s" %(ret, statement.action)
395
        return ret
396
    
397
    get_then.short_description = 'Then statement'
398
    get_then.allow_tags = True
399
#
400
    def get_match(self):
401
        ret = '<dl class="dl-horizontal">'
402
        if self.destination:
403
            ret = '%s <dt>Dst Addr</dt><dd>%s</dd>' %(ret, self.destination)
404
        if self.fragmenttype.all():
405
            ret = ret + "<dt>Fragment Types</dt><dd>%s</dd>" %(', '.join(["%s"%i for i in self.fragmenttype.all()]))
406
#            for fragment in self.fragmenttype.all():
407
#                    ret = ret + "Fragment Types:<strong>%s</dd>" %(fragment)
408
        if self.icmpcode:
409
            ret = "%s <dt>ICMP code</dt><dd>%s</dd>" %(ret, self.icmpcode)
410
        if self.icmptype:
411
            ret = "%s <dt>ICMP Type</dt><dd>%s</dd>" %(ret, self.icmptype)
412
        if self.packetlength:
413
            ret = "%s <dt>Packet Length</dt><dd>%s</dd>" %(ret, self.packetlength)
414
        if self.source:
415
            ret = "%s <dt>Src Addr</dt><dd>%s</dd>" %(ret, self.source)
416
        if self.tcpflag:
417
            ret = "%s <dt>TCP flag</dt><dd>%s</dd>" %(ret, self.tcpflag)
418
        if self.port.all():
419
            ret = ret + "<dt>Ports</dt><dd>%s</dd>" %(', '.join(["%s"%i for i in self.port.all()]))
420
#            for port in self.port.all():
421
#                    ret = ret + "Port:<strong>%s</dd>" %(port)
422
        if self.protocol.all():
423
            ret = ret + "<dt>Protocols</dt><dd>%s</dd>" %(', '.join(["%s"%i for i in self.protocol.all()]))
424
#            for protocol in self.protocol.all():
425
#                    ret = ret + "Protocol:<strong>%s</dd>" %(protocol)
426
        if self.destinationport.all():
427
            ret = ret + "<dt>DstPorts</dt><dd>%s</dd>" %(', '.join(["%s"%i for i in self.destinationport.all()]))
428
#            for port in self.destinationport.all():
429
#                    ret = ret + "Dst Port:<strong>%s</dd>" %(port)
430
        if self.sourceport.all():
431
            ret = ret + "<dt>SrcPorts</dt><dd>%s</dd>" %(', '.join(["%s"%i for i in self.sourceport.all()]))
432
#            for port in self.sourceport.all():
433
#                    ret = ret +"Src Port:<strong>%s</dd>" %(port)
434
        if self.dscp:
435
            for dscp in self.dscp.all():
436
                    ret = ret + "%s <dt>Port</dt><dd>%s</dd>" %(ret, dscp)
437
        ret = ret + "</dl>"
438
        return ret
439
        
440
    get_match.short_description = 'Match statement'
441
    get_match.allow_tags = True
442
    
443
    @property
444
    def applier_peer(self):
445
        try:
446
            applier_peer = self.applier.get_profile().peer
447
        except:
448
            applier_peer = None
449
        return applier_peer
450
    
451
    @property
452
    def days_to_expire(self):
453
        if self.status not in ['EXPIRED', 'ADMININACTIVE', 'ERROR', 'INACTIVE']:
454
            expiration_days = (self.expires - datetime.date.today()).days
455
            if expiration_days < settings.EXPIRATION_NOTIFY_DAYS:
456
                return "%s" %expiration_days
457
            else:
458
                return False
459
        else:
460
            return False
461

    
462
def send_message(msg, user):
463
#    username = user.username
464
    peer = user
465
    b = beanstalkc.Connection()
466
    b.use(settings.POLLS_TUBE)
467
    tube_message = json.dumps({'message': str(msg), 'username':peer})
468
    b.put(tube_message)
469
    b.close()