-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmodels.py
executable file
·3529 lines (2943 loc) · 162 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
import base64
import hashlib
import logging
import os
import re
from uuid import uuid4
from django.conf import settings
from auditlog.registry import auditlog
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.db import models
from django_extensions.db.models import TimeStampedModel
from django.utils.deconstruct import deconstructible
from django.utils.timezone import now
from django.utils.functional import cached_property
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToCover
from django.utils import timezone
from pytz import all_timezones
from polymorphic.models import PolymorphicModel
from multiselectfield import MultiSelectField
from django import forms
from django.utils.translation import gettext as _
from dateutil.relativedelta import relativedelta
from tagulous.models import TagField
import tagulous.admin
logger = logging.getLogger(__name__)
deduplicationLogger = logging.getLogger("dojo.specific-loggers.deduplication")
@deconstructible
class UniqueUploadNameProvider:
"""
A callable to be passed as upload_to parameter to FileField.
Uploaded files will get random names based on UUIDs inside the given directory;
strftime-style formatting is supported within the directory path. If keep_basename
is True, the original file name is prepended to the UUID. If keep_ext is disabled,
the filename extension will be dropped.
"""
def __init__(self, directory=None, keep_basename=False, keep_ext=True):
self.directory = directory
self.keep_basename = keep_basename
self.keep_ext = keep_ext
def __call__(self, model_instance, filename):
base, ext = os.path.splitext(filename)
filename = "%s_%s" % (base, uuid4()) if self.keep_basename else str(uuid4())
if self.keep_ext:
filename += ext
if self.directory is None:
return filename
return os.path.join(now().strftime(self.directory), filename)
class Regulation(models.Model):
PRIVACY_CATEGORY = 'privacy'
FINANCE_CATEGORY = 'finance'
EDUCATION_CATEGORY = 'education'
MEDICAL_CATEGORY = 'medical'
CORPORATE_CATEGORY = 'corporate'
OTHER_CATEGORY = 'other'
CATEGORY_CHOICES = (
(PRIVACY_CATEGORY, _('Privacy')),
(FINANCE_CATEGORY, _('Finance')),
(EDUCATION_CATEGORY, _('Education')),
(MEDICAL_CATEGORY, _('Medical')),
(CORPORATE_CATEGORY, _('Corporate')),
(OTHER_CATEGORY, _('Other')),
)
name = models.CharField(max_length=128, unique=True, help_text=_('The name of the regulation.'))
acronym = models.CharField(max_length=20, unique=True, help_text=_('A shortened representation of the name.'))
category = models.CharField(max_length=9, choices=CATEGORY_CHOICES, help_text=_('The subject of the regulation.'))
jurisdiction = models.CharField(max_length=64, help_text=_('The territory over which the regulation applies.'))
description = models.TextField(blank=True, help_text=_('Information about the regulation\'s purpose.'))
reference = models.URLField(blank=True, help_text=_('An external URL for more information.'))
class Meta:
ordering = ['name']
def __str__(self):
return self.acronym + ' (' + self.jurisdiction + ')'
class System_Settings(models.Model):
enable_auditlog = models.BooleanField(
default=True,
blank=False,
verbose_name='Enable audit logging',
help_text="With this setting turned on, Dojo maintains an audit log "
"of changes made to entities (Findings, Tests, Engagements, Procuts, ...)"
"If you run big import you may want to disable this "
"because the way django-auditlog currently works, there's a "
"big performance hit. Especially during (re-)imports.")
enable_deduplication = models.BooleanField(
default=False,
blank=False,
verbose_name='Deduplicate findings',
help_text="With this setting turned on, Dojo deduplicates findings by "
"comparing endpoints, cwe fields, and titles. "
"If two findings share a URL and have the same CWE or "
"title, Dojo marks the less recent finding as a duplicate. "
"When deduplication is enabled, a list of "
"deduplicated findings is added to the engagement view.")
delete_dupulicates = models.BooleanField(default=False, blank=False, help_text="Requires next setting: maximum number of duplicates to retain.")
max_dupes = models.IntegerField(blank=True, null=True, default=10,
verbose_name='Max Duplicates',
help_text="When enabled, if a single "
"issue reaches the maximum "
"number of duplicates, the "
"oldest will be deleted. Duplicate will not be deleted when left empty. A value of 0 will remove all duplicates.")
enable_jira = models.BooleanField(default=False,
verbose_name='Enable JIRA integration',
blank=False)
enable_jira_web_hook = models.BooleanField(default=False,
verbose_name='Enable JIRA web hook',
help_text='Please note: It is strongly recommended to use a secret below and / or IP whitelist the JIRA server using a proxy such as Nginx.',
blank=False)
disable_jira_webhook_secret = models.BooleanField(default=False,
verbose_name='Disable web hook secret',
help_text='Allows incoming requests without a secret (discouraged legacy behaviour)',
blank=False)
# will be set to random / uuid by initializer so null needs to be True
jira_webhook_secret = models.CharField(max_length=64, blank=False, null=True, verbose_name='JIRA Webhook URL',
help_text='Secret needed in URL for incoming JIRA Webhook')
jira_choices = (('Critical', 'Critical'),
('High', 'High'),
('Medium', 'Medium'),
('Low', 'Low'),
('Info', 'Info'))
jira_minimum_severity = models.CharField(max_length=20, blank=True,
null=True, choices=jira_choices,
default='Low')
jira_labels = models.CharField(max_length=200, blank=True, null=True,
help_text='JIRA issue labels space seperated')
enable_github = models.BooleanField(default=False,
verbose_name='Enable GITHUB integration',
blank=False)
enable_slack_notifications = \
models.BooleanField(default=False,
verbose_name='Enable Slack notifications',
blank=False)
slack_channel = models.CharField(max_length=100, default='', blank=True,
help_text='Optional. Needed if you want to send global notifications.')
slack_token = models.CharField(max_length=100, default='', blank=True,
help_text='Token required for interacting '
'with Slack. Get one at '
'https://api.slack.com/tokens')
slack_username = models.CharField(max_length=100, default='', blank=True,
help_text='Optional. Will take your bot name otherwise.')
enable_msteams_notifications = \
models.BooleanField(default=False,
verbose_name='Enable Microsoft Teams notifications',
blank=False)
msteams_url = models.CharField(max_length=400, default='', blank=True,
help_text='The full URL of the '
'incoming webhook')
enable_mail_notifications = models.BooleanField(default=False, blank=False)
mail_notifications_from = models.CharField(max_length=200,
default='from@example.com',
blank=True)
mail_notifications_to = models.CharField(max_length=200, default='',
blank=True)
s_finding_severity_naming = \
models.BooleanField(default=False, blank=False,
help_text='With this setting turned on, Dojo '
'will display S0, S1, S2, etc in most '
'places, whereas if turned off '
'Critical, High, Medium, etc will '
'be displayed.')
false_positive_history = models.BooleanField(default=False, help_text="DefectDojo will automatically mark the finding as a false positive if the finding has been previously marked as a false positive. Not needed when using deduplication, advised to not combine these two.")
url_prefix = models.CharField(max_length=300, default='', blank=True, help_text="URL prefix if DefectDojo is installed in it's own virtual subdirectory.")
team_name = models.CharField(max_length=100, default='', blank=True)
time_zone = models.CharField(max_length=50,
choices=[(tz, tz) for tz in all_timezones],
default='UTC', blank=False)
display_endpoint_uri = models.BooleanField(default=False, verbose_name="Display Endpoint Full URI", help_text="Displays the full endpoint URI in the endpoint view.")
enable_product_grade = models.BooleanField(default=False, verbose_name="Enable Product Grading", help_text="Displays a grade letter next to a product to show the overall health.")
product_grade = models.CharField(max_length=800, blank=True)
product_grade_a = models.IntegerField(default=90,
verbose_name="Grade A",
help_text="Percentage score for an "
"'A' >=")
product_grade_b = models.IntegerField(default=80,
verbose_name="Grade B",
help_text="Percentage score for a "
"'B' >=")
product_grade_c = models.IntegerField(default=70,
verbose_name="Grade C",
help_text="Percentage score for a "
"'C' >=")
product_grade_d = models.IntegerField(default=60,
verbose_name="Grade D",
help_text="Percentage score for a "
"'D' >=")
product_grade_f = models.IntegerField(default=59,
verbose_name="Grade F",
help_text="Percentage score for an "
"'F' <=")
enable_benchmark = models.BooleanField(
default=True,
blank=False,
verbose_name="Enable Benchmarks",
help_text="Enables Benchmarks such as the OWASP ASVS "
"(Application Security Verification Standard)")
enable_template_match = models.BooleanField(
default=False,
blank=False,
verbose_name="Enable Remediation Advice",
help_text="Enables global remediation advice and matching on CWE and Title. The text will be replaced for mitigation, impact and references on a finding. Useful for providing consistent impact and remediation advice regardless of the scanner.")
engagement_auto_close = models.BooleanField(
default=False,
blank=False,
verbose_name="Enable Engagement Auto-Close",
help_text="Closes an engagement after 3 days (default) past due date including last update.")
engagement_auto_close_days = models.IntegerField(
default=3,
blank=False,
verbose_name="Engagement Auto-Close Days",
help_text="Closes an engagement after the specified number of days past due date including last update.")
enable_finding_sla = models.BooleanField(
default=True,
blank=False,
verbose_name="Enable Finding SLA's",
help_text="Enables Finding SLA's for time to remediate.")
sla_critical = models.IntegerField(default=7,
verbose_name="Crital Finding SLA Days",
help_text="# of days to remediate a critical finding.")
sla_high = models.IntegerField(default=30,
verbose_name="High Finding SLA Days",
help_text="# of days to remediate a high finding.")
sla_medium = models.IntegerField(default=90,
verbose_name="Medium Finding SLA Days",
help_text="# of days to remediate a medium finding.")
sla_low = models.IntegerField(default=120,
verbose_name="Low Finding SLA Days",
help_text="# of days to remediate a low finding.")
allow_anonymous_survey_repsonse = models.BooleanField(
default=False,
blank=False,
verbose_name="Allow Anonymous Survey Responses",
help_text="Enable anyone with a link to the survey to answer a survey"
)
credentials = models.CharField(max_length=3000, blank=True)
column_widths = models.CharField(max_length=1500, blank=True)
drive_folder_ID = models.CharField(max_length=100, blank=True)
enable_google_sheets = models.BooleanField(default=False, null=True, blank=True)
email_address = models.EmailField(max_length=100, blank=True)
risk_acceptance_form_default_days = models.IntegerField(null=True, blank=True, default=180, help_text="Default expiry period for risk acceptance form.")
risk_acceptance_notify_before_expiration = models.IntegerField(null=True, blank=True, default=10,
verbose_name="Risk acceptance expiration heads up days", help_text="Notify X days before risk acceptance expires. Leave empty to disable.")
from dojo.middleware import System_Settings_Manager
objects = System_Settings_Manager()
class SystemSettingsFormAdmin(forms.ModelForm):
product_grade = forms.CharField(widget=forms.Textarea)
class Meta:
model = System_Settings
fields = ['product_grade']
class System_SettingsAdmin(admin.ModelAdmin):
form = SystemSettingsFormAdmin
fields = ('product_grade',)
def get_current_date():
return timezone.now().date()
def get_current_datetime():
return timezone.now()
User = get_user_model()
# proxy class for convenience and UI
class Dojo_User(User):
class Meta:
proxy = True
def get_full_name(self):
return Dojo_User.generate_full_name(self)
def __unicode__(self):
return self.get_full_name()
def __str__(self):
return self.get_full_name()
@staticmethod
def wants_block_execution(user):
# this return False if there is no user, i.e. in celery processes, unittests, etc.
return hasattr(user, 'usercontactinfo') and user.usercontactinfo.block_execution
@staticmethod
def generate_full_name(user):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s (%s)' % (user.first_name,
user.last_name,
user.username)
return full_name.strip()
class UserContactInfo(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
title = models.CharField(blank=True, null=True, max_length=150)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. "
"Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], blank=True,
max_length=15,
help_text="Phone number must be entered in the format: '+999999999'. "
"Up to 15 digits allowed.")
cell_number = models.CharField(validators=[phone_regex], blank=True,
max_length=15,
help_text="Phone number must be entered in the format: '+999999999'. "
"Up to 15 digits allowed.")
twitter_username = models.CharField(blank=True, null=True, max_length=150)
github_username = models.CharField(blank=True, null=True, max_length=150)
slack_username = models.CharField(blank=True, null=True, max_length=150, help_text="Email address associated with your slack account", verbose_name="Slack Email Address")
slack_user_id = models.CharField(blank=True, null=True, max_length=25)
block_execution = models.BooleanField(default=False, help_text="Instead of async deduping a finding the findings will be deduped synchronously and will 'block' the user until completion.")
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
team = models.CharField(max_length=100)
is_admin = models.BooleanField(default=False)
is_globally_read_only = models.BooleanField(default=False)
updated = models.DateTimeField(editable=False)
class Note_Type(models.Model):
name = models.CharField(max_length=100, unique=True)
description = models.CharField(max_length=200)
is_single = models.BooleanField(default=False, null=False)
is_active = models.BooleanField(default=True, null=False)
is_mandatory = models.BooleanField(default=True, null=False)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class NoteHistory(models.Model):
note_type = models.ForeignKey(Note_Type, null=True, blank=True, on_delete=models.CASCADE)
data = models.TextField()
time = models.DateTimeField(null=True, editable=False,
default=get_current_datetime)
current_editor = models.ForeignKey(User, editable=False, null=True, on_delete=models.CASCADE)
class Notes(models.Model):
note_type = models.ForeignKey(Note_Type, related_name='note_type', null=True, blank=True, on_delete=models.CASCADE)
entry = models.TextField()
date = models.DateTimeField(null=False, editable=False,
default=get_current_datetime)
author = models.ForeignKey(User, related_name='editor_notes_set', editable=False, on_delete=models.CASCADE)
private = models.BooleanField(default=False)
edited = models.BooleanField(default=False)
editor = models.ForeignKey(User, related_name='author_notes_set', editable=False, null=True, on_delete=models.CASCADE)
edit_time = models.DateTimeField(null=True, editable=False,
default=get_current_datetime)
history = models.ManyToManyField(NoteHistory, blank=True,
editable=False)
class Meta:
ordering = ['-date']
def __unicode__(self):
return self.entry
def __str__(self):
return self.entry
class FileUpload(models.Model):
title = models.CharField(max_length=100, unique=True)
file = models.FileField(upload_to=UniqueUploadNameProvider('uploaded_files'))
class Product_Type(models.Model):
name = models.CharField(max_length=255, unique=True)
critical_product = models.BooleanField(default=False)
key_product = models.BooleanField(default=False)
updated = models.DateTimeField(auto_now=True, null=True)
created = models.DateTimeField(auto_now_add=True, null=True)
authorized_users = models.ManyToManyField(User, blank=True)
@cached_property
def critical_present(self):
c_findings = Finding.objects.filter(
test__engagement__product__prod_type=self, severity='Critical')
if c_findings.count() > 0:
return True
@cached_property
def high_present(self):
c_findings = Finding.objects.filter(
test__engagement__product__prod_type=self, severity='High')
if c_findings.count() > 0:
return True
@cached_property
def calc_health(self):
h_findings = Finding.objects.filter(
test__engagement__product__prod_type=self, severity='High')
c_findings = Finding.objects.filter(
test__engagement__product__prod_type=self, severity='Critical')
health = 100
if c_findings.count() > 0:
health = 40
health = health - ((c_findings.count() - 1) * 5)
if h_findings.count() > 0:
if health == 100:
health = 60
health = health - ((h_findings.count() - 1) * 2)
if health < 5:
return 5
else:
return health
# only used by bulk risk acceptance api
@property
def unaccepted_open_findings(self):
return Finding.objects.filter(risk_accepted=False, active=True, verified=True, duplicate=False, test__engagement__product__prod_type=self)
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
def get_breadcrumbs(self):
bc = [{'title': self.__unicode__(),
'url': reverse('edit_product_type', args=(self.id,))}]
return bc
def get_absolute_url(self):
from django.urls import reverse
return reverse('product_type', args=[str(self.id)])
class Product_Line(models.Model):
name = models.CharField(max_length=300)
description = models.CharField(max_length=2000)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Report_Type(models.Model):
name = models.CharField(max_length=255)
class Test_Type(models.Model):
name = models.CharField(max_length=200, unique=True)
static_tool = models.BooleanField(default=False)
dynamic_tool = models.BooleanField(default=False)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
def get_breadcrumbs(self):
bc = [{'title': self.__unicode__(),
'url': None}]
return bc
class DojoMeta(models.Model):
name = models.CharField(max_length=120)
value = models.CharField(max_length=300)
product = models.ForeignKey('Product',
on_delete=models.CASCADE,
null=True,
editable=False,
related_name='product_meta')
endpoint = models.ForeignKey('Endpoint',
on_delete=models.CASCADE,
null=True,
editable=False,
related_name='endpoint_meta')
finding = models.ForeignKey('Finding',
on_delete=models.CASCADE,
null=True,
editable=False,
related_name='finding_meta')
"""
Verify that this metadata entry belongs only to one object.
"""
def clean(self):
ids = [self.product_id,
self.endpoint_id,
self.finding_id]
ids_count = 0
for id in ids:
if id is not None:
ids_count += 1
if ids_count == 0:
raise ValidationError('Metadata entries need either a product, an endpoint or a finding')
if ids_count > 1:
raise ValidationError('Metadata entries may not have more than one relation, either a product, an endpoint either or a finding')
def __unicode__(self):
return "%s: %s" % (self.name, self.value)
def __str__(self):
return "%s: %s" % (self.name, self.value)
class Meta:
unique_together = (('product', 'name'),
('endpoint', 'name'),
('finding', 'name'))
class Product(models.Model):
WEB_PLATFORM = 'web'
IOT = 'iot'
DESKTOP_PLATFORM = 'desktop'
MOBILE_PLATFORM = 'mobile'
WEB_SERVICE_PLATFORM = 'web service'
PLATFORM_CHOICES = (
(WEB_SERVICE_PLATFORM, _('API')),
(DESKTOP_PLATFORM, _('Desktop')),
(IOT, _('Internet of Things')),
(MOBILE_PLATFORM, _('Mobile')),
(WEB_PLATFORM, _('Web')),
)
CONSTRUCTION = 'construction'
PRODUCTION = 'production'
RETIREMENT = 'retirement'
LIFECYCLE_CHOICES = (
(CONSTRUCTION, _('Construction')),
(PRODUCTION, _('Production')),
(RETIREMENT, _('Retirement')),
)
THIRD_PARTY_LIBRARY_ORIGIN = 'third party library'
PURCHASED_ORIGIN = 'purchased'
CONTRACTOR_ORIGIN = 'contractor'
INTERNALLY_DEVELOPED_ORIGIN = 'internal'
OPEN_SOURCE_ORIGIN = 'open source'
OUTSOURCED_ORIGIN = 'outsourced'
ORIGIN_CHOICES = (
(THIRD_PARTY_LIBRARY_ORIGIN, _('Third Party Library')),
(PURCHASED_ORIGIN, _('Purchased')),
(CONTRACTOR_ORIGIN, _('Contractor Developed')),
(INTERNALLY_DEVELOPED_ORIGIN, _('Internally Developed')),
(OPEN_SOURCE_ORIGIN, _('Open Source')),
(OUTSOURCED_ORIGIN, _('Outsourced')),
)
VERY_HIGH_CRITICALITY = 'very high'
HIGH_CRITICALITY = 'high'
MEDIUM_CRITICALITY = 'medium'
LOW_CRITICALITY = 'low'
VERY_LOW_CRITICALITY = 'very low'
NONE_CRITICALITY = 'none'
BUSINESS_CRITICALITY_CHOICES = (
(VERY_HIGH_CRITICALITY, _('Very High')),
(HIGH_CRITICALITY, _('High')),
(MEDIUM_CRITICALITY, _('Medium')),
(LOW_CRITICALITY, _('Low')),
(VERY_LOW_CRITICALITY, _('Very Low')),
(NONE_CRITICALITY, _('None')),
)
name = models.CharField(max_length=255, unique=True)
description = models.CharField(max_length=4000)
'''
The following three fields are deprecated and no longer in use.
They remain in model for backwards compatibility and will be removed
in a future release. prod_manager, tech_contact, manager
The admin script migrate_product_contacts should be used to migrate data
from these fields to their replacements.
./manage.py migrate_product_contacts
'''
prod_manager = models.CharField(default=0, max_length=200, null=True, blank=True) # unused
tech_contact = models.CharField(default=0, max_length=200, null=True, blank=True) # unused
manager = models.CharField(default=0, max_length=200, null=True, blank=True) # unused
product_manager = models.ForeignKey(Dojo_User, null=True, blank=True,
related_name='product_manager', on_delete=models.CASCADE)
technical_contact = models.ForeignKey(Dojo_User, null=True, blank=True,
related_name='technical_contact', on_delete=models.CASCADE)
team_manager = models.ForeignKey(Dojo_User, null=True, blank=True,
related_name='team_manager', on_delete=models.CASCADE)
created = models.DateTimeField(editable=False, null=True, blank=True)
prod_type = models.ForeignKey(Product_Type, related_name='prod_type',
null=False, blank=False, on_delete=models.CASCADE)
updated = models.DateTimeField(editable=False, null=True, blank=True)
tid = models.IntegerField(default=0, editable=False)
authorized_users = models.ManyToManyField(User, blank=True)
prod_numeric_grade = models.IntegerField(null=True, blank=True)
# Metadata
business_criticality = models.CharField(max_length=9, choices=BUSINESS_CRITICALITY_CHOICES, blank=True, null=True)
platform = models.CharField(max_length=11, choices=PLATFORM_CHOICES, blank=True, null=True)
lifecycle = models.CharField(max_length=12, choices=LIFECYCLE_CHOICES, blank=True, null=True)
origin = models.CharField(max_length=19, choices=ORIGIN_CHOICES, blank=True, null=True)
user_records = models.PositiveIntegerField(blank=True, null=True, help_text=_('Estimate the number of user records within the application.'))
revenue = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True, help_text=_('Estimate the application\'s revenue.'))
external_audience = models.BooleanField(default=False, help_text=_('Specify if the application is used by people outside the organization.'))
internet_accessible = models.BooleanField(default=False, help_text=_('Specify if the application is accessible from the public internet.'))
regulations = models.ManyToManyField(Regulation, blank=True)
tags_from_django_tagging = models.TextField(editable=False, blank=True, help_text=_('Temporary archive with tags from the previous tagging library we used'))
# tags = TagField(blank=True, force_lowercase=True, help_text="Add tags that help describe this product. Choose from the list or add new tags. Press Enter key to add.")
tags = TagField(blank=True, force_lowercase=True, help_text="Add tags that help describe this product. Choose from the list or add new tags. Press Enter key to add.")
enable_simple_risk_acceptance = models.BooleanField(default=False, help_text=_('Allows simple risk acceptance by checking/unchecking a checkbox.'))
enable_full_risk_acceptance = models.BooleanField(default=True, help_text=_('Allows full risk acceptanc using a risk acceptance form, expiration date, uploaded proof, etc.'))
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
@cached_property
def findings_count(self):
try:
# if prefetched, it's already there
return self.active_finding_count
except AttributeError:
# ideally it's always prefetched and we can remove this code in the future
self.active_finding_count = Finding.objects.filter(active=True,
test__engagement__product=self).count()
return self.active_finding_count
@cached_property
def findings_active_verified_count(self):
try:
# if prefetched, it's already there
return self.active_verified_finding_count
except AttributeError:
# ideally it's always prefetched and we can remove this code in the future
self.active_verified_finding_count = Finding.objects.filter(active=True,
verified=True,
test__engagement__product=self).count()
return self.active_verified_finding_count
@cached_property
def endpoint_count(self):
# active_endpoints is (should be) prefetched
endpoints = self.active_endpoints
hosts = []
ids = []
for e in endpoints:
if ":" in e.host:
host_no_port = e.host[:e.host.index(':')]
else:
host_no_port = e.host
if host_no_port in hosts:
continue
else:
hosts.append(host_no_port)
ids.append(e.id)
return len(hosts)
def open_findings(self, start_date=None, end_date=None):
if start_date is None or end_date is None:
return {}
else:
critical = Finding.objects.filter(test__engagement__product=self,
mitigated__isnull=True,
verified=True,
false_p=False,
duplicate=False,
out_of_scope=False,
severity="Critical",
date__range=[start_date,
end_date]).count()
high = Finding.objects.filter(test__engagement__product=self,
mitigated__isnull=True,
verified=True,
false_p=False,
duplicate=False,
out_of_scope=False,
severity="High",
date__range=[start_date,
end_date]).count()
medium = Finding.objects.filter(test__engagement__product=self,
mitigated__isnull=True,
verified=True,
false_p=False,
duplicate=False,
out_of_scope=False,
severity="Medium",
date__range=[start_date,
end_date]).count()
low = Finding.objects.filter(test__engagement__product=self,
mitigated__isnull=True,
verified=True,
false_p=False,
duplicate=False,
out_of_scope=False,
severity="Low",
date__range=[start_date,
end_date]).count()
return {'Critical': critical,
'High': high,
'Medium': medium,
'Low': low,
'Total': (critical + high + medium + low)}
def get_breadcrumbs(self):
bc = [{'title': self.__unicode__(),
'url': reverse('view_product', args=(self.id,))}]
return bc
@property
def get_product_type(self):
return self.prod_type if self.prod_type is not None else 'unknown'
def open_findings_list(self):
findings = Finding.objects.filter(test__engagement__product=self,
mitigated__isnull=True,
verified=True,
false_p=False,
duplicate=False,
out_of_scope=False
)
findings_list = []
for i in findings:
findings_list.append(i.id)
return findings_list
@property
def has_jira_configured(self):
import dojo.jira_link.helper as jira_helper
return jira_helper.has_jira_configured(self)
def get_absolute_url(self):
from django.urls import reverse
return reverse('view_product', args=[str(self.id)])
class ScanSettings(models.Model):
product = models.ForeignKey(Product, default=1, editable=False, on_delete=models.CASCADE)
addresses = models.TextField(default="none")
user = models.ForeignKey(User, editable=False, on_delete=models.CASCADE)
date = models.DateTimeField(editable=False, blank=True,
default=get_current_datetime)
frequency = models.CharField(max_length=10000, null=True,
blank=True)
email = models.CharField(max_length=512)
protocol = models.CharField(max_length=10, default='TCP')
def addresses_as_list(self):
if self.addresses:
return [a.strip() for a in self.addresses.split(',')]
return []
def get_breadcrumbs(self):
bc = self.product.get_breadcrumbs()
bc += [{'title': "Scan Settings",
'url': reverse('view_scan_settings',
args=(self.product.id, self.id,))}]
return bc
class Scan(models.Model):
scan_settings = models.ForeignKey(ScanSettings, default=1, editable=False, on_delete=models.CASCADE)
date = models.DateTimeField(editable=False, blank=True,
default=get_current_datetime)
protocol = models.CharField(max_length=10, default='TCP')
status = models.CharField(max_length=10, default='Pending', editable=False)
baseline = models.BooleanField(default=False, verbose_name="Current Baseline")
def __unicode__(self):
return self.scan_settings.protocol + " Scan " + str(self.date)
def __str__(self):
return self.scan_settings.protocol + " Scan " + str(self.date)
def get_breadcrumbs(self):
bc = self.scan_settings.get_breadcrumbs()
bc += [{'title': self.__unicode__(),
'url': reverse('view_scan', args=(self.id,))}]
return bc
class IPScan(models.Model):
address = models.TextField(editable=False, default="none")
services = models.CharField(max_length=800, null=True)
scan = models.ForeignKey(Scan, default=1, editable=False, on_delete=models.CASCADE)
class Tool_Type(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=2000, null=True)
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Tool_Configuration(models.Model):
name = models.CharField(max_length=200, null=False)
description = models.CharField(max_length=2000, null=True, blank=True)
url = models.CharField(max_length=2000, null=True)
tool_type = models.ForeignKey(Tool_Type, related_name='tool_type', on_delete=models.CASCADE)
authentication_type = models.CharField(max_length=15,
choices=(
('API', 'API Key'),
('Password',
'Username/Password'),
('SSH', 'SSH')),
null=True, blank=True)
username = models.CharField(max_length=200, null=True, blank=True)
password = models.CharField(max_length=600, null=True, blank=True)
auth_title = models.CharField(max_length=200, null=True, blank=True,
verbose_name="Title for SSH/API Key")
ssh = models.CharField(max_length=6000, null=True, blank=True)
api_key = models.CharField(max_length=600, null=True, blank=True,
verbose_name="API Key")
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
def __str__(self):
return self.name
# declare form here as we can't import forms.py due to circular imports not even locally
class ToolConfigForm_Admin(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput, required=False)
api_key = forms.CharField(widget=forms.PasswordInput, required=False)
ssh = forms.CharField(widget=forms.PasswordInput, required=False)
# django doesn't seem to have an easy way to handle password fields as PasswordInput requires reentry of passwords
password_from_db = None
ssh_from_db = None
api_key_from_db = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance:
# keep password from db to use if the user entered no password
self.password_from_db = self.instance.password
self.ssh_from_db = self.instance.ssh
self.api_key = self.instance.api_key
def clean(self):
# self.fields['endpoints'].queryset = Endpoint.objects.all()
cleaned_data = super().clean()
if not cleaned_data['password'] and not cleaned_data['ssh'] and not cleaned_data['api_key']:
cleaned_data['password'] = self.password_from_db
cleaned_data['ssh'] = self.ssh_from_db
cleaned_data['api_key'] = self.api_key_from_db
return cleaned_data
class Tool_Configuration_Admin(admin.ModelAdmin):
form = ToolConfigForm_Admin
class Network_Locations(models.Model):
location = models.CharField(max_length=500, help_text="Location of network testing: Examples: VPN, Internet or Internal.")
def __unicode__(self):
return self.location
def __str__(self):
return self.location
class Engagement_Presets(models.Model):
title = models.CharField(max_length=500, default=None, help_text="Brief description of preset.")
test_type = models.ManyToManyField(Test_Type, default=None, blank=True)
network_locations = models.ManyToManyField(Network_Locations, default=None, blank=True)
notes = models.CharField(max_length=2000, help_text="Description of what needs to be tested or setting up environment for testing", null=True, blank=True)
scope = models.CharField(max_length=800, help_text="Scope of Engagement testing, IP's/Resources/URL's)", default=None, blank=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True, null=False)
def __unicode__(self):
return self.title
def __str__(self):
return self.title
class Meta:
ordering = ['title']
class Engagement_Type(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
ENGAGEMENT_STATUS_CHOICES = (('Not Started', 'Not Started'),
('Blocked', 'Blocked'),
('Cancelled', 'Cancelled'),
('Completed', 'Completed'),
('In Progress', 'In Progress'),
('On Hold', 'On Hold'),
('Waiting for Resource', 'Waiting for Resource'))
class Engagement(models.Model):
name = models.CharField(max_length=300, null=True, blank=True)
description = models.CharField(max_length=2000, null=True, blank=True)
version = models.CharField(max_length=100, null=True, blank=True, help_text="Version of the product the engagement tested.")
eng_type = models.ForeignKey(Engagement_Type, null=True, blank=True, on_delete=models.CASCADE)
first_contacted = models.DateField(null=True, blank=True)
target_start = models.DateField(null=False, blank=False)
target_end = models.DateField(null=False, blank=False)
lead = models.ForeignKey(User, editable=True, null=True, on_delete=models.CASCADE)
requester = models.ForeignKey(Contact, null=True, blank=True, on_delete=models.CASCADE)
preset = models.ForeignKey(Engagement_Presets, null=True, blank=True, help_text="Settings and notes for performing this engagement.", on_delete=models.CASCADE)
reason = models.CharField(max_length=2000, null=True, blank=True)
report_type = models.ForeignKey(Report_Type, null=True, blank=True, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True, null=True)
created = models.DateTimeField(auto_now_add=True, null=True)
active = models.BooleanField(default=True, editable=False)
tracker = models.URLField(max_length=200, help_text="Link to epic or ticket system with changes to version.", editable=True, blank=True, null=True)
test_strategy = models.URLField(editable=True, blank=True, null=True)
threat_model = models.BooleanField(default=True)
api_test = models.BooleanField(default=True)
pen_test = models.BooleanField(default=True)
check_list = models.BooleanField(default=True)
notes = models.ManyToManyField(Notes, blank=True, editable=False)
files = models.ManyToManyField(FileUpload, blank=True, editable=False)
status = models.CharField(editable=True, max_length=2000, default='',
null=True,