Repository navigation
Expand file tree
/
Copy pathBiDe.php
More file actions
1062 lines (889 loc) · 40 KB
/
Copy pathBiDe.php
File metadata and controls
1062 lines (889 loc) · 40 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
<?php
declare(strict_types=1);
/**
* BiDe (Bitrix Deobfuscator)
* Advanced PHP deobfuscation tool for Bitrix and other obfuscated PHP code
* GitHub: https://github.com/SirAndrewGotham/BiDe
*
* @author SirAndrewGotham
* @version 1.0
* @requires PHP 8.3+
*/
enum DeobfuscationMode
{
case SCAN_NEW;
case USE_EXISTING_LIST;
}
enum FilePattern: string
{
case BASE64_DECODE = '= array(base64_decode(';
case GLOBALS_ARRAY = 'GLOBALS.*array';
case BASE64_GENERIC = 'base64_decode';
}
enum VariableType
{
case STRING;
case VARIABLE_REF;
case SPECIAL;
}
readonly class DeobfuscationConfig
{
public function __construct(
public int $repeater_count = 2,
public string $mappings_file = 'deobfuscation_map.php',
public string $custom_mappings_file = 'custom_mappings.php',
public string $targets_file = 'deobfuscation_targets.txt',
public bool $auto_confirm = false,
public bool $enable_backup = true,
public string $backup_extension = '.backup',
public int $max_file_size_mb = 10,
public bool $learn_new_variables = true,
public bool $remove_obfuscated_blocks = true,
public bool $format_output = true,
public bool $enable_pattern_learning = true,
public bool $load_custom_mappings = true
)
{
}
}
final class ObfuscatedVariable
{
public function __construct(
public string $obfuscated_name,
public string $clean_value,
public VariableType $type,
public string $source_file = '',
public string $learned_date = ''
)
{
}
}
final class PatternLearner
{
public function __construct(
private string $codebase_path = '.',
private array $file_patterns = ['*.php', '*.js', '*.html', '*.txt']
)
{
}
public function discover_patterns(): array
{
$this->log("🔍 Scanning codebase for common patterns...");
$patterns = [
'variable_names' => $this->find_common_variables(),
'function_names' => $this->find_common_functions(),
'string_values' => $this->find_common_strings(),
'method_calls' => $this->find_common_methods()
];
$this->log("✅ Found ".array_sum(array_map('count', $patterns))." potential patterns");
return $patterns;
}
private function find_common_variables(): array
{
$variables = [];
$files = $this->find_files();
foreach ($files as $file) {
$content = file_get_contents($file);
if ($content === false) {
continue;
}
// Find common PHP variable patterns
preg_match_all('/\$([a-zA-Z_][a-zA-Z0-9_]*)\s*=/', $content, $matches);
foreach ($matches[1] as $var) {
if (strlen($var) > 2 && strlen($var) < 20) {
$variables[$var] = ($variables[$var] ?? 0) + 1;
}
}
// Find common JavaScript variable patterns
preg_match_all('/(?:var|let|const)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*=/', $content, $matches);
foreach ($matches[1] as $var) {
if (strlen($var) > 2 && strlen($var) < 20) {
$variables[$var] = ($variables[$var] ?? 0) + 1;
}
}
}
// Return most common variables
arsort($variables);
return array_slice(array_keys($variables), 0, 50);
}
private function find_common_functions(): array
{
$functions = [];
$files = $this->find_files();
foreach ($files as $file) {
$content = file_get_contents($file);
if ($content === false) continue;
// Find function definitions
preg_match_all('/function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/', $content, $matches);
foreach ($matches[1] as $func) {
if (strlen($func) > 3 && !str_starts_with($func, '_')) {
$functions[$func] = ($functions[$func] ?? 0) + 1;
}
}
// Find method calls
preg_match_all('/->([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/', $content, $matches);
foreach ($matches[1] as $method) {
if (strlen($method) > 3) {
$functions[$method] = ($functions[$method] ?? 0) + 1;
}
}
}
arsort($functions);
return array_slice(array_keys($functions), 0, 30);
}
private function find_common_strings(): array
{
$strings = [];
$files = $this->find_files();
foreach ($files as $file) {
$content = file_get_contents($file);
if ($content === false) continue;
// Find quoted strings
preg_match_all('/[\'"]([^\'"]{3,50})[\'"]/', $content, $matches);
foreach ($matches[1] as $string) {
if ($this->is_meaningful_string($string)) {
$strings[$string] = ($strings[$string] ?? 0) + 1;
}
}
}
arsort($strings);
return array_slice(array_keys($strings), 0, 100);
}
private function find_common_methods(): array
{
$methods = [];
$files = $this->find_files();
foreach ($files as $file) {
$content = file_get_contents($file);
if ($content === false) continue;
// Find common PHP method patterns
preg_match_all('/(?:->|::)([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/', $content, $matches);
foreach ($matches[1] as $method) {
if (strlen($method) > 3) {
$methods[$method] = ($methods[$method] ?? 0) + 1;
}
}
}
arsort($methods);
return array_slice(array_keys($methods), 0, 25);
}
private function find_files(): array
{
$files = [];
$patterns = array_map(fn($p) => $this->codebase_path.'/**/'.$p, $this->file_patterns);
foreach ($patterns as $pattern) {
$found = glob($pattern, GLOB_BRACE);
if ($found !== false) {
$files = array_merge($files, $found);
}
}
// Filter out obfuscated and deobfuscated files
return array_filter($files, fn($file) => !str_contains($file, '_deobfuscated.') &&
!str_contains($file, 'deobfuscation_map.php') &&
!str_contains($file, 'custom_mappings.php') &&
!str_contains($file, 'BiDe.php')
);
}
private function is_meaningful_string(string $str): bool
{
// Filter out meaningless strings
if (is_numeric($str)) {
return false;
}
if (preg_match('/^[0-9a-f]{8,}$/i', $str)) {
return false;
} // Hex strings
if (preg_match('/^[a-z0-9]{32,}$/i', $str)) {
return false;
} // MD5-like
if (strlen($str) < 3) {
return false;
}
if (preg_match('/^[^a-zA-Z]+$/', $str)) {
return false;
} // No letters
return true;
}
private function log(string $message): void
{
echo $message . \PHP_EOL;
}
}
final class BiDe {
private string $file;
private string $current_file_path;
public string $console_output = '';
private array $globalVariables = [];
private array $globalFunctions = [];
private array $functionBlocksToDelete = [];
private array $ifBlocksToDelete = [];
/** @var array<string, ObfuscatedVariable> */
private array $knownVariables = [];
private int $processed_files = 0;
private int $skipped_files = 0;
private int $obfuscated_files_found = 0;
public function __construct(
private readonly DeobfuscationConfig $config = new DeobfuscationConfig()
) {
$this->init();
}
private function console_log(string $str): void
{
$this->console_output .= $str.\PHP_EOL;
echo $str . \PHP_EOL;
}
private function read_input(string $prompt): string
{
echo $prompt;
return trim(fgets(\STDIN) ?: '');
}
public function init(): void
{
$php_version = \PHP_VERSION;
$php_major_version = \PHP_MAJOR_VERSION;
$this->console_log("=== BiDe (Bitrix Deobfuscator) Started ===");
$this->console_log("⚡ PHP Version: {$php_version} (Major: {$php_major_version})");
$this->console_log("📁 Working Directory: ".getcwd());
$this->console_log("🎯 Configuration: ".$this->get_config_summary());
// Load known obfuscated variables
$this->load_known_variables();
// Ask user for processing mode
$mode = $this->select_processing_mode();
$obfuscated_files = match($mode) {
DeobfuscationMode::USE_EXISTING_LIST => $this->load_files_from_list(),
DeobfuscationMode::SCAN_NEW => $this->find_obfuscated_files_with_grep()
};
if (empty($obfuscated_files)) {
$this->console_log("No obfuscated files found to process");
return;
}
$this->obfuscated_files_found = count($obfuscated_files);
$this->console_log("Found {$this->obfuscated_files_found} obfuscated files");
// Confirm processing
if (!$this->config->auto_confirm) {
$confirm = $this->read_input("\nProceed with deobfuscation? (y/n): ");
if (!str_starts_with(strtolower($confirm), 'y')) {
$this->console_log("Deobfuscation cancelled by user.");
return;
}
}
$this->console_log("\nStarting deobfuscation process...\n");
array_map($this->process_file(...), $obfuscated_files);
// Save updated known variables
$this->save_known_variables();
$this->generate_summary_report();
}
private function get_config_summary(): string
{
$features = [
$this->config->learn_new_variables ? '📚 Learning' : '📚 No Learning',
$this->config->remove_obfuscated_blocks ? '🗑️ Block Removal' : '🗑️ No Block Removal',
$this->config->format_output ? '📝 Formatting' : '📝 No Formatting',
$this->config->enable_backup ? '💾 Backup' : '💾 No Backup',
$this->config->enable_pattern_learning ? '🔍 Pattern Learning' : '🔍 No Pattern Learning',
$this->config->load_custom_mappings ? '📝 Custom Mappings' : '📝 No Custom Mappings'
];
return implode(' | ', $features);
}
private function select_processing_mode(): DeobfuscationMode
{
$this->console_log("\nChoose processing mode:");
$this->console_log("1. Scan for new obfuscated files");
$this->console_log("2. Use existing targets list (".$this->config->targets_file . ")");
$choice = $this->read_input("Enter your choice (1 or 2): ");
return match($choice) {
'2' => DeobfuscationMode::USE_EXISTING_LIST,
default => DeobfuscationMode::SCAN_NEW
};
}
private function load_files_from_list(): array
{
$files = [];
$current_script = realpath(__FILE__);
if (!file_exists($this->config->targets_file)) {
$this->console_log("❌ Targets file not found: ".$this->config->targets_file);
return $files;
}
$content = file_get_contents($this->config->targets_file);
$lines = explode("\n", $content ?? '');
foreach ($lines as $line) {
// Skip comments, headers, and empty lines
if (preg_match('/^\d+\.\s+(.+)\s+\([^)]+\)$/', $line, $matches)) {
$file_path = trim($matches[1]);
$full_path = realpath($file_path);
// Skip the deobfuscator script itself and check if file exists
if ($full_path && $full_path !== $current_script && file_exists($file_path)) {
$files[] = $file_path;
$this->console_log(" ✅ ".basename($file_path));
} elseif ($full_path === $current_script) {
$this->console_log(" ⏭️ ".basename($file_path)." (skipped - deobfuscator script)");
} elseif (!file_exists($file_path)) {
$this->console_log(" ❌ ".basename($file_path)." (file not found)");
}
}
}
$this->console_log("Loaded ".count($files)." files from ".$this->config->targets_file);
return $files;
}
private function load_known_variables(): void
{
$all_mappings = [];
// Load automated mappings
if (file_exists($this->config->mappings_file)) {
try {
$loaded_data = include $this->config->mappings_file;
$mappings = $loaded_data['mappings'] ?? $loaded_data;
$all_mappings = array_merge($all_mappings, $mappings);
$this->console_log("📁 Loaded ".count($mappings)." automated mappings");
} catch (Throwable $e) {
$this->console_log("❌ Error loading mappings file: ".$e->getMessage());
}
}
// Load custom mappings
if ($this->config->load_custom_mappings && file_exists($this->config->custom_mappings_file)) {
try {
$custom_data = include $this->config->custom_mappings_file;
$custom_mappings = $custom_data['mappings'] ?? $custom_data;
$all_mappings = array_merge($all_mappings, $custom_mappings);
$this->console_log("📝 Loaded ".count($custom_mappings)." custom mappings");
} catch (Throwable $e) {
$this->console_log("❌ Error loading custom mappings: ".$e->getMessage());
}
}
// Convert to ObfuscatedVariable objects
$this->knownVariables = array_map(
fn($name, $value) => new ObfuscatedVariable(
$name,
$value,
str_starts_with($value, '$') ? VariableType::VARIABLE_REF : VariableType::STRING
),
array_keys($all_mappings),
$all_mappings
);
$this->console_log("📚 Total mappings loaded: ".count($this->knownVariables));
// Run pattern learning if enabled
if ($this->config->enable_pattern_learning) {
$this->learn_from_codebase_patterns();
}
}
private function learn_from_codebase_patterns(): void
{
$this->console_log("🔍 Analyzing codebase patterns for better deobfuscation...");
$learner = new PatternLearner();
$patterns = $learner->discover_patterns();
$new_learnings = 0;
// Learn from common variable names
foreach ($patterns['variable_names'] as $variable) {
$potential_obfuscated = '_'.crc32($variable);
if (!isset($this->knownVariables[$potential_obfuscated])) {
$this->knownVariables[$potential_obfuscated] = new ObfuscatedVariable(
$potential_obfuscated,
'$'. $variable,
VariableType::VARIABLE_REF
);
$new_learnings++;
}
}
// Learn from common strings
foreach ($patterns['string_values'] as $string) {
$potential_obfuscated = '____'.crc32($string);
if (!isset($this->knownVariables[$potential_obfuscated])) {
$this->knownVariables[$potential_obfuscated] = new ObfuscatedVariable(
$potential_obfuscated,
$string,
VariableType::STRING
);
$new_learnings++;
}
}
if ($new_learnings > 0) {
$this->console_log("💡 Learned {$new_learnings} new patterns from codebase analysis");
} else {
$this->console_log("💡 No new patterns learned from codebase analysis");
}
}
private function save_known_variables(): void
{
if (!$this->config->learn_new_variables) {
$this->console_log("💡 Variable learning disabled - skipping save");
return;
}
$mappings_array = array_combine(
array_map(fn($v) => $v->obfuscated_name, $this->knownVariables),
array_map(fn($v) => $v->clean_value, $this->knownVariables)
);
$content = "<?php\n\n";
$content .= "// BiDe Deobfuscation Mappings\n";
$content .= "// DO NOT EDIT MANUALLY - Generated by BiDe Deobfuscator\n";
$content .= "// This file stores obfuscated-to-clean variable mappings\n\n";
$content .= "declare(strict_types=1);\n\n";
$content .= "return [\n";
$content .= " 'metadata' => [\n";
$content .= " 'version' => '2.0',\n";
$content .= " 'created' => '".date('Y-m-d H:i:s')."',\n";
$content .= " 'records' => ".count($this->knownVariables).",\n";
$content .= " 'checksum' => '".md5(serialize($mappings_array)) . "',\n";
$content .= " 'generator' => 'BiDe v1.0',\n";
$content .= " 'source_file' => '".basename(__FILE__) . "'\n";
$content .= " ],\n";
$content .= " 'mappings' => [\n";
foreach ($mappings_array as $var => $value) {
$content .= match(true) {
str_starts_with($value, '$') => " '{$var}' => '{$value}',\n",
default => " '{$var}' => '".addslashes($value) . "',\n"
};
}
$content .= " ]\n";
$content .= "];\n";
// Create backup if enabled
if ($this->config->enable_backup && file_exists($this->config->mappings_file)) {
$backup_file = $this->config->mappings_file.$this->config->backup_extension;
copy($this->config->mappings_file, $backup_file);
$this->console_log("💾 Backup created: ".basename($backup_file));
}
if (file_put_contents($this->config->mappings_file, $content, LOCK_EX) !== false) {
$this->console_log("💾 Saved ".count($this->knownVariables)." mappings to ".$this->config->mappings_file);
} else {
$this->console_log("❌ Could not save mappings to ".$this->config->mappings_file);
}
}
private function find_obfuscated_files_with_grep(): array
{
$obfuscated_files = [];
$current_script = realpath(__FILE__);
$mappings_file = realpath($this->config->mappings_file);
// Try patterns in order of specificity
$patterns = [
FilePattern::BASE64_DECODE->value,
FilePattern::GLOBALS_ARRAY->value,
FilePattern::BASE64_GENERIC->value
];
foreach ($patterns as $pattern) {
$grep_command = "grep -rl --include=\"*.php\" \"{$pattern}\" . 2>/dev/null";
$this->console_log("Running: {$grep_command}");
exec($grep_command, $output, $return_var);
if ($return_var === 0 && !empty($output)) {
foreach ($output as $file_path) {
$full_path = realpath($file_path);
// Skip the deobfuscator script itself, mappings file, and avoid duplicates
if ($full_path &&
$full_path !== $current_script &&
$full_path !== $mappings_file &&
!in_array($file_path, $obfuscated_files, true)) {
// Check file size limit
$file_size = filesize($file_path);
if ($file_size <= ($this->config->max_file_size_mb * 1024 * 1024)) {
$obfuscated_files[] = $file_path;
$this->console_log(" ✅ ".basename($file_path)." (".$this->format_size($file_size) . ")");
} else {
$this->console_log(" ⚠️ ".basename($file_path)." (skipped - exceeds size limit)");
}
} elseif ($full_path === $current_script) {
$this->console_log(" ⏭️ ".basename($file_path)." (skipped - deobfuscator script)");
} elseif ($full_path === $mappings_file) {
$this->console_log(" ⏭️ ".basename($file_path)." (skipped - mappings file)");
}
}
break; // Stop at first successful pattern
}
}
if (empty($obfuscated_files)) {
$this->console_log(" No obfuscated files found with common patterns");
} else {
$this->save_targets_list($obfuscated_files);
}
return $obfuscated_files;
}
private function save_targets_list(array $files): bool
{
$content = "BiDe Deobfuscation Targets - ".date('Y-m-d H:i:s')."\n";
$content .= "Total files: ".count($files) . "\n";
$content .= "Generated by: BiDe PHP Deobfuscator v1.0\n";
$content .= "PHP Version: ".\PHP_VERSION."\n";
$content .= "Configuration: ".$this->get_config_summary() . "\n";
$content .= "Note: Deobfuscator script was automatically excluded\n";
$content .= "Output files: [filename]_deobfuscated.php\n";
$content .= str_repeat("=", 80) . "\n\n";
foreach ($files as $index => $file_path) {
$file_size = file_exists($file_path) ? filesize($file_path) : 0;
$content .= ($index + 1).". ".$file_path." (".$this->format_size($file_size) . ")\n";
}
$content .= "\n".str_repeat("=", 80) . "\n";
$content .= "SUMMARY:\n";
$content .= "- Files found: ".count($files) . "\n";
$content .= "- Deobfuscated files: [filename]_deobfuscated.php\n";
$content .= "- Mappings file: deobfuscation_map.php\n";
$content .= "- Custom mappings: custom_mappings.php\n";
$content .= "- Next run: Use option 2 to process this same list\n";
if (file_put_contents($this->config->targets_file, $content, LOCK_EX) !== false) {
$this->console_log("📝 Targets list saved to: ".$this->config->targets_file);
return true;
}
$this->console_log("❌ Could not save targets list");
return false;
}
private function process_file(string $file_path): void
{
$this->current_file_path = $file_path;
$filename = basename($file_path);
$this->console_log("\n".str_repeat("=", 60));
$this->console_log("PROCESSING: {$filename}");
$this->console_log("Location: ".dirname($file_path));
$this->console_log(str_repeat("=", 60));
if (!file_exists($file_path)) {
$this->console_log("❌ ERROR: File not found");
$this->skipped_files++;
return;
}
// Check file size
$file_size = filesize($file_path);
if ($file_size > ($this->config->max_file_size_mb * 1024 * 1024)) {
$this->console_log("❌ ERROR: File too large (".$this->format_size($file_size) . ")");
$this->skipped_files++;
return;
}
$file_content = file_get_contents($file_path);
if ($file_content === false) {
$this->console_log("❌ ERROR: Could not read file");
$this->skipped_files++;
return;
}
$this->file = $file_content;
$this->console_log("File size: ".$this->format_size(strlen($this->file)));
// Create backup if enabled
if ($this->config->enable_backup) {
$backup_file = $file_path.$this->config->backup_extension;
if (copy($file_path, $backup_file)) {
$this->console_log("💾 Original backed up: ".basename($backup_file));
}
}
// Reset state for new file
$this->globalVariables = [];
$this->globalFunctions = [];
$this->functionBlocksToDelete = [];
$this->ifBlocksToDelete = [];
// Processing steps (conditional based on config)
$processing_steps = [
'Extracting obfuscated functions' => $this->define_obfuscated_functions(...),
'Finding obfuscated names' => $this->find_obfuscated_names(...),
'Processing variables and arrays' => $this->edit_variables_array(...),
'Processing functions' => $this->edit_variables_function(...),
'Preparing code' => $this->prepare(...),
];
if ($this->config->remove_obfuscated_blocks) {
$processing_steps['Removing obfuscated blocks'] = $this->remove_obfuscated_blocks(...);
}
if ($this->config->format_output) {
$processing_steps['Formatting code'] = $this->format_code(...);
}
$processing_steps['Applying known variables cleanup'] = $this->apply_known_variables_cleanup(...);
foreach ($processing_steps as $description => $step) {
$this->console_log("Step: {$description}...");
$step();
}
// Create output filename
$output_path = $this->get_output_path($file_path);
if (file_put_contents($output_path, $this->file, LOCK_EX) !== false) {
$new_size = $this->format_size(strlen($this->file));
$this->console_log("✅ SUCCESS: Deobfuscated file saved as: ".basename($output_path));
$this->console_log("📊 Size change: ".$this->format_size(strlen($file_content))." → {$new_size}");
$this->processed_files++;
} else {
$this->console_log("❌ ERROR: Could not write deobfuscated file");
$this->skipped_files++;
}
}
private function apply_known_variables_cleanup(): void
{
if (empty($this->knownVariables)) {
$this->console_log(" No known variables to apply");
return;
}
$replacements = 0;
// Sort variables by length (longest first) to prevent partial replacements
usort($this->knownVariables, fn($a, $b) => strlen($b->obfuscated_name) - strlen($a->obfuscated_name));
foreach ($this->knownVariables as $variable) {
// Skip if the clean value is exactly the same as the obfuscated variable name
if ($variable->clean_value === '$'.$variable->obfuscated_name) {
continue;
}
// Handle variable usage replacement - only match complete variable names
$usage_pattern = '/\\$'.preg_quote($variable->obfuscated_name, '/') . '\b/';
// Determine replacement value based on type
$replacement = match ($variable->type) {
VariableType::VARIABLE_REF => $variable->clean_value,
VariableType::STRING, VariableType::SPECIAL => "'".addslashes($variable->clean_value) . "'"
};
$before_count = substr_count($this->file, '$'.$variable->obfuscated_name);
$this->file = preg_replace($usage_pattern, $replacement, $this->file);
$after_count = substr_count($this->file, '$'.$variable->obfuscated_name);
$current_replacements = $before_count - $after_count;
if ($current_replacements > 0) {
$replacements += $current_replacements;
$this->console_log(" Replaced \${$variable->obfuscated_name} with {$replacement} ({$current_replacements} times)");
}
}
$this->console_log(" Applied {$replacements} variable cleanups from known variables database");
}
private function generate_summary_report(): void
{
$this->console_log("\n".str_repeat("=", 60));
$this->console_log("📊 BiDe (Bitrix Deobfuscator) - SUMMARY REPORT");
$this->console_log(str_repeat("=", 60));
$this->console_log("Obfuscated files found: {$this->obfuscated_files_found}");
$this->console_log("✅ Successfully processed: {$this->processed_files}");
$this->console_log("⏭️ Skipped/errors: {$this->skipped_files}");
$this->console_log("💾 Mappings stored: ".count($this->knownVariables));
$this->console_log("📝 Targets list: ".$this->config->targets_file);
$this->console_log("🗺️ Mappings file: ".$this->config->mappings_file);
$this->console_log("📋 Custom mappings: ".$this->config->custom_mappings_file);
$this->console_log("📁 Output location: Same directories as originals");
$this->console_log("🏷️ Output naming: [filename]_deobfuscated.php");
$this->console_log("⚡ PHP Version: ".\PHP_VERSION);
match(true) {
$this->processed_files > 0 => $this->console_log("\n🎉 Deobfuscation completed successfully!"),
default => $this->console_log("\nℹ️ No files were processed.")
};
$this->console_log(str_repeat("=", 60));
}
private function format_size(int $bytes): string
{
return match (true) {
$bytes >= 1_048_576 => round($bytes / 1_048_576, 2).' MB',
$bytes >= 1024 => round($bytes / 1024, 2).' KB',
default => $bytes . ' bytes'
};
}
private function get_output_path(string $original_path): string
{
$path_info = pathinfo($original_path);
return $path_info['dirname'].'/'.$path_info['filename'].'_deobfuscated.'.$path_info['extension'];
}
private function define_obfuscated_functions(): void
{
// First, execute global array definitions to make them available
$globalArrayPattern = '/(\$GLOBALS\[\'(_{3,}[0-9]+)\'\]\s*=\s*array\([^;]+\);)/s';
preg_match_all($globalArrayPattern, $this->file, $matches, \PREG_SET_ORDER);
if (!empty($matches)) {
$this->console_log(" Found ".count($matches)." global array(s)");
foreach ($matches as $match) {
$this->console_log(" Executing global array: ".substr($match[1], 0, 50) . "...");
@eval($match[1]);
// Store variable name for potential learning
if (preg_match('/\$GLOBALS\[\'([^\']+)\'\]/', $match[1], $var_match)) {
$this->learn_variable_values($var_match[1]);
}
}
}
// Regex to find the full function declaration
$functionPattern = '/(function\s+_{3,}[0-9]+\([^)]*\)\s*\{((?:[^{}]*|(?R))*)\})/s';
preg_match_all($functionPattern, $this->file, $matches, \PREG_SET_ORDER);
if (!empty($matches)) {
$this->console_log(" Found ".count($matches)." obfuscated function(s)");
foreach ($matches as $match) {
// Execute the full function declaration to make it available
@eval($match[0]);
// Save the full block for removal at the end
$this->functionBlocksToDelete[] = $match[0];
}
}
// Also find the if-blocks wrapping the functions for removal
$ifPattern = '/(if\s*\(!function_exists\(__NAMESPACE__\s*\.\s*\'\\\\(_{3,}[0-9]+)\'\)\)\s*\{.*\};)/sU';
preg_match_all($ifPattern, $this->file, $matches, \PREG_SET_ORDER);
if (!empty($matches)) {
$this->console_log(" Found ".count($matches)." function wrapper if-block(s)");
foreach ($matches as $match) {
$this->ifBlocksToDelete[] = $match[0];
}
}
}
private function learn_variable_values(string $var_name): void
{
// Learn values from global arrays and store them for future cleanup
if (isset($GLOBALS[$var_name]) && is_array($GLOBALS[$var_name])) {
foreach ($GLOBALS[$var_name] as $index => $value) {
if (is_string($value) && strlen($value) > 1) {
$obfuscated_var = $var_name.'_' . $index;
if (!isset($this->knownVariables[$obfuscated_var])) {
$this->knownVariables[$obfuscated_var] = new ObfuscatedVariable(
$obfuscated_var,
$value,
VariableType::STRING
);
$this->console_log(" 💡 Learned: \${$obfuscated_var} = '{$value}'");
}
}
}
}
}
private function find_obfuscated_names(): void
{
preg_match_all('/\$GLOBALS\[\'(_{3,}[0-9]+)\'\]/', $this->file, $matches);
$this->globalVariables = array_unique($matches[1]);
$this->console_log(" Found ".count($this->globalVariables)." global variable(s): ".implode(', ',
$this->globalVariables));
preg_match_all('/(_{3,}[0-9]+)\(/', $this->file, $matches);
$this->globalFunctions = array_unique($matches[1]);
$this->console_log(" Found ".count($this->globalFunctions)." obfuscated function(s): ".implode(', ',
$this->globalFunctions));
}
private function remove_obfuscated_blocks(): void
{
$original_length = strlen($this->file);
// Remove global arrays AFTER we've processed all the references
foreach ($this->globalVariables as $value) {
$pattern = '/\$GLOBALS\[\''.$value.'\'\]\s*=\s*array\(.*?\);/s';
$this->file = preg_replace($pattern, '', $this->file);
}
// Remove the complete if(!function_exists) blocks up to the second semicolon after return
foreach ($this->globalFunctions as $functionName) {
$pattern = '/if\s*\(\s*!\s*function_exists\s*\(\s*__NAMESPACE__\s*\.\s*\'\\\\[^\']*\'\s*\)\s*\).*?return[^;]*;.*?\}\s*;\s*/s';
$this->file = preg_replace($pattern, "\n", $this->file);
}
$new_length = strlen($this->file);
$reduction = $original_length - $new_length;
$this->console_log(" Removed ".$this->format_size($reduction)." of obfuscated code");
}
private function edit_variables_array(): void
{
foreach ($this->globalVariables as $value) {
$this->console_log(" Processing global variable: {$value}");
// First handle array access calls like $GLOBALS['____1965792739'][0](...)
$this->file = preg_replace_callback('/\$GLOBALS\[\''.$value.'\'\]\[(\d+)\]\s*\(([^)]*)\)/',
function ($matches) use ($value) {
$index = $matches[1];
$params = $matches[2];
if (isset($GLOBALS[$value]) && isset($GLOBALS[$value][$index])) {
$funcName = $GLOBALS[$value][$index];
return $funcName.'('.$params.')';
}
return $matches[0];
}, $this->file);
// Then handle simple array access like $GLOBALS['____1965792739'][0]
$this->file = preg_replace_callback('/\$GLOBALS\[\''.$value.'\'\]\[(\d+)\](?!\s*\()/',
function ($matches) use ($value) {
$index = $matches[1];
if (isset($GLOBALS[$value]) && isset($GLOBALS[$value][$index])) {
$result = $GLOBALS[$value][$index];
return match (true) {
is_string($result) => "'".addslashes($result)."'",
default => $result
};
}
return $matches[0];
}, $this->file);
}
}
private function edit_variables_function(): void
{
foreach ($this->globalFunctions as $value) {
$this->file = preg_replace_callback('/'.$value.'\((\d+)\)/', function ($matches) use ($value) {
return "'".addslashes($value($matches[1])) . "'";
}, $this->file);
}
}
private function prepare(): void
{
for ($i = 0; $i < $this->config->repeater_count; $i++) {
$this->prepare_func();
}
$this->prepare_compute();
}
private function prepare_func(): void
{
$this->file = preg_replace_callback('/(min|round|strtoupper|strrev|base64_decode|set_time_limit)\([^\(\)]+\)/',
function ($matches) {
$result = @eval("return ".$matches[0].";");
return match (gettype($result)) {
'string' => "'".addslashes($result)."'",
'double', 'integer' => $result,
default => $matches[0]
};
}, $this->file);
}
private function prepare_compute(): void
{
$this->file = preg_replace_callback('/\(([0-9-+*\/\s]{2,}?)\)/', function ($matches) {
return @eval("return ".$matches[1] . ";");
}, $this->file);
}
private function format_code(): void
{
// Remove extra spaces and normalize
$this->file = preg_replace('/\s+/', ' ', $this->file);
$this->file = trim($this->file);
// Basic formatting - line breaks after semicolons
$this->file = preg_replace('/;(?!\s*\})/', ";\n", $this->file);
// Line breaks before and after curly braces
$this->file = preg_replace('/(\S)\s*{/', "$1\n{", $this->file);
$this->file = preg_replace('/{\s*(\S)/', "{\n$1", $this->file);
$this->file = preg_replace('/(\S)\s*}/', "$1\n}", $this->file);
$this->file = preg_replace('/}\s*(\S)/', "}\n$1", $this->file);
// Ensure spaces around string concatenations like 0 . ' Mb'
$this->file = preg_replace('/(?<=\d)\s*\.\s*(?=\'[^']+\')/', ' . ', $this->file);
// Special handling for else and elseif
$this->file = preg_replace('/}\s*(else\s*(if\s*\(|{)|elseif\s*\()/', "}\n$1", $this->file);
// Line breaks before keywords
$this->file = preg_replace('/(if|elseif|for|while|foreach|switch|function)\s*\(/', "\n$1 (", $this->file);
$this->file = preg_replace('/(\S)\s*(class|interface|trait|private|public|protected|static|abstract|final)\s/',
"$1\n$2 ", $this->file);
// Line break before return if not preceded by bracket
$this->file = preg_replace('/([^\)\s])\s*return\s/', "$1\nreturn ", $this->file);
// Line breaks for various constructs
$this->file = preg_replace('/(\S)\s*(case\s|default\s*:)/', "$1\n$2", $this->file);
$this->file = preg_replace('/(\S)\s*(break\s*;|continue\s*;)/', "$1\n$2", $this->file);
// Remove extra line breaks
$this->file = preg_replace('/\n\s*\n\s*\n/', "\n\n", $this->file);
// Add indentation for nesting
$this->file = $this->add_indentation($this->file);