-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathforms.py
More file actions
3702 lines (2936 loc) · 154 KB
/
forms.py
File metadata and controls
3702 lines (2936 loc) · 154 KB
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 logging
import pickle
import re
import warnings
from datetime import date, datetime
from pathlib import Path
import tagulous
from crispy_forms.bootstrap import InlineCheckboxes, InlineRadios
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout
from crum import get_current_user
from dateutil.relativedelta import relativedelta
from django import forms
from django.conf import settings
from django.contrib.auth.models import Permission
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.db.models import Count, Q
from django.forms import modelformset_factory
from django.forms.widgets import Select, Widget
from django.utils import timezone
from django.utils.dates import MONTHS
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from polymorphic.base import ManagerInheritanceWarning
from tagulous.forms import TagField
from dojo.authorization.authorization import user_has_configuration_permission, user_is_superuser_or_global_owner
from dojo.authorization.roles_permissions import Permissions
from dojo.endpoint.utils import endpoint_filter, endpoint_get_or_create, validate_endpoints_to_add
from dojo.engagement.queries import get_authorized_engagements
from dojo.finding.queries import get_authorized_findings
from dojo.github.ui.forms import ( # noqa: F401 -- backward compat
DeleteGITHUBConfForm,
ExpressGITHUBForm,
GITHUB_IssueForm,
GITHUB_Product_Form,
GITHUBFindingForm,
GITHUBForm,
)
from dojo.group.queries import get_authorized_groups, get_group_member_roles
from dojo.jira import services as jira_services
from dojo.jira.forms import ( # noqa: F401 backward compat
JIRA_TEMPLATE_CHOICES,
AdvancedJIRAForm,
BaseJiraForm,
DeleteJIRAInstanceForm,
JIRA_IssueForm,
JIRAEngagementForm,
JIRAFindingForm,
JIRAForm,
JIRAImportScanForm,
JIRAProjectForm,
get_jira_issue_template_dir_choices,
)
from dojo.labels import get_labels
from dojo.location.models import Location
from dojo.location.utils import validate_locations_to_add
from dojo.models import (
EFFORT_FOR_FIXING_CHOICES,
SEVERITY_CHOICES,
Announcement,
Answered_Survey,
App_Analysis,
Benchmark_Product,
Benchmark_Product_Summary,
Benchmark_Requirement,
Check_List,
Choice,
ChoiceAnswer,
ChoiceQuestion,
Cred_Mapping,
Cred_User,
Development_Environment,
Dojo_Group,
Dojo_Group_Member,
Dojo_User,
DojoMeta,
Endpoint,
Engagement,
Engagement_Presets,
Engagement_Survey,
FileUpload,
Finding,
Finding_Group,
Finding_Template,
General_Survey,
Global_Role,
Note_Type,
Notes,
Notification_Webhooks,
Notifications,
Objects_Product,
Product,
Product_API_Scan_Configuration,
Product_Group,
Product_Member,
Product_Type,
Product_Type_Group,
Product_Type_Member,
Question,
Regulation,
Risk_Acceptance,
SLA_Configuration,
Stub_Finding,
System_Settings,
Test,
Test_Type,
TextAnswer,
TextQuestion,
Tool_Configuration,
Tool_Product_Settings,
Tool_Type,
User,
UserContactInfo,
)
from dojo.product.queries import get_authorized_products
from dojo.product_type.queries import get_authorized_product_types
from dojo.tools.factory import get_choices_sorted, requires_file, requires_tool_type
from dojo.user.queries import get_authorized_users, get_authorized_users_for_product_and_product_type
from dojo.user.utils import get_configuration_permissions_fields
from dojo.utils import (
get_password_requirements_string,
get_product,
get_system_setting,
is_finding_groups_enabled,
is_scan_file_too_large,
)
from dojo.validators import ImporterFileExtensionValidator, cvss3_validator, cvss4_validator, tag_validator
from dojo.widgets import TableCheckboxWidget
logger = logging.getLogger(__name__)
labels = get_labels()
RE_DATE = re.compile(r"(\d{4})-(\d\d?)-(\d\d?)$")
FINDING_STATUS = (("verified", "Verified"),
("false_p", "False Positive"),
("duplicate", "Duplicate"),
("out_of_scope", "Out of Scope"))
CVSS_CALCULATOR_URLS = {
"https://www.first.org/cvss/calculator/3-0": "CVSS3 Calculator by FIRST",
"https://www.first.org/cvss/calculator/4-0": "CVSS4 Calculator by FIRST",
"https://www.metaeffekt.com/security/cvss/calculator/": "CVSS2/3/4 Calculator by Metaeffekt",
}
vulnerability_ids_field = forms.CharField(max_length=5000,
required=False,
label="Vulnerability Ids",
help_text="Ids of vulnerabilities in security advisories associated with this finding. Can be Common Vulnerabilities and Exposures (CVE) or from other sources."
"You may enter one vulnerability id per line.",
widget=forms.widgets.Textarea(attrs={"rows": "3", "cols": "400"}))
EFFORT_FOR_FIXING_INVALID_CHOICE = _("Select valid choice: Low,Medium,High")
class BulletListDisplayWidget(forms.Widget):
def __init__(self, urls_dict=None, *args, **kwargs):
self.urls_dict = urls_dict or {}
super().__init__(*args, **kwargs)
def render(self, name, value, attrs=None, renderer=None):
if not self.urls_dict:
return ""
html = '<ul style="margin: 0; padding-left: 20px;">'
for url, text in self.urls_dict.items():
html += f'<li style="list-style-type: disc;"><a href="{url}" target="_blank"><i class="fa fa-arrow-up-right-from-square" style="margin-right: 5px;"></i>{text}</a></li>'
html += "</ul>"
return mark_safe(html)
class MultipleSelectWithPop(forms.SelectMultiple):
def render(self, name, *args, **kwargs):
html = super().render(name, *args, **kwargs)
popup_plus = '<div class="input-group dojo-input-group">' + html + '<span class="input-group-btn"><a href="/' + name + '/add" class="btn btn-primary" class="add-another" id="add_id_' + name + '" onclick="return showAddAnotherPopup(this);"><span class="glyphicon glyphicon-plus"></span></a></span></div>'
return mark_safe(popup_plus)
class MonthYearWidget(Widget):
"""
A Widget that splits date input into two <select> boxes for month and year,
with 'day' defaulting to the first of the month.
Based on SelectDateWidget, in
django/trunk/django/forms/extras/widgets.py
"""
none_value = (0, "---")
month_field = "%s_month"
year_field = "%s_year"
def __init__(self, attrs=None, years=None, *, required=True):
# years is an optional list/tuple of years to use in the
# "year" select box.
self.attrs = attrs or {}
self.required = required
if years:
self.years = years
else:
this_year = date.today().year
self.years = list(range(this_year - 10, this_year + 1))
def render(self, name, value, attrs=None, renderer=None):
try:
year_val, month_val = value.year, value.month
except AttributeError:
year_val = month_val = None
if isinstance(value, str):
match = RE_DATE.match(value)
if match:
year_val, month_val = match[1], match[2]
output = []
id_ = self.attrs.get("id", f"id_{name}")
month_choices = list(MONTHS.items())
if not (self.required and value):
month_choices.append(self.none_value)
month_choices.sort()
local_attrs = self.build_attrs({"id": self.month_field % id_})
s = Select(choices=month_choices)
select_html = s.render(self.month_field % name, month_val, local_attrs)
output.append(select_html)
year_choices = [(i, i) for i in self.years]
if not (self.required and value):
year_choices.insert(0, self.none_value)
local_attrs["id"] = self.year_field % id_
s = Select(choices=year_choices)
select_html = s.render(self.year_field % name, year_val, local_attrs)
output.append(select_html)
return mark_safe("\n".join(output))
@classmethod
def id_for_label(cls, id_):
return f"{id_}_month"
def value_from_datadict(self, data, files, name):
y = data.get(self.year_field % name)
m = data.get(self.month_field % name)
if y == m == "0":
return None
if y and m:
return f"{y}-{m}-{1}"
return data.get(name, None)
class Product_TypeForm(forms.ModelForm):
description = forms.CharField(widget=forms.Textarea(attrs={}),
required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["critical_product"].label = labels.ORG_CRITICAL_PRODUCT_LABEL
self.fields["key_product"].label = labels.ORG_KEY_PRODUCT_LABEL
class Meta:
model = Product_Type
fields = ["name", "description", "critical_product", "key_product"]
class Delete_Product_TypeForm(forms.ModelForm):
id = forms.IntegerField(required=True,
widget=forms.widgets.HiddenInput())
class Meta:
model = Product_Type
fields = ["id"]
class Edit_Product_Type_MemberForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["product_type"].disabled = True
self.fields["user"].queryset = Dojo_User.objects.order_by("first_name", "last_name")
self.fields["user"].disabled = True
class Meta:
model = Product_Type_Member
fields = ["product_type", "user", "role"]
class Add_Product_Type_MemberForm(forms.ModelForm):
users = forms.ModelMultipleChoiceField(queryset=Dojo_User.objects.none(), required=True, label="Users")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
current_members = Product_Type_Member.objects.filter(product_type=self.initial["product_type"]).values_list("user", flat=True)
self.fields["users"].queryset = Dojo_User.objects.exclude(
Q(is_superuser=True)
| Q(id__in=current_members)).exclude(is_active=False).order_by("first_name", "last_name")
self.fields["product_type"].label = labels.ORG_LABEL
self.fields["product_type"].disabled = True
class Meta:
model = Product_Type_Member
fields = ["product_type", "users", "role"]
class Add_Product_Type_Member_UserForm(forms.ModelForm):
product_types = forms.ModelMultipleChoiceField(queryset=Product_Type.objects.none(), required=True,
label=labels.ORG_PLURAL_LABEL)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
current_members = Product_Type_Member.objects.filter(user=self.initial["user"]).values_list("product_type", flat=True)
self.fields["product_types"].queryset = get_authorized_product_types(Permissions.Product_Type_Member_Add_Owner) \
.exclude(id__in=current_members)
self.fields["user"].disabled = True
class Meta:
model = Product_Type_Member
fields = ["product_types", "user", "role"]
class Delete_Product_Type_MemberForm(Edit_Product_Type_MemberForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["role"].disabled = True
self.fields["product_type"].label = labels.ORG_LABEL
class Test_TypeForm(forms.ModelForm):
class Meta:
model = Test_Type
exclude = ["dynamically_generated"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.pk:
self.fields["name"].widget.attrs["readonly"] = True
def clean_name(self):
if self.instance.pk:
return self.instance.name
return self.cleaned_data["name"]
class Development_EnvironmentForm(forms.ModelForm):
class Meta:
model = Development_Environment
fields = ["name"]
class Delete_Dev_EnvironmentForm(forms.ModelForm):
class Meta:
model = Development_Environment
fields = ["id"]
class ProductForm(forms.ModelForm):
name = forms.CharField(max_length=255, required=True)
description = forms.CharField(widget=forms.Textarea(attrs={}),
required=True)
prod_type = forms.ModelChoiceField(label=labels.ORG_LABEL,
queryset=Product_Type.objects.none(),
required=True)
sla_configuration = forms.ModelChoiceField(label="SLA Configuration",
queryset=SLA_Configuration.objects.all(),
required=True,
initial="Default")
product_manager = forms.ModelChoiceField(label=labels.ASSET_MANAGER_LABEL,
queryset=Dojo_User.objects.exclude(is_active=False).order_by("first_name", "last_name"), required=False)
technical_contact = forms.ModelChoiceField(queryset=Dojo_User.objects.exclude(is_active=False).order_by("first_name", "last_name"), required=False)
team_manager = forms.ModelChoiceField(queryset=Dojo_User.objects.exclude(is_active=False).order_by("first_name", "last_name"), required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["prod_type"].queryset = get_authorized_product_types(Permissions.Product_Type_Add_Product)
self.fields["enable_product_tag_inheritance"].label = labels.ASSET_TAG_INHERITANCE_ENABLE_LABEL
self.fields["enable_product_tag_inheritance"].help_text = labels.ASSET_TAG_INHERITANCE_ENABLE_HELP
if prod_type_id := kwargs.get("instance", Product()).prod_type_id: # we are editing existing instance
self.fields["prod_type"].queryset |= Product_Type.objects.filter(pk=prod_type_id) # even if user does not have permission for any other ProdType we need to add at least assign ProdType to make form submittable (otherwise empty list was here which generated invalid form)
# if this product has findings being asynchronously updated, disable the sla config field
if self.instance.async_updating:
self.fields["sla_configuration"].disabled = True
self.fields["sla_configuration"].widget.attrs["message"] = (
"Finding SLA expiration dates are currently being recalculated. "
"This field cannot be changed until the calculation is complete."
)
class Meta:
model = Product
fields = ["name", "description", "tags", "product_manager", "technical_contact", "team_manager", "prod_type", "sla_configuration", "regulations",
"business_criticality", "platform", "lifecycle", "origin", "user_records", "revenue", "external_audience", "enable_product_tag_inheritance",
"internet_accessible", "enable_simple_risk_acceptance", "enable_full_risk_acceptance", "disable_sla_breach_notifications"]
def clean_tags(self):
tag_validator(self.cleaned_data.get("tags"))
return self.cleaned_data.get("tags")
class DeleteProductForm(forms.ModelForm):
id = forms.IntegerField(required=True,
widget=forms.widgets.HiddenInput())
class Meta:
model = Product
fields = ["id"]
class EditFindingGroupForm(forms.ModelForm):
name = forms.CharField(max_length=255, required=True, label="Finding Group Name")
jira_issue = forms.CharField(max_length=255, required=False, label="Linked JIRA Issue",
help_text="Leave empty and check push to jira to create a new JIRA issue for this finding group.")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["push_to_jira"] = forms.BooleanField()
self.fields["push_to_jira"].required = False
self.fields["push_to_jira"].help_text = "Checking this will overwrite content of your JIRA issue, or create one."
self.fields["push_to_jira"].label = "Push to JIRA"
if hasattr(self.instance, "has_jira_issue") and self.instance.has_jira_issue:
jira_url = jira_services.get_url(self.instance)
self.fields["jira_issue"].initial = jira_url
self.fields["push_to_jira"].widget.attrs["checked"] = "checked"
class Meta:
model = Finding_Group
fields = ["name"]
class DeleteFindingGroupForm(forms.ModelForm):
id = forms.IntegerField(required=True,
widget=forms.widgets.HiddenInput())
class Meta:
model = Finding_Group
fields = ["id"]
class Edit_Product_MemberForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["product"].disabled = True
self.fields["product"].label = labels.ASSET_LABEL
self.fields["user"].queryset = Dojo_User.objects.order_by("first_name", "last_name")
self.fields["user"].disabled = True
class Meta:
model = Product_Member
fields = ["product", "user", "role"]
class Add_Product_MemberForm(forms.ModelForm):
users = forms.ModelMultipleChoiceField(queryset=Dojo_User.objects.none(), required=True, label="Users")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["product"].disabled = True
self.fields["product"].label = labels.ASSET_LABEL
current_members = Product_Member.objects.filter(product=self.initial["product"]).values_list("user", flat=True)
self.fields["users"].queryset = Dojo_User.objects.exclude(
Q(is_superuser=True)
| Q(id__in=current_members)).exclude(is_active=False).order_by("first_name", "last_name")
class Meta:
model = Product_Member
fields = ["product", "users", "role"]
class Add_Product_Member_UserForm(forms.ModelForm):
products = forms.ModelMultipleChoiceField(queryset=Product.objects.none(), required=True,
label=labels.ASSET_PLURAL_LABEL)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
current_members = Product_Member.objects.filter(user=self.initial["user"]).values_list("product", flat=True)
self.fields["products"].queryset = get_authorized_products(Permissions.Product_Member_Add_Owner) \
.exclude(id__in=current_members)
self.fields["user"].disabled = True
class Meta:
model = Product_Member
fields = ["products", "user", "role"]
class Delete_Product_MemberForm(Edit_Product_MemberForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["role"].disabled = True
class NoteTypeForm(forms.ModelForm):
description = forms.CharField(widget=forms.Textarea(attrs={}),
required=True)
class Meta:
model = Note_Type
fields = ["name", "description", "is_single", "is_mandatory"]
class EditNoteTypeForm(NoteTypeForm):
def __init__(self, *args, **kwargs):
is_single = kwargs.pop("is_single")
super().__init__(*args, **kwargs)
if is_single is False:
self.fields["is_single"].widget = forms.HiddenInput()
class DisableOrEnableNoteTypeForm(NoteTypeForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["name"].disabled = True
self.fields["description"].disabled = True
self.fields["is_single"].disabled = True
self.fields["is_mandatory"].disabled = True
self.fields["is_active"].disabled = True
class Meta:
model = Note_Type
fields = "__all__"
class DojoMetaDataForm(forms.ModelForm):
def full_clean(self):
# inject all fk_map values
for field, value in self.fk_map.items():
setattr(self.instance, field, value)
super().full_clean()
try:
self.instance.validate_unique()
except ValidationError:
msg = "A metadata entry with the same name exists already for this object."
self.add_error("name", msg)
def __init__(self, *args, **kwargs):
self.fk_map = kwargs.pop("fk_map", {})
super().__init__(*args, **kwargs)
class Meta:
model = DojoMeta
fields = "__all__"
DojoMetaFormSet = modelformset_factory(
DojoMeta,
form=DojoMetaDataForm,
extra=1,
can_delete=True,
)
class ImportScanForm(forms.Form):
active_verified_choices = [("not_specified", "Not specified (default)"),
("force_to_true", "Force to True"),
("force_to_false", "Force to False")]
test_title = forms.CharField(max_length=255, required=False, label="Test Title",
help_text="Optional title for the Test to be created. If empty, the scan type is used.")
scan_date = forms.DateTimeField(
required=False,
label="Scan Completion Date",
help_text="Scan completion date will be used on all findings.",
widget=forms.TextInput(attrs={"class": "datepicker"}))
minimum_severity = forms.ChoiceField(help_text="Minimum severity level to be imported",
required=True,
choices=SEVERITY_CHOICES)
active = forms.ChoiceField(required=True, choices=active_verified_choices,
help_text="Force findings to be active/inactive, or default to the original tool")
verified = forms.ChoiceField(required=True, choices=active_verified_choices,
help_text="Force findings to be verified/not verified, or default to the original tool")
# help_do_not_reactivate = 'Select if the import should ignore active findings from the report, useful for triage-less scanners. Will keep existing findings closed, without reactivating them. For more information check the docs.'
# do_not_reactivate = forms.BooleanField(help_text=help_do_not_reactivate, required=False)
scan_type = forms.ChoiceField(required=True, choices=get_choices_sorted)
environment = forms.ModelChoiceField(
queryset=Development_Environment.objects.all().order_by("name"))
endpoints = forms.ModelMultipleChoiceField(Location.objects, required=False, label="Systems / Endpoints")
endpoints_to_add = forms.CharField(max_length=5000, required=False, label="Endpoints to add",
help_text="The IP address, host name or full URL. You may enter one endpoint per line. "
"Each must be valid.",
widget=forms.widgets.Textarea(attrs={"rows": "3", "cols": "400"}))
version = forms.CharField(max_length=100, required=False, help_text="Version that was scanned.")
branch_tag = forms.CharField(max_length=100, required=False, help_text="Branch or Tag that was scanned.")
commit_hash = forms.CharField(max_length=100, required=False, help_text="Commit that was scanned.")
build_id = forms.CharField(max_length=100, required=False, help_text="ID of the build that was scanned.")
api_scan_configuration = forms.ModelChoiceField(Product_API_Scan_Configuration.objects, required=False, label="API Scan Configuration")
service = forms.CharField(max_length=200, required=False,
help_text="A service is a self-contained piece of functionality within a Product. "
"This is an optional field which is used in deduplication and closing of old findings when set.")
source_code_management_uri = forms.URLField(max_length=600, required=False, help_text="Resource link to source code")
tags = TagField(required=False, help_text="Add tags that help describe this scan. "
"Choose from the list or add new tags. Press Enter key to add.")
file = forms.FileField(
widget=forms.widgets.FileInput(attrs={"accept": ", ".join(settings.FILE_IMPORT_TYPES)}),
label="Choose report file",
allow_empty_file=True,
required=False,
validators=[ImporterFileExtensionValidator()],
)
# Close Old Findings has changed. The default is engagement only, and it requires a second flag to expand to the product scope.
# Exposing the choice as two different check boxes.
# If 'close_old_findings_product_scope' is selected, the backend will ensure that both flags are set.
close_old_findings = forms.BooleanField(help_text="Old findings no longer present in the new report get closed as mitigated when importing. "
"If service has been set, only the findings for this service will be closed; "
"if no service is set, only findings without a service will be closed. "
"This affects findings within the same engagement by default.",
label="Close old findings",
required=False,
initial=False)
close_old_findings_product_scope = forms.BooleanField(help_text=labels.ASSET_FINDINGS_CLOSE_HELP,
label=labels.ASSET_FINDINGS_CLOSE_LABEL,
required=False,
initial=False)
apply_tags_to_findings = forms.BooleanField(
help_text="If set to True, the tags will be applied to the findings",
label="Apply Tags to Findings",
required=False,
initial=False,
)
apply_tags_to_endpoints = forms.BooleanField(
help_text="If set to True, the tags will be applied to the endpoints",
label="Apply Tags to Endpoints",
required=False,
initial=False,
)
if is_finding_groups_enabled():
group_by = forms.ChoiceField(required=False, choices=Finding_Group.GROUP_BY_OPTIONS, help_text="Choose an option to automatically group new findings by the chosen option.")
create_finding_groups_for_all_findings = forms.BooleanField(help_text="If unchecked, finding groups will only be created when there is more than one grouped finding", required=False, initial=True)
def __init__(self, *args, **kwargs):
environment = kwargs.pop("environment", None)
endpoints = kwargs.pop("endpoints", None)
api_scan_configuration = kwargs.pop("api_scan_configuration", None)
super().__init__(*args, **kwargs)
self.fields["active"].initial = self.active_verified_choices[0]
self.fields["verified"].initial = self.active_verified_choices[0]
if environment:
self.fields["environment"].initial = environment
if endpoints:
self.fields["endpoints"].queryset = endpoints
elif not settings.V3_FEATURE_LOCATIONS:
# TODO: Delete this after the move to Locations
self.fields["endpoints"].queryset = Endpoint.objects
if api_scan_configuration:
self.fields["api_scan_configuration"].queryset = api_scan_configuration
# couldn't find a cleaner way to add empty default
if "group_by" in self.fields:
choices = self.fields["group_by"].choices
choices.insert(0, ("", "---------"))
self.fields["group_by"].choices = choices
self.endpoints_to_add_list = []
def clean(self):
cleaned_data = super().clean()
scan_type = cleaned_data.get("scan_type")
file = cleaned_data.get("file")
tool_type = requires_tool_type(scan_type)
if requires_file(scan_type) and not file:
msg = _("Uploading a Report File is required for %s") % scan_type
raise forms.ValidationError(msg)
if file and is_scan_file_too_large(file):
msg = _("Report file is too large. Maximum supported size is %d MB") % settings.SCAN_FILE_MAX_SIZE
raise forms.ValidationError(msg)
if tool_type:
api_scan_configuration = cleaned_data.get("api_scan_configuration")
if api_scan_configuration and tool_type != api_scan_configuration.tool_configuration.tool_type.name:
msg = f"API scan configuration must be of tool type {tool_type}"
raise forms.ValidationError(msg)
if settings.V3_FEATURE_LOCATIONS:
endpoints_to_add_list, errors = validate_locations_to_add(cleaned_data["endpoints_to_add"])
else:
# TODO: Delete this after the move to Locations
endpoints_to_add_list, errors = validate_endpoints_to_add(cleaned_data["endpoints_to_add"])
if errors:
raise forms.ValidationError(errors)
self.endpoints_to_add_list = endpoints_to_add_list
return cleaned_data
def clean_tags(self):
tag_validator(self.cleaned_data.get("tags"))
return self.cleaned_data.get("tags")
# date can only be today or in the past, not the future
def clean_scan_date(self):
date = self.cleaned_data.get("scan_date", None)
if date and date.date() > datetime.today().date():
msg = "The date cannot be in the future!"
raise forms.ValidationError(msg)
return date
def get_scan_type(self):
return self.cleaned_data["scan_type"]
class ReImportScanForm(forms.Form):
active_verified_choices = [("not_specified", "Not specified (default)"),
("force_to_true", "Force to True"),
("force_to_false", "Force to False")]
scan_date = forms.DateTimeField(
required=False,
label="Scan Completion Date",
help_text="Scan completion date will be used on all findings.",
widget=forms.TextInput(attrs={"class": "datepicker"}))
minimum_severity = forms.ChoiceField(help_text="Minimum severity level to be imported",
required=True,
choices=SEVERITY_CHOICES[0:4])
active = forms.ChoiceField(required=True, choices=active_verified_choices,
help_text="Force findings to be active/inactive, or default to the original tool")
verified = forms.ChoiceField(required=True, choices=active_verified_choices,
help_text="Force findings to be verified/not verified, or default to the original tool")
help_do_not_reactivate = "Select if the import should ignore active findings from the report, useful for triage-less scanners. Will keep existing findings closed, without reactivating them. For more information check the docs."
do_not_reactivate = forms.BooleanField(help_text=help_do_not_reactivate, required=False)
endpoints = forms.ModelMultipleChoiceField(Location.objects, required=False, label="Systems / Endpoints")
tags = TagField(required=False, help_text="Modify existing tags that help describe this scan. "
"Choose from the list or add new tags. Press Enter key to add.")
file = forms.FileField(
widget=forms.widgets.FileInput(attrs={"accept": ", ".join(settings.FILE_IMPORT_TYPES)}),
label="Choose report file",
allow_empty_file=True,
required=False,
validators=[ImporterFileExtensionValidator()],
)
close_old_findings = forms.BooleanField(help_text="Select if old findings in the same test that are no longer present in the report get closed as mitigated when importing.",
required=False, initial=True)
version = forms.CharField(max_length=100, required=False, help_text="Version that will be set on existing Test object. Leave empty to leave existing value in place.")
branch_tag = forms.CharField(max_length=100, required=False, help_text="Branch or Tag that was scanned.")
commit_hash = forms.CharField(max_length=100, required=False, help_text="Commit that was scanned.")
build_id = forms.CharField(max_length=100, required=False, help_text="ID of the build that was scanned.")
api_scan_configuration = forms.ModelChoiceField(Product_API_Scan_Configuration.objects, required=False, label="API Scan Configuration")
service = forms.CharField(max_length=200, required=False, help_text="A service is a self-contained piece of functionality within a Product. This is an optional field which is used in deduplication of findings when set.")
source_code_management_uri = forms.URLField(max_length=600, required=False, help_text="Resource link to source code")
apply_tags_to_findings = forms.BooleanField(
help_text="If set to True, the tags will be applied to the findings",
label="Apply Tags to Findings",
required=False,
initial=False,
)
apply_tags_to_endpoints = forms.BooleanField(
help_text="If set to True, the tags will be applied to the endpoints",
label="Apply Tags to Endpoints",
required=False,
initial=False,
)
if is_finding_groups_enabled():
group_by = forms.ChoiceField(required=False, choices=Finding_Group.GROUP_BY_OPTIONS, help_text="Choose an option to automatically group new findings by the chosen option")
create_finding_groups_for_all_findings = forms.BooleanField(help_text="If unchecked, finding groups will only be created when there is more than one grouped finding", required=False, initial=True)
def __init__(self, *args, test=None, **kwargs):
endpoints = kwargs.pop("endpoints", None)
api_scan_configuration = kwargs.pop("api_scan_configuration", None)
api_scan_configuration_queryset = kwargs.pop("api_scan_configuration_queryset", None)
super().__init__(*args, **kwargs)
self.fields["active"].initial = self.active_verified_choices[0]
self.fields["verified"].initial = self.active_verified_choices[0]
self.scan_type = None
if test:
self.scan_type = test.test_type.name
self.fields["tags"].initial = test.tags.all()
if endpoints:
self.fields["endpoints"].queryset = endpoints
elif not settings.V3_FEATURE_LOCATIONS:
# TODO: Delete this after the move to Locations
self.fields["endpoints"].queryset = Endpoint.objects
if api_scan_configuration:
self.initial["api_scan_configuration"] = api_scan_configuration
if api_scan_configuration_queryset:
self.fields["api_scan_configuration"].queryset = api_scan_configuration_queryset
# couldn't find a cleaner way to add empty default
if "group_by" in self.fields:
choices = self.fields["group_by"].choices
choices.insert(0, ("", "---------"))
self.fields["group_by"].choices = choices
def clean(self):
cleaned_data = super().clean()
file = cleaned_data.get("file")
if requires_file(self.scan_type) and not file:
msg = _("Uploading a report file is required for re-uploading findings.")
raise forms.ValidationError(msg)
if file and is_scan_file_too_large(file):
msg = _("Report file is too large. Maximum supported size is %d MB") % settings.SCAN_FILE_MAX_SIZE
raise forms.ValidationError(msg)
tool_type = requires_tool_type(self.scan_type)
if tool_type:
api_scan_configuration = cleaned_data.get("api_scan_configuration")
if api_scan_configuration and tool_type != api_scan_configuration.tool_configuration.tool_type.name:
msg = f"API scan configuration must be of tool type {tool_type}"
raise forms.ValidationError(msg)
return cleaned_data
def clean_tags(self):
tag_validator(self.cleaned_data.get("tags"))
return self.cleaned_data.get("tags")
# date can only be today or in the past, not the future
def clean_scan_date(self):
date = self.cleaned_data.get("scan_date", None)
if date and date.date() > timezone.localtime(timezone.now()).date():
msg = "The date cannot be in the future!"
raise forms.ValidationError(msg)
return date
class ImportEndpointMetaForm(forms.Form):
file = forms.FileField(widget=forms.widgets.FileInput(
attrs={"accept": ".csv"}),
label="Choose meta file",
required=True) # Could not get required=True to actually accept the file as present
create_endpoints = forms.BooleanField(
label="Create nonexisting Endpoint",
initial=True,
required=False,
help_text="Create endpoints that do not already exist")
create_tags = forms.BooleanField(
label="Add Tags",
initial=True,
required=False,
help_text="Add meta from file as tags in the format key:value")
create_dojo_meta = forms.BooleanField(
label="Add Meta",
initial=False,
required=False,
help_text="Add data from file as Metadata. Metadata is used for displaying custom fields")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class DoneForm(forms.Form):
done = forms.BooleanField()
class UploadThreatForm(forms.Form):
file = forms.FileField(widget=forms.widgets.FileInput(
attrs={"accept": ".jpg,.png,.pdf"}),
label="Select Threat Model")
def clean(self):
if (file := self.cleaned_data.get("file", None)) is not None:
path = Path(file.name)
ext = path.suffix
valid_extensions = [".jpg", ".png", ".pdf"]
if ext.lower() not in valid_extensions:
if accepted_extensions := f"{', '.join(valid_extensions)}":
msg = (
"Unsupported extension. Supported extensions are as "
f"follows: {accepted_extensions}"
)
else:
msg = (
"File uploads are prohibited due to the list of acceptable "
"file extensions being empty"
)
raise ValidationError(msg)
class MergeFindings(forms.ModelForm):
FINDING_ACTION = (("", "Select an Action"), ("inactive", "Inactive"), ("delete", "Delete"))
append_description = forms.BooleanField(label="Append Description", initial=True, required=False,
help_text="Description in all findings will be appended into the merged finding.")
add_endpoints = forms.BooleanField(label="Add Endpoints", initial=True, required=False,
help_text="Endpoints in all findings will be merged into the merged finding.")
dynamic_raw = forms.BooleanField(label="Dynamic Scanner Raw Requests", initial=True, required=False,
help_text="Dynamic scanner raw requests in all findings will be merged into the merged finding.")
tag_finding = forms.BooleanField(label="Add Tags", initial=True, required=False,
help_text="Tags in all findings will be merged into the merged finding.")
mark_tag_finding = forms.BooleanField(label="Tag Merged Finding", initial=True, required=False,
help_text="Creates a tag titled 'merged' for the finding that will be merged. If the 'Finding Action' is set to 'inactive' the inactive findings will be tagged with 'merged-inactive'.")
append_reference = forms.BooleanField(label="Append Reference", initial=True, required=False,
help_text="Reference in all findings will be appended into the merged finding.")
finding_action = forms.ChoiceField(
required=True,
choices=FINDING_ACTION,
label="Finding Action",
help_text="The action to take on the merged finding. Set the findings to inactive or delete the findings.")
def __init__(self, *args, **kwargs):
_ = kwargs.pop("finding")
findings = kwargs.pop("findings")
super().__init__(*args, **kwargs)
self.fields["finding_to_merge_into"] = forms.ModelChoiceField(
queryset=findings, initial=0, required="False", label="Finding to Merge Into", help_text="Findings selected below will be merged into this finding.")
# Exclude the finding to merge into from the findings to merge into
self.fields["findings_to_merge"] = forms.ModelMultipleChoiceField(
queryset=findings, required=True, label="Findings to Merge",
widget=forms.widgets.SelectMultiple(attrs={"size": 10}),
help_text=("Select the findings to merge."))
self.field_order = ["finding_to_merge_into", "findings_to_merge", "append_description", "add_endpoints", "append_reference"]
class Meta:
model = Finding
fields = ["append_description", "add_endpoints", "append_reference"]
class EditRiskAcceptanceForm(forms.ModelForm):
# unfortunately django forces us to repeat many things here. choices, default, required etc.
recommendation = forms.ChoiceField(choices=Risk_Acceptance.TREATMENT_CHOICES, initial=Risk_Acceptance.TREATMENT_ACCEPT, widget=forms.RadioSelect, label="Security Recommendation")
decision = forms.ChoiceField(choices=Risk_Acceptance.TREATMENT_CHOICES, initial=Risk_Acceptance.TREATMENT_ACCEPT, widget=forms.RadioSelect)
path = forms.FileField(label="Proof", required=False, widget=forms.widgets.FileInput(attrs={"accept": ", ".join(settings.FILE_IMPORT_TYPES)}))
expiration_date = forms.DateTimeField(required=False, widget=forms.TextInput(attrs={"class": "datepicker"}))
class Meta:
model = Risk_Acceptance
exclude = ["accepted_findings", "notes"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["path"].help_text = f"Existing proof uploaded: {self.instance.filename()}" if self.instance.filename() else "None"
self.fields["expiration_date_warned"].disabled = True
self.fields["expiration_date_handled"].disabled = True
def clean_path(self):
if (data := self.cleaned_data.get("path")) is not None:
ext = Path(data.name).suffix # [0] returns path+filename
valid_extensions = settings.FILE_UPLOAD_TYPES
if ext.lower() not in valid_extensions:
if accepted_extensions := f"{', '.join(valid_extensions)}":
msg = f"Unsupported extension. Supported extensions are as follows: {accepted_extensions}"
else:
msg = "File uploads are prohibited due to the list of acceptable file extensions being empty"
raise ValidationError(msg)
return data
class RiskAcceptanceForm(EditRiskAcceptanceForm):
accepted_findings = forms.ModelMultipleChoiceField(
queryset=Finding.objects.none(), required=True,
widget=forms.widgets.SelectMultiple(attrs={"size": 10}),
help_text=("Active, verified findings listed, please select to add findings."))
notes = forms.CharField(required=False, max_length=2400,
widget=forms.Textarea,
label="Notes")
class Meta:
model = Risk_Acceptance
fields = "__all__"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
expiration_delta_days = get_system_setting("risk_acceptance_form_default_days")
logger.debug("expiration_delta_days: %i", expiration_delta_days)
if expiration_delta_days > 0:
expiration_date = timezone.now().date() + relativedelta(days=expiration_delta_days)
# logger.debug('setting default expiration_date: %s', expiration_date)
self.fields["expiration_date"].initial = expiration_date
# self.fields['path'].help_text = 'Existing proof uploaded: %s' % self.instance.filename() if self.instance.filename() else 'None'
self.fields["accepted_findings"].queryset = get_authorized_findings(Permissions.Risk_Acceptance)
if disclaimer := get_system_setting("disclaimer_notes"):
self.disclaimer = disclaimer.strip()
class BaseManageFileFormSet(forms.BaseModelFormSet):
def clean(self):
"""Validate the IP/Mask combo is in CIDR format"""
if any(self.errors):
# Don't bother validating the formset unless each form is valid on its own
return
for form in self.forms:
file = form.cleaned_data.get("file", None)
if file:
path = Path(file.name)
ext = path.suffix
valid_extensions = settings.FILE_UPLOAD_TYPES
if ext.lower() not in valid_extensions:
if accepted_extensions := f"{', '.join(valid_extensions)}":
msg = (
"Unsupported extension. Supported extensions are as "
f"follows: {accepted_extensions}"