-
Notifications
You must be signed in to change notification settings - Fork 148
/
models.py
3109 lines (2669 loc) · 126 KB
/
models.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
"""
Copyright(C) 2014-2018 Stamus Networks
Written by Eric Leblond <eleblond@stamus-networks.com>
This file is part of Scirius.
Scirius is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Scirius 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 Scirius. If not, see <http://www.gnu.org/licenses/>.
"""
from __future__ import unicode_literals
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.conf import settings
from django.core.exceptions import FieldError, SuspiciousOperation, ValidationError
from django.core.validators import validate_ipv4_address
from django.db import transaction
from django.utils import timezone
from django.utils.html import mark_safe, format_html, format_html_join
from django.db.models import Q
from idstools import rule as rule_idstools
from enum import Enum, unique
from copy import deepcopy
from collections import OrderedDict
import requests
import tempfile
import tarfile
import re
import sys
import os
import git
import shutil
import json
import IPy
from datetime import date as datetime_date
from rules.tests_rules import TestRules
from rules.validators import validate_address_or_network
from rules.filter_sets import FILTER_SETS
from django.contrib.auth.models import User
_HUNT_FILTERS = [
{
'id': 'hits_min',
'title': 'Hits min',
'placeholder': 'Minimum Hits Count',
'filterType': 'number',
'valueType': 'positiveint',
'queryType': 'rest'
},
{
'id': 'hits_max',
'title': 'Hits max',
'placeholder': 'Maximum Hits Count',
'filterType': 'number',
'valueType': 'positiveint',
'queryType': 'rest'
},
{
'id': 'ip',
'title': 'IP',
'placeholder': 'Filter by IP',
'filterType': 'text',
'valueType': 'ip',
'queryType': 'filter'
},
{
'id': 'host',
'title': 'Probe',
'placeholder': 'Filter by Probes',
'filterType': 'text',
'valueType': 'text',
'queryType': 'filter'
},
{
'id': 'msg',
'title': 'Message',
'placeholder': 'Filter by Message',
'filterType': 'text',
'valueType': 'text',
'queryType': 'filter'
},
{
'id': 'not_in_msg',
'title': 'Not in Message',
'placeholder': 'Filter by not in Message',
'filterType': 'text',
'valueType': 'text',
'queryType': 'filter'
},
{
'id': 'search',
'title': 'Content',
'placeholder': 'Filter by Content',
'filterType': 'text',
'valueType': 'text',
'queryType': 'rest'
},
{
'id': 'not_in_content',
'title': 'Not in Content',
'placeholder': 'Filter by not in Content',
'filterType': 'text',
'valueType': 'text',
'queryType': 'rest'
},
{
'id': 'alert.signature_id',
'title': 'Signature ID',
'placeholder': 'Filter by Signature ID',
'filterType': 'number',
'valueType': 'positiveint',
'queryType': 'filter'
},
{
'id': 'protocol',
'title': 'Protocol',
'placeholder': 'Filter by Protocol',
'filterType': 'complex-select-text',
'filterCategoriesPlaceholder': 'Filter by type',
'queryType': 'filter',
'filterCategories': [
{
'id': 'dns',
'title': 'DNS',
'filterValues': [
{'id': 'query.rrname', 'title': 'Query Name'},
{'id': 'query.rrtype', 'title': 'Query Type'},
]
},
{
'id': 'http',
'title': 'HTTP',
'filterValues': [
{'id': 'http_user_agent', 'title': 'User-Agent', 'placeholder': 'Filter by User Agent'},
{'id': 'hostname', 'title': 'Host', 'placeholder': 'Filter by Host'},
{'id': 'url', 'title': 'URL', 'placeholder': 'Filter by URL'},
{'id': 'status', 'title': 'Status', 'placeholder': 'Filter by Status'},
{'id': 'http_method', 'title': 'Method', 'placeholder': 'Filter by Method'},
{'id': 'http_content_type', 'title': 'Content Type', 'placeholder': 'Filter by Content Type'},
{'id': 'http_length', 'title': 'Length', 'placeholder': 'Filter by Content Length'},
]
},
{
'id': 'smtp',
'title': 'SMTP',
'filterValues': [
{'id': 'mail_from', 'title': 'From', 'placeholder': 'Filter by From'},
{'id': 'rcpt_to', 'title': 'To', 'placeholder': 'Filter by To'},
{'id': 'helo', 'title': 'Helo', 'placeholder': 'Filter by Helo'}
]
},
{
'id': 'smb',
'title': 'SMB',
'filterValues': [
{'id': 'command', 'title': 'Command', 'placeholder': 'Filter by Command'},
{'id': 'status', 'title': 'Status', 'placeholder': 'Filter by Status'},
{'id': 'filename', 'title': 'Filename', 'placeholder': 'Filter by Filename'},
{'id': 'share', 'title': 'Share', 'placeholder': 'Filter by Share'}
]
},
{
'id': 'ssh',
'title': 'SSH',
'filterValues': [
{'id': 'client.software_version', 'title': 'Client Software', 'placeholder': 'Filter by Client Software'},
{'id': 'client.proto_version', 'title': 'Client Version', 'placeholder': 'Filter by Client Version'},
{'id': 'server.software_version', 'title': 'Server Software', 'placeholder': 'Filter by Server Software'},
{'id': 'server.proto_version', 'title': 'Server Version', 'placeholder': 'Filter by Server Version'},
]
},
{
'id': 'tls',
'title': 'TLS',
'filterValues': [
{'id': 'subject', 'title': 'Subject DN', 'placeholder': 'Filter by Subject DN'},
{'id': 'issuerdn', 'title': 'Issuer DN', 'placeholder': 'Filter by Issuer DN'},
{'id': 'sni', 'title': 'Server Name Indication', 'placeholder': 'Filter by Server Name Indication'},
{'id': 'version', 'title': 'Version', 'placeholder': 'Filter by Version'},
{'id': 'fingerprint', 'title': 'Fingerprint', 'placeholder': 'Filter by Fingerprint'},
{'id': 'serial', 'title': 'Serial', 'placeholder': 'Filter by Serial'},
{'id': 'ja3.hash', 'title': 'JA3 Hash', 'placeholder': 'Filter by JA3 Hash'},
]
},
]
}
]
def get_hunt_filters():
return deepcopy(_HUNT_FILTERS)
def validate_hostname(val):
try:
validate_ipv4_address(val)
except ValidationError:
# ip may in fact be a hostname
# http://www.regextester.com/23
HOSTNAME_RX = r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$'
if not re.match(HOSTNAME_RX, val):
raise ValidationError('Invalid hostname or IP')
def validate_port(val):
try:
val = int(val)
except ValueError:
raise ValidationError('Invalid port')
def validate_proxy(val):
if val.startswith('http://') or val.startswith('https://'):
val = val.rstrip('/')
if val.startswith('http://'):
val = val[len('http://'):]
else:
val = val[len('https://'):]
if '@' in val:
login, val = val.rsplit('@', 1)
if login.count(':') < 1:
raise ValidationError('Invalid login, no password found')
if val.count(':') != 1:
raise ValidationError('Invalid address')
host, port = val.split(':')
validate_hostname(host)
validate_port(port)
def validate_url(val):
# URL validator that does not require a FQDN
if not (val.startswith('http://') or val.startswith('https://')):
raise ValidationError('Invalid scheme')
netloc = val.split('://', 1)[1]
if '/' in netloc:
netloc = netloc.split('/', 1)[0]
if ':' in netloc:
netloc, port = netloc.split(':', 1)
validate_port(port)
validate_hostname(netloc)
class FilterSet(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
content = models.TextField()
name = models.CharField(max_length=150)
page = models.CharField(max_length=25)
description = models.TextField(blank=True, null=True)
@staticmethod
def get_default_filter_sets():
return FILTER_SETS
class UserAction(models.Model):
ACTIONS = OrderedDict([
# Login/Logout
('create_user', {
'description': '{user} has created new user {new_user}',
'title': 'Create User'
}),
('edit_user', {
'description': '{user} has edited user {other_user}',
'title': 'Edit User'
}),
('edit_user_token', {
'description': '{user} has edited {other_user} token',
'title': 'Edit User Token'
}),
('edit_user_password', {
'description': '{user} has edited {other_user} password',
'title': 'Edit User Password'
}),
('delete_user', {
'description': '{user} has deleted user {old_user}',
'title': 'Delete User'
}),
('login', {
'description': 'Logged in as {user}',
'title': 'Login'
}),
('logout', {
'description': '{user} has logged out',
'title': 'Logout'
}),
# Sources:
('create_source', {
'description': '{user} has created source {source}',
'title': 'Create Source'
}),
('update_source', {
'description': '{user} has updated source {source}',
'title': 'Update Source'
}),
('edit_source', {
'description': '{user} has edited source {source}',
'title': 'Edit Source'
}),
('upload_source', {
'description': '{user} has uploaded source {source}',
'title': 'Upload Source'
}),
('enable_source', {
'description': '{user} has enabled source {source} in ruleset {ruleset}',
'title': 'Enable Source'
}),
('disable_source', {
'description': '{user} has disabled source {source} in ruleset {ruleset}',
'title': 'Disable Source'
}),
('delete_source', {
'description': '{user} has deleted source {source}',
'title': 'Delete Source'
}),
# Rulesets:
('create_ruleset', {
'description': '{user} has created ruleset {ruleset}',
'title': 'Create Ruleset'
}),
('transform_ruleset', {
'description': '{user} has transformed ruleset {ruleset} to {transformation}',
'title': 'Transform Ruleset'
}),
('edit_ruleset', {
'description': '{user} has edited ruleset {ruleset}',
'title': 'Edit Ruleset'
}),
('copy_ruleset', {
'description': '{user} has copied ruleset {ruleset}',
'title': 'Copy Ruleset'
}),
('delete_ruleset', {
'description': '{user} has deleted ruleset {ruleset}',
'title': 'Delete Ruleset'
}),
# Categories:
('enable_category', {
'description': '{user} has enabled category {category} in ruleset {ruleset}',
'title': 'Enable Category'
}),
('transform_category', {
'description': '{user} has transformed category {category} to {transformation} in ruleset {ruleset}',
'title': 'Transform Category'
}),
('disable_category', {
'description': '{user} has disabled category {category} in ruleset {ruleset}',
'title': 'Disable Category'
}),
# Rules:
('enable_rule', {
'description': '{user} has enabled rule {rule} in ruleset {ruleset}',
'title': 'Enable Rule'
}),
('comment_rule', {
'description': '{user} has commented rule {rule}',
'title': 'Comment Rule'
}),
('transform_rule', {
'description': '{user} has transformed rule {rule} to {transformation} in ruleset {ruleset}',
'title': 'Transform Rule'
}),
('suppress_rule', {
'description': '{user} has suppressed rule {rule} in ruleset {ruleset}',
'title': 'Suppress Rule'
}),
('disable_rule', {
'description': '{user} has disabled rule {rule} in ruleset {ruleset}',
'title': 'Disable Rule'
}),
('delete_suppress_rule', {
'description': '{user} has deleted suppressed rule {rule} in ruleset {ruleset}',
'title': 'Delete Suppress Rule'
}),
# Toggle availability
('toggle_availability', {
'description': '{user} has modified rule availability {rule}',
'title': 'Toggle Availability'
}),
# Thresholds:
('create_threshold', {
'description': '{user} has created threshold on rule {rule} in ruleset {ruleset}',
'title': 'Create Threshold'
}),
('edit_threshold', {
'description': '{user} has edited threshold {threshold} on rule {rule} in ruleset {ruleset}',
'title': 'Edit Threshold'
}),
('delete_threshold', {
'description': '{user} has deleted threshold {threshold} on rule {rule} in ruleset {ruleset}',
'title': 'Delete Threshold'
}),
# Used only in REST API
('delete_transform_ruleset', {
'description': '{user} has deleted transformation {transformation} on ruleset {ruleset}',
'title': 'Deleted Ruleset Transformation'
}),
('delete_transform_rule', {
'description': '{user} has deleted transformation {transformation} on rule {rule} in ruleset {ruleset}',
'title': 'Delete Rule Transformation'
}),
('delete_transform_category', {
'description': '{user} has deleted transformation {transformation} on category {category} in ruleset {ruleset}',
'title': 'Delete Category Transformation'
}),
# End REST API
# Suricata
('edit_suricata', {
'description': '{user} has edited suricata',
'title': 'Edit Suricata'
}),
('create_suricata', {
'description': '{user} has created suricata',
'title': 'Create Suricata'
}),
('update_push_all', {
'description': '{user} has pushed ruleset {ruleset}',
'title': 'Update/Push ruleset'
}),
# Settings
('system_settings', {
'description': '{user} has edited system settings',
'title': 'Edit System Settings'
}),
('delete_alerts', {
'description': '{user} has deleted alerts from rule {rule}',
'title': 'Delete Alerts'
}),
# Rule processing filter
('create_rule_filter', {
'description': '{user} has created rule filter {rule_filter}',
'title': 'Create rule filter'
}),
('edit_rule_filter', {
'description': '{user} has edited rule filter {rule_filter}',
'title': 'Edit rule filter'
}),
('delete_rule_filter', {
'description': '{user} has deleted rule filter {rule_filter}',
'title': 'Delete rule filter'
})
])
action_type = models.CharField(max_length=1000, null=True)
date = models.DateTimeField('event date', default=timezone.now)
comment = models.TextField(null=True, blank=True)
user = models.ForeignKey(User, default=None, on_delete=models.SET_NULL, null=True, blank=True)
username = models.CharField(max_length=150)
ua_objects = GenericRelation('UserActionObject', related_query_name='ua_objects')
# Compatibilty
description = models.CharField(max_length=1512, null=True)
def __init__(self, *args, **kwargs):
super(UserAction, self).__init__(*args, **kwargs)
if not self.username and self.user:
self.username = self.user.username
def __unicode__(self):
return self.generate_description()
@classmethod
def create(cls, **kwargs):
if 'action_type' not in kwargs:
raise Exception('Cannot create UserAction without "action_type"')
force_insert = True if 'force_insert' in kwargs and kwargs.pop('force_insert') else False
# UserAction
ua_params = {}
for param in ('action_type', 'comment', 'user'):
if param in kwargs:
ua_params[param] = kwargs.pop(param)
ua = cls(**ua_params)
ua.save(force_insert)
# UserActionObject
for action_key, action_value in kwargs.iteritems():
ua_obj_params = {
'action_key': action_key,
'action_value': unicode(action_value)[:100],
'user_action': ua,
}
if not isinstance(action_value, (str, unicode,)):
ua_obj_params['content'] = action_value
ua_obj = UserActionObject(**ua_obj_params)
ua_obj.save()
# Used as test
ua.generate_description()
# Warning; do not remove.
# hack callback is called after UserAction.save is called. So the
# 2nd save will trigger the callback, once UserActionObject
# have been created
ua.save()
def generate_description(self):
if self.description:
return self.description
from scirius.utils import get_middleware_module
actions_dict = get_middleware_module('common').get_user_actions_dict()
if self.action_type not in actions_dict.keys():
raise Exception('Unknown action type "%s"' % self.action_type)
format_ = {'user': format_html('<strong>{}</strong>', self.username), 'datetime': self.date}
actions = UserActionObject.objects.filter(user_action=self).all()
for action in actions:
if action.content and hasattr(action.content, 'get_absolute_url'):
format_[action.action_key] = format_html('<a href="{}"><strong>{}</strong></a>',
action.content.get_absolute_url(),
action.action_value)
else:
format_[action.action_key] = format_html('<strong>{}</strong>', action.action_value)
try:
html = format_html(actions_dict[self.action_type]['description'], **format_)
except KeyError as e:
# bug compatibility: workaround for action_value > 100
# UserActionObjects related to UserAction (self) were
# not inserted on creation
html = ''
return html
def get_title(self):
if self.description:
return self.description[:15]
from scirius.utils import get_middleware_module
actions_dict = get_middleware_module('common').get_user_actions_dict()
if self.action_type not in actions_dict.keys():
raise Exception('Unknown action type "%s"' % self.action_type)
return actions_dict[self.action_type]['title']
@staticmethod
def get_icon():
return 'pficon-user'
def get_icons(self):
from scirius.utils import get_middleware_module
actions_dict = get_middleware_module('common').get_user_actions_dict()
actions = UserActionObject.objects.filter(user_action=self).all()
icons = [(self.get_icon(), self.username)]
for action in actions:
# ==== Coner cases
# transformation is str type
# or workaround for UserAction which can contains no instance but str (ex: create a source without a ruleset)
if action.action_key == 'transformation' or (action.action_key == 'ruleset' and action.action_value == 'No Ruleset'):
continue
ct = action.content_type
klass = ct.model_class()
if hasattr(klass, 'get_icon'):
lb = action.action_value
icon = klass.get_icon()
instances = klass.objects.filter(pk=action.object_id).all()
if len(instances):
if isinstance(instances[0], Source):
icon = Source.get_icon(instances[0])
if isinstance(instances[0], Rule):
lb = instances[0].pk
icons.append((icon, lb))
html = format_html_join(
'\n', '<div class="list-view-pf-additional-info-item"><span class="fa {}"></span>{}</div>',
((icon, klass_name) for icon, klass_name in icons)
)
return html
@staticmethod
def get_user_actions_dict():
return deepcopy(UserAction.ACTIONS)
class SystemSettings(models.Model):
use_http_proxy = models.BooleanField(default=False)
http_proxy = models.CharField(max_length=200, validators=[validate_proxy], default="", blank=True,
help_text='Proxy address of the form "host:port".')
https_proxy = models.CharField(max_length=200, validators=[validate_proxy], default="", blank=True)
use_elasticsearch = models.BooleanField(default=True)
custom_elasticsearch = models.BooleanField(default=False)
elasticsearch_url = models.CharField(max_length=200, validators=[validate_url], blank=True,
default='http://elasticsearch:9200/')
def get_proxy_params(self):
if self.use_http_proxy:
return { 'http': self.http_proxy, 'https': self.https_proxy }
else:
return None
def get_system_settings():
gsettings = SystemSettings.objects.all()
if len(gsettings):
return gsettings[0]
else:
gsettings = SystemSettings.objects.create()
if settings.USE_ELASTICSEARCH:
gsettings.use_elasticsearch = True
else:
gsettings.use_elasticsearch = False
if settings.USE_PROXY:
gsettings.use_http_proxy = True
gsettings.http_proxy = settings.PROXY_PARAMS['http']
gsettings.https_proxy = settings.PROXY_PARAMS['https']
else:
gsettings.use_http_proxy = False
gsettings.save()
return gsettings
ES_ADDRESS = None
def get_es_address():
global ES_ADDRESS
if ES_ADDRESS is not None:
return ES_ADDRESS
gsettings = get_system_settings()
if gsettings.custom_elasticsearch:
addr = gsettings.elasticsearch_url
if not addr.endswith('/'):
addr += '/'
ES_ADDRESS = addr
else:
ES_ADDRESS = 'http://%s/' % settings.ELASTICSEARCH_ADDRESS
return ES_ADDRESS
def reset_es_address():
global ES_ADDRESS
ES_ADDRESS = None
def get_es_path(path):
return get_es_address() + path.lstrip('/')
class Source(models.Model):
FETCH_METHOD = (
('http', 'HTTP URL'),
# ('https', 'HTTPS URL'),
('local', 'Upload'),
)
CONTENT_TYPE = (
('sigs', 'Signatures files in tar archive'),
('sig', 'Individual Signatures file'),
# ('iprep', 'IP reputation files'),
('other', 'Other content'),
)
TMP_DIR = "/tmp/"
name = models.CharField(max_length=100, unique = True)
created_date = models.DateTimeField('date created')
updated_date = models.DateTimeField('date updated', blank = True, null = True)
method = models.CharField(max_length=10, choices=FETCH_METHOD)
datatype = models.CharField(max_length=10, choices=CONTENT_TYPE)
uri = models.CharField(max_length=400, blank = True, null = True)
cert_verif = models.BooleanField('Check certificates', default=True)
authkey = models.CharField(max_length=400, blank = True, null = True)
cats_count = models.IntegerField(default = 0)
rules_count = models.IntegerField(default = 0)
public_source = models.CharField(max_length=100, blank = True, null = True)
use_iprep = models.BooleanField('Use IP reputation for group signatures', default=True)
editable = True
# git repo where we store the physical thing
# this allow to store the different versions
# and to checkout the sources to a given version
# for ruleset generation
# Operations
# - Create
# - Delete
# - Update: only custom one
# Use method to get new files and commit them
# Create a new SourceAtVersion when there is a real update
# In case of upload: simply propose user upload form
def __init__(self, *args, **kwargs):
models.Model.__init__(self, *args, **kwargs)
if (self.method == 'http'):
self.update_ruleset = self.update_ruleset_http
else:
self.update_ruleset = None
self.first_run = False
self.updated_rules = {"added": [], "deleted": [], "updated": []}
if len(Flowbit.objects.filter(source = self)) == 0:
self.init_flowbits = True
else:
self.init_flowbits = False
@staticmethod
def get_icon(instance=None):
if instance:
if instance.method == 'http':
return 'fa fa-external-link list-view-pf-icon-sm'
return 'pficon pficon-volume list-view-pf-icon-sm'
def delete(self):
self.needs_test()
# delete git tree
source_git_dir = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, unicode(self.pk))
try:
shutil.rmtree(source_git_dir)
# Ignore error if not present
except OSError:
pass
# delete model
models.Model.delete(self)
def __unicode__(self):
return self.name
def aggregate_update(self, update):
self.updated_rules["added"] = list(set(self.updated_rules["added"]).union(set(update["added"])))
self.updated_rules["deleted"] = list(set(self.updated_rules["deleted"]).union(set(update["deleted"])))
self.updated_rules["updated"] = list(set(self.updated_rules["updated"]).union(set(update["updated"])))
def get_categories(self):
source_git_dir = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, unicode(self.pk))
catname = re.compile("(.+)\.rules$")
existing_rules_hash = {}
for rule in Rule.objects.all().prefetch_related('category'):
existing_rules_hash[rule.sid] = rule
for f in os.listdir(os.path.join(source_git_dir, 'rules')):
if f.endswith('.rules'):
match = catname.search(f)
name = match.groups()[0]
category = Category.objects.filter(source = self, name = name)
if not category:
category = Category.objects.create(source = self,
name = name, created_date = timezone.now(),
filename = os.path.join('rules', f))
else:
category = category[0]
category.get_rules(self, existing_rules_hash = existing_rules_hash)
# get rules in this category
for category in Category.objects.filter(source = self):
if not os.path.isfile(os.path.join(source_git_dir, category.filename)):
category.delete()
def get_git_repo(self, delete = False):
# check if git tree is in place
source_git_dir = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, unicode(self.pk))
if not os.path.isdir(source_git_dir):
if os.path.isfile(source_git_dir):
raise OSError("git-sources is not a directory")
os.makedirs(source_git_dir)
repo = git.Repo.init(source_git_dir)
config = repo.config_writer()
config.set_value("user", "email", "scirius@stamus-networks.com")
config.set_value("user", "name", "Scirius")
del(config)
del(repo)
repo = git.Repo(source_git_dir)
self.first_run = True
else:
if delete:
try:
shutil.rmtree(os.path.join(source_git_dir, "rules"))
except OSError:
print("Can not delete directory")
pass
repo = git.Repo(source_git_dir)
return repo
def create_sourceatversion(self, version='HEAD'):
# look for SourceAtVersion with name and HEAD
# Update updated_date
sversions = SourceAtVersion.objects.filter(source = self, version = version)
if sversions:
sversions[0].updated_date = self.updated_date
sversions[0].save()
else:
sversion = SourceAtVersion.objects.create(source = self, version = version,
updated_date = self.updated_date, git_version = version)
def handle_rules_in_tar(self, f):
f.seek(0)
if (not tarfile.is_tarfile(f.name)):
raise OSError("Invalid tar file")
self.updated_date = timezone.now()
self.first_run = False
repo = self.get_git_repo(delete = True)
f.seek(0)
# extract file
tfile = tarfile.open(fileobj=f)
dir_list = []
rules_dir = None
for member in tfile.getmembers():
# only file and dir are allowed
if not (member.isfile() or member.isdir()):
raise SuspiciousOperation("Suspect tar file contains non regular file '%s'" % (member.name))
if member.name.startswith('/') or '..' in member.name:
raise SuspiciousOperation("Suspect tar file contains invalid path '%s'" % (member.name))
# don't allow tar file with file in root dir
if member.isfile() and not '/' in member.name:
raise SuspiciousOperation("Suspect tar file contains file in root directory '%s' instead of under 'rules' directory" % (member.name))
if member.isdir() and ('/' + member.name).endswith('/rules'):
if rules_dir:
raise SuspiciousOperation("Tar file contains two 'rules' directory instead of one")
dir_list.append(member)
rules_dir = member.name
if member.isfile() and member.name.split('/')[-2] == 'rules':
dir_list.append(member)
if rules_dir == None:
raise SuspiciousOperation("Tar file does not contain a 'rules' directory")
source_git_dir = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, unicode(self.pk))
tfile.extractall(path=source_git_dir, members = dir_list)
if "/" in rules_dir:
shutil.move(os.path.join(source_git_dir, rules_dir), os.path.join(source_git_dir, 'rules'))
shutil.rmtree(os.path.join(source_git_dir, rules_dir.split('/')[0]))
index = repo.index
if len(index.diff(None)) or self.first_run:
os.environ['USERNAME'] = 'scirius'
index.add(['rules'])
message = 'source version at %s' % (self.updated_date)
index.commit(message)
self.save()
# Now we must update SourceAtVersion for this source
# or create it if needed
self.create_sourceatversion()
# Get categories
self.get_categories()
def handle_other_file(self, f):
self.updated_date = timezone.now()
self.first_run = False
repo = self.get_git_repo(delete = True)
rules_dir = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, unicode(self.pk), 'rules')
# create rules dir if needed
if not os.path.isdir(rules_dir):
os.makedirs(rules_dir)
# copy file content to target
f.seek(0)
os.fsync(f)
shutil.copy(f.name, os.path.join(rules_dir, self.name))
index = repo.index
if len(index.diff(None)) or self.first_run:
os.environ['USERNAME'] = 'scirius'
index.add(['rules'])
message = 'source version at %s' % (self.updated_date)
index.commit(message)
self.save()
# Now we must update SourceAtVersion for this source
# or create it if needed
self.create_sourceatversion()
def handle_rules_file(self, f):
f.seek(0)
if (tarfile.is_tarfile(f.name)):
raise OSError("This is a tar file and not a individual signature file, please select another category")
f.seek(0)
self.updated_date = timezone.now()
self.first_run = False
repo = self.get_git_repo(delete = True)
rules_dir = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, unicode(self.pk), 'rules')
# create rules dir if needed
if not os.path.isdir(rules_dir):
os.makedirs(rules_dir)
# copy file content to target
f.seek(0)
os.fsync(f)
shutil.copy(f.name, os.path.join(rules_dir, 'sigs.rules'))
index = repo.index
if len(index.diff(None)) or self.first_run:
os.environ['USERNAME'] = 'scirius'
index.add(["rules"])
message = 'source version at %s' % (self.updated_date)
index.commit(message)
self.save()
# Now we must update SourceAtVersion for this source
# or create it if needed
self.create_sourceatversion()
# category based on filename
category = Category.objects.filter(source = self, name = ('%s Sigs' % (self.name))[:100])
if not category:
category = Category.objects.create(source = self,
name = ('%s Sigs' % (self.name))[:100], created_date = timezone.now(),
filename = os.path.join('rules', 'sigs.rules'))
category.get_rules(self)
else:
category[0].get_rules(self)
def json_rules_list(self, rlist):
rules = []
for rule in rlist:
rules.append({"sid":rule.sid, "msg": rule.msg,
"category": rule.category.name,
"pk": rule.pk })
# for each rule we create a json object sid + msg + content
return rules
def create_update(self):
# for each set
update = {}
update["deleted"] = self.json_rules_list(self.updated_rules["deleted"])
update["added"] = self.json_rules_list(self.updated_rules["added"])
update["updated"] = self.json_rules_list(self.updated_rules["updated"])
repo = self.get_git_repo(delete = False)
sha = repo.heads.master.log()[-1].newhexsha
SourceUpdate.objects.create(
source = self,
created_date = timezone.now(),
data = json.dumps(update),
version = sha,
changed = len(update["deleted"]) + len(update["added"]) + len(update["updated"]),
)
def build_counters(self):
cats = Category.objects.filter(source = self)
self.cats_count = len(cats)
self.rules_count = len(Rule.objects.filter(category__in = cats))
self.save()
# This method cannot be called twice consecutively
@transaction.atomic
def update(self):
# look for categories list: if none, first import
categories = Category.objects.filter(source = self)
firstimport = False
if not categories:
firstimport = True
if not self.method in ['http', 'local']:
raise FieldError("Currently unsupported method")
if self.update_ruleset:
f = tempfile.NamedTemporaryFile(dir=self.TMP_DIR)
self.update_ruleset(f)
if self.datatype == 'sigs':
self.handle_rules_in_tar(f)
elif self.datatype == 'sig':
self.handle_rules_file(f)
elif self.datatype == 'other':
self.handle_other_file(f)
if not self.datatype == 'other' and not firstimport:
self.create_update()
for rule in self.updated_rules["deleted"]:
rule.delete()
self.needs_test()
def diff(self):
source_git_dir = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, unicode(self.pk))
if not os.path.isdir(source_git_dir):
raise IOError("You have to update source first")
repo = git.Repo(source_git_dir)