-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmodels.py
4751 lines (4012 loc) · 224 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 copy
import hashlib
import logging
import os
import re
import warnings
from contextlib import suppress
from datetime import datetime
from pathlib import Path
from uuid import uuid4
import hyperlink
import tagulous.admin
from auditlog.registry import auditlog
from cvss import CVSS3
from dateutil.relativedelta import relativedelta
from django import forms
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.core.validators import MaxValueValidator, MinValueValidator, RegexValidator, validate_ipv46_address
from django.db import connection, models
from django.db.models import Count, JSONField, Q
from django.db.models.expressions import Case, When
from django.db.models.functions import Lower
from django.urls import reverse
from django.utils import timezone
from django.utils.deconstruct import deconstructible
from django.utils.functional import cached_property
from django.utils.html import escape
from django.utils.timezone import now
from django.utils.translation import gettext as _
from django_extensions.db.models import TimeStampedModel
from multiselectfield import MultiSelectField
from polymorphic.base import ManagerInheritanceWarning
from polymorphic.managers import PolymorphicManager
from polymorphic.models import PolymorphicModel
from pytz import all_timezones
from tagulous.models import TagField
from tagulous.models.managers import FakeTagRelatedManager
logger = logging.getLogger(__name__)
deduplicationLogger = logging.getLogger("dojo.specific-loggers.deduplication")
SEVERITY_CHOICES = (("Info", "Info"), ("Low", "Low"), ("Medium", "Medium"),
("High", "High"), ("Critical", "Critical"))
SEVERITIES = [s[0] for s in SEVERITY_CHOICES]
EFFORT_FOR_FIXING_CHOICES = (("", ""), ("Low", "Low"), ("Medium", "Medium"), ("High", "High"))
# fields returned in statistics, typically all status fields
STATS_FIELDS = ["active", "verified", "duplicate", "false_p", "out_of_scope", "is_mitigated", "risk_accepted", "total"]
# default template with all values set to 0
DEFAULT_STATS = {sev.lower(): dict.fromkeys(STATS_FIELDS, 0) for sev in SEVERITIES}
IMPORT_CREATED_FINDING = "N"
IMPORT_CLOSED_FINDING = "C"
IMPORT_REACTIVATED_FINDING = "R"
IMPORT_UNTOUCHED_FINDING = "U"
IMPORT_ACTIONS = [
(IMPORT_CREATED_FINDING, "created"),
(IMPORT_CLOSED_FINDING, "closed"),
(IMPORT_REACTIVATED_FINDING, "reactivated"),
(IMPORT_UNTOUCHED_FINDING, "left untouched"),
]
def _get_annotations_for_statistics():
annotations = {stats_field.lower(): Count(Case(When(**{stats_field: True}, then=1))) for stats_field in STATS_FIELDS if stats_field != "total"}
# add total
annotations["total"] = Count("id")
return annotations
def _get_statistics_for_queryset(qs, annotation_factory):
# order by to get rid of default ordering that would mess with group_by
# group by severity (lowercase)
values = qs.annotate(sev=Lower("severity")).values("sev").order_by()
# add annotation for each status field
values = values.annotate(**annotation_factory())
# make sure sev and total are included
stat_fields = ["sev", "total", *STATS_FIELDS]
# go for it
values = values.values(*stat_fields)
# not sure if there's a smarter way to convert a list of dicts into a dict of dicts
# need to copy the DEFAULT_STATS otherwise it gets overwritten
stats = copy.copy(DEFAULT_STATS)
for row in values:
sev = row.pop("sev")
stats[sev] = row
values_total = qs.values()
values_total = values_total.aggregate(**annotation_factory())
stats["total"] = values_total
return stats
def _manage_inherited_tags(obj, incoming_inherited_tags, potentially_existing_tags=[]):
# get copies of the current tag lists
current_inherited_tags = [] if isinstance(obj.inherited_tags, FakeTagRelatedManager) else [tag.name for tag in obj.inherited_tags.all()]
tag_list = potentially_existing_tags if isinstance(obj.tags, FakeTagRelatedManager) or len(potentially_existing_tags) > 0 else [tag.name for tag in obj.tags.all()]
# Clean existing tag list from the old inherited tags. This represents the tags on the object and not the product
cleaned_tag_list = [tag for tag in tag_list if tag not in current_inherited_tags]
# Add the incoming inherited tag list
if incoming_inherited_tags:
for tag in incoming_inherited_tags:
if tag not in cleaned_tag_list:
cleaned_tag_list.append(tag)
# Update the current list of inherited tags. iteratively do this because of tagulous object restraints
if isinstance(obj.inherited_tags, FakeTagRelatedManager):
obj.inherited_tags.set_tag_list(incoming_inherited_tags)
if incoming_inherited_tags:
obj.tags.set_tag_list(cleaned_tag_list)
else:
obj.inherited_tags.set(incoming_inherited_tags)
if incoming_inherited_tags:
obj.tags.set(cleaned_tag_list)
@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):
path = Path(filename)
base = path.parent / path.stem
ext = path.suffix
filename = f"{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 + ")"
User = get_user_model()
# proxy class for convenience and UI
class Dojo_User(User):
class Meta:
proxy = True
ordering = ["first_name"]
def get_full_name(self):
return Dojo_User.generate_full_name(self)
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 force_password_reset(user):
return hasattr(user, "usercontactinfo") and user.usercontactinfo.force_password_reset
def disable_force_password_reset(user):
if hasattr(user, "usercontactinfo"):
user.usercontactinfo.force_password_reset = False
user.usercontactinfo.save()
def enable_force_password_reset(user):
if hasattr(user, "usercontactinfo"):
user.usercontactinfo.force_password_reset = True
user.usercontactinfo.save()
@staticmethod
def generate_full_name(user):
"""Returns the first_name plus the last_name, with a space in between."""
full_name = f"{user.first_name} {user.last_name} ({user.username})"
return full_name.strip()
class UserContactInfo(models.Model):
user = models.OneToOneField(Dojo_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."))
force_password_reset = models.BooleanField(default=False, help_text=_("Forces this user to reset their password on next login."))
class Dojo_Group(models.Model):
AZURE = "AzureAD"
REMOTE = "Remote"
SOCIAL_CHOICES = (
(AZURE, _("AzureAD")),
(REMOTE, _("Remote")),
)
name = models.CharField(max_length=255, unique=True)
description = models.CharField(max_length=4000, null=True, blank=True)
users = models.ManyToManyField(Dojo_User, through="Dojo_Group_Member", related_name="users", blank=True)
auth_group = models.ForeignKey(Group, null=True, blank=True, on_delete=models.CASCADE)
social_provider = models.CharField(max_length=10, choices=SOCIAL_CHOICES, blank=True, null=True, help_text=_("Group imported from a social provider."), verbose_name=_("Social Authentication Provider"))
def __str__(self):
return self.name
class Role(models.Model):
name = models.CharField(max_length=255, unique=True)
is_owner = models.BooleanField(default=False)
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
class System_Settings(models.Model):
enable_deduplication = models.BooleanField(
default=False,
blank=False,
verbose_name=_("Deduplicate findings"),
help_text=_("With this setting turned on, DefectDojo deduplicates findings by "
"comparing endpoints, cwe fields, and titles. "
"If two findings share a URL and have the same CWE or "
"title, DefectDojo marks the recent finding as a duplicate. "
"When deduplication is enabled, a list of "
"deduplicated findings is added to the engagement view."))
delete_duplicates = 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."))
email_from = models.CharField(max_length=200, default="[email protected]", blank=True)
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"))
add_vulnerability_id_to_jira_label = models.BooleanField(default=False,
verbose_name=_("Add vulnerability Id as a JIRA label"),
blank=False)
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_to = models.CharField(max_length=200, default="",
blank=True)
enable_webhooks_notifications = \
models.BooleanField(default=False,
verbose_name=_("Enable Webhook notifications"),
blank=False)
webhooks_notifications_timeout = models.IntegerField(default=10,
help_text=_("How many seconds will DefectDojo waits for response from webhook endpoint"))
enforce_verified_status = models.BooleanField(
default=True,
verbose_name=_("Enforce Verified Status - Globally"),
help_text=_(
"When enabled, features such as product grading, jira "
"integration, metrics, and reports will only interact "
"with verified findings. This setting will override "
"individually scoped verified toggles.",
),
)
enforce_verified_status_jira = models.BooleanField(
default=True,
verbose_name=_("Enforce Verified Status - Jira"),
help_text=_("When enabled, findings must have a verified status to be pushed to jira."),
)
enforce_verified_status_product_grading = models.BooleanField(
default=True,
verbose_name=_("Enforce Verified Status - Product Grading"),
help_text=_(
"When enabled, findings must have a verified status to be considered as part of a product's grading.",
),
)
enforce_verified_status_metrics = models.BooleanField(
default=True,
verbose_name=_("Enforce Verified Status - Metrics"),
help_text=_(
"When enabled, findings must have a verified status to be counted in metric calculations, "
"be included in reports, and filters.",
),
)
false_positive_history = models.BooleanField(
default=False, help_text=_(
"(EXPERIMENTAL) DefectDojo will automatically mark the finding as a "
"false positive if an equal finding (according to its dedupe algorithm) "
"has been previously marked as a false positive on the same product. "
"ATTENTION: Although the deduplication algorithm is used to determine "
"if a finding should be marked as a false positive, this feature will "
"not work if deduplication is enabled since it doesn't make sense to use both.",
),
)
retroactive_false_positive_history = models.BooleanField(
default=False, help_text=_(
"(EXPERIMENTAL) FP History will also retroactively mark/unmark all "
"existing equal findings in the same product as a false positives. "
"Only works if the False Positive History feature is also enabled.",
),
)
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)
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_product_tag_inheritance = models.BooleanField(
default=False,
blank=False,
verbose_name=_("Enable Product Tag Inheritance"),
help_text=_("Enables product tag inheritance globally for all products. Any tags added on a product will automatically be added to all Engagements, Tests, and Findings"))
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."))
enable_similar_findings = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable Similar Findings"),
help_text=_("Enable the query of similar findings on the view finding page. This feature can involve potentially large queries and negatively impact performance"))
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."))
enable_notify_sla_active = models.BooleanField(
default=False,
blank=False,
verbose_name=_("Enable Notify SLA's Breach for active Findings"),
help_text=_("Enables Notify when time to remediate according to Finding SLA's is breached for active Findings."))
enable_notify_sla_active_verified = models.BooleanField(
default=False,
blank=False,
verbose_name=_("Enable Notify SLA's Breach for active, verified Findings"),
help_text=_("Enables Notify when time to remediate according to Finding SLA's is breached for active, verified Findings."))
enable_notify_sla_jira_only = models.BooleanField(
default=False,
blank=False,
verbose_name=_("Enable Notify SLA's Breach only for Findings linked to JIRA"),
help_text=_("Enables Notify when time to remediate according to Finding SLA's is breached for Findings that are linked to JIRA issues. Notification is disabled for Findings not linked to JIRA issues"))
enable_notify_sla_exponential_backoff = models.BooleanField(
default=False,
blank=False,
verbose_name=_("Enable an exponential backoff strategy for SLA breach notifications."),
help_text=_("Enable an exponential backoff strategy for SLA breach notifications, e.g. 1, 2, 4, 8, etc. Otherwise it alerts every day"))
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.TextField(max_length=3000, blank=True)
disclaimer = models.TextField(max_length=3000, default="", blank=True,
verbose_name=_("Custom Disclaimer"),
help_text=_("Include this custom disclaimer on all notifications and generated reports"))
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."))
enable_credentials = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable credentials"),
help_text=_("With this setting turned off, credentials will be disabled in the user interface."))
enable_questionnaires = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable questionnaires"),
help_text=_("With this setting turned off, questionnaires will be disabled in the user interface."))
enable_checklists = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable checklists"),
help_text=_("With this setting turned off, checklists will be disabled in the user interface."))
enable_endpoint_metadata_import = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable Endpoint Metadata Import"),
help_text=_("With this setting turned off, endpoint metadata import will be disabled in the user interface."))
enable_user_profile_editable = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable user profile for writing"),
help_text=_("When turned on users can edit their profiles"))
enable_product_tracking_files = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable Product Tracking Files"),
help_text=_("With this setting turned off, the product tracking files will be disabled in the user interface."))
enable_finding_groups = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable Finding Groups"),
help_text=_("With this setting turned off, the Finding Groups will be disabled."))
enable_ui_table_based_searching = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable UI Table Based Filtering/Sorting"),
help_text=_("With this setting enabled, table headings will contain sort buttons for the current page of data in addition to sorting buttons that consider data from all pages."))
enable_calendar = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Enable Calendar"),
help_text=_("With this setting turned off, the Calendar will be disabled in the user interface."))
default_group = models.ForeignKey(
Dojo_Group,
null=True,
blank=True,
help_text=_("New users will be assigned to this group."),
on_delete=models.RESTRICT)
default_group_role = models.ForeignKey(
Role,
null=True,
blank=True,
help_text=_("New users will be assigned to their default group with this role."),
on_delete=models.RESTRICT)
default_group_email_pattern = models.CharField(
max_length=200,
default="",
blank=True,
help_text=_("New users will only be assigned to the default group, when their email address matches this regex pattern. This is optional condition."))
minimum_password_length = models.IntegerField(
default=9,
verbose_name=_("Minimum password length"),
help_text=_("Requires user to set passwords greater than minimum length."))
maximum_password_length = models.IntegerField(
default=48,
verbose_name=_("Maximum password length"),
help_text=_("Requires user to set passwords less than maximum length."))
number_character_required = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Password must contain one digit"),
help_text=_("Requires user passwords to contain at least one digit (0-9)."))
special_character_required = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Password must contain one special character"),
help_text=_("Requires user passwords to contain at least one special character (()[]{}|\\`~!@#$%^&*_-+=;:'\",<>./?)."))
lowercase_character_required = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Password must contain one lowercase letter"),
help_text=_("Requires user passwords to contain at least one lowercase letter (a-z)."))
uppercase_character_required = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Password must contain one uppercase letter"),
help_text=_("Requires user passwords to contain at least one uppercase letter (A-Z)."))
non_common_password_required = models.BooleanField(
default=True,
blank=False,
verbose_name=_("Password must not be common"),
help_text=_("Requires user passwords to not be part of list of common passwords."))
api_expose_error_details = models.BooleanField(
default=False,
blank=False,
verbose_name=_("API expose error details"),
help_text=_("When turned on, the API will expose error details in the response."))
filter_string_matching = models.BooleanField(
default=False,
blank=False,
verbose_name=_("Filter String Matching Optimization"),
help_text=_(
"When turned on, all filter operations in the UI will require string matches rather than ID. "
"This is a performance enhancement to avoid fetching objects unnecessarily.",
))
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()
class Dojo_Group_Member(models.Model):
group = models.ForeignKey(Dojo_Group, on_delete=models.CASCADE)
user = models.ForeignKey(Dojo_User, on_delete=models.CASCADE)
role = models.ForeignKey(Role, on_delete=models.CASCADE, help_text=_("This role determines the permissions of the user to manage the group."), verbose_name=_("Group role"))
class Global_Role(models.Model):
user = models.OneToOneField(Dojo_User, null=True, blank=True, on_delete=models.CASCADE)
group = models.OneToOneField(Dojo_Group, null=True, blank=True, on_delete=models.CASCADE)
role = models.ForeignKey(Role, on_delete=models.CASCADE, null=True, blank=True, help_text=_("The global role will be applied to all product types and products."), verbose_name=_("Global role"))
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(auto_now=True)
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 __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(Dojo_User, editable=False, null=True, on_delete=models.CASCADE)
def copy(self):
copy = self
copy.pk = None
copy.id = None
copy.save()
return copy
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(Dojo_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(Dojo_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 __str__(self):
return self.entry
def copy(self):
copy = self
# Save the necessary ManyToMany relationships
old_history = list(self.history.all())
# Wipe the IDs of the new object
copy.pk = None
copy.id = None
# Save the object before setting any ManyToMany relationships
copy.save()
# Copy the history
for history in old_history:
copy.history.add(history.copy())
return copy
class FileUpload(models.Model):
title = models.CharField(max_length=100, unique=True)
file = models.FileField(upload_to=UniqueUploadNameProvider("uploaded_files"))
def copy(self):
copy = self
# Wipe the IDs of the new object
copy.pk = None
copy.id = None
# Add unique modifier to file name
copy.title = f"{self.title} - clone-{str(uuid4())[:8]}"
# Create new unique file name
current_url = self.file.url
_, current_full_filename = current_url.rsplit("/", 1)
_, extension = current_full_filename.split(".", 1)
new_file = ContentFile(self.file.read(), name=f"{uuid4()}.{extension}")
copy.file = new_file
copy.save()
return copy
def get_accessible_url(self, obj, obj_id):
if isinstance(obj, Engagement):
obj_type = "Engagement"
elif isinstance(obj, Test):
obj_type = "Test"
elif isinstance(obj, Finding):
obj_type = "Finding"
return f"access_file/{self.id}/{obj_id}/{obj_type}"
def clean(self):
if not self.title:
self.title = "<No Title>"
valid_extensions = settings.FILE_UPLOAD_TYPES
# why does this not work with self.file....
file_name = self.file.url if self.file else self.title
if Path(file_name).suffix.lower() not in valid_extensions:
if accepted_extensions := f"{', '.join(valid_extensions)}":
msg = (
_("Unsupported extension. Supported extensions are as follows: %s") % accepted_extensions
)
else:
msg = (
_("File uploads are prohibited due to the list of acceptable file extensions being empty")
)
raise ValidationError(msg)
class Product_Type(models.Model):
"""
Product types represent the top level model, these can be business unit divisions, different offices or locations, development teams, or any other logical way of distinguishing “types” of products.
`
Examples:
* IAM Team
* Internal / 3rd Party
* Main company / Acquisition
* San Francisco / New York offices
"""
name = models.CharField(max_length=255, unique=True)
description = models.CharField(max_length=4000, null=True, blank=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)
members = models.ManyToManyField(Dojo_User, through="Product_Type_Member", related_name="prod_type_members", blank=True)
authorization_groups = models.ManyToManyField(Dojo_Group, through="Product_Type_Group", related_name="product_type_groups", blank=True)
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
def get_absolute_url(self):
from django.urls import reverse
return reverse("product_type", args=[str(self.id)])
def get_breadcrumbs(self):
return [{"title": str(self),
"url": reverse("edit_product_type", args=(self.id,))}]
@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
return None
@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
return None
@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
return health
# only used by bulk risk acceptance api
@property
def unaccepted_open_findings(self):
return Finding.objects.filter(risk_accepted=False, active=True, duplicate=False, test__engagement__product__prod_type=self)
class Product_Line(models.Model):
name = models.CharField(max_length=300)
description = models.CharField(max_length=2000)
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)
active = models.BooleanField(default=True)
dynamically_generated = models.BooleanField(
default=False,
help_text=_("Set to True for test types that are created at import time"))
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
def get_breadcrumbs(self):
return [{"title": str(self),
"url": None}]
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")
class Meta:
unique_together = (("product", "name"),
("endpoint", "name"),
("finding", "name"))
def __str__(self):
return f"{self.name}: {self.value}"
"""
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:
msg = "Metadata entries need either a product, an endpoint or a finding"
raise ValidationError(msg)
if ids_count > 1:
msg = "Metadata entries may not have more than one relation, either a product, an endpoint either or a finding"
raise ValidationError(msg)
class SLA_Configuration(models.Model):
name = models.CharField(max_length=128, unique=True, blank=False, verbose_name=_("Custom SLA Name"),
help_text=_("A unique name for the set of SLAs."))
description = models.CharField(
max_length=512,
null=True,
blank=True)
critical = models.IntegerField(
default=7,
verbose_name=_("Critical Finding SLA Days"),
help_text=_("The number of days to remediate a critical finding."))
enforce_critical = models.BooleanField(
default=True,
verbose_name=_("Enforce Critical Finding SLA Days"),
help_text=_("When enabled, critical findings will be assigned an SLA expiration date based on the critical finding SLA days within this SLA configuration."))
high = models.IntegerField(
default=30,
verbose_name=_("High Finding SLA Days"),
help_text=_("The number of days to remediate a high finding."))
enforce_high = models.BooleanField(
default=True,
verbose_name=_("Enforce High Finding SLA Days"),
help_text=_("When enabled, high findings will be assigned an SLA expiration date based on the high finding SLA days within this SLA configuration."))
medium = models.IntegerField(
default=90,
verbose_name=_("Medium Finding SLA Days"),
help_text=_("The number of days to remediate a medium finding."))
enforce_medium = models.BooleanField(
default=True,
verbose_name=_("Enforce Medium Finding SLA Days"),
help_text=_("When enabled, medium findings will be assigned an SLA expiration date based on the medium finding SLA days within this SLA configuration."))
low = models.IntegerField(
default=120,
verbose_name=_("Low Finding SLA Days"),
help_text=_("The number of days to remediate a low finding."))
enforce_low = models.BooleanField(
default=True,
verbose_name=_("Enforce Low Finding SLA Days"),
help_text=_("When enabled, low findings will be assigned an SLA expiration date based on the low finding SLA days within this SLA configuration."))
async_updating = models.BooleanField(
default=False,
help_text=_("Findings under this SLA configuration are asynchronously being updated"))
class Meta:
ordering = ["name"]
def __str__(self):
return self.name
def save(self, *args, **kwargs):
# get the initial sla config before saving (if this is an existing sla config)
initial_sla_config = None
if self.pk is not None:
initial_sla_config = SLA_Configuration.objects.get(pk=self.pk)
# if initial config exists and async finding update is already running, revert sla config before saving