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):
146 if "reason" in kwargs:
147 reason = kwargs['reason']
148 reason_text = "Reason: %s. " %reason
149 peer = self.applier.get_profile().peer.domain_name
150 send_message("[%s] Removing route %s. %sPlease wait..." %(self.applier.username, self.name, reason), peer)
151 response = delete.delay(self, reason=reason)
152 logger.info("Got delete job id: %s" %response)
154 def has_expired(self):
155 today = datetime.date.today()
156 if today > self.expires:
160 def check_sync(self):
161 if not self.is_synced():
162 self.status = "OUTOFSYNC"
167 get_device = PR.Retriever()
168 device = get_device.fetch_device()
170 routes = device.routing_options[0].routes
171 except Exception as e:
172 self.status = "EXPIRED"
174 logger.error("No routing options on device. Exception: %s" %e)
177 if route.name == self.name:
179 logger.info('Found a matching route name')
180 devicematch = route.match
182 assert(self.destination)
183 assert(devicematch['destination'][0])
184 if self.destination == devicematch['destination'][0]:
185 found = found and True
186 logger.info('Found a matching destination')
189 logger.info('Destination fields do not match')
194 assert(devicematch['source'][0])
195 if self.source == devicematch['source'][0]:
196 found = found and True
197 logger.info('Found a matching source')
200 logger.info('Source fields do not match')
204 assert(self.fragmenttype)
205 assert(devicematch['fragment'][0])
206 if self.fragmenttype == devicematch['fragment'][0]:
207 found = found and True
208 logger.info('Found a matching fragment type')
211 logger.info('Fragment type fields do not match')
215 assert(self.icmpcode)
216 assert(devicematch['icmp-code'][0])
217 if self.icmpcode == devicematch['icmp-code'][0]:
218 found = found and True
219 logger.info('Found a matching icmp code')
222 logger.info('Icmp code fields do not match')
226 assert(self.icmptype)
227 assert(devicematch['icmp-type'][0])
228 if self.icmptype == devicematch['icmp-type'][0]:
229 found = found and True
230 logger.info('Found a matching icmp type')
233 logger.info('Icmp type fields do not match')
237 assert(self.protocol)
238 assert(devicematch['protocol'][0])
239 if self.protocol == devicematch['protocol'][0]:
240 found = found and True
241 logger.info('Found a matching protocol')
244 logger.info('Protocol fields do not match')
247 if found and self.status != "ACTIVE":
248 logger.error('Rule is applied on device but appears as offline')
249 self.status = "ACTIVE"
256 then_statements = self.then.all()
257 for statement in then_statements:
258 if statement.action_value:
259 ret = "%s %s:<strong>%s</strong><br/>" %(ret, statement.action, statement.action_value)
261 ret = "%s %s<br>" %(ret, statement.action)
262 return ret.rstrip(',')
264 get_then.short_description = 'Then statement'
265 get_then.allow_tags = True
270 ret = '%s Dst Addr:<strong>%s</strong><br/>' %(ret, self.destination)
271 if self.fragmenttype:
272 ret = "%s Fragment Type:<strong>%s</strong><br/>" %(ret, self.fragmenttype)
274 ret = "%s ICMP code:<strong>%s</strong><br/>" %(ret, self.icmpcode)
276 ret = "%s ICMP Type:<strong>%s</strong><br/>" %(ret, self.icmptype)
277 if self.packetlength:
278 ret = "%s Packet Length:<strong>%s</strong><br/>" %(ret, self.packetlength)
280 ret = "%s Protocol:<strong>%s</strong><br/>" %(ret, self.protocol)
282 ret = "%s Src Addr:<strong>%s</strong><br/>" %(ret, self.source)
284 ret = "%s TCP flag:<strong>%s</strong><br/>" %(ret, self.tcpflag)
286 for port in self.port.all():
287 ret = ret + "Port:<strong>%s</strong><br/>" %(port)
288 if self.destinationport:
289 for port in self.destinationport.all():
290 ret = ret + "Dst Port:<strong>%s</strong><br/>" %(port)
292 for port in self.sourceport.all():
293 ret = ret +"Src Port:<strong>%s</strong><br/>" %(port)
295 for dscp in self.dscp.all():
296 ret = ret + "%s Port:<strong>%s</strong><br/>" %(ret, dscp)
297 return ret.rstrip('<br/>')
299 get_match.short_description = 'Match statement'
300 get_match.allow_tags = True
302 def send_message(msg, user):
303 # username = user.username
305 b = beanstalkc.Connection()
306 b.use(settings.POLLS_TUBE)
307 tube_message = json.dumps({'message': str(msg), 'username':peer})