-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·258 lines (213 loc) · 10.7 KB
/
main.py
File metadata and controls
executable file
·258 lines (213 loc) · 10.7 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
#!/usr/bin/env python3
"""
XSS Detection System - Main Entry Point
A multi-agent XSS vulnerability scanner
"""
import argparse
import asyncio
import sys
from pathlib import Path
from typing import Optional, List
import httpx
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from agents.recon import ReconnaissanceAgent
from agents.payload import PayloadAgent
from agents.injector import InjectionAgent
from agents.detector import DetectionAgent
from agents.learner import LearningAgent
from agents.reporter import ReportingAgent
from agents.ai_agent import AIAgent
console = Console()
class XSSScanner:
def __init__(self, target: str, depth: int = 2, threads: int = 10, custom_payloads: Optional[List[str]] = None):
self.target = target.rstrip('/')
self.depth = depth
self.threads = threads
self.client = httpx.AsyncClient(timeout=30.0, follow_redirects=True, headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
})
self.agents = {
'recon': ReconnaissanceAgent(self.client),
'payload': PayloadAgent(custom_payloads),
'injector': InjectionAgent(self.client),
'detector': DetectionAgent(),
'learner': LearningAgent(),
'reporter': ReportingAgent()
}
self.results = []
self.attack_surface = {}
async def run(self):
console.print(Panel.fit(
f"[bold cyan]XSS Detection System[/bold cyan]\n"
f"Target: {self.target}\n"
f"Depth: {self.depth}\n"
f"Threads: {self.threads}",
title="Scanner Started"
))
console.print("\n[yellow]Phase 1: Reconnaissance...[/yellow]")
self.attack_surface = await self.agents['recon'].crawl(
self.target, self.depth
)
if not self.attack_surface['urls']:
console.print("[red]No URLs discovered. Exiting.[/red]")
return
console.print(f" Discovered {len(self.attack_surface['urls'])} URLs")
console.print(f" Found {len(self.attack_surface['forms'])} forms")
console.print(f" Found {len(self.attack_surface['params'])} parameters")
console.print(f" Found {len(self.attack_surface.get('js_endpoints', []))} JS endpoints")
if not self.attack_surface['params']:
console.print("\n[yellow]No parameters found. Crawling deeper...[/yellow]")
deeper_attack_surface = await self.agents['recon'].crawl(
self.target, min(self.depth + 1, 3)
)
self.attack_surface['urls'] = list(set(self.attack_surface['urls']))
self.attack_surface['params'] = deeper_attack_surface['params']
self.attack_surface['forms'] = deeper_attack_surface['forms']
console.print(f" Now found {len(self.attack_surface['params'])} parameters")
if self.attack_surface['js_endpoints']:
console.print("\n [cyan]JS Endpoints discovered:[/cyan]")
table = Table(show_header=True, header_style="bold cyan", box=None)
table.add_column("#", style="yellow")
table.add_column("Endpoint", style="magenta")
for i, ep in enumerate(self.attack_surface['js_endpoints'][:10], 1):
table.add_row(str(i), ep)
console.print(table)
if self.attack_surface['urls']:
console.print("\n [cyan]URLs discovered:[/cyan]")
table = Table(show_header=True, header_style="bold cyan", box=None)
table.add_column("#", style="yellow")
table.add_column("URL", style="magenta")
for i, url in enumerate(self.attack_surface['urls'], 1):
table.add_row(str(i), url)
console.print(table)
if self.attack_surface['forms']:
console.print("\n [cyan]Forms discovered:[/cyan]")
table = Table(show_header=True, header_style="bold cyan", box=None)
table.add_column("Action", style="yellow")
table.add_column("Method", style="green")
table.add_column("Inputs", style="blue")
for form in self.attack_surface['forms']:
inputs = ', '.join([i.get('name', '') for i in form.get('inputs', [])[:3]])
if len(form.get('inputs', [])) > 3:
inputs += f" (+{len(form.get('inputs', [])) - 3})"
table.add_row(form.get('action', ''), form.get('method', 'GET'), inputs)
console.print(table)
if self.attack_surface['params']:
console.print("\n [cyan]Parameters discovered:[/cyan]")
table = Table(show_header=True, header_style="bold cyan", box=None)
table.add_column("Param", style="yellow")
table.add_column("Method", style="green")
table.add_column("Context", style="blue")
table.add_column("URL", style="magenta")
for param in self.attack_surface['params']:
table.add_row(
param.get('param', ''),
param.get('method', 'GET'),
param.get('context', 'url'),
param.get('url', '')
)
console.print(table)
console.print("\n[yellow]Phase 2: Generating payloads...[/yellow]")
payloads = self.agents['payload'].generate_payloads()
console.print(f" Generated {len(payloads)} payloads")
console.print("\n[yellow]Phase 3: Scanning for XSS...[/yellow]")
semaphore = asyncio.Semaphore(self.threads)
tasks = []
for param_info in self.attack_surface['params']:
for payload in payloads:
task = self._scan_with_semaphore(param_info, payload, semaphore)
tasks.append(task)
self.results = await asyncio.gather(*tasks)
self.results = [r for r in self.results if r]
console.print("\n[yellow]Phase 4: Learning from results...[/yellow]")
for result in self.results:
self.agents['learner'].record_success(result)
console.print("\n[yellow]Phase 5: Generating report...[/yellow]")
self.agents['reporter'].generate_report(self.results, self.target)
console.print(f"\n[green]Scan complete! Found {len(self.results)} potential vulnerabilities.[/green]")
async def _scan_with_semaphore(self, param_info, payload, semaphore):
async with semaphore:
try:
response = await self.agents['injector'].inject(
param_info, payload
)
if response:
detection = self.agents['detector'].analyze(
response, payload, param_info
)
if detection and detection.get('vulnerable'):
self.agents['learner'].record_success(detection)
return detection
except Exception as e:
console.print(f"[dim]Error: {e}[/dim]")
return None
async def close(self):
await self.client.aclose()
async def main():
parser = argparse.ArgumentParser(description='XSS Detection System',
epilog='Example: python3 main.py -t http://target.com/search?q= -p payloads.txt')
parser.add_argument('-t', '--target', help='Target URL')
parser.add_argument('-d', '--depth', type=int, default=2, help='Crawl depth')
parser.add_argument('-n', '--threads', type=int, default=10, help='Concurrent threads')
parser.add_argument('-p', '--payloads', help='Custom payloads (space-separated or file path)')
parser.add_argument('-ai', '--ai', nargs='?', const='autonomous', default=False,
choices=['autonomous', 'intelligent'],
help='Use AI-powered scanning (autonomous or intelligent)')
args = parser.parse_args()
console.print("\n[bold red]⚠️ WARNING: Use only for authorized security testing![/bold red]\n")
if args.ai:
ai_agent = AIAgent()
target = args.target or "https://example.com"
scan_mode = args.ai
try:
console.print(Panel.fit(
f"[bold cyan]AI-Powered XSS Detection[/bold cyan]\n"
f"Target: {target}\n"
f"Mode: {scan_mode.title()} AI Scan",
title="AI Scanner Started"
))
if scan_mode == 'intelligent':
results = await ai_agent.intelligent_scan(target)
else:
results = await ai_agent.autonomous_scan(target)
if 'security_analysis' in results:
sa = results['security_analysis']
if sa.get('waf_detected'):
console.print(f"\n[yellow]WAF Detected:[/yellow] {', '.join(sa['waf_detected'])}")
elif results.get('error') and 'WAF' in results.get('error', ''):
console.print(f"\n[yellow]WAF Detected:[/yellow] Yes")
if sa.get('input_points', 0) > 0:
console.print(f"[cyan]Input points found:[/cyan] {sa['input_points']}")
else:
console.print("[yellow]Note: WAF may be blocking requests[/yellow]")
ai_agent.agents['reporter'].generate_report(results.get('vulnerabilities', []), target)
console.print(f"\n[green]AI Scan complete![/green]")
if not ai_agent.api_key:
console.print("[dim]Set GEMINI_API_KEY for full AI-powered analysis[/dim]")
finally:
await ai_agent.close()
return
target = args.target
if not target:
target = "https://example.com"
custom_payloads = []
if args.payloads:
payload_input = args.payloads
if Path(payload_input).exists() and Path(payload_input).suffix == '.txt':
with open(payload_input, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
custom_payloads.append(line)
console.print(f"[dim]Loaded {len(custom_payloads)} payloads from {payload_input}[/dim]")
else:
custom_payloads = payload_input.split('\n') if '\n' in payload_input else [payload_input]
scanner = XSSScanner(target, args.depth, args.threads, custom_payloads)
try:
await scanner.run()
finally:
await scanner.close()
if __name__ == "__main__":
asyncio.run(main())