-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
forms.py
executable file
·3194 lines (2456 loc) · 136 KB
/
forms.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 os
import re
from datetime import datetime, date
import pickle
from crispy_forms.bootstrap import InlineRadios, InlineCheckboxes
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout
from django.db.models import Count, Q
from dateutil.relativedelta import relativedelta
from django import forms
from django.contrib.auth.password_validation import validate_password
from django.core import validators
from django.core.exceptions import ValidationError
from django.forms import modelformset_factory
from django.forms import utils as form_utils
from django.forms.widgets import Widget, Select
from django.utils.dates import MONTHS
from django.utils.safestring import mark_safe
from django.utils import timezone
import tagulous
from dojo.endpoint.utils import endpoint_get_or_create, endpoint_filter, \
validate_endpoints_to_add
from dojo.models import Finding, Finding_Group, Product_Type, Product, Note_Type, \
Check_List, User, Engagement, Test, Test_Type, Notes, Risk_Acceptance, \
Development_Environment, Dojo_User, Endpoint, Stub_Finding, Finding_Template, \
JIRA_Issue, JIRA_Project, JIRA_Instance, GITHUB_Issue, GITHUB_PKey, GITHUB_Conf, UserContactInfo, Tool_Type, \
Tool_Configuration, Tool_Product_Settings, Cred_User, Cred_Mapping, System_Settings, Notifications, \
Languages, Language_Type, App_Analysis, Objects_Product, Benchmark_Product, Benchmark_Requirement, \
Benchmark_Product_Summary, Rule, Child_Rule, Engagement_Presets, DojoMeta, \
Engagement_Survey, Answered_Survey, TextAnswer, ChoiceAnswer, Choice, Question, TextQuestion, \
ChoiceQuestion, General_Survey, Regulation, FileUpload, SEVERITY_CHOICES, Product_Type_Member, \
Product_Member, Global_Role, Dojo_Group, Product_Group, Product_Type_Group, Dojo_Group_Member, \
Product_API_Scan_Configuration
from dojo.tools.factory import requires_file, get_choices_sorted, requires_tool_type
from dojo.user.helper import user_is_authorized
from django.urls import reverse
from tagulous.forms import TagField
import logging
from crum import get_current_user
from dojo.utils import get_system_setting, get_product
from django.conf import settings
from dojo.authorization.roles_permissions import Permissions
from dojo.product_type.queries import get_authorized_product_types
from dojo.product.queries import get_authorized_products
from dojo.finding.queries import get_authorized_findings
from dojo.user.queries import get_authorized_users_for_product_and_product_type
from dojo.group.queries import get_authorized_groups, get_group_member_roles
logger = logging.getLogger(__name__)
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'))
class MultipleSelectWithPop(forms.SelectMultiple):
def render(self, name, *args, **kwargs):
html = super(MultipleSelectWithPop, self).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,
day_val = [int(v) for v in match.groups()]
output = []
if 'id' in self.attrs:
id_ = self.attrs['id']
else:
id_ = 'id_%s' % 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))
def id_for_label(self, id_):
return '%s_month' % id_
id_for_label = classmethod(id_for_label)
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 '%s-%s-%s' % (y, m, 1)
return data.get(name, None)
class Product_TypeForm(forms.ModelForm):
description = forms.CharField(widget=forms.Textarea(attrs={}),
required=False)
if not settings.FEATURE_AUTHORIZATION_V2:
authorized_users = forms.ModelMultipleChoiceField(
queryset=None,
required=False, label="Authorized Users")
def __init__(self, *args, **kwargs):
non_staff = Dojo_User.objects.exclude(is_staff=True) \
.exclude(is_active=False).order_by('first_name', 'last_name')
super(Product_TypeForm, self).__init__(*args, **kwargs)
if not settings.FEATURE_AUTHORIZATION_V2:
self.fields['authorized_users'].queryset = non_staff
class Meta:
model = Product_Type
if settings.FEATURE_AUTHORIZATION_V2:
fields = ['name', 'description', 'critical_product', 'key_product']
else:
fields = ['name', 'description', 'authorized_users', '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(Edit_Product_Type_MemberForm, self).__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(Add_Product_Type_MemberForm, self).__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'].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='Product Types')
def __init__(self, *args, **kwargs):
super(Add_Product_Type_Member_UserForm, self).__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(Delete_Product_Type_MemberForm, self).__init__(*args, **kwargs)
self.fields['role'].disabled = True
class Test_TypeForm(forms.ModelForm):
class Meta:
model = Test_Type
exclude = ['']
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='Product Type',
queryset=Product_Type.objects.none(),
required=True)
if not settings.FEATURE_AUTHORIZATION_V2:
authorized_users = forms.ModelMultipleChoiceField(
queryset=None,
required=False, label="Authorized Users")
product_manager = forms.ModelChoiceField(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):
non_staff = Dojo_User.objects.exclude(is_staff=True) \
.exclude(is_active=False).order_by('first_name', 'last_name')
super(ProductForm, self).__init__(*args, **kwargs)
if not settings.FEATURE_AUTHORIZATION_V2:
self.fields['authorized_users'].queryset = non_staff
self.fields['prod_type'].queryset = get_authorized_product_types(Permissions.Product_Type_Add_Product)
class Meta:
model = Product
if settings.FEATURE_AUTHORIZATION_V2:
fields = ['name', 'description', 'tags', 'product_manager', 'technical_contact', 'team_manager', 'prod_type', 'regulations',
'business_criticality', 'platform', 'lifecycle', 'origin', 'user_records', 'revenue', 'external_audience',
'internet_accessible', 'enable_simple_risk_acceptance', 'enable_full_risk_acceptance']
else:
fields = ['name', 'description', 'tags', 'product_manager', 'technical_contact', 'team_manager', 'prod_type', 'regulations',
'authorized_users', 'business_criticality', 'platform', 'lifecycle', 'origin', 'user_records', 'revenue', 'external_audience',
'internet_accessible', 'enable_simple_risk_acceptance', 'enable_full_risk_acceptance']
class DeleteProductForm(forms.ModelForm):
id = forms.IntegerField(required=True,
widget=forms.widgets.HiddenInput())
class Meta:
model = Product
fields = ['id']
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(Edit_Product_MemberForm, self).__init__(*args, **kwargs)
self.fields['product'].disabled = True
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(Add_Product_MemberForm, self).__init__(*args, **kwargs)
self.fields['product'].disabled = True
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='Products')
def __init__(self, *args, **kwargs):
super(Add_Product_Member_UserForm, self).__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(Delete_Product_MemberForm, self).__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(EditNoteTypeForm, self).__init__(*args, **kwargs)
if is_single is False:
self.fields['is_single'].widget = forms.HiddenInput()
class DisableOrEnableNoteTypeForm(NoteTypeForm):
def __init__(self, *args, **kwargs):
super(DisableOrEnableNoteTypeForm, self).__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):
value = forms.CharField(widget=forms.Textarea(attrs={}),
required=True)
def full_clean(self):
super(DojoMetaDataForm, self).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)
class Meta:
model = DojoMeta
fields = '__all__'
class ImportScanForm(forms.Form):
scan_date = forms.DateTimeField(
required=True,
label="Scan Completion Date",
help_text="Scan completion date will be used on all findings.",
initial=datetime.now().strftime("%Y-%m-%d"),
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.BooleanField(help_text="Select if these findings are currently active.", required=False, initial=True)
verified = forms.BooleanField(help_text="Select if these findings have been verified.", 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(Endpoint.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 of findings when set.")
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": ".xml, .csv, .nessus, .json, .html, .js, .zip, .xlsx, .txt, .sarif"}),
label="Choose report file",
required=False)
close_old_findings = forms.BooleanField(help_text="Select if old findings no longer present in the report get mitigated when importing."
"This affects the whole engagement/product depending on your deduplication scope.",
required=False, initial=False)
if settings.FEATURE_FINDING_GROUPS:
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.')
def __init__(self, *args, **kwargs):
super(ImportScanForm, self).__init__(*args, **kwargs)
# 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")
if requires_file(scan_type) and not file:
raise forms.ValidationError('Uploading a Report File is required for {}'.format(scan_type))
tool_type = requires_tool_type(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:
raise forms.ValidationError(f'API scan configuration must be of tool type {tool_type}')
endpoints_to_add_list, errors = validate_endpoints_to_add(cleaned_data['endpoints_to_add'])
if errors:
raise forms.ValidationError(errors)
else:
self.endpoints_to_add_list = endpoints_to_add_list
return cleaned_data
# date can only be today or in the past, not the future
def clean_scan_date(self):
date = self.cleaned_data['scan_date']
if date.date() > datetime.today().date():
raise forms.ValidationError("The date cannot be in the future!")
return date
def get_scan_type(self):
TGT_scan = self.cleaned_data['scan_type']
return TGT_scan
class ReImportScanForm(forms.Form):
scan_date = forms.DateTimeField(
required=True,
label="Scan Completion Date",
help_text="Scan completion date will be used on all findings.",
initial=datetime.now().strftime("%m/%d/%Y"),
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.BooleanField(help_text="Select if these findings are currently active.", required=False, initial=True)
verified = forms.BooleanField(help_text="Select if these findings have been verified.", required=False)
endpoints = forms.ModelMultipleChoiceField(Endpoint.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": ".xml, .csv, .nessus, .json, .html, .js, .zip, .xlsx, .txt, .sarif"}),
label="Choose report file",
required=False)
close_old_findings = forms.BooleanField(help_text="Select if old findings get 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.")
if settings.FEATURE_FINDING_GROUPS:
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')
def __init__(self, *args, test=None, **kwargs):
super(ReImportScanForm, self).__init__(*args, **kwargs)
self.scan_type = None
if test:
self.scan_type = test.test_type.name
self.fields['tags'].initial = test.tags.all()
# 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:
raise forms.ValidationError("Uploading a report file is required for re-uploading findings.")
tool_type = requires_tool_type(self.scan_type)
if tool_type:
api_scan_configuration = cleaned_data.get('api_scan_configuration')
if tool_type != api_scan_configuration.tool_configuration.tool_type.name:
raise forms.ValidationError(f'API scan configuration must be of tool type {tool_type}')
return cleaned_data
# date can only be today or in the past, not the future
def clean_scan_date(self):
date = self.cleaned_data['scan_date']
if date.date() > datetime.today().date():
raise forms.ValidationError("The date cannot be in the future!")
return date
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")
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):
finding = kwargs.pop('finding')
findings = kwargs.pop('findings')
super(MergeFindings, self).__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": ".jpg,.png,.pdf"}))
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 = 'Existing proof uploaded: %s' % self.instance.filename() if self.instance.filename() else 'None'
self.fields['expiration_date_warned'].disabled = True
self.fields['expiration_date_handled'].disabled = True
class RiskAcceptanceForm(EditRiskAcceptanceForm):
# path = forms.FileField(label="Proof", required=False, widget=forms.widgets.FileInput(attrs={"accept": ".jpg,.png,.pdf"}))
# expiration_date = forms.DateTimeField(required=False, widget=forms.TextInput(attrs={'class': 'datepicker'}))
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)
class UploadFileForm(forms.ModelForm):
class Meta:
model = FileUpload
fields = ['title', 'file']
ManageFileFormSet = modelformset_factory(FileUpload, extra=3, max_num=10, fields=['title', 'file'], can_delete=True)
class ReplaceRiskAcceptanceProofForm(forms.ModelForm):
path = forms.FileField(label="Proof", required=True, widget=forms.widgets.FileInput(attrs={"accept": ".jpg,.png,.pdf"}))
class Meta:
model = Risk_Acceptance
fields = ['path']
class AddFindingsRiskAcceptanceForm(forms.ModelForm):
accepted_findings = forms.ModelMultipleChoiceField(
queryset=Finding.objects.none(), required=True,
widget=forms.widgets.SelectMultiple(attrs={'size': 10}),
help_text=('Select to add findings.'), label="Add findings as accepted:")
class Meta:
model = Risk_Acceptance
fields = ['accepted_findings']
# exclude = ('name', 'owner', 'path', 'notes', 'accepted_by', 'expiration_date', 'compensating_control')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['accepted_findings'].queryset = get_authorized_findings(Permissions.Risk_Acceptance)
class CheckForm(forms.ModelForm):
options = (('Pass', 'Pass'), ('Fail', 'Fail'), ('N/A', 'N/A'))
session_management = forms.ChoiceField(choices=options)
encryption_crypto = forms.ChoiceField(choices=options)
configuration_management = forms.ChoiceField(choices=options)
authentication = forms.ChoiceField(choices=options)
authorization_and_access_control = forms.ChoiceField(choices=options)
data_input_sanitization_validation = forms.ChoiceField(choices=options)
sensitive_data = forms.ChoiceField(choices=options)
other = forms.ChoiceField(choices=options)
def __init__(self, *args, **kwargs):
findings = kwargs.pop('findings')
super(CheckForm, self).__init__(*args, **kwargs)
self.fields['session_issues'].queryset = findings
self.fields['crypto_issues'].queryset = findings
self.fields['config_issues'].queryset = findings
self.fields['auth_issues'].queryset = findings
self.fields['author_issues'].queryset = findings
self.fields['data_issues'].queryset = findings
self.fields['sensitive_issues'].queryset = findings
self.fields['other_issues'].queryset = findings
class Meta:
model = Check_List
fields = ['session_management', 'session_issues', 'encryption_crypto', 'crypto_issues',
'configuration_management', 'config_issues', 'authentication', 'auth_issues',
'authorization_and_access_control', 'author_issues',
'data_input_sanitization_validation', 'data_issues',
'sensitive_data', 'sensitive_issues', 'other', 'other_issues', ]
class EngForm(forms.ModelForm):
name = forms.CharField(
max_length=300, required=False,
help_text="Add a descriptive name to identify this engagement. " +
"Without a name the target start date will be set.")
description = forms.CharField(widget=forms.Textarea(attrs={}),
required=False, help_text="Description of the engagement and details regarding the engagement.")
product = forms.ModelChoiceField(label='Product',
queryset=Product.objects.none(),
required=True)
target_start = forms.DateField(widget=forms.TextInput(
attrs={'class': 'datepicker', 'autocomplete': 'off'}))
target_end = forms.DateField(widget=forms.TextInput(
attrs={'class': 'datepicker', 'autocomplete': 'off'}))
lead = forms.ModelChoiceField(
queryset=None,
required=True, label="Testing Lead")
test_strategy = forms.URLField(required=False, label="Test Strategy URL")
def __init__(self, *args, **kwargs):
cicd = False
product = None
if 'cicd' in kwargs:
cicd = kwargs.pop('cicd')
if 'product' in kwargs:
product = kwargs.pop('product')
self.user = None
if 'user' in kwargs:
self.user = kwargs.pop('user')
super(EngForm, self).__init__(*args, **kwargs)
if product:
self.fields['preset'] = forms.ModelChoiceField(help_text="Settings and notes for performing this engagement.", required=False, queryset=Engagement_Presets.objects.filter(product=product))
if not settings.FEATURE_AUTHORIZATION_V2:
authorized_for_lead = [user.id for user in User.objects.all() if user_is_authorized(user, 'staff', product)]
self.fields['lead'].queryset = User.objects.filter(id__in=authorized_for_lead)
else:
self.fields['lead'].queryset = get_authorized_users_for_product_and_product_type(None, product, Permissions.Product_View)
else:
self.fields['lead'].queryset = User.objects.exclude(is_staff=False)
self.fields['product'].queryset = get_authorized_products(Permissions.Engagement_Add)
# Don't show CICD fields on a interactive engagement
if cicd is False:
del self.fields['build_id']
del self.fields['commit_hash']
del self.fields['branch_tag']
del self.fields['build_server']
del self.fields['source_code_management_server']
# del self.fields['source_code_management_uri']
del self.fields['orchestration_engine']
else:
del self.fields['test_strategy']
del self.fields['status']
def is_valid(self):
valid = super(EngForm, self).is_valid()
# we're done now if not valid
if not valid:
return valid
if self.cleaned_data['target_start'] > self.cleaned_data['target_end']:
self.add_error('target_start', 'Your target start date exceeds your target end date')
self.add_error('target_end', 'Your target start date exceeds your target end date')
return False
return True
class Meta:
model = Engagement
exclude = ('first_contacted', 'real_start', 'engagement_type',
'real_end', 'requester', 'reason', 'updated', 'report_type',
'product', 'threat_model', 'api_test', 'pen_test', 'check_list')
class DeleteEngagementForm(forms.ModelForm):
id = forms.IntegerField(required=True,
widget=forms.widgets.HiddenInput())
class Meta:
model = Engagement
fields = ['id']
class TestForm(forms.ModelForm):
title = forms.CharField(max_length=255, required=False)
description = forms.CharField(widget=forms.Textarea(attrs={'rows': '3'}), required=False)
test_type = forms.ModelChoiceField(queryset=Test_Type.objects.all().order_by('name'))
environment = forms.ModelChoiceField(
queryset=Development_Environment.objects.all().order_by('name'))
# credential = forms.ModelChoiceField(Cred_User.objects.all(), required=False)
target_start = forms.DateTimeField(widget=forms.TextInput(
attrs={'class': 'datepicker', 'autocomplete': 'off'}))
target_end = forms.DateTimeField(widget=forms.TextInput(
attrs={'class': 'datepicker', 'autocomplete': 'off'}))
lead = forms.ModelChoiceField(
queryset=None,
required=False, label="Testing Lead")
def __init__(self, *args, **kwargs):
obj = None
if 'engagement' in kwargs:
obj = kwargs.pop('engagement')
if 'instance' in kwargs:
obj = kwargs.get('instance')
super(TestForm, self).__init__(*args, **kwargs)
if obj:
product = get_product(obj)
if not settings.FEATURE_AUTHORIZATION_V2:
authorized_for_lead = [user.id for user in User.objects.all() if user_is_authorized(user, 'staff', product)]
self.fields['lead'].queryset = User.objects.filter(id__in=authorized_for_lead)
else:
self.fields['lead'].queryset = get_authorized_users_for_product_and_product_type(None, product, Permissions.Product_View)
self.fields['api_scan_configuration'].queryset = Product_API_Scan_Configuration.objects.filter(product=product)
else:
self.fields['lead'].queryset = User.objects.exclude(is_staff=False)
class Meta:
model = Test
fields = ['title', 'test_type', 'target_start', 'target_end', 'description',
'environment', 'percent_complete', 'tags', 'lead', 'version', 'branch_tag', 'build_id', 'commit_hash',
'api_scan_configuration']
class DeleteTestForm(forms.ModelForm):
id = forms.IntegerField(required=True,
widget=forms.widgets.HiddenInput())
class Meta:
model = Test
fields = ['id']
class AddFindingForm(forms.ModelForm):
title = forms.CharField(max_length=1000)
date = forms.DateField(required=True,
widget=forms.TextInput(attrs={'class': 'datepicker', 'autocomplete': 'off'}))
cwe = forms.IntegerField(required=False)
cve = forms.CharField(max_length=28, required=False)
cvssv3 = forms.CharField(max_length=117, required=False, widget=forms.TextInput(attrs={'class': 'cvsscalculator', 'data-toggle': 'dropdown', 'aria-haspopup': 'true', 'aria-expanded': 'false'}))
description = forms.CharField(widget=forms.Textarea)
severity = forms.ChoiceField(
choices=SEVERITY_CHOICES,
error_messages={
'required': 'Select valid choice: In Progress, On Hold, Completed',
'invalid_choice': 'Select valid choice: Critical,High,Medium,Low'})
mitigation = forms.CharField(widget=forms.Textarea, required=False)
impact = forms.CharField(widget=forms.Textarea, required=False)
request = forms.CharField(widget=forms.Textarea, required=False)
response = forms.CharField(widget=forms.Textarea, required=False)
endpoints = forms.ModelMultipleChoiceField(Endpoint.objects.none(), 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'}))
references = forms.CharField(widget=forms.Textarea, required=False)
publish_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'datepicker', 'autocomplete': 'off'}), required=False)
# the only reliable way without hacking internal fields to get predicatble ordering is to make it explicit
field_order = ('title', 'date', 'cwe', 'cve', 'severity', 'cvssv3', 'description', 'mitigation', 'impact', 'request', 'response', 'steps_to_reproduce',
'severity_justification', 'endpoints', 'endpoints_to_add', 'references', 'active', 'verified', 'false_p', 'duplicate', 'out_of_scope',
'risk_accepted', 'under_defect_review')
def __init__(self, *args, **kwargs):
req_resp = kwargs.pop('req_resp')
product = None
if 'product' in kwargs:
product = kwargs.pop('product')
super(AddFindingForm, self).__init__(*args, **kwargs)
if product:
self.fields['endpoints'].queryset = Endpoint.objects.filter(product=product)
if req_resp:
self.fields['request'].initial = req_resp[0]
self.fields['response'].initial = req_resp[1]
self.endpoints_to_add_list = []
def clean(self):
cleaned_data = super(AddFindingForm, self).clean()
if ((cleaned_data['active'] or cleaned_data['verified']) and cleaned_data['duplicate']):
raise forms.ValidationError('Duplicate findings cannot be'
' verified or active')
if cleaned_data['false_p'] and cleaned_data['verified']:
raise forms.ValidationError('False positive findings cannot '
'be verified.')
if cleaned_data['active'] and 'risk_accepted' in cleaned_data and cleaned_data['risk_accepted']:
raise forms.ValidationError('Active findings cannot '
'be risk accepted.')
endpoints_to_add_list, errors = validate_endpoints_to_add(cleaned_data['endpoints_to_add'])
if errors:
raise forms.ValidationError(errors)
else:
self.endpoints_to_add_list = endpoints_to_add_list
return cleaned_data
class Meta:
model = Finding
exclude = ('reporter', 'url', 'numerical_severity', 'endpoint', 'under_review', 'reviewers',
'review_requested_by', 'is_mitigated', 'jira_creation', 'jira_change', 'endpoint_status', 'sla_start_date')
class AdHocFindingForm(forms.ModelForm):
title = forms.CharField(max_length=1000)
date = forms.DateField(required=True,
widget=forms.TextInput(attrs={'class': 'datepicker', 'autocomplete': 'off'}))
cwe = forms.IntegerField(required=False)
cve = forms.CharField(max_length=28, required=False)
cvssv3 = forms.CharField(max_length=117, required=False, widget=forms.TextInput(attrs={'class': 'cvsscalculator', 'data-toggle': 'dropdown', 'aria-haspopup': 'true', 'aria-expanded': 'false'}))
description = forms.CharField(widget=forms.Textarea)
severity = forms.ChoiceField(
choices=SEVERITY_CHOICES,
error_messages={
'required': 'Select valid choice: In Progress, On Hold, Completed',
'invalid_choice': 'Select valid choice: Critical,High,Medium,Low'})
mitigation = forms.CharField(widget=forms.Textarea, required=False)
impact = forms.CharField(widget=forms.Textarea, required=False)
request = forms.CharField(widget=forms.Textarea, required=False)
response = forms.CharField(widget=forms.Textarea, required=False)
endpoints = forms.ModelMultipleChoiceField(queryset=Endpoint.objects.none(), 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'}))
references = forms.CharField(widget=forms.Textarea, required=False)
publish_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'datepicker', 'autocomplete': 'off'}), required=False)
# the only reliable way without hacking internal fields to get predicatble ordering is to make it explicit
field_order = ('title', 'date', 'cwe', 'cve', 'severity', 'cvssv3', 'description', 'mitigation', 'impact', 'request', 'response', 'steps_to_reproduce',
'severity_justification', 'endpoints', 'endpoints_to_add', 'references', 'active', 'verified', 'false_p', 'duplicate', 'out_of_scope',
'risk_accepted', 'under_defect_review', 'sla_start_date')
def __init__(self, *args, **kwargs):
req_resp = kwargs.pop('req_resp')
product = None
if 'product' in kwargs:
product = kwargs.pop('product')
super(AdHocFindingForm, self).__init__(*args, **kwargs)
if product:
self.fields['endpoints'].queryset = Endpoint.objects.filter(product=product)
if req_resp:
self.fields['request'].initial = req_resp[0]
self.fields['response'].initial = req_resp[1]
self.endpoints_to_add_list = []
def clean(self):
cleaned_data = super(AdHocFindingForm, self).clean()
if ((cleaned_data['active'] or cleaned_data['verified']) and cleaned_data['duplicate']):
raise forms.ValidationError('Duplicate findings cannot be'
' verified or active')
if cleaned_data['false_p'] and cleaned_data['verified']:
raise forms.ValidationError('False positive findings cannot '
'be verified.')
endpoints_to_add_list, errors = validate_endpoints_to_add(cleaned_data['endpoints_to_add'])
if errors:
raise forms.ValidationError(errors)
else:
self.endpoints_to_add_list = endpoints_to_add_list
return cleaned_data