Statistics
| Branch: | Tag: | Revision:

root / flowspec / models.py @ 971645d6

History | View | Annotate | Download (10.8 kB)

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

    
4
from django.db import models
5
from django.conf import settings
6
from django.contrib.auth.models import User
7
from utils import proxy as PR
8
from ipaddr import *
9
from datetime import *
10
import logging
11
from flowspec.tasks import *
12
from time import sleep
13

    
14
FORMAT = '%(asctime)s %(levelname)s: %(message)s'
15
logging.basicConfig(format=FORMAT)
16
logger = logging.getLogger(__name__)
17
logger.setLevel(logging.DEBUG)
18

    
19

    
20
FRAGMENT_CODES = (
21
    ("dont-fragment", "Don't fragment"),
22
    ("first-fragment", "First fragment"),
23
    ("is-fragment", "Is fragment"),
24
    ("last-fragment", "Last fragment"),
25
    ("not-a-fragment", "Not a fragment")
26
)
27

    
28
THEN_CHOICES = (
29
    ("accept", "Accept"),
30
    ("discard", "Discard"),
31
    ("community", "Community"),
32
    ("next-term", "Next term"),
33
    ("routing-instance", "Routing Instance"),
34
    ("rate-limit", "Rate limit"),
35
    ("sample", "Sample")                
36
)
37

    
38

    
39
def days_offset(): return datetime.now() + timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
40
    
41
class MatchPort(models.Model):
42
    port = models.CharField(max_length=24)
43
    def __unicode__(self):
44
        return self.port
45
    class Meta:
46
        db_table = u'match_port'    
47

    
48
class MatchDscp(models.Model):
49
    dscp = models.CharField(max_length=24)
50
    def __unicode__(self):
51
        return self.dscp
52
    class Meta:
53
        db_table = u'match_dscp'
54

    
55
   
56
class ThenAction(models.Model):
57
    action = models.CharField(max_length=60, choices=THEN_CHOICES, verbose_name="Action")
58
    action_value = models.CharField(max_length=255, blank=True, null=True, verbose_name="Action Value")
59
    def __unicode__(self):
60
        return "%s: %s" %(self.action, self.action_value)
61
    class Meta:
62
        db_table = u'then_action'
63

    
64
class Route(models.Model):
65
    name = models.SlugField(max_length=128)
66
    applier = models.ForeignKey(User, blank=True, null=True)
67
    source = models.CharField(max_length=32, blank=True, null=True, help_text=u"Network address. Use address/CIDR notation", verbose_name="Source Address")
68
    sourceport = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchSourcePort", verbose_name="Source Port")
69
    destination = models.CharField(max_length=32, help_text=u"Network address. Use address/CIDR notation", verbose_name="Destination Address")
70
    destinationport = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchDestinationPort", verbose_name="Destination Port")
71
    port = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchPort", verbose_name="Port" )
72
    dscp = models.ManyToManyField(MatchDscp, blank=True, null=True, verbose_name="DSCP")
73
    fragmenttype = models.CharField(max_length=20, choices=FRAGMENT_CODES, blank=True, null=True, verbose_name="Fragment Type")
74
    icmpcode = models.CharField(max_length=32, blank=True, null=True, verbose_name="ICMP Code")
75
    icmptype = models.CharField(max_length=32, blank=True, null=True, verbose_name="ICMP Type")
76
    packetlength = models.IntegerField(blank=True, null=True, verbose_name="Packet Length")
77
    protocol = models.CharField(max_length=32, blank=True, null=True, verbose_name="Protocol")
78
    tcpflag = models.CharField(max_length=128, blank=True, null=True, verbose_name="TCP flag")
79
    then = models.ManyToManyField(ThenAction, verbose_name="Then")
80
    filed = models.DateTimeField(auto_now_add=True)
81
    last_updated = models.DateTimeField(auto_now=True)
82
    is_online = models.BooleanField(default=False)
83
    is_active = models.BooleanField(default=False)
84
    expires = models.DateField(default=days_offset, blank=True, null=True,)
85
    response = models.CharField(max_length=512, blank=True, null=True)
86
    comments = models.TextField(null=True, blank=True, verbose_name="Comments")
87

    
88
    
89
    def __unicode__(self):
90
        return self.name
91
    
92
    class Meta:
93
        unique_together = (("name", "is_active"),)
94
        db_table = u'route'
95
    
96
    def clean(self, *args, **kwargs):
97
        from django.core.exceptions import ValidationError
98
        if self.destination:
99
            try:
100
                address = IPNetwork(self.destination)
101
                self.destination = address.exploded
102
            except Exception:
103
                raise ValidationError('Invalid network address format at Destination Field')
104
        if self.source:
105
            try:
106
                address = IPNetwork(self.source)
107
                self.source = address.exploded
108
            except Exception:
109
                raise ValidationError('Invalid network address format at Source Field')
110
    
111
#    def save(self, *args, **kwargs):
112
#        edit = False
113
#        if self.pk:
114
#            #This is an edit
115
#            edit = True
116
#        super(Route, self).save(*args, **kwargs)
117
#        if not edit:
118
#            response = add.delay(self)
119
#            logger.info("Got save job id: %s" %response)
120
    
121
    def commit_add(self, *args, **kwargs):
122
        response = add.delay(self)
123
        logger.info("Got save job id: %s" %response)
124
#    
125
#    def delete(self, *args, **kwargs):
126
#        response = delete.delay(self)
127
#        logger.info("Got delete job id: %s" %response)
128
        
129

    
130
    def is_synced(self):
131
        
132
        found = False
133
        get_device = PR.Retriever()
134
        device = get_device.fetch_device()
135
        try:
136
            routes = device.routing_options[0].routes
137
        except Exception as e:
138
            self.is_online = False
139
            self.save()
140
            logger.error("No routing options on device. Exception: %s" %e)
141
            return False
142
        for route in routes:
143
            if route.name == self.name:
144
                found = True
145
                logger.info('Found a matching route name')
146
                devicematch = route.match
147
                try:
148
                    assert(self.destination)
149
                    assert(devicematch['destination'][0])
150
                    if self.destination == devicematch['destination'][0]:
151
                        found = found and True
152
                        logger.info('Found a matching destination')
153
                    else:
154
                        found = False
155
                        logger.info('Destination fields do not match')
156
                except:
157
                    pass
158
                try:
159
                    assert(self.source)
160
                    assert(devicematch['source'][0])
161
                    if self.source == devicematch['source'][0]:
162
                        found = found and True
163
                        logger.info('Found a matching source')
164
                    else:
165
                        found = False
166
                        logger.info('Source fields do not match')
167
                except:
168
                    pass
169
                try:
170
                    assert(self.fragmenttype)
171
                    assert(devicematch['fragment'][0])
172
                    if self.fragmenttype == devicematch['fragment'][0]:
173
                        found = found and True
174
                        logger.info('Found a matching fragment type')
175
                    else:
176
                        found = False
177
                        logger.info('Fragment type fields do not match')
178
                except:
179
                    pass
180
                try:
181
                    assert(self.icmpcode)
182
                    assert(devicematch['icmp-code'][0])
183
                    if self.icmpcode == devicematch['icmp-code'][0]:
184
                        found = found and True
185
                        logger.info('Found a matching icmp code')
186
                    else:
187
                        found = False
188
                        logger.info('Icmp code fields do not match')
189
                except:
190
                    pass
191
                try:
192
                    assert(self.icmptype)
193
                    assert(devicematch['icmp-type'][0])
194
                    if self.icmptype == devicematch['icmp-type'][0]:
195
                        found = found and True
196
                        logger.info('Found a matching icmp type')
197
                    else:
198
                        found = False
199
                        logger.info('Icmp type fields do not match')
200
                except:
201
                    pass
202
                try:
203
                    assert(self.protocol)
204
                    assert(devicematch['protocol'][0])
205
                    if self.protocol == devicematch['protocol'][0]:
206
                        found = found and True
207
                        logger.info('Found a matching protocol')
208
                    else:
209
                        found = False
210
                        logger.info('Protocol fields do not match')
211
                except:
212
                    pass
213
                if found and not self.is_online:
214
                     logger.error('Rule is applied on device but appears as offline')
215
                     found = False
216
        
217
        return found
218

    
219
    def get_then(self):
220
        ret = ''
221
        then_statements = self.then.all()
222
        for statement in then_statements:
223
            if statement.action_value:
224
                ret = "%s %s:<strong>%s</strong><br/>" %(ret, statement.action, statement.action_value)
225
            else: 
226
                ret = "%s %s<br>" %(ret, statement.action)
227
        return ret.rstrip(',')
228
    
229
    get_then.short_description = 'Then statement'
230
    get_then.allow_tags = True
231
#
232
    def get_match(self):
233
        ret = ''
234
        if self.destination:
235
            ret = ret = '%s Destination Address:<strong>%s</strong><br/>' %(ret, self.destination)
236
        if self.fragmenttype:
237
            ret = ret = "%s Fragment Type:<strong>%s</strong><br/>" %(ret, self.fragmenttype)
238
        if self.icmpcode:
239
            ret = ret = "%s ICMP code:<strong>%s</strong><br/>" %(ret, self.icmpcode)
240
        if self.icmptype:
241
            ret = ret = "%s ICMP Type:<strong>%s</strong><br/>" %(ret, self.icmptype)
242
        if self.packetlength:
243
            ret = ret = "%s Packet Length:<strong>%s</strong><br/>" %(ret, self.packetlength)
244
        if self.protocol:
245
            ret = ret = "%s Protocol:<strong>%s</strong><br/>" %(ret, self.protocol)
246
        if self.source:
247
            ret = ret = "%s Source Address:<strong>%s</strong><br/>" %(ret, self.source)
248
        if self.tcpflag:
249
            ret = ret = "%s TCP flag:<strong>%s</strong><br/>" %(ret, self.tcpflag)
250
        if self.port:
251
            for port in self.port.all():
252
                    ret = "%s Port:<strong>%s</strong><br/>" %(ret, port)
253
        if self.destinationport:
254
            for port in self.destinationport.all():
255
                    ret = "%s Port:<strong>%s</strong><br/>" %(ret, port)
256
        if self.sourceport:
257
            for port in self.sourceport.all():
258
                    ret = "%s Port:<strong>%s</strong><br/>" %(ret, port)
259
        if self.dscp:
260
            for dscp in self.dscp.all():
261
                    ret = "%s Port:<strong>%s</strong><br/>" %(ret, dscp)
262
        return ret.rstrip('<br/>')
263
        
264
    get_match.short_description = 'Match statement'
265
    get_match.allow_tags = True
266