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
1123 lines (982 loc) · 47.8 KB
/
utils.py
File metadata and controls
1123 lines (982 loc) · 47.8 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 calendar as tcalendar
import re
import binascii, os, hashlib
from Crypto.Cipher import AES
from calendar import monthrange
from datetime import date, datetime, timedelta
from math import pi, sqrt
import vobject
import requests
from dateutil.relativedelta import relativedelta, MO
from django.conf import settings
from django.core.mail import send_mail
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import get_resolver, reverse
from django.contrib import messages
from django.db.models import Q, Sum, Case, When, IntegerField, Value, Count
from django.template.defaultfilters import pluralize
from pytz import timezone
from jira import JIRA
from jira.exceptions import JIRAError
from dojo.models import Finding, Scan, Test, Engagement, Stub_Finding, Finding_Template, Report, Product, JIRA_PKey, JIRA_Issue, Dojo_User, User, Notes, FindingImage, Alerts
localtz = timezone(settings.TIME_ZONE)
"""
Michael & Fatima:
Helper function for metrics
Counts the number of findings and the count for the products for each level of
severity for a given finding querySet
"""
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 = localtz.localize(datetime.today())
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
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':
a_count['zero'] += 1
elif f.severity == 'High':
a_count['one'] += 1
elif f.severity == 'Medium':
a_count['two'] += 1
elif f.severity == 'Low':
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.append(o_count['zero'])
counts.append(o_count['one'])
counts.append(o_count['two'])
counts.append(o_count['three'])
counts.append(total)
counts.append(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.append(a_count['zero'])
a_counts.append(a_count['one'])
a_counts.append(a_count['two'])
a_counts.append(a_count['three'])
a_counts.append(a_total)
a_stuff.append(a_counts)
def add_breadcrumb(parent=None, title=None, top_level=True, url=None, request=None, clear=False):
title_done = False
if clear:
request.session['dojo_breadcrumbs'] = None
return
else:
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:
title_done = True
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:
title_done = True
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 get_punchcard_data(findings, weeks_between, start_date):
punchcard = list()
ticks = list()
highest_count = 0
tick = 0
week_count = 1
# mon 0, tues 1, wed 2, thurs 3, fri 4, sat 5, sun 6
# sat 0, sun 6, mon 5, tue 4, wed 3, thur 2, fri 1
day_offset = {0: 5, 1: 4, 2: 3, 3: 2, 4: 1, 5: 0, 6: 6}
for x in range(-1, weeks_between):
# week starts the monday before
new_date = start_date + relativedelta(weeks=x, weekday=MO(1))
end_date = new_date + relativedelta(weeks=1)
append_tick = True
days = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
for finding in findings:
try:
if new_date < datetime.combine(finding.date, datetime.min.time()).replace(tzinfo=localtz) <= end_date:
# [0,0,(20*.02)]
# [week, day, weight]
days[day_offset[finding.date.weekday()]] += 1
if days[day_offset[finding.date.weekday()]] > highest_count:
highest_count = days[day_offset[finding.date.weekday()]]
except:
if new_date < finding.date <= end_date:
# [0,0,(20*.02)]
# [week, day, weight]
days[day_offset[finding.date.weekday()]] += 1
if days[day_offset[finding.date.weekday()]] > highest_count:
highest_count = days[day_offset[finding.date.weekday()]]
pass
if sum(days.values()) > 0:
for day, count in days.items():
punchcard.append([tick, day, count])
if append_tick:
ticks.append([tick, new_date.strftime("<span class='small'>%m/%d<br/>%Y</span>")])
append_tick = False
tick += 1
week_count += 1
# adjust the size
ratio = (sqrt(highest_count / pi))
for punch in punchcard:
punch[2] = (sqrt(punch[2] / pi)) / ratio
return punchcard, ticks, highest_count
#5 params
def get_period_counts_legacy(findings, findings_closed, accepted_findings, period_interval, start_date,
relative_delta='months'):
opened_in_period = list()
accepted_in_period = list()
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__range=[new_date, end_date]).count()
if accepted_findings:
risks_a = accepted_findings.filter(
risk_acceptance__created__range=[datetime(new_date.year,
new_date.month, 1,
tzinfo=localtz),
datetime(new_date.year,
new_date.month,
monthrange(new_date.year,
new_date.month)[1],
tzinfo=localtz)])
else:
risks_a = None
crit_count, high_count, med_count, low_count, closed_count = [0, 0, 0, 0, 0]
for finding in findings:
if new_date <= datetime.combine(finding.date, datetime.min.time()).replace(tzinfo=localtz) <= 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, closed_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(active_findings, findings, findings_closed, accepted_findings, period_interval, start_date,
relative_delta='months'):
opened_in_period = list()
active_in_period = list()
accepted_in_period = list()
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))
closed_in_range_count = findings_closed.filter(mitigated__range=[new_date, end_date]).count()
if accepted_findings:
risks_a = accepted_findings.filter(
risk_acceptance__created__range=[datetime(new_date.year,
new_date.month, 1,
tzinfo=localtz),
datetime(new_date.year,
new_date.month,
monthrange(new_date.year,
new_date.month)[1],
tzinfo=localtz)])
else:
risks_a = None
crit_count, high_count, med_count, low_count, closed_count = [0, 0, 0, 0, 0]
for finding in findings:
try:
if new_date <= datetime.combine(finding.date, datetime.min.time()).replace(tzinfo=localtz) <= 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
except:
if new_date <= finding.date <= 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
pass
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, closed_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])
crit_count, high_count, med_count, low_count, closed_count = [0, 0, 0, 0, 0]
for finding in active_findings:
try:
if datetime.combine(finding.date, datetime.min.time()).replace(tzinfo=localtz) <= 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
except:
if finding.date <= 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
pass
total = crit_count + high_count + med_count + low_count
active_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,
'active_per_period': active_in_period}
def opened_in_period(start_date, end_date, pt):
opened_in_period = Finding.objects.filter(date__range=[start_date, end_date],
test__engagement__product__prod_type=pt,
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],
test__engagement__product__prod_type=pt,
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__range=[start_date, end_date],
test__engagement__product__prod_type=pt,
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,
test__engagement__product__prod_type=pt,
severity__in=('Critical', 'High', 'Medium', 'Low')).count()}
for o in opened_in_period:
oip[o['numerical_severity']] = o['numerical_severity__count']
return oip
def message(count, noun, verb):
return ('{} ' + noun + '{} {} ' + verb).format(count, pluralize(count), pluralize(count, 'was,were'))
class FileIterWrapper(object):
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
else:
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(**{"%s__icontains" % field_name: term})
if or_query:
or_query = or_query | q
else:
or_query = q
if query:
query = query & or_query
else:
query = or_query
return query
def template_search_helper(fields=None, query_string=None):
if not fields:
fields = ['title', 'description', ]
findings = Finding_Template.objects.all()
if not query_string:
return findings
entry_query = build_query(query_string, fields)
found_entries = findings.filter(entry_query)
return found_entries
def get_page_items(request, items, page_size, param_name='page'):
size = request.GET.get('page_size', page_size)
paginator = Paginator(items, size)
page = request.GET.get(param_name)
try:
page = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
page = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
page = paginator.page(paginator.num_pages)
return page
def get_alerts(user):
import humanize
now = localtz.localize(datetime.today())
start = now - timedelta(days=7)
dojo_user = Dojo_User.objects.get(id=user.id)
alerts = []
#atmentions in notes
atmentions=Notes.objects.filter(date__range=[start, now],
entry__icontains='@'+user.username)
#show a single alert per finding/test for any finding where
#user was @mentioned in notes AND hasn't afterwards responded
findings_with_atmention=set([Finding.objects.get(notes=note)
for note in atmentions if Finding.objects.filter(notes=note).exists()])
for f in findings_with_atmention:
f_notes=list(f.notes.all())
latest_mention=[n for n in f_notes if n in atmentions][0]
index_latest_mention=f_notes.index(latest_mention)
later_notes_than_mention=f_notes[:index_latest_mention]
if not any(n.author==user for n in later_notes_than_mention):
alerts.append(['You were mentioned in notes on Finding:{}'.format(f.title),
'Posted ' + latest_mention.date.strftime("%b. %d, %Y"),
'file-text-o',
reverse('view_finding', args=(f.id,))])
tests_with_atmention=set([Test.objects.get(notes=note)
for note in atmentions if Test.objects.filter(notes=note).exists()])
for t in tests_with_atmention:
t_notes=list(t.notes.all())
latest_mention=[n for n in t_notes if n in atmentions][0]
index_latest_mention=t_notes.index(latest_mention)
later_notes_than_mention=t_notes[:index_latest_mention]
if not any(n.author==user for n in later_notes_than_mention):
alerts.append(['You were mentioned in notes on Test: %s on %s' % (t.test_type.name, t.engagement.product.name),
'Posted ' + latest_mention.date.strftime("%b. %d, %Y"),
'file-text-o',
reverse('view_test', args=(t.id,))])
# findings under review
under_review = Finding.objects.filter(under_review=True, reviewers__in=[dojo_user])
for fur in under_review:
alerts.append(['Finding Review: ' + fur.title,
'Reviewed On ' + fur.last_reviewed.strftime("%b. %d, %Y"),
' icon-user-check',
reverse('view_finding', args=(fur.id,))])
# Alerts itmes in the last 7 days, ToDo add admin vs user view
# reports requested in the last 7 days
total_alerts = Alerts.objects.filter(created__range=[start, now]).order_by('-display_date')
for alert_item in total_alerts:
alerts.append([alert_item.description,
humanize.naturaltime(localtz.normalize(now) - localtz.normalize(alert_item.display_date)),
alert_item.icon,
alert_item.url])
# reports requested in the last 7 days
completed_reports = Report.objects.filter(requester=user, datetime__range=[start, now], status='success')
running_reports = Report.objects.filter(requester=user, datetime__range=[start, now], status='requested')
for report in completed_reports:
alerts.append(['Report Ready: ' + report.name,
humanize.naturaltime(localtz.normalize(now) - localtz.normalize(report.datetime)),
'file-text-o',
reverse('reports')])
for report in running_reports:
alerts.append(['Report Running: ' + report.name,
humanize.naturaltime(localtz.normalize(now) - localtz.normalize(report.datetime)),
'spinner fa-pulse',
reverse('reports')])
# scans completed in last 7 days
completed_scans = Scan.objects.filter(
date__range=[start, now],
scan_settings__user=user).order_by('-date')
running_scans = Scan.objects.filter(date__range=[start, now],
status='Running').order_by('-date')
for scan in completed_scans:
alerts.append(['Scan Completed',
humanize.naturaltime(localtz.normalize(now) - localtz.normalize(scan.date)),
'crosshairs',
reverse('view_scan', args=(scan.id,))])
for scan in running_scans:
alerts.append(['Scan Running',
humanize.naturaltime(localtz.normalize(now) - localtz.normalize(scan.date)),
'crosshairs',
reverse('view_scan_settings', args=(scan.scan_settings.product.id, scan.scan_settings.id,))])
upcoming_tests = Test.objects.filter(
target_start__gt=now,
engagement__lead=user).order_by('target_start')
for test in upcoming_tests:
alerts.append([
'Upcomming ' + (
test.test_type.name if test.test_type is not None else 'Test'),
'Target Start ' + test.target_start.strftime("%b. %d, %Y"),
'user-secret',
reverse('view_test', args=(test.id,))])
outstanding_engagements = Engagement.objects.filter(
target_end__lt=now,
status='In Progress',
lead=user).order_by('-target_end')
for eng in outstanding_engagements:
alerts.append([
'Stale Engagement: ' + (
eng.name if eng.name is not None else 'Engagement'),
'Target End ' + eng.target_end.strftime("%b. %d, %Y"),
'bullseye',
reverse('view_engagement', args=(eng.id,))])
twenty_four_hours_ago = now - timedelta(hours=24)
outstanding_s0_findings = Finding.objects.filter(
severity='Critical',
reporter=user,
mitigated=None,
verified=True,
false_p=False,
last_reviewed__lt=twenty_four_hours_ago).order_by('-date')
for finding in outstanding_s0_findings:
alerts.append([
'S0 Finding: ' + (
finding.title if finding.title is not None else 'Finding'),
'Reviewed On ' + finding.last_reviewed.strftime("%b. %d, %Y"),
'bug',
reverse('view_finding', args=(finding.id,))])
seven_days_ago = now - timedelta(days=7)
outstanding_s1_findings = Finding.objects.filter(
severity='High',
reporter=user,
mitigated=None,
verified=True,
false_p=False,
last_reviewed__lt=seven_days_ago).order_by('-date')
for finding in outstanding_s1_findings:
alerts.append([
'S1 Finding: ' + (
finding.title if finding.title is not None else 'Finding'),
'Reviewed On ' + finding.last_reviewed.strftime("%b. %d, %Y"),
'bug',
reverse('view_finding', args=(finding.id,))])
fourteen_days_ago = now - timedelta(days=14)
outstanding_s2_findings = Finding.objects.filter(
severity='Medium',
reporter=user,
mitigated=None,
verified=True,
false_p=False,
last_reviewed__lt=fourteen_days_ago).order_by('-date')
for finding in outstanding_s2_findings:
alerts.append([
'S2 Finding: ' + (
finding.title if finding.title is not None else 'Finding'),
'Reviewed On ' + finding.last_reviewed.strftime("%b. %d, %Y"),
'bug',
reverse('view_finding', args=(finding.id,))])
incomplete_findings = Stub_Finding.objects.filter(reporter=user)
for incomplete_finding in incomplete_findings:
alerts.append([
'Incomplete Finding: ' + (
incomplete_finding.title if incomplete_finding.title is not None else 'Finding'),
'Started On ' + incomplete_finding.date.strftime("%b. %d, %Y"),
'bug',
reverse('promote_to_finding', args=(incomplete_finding.id,))])
return alerts
def handle_uploaded_threat(f, eng):
name, extension = os.path.splitext(f.name)
with open(settings.MEDIA_ROOT + '/threat/%s%s' % (eng.id, extension),
'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
eng.tmodel_path = settings.MEDIA_ROOT + '/threat/%s%s' % (eng.id, extension)
eng.save()
def handle_uploaded_selenium(f, cred):
name, extension = os.path.splitext(f.name)
with open(settings.MEDIA_ROOT + '/selenium/%s%s' % (cred.id, extension),
'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
cred.selenium_script = settings.MEDIA_ROOT + '/selenium/%s%s' % (cred.id, extension)
cred.save()
#Gets a connection to a Jira server based on the finding
def get_jira_connection(finding):
prod = Product.objects.get(engagement=Engagement.objects.get(test=finding.test))
jpkey = JIRA_PKey.objects.get(product=prod)
jira_conf = jpkey.conf
jira = JIRA(server=jira_conf.url, basic_auth=(jira_conf.username, jira_conf.password))
return jira
def jira_get_resolution_id(jira, issue, status):
transitions = jira.transitions(issue)
resolution_id = None
for t in transitions:
if t['name'] == "Resolve Issue":
resolution_id = t['id']
break
if t['name'] == "Reopen Issue":
resolution_id = t['id']
break
return resolution_id
def jira_change_resolution_id(jira, issue, id):
jira.transition_issue(issue, id)
# Logs the error to the alerts table, which appears in the notification toolbar
def log_jira_alert(error, finding):
alerts = Alerts(description="Jira update issue: Finding: " + str(finding.id) + ", " + error, url=reverse('view_finding', args=(finding.id,)), icon="bullseye", display_date=localtz.localize(datetime.today()), source="Jira")
alerts.save()
# Displays an alert for Jira notifications
def log_jira_message(text, finding):
alerts = Alerts(description=text + " Finding: " + str(finding.id), url=reverse('view_finding', args=(finding.id,)), icon="bullseye", display_date=localtz.localize(datetime.today()), source="Jira")
alerts.save()
# Adds labels to a Jira issue
def add_labels(find, issue):
#Update Label with Security
issue.fields.labels.append(u'security')
#Update the label with the product name (underscore)
prod_name = find.test.engagement.product.name.replace(" ", "_")
issue.fields.labels.append(prod_name)
issue.update(fields={"labels": issue.fields.labels})
def jira_long_description(find_description, find_id, jira_conf_finding_text):
return find_description + "\n\n*Dojo ID:* " + str(find_id) + "\n\n" + jira_conf_finding_text
def add_issue(find, push_to_jira):
eng = Engagement.objects.get(test=find.test)
prod = Product.objects.get(engagement= eng)
jpkey = JIRA_PKey.objects.get(product=prod)
jira_conf = jpkey.conf
if push_to_jira:
if 'Active' in find.status() and 'Verified' in find.status():
try:
JIRAError.log_to_tempfile=False
jira = JIRA(server=jira_conf.url, basic_auth=(jira_conf.username, jira_conf.password))
if jpkey.component:
new_issue = jira.create_issue(project=jpkey.project_key, summary=find.title,
components=[{'name': jpkey.component}, ],
description=jira_long_description(find.long_desc(), find.id,
jira_conf.finding_text),
issuetype={'name': jira_conf.default_issue_type},
priority={'name': jira_conf.get_priority(find.severity)})
else:
new_issue = jira.create_issue(project=jpkey.project_key, summary=find.title,
description=jira_long_description(find.long_desc(), find.id,
jira_conf.finding_text),
issuetype={'name': jira_conf.default_issue_type},
priority={'name': jira_conf.get_priority(find.severity)})
j_issue = JIRA_Issue(jira_id=new_issue.id, jira_key=new_issue, finding=find)
j_issue.save()
issue = jira.issue(new_issue.id)
#Add labels (security & product)
add_labels(find, new_issue)
#Upload dojo finding screenshots to Jira
for pic in find.images.all():
jira_attachment(jira, issue, settings.MEDIA_ROOT + pic.image_large.name)
#if jpkey.enable_engagement_epic_mapping:
# epic = JIRA_Issue.objects.get(engagement=eng)
# issue_list = [j_issue.jira_id,]
# jira.add_issues_to_epic(epic_id=epic.jira_id, issue_keys=[str(j_issue.jira_id)], ignore_epics=True)
except JIRAError as e:
log_jira_alert(e.text, find)
else:
log_jira_alert("Finding not active or verified.", find)
def jira_attachment(jira, issue, file, jira_filename=None):
basename = file
if jira_filename is None:
basename = os.path.basename(file)
# Check to see if the file has been uploaded to Jira
if jira_check_attachment(issue, basename) == False:
try:
if jira_filename is not None:
attachment = StringIO.StringIO()
attachment.write(data)
jira.add_attachment(issue=issue, attachment=attachment, filename=jira_filename)
else:
# read and upload a file
with open(file, 'rb') as f:
jira.add_attachment(issue=issue, attachment=f)
except JIRAError as e:
log_jira_alert("Attachment: " + e.text, find)
def jira_check_attachment(issue, source_file_name):
file_exists = False
for attachment in issue.fields.attachment:
filename=attachment.filename
if filename == source_file_name:
file_exists = True
break
return file_exists
def update_issue(find, old_status, push_to_jira):
prod = Product.objects.get(engagement=Engagement.objects.get(test=find.test))
jpkey = JIRA_PKey.objects.get(product=prod)
jira_conf = jpkey.conf
if push_to_jira:
j_issue = JIRA_Issue.objects.get(finding=find)
try:
JIRAError.log_to_tempfile=False
jira = JIRA(server=jira_conf.url, basic_auth=(jira_conf.username, jira_conf.password))
issue = jira.issue(j_issue.jira_id)
fields={}
# Only update the component if it didn't exist earlier in Jira, this is to avoid assigning multiple components to an item
if issue.fields.components:
log_jira_alert("Component not updated, exists in Jira already. Update from Jira instead.", find)
else:
#Add component to the Jira issue
component = [{'name': jpkey.component},]
fields={"components": component}
#Upload dojo finding screenshots to Jira
for pic in find.images.all():
jira_attachment(jira, issue, settings.MEDIA_ROOT + pic.image_large.name)
issue.update(summary=find.title, description=jira_long_description(find.long_desc(), find.id, jira_conf.finding_text), priority={'name': jira_conf.get_priority(find.severity)}, fields=fields)
#Add labels(security & product)
add_labels(find, issue)
except JIRAError as e:
log_jira_alert(e.text, find)
req_url =jira_conf.url+'/rest/api/latest/issue/'+ j_issue.jira_id+'/transitions'
if 'Inactive' in find.status() or 'Mitigated' in find.status() or 'False Positive' in find.status() or 'Out of Scope' in find.status() or 'Duplicate' in find.status():
if 'Active' in old_status:
json_data = {'transition':{'id':jira_conf.close_status_key}}
r = requests.post(url=req_url, auth=HTTPBasicAuth(jira_conf.username, jira_conf.password), json=json_data)
elif 'Active' in find.status() and 'Verified' in find.status():
if 'Inactive' in old_status:
json_data = {'transition':{'id':jira_conf.open_status_key}}
r = requests.post(url=req_url, auth=HTTPBasicAuth(jira_conf.username, jira_conf.password), json=json_data)
def close_epic(eng, push_to_jira):
engagement = eng
prod = Product.objects.get(engagement=engagement)
jpkey = JIRA_PKey.objects.get(product=prod)
jira_conf = jpkey.conf
if jpkey.enable_engagement_epic_mapping and push_to_jira:
j_issue = JIRA_Issue.objects.get(engagement=eng)
req_url = jira_conf.url+'/rest/api/latest/issue/'+ j_issue.jira_id+'/transitions'
j_issue = JIRA_Issue.objects.get(engagement=eng)
json_data = {'transition':{'id':jira_conf.close_status_key}}
r = requests.post(url=req_url, auth=HTTPBasicAuth(jira_conf.username, jira_conf.password), json=json_data)
def update_epic(eng, push_to_jira):
engagement = eng
prod = Product.objects.get(engagement=engagement)
jpkey = JIRA_PKey.objects.get(product=prod)
jira_conf = jpkey.conf
if jpkey.enable_engagement_epic_mapping and push_to_jira:
jira = JIRA(server=jira_conf.url, basic_auth=(jira_conf.username, jira_conf.password))
j_issue = JIRA_Issue.objects.get(engagement=eng)
issue = jira.issue(j_issue.jira_id)
issue.update(summary=eng.name, description=eng.name)
def add_epic(eng, push_to_jira):
engagement = eng
prod = Product.objects.get(engagement=engagement)
jpkey = JIRA_PKey.objects.get(product=prod)
jira_conf = jpkey.conf
if jpkey.enable_engagement_epic_mapping and push_to_jira:
issue_dict = {
'project': {'key': jpkey.project_key},
'summary': engagement.name,
'description' : engagement.name,
'issuetype': {'name': 'Epic'},
'customfield_' + str(jira_conf.epic_name_id) : engagement.name,
}
jira = JIRA(server=jira_conf.url, basic_auth=(jira_conf.username, jira_conf.password))
new_issue = jira.create_issue(fields=issue_dict)
j_issue = JIRA_Issue(jira_id=new_issue.id, jira_key=new_issue, engagement=engagement)
j_issue.save()
def add_comment(find, note, force_push=False):
prod = Product.objects.get(engagement=Engagement.objects.get(test=find.test))
jpkey = JIRA_PKey.objects.get(product=prod)
jira_conf = jpkey.conf
if jpkey.push_notes or force_push == True:
jira = JIRA(server=jira_conf.url, basic_auth=(jira_conf.username, jira_conf.password))
j_issue = JIRA_Issue.objects.get(finding=find)