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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .NET Forge Ultra - Advanced Reverse Engineering Workstation
3
+ HuggingFace Spaces Deployment
4
+
5
+ Features:
6
+ - IL Metadata Parsing (dnlib)
7
+ - Method Editing + Recompilation (Mono.Cecil)
8
+ - APK Decompilation Tools (androguard, apktool)
9
+ - Magisk Module Manager
10
+ - ADB Device Explorer
11
+ - Termux Package Manager UI
12
+ - AI-Powered Code Analysis (DeepSeek/Google AI)
13
+ - Firebase Backend Integration
14
+ - Cloudflare Tunnel Support
15
+ """
16
+
17
+ import gradio as gr
18
+ import os
19
+ import sys
20
+ import json
21
+ import hashlib
22
+ import subprocess
23
+ from pathlib import Path
24
+ from typing import Optional, Dict, Any, List
25
+ from datetime import datetime
26
+ import requests
27
+
28
+ # Try imports - will install if missing
29
+ try:
30
+ import dnlib
31
+ except ImportError:
32
+ os.system("pip install dnlib")
33
+ import dnlib
34
+
35
+ try:
36
+ import Mono.Cecil
37
+ except ImportError:
38
+ os.system("pip install Mono.Cecil")
39
+
40
+ try:
41
+ import androguard.core.bytecodes.apk as apk
42
+ except ImportError:
43
+ os.system("pip install androguard")
44
+ import androguard.core.bytecodes.apk as apk
45
+
46
+ try:
47
+ import firebase_admin
48
+ from firebase_admin import credentials, auth, firestore
49
+ except ImportError:
50
+ os.system("pip install firebase-admin")
51
+ import firebase_admin
52
+ from firebase_admin import credentials, auth, firestore
53
+
54
+ from dotenv import load_dotenv
55
+ load_dotenv()
56
+
57
+
58
+ class DotNetForgeUltra:
59
+ """Main application class for .NET Forge Ultra"""
60
+
61
+ def __init__(self):
62
+ self.config = {
63
+ "hf_token": os.getenv("HF_TOKEN", ""),
64
+ "github_token": os.getenv("GITHUB_TOKEN", ""),
65
+ "cloudflare_token": os.getenv("CLOUDFLARE_API_TOKEN", ""),
66
+ "firebase_key": os.getenv("FIREBASE_API_KEY", ""),
67
+ "google_ai_key": os.getenv("GOOGLE_AI_API_KEY", ""),
68
+ "deepseek_key": os.getenv("DEEPSEEK_API_KEY", ""),
69
+ }
70
+ self.uploaded_files = []
71
+ self.decompiled_output = ""
72
+ self.device_info = {}
73
+
74
+ def analyze_dotnet_assembly(self, file_path: str) -> str:
75
+ """Analyze .NET assembly metadata"""
76
+ try:
77
+ assembly = dnlib.DotNet.ModuleDefMD.Load(file_path)
78
+
79
+ output = []
80
+ output.append(f"Assembly: {assembly.Name}")
81
+ output.append(f"Version: {assembly.Assembly.DefAssembly.Version}")
82
+ output.append(f"MDRVA: 0x{assembly.MD_RVA:X8}")
83
+ output.append("\n=== Types ===\n")
84
+
85
+ for type_def in assembly.GetTypes():
86
+ output.append(f"Type: {type_def.FullName}")
87
+ output.append(f" Namespace: {type_def.Namespace}")
88
+ output.append(f" Base Type: {type_def.BaseType}")
89
+ output.append(f" Attributes: {type_def.Attributes}")
90
+
91
+ for method in type_def.Methods:
92
+ output.append(f" Method: {method.Name}{method.Signature}")
93
+
94
+ output.append("")
95
+
96
+ return "\n".join(output[:500]) # Limit output
97
+ except Exception as e:
98
+ return f"Error analyzing assembly: {str(e)}"
99
+
100
+ def decompile_apk(self, file_path: str) -> str:
101
+ """Decompile APK file"""
102
+ try:
103
+ apk_obj = apk.APK(file_path)
104
+
105
+ output = []
106
+ output.append(f"Package: {apk_obj.get_package()}")
107
+ output.append(f"Version: {apk_obj.get_androidversion_name()}")
108
+ output.append(f"SDK Version: {apk_obj.get_target_sdk_version()}")
109
+ output.append(f"Permissions: {len(apk_obj.get_permissions())}")
110
+ output.append("\n=== Activities ===\n")
111
+
112
+ for activity in apk_obj.get_activities():
113
+ output.append(f" - {activity}")
114
+
115
+ output.append("\n=== Services ===\n")
116
+ for service in apk_obj.get_services():
117
+ output.append(f" - {service}")
118
+
119
+ output.append("\n=== Receivers ===\n")
120
+ for receiver in apk_obj.get_receivers():
121
+ output.append(f" - {receiver}")
122
+
123
+ return "\n".join(output)
124
+ except Exception as e:
125
+ return f"Error decompiling APK: {str(e)}"
126
+
127
+ def list_adb_devices(self) -> str:
128
+ """List connected ADB devices"""
129
+ try:
130
+ result = subprocess.run(
131
+ ["adb", "devices"],
132
+ capture_output=True,
133
+ text=True,
134
+ timeout=10
135
+ )
136
+ return result.stdout
137
+ except Exception as e:
138
+ return f"ADB Error: {str(e)}"
139
+
140
+ def get_device_info(self, device_id: str) -> str:
141
+ """Get detailed device information"""
142
+ try:
143
+ commands = [
144
+ ("Model", f"adb -s {device_id} shell getprop ro.product.model"),
145
+ ("Android Version", f"adb -s {device_id} shell getprop ro.build.version.release"),
146
+ ("SDK Level", f"adb -s {device_id} shell getprop ro.build.version.sdk"),
147
+ ("Serial", f"adb -s {device_id} shell getprop ro.serialno"),
148
+ ]
149
+
150
+ output = []
151
+ for name, cmd in commands:
152
+ result = subprocess.run(
153
+ cmd, shell=True, capture_output=True, text=True, timeout=10
154
+ )
155
+ output.append(f"{name}: {result.stdout.strip()}")
156
+
157
+ return "\n".join(output)
158
+ except Exception as e:
159
+ return f"Error: {str(e)}"
160
+
161
+ def list_magisk_modules(self, device_id: str) -> str:
162
+ """List installed Magisk modules"""
163
+ try:
164
+ cmd = f"adb -s {device_id} shell ls /data/adb/modules"
165
+ result = subprocess.run(
166
+ cmd, shell=True, capture_output=True, text=True, timeout=10
167
+ )
168
+
169
+ modules = result.stdout.strip().split("\n")
170
+ output = ["=== Installed Magisk Modules ===\n"]
171
+
172
+ for module in modules:
173
+ if module:
174
+ output.append(f" β€’ {module}")
175
+
176
+ return "\n".join(output)
177
+ except Exception as e:
178
+ return f"Error: {str(e)}"
179
+
180
+ def ai_code_analysis(self, code: str, language: str, task: str) -> str:
181
+ """Analyze code using AI (DeepSeek or Google AI)"""
182
+
183
+ prompt = f"""Analyze this {language} code for {task}:
184
+
185
+ ```{language}
186
+ {code[:5000]} # Limit to 5000 chars
187
+ ```
188
+
189
+ Provide:
190
+ 1. Security vulnerabilities
191
+ 2. Code quality issues
192
+ 3. Optimization suggestions
193
+ 4. Reverse engineering insights
194
+ """
195
+
196
+ # Try DeepSeek first
197
+ if self.config["deepseek_key"]:
198
+ try:
199
+ response = requests.post(
200
+ "https://api.deepseek.com/v1/chat/completions",
201
+ headers={"Authorization": f"Bearer {self.config['deepseek_key']}"},
202
+ json={
203
+ "model": "deepseek-coder",
204
+ "messages": [{"role": "user", "content": prompt}],
205
+ "max_tokens": 2000
206
+ },
207
+ timeout=60
208
+ )
209
+ if response.status_code == 200:
210
+ return response.json()["choices"][0]["message"]["content"]
211
+ except:
212
+ pass
213
+
214
+ # Fallback to Google AI
215
+ if self.config["google_ai_key"]:
216
+ try:
217
+ response = requests.post(
218
+ f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={self.config['google_ai_key']}",
219
+ json={
220
+ "contents": [{"parts": [{"text": prompt}]}]
221
+ },
222
+ timeout=60
223
+ )
224
+ if response.status_code == 200:
225
+ return response.json()["candidates"][0]["content"]["parts"][0]["text"]
226
+ except:
227
+ pass
228
+
229
+ return "AI services not configured. Add DEEPSEEK_API_KEY or GOOGLE_AI_API_KEY to .env"
230
+
231
+ def list_termux_packages(self) -> str:
232
+ """List available Termux packages"""
233
+ # Common reverse engineering packages
234
+ packages = [
235
+ ("radare2", "Advanced reverse engineering framework"),
236
+ ("ghidra", "NSA reverse engineering tool"),
237
+ ("frida", "Dynamic instrumentation toolkit"),
238
+ ("objection", "Runtime mobile exploration"),
239
+ ("mitmproxy", "HTTPS proxy for analysis"),
240
+ ("dex2jar", "DEX to JAR converter"),
241
+ ("jd-gui", "Java decompiler"),
242
+ ("apktool", "APK reverse engineering"),
243
+ ("jadx", "DEX to Java decompiler"),
244
+ ("bytecode-viewer", "Java bytecode viewer"),
245
+ ]
246
+
247
+ output = ["=== Recommended Termux Packages ===\n"]
248
+ for pkg, desc in packages:
249
+ output.append(f" pkg install {pkg:20} # {desc}")
250
+
251
+ return "\n".join(output)
252
+
253
+
254
+ def create_ui() -> gr.Blocks:
255
+ """Create the Gradio interface"""
256
+
257
+ forge = DotNetForgeUltra()
258
+
259
+ with gr.Blocks(
260
+ title=".NET Forge Ultra",
261
+ theme=gr.themes.Base(primary_hue="cyan"),
262
+ css="""
263
+ .gradio-container { max-width: 1400px !important; }
264
+ .code-output { font-family: 'Consolas', monospace; font-size: 12px; }
265
+ .status-badge { padding: 4px 12px; border-radius: 20px; font-weight: bold; }
266
+ .status-active { background: #22c55e; color: white; }
267
+ .status-inactive { background: #ef4444; color: white; }
268
+ """
269
+ ) as demo:
270
+
271
+ # Header
272
+ gr.Markdown("""
273
+ # πŸ”₯ .NET Forge Ultra
274
+ ### Advanced Reverse Engineering Workstation
275
+
276
+ **Features:** IL Parsing β€’ APK Decompilation β€’ ADB Explorer β€’ Magisk Manager β€’ AI Analysis
277
+ """)
278
+
279
+ # Status Bar
280
+ with gr.Row():
281
+ status_items = [
282
+ ("HuggingFace", os.getenv("HF_TOKEN", "")),
283
+ ("GitHub", os.getenv("GITHUB_TOKEN", "")),
284
+ ("Cloudflare", os.getenv("CLOUDFLARE_API_TOKEN", "")),
285
+ ("Firebase", os.getenv("FIREBASE_API_KEY", "")),
286
+ ("DeepSeek AI", os.getenv("DEEPSEEK_API_KEY", "")),
287
+ ]
288
+
289
+ for name, value in status_items:
290
+ status = "🟒 Active" if value else "πŸ”΄ Inactive"
291
+ gr.Markdown(f"**{name}:** {status}")
292
+
293
+ # Main Tabs
294
+ with gr.Tabs():
295
+
296
+ # Tab 1: .NET Assembly Analyzer
297
+ with gr.TabItem("πŸ”· .NET Analyzer"):
298
+ gr.Markdown("### Upload and analyze .NET assemblies (DLL/EXE)")
299
+
300
+ with gr.Row():
301
+ with gr.Column(scale=1):
302
+ dotnet_file = gr.File(
303
+ label="Upload .NET Assembly",
304
+ file_types=[".dll", ".exe"]
305
+ )
306
+ analyze_btn = gr.Button("πŸ” Analyze Assembly", variant="primary")
307
+
308
+ with gr.Column(scale=2):
309
+ dotnet_output = gr.Code(
310
+ label="Analysis Results",
311
+ language="text",
312
+ lines=30,
313
+ elem_classes=["code-output"]
314
+ )
315
+
316
+ analyze_btn.click(
317
+ fn=lambda f: forge.analyze_dotnet_assembly(f.name) if f else "No file uploaded",
318
+ inputs=[dotnet_file],
319
+ outputs=[dotnet_output]
320
+ )
321
+
322
+ # Tab 2: APK Decompiler
323
+ with gr.TabItem("πŸ“± APK Decompiler"):
324
+ gr.Markdown("### Decompile Android APK files")
325
+
326
+ with gr.Row():
327
+ with gr.Column(scale=1):
328
+ apk_file = gr.File(
329
+ label="Upload APK",
330
+ file_types=[".apk"]
331
+ )
332
+ decompile_btn = gr.Button("πŸ”“ Decompile APK", variant="primary")
333
+
334
+ with gr.Column(scale=2):
335
+ apk_output = gr.Code(
336
+ label="Decompiled Output",
337
+ language="text",
338
+ lines=30,
339
+ elem_classes=["code-output"]
340
+ )
341
+
342
+ decompile_btn.click(
343
+ fn=lambda f: forge.decompile_apk(f.name) if f else "No file uploaded",
344
+ inputs=[apk_file],
345
+ outputs=[apk_output]
346
+ )
347
+
348
+ # Tab 3: ADB Device Explorer
349
+ with gr.TabItem("πŸ“² ADB Explorer"):
350
+ gr.Markdown("### Explore connected Android devices")
351
+
352
+ with gr.Row():
353
+ with gr.Column(scale=1):
354
+ refresh_btn = gr.Button("πŸ”„ Refresh Devices")
355
+ device_list = gr.Textbox(
356
+ label="Connected Devices",
357
+ lines=5,
358
+ interactive=False
359
+ )
360
+
361
+ with gr.Column(scale=2):
362
+ device_id = gr.Textbox(
363
+ label="Device ID",
364
+ placeholder="Enter device serial"
365
+ )
366
+ with gr.Row():
367
+ info_btn = gr.Button("πŸ“‹ Device Info")
368
+ magisk_btn = gr.Button("πŸ”§ Magisk Modules")
369
+ device_output = gr.Code(
370
+ label="Device Details",
371
+ language="text",
372
+ lines=15,
373
+ elem_classes=["code-output"]
374
+ )
375
+
376
+ refresh_btn.click(
377
+ fn=forge.list_adb_devices,
378
+ outputs=[device_list]
379
+ )
380
+
381
+ info_btn.click(
382
+ fn=lambda d: forge.get_device_info(d) if d else "No device ID",
383
+ inputs=[device_id],
384
+ outputs=[device_output]
385
+ )
386
+
387
+ magisk_btn.click(
388
+ fn=lambda d: forge.list_magisk_modules(d) if d else "No device ID",
389
+ inputs=[device_id],
390
+ outputs=[device_output]
391
+ )
392
+
393
+ # Tab 4: Termux Package Manager
394
+ with gr.TabItem("πŸ“¦ Termux Packages"):
395
+ gr.Markdown("### Manage reverse engineering tools on Termux")
396
+
397
+ load_packages = gr.Button("πŸ“‹ Load Package List")
398
+ package_output = gr.Code(
399
+ label="Available Packages",
400
+ language="bash",
401
+ lines=20,
402
+ elem_classes=["code-output"]
403
+ )
404
+
405
+ load_packages.click(
406
+ fn=forge.list_termux_packages,
407
+ outputs=[package_output]
408
+ )
409
+
410
+ # Tab 5: AI Code Analysis
411
+ with gr.TabItem("πŸ€– AI Analysis"):
412
+ gr.Markdown("### AI-powered code analysis and reverse engineering insights")
413
+
414
+ with gr.Row():
415
+ with gr.Column(scale=2):
416
+ code_input = gr.Code(
417
+ label="Paste Code",
418
+ language="csharp",
419
+ lines=15
420
+ )
421
+ language_select = gr.Dropdown(
422
+ label="Language",
423
+ choices=["C#", "Java", "Python", "JavaScript", "C++", "Smali"],
424
+ value="C#"
425
+ )
426
+ task_select = gr.Dropdown(
427
+ label="Analysis Type",
428
+ choices=[
429
+ "Security Vulnerabilities",
430
+ "Code Quality Review",
431
+ "Optimization Suggestions",
432
+ "Reverse Engineering Insights",
433
+ "Malware Detection"
434
+ ],
435
+ value="Security Vulnerabilities"
436
+ )
437
+ analyze_ai_btn = gr.Button("🧠 Analyze with AI", variant="primary")
438
+
439
+ with gr.Column(scale=2):
440
+ ai_output = gr.Code(
441
+ label="AI Analysis Results",
442
+ language="markdown",
443
+ lines=25,
444
+ elem_classes=["code-output"]
445
+ )
446
+
447
+ analyze_ai_btn.click(
448
+ fn=lambda code, lang, task: forge.ai_code_analysis(code, lang, task),
449
+ inputs=[code_input, language_select, task_select],
450
+ outputs=[ai_output]
451
+ )
452
+
453
+ # Tab 6: Settings & Configuration
454
+ with gr.TabItem("βš™οΈ Settings"):
455
+ gr.Markdown("### Configure API keys and integrations")
456
+
457
+ gr.Markdown("""
458
+ **Important:** Set these in your `.env` file or HuggingFace Space secrets.
459
+
460
+ ```bash
461
+ # Required for full functionality
462
+ HF_TOKEN=hf_xxx
463
+ GITHUB_TOKEN=ghp_xxx
464
+ CLOUDFLARE_API_TOKEN=xxx
465
+ FIREBASE_API_KEY=xxx
466
+ GOOGLE_AI_API_KEY=xxx
467
+ DEEPSEEK_API_KEY=sk_xxx
468
+ ```
469
+ """)
470
+
471
+ with gr.Group():
472
+ gr.Markdown("### πŸ”— Quick Links")
473
+ gr.HTML("""
474
+ <div style="display: flex; gap: 10px; flex-wrap: wrap;">
475
+ <a href="https://huggingface.co/settings/tokens" target="_blank" style="padding: 8px 16px; background: #FFD21E; color: black; text-decoration: none; border-radius: 6px;">Get HF Token</a>
476
+ <a href="https://github.com/settings/tokens" target="_blank" style="padding: 8px 16px; background: #24292e; color: white; text-decoration: none; border-radius: 6px;">Get GitHub Token</a>
477
+ <a href="https://console.cloudflare.com/" target="_blank" style="padding: 8px 16px; background: #F38020; color: white; text-decoration: none; border-radius: 6px;">Cloudflare Dashboard</a>
478
+ <a href="https://console.firebase.google.com/" target="_blank" style="padding: 8px 16px; background: #FFCA28; color: black; text-decoration: none; border-radius: 6px;">Firebase Console</a>
479
+ <a href="https://platform.deepseek.com/" target="_blank" style="padding: 8px 16px; background: #10a37f; color: white; text-decoration: none; border-radius: 6px;">DeepSeek API</a>
480
+ <a href="https://aistudio.google.com/app/apikey" target="_blank" style="padding: 8px 16px; background: #4285F4; color: white; text-decoration: none; border-radius: 6px;">Google AI Studio</a>
481
+ </div>
482
+ """)
483
+
484
+ # Footer
485
+ gr.Markdown("""
486
+ ---
487
+ **⚠️ Legal Disclaimer:** This tool is for educational and authorized security research only.
488
+ Always obtain proper authorization before analyzing or modifying software.
489
+
490
+ **Built with:** Gradio β€’ dnlib β€’ Androguard β€’ Firebase β€’ DeepSeek AI
491
+ """)
492
+
493
+ return demo
494
+
495
+
496
+ # Launch
497
+ if __name__ == "__main__":
498
+ demo = create_ui()
499
+ demo.launch(
500
+ server_name="0.0.0.0",
501
+ server_port=7860,
502
+ share=False,
503
+ show_error=True
504
+ )