Repository navigation
Expand file tree
/
Copy pathanalyzer_bot.py
More file actions
1630 lines (1353 loc) · 63.8 KB
/
Copy pathanalyzer_bot.py
File metadata and controls
1630 lines (1353 loc) · 63.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Enhanced SO Library & C File Analysis Bot with Parallel Processing
Features:
- Parallel .so file processing
- PATCH_LIB and HOOK_LIB code generation
- C file hook generation with AI (DeepSeek + OpenRouter fallback)
- Configurable output limits
- Unique function implementations
- Improved error handling and UI
"""
import os
import json
import subprocess
import logging
import re
import asyncio
import aiohttp
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, Tuple
from concurrent.futures import ThreadPoolExecutor
import hashlib
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
CallbackQueryHandler,
ContextTypes,
filters
)
from openai import OpenAI
# Configure logging with better formatting
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Configuration
OWNER_ID = user-id-here
TELEGRAM_BOT_TOKEN = "bot-token"
# AI API Configuration - Multiple fallback options
DEEPSEEK_API_KEY = "sk-key-here"
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
DEEPSEEK_MODEL = "deepseek-chat"
OPENROUTER_API_KEY = "sk-key-here"
OPENROUTER_API_URL = "https://openrouter.ai/api/v1"
# Models (aligned with req.py)
MODEL_TEXT = "mistralai/devstral-2512:free"
MODEL_VISION = "qwen/qwen-2.5-vl-7b-instruct:free"
MODEL_GEN = "mistralai/devstral-2512:free"
# Multiple OpenRouter models to try (in order of preference)
OPENROUTER_MODELS = [
MODEL_TEXT,
MODEL_GEN,
MODEL_VISION,
]
# Initialize OpenAI client for OpenRouter (better compatibility with free models)
openrouter_client = OpenAI(
base_url=OPENROUTER_API_URL,
api_key=OPENROUTER_API_KEY
)
# Get script directory for saving files
SCRIPT_DIR = Path(__file__).parent.resolve()
USERS_FILE = SCRIPT_DIR / "users.json"
CONFIG_FILE = SCRIPT_DIR / "config.json"
ANALYSIS_DIR = SCRIPT_DIR / "analysis_results"
ANALYSIS_DIR.mkdir(exist_ok=True)
# Default limits
DEFAULT_PATCH_LIMIT = 15
DEFAULT_HOOK_LIMIT = 10
class ConfigManager:
"""Manages configuration for patch and hook limits"""
def __init__(self):
self.config = self._load_config()
def _load_config(self):
"""Load config from JSON file"""
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE, 'r') as f:
return json.load(f)
except:
return {
"patch_limit": DEFAULT_PATCH_LIMIT,
"hook_limit": DEFAULT_HOOK_LIMIT
}
return {
"patch_limit": DEFAULT_PATCH_LIMIT,
"hook_limit": DEFAULT_HOOK_LIMIT
}
def _save_config(self):
"""Save config to JSON file"""
with open(CONFIG_FILE, 'w') as f:
json.dump(self.config, f, indent=2)
def set_patch_limit(self, limit: int):
"""Set patch output limit"""
self.config["patch_limit"] = limit
self._save_config()
def set_hook_limit(self, limit: int):
"""Set hook output limit"""
self.config["hook_limit"] = limit
self._save_config()
def get_patch_limit(self) -> int:
return self.config.get("patch_limit", DEFAULT_PATCH_LIMIT)
def get_hook_limit(self) -> int:
return self.config.get("hook_limit", DEFAULT_HOOK_LIMIT)
config_manager = ConfigManager()
class UserManager:
"""Manages user permissions and admin list"""
def __init__(self):
self.data = self._load_data()
def _load_data(self):
"""Load user data from JSON file"""
if USERS_FILE.exists():
try:
with open(USERS_FILE, 'r') as f:
return json.load(f)
except:
return {
"admins": [],
"approved_users": [],
"disapproved_users": []
}
return {
"admins": [],
"approved_users": [],
"disapproved_users": []
}
def _save_data(self):
"""Save user data to JSON file"""
with open(USERS_FILE, 'w') as f:
json.dump(self.data, f, indent=2)
def is_owner(self, user_id: int) -> bool:
return user_id == OWNER_ID
def is_admin(self, user_id: int) -> bool:
return user_id in self.data["admins"]
def is_approved(self, user_id: int) -> bool:
return user_id in self.data["approved_users"]
def approve_user(self, user_id: int):
if user_id not in self.data["approved_users"]:
self.data["approved_users"].append(user_id)
if user_id in self.data["disapproved_users"]:
self.data["disapproved_users"].remove(user_id)
self._save_data()
def disapprove_user(self, user_id: int):
if user_id in self.data["approved_users"]:
self.data["approved_users"].remove(user_id)
if user_id not in self.data["disapproved_users"]:
self.data["disapproved_users"].append(user_id)
self._save_data()
def add_admin(self, user_id: int):
if user_id not in self.data["admins"]:
self.data["admins"].append(user_id)
self._save_data()
def remove_admin(self, user_id: int):
if user_id in self.data["admins"]:
self.data["admins"].remove(user_id)
self._save_data()
user_manager = UserManager()
class Radare2Analyzer:
"""Enhanced analyzer using radare2 for comprehensive binary analysis"""
def __init__(self, file_path: str):
self.file_path = file_path
self.lib_name = Path(file_path).name
self.analysis_data = {}
def run_r2_command(self, command: str) -> str:
"""Execute radare2 command and return output"""
try:
result = subprocess.run(
['r2', '-q', '-c', command, self.file_path],
capture_output=True,
text=True,
timeout=60
)
return result.stdout
except Exception as e:
logger.error(f"r2 command '{command}' failed: {e}")
return f"Error: {e}"
async def analyze_async(self) -> Dict:
"""Perform comprehensive radare2 analysis with parallel execution"""
logger.info(f"Starting parallel radare2 analysis of {self.lib_name}")
# Commands to run in parallel
commands = {
"exports": "iE",
"imports": "ii",
"strings": "izz",
"symbols": "is",
"sections": "iS",
"relocations": "ir",
"info": "i",
"entrypoints": "ie",
"libraries": "il",
"binary_info": "ij"
}
# Run commands in parallel using ThreadPoolExecutor
loop = asyncio.get_event_loop()
with ThreadPoolExecutor(max_workers=len(commands)) as executor:
tasks = {
key: loop.run_in_executor(executor, self.run_r2_command, cmd)
for key, cmd in commands.items()
}
# Wait for all tasks to complete
for key, task in tasks.items():
self.analysis_data[key] = await task
logger.info(f"Parallel radare2 analysis complete for {self.lib_name}")
return self.analysis_data
def save_analysis(self) -> tuple:
"""Save analysis to JSON and TXT files"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
base_name = f"{self.lib_name}_{timestamp}"
# Save JSON
json_path = ANALYSIS_DIR / f"{base_name}.json"
with open(json_path, 'w') as f:
json.dump(self.analysis_data, f, indent=2)
# Save TXT
txt_path = ANALYSIS_DIR / f"{base_name}.txt"
with open(txt_path, 'w') as f:
f.write(f"Radare2 Library Analysis Report\n")
f.write(f"{'='*80}\n")
f.write(f"Library: {self.lib_name}\n")
f.write(f"Analysis Date: {datetime.now().isoformat()}\n")
f.write(f"{'='*80}\n\n")
for key, value in self.analysis_data.items():
f.write(f"\n{'='*80}\n")
f.write(f"{key.upper().replace('_', ' ')}\n")
f.write(f"{'='*80}\n")
f.write(f"{value}\n")
return str(json_path), str(txt_path)
class CFileAnalyzer:
"""Analyzer for C decompiled files"""
def __init__(self, file_path: str):
self.file_path = file_path
self.file_name = Path(file_path).name
self.content = ""
async def load_content(self):
"""Load C file content"""
with open(self.file_path, 'r', encoding='utf-8', errors='ignore') as f:
self.content = f.read()
return self.content
def extract_functions(self) -> List[Dict]:
"""Extract function signatures and addresses from C file"""
functions = []
# Pattern to match function definitions with addresses
# Example: __int64 __fastcall sub_6646538(_QWORD *a1)
pattern = r'(__int64|int|void|char|float|double)\s+(?:__fastcall\s+)?(\w+)\s*\([^)]*\)'
matches = re.finditer(pattern, self.content)
for match in matches:
func_name = match.group(2)
if func_name.startswith('sub_'):
# Extract hex address from function name
addr = func_name.replace('sub_', '')
if addr:
functions.append({
'name': func_name,
'address': f"0x{addr}",
'signature': match.group(0)
})
return functions
class AIAnalyzer:
"""AI-powered analysis with DeepSeek (primary) and OpenRouter (fallback)"""
@staticmethod
def _load_previous_values(lib_name: str) -> Dict:
"""Load previously extracted values for this library"""
history_file = ANALYSIS_DIR / f"{lib_name}_value_history.json"
if history_file.exists():
try:
with open(history_file, 'r') as f:
data = json.load(f)
return {
'patches': set(data.get('previous_patches', [])),
'hooks': set(data.get('previous_hooks', [])),
'functions': set(data.get('previous_functions', []))
}
except:
return {'patches': set(), 'hooks': set(), 'functions': set()}
return {'patches': set(), 'hooks': set(), 'functions': set()}
@staticmethod
def _save_values(lib_name: str, patches: list, hooks: list, functions: list):
"""Save extracted values to history"""
history_file = ANALYSIS_DIR / f"{lib_name}_value_history.json"
previous = AIAnalyzer._load_previous_values(lib_name)
previous['patches'].update(patches)
previous['hooks'].update(hooks)
previous['functions'].update(functions)
with open(history_file, 'w') as f:
json.dump({
'previous_patches': list(previous['patches']),
'previous_hooks': list(previous['hooks']),
'previous_functions': list(previous['functions']),
'last_updated': datetime.now().isoformat()
}, f, indent=2)
@staticmethod
async def _call_ai_api(system_prompt: str, user_prompt: str, temperature: float = 0.9, timeout: int = 120) -> Dict:
"""
Call AI API with automatic fallback from DeepSeek to OpenRouter (tries multiple models)
Returns: {'success': bool, 'content': str, 'provider': str, 'error': str}
"""
# Try DeepSeek first (if it has balance)
try:
logger.info("🔵 Attempting DeepSeek API...")
async with aiohttp.ClientSession() as session:
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {DEEPSEEK_API_KEY}"
}
payload = {
"model": DEEPSEEK_MODEL,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
"temperature": temperature
}
async with session.post(DEEPSEEK_API_URL, headers=headers, json=payload, timeout=timeout) as response:
if response.status == 200:
result = await response.json()
content = result['choices'][0]['message']['content']
logger.info("✅ DeepSeek API successful")
return {
'success': True,
'content': content,
'provider': 'DeepSeek',
'error': None
}
elif response.status == 402:
error_text = await response.text()
logger.warning(f"⚠️ DeepSeek: No balance, skipping to fallback")
else:
error_text = await response.text()
logger.warning(f"⚠️ DeepSeek API failed: {response.status}")
except Exception as e:
logger.warning(f"⚠️ DeepSeek API exception: {str(e)}")
# Fallback to OpenRouter - try multiple models
logger.info("🟢 Trying OpenRouter API with multiple models...")
for idx, model in enumerate(OPENROUTER_MODELS, 1):
try:
logger.info(f" 📡 Attempt {idx}/{len(OPENROUTER_MODELS)}: {model}")
# Run synchronous OpenAI call in thread pool to avoid blocking
loop = asyncio.get_event_loop()
def call_openrouter():
response = openrouter_client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=temperature
)
return response.choices[0].message.content
# Execute in thread pool with timeout
content = await asyncio.wait_for(
loop.run_in_executor(None, call_openrouter),
timeout=timeout
)
logger.info(f"✅ OpenRouter successful with model: {model}")
return {
'success': True,
'content': content,
'provider': f'OpenRouter ({model.split("/")[-1].replace(":free", "")})',
'error': None
}
except asyncio.TimeoutError:
logger.warning(f" ⏱️ Timeout with {model}, trying next...")
continue
except Exception as e:
error_msg = str(e)
if "404" in error_msg and "data policy" in error_msg.lower():
logger.warning(f" ⚠️ {model} requires privacy config, trying next...")
elif "rate limit" in error_msg.lower():
logger.warning(f" ⚠️ {model} rate limited, trying next...")
else:
logger.warning(f" ❌ {model} failed: {error_msg[:100]}")
continue
# All APIs failed
logger.error("❌ All AI APIs exhausted")
return {
'success': False,
'content': None,
'provider': None,
'error': (
"All AI APIs failed:\n"
"• DeepSeek: Insufficient balance\n"
"• OpenRouter: All models failed or require configuration\n\n"
"💡 Solutions:\n"
"1. Add balance to DeepSeek account\n"
"2. Configure privacy settings at: https://openrouter.ai/settings/privacy\n"
"3. Try again later (rate limits may be temporary)"
)
}
@staticmethod
async def analyze_with_ai_parallel(lib_name: str, analysis_data: Dict) -> Dict:
"""Send multiple parallel requests to AI for faster analysis"""
# Load previously extracted values
previous_values = AIAnalyzer._load_previous_values(lib_name)
patch_limit = config_manager.get_patch_limit()
hook_limit = config_manager.get_hook_limit()
# Split analysis data into chunks for parallel processing
exports = analysis_data.get('exports', '')
imports = analysis_data.get('imports', '')
strings = analysis_data.get('strings', '')
symbols = analysis_data.get('symbols', '')
sections = analysis_data.get('sections', '')
# Create multiple AI requests in parallel
tasks = [
AIAnalyzer._request_patches(lib_name, exports, symbols, sections, previous_values['patches'], patch_limit),
AIAnalyzer._request_hooks(lib_name, exports, imports, strings, previous_values['hooks'], previous_values['functions'], hook_limit)
]
# Execute all requests in parallel
results = await asyncio.gather(*tasks, return_exceptions=True)
# Combine results
patches_result = results[0] if not isinstance(results[0], Exception) else {'patches': [], 'error': str(results[0]), 'provider': None}
hooks_result = results[1] if not isinstance(results[1], Exception) else {'hooks': [], 'error': str(results[1]), 'provider': None}
# Save new values
all_patches = [p['address'] for p in patches_result.get('patches', [])]
all_hooks = [h['address'] for h in hooks_result.get('hooks', [])]
all_functions = [h['function_name'] for h in hooks_result.get('hooks', [])]
if all_patches or all_hooks:
AIAnalyzer._save_values(lib_name, all_patches, all_hooks, all_functions)
return {
'success': True,
'lib_name': lib_name,
'patches': patches_result.get('patches', []),
'hooks': hooks_result.get('hooks', []),
'provider_patches': patches_result.get('provider', 'Unknown'),
'provider_hooks': hooks_result.get('provider', 'Unknown'),
'previous_count': {
'patches': len(previous_values['patches']),
'hooks': len(previous_values['hooks'])
},
'timestamp': datetime.now().isoformat()
}
@staticmethod
async def _request_patches(lib_name: str, exports: str, symbols: str, sections: str, previous: set, limit: int) -> Dict:
"""Request PATCH_LIB format from AI"""
exclusion_text = ""
if previous:
exclusion_text = f"\n\n**CRITICAL: DO NOT USE THESE PREVIOUSLY EXTRACTED ADDRESSES:**\n{', '.join(sorted(previous))}\n\nYou MUST find NEW addresses!"
system_prompt = f"""You are an expert reverse engineer specializing in Android game anti-cheat bypass.
Your task is to analyze the binary data and generate EXACTLY {limit} PATCH_LIB entries.
Identify which functions likely ban, kick, or suspend players, and prioritize those targets.
**FORMAT REQUIRED:**
PATCH_LIB("{lib_name}", "0xADDRESS", "00 00 80 D2 C0 03 5F D6");
**Requirements:**
1. Extract {limit} unique memory addresses from the provided data
2. Each address must be a real address from exports, symbols, or sections
3. Use the hex patch bytes: "00 00 80 D2 C0 03 5F D6" (ARM64 NOP + RET)
4. Focus on security check functions, validation routines, anti-cheat checks
5. DO NOT repeat previously used addresses
6. Addresses should target functions that can be bypassed
**Response Format:**
Provide ONLY the PATCH_LIB lines, one per line, no explanations."""
user_prompt = f"""Library: {lib_name}
EXPORTS:
{exports}
SYMBOLS:
{symbols}
SECTIONS:
{sections}
{exclusion_text}
Generate {limit} PATCH_LIB entries for bypassing anti-cheat mechanisms. Focus on functions that cause player bans or kicks."""
# Call AI with automatic fallback
ai_response = await AIAnalyzer._call_ai_api(system_prompt, user_prompt, temperature=0.9, timeout=120)
if not ai_response['success']:
return {'patches': [], 'error': ai_response['error'], 'provider': None}
# Parse PATCH_LIB entries
patches = []
pattern = r'PATCH_LIB\s*\(\s*"([^"]+)"\s*,\s*"(0x[0-9a-fA-F]+)"\s*,\s*"([^"]+)"\s*\)'
matches = re.finditer(pattern, ai_response['content'])
for match in matches:
lib, addr, bytes_str = match.groups()
addr_lower = addr.lower()
if addr_lower not in {p.lower() for p in previous}:
patches.append({
'lib': lib,
'address': addr,
'bytes': bytes_str,
'code': f'PATCH_LIB("{lib}", "{addr}", "{bytes_str}");'
})
return {
'patches': patches[:limit],
'provider': ai_response['provider']
}
@staticmethod
async def _request_hooks(lib_name: str, exports: str, imports: str, strings: str, previous_hooks: set, previous_functions: set, limit: int) -> Dict:
"""Request HOOK_LIB format from AI with unique function implementations"""
exclusion_text = ""
if previous_hooks:
exclusion_text = f"\n\n**CRITICAL: DO NOT USE THESE PREVIOUSLY EXTRACTED ADDRESSES:**\n{', '.join(sorted(previous_hooks))}"
if previous_functions:
exclusion_text += f"\n\n**DO NOT USE THESE FUNCTION PATTERNS:**\n{', '.join(sorted(previous_functions))}\n\nCreate COMPLETELY DIFFERENT function implementations!"
system_prompt = f"""You are an expert reverse engineer creating hook functions for Android game modding.
Your task is to generate EXACTLY {limit} unique HOOK implementations.
Identify which functions likely ban, kick, or suspend players, and prioritize those targets.
**FORMAT REQUIRED (Generate BOTH formats for each hook):**
Format 1 - NO_ORIG (Direct bypass):
```
HOOK_LIB_NO_ORIG("{lib_name}", "0xADDRESS", function_name);
```
Format 2 - WITH_ORIG (Wrapper with modifications):
```
__int64 (*orig_function_name)(__int64, __int64*);
__int64 function_name(__int64 a1, __int64 *a2) {{
// Unique implementation here
return orig_function_name(a1, a2);
}}
HOOK_LIB("{lib_name}", "0xADDRESS", function_name, orig_function_name);
```
**CRITICAL REQUIREMENTS:**
1. Generate {limit} DIFFERENT hook implementations
2. Each function must have UNIQUE logic - DO NOT repeat patterns
3. Use different variable names, different checks, different modifications
4. Create diverse bypass strategies:
- Memory zeroing (different offsets each time)
- Return value manipulation (different values)
- Parameter validation bypass (different conditions)
- Flag manipulation (different flags)
- Pointer nullification (different pointers)
5. Extract real addresses from the binary data
6. Use creative function names (not just sub_XXXXX)
7. Add meaningful comments explaining what each hook does
**Response Format:**
For each hook, provide:
1. Function implementation with unique logic
2. Both HOOK_LIB_NO_ORIG and HOOK_LIB formats
3. Comment explaining bypass strategy"""
user_prompt = f"""Library: {lib_name}
EXPORTS (Functions to hook):
{exports}
IMPORTS (External dependencies):
{imports}
STRINGS (Context clues):
{strings}
{exclusion_text}
Generate {limit} UNIQUE hook implementations with DIVERSE bypass strategies. Focus on functions that ban players. Make each function implementation COMPLETELY DIFFERENT from others!"""
# Call AI with automatic fallback
ai_response = await AIAnalyzer._call_ai_api(system_prompt, user_prompt, temperature=1.0, timeout=180)
if not ai_response['success']:
return {'hooks': [], 'error': ai_response['error'], 'provider': None}
# Parse hook implementations
hooks = []
# Pattern for HOOK_LIB_NO_ORIG
pattern_no_orig = r'HOOK_LIB_NO_ORIG\s*\(\s*"([^"]+)"\s*,\s*"(0x[0-9a-fA-F]+)"\s*,\s*(\w+)\s*\)'
# Pattern for HOOK_LIB with implementation
pattern_impl = r'(__int64[^;]+;[\s\S]+?HOOK_LIB\s*\([^)]+\)\s*;)'
# Extract implementations
impl_matches = re.finditer(pattern_impl, ai_response['content'])
for match in impl_matches:
impl_block = match.group(1)
# Extract address from this block
addr_match = re.search(r'"(0x[0-9a-fA-F]+)"', impl_block)
if addr_match:
addr = addr_match.group(1)
addr_lower = addr.lower()
if addr_lower not in {h.lower() for h in previous_hooks}:
# Extract function name
func_match = re.search(r'(\w+)\s*\(__int64', impl_block)
func_name = func_match.group(1) if func_match else f"hook_{addr[2:]}"
if func_name not in previous_functions:
hooks.append({
'lib': lib_name,
'address': addr,
'function_name': func_name,
'code': impl_block.strip(),
'type': 'HOOK_LIB'
})
# Also extract NO_ORIG hooks
no_orig_matches = re.finditer(pattern_no_orig, ai_response['content'])
for match in no_orig_matches:
lib, addr, func_name = match.groups()
addr_lower = addr.lower()
if addr_lower not in {h.lower() for h in previous_hooks}:
if func_name not in previous_functions:
hooks.append({
'lib': lib,
'address': addr,
'function_name': func_name,
'code': f'HOOK_LIB_NO_ORIG("{lib}", "{addr}", {func_name});',
'type': 'HOOK_LIB_NO_ORIG'
})
return {
'hooks': hooks[:limit],
'provider': ai_response['provider']
}
@staticmethod
async def analyze_c_file(file_name: str, content: str) -> Dict:
"""Analyze C file and generate hooks"""
previous_values = AIAnalyzer._load_previous_values(file_name)
hook_limit = config_manager.get_hook_limit()
# Extract real library name from file
lib_name_match = re.search(r'(lib\w+\.so)', file_name)
real_lib_name = lib_name_match.group(1) if lib_name_match else "libanogs.so"
exclusion_text = ""
if previous_values['hooks']:
exclusion_text = f"\n\n**CRITICAL: DO NOT USE THESE ADDRESSES:**\n{', '.join(sorted(previous_values['hooks']))}"
if previous_values['functions']:
exclusion_text += f"\n\n**DO NOT REUSE THESE FUNCTION PATTERNS:**\n{', '.join(sorted(previous_values['functions']))}"
primary_chunk = content
system_prompt = f"""You are an expert C code analyzer and hook generator for game modding.
Analyze the provided decompiled C code and generate {hook_limit} UNIQUE hook implementations.
**REQUIREMENTS:**
1. Identify {hook_limit} different functions from the C code
2. Extract the real function address from function names (e.g., sub_51B774 → 0x51B774)
3. Generate BOTH hook formats for each function
4. Create UNIQUE implementations - each should use DIFFERENT bypass techniques
5. Use the real library name: {real_lib_name}
**HOOK FORMATS TO GENERATE:**
Format 1 - Simple Hook:
```
HOOK_LIB_NO_ORIG("{real_lib_name}", "0xADDRESS", function_name);
```
Format 2 - Advanced Hook with unique implementation:
```
__int64 (*orig_function)(__int64, __int64*);
__int64 function(__int64 a1, __int64 *a2) {{
// UNIQUE bypass logic here - make it DIFFERENT from others!
return orig_function(a1, a2);
}}
HOOK_LIB("{real_lib_name}", "0xADDRESS", function, orig_function); // description
```
**DIVERSITY REQUIREMENTS:**
Each hook MUST use different techniques - different memory offsets, return values, validations, etc.
**OUTPUT:**
Generate {hook_limit} hooks with COMPLETELY DIFFERENT implementations. Add descriptive comments for each."""
user_prompt = f"""C Decompiled Code ({len(content)} bytes):
{primary_chunk}
{exclusion_text}
Analyze the code and generate {hook_limit} UNIQUE hook implementations with DIVERSE bypass strategies for {real_lib_name}. Focus on ban-related functions."""
# Call AI with automatic fallback
ai_response = await AIAnalyzer._call_ai_api(system_prompt, user_prompt, temperature=1.0, timeout=300)
if not ai_response['success']:
return {
'success': False,
'error': ai_response['error'],
'provider': None
}
# Parse all hooks
hooks = []
# Extract full hook implementations
pattern_impl = r'(__int64[^;]+;[\s\S]+?HOOK_LIB\s*\([^)]+\)\s*;[^\n]*)'
impl_matches = re.finditer(pattern_impl, ai_response['content'])
for match in impl_matches:
impl_block = match.group(1)
# Extract address
addr_match = re.search(r'"(0x[0-9a-fA-F]+)"', impl_block)
if addr_match:
addr = addr_match.group(1)
addr_lower = addr.lower()
if addr_lower not in {h.lower() for h in previous_values['hooks']}:
# Extract function name
func_match = re.search(r'(\w+)\s*\(__int64', impl_block)
func_name = func_match.group(1) if func_match else f"hook_{addr[2:]}"
if func_name not in previous_values['functions']:
hooks.append({
'lib': real_lib_name,
'address': addr,
'function_name': func_name,
'code': impl_block.strip(),
'type': 'HOOK_LIB'
})
# Extract NO_ORIG hooks
pattern_no_orig = r'HOOK_LIB_NO_ORIG\s*\(\s*"([^"]+)"\s*,\s*"(0x[0-9a-fA-F]+)"\s*,\s*(\w+)\s*\)'
no_orig_matches = re.finditer(pattern_no_orig, ai_response['content'])
for match in no_orig_matches:
lib, addr, func_name = match.groups()
addr_lower = addr.lower()
if addr_lower not in {h.lower() for h in previous_values['hooks']}:
if func_name not in previous_values['functions']:
hooks.append({
'lib': lib,
'address': addr,
'function_name': func_name,
'code': f'HOOK_LIB_NO_ORIG("{lib}", "{addr}", {func_name});',
'type': 'HOOK_LIB_NO_ORIG'
})
# Save new hooks
all_addrs = [h['address'] for h in hooks]
all_funcs = [h['function_name'] for h in hooks]
if hooks:
AIAnalyzer._save_values(file_name, [], all_addrs, all_funcs)
return {
'success': True,
'lib_name': real_lib_name,
'hooks': hooks[:hook_limit],
'provider': ai_response['provider'],
'previous_count': len(previous_values['hooks']),
'timestamp': datetime.now().isoformat()
}
# Bot Handlers
def create_main_keyboard(user_id: int):
"""Create main menu keyboard based on user permissions"""
keyboard = []
if user_manager.is_owner(user_id) or user_manager.is_admin(user_id):
keyboard.append([
InlineKeyboardButton("👤 Approve User", callback_data="menu_approve"),
InlineKeyboardButton("🚫 Disapprove User", callback_data="menu_disapprove")
])
if user_manager.is_owner(user_id):
keyboard.append([
InlineKeyboardButton("⚡ Add Admin", callback_data="menu_add_admin"),
InlineKeyboardButton("❌ Remove Admin", callback_data="menu_remove_admin")
])
keyboard.append([
InlineKeyboardButton("⚙️ Set Patch Limit", callback_data="menu_set_patch"),
InlineKeyboardButton("⚙️ Set Hook Limit", callback_data="menu_set_hook")
])
if user_manager.is_approved(user_id):
keyboard.append([
InlineKeyboardButton("📤 Analyze .so Library", callback_data="menu_analyze_so"),
InlineKeyboardButton("📄 Analyze .c File", callback_data="menu_analyze_c")
])
keyboard.append([
InlineKeyboardButton("ℹ️ My Status", callback_data="menu_status"),
InlineKeyboardButton("❓ Help", callback_data="menu_help")
])
return InlineKeyboardMarkup(keyboard)
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle start command with button UI"""
user_id = update.effective_user.id
username = update.effective_user.username or "User"
welcome_text = (
"🤖 <b>Advanced SO & C File Analyzer v2.0</b>\n\n"
f"Welcome <b>{username}</b>!\n\n"
"✨ <b>Features:</b>\n"
"• Parallel .so analysis\n"
"• PATCH_LIB code generation\n"
"• HOOK_LIB code generation\n"
"• C file hook analysis\n"
"• Configurable output limits\n"
"• <b>Dual AI engines with auto-fallback</b>\n\n"
f"🆔 Your User ID: <code>{user_id}</code>\n\n"
"Choose an option below:"
)
keyboard = create_main_keyboard(user_id)
await update.message.reply_text(
welcome_text,
reply_markup=keyboard,
parse_mode='HTML'
)
async def set_patch_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /set_patch command"""
user_id = update.effective_user.id
if not user_manager.is_owner(user_id):
await update.message.reply_text("❌ Owner only command")
return
try:
if len(context.args) < 1:
current = config_manager.get_patch_limit()
await update.message.reply_text(
f"⚙️ <b>Current patch limit:</b> {current}\n\n"
f"<b>Usage:</b> <code>/set_patch <number></code>\n"
f"<b>Example:</b> <code>/set_patch 20</code>",
parse_mode='HTML'
)
return
limit = int(context.args[0])
if limit < 1 or limit > 50:
await update.message.reply_text("❌ Limit must be between 1 and 50")
return
config_manager.set_patch_limit(limit)
await update.message.reply_text(f"✅ Patch limit set to <b>{limit}</b>", parse_mode='HTML')
except ValueError:
await update.message.reply_text("❌ Invalid number")
async def set_hook_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /set_hook command"""
user_id = update.effective_user.id
if not user_manager.is_owner(user_id):
await update.message.reply_text("❌ Owner only command")
return
try:
if len(context.args) < 1:
current = config_manager.get_hook_limit()
await update.message.reply_text(
f"⚙️ <b>Current hook limit:</b> {current}\n\n"
f"<b>Usage:</b> <code>/set_hook <number></code>\n"
f"<b>Example:</b> <code>/set_hook 15</code>",
parse_mode='HTML'
)
return
limit = int(context.args[0])
if limit < 1 or limit > 30:
await update.message.reply_text("❌ Limit must be between 1 and 30")
return
config_manager.set_hook_limit(limit)
await update.message.reply_text(f"✅ Hook limit set to <b>{limit}</b>", parse_mode='HTML')
except ValueError:
await update.message.reply_text("❌ Invalid number")
async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle button callbacks"""
query = update.callback_query
user_id = query.from_user.id
data = query.data
await query.answer()
if data == "menu_status":
status_text = f"👤 <b>Your Status</b>\n\n🆔 User ID: <code>{user_id}</code>\n\n"
if user_manager.is_owner(user_id):
status_text += "🔑 Role: <b>OWNER</b>\n✅ All permissions granted\n\n"
elif user_manager.is_admin(user_id):
status_text += "⚡ Role: <b>ADMIN</b>\n✅ Can manage users\n\n"
elif user_manager.is_approved(user_id):
status_text += "✅ Status: <b>APPROVED</b>\n✅ Can analyze files\n\n"
else:
status_text += "❌ Status: <b>NOT APPROVED</b>\n❌ Limited access\n\n💡 Contact admin for approval\n\n"
status_text += f"⚙️ <b>Current Settings:</b>\n"
status_text += f"• Patch limit: {config_manager.get_patch_limit()}\n"
status_text += f"• Hook limit: {config_manager.get_hook_limit()}\n\n"