Spaces:
Paused
Paused
Update app.py
Browse files41 unmodified lines42434445464763 unmodified lines1111121131141151161177 unmodified lines12512612712812913013123 unmodified lines1551561571581591601614 unmodified lines1661671681691701711722 unmodified lines17517617717817918018114 unmodified lines19619719819920020120220320420520620711 unmodified lines2192202212222232242257 unmodified lines23323423523623723823928 unmodified lines26826927027127227327427527627727827928017 unmodified lines29829930030130230330414 unmodified lines3193203213223233243259 unmodified lines3353363373383393403418 unmodified lines35035135235335435535619 unmodified lines37637737837938038138238338481 unmodified lines46646746846947047147241 unmodified lines'.png', '.jpg', '.jpeg', '.gif', '.svg', 'http://www.w3.org/', 'xmlns:']ALLOWED_SECTIONS = {'.rodata', '.data', '.dynstr', '.strtab'}# 2. التعابير النمطية المستهدفة63 unmodified linesreturn entropydef is_noise_string(text: str) -> bool:"""فلتر صارم لاستبعاد نصوص HTML/CSS والأيقونات"""text_lower = text.lower()for noise in NOISE_REJECT_PATTERNS:if noise in text_lower:7 unmodified linesreturn f"...{clean_text}..."def parse_il2cpp_metadata(file_path: str) -> List[str]:"""محلل بنية Unity global-metadata.dat لاستخراج جدول النصوص C# مباشرة"""extracted_strings = []try:with open(file_path, 'rb') as f:23 unmodified linesreturn extracted_stringsdef demangle_symbol_name(sym_name: str) -> str:"""فك تزييف أسماء C++ Mangled Symbols"""if not sym_name:return ""if cxxfilt:4 unmodified linesreturn sym_namedef analyze_elf_binary(file_path: str) -> Tuple[str, List[Dict[str, Any]], List[Dict[str, Any]]]:"""قراءة هيكلية ELF الرسمية واستخراج الأقسام والرموز والدوال المشبوهة"""extracted_text_blocks = []suspicious_symbols = []high_entropy_sections = []2 unmodified lineswith open(file_path, 'rb') as f:elf = ELFFile(f)# 1. استخراج الأقسام الحيوية فقط وسحب النصوص منهاfor section in elf.iter_sections():sec_name = section.namesec_data = section.data()14 unmodified liness = m.decode('ascii', errors='ignore')if not is_noise_string(s):s_lower = s.lower()if any(trigger in s_lower for k in ACCEPT_KEYWORD_TRIGGERS for trigger in [k]):extracted_text_blocks.append(s)except Exception:pass# 2. استخراج الرموز والدوال المشبوهة من جداول الرموزif isinstance(section, SymbolTableSection):for symbol in section.iter_symbols():sym_name = symbol.name11 unmodified lines})except Exception:# حل بديل إذا كان الملف ثنائياً عادياً وليس ELF قياسيtry:res = subprocess.run(['strings', '-n', '4', file_path], capture_output=True, text=True, errors='ignore', timeout=10)for line in res.stdout.splitlines():7 unmodified linesreturn "\n".join(extracted_text_blocks), suspicious_symbols, high_entropy_sectionsdef brute_force_xor_full(raw_bytes: bytes) -> List[Dict[str, Any]]:"""تطبيق مفاتيح XOR العنيفة (1-255) على الملفات وحصد النتائج الحقيقية"""results = []sample = raw_bytes[:250000]targets = [b"http://", b"https://", b"discord", b"stuartmods", b"license", b"verify"]28 unmodified linesentropy = calculate_entropy(raw_bytes)text_content = ""# أ) ملفات global-metadata.datif "global-metadata.dat" in file_name:metadata_strings = parse_il2cpp_metadata(file_path)if metadata_strings:text_content = "\n".join(metadata_strings)# ب) ملفات .so المباشرة والـ ELF Binariesif not text_content:if file_name.endswith('.so') or b'ELF' in raw_bytes[:4]:extracted_text, elf_syms, high_sec = analyze_elf_binary(file_path)17 unmodified lineselse:text_content = raw_bytes.decode('utf-8', errors='ignore')# 1. كشف وتصفية الروابط الحرجّة (Discord & StuartMods)for m in DISCORD_PATTERN.finditer(text_content):val = m.group()snip = extract_snippet(text_content, m.start(), m.end(), 100)14 unmodified lines"severity": "CRITICAL"})# 2. كشف الروابط العامة التابعة لـ APIs والتحققfor m in GENERIC_URL_PATTERN.finditer(text_content):val = m.group()if not is_noise_string(val) and "discord" not in val.lower() and "stuartmods" not in val.lower():9 unmodified lines"severity": "HIGH"})# 3. فك تشفير Base64 وسلاسل XORbase64_matches = re.findall(r'(?:[A-Za-z0-9+/]{4}){6,}(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?', text_content)for b64 in base64_matches[:10]:try:8 unmodified linesexcept Exception:pass# XOR Full Brute Force للملفات أصغر من 5MBif file_size <= 5 * 1024 * 1024 and (file_name.endswith('.so') or entropy > 6.8):xor_hits = brute_force_xor_full(raw_bytes)for x_item in xor_hits:19 unmodified linesfor root, _, files in os.walk(extract_folder):for f in files:full_p = os.path.join(root, f)rel_p = os.path.relpath(full_p, extract_folder).replace('\\', '/')if any(rel_p.startswith(sub) for sub in IGNORED_SUBDIRS):continuefiles_to_scan.append(full_p)total_files = len(files_to_scan)81 unmodified linesawait manager.broadcast_log("INFO", "بدء تحليل ELF Sections واستخراج الرموز وفك التشفير بـ XOR...", 30)# تشغيل الفحص بعيداً عن الخيط الرئيسي لحماية الـ CPU والـ Event Loopreport_data = await asyncio.to_thread(run_full_analysis_sync, extract_folder)await manager.broadcast_log("SUCCESS", f"اكتمل التفتيش! تم اكتشاف {report_data['summary']['total_links']} رابط حاسم و {report_data['summary']['total_functions']} دالة مشبوهة.", 100)41 unmodified lines424344454647484950515253545556575863 unmodified lines1221231241251261277 unmodified lines13513613713813914023 unmodified lines1641651661671681694 unmodified lines1741751761771781792 unmodified lines18218318418518618714 unmodified lines20220320420520620720820921021121211 unmodified lines2242252262272282297 unmodified lines23723823924024124228 unmodified lines27127227327427527627727827928028117 unmodified lines29930030130230330414 unmodified lines3193203213223233249 unmodified lines3343353363373383398 unmodified lines34834935035135235319 unmodified lines37337437537637737837938038138238338438538681 unmodified lines46846947047147247341 unmodified lines'.png', '.jpg', '.jpeg', '.gif', '.svg', 'http://www.w3.org/', 'xmlns:']IGNORED_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.ico','.mp4', '.avi', '.mkv', '.mov', '.flv', '.wmv', '.mp3', '.wav', '.ogg','.ttf', '.otf', '.woff', '.woff2', '.eot', '.pdf'}# المجلدات الواهية المستبعدة (تصاميم وأيقونات لا تحتوي كوداً)IGNORED_SUBDIRS = ['res/drawable', 'res/color', 'res/anim', 'res/mipmap', 'res/values-']ALLOWED_SECTIONS = {'.rodata', '.data', '.dynstr', '.strtab'}# 2. التعابير النمطية المستهدفة63 unmodified linesreturn entropydef is_noise_string(text: str) -> bool:text_lower = text.lower()for noise in NOISE_REJECT_PATTERNS:if noise in text_lower:7 unmodified linesreturn f"...{clean_text}..."def parse_il2cpp_metadata(file_path: str) -> List[str]:extracted_strings = []try:with open(file_path, 'rb') as f:23 unmodified linesreturn extracted_stringsdef demangle_symbol_name(sym_name: str) -> str:if not sym_name:return ""if cxxfilt:4 unmodified linesreturn sym_namedef analyze_elf_binary(file_path: str) -> Tuple[str, List[Dict[str, Any]], List[Dict[str, Any]]]:extracted_text_blocks = []suspicious_symbols = []high_entropy_sections = []2 unmodified lineswith open(file_path, 'rb') as f:elf = ELFFile(f)for section in elf.iter_sections():sec_name = section.namesec_data = section.data()14 unmodified liness = m.decode('ascii', errors='ignore')if not is_noise_string(s):s_lower = s.lower()if any(trigger in s_lower for trigger in ACCEPT_KEYWORD_TRIGGERS):extracted_text_blocks.append(s)except Exception:passif isinstance(section, SymbolTableSection):for symbol in section.iter_symbols():sym_name = symbol.name11 unmodified lines})except Exception:try:res = subprocess.run(['strings', '-n', '4', file_path], capture_output=True, text=True, errors='ignore', timeout=10)for line in res.stdout.splitlines():7 unmodified linesreturn "\n".join(extracted_text_blocks), suspicious_symbols, high_entropy_sectionsdef brute_force_xor_full(raw_bytes: bytes) -> List[Dict[str, Any]]:results = []sample = raw_bytes[:250000]targets = [b"http://", b"https://", b"discord", b"stuartmods", b"license", b"verify"]28 unmodified linesentropy = calculate_entropy(raw_bytes)text_content = ""if "global-metadata.dat" in file_name:metadata_strings = parse_il2cpp_metadata(file_path)if metadata_strings:text_content = "\n".join(metadata_strings)if not text_content:if file_name.endswith('.so') or b'ELF' in raw_bytes[:4]:extracted_text, elf_syms, high_sec = analyze_elf_binary(file_path)17 unmodified lineselse:text_content = raw_bytes.decode('utf-8', errors='ignore')for m in DISCORD_PATTERN.finditer(text_content):val = m.group()snip = extract_snippet(text_content, m.start(), m.end(), 100)14 unmodified lines"severity": "CRITICAL"})for m in GENERIC_URL_PATTERN.finditer(text_content):val = m.group()if not is_noise_string(val) and "discord" not in val.lower() and "stuartmods" not in val.lower():9 unmodified lines"severity": "HIGH"})base64_matches = re.findall(r'(?:[A-Za-z0-9+/]{4}){6,}(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?', text_content)for b64 in base64_matches[:10]:try:8 unmodified linesexcept Exception:passif file_size <= 5 * 1024 * 1024 and (file_name.endswith('.so') or entropy > 6.8):xor_hits = brute_force_xor_full(raw_bytes)for x_item in xor_hits:19 unmodified linesfor root, _, files in os.walk(extract_folder):for f in files:full_p = os.path.join(root, f)ext = os.path.splitext(f)[1].lower()if ext in IGNORED_EXTENSIONS:continuerel_p = os.path.relpath(full_p, extract_folder).replace('\\', '/')if any(rel_p.startswith(sub) for sub in IGNORED_SUBDIRS):continuefiles_to_scan.append(full_p)total_files = len(files_to_scan)81 unmodified linesawait manager.broadcast_log("INFO", "بدء تحليل ELF Sections واستخراج الرموز وفك التشفير بـ XOR...", 30)report_data = await asyncio.to_thread(run_full_analysis_sync, extract_folder)await manager.broadcast_log("SUCCESS", f"اكتمل التفتيش! تم اكتشاف {report_data['summary']['total_links']} رابط حاسم و {report_data['summary']['total_functions']} دالة مشبوهة.", 100)
app.py+17-16