Implemented login page. Altered settings.py.dist . Implemented update on change
[flowspy] / flowspec / models.py
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 import datetime
10 import logging
11 from flowspec.tasks import *
12 from time import sleep
13
14 from flowspy.utils import beanstalkc
15 from flowspy.utils.randomizer import id_generator as id_gen
16
17
18 FORMAT = '%(asctime)s %(levelname)s: %(message)s'
19 logging.basicConfig(format=FORMAT)
20 logger = logging.getLogger(__name__)
21 logger.setLevel(logging.DEBUG)
22
23
24 FRAGMENT_CODES = (
25     ("dont-fragment", "Don't fragment"),
26     ("first-fragment", "First fragment"),
27     ("is-fragment", "Is fragment"),
28     ("last-fragment", "Last fragment"),
29     ("not-a-fragment", "Not a fragment")
30 )
31
32 THEN_CHOICES = (
33     ("accept", "Accept"),
34     ("discard", "Discard"),
35     ("community", "Community"),
36     ("next-term", "Next term"),
37     ("routing-instance", "Routing Instance"),
38     ("rate-limit", "Rate limit"),
39     ("sample", "Sample")                
40 )
41
42 ROUTE_STATES = (
43     ("ACTIVE", "ACTIVE"),
44     ("ERROR", "ERROR"),
45     ("EXPIRED", "EXPIRED"),
46     ("PENDING", "PENDING"),
47     ("OUTOFSYNC", "OUTOFSYNC"),
48     ("INACTIVE", "INACTIVE"),            
49 )
50
51
52 def days_offset(): return datetime.date.today() + datetime.timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
53     
54 class MatchPort(models.Model):
55     port = models.CharField(max_length=24, unique=True)
56     def __unicode__(self):
57         return self.port
58     class Meta:
59         db_table = u'match_port'    
60
61 class MatchDscp(models.Model):
62     dscp = models.CharField(max_length=24)
63     def __unicode__(self):
64         return self.dscp
65     class Meta:
66         db_table = u'match_dscp'
67
68    
69 class ThenAction(models.Model):
70     action = models.CharField(max_length=60, choices=THEN_CHOICES, verbose_name="Action")
71     action_value = models.CharField(max_length=255, blank=True, null=True, verbose_name="Action Value")
72     def __unicode__(self):
73         ret = "%s:%s" %(self.action, self.action_value)
74         return ret.rstrip(":")
75     class Meta:
76         db_table = u'then_action'
77
78 class Route(models.Model):
79     name = models.SlugField(max_length=128)
80     applier = models.ForeignKey(User, blank=True, null=True)
81     source = models.CharField(max_length=32, blank=True, null=True, help_text=u"Network address. Use address/CIDR notation", verbose_name="Source Address")
82     sourceport = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchSourcePort", verbose_name="Source Port")
83     destination = models.CharField(max_length=32, help_text=u"Network address. Use address/CIDR notation", verbose_name="Destination Address")
84     destinationport = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchDestinationPort", verbose_name="Destination Port")
85     port = models.ManyToManyField(MatchPort, blank=True, null=True, related_name="matchPort", verbose_name="Port" )
86     dscp = models.ManyToManyField(MatchDscp, blank=True, null=True, verbose_name="DSCP")
87     fragmenttype = models.CharField(max_length=20, choices=FRAGMENT_CODES, blank=True, null=True, verbose_name="Fragment Type")
88     icmpcode = models.CharField(max_length=32, blank=True, null=True, verbose_name="ICMP Code")
89     icmptype = models.CharField(max_length=32, blank=True, null=True, verbose_name="ICMP Type")
90     packetlength = models.IntegerField(blank=True, null=True, verbose_name="Packet Length")
91     protocol = models.CharField(max_length=32, blank=True, null=True, verbose_name="Protocol")
92     tcpflag = models.CharField(max_length=128, blank=True, null=True, verbose_name="TCP flag")
93     then = models.ManyToManyField(ThenAction, verbose_name="Then")
94     filed = models.DateTimeField(auto_now_add=True)
95     last_updated = models.DateTimeField(auto_now=True)
96     status = models.CharField(max_length=20, choices=ROUTE_STATES, blank=True, null=True, verbose_name="Status", default="PENDING")
97 #    is_online = models.BooleanField(default=False)
98 #    is_active = models.BooleanField(default=False)
99     expires = models.DateField(default=days_offset, blank=True, null=True,)
100     response = models.CharField(max_length=512, blank=True, null=True)
101     comments = models.TextField(null=True, blank=True, verbose_name="Comments")
102
103     
104     def __unicode__(self):
105         return self.name
106     
107     class Meta:
108         db_table = u'route'
109     
110     def save(self, *args, **kwargs):
111         if not self.pk:
112             hash = id_gen()
113             self.name = "%s_%s" %(self.name, hash)
114         super(Route, self).save(*args, **kwargs) # Call the "real" save() method.
115
116         
117     def clean(self, *args, **kwargs):
118         from django.core.exceptions import ValidationError
119         if self.destination:
120             try:
121                 address = IPNetwork(self.destination)
122                 self.destination = address.exploded
123             except Exception:
124                 raise ValidationError('Invalid network address format at Destination Field')
125         if self.source:
126             try:
127                 address = IPNetwork(self.source)
128                 self.source = address.exploded
129             except Exception:
130                 raise ValidationError('Invalid network address format at Source Field')
131    
132     def commit_add(self, *args, **kwargs):
133         peer = self.applier.get_profile().peer.domain_name
134         send_message("[%s] Adding route %s. Please wait..." %(self.applier.username, self.name), peer)
135         response = add.delay(self)
136         logger.info("Got add job id: %s" %response)
137         
138     def commit_edit(self, *args, **kwargs):
139         peer = self.applier.get_profile().peer.domain_name
140         send_message("[%s] Editing route %s. Please wait..." %(self.applier.username, self.name), peer)
141         response = edit.delay(self)
142         logger.info("Got edit job id: %s" %response)
143
144     def commit_delete(self, *args, **kwargs):
145         reason_text = ''
146         reason = ''
147         if "reason" in kwargs:
148             reason = kwargs['reason']
149             reason_text = "Reason: %s. " %reason
150         peer = self.applier.get_profile().peer.domain_name
151         send_message("[%s] Removing route %s. %sPlease wait..." %(self.applier.username, self.name, reason_text), peer)
152         response = delete.delay(self, reason=reason)
153         logger.info("Got delete job id: %s" %response)
154
155     def has_expired(self):
156         today = datetime.date.today()
157         if today > self.expires:
158             return True
159         return False
160     
161     def check_sync(self):
162         if not self.is_synced():
163             self.status = "OUTOFSYNC"
164             self.save()
165     
166     def is_synced(self):
167         found = False
168         get_device = PR.Retriever()
169         device = get_device.fetch_device()
170         try:
171             routes = device.routing_options[0].routes
172         except Exception as e:
173             self.status = "EXPIRED"
174             self.save()
175             logger.error("No routing options on device. Exception: %s" %e)
176             return True
177         for route in routes:
178             if route.name == self.name:
179                 found = True
180                 logger.info('Found a matching route name')
181                 devicematch = route.match
182                 try:
183                     assert(self.destination)
184                     assert(devicematch['destination'][0])
185                     if self.destination == devicematch['destination'][0]:
186                         found = found and True
187                         logger.info('Found a matching destination')
188                     else:
189                         found = False
190                         logger.info('Destination fields do not match')
191                 except:
192                     pass
193                 try:
194                     assert(self.source)
195                     assert(devicematch['source'][0])
196                     if self.source == devicematch['source'][0]:
197                         found = found and True
198                         logger.info('Found a matching source')
199                     else:
200                         found = False
201                         logger.info('Source fields do not match')
202                 except:
203                     pass
204                 try:
205                     assert(self.fragmenttype)
206                     assert(devicematch['fragment'][0])
207                     if self.fragmenttype == devicematch['fragment'][0]:
208                         found = found and True
209                         logger.info('Found a matching fragment type')
210                     else:
211                         found = False
212                         logger.info('Fragment type fields do not match')
213                 except:
214                     pass
215                 try:
216                     assert(self.icmpcode)
217                     assert(devicematch['icmp-code'][0])
218                     if self.icmpcode == devicematch['icmp-code'][0]:
219                         found = found and True
220                         logger.info('Found a matching icmp code')
221                     else:
222                         found = False
223                         logger.info('Icmp code fields do not match')
224                 except:
225                     pass
226                 try:
227                     assert(self.icmptype)
228                     assert(devicematch['icmp-type'][0])
229                     if self.icmptype == devicematch['icmp-type'][0]:
230                         found = found and True
231                         logger.info('Found a matching icmp type')
232                     else:
233                         found = False
234                         logger.info('Icmp type fields do not match')
235                 except:
236                     pass
237                 try:
238                     assert(self.protocol)
239                     assert(devicematch['protocol'][0])
240                     if self.protocol == devicematch['protocol'][0]:
241                         found = found and True
242                         logger.info('Found a matching protocol')
243                     else:
244                         found = False
245                         logger.info('Protocol fields do not match')
246                 except:
247                     pass
248                 if found and self.status != "ACTIVE":
249                      logger.error('Rule is applied on device but appears as offline')
250                      self.status = "ACTIVE"
251                      self.save()
252                      found = True
253         return found
254
255     def get_then(self):
256         ret = ''
257         then_statements = self.then.all()
258         for statement in then_statements:
259             if statement.action_value:
260                 ret = "%s %s:<strong>%s</strong><br/>" %(ret, statement.action, statement.action_value)
261             else: 
262                 ret = "%s %s<br>" %(ret, statement.action)
263         return ret.rstrip(',')
264     
265     get_then.short_description = 'Then statement'
266     get_then.allow_tags = True
267 #
268     def get_match(self):
269         ret = ''
270         if self.destination:
271             ret = '%s Dst Addr:<strong>%s</strong><br/>' %(ret, self.destination)
272         if self.fragmenttype:
273             ret = "%s Fragment Type:<strong>%s</strong><br/>" %(ret, self.fragmenttype)
274         if self.icmpcode:
275             ret = "%s ICMP code:<strong>%s</strong><br/>" %(ret, self.icmpcode)
276         if self.icmptype:
277             ret = "%s ICMP Type:<strong>%s</strong><br/>" %(ret, self.icmptype)
278         if self.packetlength:
279             ret = "%s Packet Length:<strong>%s</strong><br/>" %(ret, self.packetlength)
280         if self.protocol:
281             ret = "%s Protocol:<strong>%s</strong><br/>" %(ret, self.protocol)
282         if self.source:
283             ret = "%s Src Addr:<strong>%s</strong><br/>" %(ret, self.source)
284         if self.tcpflag:
285             ret = "%s TCP flag:<strong>%s</strong><br/>" %(ret, self.tcpflag)
286         if self.port:
287             for port in self.port.all():
288                     ret = ret + "Port:<strong>%s</strong><br/>" %(port)
289         if self.destinationport:
290             for port in self.destinationport.all():
291                     ret = ret + "Dst Port:<strong>%s</strong><br/>" %(port)
292         if self.sourceport:
293             for port in self.sourceport.all():
294                     ret = ret +"Src Port:<strong>%s</strong><br/>" %(port)
295         if self.dscp:
296             for dscp in self.dscp.all():
297                     ret = ret + "%s Port:<strong>%s</strong><br/>" %(ret, dscp)
298         return ret.rstrip('<br/>')
299         
300     get_match.short_description = 'Match statement'
301     get_match.allow_tags = True
302
303 def send_message(msg, user):
304 #    username = user.username
305     peer = user
306     b = beanstalkc.Connection()
307     b.use(settings.POLLS_TUBE)
308     tube_message = json.dumps({'message': str(msg), 'username':peer})
309     b.put(tube_message)
310     b.close()