-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
tasks.py
4692 lines (4086 loc) · 141 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 csv
import json
import os
import pprint
import subprocess
import time
import validators
import whatportis
import xmltodict
import yaml
import tldextract
import concurrent.futures
from datetime import datetime
from urllib.parse import urlparse
from api.serializers import SubdomainSerializer
from celery import chain, chord, group
from celery.result import allow_join_result
from celery.utils.log import get_task_logger
from django.db.models import Count
from dotted_dict import DottedDict
from django.utils import timezone
from pycvesearch import CVESearch
from metafinder.extractor import extract_metadata_from_google_search
from reNgine.celery import app
from reNgine.gpt import GPTVulnerabilityReportGenerator
from reNgine.celery_custom_task import RengineTask
from reNgine.common_func import *
from reNgine.definitions import *
from reNgine.settings import *
from reNgine.gpt import *
from scanEngine.models import (EngineType, InstalledExternalTool, Notification, Proxy)
from startScan.models import *
from startScan.models import EndPoint, Subdomain, Vulnerability
from targetApp.models import Domain
"""
Celery tasks.
"""
logger = get_task_logger(__name__)
#----------------------#
# Scan / Subscan tasks #
#----------------------#
@app.task(name='initiate_scan', bind=False, queue='initiate_scan_queue')
def initiate_scan(
scan_history_id,
domain_id,
engine_id=None,
scan_type=LIVE_SCAN,
results_dir=RENGINE_RESULTS,
imported_subdomains=[],
out_of_scope_subdomains=[],
url_filter=''):
"""Initiate a new scan.
Args:
scan_history_id (int): ScanHistory id.
domain_id (int): Domain id.
engine_id (int): Engine ID.
scan_type (int): Scan type (periodic, live).
results_dir (str): Results directory.
imported_subdomains (list): Imported subdomains.
out_of_scope_subdomains (list): Out-of-scope subdomains.
url_filter (str): URL path. Default: ''
"""
# Get scan history
scan = ScanHistory.objects.get(pk=scan_history_id)
# Get scan engine
engine_id = engine_id or scan.scan_type.id # scan history engine_id
engine = EngineType.objects.get(pk=engine_id)
# Get YAML config
config = yaml.safe_load(engine.yaml_configuration)
enable_http_crawl = config.get(ENABLE_HTTP_CRAWL, DEFAULT_ENABLE_HTTP_CRAWL)
gf_patterns = config.get(GF_PATTERNS, [])
# Get domain and set last_scan_date
domain = Domain.objects.get(pk=domain_id)
domain.last_scan_date = timezone.now()
domain.save()
# Get path filter
url_filter = url_filter.rstrip('/')
# Get or create ScanHistory() object
if scan_type == LIVE_SCAN: # immediate
scan = ScanHistory.objects.get(pk=scan_history_id)
scan.scan_status = RUNNING_TASK
elif scan_type == SCHEDULED_SCAN: # scheduled
scan = ScanHistory()
scan.scan_status = INITIATED_TASK
scan.scan_type = engine
scan.celery_ids = [initiate_scan.request.id]
scan.domain = domain
scan.start_scan_date = timezone.now()
scan.tasks = engine.tasks
scan.results_dir = f'{results_dir}/{domain.name}_{scan.id}'
add_gf_patterns = gf_patterns and 'fetch_url' in engine.tasks
if add_gf_patterns:
scan.used_gf_patterns = ','.join(gf_patterns)
scan.save()
# Create scan results dir
os.makedirs(scan.results_dir)
# Build task context
ctx = {
'scan_history_id': scan_history_id,
'engine_id': engine_id,
'domain_id': domain.id,
'results_dir': scan.results_dir,
'url_filter': url_filter,
'yaml_configuration': config,
'out_of_scope_subdomains': out_of_scope_subdomains
}
ctx_str = json.dumps(ctx, indent=2)
# Send start notif
logger.warning(f'Starting scan {scan_history_id} with context:\n{ctx_str}')
send_scan_notif.delay(
scan_history_id,
subscan_id=None,
engine_id=engine_id,
status=CELERY_TASK_STATUS_MAP[scan.scan_status])
# Save imported subdomains in DB
save_imported_subdomains(imported_subdomains, ctx=ctx)
# Create initial subdomain in DB: make a copy of domain as a subdomain so
# that other tasks using subdomains can use it.
subdomain_name = domain.name
subdomain, _ = save_subdomain(subdomain_name, ctx=ctx)
# If enable_http_crawl is set, create an initial root HTTP endpoint so that
# HTTP crawling can start somewhere
http_url = f'{domain.name}{url_filter}' if url_filter else domain.name
endpoint, _ = save_endpoint(
http_url,
ctx=ctx,
crawl=enable_http_crawl,
is_default=True,
subdomain=subdomain
)
if endpoint and endpoint.is_alive:
# TODO: add `root_endpoint` property to subdomain and simply do
# subdomain.root_endpoint = endpoint instead
logger.warning(f'Found subdomain root HTTP URL {endpoint.http_url}')
subdomain.http_url = endpoint.http_url
subdomain.http_status = endpoint.http_status
subdomain.response_time = endpoint.response_time
subdomain.page_title = endpoint.page_title
subdomain.content_type = endpoint.content_type
subdomain.content_length = endpoint.content_length
for tech in endpoint.techs.all():
subdomain.technologies.add(tech)
subdomain.save()
# Build Celery tasks, crafted according to the dependency graph below:
# subdomain_discovery --> port_scan --> fetch_url --> dir_file_fuzz
# osint vulnerability_scan
# osint dalfox xss scan
# screenshot
# waf_detection
workflow = chain(
group(
subdomain_discovery.si(ctx=ctx, description='Subdomain discovery'),
osint.si(ctx=ctx, description='OS Intelligence')
),
port_scan.si(ctx=ctx, description='Port scan'),
fetch_url.si(ctx=ctx, description='Fetch URL'),
group(
dir_file_fuzz.si(ctx=ctx, description='Directories & files fuzz'),
vulnerability_scan.si(ctx=ctx, description='Vulnerability scan'),
screenshot.si(ctx=ctx, description='Screenshot'),
waf_detection.si(ctx=ctx, description='WAF detection')
)
)
# Build callback
callback = report.si(ctx=ctx).set(link_error=[report.si(ctx=ctx)])
# Run Celery chord
logger.info(f'Running Celery workflow with {len(workflow.tasks) + 1} tasks')
task = chain(workflow, callback).on_error(callback).delay()
scan.celery_ids.append(task.id)
scan.save()
return {
'success': True,
'task_id': task.id
}
@app.task(name='initiate_subscan', bind=False, queue='subscan_queue')
def initiate_subscan(
scan_history_id,
subdomain_id,
engine_id=None,
scan_type=None,
results_dir=RENGINE_RESULTS,
url_filter=''):
"""Initiate a new subscan.
Args:
scan_history_id (int): ScanHistory id.
subdomain_id (int): Subdomain id.
engine_id (int): Engine ID.
scan_type (int): Scan type (periodic, live).
results_dir (str): Results directory.
url_filter (str): URL path. Default: ''
"""
# Get Subdomain and ScanHistory
subdomain = Subdomain.objects.get(pk=subdomain_id)
scan = ScanHistory.objects.get(pk=subdomain.scan_history.id)
# Get EngineType
engine_id = engine_id or scan.scan_type.id
engine = EngineType.objects.get(pk=engine_id)
# Get YAML config
config = yaml.safe_load(engine.yaml_configuration)
enable_http_crawl = config.get(ENABLE_HTTP_CRAWL, DEFAULT_ENABLE_HTTP_CRAWL)
# Create scan activity of SubScan Model
subscan = SubScan(
start_scan_date=timezone.now(),
celery_ids=[initiate_subscan.request.id],
scan_history=scan,
subdomain=subdomain,
type=scan_type,
status=RUNNING_TASK,
engine=engine)
subscan.save()
# Get YAML configuration
config = yaml.safe_load(engine.yaml_configuration)
# Create results directory
results_dir = f'{scan.results_dir}/subscans/{subscan.id}'
os.makedirs(results_dir, exist_ok=True)
# Run task
method = globals().get(scan_type)
if not method:
logger.warning(f'Task {scan_type} is not supported by reNgine. Skipping')
return
scan.tasks.append(scan_type)
scan.save()
# Send start notif
send_scan_notif.delay(
scan.id,
subscan_id=subscan.id,
engine_id=engine_id,
status='RUNNING')
# Build context
ctx = {
'scan_history_id': scan.id,
'subscan_id': subscan.id,
'engine_id': engine_id,
'subdomain_id': subdomain.id,
'yaml_configuration': config,
'results_dir': results_dir,
'url_filter': url_filter
}
# Create initial endpoints in DB: find domain HTTP endpoint so that HTTP
# crawling can start somewhere
base_url = f'{subdomain.name}{url_filter}' if url_filter else subdomain.name
endpoint, _ = save_endpoint(
base_url,
crawl=enable_http_crawl,
ctx=ctx,
subdomain=subdomain)
if endpoint and endpoint.is_alive:
# TODO: add `root_endpoint` property to subdomain and simply do
# subdomain.root_endpoint = endpoint instead
logger.warning(f'Found subdomain root HTTP URL {endpoint.http_url}')
subdomain.http_url = endpoint.http_url
subdomain.http_status = endpoint.http_status
subdomain.response_time = endpoint.response_time
subdomain.page_title = endpoint.page_title
subdomain.content_type = endpoint.content_type
subdomain.content_length = endpoint.content_length
for tech in endpoint.techs.all():
subdomain.technologies.add(tech)
subdomain.save()
# Build header + callback
workflow = method.si(ctx=ctx)
callback = report.si(ctx=ctx).set(link_error=[report.si(ctx=ctx)])
# Run Celery tasks
task = chain(workflow, callback).on_error(callback).delay()
subscan.celery_ids.append(task.id)
subscan.save()
return {
'success': True,
'task_id': task.id
}
@app.task(name='report', bind=False, queue='report_queue')
def report(ctx={}, description=None):
"""Report task running after all other tasks.
Mark ScanHistory or SubScan object as completed and update with final
status, log run details and send notification.
Args:
description (str, optional): Task description shown in UI.
"""
# Get objects
subscan_id = ctx.get('subscan_id')
scan_id = ctx.get('scan_history_id')
engine_id = ctx.get('engine_id')
scan = ScanHistory.objects.filter(pk=scan_id).first()
subscan = SubScan.objects.filter(pk=subscan_id).first()
# Get failed tasks
tasks = ScanActivity.objects.filter(scan_of=scan).all()
if subscan:
tasks = tasks.filter(celery_id__in=subscan.celery_ids)
failed_tasks = tasks.filter(status=FAILED_TASK)
# Get task status
failed_count = failed_tasks.count()
status = SUCCESS_TASK if failed_count == 0 else FAILED_TASK
status_h = 'SUCCESS' if failed_count == 0 else 'FAILED'
# Update scan / subscan status
if subscan:
subscan.stop_scan_date = timezone.now()
subscan.status = status
subscan.save()
else:
scan.scan_status = status
scan.stop_scan_date = timezone.now()
scan.save()
# Send scan status notif
send_scan_notif.delay(
scan_history_id=scan_id,
subscan_id=subscan_id,
engine_id=engine_id,
status=status_h)
#------------------------- #
# Tracked reNgine tasks #
#--------------------------#
@app.task(name='subdomain_discovery', queue='main_scan_queue', base=RengineTask, bind=True)
def subdomain_discovery(
self,
host=None,
ctx=None,
description=None):
"""Uses a set of tools (see SUBDOMAIN_SCAN_DEFAULT_TOOLS) to scan all
subdomains associated with a domain.
Args:
host (str): Hostname to scan.
Returns:
subdomains (list): List of subdomain names.
"""
if not host:
host = self.subdomain.name if self.subdomain else self.domain.name
if self.url_filter:
logger.warning(f'Ignoring subdomains scan as an URL path filter was passed ({self.url_filter}).')
return
# Config
config = self.yaml_configuration.get(SUBDOMAIN_DISCOVERY) or {}
enable_http_crawl = config.get(ENABLE_HTTP_CRAWL) or self.yaml_configuration.get(ENABLE_HTTP_CRAWL, DEFAULT_ENABLE_HTTP_CRAWL)
threads = config.get(THREADS) or self.yaml_configuration.get(THREADS, DEFAULT_THREADS)
timeout = config.get(TIMEOUT) or self.yaml_configuration.get(TIMEOUT, DEFAULT_HTTP_TIMEOUT)
tools = config.get(USES_TOOLS, SUBDOMAIN_SCAN_DEFAULT_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)]
send_subdomain_changes, send_interesting = False, False
notif = Notification.objects.first()
if notif:
send_subdomain_changes = notif.send_subdomain_changes_notif
send_interesting = notif.send_interesting_notif
# Gather tools to run for subdomain scan
if ALL in tools:
tools = SUBDOMAIN_SCAN_DEFAULT_TOOLS + custom_subdomain_tools
tools = [t.lower() for t in tools]
# Make exception for amass since tool name is amass, but command is amass-active/passive
default_subdomain_tools.append('amass-passive')
default_subdomain_tools.append('amass-active')
# Run tools
for tool in tools:
cmd = None
logger.info(f'Scanning subdomains for {host} with {tool}')
proxy = get_random_proxy()
if tool in default_subdomain_tools:
if tool == 'amass-passive':
cmd = f'amass enum -passive -d {host} -o {self.results_dir}/subdomains_amass.txt'
cmd += ' -config /root/.config/amass.ini' if use_amass_config else ''
elif tool == 'amass-active':
use_amass_config = config.get(USE_AMASS_CONFIG, False)
amass_wordlist_name = config.get(AMASS_WORDLIST, 'deepmagic.com-prefixes-top50000')
wordlist_path = f'/usr/src/wordlist/{amass_wordlist_name}.txt'
cmd = f'amass enum -active -d {host} -o {self.results_dir}/subdomains_amass_active.txt'
cmd += ' -config /root/.config/amass.ini' if use_amass_config else ''
cmd += f' -brute -w {wordlist_path}'
elif tool == 'sublist3r':
cmd = f'python3 /usr/src/github/Sublist3r/sublist3r.py -d {host} -t {threads} -o {self.results_dir}/subdomains_sublister.txt'
elif tool == 'subfinder':
cmd = f'subfinder -d {host} -o {self.results_dir}/subdomains_subfinder.txt'
use_subfinder_config = config.get(USE_SUBFINDER_CONFIG, False)
cmd += ' -config /root/.config/subfinder/config.yaml' if use_subfinder_config else ''
cmd += f' -proxy {proxy}' if proxy else ''
cmd += f' -timeout {timeout}' if timeout else ''
cmd += f' -t {threads}' if threads else ''
cmd += f' -silent'
elif tool == 'oneforall':
cmd = f'python3 /usr/src/github/OneForAll/oneforall.py --target {host} run'
cmd_extract = f'cut -d\',\' -f6 /usr/src/github/OneForAll/results/{host}.csv > {self.results_dir}/subdomains_oneforall.txt'
cmd_rm = f'rm -rf /usr/src/github/OneForAll/results/{host}.csv'
cmd += f' && {cmd_extract} && {cmd_rm}'
elif tool == 'ctfr':
results_file = self.results_dir + '/subdomains_ctfr.txt'
cmd = f'python3 /usr/src/github/ctfr/ctfr.py -d {host} -o {results_file}'
cmd_extract = f"cat {results_file} | sed 's/\*.//g' | tail -n +12 | uniq | sort > {results_file}"
cmd += f' && {cmd_extract}'
elif tool == 'tlsx':
results_file = self.results_dir + '/subdomains_tlsx.txt'
cmd = f'tlsx -san -cn -silent -ro -host {host}'
cmd += f" | sed -n '/^\([a-zA-Z0-9]\([-a-zA-Z0-9]*[a-zA-Z0-9]\)\?\.\)\+{host}$/p' | uniq | sort"
cmd += f' > {results_file}'
elif tool == 'netlas':
results_file = self.results_dir + '/subdomains_netlas.txt'
cmd = f'netlas search -d domain -i domain domain:"*.{host}" -f json'
netlas_key = get_netlas_key()
cmd += f' -a {netlas_key}' if netlas_key else ''
cmd_extract = f"grep -oE '([a-zA-Z0-9]([-a-zA-Z0-9]*[a-zA-Z0-9])?\.)+{host}'"
cmd += f' | {cmd_extract} > {results_file}'
elif tool in custom_subdomain_tools:
tool_query = InstalledExternalTool.objects.filter(name__icontains=tool.lower())
if not tool_query.exists():
logger.error(f'Missing {{TARGET}} and {{OUTPUT}} placeholders in {tool} configuration. Skipping.')
continue
custom_tool = tool_query.first()
cmd = custom_tool.subdomain_gathering_command
if '{TARGET}' in cmd and '{OUTPUT}' in cmd:
cmd = cmd.replace('{TARGET}', host)
cmd = cmd.replace('{OUTPUT}', f'{self.results_dir}/subdomains_{tool}.txt')
cmd = cmd.replace('{PATH}', custom_tool.github_clone_path) if '{PATH}' in cmd else cmd
else:
logger.warning(
f'Subdomain discovery tool "{tool}" is not supported by reNgine. Skipping.')
continue
# Run tool
try:
run_command(
cmd,
shell=True,
history_file=self.history_file,
scan_id=self.scan_id,
activity_id=self.activity_id)
except Exception as e:
logger.error(
f'Subdomain discovery tool "{tool}" raised an exception')
logger.exception(e)
# Gather all the tools' results in one single file. Write subdomains into
# separate files, and sort all subdomains.
run_command(
f'cat {self.results_dir}/subdomains_*.txt > {self.output_path}',
shell=True,
history_file=self.history_file,
scan_id=self.scan_id,
activity_id=self.activity_id)
run_command(
f'sort -u {self.output_path} -o {self.output_path}',
shell=True,
history_file=self.history_file,
scan_id=self.scan_id,
activity_id=self.activity_id)
with open(self.output_path) as f:
lines = f.readlines()
# Parse the output_file file and store Subdomain and EndPoint objects found
# in db.
subdomain_count = 0
subdomains = []
urls = []
for line in lines:
subdomain_name = line.strip()
valid_url = bool(validators.url(subdomain_name))
valid_domain = (
bool(validators.domain(subdomain_name)) or
bool(validators.ipv4(subdomain_name)) or
bool(validators.ipv6(subdomain_name)) or
valid_url
)
if not valid_domain:
logger.error(f'Subdomain {subdomain_name} is not a valid domain, IP or URL. Skipping.')
continue
if valid_url:
subdomain_name = urlparse(subdomain_name).netloc
if subdomain_name in self.out_of_scope_subdomains:
logger.error(f'Subdomain {subdomain_name} is out of scope. Skipping.')
continue
# Add subdomain
subdomain, _ = save_subdomain(subdomain_name, ctx=ctx)
subdomain_count += 1
subdomains.append(subdomain)
urls.append(subdomain.name)
# Bulk crawl subdomains
if enable_http_crawl:
ctx['track'] = True
http_crawl(urls, ctx=ctx, is_ran_from_subdomain_scan=True)
# Find root subdomain endpoints
for subdomain in subdomains:
pass
# Send notifications
subdomains_str = '\n'.join([f'• `{subdomain.name}`' for subdomain in subdomains])
self.notify(fields={
'Subdomain count': len(subdomains),
'Subdomains': subdomains_str,
})
if send_subdomain_changes and self.scan_id and self.domain_id:
added = get_new_added_subdomain(self.scan_id, self.domain_id)
removed = get_removed_subdomain(self.scan_id, self.domain_id)
if added:
subdomains_str = '\n'.join([f'• `{subdomain}`' for subdomain in added])
self.notify(fields={'Added subdomains': subdomains_str})
if removed:
subdomains_str = '\n'.join([f'• `{subdomain}`' for subdomain in removed])
self.notify(fields={'Removed subdomains': subdomains_str})
if send_interesting and self.scan_id and self.domain_id:
interesting_subdomains = get_interesting_subdomains(self.scan_id, self.domain_id)
if interesting_subdomains:
subdomains_str = '\n'.join([f'• `{subdomain}`' for subdomain in interesting_subdomains])
self.notify(fields={'Interesting subdomains': subdomains_str})
return SubdomainSerializer(subdomains, many=True).data
@app.task(name='osint', queue='main_scan_queue', base=RengineTask, bind=True)
def osint(self, host=None, ctx={}, description=None):
"""Run Open-Source Intelligence tools on selected domain.
Args:
host (str): Hostname to scan.
Returns:
dict: Results from osint discovery and dorking.
"""
config = self.yaml_configuration.get(OSINT) or OSINT_DEFAULT_CONFIG
results = {}
grouped_tasks = []
if 'discover' in config:
ctx['track'] = False
# results = osint_discovery(host=host, ctx=ctx)
_task = osint_discovery.si(
config=config,
host=self.scan.domain.name,
scan_history_id=self.scan.id,
activity_id=self.activity_id,
results_dir=self.results_dir,
ctx=ctx
)
grouped_tasks.append(_task)
if OSINT_DORK in config or OSINT_CUSTOM_DORK in config:
_task = dorking.si(
config=config,
host=self.scan.domain.name,
scan_history_id=self.scan.id,
results_dir=self.results_dir
)
grouped_tasks.append(_task)
celery_group = group(grouped_tasks)
job = celery_group.apply_async()
while not job.ready():
# wait for all jobs to complete
time.sleep(5)
logger.info('OSINT Tasks finished...')
# with open(self.output_path, 'w') as f:
# json.dump(results, f, indent=4)
#
# return results
@app.task(name='osint_discovery', queue='osint_discovery_queue', bind=False)
def osint_discovery(config, host, scan_history_id, activity_id, results_dir, ctx={}):
"""Run OSINT discovery.
Args:
config (dict): yaml_configuration
host (str): target name
scan_history_id (startScan.ScanHistory): Scan History ID
results_dir (str): Path to store scan results
Returns:
dict: osint metadat and theHarvester and h8mail results.
"""
scan_history = ScanHistory.objects.get(pk=scan_history_id)
osint_lookup = config.get(OSINT_DISCOVER, [])
osint_intensity = config.get(INTENSITY, 'normal')
documents_limit = config.get(OSINT_DOCUMENTS_LIMIT, 50)
results = {}
meta_info = []
emails = []
creds = []
# Get and save meta info
if 'metainfo' in osint_lookup:
if osint_intensity == 'normal':
meta_dict = DottedDict({
'osint_target': host,
'domain': host,
'scan_id': scan_history_id,
'documents_limit': documents_limit
})
meta_info.append(save_metadata_info(meta_dict))
# TODO: disabled for now
# elif osint_intensity == 'deep':
# subdomains = Subdomain.objects
# if self.scan:
# subdomains = subdomains.filter(scan_history=self.scan)
# for subdomain in subdomains:
# meta_dict = DottedDict({
# 'osint_target': subdomain.name,
# 'domain': self.domain,
# 'scan_id': self.scan_id,
# 'documents_limit': documents_limit
# })
# meta_info.append(save_metadata_info(meta_dict))
grouped_tasks = []
if 'emails' in osint_lookup:
emails = get_and_save_emails(scan_history, activity_id, results_dir)
emails_str = '\n'.join([f'• `{email}`' for email in emails])
# self.notify(fields={'Emails': emails_str})
# ctx['track'] = False
_task = h8mail.si(
config=config,
host=host,
scan_history_id=scan_history_id,
activity_id=activity_id,
results_dir=results_dir,
ctx=ctx
)
grouped_tasks.append(_task)
if 'employees' in osint_lookup:
ctx['track'] = False
_task = theHarvester.si(
config=config,
host=host,
scan_history_id=scan_history_id,
activity_id=activity_id,
results_dir=results_dir,
ctx=ctx
)
grouped_tasks.append(_task)
celery_group = group(grouped_tasks)
job = celery_group.apply_async()
while not job.ready():
# wait for all jobs to complete
time.sleep(5)
# results['emails'] = results.get('emails', []) + emails
# results['creds'] = creds
# results['meta_info'] = meta_info
return results
@app.task(name='dorking', bind=False, queue='dorking_queue')
def dorking(config, host, scan_history_id, results_dir):
"""Run Google dorks.
Args:
config (dict): yaml_configuration
host (str): target name
scan_history_id (startScan.ScanHistory): Scan History ID
results_dir (str): Path to store scan results
Returns:
list: Dorking results for each dork ran.
"""
# Some dork sources: https://github.com/six2dez/degoogle_hunter/blob/master/degoogle_hunter.sh
scan_history = ScanHistory.objects.get(pk=scan_history_id)
dorks = config.get(OSINT_DORK, [])
custom_dorks = config.get(OSINT_CUSTOM_DORK, [])
results = []
# custom dorking has higher priority
try:
for custom_dork in custom_dorks:
lookup_target = custom_dork.get('lookup_site')
# replace with original host if _target_
lookup_target = host if lookup_target == '_target_' else lookup_target
if 'lookup_extensions' in custom_dork:
results = get_and_save_dork_results(
lookup_target=lookup_target,
results_dir=results_dir,
type='custom_dork',
lookup_extensions=custom_dork.get('lookup_extensions'),
scan_history=scan_history
)
elif 'lookup_keywords' in custom_dork:
results = get_and_save_dork_results(
lookup_target=lookup_target,
results_dir=results_dir,
type='custom_dork',
lookup_keywords=custom_dork.get('lookup_keywords'),
scan_history=scan_history
)
except Exception as e:
logger.exception(e)
# default dorking
try:
for dork in dorks:
logger.info(f'Getting dork information for {dork}')
if dork == 'stackoverflow':
results = get_and_save_dork_results(
lookup_target='stackoverflow.com',
results_dir=results_dir,
type=dork,
lookup_keywords=host,
scan_history=scan_history
)
elif dork == 'login_pages':
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_keywords='/login/,login.html',
page_count=5,
scan_history=scan_history
)
elif dork == 'admin_panels':
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_keywords='/admin/,admin.html',
page_count=5,
scan_history=scan_history
)
elif dork == 'dashboard_pages':
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_keywords='/dashboard/,dashboard.html',
page_count=5,
scan_history=scan_history
)
elif dork == 'social_media' :
social_websites = [
'tiktok.com',
'facebook.com',
'twitter.com',
'youtube.com',
'reddit.com'
]
for site in social_websites:
results = get_and_save_dork_results(
lookup_target=site,
results_dir=results_dir,
type=dork,
lookup_keywords=host,
scan_history=scan_history
)
elif dork == 'project_management' :
project_websites = [
'trello.com',
'atlassian.net'
]
for site in project_websites:
results = get_and_save_dork_results(
lookup_target=site,
results_dir=results_dir,
type=dork,
lookup_keywords=host,
scan_history=scan_history
)
elif dork == 'code_sharing' :
project_websites = [
'github.com',
'gitlab.com',
'bitbucket.org'
]
for site in project_websites:
results = get_and_save_dork_results(
lookup_target=site,
results_dir=results_dir,
type=dork,
lookup_keywords=host,
scan_history=scan_history
)
elif dork == 'config_files' :
config_file_exts = [
'env',
'xml',
'conf',
'toml',
'yml',
'yaml',
'cnf',
'inf',
'rdp',
'ora',
'txt',
'cfg',
'ini'
]
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_extensions=','.join(config_file_exts),
page_count=4,
scan_history=scan_history
)
elif dork == 'jenkins' :
lookup_keyword = 'Jenkins'
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_keywords=lookup_keyword,
page_count=1,
scan_history=scan_history
)
elif dork == 'wordpress_files' :
lookup_keywords = [
'/wp-content/',
'/wp-includes/'
]
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_keywords=','.join(lookup_keywords),
page_count=5,
scan_history=scan_history
)
elif dork == 'php_error' :
lookup_keywords = [
'PHP Parse error',
'PHP Warning',
'PHP Error'
]
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_keywords=','.join(lookup_keywords),
page_count=5,
scan_history=scan_history
)
elif dork == 'jenkins' :
lookup_keywords = [
'PHP Parse error',
'PHP Warning',
'PHP Error'
]
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_keywords=','.join(lookup_keywords),
page_count=5,
scan_history=scan_history
)
elif dork == 'exposed_documents' :
docs_file_ext = [
'doc',
'docx',
'odt',
'pdf',
'rtf',
'sxw',
'psw',
'ppt',
'pptx',
'pps',
'csv'
]
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_extensions=','.join(docs_file_ext),
page_count=7,
scan_history=scan_history
)
elif dork == 'db_files' :
file_ext = [
'sql',
'db',
'dbf',
'mdb'
]
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_extensions=','.join(file_ext),
page_count=1,
scan_history=scan_history
)
elif dork == 'git_exposed' :
file_ext = [
'git',
]
results = get_and_save_dork_results(
lookup_target=host,
results_dir=results_dir,
type=dork,
lookup_extensions=','.join(file_ext),
page_count=1,
scan_history=scan_history
)
except Exception as e:
logger.exception(e)
return results
@app.task(name='theHarvester', queue='theHarvester_queue', bind=False)
def theHarvester(config, host, scan_history_id, activity_id, results_dir, ctx={}):
"""Run theHarvester to get save emails, hosts, employees found in domain.
Args:
config (dict): yaml_configuration
host (str): target name
scan_history_id (startScan.ScanHistory): Scan History ID
activity_id: ScanActivity ID
results_dir (str): Path to store scan results
ctx (dict): context of scan
Returns:
dict: Dict of emails, employees, hosts and ips found during crawling.