Skydata001 commited on
Commit
e092c28
·
verified ·
1 Parent(s): 720f20f

Upload 7 files

Browse files
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # APK Deep Diff Analyzer Package
src/apk_analyzer.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ APK Deep Diff Analyzer - Main Analysis Engine
3
+ """
4
+ import os
5
+ import zipfile
6
+ import re
7
+ from typing import Dict, Any, List, Tuple, Set
8
+ from concurrent.futures import ThreadPoolExecutor, as_completed
9
+
10
+ from utils import (
11
+ get_file_hash, get_file_size_formatted, extract_apk,
12
+ list_files_recursive, get_zip_entries, calculate_similarity,
13
+ create_temp_dir, cleanup_temp_dir, get_apk_info
14
+ )
15
+ from manifest_parser import compare_manifests, ManifestAnalyzer
16
+ from dex_analyzer import analyze_all_dex, find_dex_files, DexAnalyzer
17
+ from signature_analyzer import compare_signatures, SignatureAnalyzer
18
+
19
+
20
+ class APKDeepAnalyzer:
21
+ """Main engine for deep APK analysis and comparison."""
22
+
23
+ def __init__(self, orig_apk: str, mod_apk: str, progress_callback=None):
24
+ self.orig_apk = orig_apk
25
+ self.mod_apk = mod_apk
26
+ self.progress_callback = progress_callback
27
+ self.orig_temp_dir = None
28
+ self.mod_temp_dir = None
29
+ self.results = {}
30
+
31
+ def _update_progress(self, stage: int, message: str = ""):
32
+ """Update progress via callback."""
33
+ if self.progress_callback:
34
+ self.progress_callback(stage, message)
35
+
36
+ def analyze(self) -> Dict[str, Any]:
37
+ """Run complete analysis pipeline."""
38
+ try:
39
+ self._update_progress(0, "جاري رفع الملفات...")
40
+
41
+ # Stage 1: Validate APKs
42
+ self._update_progress(1, "التحقق من صحة ملفات APK...")
43
+ if not self._validate_apk(self.orig_apk):
44
+ raise ValueError("ملف APK الأصلي غير صالح (Invalid Original APK)")
45
+ if not self._validate_apk(self.mod_apk):
46
+ raise ValueError("ملف APK المعدل غير صالح (Invalid Modified APK)")
47
+
48
+ # Stage 2: Extract APKs
49
+ self._update_progress(2, "فك ضغط ملفات APK...")
50
+ self.orig_temp_dir = create_temp_dir("orig_")
51
+ self.mod_temp_dir = create_temp_dir("mod_")
52
+
53
+ extract_apk(self.orig_apk, self.orig_temp_dir)
54
+ extract_apk(self.mod_apk, self.mod_temp_dir)
55
+
56
+ # Stage 3: ZIP structure analysis
57
+ self._update_progress(3, "تحليل بنية ZIP...")
58
+ orig_zip = get_zip_entries(self.orig_apk)
59
+ mod_zip = get_zip_entries(self.mod_apk)
60
+
61
+ # Stage 4: File comparison
62
+ self._update_progress(4, "مقارنة الملفات...")
63
+ file_comparison = self._compare_files()
64
+
65
+ # Stage 5: Manifest analysis
66
+ self._update_progress(5, "تحليل AndroidManifest.xml...")
67
+ manifest_comparison = self._analyze_manifest()
68
+
69
+ # Stage 6: DEX analysis
70
+ self._update_progress(6, "تحليل ملفات DEX...")
71
+ dex_analysis = self._analyze_dex()
72
+
73
+ # Stage 7: Native libraries
74
+ self._update_progress(7, "تحليل المكتبات الأصلية...")
75
+ native_libs = self._analyze_native_libraries()
76
+
77
+ # Stage 8: Resources
78
+ self._update_progress(8, "تحليل الموارد...")
79
+ resources = self._analyze_resources()
80
+
81
+ # Stage 9: Signature
82
+ self._update_progress(9, "تحليل التوقيع...")
83
+ signature_comparison = compare_signatures(self.orig_apk, self.mod_apk)
84
+
85
+ # Stage 10: Strings & URLs
86
+ self._update_progress(10, "تحليل النصوص والروابط...")
87
+ strings_analysis = self._analyze_strings()
88
+
89
+ # Stage 11: Suspicious changes
90
+ self._update_progress(11, "البحث عن تغييرات مشبوهة...")
91
+ suspicious = self._detect_suspicious(
92
+ manifest_comparison, dex_analysis, native_libs,
93
+ signature_comparison, file_comparison
94
+ )
95
+
96
+ # Compile results
97
+ self.results = {
98
+ "original_info": get_apk_info(self.orig_apk),
99
+ "modified_info": get_apk_info(self.mod_apk),
100
+ "zip_comparison": {
101
+ "original_entries": len(orig_zip),
102
+ "modified_entries": len(mod_zip),
103
+ },
104
+ "file_comparison": file_comparison,
105
+ "manifest_comparison": manifest_comparison,
106
+ "dex_analysis": dex_analysis,
107
+ "native_libraries": native_libs,
108
+ "resources": resources,
109
+ "signature_comparison": signature_comparison,
110
+ "strings_analysis": strings_analysis,
111
+ "suspicious_changes": suspicious,
112
+ }
113
+
114
+ self._update_progress(12, "اكتمل التحليل!")
115
+ return self.results
116
+
117
+ except Exception as e:
118
+ self.results = {"error": str(e)}
119
+ return self.results
120
+ finally:
121
+ self._cleanup()
122
+
123
+ def _validate_apk(self, apk_path: str) -> bool:
124
+ """Validate APK file."""
125
+ if not os.path.exists(apk_path):
126
+ return False
127
+ if not zipfile.is_zipfile(apk_path):
128
+ return False
129
+ try:
130
+ with zipfile.ZipFile(apk_path, 'r') as zf:
131
+ # Check for AndroidManifest.xml
132
+ if "AndroidManifest.xml" not in zf.namelist():
133
+ return False
134
+ # Check for at least one DEX file
135
+ has_dex = any(name.endswith('.dex') for name in zf.namelist())
136
+ if not has_dex:
137
+ return False
138
+ return True
139
+ except Exception:
140
+ return False
141
+
142
+ def _compare_files(self) -> Dict[str, Any]:
143
+ """Compare all files between two extracted APKs."""
144
+ orig_files = list_files_recursive(self.orig_temp_dir)
145
+ mod_files = list_files_recursive(self.mod_temp_dir)
146
+
147
+ orig_map = {path: (size, sha) for path, size, sha in orig_files}
148
+ mod_map = {path: (size, sha) for path, size, sha in mod_files}
149
+
150
+ all_paths = set(orig_map.keys()) | set(mod_map.keys())
151
+
152
+ comparison = {
153
+ "added": [],
154
+ "removed": [],
155
+ "modified": [],
156
+ "unchanged": [],
157
+ "details": [],
158
+ }
159
+
160
+ for path in sorted(all_paths):
161
+ in_orig = path in orig_map
162
+ in_mod = path in mod_map
163
+
164
+ if in_orig and not in_mod:
165
+ comparison["removed"].append(path)
166
+ comparison["details"].append({
167
+ "path": path,
168
+ "original_size": orig_map[path][0],
169
+ "modified_size": 0,
170
+ "original_sha256": orig_map[path][1],
171
+ "modified_sha256": "",
172
+ "status": "Removed",
173
+ })
174
+ elif in_mod and not in_orig:
175
+ comparison["added"].append(path)
176
+ comparison["details"].append({
177
+ "path": path,
178
+ "original_size": 0,
179
+ "modified_size": mod_map[path][0],
180
+ "original_sha256": "",
181
+ "modified_sha256": mod_map[path][1],
182
+ "status": "Added",
183
+ })
184
+ else:
185
+ orig_size, orig_sha = orig_map[path]
186
+ mod_size, mod_sha = mod_map[path]
187
+
188
+ if orig_sha == mod_sha:
189
+ comparison["unchanged"].append(path)
190
+ status = "Unchanged"
191
+ else:
192
+ comparison["modified"].append(path)
193
+ status = "Modified"
194
+
195
+ comparison["details"].append({
196
+ "path": path,
197
+ "original_size": orig_size,
198
+ "modified_size": mod_size,
199
+ "original_sha256": orig_sha,
200
+ "modified_sha256": mod_sha,
201
+ "status": status,
202
+ "similarity": calculate_similarity(orig_size, mod_size, orig_sha, mod_sha),
203
+ })
204
+
205
+ comparison["summary"] = {
206
+ "total": len(all_paths),
207
+ "added": len(comparison["added"]),
208
+ "removed": len(comparison["removed"]),
209
+ "modified": len(comparison["modified"]),
210
+ "unchanged": len(comparison["unchanged"]),
211
+ }
212
+
213
+ return comparison
214
+
215
+ def _analyze_manifest(self) -> Dict[str, Any]:
216
+ """Analyze and compare AndroidManifest.xml."""
217
+ orig_manifest = os.path.join(self.orig_temp_dir, "AndroidManifest.xml")
218
+ mod_manifest = os.path.join(self.mod_temp_dir, "AndroidManifest.xml")
219
+
220
+ if os.path.exists(orig_manifest) and os.path.exists(mod_manifest):
221
+ return compare_manifests(orig_manifest, mod_manifest)
222
+ return {"error": "AndroidManifest.xml not found"}
223
+
224
+ def _analyze_dex(self) -> Dict[str, Any]:
225
+ """Analyze DEX files."""
226
+ orig_dex = analyze_all_dex(self.orig_temp_dir)
227
+ mod_dex = analyze_all_dex(self.mod_temp_dir)
228
+
229
+ # Compare DEX files
230
+ orig_files = set(orig_dex["dex_files"].keys())
231
+ mod_files = set(mod_dex["dex_files"].keys())
232
+
233
+ dex_comparison = {
234
+ "original_count": orig_dex["dex_count"],
235
+ "modified_count": mod_dex["dex_count"],
236
+ "added": sorted(list(mod_files - orig_files)),
237
+ "removed": sorted(list(orig_files - mod_files)),
238
+ "common": sorted(list(orig_files & mod_files)),
239
+ }
240
+
241
+ # Compare common DEX files
242
+ for fname in dex_comparison["common"]:
243
+ orig_header = orig_dex["dex_files"][fname].get("header", {})
244
+ mod_header = mod_dex["dex_files"][fname].get("header", {})
245
+ if orig_header != mod_header:
246
+ dex_comparison["modified"] = dex_comparison.get("modified", []) + [fname]
247
+
248
+ return {
249
+ "dex_count": max(orig_dex["dex_count"], mod_dex["dex_count"]),
250
+ "dex_files": {**orig_dex["dex_files"], **mod_dex["dex_files"]},
251
+ "comparison": dex_comparison,
252
+ "all_strings": list(set(orig_dex["all_strings"]) | set(mod_dex["all_strings"])),
253
+ "all_urls": list(set(orig_dex["all_urls"]) | set(mod_dex["all_urls"])),
254
+ "all_domains": list(set(orig_dex["all_domains"]) | set(mod_dex["all_domains"])),
255
+ "all_ips": list(set(orig_dex["all_ips"]) | set(mod_dex["all_ips"])),
256
+ "all_suspicious": list(set(orig_dex["all_suspicious"]) | set(mod_dex["all_suspicious"])),
257
+ }
258
+
259
+ def _analyze_native_libraries(self) -> Dict[str, Any]:
260
+ """Analyze native libraries."""
261
+ def get_libs(temp_dir: str) -> Dict[str, Dict[str, Any]]:
262
+ libs = {}
263
+ lib_dir = os.path.join(temp_dir, "lib")
264
+ if os.path.exists(lib_dir):
265
+ for arch in os.listdir(lib_dir):
266
+ arch_dir = os.path.join(lib_dir, arch)
267
+ if os.path.isdir(arch_dir):
268
+ for f in os.listdir(arch_dir):
269
+ if f.endswith('.so'):
270
+ filepath = os.path.join(arch_dir, f)
271
+ libs[f"{arch}/{f}"] = {
272
+ "path": filepath,
273
+ "size": os.path.getsize(filepath),
274
+ "sha256": get_file_hash(filepath),
275
+ "architecture": arch,
276
+ }
277
+ return libs
278
+
279
+ orig_libs = get_libs(self.orig_temp_dir)
280
+ mod_libs = get_libs(self.mod_temp_dir)
281
+
282
+ all_keys = set(orig_libs.keys()) | set(mod_libs.keys())
283
+
284
+ result = {
285
+ "original": list(orig_libs.keys()),
286
+ "modified": list(mod_libs.keys()),
287
+ "added": [],
288
+ "removed": [],
289
+ "modified": [],
290
+ "details": [],
291
+ }
292
+
293
+ for key in sorted(all_keys):
294
+ if key in mod_libs and key not in orig_libs:
295
+ result["added"].append(key)
296
+ result["details"].append({
297
+ "name": key,
298
+ "status": "Added",
299
+ "modified_size": mod_libs[key]["size"],
300
+ })
301
+ elif key in orig_libs and key not in mod_libs:
302
+ result["removed"].append(key)
303
+ result["details"].append({
304
+ "name": key,
305
+ "status": "Removed",
306
+ "original_size": orig_libs[key]["size"],
307
+ })
308
+ else:
309
+ if orig_libs[key]["sha256"] != mod_libs[key]["sha256"]:
310
+ result["modified"].append(key)
311
+ status = "Modified"
312
+ else:
313
+ status = "Unchanged"
314
+ result["details"].append({
315
+ "name": key,
316
+ "status": status,
317
+ "original_size": orig_libs[key]["size"],
318
+ "modified_size": mod_libs[key]["size"],
319
+ "original_sha256": orig_libs[key]["sha256"],
320
+ "modified_sha256": mod_libs[key]["sha256"],
321
+ })
322
+
323
+ return result
324
+
325
+ def _analyze_resources(self) -> Dict[str, Any]:
326
+ """Analyze resources (res, assets, resources.arsc)."""
327
+ def analyze_dir(temp_dir: str, dir_name: str) -> Dict[str, Any]:
328
+ result = {"files": [], "count": 0}
329
+ target = os.path.join(temp_dir, dir_name)
330
+ if os.path.exists(target):
331
+ for root, dirs, files in os.walk(target):
332
+ for f in files:
333
+ filepath = os.path.join(root, f)
334
+ rel = os.path.relpath(filepath, target)
335
+ result["files"].append({
336
+ "name": f"{dir_name}/{rel}",
337
+ "size": os.path.getsize(filepath),
338
+ "sha256": get_file_hash(filepath),
339
+ })
340
+ result["count"] = len(result["files"])
341
+ return result
342
+
343
+ orig_res = analyze_dir(self.orig_temp_dir, "res")
344
+ mod_res = analyze_dir(self.mod_temp_dir, "res")
345
+ orig_assets = analyze_dir(self.orig_temp_dir, "assets")
346
+ mod_assets = analyze_dir(self.mod_temp_dir, "assets")
347
+
348
+ # resources.arsc
349
+ orig_arsc = os.path.join(self.orig_temp_dir, "resources.arsc")
350
+ mod_arsc = os.path.join(self.mod_temp_dir, "resources.arsc")
351
+
352
+ arsc_info = {
353
+ "original_exists": os.path.exists(orig_arsc),
354
+ "modified_exists": os.path.exists(mod_arsc),
355
+ "original_size": os.path.getsize(orig_arsc) if os.path.exists(orig_arsc) else 0,
356
+ "modified_size": os.path.getsize(mod_arsc) if os.path.exists(mod_arsc) else 0,
357
+ }
358
+
359
+ return {
360
+ "res": {"original": orig_res, "modified": mod_res},
361
+ "assets": {"original": orig_assets, "modified": mod_assets},
362
+ "resources_arsc": arsc_info,
363
+ }
364
+
365
+ def _analyze_strings(self) -> Dict[str, Any]:
366
+ """Extract and compare strings from both APKs."""
367
+ # Collect all strings from file comparison
368
+ orig_strings = set()
369
+ mod_strings = set()
370
+
371
+ # Extract strings from text files
372
+ def extract_strings_from_dir(temp_dir: str) -> Set[str]:
373
+ strings = set()
374
+ for root, dirs, files in os.walk(temp_dir):
375
+ for f in files:
376
+ if f.endswith(('.xml', '.json', '.txt', '.properties', '.cfg', '.ini')):
377
+ try:
378
+ filepath = os.path.join(root, f)
379
+ with open(filepath, 'r', encoding='utf-8', errors='ignore') as file:
380
+ content = file.read()
381
+ # Extract URLs
382
+ urls = re.findall(r'https?://[^\s<>"{}|\^`\[\]]+', content, re.IGNORECASE)
383
+ strings.update(urls)
384
+ # Extract domains
385
+ domains = re.findall(r'(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}', content, re.IGNORECASE)
386
+ strings.update(domains)
387
+ # Extract IPs
388
+ ips = re.findall(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b', content)
389
+ strings.update(ips)
390
+ except:
391
+ pass
392
+ return strings
393
+
394
+ orig_strings = extract_strings_from_dir(self.orig_temp_dir)
395
+ mod_strings = extract_strings_from_dir(self.mod_temp_dir)
396
+
397
+ return {
398
+ "added": sorted(list(mod_strings - orig_strings)),
399
+ "removed": sorted(list(orig_strings - mod_strings)),
400
+ "common": sorted(list(orig_strings & mod_strings)),
401
+ }
402
+
403
+ def _detect_suspicious(self, manifest: Dict, dex: Dict, native: Dict,
404
+ signature: Dict, files: Dict) -> List[str]:
405
+ """Detect potentially suspicious changes."""
406
+ suspicious = []
407
+
408
+ # New permissions
409
+ perms = manifest.get("changes", {}).get("permissions", {})
410
+ dangerous_perms = [
411
+ "android.permission.SEND_SMS",
412
+ "android.permission.READ_SMS",
413
+ "android.permission.RECEIVE_SMS",
414
+ "android.permission.CALL_PHONE",
415
+ "android.permission.READ_PHONE_STATE",
416
+ "android.permission.ACCESS_FINE_LOCATION",
417
+ "android.permission.RECORD_AUDIO",
418
+ "android.permission.CAMERA",
419
+ "android.permission.WRITE_EXTERNAL_STORAGE",
420
+ "android.permission.READ_EXTERNAL_STORAGE",
421
+ "android.permission.SYSTEM_ALERT_WINDOW",
422
+ "android.permission.BIND_ACCESSIBILITY_SERVICE",
423
+ "android.permission.REQUEST_INSTALL_PACKAGES",
424
+ ]
425
+ for perm in perms.get("added", []):
426
+ if any(dp in perm for dp in dangerous_perms):
427
+ suspicious.append(f"صلاحية خطيرة مضافة: {perm}")
428
+
429
+ # Debug enabled
430
+ pkg_changes = manifest.get("changes", {}).get("package_info", {})
431
+ if "debuggable" in pkg_changes:
432
+ debug_orig = str(pkg_changes["debuggable"].get("original", "")).lower()
433
+ debug_mod = str(pkg_changes["debuggable"].get("modified", "")).lower()
434
+ if debug_orig in ["false", ""] and debug_mod == "true":
435
+ suspicious.append("تم تفعيل وضع التصحيح (debuggable=true)")
436
+
437
+ # Cleartext traffic
438
+ if "usesCleartextTraffic" in pkg_changes:
439
+ suspicious.append("تم تغيير إعدادات نقل البيانات غير المشفرة")
440
+
441
+ # New services/receivers
442
+ svc_changes = manifest.get("changes", {}).get("services", {})
443
+ if svc_changes.get("added"):
444
+ for svc in svc_changes["added"]:
445
+ suspicious.append(f"خدمة جديدة (Service): {svc.get('name', 'Unknown')}")
446
+
447
+ rec_changes = manifest.get("changes", {}).get("receivers", {})
448
+ if rec_changes.get("added"):
449
+ for rec in rec_changes["added"]:
450
+ suspicious.append(f"مستقبل جديد (Receiver): {rec.get('name', 'Unknown')}")
451
+
452
+ # New native libraries
453
+ if native.get("added"):
454
+ for lib in native["added"]:
455
+ suspicious.append(f"مكتبة Native جديدة: {lib}")
456
+
457
+ # Signature changed
458
+ if signature.get("signature_changed"):
459
+ suspicious.append("تغيير في توقيع APK (Signature Changed)")
460
+
461
+ # Suspicious APIs in DEX
462
+ suspicious_apis = dex.get("all_suspicious", [])
463
+ if suspicious_apis:
464
+ suspicious.append(f"تم العثور على {len(suspicious_apis)} استدعاء API مشبوه في DEX")
465
+
466
+ # New URLs/domains
467
+ strings = self._analyze_strings()
468
+ new_urls = strings.get("added", [])
469
+ suspicious_domains = ['.tk', '.ml', '.ga', '.cf', '.gq']
470
+ for url in new_urls:
471
+ if any(sd in url for sd in suspicious_domains):
472
+ suspicious.append(f"نطاق مشبوه جديد: {url}")
473
+
474
+ return suspicious
475
+
476
+ def _cleanup(self):
477
+ """Clean up temporary files."""
478
+ if self.orig_temp_dir:
479
+ cleanup_temp_dir(self.orig_temp_dir)
480
+ if self.mod_temp_dir:
481
+ cleanup_temp_dir(self.mod_temp_dir)
src/dex_analyzer.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ APK Deep Diff Analyzer - DEX File Analyzer
3
+ """
4
+ import struct
5
+ import os
6
+ import zipfile
7
+ from typing import Dict, List, Any, Optional, Set
8
+ import re
9
+
10
+
11
+ class DexAnalyzer:
12
+ """Analyze DEX (Dalvik Executable) files."""
13
+
14
+ DEX_MAGIC = b'dex\n'
15
+
16
+ def __init__(self, dex_path: str):
17
+ self.dex_path = dex_path
18
+ self.data = None
19
+ self._load()
20
+
21
+ def _load(self):
22
+ """Load DEX file."""
23
+ try:
24
+ with open(self.dex_path, 'rb') as f:
25
+ self.data = f.read()
26
+ except Exception:
27
+ self.data = b''
28
+
29
+ def is_valid_dex(self) -> bool:
30
+ """Check if file is a valid DEX."""
31
+ return self.data.startswith(self.DEX_MAGIC) if self.data else False
32
+
33
+ def get_header_info(self) -> Dict[str, Any]:
34
+ """Parse DEX header information."""
35
+ if not self.is_valid_dex():
36
+ return {}
37
+
38
+ try:
39
+ # DEX header format (simplified)
40
+ magic = self.data[:8]
41
+ checksum = struct.unpack('<I', self.data[8:12])[0]
42
+ signature = self.data[12:32].hex()
43
+ file_size = struct.unpack('<I', self.data[32:36])[0]
44
+ header_size = struct.unpack('<I', self.data[36:40])[0]
45
+ endian_tag = struct.unpack('<I', self.data[40:44])[0]
46
+
47
+ # String IDs
48
+ string_ids_size = struct.unpack('<I', self.data[56:60])[0]
49
+ string_ids_off = struct.unpack('<I', self.data[60:64])[0]
50
+
51
+ # Type IDs
52
+ type_ids_size = struct.unpack('<I', self.data[64:68])[0]
53
+ type_ids_off = struct.unpack('<I', self.data[68:72])[0]
54
+
55
+ # Proto IDs
56
+ proto_ids_size = struct.unpack('<I', self.data[72:76])[0]
57
+ proto_ids_off = struct.unpack('<I', self.data[76:80])[0]
58
+
59
+ # Field IDs
60
+ field_ids_size = struct.unpack('<I', self.data[80:84])[0]
61
+ field_ids_off = struct.unpack('<I', self.data[84:88])[0]
62
+
63
+ # Method IDs
64
+ method_ids_size = struct.unpack('<I', self.data[88:92])[0]
65
+ method_ids_off = struct.unpack('<I', self.data[92:96])[0]
66
+
67
+ # Class defs
68
+ class_defs_size = struct.unpack('<I', self.data[96:100])[0]
69
+ class_defs_off = struct.unpack('<I', self.data[100:104])[0]
70
+
71
+ return {
72
+ "magic": magic.hex(),
73
+ "checksum": checksum,
74
+ "signature": signature,
75
+ "file_size": file_size,
76
+ "header_size": header_size,
77
+ "endian_tag": endian_tag,
78
+ "string_ids_count": string_ids_size,
79
+ "type_ids_count": type_ids_size,
80
+ "proto_ids_count": proto_ids_size,
81
+ "field_ids_count": field_ids_size,
82
+ "method_ids_count": method_ids_size,
83
+ "class_defs_count": class_defs_size,
84
+ }
85
+ except Exception as e:
86
+ return {"error": str(e)}
87
+
88
+ def extract_strings(self) -> List[str]:
89
+ """Extract strings from DEX file."""
90
+ if not self.is_valid_dex():
91
+ return []
92
+
93
+ strings = []
94
+ try:
95
+ # Simple string extraction - look for readable ASCII/UTF-8 strings
96
+ # This is a basic approach; full DEX parsing is complex
97
+ pattern = rb'[\x20-\x7E]{4,}'
98
+ matches = re.findall(pattern, self.data)
99
+ for match in matches:
100
+ try:
101
+ s = match.decode('utf-8', errors='ignore')
102
+ if len(s) >= 4:
103
+ strings.append(s)
104
+ except:
105
+ pass
106
+
107
+ # Also try to extract from string data section
108
+ string_ids_size = struct.unpack('<I', self.data[56:60])[0]
109
+ string_ids_off = struct.unpack('<I', self.data[60:64])[0]
110
+
111
+ for i in range(min(string_ids_size, 10000)): # Limit for performance
112
+ try:
113
+ offset = struct.unpack('<I', self.data[string_ids_off + i*4:string_ids_off + i*4 + 4])[0]
114
+ # Read MUTF-8 string
115
+ str_len, bytes_read = self._read_uleb128(offset)
116
+ if str_len > 0 and str_len < 10000:
117
+ str_data = self.data[offset + bytes_read:offset + bytes_read + str_len]
118
+ s = str_data.decode('utf-8', errors='ignore')
119
+ if s and len(s) > 1:
120
+ strings.append(s)
121
+ except:
122
+ pass
123
+ except Exception:
124
+ pass
125
+
126
+ return sorted(set(strings))
127
+
128
+ def _read_uleb128(self, offset: int) -> tuple:
129
+ """Read unsigned LEB128 value."""
130
+ result = 0
131
+ shift = 0
132
+ bytes_read = 0
133
+ while True:
134
+ byte = self.data[offset + bytes_read]
135
+ result |= (byte & 0x7f) << shift
136
+ bytes_read += 1
137
+ if (byte & 0x80) == 0:
138
+ break
139
+ shift += 7
140
+ return result, bytes_read
141
+
142
+ def extract_urls(self) -> List[str]:
143
+ """Extract URLs from DEX strings."""
144
+ strings = self.extract_strings()
145
+ urls = []
146
+ url_pattern = re.compile(
147
+ r'https?://[^\s<>"{}|\^`\[\]]+',
148
+ re.IGNORECASE
149
+ )
150
+ for s in strings:
151
+ matches = url_pattern.findall(s)
152
+ urls.extend(matches)
153
+ return sorted(set(urls))
154
+
155
+ def extract_domains(self) -> List[str]:
156
+ """Extract domain names from strings."""
157
+ strings = self.extract_strings()
158
+ domains = []
159
+ domain_pattern = re.compile(
160
+ r'(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}',
161
+ re.IGNORECASE
162
+ )
163
+ for s in strings:
164
+ matches = domain_pattern.findall(s)
165
+ domains.extend(matches)
166
+ return sorted(set(domains))
167
+
168
+ def extract_ips(self) -> List[str]:
169
+ """Extract IP addresses from strings."""
170
+ strings = self.extract_strings()
171
+ ips = []
172
+ ip_pattern = re.compile(
173
+ r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
174
+ )
175
+ for s in strings:
176
+ matches = ip_pattern.findall(s)
177
+ ips.extend(matches)
178
+ return sorted(set(ips))
179
+
180
+ def extract_api_calls(self) -> List[str]:
181
+ """Extract suspicious API references."""
182
+ strings = self.extract_strings()
183
+ suspicious = []
184
+ suspicious_patterns = [
185
+ r'Landroid/telephony/SmsManager;',
186
+ r'Landroid/content/pm/PackageManager;',
187
+ r'Landroid/app/admin/DevicePolicyManager;',
188
+ r'Ljava/net/HttpURLConnection;',
189
+ r'Landroid/location/LocationManager;',
190
+ r'Landroid/hardware/Camera;',
191
+ r'getDeviceId',
192
+ r'sendTextMessage',
193
+ r'exec\(',
194
+ r'Runtime\.getRuntime',
195
+ r'DexClassLoader',
196
+ r'PathClassLoader',
197
+ r'loadClass',
198
+ r'invoke',
199
+ r'getMethod',
200
+ r'getDeclaredField',
201
+ ]
202
+ for s in strings:
203
+ for pattern in suspicious_patterns:
204
+ if re.search(pattern, s, re.IGNORECASE):
205
+ suspicious.append(s)
206
+ break
207
+ return sorted(set(suspicious))
208
+
209
+ def get_full_analysis(self) -> Dict[str, Any]:
210
+ """Get complete DEX analysis."""
211
+ header = self.get_header_info()
212
+ return {
213
+ "valid": self.is_valid_dex(),
214
+ "header": header,
215
+ "strings_count": len(self.extract_strings()),
216
+ "urls": self.extract_urls(),
217
+ "domains": self.extract_domains(),
218
+ "ips": self.extract_ips(),
219
+ "suspicious_apis": self.extract_api_calls(),
220
+ }
221
+
222
+
223
+ def find_dex_files(extract_dir: str) -> List[str]:
224
+ """Find all DEX files in extracted APK directory."""
225
+ dex_files = []
226
+ for root, dirs, files in os.walk(extract_dir):
227
+ for f in files:
228
+ if f.endswith('.dex'):
229
+ dex_files.append(os.path.join(root, f))
230
+ # Sort by name (classes.dex, classes2.dex, etc.)
231
+ dex_files.sort(key=lambda x: (
232
+ 0 if os.path.basename(x) == 'classes.dex' else 1,
233
+ os.path.basename(x)
234
+ ))
235
+ return dex_files
236
+
237
+
238
+ def analyze_all_dex(extract_dir: str) -> Dict[str, Any]:
239
+ """Analyze all DEX files in directory."""
240
+ dex_files = find_dex_files(extract_dir)
241
+ results = {
242
+ "dex_count": len(dex_files),
243
+ "dex_files": {},
244
+ "all_strings": set(),
245
+ "all_urls": set(),
246
+ "all_domains": set(),
247
+ "all_ips": set(),
248
+ "all_suspicious": set(),
249
+ }
250
+
251
+ for dex_path in dex_files:
252
+ analyzer = DexAnalyzer(dex_path)
253
+ filename = os.path.basename(dex_path)
254
+ results["dex_files"][filename] = analyzer.get_full_analysis()
255
+
256
+ if analyzer.is_valid_dex():
257
+ results["all_strings"].update(analyzer.extract_strings())
258
+ results["all_urls"].update(analyzer.extract_urls())
259
+ results["all_domains"].update(analyzer.extract_domains())
260
+ results["all_ips"].update(analyzer.extract_ips())
261
+ results["all_suspicious"].update(analyzer.extract_api_calls())
262
+
263
+ # Convert sets to sorted lists
264
+ results["all_strings"] = sorted(results["all_strings"])
265
+ results["all_urls"] = sorted(results["all_urls"])
266
+ results["all_domains"] = sorted(results["all_domains"])
267
+ results["all_ips"] = sorted(results["all_ips"])
268
+ results["all_suspicious"] = sorted(results["all_suspicious"])
269
+
270
+ return results
src/manifest_parser.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ APK Deep Diff Analyzer - AndroidManifest.xml Parser
3
+ """
4
+ import xml.etree.ElementTree as ET
5
+ from typing import Dict, List, Any, Optional
6
+ import os
7
+
8
+
9
+ class ManifestAnalyzer:
10
+ """Analyze AndroidManifest.xml content."""
11
+
12
+ def __init__(self, manifest_path: str):
13
+ self.manifest_path = manifest_path
14
+ self.tree = None
15
+ self.root = None
16
+ self._parse()
17
+
18
+ def _parse(self):
19
+ """Parse the manifest XML."""
20
+ try:
21
+ self.tree = ET.parse(self.manifest_path)
22
+ self.root = self.tree.getroot()
23
+ except Exception:
24
+ self.tree = None
25
+ self.root = None
26
+
27
+ def _get_attr(self, element: ET.Element, attr: str, namespace: str = "android") -> Optional[str]:
28
+ """Get attribute value with namespace handling."""
29
+ ns = "http://schemas.android.com/apk/res/android"
30
+ val = element.get(f"{{{ns}}}{attr}")
31
+ if val is None:
32
+ val = element.get(attr)
33
+ return val
34
+
35
+ def get_package_info(self) -> Dict[str, Any]:
36
+ """Get package and application info."""
37
+ if self.root is None:
38
+ return {}
39
+
40
+ info = {
41
+ "package": self.root.get("package", ""),
42
+ "versionCode": self._get_attr(self.root, "versionCode"),
43
+ "versionName": self._get_attr(self.root, "versionName"),
44
+ }
45
+
46
+ app = self.root.find("application")
47
+ if app is not None:
48
+ info["application"] = {
49
+ "label": self._get_attr(app, "label"),
50
+ "icon": self._get_attr(app, "icon"),
51
+ "theme": self._get_attr(app, "theme"),
52
+ "debuggable": self._get_attr(app, "debuggable"),
53
+ "networkSecurityConfig": self._get_attr(app, "networkSecurityConfig"),
54
+ "usesCleartextTraffic": self._get_attr(app, "usesCleartextTraffic"),
55
+ "allowBackup": self._get_attr(app, "allowBackup"),
56
+ "extractNativeLibs": self._get_attr(app, "extractNativeLibs"),
57
+ }
58
+
59
+ # SDK info
60
+ uses_sdk = self.root.find("uses-sdk")
61
+ if uses_sdk is not None:
62
+ info["minSdkVersion"] = self._get_attr(uses_sdk, "minSdkVersion")
63
+ info["targetSdkVersion"] = self._get_attr(uses_sdk, "targetSdkVersion")
64
+ info["maxSdkVersion"] = self._get_attr(uses_sdk, "maxSdkVersion")
65
+
66
+ return info
67
+
68
+ def get_permissions(self) -> List[str]:
69
+ """Get all permissions."""
70
+ if self.root is None:
71
+ return []
72
+
73
+ permissions = []
74
+ for perm in self.root.findall("uses-permission"):
75
+ name = self._get_attr(perm, "name")
76
+ if name:
77
+ permissions.append(name)
78
+ return sorted(set(permissions))
79
+
80
+ def get_activities(self) -> List[Dict[str, Any]]:
81
+ """Get all activities."""
82
+ if self.root is None:
83
+ return []
84
+
85
+ activities = []
86
+ app = self.root.find("application")
87
+ if app is not None:
88
+ for activity in app.findall("activity"):
89
+ name = self._get_attr(activity, "name")
90
+ if name:
91
+ acts = {
92
+ "name": name,
93
+ "exported": self._get_attr(activity, "exported"),
94
+ "permission": self._get_attr(activity, "permission"),
95
+ "intent_filters": [],
96
+ }
97
+ for intent in activity.findall("intent-filter"):
98
+ actions = [a.get("name", "") for a in intent.findall("action")]
99
+ categories = [c.get("name", "") for c in intent.findall("category")]
100
+ acts["intent_filters"].append({
101
+ "actions": actions,
102
+ "categories": categories,
103
+ })
104
+ activities.append(acts)
105
+ return activities
106
+
107
+ def get_services(self) -> List[Dict[str, Any]]:
108
+ """Get all services."""
109
+ if self.root is None:
110
+ return []
111
+
112
+ services = []
113
+ app = self.root.find("application")
114
+ if app is not None:
115
+ for service in app.findall("service"):
116
+ name = self._get_attr(service, "name")
117
+ if name:
118
+ services.append({
119
+ "name": name,
120
+ "exported": self._get_attr(service, "exported"),
121
+ "permission": self._get_attr(service, "permission"),
122
+ })
123
+ return services
124
+
125
+ def get_receivers(self) -> List[Dict[str, Any]]:
126
+ """Get all broadcast receivers."""
127
+ if self.root is None:
128
+ return []
129
+
130
+ receivers = []
131
+ app = self.root.find("application")
132
+ if app is not None:
133
+ for receiver in app.findall("receiver"):
134
+ name = self._get_attr(receiver, "name")
135
+ if name:
136
+ receivers.append({
137
+ "name": name,
138
+ "exported": self._get_attr(receiver, "exported"),
139
+ "permission": self._get_attr(receiver, "permission"),
140
+ })
141
+ return receivers
142
+
143
+ def get_providers(self) -> List[Dict[str, Any]]:
144
+ """Get all content providers."""
145
+ if self.root is None:
146
+ return []
147
+
148
+ providers = []
149
+ app = self.root.find("application")
150
+ if app is not None:
151
+ for provider in app.findall("provider"):
152
+ name = self._get_attr(provider, "name")
153
+ if name:
154
+ providers.append({
155
+ "name": name,
156
+ "authorities": self._get_attr(provider, "authorities"),
157
+ "exported": self._get_attr(provider, "exported"),
158
+ })
159
+ return providers
160
+
161
+ def get_metadata(self) -> List[Dict[str, str]]:
162
+ """Get application metadata."""
163
+ if self.root is None:
164
+ return []
165
+
166
+ metadata = []
167
+ app = self.root.find("application")
168
+ if app is not None:
169
+ for meta in app.findall("meta-data"):
170
+ name = self._get_attr(meta, "name")
171
+ value = self._get_attr(meta, "value")
172
+ if name:
173
+ metadata.append({"name": name, "value": value or ""})
174
+ return metadata
175
+
176
+ def get_full_analysis(self) -> Dict[str, Any]:
177
+ """Get complete manifest analysis."""
178
+ return {
179
+ "package_info": self.get_package_info(),
180
+ "permissions": self.get_permissions(),
181
+ "activities": self.get_activities(),
182
+ "services": self.get_services(),
183
+ "receivers": self.get_receivers(),
184
+ "providers": self.get_providers(),
185
+ "metadata": self.get_metadata(),
186
+ }
187
+
188
+
189
+ def compare_manifests(orig_manifest: str, mod_manifest: str) -> Dict[str, Any]:
190
+ """Compare two AndroidManifest.xml files."""
191
+ orig = ManifestAnalyzer(orig_manifest)
192
+ mod = ManifestAnalyzer(mod_manifest)
193
+
194
+ orig_data = orig.get_full_analysis()
195
+ mod_data = mod.get_full_analysis()
196
+
197
+ result = {
198
+ "original": orig_data,
199
+ "modified": mod_data,
200
+ "changes": {},
201
+ }
202
+
203
+ # Package info comparison
204
+ orig_pkg = orig_data.get("package_info", {})
205
+ mod_pkg = mod_data.get("package_info", {})
206
+ pkg_changes = {}
207
+
208
+ for key in set(list(orig_pkg.keys()) + list(mod_pkg.keys())):
209
+ if key == "application":
210
+ continue
211
+ o_val = orig_pkg.get(key)
212
+ m_val = mod_pkg.get(key)
213
+ if o_val != m_val:
214
+ pkg_changes[key] = {"original": o_val, "modified": m_val}
215
+
216
+ # Application attributes
217
+ orig_app = orig_pkg.get("application", {})
218
+ mod_app = mod_pkg.get("application", {})
219
+ app_changes = {}
220
+ for key in set(list(orig_app.keys()) + list(mod_app.keys())):
221
+ o_val = orig_app.get(key)
222
+ m_val = mod_app.get(key)
223
+ if o_val != m_val:
224
+ app_changes[key] = {"original": o_val, "modified": m_val}
225
+
226
+ if pkg_changes or app_changes:
227
+ result["changes"]["package_info"] = {**pkg_changes, **app_changes}
228
+
229
+ # Permissions
230
+ orig_perms = set(orig_data.get("permissions", []))
231
+ mod_perms = set(mod_data.get("permissions", []))
232
+ result["changes"]["permissions"] = {
233
+ "added": sorted(list(mod_perms - orig_perms)),
234
+ "removed": sorted(list(orig_perms - mod_perms)),
235
+ "unchanged": sorted(list(orig_perms & mod_perms)),
236
+ }
237
+
238
+ # Activities
239
+ orig_acts = {a["name"]: a for a in orig_data.get("activities", [])}
240
+ mod_acts = {a["name"]: a for a in mod_data.get("activities", [])}
241
+ act_changes = {
242
+ "added": [],
243
+ "removed": [],
244
+ "modified": [],
245
+ }
246
+ for name, data in mod_acts.items():
247
+ if name not in orig_acts:
248
+ act_changes["added"].append(data)
249
+ elif data != orig_acts[name]:
250
+ act_changes["modified"].append({
251
+ "name": name,
252
+ "original": orig_acts[name],
253
+ "modified": data,
254
+ })
255
+ for name, data in orig_acts.items():
256
+ if name not in mod_acts:
257
+ act_changes["removed"].append(data)
258
+ result["changes"]["activities"] = act_changes
259
+
260
+ # Services
261
+ orig_svcs = {s["name"]: s for s in orig_data.get("services", [])}
262
+ mod_svcs = {s["name"]: s for s in mod_data.get("services", [])}
263
+ svc_changes = {"added": [], "removed": [], "modified": []}
264
+ for name, data in mod_svcs.items():
265
+ if name not in orig_svcs:
266
+ svc_changes["added"].append(data)
267
+ elif data != orig_svcs[name]:
268
+ svc_changes["modified"].append({"name": name, "original": orig_svcs[name], "modified": data})
269
+ for name, data in orig_svcs.items():
270
+ if name not in mod_svcs:
271
+ svc_changes["removed"].append(data)
272
+ result["changes"]["services"] = svc_changes
273
+
274
+ # Receivers
275
+ orig_recs = {r["name"]: r for r in orig_data.get("receivers", [])}
276
+ mod_recs = {r["name"]: r for r in mod_data.get("receivers", [])}
277
+ rec_changes = {"added": [], "removed": [], "modified": []}
278
+ for name, data in mod_recs.items():
279
+ if name not in orig_recs:
280
+ rec_changes["added"].append(data)
281
+ elif data != orig_recs[name]:
282
+ rec_changes["modified"].append({"name": name, "original": orig_recs[name], "modified": data})
283
+ for name, data in orig_recs.items():
284
+ if name not in mod_recs:
285
+ rec_changes["removed"].append(data)
286
+ result["changes"]["receivers"] = rec_changes
287
+
288
+ # Providers
289
+ orig_provs = {p["name"]: p for p in orig_data.get("providers", [])}
290
+ mod_provs = {p["name"]: p for p in mod_data.get("providers", [])}
291
+ prov_changes = {"added": [], "removed": [], "modified": []}
292
+ for name, data in mod_provs.items():
293
+ if name not in orig_provs:
294
+ prov_changes["added"].append(data)
295
+ elif data != orig_provs[name]:
296
+ prov_changes["modified"].append({"name": name, "original": orig_provs[name], "modified": data})
297
+ for name, data in orig_provs.items():
298
+ if name not in mod_provs:
299
+ prov_changes["removed"].append(data)
300
+ result["changes"]["providers"] = prov_changes
301
+
302
+ # Metadata
303
+ orig_meta = {m["name"]: m["value"] for m in orig_data.get("metadata", [])}
304
+ mod_meta = {m["name"]: m["value"] for m in mod_data.get("metadata", [])}
305
+ meta_changes = {
306
+ "added": [{"name": k, "value": v} for k, v in mod_meta.items() if k not in orig_meta],
307
+ "removed": [{"name": k, "value": v} for k, v in orig_meta.items() if k not in mod_meta],
308
+ "modified": [{"name": k, "original": orig_meta[k], "modified": mod_meta[k]}
309
+ for k in orig_meta if k in mod_meta and orig_meta[k] != mod_meta[k]],
310
+ }
311
+ result["changes"]["metadata"] = meta_changes
312
+
313
+ return result
src/report_generator.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ APK Deep Diff Analyzer - Report Generator
3
+ """
4
+ import json
5
+ from typing import Dict, Any, List
6
+ from datetime import datetime
7
+
8
+
9
+ class ReportGenerator:
10
+ """Generate analysis reports in multiple formats."""
11
+
12
+ def __init__(self, analysis_data: Dict[str, Any]):
13
+ self.data = analysis_data
14
+
15
+ def generate_txt_report(self) -> str:
16
+ """Generate plain text report in Arabic."""
17
+ lines = []
18
+ d = self.data
19
+
20
+ lines.append("=" * 80)
21
+ lines.append("تقرير تحليل عميق لمقارنة ملفات APK")
22
+ lines.append("APK Deep Diff Analyzer Report")
23
+ lines.append("=" * 80)
24
+ lines.append("")
25
+
26
+ # Basic info
27
+ lines.append("معلومات الملفات | File Information")
28
+ lines.append("-" * 40)
29
+ orig = d.get("original_info", {})
30
+ mod = d.get("modified_info", {})
31
+ lines.append(f"APK الأصلي (Original): {orig.get('filename', 'N/A')}")
32
+ lines.append(f" الحجم (Size): {orig.get('size_formatted', 'N/A')}")
33
+ lines.append(f" SHA-256: {orig.get('sha256', 'N/A')}")
34
+ lines.append(f" MD5: {orig.get('md5', 'N/A')}")
35
+ lines.append("")
36
+ lines.append(f"APK المعدل (Modified): {mod.get('filename', 'N/A')}")
37
+ lines.append(f" الحجم (Size): {mod.get('size_formatted', 'N/A')}")
38
+ lines.append(f" SHA-256: {mod.get('sha256', 'N/A')}")
39
+ lines.append(f" MD5: {mod.get('md5', 'N/A')}")
40
+ lines.append("")
41
+
42
+ # Summary
43
+ summary = d.get("file_comparison", {}).get("summary", {})
44
+ lines.append("ملخص المقارنة | Comparison Summary")
45
+ lines.append("-" * 40)
46
+ lines.append(f"إجمالي الملفات (Total Files): {summary.get('total', 0)}")
47
+ lines.append(f"متطابقة (Unchanged): {summary.get('unchanged', 0)}")
48
+ lines.append(f"معدلة (Modified): {summary.get('modified', 0)}")
49
+ lines.append(f"مضافة (Added): {summary.get('added', 0)}")
50
+ lines.append(f"محذوفة (Removed): {summary.get('removed', 0)}")
51
+ lines.append("")
52
+
53
+ # Manifest changes
54
+ manifest = d.get("manifest_comparison", {})
55
+ changes = manifest.get("changes", {})
56
+ lines.append("تغييرات AndroidManifest.xml")
57
+ lines.append("-" * 40)
58
+
59
+ perms = changes.get("permissions", {})
60
+ added_perms = perms.get("added", [])
61
+ removed_perms = perms.get("removed", [])
62
+ if added_perms:
63
+ lines.append("صلاحيات مضافة (+Permissions Added):")
64
+ for p in added_perms:
65
+ lines.append(f" + {p}")
66
+ if removed_perms:
67
+ lines.append("صلاحيات محذوفة (-Permissions Removed):")
68
+ for p in removed_perms:
69
+ lines.append(f" - {p}")
70
+
71
+ pkg_changes = changes.get("package_info", {})
72
+ if pkg_changes:
73
+ lines.append("تغييرات معلومات الحزمة (Package Info Changes):")
74
+ for key, vals in pkg_changes.items():
75
+ lines.append(f" {key}: {vals.get('original', 'N/A')} → {vals.get('modified', 'N/A')}")
76
+ lines.append("")
77
+
78
+ # DEX changes
79
+ dex = d.get("dex_analysis", {})
80
+ lines.append("تحليل ملفات DEX")
81
+ lines.append("-" * 40)
82
+ lines.append(f"عدد ملفات DEX (DEX Count): {dex.get('dex_count', 0)}")
83
+ for fname, fdata in dex.get("dex_files", {}).items():
84
+ lines.append(f" {fname}:")
85
+ header = fdata.get("header", {})
86
+ if "error" not in header:
87
+ lines.append(f" Classes: {header.get('class_defs_count', 'N/A')}")
88
+ lines.append(f" Methods: {header.get('method_ids_count', 'N/A')}")
89
+ lines.append(f" Fields: {header.get('field_ids_count', 'N/A')}")
90
+ lines.append(f" Strings: {header.get('string_ids_count', 'N/A')}")
91
+
92
+ urls = dex.get("all_urls", [])
93
+ if urls:
94
+ lines.append("URLs المستخرجة:")
95
+ for url in urls[:20]: # Limit output
96
+ lines.append(f" {url}")
97
+ lines.append("")
98
+
99
+ # Native libraries
100
+ native = d.get("native_libraries", {})
101
+ lines.append("مكتبات Native")
102
+ lines.append("-" * 40)
103
+ lines.append(f"مكتبات في الأصلي (Original): {len(native.get('original', []))}")
104
+ lines.append(f"مكتبات في المعدل (Modified): {len(native.get('modified', []))}")
105
+ added_libs = native.get("added", [])
106
+ removed_libs = native.get("removed", [])
107
+ if added_libs:
108
+ lines.append("مكتبات مضافة:")
109
+ for lib in added_libs:
110
+ lines.append(f" + {lib}")
111
+ if removed_libs:
112
+ lines.append("مكتبات محذوفة:")
113
+ for lib in removed_libs:
114
+ lines.append(f" - {lib}")
115
+ lines.append("")
116
+
117
+ # Signature
118
+ sig = d.get("signature_comparison", {})
119
+ lines.append("تحليل التوقيع | Signature Analysis")
120
+ lines.append("-" * 40)
121
+ if sig.get("signature_changed"):
122
+ lines.append("⚠️ التوقيع تغير! (Signature Changed)")
123
+ else:
124
+ lines.append("✅ التوقيع متطابق (Signature Match)")
125
+ lines.append("")
126
+
127
+ # Suspicious changes
128
+ suspicious = d.get("suspicious_changes", [])
129
+ if suspicious:
130
+ lines.append("تغييرات مشبوهة محتملة | Potentially Suspicious Changes")
131
+ lines.append("-" * 40)
132
+ for item in suspicious:
133
+ lines.append(f" ⚠️ {item}")
134
+ lines.append("")
135
+
136
+ lines.append("=" * 80)
137
+ lines.append("نهاية التقرير | End of Report")
138
+ lines.append(f"تاريخ التحليل: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
139
+ lines.append("=" * 80)
140
+
141
+ return "\n".join(lines)
142
+
143
+ def generate_json_report(self) -> str:
144
+ """Generate JSON report."""
145
+ return json.dumps(self.data, indent=2, ensure_ascii=False, default=str)
146
+
147
+ def generate_html_report(self) -> str:
148
+ """Generate HTML report."""
149
+ d = self.data
150
+ summary = d.get("file_comparison", {}).get("summary", {})
151
+
152
+ html = f"""<!DOCTYPE html>
153
+ <html dir="rtl" lang="ar">
154
+ <head>
155
+ <meta charset="UTF-8">
156
+ <title>APK Deep Diff Analyzer Report</title>
157
+ <style>
158
+ body {{ font-family: 'Segoe UI', Tahoma, Arial, sans-serif; margin: 20px; background: #1a1a2e; color: #eee; }}
159
+ .container {{ max-width: 1200px; margin: 0 auto; }}
160
+ h1 {{ color: #00d4ff; text-align: center; }}
161
+ h2 {{ color: #ff6b6b; border-bottom: 2px solid #ff6b6b; padding-bottom: 5px; }}
162
+ .summary-box {{ background: #16213e; padding: 20px; border-radius: 10px; margin: 15px 0; }}
163
+ .added {{ color: #4ecdc4; }}
164
+ .removed {{ color: #ff6b6b; }}
165
+ .modified {{ color: #feca57; }}
166
+ .unchanged {{ color: #48dbfb; }}
167
+ .warning {{ color: #ff9f43; }}
168
+ table {{ width: 100%; border-collapse: collapse; margin: 15px 0; }}
169
+ th, td {{ padding: 10px; text-align: right; border: 1px solid #333; }}
170
+ th {{ background: #0f3460; }}
171
+ tr:nth-child(even) {{ background: #1a1a2e; }}
172
+ </style>
173
+ </head>
174
+ <body>
175
+ <div class="container">
176
+ <h1>🔍 APK Deep Diff Analyzer</h1>
177
+ <div class="summary-box">
178
+ <h2>📊 ملخص المقارنة</h2>
179
+ <p>إجمالي الملفات: <strong>{summary.get('total', 0)}</strong></p>
180
+ <p class="unchanged">✅ متطابقة: {summary.get('unchanged', 0)}</p>
181
+ <p class="modified">⚠️ معدلة: {summary.get('modified', 0)}</p>
182
+ <p class="added">➕ مضافة: {summary.get('added', 0)}</p>
183
+ <p class="removed">➖ محذوفة: {summary.get('removed', 0)}</p>
184
+ </div>
185
+ """
186
+
187
+ # Manifest section
188
+ manifest = d.get("manifest_comparison", {})
189
+ changes = manifest.get("changes", {})
190
+ html += "<div class='summary-box'>"
191
+ html += "<h2>📋 AndroidManifest.xml</h2>"
192
+
193
+ perms = changes.get("permissions", {})
194
+ if perms.get("added"):
195
+ html += "<h3 class='added'>صلاحيات مضافة:</h3><ul>"
196
+ for p in perms["added"]:
197
+ html += f"<li class='added'>+ {p}</li>"
198
+ html += "</ul>"
199
+
200
+ if perms.get("removed"):
201
+ html += "<h3 class='removed'>صلاحيات محذوفة:</h3><ul>"
202
+ for p in perms["removed"]:
203
+ html += f"<li class='removed'>- {p}</li>"
204
+ html += "</ul>"
205
+
206
+ html += "</div>"
207
+
208
+ # Signature
209
+ sig = d.get("signature_comparison", {})
210
+ html += "<div class='summary-box'>"
211
+ html += "<h2>🔐 التوقيع</h2>"
212
+ if sig.get("signature_changed"):
213
+ html += "<p class='warning'>⚠️ التوقيع تغير!</p>"
214
+ else:
215
+ html += "<p class='unchanged'>✅ التوقيع متطابق</p>"
216
+ html += "</div>"
217
+
218
+ # Suspicious
219
+ suspicious = d.get("suspicious_changes", [])
220
+ if suspicious:
221
+ html += "<div class='summary-box'>"
222
+ html += "<h2 class='warning'>⚠️ تغييرات مشبوهة محتملة</h2><ul>"
223
+ for item in suspicious:
224
+ html += f"<li class='warning'>{item}</li>"
225
+ html += "</ul></div>"
226
+
227
+ html += "</div></body></html>"
228
+ return html
src/signature_analyzer.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ APK Deep Diff Analyzer - Signature Analyzer
3
+ """
4
+ import zipfile
5
+ import os
6
+ from typing import Dict, List, Any, Optional
7
+ import hashlib
8
+
9
+
10
+ class SignatureAnalyzer:
11
+ """Analyze APK signing information."""
12
+
13
+ def __init__(self, apk_path: str):
14
+ self.apk_path = apk_path
15
+
16
+ def get_signature_files(self) -> Dict[str, Any]:
17
+ """Extract signature-related files from META-INF."""
18
+ signatures = {
19
+ "meta_inf_files": [],
20
+ "cert_files": [],
21
+ "sf_files": [],
22
+ "manifest_mf": None,
23
+ "v1_signing": False,
24
+ "v2_signing": False,
25
+ "v3_signing": False,
26
+ }
27
+
28
+ try:
29
+ with zipfile.ZipFile(self.apk_path, 'r') as zf:
30
+ for info in zf.infolist():
31
+ if info.filename.startswith("META-INF/"):
32
+ signatures["meta_inf_files"].append({
33
+ "name": info.filename,
34
+ "size": info.file_size,
35
+ })
36
+
37
+ if info.filename.endswith('.RSA') or info.filename.endswith('.DSA') or info.filename.endswith('.EC'):
38
+ signatures["cert_files"].append(info.filename)
39
+ signatures["v1_signing"] = True
40
+ elif info.filename.endswith('.SF'):
41
+ signatures["sf_files"].append(info.filename)
42
+ elif info.filename == "META-INF/MANIFEST.MF":
43
+ signatures["manifest_mf"] = info.filename
44
+
45
+ # Check for APK Signing Block (v2/v3) - look for magic bytes
46
+ # This is a simplified check
47
+ with open(self.apk_path, 'rb') as f:
48
+ # Read end of central directory
49
+ f.seek(-22, 2)
50
+ eocd = f.read(22)
51
+ if len(eocd) >= 22:
52
+ cd_size = int.from_bytes(eocd[12:16], 'little')
53
+ cd_offset = int.from_bytes(eocd[16:20], 'little')
54
+
55
+ # Check for APK Signing Block before central directory
56
+ f.seek(max(0, cd_offset - 32))
57
+ block = f.read(32)
58
+ if b'APK Sig Block' in block or any(b == 0x504b0304 for b in [block[i:i+4] for i in range(len(block)-3)]):
59
+ signatures["v2_signing"] = True
60
+ signatures["v3_signing"] = True
61
+ except Exception:
62
+ pass
63
+
64
+ return signatures
65
+
66
+ def get_certificate_info(self) -> List[Dict[str, Any]]:
67
+ """Extract certificate information from RSA/DSA files."""
68
+ certs = []
69
+ try:
70
+ with zipfile.ZipFile(self.apk_path, 'r') as zf:
71
+ for info in zf.infolist():
72
+ if info.filename.endswith(('.RSA', '.DSA', '.EC')):
73
+ data = zf.read(info.filename)
74
+ certs.append({
75
+ "filename": info.filename,
76
+ "size": len(data),
77
+ "sha256": hashlib.sha256(data).hexdigest(),
78
+ "md5": hashlib.md5(data).hexdigest(),
79
+ })
80
+ except Exception:
81
+ pass
82
+ return certs
83
+
84
+ def get_full_analysis(self) -> Dict[str, Any]:
85
+ """Get complete signature analysis."""
86
+ sig_files = self.get_signature_files()
87
+ certs = self.get_certificate_info()
88
+
89
+ return {
90
+ "signature_files": sig_files,
91
+ "certificates": certs,
92
+ "has_v1_signing": sig_files["v1_signing"],
93
+ "has_v2_signing": sig_files["v2_signing"],
94
+ "has_v3_signing": sig_files["v3_signing"],
95
+ }
96
+
97
+
98
+ def compare_signatures(orig_apk: str, mod_apk: str) -> Dict[str, Any]:
99
+ """Compare signatures between two APKs."""
100
+ orig = SignatureAnalyzer(orig_apk)
101
+ mod = SignatureAnalyzer(mod_apk)
102
+
103
+ orig_data = orig.get_full_analysis()
104
+ mod_data = mod.get_full_analysis()
105
+
106
+ # Compare certificates
107
+ orig_certs = {c["sha256"]: c for c in orig_data["certificates"]}
108
+ mod_certs = {c["sha256"]: c for c in mod_data["certificates"]}
109
+
110
+ cert_changed = orig_certs != mod_certs
111
+
112
+ # Compare signing schemes
113
+ scheme_changed = (
114
+ orig_data["has_v1_signing"] != mod_data["has_v1_signing"] or
115
+ orig_data["has_v2_signing"] != mod_data["has_v2_signing"] or
116
+ orig_data["has_v3_signing"] != mod_data["has_v3_signing"]
117
+ )
118
+
119
+ return {
120
+ "original": orig_data,
121
+ "modified": mod_data,
122
+ "signature_changed": cert_changed or scheme_changed,
123
+ "certificates_match": not cert_changed,
124
+ "schemes_match": not scheme_changed,
125
+ "warning": cert_changed,
126
+ }
src/utils.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ APK Deep Diff Analyzer - Utilities Module
3
+ """
4
+ import hashlib
5
+ import os
6
+ import tempfile
7
+ import shutil
8
+ import zipfile
9
+ from pathlib import Path
10
+ from typing import Dict, List, Tuple, Optional, Any
11
+ import time
12
+
13
+
14
+ def get_file_hash(filepath: str, algorithm: str = "sha256", chunk_size: int = 8192) -> str:
15
+ """Calculate file hash using streaming (memory efficient)."""
16
+ h = hashlib.new(algorithm)
17
+ with open(filepath, "rb") as f:
18
+ while chunk := f.read(chunk_size):
19
+ h.update(chunk)
20
+ return h.hexdigest()
21
+
22
+
23
+ def get_file_size_formatted(size_bytes: int) -> str:
24
+ """Format file size in human readable format."""
25
+ if size_bytes < 1024:
26
+ return f"{size_bytes} B"
27
+ elif size_bytes < 1024 * 1024:
28
+ return f"{size_bytes / 1024:.2f} KB"
29
+ elif size_bytes < 1024 * 1024 * 1024:
30
+ return f"{size_bytes / (1024 * 1024):.2f} MB"
31
+ else:
32
+ return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"
33
+
34
+
35
+ def create_temp_dir(prefix: str = "apk_") -> str:
36
+ """Create a temporary directory."""
37
+ return tempfile.mkdtemp(prefix=prefix)
38
+
39
+
40
+ def cleanup_temp_dir(path: str):
41
+ """Remove temporary directory and all contents."""
42
+ if os.path.exists(path):
43
+ shutil.rmtree(path, ignore_errors=True)
44
+
45
+
46
+ def extract_apk(apk_path: str, extract_dir: str) -> bool:
47
+ """Extract APK (ZIP) contents to directory."""
48
+ try:
49
+ with zipfile.ZipFile(apk_path, 'r') as zf:
50
+ zf.extractall(extract_dir)
51
+ return True
52
+ except Exception:
53
+ return False
54
+
55
+
56
+ def get_apk_info(apk_path: str) -> Dict[str, Any]:
57
+ """Get basic APK file information."""
58
+ info = {
59
+ "filename": os.path.basename(apk_path),
60
+ "size": os.path.getsize(apk_path),
61
+ "size_formatted": get_file_size_formatted(os.path.getsize(apk_path)),
62
+ "sha256": get_file_hash(apk_path, "sha256"),
63
+ "md5": get_file_hash(apk_path, "md5"),
64
+ }
65
+ return info
66
+
67
+
68
+ def list_files_recursive(directory: str) -> List[Tuple[str, int, str]]:
69
+ """
70
+ List all files recursively.
71
+ Returns list of (relative_path, size, sha256) tuples.
72
+ """
73
+ files = []
74
+ base_path = Path(directory)
75
+ for filepath in base_path.rglob("*"):
76
+ if filepath.is_file():
77
+ rel_path = filepath.relative_to(base_path).as_posix()
78
+ size = filepath.stat().st_size
79
+ sha256 = get_file_hash(str(filepath))
80
+ files.append((rel_path, size, sha256))
81
+ return files
82
+
83
+
84
+ def get_zip_entries(apk_path: str) -> List[Dict[str, Any]]:
85
+ """Get ZIP entry information from APK."""
86
+ entries = []
87
+ try:
88
+ with zipfile.ZipFile(apk_path, 'r') as zf:
89
+ for info in zf.infolist():
90
+ entries.append({
91
+ "filename": info.filename,
92
+ "size": info.file_size,
93
+ "compressed_size": info.compress_size,
94
+ "compression": info.compress_type,
95
+ "crc": info.CRC,
96
+ })
97
+ except Exception:
98
+ pass
99
+ return entries
100
+
101
+
102
+ def calculate_similarity(size1: int, size2: int, hash1: str, hash2: str) -> float:
103
+ """Calculate a simple similarity score between two files."""
104
+ if hash1 == hash2:
105
+ return 100.0
106
+ if size1 == 0 and size2 == 0:
107
+ return 100.0
108
+ if size1 == 0 or size2 == 0:
109
+ return 0.0
110
+ size_diff = abs(size1 - size2) / max(size1, size2)
111
+ similarity = max(0.0, (1.0 - size_diff) * 100)
112
+ return round(similarity, 2)
113
+
114
+
115
+ def format_time_elapsed(seconds: float) -> str:
116
+ """Format elapsed time."""
117
+ if seconds < 60:
118
+ return f"{seconds:.2f} ثانية"
119
+ elif seconds < 3600:
120
+ return f"{seconds / 60:.2f} دقيقة"
121
+ else:
122
+ return f"{seconds / 3600:.2f} ساعة"
123
+
124
+
125
+ class ProgressTracker:
126
+ """Track analysis progress."""
127
+
128
+ STAGES = [
129
+ "Uploading",
130
+ "Validating APK",
131
+ "Extracting APK",
132
+ "Analyzing ZIP structure",
133
+ "Analyzing AndroidManifest.xml",
134
+ "Comparing resources",
135
+ "Comparing DEX files",
136
+ "Comparing native libraries",
137
+ "Comparing assets",
138
+ "Comparing signatures",
139
+ "Calculating hashes",
140
+ "Generating report",
141
+ ]
142
+
143
+ def __init__(self):
144
+ self.current_stage = 0
145
+ self.start_time = time.time()
146
+ self.stage_times = {}
147
+
148
+ def set_stage(self, stage_index: int):
149
+ """Set current stage."""
150
+ if 0 <= stage_index < len(self.STAGES):
151
+ self.current_stage = stage_index
152
+ self.stage_times[stage_index] = time.time()
153
+
154
+ def get_progress(self) -> Tuple[float, str, str]:
155
+ """Get progress percentage, current stage name, and time elapsed."""
156
+ total = len(self.STAGES)
157
+ pct = (self.current_stage / total) * 100
158
+ stage_name = self.STAGES[self.current_stage] if self.current_stage < total else "Complete"
159
+ elapsed = format_time_elapsed(time.time() - self.start_time)
160
+ return pct, stage_name, elapsed
161
+
162
+ def get_stage_time(self, stage_index: int) -> str:
163
+ """Get time spent on a specific stage."""
164
+ if stage_index in self.stage_times and stage_index + 1 in self.stage_times:
165
+ elapsed = self.stage_times[stage_index + 1] - self.stage_times[stage_index]
166
+ return format_time_elapsed(elapsed)
167
+ return "N/A"