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