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"),
52 def days_offset(): return datetime.date.today() + datetime.timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
54 class MatchPort(models.Model):
55 port = models.CharField(max_length=24, unique=True)
56 def __unicode__(self):
59 db_table = u'match_port'
61 class MatchDscp(models.Model):
62 dscp = models.CharField(max_length=24)
63 def __unicode__(self):
66 db_table = u'match_dscp'
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(":")
76 db_table = u'then_action'
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")
104 def __unicode__(self):
110 def save(self, *args, **kwargs):
113 self.name = "%s_%s" %(self.name, hash)
114 super(Route, self).save(*args, **kwargs) # Call the "real" save() method.
117 def clean(self, *args, **kwargs):
118 from django.core.exceptions import ValidationError
121 address = IPNetwork(self.destination)
122 self.destination = address.exploded
124 raise ValidationError('Invalid network address format at Destination Field')
127 address = IPNetwork(self.source)
128 self.source = address.exploded
130 raise ValidationError('Invalid network address format at Source Field')
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)
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)
144 def commit_delete(self, *args, **kwargs):
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)
155 def has_expired(self):
156 today = datetime.date.today()
157 if today > self.expires:
161 def check_sync(self):
162 if not self.is_synced():
163 self.status = "OUTOFSYNC"
168 get_device = PR.Retriever()
169 device = get_device.fetch_device()
171 routes = device.routing_options[0].routes
172 except Exception as e:
173 self.status = "EXPIRED"
175 logger.error("No routing options on device. Exception: %s" %e)
178 if route.name == self.name:
180 logger.info('Found a matching route name')
181 devicematch = route.match
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')
190 logger.info('Destination fields do not match')
195 assert(devicematch['source'][0])
196 if self.source == devicematch['source'][0]:
197 found = found and True
198 logger.info('Found a matching source')
201 logger.info('Source fields do not match')
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')
212 logger.info('Fragment type fields do not match')
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')
223 logger.info('Icmp code fields do not match')
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')
234 logger.info('Icmp type fields do not match')
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')
245 logger.info('Protocol fields do not match')
248 if found and self.status != "ACTIVE":
249 logger.error('Rule is applied on device but appears as offline')
250 self.status = "ACTIVE"
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)
262 ret = "%s %s<br>" %(ret, statement.action)
263 return ret.rstrip(',')
265 get_then.short_description = 'Then statement'
266 get_then.allow_tags = True
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)
275 ret = "%s ICMP code:<strong>%s</strong><br/>" %(ret, self.icmpcode)
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)
281 ret = "%s Protocol:<strong>%s</strong><br/>" %(ret, self.protocol)
283 ret = "%s Src Addr:<strong>%s</strong><br/>" %(ret, self.source)
285 ret = "%s TCP flag:<strong>%s</strong><br/>" %(ret, self.tcpflag)
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)
293 for port in self.sourceport.all():
294 ret = ret +"Src Port:<strong>%s</strong><br/>" %(port)
296 for dscp in self.dscp.all():
297 ret = ret + "%s Port:<strong>%s</strong><br/>" %(ret, dscp)
298 return ret.rstrip('<br/>')
300 get_match.short_description = 'Match statement'
301 get_match.allow_tags = True
303 def send_message(msg, user):
304 # username = user.username
306 b = beanstalkc.Connection()
307 b.use(settings.POLLS_TUBE)
308 tube_message = json.dumps({'message': str(msg), 'username':peer})