forked from Uninett/nav
/
profiles.py
1608 lines (1305 loc) · 50.4 KB
/
profiles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Uninett AS
# Copyright (C) 2022 Sikt
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 3 as published by the Free
# Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details. You should have received a copy of the GNU General Public
# License along with NAV. If not, see <http://www.gnu.org/licenses/>.
#
"""Django ORM wrapper for profiles in NAV"""
# pylint: disable=R0903
from hashlib import md5
import itertools
import logging
from datetime import datetime
import re
import json
from django.views.decorators.debug import sensitive_variables
from django.db import models, transaction
from django.urls import reverse
from django.forms.models import model_to_dict
from nav.adapters import HStoreField
import nav.buildconf
import nav.pwhash
from nav.config import getconfig as get_alertengine_config
from nav.alertengine.dispatchers import DispatcherException
from nav.alertengine.dispatchers import FatalDispatcherException
from nav.models.event import AlertQueue, AlertType, EventType
from nav.models.manage import Arp, Cam, Category, Device, Location
from nav.models.manage import Memory, Netbox, NetboxInfo, NetboxType
from nav.models.manage import Organization, Prefix, Room, NetboxGroup
from nav.models.manage import Interface, Usage, Vlan, Vendor
from nav.models.fields import VarcharField, DictAsJsonField
# This should be the authorative source as to which models alertengine
# supports. The acctuall mapping from alerts to data in these models is done
# the MatchField model.
SUPPORTED_MODELS = [
# event models
AlertQueue,
AlertType,
EventType,
# manage models
Arp,
Cam,
Category,
Device,
Location,
Memory,
Netbox,
NetboxInfo,
NetboxType,
Organization,
Prefix,
Room,
NetboxGroup,
Interface,
Vendor,
Vlan,
Usage,
]
_ = lambda a: a
#######################################################################
### Account models
class Account(models.Model):
"""NAV's basic account model"""
DEFAULT_ACCOUNT = 0
ADMIN_ACCOUNT = 1
# An overview of current preferences.
# They should start with PREFERENCE_KEY
PREFERENCE_KEY_LANGUAGE = 'language' # AlertProfiles
PREFERENCE_KEY_STATUS = 'status-preferences'
PREFERENCE_KEY_WIDGET_COLUMNS = 'widget_columns'
PREFERENCE_KEY_REPORT_PAGE_SIZE = 'report_page_size'
PREFERENCE_KEY_WIDGET_DISPLAY_DENSITY = 'widget_display_density'
PREFERENCE_KEY_IPDEVINFO_PORT_LAYOUT = 'ipdevinfo_port_layout'
# FIXME get this from setting.
MIN_PASSWD_LENGTH = 8
login = VarcharField(unique=True)
name = VarcharField()
password = VarcharField()
ext_sync = VarcharField(blank=True)
preferences = HStoreField(default=dict)
organizations = models.ManyToManyField(
Organization, db_table='accountorg', blank=True
)
# Set this in order to provide a link to the actual operator when Account
# objects are retrieved from session data
sudo_operator = None
class Meta(object):
db_table = u'account'
ordering = ('login',)
def __str__(self):
if self.sudo_operator and self.sudo_operator != self:
return '{} (operated by {})'.format(self.login, self.sudo_operator)
else:
return self.login
def get_active_profile(self):
"""Returns the account's active alert profile"""
try:
return self.alertpreference.active_profile
except (AlertPreference.DoesNotExist, AlertProfile.DoesNotExist):
pass
def get_groups(self):
"""Fetches and returns this users groups.
Also stores groups in this object for later use.
"""
try:
return self._cached_groups
except AttributeError:
self._cached_groups = self.accountgroup_set.values_list('id', flat=True)
return self._cached_groups
def get_privileges(self):
"""Fetches privileges for this users groups.
Also stores privileges in this object for later use.
"""
try:
return self._cached_privileges
except AttributeError:
self._cached_privileges = Privilege.objects.filter(
group__in=self.get_groups()
)
return self._cached_privileges
def get_tools(self):
"""Get the tool list for this account"""
return [
tool
for tool in self.accounttool_set.all().order_by('priority')
if self.has_perm('web_access', tool.tool.uri)
]
def has_perm(self, action, target):
"""Checks if user has permission to do action on target."""
groups = self.get_groups()
privileges = self.get_privileges()
if AccountGroup.ADMIN_GROUP in groups:
return True
elif privileges.count() == 0:
return False
elif action == 'web_access':
for privilege in privileges:
regexp = re.compile(privilege.target)
if regexp.search(target):
return True
return False
else:
return privileges.filter(target=target).count() > 0
def is_system_account(self):
"""Is this system (undeleteable) account?"""
return self.id < 1000
def is_default_account(self):
"""Is this the anonymous user account?"""
return self.id == self.DEFAULT_ACCOUNT
def is_admin_account(self):
"""Is this the admin account?"""
return self.id == self.ADMIN_ACCOUNT
def is_admin(self):
"""Has this user administrator rights?"""
return self.has_perm(None, None)
@sensitive_variables('password')
def set_password(self, password):
"""Sets user password. Copied from nav.db.navprofiles"""
if password.strip():
pw_hash = nav.pwhash.Hash(password=password)
self.password = str(pw_hash)
else:
self.password = ''
@sensitive_variables('password')
def check_password(self, password):
"""
Return True if the submitted authentication tokens are valid
for this Account. In simpler terms; when password
authentication is used, this method compares the given
password with the one stored for this account and returns true
if they are equal. If the stored password is blank, we
interpret this as: 'The user is not allowed to log in'
In the future, this could be extended to accept other types of
authentication tokens, such as personal certificates or
whatever.
Copied from nav.db.navprofiles
"""
if not self.locked:
try:
stored_hash = self.password_hash
except nav.pwhash.InvalidHashStringError:
# Probably an old style NAV password hash, get out
# of here and check it the old way
pass
else:
return stored_hash.verify(password)
if self.has_old_style_password_hash():
return self._verify_old_password_hash_and_rehash(password)
else:
return password == self.password
else:
return False
def has_old_style_password_hash(self):
"""Returns True if this account has an old-style, insecure password hash"""
return self.unlocked_password.startswith("md5")
def has_plaintext_password(self):
"""Returns True if this account appears to contain a plain-text password"""
if not self.has_old_style_password_hash():
try:
self.password_hash
except nav.pwhash.InvalidHashStringError:
return True
return False
def has_deprecated_password_hash_method(self):
"""Returns True if this account's password is salted hash, but using a
deprecated hashing method.
"""
if not (self.has_plaintext_password() or self.has_old_style_password_hash()):
return self.password_hash.method != nav.pwhash.DEFAULT_METHOD
return False
@sensitive_variables('password')
def _verify_old_password_hash_and_rehash(self, password):
"""Verifies an old-style MD5 password hash, and if there is a match,
the password is re-hashed using the modern and more secure method.
"""
pw_hash = md5(password.encode("utf-8"))
verified = pw_hash.hexdigest() == self.password[3:]
if verified:
self.set_password(password)
if self.pk:
Account.objects.filter(pk=self.pk).update(password=self.password)
return verified
@property
def locked(self):
return not self.password or self.password.startswith('!')
@locked.setter
def locked(self, value):
if not value and self.password.startswith('!'):
self.password = self.password[1:]
elif value and not self.password.startswith('!'):
self.password = '!' + self.password
@property
def password_hash(self):
"""Returns the Account's password as a Hash object"""
stored_hash = nav.pwhash.Hash()
stored_hash.set_hash(self.unlocked_password)
return stored_hash
@property
def unlocked_password(self):
"""Returns the raw password value, but with any lock status stripped"""
if not self.locked:
return self.password or ''
else:
return self.password[1:] if self.password else ''
def get_email_addresses(self):
return self.alertaddress_set.filter(type__name=AlertSender.EMAIL)
class AccountGroup(models.Model):
"""NAV account groups"""
# FIXME other places in code that use similiar definitions should switch to
# using this one.
ADMIN_GROUP = 1
EVERYONE_GROUP = 2
AUTHENTICATED_GROUP = 3
name = VarcharField()
description = VarcharField(db_column='descr')
# FIXME this uses a view hack, was AccountInGroup
accounts = models.ManyToManyField('Account')
class Meta(object):
db_table = u'accountgroup'
ordering = ('name',)
def __str__(self):
return self.name
def is_system_group(self):
"""Is this a system (undeleteable) group?"""
return self.id < 1000
def is_protected_group(self):
"""Is this a protected group?
Users cannot be removed from protected groups.
"""
return self.id in [self.EVERYONE_GROUP, self.AUTHENTICATED_GROUP]
def is_admin_group(self):
"""Is this the administrators group?"""
return self.id == self.ADMIN_GROUP
class NavbarLink(models.Model):
"""A hyperlink on a user's navigation bar."""
account = models.ForeignKey(
'Account', on_delete=models.CASCADE, db_column='accountid'
)
name = models.CharField('Link text', blank=False, max_length=100)
uri = models.CharField('URL', blank=False, max_length=100)
class Meta(object):
db_table = u'navbarlink'
ordering = ('id',)
def __str__(self):
return '%s=%s' % (self.name, self.uri)
class Privilege(models.Model):
"""A privilege granted to an AccountGroup."""
group = models.ForeignKey(
'AccountGroup', on_delete=models.CASCADE, db_column='accountgroupid'
)
type = models.ForeignKey(
'PrivilegeType', on_delete=models.CASCADE, db_column='privilegeid'
)
target = VarcharField()
class Meta(object):
db_table = u'accountgroupprivilege'
def __str__(self):
return '%s for %s' % (self.type, self.target)
class PrivilegeType(models.Model):
"""A registered privilege type."""
id = models.AutoField(db_column='privilegeid', primary_key=True)
name = models.CharField(max_length=30, db_column='privilegename')
class Meta(object):
db_table = u'privilege'
def __str__(self):
return self.name
class AlertAddress(models.Model):
"""Accounts alert addresses, valid types are retrived from
alertengine.conf
"""
DEBUG_MODE = False
account = models.ForeignKey(
'Account', on_delete=models.CASCADE, db_column='accountid'
)
type = models.ForeignKey('AlertSender', on_delete=models.CASCADE, db_column='type')
address = VarcharField()
class Meta(object):
db_table = u'alertaddress'
def __str__(self):
return self.type.scheme() + self.address
@transaction.atomic
def send(self, alert, subscription):
"""Handles sending of alerts to with defined alert notification types
Return value should indicate if message was sent"""
_logger = logging.getLogger('nav.alertengine.alertaddress.send')
# Determine the right language for the user.
lang = self.account.preferences.get(Account.PREFERENCE_KEY_LANGUAGE, 'en')
if not (self.address or '').strip():
_logger.error(
'Ignoring alert %d (%s: %s)! Account %s does not have an '
'address set for the alertaddress with id %d, this needs '
'to be fixed before the user will recieve any alerts.',
alert.id,
alert,
alert.netbox,
self.account,
self.id,
)
return True
if self.type.is_blacklisted():
_logger.warning(
'Not sending alert %s to %s as handler %s is blacklisted: %s',
alert.id,
self.address,
self.type,
self.type.blacklist_reason(),
)
return False
try:
self.type.send(self, alert, language=lang)
_logger.info(
'alert %d sent by %s to %s due to %s subscription %d',
alert.id,
self.type,
self.address,
subscription.get_type_display(),
subscription.id,
)
except FatalDispatcherException as error:
_logger.error(
'%s raised a FatalDispatcherException indicating that the '
'alert never will be sent: %s',
self.type,
error,
)
raise
except DispatcherException as error:
_logger.error(
'%s raised a DispatcherException indicating that an alert '
'could not be sent at this time: %s',
self.type,
error,
)
return False
except Exception as error:
_logger.exception(
'Unhandled error from %s (the handler has been blacklisted)', self.type
)
self.type.blacklist(error)
return False
return True
class AlertSender(models.Model):
"""A registered alert sender/medium."""
name = models.CharField(max_length=100)
handler = models.CharField(max_length=100)
supported = models.BooleanField(default=True)
_blacklist = {}
_handlers = {}
EMAIL = u'Email'
SMS = u'SMS'
SLACK = u'Slack'
SCHEMES = {EMAIL: u'mailto:', SMS: u'sms:', SLACK: u'slack:'}
def __str__(self):
return self.name
@transaction.atomic
def send(self, *args, **kwargs):
"""Sends an alert via this medium."""
if not self.supported:
raise FatalDispatcherException("{} is not supported".format(self.name))
if self.handler not in self._handlers:
dispatcher_class = self._load_dispatcher_class()
dispatcher = dispatcher_class(
config=AlertSender.config.get(self.handler, {})
)
self._handlers[self.handler] = dispatcher
else:
dispatcher = self._handlers[self.handler]
# Delegate sending of message
return dispatcher.send(*args, **kwargs)
def _load_dispatcher_class(self):
# Get config
if not hasattr(AlertSender, 'config'):
AlertSender.config = get_alertengine_config('alertengine.conf')
# Load module
module = __import__(
'nav.alertengine.dispatchers.%s_dispatcher' % self.handler,
globals(),
locals(),
[self.handler],
)
# Return matching object from module based on case-insensitive match
namemap = {name.lower(): obj for name, obj in vars(module).items()}
return namemap[self.handler.lower()]
def blacklist(self, reason=None):
"""Blacklists this sender/medium from further alert dispatch."""
self.__class__._blacklist[self.handler] = reason
def is_blacklisted(self):
"""Gets the blacklist status of this sender/medium."""
return self.handler in self.__class__._blacklist
def blacklist_reason(self):
"""Gets the reason for a blacklist for this sender/medium"""
return self.__class__._blacklist.get(self.handler, 'Unknown reason')
def scheme(self):
return self.SCHEMES.get(self.name, u'')
class Meta(object):
db_table = 'alertsender'
class AlertPreference(models.Model):
"""AlertProfile account preferences"""
account = models.OneToOneField(
'Account', primary_key=True, on_delete=models.CASCADE, db_column='accountid'
)
active_profile = models.OneToOneField(
'AlertProfile', on_delete=models.CASCADE, db_column='activeprofile', null=True
)
last_sent_day = models.DateTimeField(db_column='lastsentday')
last_sent_week = models.DateTimeField(db_column='lastsentweek')
class Meta(object):
db_table = u'alertpreference'
def __str__(self):
return 'preferences for %s' % self.account
#######################################################################
### Profile models
class AlertProfile(models.Model):
"""Account AlertProfiles"""
# Weekday numbers follows date.weekday(), not day.isoweekday().
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
THURSDAY = 3
FRIDAY = 4
SATURDAY = 5
SUNDAY = 6
VALID_WEEKDAYS = (
(MONDAY, _('monday')),
(TUESDAY, _('tuesday')),
(WEDNESDAY, _('wednesday')),
(THURSDAY, _('thursday')),
(FRIDAY, _('friday')),
(SATURDAY, _('saturday')),
(SUNDAY, _('sunday')),
)
account = models.ForeignKey(
'Account', on_delete=models.CASCADE, db_column='accountid'
)
name = VarcharField()
daily_dispatch_time = models.TimeField(default='08:00')
weekly_dispatch_day = models.IntegerField(choices=VALID_WEEKDAYS, default=MONDAY)
weekly_dispatch_time = models.TimeField(default='08:00')
class Meta(object):
db_table = u'alertprofile'
def __str__(self):
return self.name
def get_active_timeperiod(self):
"""Gets the currently active timeperiod for this profile"""
# Could have been done with a ModelManager, but the logic
# is somewhat tricky to do with the django ORM.
_logger = logging.getLogger(
'nav.alertengine.alertprofile.get_active_timeperiod'
)
now = datetime.now()
# Limit our query to the correct type of time periods
if now.isoweekday() in [6, 7]:
valid_during = [TimePeriod.ALL_WEEK, TimePeriod.WEEKENDS]
else:
valid_during = [TimePeriod.ALL_WEEK, TimePeriod.WEEKDAYS]
# The following code should get the currently active timeperiod.
active_timeperiod = None
timeperiods = list(
self.timeperiod_set.filter(valid_during__in=valid_during).order_by('start')
)
# If the current time is before the start of the first time
# period, the active time period is the last one (i.e. from
# the day before)
if timeperiods and timeperiods[0].start > now.time():
active_timeperiod = timeperiods[-1]
else:
for period in timeperiods:
if period.start <= now.time():
active_timeperiod = period
if active_timeperiod:
_logger.debug(
"Active timeperiod for alertprofile %d is %s (%d)",
self.id,
active_timeperiod,
active_timeperiod.id,
)
else:
_logger.debug("No active timeperiod for alertprofile %d", self.id)
return active_timeperiod
class TimePeriod(models.Model):
"""Defines TimerPeriods and which part of the week they are valid"""
ALL_WEEK = 1
WEEKDAYS = 2
WEEKENDS = 3
VALID_DURING_CHOICES = (
(ALL_WEEK, _('all days')),
(WEEKDAYS, _('weekdays')),
(WEEKENDS, _('weekends')),
)
profile = models.ForeignKey(
'AlertProfile', on_delete=models.CASCADE, db_column='alert_profile_id'
)
start = models.TimeField(db_column='start_time', default='08:00')
valid_during = models.IntegerField(choices=VALID_DURING_CHOICES, default=ALL_WEEK)
class Meta(object):
db_table = u'timeperiod'
def __str__(self):
return u'from %s for %s profile on %s' % (
self.start,
self.profile,
self.get_valid_during_display(),
)
class AlertSubscription(models.Model):
"""Links an address and timeperiod to a filtergroup with a given
subscription type.
"""
NOW = 0
DAILY = 1
WEEKLY = 2
NEXT = 3
SUBSCRIPTION_TYPES = (
(NOW, _('immediately')),
(DAILY, _('daily at predefined time')),
(WEEKLY, _('weekly at predefined time')),
(NEXT, _('at end of timeperiod')),
)
alert_address = models.ForeignKey(
'AlertAddress',
on_delete=models.CASCADE,
)
time_period = models.ForeignKey(
'TimePeriod',
on_delete=models.CASCADE,
)
filter_group = models.ForeignKey(
'FilterGroup',
on_delete=models.CASCADE,
)
type = models.IntegerField(
db_column='subscription_type', choices=SUBSCRIPTION_TYPES, default=NOW
)
ignore_resolved_alerts = models.BooleanField(default=False)
class Meta(object):
db_table = u'alertsubscription'
def delete(self):
for a in self.accountalertqueue_set.all():
a.delete()
super(AlertSubscription, self).delete()
def __str__(self):
return 'alerts received %s should be sent %s to %s' % (
self.time_period,
self.get_type_display(),
self.alert_address,
)
#######################################################################
### Equipment models
class FilterGroupContent(models.Model):
"""Defines how a given filter should be used in a filtergroup"""
# inc pos
# Add | 1 | 1 | union in set theory
# Sub | 0 | 1 | exclusion
# And | 0 | 0 | intersection in set theory
# Add inv. | 1 | 0 | complement of set
# include and positive are used to decide how the match result of the
# filter should be applied. the table above is an attempt at showing how
# this should work. Add inv is really the only tricky one, basicly it is
# nothing more that a negated add, ie if we have a filter that checks
# severity < 4 using a add inv on it is equivilent til severity >= 4.
# The actual checking of the FilterGroup is done in the alertengine
# subsystem in an attempt to keep most of the alerteninge code simple and
# in one place.
include = models.BooleanField(default=False)
positive = models.BooleanField(default=False)
priority = models.IntegerField()
filter = models.ForeignKey(
'Filter',
on_delete=models.CASCADE,
)
filter_group = models.ForeignKey(
'FilterGroup',
on_delete=models.CASCADE,
)
class Meta(object):
db_table = u'filtergroupcontent'
ordering = ['priority']
def __str__(self):
if self.include:
type_ = 'inclusive'
else:
type_ = 'exclusive'
if not self.positive:
type_ = 'inverted %s' % type_
return '%s filter on %s' % (type_, self.filter)
class Operator(models.Model):
"""Defines valid operators for a given matchfield."""
EQUALS = 0
GREATER = 1
GREATER_EQ = 2
LESS = 3
LESS_EQ = 4
NOT_EQUAL = 5
STARTSWITH = 6
ENDSWITH = 7
CONTAINS = 8
REGEXP = 9
WILDCARD = 10
IN = 11
# This list designates which operators are supported for any field. The
# only major special case is IP's which are matched with special pg ip
# operators where it makes sense, the rest of the operators are handeled
# with plain text comaparisons against the result of text(ip)
OPERATOR_TYPES = (
(EQUALS, _('equals')),
(GREATER, _('is greater')),
(GREATER_EQ, _('is greater or equal')),
(LESS, _('is less')),
(LESS_EQ, _('is less or equal')),
(NOT_EQUAL, _('not equals')),
(STARTSWITH, _('starts with')),
(ENDSWITH, _('ends with')),
(CONTAINS, _('contains')),
(REGEXP, _('regexp')),
(WILDCARD, _('wildcard (? og *)')),
(IN, _('in')),
)
# This is the mapping that is jused when we try querying the ORM to se if
# filtes match. Note that wildcard is not here as it neeeds to be special
# cased.
OPERATOR_MAPPING = {
EQUALS: '__exact',
NOT_EQUAL: '', # exclusion is special-cased by Filter.check()
GREATER: '__gt',
GREATER_EQ: '__gte',
LESS: '__lt',
LESS_EQ: '__lte',
STARTSWITH: '__istartswith',
ENDSWITH: '__iendswith',
CONTAINS: '__icontains',
REGEXP: '__iregex',
IN: '__in',
}
# The IpAddressField in django does not support ipv6 yet so the IP
# datatype needs to be completly special cased. The following operator
# mapping is used to achive this and expects that it will get '% field'
IP_OPERATOR_MAPPING = {
EQUALS: '%s = %%s',
GREATER: '%s > %%s',
GREATER_EQ: '%s >= %%s',
LESS: '%s < %%s',
LESS_EQ: '%s <= %%s',
NOT_EQUAL: '%s <> %%s',
CONTAINS: '%s >>= %%s',
IN: '%s <<= %%s',
WILDCARD: "host(%s) LIKE %%s",
REGEXP: "host(%s) ~* %%s",
STARTSWITH: "host(%s) ILIKE '%%%%' + %%s",
ENDSWITH: "host(%s) ILIKE %%s + '%%%%'",
}
type = models.IntegerField(choices=OPERATOR_TYPES, db_column='operator_id')
match_field = models.ForeignKey(
'MatchField',
on_delete=models.CASCADE,
)
class Meta(object):
db_table = u'operator'
unique_together = (('type', 'match_field'),)
def __str__(self):
return u'%s match on %s' % (self.get_type_display(), self.match_field)
def get_operator_mapping(self):
"""Returns the Django query operator represented by this instance."""
return self.OPERATOR_MAPPING[self.type]
def get_ip_operator_mapping(self):
"""Returns the SQL query IP operator represented by this instance."""
return self.IP_OPERATOR_MAPPING[self.type]
class Expression(models.Model):
"""Combines filer, operator, matchfield and value into an expression that
can be evaluated.
"""
filter = models.ForeignKey(
'Filter',
on_delete=models.CASCADE,
)
match_field = models.ForeignKey(
'MatchField',
on_delete=models.CASCADE,
)
operator = models.IntegerField(choices=Operator.OPERATOR_TYPES)
value = VarcharField()
class Meta(object):
db_table = u'expression'
def __str__(self):
return '%s match on %s against %s' % (
self.get_operator_display(),
self.match_field,
self.value,
)
def get_operator_mapping(self):
"""Returns the Django query operator represented by this expression."""
return Operator(type=self.operator).get_operator_mapping()
class Filter(models.Model):
"""One or more expressions that are combined with an and operation.
Handles the actual construction of queries to be run taking into account
special cases like the IP datatype and WILDCARD lookups."""
owner = models.ForeignKey('Account', on_delete=models.CASCADE, null=True)
name = VarcharField()
class Meta(object):
db_table = u'filter'
def __str__(self):
return self.name
def verify(self, alert):
"""Combines expressions to an ORM query that will tell us if an alert
matched.
This function builds three dicts that are used in the ORM .filter()
.exclude() and .extra() methods which finally gets a .count() as we
only need to know if something matched.
Running alertengine in debug mode will print the dicts to the logs.
:type alert: nav.models.event.AlertQueue
"""
_logger = logging.getLogger('nav.alertengine.filter.check')
filtr = {}
exclude = {}
extra = {'where': [], 'params': []}
for expression in self.expression_set.all():
# Handle IP datatypes:
if expression.match_field.data_type == MatchField.IP:
# Trick the ORM into joining the tables we want
lookup = '%s__isnull' % expression.match_field.get_lookup_mapping()
filtr[lookup] = False
where = Operator(type=expression.operator).get_ip_operator_mapping()
if expression.operator in [Operator.IN, Operator.CONTAINS]:
values = expression.value.split('|')
where = ' OR '.join(
[where % expression.match_field.value_id] * len(values)
)
extra['where'].append('(%s)' % where)
extra['params'].extend(values)
else:
# Get the IP mapping and put in the field before adding it
# to our where clause.
extra['where'].append(where % expression.match_field.value_id)
extra['params'].append(expression.value)
# Include all sublocations when matching on location
elif expression.match_field.name == 'Location':
lookup = "{}__in".format(MatchField.FOREIGN_MAP[MatchField.LOCATION])
# Location only have two Operators (in and exact) so we handle
# both with a split
locations = Location.objects.filter(pk__in=expression.value.split('|'))
# Find all descendants for locations in a totally readable way
filtr[lookup] = list(
set(
itertools.chain(
*[l.get_descendants(include_self=True) for l in locations]
)
)
)
# Handle wildcard lookups which are not directly supported by
# django (as far as i know)
elif expression.operator == Operator.WILDCARD:
# Trick the ORM into joining the tables we want
lookup = '%s__isnull' % expression.match_field.get_lookup_mapping()
filtr[lookup] = False
extra['where'].append('%s ILIKE %%s' % expression.match_field.value_id)
extra['params'].append(expression.value)
# Handle the plain lookups that we can do directly in ORM
else:
lookup = (