-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
views.py
3155 lines (2723 loc) · 96.1 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import socket
import logging
import requests
import validators
import requests
from ipaddress import IPv4Network
from django.db.models import CharField, Count, F, Q, Value
from django.utils import timezone
from packaging import version
from django.template.defaultfilters import slugify
from datetime import datetime
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_204_NO_CONTENT, HTTP_202_ACCEPTED
from rest_framework.decorators import action
from django.core.exceptions import ObjectDoesNotExist
from django.core.cache import cache
from dashboard.models import *
from recon_note.models import *
from reNgine.celery import app
from reNgine.common_func import *
from reNgine.database_utils import *
from reNgine.definitions import ABORTED_TASK
from reNgine.tasks import *
from reNgine.llm import *
from reNgine.utilities import is_safe_path
from scanEngine.models import *
from startScan.models import *
from startScan.models import EndPoint
from targetApp.models import *
from api.shared_api_tasks import import_hackerone_programs_task, sync_bookmarked_programs_task
from .serializers import *
logger = logging.getLogger(__name__)
class ToggleBugBountyModeView(APIView):
"""
This class manages the user bug bounty mode
"""
def post(self, request, *args, **kwargs):
user_preferences = get_object_or_404(UserPreferences, user=request.user)
user_preferences.bug_bounty_mode = not user_preferences.bug_bounty_mode
user_preferences.save()
return Response({
'bug_bounty_mode': user_preferences.bug_bounty_mode
}, status=status.HTTP_200_OK)
class HackerOneProgramViewSet(viewsets.ViewSet):
"""
This class manages the HackerOne Program model,
provides basic fetching of programs and caching
"""
CACHE_KEY = 'hackerone_programs'
CACHE_TIMEOUT = 60 * 30 # 30 minutes
PROGRAM_CACHE_KEY = 'hackerone_program_{}'
API_BASE = 'https://api.hackerone.com/v1/hackers'
ALLOWED_ASSET_TYPES = ["WILDCARD", "DOMAIN", "IP_ADDRESS", "CIDR", "URL"]
def list(self, request):
try:
sort_by = request.query_params.get('sort_by', 'age')
sort_order = request.query_params.get('sort_order', 'desc')
programs = self.get_cached_programs()
if sort_by == 'name':
programs = sorted(programs, key=lambda x: x['attributes']['name'].lower(),
reverse=(sort_order.lower() == 'desc'))
elif sort_by == 'reports':
programs = sorted(programs, key=lambda x: x['attributes'].get('number_of_reports_for_user', 0),
reverse=(sort_order.lower() == 'desc'))
elif sort_by == 'age':
programs = sorted(programs,
key=lambda x: datetime.strptime(x['attributes'].get('started_accepting_at', '1970-01-01T00:00:00.000Z'), '%Y-%m-%dT%H:%M:%S.%fZ'),
reverse=(sort_order.lower() == 'desc')
)
serializer = HackerOneProgramSerializer(programs, many=True)
return Response(serializer.data)
except Exception as e:
return self.handle_exception(e)
def get_api_credentials(self):
try:
api_key = HackerOneAPIKey.objects.first()
if not api_key:
raise ObjectDoesNotExist("HackerOne API credentials not found")
return api_key.username, api_key.key
except ObjectDoesNotExist:
raise Exception("HackerOne API credentials not configured")
@action(detail=False, methods=['get'])
def bookmarked_programs(self, request):
try:
# do not cache bookmarked programs due to the user specific nature
programs = self.fetch_programs_from_hackerone()
bookmarked = [p for p in programs if p['attributes']['bookmarked']]
serializer = HackerOneProgramSerializer(bookmarked, many=True)
return Response(serializer.data)
except Exception as e:
return self.handle_exception(e)
@action(detail=False, methods=['get'])
def bounty_programs(self, request):
try:
programs = self.get_cached_programs()
bounty_programs = [p for p in programs if p['attributes']['offers_bounties']]
serializer = HackerOneProgramSerializer(bounty_programs, many=True)
return Response(serializer.data)
except Exception as e:
return self.handle_exception(e)
def get_cached_programs(self):
programs = cache.get(self.CACHE_KEY)
if programs is None:
programs = self.fetch_programs_from_hackerone()
cache.set(self.CACHE_KEY, programs, self.CACHE_TIMEOUT)
return programs
def fetch_programs_from_hackerone(self):
url = f'{self.API_BASE}/programs?page[size]=100'
headers = {'Accept': 'application/json'}
all_programs = []
try:
username, api_key = self.get_api_credentials()
except Exception as e:
raise Exception("API credentials error: " + str(e))
while url:
response = requests.get(
url,
headers=headers,
auth=(username, api_key)
)
if response.status_code == 401:
raise Exception("Invalid API credentials")
elif response.status_code != 200:
raise Exception(f"HackerOne API request failed with status code {response.status_code}")
data = response.json()
all_programs.extend(data['data'])
url = data['links'].get('next')
return all_programs
@action(detail=False, methods=['post'])
def refresh_cache(self, request):
try:
programs = self.fetch_programs_from_hackerone()
cache.set(self.CACHE_KEY, programs, self.CACHE_TIMEOUT)
return Response({"status": "Cache refreshed successfully"})
except Exception as e:
return self.handle_exception(e)
@action(detail=True, methods=['get'])
def program_details(self, request, pk=None):
try:
program_handle = pk
cache_key = self.PROGRAM_CACHE_KEY.format(program_handle)
program_details = cache.get(cache_key)
if program_details is None:
program_details = self.fetch_program_details_from_hackerone(program_handle)
if program_details:
cache.set(cache_key, program_details, self.CACHE_TIMEOUT)
if program_details:
filtered_scopes = [
scope for scope in program_details.get('relationships', {}).get('structured_scopes', {}).get('data', [])
if scope.get('attributes', {}).get('asset_type') in self.ALLOWED_ASSET_TYPES
]
program_details['relationships']['structured_scopes']['data'] = filtered_scopes
return Response(program_details)
else:
return Response({"error": "Program not found"}, status=status.HTTP_404_NOT_FOUND)
except Exception as e:
return self.handle_exception(e)
def fetch_program_details_from_hackerone(self, program_handle):
url = f'{self.API_BASE}/programs/{program_handle}'
headers = {'Accept': 'application/json'}
try:
username, api_key = self.get_api_credentials()
except Exception as e:
raise Exception("API credentials error: " + str(e))
response = requests.get(
url,
headers=headers,
auth=(username, api_key)
)
if response.status_code == 401:
raise Exception("Invalid API credentials")
elif response.status_code == 200:
return response.json()
else:
return None
@action(detail=False, methods=['post'])
def import_programs(self, request):
try:
project_slug = request.query_params.get('project_slug')
if not project_slug:
return Response({"error": "Project slug is required"}, status=status.HTTP_400_BAD_REQUEST)
handles = request.data.get('handles', [])
if not handles:
return Response({"error": "No program handles provided"}, status=status.HTTP_400_BAD_REQUEST)
import_hackerone_programs_task.delay(handles, project_slug)
create_inappnotification(
title="HackerOne Program Import Started",
description=f"Import process for {len(handles)} program(s) has begun.",
notification_type=PROJECT_LEVEL_NOTIFICATION,
project_slug=project_slug,
icon="mdi-download",
status='info'
)
return Response({"message": f"Import process for {len(handles)} program(s) has begun."}, status=status.HTTP_202_ACCEPTED)
except Exception as e:
return self.handle_exception(e)
@action(detail=False, methods=['get'])
def sync_bookmarked(self, request):
try:
project_slug = request.query_params.get('project_slug')
if not project_slug:
return Response({"error": "Project slug is required"}, status=status.HTTP_400_BAD_REQUEST)
sync_bookmarked_programs_task.delay(project_slug)
create_inappnotification(
title="HackerOne Bookmarked Programs Sync Started",
description="Sync process for bookmarked programs has begun.",
notification_type=PROJECT_LEVEL_NOTIFICATION,
project_slug=project_slug,
icon="mdi-sync",
status='info'
)
return Response({"message": "Sync process for bookmarked programs has begun."}, status=status.HTTP_202_ACCEPTED)
except Exception as e:
return self.handle_exception(e)
def handle_exception(self, exc):
if isinstance(exc, ObjectDoesNotExist):
return Response({"error": "HackerOne API credentials not configured"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
elif str(exc) == "Invalid API credentials":
return Response({"error": "Invalid HackerOne API credentials"}, status=status.HTTP_401_UNAUTHORIZED)
else:
return Response({"error": str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class InAppNotificationManagerViewSet(viewsets.ModelViewSet):
"""
This class manages the notification model, provided CRUD operation on notif model
such as read notif, clear all, fetch all notifications etc
"""
serializer_class = InAppNotificationSerializer
pagination_class = None
def get_queryset(self):
# we will see later if user based notif is needed
# return InAppNotification.objects.filter(user=self.request.user)
project_slug = self.request.query_params.get('project_slug')
queryset = InAppNotification.objects.all()
if project_slug:
queryset = queryset.filter(
Q(project__slug=project_slug) | Q(notification_type='system')
)
return queryset.order_by('-created_at')
@action(detail=False, methods=['post'])
def mark_all_read(self, request):
# marks all notification read
project_slug = self.request.query_params.get('project_slug')
queryset = self.get_queryset()
if project_slug:
queryset = queryset.filter(
Q(project__slug=project_slug) | Q(notification_type='system')
)
queryset.update(is_read=True)
return Response(status=HTTP_204_NO_CONTENT)
@action(detail=True, methods=['post'])
def mark_read(self, request, pk=None):
# mark individual notification read when cliked
notification = self.get_object()
notification.is_read = True
notification.save()
return Response(status=HTTP_204_NO_CONTENT)
@action(detail=False, methods=['get'])
def unread_count(self, request):
# this fetches the count for unread notif mainly for the badge
project_slug = self.request.query_params.get('project_slug')
queryset = self.get_queryset()
if project_slug:
queryset = queryset.filter(
Q(project__slug=project_slug) | Q(notification_type='system')
)
count = queryset.filter(is_read=False).count()
return Response({'count': count})
@action(detail=False, methods=['post'])
def clear_all(self, request):
# when clicked on the clear button this must be called to clear all notif
project_slug = self.request.query_params.get('project_slug')
queryset = self.get_queryset()
if project_slug:
queryset = queryset.filter(
Q(project__slug=project_slug) | Q(notification_type='system')
)
queryset.delete()
return Response(status=HTTP_204_NO_CONTENT)
class OllamaManager(APIView):
def get(self, request):
"""
API to download Ollama Models
sends a POST request to download the model
"""
req = self.request
model_name = req.query_params.get('model')
response = {
'status': False
}
try:
pull_model_api = f'{OLLAMA_INSTANCE}/api/pull'
_response = requests.post(
pull_model_api,
json={
'name': model_name,
'stream': False
}
).json()
if _response.get('error'):
response['status'] = False
response['error'] = _response.get('error')
else:
response['status'] = True
except Exception as e:
response['error'] = str(e)
return Response(response)
def delete(self, request):
req = self.request
model_name = req.query_params.get('model')
delete_model_api = f'{OLLAMA_INSTANCE}/api/delete'
response = {
'status': False
}
try:
_response = requests.delete(
delete_model_api,
json={
'name': model_name
}
).json()
if _response.get('error'):
response['status'] = False
response['error'] = _response.get('error')
else:
response['status'] = True
except Exception as e:
response['error'] = str(e)
return Response(response)
def put(self, request):
req = self.request
model_name = req.query_params.get('model')
# check if model_name is in DEFAULT_GPT_MODELS
response = {
'status': False
}
use_ollama = True
if any(model['name'] == model_name for model in DEFAULT_GPT_MODELS):
use_ollama = False
try:
OllamaSettings.objects.update_or_create(
defaults={
'selected_model': model_name,
'use_ollama': use_ollama
},
id=1
)
response['status'] = True
except Exception as e:
response['error'] = str(e)
return Response(response)
class GPTAttackSuggestion(APIView):
def get(self, request):
req = self.request
subdomain_id = req.query_params.get('subdomain_id')
if not subdomain_id:
return Response({
'status': False,
'error': 'Missing GET param Subdomain `subdomain_id`'
})
try:
subdomain = Subdomain.objects.get(id=subdomain_id)
except Exception as e:
return Response({
'status': False,
'error': 'Subdomain not found with id ' + subdomain_id
})
if subdomain.attack_surface:
return Response({
'status': True,
'subdomain_name': subdomain.name,
'description': subdomain.attack_surface
})
ip_addrs = subdomain.ip_addresses.all()
open_ports_str = ''
for ip in ip_addrs:
ports = ip.ports.all()
for port in ports:
open_ports_str += f'{port.number}/{port.service_name}, '
tech_used = ''
for tech in subdomain.technologies.all():
tech_used += f'{tech.name}, '
llm_input = f'''
Subdomain Name: {subdomain.name}
Subdomain Page Title: {subdomain.page_title}
Open Ports: {open_ports_str}
HTTP Status: {subdomain.http_status}
Technologies Used: {tech_used}
Content type: {subdomain.content_type}
Web Server: {subdomain.webserver}
Page Content Length: {subdomain.content_length}
'''
llm_input = re.sub(r'\t', '', llm_input)
gpt = LLMAttackSuggestionGenerator(logger)
response = gpt.get_attack_suggestion(llm_input)
response['subdomain_name'] = subdomain.name
if response.get('status'):
subdomain.attack_surface = response.get('description')
subdomain.save()
return Response(response)
class LLMVulnerabilityReportGenerator(APIView):
def get(self, request):
req = self.request
vulnerability_id = req.query_params.get('id')
if not vulnerability_id:
return Response({
'status': False,
'error': 'Missing GET param Vulnerability `id`'
})
task = llm_vulnerability_description.apply_async(args=(vulnerability_id,))
response = task.wait()
return Response(response)
class CreateProjectApi(APIView):
def get(self, request):
req = self.request
project_name = req.query_params.get('name')
slug = slugify(project_name)
insert_date = timezone.now()
try:
project = Project.objects.create(
name=project_name,
slug=slug,
insert_date =insert_date
)
response = {
'status': True,
'project_name': project_name
}
return Response(response)
except Exception as e:
response = {
'status': False,
'error': str(e)
}
return Response(response, status=HTTP_400_BAD_REQUEST)
class QueryInterestingSubdomains(APIView):
def get(self, request):
req = self.request
scan_id = req.query_params.get('scan_id')
domain_id = req.query_params.get('target_id')
if scan_id:
queryset = get_interesting_subdomains(scan_history=scan_id)
elif domain_id:
queryset = get_interesting_subdomains(domain_id=domain_id)
else:
queryset = get_interesting_subdomains()
queryset = queryset.distinct('name')
return Response(InterestingSubdomainSerializer(queryset, many=True).data)
class ListTargetsDatatableViewSet(viewsets.ModelViewSet):
queryset = Domain.objects.all()
serializer_class = DomainSerializer
def get_queryset(self):
slug = self.request.GET.get('slug', None)
if slug:
self.queryset = self.queryset.filter(project__slug=slug)
return self.queryset
def filter_queryset(self, qs):
qs = self.queryset.filter()
search_value = self.request.GET.get(u'search[value]', None)
_order_col = self.request.GET.get(u'order[0][column]', None)
_order_direction = self.request.GET.get(u'order[0][dir]', None)
if search_value or _order_col or _order_direction:
order_col = 'id'
if _order_col == '2':
order_col = 'name'
elif _order_col == '4':
order_col = 'insert_date'
elif _order_col == '5':
order_col = 'start_scan_date'
if _order_direction == 'desc':
return qs.order_by(F('start_scan_date').desc(nulls_last=True))
return qs.order_by(F('start_scan_date').asc(nulls_last=True))
if _order_direction == 'desc':
order_col = f'-{order_col}'
qs = self.queryset.filter(
Q(name__icontains=search_value) |
Q(description__icontains=search_value) |
Q(domains__name__icontains=search_value)
)
return qs.order_by(order_col)
return qs.order_by('-id')
class WafDetector(APIView):
def get(self, request):
req = self.request
url= req.query_params.get('url')
response = {}
response['status'] = False
# validate url as a first step to avoid command injection
if not (validators.url(url) or validators.domain(url)):
response['message'] = 'Invalid Domain/URL provided!'
return Response(response)
wafw00f_command = f'wafw00f {url}'
_, output = run_command(wafw00f_command, remove_ansi_sequence=True)
regex = r"behind (.*?) WAF"
group = re.search(regex, output)
if group:
response['status'] = True
response['results'] = group.group(1)
else:
response['message'] = 'Could not detect any WAF!'
return Response(response)
class SearchHistoryView(APIView):
def get(self, request):
req = self.request
response = {}
response['status'] = False
scan_history = SearchHistory.objects.all().order_by('-id')[:5]
if scan_history:
response['status'] = True
response['results'] = SearchHistorySerializer(scan_history, many=True).data
return Response(response)
class UniversalSearch(APIView):
def get(self, request):
req = self.request
query = req.query_params.get('query')
response = {}
response['status'] = False
if not query:
response['message'] = 'No query parameter provided!'
return Response(response)
response['results'] = {}
# search history to be saved
SearchHistory.objects.get_or_create(
query=query
)
# lookup query in subdomain
subdomain = Subdomain.objects.filter(
Q(name__icontains=query) |
Q(cname__icontains=query) |
Q(page_title__icontains=query) |
Q(http_url__icontains=query)
).distinct('name')
subdomain_data = SubdomainSerializer(subdomain, many=True).data
response['results']['subdomains'] = subdomain_data
endpoint = EndPoint.objects.filter(
Q(http_url__icontains=query) |
Q(page_title__icontains=query)
).distinct('http_url')
endpoint_data = EndpointSerializer(endpoint, many=True).data
response['results']['endpoints'] = endpoint_data
vulnerability = Vulnerability.objects.filter(
Q(http_url__icontains=query) |
Q(name__icontains=query) |
Q(description__icontains=query)
).distinct()
vulnerability_data = VulnerabilitySerializer(vulnerability, many=True).data
response['results']['vulnerabilities'] = vulnerability_data
response['results']['others'] = {}
if subdomain_data or endpoint_data or vulnerability_data:
response['status'] = True
return Response(response)
class FetchMostCommonVulnerability(APIView):
def post(self, request):
req = self.request
data = req.data
try:
limit = data.get('limit', 20)
project_slug = data.get('slug')
scan_history_id = data.get('scan_history_id')
target_id = data.get('target_id')
is_ignore_info = data.get('ignore_info', False)
response = {}
response['status'] = False
if project_slug:
project = Project.objects.get(slug=project_slug)
vulnerabilities = Vulnerability.objects.filter(target_domain__project=project)
else:
vulnerabilities = Vulnerability.objects.all()
if scan_history_id:
vuln_query = (
vulnerabilities
.filter(scan_history__id=scan_history_id)
.values("name", "severity")
)
if is_ignore_info:
most_common_vulnerabilities = (
vuln_query
.exclude(severity=0)
.annotate(count=Count('name'))
.order_by("-count")[:limit]
)
else:
most_common_vulnerabilities = (
vuln_query
.annotate(count=Count('name'))
.order_by("-count")[:limit]
)
elif target_id:
vuln_query = vulnerabilities.filter(target_domain__id=target_id).values("name", "severity")
if is_ignore_info:
most_common_vulnerabilities = (
vuln_query
.exclude(severity=0)
.annotate(count=Count('name'))
.order_by("-count")[:limit]
)
else:
most_common_vulnerabilities = (
vuln_query
.annotate(count=Count('name'))
.order_by("-count")[:limit]
)
else:
vuln_query = vulnerabilities.values("name", "severity")
if is_ignore_info:
most_common_vulnerabilities = (
vuln_query.exclude(severity=0)
.annotate(count=Count('name'))
.order_by("-count")[:limit]
)
else:
most_common_vulnerabilities = (
vuln_query.annotate(count=Count('name'))
.order_by("-count")[:limit]
)
most_common_vulnerabilities = [vuln for vuln in most_common_vulnerabilities]
if most_common_vulnerabilities:
response['status'] = True
response['result'] = most_common_vulnerabilities
except Exception as e:
print(str(e))
response = {}
return Response(response)
class FetchMostVulnerable(APIView):
def post(self, request):
req = self.request
data = req.data
project_slug = data.get('slug')
scan_history_id = data.get('scan_history_id')
target_id = data.get('target_id')
limit = data.get('limit', 20)
is_ignore_info = data.get('ignore_info', False)
response = {}
response['status'] = False
if project_slug:
project = Project.objects.get(slug=project_slug)
subdomains = Subdomain.objects.filter(target_domain__project=project)
domains = Domain.objects.filter(project=project)
else:
subdomains = Subdomain.objects.all()
domains = Domain.objects.all()
if scan_history_id:
subdomain_query = subdomains.filter(scan_history__id=scan_history_id)
if is_ignore_info:
most_vulnerable_subdomains = (
subdomain_query
.annotate(
vuln_count=Count('vulnerability__name', filter=~Q(vulnerability__severity=0))
)
.order_by('-vuln_count')
.exclude(vuln_count=0)[:limit]
)
else:
most_vulnerable_subdomains = (
subdomain_query
.annotate(vuln_count=Count('vulnerability__name'))
.order_by('-vuln_count')
.exclude(vuln_count=0)[:limit]
)
if most_vulnerable_subdomains:
response['status'] = True
response['result'] = (
SubdomainSerializer(
most_vulnerable_subdomains,
many=True)
.data
)
elif target_id:
subdomain_query = subdomains.filter(target_domain__id=target_id)
if is_ignore_info:
most_vulnerable_subdomains = (
subdomain_query
.annotate(vuln_count=Count('vulnerability__name', filter=~Q(vulnerability__severity=0)))
.order_by('-vuln_count')
.exclude(vuln_count=0)[:limit]
)
else:
most_vulnerable_subdomains = (
subdomain_query
.annotate(vuln_count=Count('vulnerability__name'))
.order_by('-vuln_count')
.exclude(vuln_count=0)[:limit]
)
if most_vulnerable_subdomains:
response['status'] = True
response['result'] = (
SubdomainSerializer(
most_vulnerable_subdomains,
many=True)
.data
)
else:
if is_ignore_info:
most_vulnerable_targets = (
domains
.annotate(vuln_count=Count('subdomain__vulnerability__name', filter=~Q(subdomain__vulnerability__severity=0)))
.order_by('-vuln_count')
.exclude(vuln_count=0)[:limit]
)
else:
most_vulnerable_targets = (
domains
.annotate(vuln_count=Count('subdomain__vulnerability__name'))
.order_by('-vuln_count')
.exclude(vuln_count=0)[:limit]
)
if most_vulnerable_targets:
response['status'] = True
response['result'] = (
DomainSerializer(
most_vulnerable_targets,
many=True)
.data
)
return Response(response)
class CVEDetails(APIView):
def get(self, request):
req = self.request
cve_id = req.query_params.get('cve_id')
if not cve_id:
return Response({'status': False, 'message': 'CVE ID not provided'})
response = requests.get('https://cve.circl.lu/api/cve/' + cve_id)
if response.status_code != 200:
return Response({'status': False, 'message': 'Unknown Error Occured!'})
if not response.json():
return Response({'status': False, 'message': 'CVE ID does not exists.'})
return Response({'status': True, 'result': response.json()})
class AddReconNote(APIView):
def post(self, request):
req = self.request
data = req.data
subdomain_id = data.get('subdomain_id')
title = data.get('title')
description = data.get('description')
project = data.get('project')
try:
project = Project.objects.get(slug=project)
note = TodoNote()
note.title = title
note.description = description
# get scan history for subdomain_id
if subdomain_id:
subdomain = Subdomain.objects.get(id=subdomain_id)
note.subdomain = subdomain
# also get scan history
scan_history_id = subdomain.scan_history.id
scan_history = ScanHistory.objects.get(id=scan_history_id)
note.scan_history = scan_history
note.project = project
note.save()
response = {'status': True}
except Exception as e:
response = {'status': False, 'message': str(e)}
return Response(response)
class ToggleSubdomainImportantStatus(APIView):
def post(self, request):
req = self.request
data = req.data
subdomain_id = data.get('subdomain_id')
response = {'status': False, 'message': 'No subdomain_id provided'}
name = Subdomain.objects.get(id=subdomain_id)
name.is_important = not name.is_important
name.save()
response = {'status': True}
return Response(response)
class AddTarget(APIView):
def post(self, request):
req = self.request
data = req.data
h1_team_handle = data.get('h1_team_handle')
description = data.get('description')
domain_name = data.get('domain_name')
# remove wild card from domain
domain_name = domain_name.replace('*', '')
# if domain_name begins with . remove that
if domain_name.startswith('.'):
domain_name = domain_name[1:]
organization_name = data.get('organization')
slug = data.get('slug')
# Validate domain name
if not validators.domain(domain_name):
return Response({'status': False, 'message': 'Invalid domain or IP'})
status = bulk_import_targets(
targets=[{
'name': domain_name,
'description': description,
}],
organization_name=organization_name,
h1_team_handle=h1_team_handle,
project_slug=slug
)
if status:
return Response({
'status': True,
'message': 'Domain successfully added as target !',
'domain_name': domain_name,
# 'domain_id': domain.id
})
return Response({
'status': False,
'message': 'Failed to add as target !'
})
class FetchSubscanResults(APIView):
def get(self, request):
req = self.request
# data = req.data
subscan_id = req.query_params.get('subscan_id')
subscan = SubScan.objects.filter(id=subscan_id)
if not subscan.exists():
return Response({
'status': False,
'error': f'Subscan {subscan_id} does not exist'
})
subscan_data = SubScanResultSerializer(subscan.first(), many=False).data
task_name = subscan_data['type']
subscan_results = []
if task_name == 'port_scan':
ips_in_subscan = IpAddress.objects.filter(ip_subscan_ids__in=subscan)
subscan_results = IpSerializer(ips_in_subscan, many=True).data
elif task_name == 'vulnerability_scan':
vulns_in_subscan = Vulnerability.objects.filter(vuln_subscan_ids__in=subscan)
subscan_results = VulnerabilitySerializer(vulns_in_subscan, many=True).data
elif task_name == 'fetch_url':
endpoints_in_subscan = EndPoint.objects.filter(endpoint_subscan_ids__in=subscan)
subscan_results = EndpointSerializer(endpoints_in_subscan, many=True).data
elif task_name == 'dir_file_fuzz':
dirs_in_subscan = DirectoryScan.objects.filter(dir_subscan_ids__in=subscan)
subscan_results = DirectoryScanSerializer(dirs_in_subscan, many=True).data
elif task_name == 'subdomain_discovery':
subdomains_in_subscan = Subdomain.objects.filter(subdomain_subscan_ids__in=subscan)
subscan_results = SubdomainSerializer(subdomains_in_subscan, many=True).data
elif task_name == 'screenshot':
subdomains_in_subscan = Subdomain.objects.filter(subdomain_subscan_ids__in=subscan, screenshot_path__isnull=False)
subscan_results = SubdomainSerializer(subdomains_in_subscan, many=True).data
logger.info(subscan_data)
logger.info(subscan_results)