Spaces:
Paused
Paused
Update app.py
Browse files11 unmodified lines121314151617181920212223242 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616249 unmodified lines11211311411511611711811912012112212312412512612712812913013113213313413513613713816 unmodified lines1551561571581591601611621631641651661671681691701711721731741751762 unmodified lines1791801811821831841851861871882 unmodified lines1911921931941951961971983 unmodified lines2022032042052062072082092102112122132142152162172182192202212222232242252262 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942953 unmodified lines2993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313321 unmodified line3343353363373383393403413423433443453463473483493503513523533543553563573583593 unmodified lines36336436536636736836937037137237337437537637737837938038138238338438538638738838939039113 unmodified lines4054064074084094104115 unmodified lines4174184194204214224234242 unmodified lines4274284294304314324334344354364374389 unmodified lines4484494504514524534549 unmodified lines46446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649711 unmodified linesimport structimport subprocessfrom datetime import datetimefrom typing import List, Dict, Any, Tuplefrom fastapi import FastAPI, UploadFile, File, Request, WebSocket, WebSocketDisconnectfrom fastapi.responses import HTMLResponse, FileResponsefrom fastapi.templating import Jinja2Templatesapp = FastAPI(title="APK & Binary Advanced RE Inspector")WORKSPACE_DIR = "/tmp/re_workspace"OUTPUT_DIR = "/tmp/re_output"2 unmodified linestemplates = Jinja2Templates(directory="templates")# الامتدادات المقتطعة لتوفير الوقت والرام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']# تعابير نمطية مستهدفة بدقةDISCORD_PATTERN = re.compile(r'discord\.(?:gg|com/invite)/[a-zA-Z0-9_-]+', re.IGNORECASE)STUART_PATTERN = re.compile(r'https?://[a-zA-Z0-9.-]*stuartmods[a-zA-Z0-9.-]*\.[a-zA-Z]{2,}[^\s<>"{}|\\^`\']*', re.IGNORECASE)GENERIC_URL_PATTERN = re.compile(r'https?://[^\s<>"{}|\\^`\']+', re.IGNORECASE)EMAIL_PATTERN = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', re.IGNORECASE)# أنماط السياق البرمجي (Code Context Analysis)CODE_CONTEXT_PATTERNS = [(re.compile(r'(?:getKey|get_Key|verify|LicenseManager|NetworkClient|loadUrl)\s*\(\s*["\']([^"\']+)["\']', re.IGNORECASE), "METHOD_CALL"),(re.compile(r'(?:BaseURL|API_URL|ENDPOINT|SERVER_URL|HOST_URL)\s*[:=]\s*["\']([^"\']+)["\']', re.IGNORECASE), "API_ENDPOINT_VAR"),(re.compile(r'const-string\s+v\d+,\s*["\']([^"\']+)["\']', re.IGNORECASE), "SMALI_CONST_STRING")]NETWORK_API_PATTERNS = re.compile(r'(?:HttpURLConnection|OkHttpClient|Retrofit|WebView|loadUrl|HttpClient|curl_easy_init|SSL_read)',re.IGNORECASE)BASE64_PATTERN = re.compile(r'(?:[A-Za-z0-9+/]{4}){5,}(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?')HEX_ESCAPED_PATTERN = re.compile(r'(?:\\x[0-9a-fA-F]{2}){4,}')class ConnectionManager:def __init__(self):49 unmodified linesentropy -= p * math.log2(p)return entropydef rot13(text: str) -> str:trans = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz','NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')return text.translate(trans)def extract_strings_native(file_path: str) -> str:try:res = subprocess.run(['strings', '-n', '4', file_path], capture_output=True, text=True, errors='ignore', timeout=10)return res.stdoutexcept Exception:try:with open(file_path, 'rb') as f:content = f.read()matches = re.findall(rb'[\x20-\x7e]{4,}', content)return "\n".join([m.decode('ascii', errors='ignore') for m in matches])except Exception:return ""def parse_il2cpp_metadata(file_path: str) -> List[str]:extracted_strings = []try:with open(file_path, 'rb') as f:16 unmodified lineslit_len, lit_data_off = struct.unpack("<II", data[sl_offset + i * 8 : sl_offset + i * 8 + 8])if sld_offset + lit_data_off + lit_len <= len(data):s = data[sld_offset + lit_data_off : sld_offset + lit_data_off + lit_len].decode('utf-8', errors='ignore')if len(s.strip()) > 2:extracted_strings.append(s)except Exception:passreturn extracted_stringsdef extract_snippet(text: str, start: int, end: int, margin: int = 100) -> str:s_start = max(0, start - margin)s_end = min(len(text), end + margin)snippet_text = text[s_start:s_end].replace('\n', ' ').replace('\r', ' ')return f"...{snippet_text}..."def brute_force_xor_full(raw_bytes: bytes) -> List[Dict[str, Any]]:"""تطبيق XOR على كامل مفاتيح 1-255 للملفات الصغيرة"""results = []sample = raw_bytes[:200000] # أخذ عينة 200KB للأداء الفائقtargets = [b"http://", b"https://", b"discord", b"stuartmods", b"license", b"verify"]for key in range(1, 256):2 unmodified linesif t in dec.lower():urls = GENERIC_URL_PATTERN.findall(dec.decode('ascii', errors='ignore'))for u in set(urls[:5]):results.append({"key": f"0x{key:02X}","decoded": u})breakreturn results2 unmodified linesfile_name = os.path.basename(file_path).lower()file_size = os.path.getsize(file_path)links_found = []suspicious_findings = []encrypted_findings = []try:3 unmodified linesentropy = calculate_entropy(raw_bytes)text_content = ""# 1. تحليل 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)# 2. الملفات الثنائية (.so, .dex, .dat)if not text_content:if file_name.endswith(('.so', '.dex', '.dat')) or b'\x00' in raw_bytes[:512]:text_content = extract_strings_native(file_path)else:text_content = raw_bytes.decode('utf-8', errors='ignore')# أ) البحث في روابط Discord وسيرفر stuartmods (CRITICAL)for m in DISCORD_PATTERN.finditer(text_content):val = m.group()snip = extract_snippet(text_content, m.start(), m.end(), 100)links_found.append({"type": "DISCORD_LINK","value": val,"snippet": snip,"severity": "CRITICAL"2 unmodified linesfor m in STUART_PATTERN.finditer(text_content):val = m.group()snip = extract_snippet(text_content, m.start(), m.end(), 100)links_found.append({"type": "STUARTMODS_SERVER","value": val,"snippet": snip,"severity": "CRITICAL"})# ب) البحث في الروابط العامة والربط بالسياق البرمجي (HIGH / MEDIUM)for m in GENERIC_URL_PATTERN.finditer(text_content):val = m.group()if "discord" not in val.lower() and "stuartmods" not in val.lower():snip = extract_snippet(text_content, m.start(), m.end(), 100)# تقييم ذكي بناءً على الكلمات المجاورةsnip_lower = snip.lower()is_high = any(k in snip_lower for k in ["verify", "license", "activation", "api", "auth", "getkey"])links_found.append({"type": "URL","value": val,"snippet": snip,"severity": "HIGH" if is_high else "MEDIUM"})# ج) تحليل السياق البرمجي والدوال الشبكية (Suspicious Files)has_net_api = bool(NETWORK_API_PATTERNS.search(text_content))for pattern, ctx_type in CODE_CONTEXT_PATTERNS:for m in pattern.finditer(text_content):matched_val = m.group(1) if m.groups() else m.group()snip = extract_snippet(text_content, m.start(), m.end(), 100)suspicious_findings.append({"type": f"CODE_CONTEXT_{ctx_type}","value": matched_val,"snippet": snip,"severity": "HIGH" if has_net_api else "MEDIUM"})# د) فك التشفير المتقدم (ROT13, Base64, Hex, XOR, Zlib)# Base64for b64 in BASE64_PATTERN.findall(text_content)[:10]:try:dec = base64.b64decode(b64).decode('utf-8', errors='ignore')if any(k in dec.lower() for k in ['http', 'discord', 'stuartmods', 'key', 'license', 'verify']):encrypted_findings.append({"method": "Base64 Decoded","value": f"{b64} -> {dec}","snippet": f"مفكوك Base64: {dec}","severity": "HIGH" if "discord" in dec.lower() or "http" in dec.lower() else "MEDIUM"})except Exception:pass# ROT13 Testif "discord" in rot13(text_content).lower() or "stuartmods" in rot13(text_content).lower():encrypted_findings.append({"method": "ROT13 Cipher","value": "اكتشاف نصوص مشفرة بـ ROT13","snippet": "تم رصد سلاسل نصية مفكوكة بـ ROT13 تحتوي على روابط أو مفاتيح","severity": "HIGH"})# XOR Full Brute Force للملفات < 5MBif file_size <= 5 * 1024 * 1024 and (file_name.endswith('.so') or entropy > 6.0):xor_hits = brute_force_xor_full(raw_bytes)for x_item in xor_hits:encrypted_findings.append({3 unmodified lines"severity": "CRITICAL" if "discord" in x_item['decoded'].lower() or "stuartmods" in x_item['decoded'].lower() else "HIGH"})# هـ) فحص الملفات عالية العشوائية (Entropy > 7.5)if entropy > 7.5:suggested_decomp = "XOR / Custom Packer"try:zlib.decompress(raw_bytes)suggested_decomp = "Zlib Compressed"except Exception:try:gzip.decompress(raw_bytes)suggested_decomp = "Gzip Compressed"except Exception:passencrypted_findings.append({"method": f"High Entropy ({entropy:.2f})","value": f"ملف مشفر/مضغوط: {rel_path}","snippet": f"العشوائية مرتفعة جداً ({entropy:.2f}). طريقة الفك المقترحة: {suggested_decomp}","severity": "HIGH"})except Exception:passreturn {"file": rel_path,"links": links_found,"suspicious": suspicious_findings,"encrypted": encrypted_findings}def run_full_analysis_sync(extract_folder: str) -> Dict[str, Any]:1 unmodified linefor 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)all_links = []all_suspicious = []all_encrypted = []stats = {"total_files": total_files,"total_links": 0,"total_suspicious": 0,"total_encrypted": 0,"critical_count": 0,"high_count": 0,3 unmodified linesfor file_p in files_to_scan:res = analyze_file_deep(file_p, extract_folder)if res["links"]:stats["total_links"] += len(res["links"])for l in res["links"]:stats[f"{l['severity'].lower()}_count"] = stats.get(f"{l['severity'].lower()}_count", 0) + 1all_links.append({"file": res["file"], "items": res["links"]})if res["suspicious"]:stats["total_suspicious"] += len(res["suspicious"])for s in res["suspicious"]:stats[f"{s['severity'].lower()}_count"] = stats.get(f"{s['severity'].lower()}_count", 0) + 1all_suspicious.append({"file": res["file"], "items": res["suspicious"]})if res["encrypted"]:stats["total_encrypted"] += len(res["encrypted"])for e in res["encrypted"]:stats[f"{e['severity'].lower()}_count"] = stats.get(f"{e['severity'].lower()}_count", 0) + 1all_encrypted.append({"file": res["file"], "items": res["encrypted"]})return {"summary": stats,"links_found": all_links,"suspicious_files": all_suspicious,"encrypted_files": all_encrypted}@app.get("/", response_class=HTMLResponse)13 unmodified linesasync def analyze_files(files: List[UploadFile] = File(...)):clean_workspace()await manager.broadcast_log("INFO", f"بدء استقبال {len(files)} ملف/ملفات...", 5)extract_folder = os.path.join(WORKSPACE_DIR, "extracted")os.makedirs(extract_folder, exist_ok=True)5 unmodified lineswhile chunk := await uploaded_file.read(4 * 1024 * 1024):buffer.write(chunk)if uploaded_file.filename.lower().endswith(".zip") or uploaded_file.filename.lower().endswith(".apk"):await manager.broadcast_log("INFO", f"جاري فك ضغط الأرشيف: {uploaded_file.filename}...", 15)try:with zipfile.ZipFile(file_path, 'r') as zf:zf.extractall(extract_folder)2 unmodified lineselse:shutil.copy(file_path, os.path.join(extract_folder, uploaded_file.filename))await manager.broadcast_log("INFO", "بدء الفحص البرمجي المتطور وتتبع الدوال والتشفير...", 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_suspicious']} ملف مشتبه به.", 100)json_path = os.path.join(OUTPUT_DIR, "analysis_report.json")with open(json_path, "w", encoding="utf-8") as f:9 unmodified lines<html lang="ar" dir="rtl"><head><meta charset="UTF-8"><title>Advanced RE Inspection Report</title><style>body {{ font-family: system-ui, sans-serif; background: #0f172a; color: #f8fafc; padding: 20px; line-height: 1.5; }}.card {{ background: #1e293b; padding: 16px; border-radius: 10px; margin-bottom: 16px; border: 1px solid #334155; }}9 unmodified lines</style></head><body><h1>تقرير التفتيش البرمجي وفحص الروابط والتشفير</h1><div class="card"><h3>الملخص الإحصائي</h3><div class="stats-grid"><div class="stat-card">الملفات المفحوصة<br><b>{summary['total_files']}</b></div><div class="stat-card">الروابط المكتشفة<br><b>{summary['total_links']}</b></div><div class="stat-card">الملفات المشبوهة<br><b>{summary['total_suspicious']}</b></div><div class="stat-card">حاسمة (CRITICAL)<br><b style="color:#dc2626;">{summary['critical_count']}</b></div></div></div><h2>1. الروابط المكتشفة (Links Found)</h2>"""for file_item in data['links_found']:html += f"""<div class="card"><h4 style="color:#facc15;">📁 {file_item['file']}</h4>"""for item in file_item['items']:html += f"""<div class="snippet"><span class="badge {item['severity']}">{item['severity']}</span> <b>[{item['type']}]</b>: {item['value']}<br><span style="color:#94a3b8;">{item['snippet']}</span></div>"""html += "</div>"html += "<h2>2. الملفات المشبوهة (Suspicious Files)</h2>"for file_item in data['suspicious_files']:html += f"""<div class="card"><h4 style="color:#facc15;">📁 {file_item['file']}</h4>"""for item in file_item['items']:html += f"""<div class="snippet"><span class="badge {item['severity']}">{item['severity']}</span> <b>[{item['type']}]</b>: {item['value']}<br><span style="color:#94a3b8;">{item['snippet']}</span></div>"""html += "</div>"html += "<h2>3. الملفات المشفرة (Encrypted Files)</h2>"for file_item in data['encrypted_files']:html += f"""<div class="card"><h4 style="color:#facc15;">📁 {file_item['file']}</h4>"""for item in file_item['items']:html += f"""<div class="snippet"><span class="badge {item['severity']}">{item['severity']}</span> <b>[{item['method']}]</b>: {item['value']}<br><span style="color:#94a3b8;">{item['snippet']}</span></div>"""11 unmodified lines1213141516171819202122232425262728293031322 unmodified lines353637383940414243444546474849505152535455565758596049 unmodified lines11011111211311411511611711811912012112212312412512612712812913013116 unmodified lines1481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412 unmodified lines2442452462472482492502512522532542 unmodified lines2572582592602612622632643 unmodified lines2682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083092 unmodified lines3123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573 unmodified lines3613623633643653663673683693703713723733741 unmodified line3763773783793803813823833843853863873883893903913923933943953963 unmodified lines40040140240340440540640740840941041141241341441541641741841942042142242342442542642742813 unmodified lines4424434444454464474485 unmodified lines4544554564574584594604612 unmodified lines4644654664674684694704714724734744759 unmodified lines4854864874884894904919 unmodified lines50150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353411 unmodified linesimport structimport subprocessfrom datetime import datetimefrom typing import List, Dict, Any, Tuple, Setfrom fastapi import FastAPI, UploadFile, File, Request, WebSocket, WebSocketDisconnectfrom fastapi.responses import HTMLResponse, FileResponsefrom fastapi.templating import Jinja2Templatesfrom elftools.elf.elffile import ELFFilefrom elftools.elf.sections import SymbolTableSectiontry:import cxxfiltexcept ImportError:cxxfilt = Noneapp = FastAPI(title="Professional ELF & Native RE Inspector")WORKSPACE_DIR = "/tmp/re_workspace"OUTPUT_DIR = "/tmp/re_output"2 unmodified linestemplates = Jinja2Templates(directory="templates")# 1. قائمة التصفية والاستبعاد الصارمة للقضاء على النويز وHTML/CSSNOISE_REJECT_PATTERNS = ['<', '>', 'style=', 'font-family', 'margin-top', 'padding-', 'background-color','display:', 'position:', 'color:', 'width:', 'height:', 'border:', '.css', '.js','.png', '.jpg', '.jpeg', '.gif', '.svg', 'http://www.w3.org/', 'xmlns:']ALLOWED_SECTIONS = {'.rodata', '.data', '.dynstr', '.strtab'}# 2. التعابير النمطية المستهدفةDISCORD_PATTERN = re.compile(r'discord\.(?:gg|com/invite)/[a-zA-Z0-9_-]+', re.IGNORECASE)STUART_PATTERN = re.compile(r'https?://[a-zA-Z0-9.-]*stuartmods[a-zA-Z0-9.-]*\.[a-zA-Z]{2,}[^\s<>"{}|\\^`\']*', re.IGNORECASE)GENERIC_URL_PATTERN = re.compile(r'https?://[^\s<>"{}|\\^`\']+', re.IGNORECASE)ACCEPT_KEYWORD_TRIGGERS = ['http://', 'https://', 'discord.gg', 'discord.com', 'stuartmods','api.', 'verify', 'license', 'activation', 'key', 'password', 'check_key', 'auth']FUNCTION_TRIGGER_KEYWORDS = ['check', 'verify', 'license', 'auth', 'java_', 'jni_onload', 'stuart', 'key']class ConnectionManager:def __init__(self):49 unmodified linesentropy -= p * math.log2(p)return entropydef is_noise_string(text: str) -> bool:"""فلتر صارم لاستبعاد نصوص HTML/CSS والأيقونات"""text_lower = text.lower()for noise in NOISE_REJECT_PATTERNS:if noise in text_lower:return Truereturn Falsedef extract_snippet(text: str, start: int, end: int, margin: int = 100) -> str:s_start = max(0, start - margin)s_end = min(len(text), end + margin)clean_text = text[s_start:s_end].replace('\n', ' ').replace('\r', ' ')return 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:16 unmodified lineslit_len, lit_data_off = struct.unpack("<II", data[sl_offset + i * 8 : sl_offset + i * 8 + 8])if sld_offset + lit_data_off + lit_len <= len(data):s = data[sld_offset + lit_data_off : sld_offset + lit_data_off + lit_len].decode('utf-8', errors='ignore')if len(s.strip()) > 3 and not is_noise_string(s):extracted_strings.append(s)except Exception:passreturn extracted_stringsdef demangle_symbol_name(sym_name: str) -> str:"""فك تزييف أسماء C++ Mangled Symbols"""if not sym_name:return ""if cxxfilt:try:return cxxfilt.demangle(sym_name)except Exception:passreturn 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 = []try:with open(file_path, 'rb') as f:elf = ELFFile(f)# 1. استخراج الأقسام الحيوية فقط وسحب النصوص منهاfor section in elf.iter_sections():sec_name = section.namesec_data = section.data()sec_entropy = calculate_entropy(sec_data)if sec_entropy > 7.4 and section.size() > 1024:high_entropy_sections.append({"section_name": sec_name,"size": section.size(),"entropy": round(sec_entropy, 2),"suggested_action": "XOR Brute-force / Custom Unpacker Required"})if sec_name in ALLOWED_SECTIONS:matches = re.findall(rb'[\x20-\x7e]{4,}', sec_data)for m in matches:try:s = 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.nameif not sym_name:continuesym_lower = sym_name.lower()if any(kw in sym_lower for kw in FUNCTION_TRIGGER_KEYWORDS):demangled = demangle_symbol_name(sym_name)suspicious_symbols.append({"mangled": sym_name,"demangled": demangled,"section": sec_name,"binding": symbol['st_info']['bind']})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():if not is_noise_string(line):line_lower = line.lower()if any(trigger in line_lower for trigger in ACCEPT_KEYWORD_TRIGGERS):extracted_text_blocks.append(line)except Exception:passreturn "\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"]for key in range(1, 256):2 unmodified linesif t in dec.lower():urls = GENERIC_URL_PATTERN.findall(dec.decode('ascii', errors='ignore'))for u in set(urls[:5]):if not is_noise_string(u):results.append({"key": f"0x{key:02X}","decoded": u})breakreturn results2 unmodified linesfile_name = os.path.basename(file_path).lower()file_size = os.path.getsize(file_path)critical_links = []suspicious_functions = []encrypted_findings = []try:3 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)text_content = extracted_textfor sym in elf_syms:suspicious_functions.append({"function_name": sym["demangled"] or sym["mangled"],"mangled_symbol": sym["mangled"],"section": sym["section"],"severity": "HIGH" if "verify" in sym["mangled"].lower() or "license" in sym["mangled"].lower() else "MEDIUM"})for sec in high_sec:encrypted_findings.append({"method": f"High Entropy Section ({sec['section_name']})","value": f"الحجم: {sec['size']} bytes | العشوائية: {sec['entropy']}","snippet": sec["suggested_action"],"severity": "HIGH"})else: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)critical_links.append({"type": "DISCORD_INVITE","value": val,"snippet": snip,"severity": "CRITICAL"2 unmodified linesfor m in STUART_PATTERN.finditer(text_content):val = m.group()snip = extract_snippet(text_content, m.start(), m.end(), 100)critical_links.append({"type": "STUARTMODS_SERVER","value": val,"snippet": snip,"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():snip = extract_snippet(text_content, m.start(), m.end(), 100)snip_lower = snip.lower()is_high = any(k in snip_lower for k in ["verify", "license", "activation", "api", "auth", "getkey"])if is_high:critical_links.append({"type": "VERIFICATION_API_URL","value": val,"snippet": snip,"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:dec = base64.b64decode(b64).decode('utf-8', errors='ignore')if not is_noise_string(dec) and any(k in dec.lower() for k in ['http', 'discord', 'stuartmods', 'key', 'license', 'verify']):encrypted_findings.append({"method": "Base64 Decoded","value": f"{b64} -> {dec}","snippet": f"فك ترميز Base64: {dec}","severity": "CRITICAL" if "discord" in dec.lower() or "stuartmods" in dec.lower() else "HIGH"})except 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:encrypted_findings.append({3 unmodified lines"severity": "CRITICAL" if "discord" in x_item['decoded'].lower() or "stuartmods" in x_item['decoded'].lower() else "HIGH"})except Exception:passreturn {"file": rel_path,"critical_links": critical_links,"suspicious_functions": suspicious_functions,"encrypted_sections": encrypted_findings}def run_full_analysis_sync(extract_folder: str) -> Dict[str, Any]:1 unmodified linefor 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)all_links = []all_functions = []all_encrypted = []stats = {"total_files": total_files,"total_links": 0,"total_functions": 0,"total_encrypted": 0,"critical_count": 0,"high_count": 0,3 unmodified linesfor file_p in files_to_scan:res = analyze_file_deep(file_p, extract_folder)if res["critical_links"]:stats["total_links"] += len(res["critical_links"])for l in res["critical_links"]:stats[f"{l['severity'].lower()}_count"] = stats.get(f"{l['severity'].lower()}_count", 0) + 1all_links.append({"file": res["file"], "items": res["critical_links"]})if res["suspicious_functions"]:stats["total_functions"] += len(res["suspicious_functions"])for f_item in res["suspicious_functions"]:stats[f"{f_item['severity'].lower()}_count"] = stats.get(f"{f_item['severity'].lower()}_count", 0) + 1all_functions.append({"file": res["file"], "items": res["suspicious_functions"]})if res["encrypted_sections"]:stats["total_encrypted"] += len(res["encrypted_sections"])for e in res["encrypted_sections"]:stats[f"{e['severity'].lower()}_count"] = stats.get(f"{e['severity'].lower()}_count", 0) + 1all_encrypted.append({"file": res["file"], "items": res["encrypted_sections"]})return {"summary": stats,"critical_links": all_links,"suspicious_functions": all_functions,"encrypted_sections": all_encrypted}@app.get("/", response_class=HTMLResponse)13 unmodified linesasync def analyze_files(files: List[UploadFile] = File(...)):clean_workspace()await manager.broadcast_log("INFO", f"بدء استقبال {len(files)} ملف/ملفات للتفتيش...", 5)extract_folder = os.path.join(WORKSPACE_DIR, "extracted")os.makedirs(extract_folder, exist_ok=True)5 unmodified lineswhile chunk := await uploaded_file.read(4 * 1024 * 1024):buffer.write(chunk)if uploaded_file.filename.lower().endswith((".zip", ".apk")):await manager.broadcast_log("INFO", f"جاري فك الأرشيف المرفوع: {uploaded_file.filename}...", 15)try:with zipfile.ZipFile(file_path, 'r') as zf:zf.extractall(extract_folder)2 unmodified lineselse:shutil.copy(file_path, os.path.join(extract_folder, uploaded_file.filename))await 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)json_path = os.path.join(OUTPUT_DIR, "analysis_report.json")with open(json_path, "w", encoding="utf-8") as f:9 unmodified lines<html lang="ar" dir="rtl"><head><meta charset="UTF-8"><title>Professional ELF RE Inspection Report</title><style>body {{ font-family: system-ui, sans-serif; background: #0f172a; color: #f8fafc; padding: 20px; line-height: 1.5; }}.card {{ background: #1e293b; padding: 16px; border-radius: 10px; margin-bottom: 16px; border: 1px solid #334155; }}9 unmodified lines</style></head><body><h1>تقرير التفتيش الهندسي ومحلل المكتبات الأصلية (ELF / SO)</h1><div class="card"><h3>الملخص الإحصائي</h3><div class="stats-grid"><div class="stat-card">الملفات المفحوصة<br><b>{summary['total_files']}</b></div><div class="stat-card">الروابط الحاسمة<br><b>{summary['total_links']}</b></div><div class="stat-card">الدوال المستخرجة<br><b>{summary['total_functions']}</b></div><div class="stat-card">حاسمة (CRITICAL)<br><b style="color:#dc2626;">{summary['critical_count']}</b></div></div></div><h2>1. الروابط الحرجة (Critical Links)</h2>"""for file_item in data['critical_links']:html += f"""<div class="card"><h4 style="color:#facc15;">📁 {file_item['file']}</h4>"""for item in file_item['items']:html += f"""<div class="snippet"><span class="badge {item['severity']}">{item['severity']}</span> <b>[{item['type']}]</b>: {item['value']}<br><span style="color:#94a3b8;">{item['snippet']}</span></div>"""html += "</div>"html += "<h2>2. الدوال والرموز المشبوهة (Suspicious Functions)</h2>"for file_item in data['suspicious_functions']:html += f"""<div class="card"><h4 style="color:#facc15;">📁 {file_item['file']}</h4>"""for item in file_item['items']:html += f"""<div class="snippet"><span class="badge {item['severity']}">{item['severity']}</span> <b>[Function]</b>: {item['function_name']}<br><span style="color:#94a3b8;">Symbol: {item['mangled_symbol']} | Section: {item['section']}</span></div>"""html += "</div>"html += "<h2>3. الأقسام المشفّرة ومخرجات فك التشفير (Encrypted Sections)</h2>"for file_item in data['encrypted_sections']:html += f"""<div class="card"><h4 style="color:#facc15;">📁 {file_item['file']}</h4>"""for item in file_item['items']:html += f"""<div class="snippet"><span class="badge {item['severity']}">{item['severity']}</span> <b>[{item['method']}]</b>: {item['value']}<br><span style="color:#94a3b8;">{item['snippet']}</span></div>"""
app.py+203-166