/
tasks.py
2640 lines (2277 loc) · 84 KB
/
tasks.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 os
import traceback
import yaml
import json
import csv
import validators
import random
import requests
import time
import logging
import metafinder.extractor as metadata_extractor
import whatportis
import subprocess
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver
from emailfinder.extractor import *
from dotted_dict import DottedDict
from celery import shared_task
from discord_webhook import DiscordWebhook
from reNgine.celery import app
from startScan.models import *
from targetApp.models import Domain
from scanEngine.models import EngineType
from django.conf import settings
from django.shortcuts import get_object_or_404
from celery import shared_task
from datetime import datetime
from degoogle import degoogle
from django.conf import settings
from django.utils import timezone, dateformat
from django.shortcuts import get_object_or_404
from django.core.exceptions import ObjectDoesNotExist
from reNgine.celery import app
from reNgine.definitions import *
from startScan.models import *
from targetApp.models import Domain
from scanEngine.models import EngineType, Configuration, Wordlist
from .common_func import *
'''
All the background tasks to be executed in celery will be here
'''
@app.task
def run_system_commands(system_command):
'''
This function will run system commands in celery container
'''
os.system(system_command)
@app.task
def initiate_subtask(
subdomain_id,
port_scan=False,
osint=False,
endpoint=False,
dir_fuzz=False,
vuln_scan=False,
engine_id=None
):
# TODO: OSINT IS NOT Currently SUPPORTED!, make it available in later releases
logger.info('Initiating Subtask')
# get scan history and yaml Configuration for this subdomain
subdomain = Subdomain.objects.get(id=subdomain_id)
scan_history = ScanHistory.objects.get(id=subdomain.scan_history.id)
# create scan activity of SubScan Model
current_scan_time = timezone.now()
sub_scan = SubScan()
sub_scan.start_scan_date = current_scan_time
sub_scan.celery_id = initiate_subtask.request.id
sub_scan.scan_history = scan_history
sub_scan.subdomain = subdomain
sub_scan.port_scan = port_scan
sub_scan.osint = osint
sub_scan.fetch_url = endpoint
sub_scan.dir_file_fuzz = dir_fuzz
sub_scan.vulnerability_scan = vuln_scan
sub_scan.status = INITIATED_TASK
sub_scan.save()
if engine_id:
engine = EngineType.objects.get(id=engine_id)
else:
engine = EngineType.objects.get(id=scan_history.scan_type.id)
sub_scan.engine = engine
sub_scan.save()
results_dir = '/usr/src/scan_results/' + scan_history.results_dir
# if not results_dir exists, create one
if not os.path.exists(results_dir):
os.mkdir(results_dir)
try:
yaml_configuration = yaml.load(
engine.yaml_configuration,
Loader=yaml.FullLoader)
sub_scan.start_scan_date = current_scan_time
sub_scan.status = RUNNING_TASK
sub_scan.save()
if port_scan:
# delete any existing ports.json
rand_name = str(time.time()).split('.')[0]
file_name = 'ports_{}_{}.json'.format(subdomain.name, rand_name)
scan_history.port_scan = True
scan_history.save()
port_scanning(
scan_history,
0,
yaml_configuration,
results_dir,
subdomain=subdomain.name,
file_name=file_name,
subscan=sub_scan
)
elif dir_fuzz:
rand_name = str(time.time()).split('.')[0]
file_name = 'dir_fuzz_{}_{}.json'.format(subdomain.name, rand_name)
scan_history.dir_file_fuzz = True
scan_history.save()
directory_fuzz(
scan_history,
0,
yaml_configuration,
results_dir,
subdomain=subdomain.name,
file_name=file_name,
subscan=sub_scan
)
elif endpoint:
rand_name = str(time.time()).split('.')[0]
file_name = 'endpoints_{}_{}.txt'.format(subdomain.name, rand_name)
scan_history.fetch_url = True
scan_history.save()
fetch_endpoints(
scan_history,
0,
yaml_configuration,
results_dir,
subdomain=subdomain,
file_name=file_name,
subscan=sub_scan
)
elif vuln_scan:
rand_name = str(time.time()).split('.')[0]
file_name = 'vuln_{}_{}.txt'.format(subdomain.name, rand_name)
scan_history.vulnerability_scan = True
scan_history.save()
vulnerability_scan(
scan_history,
0,
yaml_configuration,
results_dir,
subdomain=subdomain,
file_name=file_name,
subscan=sub_scan
)
task_status = SUCCESS_TASK
except Exception as e:
logger.error(e)
task_status = FAILED_TASK
sub_scan.error_message = str(e)
finally:
sub_scan.stop_scan_date = timezone.now()
sub_scan.status = task_status
sub_scan.save()
@app.task
def initiate_scan(
domain_id,
scan_history_id,
scan_type,
engine_type,
imported_subdomains=None,
out_of_scope_subdomains=[]
):
'''
scan_type = 0 -> immediate scan, need not create scan object
scan_type = 1 -> scheduled scan
'''
engine_object = EngineType.objects.get(pk=engine_type)
domain = Domain.objects.get(pk=domain_id)
if scan_type == 1:
task = ScanHistory()
task.scan_status = -1
elif scan_type == 0:
task = ScanHistory.objects.get(pk=scan_history_id)
# save the last scan date for domain model
domain.last_scan_date = timezone.now()
domain.save()
# once the celery task starts, change the task status to Started
task.scan_type = engine_object
task.celery_id = initiate_scan.request.id
task.domain = domain
task.scan_status = 1
task.start_scan_date = timezone.now()
task.subdomain_discovery = True if engine_object.subdomain_discovery else False
task.dir_file_fuzz = True if engine_object.dir_file_fuzz else False
task.port_scan = True if engine_object.port_scan else False
task.fetch_url = True if engine_object.fetch_url else False
task.osint = True if engine_object.osint else False
task.screenshot = True if engine_object.screenshot else False
task.vulnerability_scan = True if engine_object.vulnerability_scan else False
task.save()
activity_id = create_scan_activity(task, "Scanning Started", 2)
results_dir = '/usr/src/scan_results/'
os.chdir(results_dir)
notification = Notification.objects.all()
if notification and notification[0].send_scan_status_notif:
send_notification('reNgine has initiated recon for target {} with engine type {}'.format(domain.name, engine_object.engine_name))
try:
current_scan_dir = domain.name + '_' + str(random.randint(100000000000, 999999999999))
os.mkdir(current_scan_dir)
task.results_dir = current_scan_dir
task.save()
except Exception as exception:
logger.error(exception)
scan_failed(task)
yaml_configuration = None
excluded_subdomains = ''
try:
yaml_configuration = yaml.load(
task.scan_type.yaml_configuration,
Loader=yaml.FullLoader)
except Exception as exception:
logger.error(exception)
# TODO: Put failed reason on db
'''
Add GF patterns name to db for dynamic URLs menu
'''
if engine_object.fetch_url and GF_PATTERNS in yaml_configuration[FETCH_URL]:
task.used_gf_patterns = ','.join(
pattern for pattern in yaml_configuration[FETCH_URL][GF_PATTERNS])
task.save()
results_dir = results_dir + current_scan_dir
# put all imported subdomains into txt file and also in Subdomain model
if imported_subdomains:
extract_imported_subdomain(
imported_subdomains, task, domain, results_dir)
if not yaml_configuration:
return
'''
a target in itself is a subdomain, some tool give subdomains as
www.yogeshojha.com but url and everything else resolves to yogeshojha.com
In that case, we would already need to store target itself as subdomain
'''
initial_subdomain_file = '/target_domain.txt' if task.subdomain_discovery else '/sorted_subdomain_collection.txt'
subdomain_file = open(results_dir + initial_subdomain_file, "w")
subdomain_file.write(domain.name + "\n")
subdomain_file.close()
if(task.subdomain_discovery):
activity_id = create_scan_activity(task, "Subdomain Scanning", 1)
try:
subdomain_scan(
task,
domain,
yaml_configuration,
results_dir,
activity_id,
out_of_scope_subdomains
)
except Exception as e:
logger.error(e)
update_last_activity(activity_id, 0, error_message=str(e))
else:
skip_subdomain_scan(task, domain, results_dir)
update_last_activity(activity_id, 2)
activity_id = create_scan_activity(task, "HTTP Crawler", 1)
http_crawler(
task,
domain,
yaml_configuration,
results_dir,
activity_id)
update_last_activity(activity_id, 2)
# start wafw00f
try:
activity_id = create_scan_activity(task, "Detecting WAF", 1)
check_waf(task, results_dir)
update_last_activity(activity_id, 2)
except Exception as e:
logger.error(e)
update_last_activity(activity_id, 0, error_message=str(e))
try:
if task.screenshot:
activity_id = create_scan_activity(
task, "Visual Recon - Screenshot", 1)
grab_screenshot(
task,
domain,
yaml_configuration,
current_scan_dir,
activity_id)
update_last_activity(activity_id, 2)
except Exception as e:
logger.error(e)
update_last_activity(activity_id, 0, error_message=str(e))
task.error_message = str(e)
task.save()
try:
if(task.port_scan):
activity_id = create_scan_activity(task, "Port Scanning", 1)
port_scanning(task, activity_id, yaml_configuration, results_dir, domain)
update_last_activity(activity_id, 2)
except Exception as e:
logger.error(e)
update_last_activity(activity_id, 0, error_message=str(e))
task.error_message = str(e)
task.save()
try:
if task.osint:
activity_id = create_scan_activity(task, "OSINT Running", 1)
perform_osint(task, domain, yaml_configuration, results_dir)
update_last_activity(activity_id, 2)
except Exception as e:
logger.error(e)
update_last_activity(activity_id, 0, error_message=str(e))
task.error_message = str(e)
task.save()
try:
if task.dir_file_fuzz:
activity_id = create_scan_activity(task, "Directory Search", 1)
directory_fuzz(
task,
activity_id,
yaml_configuration,
results_dir,
domain=domain,
)
update_last_activity(activity_id, 2)
except Exception as e:
logger.error(e)
update_last_activity(activity_id, 0, error_message=str(e))
task.error_message = str(e)
task.save()
try:
if task.fetch_url:
activity_id = create_scan_activity(task, "Fetching endpoints", 1)
fetch_endpoints(
task,
activity_id,
yaml_configuration,
results_dir,
domain=domain,
)
update_last_activity(activity_id, 2)
except Exception as e:
logger.error(e)
update_last_activity(activity_id, 0, error_message=str(e))
task.error_message = str(e)
task.save()
try:
if task.vulnerability_scan:
activity_id = create_scan_activity(task, "Vulnerability Scan", 1)
vulnerability_scan(
task,
activity_id,
yaml_configuration,
results_dir,
domain=domain,
)
update_last_activity(activity_id, 2)
except Exception as e:
logger.error(e)
update_last_activity(activity_id, 0, error_message=str(e))
task.error_message = str(e)
task.save()
activity_id = create_scan_activity(task, "Scan Completed", 2)
if notification and notification[0].send_scan_status_notif:
send_notification('*Scan Completed*\nreNgine has finished performing recon on target {}.'.format(domain.name))
'''
Once the scan is completed, save the status to successful
'''
if ScanActivity.objects.filter(scan_of=task).filter(status=0).all():
task.scan_status = 0
else:
task.scan_status = 2
task.stop_scan_date = timezone.now()
task.save()
# cleanup results
# delete_scan_data(results_dir)
return {"status": True}
def skip_subdomain_scan(task, domain, results_dir):
# store default target as subdomain
'''
If the imported subdomain already has target domain saved, we can skip this
'''
if not Subdomain.objects.filter(
scan_history=task,
name=domain.name).exists():
subdomain_dict = DottedDict({
'name': domain.name,
'scan_history': task,
'target_domain': domain
})
save_subdomain(subdomain_dict)
# Save target into target_domain.txt
with open('{}/target_domain.txt'.format(results_dir), 'w+') as file:
file.write(domain.name + '\n')
file.close()
'''
We can have two conditions, either subdomain scan happens, or subdomain scan
does not happen, in either cases, because we are using import subdomain, we
need to collect and sort all the subdomains
Write target domain into subdomain_collection
'''
os.system(
'cat {0}/target_domain.txt > {0}/subdomain_collection.txt'.format(results_dir))
os.system(
'cat {0}/from_imported.txt > {0}/subdomain_collection.txt'.format(results_dir))
os.system('rm -f {}/from_imported.txt'.format(results_dir))
'''
Sort all Subdomains
'''
os.system(
'sort -u {0}/subdomain_collection.txt -o {0}/sorted_subdomain_collection.txt'.format(results_dir))
os.system('rm -f {}/subdomain_collection.txt'.format(results_dir))
def extract_imported_subdomain(imported_subdomains, task, domain, results_dir):
valid_imported_subdomains = [subdomain for subdomain in imported_subdomains if validators.domain(
subdomain) and domain.name == get_domain_from_subdomain(subdomain)]
# remove any duplicate
valid_imported_subdomains = list(set(valid_imported_subdomains))
with open('{}/from_imported.txt'.format(results_dir), 'w+') as file:
for subdomain_name in valid_imported_subdomains:
# save _subdomain to Subdomain model db
if not Subdomain.objects.filter(
scan_history=task, name=subdomain_name).exists():
subdomain_dict = DottedDict({
'scan_history': task,
'target_domain': domain,
'name': subdomain_name,
'is_imported_subdomain': True
})
save_subdomain(subdomain_dict)
# save subdomain to file
file.write('{}\n'.format(subdomain_name))
file.close()
def subdomain_scan(
task,
domain,
yaml_configuration,
results_dir,
activity_id,
out_of_scope_subdomains=None,
subscan=None
):
# get all external subdomain enum tools
default_subdomain_tools = [tool.name.lower() for tool in InstalledExternalTool.objects.filter(is_default=True).filter(is_subdomain_gathering=True)]
custom_subdomain_tools = [tool.name.lower() for tool in InstalledExternalTool.objects.filter(is_default=False).filter(is_subdomain_gathering=True)]
notification = Notification.objects.all()
if notification and notification[0].send_scan_status_notif:
send_notification('Subdomain Gathering for target {} has been started'.format(domain.name))
subdomain_scan_results_file = results_dir + '/sorted_subdomain_collection.txt'
# check for all the tools and add them into string
# if tool selected is all then make string, no need for loop
if ALL in yaml_configuration[SUBDOMAIN_DISCOVERY][USES_TOOLS]:
tools = 'amass-active amass-passive assetfinder sublist3r subfinder oneforall'
# also put all custom subdomain tools
custom_tools = ' '.join(tool for tool in custom_subdomain_tools)
if custom_tools:
tools = tools + ' ' + custom_subdomain_tools
else:
tools = ' '.join(
str(tool).lower() for tool in yaml_configuration[SUBDOMAIN_DISCOVERY][USES_TOOLS])
logging.info(tools)
logging.info(default_subdomain_tools)
logging.info(custom_subdomain_tools)
# check for THREADS, by default 10
threads = 10
if THREADS in yaml_configuration[SUBDOMAIN_DISCOVERY]:
_threads = yaml_configuration[SUBDOMAIN_DISCOVERY][THREADS]
if _threads > 0:
threads = _threads
try:
for tool in tools.split(' '):
if tool in default_subdomain_tools:
if tool == 'amass-passive':
amass_command = 'amass enum -passive -d {} -o {}/from_amass.txt'.format(
domain.name, results_dir)
if USE_AMASS_CONFIG in yaml_configuration[SUBDOMAIN_DISCOVERY] and yaml_configuration[SUBDOMAIN_DISCOVERY][USE_AMASS_CONFIG]:
amass_command += ' -config /root/.config/amass.ini'
# Run Amass Passive
logging.info(amass_command)
process = subprocess.Popen(amass_command.split())
process.wait()
elif tool == 'amass-active':
amass_command = 'amass enum -active -d {} -o {}/from_amass_active.txt'.format(
domain.name, results_dir)
if USE_AMASS_CONFIG in yaml_configuration[SUBDOMAIN_DISCOVERY] and yaml_configuration[SUBDOMAIN_DISCOVERY][USE_AMASS_CONFIG]:
amass_command += ' -config /root/.config/amass.ini'
if AMASS_WORDLIST in yaml_configuration[SUBDOMAIN_DISCOVERY]:
wordlist = yaml_configuration[SUBDOMAIN_DISCOVERY][AMASS_WORDLIST]
if wordlist == 'default':
wordlist_path = '/usr/src/wordlist/deepmagic.com-prefixes-top50000.txt'
else:
wordlist_path = '/usr/src/wordlist/' + wordlist + '.txt'
if not os.path.exists(wordlist_path):
wordlist_path = '/usr/src/' + AMASS_WORDLIST
amass_command = amass_command + \
' -brute -w {}'.format(wordlist_path)
# Run Amass Active
logging.info(amass_command)
process = subprocess.Popen(amass_command.split())
process.wait()
elif tool == 'assetfinder':
assetfinder_command = 'assetfinder --subs-only {} > {}/from_assetfinder.txt'.format(
domain.name, results_dir)
# Run Assetfinder
logging.info(assetfinder_command)
process = subprocess.Popen(assetfinder_command.split())
process.wait()
elif tool == 'sublist3r':
sublist3r_command = 'python3 /usr/src/github/Sublist3r/sublist3r.py -d {} -t {} -o {}/from_sublister.txt'.format(
domain.name, threads, results_dir)
# Run sublist3r
logging.info(sublist3r_command)
process = subprocess.Popen(sublist3r_command.split())
process.wait()
elif tool == 'subfinder':
subfinder_command = 'subfinder -d {} -t {} -o {}/from_subfinder.txt'.format(
domain.name, threads, results_dir)
if USE_SUBFINDER_CONFIG in yaml_configuration[SUBDOMAIN_DISCOVERY] and yaml_configuration[SUBDOMAIN_DISCOVERY][USE_SUBFINDER_CONFIG]:
subfinder_command += ' -config /root/.config/subfinder/config.yaml'
# Run Subfinder
logging.info(subfinder_command)
process = subprocess.Popen(subfinder_command.split())
process.wait()
elif tool == 'oneforall':
oneforall_command = 'python3 /usr/src/github/OneForAll/oneforall.py --target {} run'.format(
domain.name, results_dir)
# Run OneForAll
logging.info(oneforall_command)
process = subprocess.Popen(oneforall_command.split())
process.wait()
extract_subdomain = "cut -d',' -f6 /usr/src/github/OneForAll/results/{}.csv >> {}/from_oneforall.txt".format(
domain.name, results_dir)
os.system(extract_subdomain)
# remove the results from oneforall directory
os.system(
'rm -rf /usr/src/github/OneForAll/results/{}.*'.format(domain.name))
elif tool.lower() in custom_subdomain_tools:
# this is for all the custom tools, and tools runs based on instalaltion steps provided
if InstalledExternalTool.objects.filter(name__icontains=tool.lower()).exists():
custom_tool = InstalledExternalTool.objects.get(name__icontains=tool)
execution_command = custom_tool.subdomain_gathering_command
print(execution_command)
# replace syntax with actual commands and path
if '{TARGET}' in execution_command and '{OUTPUT}' in execution_command:
execution_command = execution_command.replace('{TARGET}', domain.name)
execution_command = execution_command.replace('{OUTPUT}', '{}/from_{}.txt'.format(results_dir, tool))
execution_command = execution_command.replace('{PATH}', custom_tool.github_clone_path) if '{PATH}' in execution_command else execution_command
logger.info('Custom tool {} running with command {}'.format(tool, execution_command))
process = subprocess.Popen(execution_command.split())
process.wait()
else:
logger.error('Sorry can not run this tool! because TARGET and OUTPUT are not available!')
except Exception as e:
logger.error(e)
'''
All tools have gathered the list of subdomains with filename
initials as from_*
We will gather all the results in one single file, sort them and
remove the older results from_*
'''
os.system(
'cat {0}/*.txt > {0}/subdomain_collection.txt'.format(results_dir))
'''
Write target domain into subdomain_collection
'''
os.system(
'cat {0}/target_domain.txt >> {0}/subdomain_collection.txt'.format(results_dir))
'''
Remove all the from_* files
'''
os.system('rm -f {}/from*'.format(results_dir))
'''
Sort all Subdomains
'''
os.system(
'sort -u {0}/subdomain_collection.txt -o {0}/sorted_subdomain_collection.txt'.format(results_dir))
os.system('rm -f {}/subdomain_collection.txt'.format(results_dir))
'''
The final results will be stored in sorted_subdomain_collection.
'''
# parse the subdomain list file and store in db
with open(subdomain_scan_results_file) as subdomain_list:
for _subdomain in subdomain_list:
__subdomain = _subdomain.rstrip('\n')
if not Subdomain.objects.filter(scan_history=task, name=__subdomain).exists(
) and validators.domain(__subdomain) and __subdomain not in out_of_scope_subdomains:
subdomain_dict = DottedDict({
'scan_history': task,
'target_domain': domain,
'name': __subdomain,
})
save_subdomain(subdomain_dict)
notification = Notification.objects.all()
if notification and notification[0].send_scan_status_notif:
subdomains_count = Subdomain.objects.filter(scan_history=task).count()
send_notification('Subdomain Gathering for target {} has been completed and has discovered *{}* subdomains.'.format(domain.name, subdomains_count))
if notification and notification[0].send_scan_output_file:
send_files_to_discord(results_dir + '/sorted_subdomain_collection.txt')
# check for any subdomain changes and send notif if any
if notification and notification[0].send_subdomain_changes_notif:
newly_added_subdomain = get_new_added_subdomain(task.id, domain.id)
if newly_added_subdomain:
message = "**{} New Subdomains Discovered on domain {}**".format(newly_added_subdomain.count(), domain.name)
for subdomain in newly_added_subdomain:
message += "\n• {}".format(subdomain.name)
send_notification(message)
removed_subdomain = get_removed_subdomain(task.id, domain.id)
if removed_subdomain:
message = "**{} Subdomains are no longer available on domain {}**".format(removed_subdomain.count(), domain.name)
for subdomain in removed_subdomain:
message += "\n• {}".format(subdomain.name)
send_notification(message)
# check for interesting subdomains and send notif if any
if notification and notification[0].send_interesting_notif:
interesting_subdomain = get_interesting_subdomains(task.id, domain.id)
print(interesting_subdomain)
if interesting_subdomain:
message = "**{} Interesting Subdomains Found on domain {}**".format(interesting_subdomain.count(), domain.name)
for subdomain in interesting_subdomain:
message += "\n• {}".format(subdomain.name)
send_notification(message)
def get_new_added_subdomain(scan_id, domain_id):
scan_history = ScanHistory.objects.filter(
domain=domain_id).filter(
subdomain_discovery=True).filter(
id__lte=scan_id)
if scan_history.count() > 1:
last_scan = scan_history.order_by('-start_scan_date')[1]
scanned_host_q1 = Subdomain.objects.filter(
scan_history__id=scan_id).values('name')
scanned_host_q2 = Subdomain.objects.filter(
scan_history__id=last_scan.id).values('name')
added_subdomain = scanned_host_q1.difference(scanned_host_q2)
return Subdomain.objects.filter(
scan_history=scan_id).filter(
name__in=added_subdomain)
def get_removed_subdomain(scan_id, domain_id):
scan_history = ScanHistory.objects.filter(
domain=domain_id).filter(
subdomain_discovery=True).filter(
id__lte=scan_id)
if scan_history.count() > 1:
last_scan = scan_history.order_by('-start_scan_date')[1]
scanned_host_q1 = Subdomain.objects.filter(
scan_history__id=scan_id).values('name')
scanned_host_q2 = Subdomain.objects.filter(
scan_history__id=last_scan.id).values('name')
removed_subdomains = scanned_host_q2.difference(scanned_host_q1)
return Subdomain.objects.filter(
scan_history=last_scan).filter(
name__in=removed_subdomains)
def http_crawler(task, domain, yaml_configuration, results_dir, activity_id):
'''
This function is runs right after subdomain gathering, and gathers important
like page title, http status, etc
HTTP Crawler runs by default
'''
notification = Notification.objects.all()
if notification and notification[0].send_scan_status_notif:
send_notification('HTTP Crawler for target {} has been initiated.'.format(domain.name))
alive_file_location = results_dir + '/alive.txt'
httpx_results_file = results_dir + '/httpx.json'
subdomain_scan_results_file = results_dir + '/sorted_subdomain_collection.txt'
httpx_command = 'httpx -status-code -content-length -title -tech-detect -cdn -ip -follow-host-redirects -random-agent'
proxy = get_random_proxy()
if proxy:
httpx_command += " --http-proxy {} ".format(proxy)
if CUSTOM_HEADER in yaml_configuration and yaml_configuration[CUSTOM_HEADER]:
httpx_command += ' -H "{}" '.format(yaml_configuration[CUSTOM_HEADER])
httpx_command += ' -json -o {} -l {}'.format(
httpx_results_file,
subdomain_scan_results_file
)
logger.info(httpx_command)
process = subprocess.Popen(httpx_command.split())
process.wait()
# alive subdomains from httpx
alive_file = open(alive_file_location, 'w')
# writing httpx results
if os.path.isfile(httpx_results_file):
httpx_json_result = open(httpx_results_file, 'r')
lines = httpx_json_result.readlines()
for line in lines:
json_st = json.loads(line.strip())
try:
# fallback for older versions of httpx
if 'url' in json_st:
subdomain = Subdomain.objects.get(
scan_history=task, name=json_st['input'])
else:
subdomain = Subdomain.objects.get(
scan_history=task, name=json_st['url'].split("//")[-1])
'''
Saving Default http urls to EndPoint
'''
endpoint = EndPoint()
endpoint.scan_history = task
endpoint.target_domain = domain
endpoint.subdomain = subdomain
if 'url' in json_st:
endpoint.http_url = json_st['url']
subdomain.http_url = json_st['url']
if 'status-code' in json_st:
endpoint.http_status = json_st['status-code']
subdomain.http_status = json_st['status-code']
if 'title' in json_st:
endpoint.page_title = json_st['title']
subdomain.page_title = json_st['title']
if 'content-length' in json_st:
endpoint.content_length = json_st['content-length']
subdomain.content_length = json_st['content-length']
if 'content-type' in json_st:
endpoint.content_type = json_st['content-type']
subdomain.content_type = json_st['content-type']
if 'webserver' in json_st:
endpoint.webserver = json_st['webserver']
subdomain.webserver = json_st['webserver']
if 'response-time' in json_st:
response_time = float(
''.join(
ch for ch in json_st['response-time'] if not ch.isalpha()))
if json_st['response-time'][-2:] == 'ms':
response_time = response_time / 1000
endpoint.response_time = response_time
subdomain.response_time = response_time
if 'cnames' in json_st:
cname_list = ','.join(json_st['cnames'])
subdomain.cname = cname_list
discovered_date = timezone.now()
endpoint.discovered_date = discovered_date
subdomain.discovered_date = discovered_date
endpoint.is_default = True
endpoint.save()
subdomain.save()
if 'technologies' in json_st:
for _tech in json_st['technologies']:
if Technology.objects.filter(name=_tech).exists():
tech = Technology.objects.get(name=_tech)
else:
tech = Technology(name=_tech)
tech.save()
subdomain.technologies.add(tech)
endpoint.technologies.add(tech)
if 'a' in json_st:
for _ip in json_st['a']:
if IpAddress.objects.filter(address=_ip).exists():
ip = IpAddress.objects.get(address=_ip)
else:
ip = IpAddress(address=_ip)
if 'cdn' in json_st:
ip.is_cdn = json_st['cdn']
ip.save()
subdomain.ip_addresses.add(ip)
# see if to ignore 404 or 5xx
alive_file.write(json_st['url'] + '\n')
subdomain.save()
endpoint.save()
except Exception as exception:
logging.error(exception)
alive_file.close()
if notification and notification[0].send_scan_status_notif:
alive_count = Subdomain.objects.filter(
scan_history__id=task.id).values('name').distinct().filter(
http_status__exact=200).count()
send_notification('HTTP Crawler for target {} has been completed.\n\n {} subdomains were alive (http status 200).'.format(domain.name, alive_count))
def grab_screenshot(task, domain, yaml_configuration, results_dir, activity_id):
'''
This function is responsible for taking screenshots
'''
notification = Notification.objects.all()
if notification and notification[0].send_scan_status_notif:
send_notification('reNgine is currently gathering screenshots for {}'.format(domain.name))
output_screenshots_path = results_dir + '/screenshots'
result_csv_path = results_dir + '/screenshots/Requests.csv'
alive_subdomains_path = results_dir + '/alive.txt'
eyewitness_command = 'python3 /usr/src/github/EyeWitness/Python/EyeWitness.py'
eyewitness_command += ' -f {} -d {} --no-prompt '.format(
alive_subdomains_path,
output_screenshots_path
)
if SCREENSHOT in yaml_configuration \
and TIMEOUT in yaml_configuration[SCREENSHOT] \
and yaml_configuration[SCREENSHOT][TIMEOUT] > 0:
eyewitness_command += ' --timeout {} '.format(
yaml_configuration[SCREENSHOT][TIMEOUT]
)
if SCREENSHOT in yaml_configuration \
and THREADS in yaml_configuration[SCREENSHOT] \
and yaml_configuration[SCREENSHOT][THREADS] > 0:
eyewitness_command += ' --threads {} '.format(
yaml_configuration[SCREENSHOT][THREADS]
)
logger.info(eyewitness_command)
process = subprocess.Popen(eyewitness_command.split())
process.wait()
if os.path.isfile(result_csv_path):
logger.info('Gathering Eyewitness results')
with open(result_csv_path, 'r') as file:
reader = csv.reader(file)
for row in reader:
if row[3] == 'Successful' \
and Subdomain.objects.filter(
scan_history__id=task.id).filter(name=row[2]).exists():
subdomain = Subdomain.objects.get(
scan_history__id=task.id,
name=row[2]
)
subdomain.screenshot_path = row[4].replace(
'/usr/src/scan_results/',
''
)
subdomain.save()
# remove all db, html extra files in screenshot results
os.system('rm -rf {0}/*.csv {0}/*.db {0}/*.js {0}/*.html {0}/*.css'.format(
output_screenshots_path,
))
os.system('rm -rf {0}/source'.format(
output_screenshots_path,
))
if notification and notification[0].send_scan_status_notif:
send_notification('reNgine has finished gathering screenshots for {}'.format(domain.name))
def port_scanning(
scan_history,
activity_id,
yaml_configuration,
results_dir,
domain=None,
subdomain=None,
file_name=None,
subscan=None
):
'''
This function is responsible for running the port scan
'''
output_file_name = file_name if file_name else 'ports.json'
port_results_file = results_dir + '/' + output_file_name
domain_name = domain.name if domain else subdomain
notification = Notification.objects.all()
if notification and notification[0].send_scan_status_notif:
send_notification('Port Scan initiated for {}'.format(domain_name))
if domain:
subdomain_scan_results_file = results_dir + '/sorted_subdomain_collection.txt'
naabu_command = 'cat {} | naabu -json -o {}'.format(
subdomain_scan_results_file,
port_results_file
)
elif subdomain:
naabu_command = 'naabu -host {} -o {} -json '.format(
subdomain,
port_results_file
)
# check the yaml_configuration and choose the ports to be scanned
scan_ports = '-' # default port scan everything
if PORTS in yaml_configuration[PORT_SCAN]:
# TODO: legacy code, remove top-100 in future versions
all_ports = yaml_configuration[PORT_SCAN][PORTS]
if 'full' in all_ports:
naabu_command += ' -p -'
elif 'top-100' in all_ports:
naabu_command += ' -top-ports 100 '
elif 'top-1000' in all_ports:
naabu_command += ' -top-ports 1000 '
else:
scan_ports = ','.join(
str(port) for port in all_ports)
naabu_command += ' -p {} '.format(scan_ports)