MrA7A commited on
Commit
8e9eb33
·
verified ·
1 Parent(s): ac53b63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -84
app.py CHANGED
@@ -4,8 +4,7 @@ import logging
4
  import asyncio
5
  import aiohttp
6
  from fastapi import FastAPI, HTTPException, BackgroundTasks
7
- from fastapi.responses import HTMLResponse
8
- from fastapi.staticfiles import StaticFiles
9
  from pydantic import BaseModel, Field
10
  from typing import List, Dict, Optional, Any
11
  import torch
@@ -35,9 +34,6 @@ os.makedirs("/tmp/hf_cache", exist_ok=True)
35
 
36
  app = FastAPI(title="نظام الذكاء الاصطناعي المتقدم للتحكم في Windows")
37
 
38
- # Mount static files
39
- app.mount("/static", StaticFiles(directory="static"), name="static")
40
-
41
  # إعداد التسجيل
42
  logging.basicConfig(
43
  level=logging.INFO,
@@ -53,7 +49,7 @@ class WindowsTask(BaseModel):
53
  priority: str = "normal"
54
 
55
  class ClientCommand(BaseModel):
56
- command_type: str # execute, analyze, create_bot, install, monitor
57
  parameters: Dict[str, Any]
58
  client_id: Optional[str] = None
59
 
@@ -121,11 +117,14 @@ class WindowsAIAdvisor:
121
 
122
  except Exception as e:
123
  logger.error(f"فشل تحميل النماذج: {e}")
124
- raise e
125
 
126
  def generate_ai_response(self, prompt: str, context: List[Dict] = None) -> str:
127
  """توليد رد الذكاء الاصطناعي"""
128
  try:
 
 
 
129
  system_context = """
130
  أنت مساعد ذكي متخصص في تحليل واختراق ألعاب Windows وبناء البوتات المتقدمة.
131
  خبرتك تشمل:
@@ -160,28 +159,37 @@ class WindowsAIAdvisor:
160
 
161
  def analyze_task(self, task_description: str) -> Dict:
162
  """تحليل المهمة وإنشاء خطة تنفيذ"""
163
- analysis_prompt = f"""
164
- قم بتحليل المهمة التالية وإنشاء خطة تنفيذ مفصلة للعميل على Windows:
165
- {task_description}
166
-
167
- قدم خطة تنفيذ تشمل:
168
- 1. الأدوات المطلوبة
169
- 2. الخطوات التقنية
170
- 3. الأوامر المطلوبة
171
- 4. المخاطر المحتملة
172
- 5. البدائل
173
-
174
- ركز على الجانب العملي والتنفيذي.
175
- """
176
-
177
- plan = self.generate_ai_response(analysis_prompt)
178
-
179
- return {
180
- "plan": plan,
181
- "steps": self.extract_execution_steps(plan),
182
- "tools": self.extract_required_tools(plan),
183
- "commands": self.generate_client_commands(plan, task_description)
184
- }
 
 
 
 
 
 
 
 
 
185
 
186
  def extract_execution_steps(self, plan: str) -> List[str]:
187
  """استخراج خطوات التنفيذ من الخطة"""
@@ -192,11 +200,10 @@ class WindowsAIAdvisor:
192
  line = line.strip()
193
  if any(marker in line for marker in ['1.', '2.', '3.', '4.', '5.', '- ', '• ', 'خطوة']):
194
  if len(line) > 10:
195
- # تنظيف الخطوة
196
  clean_step = re.sub(r'^[0-9•\-\.,]+\s*', '', line)
197
  steps.append(clean_step)
198
 
199
- return steps[:15] # إرجاع أول 15 خطوة فقط
200
 
201
  def extract_required_tools(self, plan: str) -> List[str]:
202
  """استخراج الأدوات المطلوبة"""
@@ -218,7 +225,6 @@ class WindowsAIAdvisor:
218
  """توليد أوامر للعميل"""
219
  commands = []
220
 
221
- # تحليل نوع المهمة
222
  task_lower = task_description.lower()
223
 
224
  if any(word in task_lower for word in ['تحليل', 'analyze', 'فحص']):
@@ -246,15 +252,6 @@ class WindowsAIAdvisor:
246
  "depth": "deep"
247
  },
248
  "description": "تحليل عمليات وذاكرة النظام"
249
- },
250
- {
251
- "command_type": "analyze",
252
- "parameters": {
253
- "task": task,
254
- "analysis_type": "game_files",
255
- "depth": "standard"
256
- },
257
- "description": "فحص ملفات اللعبة"
258
  }
259
  ]
260
 
@@ -300,14 +297,6 @@ class WindowsAIAdvisor:
300
  "depth": "deep"
301
  },
302
  "description": "مسح الثغرات الأمنية"
303
- },
304
- {
305
- "command_type": "execute",
306
- "parameters": {
307
- "script_type": "exploit",
308
- "task": task
309
- },
310
- "description": "تنفيذ استغلال الثغرات"
311
  }
312
  ]
313
 
@@ -377,23 +366,105 @@ class WindowsAIAdvisor:
377
  }
378
  logger.info(f"تم تسجيل العميل: {client_id}")
379
 
380
- def update_client_status(self, client_id: str, status: str):
381
- """تحديث حالة العميل"""
382
- if client_id in self.connected_clients:
383
- self.connected_clients[client_id].update({
384
- "last_seen": datetime.now(),
385
- "status": status
386
- })
387
-
388
  # تهيئة النظام
389
  ai_advisor = WindowsAIAdvisor()
390
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
  # نقاط النهاية
392
- @app.get("/", response_class=HTMLResponse)
393
  async def read_root():
394
- """خدمة واجهة HTML الرئيسية"""
395
- with open("static/index.html", "r", encoding="utf-8") as f:
396
- return HTMLResponse(content=f.read())
397
 
398
  @app.post("/api/analyze-task")
399
  async def analyze_windows_task(task: WindowsTask):
@@ -439,7 +510,7 @@ async def generate_bot_script(task: WindowsTask):
439
  "bot_script": bot_code,
440
  "language": "cpp",
441
  "features": ai_advisor.extract_bot_features(task.task_description),
442
- "compilation_instructions": self.generate_compilation_instructions(bot_code)
443
  }
444
  }
445
  except Exception as e:
@@ -467,7 +538,7 @@ async def generate_exploit_code(task: WindowsTask):
467
  "success": True,
468
  "data": {
469
  "exploit_code": exploit_code,
470
- "techniques_used": self.extract_exploit_techniques(exploit_code),
471
  "risk_level": "high",
472
  "instructions": "يتطلب خبرة متقدمة في التنفيذ"
473
  }
@@ -493,25 +564,6 @@ async def register_client(client_info: Dict):
493
  except Exception as e:
494
  raise HTTPException(status_code=500, detail=str(e))
495
 
496
- @app.post("/api/client/command")
497
- async def send_client_command(command: ClientCommand):
498
- """إرسال أمر للعميل"""
499
- try:
500
- # هنا يمكن حفظ الأمر في قاعدة بيانات pending commands
501
- command_id = f"cmd_{int(time.time())}"
502
-
503
- return {
504
- "success": True,
505
- "data": {
506
- "command_id": command_id,
507
- "command": command,
508
- "status": "sent_to_client",
509
- "timestamp": datetime.now().isoformat()
510
- }
511
- }
512
- except Exception as e:
513
- raise HTTPException(status_code=500, detail=str(e))
514
-
515
  @app.get("/api/system/status")
516
  async def get_system_status():
517
  """الحصول على حالة النظام"""
@@ -525,7 +577,12 @@ async def get_system_status():
525
  }
526
  }
527
 
528
- def generate_compilation_instructions(self, code: str) -> str:
 
 
 
 
 
529
  """توليد تعليمات التجميع"""
530
  if "cpp" in code.lower() or "c++" in code.lower():
531
  return """
@@ -547,7 +604,7 @@ def generate_compilation_instructions(self, code: str) -> str:
547
  else:
548
  return "تعليمات التجميع: استخدم المترجم المناسب للغة المستخدمة"
549
 
550
- def extract_exploit_techniques(self, code: str) -> List[str]:
551
  """استخراج تقنيات الاستغلال المستخدمة"""
552
  techniques = []
553
  code_lower = code.lower()
 
4
  import asyncio
5
  import aiohttp
6
  from fastapi import FastAPI, HTTPException, BackgroundTasks
7
+ from fastapi.responses import HTMLResponse, JSONResponse
 
8
  from pydantic import BaseModel, Field
9
  from typing import List, Dict, Optional, Any
10
  import torch
 
34
 
35
  app = FastAPI(title="نظام الذكاء الاصطناعي المتقدم للتحكم في Windows")
36
 
 
 
 
37
  # إعداد التسجيل
38
  logging.basicConfig(
39
  level=logging.INFO,
 
49
  priority: str = "normal"
50
 
51
  class ClientCommand(BaseModel):
52
+ command_type: str
53
  parameters: Dict[str, Any]
54
  client_id: Optional[str] = None
55
 
 
117
 
118
  except Exception as e:
119
  logger.error(f"فشل تحميل النماذج: {e}")
120
+ # لا نرفع الخطأ لنتمكن من تشغيل التطبيق بدون النموذج
121
 
122
  def generate_ai_response(self, prompt: str, context: List[Dict] = None) -> str:
123
  """توليد رد الذكاء الاصطناعي"""
124
  try:
125
+ if not self.is_loaded:
126
+ return "النظام قيد التهيئة. يرجى المحاولة لاحقاً."
127
+
128
  system_context = """
129
  أنت مساعد ذكي متخصص في تحليل واختراق ألعاب Windows وبناء البوتات المتقدمة.
130
  خبرتك تشمل:
 
159
 
160
  def analyze_task(self, task_description: str) -> Dict:
161
  """تحليل المهمة وإنشاء خطة تنفيذ"""
162
+ try:
163
+ analysis_prompt = f"""
164
+ قم بتحليل المهمة التالية وإنشاء خطة تنفيذ مفصلة للعميل على Windows:
165
+ {task_description}
166
+
167
+ قدم خطة تنفيذ تشمل:
168
+ 1. الأدوات المطلوبة
169
+ 2. الخطوات التقنية
170
+ 3. الأوامر المطلوبة
171
+ 4. المخاطر المحتملة
172
+ 5. البدائل
173
+
174
+ ركز على الجانب العملي والتنفيذي.
175
+ """
176
+
177
+ plan = self.generate_ai_response(analysis_prompt)
178
+
179
+ return {
180
+ "plan": plan,
181
+ "steps": self.extract_execution_steps(plan),
182
+ "tools": self.extract_required_tools(plan),
183
+ "commands": self.generate_client_commands(plan, task_description)
184
+ }
185
+ except Exception as e:
186
+ logger.error(f"فشل تحليل المهمة: {e}")
187
+ return {
188
+ "plan": f"خطأ في التحليل: {str(e)}",
189
+ "steps": [],
190
+ "tools": [],
191
+ "commands": []
192
+ }
193
 
194
  def extract_execution_steps(self, plan: str) -> List[str]:
195
  """استخراج خطوات التنفيذ من الخطة"""
 
200
  line = line.strip()
201
  if any(marker in line for marker in ['1.', '2.', '3.', '4.', '5.', '- ', '• ', 'خطوة']):
202
  if len(line) > 10:
 
203
  clean_step = re.sub(r'^[0-9•\-\.,]+\s*', '', line)
204
  steps.append(clean_step)
205
 
206
+ return steps[:15]
207
 
208
  def extract_required_tools(self, plan: str) -> List[str]:
209
  """استخراج الأدوات المطلوبة"""
 
225
  """توليد أوامر للعميل"""
226
  commands = []
227
 
 
228
  task_lower = task_description.lower()
229
 
230
  if any(word in task_lower for word in ['تحليل', 'analyze', 'فحص']):
 
252
  "depth": "deep"
253
  },
254
  "description": "تحليل عمليات وذاكرة النظام"
 
 
 
 
 
 
 
 
 
255
  }
256
  ]
257
 
 
297
  "depth": "deep"
298
  },
299
  "description": "مسح الثغرات الأمنية"
 
 
 
 
 
 
 
 
300
  }
301
  ]
302
 
 
366
  }
367
  logger.info(f"تم تسجيل العميل: {client_id}")
368
 
 
 
 
 
 
 
 
 
369
  # تهيئة النظام
370
  ai_advisor = WindowsAIAdvisor()
371
 
372
+ # واجهة HTML بسيطة مدمجة في الكود
373
+ HTML_INTERFACE = """
374
+ <!DOCTYPE html>
375
+ <html lang="ar" dir="rtl">
376
+ <head>
377
+ <meta charset="UTF-8">
378
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
379
+ <title>نظام الذكاء الاصطناعي للتحكم في Windows</title>
380
+ <style>
381
+ * { margin: 0; padding: 0; box-sizing: border-box; font-family: Arial, sans-serif; }
382
+ body { background: #1a1a2e; color: white; padding: 20px; }
383
+ .container { max-width: 1200px; margin: 0 auto; }
384
+ .header { text-align: center; margin-bottom: 30px; padding: 20px; background: #16213e; border-radius: 10px; }
385
+ .card { background: #0f3460; padding: 20px; margin: 15px 0; border-radius: 8px; }
386
+ textarea, input, button { width: 100%; padding: 10px; margin: 10px 0; border-radius: 5px; border: none; }
387
+ button { background: #e94560; color: white; cursor: pointer; font-weight: bold; }
388
+ button:hover { background: #c23616; }
389
+ .result { background: #2d4059; padding: 15px; border-radius: 5px; margin: 10px 0; white-space: pre-wrap; }
390
+ </style>
391
+ </head>
392
+ <body>
393
+ <div class="container">
394
+ <div class="header">
395
+ <h1>🖥️ نظام الذكاء الاصطناعي للتحكم في Windows</h1>
396
+ <p>أدخل المهمة المطلوبة وسيتم توليد خطة تنفيذ مفصلة</p>
397
+ </div>
398
+
399
+ <div class="card">
400
+ <h3>🎯 إدخال المهمة</h3>
401
+ <textarea id="taskInput" rows="5" placeholder="مثال: قم بتحليل لعبة Genshin Impact وابني بوتاً للتعدين التلقائي..."></textarea>
402
+ <select id="taskType">
403
+ <option value="analysis">تحليل لعبة</option>
404
+ <option value="bot_creation">بناء بوت</option>
405
+ <option value="hacking">تحليل اختراق</option>
406
+ <option value="software_install">تثبيت برامج</option>
407
+ </select>
408
+ <button onclick="analyzeTask()">🚀 تحليل المهمة</button>
409
+ </div>
410
+
411
+ <div class="card">
412
+ <h3>📊 النتائج</h3>
413
+ <div id="results"></div>
414
+ </div>
415
+ </div>
416
+
417
+ <script>
418
+ async function analyzeTask() {
419
+ const task = document.getElementById('taskInput').value;
420
+ const taskType = document.getElementById('taskType').value;
421
+
422
+ if (!task) {
423
+ alert('يرجى إدخال المهمة');
424
+ return;
425
+ }
426
+
427
+ document.getElementById('results').innerHTML = 'جاري التحليل...';
428
+
429
+ try {
430
+ const response = await fetch('/api/analyze-task', {
431
+ method: 'POST',
432
+ headers: { 'Content-Type': 'application/json' },
433
+ body: JSON.stringify({
434
+ task_description: task,
435
+ task_type: taskType,
436
+ priority: 'high'
437
+ })
438
+ });
439
+
440
+ const data = await response.json();
441
+ displayResults(data);
442
+ } catch (error) {
443
+ document.getElementById('results').innerHTML = 'خطأ في الاتصال: ' + error;
444
+ }
445
+ }
446
+
447
+ function displayResults(data) {
448
+ let html = '';
449
+ if (data.success) {
450
+ html += `<div class="result"><strong>✅ الخطة:</strong><br>${data.data.execution_plan}</div>`;
451
+ html += `<div class="result"><strong>🛠️ الأدوات المطلوبة:</strong><br>${data.data.analysis.tools.join(', ')}</div>`;
452
+ html += `<div class="result"><strong>📋 خطوات التنفيذ:</strong><br>${data.data.analysis.steps.join('<br>')}</div>`;
453
+ } else {
454
+ html = `<div class="result">❌ خطأ: ${data.detail}</div>`;
455
+ }
456
+ document.getElementById('results').innerHTML = html;
457
+ }
458
+ </script>
459
+ </body>
460
+ </html>
461
+ """
462
+
463
  # نقاط النهاية
464
+ @app.get("/")
465
  async def read_root():
466
+ """الصفحة الرئيسية"""
467
+ return HTMLResponse(content=HTML_INTERFACE)
 
468
 
469
  @app.post("/api/analyze-task")
470
  async def analyze_windows_task(task: WindowsTask):
 
510
  "bot_script": bot_code,
511
  "language": "cpp",
512
  "features": ai_advisor.extract_bot_features(task.task_description),
513
+ "compilation_instructions": generate_compilation_instructions(bot_code)
514
  }
515
  }
516
  except Exception as e:
 
538
  "success": True,
539
  "data": {
540
  "exploit_code": exploit_code,
541
+ "techniques_used": extract_exploit_techniques(exploit_code),
542
  "risk_level": "high",
543
  "instructions": "يتطلب خبرة متقدمة في التنفيذ"
544
  }
 
564
  except Exception as e:
565
  raise HTTPException(status_code=500, detail=str(e))
566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
567
  @app.get("/api/system/status")
568
  async def get_system_status():
569
  """الحصول على حالة النظام"""
 
577
  }
578
  }
579
 
580
+ @app.get("/health")
581
+ async def health_check():
582
+ """فحص صحة النظام"""
583
+ return {"status": "healthy", "timestamp": datetime.now().isoformat()}
584
+
585
+ def generate_compilation_instructions(code: str) -> str:
586
  """توليد تعليمات التجميع"""
587
  if "cpp" in code.lower() or "c++" in code.lower():
588
  return """
 
604
  else:
605
  return "تعليمات التجميع: استخدم المترجم المناسب للغة المستخدمة"
606
 
607
+ def extract_exploit_techniques(code: str) -> List[str]:
608
  """استخراج تقنيات الاستغلال المستخدمة"""
609
  techniques = []
610
  code_lower = code.lower()