-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmain.cpp
More file actions
3256 lines (2967 loc) · 152 KB
/
Copy pathmain.cpp
File metadata and controls
3256 lines (2967 loc) · 152 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
#include <iostream>
#include <vector>
#include <string>
#include <string_view>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <iomanip>
#include <limits>
#include <sstream>
#include <fstream>
#include <cstdint>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <filesystem>
#include <new>
#include <utility>
#include "miniz.h"
#include "apk_scan_limits.h"
#include "custom_linker_detector.h"
#include "disasm_arm64.h"
#include "elf_dynamic.h"
#include "vmp_detector.h"
#include "vmp_linkage.h"
#ifdef _WIN32
#include <windows.h>
#include <shellapi.h>
#endif
// =========================
// 轻量 ELF64 定义(避免依赖 elf.h,方便跨平台)
// =========================
static constexpr uint8_t ELFCLASS64_VAL = 2;
static constexpr uint8_t ELFDATA2LSB_VAL = 1;
static constexpr uint16_t EM_AARCH64_VAL = 183;
static constexpr uint32_t PT_LOAD_VAL = 1;
static constexpr uint32_t PF_X_VAL = 0x1;
static constexpr uint32_t PF_W_VAL = 0x2;
static constexpr uint32_t PF_R_VAL = 0x4;
static constexpr uint32_t SHT_SYMTAB_VAL = 2;
static constexpr uint32_t SHT_DYNSYM_VAL = 11;
static constexpr uint64_t SHF_EXECINSTR_VAL = 0x4;
static constexpr uint64_t SHN_UNDEF_VAL = 0;
static constexpr uint8_t STT_FUNC_VAL = 2;
#pragma pack(push, 1)
struct Elf64_Ehdr_L {
unsigned char e_ident[16];
uint16_t e_type;
uint16_t e_machine;
uint32_t e_version;
uint64_t e_entry;
uint64_t e_phoff;
uint64_t e_shoff;
uint32_t e_flags;
uint16_t e_ehsize;
uint16_t e_phentsize;
uint16_t e_phnum;
uint16_t e_shentsize;
uint16_t e_shnum;
uint16_t e_shstrndx;
};
struct Elf64_Phdr_L {
uint32_t p_type;
uint32_t p_flags;
uint64_t p_offset;
uint64_t p_vaddr;
uint64_t p_paddr;
uint64_t p_filesz;
uint64_t p_memsz;
uint64_t p_align;
};
struct Elf64_Shdr_L {
uint32_t sh_name;
uint32_t sh_type;
uint64_t sh_flags;
uint64_t sh_addr;
uint64_t sh_offset;
uint64_t sh_size;
uint32_t sh_link;
uint32_t sh_info;
uint64_t sh_addralign;
uint64_t sh_entsize;
};
struct Elf64_Sym_L {
uint32_t st_name;
unsigned char st_info;
unsigned char st_other;
uint16_t st_shndx;
uint64_t st_value;
uint64_t st_size;
};
#pragma pack(pop)
// =========================
// 工具函数
// =========================
static void init_console_utf8() {
#ifdef _WIN32
SetConsoleOutputCP(CP_UTF8);
SetConsoleCP(CP_UTF8);
#endif
}
static std::string json_escape(const std::string &s) {
std::ostringstream oss;
for (unsigned char c : s) {
switch (c) {
case '\"': oss << "\\\""; break;
case '\\': oss << "\\\\"; break;
case '\b': oss << "\\b"; break;
case '\f': oss << "\\f"; break;
case '\n': oss << "\\n"; break;
case '\r': oss << "\\r"; break;
case '\t': oss << "\\t"; break;
default:
if (c < 0x20) {
oss << "\\u"
<< std::hex << std::setw(4) << std::setfill('0')
<< (int)c << std::dec;
} else {
oss << c;
}
}
}
return oss.str();
}
static bool starts_with(const std::string &s, const std::string &prefix) {
return s.size() >= prefix.size() &&
std::equal(prefix.begin(), prefix.end(), s.begin());
}
static bool ends_with(const std::string &s, const std::string &suffix) {
return s.size() >= suffix.size() &&
std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
}
static double clamp01(double x) {
if (x < 0.0) return 0.0;
if (x > 1.0) return 1.0;
return x;
}
static double shannon_entropy(const uint8_t *data, size_t size) {
if (!data || size == 0) return 0.0;
uint64_t freq[256] = {0};
for (size_t i = 0; i < size; ++i) freq[data[i]]++;
double ent = 0.0;
for (uint64_t f : freq) {
if (!f) continue;
double p = (double)f / (double)size;
ent -= p * std::log2(p);
}
return ent;
}
static size_t count_printable_strings(const std::vector<uint8_t> &buf, size_t min_len = 4) {
size_t count = 0;
size_t i = 0;
while (i < buf.size()) {
size_t j = i;
while (j < buf.size()) {
unsigned char c = buf[j];
if (c >= 0x20 && c <= 0x7e) ++j;
else break;
}
if (j - i >= min_len) count++;
i = (j == i) ? (i + 1) : (j + 1);
}
return count;
}
template<typename T>
static bool read_struct(const std::vector<uint8_t> &buf, size_t offset, T &out) {
if (offset > buf.size() || sizeof(T) > buf.size() - offset) return false;
std::memcpy(&out, buf.data() + offset, sizeof(T));
return true;
}
static std::string get_cstr_from_table(const std::vector<uint8_t> &table, uint32_t off) {
if (off >= table.size()) return "";
const char *p = reinterpret_cast<const char*>(table.data() + off);
size_t maxlen = table.size() - off;
size_t n = 0;
while (n < maxlen && p[n] != '\0') n++;
return std::string(p, n);
}
static std::string hex_dump_prefix(const std::vector<uint8_t>& buf, size_t n = 32) {
std::ostringstream oss;
size_t m = std::min(n, buf.size());
for (size_t i = 0; i < m; ++i) {
if (i) oss << " ";
oss << std::hex << std::setw(2) << std::setfill('0') << (int)buf[i];
}
return oss.str();
}
static bool contains_any_icase(const std::vector<std::string> &hay, const std::vector<std::string> &needles) {
for (const auto &s : hay) {
std::string ls = s;
std::transform(ls.begin(), ls.end(), ls.begin(), [](unsigned char c){ return (char)std::tolower(c); });
for (const auto &n : needles) {
if (ls.find(n) != std::string::npos) return true;
}
}
return false;
}
static bool valid_file_range(uint64_t offset, uint64_t size, size_t file_size) {
return offset <= file_size && size <= static_cast<uint64_t>(file_size) - offset;
}
struct ScanDiagnostic {
std::string severity;
std::string code;
std::string entry;
std::string detail;
uint64_t entry_index = 0;
uint64_t compressed_bytes = 0;
uint64_t uncompressed_bytes = 0;
bool has_entry_index = false;
};
static void record_scan_diagnostic(std::vector<ScanDiagnostic>& diagnostics,
uint64_t& suppressed_count,
ScanDiagnostic diagnostic) {
if (diagnostics.size() < obfuscan::ApkScanLimits::kMaxRecordedDiagnostics) {
diagnostics.push_back(std::move(diagnostic));
} else {
++suppressed_count;
}
}
struct MinizAllocationBudget {
size_t limit_bytes = 0;
size_t current_bytes = 0;
size_t peak_bytes = 0;
bool limit_hit = false;
};
struct alignas(std::max_align_t) BoundedAllocationHeader {
size_t payload_bytes = 0;
};
static bool checked_allocation_size(size_t items, size_t size, size_t& out) {
if (items != 0 && size > std::numeric_limits<size_t>::max() / items) return false;
out = items * size;
if (out == 0) out = 1;
return out <= std::numeric_limits<size_t>::max() - sizeof(BoundedAllocationHeader);
}
static void* bounded_miniz_alloc(void* opaque, size_t items, size_t size) {
auto* budget = static_cast<MinizAllocationBudget*>(opaque);
size_t requested = 0;
if (!budget || !checked_allocation_size(items, size, requested) ||
requested > budget->limit_bytes - std::min(budget->current_bytes, budget->limit_bytes)) {
if (budget) budget->limit_hit = true;
return nullptr;
}
auto* header = static_cast<BoundedAllocationHeader*>(
std::malloc(sizeof(BoundedAllocationHeader) + requested));
if (!header) return nullptr;
header->payload_bytes = requested;
budget->current_bytes += requested;
budget->peak_bytes = std::max(budget->peak_bytes, budget->current_bytes);
return header + 1;
}
static void bounded_miniz_free(void* opaque, void* address) {
if (!address) return;
auto* budget = static_cast<MinizAllocationBudget*>(opaque);
auto* header = static_cast<BoundedAllocationHeader*>(address) - 1;
if (budget) {
budget->current_bytes = header->payload_bytes <= budget->current_bytes
? budget->current_bytes - header->payload_bytes
: 0;
}
std::free(header);
}
static void* bounded_miniz_realloc(void* opaque, void* address,
size_t items, size_t size) {
if (!address) return bounded_miniz_alloc(opaque, items, size);
auto* budget = static_cast<MinizAllocationBudget*>(opaque);
auto* old_header = static_cast<BoundedAllocationHeader*>(address) - 1;
const size_t old_size = old_header->payload_bytes;
size_t requested = 0;
if (!budget || !checked_allocation_size(items, size, requested)) {
if (budget) budget->limit_hit = true;
return nullptr;
}
const size_t base = old_size <= budget->current_bytes
? budget->current_bytes - old_size
: 0;
if (requested > budget->limit_bytes - std::min(base, budget->limit_bytes)) {
budget->limit_hit = true;
return nullptr;
}
auto* new_header = static_cast<BoundedAllocationHeader*>(
std::realloc(old_header, sizeof(BoundedAllocationHeader) + requested));
if (!new_header) return nullptr;
new_header->payload_bytes = requested;
budget->current_bytes = base + requested;
budget->peak_bytes = std::max(budget->peak_bytes, budget->current_bytes);
return new_header + 1;
}
static void configure_bounded_miniz_allocator(mz_zip_archive& zip,
MinizAllocationBudget& budget) {
zip.m_pAlloc = bounded_miniz_alloc;
zip.m_pFree = bounded_miniz_free;
zip.m_pRealloc = bounded_miniz_realloc;
zip.m_pAlloc_opaque = &budget;
}
struct ZipReaderScope {
mz_zip_archive* zip = nullptr;
MZ_FILE* external_file = nullptr;
bool initialized = false;
~ZipReaderScope() {
if (initialized && zip) mz_zip_reader_end(zip);
if (external_file) std::fclose(external_file);
}
};
static std::string miniz_error_detail(mz_zip_archive& zip) {
const char* text = mz_zip_get_error_string(mz_zip_get_last_error(&zip));
return text ? text : "unknown miniz error";
}
static bool table_entry_offset(uint64_t table_offset,
uint64_t index,
uint64_t entry_size,
size_t required_size,
size_t file_size,
size_t& out) {
if (entry_size < required_size) return false;
if (index != 0 && entry_size >
(std::numeric_limits<uint64_t>::max() - table_offset) / index) {
return false;
}
const uint64_t offset = table_offset + index * entry_size;
if (!valid_file_range(offset, required_size, file_size)) return false;
out = static_cast<size_t>(offset);
return true;
}
static size_t count_buffer_needles_icase(const std::vector<uint8_t>& hay,
const std::vector<std::string>& needles) {
auto ascii_lower = [](unsigned char c) -> unsigned char {
return (c >= 'A' && c <= 'Z') ? static_cast<unsigned char>(c + ('a' - 'A')) : c;
};
size_t count = 0;
for (const auto& needle : needles) {
if (needle.empty() || needle.size() > hay.size()) continue;
auto found = std::search(hay.begin(), hay.end(), needle.begin(), needle.end(),
[&](uint8_t lhs, char rhs) {
return ascii_lower(lhs) == ascii_lower(static_cast<unsigned char>(rhs));
});
if (found != hay.end()) count++;
}
return count;
}
static size_t count_import_name_hits(const std::vector<std::string> &imports,
const std::vector<std::string> &names) {
std::unordered_set<std::string> wanted;
for (auto name : names) {
std::transform(name.begin(), name.end(), name.begin(),
[](unsigned char c){ return (char)std::tolower(c); });
wanted.insert(std::move(name));
}
size_t count = 0;
for (auto imp : imports) {
std::transform(imp.begin(), imp.end(), imp.begin(),
[](unsigned char c){ return (char)std::tolower(c); });
size_t version_pos = imp.find('@');
if (version_pos != std::string::npos) {
imp = imp.substr(0, version_pos);
}
if (wanted.count(imp)) count++;
}
return count;
}
static bool is_zip_magic(const std::vector<uint8_t>& buf) {
return buf.size() >= 4 &&
buf[0] == 0x50 &&
buf[1] == 0x4b &&
buf[2] == 0x03 &&
buf[3] == 0x04;
}
static bool is_aarch64_elf64_little(const std::vector<uint8_t>& buf) {
Elf64_Ehdr_L eh{};
if (!read_struct(buf, 0, eh)) return false;
return eh.e_ident[0] == 0x7f &&
eh.e_ident[1] == 'E' &&
eh.e_ident[2] == 'L' &&
eh.e_ident[3] == 'F' &&
eh.e_ident[4] == ELFCLASS64_VAL &&
eh.e_ident[5] == ELFDATA2LSB_VAL &&
eh.e_machine == EM_AARCH64_VAL;
}
static bool extract_first_elf_from_zip_buffer(
const std::vector<uint8_t>& zip_buf,
std::vector<uint8_t>& out_elf,
std::string& inner_name,
const std::string& outer_entry_name,
std::vector<ScanDiagnostic>* diagnostics,
uint64_t* suppressed_diagnostics,
std::string& failure_code) {
MinizAllocationBudget allocation_budget{
static_cast<size_t>(obfuscan::ApkScanLimits::kMaxInnerZipMetadataBytes)};
mz_zip_archive zip{};
memset(&zip, 0, sizeof(zip));
configure_bounded_miniz_allocator(zip, allocation_budget);
ZipReaderScope scope{&zip, nullptr, false};
auto report_inner = [&](const std::string& code,
const std::string& inner_entry,
uint64_t entry_index,
uint64_t compressed_bytes,
uint64_t uncompressed_bytes,
const std::string& detail = std::string()) {
if (failure_code.empty()) failure_code = code;
if (!diagnostics || !suppressed_diagnostics) return;
const std::string qualified_name = inner_entry.empty()
? outer_entry_name
: outer_entry_name + "!" + inner_entry;
record_scan_diagnostic(
*diagnostics, *suppressed_diagnostics,
ScanDiagnostic{"warning", code, qualified_name, detail, entry_index,
compressed_bytes, uncompressed_bytes, true});
};
if (!mz_zip_reader_init_mem(&zip, zip_buf.data(), zip_buf.size(),
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) {
report_inner(allocation_budget.limit_hit ? "INNER_ZIP_METADATA_LIMIT"
: "INNER_ZIP_OPEN_FAILED",
"", 0, 0, 0, miniz_error_detail(zip));
return false;
}
scope.initialized = true;
mz_uint file_count = mz_zip_reader_get_num_files(&zip);
if (file_count > obfuscan::ApkScanLimits::kMaxInnerZipEntries) {
report_inner("INNER_ZIP_ENTRY_LIMIT", "", 0, 0, file_count);
return false;
}
bool found = false;
uint64_t best_rank = 0;
uint64_t accepted_uncompressed_bytes = 0;
const obfuscan::ZipPayloadPolicy policy{
obfuscan::ApkScanLimits::kMaxSingleInnerEntryBytes,
obfuscan::ApkScanLimits::kMaxCompressionRatio,
obfuscan::ApkScanLimits::kCompressionRatioFloorBytes,
};
for (mz_uint i = 0; i < file_count; ++i) {
mz_zip_archive_file_stat st{};
if (!mz_zip_reader_file_stat(&zip, i, &st)) {
report_inner("INNER_ZIP_ENTRY_STAT_FAILED", "", i, 0, 0,
miniz_error_detail(zip));
continue;
}
if (st.m_is_directory) continue;
const obfuscan::ZipPayloadDecision decision = obfuscan::evaluate_zip_payload(
{st.m_comp_size, st.m_uncomp_size,
st.m_is_encrypted != 0, st.m_is_supported != 0},
policy);
if (decision == obfuscan::ZipPayloadDecision::kEmpty) continue;
if (decision != obfuscan::ZipPayloadDecision::kAllow) {
report_inner("INNER_ZIP_" +
std::string(obfuscan::zip_payload_decision_code(decision)),
st.m_filename, i, st.m_comp_size, st.m_uncomp_size);
continue;
}
if (!obfuscan::fits_cumulative_budget(
accepted_uncompressed_bytes, st.m_uncomp_size,
obfuscan::ApkScanLimits::kMaxTotalInnerEntryBytes)) {
report_inner("INNER_ZIP_TOTAL_UNCOMPRESSED_LIMIT", st.m_filename, i,
st.m_comp_size, st.m_uncomp_size);
continue;
}
accepted_uncompressed_bytes += st.m_uncomp_size;
std::vector<uint8_t> tmp;
try {
tmp.resize(static_cast<size_t>(st.m_uncomp_size));
} catch (const std::bad_alloc&) {
report_inner("INNER_ZIP_ALLOCATION_FAILED", st.m_filename, i,
st.m_comp_size, st.m_uncomp_size);
continue;
}
if (!mz_zip_reader_extract_to_mem(&zip, i, tmp.data(), tmp.size(), 0)) {
report_inner("INNER_ZIP_EXTRACT_FAILED", st.m_filename, i,
st.m_comp_size, st.m_uncomp_size, miniz_error_detail(zip));
continue;
}
const bool elf_magic = tmp.size() >= 4 && tmp[0] == 0x7f && tmp[1] == 'E' &&
tmp[2] == 'L' && tmp[3] == 'F';
if (elf_magic) {
uint64_t rank = static_cast<uint64_t>(tmp.size());
if (is_aarch64_elf64_little(tmp)) {
rank += (1ULL << 62);
}
if (!found || rank > best_rank) {
found = true;
best_rank = rank;
out_elf = std::move(tmp);
inner_name = st.m_filename;
}
}
}
return found;
}
// =========================
// ELF 分析
// =========================
struct SectionInfo {
std::string name;
uint32_t type = 0;
uint64_t address = 0;
uint64_t offset = 0;
uint64_t size = 0;
uint64_t flags = 0;
double entropy = 0.0;
};
struct SegmentInfo {
uint32_t type = 0;
uint32_t flags = 0;
uint64_t offset = 0;
uint64_t vaddr = 0;
uint64_t filesz = 0;
uint64_t memsz = 0;
};
struct EntryPreview {
std::string name;
uint64_t va = 0;
uint64_t file_offset = 0;
std::vector<DisasmLine> lines;
};
struct DefinedFunctionRange {
std::string name;
uint64_t address = 0;
uint64_t size = 0;
};
struct AnalysisResult {
std::string so_name;
uint64_t file_size = 0; // 外层条目大小
uint64_t analyzed_file_size = 0; // 实际分析对象大小(内层ELF或原始ELF)
bool valid_elf = false;
bool is_64 = false;
bool is_aarch64 = false;
bool little_endian = false;
bool stripped = false;
bool has_symtab = false;
bool has_dynsym = false;
bool has_init_array = false;
bool has_jni_onload_string = false;
bool rwx_segment = false;
bool entry_in_writable_segment = false;
bool is_zip_container = false;
bool inner_elf_found = false;
bool known_hook_framework = false;
bool known_runtime_framework = false;
bool known_vm_runtime = false;
bool embedded_cxxabi_runtime = false;
uint8_t runtime_evidence_classes = 0;
size_t runtime_raw_identity_hits = 0;
size_t runtime_import_api_hits = 0;
bool possible_custom_linker = false;
obfuscan::custom_linker::Result custom_linker;
std::string format_note;
std::string known_framework_name;
std::string known_runtime_name;
uint16_t section_count = 0;
uint16_t ph_count = 0;
uint64_t text_size = 0;
uint64_t rodata_size = 0;
uint64_t data_size = 0;
uint64_t init_array_offset = 0;
uint64_t init_array_size = 0;
double file_entropy = 0.0;
double max_section_entropy = 0.0;
double avg_exec_entropy = 0.0;
size_t printable_string_count = 0;
size_t import_count = 0;
size_t exported_dynsym_count = 0;
std::vector<std::string> imports;
std::vector<std::string> needed_libraries;
std::vector<std::string> defined_exports;
std::vector<DefinedFunctionRange> defined_function_ranges;
std::vector<SectionInfo> sections;
std::vector<SegmentInfo> segments;
A64StatsEx a64;
std::vector<DisasmLine> preview_lines;
std::vector<EntryPreview> entry_previews;
VmpDeepResult vmp;
double packer_score = 0.0;
double ollvm_score = 0.0;
double strong_obf_score = 0.0;
bool vmp_protected_client = false;
std::string vmp_provider_so;
std::string vmp_needed_library;
std::vector<std::string> vmp_shared_symbols;
std::string final_label;
std::vector<std::string> reasons;
};
static bool va_to_file_offset(uint64_t va,
const std::vector<SegmentInfo>& segments,
uint64_t& out_off) {
for (const auto& seg : segments) {
if (seg.type != PT_LOAD_VAL) continue;
if (va >= seg.vaddr && va - seg.vaddr < seg.filesz) {
const uint64_t delta = va - seg.vaddr;
if (delta > std::numeric_limits<uint64_t>::max() - seg.offset) continue;
out_off = seg.offset + delta;
return true;
}
}
return false;
}
static void add_entry_preview(AnalysisResult& r,
Arm64DisasmEngine& engine,
const std::vector<uint8_t>& work_buf,
const std::string& name,
uint64_t va,
size_t max_insn = 12) {
uint64_t file_off = 0;
if (!va_to_file_offset(va, r.segments, file_off)) return;
if (file_off >= work_buf.size()) return;
size_t remain = work_buf.size() - static_cast<size_t>(file_off);
size_t preview_size = std::min<size_t>(remain, 96);
EntryPreview ep;
ep.name = name;
ep.va = va;
ep.file_offset = file_off;
ep.lines = engine.disasm_preview(work_buf.data() + file_off, preview_size, va, max_insn);
if (!ep.lines.empty()) {
r.entry_previews.push_back(std::move(ep));
}
}
static std::vector<AddressRange> find_dynamic_plt_branch_ranges(
const std::vector<ExecutableRegionView>& regions,
const std::vector<uint64_t>& jump_slot_vas);
static bool is_high_risk_result(const AnalysisResult& r) {
return r.vmp_protected_client ||
r.possible_custom_linker ||
r.packer_score >= 0.68 ||
r.strong_obf_score >= 0.70 ||
r.vmp.possible ||
(r.packer_score >= 0.62 && r.strong_obf_score >= 0.58) ||
(r.ollvm_score >= 0.65 && r.strong_obf_score >= 0.60);
}
static bool is_medium_risk_result(const AnalysisResult& r) {
return r.known_hook_framework ||
r.custom_linker.loader_component() ||
r.packer_score >= 0.45 ||
r.ollvm_score >= 0.50 ||
r.strong_obf_score >= 0.50 ||
r.vmp.score >= 0.50;
}
static std::string path_basename_lower(const std::string& path) {
size_t pos = path.find_last_of("/\\");
std::string base = (pos == std::string::npos) ? path : path.substr(pos + 1);
std::transform(base.begin(), base.end(), base.begin(),
[](unsigned char c) { return (char)std::tolower(c); });
return base;
}
static bool is_known_runtime_library_name(const std::string& base, std::string& family) {
struct KnownName {
const char* needle;
const char* family;
};
static const KnownName names[] = {
{"libreact", "React Native"},
{"librn", "React Native"},
{"libhermes", "Hermes/React Native"},
{"libjsi", "React Native JSI"},
{"libjsc", "JavaScriptCore/React Native"},
{"libturbomodule", "React Native TurboModule"},
{"libuimanager", "React Native UIManager"},
{"libmapbuffer", "React Native MapBuffer"},
{"libyoga", "Yoga layout"},
{"libfbjni", "fbjni"},
{"libglog", "glog"},
{"libsentry", "Sentry native"},
{"libgifimage", "image codec"},
{"libglide-webp", "image codec"},
{"libnative-imagetranscoder", "image codec"},
{"libreanimated", "React Native Reanimated"},
{"libvisioncamera", "React Native VisionCamera"},
{"libjscexecutor", "React Native JS executor"},
{"libjserrorhandler", "React Native JS error handler"},
{"libjsinspector", "React Native JS inspector"},
{"libjsijniprofiler", "React Native JSI profiler"},
{"libnative-filters", "image filter"},
{"libmetis", "Metis/native graph library"},
{"liblogger", "native logging"},
{"libtt_ugen_layout", "layout engine"}
};
for (const auto& item : names) {
if (base.find(item.needle) != std::string::npos) {
family = item.family;
return true;
}
}
return false;
}
struct RuntimeEvidence {
std::string family;
bool basename_hit = false;
bool raw_identity_hit = false;
bool import_api_hit = false;
size_t raw_hits = 0;
size_t import_hits = 0;
uint8_t evidence_classes() const {
return static_cast<uint8_t>(basename_hit) +
static_cast<uint8_t>(raw_identity_hit) +
static_cast<uint8_t>(import_api_hit);
}
bool present() const { return evidence_classes() != 0; }
bool confirmed() const { return evidence_classes() >= 2; }
};
static RuntimeEvidence detect_known_vm_or_branch_runtime(
const std::string& basename,
const std::vector<uint8_t>& image,
const std::vector<std::string>& imports) {
RuntimeEvidence best;
auto consider = [&](const char* family,
bool basename_hit,
const std::vector<std::string>& identity_needles,
const std::vector<std::string>& api_names) {
RuntimeEvidence candidate;
candidate.family = family;
candidate.basename_hit = basename_hit;
candidate.raw_hits = count_buffer_needles_icase(image, identity_needles);
candidate.import_hits = count_import_name_hits(imports, api_names);
candidate.raw_identity_hit = candidate.raw_hits >= 2;
candidate.import_api_hit = candidate.import_hits >= 2;
if (!candidate.present()) return;
const auto rank = [](const RuntimeEvidence& item) {
return std::make_pair(item.evidence_classes(), item.raw_hits + item.import_hits);
};
if (!best.present() || rank(candidate) > rank(best)) best = std::move(candidate);
};
const bool libcxx_name = basename == "libc++_shared.so" ||
basename == "libc++_shared_64.so" ||
basename == "libstlport_shared.so" ||
basename == "libgnustl_shared.so";
// C++ ABI symbols occur in almost every native library, so they are only
// an SO-wide alternative when the SONAME itself is the shared C++ runtime.
if (libcxx_name) {
consider("C++ runtime callback/virtual dispatch", true,
{"std::__ndk1", "LLVM libc++", "__cxa_demangle", "__gxx_personality_v0",
"__vmi_class_type_info", "__cxxabi"},
{"__cxa_throw", "__cxa_begin_catch", "__cxa_end_catch", "__gxx_personality_v0"});
}
consider("Nano Compose expression/layout runtime",
basename.find("nano_compose") != std::string::npos,
{"ComposeFunc", "ExprIDValue", "OpGroupValue", "LayoutNode"}, {});
consider("QuickJS bytecode runtime",
basename.find("quickjs") != std::string::npos,
{"QuickJS", "JS_EvalInternal", "JS_CallInternal", "JS_ExecutePendingJob"},
{"JS_NewRuntime", "JS_NewContext", "JS_Eval", "JS_ExecutePendingJob"});
const bool ffmpeg_name = basename.find("ffmpeg") != std::string::npos ||
basename == "libavcodec.so" || basename == "libavutil.so" ||
basename == "libavfilter.so" || basename == "libavformat.so" ||
basename == "libswscale.so" || basename == "libavdevice.so" ||
basename == "libijkplayer.so";
// A basename is deliberately only one evidence class. At least one
// independent identity-string or imported-API class is still required by
// RuntimeEvidence::confirmed() before this can override a VMP verdict.
consider("FFmpeg/media codec runtime", ffmpeg_name,
{"FFmpeg version", "Lavc", "Lavf", "Lavu", "Lavfi", "Sws",
"ff_h264_", "libavcodec", "libavutil", "libavformat",
"libavfilter", "libswscale", "ijkplayer"},
{"avcodec_send_packet", "avcodec_receive_frame", "avformat_open_input",
"av_read_frame", "av_malloc", "av_free", "av_log", "av_frame_alloc",
"sws_scale", "avfilter_graph_alloc"});
consider("SQLite VDBE runtime",
basename.find("sqlite") != std::string::npos,
{"SQLite format 3", "sqlite3VdbeExec", "database disk image is malformed",
"malformed database schema", "sqlite_master", "sqlite_sequence"},
{"sqlite3_prepare_v2", "sqlite3_step", "sqlite3_finalize", "sqlite3_open_v2"});
consider("Unicorn/Flutter UI runtime",
basename == "libunicorn.so" || basename.rfind("libunicorn_", 0) == 0,
{"Unicorn Engine", "unicorn_render_engine", "FlutterJNI",
"FlutterMutatorsStack", "unicorn_library_loader"}, {});
consider("CPU emulation runtime",
basename.find("unicorn") != std::string::npos ||
basename.find("qemu") != std::string::npos,
{"unicorn engine", "qemu-system", "cpu_exec", "uc_version"},
{"uc_open", "uc_emu_start", "uc_hook_add", "uc_close"});
consider("Hermes JavaScript runtime",
basename.find("hermes") != std::string::npos,
{"facebook::hermes", "HermesRuntime", "Hermes bytecode", "HermesVM"},
{"hermes_create_runtime", "hermes_get_runtime_properties"});
const bool lua_name = basename.rfind("liblua", 0) == 0 ||
basename.rfind("lua", 0) == 0;
consider("Lua bytecode runtime", lua_name,
{"Lua 5.", "luaV_execute", "luaD_precall", "luaG_runerror"},
{"lua_pcall", "lua_pcallk", "lua_newstate", "luaL_newstate"});
const bool jsc_name = basename.rfind("libjsc", 0) == 0 ||
basename.find("javascriptcore") != std::string::npos;
consider("JavaScriptCore runtime", jsc_name,
{"JavaScriptCore", "JSC::VM", "WTF::", "JSGlobalObject"},
{"JSEvaluateScript", "JSGlobalContextCreate", "JSContextGroupCreate"});
const bool wasm_name = basename.rfind("libwasm", 0) == 0 ||
basename.find("webassembly") != std::string::npos;
consider("WebAssembly runtime", wasm_name,
{"WebAssembly", "wasm interpreter", "wasm_runtime", "WASM bytecode"},
{"wasm_runtime_init", "wasm_runtime_load", "wasm_runtime_instantiate"});
const bool regex_name = basename.rfind("libpcre", 0) == 0 ||
basename.rfind("libre2", 0) == 0 ||
basename.rfind("libregex", 0) == 0;
consider("regular-expression runtime", regex_name,
{"PCRE2", "pcre2_match", "regex bytecode", "RE2::"},
{"pcre_exec", "pcre2_match", "regexec"});
return best;
}
static bool is_known_non_vm_candidate_function(const std::string& symbol) {
std::string lower = symbol;
std::transform(lower.begin(), lower.end(), lower.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return symbol.find("_M_open") != std::string::npos ||
symbol.find("cJSON_PrintBuffered") != std::string::npos ||
symbol.find("__do_find_public_src") != std::string::npos ||
symbol.find("av_sscanf") != std::string::npos ||
symbol.find("__cxa_demangle") != std::string::npos ||
lower.find("demangler") != std::string::npos;
}
static bool is_cxxabi_runtime_anchor_function(const std::string& symbol) {
return symbol.rfind("__cxa_", 0) == 0 ||
symbol == "__gxx_personality_v0" ||
symbol == "__dynamic_cast" ||
symbol.find("__cxxabi") != std::string::npos;
}
static AnalysisResult analyze_so(const std::string &name,
const std::vector<uint8_t> &input_buf,
std::vector<ScanDiagnostic>* diagnostics = nullptr,
uint64_t* suppressed_diagnostics = nullptr) {
AnalysisResult r;
r.so_name = name;
r.file_size = input_buf.size();
bool loaded_from_assets = (name.find("assets/") != std::string::npos);
if (loaded_from_assets) {
r.reasons.push_back("loaded from assets path");
}
std::string so_basename = path_basename_lower(name);
if (is_known_runtime_library_name(so_basename, r.known_runtime_name)) {
r.known_runtime_framework = true;
}
const bool pine_basename_hint =
so_basename == "libpine.so" || so_basename == "libpinehook.so";
std::vector<uint8_t> inner_work_buf;
const std::vector<uint8_t>* work_buf_ptr = &input_buf;
if (is_zip_magic(input_buf)) {
r.is_zip_container = true;
r.format_note = "ZIP伪装SO";
std::string inner_name;
std::string inner_failure_code;
if (extract_first_elf_from_zip_buffer(
input_buf, inner_work_buf, inner_name, name,
diagnostics, suppressed_diagnostics, inner_failure_code)) {
r.inner_elf_found = true;
r.format_note = "ZIP伪装SO,已提取内层ELF";
r.reasons.push_back("so entry is actually a zip container");
work_buf_ptr = &inner_work_buf;
} else {
r.final_label = "ZIP_SO_CONTAINER";
r.reasons.push_back("so entry is actually a zip container");
r.packer_score = 0.78;
r.strong_obf_score = 0.68;
if (!inner_failure_code.empty()) {
r.reasons.push_back("inner ZIP scan stopped: " + inner_failure_code);
r.vmp.outcome = "PARTIAL_ANALYSIS";
r.vmp.limitation = "Inner ZIP analysis stopped safely: " +
inner_failure_code;
} else {
r.vmp.outcome = "INCONCLUSIVE_PACKED";
r.vmp.limitation = "No observable inner ELF was found in the container";
}
r.vmp.confidence = "UNKNOWN";
return r;
}
}
const std::vector<uint8_t>& work_buf = *work_buf_ptr;
r.analyzed_file_size = work_buf.size();
r.file_entropy = shannon_entropy(work_buf.data(), work_buf.size());
r.printable_string_count = count_printable_strings(work_buf, 4);
r.has_jni_onload_string =
count_buffer_needles_icase(work_buf, {"JNI_OnLoad"}) != 0;
if (work_buf.size() < sizeof(Elf64_Ehdr_L)) {
r.final_label = "INVALID_ELF";
return r;
}
Elf64_Ehdr_L eh{};
if (!read_struct(work_buf, 0, eh)) {
r.final_label = "INVALID_ELF";
return r;
}
if (!(eh.e_ident[0] == 0x7f &&
eh.e_ident[1] == 'E' &&
eh.e_ident[2] == 'L' &&
eh.e_ident[3] == 'F')) {
std::cerr << "[INVALID_ELF] " << name
<< " size=" << work_buf.size()
<< " prefix=" << hex_dump_prefix(work_buf, 32)
<< "\n";
r.final_label = "INVALID_ELF";
return r;
}
r.valid_elf = true;
r.is_64 = (eh.e_ident[4] == ELFCLASS64_VAL);
r.little_endian = (eh.e_ident[5] == ELFDATA2LSB_VAL);
r.is_aarch64 = (eh.e_machine == EM_AARCH64_VAL);