-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
views.py
1962 lines (1715 loc) · 89 KB
/
views.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
# # product
import base64
import calendar as tcalendar
import contextlib
import logging
from collections import OrderedDict
from datetime import date, datetime, timedelta
from math import ceil
from dateutil.relativedelta import relativedelta
from django.contrib import messages
from django.contrib.admin.utils import NestedObjects
from django.contrib.postgres.aggregates import StringAgg
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import DEFAULT_DB_ALIAS, connection
from django.db.models import Count, F, Max, OuterRef, Prefetch, Q, Subquery, Sum
from django.db.models.expressions import Value
from django.db.models.query import QuerySet
from django.http import Http404, HttpRequest, HttpResponseRedirect, JsonResponse
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext as _
from django.views import View
from github import Github
import dojo.finding.helper as finding_helper
import dojo.jira_link.helper as jira_helper
from dojo.authorization.authorization import user_has_permission, user_has_permission_or_403
from dojo.authorization.authorization_decorators import user_is_authorized
from dojo.authorization.roles_permissions import Permissions
from dojo.components.sql_group_concat import Sql_GroupConcat
from dojo.filters import (
EngagementFilter,
EngagementFilterWithoutObjectLookups,
MetricsEndpointFilter,
MetricsEndpointFilterWithoutObjectLookups,
MetricsFindingFilter,
MetricsFindingFilterWithoutObjectLookups,
ProductComponentFilter,
ProductEngagementFilter,
ProductEngagementFilterWithoutObjectLookups,
ProductFilter,
ProductFilterWithoutObjectLookups,
)
from dojo.forms import (
Add_Product_GroupForm,
Add_Product_MemberForm,
AdHocFindingForm,
AppAnalysisForm,
Delete_Product_GroupForm,
Delete_Product_MemberForm,
DeleteAppAnalysisForm,
DeleteEngagementPresetsForm,
DeleteProduct_API_Scan_ConfigurationForm,
DeleteProductForm,
DojoMetaDataForm,
Edit_Product_Group_Form,
Edit_Product_MemberForm,
EngagementPresetsForm,
EngForm,
GITHUB_Product_Form,
GITHUBFindingForm,
JIRAEngagementForm,
JIRAFindingForm,
JIRAProjectForm,
Product_API_Scan_ConfigurationForm,
ProductForm,
ProductNotificationsForm,
SLA_Configuration,
)
from dojo.models import (
App_Analysis,
Benchmark_Product_Summary,
BurpRawRequestResponse,
DojoMeta,
Endpoint,
Endpoint_Status,
Engagement,
Engagement_Presets,
Finding,
GITHUB_PKey,
Languages,
Note_Type,
Notifications,
Product,
Product_API_Scan_Configuration,
Product_Group,
Product_Member,
Product_Type,
System_Settings,
Test,
Test_Type,
)
from dojo.product.queries import (
get_authorized_global_groups_for_product,
get_authorized_global_members_for_product,
get_authorized_groups_for_product,
get_authorized_members_for_product,
get_authorized_products,
)
from dojo.product_type.queries import (
get_authorized_groups_for_product_type,
get_authorized_members_for_product_type,
get_authorized_product_types,
)
from dojo.templatetags.display_tags import asvs_calc_level
from dojo.tool_config.factory import create_API
from dojo.tools.factory import get_api_scan_configuration_hints
from dojo.utils import (
Product_Tab,
add_breadcrumb,
add_error_message_to_response,
add_external_issue,
add_field_errors_to_response,
async_delete,
calculate_finding_age,
get_enabled_notifications_list,
get_open_findings_burndown,
get_page_items,
get_punchcard_data,
get_setting,
get_system_setting,
get_zero_severity_level,
is_title_in_breadcrumbs,
queryset_check,
sum_by_severity_level,
)
logger = logging.getLogger(__name__)
def product(request):
prods = get_authorized_products(Permissions.Product_View)
# perform all stuff for filtering and pagination first, before annotation/prefetching
# otherwise the paginator will perform all the annotations/prefetching already only to count the total number of records
# see https://code.djangoproject.com/ticket/23771 and https://code.djangoproject.com/ticket/25375
name_words = prods.values_list("name", flat=True)
prods = prods.annotate(
findings_count=Count("engagement__test__finding", filter=Q(engagement__test__finding__active=True)),
)
filter_string_matching = get_system_setting("filter_string_matching", False)
filter_class = ProductFilterWithoutObjectLookups if filter_string_matching else ProductFilter
prod_filter = filter_class(request.GET, queryset=prods, user=request.user)
prod_list = get_page_items(request, prod_filter.qs, 25)
# perform annotation/prefetching by replacing the queryset in the page with an annotated/prefetched queryset.
prod_list.object_list = prefetch_for_product(prod_list.object_list)
add_breadcrumb(title=_("Product List"), top_level=not len(request.GET), request=request)
return render(request, "dojo/product.html", {
"prod_list": prod_list,
"prod_filter": prod_filter,
"name_words": sorted(set(name_words)),
"enable_table_filtering": get_system_setting("enable_ui_table_based_searching"),
"user": request.user})
def prefetch_for_product(prods):
prefetched_prods = prods
if isinstance(prods,
QuerySet): # old code can arrive here with prods being a list because the query was already executed
prefetched_prods = prefetched_prods.prefetch_related("team_manager")
prefetched_prods = prefetched_prods.prefetch_related("product_manager")
prefetched_prods = prefetched_prods.prefetch_related("technical_contact")
prefetched_prods = prefetched_prods.annotate(
active_engagement_count=Count("engagement__id", filter=Q(engagement__active=True)))
prefetched_prods = prefetched_prods.annotate(
closed_engagement_count=Count("engagement__id", filter=Q(engagement__active=False)))
prefetched_prods = prefetched_prods.annotate(last_engagement_date=Max("engagement__target_start"))
prefetched_prods = prefetched_prods.annotate(active_finding_count=Count("engagement__test__finding__id",
filter=Q(
engagement__test__finding__active=True)))
prefetched_prods = prefetched_prods.annotate(
active_verified_finding_count=Count("engagement__test__finding__id",
filter=Q(
engagement__test__finding__active=True,
engagement__test__finding__verified=True)))
prefetched_prods = prefetched_prods.prefetch_related("jira_project_set__jira_instance")
prefetched_prods = prefetched_prods.prefetch_related("members")
prefetched_prods = prefetched_prods.prefetch_related("prod_type__members")
active_endpoint_query = Endpoint.objects.filter(
status_endpoint__mitigated=False,
status_endpoint__false_positive=False,
status_endpoint__out_of_scope=False,
status_endpoint__risk_accepted=False,
).distinct()
prefetched_prods = prefetched_prods.prefetch_related(
Prefetch("endpoint_set", queryset=active_endpoint_query, to_attr="active_endpoints"))
prefetched_prods = prefetched_prods.prefetch_related("tags")
if get_system_setting("enable_github"):
prefetched_prods = prefetched_prods.prefetch_related(
Prefetch("github_pkey_set", queryset=GITHUB_PKey.objects.all().select_related("git_conf"),
to_attr="github_confs"))
else:
logger.debug("unable to prefetch because query was already executed")
return prefetched_prods
def iso_to_gregorian(iso_year, iso_week, iso_day):
jan4 = date(iso_year, 1, 4)
start = jan4 - timedelta(days=jan4.isoweekday() - 1)
return start + timedelta(weeks=iso_week - 1, days=iso_day - 1)
@user_is_authorized(Product, Permissions.Product_View, "pid")
def view_product(request, pid):
prod_query = Product.objects.all().select_related("product_manager", "technical_contact", "team_manager", "sla_configuration") \
.prefetch_related("members") \
.prefetch_related("prod_type__members")
prod = get_object_or_404(prod_query, id=pid)
product_members = get_authorized_members_for_product(prod, Permissions.Product_View)
global_product_members = get_authorized_global_members_for_product(prod, Permissions.Product_View)
product_type_members = get_authorized_members_for_product_type(prod.prod_type, Permissions.Product_Type_View)
product_groups = get_authorized_groups_for_product(prod, Permissions.Product_View)
global_product_groups = get_authorized_global_groups_for_product(prod, Permissions.Product_View)
product_type_groups = get_authorized_groups_for_product_type(prod.prod_type, Permissions.Product_Type_View)
personal_notifications_form = ProductNotificationsForm(
instance=Notifications.objects.filter(user=request.user).filter(product=prod).first())
langSummary = Languages.objects.filter(product=prod).aggregate(Sum("files"), Sum("code"), Count("files"))
languages = Languages.objects.filter(product=prod).order_by("-code").select_related("language")
app_analysis = App_Analysis.objects.filter(product=prod).order_by("name")
benchmarks = Benchmark_Product_Summary.objects.filter(product=prod, publish=True,
benchmark_type__enabled=True).order_by("benchmark_type__name")
sla = SLA_Configuration.objects.filter(id=prod.sla_configuration_id).first()
benchAndPercent = []
for i in range(len(benchmarks)):
desired_level, total, total_pass, total_wait, total_fail, _total_viewed = asvs_calc_level(benchmarks[i])
success_percent = round((float(total_pass) / float(total)) * 100, 2)
waiting_percent = round((float(total_wait) / float(total)) * 100, 2)
fail_percent = round(100 - success_percent - waiting_percent, 2)
benchAndPercent.append({
"id": benchmarks[i].benchmark_type.id,
"name": benchmarks[i].benchmark_type,
"level": desired_level,
"success": {"count": total_pass, "percent": success_percent},
"waiting": {"count": total_wait, "percent": waiting_percent},
"fail": {"count": total_fail, "percent": fail_percent},
"pass": total_pass + total_fail,
"total": total,
})
system_settings = System_Settings.objects.get()
product_metadata = dict(prod.product_meta.order_by("name").values_list("name", "value"))
open_findings = Finding.objects.filter(test__engagement__product=prod,
false_p=False,
active=True,
duplicate=False,
out_of_scope=False).order_by("numerical_severity").values(
"severity").annotate(count=Count("severity"))
critical = 0
high = 0
medium = 0
low = 0
info = 0
for v in open_findings:
if v["severity"] == "Critical":
critical = v["count"]
elif v["severity"] == "High":
high = v["count"]
elif v["severity"] == "Medium":
medium = v["count"]
elif v["severity"] == "Low":
low = v["count"]
elif v["severity"] == "Info":
info = v["count"]
total = critical + high + medium + low + info
product_tab = Product_Tab(prod, title=_("Product"), tab="overview")
return render(request, "dojo/view_product_details.html", {
"prod": prod,
"product_tab": product_tab,
"product_metadata": product_metadata,
"critical": critical,
"high": high,
"medium": medium,
"low": low,
"info": info,
"total": total,
"user": request.user,
"languages": languages,
"langSummary": langSummary,
"app_analysis": app_analysis,
"system_settings": system_settings,
"benchmarks_percents": benchAndPercent,
"benchmarks": benchmarks,
"product_members": product_members,
"global_product_members": global_product_members,
"product_type_members": product_type_members,
"product_groups": product_groups,
"global_product_groups": global_product_groups,
"product_type_groups": product_type_groups,
"personal_notifications_form": personal_notifications_form,
"enabled_notifications": get_enabled_notifications_list(),
"sla": sla})
@user_is_authorized(Product, Permissions.Component_View, "pid")
def view_product_components(request, pid):
prod = get_object_or_404(Product, id=pid)
product_tab = Product_Tab(prod, title=_("Product"), tab="components")
separator = ", "
# Get components ordered by component_name and concat component versions to the same row
if connection.vendor == "postgresql":
component_query = Finding.objects.filter(test__engagement__product__id=pid).values("component_name").order_by(
"component_name").annotate(
component_version=StringAgg("component_version", delimiter=separator, distinct=True, default=Value("")))
else:
component_query = Finding.objects.filter(test__engagement__product__id=pid).values("component_name")
component_query = component_query.annotate(
component_version=Sql_GroupConcat("component_version", separator=separator, distinct=True))
# Append finding counts
component_query = component_query.annotate(total=Count("id")).order_by("component_name", "component_version")
component_query = component_query.annotate(active=Count("id", filter=Q(active=True)))
component_query = component_query.annotate(duplicate=(Count("id", filter=Q(duplicate=True))))
# Default sort by total descending
component_query = component_query.order_by("-total")
comp_filter = ProductComponentFilter(request.GET, queryset=component_query)
result = get_page_items(request, comp_filter.qs, 25)
# Filter out None values for auto-complete
component_words = component_query.exclude(component_name__isnull=True).values_list("component_name", flat=True)
return render(request, "dojo/product_components.html", {
"prod": prod,
"filter": comp_filter,
"product_tab": product_tab,
"result": result,
"enable_table_filtering": get_system_setting("enable_ui_table_based_searching"),
"component_words": sorted(set(component_words)),
})
def identify_view(request):
get_data = request.GET
view = get_data.get("type", None)
if view:
# value of view is reflected in the template, make sure it's valid
# although any XSS should be catch by django autoescape, we see people sometimes using '|safe'...
if view in ["Endpoint", "Finding"]:
return view
msg = 'invalid view, view must be "Endpoint" or "Finding"'
raise ValueError(msg)
if get_data.get("finding__severity", None) or get_data.get("false_positive", None):
return "Endpoint"
referer = request.META.get("HTTP_REFERER", None)
if referer:
if referer.find("type=Endpoint") > -1:
return "Endpoint"
return "Finding"
def finding_querys(request, prod):
filters = {}
findings_query = Finding.objects.filter(test__engagement__product=prod)
# prefetch only what's needed to avoid lots of repeated queries
findings_query = findings_query.prefetch_related(
# 'test__engagement',
# 'test__engagement__risk_acceptance',
# 'found_by',
# 'test',
# 'test__test_type',
# 'risk_acceptance_set',
"reporter")
filter_string_matching = get_system_setting("filter_string_matching", False)
finding_filter_class = MetricsFindingFilterWithoutObjectLookups if filter_string_matching else MetricsFindingFilter
findings = finding_filter_class(request.GET, queryset=findings_query, pid=prod)
findings_qs = queryset_check(findings)
filters["form"] = findings.form
try:
# logger.debug(findings_qs.query)
start_date = findings_qs.earliest("date").date
start_date = datetime(
start_date.year,
start_date.month, start_date.day,
tzinfo=timezone.get_current_timezone())
end_date = findings_qs.latest("date").date
end_date = datetime(
end_date.year,
end_date.month, end_date.day,
tzinfo=timezone.get_current_timezone())
except Exception as e:
logger.debug(e)
start_date = timezone.now()
end_date = timezone.now()
week = end_date - timedelta(days=7) # seven days and /newer are considered "new"
filters["accepted"] = findings_qs.filter(finding_helper.ACCEPTED_FINDINGS_QUERY).filter(date__range=[start_date, end_date]).order_by("date")
filters["verified"] = findings_qs.filter(finding_helper.VERIFIED_FINDINGS_QUERY).filter(date__range=[start_date, end_date]).order_by("date")
filters["new_verified"] = findings_qs.filter(finding_helper.VERIFIED_FINDINGS_QUERY).filter(date__range=[start_date, end_date]).order_by("date")
filters["open"] = findings_qs.filter(finding_helper.OPEN_FINDINGS_QUERY).filter(date__range=[start_date, end_date]).order_by("date")
filters["inactive"] = findings_qs.filter(finding_helper.INACTIVE_FINDINGS_QUERY).filter(date__range=[start_date, end_date]).order_by("date")
filters["closed"] = findings_qs.filter(finding_helper.CLOSED_FINDINGS_QUERY).filter(date__range=[start_date, end_date]).order_by("date")
filters["false_positive"] = findings_qs.filter(finding_helper.FALSE_POSITIVE_FINDINGS_QUERY).filter(date__range=[start_date, end_date]).order_by("date")
filters["out_of_scope"] = findings_qs.filter(finding_helper.OUT_OF_SCOPE_FINDINGS_QUERY).filter(date__range=[start_date, end_date]).order_by("date")
filters["all"] = findings_qs.order_by("date")
filters["open_vulns"] = findings_qs.filter(finding_helper.OPEN_FINDINGS_QUERY).filter(
cwe__isnull=False,
).order_by("cwe").values(
"cwe",
).annotate(
count=Count("cwe"),
)
filters["all_vulns"] = findings_qs.filter(
duplicate=False,
cwe__isnull=False,
).order_by("cwe").values(
"cwe",
).annotate(
count=Count("cwe"),
)
filters["start_date"] = start_date
filters["end_date"] = end_date
filters["week"] = week
return filters
def endpoint_querys(request, prod):
filters = {}
endpoints_query = Endpoint_Status.objects.filter(finding__test__engagement__product=prod,
finding__severity__in=(
"Critical", "High", "Medium", "Low", "Info")).prefetch_related(
"finding__test__engagement",
"finding__test__engagement__risk_acceptance",
"finding__risk_acceptance_set",
"finding__reporter").annotate(severity=F("finding__severity"))
filter_string_matching = get_system_setting("filter_string_matching", False)
filter_class = MetricsEndpointFilterWithoutObjectLookups if filter_string_matching else MetricsEndpointFilter
endpoints = filter_class(request.GET, queryset=endpoints_query)
endpoints_qs = queryset_check(endpoints)
filters["form"] = endpoints.form
if not endpoints_qs and not endpoints_query:
endpoints = endpoints_query
endpoints_qs = queryset_check(endpoints)
messages.add_message(request,
messages.ERROR,
_("All objects have been filtered away. Displaying all objects"),
extra_tags="alert-danger")
try:
start_date = endpoints_qs.earliest("date").date
start_date = datetime(start_date.year,
start_date.month, start_date.day,
tzinfo=timezone.get_current_timezone())
end_date = endpoints_qs.latest("date").date
end_date = datetime(end_date.year,
end_date.month, end_date.day,
tzinfo=timezone.get_current_timezone())
except:
start_date = timezone.now()
end_date = timezone.now()
week = end_date - timedelta(days=7) # seven days and /newnewer are considered "new"
filters["accepted"] = endpoints_qs.filter(date__range=[start_date, end_date],
risk_accepted=True).order_by("date")
filters["verified"] = endpoints_qs.filter(date__range=[start_date, end_date],
false_positive=False,
mitigated=True,
out_of_scope=False).order_by("date")
filters["new_verified"] = endpoints_qs.filter(date__range=[week, end_date],
false_positive=False,
mitigated=True,
out_of_scope=False).order_by("date")
filters["open"] = endpoints_qs.filter(date__range=[start_date, end_date],
mitigated=False,
finding__active=True)
filters["inactive"] = endpoints_qs.filter(date__range=[start_date, end_date],
mitigated=True)
filters["closed"] = endpoints_qs.filter(date__range=[start_date, end_date],
mitigated=True)
filters["false_positive"] = endpoints_qs.filter(date__range=[start_date, end_date],
false_positive=True)
filters["out_of_scope"] = endpoints_qs.filter(date__range=[start_date, end_date],
out_of_scope=True)
filters["all"] = endpoints_qs
filters["open_vulns"] = endpoints_qs.filter(
false_positive=False,
out_of_scope=False,
mitigated=True,
finding__cwe__isnull=False,
).order_by("finding__cwe").values(
"finding__cwe",
).annotate(
count=Count("finding__cwe"),
).annotate(
cwe=F("finding__cwe"),
)
filters["all_vulns"] = endpoints_qs.filter(
finding__cwe__isnull=False,
).order_by("finding__cwe").values(
"finding__cwe",
).annotate(
count=Count("finding__cwe"),
).annotate(
cwe=F("finding__cwe"),
)
filters["start_date"] = start_date
filters["end_date"] = end_date
filters["week"] = week
return filters
@user_is_authorized(Product, Permissions.Product_View, "pid")
def view_product_metrics(request, pid):
prod = get_object_or_404(Product, id=pid)
engs = Engagement.objects.filter(product=prod, active=True)
view = identify_view(request)
filter_string_matching = get_system_setting("filter_string_matching", False)
filter_class = EngagementFilterWithoutObjectLookups if filter_string_matching else EngagementFilter
result = filter_class(
request.GET,
queryset=Engagement.objects.filter(product=prod, active=False).order_by("-target_end"))
inactive_engs_page = get_page_items(request, result.qs, 10)
filters = {}
if view == "Finding":
filters = finding_querys(request, prod)
elif view == "Endpoint":
filters = endpoint_querys(request, prod)
start_date = timezone.make_aware(datetime.combine(filters["start_date"], datetime.min.time()))
end_date = filters["end_date"]
r = relativedelta(end_date, start_date)
weeks_between = int(ceil((((r.years * 12) + r.months) * 4.33) + (r.days / 7)))
if weeks_between <= 0:
weeks_between += 2
punchcard, ticks = get_punchcard_data(filters.get("open", None), start_date, weeks_between, view)
add_breadcrumb(parent=prod, top_level=False, request=request)
# An ordered dict does not make sense here.
open_close_weekly = OrderedDict()
severity_weekly = OrderedDict()
critical_weekly = OrderedDict()
high_weekly = OrderedDict()
medium_weekly = OrderedDict()
open_objs_by_age = {}
open_objs_by_severity = get_zero_severity_level()
closed_objs_by_severity = get_zero_severity_level()
accepted_objs_by_severity = get_zero_severity_level()
# Optimization: Make all queries lists, and only pull values of fields for metrics based calculations
open_vulnerabilities = list(filters["open_vulns"].values("cwe", "count"))
all_vulnerabilities = list(filters["all_vulns"].values("cwe", "count"))
verified_objs_by_severity = list(filters.get("verified").values("severity"))
inactive_objs_by_severity = list(filters.get("inactive").values("severity"))
false_positive_objs_by_severity = list(filters.get("false_positive").values("severity"))
out_of_scope_objs_by_severity = list(filters.get("out_of_scope").values("severity"))
new_objs_by_severity = list(filters.get("new_verified").values("severity"))
all_objs_by_severity = list(filters.get("all").values("severity"))
all_findings = list(filters.get("all", []).values("id", "date", "severity"))
open_findings = list(filters.get("open", []).values("id", "date", "mitigated", "severity"))
closed_findings = list(filters.get("closed", []).values("id", "date", "severity"))
accepted_findings = list(filters.get("accepted", []).values("id", "date", "severity"))
"""
Optimization: Create dictionaries in the structure of { finding_id: True } for index based search
Previously the for-loop below used "if finding in open_findings" -- an average O(n^2) time complexity
This allows for "if open_findings.get(finding_id, None)" -- an average O(n) time complexity
"""
open_findings_dict = {f.get("id"): True for f in open_findings}
closed_findings_dict = {f.get("id"): True for f in closed_findings}
accepted_findings_dict = {f.get("id"): True for f in accepted_findings}
for finding in all_findings:
iso_cal = finding.get("date").isocalendar()
date = iso_to_gregorian(iso_cal[0], iso_cal[1], 1)
html_date = date.strftime("<span class='small'>%m/%d<br/>%Y</span>")
unix_timestamp = (tcalendar.timegm(date.timetuple()) * 1000)
# Open findings
if open_findings_dict.get(finding.get("id", None), None):
if unix_timestamp not in critical_weekly:
critical_weekly[unix_timestamp] = {"count": 0, "week": html_date}
if unix_timestamp not in high_weekly:
high_weekly[unix_timestamp] = {"count": 0, "week": html_date}
if unix_timestamp not in medium_weekly:
medium_weekly[unix_timestamp] = {"count": 0, "week": html_date}
if unix_timestamp in open_close_weekly:
open_close_weekly[unix_timestamp]["open"] += 1
else:
open_close_weekly[unix_timestamp] = {"closed": 0, "open": 1, "accepted": 0}
open_close_weekly[unix_timestamp]["week"] = html_date
if view == "Finding" or view == "Endpoint":
severity = finding.get("severity")
finding_age = calculate_finding_age(finding)
if open_objs_by_age.get(finding_age):
open_objs_by_age[finding_age] += 1
else:
open_objs_by_age[finding_age] = 1
if unix_timestamp in severity_weekly:
if severity in severity_weekly[unix_timestamp]:
severity_weekly[unix_timestamp][severity] += 1
else:
severity_weekly[unix_timestamp][severity] = 1
else:
severity_weekly[unix_timestamp] = get_zero_severity_level()
severity_weekly[unix_timestamp][severity] = 1
severity_weekly[unix_timestamp]["week"] = html_date
if severity == "Critical":
if unix_timestamp in critical_weekly:
critical_weekly[unix_timestamp]["count"] += 1
else:
critical_weekly[unix_timestamp] = {"count": 1, "week": html_date}
elif severity == "High":
if unix_timestamp in high_weekly:
high_weekly[unix_timestamp]["count"] += 1
else:
high_weekly[unix_timestamp] = {"count": 1, "week": html_date}
elif severity == "Medium":
if unix_timestamp in medium_weekly:
medium_weekly[unix_timestamp]["count"] += 1
else:
medium_weekly[unix_timestamp] = {"count": 1, "week": html_date}
# Optimization: count severity level on server side
if open_objs_by_severity.get(finding.get("severity")) is not None:
open_objs_by_severity[finding.get("severity")] += 1
# Close findings
elif closed_findings_dict.get(finding.get("id", None), None):
if unix_timestamp in open_close_weekly:
open_close_weekly[unix_timestamp]["closed"] += 1
else:
open_close_weekly[unix_timestamp] = {"closed": 1, "open": 0, "accepted": 0}
open_close_weekly[unix_timestamp]["week"] = html_date
# Optimization: count severity level on server side
if closed_objs_by_severity.get(finding.get("severity")) is not None:
closed_objs_by_severity[finding.get("severity")] += 1
# Risk Accepted findings
if accepted_findings_dict.get(finding.get("id", None), None):
if unix_timestamp in open_close_weekly:
open_close_weekly[unix_timestamp]["accepted"] += 1
else:
open_close_weekly[unix_timestamp] = {"closed": 0, "open": 0, "accepted": 1}
open_close_weekly[unix_timestamp]["week"] = html_date
# Optimization: count severity level on server side
if accepted_objs_by_severity.get(finding.get("severity")) is not None:
accepted_objs_by_severity[finding.get("severity")] += 1
tests = Test.objects.filter(engagement__product=prod).prefetch_related("finding_set", "test_type")
tests = tests.annotate(verified_finding_count=Count("finding__id", filter=Q(finding__verified=True)))
test_data = {}
for t in tests:
if t.test_type.name in test_data:
test_data[t.test_type.name] += t.verified_finding_count
else:
test_data[t.test_type.name] = t.verified_finding_count
# Optimization: Format Open/Total CWE vulnerabilities graph data here, instead of template
open_vulnerabilities = [["CWE-" + str(f.get("cwe")), f.get("count")] for f in open_vulnerabilities]
all_vulnerabilities = [["CWE-" + str(f.get("cwe")), f.get("count")] for f in all_vulnerabilities]
product_tab = Product_Tab(prod, title=_("Product"), tab="metrics")
return render(request, "dojo/product_metrics.html", {
"prod": prod,
"product_tab": product_tab,
"engs": engs,
"inactive_engs": inactive_engs_page,
"view": view,
"verified_objs": len(verified_objs_by_severity),
"verified_objs_by_severity": sum_by_severity_level(verified_objs_by_severity),
"open_objs": len(open_findings),
"open_objs_by_severity": open_objs_by_severity,
"open_objs_by_age": open_objs_by_age,
"inactive_objs": len(inactive_objs_by_severity),
"inactive_objs_by_severity": sum_by_severity_level(inactive_objs_by_severity),
"closed_objs": len(closed_findings),
"closed_objs_by_severity": closed_objs_by_severity,
"false_positive_objs": len(false_positive_objs_by_severity),
"false_positive_objs_by_severity": sum_by_severity_level(false_positive_objs_by_severity),
"out_of_scope_objs": len(out_of_scope_objs_by_severity),
"out_of_scope_objs_by_severity": sum_by_severity_level(out_of_scope_objs_by_severity),
"accepted_objs": len(accepted_findings),
"accepted_objs_by_severity": accepted_objs_by_severity,
"new_objs": len(new_objs_by_severity),
"new_objs_by_severity": sum_by_severity_level(new_objs_by_severity),
"all_objs": len(all_objs_by_severity),
"all_objs_by_severity": sum_by_severity_level(all_objs_by_severity),
"form": filters.get("form", None),
"reset_link": reverse("view_product_metrics", args=(prod.id,)) + "?type=" + view,
"open_vulnerabilities_count": len(open_vulnerabilities),
"open_vulnerabilities": open_vulnerabilities,
"all_vulnerabilities_count": len(all_vulnerabilities),
"all_vulnerabilities": all_vulnerabilities,
"start_date": start_date,
"punchcard": punchcard,
"ticks": ticks,
"open_close_weekly": open_close_weekly,
"severity_weekly": severity_weekly,
"critical_weekly": critical_weekly,
"high_weekly": high_weekly,
"medium_weekly": medium_weekly,
"test_data": test_data,
"user": request.user})
@user_is_authorized(Product, Permissions.Product_View, "pid")
def async_burndown_metrics(request, pid):
prod = get_object_or_404(Product, id=pid)
open_findings_burndown = get_open_findings_burndown(prod)
return JsonResponse({
"critical": open_findings_burndown.get("Critical", []),
"high": open_findings_burndown.get("High", []),
"medium": open_findings_burndown.get("Medium", []),
"low": open_findings_burndown.get("Low", []),
"info": open_findings_burndown.get("Info", []),
"max": open_findings_burndown.get("y_max", 0),
"min": open_findings_burndown.get("y_min", 0),
})
@user_is_authorized(Product, Permissions.Engagement_View, "pid")
def view_engagements(request, pid):
prod = get_object_or_404(Product, id=pid)
default_page_num = 10
recent_test_day_count = 7
filter_string_matching = get_system_setting("filter_string_matching", False)
filter_class = ProductEngagementFilterWithoutObjectLookups if filter_string_matching else ProductEngagementFilter
# In Progress Engagements
engs = Engagement.objects.filter(product=prod, active=True, status="In Progress").order_by("-updated")
active_engs_filter = filter_class(request.GET, queryset=engs, prefix="active")
result_active_engs = get_page_items(request, active_engs_filter.qs, default_page_num, prefix="engs")
# prefetch only after creating the filters to avoid https://code.djangoproject.com/ticket/23771
# and https://code.djangoproject.com/ticket/25375
result_active_engs.object_list = prefetch_for_view_engagements(
result_active_engs.object_list,
recent_test_day_count,
)
# Engagements that are queued because they haven't started or paused
engs = Engagement.objects.filter(~Q(status="In Progress"), product=prod, active=True).order_by("-updated")
queued_engs_filter = filter_class(request.GET, queryset=engs, prefix="queued")
result_queued_engs = get_page_items(request, queued_engs_filter.qs, default_page_num, prefix="queued_engs")
result_queued_engs.object_list = prefetch_for_view_engagements(
result_queued_engs.object_list,
recent_test_day_count,
)
# Cancelled or Completed Engagements
engs = Engagement.objects.filter(product=prod, active=False).order_by("-target_end")
inactive_engs_filter = filter_class(request.GET, queryset=engs, prefix="closed")
result_inactive_engs = get_page_items(request, inactive_engs_filter.qs, default_page_num, prefix="inactive_engs")
result_inactive_engs.object_list = prefetch_for_view_engagements(
result_inactive_engs.object_list,
recent_test_day_count,
)
product_tab = Product_Tab(prod, title=_("All Engagements"), tab="engagements")
return render(request, "dojo/view_engagements.html", {
"prod": prod,
"product_tab": product_tab,
"engs": result_active_engs,
"engs_count": result_active_engs.paginator.count,
"engs_filter": active_engs_filter,
"queued_engs": result_queued_engs,
"queued_engs_count": result_queued_engs.paginator.count,
"queued_engs_filter": queued_engs_filter,
"inactive_engs": result_inactive_engs,
"inactive_engs_count": result_inactive_engs.paginator.count,
"enable_table_filtering": get_system_setting("enable_ui_table_based_searching"),
"inactive_engs_filter": inactive_engs_filter,
"recent_test_day_count": recent_test_day_count,
"user": request.user})
def prefetch_for_view_engagements(engagements, recent_test_day_count):
engagements = engagements.select_related(
"lead",
).prefetch_related(
Prefetch("test_set", queryset=Test.objects.filter(
id__in=Subquery(
Test.objects.filter(
engagement_id=OuterRef("engagement_id"),
updated__gte=timezone.now() - timedelta(days=recent_test_day_count),
).values_list("id", flat=True),
)),
),
"test_set__test_type",
).annotate(
count_tests=Count("test", distinct=True),
count_findings_all=Count("test__finding__id"),
count_findings_open=Count("test__finding__id", filter=Q(test__finding__active=True)),
count_findings_open_verified=Count("test__finding__id",
filter=Q(test__finding__active=True) & Q(test__finding__verified=True)),
count_findings_close=Count("test__finding__id", filter=Q(test__finding__is_mitigated=True)),
count_findings_duplicate=Count("test__finding__id", filter=Q(test__finding__duplicate=True)),
count_findings_accepted=Count("test__finding__id", filter=Q(test__finding__risk_accepted=True)),
)
if System_Settings.objects.get().enable_jira:
engagements = engagements.prefetch_related(
"jira_project__jira_instance",
"product__jira_project_set__jira_instance",
)
return engagements
# Authorization is within the import_scan_results method
def import_scan_results_prod(request, pid=None):
from dojo.engagement.views import import_scan_results
return import_scan_results(request, pid=pid)
def new_product(request, ptid=None):
if get_authorized_product_types(Permissions.Product_Type_Add_Product).count() == 0:
raise PermissionDenied
jira_project_form = None
error = False
initial = None
if ptid is not None:
prod_type = get_object_or_404(Product_Type, pk=ptid)
initial = {"prod_type": prod_type}
form = ProductForm(initial=initial)
if request.method == "POST":
form = ProductForm(request.POST, instance=Product())
if get_system_setting("enable_github"):
gform = GITHUB_Product_Form(request.POST, instance=GITHUB_PKey())
else:
gform = None
if form.is_valid():
product_type = form.instance.prod_type
user_has_permission_or_403(request.user, product_type, Permissions.Product_Type_Add_Product)
product = form.save()
messages.add_message(request,
messages.SUCCESS,
_("Product added successfully."),
extra_tags="alert-success")
success, jira_project_form = jira_helper.process_jira_project_form(request, product=product)
error = not success
if get_system_setting("enable_github"):
if gform.is_valid():
github_pkey = gform.save(commit=False)
if github_pkey.git_conf is not None and github_pkey.git_project:
github_pkey.product = product
github_pkey.save()
messages.add_message(request,
messages.SUCCESS,
_("GitHub information added successfully."),
extra_tags="alert-success")
# Create appropriate labels in the repo
logger.info("Create label in repo: " + github_pkey.git_project)
description = _("This label is automatically applied to all issues created by DefectDojo")
try:
g = Github(github_pkey.git_conf.api_key)
repo = g.get_repo(github_pkey.git_project)
repo.create_label(name="security", color="FF0000",
description=description)
repo.create_label(name="security / info", color="00FEFC",
description=description)
repo.create_label(name="security / low", color="B7FE00",
description=description)
repo.create_label(name="security / medium", color="FEFE00",
description=description)
repo.create_label(name="security / high", color="FE9A00",
description=description)
repo.create_label(name="security / critical", color="FE2200",
description=description)
except:
logger.info("Labels cannot be created - they may already exists")
if not error:
return HttpResponseRedirect(reverse("view_product", args=(product.id,)))
# engagement was saved, but JIRA errors, so goto edit_product
return HttpResponseRedirect(reverse("edit_product", args=(product.id,)))
else:
if get_system_setting("enable_jira"):
jira_project_form = JIRAProjectForm()
gform = GITHUB_Product_Form() if get_system_setting("enable_github") else None
add_breadcrumb(title=_("New Product"), top_level=False, request=request)
return render(request, "dojo/new_product.html",
{"form": form,
"jform": jira_project_form,
"gform": gform})
@user_is_authorized(Product, Permissions.Product_Edit, "pid")
def edit_product(request, pid):
product = Product.objects.get(pk=pid)
system_settings = System_Settings.objects.get()
jira_enabled = system_settings.enable_jira
jira_project = None
jform = None
github_enabled = system_settings.enable_github
github_inst = None
gform = None
error = False
try:
github_inst = GITHUB_PKey.objects.get(product=product)
except:
github_inst = None
if request.method == "POST":
form = ProductForm(request.POST, instance=product)
jira_project = jira_helper.get_jira_project(product)
if form.is_valid():
initial_sla_config = Product.objects.get(pk=form.instance.id).sla_configuration
form.save()
msg = "Product updated successfully."
# check if the SLA config was changed, append additional context to message
if initial_sla_config != form.instance.sla_configuration:
msg += " All SLA expiration dates for findings within this product will be recalculated asynchronously for the newly assigned SLA configuration."
messages.add_message(request,
messages.SUCCESS,
_(msg),
extra_tags="alert-success")
success, jform = jira_helper.process_jira_project_form(request, instance=jira_project, product=product)
error = not success
if get_system_setting("enable_github") and github_inst:
gform = GITHUB_Product_Form(request.POST, instance=github_inst)
# need to handle delete
with contextlib.suppress(Exception):
gform.save()
elif get_system_setting("enable_github"):
gform = GITHUB_Product_Form(request.POST)
if gform.is_valid():
new_conf = gform.save(commit=False)
new_conf.product_id = pid
new_conf.save()
messages.add_message(request,
messages.SUCCESS,
_("GITHUB information updated successfully."),
extra_tags="alert-success")
if not error:
return HttpResponseRedirect(reverse("view_product", args=(pid,)))
else:
form = ProductForm(instance=product)
if jira_enabled:
jira_project = jira_helper.get_jira_project(product)
jform = JIRAProjectForm(instance=jira_project)
else:
jform = None
if github_enabled:
gform = GITHUB_Product_Form(instance=github_inst) if github_inst is not None else GITHUB_Product_Form()
else:
gform = None
product_tab = Product_Tab(product, title=_("Edit Product"), tab="settings")
return render(request,
"dojo/edit_product.html",
{"form": form,
"product_tab": product_tab,
"jform": jform,
"gform": gform,
"product": product,
})