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