forked from DefectDojo/django-DefectDojo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
executable file
·3711 lines (3107 loc) · 173 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 typing import Dict, Set, Optional
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.contrib.auth.models import Group
from django.urls import reverse
from django.core.validators import RegexValidator, validate_ipv46_address
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q, Count
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 django.utils import timezone
from django.utils.html import escape
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
from django.db.models import JSONField
import hyperlink
from cvss import CVSS3
from dojo.settings.settings import SLA_BUSINESS_DAYS
from numpy import busday_count
logger = logging.getLogger(__name__)
deduplicationLogger = logging.getLogger("dojo.specific-loggers.deduplication")
SEVERITY_CHOICES = (('Info', 'Info'), ('Low', 'Low'), ('Medium', 'Medium'),
('High', 'High'), ('Critical', 'Critical'))
IMPORT_CREATED_FINDING = 'N'
IMPORT_CLOSED_FINDING = 'C'
IMPORT_REACTIVATED_FINDING = 'R'
IMPORT_UPDATED_FINDING = 'U'
IMPORT_ACTIONS = [
(IMPORT_CREATED_FINDING, 'created'),
(IMPORT_CLOSED_FINDING, 'closed'),
(IMPORT_REACTIVATED_FINDING, 'reactivated'),
(IMPORT_UPDATED_FINDING, 'updated'),
]
@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 + ')'
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 = '%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.")
force_password_reset = models.BooleanField(default=False, help_text='Forces this user to reset their password on next login.')
class Dojo_Group(models.Model):
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)
def __str__(self):
return self.name
class Role(models.Model):
name = models.CharField(max_length=255, unique=True)
is_owner = models.BooleanField(default=False)
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
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_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')
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)
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)
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="Critical 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.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")
column_widths = models.TextField(max_length=1500, blank=True)
drive_folder_ID = models.CharField(max_length=100, 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.")
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_google_sheets = models.BooleanField(
default=False,
blank=False,
verbose_name='Enable Google Sheets Integration',
help_text="With this setting turned off, the Google sheets integration will be disabled in the user interface.")
enable_rules_framework = models.BooleanField(
default=False,
blank=False,
verbose_name='Enable Rules Framework',
help_text="With this setting turned off, the rules framwork 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.")
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)
staff_user_email_pattern = models.CharField(
max_length=200,
default='',
blank=True,
verbose_name='Email pattern for staff users',
help_text="When the email address of a new user created by OAuth2 matches this regex pattern, their is_staff flag will be set to True.")
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(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(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 __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 __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):
"""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)
@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, duplicate=False, test__engagement__product__prod_type=self)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
def get_breadcrumbs(self):
bc = [{'title': str(self),
'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 __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)
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
def get_breadcrumbs(self):
bc = [{'title': str(self),
'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 __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)
product_manager = models.ForeignKey(Dojo_User, null=True, blank=True,
related_name='product_manager', on_delete=models.RESTRICT)
technical_contact = models.ForeignKey(Dojo_User, null=True, blank=True,
related_name='technical_contact', on_delete=models.RESTRICT)
team_manager = models.ForeignKey(Dojo_User, null=True, blank=True,
related_name='team_manager', on_delete=models.RESTRICT)
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)
members = models.ManyToManyField(Dojo_User, through='Product_Member', related_name='product_members', blank=True)
authorization_groups = models.ManyToManyField(Dojo_Group, through='Product_Group', related_name='product_groups', 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 = 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 acceptance using a risk acceptance form, expiration date, uploaded proof, etc.'))
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_host_count(self):
# active_endpoints is (should be) prefetched
endpoints = self.active_endpoints
hosts = []
for e in endpoints:
if e.host in hosts:
continue
else:
hosts.append(e.host)
return len(hosts)
@cached_property
def endpoint_count(self):
# active_endpoints is (should be) prefetched
return len(self.active_endpoints)
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': str(self),
'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'
# only used in APIv2 serializers.py, query should be aligned with findings_count
@cached_property
def open_findings_list(self):
findings = Finding.objects.filter(test__engagement__product=self,
active=True,
)
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 Product_Member(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(Dojo_User, on_delete=models.CASCADE)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
class Product_Group(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
group = models.ForeignKey(Dojo_Group, on_delete=models.CASCADE)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
class Product_Type_Member(models.Model):
product_type = models.ForeignKey(Product_Type, on_delete=models.CASCADE)
user = models.ForeignKey(Dojo_User, on_delete=models.CASCADE)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
class Product_Type_Group(models.Model):
product_type = models.ForeignKey(Product_Type, on_delete=models.CASCADE)
group = models.ForeignKey(Dojo_Group, on_delete=models.CASCADE)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
class Tool_Type(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=2000, null=True, blank=True)
class Meta:
ordering = ['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, blank=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)
extras = models.CharField(max_length=255, null=True, blank=True, help_text="Additional definitions that will be "
"consumed by scanner")
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 __str__(self):
return self.name
class Product_API_Scan_Configuration(models.Model):
product = models.ForeignKey(Product, null=False, blank=False, on_delete=models.CASCADE)
tool_configuration = models.ForeignKey(Tool_Configuration, null=False, blank=False, on_delete=models.CASCADE)
service_key_1 = models.CharField(max_length=200, null=True, blank=True)
service_key_2 = models.CharField(max_length=200, null=True, blank=True)
service_key_3 = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
name = self.tool_configuration.name
if self.service_key_1 or self.service_key_2 or self.service_key_3:
name += f' ({self.details})'
return name
@property
def details(self):
details = ''
if self.service_key_1:
details += f'{self.service_key_1}'
if self.service_key_2:
details += f' | {self.service_key_2}'
if self.service_key_3:
details += f' | {self.service_key_3}'
return details
# 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):
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