1 # -*- coding: utf-8 -*- vim:encoding=utf-8:
2 # vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
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
11 from flowspec.tasks import *
12 from time import sleep
14 from flowspy.utils import beanstalkc
15 from flowspy.utils.randomizer import id_generator as id_gen
18 FORMAT = '%(asctime)s %(levelname)s: %(message)s'
19 logging.basicConfig(format=FORMAT)
20 logger = logging.getLogger(__name__)
21 logger.setLevel(logging.DEBUG)
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")
34 ("discard", "Discard"),
35 ("community", "Community"),
36 ("next-term", "Next term"),
37 ("routing-instance", "Routing Instance"),
38 ("rate-limit", "Rate limit"),
45 ("EXPIRED", "EXPIRED"),
46 ("PENDING", "PENDING"),
47 ("OUTOFSYNC", "OUTOFSYNC"),
48 ("INACTIVE", "INACTIVE"),
49 ("ADMININACTIVE", "ADMININACTIVE"),
53 def days_offset(): return datetime.date.today() + datetime.timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
55 class MatchPort(models.Model):
56 port = models.CharField(max_length=24, unique=True)
57 def __unicode__(self):
60 db_table = u'match_port'
62 class MatchDscp(models.Model):
63 dscp = models.CharField(max_length=24)
64 def __unicode__(self):
67 db_table = u'match_dscp'
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(":")
77 db_table = u'then_action'
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")
105 def __unicode__(self):
110 verbose_name = "Rule"
111 verbose_name_plural = "Rules"
113 def save(self, *args, **kwargs):
116 self.name = "%s_%s" %(self.name, hash)
117 super(Route, self).save(*args, **kwargs) # Call the "real" save() method.
120 def clean(self, *args, **kwargs):
121 from django.core.exceptions import ValidationError
124 address = IPNetwork(self.destination)
125 self.destination = address.exploded
127 raise ValidationError('Invalid network address format at Destination Field')
130 address = IPNetwork(self.source)
131 self.source = address.exploded
133 raise ValidationError('Invalid network address format at Source Field')
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)
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)
147 def commit_delete(self, *args, **kwargs):
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)
158 def has_expired(self):
159 today = datetime.date.today()
160 if today > self.expires:
164 def check_sync(self):
165 if not self.is_synced():
166 self.status = "OUTOFSYNC"
171 get_device = PR.Retriever()
172 device = get_device.fetch_device()
174 routes = device.routing_options[0].routes
175 except Exception as e:
176 self.status = "EXPIRED"
178 logger.error("No routing options on device. Exception: %s" %e)
181 if route.name == self.name:
183 logger.info('Found a matching route name')
184 devicematch = route.match
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')
193 logger.info('Destination fields do not match')
198 assert(devicematch['source'][0])
199 if self.source == devicematch['source'][0]:
200 found = found and True
201 logger.info('Found a matching source')
204 logger.info('Source fields do not match')
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')
215 logger.info('Fragment type fields do not match')
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')
226 logger.info('Icmp code fields do not match')
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')
237 logger.info('Icmp type fields do not match')
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')
248 logger.info('Protocol fields do not match')
251 if found and self.status != "ACTIVE":
252 logger.error('Rule is applied on device but appears as offline')
253 self.status = "ACTIVE"
256 if not found and self.status == "ADMININACTIVE":
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)
267 ret = "%s %s<br>" %(ret, statement.action)
268 return ret.rstrip(',')
270 get_then.short_description = 'Then statement'
271 get_then.allow_tags = True
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)
280 ret = "%s ICMP code:<strong>%s</strong><br/>" %(ret, self.icmpcode)
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)
286 ret = "%s Protocol:<strong>%s</strong><br/>" %(ret, self.protocol)
288 ret = "%s Src Addr:<strong>%s</strong><br/>" %(ret, self.source)
290 ret = "%s TCP flag:<strong>%s</strong><br/>" %(ret, self.tcpflag)
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)
298 for port in self.sourceport.all():
299 ret = ret +"Src Port:<strong>%s</strong><br/>" %(port)
301 for dscp in self.dscp.all():
302 ret = ret + "%s Port:<strong>%s</strong><br/>" %(ret, dscp)
303 return ret.rstrip('<br/>')
305 get_match.short_description = 'Match statement'
306 get_match.allow_tags = True
309 def applier_peer(self):
311 applier_peer = self.applier.get_profile().peer
316 def send_message(msg, user):
317 # username = user.username
319 b = beanstalkc.Connection()
320 b.use(settings.POLLS_TUBE)
321 tube_message = json.dumps({'message': str(msg), 'username':peer})