-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.py
More file actions
1117 lines (923 loc) · 43.4 KB
/
scanner.py
File metadata and controls
1117 lines (923 loc) · 43.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Advanced Scanner Module v2.0
Enhanced with Intelligent Fingerprinting, WAF Detection, and Fast Socket Scanning
"""
import asyncio
import aiohttp
import socket
import ssl
import json
import time
import re
import random
import ipaddress
import struct
from concurrent.futures import ThreadPoolExecutor
from config import *
from utils import get_headers, save_finding, clean, get_session, get_random_ua
class IntelligentScanner:
"""Intelligent scanner with advanced fingerprinting"""
def __init__(self, proxy_manager=None):
self.proxy_manager = proxy_manager
self.port_services = self._load_service_db()
self.waf_signatures = self._load_waf_signatures()
self.service_fingerprints = self._load_service_fingerprints()
def _load_service_db(self):
"""Load service database"""
return {
21: {"name": "FTP", "banner_keywords": ["FTP", "vsftpd", "ProFTPD"]},
22: {"name": "SSH", "banner_keywords": ["SSH", "OpenSSH"]},
23: {"name": "Telnet", "banner_keywords": ["Telnet"]},
25: {"name": "SMTP", "banner_keywords": ["SMTP", "ESMTP", "Postfix"]},
53: {"name": "DNS", "banner_keywords": []},
80: {"name": "HTTP", "banner_keywords": ["Apache", "nginx", "IIS", "lighttpd"]},
110: {"name": "POP3", "banner_keywords": ["POP3", "Dovecot"]},
143: {"name": "IMAP", "banner_keywords": ["IMAP", "Dovecot"]},
443: {"name": "HTTPS", "banner_keywords": ["Apache", "nginx", "IIS"]},
445: {"name": "SMB", "banner_keywords": ["SMB", "SAMBA"]},
3306: {"name": "MySQL", "banner_keywords": ["MySQL"]},
3389: {"name": "RDP", "banner_keywords": ["RDP", "Terminal Server"]},
5432: {"name": "PostgreSQL", "banner_keywords": ["PostgreSQL"]},
5900: {"name": "VNC", "banner_keywords": ["RFB", "VNC"]},
6379: {"name": "Redis", "banner_keywords": ["Redis"]},
8080: {"name": "HTTP-Proxy", "banner_keywords": ["Apache", "nginx", "Tomcat"]},
8443: {"name": "HTTPS-Alt", "banner_keywords": ["Apache", "nginx"]},
9000: {"name": "PHP-FPM", "banner_keywords": ["PHP"]},
9200: {"name": "Elasticsearch", "banner_keywords": ["elasticsearch"]},
27017: {"name": "MongoDB", "banner_keywords": ["MongoDB"]},
}
def _load_waf_signatures(self):
"""Load WAF detection signatures"""
return {
"Cloudflare": {
"headers": ["cf-ray", "cf-cache-status", "cf-request-id"],
"cookies": ["__cfduid", "__cflb"],
"html_patterns": ["cloudflare", "Ray ID"],
"response_codes": [403, 503]
},
"Akamai": {
"headers": ["x-akamai-transformed", "x-akamai-request-id"],
"cookies": ["ak_bmsc"],
"html_patterns": ["Akamai", "Error 403 Access Denied"],
"response_codes": [403]
},
"Imperva": {
"headers": ["x-cdn", "incap_ses_", "visid_incap_"],
"cookies": ["incap_ses_", "visid_incap_"],
"html_patterns": ["imperva", "Request unsuccessful"],
"response_codes": [403, 406]
},
"AWS WAF": {
"headers": ["x-amz-id-1", "x-amz-id-2"],
"cookies": ["aws-waf-token"],
"html_patterns": ["Request blocked"],
"response_codes": [403]
},
"Sucuri": {
"headers": ["x-sucuri-id", "x-sucuri-cache"],
"cookies": ["sucuri_cloudproxy_uuid_"],
"html_patterns": ["Sucuri", "Access Denied"],
"response_codes": [403]
},
"ModSecurity": {
"headers": [],
"cookies": [],
"html_patterns": ["Mod_Security", "This error was generated by Mod_Security"],
"response_codes": [403]
}
}
def _load_service_fingerprints(self):
"""Load service fingerprints for banner grabbing"""
return {
"HTTP": {
"probes": [
b"GET / HTTP/1.0\r\n\r\n",
b"HEAD / HTTP/1.0\r\n\r\n",
b"GET /robots.txt HTTP/1.0\r\n\r\n"
],
"patterns": {
"Apache": [r"Apache", r"Server:\s*Apache"],
"nginx": [r"nginx", r"Server:\s*nginx"],
"IIS": [r"Microsoft-IIS", r"Server:\s*Microsoft-IIS"],
"Tomcat": [r"Apache-Coyote", r"Server:\s*Apache-Coyote"],
"lighttpd": [r"lighttpd", r"Server:\s*lighttpd"]
}
},
"SSH": {
"probes": [b"\n"],
"patterns": {
"OpenSSH": [r"OpenSSH"],
"Dropbear": [r"dropbear"],
"Cisco": [r"Cisco"]
}
},
"SMTP": {
"probes": [b"EHLO test\r\n"],
"patterns": {
"Postfix": [r"Postfix"],
"Exim": [r"Exim"],
"Sendmail": [r"Sendmail"],
"Microsoft Exchange": [r"Microsoft ESMTP"]
}
},
"FTP": {
"probes": [b"\n"],
"patterns": {
"vsftpd": [r"vsFTPd"],
"ProFTPD": [r"ProFTPD"],
"Pure-FTPd": [r"Pure-FTPd"]
}
}
}
def scan_port_socket(self, target, port, timeout=1.0):
"""Fast socket-based port scanning"""
result = {
"port": port,
"open": False,
"service": "unknown",
"banner": "",
"version": "",
"response_time": 0
}
try:
start_time = time.time()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
# Set socket options for faster scanning
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
response = sock.connect_ex((target, port))
elapsed = (time.time() - start_time) * 1000 # Convert to ms
if response == 0:
result["open"] = True
result["response_time"] = round(elapsed, 2)
# Try to grab banner
try:
sock.settimeout(0.5)
banner = sock.recv(1024)
if banner:
result["banner"] = banner.decode('utf-8', errors='ignore').strip()
# Fingerprint service
service_info = self._fingerprint_service(port, result["banner"])
result["service"] = service_info["name"]
result["version"] = service_info["version"]
except:
pass
sock.close()
except socket.timeout:
pass
except Exception as e:
pass
return result
def _fingerprint_service(self, port, banner):
"""Intelligent service fingerprinting"""
result = {"name": "unknown", "version": ""}
if not banner:
# Default service name from port
if port in self.port_services:
result["name"] = self.port_services[port]["name"]
return result
banner_lower = banner.lower()
# HTTP services
if port in [80, 443, 8080, 8443]:
for server, patterns in self.service_fingerprints.get("HTTP", {}).get("patterns", {}).items():
for pattern in patterns:
if re.search(pattern, banner, re.IGNORECASE):
result["name"] = f"HTTP ({server})"
# Try to extract version
version_match = re.search(r'(\d+\.\d+(\.\d+)?)', banner)
if version_match:
result["version"] = version_match.group(1)
break
# SSH fingerprinting
elif port == 22:
for server, patterns in self.service_fingerprints.get("SSH", {}).get("patterns", {}).items():
for pattern in patterns:
if re.search(pattern, banner, re.IGNORECASE):
result["name"] = f"SSH ({server})"
version_match = re.search(r'(\d+\.\d+(\.\d+)?)', banner)
if version_match:
result["version"] = version_match.group(1)
break
# SMTP fingerprinting
elif port == 25:
for server, patterns in self.service_fingerprints.get("SMTP", {}).get("patterns", {}).items():
for pattern in patterns:
if re.search(pattern, banner, re.IGNORECASE):
result["name"] = f"SMTP ({server})"
break
# FTP fingerprinting
elif port == 21:
for server, patterns in self.service_fingerprints.get("FTP", {}).get("patterns", {}).items():
for pattern in patterns:
if re.search(pattern, banner, re.IGNORECASE):
result["name"] = f"FTP ({server})"
break
# Database services
elif "mysql" in banner_lower:
result["name"] = "MySQL"
version_match = re.search(r'(\d+\.\d+\.\d+)', banner)
if version_match:
result["version"] = version_match.group(1)
elif "postgresql" in banner_lower:
result["name"] = "PostgreSQL"
elif "redis" in banner_lower:
result["name"] = "Redis"
version_match = re.search(r'v=(\d+\.\d+\.\d+)', banner)
if version_match:
result["version"] = version_match.group(1)
elif "mongodb" in banner_lower:
result["name"] = "MongoDB"
# Custom service detection based on keywords
for service_keywords in ["apache", "nginx", "iis", "tomcat", "node", "python"]:
if service_keywords in banner_lower:
result["name"] = service_keywords.capitalize()
break
return result
async def detect_waf_async(self, target_url):
"""Asynchronous WAF detection"""
waf_results = []
try:
connector = aiohttp.TCPConnector(ssl=False)
headers = {
'User-Agent': get_random_ua(),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
}
# Test with malicious payload to trigger WAF
test_payloads = [
"/../../../etc/passwd",
"<script>alert(1)</script>",
"' OR '1'='1",
"| cat /etc/passwd",
"../../../windows/win.ini"
]
async with aiohttp.ClientSession(headers=headers, connector=connector) as session:
# First, get normal response
try:
async with session.get(target_url, timeout=10) as normal_resp:
normal_html = await normal_resp.text()
normal_headers = dict(normal_resp.headers)
normal_status = normal_resp.status
except:
normal_html = ""
normal_headers = {}
normal_status = 0
# Test with malicious payloads
for payload in test_payloads[:2]: # Limit to 2 for speed
test_url = f"{target_url.rstrip('/')}/{payload}"
try:
async with session.get(test_url, timeout=8) as resp:
resp_status = resp.status
resp_headers = dict(resp.headers)
resp_html = await resp.text()
# Check WAF signatures
for waf_name, signatures in self.waf_signatures.items():
detected = False
# Check headers
for header in signatures.get("headers", []):
if header.lower() in (h.lower() for h in resp_headers.keys()):
detected = True
break
# Check cookies
if not detected and "set-cookie" in resp_headers:
cookies = resp_headers["set-cookie"].lower()
for cookie in signatures.get("cookies", []):
if cookie.lower() in cookies:
detected = True
break
# Check HTML patterns
if not detected:
for pattern in signatures.get("html_patterns", []):
if pattern.lower() in resp_html.lower():
detected = True
break
# Check response codes
if not detected and resp_status in signatures.get("response_codes", []):
if resp_status != normal_status: # Different from normal response
detected = True
if detected:
waf_results.append({
"waf": waf_name,
"confidence": "high",
"indicators": [
f"Response code: {resp_status}",
f"Headers match: {list(signatures['headers'])[:2] if signatures['headers'] else 'N/A'}"
]
})
except:
continue
except Exception as e:
pass
return waf_results
def fast_port_scan(self, target, ports=None, max_workers=100):
"""Fast multi-threaded port scanning"""
if ports is None:
ports = [21, 22, 23, 25, 53, 80, 110, 143, 443, 445, 993, 995,
1433, 1521, 1723, 3306, 3389, 5432, 5900, 6379, 8080,
8443, 9000, 9200, 11211, 27017]
open_ports = []
print(f"{C}[*] Scanning {len(ports)} ports on {target}{W}")
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(self.scan_port_socket, target, port): port for port in ports}
for future in futures:
port = futures[future]
try:
result = future.result(timeout=2.0)
if result["open"]:
open_ports.append(result)
service_color = G if result["service"] != "unknown" else Y
banner_preview = result["banner"][:50] + "..." if len(result["banner"]) > 50 else result["banner"]
print(f" {G}[+] Port {port}/TCP {service_color}({result['service']}){W}")
if result["version"]:
print(f" Version: {result['version']}")
if result["banner"]:
print(f" Banner: {banner_preview}")
if result["response_time"]:
print(f" Response: {result['response_time']}ms")
print()
except:
pass
return open_ports
def advanced_fingerprinting(self, target, port):
"""Advanced service fingerprinting with multiple probes"""
results = []
if port in [80, 443, 8080, 8443]:
# HTTP fingerprinting
http_probes = [
("GET / HTTP/1.0\r\nHost: {}\r\n\r\n".format(target), "HTTP/1.0"),
("GET / HTTP/1.1\r\nHost: {}\r\n\r\n".format(target), "HTTP/1.1"),
("OPTIONS / HTTP/1.0\r\nHost: {}\r\n\r\n".format(target), "OPTIONS"),
("GET /robots.txt HTTP/1.0\r\nHost: {}\r\n\r\n".format(target), "ROBOTS"),
]
for probe, probe_name in http_probes:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
sock.connect((target, port))
sock.send(probe.encode())
response = sock.recv(4096).decode('utf-8', errors='ignore')
sock.close()
if response:
server_match = re.search(r'Server:\s*(.+?)\r\n', response, re.IGNORECASE)
if server_match:
results.append(f"Server: {server_match.group(1)}")
powered_by = re.search(r'X-Powered-By:\s*(.+?)\r\n', response, re.IGNORECASE)
if powered_by:
results.append(f"Powered By: {powered_by.group(1)}")
# Check for technologies
tech_indicators = {
"PHP": ["PHP", "X-PHP"],
"ASP.NET": ["ASP.NET", "X-AspNet-Version"],
"Node.js": ["X-Powered-By: Express"],
"Python": ["Python", "Django", "Flask"],
"Ruby": ["Ruby", "Rails", "Phusion Passenger"],
"Java": ["Servlet", "JSP", "JSESSIONID"]
}
for tech, indicators in tech_indicators.items():
for indicator in indicators:
if indicator in response:
results.append(f"Technology: {tech}")
break
break
except:
continue
return results
async def advanced_recon_async(target, scanner=None):
"""Enhanced reconnaissance with all new features"""
if scanner is None:
scanner = IntelligentScanner()
results = {
"geo_info": {},
"open_ports": [],
"fingerprint_results": [],
"waf_detected": [],
"technologies": [],
"vulnerability_hints": []
}
print(f"\n{G}[*] Advanced Intelligence Gathering on {target}...{W}")
print(f"{C}{'='*60}{W}")
# Step 1: Basic host resolution
try:
print(f"{Y}[1] Host Resolution:{W}")
ip_addr = socket.gethostbyname(target.split('://')[-1].split('/')[0].split(':')[0])
print(f" {C}IP Address: {ip_addr}{W}")
# Get hostname if available
try:
hostname = socket.gethostbyaddr(ip_addr)[0]
print(f" {C}Hostname: {hostname}{W}")
except:
hostname = ip_addr
results["target_ip"] = ip_addr
results["hostname"] = hostname
except Exception as e:
print(f" {R}[!] Cannot resolve target: {e}{W}")
return results
# Step 2: Fast port scanning
print(f"\n{Y}[2] Port Scanning (Fast Socket Method):{W}")
open_ports = scanner.fast_port_scan(ip_addr)
results["open_ports"] = open_ports
if not open_ports:
print(f" {Y}[!] No open ports found{W}")
else:
print(f" {G}[+] Found {len(open_ports)} open ports{W}")
# Step 3: Advanced fingerprinting on open ports
if open_ports:
print(f"\n{Y}[3] Service Fingerprinting:{W}")
for port_info in open_ports[:5]: # Limit to first 5 for speed
port = port_info["port"]
print(f" {C}[*] Analyzing port {port}...{W}")
fingerprint = scanner.advanced_fingerprinting(ip_addr, port)
if fingerprint:
for item in fingerprint:
print(f" {G}→ {item}{W}")
results["fingerprint_results"].append({
"port": port,
"info": item
})
# Step 4: WAF Detection
print(f"\n{Y}[4] WAF Detection:{W}")
try:
target_url = f"http://{target}" if not target.startswith(('http://', 'https://')) else target
waf_results = await scanner.detect_waf_async(target_url)
if waf_results:
for waf in waf_results:
print(f" {R}[!] Detected WAF: {waf['waf']} (confidence: {waf['confidence']}){W}")
for indicator in waf.get('indicators', []):
print(f" {Y}→ {indicator}{W}")
results["waf_detected"].append(waf)
else:
print(f" {G}[✓] No WAF detected{W}")
except Exception as e:
print(f" {Y}[!] WAF detection failed: {e}{W}")
# Step 5: Technology Detection
print(f"\n{Y}[5] Technology Detection:{W}")
tech_detected = set()
# Check common technologies
tech_checks = [
(80, "HTTP", ["Apache", "nginx", "IIS"]),
(443, "HTTPS", ["Apache", "nginx", "IIS"]),
(8080, "HTTP-Proxy", ["Apache", "nginx", "Tomcat"]),
(3306, "MySQL", ["MySQL"]),
(5432, "PostgreSQL", ["PostgreSQL"]),
]
for port, service, techs in tech_checks:
for port_info in open_ports:
if port_info["port"] == port:
for tech in techs:
if tech.lower() in str(port_info.get("banner", "")).lower():
tech_detected.add(tech)
print(f" {G}[+] {tech} detected on port {port}{W}")
if tech_detected:
results["technologies"] = list(tech_detected)
else:
print(f" {Y}[!] No specific technologies identified{W}")
# Step 6: Vulnerability hints based on findings
print(f"\n{Y}[6] Vulnerability Assessment Hints:{W}")
vulnerability_hints = []
# Check for common vulnerable services
for port_info in open_ports:
port = port_info["port"]
service = port_info.get("service", "").lower()
banner = port_info.get("banner", "").lower()
# SSH vulnerabilities
if port == 22:
if "openssh" in banner:
if any(ver in banner for ver in ["7.2", "7.3", "7.4"]):
vulnerability_hints.append({
"port": port,
"service": "SSH",
"vulnerability": "Potential OpenSSH vulnerabilities",
"severity": "medium",
"cve": ["CVE-2018-15473", "CVE-2016-6515"]
})
print(f" {R}[!] Port 22: Check for OpenSSH vulnerabilities{W}")
# HTTP vulnerabilities
elif port in [80, 443, 8080]:
if "apache" in banner and "2.4" in banner:
vulnerability_hints.append({
"port": port,
"service": "HTTP",
"vulnerability": "Apache HTTP Server vulnerabilities",
"severity": "low",
"cve": ["CVE-2021-40438", "CVE-2021-41773"]
})
print(f" {Y}[!] Port {port}: Check Apache version for vulnerabilities{W}")
# SMB vulnerabilities
elif port == 445:
vulnerability_hints.append({
"port": port,
"service": "SMB",
"vulnerability": "SMB protocol vulnerabilities (EternalBlue)",
"severity": "critical",
"cve": ["CVE-2017-0144", "CVE-2017-0145"]
})
print(f" {R}[!] Port 445: SMB port open - check for EternalBlue vulnerability{W}")
# RDP vulnerabilities
elif port == 3389:
vulnerability_hints.append({
"port": port,
"service": "RDP",
"vulnerability": "RDP BlueKeep vulnerability",
"severity": "critical",
"cve": ["CVE-2019-0708"]
})
print(f" {R}[!] Port 3389: RDP port open - check for BlueKeep vulnerability{W}")
results["vulnerability_hints"] = vulnerability_hints
print(f"\n{G}{'='*60}{W}")
print(f"{C}[*] Reconnaissance Completed!{W}")
print(f"{G}{'='*60}{W}")
# Save results
save_finding("advanced_recon", target, results)
return results
async def web_auditor_advanced(proxy_manager=None):
"""Advanced web auditor with WAF detection and intelligent scanning"""
clean()
scanner = IntelligentScanner(proxy_manager)
print(f"\n{G}{'='*60}{W}")
print(f"{C} ADVANCED WEB VULNERABILITY AUDITOR{W}")
print(f"{G}{'='*60}{W}")
target = input(f"\n{Y}Target URL (e.g. http://site.com/): {W}").strip()
if not target.startswith(('http://', 'https://')):
target = 'http://' + target
# Phase 1: WAF Detection
print(f"\n{Y}[PHASE 1] WAF Detection:{W}")
waf_results = await scanner.detect_waf_async(target)
if waf_results:
print(f"{R}[!] WAF Detected: {waf_results[0]['waf']}{W}")
print(f"{Y}[*] Adjusting scan strategy...{W}")
else:
print(f"{G}[✓] No WAF detected{W}")
# Phase 2: Technology Stack Detection
print(f"\n{Y}[PHASE 2] Technology Detection:{W}")
try:
session = get_session(proxy_manager)
response = session.get(target, timeout=10, verify=False)
tech_indicators = {
"PHP": ["PHP", "X-Powered-By: PHP", ".php"],
"ASP.NET": [".aspx", "ASP.NET", "X-AspNet-Version"],
"Node.js": ["X-Powered-By: Express", "Node.js"],
"Python": ["Python", "Django", "Flask", ".py"],
"Java": ["JSESSIONID", "Servlet", "JSP", ".jsp"],
"Ruby": ["Ruby", "Rails", ".rb"],
"WordPress": ["wp-content", "wp-includes", "WordPress"],
"Joomla": ["joomla", "Joomla"],
"Drupal": ["Drupal", "drupal"],
}
detected_tech = []
response_text = response.text
headers = response.headers
for tech, indicators in tech_indicators.items():
for indicator in indicators:
if indicator.lower() in response_text.lower() or \
any(indicator.lower() in str(h).lower() for h in headers.values()):
detected_tech.append(tech)
print(f" {G}[+] {tech}{W}")
break
if not detected_tech:
print(f" {Y}[!] Could not detect specific technology{W}")
# Check security headers
print(f"\n{Y}[PHASE 3] Security Headers Analysis:{W}")
security_headers = {
"Content-Security-Policy": "Prevents XSS",
"X-Frame-Options": "Prevents clickjacking",
"X-Content-Type-Options": "Prevents MIME sniffing",
"X-XSS-Protection": "XSS protection",
"Strict-Transport-Security": "HSTS",
"Referrer-Policy": "Controls referrer info",
}
missing_headers = []
for header, purpose in security_headers.items():
if header in headers:
print(f" {G}[✓] {header}: {headers[header][:50]}...{W}")
else:
print(f" {R}[✗] Missing: {header} - {purpose}{W}")
missing_headers.append(header)
if missing_headers:
save_finding("security_headers", target, {
"missing_headers": missing_headers,
"detected_tech": detected_tech,
"waf_detected": [waf['waf'] for waf in waf_results] if waf_results else []
})
except Exception as e:
print(f"{R}[!] Initial analysis failed: {e}{W}")
# Phase 4: Vulnerability Scanning
print(f"\n{Y}[PHASE 4] Vulnerability Scanning:{W}")
# Import vulnerability scanning functions
from scanner_legacy import scan_url_advanced # Keep original scanning logic
payloads = {
'SQLi': ["'", "' OR '1'='1", "' UNION SELECT NULL--"],
'XSS': ["<script>alert(1)</script>", "\"><img src=x onerror=alert(1)>"],
'LFI': ["../../../../etc/passwd", "....//....//etc/passwd"],
'Command Injection': [";whoami", "|id", "$(ls -la)"],
'XXE': ["<?xml", "<!DOCTYPE"],
'SSRF': ["http://169.254.169.254", "http://localhost"],
}
connector = aiohttp.TCPConnector(limit=THREADS, ssl=False)
async with aiohttp.ClientSession(
connector=connector,
headers=get_headers(),
timeout=aiohttp.ClientTimeout(total=30)
) as session:
total_findings = 0
tasks = []
for cat, p_list in payloads.items():
print(f"{C}[*] Testing {cat}...{W}")
for p in p_list[:3]: # Limit payloads for speed
task = asyncio.create_task(
scan_url_advanced(session, target, p, cat, target, proxy_manager)
)
tasks.append(task)
for future in asyncio.as_completed(tasks):
found, vuln_type, confidence = await future
if found:
total_findings += 1
print(f"\n{G}[*] Scan completed!{W}")
print(f"{C}[*] Total findings: {total_findings}{W}")
# Generate report
if total_findings > 0 or waf_results or missing_headers:
print(f"\n{Y}[REPORT SUMMARY]{W}")
print(f"{C}{'-'*50}{W}")
if waf_results:
print(f"{R}• WAF Detected: {waf_results[0]['waf']}{W}")
if missing_headers:
print(f"{Y}• Missing Security Headers: {len(missing_headers)}{W}")
if total_findings > 0:
print(f"{R}• Vulnerabilities Found: {total_findings}{W}")
print(f"{G}[+] Report saved to: {REPORT_FILE}{W}")
input(f"\n{Y}Press Enter to return...{W}")
async def fast_bruter_advanced():
"""Fast brute forcer with intelligent wordlist selection"""
clean()
print(f"\n{G}{'='*60}{W}")
print(f"{C} INTELLIGENT DIRECTORY BRUTEFORCER{W}")
print(f"{G}{'='*60}{W}")
target = input(f"{Y}Target Base URL: {W}").strip()
if not target.startswith(('http://', 'https://')):
target = 'http://' + target
if not target.endswith("/"):
target += "/"
# Select wordlist based on target
print(f"\n{Y}[*] Selecting optimal wordlist...{W}")
wordlists = {
"common": ["admin", "login", "dashboard", "wp-admin", "config", ".env",
"phpmyadmin", "test", "api", "robots.txt", ".git", ".htaccess",
"backup", "archive", "old", "temp", "tmp", "cgi-bin"],
"api": ["api/v1", "api/v2", "rest/api", "graphql", "swagger", "openapi",
"docs", "documentation", "v1/users", "v2/auth", "oauth"],
"admin": ["administrator", "adminpanel", "controlpanel", "cp", "manager",
"moderator", "superadmin", "sysadmin", "webadmin"],
"files": ["config.php", "config.json", ".env.local", ".env.production",
"database.yml", "settings.py", "composer.json", "package.json",
"web.config", ".htpasswd", ".gitignore"],
}
# Choose wordlist based on target analysis
selected_words = []
# Always include common words
selected_words.extend(wordlists["common"])
# Check if API endpoint might exist
if any(keyword in target.lower() for keyword in ["api", "rest", "graphql"]):
selected_words.extend(wordlists["api"][:5])
print(f"{C}[*] Adding API endpoints to scan{W}")
# Check for admin panels
selected_words.extend(wordlists["admin"][:5])
# Add file extensions based on technology guess
if ".php" in target or "php" in target:
selected_words.extend(["index.php", "login.php", "admin.php", "config.php"])
elif ".asp" in target or ".aspx" in target:
selected_words.extend(["default.aspx", "login.aspx", "admin.aspx"])
print(f"{C}[*] Using {len(selected_words)} optimized paths{W}")
found_paths = []
async with aiohttp.ClientSession(
headers=get_headers(),
timeout=aiohttp.ClientTimeout(total=30)
) as session:
tasks = []
for path in selected_words:
task = asyncio.create_task(brute_path_advanced(session, target, path))
tasks.append(task)
for future in asyncio.as_completed(tasks):
result = await future
if result:
url, status, msg, path = result
found_paths.append({
"url": url,
"status": status,
"message": msg,
"path": path
})
# Display results
if found_paths:
print(f"\n{G}[*] Found {len(found_paths)} accessible paths:{W}")
# Categorize by status code
status_200 = [p for p in found_paths if p["status"] == 200]
status_403 = [p for p in found_paths if p["status"] == 403]
status_redirect = [p for p in found_paths if p["status"] in [301, 302]]
if status_200:
print(f"\n{Y}[200 OK - Accessible]{W}")
for item in status_200[:5]:
print(f" {G}→ {item['path']}{W}")
if status_403:
print(f"\n{Y}[403 Forbidden - Exists but restricted]{W}")
for item in status_403[:3]:
print(f" {R}→ {item['path']}{W}")
if status_redirect:
print(f"\n{Y}[30X Redirect]{W}")
for item in status_redirect[:3]:
print(f" {BL}→ {item['path']}{W}")
# Save findings
save_finding("bruteforce", target, {
"paths_found": found_paths,
"total_tested": len(selected_words),
"wordlist_type": "optimized"
})
else:
print(f"{Y}[!] No accessible paths found{W}")
input(f"\n{Y}Press Enter to return...{W}")
async def brute_path_advanced(session, url, word):
"""Advanced path brute forcer with intelligent detection"""
try:
# Test different variations
variations = [
url + word,
url + word + "/",
url + word + ".php",
url + word + ".html",
url + word.upper(),
url + word.lower(),
url + word + "~",
]
for test_url in variations:
try:
async with session.get(test_url, timeout=3, ssl=False) as resp:
status = resp.status
content_length = resp.headers.get('Content-Length', 0)
if status == 200:
# Check if it's not a generic 404 page
content = await resp.text()
if len(content) > 100: # Not a tiny error page
return (test_url, 200, "Found", word)
elif status == 403:
return (test_url, 403, "Forbidden", word)
elif status in [301, 302]:
location = resp.headers.get('Location', '')
return (test_url, status, f"Redirect to {location[:30]}", word)
except asyncio.TimeoutError:
continue
except:
continue
return None
except Exception:
return None
def advanced_recon():
"""Main recon function wrapper"""
clean()
print(f"\n{G}{'='*60}{W}")
print(f"{C} ADVANCED INTELLIGENCE GATHERING{W}")
print(f"{G}{'='*60}{W}")
target = input(f"{Y}Enter Target Domain/IP: {W}").strip()
# Remove protocol if present
if target.startswith(('http://', 'https://')):
target = target.split('://')[1]
scanner = IntelligentScanner()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
results = loop.run_until_complete(advanced_recon_async(target, scanner))
# Display summary
if results:
print(f"\n{Y}[SUMMARY]{W}")
print(f"{C}{'-'*50}{W}")
print(f"{G}• Target IP: {results.get('target_ip', 'Unknown')}{W}")
print(f"{G}• Open Ports: {len(results.get('open_ports', []))}{W}")
print(f"{G}• WAF Detected: {len(results.get('waf_detected', []))}{W}")
print(f"{G}• Technologies: {len(results.get('technologies', []))}{W}")
print(f"{G}• Vulnerability Hints: {len(results.get('vulnerability_hints', []))}{W}")
# Show critical findings
vuln_hints = results.get('vulnerability_hints', [])
for hint in vuln_hints:
if hint.get('severity') == 'critical':
print(f"{R} ! Critical: {hint.get('vulnerability')} on port {hint.get('port')}{W}")
input(f"\n{Y}Press Enter to return to menu...{W}")
def network_scanner():
"""Network scanner for discovering hosts"""
clean()
print(f"\n{G}{'='*60}{W}")
print(f"{C} NETWORK SCANNER{W}")
print(f"{G}{'='*60}{W}")
network = input(f"{Y}Enter Network (e.g., 192.168.1.0/24): {W}").strip()
try:
network_obj = ipaddress.ip_network(network, strict=False)
print(f"{C}[*] Scanning {network_obj.num_addresses} hosts...{W}")
# Scan common ports
common_ports = [22, 80, 443, 3389, 8080]
scanner = IntelligentScanner()
live_hosts = []
for i, ip in enumerate(network_obj.hosts()):
if i >= 10: # Limit for demo
print(f"{Y}[*] Limited to first 10 hosts for demonstration{W}")
break
print(f"{C}[*] Scanning {ip}...{W}", end='\r')
# Quick ping check
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((str(ip), 80))
if result == 0 or result == 111: # Different connection errors
open_ports = scanner.fast_port_scan(str(ip), common_ports, max_workers=5)
if open_ports:
live_hosts.append({