forked from DefectDojo/django-DefectDojo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
2711 lines (2275 loc) · 104 KB
/
utils.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 binascii
import calendar as tcalendar
import hashlib
import importlib
import logging
import mimetypes
import os
import pathlib
import re
from calendar import monthrange
from collections.abc import Callable
from datetime import date, datetime, timedelta
from math import pi, sqrt
from pathlib import Path
import bleach
import crum
import hyperlink
import vobject
from asteval import Interpreter
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from dateutil.parser import parse
from dateutil.relativedelta import MO, SU, relativedelta
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
from django.core.paginator import Paginator
from django.db.models import Case, Count, IntegerField, Q, Sum, Value, When
from django.db.models.query import QuerySet
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.http import FileResponse, HttpResponseRedirect
from django.urls import get_resolver, get_script_prefix, reverse
from django.utils import timezone
from django.utils.translation import gettext as _
from dojo.authorization.roles_permissions import Permissions
from dojo.celery import app
from dojo.decorators import dojo_async_task, dojo_model_from_id, dojo_model_to_id
from dojo.finding.queries import get_authorized_findings
from dojo.github import (
add_external_issue_github,
close_external_issue_github,
reopen_external_issue_github,
update_external_issue_github,
)
from dojo.models import (
NOTIFICATION_CHOICES,
Benchmark_Type,
Dojo_Group_Member,
Dojo_User,
Endpoint,
Engagement,
FileUpload,
Finding,
Finding_Group,
Finding_Template,
Language_Type,
Languages,
Notifications,
Product,
System_Settings,
Test,
User,
)
from dojo.notifications.helper import create_notification
logger = logging.getLogger(__name__)
deduplicationLogger = logging.getLogger("dojo.specific-loggers.deduplication")
WEEKDAY_FRIDAY = 4 # date.weekday() starts with 0
"""
Helper functions for DefectDojo
"""
def do_false_positive_history(finding, *args, **kwargs):
"""
Replicate false positives across product.
Mark finding as false positive if the same finding was previously marked
as false positive in the same product, beyond that, retroactively mark
all equal findings in the product as false positive (if they weren't already).
The retroactively replication will be also trigerred if the finding passed as
an argument already is a false positive. With this feature we can assure that
on each call of this method all findings in the product complies to the rule
(if one finding is a false positive, all equal findings in the same product also are).
Args:
finding (:model:`dojo.Finding`): Finding to be replicated
"""
to_mark_as_fp = set()
existing_findings = match_finding_to_existing_findings(finding, product=finding.test.engagement.product)
deduplicationLogger.debug(
"FALSE_POSITIVE_HISTORY: Found %i existing findings in the same product",
len(existing_findings),
)
existing_fp_findings = existing_findings.filter(false_p=True)
deduplicationLogger.debug(
"FALSE_POSITIVE_HISTORY: Found %i existing findings in the same product "
+ "that were previously marked as false positive",
len(existing_fp_findings),
)
if existing_fp_findings:
finding.false_p = True
to_mark_as_fp.add(finding)
system_settings = System_Settings.objects.get()
if system_settings.retroactive_false_positive_history:
# Retroactively mark all active existing findings as false positive if this one
# is being (or already was) marked as a false positive
if finding.false_p:
existing_non_fp_findings = existing_findings.filter(active=True).exclude(false_p=True)
to_mark_as_fp.update(set(existing_non_fp_findings))
# Remove the async user kwarg because save() really does not like it
# Would rather not add anything to Finding.save()
if "async_user" in kwargs:
kwargs.pop("async_user")
for find in to_mark_as_fp:
deduplicationLogger.debug(
"FALSE_POSITIVE_HISTORY: Marking Finding %i:%s from %s as false positive",
find.id, find.title, find.test.engagement,
)
try:
find.false_p = True
find.active = False
find.verified = False
super(Finding, find).save(*args, **kwargs)
except Exception as e:
deduplicationLogger.debug(str(e))
def match_finding_to_existing_findings(finding, product=None, engagement=None, test=None):
"""
Customizable lookup that returns all existing findings for a given finding.
Takes one finding as an argument and returns all findings that are equal to it
on the same product, engagement or test. For now, only one custom filter can
be used, so you should choose between product, engagement or test.
The lookup is done based on the deduplication_algorithm of the given finding test.
Args:
finding (:model:`dojo.Finding`): Finding to be matched
product (:model:`dojo.Product`, optional): Product to filter findings by
engagement (:model:`dojo.Engagement`, optional): Engagement to filter findings by
test (:model:`dojo.Test`, optional): Test to filter findings by
"""
if product:
custom_filter_type = "product"
custom_filter = {"test__engagement__product": product}
elif engagement:
custom_filter_type = "engagement"
custom_filter = {"test__engagement": engagement}
elif test:
custom_filter_type = "test"
custom_filter = {"test": test}
else:
msg = "No product, engagement or test provided as argument."
raise ValueError(msg)
deduplication_algorithm = finding.test.deduplication_algorithm
deduplicationLogger.debug(
"Matching finding %i:%s to existing findings in %s %s using %s as deduplication algorithm.",
finding.id, finding.title, custom_filter_type, list(custom_filter.values())[0], deduplication_algorithm,
)
if deduplication_algorithm == "hash_code":
return (
Finding.objects.filter(
**custom_filter,
hash_code=finding.hash_code,
).exclude(hash_code=None)
.exclude(id=finding.id)
.order_by("id")
)
if deduplication_algorithm == "unique_id_from_tool":
return (
Finding.objects.filter(
**custom_filter,
unique_id_from_tool=finding.unique_id_from_tool,
).exclude(unique_id_from_tool=None)
.exclude(id=finding.id)
.order_by("id")
)
if deduplication_algorithm == "unique_id_from_tool_or_hash_code":
query = Finding.objects.filter(
Q(**custom_filter),
(
(Q(hash_code__isnull=False) & Q(hash_code=finding.hash_code))
| (Q(unique_id_from_tool__isnull=False) & Q(unique_id_from_tool=finding.unique_id_from_tool))
),
).exclude(id=finding.id).order_by("id")
deduplicationLogger.debug(query.query)
return query
if deduplication_algorithm == "legacy":
# This is the legacy reimport behavior. Although it's pretty flawed and
# doesn't match the legacy algorithm for deduplication, this is left as is for simplicity.
# Re-writing the legacy deduplication here would be complicated and counter-productive.
# If you have use cases going through this section, you're advised to create a deduplication configuration for your parser
logger.debug("Legacy dedupe. In case of issue, you're advised to create a deduplication configuration in order not to go through this section")
return (
Finding.objects.filter(
**custom_filter,
title=finding.title,
severity=finding.severity,
numerical_severity=Finding.get_numerical_severity(finding.severity),
).order_by("id")
)
logger.error("Internal error: unexpected deduplication_algorithm: '%s' ", deduplication_algorithm)
return None
# true if both findings are on an engagement that have a different "deduplication on engagement" configuration
def is_deduplication_on_engagement_mismatch(new_finding, to_duplicate_finding):
return not new_finding.test.engagement.deduplication_on_engagement and to_duplicate_finding.test.engagement.deduplication_on_engagement
def get_endpoints_as_url(finding):
list1 = []
for e in finding.endpoints.all():
list1.append(hyperlink.parse(str(e)))
return list1
def are_urls_equal(url1, url2, fields):
# Possible values are: scheme, host, port, path, query, fragment, userinfo, and user.
# For a details description see https://hyperlink.readthedocs.io/en/latest/api.html#attributes
deduplicationLogger.debug("Check if url %s and url %s are equal in terms of %s.", url1, url2, fields)
for field in fields:
if field == "scheme":
if url1.scheme != url2.scheme:
return False
elif field == "host":
if url1.host != url2.host:
return False
elif field == "port":
if url1.port != url2.port:
return False
elif field == "path":
if url1.path != url2.path:
return False
elif field == "query":
if url1.query != url2.query:
return False
elif field == "fragment":
if url1.fragment != url2.fragment:
return False
elif field == "userinfo":
if url1.userinfo != url2.userinfo:
return False
elif field == "user":
if url1.user != url2.user:
return False
else:
logger.warning("Field " + field + " is not supported by the endpoint dedupe algorithm, ignoring it.")
return True
def are_endpoints_duplicates(new_finding, to_duplicate_finding):
fields = settings.DEDUPE_ALGO_ENDPOINT_FIELDS
# shortcut if fields list is empty/feature is disabled
if len(fields) == 0:
deduplicationLogger.debug("deduplication by endpoint fields is disabled")
return True
list1 = get_endpoints_as_url(new_finding)
list2 = get_endpoints_as_url(to_duplicate_finding)
deduplicationLogger.debug(f"Starting deduplication by endpoint fields for finding {new_finding.id} with urls {list1} and finding {to_duplicate_finding.id} with urls {list2}")
if list1 == [] and list2 == []:
return True
for l1 in list1:
for l2 in list2:
if are_urls_equal(l1, l2, fields):
return True
return False
@dojo_model_to_id
@dojo_async_task
@app.task
@dojo_model_from_id
def do_dedupe_finding_task(new_finding, *args, **kwargs):
return do_dedupe_finding(new_finding, *args, **kwargs)
def do_dedupe_finding(new_finding, *args, **kwargs):
if dedupe_method := get_custom_method("FINDING_DEDUPE_METHOD"):
return dedupe_method(new_finding, *args, **kwargs)
try:
enabled = System_Settings.objects.get(no_cache=True).enable_deduplication
except System_Settings.DoesNotExist:
logger.warning("system settings not found")
enabled = False
if enabled:
deduplicationLogger.debug("dedupe for: " + str(new_finding.id)
+ ":" + str(new_finding.title))
deduplicationAlgorithm = new_finding.test.deduplication_algorithm
deduplicationLogger.debug("deduplication algorithm: " + deduplicationAlgorithm)
if deduplicationAlgorithm == settings.DEDUPE_ALGO_UNIQUE_ID_FROM_TOOL:
deduplicate_unique_id_from_tool(new_finding)
elif deduplicationAlgorithm == settings.DEDUPE_ALGO_HASH_CODE:
deduplicate_hash_code(new_finding)
elif deduplicationAlgorithm == settings.DEDUPE_ALGO_UNIQUE_ID_FROM_TOOL_OR_HASH_CODE:
deduplicate_uid_or_hash_code(new_finding)
else:
deduplicationLogger.debug("no configuration per parser found; using legacy algorithm")
deduplicate_legacy(new_finding)
else:
deduplicationLogger.debug("dedupe: skipping dedupe because it's disabled in system settings get()")
return None
def deduplicate_legacy(new_finding):
# ---------------------------------------------------------
# 1) Collects all the findings that have the same:
# (title and static_finding and dynamic_finding)
# or (CWE and static_finding and dynamic_finding)
# as the new one
# (this is "cond1")
# ---------------------------------------------------------
if new_finding.test.engagement.deduplication_on_engagement:
eng_findings_cwe = Finding.objects.filter(
test__engagement=new_finding.test.engagement,
cwe=new_finding.cwe).exclude(id=new_finding.id).exclude(cwe=0).exclude(duplicate=True).values("id")
eng_findings_title = Finding.objects.filter(
test__engagement=new_finding.test.engagement,
title=new_finding.title).exclude(id=new_finding.id).exclude(duplicate=True).values("id")
else:
eng_findings_cwe = Finding.objects.filter(
test__engagement__product=new_finding.test.engagement.product,
cwe=new_finding.cwe).exclude(id=new_finding.id).exclude(cwe=0).exclude(duplicate=True).values("id")
eng_findings_title = Finding.objects.filter(
test__engagement__product=new_finding.test.engagement.product,
title=new_finding.title).exclude(id=new_finding.id).exclude(duplicate=True).values("id")
total_findings = Finding.objects.filter(Q(id__in=eng_findings_cwe) | Q(id__in=eng_findings_title)).prefetch_related("endpoints", "test", "test__engagement", "found_by", "original_finding", "test__test_type")
deduplicationLogger.debug("Found "
+ str(len(eng_findings_cwe)) + " findings with same cwe, "
+ str(len(eng_findings_title)) + " findings with same title: "
+ str(len(total_findings)) + " findings with either same title or same cwe")
# total_findings = total_findings.order_by('date')
for find in total_findings.order_by("id"):
flag_endpoints = False
flag_line_path = False
flag_hash = False
if is_deduplication_on_engagement_mismatch(new_finding, find):
deduplicationLogger.debug(
"deduplication_on_engagement_mismatch, skipping dedupe.")
continue
# ---------------------------------------------------------
# 2) If existing and new findings have endpoints: compare them all
# Else look at line+file_path
# (if new finding is not static, do not deduplicate)
# ---------------------------------------------------------
if find.endpoints.count() != 0 and new_finding.endpoints.count() != 0:
list1 = [str(e) for e in new_finding.endpoints.all()]
list2 = [str(e) for e in find.endpoints.all()]
if all(x in list1 for x in list2):
deduplicationLogger.debug("%s: existing endpoints are present in new finding", find.id)
flag_endpoints = True
elif new_finding.static_finding and new_finding.file_path and len(new_finding.file_path) > 0:
if str(find.line) == str(new_finding.line) and find.file_path == new_finding.file_path:
deduplicationLogger.debug("%s: file_path and line match", find.id)
flag_line_path = True
else:
deduplicationLogger.debug("no endpoints on one of the findings and file_path doesn't match; Deduplication will not occur")
else:
deduplicationLogger.debug("find.static/dynamic: %s/%s", find.static_finding, find.dynamic_finding)
deduplicationLogger.debug("new_finding.static/dynamic: %s/%s", new_finding.static_finding, new_finding.dynamic_finding)
deduplicationLogger.debug("find.file_path: %s", find.file_path)
deduplicationLogger.debug("new_finding.file_path: %s", new_finding.file_path)
deduplicationLogger.debug("no endpoints on one of the findings and the new finding is either dynamic or doesn't have a file_path; Deduplication will not occur")
if find.hash_code == new_finding.hash_code:
flag_hash = True
deduplicationLogger.debug(
"deduplication flags for new finding (" + ("dynamic" if new_finding.dynamic_finding else "static") + ") " + str(new_finding.id) + " and existing finding " + str(find.id)
+ " flag_endpoints: " + str(flag_endpoints) + " flag_line_path:" + str(flag_line_path) + " flag_hash:" + str(flag_hash))
# ---------------------------------------------------------
# 3) Findings are duplicate if (cond1 is true) and they have the same:
# hash
# and (endpoints or (line and file_path)
# ---------------------------------------------------------
if ((flag_endpoints or flag_line_path) and flag_hash):
try:
set_duplicate(new_finding, find)
except Exception as e:
deduplicationLogger.debug(str(e))
continue
break
def deduplicate_unique_id_from_tool(new_finding):
if new_finding.test.engagement.deduplication_on_engagement:
existing_findings = Finding.objects.filter(
test__engagement=new_finding.test.engagement,
unique_id_from_tool=new_finding.unique_id_from_tool).exclude(
id=new_finding.id).exclude(
unique_id_from_tool=None).exclude(
duplicate=True).order_by("id")
else:
existing_findings = Finding.objects.filter(
test__engagement__product=new_finding.test.engagement.product,
# the unique_id_from_tool is unique for a given tool: do not compare with other tools
test__test_type=new_finding.test.test_type,
unique_id_from_tool=new_finding.unique_id_from_tool).exclude(
id=new_finding.id).exclude(
unique_id_from_tool=None).exclude(
duplicate=True).order_by("id")
deduplicationLogger.debug("Found "
+ str(len(existing_findings)) + " findings with same unique_id_from_tool")
for find in existing_findings:
if is_deduplication_on_engagement_mismatch(new_finding, find):
deduplicationLogger.debug(
"deduplication_on_engagement_mismatch, skipping dedupe.")
continue
try:
set_duplicate(new_finding, find)
break
except Exception as e:
deduplicationLogger.debug(str(e))
continue
def deduplicate_hash_code(new_finding):
if new_finding.test.engagement.deduplication_on_engagement:
existing_findings = Finding.objects.filter(
test__engagement=new_finding.test.engagement,
hash_code=new_finding.hash_code).exclude(
id=new_finding.id).exclude(
hash_code=None).exclude(
duplicate=True).order_by("id")
else:
existing_findings = Finding.objects.filter(
test__engagement__product=new_finding.test.engagement.product,
hash_code=new_finding.hash_code).exclude(
id=new_finding.id).exclude(
hash_code=None).exclude(
duplicate=True).order_by("id")
deduplicationLogger.debug("Found "
+ str(len(existing_findings)) + " findings with same hash_code")
for find in existing_findings:
if is_deduplication_on_engagement_mismatch(new_finding, find):
deduplicationLogger.debug(
"deduplication_on_engagement_mismatch, skipping dedupe.")
continue
try:
if are_endpoints_duplicates(new_finding, find):
set_duplicate(new_finding, find)
break
except Exception as e:
deduplicationLogger.debug(str(e))
continue
def deduplicate_uid_or_hash_code(new_finding):
if new_finding.test.engagement.deduplication_on_engagement:
existing_findings = Finding.objects.filter(
(Q(hash_code__isnull=False) & Q(hash_code=new_finding.hash_code))
# unique_id_from_tool can only apply to the same test_type because it is parser dependent
| (Q(unique_id_from_tool__isnull=False) & Q(unique_id_from_tool=new_finding.unique_id_from_tool) & Q(test__test_type=new_finding.test.test_type)),
test__engagement=new_finding.test.engagement).exclude(
id=new_finding.id).exclude(
duplicate=True).order_by("id")
else:
# same without "test__engagement=new_finding.test.engagement" condition
existing_findings = Finding.objects.filter(
(Q(hash_code__isnull=False) & Q(hash_code=new_finding.hash_code))
| (Q(unique_id_from_tool__isnull=False) & Q(unique_id_from_tool=new_finding.unique_id_from_tool) & Q(test__test_type=new_finding.test.test_type)),
test__engagement__product=new_finding.test.engagement.product).exclude(
id=new_finding.id).exclude(
duplicate=True).order_by("id")
deduplicationLogger.debug("Found "
+ str(len(existing_findings)) + " findings with either the same unique_id_from_tool or hash_code")
for find in existing_findings:
if is_deduplication_on_engagement_mismatch(new_finding, find):
deduplicationLogger.debug(
"deduplication_on_engagement_mismatch, skipping dedupe.")
continue
try:
if are_endpoints_duplicates(new_finding, find):
set_duplicate(new_finding, find)
except Exception as e:
deduplicationLogger.debug(str(e))
continue
break
def set_duplicate(new_finding, existing_finding):
deduplicationLogger.debug(f"new_finding.status(): {new_finding.id} {new_finding.status()}")
deduplicationLogger.debug(f"existing_finding.status(): {existing_finding.id} {existing_finding.status()}")
if existing_finding.duplicate:
deduplicationLogger.debug("existing finding: %s:%s:duplicate=%s;duplicate_finding=%s", existing_finding.id, existing_finding.title, existing_finding.duplicate, existing_finding.duplicate_finding.id if existing_finding.duplicate_finding else "None")
msg = "Existing finding is a duplicate"
raise Exception(msg)
if existing_finding.id == new_finding.id:
msg = "Can not add duplicate to itself"
raise Exception(msg)
if is_duplicate_reopen(new_finding, existing_finding):
msg = "Found a regression. Ignore this so that a new duplicate chain can be made"
raise Exception(msg)
if new_finding.duplicate and finding_mitigated(existing_finding):
msg = "Skip this finding as we do not want to attach a new duplicate to a mitigated finding"
raise Exception(msg)
deduplicationLogger.debug("Setting new finding " + str(new_finding.id) + " as a duplicate of existing finding " + str(existing_finding.id))
new_finding.duplicate = True
new_finding.active = False
new_finding.verified = False
new_finding.duplicate_finding = existing_finding
# Make sure transitive duplication is flattened
# if A -> B and B is made a duplicate of C here, aferwards:
# A -> C and B -> C should be true
for find in new_finding.original_finding.all().order_by("-id"):
new_finding.original_finding.remove(find)
set_duplicate(find, existing_finding)
existing_finding.found_by.add(new_finding.test.test_type)
logger.debug("saving new finding: %d", new_finding.id)
super(Finding, new_finding).save()
logger.debug("saving existing finding: %d", existing_finding.id)
super(Finding, existing_finding).save()
def is_duplicate_reopen(new_finding, existing_finding) -> bool:
return finding_mitigated(existing_finding) and finding_not_human_set_status(existing_finding) and not finding_mitigated(new_finding)
def finding_mitigated(finding: Finding) -> bool:
return finding.active is False and (finding.is_mitigated is True or finding.mitigated is not None)
def finding_not_human_set_status(finding: Finding) -> bool:
return finding.out_of_scope is False and finding.false_p is False
def set_duplicate_reopen(new_finding, existing_finding):
logger.debug("duplicate reopen existing finding")
existing_finding.mitigated = new_finding.mitigated
existing_finding.is_mitigated = new_finding.is_mitigated
existing_finding.active = new_finding.active
existing_finding.verified = new_finding.verified
existing_finding.notes.create(author=existing_finding.reporter,
entry="This finding has been automatically re-opened as it was found in recent scans.")
existing_finding.save()
def count_findings(findings):
product_count = {}
finding_count = {"low": 0, "med": 0, "high": 0, "crit": 0}
for f in findings:
product = f.test.engagement.product
if product in product_count:
product_count[product][4] += 1
if f.severity == "Low":
product_count[product][3] += 1
finding_count["low"] += 1
if f.severity == "Medium":
product_count[product][2] += 1
finding_count["med"] += 1
if f.severity == "High":
product_count[product][1] += 1
finding_count["high"] += 1
if f.severity == "Critical":
product_count[product][0] += 1
finding_count["crit"] += 1
else:
product_count[product] = [0, 0, 0, 0, 0]
product_count[product][4] += 1
if f.severity == "Low":
product_count[product][3] += 1
finding_count["low"] += 1
if f.severity == "Medium":
product_count[product][2] += 1
finding_count["med"] += 1
if f.severity == "High":
product_count[product][1] += 1
finding_count["high"] += 1
if f.severity == "Critical":
product_count[product][0] += 1
finding_count["crit"] += 1
return product_count, finding_count
def findings_this_period(findings, period_type, stuff, o_stuff, a_stuff):
# periodType: 0 - weeks
# 1 - months
now = timezone.now()
for i in range(6):
counts = []
# Weeks start on Monday
if period_type == 0:
curr = now - relativedelta(weeks=i)
start_of_period = curr - relativedelta(
weeks=1, weekday=0, hour=0, minute=0, second=0)
end_of_period = curr + relativedelta(
weeks=0, weekday=0, hour=0, minute=0, second=0)
else:
curr = now - relativedelta(months=i)
start_of_period = curr - relativedelta(
day=1, hour=0, minute=0, second=0)
end_of_period = curr + relativedelta(
day=31, hour=23, minute=59, second=59)
o_count = {
"closed": 0,
"zero": 0,
"one": 0,
"two": 0,
"three": 0,
"total": 0,
}
a_count = {
"closed": 0,
"zero": 0,
"one": 0,
"two": 0,
"three": 0,
"total": 0,
}
for f in findings:
if f.mitigated is not None and end_of_period >= f.mitigated >= start_of_period:
o_count["closed"] += 1
elif f.mitigated is not None and f.mitigated > end_of_period and f.date <= end_of_period.date():
if f.severity == "Critical":
o_count["zero"] += 1
elif f.severity == "High":
o_count["one"] += 1
elif f.severity == "Medium":
o_count["two"] += 1
elif f.severity == "Low":
o_count["three"] += 1
elif f.mitigated is None and f.date <= end_of_period.date():
if f.severity == "Critical":
o_count["zero"] += 1
a_count["zero"] += 1
elif f.severity == "High":
o_count["one"] += 1
a_count["one"] += 1
elif f.severity == "Medium":
o_count["two"] += 1
a_count["two"] += 1
elif f.severity == "Low":
o_count["three"] += 1
a_count["three"] += 1
total = sum(o_count.values()) - o_count["closed"]
if period_type == 0:
counts.append(
start_of_period.strftime("%b %d") + " - "
+ end_of_period.strftime("%b %d"))
else:
counts.append(start_of_period.strftime("%b %Y"))
counts.extend((
o_count["zero"],
o_count["one"],
o_count["two"],
o_count["three"],
total,
o_count["closed"],
))
stuff.append(counts)
o_stuff.append(counts[:-1])
a_counts = []
a_total = sum(a_count.values())
if period_type == 0:
a_counts.append(
start_of_period.strftime("%b %d") + " - "
+ end_of_period.strftime("%b %d"))
else:
a_counts.append(start_of_period.strftime("%b %Y"))
a_counts.extend((
a_count["zero"],
a_count["one"],
a_count["two"],
a_count["three"],
a_total,
))
a_stuff.append(a_counts)
def add_breadcrumb(parent=None,
title=None,
top_level=True,
url=None,
request=None,
clear=False):
if clear:
request.session["dojo_breadcrumbs"] = None
return
crumbs = request.session.get("dojo_breadcrumbs", None)
if top_level or crumbs is None:
crumbs = [
{
"title": _("Home"),
"url": reverse("home"),
},
]
if parent is not None and getattr(parent, "get_breadcrumbs", None):
crumbs += parent.get_breadcrumbs()
else:
crumbs += [{
"title": title,
"url": request.get_full_path() if url is None else url,
}]
else:
resolver = get_resolver(None).resolve
if parent is not None and getattr(parent, "get_breadcrumbs", None):
obj_crumbs = parent.get_breadcrumbs()
if title is not None:
obj_crumbs += [{
"title": title,
"url": request.get_full_path() if url is None else url,
}]
else:
obj_crumbs = [{
"title": title,
"url": request.get_full_path() if url is None else url,
}]
for crumb in crumbs:
crumb_to_resolve = crumb["url"] if "?" not in crumb[
"url"] else crumb["url"][:crumb["url"].index("?")]
crumb_view = resolver(crumb_to_resolve)
for obj_crumb in obj_crumbs:
obj_crumb_to_resolve = obj_crumb[
"url"] if "?" not in obj_crumb["url"] else obj_crumb[
"url"][:obj_crumb["url"].index("?")]
obj_crumb_view = resolver(obj_crumb_to_resolve)
if crumb_view.view_name == obj_crumb_view.view_name:
if crumb_view.kwargs == obj_crumb_view.kwargs:
if len(obj_crumbs) == 1 and crumb in crumbs:
crumbs = crumbs[:crumbs.index(crumb)]
else:
obj_crumbs.remove(obj_crumb)
else:
if crumb in crumbs:
crumbs = crumbs[:crumbs.index(crumb)]
crumbs += obj_crumbs
request.session["dojo_breadcrumbs"] = crumbs
def is_title_in_breadcrumbs(title):
request = crum.get_current_request()
if request is None:
return False
breadcrumbs = request.session.get("dojo_breadcrumbs")
if breadcrumbs is None:
return False
return any(breadcrumb.get("title") == title for breadcrumb in breadcrumbs)
def get_punchcard_data(objs, start_date, weeks, view="Finding"):
# use try catch to make sure any teething bugs in the bunchcard don't break the dashboard
try:
# gather findings over past half year, make sure to start on a sunday
first_sunday = start_date - relativedelta(weekday=SU(-1))
last_sunday = start_date + relativedelta(weeks=weeks)
# reminder: The first week of a year is the one that contains the year's first Thursday
# so we could have for 29/12/2019: week=1 and year=2019 :-D. So using week number from db is not practical
if view == "Finding":
severities_by_day = objs.filter(created__date__gte=first_sunday).filter(created__date__lt=last_sunday) \
.values("created__date") \
.annotate(count=Count("id")) \
.order_by("created__date")
elif view == "Endpoint":
severities_by_day = objs.filter(date__gte=first_sunday).filter(date__lt=last_sunday) \
.values("date") \
.annotate(count=Count("id")) \
.order_by("date")
# return empty stuff if no findings to be statted
if severities_by_day.count() <= 0:
return None, None
# day of the week numbers:
# javascript database python
# sun 6 1 6
# mon 5 2 0
# tue 4 3 1
# wed 3 4 2
# thu 2 5 3
# fri 1 6 4
# sat 0 7 5
# map from python to javascript, do not use week numbers or day numbers from database.
day_offset = {0: 5, 1: 4, 2: 3, 3: 2, 4: 1, 5: 0, 6: 6}
punchcard = []
ticks = []
highest_day_count = 0
tick = 0
day_counts = [0, 0, 0, 0, 0, 0, 0]
start_of_week = timezone.make_aware(datetime.combine(first_sunday, datetime.min.time()))
start_of_next_week = start_of_week + relativedelta(weeks=1)
for day in severities_by_day:
if view == "Finding":
created = day["created__date"]
elif view == "Endpoint":
created = day["date"]
day_count = day["count"]
created = timezone.make_aware(datetime.combine(created, datetime.min.time()))
if created < start_of_week:
raise ValueError("date found outside supported range: " + str(created))
if created >= start_of_week and created < start_of_next_week:
# add day count to current week data
day_counts[day_offset[created.weekday()]] = day_count
highest_day_count = max(highest_day_count, day_count)
else:
# created >= start_of_next_week, so store current week, prepare for next
while created >= start_of_next_week:
week_data, label = get_week_data(start_of_week, tick, day_counts)
punchcard.extend(week_data)
ticks.append(label)
tick += 1
# new week, new values!
day_counts = [0, 0, 0, 0, 0, 0, 0]
start_of_week = start_of_next_week
start_of_next_week += relativedelta(weeks=1)
# finally a day that falls into the week bracket
day_counts[day_offset[created.weekday()]] = day_count
highest_day_count = max(highest_day_count, day_count)
# add week in progress + empty weeks on the end if needed
while tick < weeks + 1:
week_data, label = get_week_data(start_of_week, tick, day_counts)
punchcard.extend(week_data)
ticks.append(label)
tick += 1
day_counts = [0, 0, 0, 0, 0, 0, 0]
start_of_week = start_of_next_week
start_of_next_week += relativedelta(weeks=1)
# adjust the size or circles
ratio = (sqrt(highest_day_count / pi))
for punch in punchcard:
# front-end needs both the count for the label and the ratios of the radii of the circles
punch.append(punch[2])
punch[2] = (sqrt(punch[2] / pi)) / ratio
return punchcard, ticks
except Exception:
logger.exception("Not showing punchcard graph due to exception gathering data")
return None, None
def get_week_data(week_start_date, tick, day_counts):
data = []
for i in range(len(day_counts)):
data.append([tick, i, day_counts[i]])
label = [tick, week_start_date.strftime("<span class='small'>%m/%d<br/>%Y</span>")]
return data, label
# 5 params
def get_period_counts_legacy(findings,
findings_closed,
accepted_findings,
period_interval,
start_date,
relative_delta="months"):
opened_in_period = []
accepted_in_period = []
opened_in_period.append(
["Timestamp", "Date", "S0", "S1", "S2", "S3", "Total", "Closed"])
accepted_in_period.append(
["Timestamp", "Date", "S0", "S1", "S2", "S3", "Total", "Closed"])
for x in range(-1, period_interval):
if relative_delta == "months":
# make interval the first through last of month
end_date = (start_date + relativedelta(months=x)) + relativedelta(
day=1, months=+1, days=-1)
new_date = (
start_date + relativedelta(months=x)) + relativedelta(day=1)
else:
# week starts the monday before
new_date = start_date + relativedelta(weeks=x, weekday=MO(1))
end_date = new_date + relativedelta(weeks=1, weekday=MO(1))
closed_in_range_count = findings_closed.filter(
mitigated__date__range=[new_date, end_date]).count()
if accepted_findings:
risks_a = accepted_findings.filter(
risk_acceptance__created__date__range=[
datetime(
new_date.year,
new_date.month,
1,
tzinfo=timezone.get_current_timezone()),
datetime(
new_date.year,
new_date.month,
monthrange(new_date.year, new_date.month)[1],
tzinfo=timezone.get_current_timezone()),
])
else:
risks_a = None
crit_count, high_count, med_count, low_count, _ = [
0, 0, 0, 0, 0,
]
for finding in findings:
if new_date <= datetime.combine(finding.date, datetime.min.time(
)).replace(tzinfo=timezone.get_current_timezone()) <= end_date:
if finding.severity == "Critical":
crit_count += 1
elif finding.severity == "High":
high_count += 1
elif finding.severity == "Medium":
med_count += 1
elif finding.severity == "Low":
low_count += 1
total = crit_count + high_count + med_count + low_count
opened_in_period.append(
[(tcalendar.timegm(new_date.timetuple()) * 1000), new_date,
crit_count, high_count, med_count, low_count, total,
closed_in_range_count])
crit_count, high_count, med_count, low_count, _ = [
0, 0, 0, 0, 0,
]
if risks_a is not None:
for finding in risks_a:
if finding.severity == "Critical":
crit_count += 1
elif finding.severity == "High":
high_count += 1
elif finding.severity == "Medium":
med_count += 1
elif finding.severity == "Low":
low_count += 1
total = crit_count + high_count + med_count + low_count
accepted_in_period.append(
[(tcalendar.timegm(new_date.timetuple()) * 1000), new_date,
crit_count, high_count, med_count, low_count, total])
return {
"opened_per_period": opened_in_period,
"accepted_per_period": accepted_in_period,
}
def get_period_counts(findings,
findings_closed,
accepted_findings,
period_interval,
start_date,
relative_delta="months"):
tz = timezone.get_current_timezone()
start_date = datetime(start_date.year, start_date.month, start_date.day, tzinfo=tz)