forked from DefectDojo/django-DefectDojo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
2481 lines (2080 loc) · 91.6 KB
/
utils.py
File metadata and controls
2481 lines (2080 loc) · 91.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import binascii
import calendar as tcalendar
import hashlib
import importlib
import logging
import mimetypes
import os
import pathlib
import random
import re
import time
from calendar import monthrange
from collections.abc import Callable
from datetime import date, datetime, timedelta
from functools import cached_property
from math import pi, sqrt
from pathlib import Path
import bleach
import crum
import cvss
import vobject
from auditlog.models import LogEntry
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cvss import CVSS2, CVSS3, CVSS4
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.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator
from django.db import OperationalError
from django.db.models import Case, Count, F, 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.shortcuts import redirect as django_redirect
from django.urls import get_resolver, get_script_prefix, reverse
from django.utils import timezone
from django.utils.http import url_has_allowed_host_and_scheme
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.labels import get_labels
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,
Test_Type,
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
labels = get_labels()
"""
Helper functions for DefectDojo
"""
def get_visible_scan_types():
"""Returns a QuerySet of active Test_Type objects."""
return Test_Type.objects.filter(active=True)
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__iexact=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
def count_findings(findings: QuerySet) -> tuple[dict["Product", list[int]], dict[str, int]]:
agg = (
findings.values(prod_id=F("test__engagement__product_id"))
.annotate(
crit=Count("id", filter=Q(severity="Critical")),
high=Count("id", filter=Q(severity="High")),
med=Count("id", filter=Q(severity="Medium")),
low=Count("id", filter=Q(severity="Low")),
total=Count("id"),
)
)
rows = list(agg)
products = Product.objects.in_bulk([r["prod_id"] for r in rows])
product_count = {
products[r["prod_id"]]: [r["crit"], r["high"], r["med"], r["low"], r["total"]] for r in rows
}
finding_count = {
"low": sum(r["low"] for r in rows),
"med": sum(r["med"] for r in rows),
"high": sum(r["high"] for r in rows),
"crit": sum(r["crit"] for r in rows),
}
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)
elif 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
except Exception:
logger.exception("Not showing punchcard graph due to exception gathering data")
return None, None
return punchcard, ticks
def get_week_data(week_start_date, tick, day_counts):
data = [[tick, i, day_counts[i]] for i in range(len(day_counts))]
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)
opened_in_period = []
active_in_period = []
accepted_in_period = []
opened_in_period.append(
["Timestamp", "Date", "S0", "S1", "S2", "S3", "Total", "Closed"])
active_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))
try:
closed_in_range_count = findings_closed.filter(
mitigated__date__range=[new_date, end_date]).count()
except:
closed_in_range_count = findings_closed.filter(
mitigated_time__range=[new_date, end_date]).count()
if accepted_findings:
date_range = [
datetime(new_date.year, new_date.month, new_date.day, tzinfo=tz),
datetime(end_date.year, end_date.month, end_date.day, tzinfo=tz),
]
try:
risks_a = accepted_findings.filter(risk_acceptance__created__date__range=date_range)
except:
risks_a = accepted_findings.filter(date__range=date_range)
else:
risks_a = None
f_crit_count, f_high_count, f_med_count, f_low_count, _ = [
0, 0, 0, 0, 0,
]
ra_crit_count, ra_high_count, ra_med_count, ra_low_count, _ = [
0, 0, 0, 0, 0,
]
active_crit_count, active_high_count, active_med_count, active_low_count, _ = [
0, 0, 0, 0, 0,
]
for finding in findings:
try:
severity = finding.severity
active = finding.active
# risk_accepted = finding.risk_accepted TODO: in future release
except:
severity = finding.finding.severity
active = finding.finding.active
# risk_accepted = finding.finding.risk_accepted
try:
f_time = datetime.combine(finding.date, datetime.min.time()).replace(tzinfo=tz)
except:
f_time = finding.date
if f_time <= end_date:
if severity == "Critical":
if new_date <= f_time:
f_crit_count += 1
if active:
active_crit_count += 1
elif severity == "High":
if new_date <= f_time:
f_high_count += 1
if active:
active_high_count += 1
elif severity == "Medium":
if new_date <= f_time:
f_med_count += 1
if active:
active_med_count += 1
elif severity == "Low":
if new_date <= f_time:
f_low_count += 1
if active:
active_low_count += 1
if risks_a is not None:
for finding in risks_a:
try:
severity = finding.severity
except:
severity = finding.finding.severity
if severity == "Critical":
ra_crit_count += 1
elif severity == "High":
ra_high_count += 1
elif severity == "Medium":
ra_med_count += 1
elif severity == "Low":
ra_low_count += 1
total = f_crit_count + f_high_count + f_med_count + f_low_count
opened_in_period.append(
[(tcalendar.timegm(new_date.timetuple()) * 1000), new_date,
f_crit_count, f_high_count, f_med_count, f_low_count, total,
closed_in_range_count])
total = ra_crit_count + ra_high_count + ra_med_count + ra_low_count
accepted_in_period.append(
[(tcalendar.timegm(new_date.timetuple()) * 1000), new_date,
ra_crit_count, ra_high_count, ra_med_count, ra_low_count, total])
total = active_crit_count + active_high_count + active_med_count + active_low_count
active_in_period.append(
[(tcalendar.timegm(new_date.timetuple()) * 1000), new_date,
active_crit_count, active_high_count, active_med_count, active_low_count, total])
return {
"opened_per_period": opened_in_period,
"accepted_per_period": accepted_in_period,
"active_per_period": active_in_period,
}
def opened_in_period(start_date, end_date, **kwargs):
start_date = datetime(
start_date.year,
start_date.month,
start_date.day,
tzinfo=timezone.get_current_timezone())
end_date = datetime(
end_date.year,
end_date.month,
end_date.day,
tzinfo=timezone.get_current_timezone())
if get_system_setting("enforce_verified_status", True) or get_system_setting("enforce_verified_status_metrics", True):
opened_in_period = Finding.objects.filter(
date__range=[start_date, end_date],
**kwargs,
verified=True,
false_p=False,
duplicate=False,
out_of_scope=False,
mitigated__isnull=True,
severity__in=(
"Critical", "High", "Medium",
"Low")).values("numerical_severity").annotate(
Count("numerical_severity")).order_by("numerical_severity")
total_opened_in_period = Finding.objects.filter(
date__range=[start_date, end_date],
**kwargs,
verified=True,
false_p=False,
duplicate=False,
out_of_scope=False,
mitigated__isnull=True,
severity__in=("Critical", "High", "Medium", "Low")).aggregate(
total=Sum(
Case(
When(
severity__in=("Critical", "High", "Medium", "Low"),
then=Value(1)),
output_field=IntegerField())))["total"]
oip = {
"S0":
0,
"S1":
0,
"S2":
0,
"S3":
0,
"Total":
total_opened_in_period,
"start_date":
start_date,
"end_date":
end_date,
"closed":
Finding.objects.filter(
mitigated__date__range=[start_date, end_date],
**kwargs,
severity__in=("Critical", "High", "Medium", "Low")).aggregate(
total=Sum(
Case(
When(
severity__in=("Critical", "High", "Medium", "Low"),
then=Value(1)),
output_field=IntegerField())))["total"],
"to_date_total":
Finding.objects.filter(
date__lte=end_date.date(),
verified=True,
false_p=False,
duplicate=False,
out_of_scope=False,
mitigated__isnull=True,
**kwargs,
severity__in=("Critical", "High", "Medium", "Low")).count(),
}
else:
opened_in_period = Finding.objects.filter(
date__range=[start_date, end_date],
**kwargs,
false_p=False,
duplicate=False,
out_of_scope=False,
mitigated__isnull=True,
severity__in=(
"Critical", "High", "Medium",
"Low")).values("numerical_severity").annotate(
Count("numerical_severity")).order_by("numerical_severity")
total_opened_in_period = Finding.objects.filter(
date__range=[start_date, end_date],
**kwargs,
false_p=False,
duplicate=False,
out_of_scope=False,
mitigated__isnull=True,
severity__in=("Critical", "High", "Medium", "Low")).aggregate(
total=Sum(
Case(
When(
severity__in=("Critical", "High", "Medium", "Low"),
then=Value(1)),
output_field=IntegerField())))["total"]
oip = {
"S0":
0,
"S1":
0,
"S2":
0,
"S3":
0,
"Total":
total_opened_in_period,
"start_date":
start_date,
"end_date":
end_date,
"closed":
Finding.objects.filter(
mitigated__date__range=[start_date, end_date],
**kwargs,
severity__in=("Critical", "High", "Medium", "Low")).aggregate(
total=Sum(
Case(
When(
severity__in=("Critical", "High", "Medium", "Low"),
then=Value(1)),
output_field=IntegerField())))["total"],
"to_date_total":
Finding.objects.filter(
date__lte=end_date.date(),
false_p=False,
duplicate=False,
out_of_scope=False,
mitigated__isnull=True,
**kwargs,
severity__in=("Critical", "High", "Medium", "Low")).count(),
}
for o in opened_in_period:
oip[o["numerical_severity"]] = o["numerical_severity__count"]
return oip
class FileIterWrapper:
def __init__(self, flo, chunk_size=1024**2):
self.flo = flo
self.chunk_size = chunk_size
def __next__(self):
data = self.flo.read(self.chunk_size)
if data:
return data
raise StopIteration
def __iter__(self):
return self
def get_cal_event(start_date, end_date, summary, description, uid):
cal = vobject.iCalendar()
cal.add("vevent")
cal.vevent.add("summary").value = summary
cal.vevent.add("description").value = description
start = cal.vevent.add("dtstart")
start.value = start_date
end = cal.vevent.add("dtend")
end.value = end_date
cal.vevent.add("uid").value = uid
return cal
def named_month(month_number):
"""Return the name of the month, given the number."""
return date(1900, month_number, 1).strftime("%B")
def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r"\s{2,}").sub):
return [
normspace(" ", (t[0] or t[1]).strip()) for t in findterms(query_string)
]
def build_query(query_string, search_fields):
"""
Returns a query, that is a combination of Q objects. That combination
aims to search keywords within a model by testing the given search fields.
"""
query = None # Query to search for every search term
terms = normalize_query(query_string)
for term in terms:
or_query = None # Query to search for a given term in each field
for field_name in search_fields:
q = Q(**{f"{field_name}__icontains": term})
or_query = or_query | q if or_query else q
query = query & or_query if query else or_query
return query
def template_search_helper(fields=None, query_string=None):
if not fields:
fields = [
"title",
"description",
]
findings = Finding_Template.objects.all()