feat(defender): 运行时防护库 + readoor 接入(检测→分级→数据毒化)+ §7 硬化与二进制完整性探针 #1
@@ -8,12 +8,15 @@ ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# Build artifacts
|
||||
/readoor-test/
|
||||
/test-results/
|
||||
build/
|
||||
bin/
|
||||
dist/
|
||||
DerivedData/
|
||||
*.o
|
||||
*.obj
|
||||
*.bc
|
||||
*.dylib
|
||||
*.a
|
||||
*.framework
|
||||
@@ -40,6 +43,7 @@ project.xcworkspace/xcuserdata/
|
||||
*.log
|
||||
*.tmp
|
||||
*.cache
|
||||
.obfuscate_extraction_cache.json
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
# iOSGuard - 企业级 iOS 加固与安全防护系统
|
||||
|
||||
[](https://developer.apple.com/ios/)
|
||||
[]()
|
||||
[]()
|
||||
|
||||
> **iOSGuard** 是一套融合了 **小蟹加固 (Crab iOS)** 与 **网易易盾 (NetEase YiDun)** 核心能力的企业级 iOS 应用安全加固与对抗系统。
|
||||
> 支持 **“源码工程编译期深度混淆”** 与 **“无源码 IPA 纯二进制后处理加固”** 双模形态,满足 App Store 审核对抗(防 4.3 / 2.3.1 拒审)、核心代码防逆向防反编译、反外挂反调试、游戏与核心资产保护等多维需求。
|
||||
|
||||
---
|
||||
|
||||
## 🌟 核心特性概览
|
||||
|
||||
| 模块 | 核心能力 | 对标产品 |
|
||||
| :--- | :--- | :--- |
|
||||
| **Mach-O 深度重构** | Header 动态扩容、段全局平移、`LC_LOAD_DYLIB` 守护库注入、0x4000 严格页面对齐 | 网易易盾 / 顶象 |
|
||||
| **Class-Dump 彻底防御** | 抹除 `__objc_methname`、`__objc_classname`,动态解密重构 `class_rw_t` | 网易易盾 / 爱加密 |
|
||||
| **原生代码虚拟化 (VMP)** | ARM64 汇编抽离、私有紧凑字节码转换、合规纯解释型虚拟机(不破坏 W^X) | 网易易盾 / 梆梆安全 |
|
||||
| **LLVM 编译加固 Pass** | 控制流平坦化 (Fla)、虚假控制流 (BCF)、常量字符串动态加密、调用栈蹦床代理 | 小蟹加固 / OLLVM / Hikari |
|
||||
| **全维度主动防御 (Defender)** | 内联汇编 SVC 0x80 反调试、ARM64 硬件断点 (DR0-DR7) 探测、反 Frida、反 Inline/GOT Hook、沙盒越狱感知 | 网易易盾 |
|
||||
| **双符号表与崩溃还原** | 编译期记录 `mapping.db`,重构 DWARF 调试节,无缝兼容 Bugly / Sentry / Crashlytics | 小蟹加固 |
|
||||
| **资产与游戏安全** | 免加密文件 Hash 扰动、ChaCha20 流式透明解密、Unity `global-metadata.dat` 与 Cocos Lua/JS 保护 | 小蟹加固 / 网易易盾 |
|
||||
| **跨平台自动化重签名** | 支持 macOS (`codesign`) 与 Linux/Docker (`zsign` 改造内核),强制支持 iOS 15+ DER 规范 | 企业自动化流水线 |
|
||||
| **4.3 审核预检分析器** | 基于 SSDEEP 模糊哈希的 Mach-O 机器码比对、符号集 Jaccard 相似度、图片 pHash 差异度评分 | 小蟹加固 |
|
||||
|
||||
---
|
||||
|
||||
## 📂 项目模块结构
|
||||
|
||||
```
|
||||
iOSGuard/
|
||||
├── docs/ # 详细设计与实现方案文档
|
||||
│ ├── 01_ROADMAP.md # 小蟹加固路线与技术全景
|
||||
│ ├── 02_SECURITY_ARCHITECTURE.md # 易盾级安全加固架构深度剖析
|
||||
│ └── 03_COMPLETE_IMPLEMENTATION_PLAN.md # 完整工程实现蓝图与技术规范
|
||||
├── core/ # 核心 C/C++ 跨平台加固引擎
|
||||
│ ├── macho/ # Mach-O 解析与重构器 (Header扩容 / 段平移 / 对齐)
|
||||
│ ├── metadata/ # Objective-C 元数据清洗与加密 (防 Class-Dump)
|
||||
│ ├── vmp/ # 原生代码虚拟化编译器与虚拟机解释引擎
|
||||
│ └── signer/ # 跨平台重签名核心 (基于 zsign 扩展,支持 DER)
|
||||
├── defender/ # 注入的运行时防护库源码 (输出 libDefender.dylib)
|
||||
│ ├── anti_debug/ # 内联汇编 SVC 系统调用反调试、硬件断点轮询
|
||||
│ ├── anti_hook/ # Inline Hook 前向指令探测、Dyld GOT 范围校验
|
||||
│ ├── anti_frida/ # Frida 端口探测、线程扫描、动态库匹配
|
||||
│ ├── anti_jailbreak/ # 沙盒感知、fork 检测、特征路径探测
|
||||
│ └── vfs_crypto/ # 资源透明解密 Hook (open/read/imageNamed)
|
||||
├── llvm-plugins/ # 源码加固 LLVM Pass (集成至 Xcode 自定义 Toolchain)
|
||||
│ ├── Flattening/ # 控制流平坦化 Pass
|
||||
│ ├── BogusControlFlow/ # 虚假控制流 Pass
|
||||
│ ├── StringEncryption/ # 常量字符串加密 Pass
|
||||
│ └── CallStackObfuscate/ # 调用栈伪装与蹦床代理 Pass
|
||||
├── tools/ # 辅助工具链
|
||||
│ ├── dsym_restorer/ # dSYM 崩溃逆向还原工具 (DWARF 重写)
|
||||
│ ├── ipa_diff_analyzer/ # IPA 4.3 相似度静态评估分析器
|
||||
│ └── pbx_injector/ # Xcode 工程配置与 Build Phase 自动化注入脚本
|
||||
├── cli/ # 命令行终端工具
|
||||
└── README.md # 本文件
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📖 技术文档导航
|
||||
|
||||
详细技术实现细节与数学/算法推导请参阅 `docs/` 目录:
|
||||
1. **[小蟹路线与技术全景](docs/01_ROADMAP.md)**:包含符号策略、资源 Hash 扰动、COSDK 运行时反射修复与 dSYM 崩溃还原体系。
|
||||
2. **[易盾安全防护架构方案](docs/02_SECURITY_ARCHITECTURE.md)**:包含代码虚拟化 (VMP)、全维度主动防御底层汇编、游戏资产防护与白盒加密。
|
||||
3. **[完整工程实现蓝图](docs/03_COMPLETE_IMPLEMENTATION_PLAN.md)**:包含八大子系统详细设计规范、Mach-O 段平移算法、跨平台签名时序与里程碑规划。
|
||||
|
||||
---
|
||||
|
||||
## 🚀 研发里程碑规划
|
||||
|
||||
- **M1 (第 1~4 周,极简闭环 MVP)**:自建 arm64 测试工程 + Padding 充足条件下验证 `LC_LOAD_DYLIB` 原地注入 + 物理嵌入 `libDefender.dylib` 与 `@rpath` 解析 + macOS 原生 `codesign` 重签名 + 真机冷启/基础合规反调试/崩溃符号化全流程闭环验证。
|
||||
- **M2 (第 5~9 周,进阶加固与重定位修复)**:全局段平移(Segment Shift)与 `LC_DYLD_CHAINED_FIXUPS` 修复 + Objective-C 元数据精细化抽取与 ASLR 动态恢复 + Linux 端 `zsign` 无 Mac 依赖签名闭环。
|
||||
- **M3 (第 10~14 周,LLVM 混淆与 dSYM 还原)**:控制流平坦化、字符串加密 Pass + DWARF 定点重写与线上崩溃还原。
|
||||
- **M4 (第 15~20 周,代码虚拟化与游戏安全)**:原生纯解释型 VMP 虚拟机 + 完整内存/指令边界防御 + Unity IL2CPP / Cocos 加密保护。
|
||||
- **M5 (第 21~24 周,4.3 预检与平台化)**:SSDEEP 相似度分析工具 + 内部风控度量体系 + CLI 命令行与商业控制台交付。
|
||||
|
||||
---
|
||||
|
||||
## ⚖️ 苹果审核与合规声明
|
||||
|
||||
1. **AMFI 与 W^X 合规**:本系统代码虚拟化 (VMP) 采用纯解释型虚拟机,不申请可执行内存(无 `mprotect(PROT_EXEC)`),严格遵守苹果 W^X 内存安全规范。
|
||||
2. **公开 API 提审合规 (Guideline §2.5.1)**:App Store 提审版本中通过宏开关物理排除所有私有未公开符号(如 iPhoneOS SDK 未包含的 `ptrace` 相关调用)及裸汇编 syscall,仅依赖公开文档支持的 `sysctl` 调试检测;内核级汇编软中断与 `PT_DENY_ATTACH` 严格限制于企业内部分发 (Enterprise) / Ad-Hoc 场景。
|
||||
3. **签名标准化**:重签名引擎严格遵从苹果 iOS 15+ DER-encoded Entitlements 与 CodeDirectory 16KB 分页哈希规范,保证 App Store 提审解签正常。
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# Third-Party Notices
|
||||
|
||||
This repository incorporates clean-room implementations and algorithmic concepts adapted from third-party open-source projects.
|
||||
|
||||
## O-MVLL (Open-Obfuscator)
|
||||
- Upstream: https://github.com/open-obfuscator/o-mvll
|
||||
- License: Apache License, Version 2.0 (Apache-2.0)
|
||||
- Adapted concepts in `llvm_passes/src/`:
|
||||
- `IGArithmetic.cpp`: Mixed Boolean-Arithmetic (MBA) linear expression rewriting.
|
||||
- `IGOpaqueConstants.cpp`: Opaque constant encoding and splitting.
|
||||
- `IGIndirectBranch.cpp`: Encrypted jump-table indirect branching (`indirectbr`).
|
||||
- `IGAntiHooking.cpp`: AArch64 `x16`/`x17` prologue insertion (`Function::setPrologueData`).
|
||||
- `IGIndirectCall.cpp`: Dual read-only share table encoding for indirect calls.
|
||||
- `IGStringEncryption.cpp`: Stack-buffer decryption with volatile zero-wipe for non-escaping short literals.
|
||||
@@ -0,0 +1,144 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"description": "Production diagnostic event code mapping replacing plaintext business semantic log tags",
|
||||
"events": {
|
||||
"E-3101": "RD30EpubCoordinator: resource_resolve_failure",
|
||||
"E-3102": "RD30EpubCoordinator: reader_create",
|
||||
"E-3103": "RD30EpubCoordinator: reader_open_failure",
|
||||
"E-3104": "RD30EpubCoordinator: reader_open_success",
|
||||
"E-3105": "RD30EpubCoordinator: reader_trial_wall",
|
||||
"E-3106": "RD30EpubCoordinator: entry_open",
|
||||
"E-3107": "RD30EpubFileStore: local_cache_miss",
|
||||
"E-3108": "RD30EpubFileStore: local_cache_hit",
|
||||
"E-3109": "RD30EpubResourceService: resource_request_start",
|
||||
"E-3110": "RD30EpubResourceService: resource_resolved",
|
||||
"E-3111": "RD30EpubDownloadManager: download_start",
|
||||
"E-3112": "RD30EpubDownloadManager: download_cancel",
|
||||
"E-3113": "RD30EpubDownloadManager: download_complete",
|
||||
"E-3114": "RD30EpubDownloadManager: download_failure",
|
||||
"E-3115": "EpubParser: missing_container_xml",
|
||||
"E-3201": "RDPDFStsSimpleCryptBridge: decrypt_nil",
|
||||
"E-3202": "RDPDFDownloadAPIService: Range 下载非 206 响应: urlPath=",
|
||||
"E-3203": "RDPDFDownloadAPIService: Range 下载写入失败",
|
||||
"E-3204": "RDPDFDownloadAPIService: Range 下载失败",
|
||||
"E-3205": "RDPDFDownloadAPIService: 下载失败",
|
||||
"E-3206": "RDPDFLoadBookUseCase: API 失败",
|
||||
"E-3207": "RDPDFLoadBookUseCase: trial_auth_keya_nm 下载解压失败",
|
||||
"E-3208": "RDPDFLoadBookUseCase: Auth key 文件存在但为空/无法读取大小,删除后重新写入",
|
||||
"E-3209": "RDPDFLoadBookUseCase: Auth key 转换 Data 失败",
|
||||
"E-3210": "RDPDFLoadBookUseCase: Auth key base64 解码失败",
|
||||
"E-3211": "RDPDFLoadBookUseCase: Auth key 写入失败",
|
||||
"E-3212": "RDPDFLoadBookUseCase: 未取到 coursewareGuid,点读热区无法加载: sectionGuid=",
|
||||
"E-3213": "RDPDFDecryptPageUseCase: PDF 映射文件不存在",
|
||||
"E-3214": "RDPDFDecryptPageUseCase: Auth 映射文件不存在",
|
||||
"E-3215": "RDPDFDecryptPageUseCase: PDF 映射表解密失败: path=",
|
||||
"E-3216": "RDPDFDecryptPageUseCase: Auth 映射表解密失败: path=",
|
||||
"E-3217": "RDPDFDecryptPageUseCase: 映射表 JSON 解析失败: pdfPages存在=",
|
||||
"E-3218": "RDPDFDecryptPageUseCase: PDF 切片文件不存在",
|
||||
"E-3219": "RDPDFDecryptPageUseCase: Auth 文件不存在",
|
||||
"E-3220": "RDPDFDecryptPageUseCase: authMap 索引越界: pageIdx=",
|
||||
"E-3221": "RDPDFDecryptPageUseCase: auth data 长度为 0: start=",
|
||||
"E-3222": "RDPDFDecryptPageUseCase: auth data 越界: start+dataLen=",
|
||||
"E-3223": "RDPDFDecryptPageUseCase: 初始化解密引擎失败: deIndex=",
|
||||
"E-3224": "RDPDFDecryptPageUseCase: 合并解密失败: result=",
|
||||
"E-3225": "RDPDFDecryptPageUseCase: 重命名失败",
|
||||
"E-3226": "RDPDFDecryptPageUseCase: 读取 auth 文件失败",
|
||||
"E-3227": "RDPDFRenderPageUseCase: extractText: openDecryptedPage failed, bookId=",
|
||||
"E-3228": "RDPDFDownloadScheduler: downloadPdfPage: pdfMap 缺少页码 的字节偏移",
|
||||
"E-3229": "RDPDFReaderViewModel+SDKPageSource: 缺页插队下载失败: pageNo=",
|
||||
"E-3230": "RDPDFRenderPageUseCase: openDecryptedPage_file_missing",
|
||||
"E-3231": "RDPDFRenderPageUseCase: initializeParser_file_missing",
|
||||
"E-3232": "RDPDFRenderPageUseCase: initializeParser_init_failed",
|
||||
"E-3233": "RDPDFRenderPageUseCase: initializeParser_open_failed",
|
||||
"E-3234": "RDPDFBookReaderViewController: annotation_persistence_failed",
|
||||
"E-3235": "RDPDFReaderViewModel+SDKPageSource: sdk_page_render_failed",
|
||||
"E-3236": "RDPDFReaderViewModel: decryptAndPrepare_bookInfo_nil",
|
||||
"E-3237": "RDPDFReaderViewModel: decrypt_mapping_failed",
|
||||
"E-3238": "RDPDFReaderViewModel: missing_pdfMap_byte_range",
|
||||
"E-3239": "RDPDFReaderViewModel: initial_page_range_download_failed",
|
||||
"E-3240": "RDPDFReaderViewModel: initial_page_decrypt_failed",
|
||||
"E-3241": "RDPDFReaderViewModel: initial_page_render_failed",
|
||||
"E-3242": "RDPDFReaderViewModel: preload_page_decrypt_failed",
|
||||
"E-3301": "RDHLSLocalProxy: stale_port_listener_rebuild",
|
||||
"E-3302": "RDHLSLocalProxy: listener_start_failed",
|
||||
"E-3303": "RDHLSLocalProxy: listener_start_exception",
|
||||
"E-3304": "RDHLSLocalProxy: unsupported_playlist_fallback",
|
||||
"E-3305": "RDHLSLocalProxy: missing_stream_context",
|
||||
"E-3306": "RDHLSLocalProxy: segment_key_fetch_failed",
|
||||
"E-3307": "RDHLSLocalProxy: segment_aes128_decrypt_failed",
|
||||
"E-3308": "RDHLSLocalProxy: sps_pps_extract_failed",
|
||||
"E-3309": "RDHLSLocalProxy: upstream_fetch_failed",
|
||||
"E-4101": "RDSDPrivateKeyManager: missing_bundled_encrypted_key_blob",
|
||||
"E-4102": "RDSDPrivateKeyManager: aes_gcm_decrypt_bundled_key_failed",
|
||||
"E-4103": "RDSDPrivateKeyManager: derive_aes_key_or_slot_failed",
|
||||
"E-4104": "RDSDPrivateKeyManager: create_sec_key_from_pem_failed",
|
||||
"E-4105": "RDSDAuthV32Signer: missing_auth_token",
|
||||
"E-4106": "RDSDAuthV32Signer: missing_device_id_in_jwt",
|
||||
"E-4107": "RDSDAuthV32Signer: missing_required_request_headers",
|
||||
"E-4108": "RDSDAuthV32Signer: signing_key_unavailable",
|
||||
"E-4109": "RDSDAuthV32Signer: rsa_sign_failed",
|
||||
"E-4110": "RDSDAuthV32Signer: sec_key_create_signature_failed",
|
||||
"E-4111": "RDBaseNetworkService: auth_v32_sign_aborted",
|
||||
"E-4112": "RDBaseNetworkService: encrypted_endpoint_rejected_plaintext_json",
|
||||
"E-4113": "RDBaseNetworkService: encrypted_endpoint_malformed_error_or_html",
|
||||
"E-4114": "RDBaseNetworkService: encrypted_endpoint_decrypt_empty_or_nil",
|
||||
"E-4115": "RDBaseNetworkService: encrypted_endpoint_json_parse_failed",
|
||||
"E-4201": "RDAccountTokenHandler: startup_get_account_info_failed",
|
||||
"E-4202": "RDAccountTokenHandler: replace_token_sign_expired",
|
||||
"E-4203": "RDAccountTokenHandler: replace_token_retry_scheduled",
|
||||
"E-4204": "RDAccountTokenHandler: logout_before_guest_register_failed",
|
||||
"E-4205": "RDAccountTokenHandler: force_replace_token_for_device_id_migration",
|
||||
"E-5101": "RDIAPPurchaseManager: init_purchase_manager",
|
||||
"E-5102": "RDIAPPurchaseManager: deinit_purchase_manager",
|
||||
"E-5103": "RDIAPPurchaseManager: gate_claimed",
|
||||
"E-5104": "RDIAPPurchaseManager: gate_reclaimed_stale",
|
||||
"E-5105": "RDIAPPurchaseManager: gate_released",
|
||||
"E-5106": "RDIAPPurchaseManager: gate_release_noop",
|
||||
"E-5107": "RDIAPPurchaseManager: unfinished_order_matched",
|
||||
"E-5108": "RDIAPPurchaseManager: unfinished_order_lookup_failed",
|
||||
"E-5109": "RDIAPPurchaseManager: resume_missing_order_no_or_finished",
|
||||
"E-5110": "RDIAPPurchaseManager: resume_unfinished_iteration_failed",
|
||||
"E-5111": "RDIAPPurchaseManager: retry_pending_transaction_not_found_or_invalid",
|
||||
"E-5112": "RDIAPPurchaseManager: retry_pending_server_verified_success",
|
||||
"E-5113": "RDIAPPurchaseManager: retry_pending_server_verified_failed",
|
||||
"E-5114": "RDIAPPurchaseManager: retry_pending_server_confirming_or_error",
|
||||
"E-5115": "RDIAPPurchaseManager: handle_verified_transaction_success",
|
||||
"E-5116": "RDIAPPurchaseManager: handle_verified_transaction_failed_final",
|
||||
"E-5117": "RDIAPPurchaseManager: handle_verified_transaction_confirming",
|
||||
"E-5118": "RDIAPPurchaseManager: request_storekit_products_failed",
|
||||
"E-5119": "RDIAPPurchaseManager: process_claimed_purchase_success",
|
||||
"E-5120": "RDIAPPurchaseManager: process_claimed_purchase_failed_or_cancelled",
|
||||
"E-5121": "RDIAPPurchaseManager: process_claimed_purchase_confirming_or_pending",
|
||||
"E-5122": "RDIAPPurchaseManager: transaction_verification_or_refund_failed",
|
||||
"E-5123": "RDIAPHandler: request_apple_products_empty",
|
||||
"E-5124": "RDIAPHandler: submit_order_missing_pay_config",
|
||||
"E-5125": "RDIAPHandler: submit_order_reattach_pending_verifying_order",
|
||||
"E-5126": "RDIAPHandler: submit_order_reattach_unfinished_storekit_order",
|
||||
"E-5127": "RDIAPHandler: submit_order_create_trade_order_failed",
|
||||
"E-5128": "RDIAPHandler: to_purchase_existing_order_retry_or_abort",
|
||||
"E-5129": "RDIAPHandler: to_purchase_finish_state_dispatch",
|
||||
"E-5130": "RDIAPHandler: pending_purchase_timeout_triggered",
|
||||
"E-5131": "RDIAPHandler: server_check_transaction_success",
|
||||
"E-5132": "RDIAPHandler: server_check_transaction_failed",
|
||||
"E-5133": "RDIAPHandler: server_check_transaction_id_success",
|
||||
"E-5134": "RDIAPHandler: server_check_transaction_id_failed",
|
||||
"E-5135": "RDIAPHandler: request_server_check_apple_pay_config_unavailable",
|
||||
"E-5136": "RDIAPHandler: iap_purchase_result_no_pending_handler",
|
||||
"E-5191": "RDIAPPurchaseException: no_product_matched",
|
||||
"E-5192": "RDIAPPurchaseException: purchase_exception",
|
||||
"E-5193": "RDIAPPurchaseException: purchase_in_progress",
|
||||
"E-5194": "RDIAPPurchaseException: transaction_verification_failed",
|
||||
"E-6101": "RDSecurityGuard: high_confidence_degradation_triggered",
|
||||
"E-6102": "RDSecurityGuard: sensitive_operation_restricted",
|
||||
"E-6103": "RDSecurityGuard: policy_decision_evaluated",
|
||||
"E-6104": "RDSecurityGuard: risk_context_evaluated",
|
||||
"E-6105": "RDSecurityGuard: observation_record_write_failed",
|
||||
"E-6106": "RDInjectionDetector: whitelist_missing_or_corrupt",
|
||||
"E-6107": "RDInjectionDetector: whitelist_unparseable",
|
||||
"E-6108": "RDInjectionDetector: whitelist_hmac_mismatch",
|
||||
"E-6109": "RDInjectionDetector: release_whitelist_tamper_risk",
|
||||
"E-6110": "RDInjectionDetector: suspicious_dyld_insert_libraries",
|
||||
"E-6111": "RDInjectionDetector: skip_external_non_system_image",
|
||||
"E-6112": "RDInjectionDetector: unauthorized_image_detected"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,865 @@
|
||||
{
|
||||
"schema_version": 3,
|
||||
"description": "Milestone 3+ + M1-M4 O-MVLL Core Pass Integration: Star-Switch + Indirect-Call + OpaqueConstants + MBA Arithmetic + OC/Swift hybrid compensation",
|
||||
"flatten_topology": "sparse_switch",
|
||||
"flatten_bogus_blocks": 2,
|
||||
"flatten_split_linear_blocks": true,
|
||||
"opaque_const_max_per_fn": 48,
|
||||
"arithmetic_rounds": 1,
|
||||
"arithmetic_max_per_fn": 96,
|
||||
"string_encrypt_stack_max_len": 128,
|
||||
"indirect_call_dual_table": true,
|
||||
"opaque_const_exempt_functions": [
|
||||
"rd_sd_sha256_transform"
|
||||
],
|
||||
"arithmetic_exempt_functions": [
|
||||
"rd_sd_sha256_transform",
|
||||
"rd_sd_md5_hex"
|
||||
],
|
||||
"indirect_branch_exempt_functions": [
|
||||
"rd_sd_sha256_transform",
|
||||
"rd_sd_md5_hex"
|
||||
],
|
||||
"exempt_path_substrings": [
|
||||
"/Pods/",
|
||||
"/Vendor/AliPlayerSDK_iOS/",
|
||||
"/Vendor/TAI/",
|
||||
"/readoorTests/",
|
||||
"/DerivedData/"
|
||||
],
|
||||
"obfuscate_static_frameworks": [
|
||||
"RDEpubReaderView",
|
||||
"RDPDFReaderView"
|
||||
],
|
||||
"exempt_function_prefixes": [
|
||||
"__ig_",
|
||||
"ig_call_",
|
||||
"ig_poison_",
|
||||
"ig_sys_",
|
||||
"ig_archive_",
|
||||
"ig_anti_hook_warmup",
|
||||
"ig_dispatch_warmup",
|
||||
"ig_objc_baseline_init",
|
||||
"_IG_dispatch_",
|
||||
"IG_dispatch_",
|
||||
"ig_a0",
|
||||
"ig_a1",
|
||||
"ig_a2",
|
||||
"ig_a3",
|
||||
"ig_a4",
|
||||
"rd_a0",
|
||||
"rd_a1",
|
||||
"rd_a2",
|
||||
"rd_a3",
|
||||
"rd_a4",
|
||||
"llvm.",
|
||||
"__swift_"
|
||||
],
|
||||
"scrub_path_substrings": [
|
||||
"/tmp/ig-ipa-work/",
|
||||
"/tmp/ig-",
|
||||
"/src/readoor/"
|
||||
],
|
||||
"string_encrypt_targets": [
|
||||
{
|
||||
"id": "objc_sts_jailbreak_str",
|
||||
"path_contains": "STSJailbreakDetectTool.m"
|
||||
},
|
||||
{
|
||||
"id": "c_rd_epub_keybox_str",
|
||||
"path_contains": "RDEpubKeyBox.c"
|
||||
},
|
||||
{
|
||||
"id": "c_rd_sd_keybox_str",
|
||||
"path_contains": "RDSDKeyBox.c"
|
||||
},
|
||||
{
|
||||
"id": "swift_rd_key_generator_str",
|
||||
"path_contains": "RDKeyGenerator.swift"
|
||||
},
|
||||
{
|
||||
"id": "objc_rd_epub_bridge_str",
|
||||
"path_contains": "RDEpubCryptBridge.m"
|
||||
},
|
||||
{
|
||||
"id": "core_security_dir_str",
|
||||
"path_contains": "3.0/Base/Security/"
|
||||
},
|
||||
{
|
||||
"id": "core_storekit_dir_str",
|
||||
"path_contains": "3.0/Base/StoreKit/"
|
||||
},
|
||||
{
|
||||
"id": "core_network_dir_str",
|
||||
"path_contains": "3.0/Network/"
|
||||
},
|
||||
{
|
||||
"id": "core_iap_handler_dir_str",
|
||||
"path_contains": "3.0/Features/IAP/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_iap_controllers_dir_str",
|
||||
"path_contains": "3.0/Features/IAP/Controllers/"
|
||||
},
|
||||
{
|
||||
"id": "core_wallet_handler_dir_str",
|
||||
"path_contains": "3.0/Features/IAP/WalletBill/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_vip_ext_dir_str",
|
||||
"path_contains": "3.0/Features/VIP/Extension/"
|
||||
},
|
||||
{
|
||||
"id": "core_vip_handler_dir_str",
|
||||
"path_contains": "3.0/Features/VIP/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_vip_controllers_dir_str",
|
||||
"path_contains": "3.0/Features/VIP/Controllers/"
|
||||
},
|
||||
{
|
||||
"id": "core_login_handler_dir_str",
|
||||
"path_contains": "3.0/Features/Account/Login/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_login_controllers_dir_str",
|
||||
"path_contains": "3.0/Features/Account/Login/Controllers/"
|
||||
},
|
||||
{
|
||||
"id": "core_login_ext_dir_str",
|
||||
"path_contains": "3.0/Features/Account/Login/Extension/"
|
||||
},
|
||||
{
|
||||
"id": "core_epub_30_dir_str",
|
||||
"path_contains": "3.0/Features/ReadView/Epub/"
|
||||
},
|
||||
{
|
||||
"id": "core_pdf_bridge_dir_str",
|
||||
"path_contains": "3.0/Features/ReadView/PDF/Bridge/"
|
||||
},
|
||||
{
|
||||
"id": "core_pdf_network_dir_str",
|
||||
"path_contains": "3.0/Features/ReadView/PDF/Network/"
|
||||
},
|
||||
{
|
||||
"id": "core_pdf_decrypt_uc_str",
|
||||
"path_contains": "RDPDFDecryptPageUseCase.swift"
|
||||
},
|
||||
{
|
||||
"id": "core_pdf_load_uc_str",
|
||||
"path_contains": "RDPDFLoadBookUseCase.swift"
|
||||
},
|
||||
{
|
||||
"id": "legacy_iap_handler_dir_str",
|
||||
"path_contains": "BookShelf/Classes/Features/IAP/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "legacy_iap_ext_dir_str",
|
||||
"path_contains": "BookShelf/Classes/Features/IAP/Extension/"
|
||||
},
|
||||
{
|
||||
"id": "legacy_login_ext_dir_str",
|
||||
"path_contains": "BookShelf/Classes/Features/Login/Extension/"
|
||||
},
|
||||
{
|
||||
"id": "legacy_read_or_pay_ext_str",
|
||||
"path_contains": "BookShelf/Classes/Extension/ControllersExtension/STSBaseViewController+STSReadOrPayExtension.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_login_or_pay_ext_str",
|
||||
"path_contains": "BookView/EPUB/Core/Classes/STSBaseViewController+STSEpubViewLoginOrPayExtension.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_pdf_login_or_pay_ext_str",
|
||||
"path_contains": "BookView/PDF/Core/Classes/Stage/STSBaseViewController+STSPDFViewLoginOrPayExtension.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_loader_str",
|
||||
"path_contains": "STSEpubWebResourceLoader.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_ctrl_str",
|
||||
"path_contains": "RBCoreEpubLoadController.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_parser_str",
|
||||
"path_contains": "EpubParser.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_chapter_str",
|
||||
"path_contains": "EpubChapter.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_load_str",
|
||||
"path_contains": "LoadEpub.m"
|
||||
},
|
||||
{
|
||||
"id": "vendor_pdf_trial_str",
|
||||
"path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift"
|
||||
},
|
||||
{
|
||||
"id": "vendor_epub_core_str",
|
||||
"path_contains": "Vendor/RDEpubReaderView/EPUBCore/"
|
||||
}
|
||||
],
|
||||
"string_encrypt_objc_targets": [
|
||||
{ "id": "objc_sts_jailbreak_cfstr", "path_contains": "STSJailbreakDetectTool.m" },
|
||||
{ "id": "objc_rd_epub_bridge_cfstr", "path_contains": "RDEpubCryptBridge.m" },
|
||||
{ "id": "core_security_dir_cfstr", "path_contains": "3.0/Base/Security/" },
|
||||
{ "id": "legacy_iap_handler_cfstr", "path_contains": "BookShelf/Classes/Features/IAP/Handler/" },
|
||||
{ "id": "objc_pay_ext_cfstr", "path_contains": "STSBaseViewController+STSPayExtension.m" },
|
||||
{ "id": "objc_epub_login_pay_ext_cfstr", "path_contains": "STSBaseViewController+STSEpubViewLoginOrPayExtension.m" },
|
||||
{ "id": "objc_pdf_login_pay_ext_cfstr", "path_contains": "STSBaseViewController+STSPDFViewLoginOrPayExtension.m" }
|
||||
],
|
||||
"string_encrypt_swift_targets": [
|
||||
{ "id": "core_security_dir_swstr", "path_contains": "3.0/Base/Security/" },
|
||||
{ "id": "core_storekit_dir_swstr", "path_contains": "3.0/Base/StoreKit/" },
|
||||
{ "id": "core_network_dir_swstr", "path_contains": "3.0/Network/" },
|
||||
{ "id": "core_iap_handler_dir_swstr", "path_contains": "3.0/Features/IAP/Handler/" },
|
||||
{ "id": "core_epub_30_dir_swstr", "path_contains": "3.0/Features/ReadView/Epub/" },
|
||||
{ "id": "vendor_pdf_trial_swstr", "path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift" },
|
||||
{ "id": "vendor_epub_core_swstr", "path_contains": "Vendor/RDEpubReaderView/EPUBCore/" }
|
||||
],
|
||||
"indirect_call_same_image_prefixes": [
|
||||
"rd_epub_",
|
||||
"rd_sd_",
|
||||
"rd_content_",
|
||||
"rd_iap_",
|
||||
"rd_sec_",
|
||||
"ig_sub_",
|
||||
"ig_defender_",
|
||||
"ig_anti_",
|
||||
"ig_resolve_",
|
||||
"ig_verify_",
|
||||
"ig_has_loaded_image_substr",
|
||||
"ig_objc_baseline_",
|
||||
"ig_resolve_verified"
|
||||
],
|
||||
"indirect_call_targets": [
|
||||
{
|
||||
"id": "app30_appconfig_icall",
|
||||
"path_contains": "3.0/AppConfig/"
|
||||
},
|
||||
{
|
||||
"id": "app30_base_icall",
|
||||
"path_contains": "3.0/Base/"
|
||||
},
|
||||
{
|
||||
"id": "app30_database_icall",
|
||||
"path_contains": "3.0/Database/"
|
||||
},
|
||||
{
|
||||
"id": "app30_features_icall",
|
||||
"path_contains": "3.0/Features/"
|
||||
},
|
||||
{
|
||||
"id": "app30_network_icall",
|
||||
"path_contains": "3.0/Network/"
|
||||
},
|
||||
{
|
||||
"id": "app30_router_icall",
|
||||
"path_contains": "3.0/Router/"
|
||||
},
|
||||
{
|
||||
"id": "app30_appdelegate_icall",
|
||||
"path_contains": "3.0/RDAppDelegate.swift"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_base_icall",
|
||||
"path_contains": "BookShelf/Classes/Base/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_database_icall",
|
||||
"path_contains": "BookShelf/Classes/Database/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_extension_icall",
|
||||
"path_contains": "BookShelf/Classes/Extension/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_features_icall",
|
||||
"path_contains": "BookShelf/Classes/Features/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_handler_icall",
|
||||
"path_contains": "BookShelf/Classes/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_macro_icall",
|
||||
"path_contains": "BookShelf/Classes/Macro/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_models_icall",
|
||||
"path_contains": "BookShelf/Classes/Models/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_network_icall",
|
||||
"path_contains": "BookShelf/Classes/Network/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_storage_icall",
|
||||
"path_contains": "BookShelf/Classes/Storage/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_util_icall",
|
||||
"path_contains": "BookShelf/Classes/Util/"
|
||||
},
|
||||
{
|
||||
"id": "bookshelf_sts_root_icall",
|
||||
"path_contains": "BookShelf/Classes/STS"
|
||||
},
|
||||
{
|
||||
"id": "bookview_audio_icall",
|
||||
"path_contains": "BookView/Audio/"
|
||||
},
|
||||
{
|
||||
"id": "bookview_audiovideo_icall",
|
||||
"path_contains": "BookView/Audio&Video/"
|
||||
},
|
||||
{
|
||||
"id": "bookview_download_icall",
|
||||
"path_contains": "BookView/BookDownLoad/"
|
||||
},
|
||||
{
|
||||
"id": "bookview_common_icall",
|
||||
"path_contains": "BookView/Common/"
|
||||
},
|
||||
{
|
||||
"id": "bookview_epub_icall",
|
||||
"path_contains": "BookView/EPUB/"
|
||||
},
|
||||
{
|
||||
"id": "bookview_pdf_icall",
|
||||
"path_contains": "BookView/PDF/"
|
||||
},
|
||||
{
|
||||
"id": "bookview_ppt_icall",
|
||||
"path_contains": "BookView/PPT/"
|
||||
},
|
||||
{
|
||||
"id": "bookview_video_icall",
|
||||
"path_contains": "BookView/Video/"
|
||||
},
|
||||
{
|
||||
"id": "objc_sts_startup_icall",
|
||||
"path_contains": "STSAppStartupProcess.m"
|
||||
},
|
||||
{
|
||||
"id": "c_ig_defender_icall",
|
||||
"path_contains": "3.0/Base/Security/IGDefender/"
|
||||
},
|
||||
{
|
||||
"id": "vendor_pdf_trial_icall",
|
||||
"path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift"
|
||||
},
|
||||
{
|
||||
"id": "vendor_epub_core_icall",
|
||||
"path_contains": "Vendor/RDEpubReaderView/EPUBCore/"
|
||||
}
|
||||
],
|
||||
"flatten_targets": [
|
||||
{
|
||||
"id": "objc_sts_jailbreak_detect",
|
||||
"path_contains": "STSJailbreakDetectTool.m"
|
||||
},
|
||||
{
|
||||
"id": "swift_rd_injection_dyld_check",
|
||||
"path_contains": "RDInjectionDetector.swift"
|
||||
},
|
||||
{
|
||||
"id": "c_rd_epub_keybox_flatten",
|
||||
"path_contains": "RDEpubKeyBox.c"
|
||||
},
|
||||
{
|
||||
"id": "c_rd_epub_key_guard_flatten",
|
||||
"path_contains": "RDEpubKeyGuard.c"
|
||||
},
|
||||
{
|
||||
"id": "objc_rd_epub_bridge_flatten",
|
||||
"path_contains": "RDEpubCryptBridge.m"
|
||||
},
|
||||
{
|
||||
"id": "c_rd_sd_keybox_flatten",
|
||||
"path_contains": "RDSDKeyBox.c"
|
||||
},
|
||||
{
|
||||
"id": "swift_rd_key_generator_flatten",
|
||||
"path_contains": "RDKeyGenerator.swift"
|
||||
},
|
||||
{
|
||||
"id": "core_security_dir_flatten",
|
||||
"path_contains": "3.0/Base/Security/"
|
||||
},
|
||||
{
|
||||
"id": "core_storekit_dir_flatten",
|
||||
"path_contains": "3.0/Base/StoreKit/"
|
||||
},
|
||||
{
|
||||
"id": "core_network_dir_flatten",
|
||||
"path_contains": "3.0/Network/"
|
||||
},
|
||||
{
|
||||
"id": "swift_sd_signer_build_flatten",
|
||||
"path_contains": "RDSDAuthV32Signer.swift"
|
||||
},
|
||||
{
|
||||
"id": "objc_iap_verify_handler_keychain_flatten",
|
||||
"path_contains": "STSIAPVerifyHandler.m"
|
||||
},
|
||||
{
|
||||
"id": "core_iap_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/IAP/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_iap_controllers_dir_flatten",
|
||||
"path_contains": "3.0/Features/IAP/Controllers/"
|
||||
},
|
||||
{
|
||||
"id": "core_wallet_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/IAP/WalletBill/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_vip_ext_dir_flatten",
|
||||
"path_contains": "3.0/Features/VIP/Extension/"
|
||||
},
|
||||
{
|
||||
"id": "core_vip_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/VIP/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_vip_controllers_dir_flatten",
|
||||
"path_contains": "3.0/Features/VIP/Controllers/"
|
||||
},
|
||||
{
|
||||
"id": "core_login_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/Account/Login/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_login_controllers_dir_flatten",
|
||||
"path_contains": "3.0/Features/Account/Login/Controllers/"
|
||||
},
|
||||
{
|
||||
"id": "core_login_ext_dir_flatten",
|
||||
"path_contains": "3.0/Features/Account/Login/Extension/"
|
||||
},
|
||||
{
|
||||
"id": "core_epub_30_dir_flatten",
|
||||
"path_contains": "3.0/Features/ReadView/Epub/"
|
||||
},
|
||||
{
|
||||
"id": "core_pdf_bridge_dir_flatten",
|
||||
"path_contains": "3.0/Features/ReadView/PDF/Bridge/"
|
||||
},
|
||||
{
|
||||
"id": "core_pdf_network_dir_flatten",
|
||||
"path_contains": "3.0/Features/ReadView/PDF/Network/"
|
||||
},
|
||||
{
|
||||
"id": "core_pdf_decrypt_uc_flatten",
|
||||
"path_contains": "RDPDFDecryptPageUseCase.swift"
|
||||
},
|
||||
{
|
||||
"id": "core_pdf_load_uc_flatten",
|
||||
"path_contains": "RDPDFLoadBookUseCase.swift"
|
||||
},
|
||||
{
|
||||
"id": "legacy_iap_handler_dir_flatten",
|
||||
"path_contains": "BookShelf/Classes/Features/IAP/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "legacy_iap_ext_dir_flatten",
|
||||
"path_contains": "BookShelf/Classes/Features/IAP/Extension/"
|
||||
},
|
||||
{
|
||||
"id": "legacy_login_ext_dir_flatten",
|
||||
"path_contains": "BookShelf/Classes/Features/Login/Extension/"
|
||||
},
|
||||
{
|
||||
"id": "legacy_read_or_pay_ext_flatten",
|
||||
"path_contains": "BookShelf/Classes/Extension/ControllersExtension/STSBaseViewController+STSReadOrPayExtension.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_login_or_pay_ext_flatten",
|
||||
"path_contains": "BookView/EPUB/Core/Classes/STSBaseViewController+STSEpubViewLoginOrPayExtension.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_pdf_login_or_pay_ext_flatten",
|
||||
"path_contains": "BookView/PDF/Core/Classes/Stage/STSBaseViewController+STSPDFViewLoginOrPayExtension.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_iap_ctrl_flatten",
|
||||
"path_contains": "BookShelf/Classes/Features/IAP/Controllers/"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_loader_flatten",
|
||||
"path_contains": "STSEpubWebResourceLoader.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_ctrl_flatten",
|
||||
"path_contains": "RBCoreEpubLoadController.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_parser_flatten",
|
||||
"path_contains": "EpubParser.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_chapter_flatten",
|
||||
"path_contains": "EpubChapter.m"
|
||||
},
|
||||
{
|
||||
"id": "legacy_epub_load_flatten",
|
||||
"path_contains": "LoadEpub.m"
|
||||
},
|
||||
{
|
||||
"id": "c_ig_defender_flatten",
|
||||
"path_contains": "IGDefender.c"
|
||||
},
|
||||
{
|
||||
"id": "c_ig_anti_hook_flatten",
|
||||
"path_contains": "IGAntiHook.c"
|
||||
},
|
||||
{
|
||||
"id": "c_ig_anti_inject_flatten",
|
||||
"path_contains": "IGAntiInject.c"
|
||||
},
|
||||
{
|
||||
"id": "c_ig_anti_tamper_flatten",
|
||||
"path_contains": "IGAntiTamper.c"
|
||||
},
|
||||
{
|
||||
"id": "c_ig_resolve_flatten",
|
||||
"path_contains": "IGResolve.c"
|
||||
},
|
||||
{
|
||||
"id": "vendor_pdf_trial_flatten",
|
||||
"path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift"
|
||||
},
|
||||
{
|
||||
"id": "vendor_epub_core_flatten",
|
||||
"path_contains": "Vendor/RDEpubReaderView/EPUBCore/"
|
||||
},
|
||||
{
|
||||
"id": "core_personal_center_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/PersonalCenter/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_account_userinfo_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/Account/UserInfo/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_account_token_handler_flatten",
|
||||
"path_contains": "3.0/Features/Account/Token/RDAccountTokenHandler.swift"
|
||||
},
|
||||
{
|
||||
"id": "core_account_guest_handler_flatten",
|
||||
"path_contains": "3.0/Features/Account/Guest/RDGuestHandler.swift"
|
||||
},
|
||||
{
|
||||
"id": "core_appinfo_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/AppInfo/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_appinfo_config_handler_flatten",
|
||||
"path_contains": "3.0/Features/AppInfo/RDAppConfigHandler.swift"
|
||||
},
|
||||
{
|
||||
"id": "core_appinfo_update_handler_flatten",
|
||||
"path_contains": "3.0/Features/AppInfo/RDAppVersionUpdateHandler.swift"
|
||||
},
|
||||
{
|
||||
"id": "core_detail_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/Detail/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_home_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/Home/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_learning_task_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/LearningTask/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_message_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/Message/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_pop_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/Pop/RD/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_order_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/PurchaseOrOrder/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_qrcode_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/QRCode/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_readview_base_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/ReadView/BaseHandler/"
|
||||
},
|
||||
{
|
||||
"id": "core_readview_media_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/ReadView/Media/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_readview_words_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/ReadView/MemorizeWords/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_readview_practice_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/ReadView/Practice/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_search_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/Search/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_tabbar_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/TabBar/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_third_redeem_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/ThirdOrderRedeem/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_nmh_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/ThirdPartyService/NMH/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_shenxue_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/ThirdPartyService/ShenXue/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_tracker_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/Tracker/CustomTracker/Handler/"
|
||||
},
|
||||
{
|
||||
"id": "core_webview_handler_dir_flatten",
|
||||
"path_contains": "3.0/Features/WebView/Handler/"
|
||||
}
|
||||
],
|
||||
"opaque_const_targets": [
|
||||
{ "id": "c_rd_sd_keybox_const", "path_contains": "RDSDKeyBox.c", "opaque_zero": true },
|
||||
{ "id": "c_rd_epub_keybox_const", "path_contains": "RDEpubKeyBox.c", "opaque_zero": true },
|
||||
{ "id": "c_rd_epub_key_guard_const", "path_contains": "RDEpubKeyGuard.c", "opaque_zero": true },
|
||||
{ "id": "objc_rd_epub_bridge_const", "path_contains": "RDEpubCryptBridge.m" },
|
||||
{ "id": "core_security_dir_const", "path_contains": "3.0/Base/Security/" },
|
||||
{ "id": "c_ig_defender_const", "path_contains": "IGDefender/", "opaque_zero": true },
|
||||
{ "id": "core_storekit_dir_const", "path_contains": "3.0/Base/StoreKit/" },
|
||||
{ "id": "core_iap_handler_dir_const", "path_contains": "3.0/Features/IAP/Handler/" },
|
||||
{ "id": "legacy_iap_handler_dir_const", "path_contains": "BookShelf/Classes/Features/IAP/Handler/" },
|
||||
{ "id": "legacy_iap_ext_dir_const", "path_contains": "BookShelf/Classes/Features/IAP/Extension/" },
|
||||
{ "id": "legacy_login_ext_dir_const", "path_contains": "BookShelf/Classes/Features/Login/Extension/" },
|
||||
{ "id": "legacy_read_or_pay_ext_const", "path_contains": "STSBaseViewController+STSReadOrPayExtension.m" },
|
||||
{ "id": "legacy_epub_login_pay_ext_const", "path_contains": "STSBaseViewController+STSEpubViewLoginOrPayExtension.m" },
|
||||
{ "id": "legacy_pdf_login_pay_ext_const", "path_contains": "STSBaseViewController+STSPDFViewLoginOrPayExtension.m" },
|
||||
{ "id": "swift_sd_signer_const", "path_contains": "RDSDAuthV32Signer.swift" },
|
||||
{ "id": "swift_key_generator_const", "path_contains": "RDKeyGenerator.swift" },
|
||||
{ "id": "vendor_pdf_trial_const", "path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift", "opaque_zero": true },
|
||||
{ "id": "vendor_epub_core_const", "path_contains": "Vendor/RDEpubReaderView/EPUBCore/" }
|
||||
],
|
||||
"arithmetic_targets": [
|
||||
{ "id": "c_rd_sd_keybox_arith", "path_contains": "RDSDKeyBox.c", "nonlinear_mba": true },
|
||||
{ "id": "c_rd_epub_keybox_arith", "path_contains": "RDEpubKeyBox.c", "nonlinear_mba": true },
|
||||
{ "id": "c_rd_epub_key_guard_arith", "path_contains": "RDEpubKeyGuard.c", "nonlinear_mba": true },
|
||||
{ "id": "objc_rd_epub_bridge_arith", "path_contains": "RDEpubCryptBridge.m" },
|
||||
{ "id": "core_security_dir_arith", "path_contains": "3.0/Base/Security/" },
|
||||
{ "id": "c_ig_defender_arith", "path_contains": "IGDefender/", "nonlinear_mba": true },
|
||||
{ "id": "core_storekit_dir_arith", "path_contains": "3.0/Base/StoreKit/" },
|
||||
{ "id": "core_iap_handler_dir_arith", "path_contains": "3.0/Features/IAP/Handler/" },
|
||||
{ "id": "legacy_iap_handler_dir_arith", "path_contains": "BookShelf/Classes/Features/IAP/Handler/" },
|
||||
{ "id": "legacy_iap_ext_dir_arith", "path_contains": "BookShelf/Classes/Features/IAP/Extension/" },
|
||||
{ "id": "legacy_login_ext_dir_arith", "path_contains": "BookShelf/Classes/Features/Login/Extension/" },
|
||||
{ "id": "legacy_read_or_pay_ext_arith", "path_contains": "STSBaseViewController+STSReadOrPayExtension.m" },
|
||||
{ "id": "legacy_epub_login_pay_ext_arith", "path_contains": "STSBaseViewController+STSEpubViewLoginOrPayExtension.m" },
|
||||
{ "id": "legacy_pdf_login_pay_ext_arith", "path_contains": "STSBaseViewController+STSPDFViewLoginOrPayExtension.m" },
|
||||
{ "id": "swift_sd_signer_arith", "path_contains": "RDSDAuthV32Signer.swift" },
|
||||
{ "id": "swift_key_generator_arith", "path_contains": "RDKeyGenerator.swift" },
|
||||
{ "id": "vendor_pdf_trial_arith", "path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift", "nonlinear_mba": true },
|
||||
{ "id": "vendor_epub_core_arith", "path_contains": "Vendor/RDEpubReaderView/EPUBCore/" }
|
||||
],
|
||||
"indirect_branch_targets": [
|
||||
{ "id": "c_rd_sd_keybox_ibr", "path_contains": "RDSDKeyBox.c" },
|
||||
{ "id": "c_rd_epub_keybox_ibr", "path_contains": "RDEpubKeyBox.c" },
|
||||
{ "id": "c_rd_epub_key_guard_ibr", "path_contains": "RDEpubKeyGuard.c" },
|
||||
{ "id": "objc_rd_epub_bridge_ibr", "path_contains": "RDEpubCryptBridge.m" },
|
||||
{ "id": "c_ig_defender_ibr", "path_contains": "IGDefender/" },
|
||||
{ "id": "swift_injection_det_ibr", "path_contains": "RDInjectionDetector.swift" },
|
||||
{ "id": "swift_jailbreak_det_ibr", "path_contains": "RDJailbreakDetector.swift" },
|
||||
{ "id": "swift_sd_signer_ibr", "path_contains": "RDSDAuthV32Signer.swift" },
|
||||
{ "id": "swift_sd_request_format_ibr", "path_contains": "RDRequestParamsFormat.swift" },
|
||||
{ "id": "swift_sd_private_key_manager_ibr", "path_contains": "RDSDPrivateKeyManager.swift" },
|
||||
{ "id": "swift_iap_transaction_gate_ibr", "path_contains": "RDIAPPurchaseManager.swift", "function_contains": "RDIAPTransactionGate" },
|
||||
{ "id": "swift_iap_handler_ibr", "path_contains": "RDIAPHandler.swift" },
|
||||
{ "id": "objc_iap_verify_handler_ibr", "path_contains": "STSIAPVerifyHandler.m" },
|
||||
{ "id": "objc_pay_ext_ibr", "path_contains": "STSBaseViewController+STSPayExtension.m" },
|
||||
{ "id": "objc_epub_login_pay_ext_ibr", "path_contains": "STSBaseViewController+STSEpubViewLoginOrPayExtension.m" },
|
||||
{ "id": "objc_pdf_login_pay_ext_ibr", "path_contains": "STSBaseViewController+STSPDFViewLoginOrPayExtension.m" },
|
||||
{ "id": "vendor_pdf_trial_ibr", "path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift" },
|
||||
{ "id": "vendor_epub_core_ibr", "path_contains": "Vendor/RDEpubReaderView/EPUBCore/" }
|
||||
],
|
||||
"required_indirect_branch_sources": [
|
||||
"RDRequestParamsFormat.swift",
|
||||
"RDSDPrivateKeyManager.swift",
|
||||
"RDIAPPurchaseManager.swift"
|
||||
],
|
||||
"string_encrypt_stack_targets": [
|
||||
{ "id": "c_rd_sd_keybox_sstr", "path_contains": "RDSDKeyBox.c" },
|
||||
{ "id": "c_rd_epub_keybox_sstr", "path_contains": "RDEpubKeyBox.c" },
|
||||
{ "id": "c_ig_defender_sstr", "path_contains": "IGDefender/" },
|
||||
{ "id": "swift_rd_injection_sstr", "path_contains": "RDInjectionDetector.swift" }
|
||||
],
|
||||
"anti_hooking_targets": [
|
||||
{ "id": "c_rd_sd_keybox_antihook", "path_contains": "RDSDKeyBox.c" },
|
||||
{ "id": "c_rd_epub_keybox_antihook", "path_contains": "RDEpubKeyBox.c" },
|
||||
{ "id": "c_rd_epub_key_guard_antihook", "path_contains": "RDEpubKeyGuard.c" },
|
||||
{ "id": "c_ig_defender_antihook", "path_contains": "IGDefender/" }
|
||||
],
|
||||
"function_outline_max_per_fn": 2,
|
||||
"function_outline_min_insts": 6,
|
||||
"function_outline_exempt_functions": [
|
||||
"rd_sd_sha256_transform",
|
||||
"rd_sd_md5_hex"
|
||||
],
|
||||
"function_outline_targets": [
|
||||
{ "id": "c_rd_sd_keybox_outline", "path_contains": "RDSDKeyBox.c" },
|
||||
{ "id": "c_rd_epub_keybox_outline", "path_contains": "RDEpubKeyBox.c" },
|
||||
{ "id": "c_rd_epub_key_guard_outline", "path_contains": "RDEpubKeyGuard.c" },
|
||||
{ "id": "c_ig_defender_outline", "path_contains": "IGDefender/" },
|
||||
{ "id": "swift_injection_det_outline", "path_contains": "RDInjectionDetector.swift" },
|
||||
{ "id": "swift_iap_handler_outline", "path_contains": "RDIAPHandler.swift" },
|
||||
{ "id": "objc_iap_verify_handler_outline", "path_contains": "STSIAPVerifyHandler.m" },
|
||||
{ "id": "vendor_pdf_trial_outline", "path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift" }
|
||||
],
|
||||
"opaque_field_max_per_fn": 32,
|
||||
"opaque_field_exempt_functions": [
|
||||
"rd_sd_sha256_transform",
|
||||
"rd_sd_md5_hex"
|
||||
],
|
||||
"opaque_field_targets": [
|
||||
{ "id": "c_rd_sd_keybox_field", "path_contains": "RDSDKeyBox.c" },
|
||||
{ "id": "c_rd_epub_keybox_field", "path_contains": "RDEpubKeyBox.c" },
|
||||
{ "id": "c_rd_epub_key_guard_field", "path_contains": "RDEpubKeyGuard.c" },
|
||||
{ "id": "c_ig_defender_field", "path_contains": "IGDefender/" },
|
||||
{ "id": "objc_rd_epub_bridge_field", "path_contains": "RDEpubCryptBridge.m" },
|
||||
{ "id": "core_security_dir_field", "path_contains": "3.0/Base/Security/" },
|
||||
{ "id": "core_storekit_dir_field", "path_contains": "3.0/Base/StoreKit/" },
|
||||
{ "id": "core_iap_handler_dir_field", "path_contains": "3.0/Features/IAP/Handler/" },
|
||||
{ "id": "vendor_pdf_trial_field", "path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift" },
|
||||
{ "id": "vendor_epub_core_field", "path_contains": "Vendor/RDEpubReaderView/EPUBCore/" }
|
||||
],
|
||||
"bb_split_max_per_fn": 4,
|
||||
"bb_split_min_insts": 8,
|
||||
"bb_split_exempt_functions": [
|
||||
"rd_sd_sha256_transform",
|
||||
"rd_sd_md5_hex"
|
||||
],
|
||||
"bb_split_targets": [
|
||||
{ "id": "c_rd_sd_keybox_bbsplit", "path_contains": "RDSDKeyBox.c" },
|
||||
{ "id": "c_rd_epub_keybox_bbsplit", "path_contains": "RDEpubKeyBox.c" },
|
||||
{ "id": "c_rd_epub_key_guard_bbsplit", "path_contains": "RDEpubKeyGuard.c" },
|
||||
{ "id": "c_ig_defender_bbsplit", "path_contains": "IGDefender/" },
|
||||
{ "id": "swift_injection_det_bbsplit", "path_contains": "RDInjectionDetector.swift" },
|
||||
{ "id": "swift_iap_handler_bbsplit", "path_contains": "RDIAPHandler.swift" },
|
||||
{ "id": "objc_iap_verify_handler_bbsplit", "path_contains": "STSIAPVerifyHandler.m" },
|
||||
{ "id": "vendor_pdf_trial_bbsplit", "path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift" },
|
||||
{ "id": "vendor_epub_core_bbsplit", "path_contains": "Vendor/RDEpubReaderView/EPUBCore/" }
|
||||
],
|
||||
"required_targets": [
|
||||
{
|
||||
"id": "objc_sts_jailbreak_detect",
|
||||
"path_contains": "STSJailbreakDetectTool.m",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "swift_rd_injection_dyld_check",
|
||||
"path_contains": "RDInjectionDetector.swift",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 1
|
||||
},
|
||||
{
|
||||
"id": "c_rd_epub_keybox",
|
||||
"path_contains": "RDEpubKeyBox.c",
|
||||
"symbol_contains": "rd_epub_derive_book_key",
|
||||
"str_symbol_contains": "rd_",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 1,
|
||||
"min_opaque_constants": 5,
|
||||
"min_arithmetic_rewrites": 5,
|
||||
"min_indirect_branches": 2,
|
||||
"min_anti_hook_functions": 1
|
||||
},
|
||||
{
|
||||
"id": "swift_epub_provider",
|
||||
"path_contains": "RDEncryptedEpubResourceProvider.swift",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "c_rd_sd_keybox",
|
||||
"path_contains": "RDSDKeyBox.c",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 4,
|
||||
"min_opaque_constants": 10,
|
||||
"min_arithmetic_rewrites": 10,
|
||||
"min_indirect_branches": 5,
|
||||
"min_anti_hook_functions": 1
|
||||
},
|
||||
{
|
||||
"id": "swift_sd_key_manager",
|
||||
"path_contains": "RDSDPrivateKeyManager.swift",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "swift_sd_signer",
|
||||
"path_contains": "RDSDAuthV32Signer.swift",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "swift_iap_handler",
|
||||
"path_contains": "RDIAPHandler.swift",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "objc_iap_verify_handler",
|
||||
"path_contains": "STSIAPVerifyHandler.m",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "c_ig_defender_core",
|
||||
"path_contains": "IGDefender/",
|
||||
"min_flattened": 5,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "objc_pay_ext_core",
|
||||
"path_contains": "STSBaseViewController+STSPayExtension.m",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "objc_epub_login_pay_ext_core",
|
||||
"path_contains": "STSBaseViewController+STSEpubViewLoginOrPayExtension.m",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "vendor_pdf_trial",
|
||||
"path_contains": "Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "vendor_epub_core",
|
||||
"path_contains": "Vendor/RDEpubReaderView/EPUBCore/",
|
||||
"min_flattened": 2,
|
||||
"min_strings_encrypted": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"description": "Milestone 1 Round 1 Group B policy: flatten + controlled string encrypt pre-cleanup EPUB call chain + M0 targets",
|
||||
"exempt_path_substrings": [
|
||||
"/Pods/",
|
||||
"/Vendor/",
|
||||
"/IGDefender/",
|
||||
"/readoorTests/",
|
||||
"/DerivedData/"
|
||||
],
|
||||
"exempt_function_prefixes": [
|
||||
"__ig_",
|
||||
"ig_defender_",
|
||||
"ig_call_",
|
||||
"ig_poison_",
|
||||
"ig_sys_",
|
||||
"ig_a",
|
||||
"ig_archive_",
|
||||
"_IG_dispatch_",
|
||||
"IG_dispatch_",
|
||||
"llvm."
|
||||
],
|
||||
"string_encrypt_targets": [
|
||||
{
|
||||
"id": "objc_sts_jailbreak_str",
|
||||
"path_contains": "STSJailbreakDetectTool.m"
|
||||
},
|
||||
{
|
||||
"id": "swift_rd_injection_str",
|
||||
"path_contains": "RDInjectionDetector.swift"
|
||||
},
|
||||
{
|
||||
"id": "swift_epub_provider_str",
|
||||
"path_contains": "RDEncryptedEpubResourceProvider.swift"
|
||||
},
|
||||
{
|
||||
"id": "objc_epub_loader_str",
|
||||
"path_contains": "STSEpubWebResourceLoader.m"
|
||||
},
|
||||
{
|
||||
"id": "objc_epub_parser_str",
|
||||
"path_contains": "EpubParser.m"
|
||||
}
|
||||
],
|
||||
"flatten_targets": [
|
||||
{
|
||||
"id": "objc_sts_jailbreak_detect",
|
||||
"path_contains": "STSJailbreakDetectTool.m",
|
||||
"function_contains": "detectCurrentDeviceIsJailbroken"
|
||||
},
|
||||
{
|
||||
"id": "swift_rd_injection_dyld_check",
|
||||
"path_contains": "RDInjectionDetector.swift",
|
||||
"function_contains": "32hasSuspiciousDyldInsertLibraries"
|
||||
},
|
||||
{
|
||||
"id": "swift_epub_provider_flatten",
|
||||
"path_contains": "RDEncryptedEpubResourceProvider.swift"
|
||||
},
|
||||
{
|
||||
"id": "swift_epub_launcher_flatten",
|
||||
"path_contains": "RDEpubReaderLauncher.swift",
|
||||
"function_contains": "makeReader"
|
||||
},
|
||||
{
|
||||
"id": "swift_epub_coordinator_flatten",
|
||||
"path_contains": "RD30EpubCoordinator.swift",
|
||||
"function_contains": "openReader"
|
||||
},
|
||||
{
|
||||
"id": "swift_epub_service_flatten",
|
||||
"path_contains": "RD30EpubResourceService.swift",
|
||||
"function_contains": "parse"
|
||||
},
|
||||
{
|
||||
"id": "objc_epub_web_loader_flatten",
|
||||
"path_contains": "STSEpubWebResourceLoader.m",
|
||||
"function_contains": "obtainLocalResource"
|
||||
},
|
||||
{
|
||||
"id": "objc_epub_parser_flatten",
|
||||
"path_contains": "EpubParser.m",
|
||||
"function_contains": "initWithEPubPath"
|
||||
},
|
||||
{
|
||||
"id": "objc_epub_chapter_flatten",
|
||||
"path_contains": "EpubChapter.m",
|
||||
"function_contains": "initWithPath"
|
||||
}
|
||||
],
|
||||
"required_targets": [
|
||||
{
|
||||
"id": "objc_sts_jailbreak_detect",
|
||||
"path_contains": "STSJailbreakDetectTool.m",
|
||||
"symbol_contains": "detectCurrentDeviceIsJailbroken",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 1
|
||||
},
|
||||
{
|
||||
"id": "swift_rd_injection_dyld_check",
|
||||
"path_contains": "RDInjectionDetector.swift",
|
||||
"symbol_contains": "32hasSuspiciousDyldInsertLibraries",
|
||||
"str_symbol_contains": "19RDInjectionDetectorC",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 1
|
||||
},
|
||||
{
|
||||
"id": "swift_epub_provider",
|
||||
"path_contains": "RDEncryptedEpubResourceProvider.swift",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
},
|
||||
{
|
||||
"id": "objc_epub_web_loader",
|
||||
"path_contains": "STSEpubWebResourceLoader.m",
|
||||
"symbol_contains": "obtainLocalResource",
|
||||
"min_flattened": 1,
|
||||
"min_strings_encrypted": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"schema_version": 2,
|
||||
"toolchains": {
|
||||
"27A9275:arm64": {
|
||||
"xcode_version": "27.1",
|
||||
"xcode_build": "27A9275",
|
||||
"sdk_version": "27.1",
|
||||
"host_arch": "arm64",
|
||||
"swiftlang_version": "Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1)",
|
||||
"llvm_branch": "swift/release/6.4.0",
|
||||
"llvm_commit": "903b9faaae5c43ecc9b7e33f8db9c94c7429374a",
|
||||
"cmake_version": "cmake version 4.4.2",
|
||||
"opt_sha256": "186ed12397dcf585a2cfae94f16a3c15397684a75baec6e7a0dd8af27faf6e77",
|
||||
"bundle_path": "~/.cache/iosguard/bundles/igopt-27A9275-arm64.tar.gz",
|
||||
"bundle_sha256": "f1ced88b2ea544b15de911387c44feae5edbb80ce9dd96d8880423c4e2f604e6"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"by_xcode_build": {},
|
||||
"by_swiftlang": {
|
||||
"6.4.0": "swift/release/6.4.0"
|
||||
},
|
||||
"by_swift_major_minor": {
|
||||
"6.4": "swift/release/6.4.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* IGDefender.c — 运行时防护聚合入口。
|
||||
*
|
||||
* 一次性运行 anti_hook + 注入/Frida 全部探针,证据统一经 sink 上报;不做任何处置。
|
||||
* 典型用法(观察模式):App 启动 / 回前台 / 关键操作前调用 ig_defender_scan,
|
||||
* 由上层策略根据 reason 组合决定是否限制功能——本库绝不 exit。
|
||||
*/
|
||||
#include "IGDefender.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include "anti_hook/IGObjCBaseline.h"
|
||||
#include "anti_frida/IGAntiInject.h"
|
||||
#include "anti_debug/IGAntiDebug.h"
|
||||
#include "anti_jailbreak/IGAntiJailbreak.h"
|
||||
#include "dispatch/IGDispatch.h"
|
||||
|
||||
int ig_defender_scan(const char *bundle_path, int probe_port,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
int hits = 0;
|
||||
hits += ig_dispatch_check(sink, ctx);
|
||||
hits += ig_anti_hook_check_default(sink, ctx);
|
||||
hits += ig_objc_baseline_check(sink, ctx);
|
||||
hits += ig_anti_inject_check(bundle_path, sink, ctx);
|
||||
hits += ig_anti_frida_check(probe_port, sink, ctx);
|
||||
hits += ig_anti_debug_check(sink, ctx);
|
||||
hits += ig_anti_jb_check(sink, ctx);
|
||||
return hits;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* IGAntiDebug.c — 调试器跟踪探针实现。
|
||||
* 全部逻辑在 syscall 模块(ig_sys_is_debugged,直发 svc + P_TRACED),
|
||||
* 这里只做三态到 IGFinding 的映射与上报。
|
||||
*/
|
||||
#include "IGAntiDebug.h"
|
||||
#include "syscall/IGSyscall.h"
|
||||
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
# include <stdio.h>
|
||||
#endif
|
||||
|
||||
int ig_anti_debug_check(IGFindingSink sink, void *ctx) {
|
||||
int traced = ig_sys_is_debugged();
|
||||
if (traced == 1) {
|
||||
IGFinding f;
|
||||
__builtin_memset(&f, 0, sizeof(f));
|
||||
f.status = IG_DETECTED;
|
||||
f.reason = IG_REASON_DEBUGGER_ATTACHED;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
snprintf(f.subject, sizeof(f.subject), "kinfo_proc.p_flag&P_TRACED");
|
||||
snprintf(f.evidence, sizeof(f.evidence), "直发 sysctl 检出进程被调试器跟踪");
|
||||
#endif
|
||||
if (sink) sink(&f, ctx);
|
||||
return 1;
|
||||
}
|
||||
if (traced < 0) {
|
||||
IGFinding f;
|
||||
__builtin_memset(&f, 0, sizeof(f));
|
||||
f.status = IG_UNAVAILABLE;
|
||||
f.reason = IG_REASON_DEBUGGER_ATTACHED;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
snprintf(f.subject, sizeof(f.subject), "kinfo_proc.p_flag&P_TRACED");
|
||||
snprintf(f.evidence, sizeof(f.evidence), "sysctl 查询失败,无法判定");
|
||||
#endif
|
||||
if (sink) sink(&f, ctx);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* IGAntiDebug.h — 调试器跟踪探针(接入聚合扫描)。
|
||||
*
|
||||
* 复用 syscall 模块的 ig_sys_is_debugged():直发 sysctl 读 kinfo_proc 的
|
||||
* P_TRACED 位(公开 API 语义,docs/12 已在 lldb 下实测命中),此前该能力
|
||||
* 已实现但未进入 ig_defender_scan 聚合,策略层无从消费——本模块补上接线。
|
||||
* 三态映射:1 → DETECTED(300),0 → clear,-1 → UNAVAILABLE(300)。
|
||||
*/
|
||||
#ifndef IG_ANTI_DEBUG_H
|
||||
#define IG_ANTI_DEBUG_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 调试器跟踪检测:只采集证据不处置(绝不自行 ptrace/exit)。返回 DETECTED 条数。 */
|
||||
int ig_anti_debug_check(IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_ANTI_DEBUG_H */
|
||||
@@ -0,0 +1,284 @@
|
||||
/*
|
||||
* IGAntiInject.c — 代码注入与 Frida 运行时检测实现。
|
||||
*
|
||||
* 全部公开 API:<mach-o/dyld.h>(镜像枚举)、getenv(dyld 环境变量)、
|
||||
* task_threads + thread_info(THREAD_EXTENDED_INFO)(线程名)、BSD socket(端口弱探测)。
|
||||
*
|
||||
* 边界:
|
||||
* - 镜像特征按文件名子串匹配,越狱/注入框架会更名规避——命中是强证据,未命中不等于干净。
|
||||
* - 端口探测仅弱信号(docs/05:不以单一端口判定);默认不启用,需显式传 probe_port。
|
||||
* - 线程名依赖目标进程把 frida 线程命名为已知值,新版本可能改名——同为组合证据之一。
|
||||
*/
|
||||
#include "IGAntiInject.h"
|
||||
#include "IGInline.h" /* ig_strstr/ig_strcmp/ig_strncmp/ig_strlen:抹除探针自身对 libc 匹配函数的依赖 */
|
||||
#include "../dispatch/IGDispatch.h"
|
||||
|
||||
#include <string.h>
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
# include <stdio.h>
|
||||
#endif
|
||||
#include <stdlib.h>
|
||||
#include <strings.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <crt_externs.h> /* _NSGetEnviron:手工遍历环境表,替代可被 hook 的 getenv */
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach/thread_act.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
|
||||
/*
|
||||
* 经 _NSGetEnviron 手工遍历环境表取变量,规避对 getenv 的 hook/特征。
|
||||
* 关键:攻击者只需 hook getenv 让其对 "DYLD_INSERT_LIBRARIES" 返回 NULL,
|
||||
* 即可让下方第 3 步「插入库」检测彻底失明;本函数不经 libc getenv,关闭该盲点。
|
||||
* 仅用 ig_* 内联原语比较,不引入新的可 hook 导入符号。
|
||||
*/
|
||||
static const char *ig_local_getenv(const char *name) {
|
||||
char ***envp = _NSGetEnviron();
|
||||
if (!name || !envp || !*envp) return NULL;
|
||||
size_t nlen = ig_strlen(name);
|
||||
for (char **e = *envp; *e; ++e) {
|
||||
const char *entry = *e;
|
||||
if (ig_strncmp(entry, name, nlen) == 0 && entry[nlen] == '=') {
|
||||
return entry + nlen + 1;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* §7.1 IG_ENC:注入特征串与 frida 线程名不再明文驻留(避免 `strings` 捞出 frida/substrate/
|
||||
* gum-js-loop 等,白送检测目标)。混淆表由 tools/gen_jb_paths.py 生成,运行期解码进栈。
|
||||
*/
|
||||
#include "IGInjectSignatures.inc"
|
||||
|
||||
/* 解码单条混淆串到 out(容量 cap,含结尾 0)。返回长度,失败返回 0。
|
||||
* k0 取 volatile:阻止 -O2 把「常量 enc + 常量 key」整条折叠回明文存入 __const
|
||||
* (否则 strings 又能捞出 frida/gum-js-loop)。强制运行期解码。 */
|
||||
static size_t ig_inj_decode(const unsigned char *enc, size_t n, int idx,
|
||||
char *out, size_t cap) {
|
||||
volatile unsigned k0 = IG_INJ_XOR_K0;
|
||||
if (n + 1 > cap) return 0;
|
||||
for (size_t j = 0; j < n; ++j) {
|
||||
unsigned ks = ((unsigned)k0 + (unsigned)idx * IG_INJ_XOR_K1 + j * IG_INJ_XOR_K2) & 0xFFu;
|
||||
out[j] = (char)(enc[j] ^ ks);
|
||||
}
|
||||
out[n] = '\0';
|
||||
return n;
|
||||
}
|
||||
|
||||
/* "DYLD_INSERT_LIBRARIES" ^ 0x5A(避免明文驻留 __cstring)。 */
|
||||
static const unsigned char kIGDyldEnvEnc[21] = {
|
||||
0x1eu, 0x03u, 0x16u, 0x1eu, 0x05u, 0x13u, 0x14u, 0x09u, 0x1fu, 0x08u, 0x0eu,
|
||||
0x05u, 0x16u, 0x13u, 0x18u, 0x08u, 0x1bu, 0x08u, 0x13u, 0x1fu, 0x09u
|
||||
};
|
||||
|
||||
static void ig_emit2(IGFindingSink sink, void *ctx, int *stop, int *hits,
|
||||
IGStatus st, int reason, const char *subject, const char *evidence) {
|
||||
if (*stop) return;
|
||||
IGFinding f;
|
||||
memset(&f, 0, sizeof(f));
|
||||
f.status = st;
|
||||
f.reason = reason;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
if (subject) strncpy(f.subject, subject, sizeof(f.subject)-1);
|
||||
if (evidence) strncpy(f.evidence, evidence, sizeof(f.evidence)-1);
|
||||
#else
|
||||
(void)subject;
|
||||
(void)evidence;
|
||||
#endif
|
||||
if (st == IG_DETECTED) (*hits)++;
|
||||
if (sink && sink(&f, ctx) != 0) *stop = 1;
|
||||
}
|
||||
|
||||
/* 小写化到缓冲区,便于大小写无关子串匹配。 */
|
||||
static void ig_lower(const char *src, char *dst, size_t cap) {
|
||||
size_t i = 0;
|
||||
for (; src && src[i] && i + 1 < cap; ++i) {
|
||||
char c = src[i];
|
||||
dst[i] = (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : c;
|
||||
}
|
||||
dst[i] = '\0';
|
||||
}
|
||||
|
||||
static int ig_is_system_path2(const char *path) {
|
||||
if (!path) return 0;
|
||||
return ig_strncmp(path, "/usr/lib/", 9) == 0 ||
|
||||
ig_strncmp(path, "/System/", 8) == 0 ||
|
||||
/* iOS 16+ 系统库经 Cryptex 挂载(/private/preboot/Cryptexes/OS/...),系统自身非注入。 */
|
||||
ig_strncmp(path, "/private/preboot/Cryptexes/", 27) == 0;
|
||||
}
|
||||
|
||||
int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx) {
|
||||
int hits = 0, stop = 0;
|
||||
|
||||
/* §7.1:特征串运行期解码进栈,循环内用解码副本;函数退出前擦除。 */
|
||||
char injsig[IG_INJ_ENC_COUNT][24];
|
||||
for (int s = 0; s < IG_INJ_ENC_COUNT; ++s)
|
||||
ig_inj_decode(kIGInjEnc[s].b, kIGInjEnc[s].n, s, injsig[s], sizeof(injsig[s]));
|
||||
|
||||
/* 1+2. 镜像扫描。 */
|
||||
uint32_t imgc = _dyld_image_count();
|
||||
for (uint32_t i = 0; i < imgc && !stop; ++i) {
|
||||
const char *name = _dyld_get_image_name(i);
|
||||
if (!name) continue;
|
||||
/* Apple 系统镜像(/System、/usr/lib、Cryptex)只读且 Apple 签名,永不作为注入证据先行跳过:
|
||||
* 否则子串匹配会把 Apple 私有框架(如 RevealCore 命中 "reveal")误判为注入;
|
||||
* Xcode 调试还会加载 GPUToolsCapture/libViewDebuggerSupport 等系统库。
|
||||
* 真正的 frida/substrate/gadget 装在 Bundle 内或越狱路径(/Library、/var),不在此列。 */
|
||||
if (ig_is_system_path2(name)) continue;
|
||||
|
||||
char low[1024];
|
||||
ig_lower(name, low, sizeof(low));
|
||||
|
||||
int matched = 0;
|
||||
for (int s = 0; s < IG_INJ_ENC_COUNT; ++s) {
|
||||
if (ig_strstr(low, injsig[s])) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "镜像=%s 命中特征=%s", name, injsig[s]);
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_INJECTED_IMAGE, name, ev);
|
||||
#else
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_INJECTED_IMAGE, NULL, NULL);
|
||||
#endif
|
||||
matched = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched) continue;
|
||||
|
||||
/* 非系统、非特征命中:若在 Bundle 外则作为弱信号上报。 */
|
||||
if (bundle_path && ig_strncmp(name, bundle_path, ig_strlen(bundle_path)) != 0) {
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_FOREIGN_IMAGE, name,
|
||||
IG_DIAG_STR("Bundle 外非系统镜像(弱信号,需结合其它证据)"));
|
||||
}
|
||||
}
|
||||
|
||||
/* 3. DYLD_INSERT_LIBRARIES 逐条解析(运行期解码环境变量名)。 */
|
||||
char env_name[24];
|
||||
{
|
||||
volatile unsigned char emask = 0x5Au;
|
||||
for (size_t ei = 0; ei < sizeof(kIGDyldEnvEnc); ++ei) {
|
||||
env_name[ei] = (char)(kIGDyldEnvEnc[ei] ^ emask);
|
||||
}
|
||||
env_name[sizeof(kIGDyldEnvEnc)] = '\0';
|
||||
}
|
||||
const char *dyld = ig_local_getenv(env_name);
|
||||
__builtin_memset(env_name, 0, sizeof(env_name));
|
||||
if (dyld && dyld[0] && !stop) {
|
||||
char buf[4096];
|
||||
strncpy(buf, dyld, sizeof(buf)-1); buf[sizeof(buf)-1] = '\0';
|
||||
char *save = NULL;
|
||||
for (char *tok = strtok_r(buf, ":", &save); tok && !stop;
|
||||
tok = strtok_r(NULL, ":", &save)) {
|
||||
int in_bundle = (bundle_path && ig_strncmp(tok, bundle_path, ig_strlen(bundle_path)) == 0);
|
||||
/* 排除 Apple 系统路径条目:Xcode 调试经 DYLD_INSERT_LIBRARIES 注入
|
||||
* /usr/lib/libViewDebuggerSupport.dylib、/System/.../GPUToolsCapture 等,非恶意注入。
|
||||
* 越狱 frida/substrate 的插入库位于 Bundle 内或非系统路径,仍会命中。 */
|
||||
if (!in_bundle && !ig_is_system_path2(tok)) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "DYLD_INSERT_LIBRARIES 条目=%s(Bundle 外)", tok);
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_DYLD_INSERT, tok, ev);
|
||||
#else
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_DYLD_INSERT, NULL, NULL);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
__builtin_memset(injsig, 0, sizeof(injsig));
|
||||
return hits;
|
||||
}
|
||||
|
||||
/* 遍历本进程线程,匹配 frida 线程名。 */
|
||||
static void ig_scan_threads(IGFindingSink sink, void *ctx, int *stop, int *hits) {
|
||||
thread_act_array_t threads;
|
||||
mach_msg_type_number_t count = 0;
|
||||
if (task_threads(mach_task_self(), &threads, &count) != KERN_SUCCESS) {
|
||||
ig_emit2(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_FRIDA_THREAD,
|
||||
IG_DIAG_STR("task_threads"), IG_DIAG_STR("无法枚举线程"));
|
||||
return;
|
||||
}
|
||||
/* §7.1:frida 线程名运行期解码进栈,比对后擦除。 */
|
||||
char thr[IG_THR_ENC_COUNT][24];
|
||||
for (int t = 0; t < IG_THR_ENC_COUNT; ++t)
|
||||
ig_inj_decode(kIGThrEnc[t].b, kIGThrEnc[t].n, t, thr[t], sizeof(thr[t]));
|
||||
|
||||
for (mach_msg_type_number_t i = 0; i < count; ++i) {
|
||||
thread_extended_info_data_t info;
|
||||
mach_msg_type_number_t icount = THREAD_EXTENDED_INFO_COUNT;
|
||||
if (thread_info(threads[i], THREAD_EXTENDED_INFO,
|
||||
(thread_info_t)&info, &icount) != KERN_SUCCESS) continue;
|
||||
if (info.pth_name[0] == '\0') continue;
|
||||
for (int t = 0; t < IG_THR_ENC_COUNT; ++t) {
|
||||
if (ig_strcmp(info.pth_name, thr[t]) == 0) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "线程名=%s 命中注入运行时特征", info.pth_name);
|
||||
ig_emit2(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_FRIDA_THREAD,
|
||||
info.pth_name, ev);
|
||||
#else
|
||||
ig_emit2(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_FRIDA_THREAD,
|
||||
NULL, NULL);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (*stop) break;
|
||||
}
|
||||
__builtin_memset(thr, 0, sizeof(thr));
|
||||
/* 回收端口。 */
|
||||
for (mach_msg_type_number_t i = 0; i < count; ++i) {
|
||||
mach_port_deallocate(mach_task_self(), threads[i]);
|
||||
}
|
||||
vm_deallocate(mach_task_self(), (vm_address_t)threads, count * sizeof(thread_act_t));
|
||||
}
|
||||
|
||||
/* 非阻塞 connect 到 127.0.0.1:port,可连通即弱信号。 */
|
||||
static int ig_port_open(int port) {
|
||||
int fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) return 0;
|
||||
fcntl(fd, F_SETFL, O_NONBLOCK);
|
||||
struct sockaddr_in sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sin_family = AF_INET;
|
||||
sa.sin_port = htons((uint16_t)port);
|
||||
sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
int rc = connect(fd, (struct sockaddr *)&sa, sizeof(sa));
|
||||
int open = 0;
|
||||
if (rc == 0) {
|
||||
open = 1;
|
||||
} else if (errno == EINPROGRESS) {
|
||||
fd_set wset; FD_ZERO(&wset); FD_SET(fd, &wset);
|
||||
struct timeval tv = { .tv_sec = 0, .tv_usec = 200000 }; /* 200ms 预算 */
|
||||
if (select(fd + 1, NULL, &wset, NULL, &tv) > 0) {
|
||||
int err = 0; socklen_t len = sizeof(err);
|
||||
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len);
|
||||
open = (err == 0);
|
||||
}
|
||||
}
|
||||
IG_dispatch_close(fd);
|
||||
return open;
|
||||
}
|
||||
|
||||
int ig_anti_frida_check(int probe_port, IGFindingSink sink, void *ctx) {
|
||||
int hits = 0, stop = 0;
|
||||
ig_scan_threads(sink, ctx, &stop, &hits);
|
||||
if (probe_port && !stop) {
|
||||
if (ig_port_open(probe_port)) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[128];
|
||||
snprintf(ev, sizeof(ev), "127.0.0.1:%d 可连接(弱信号)", probe_port);
|
||||
char sub[32]; snprintf(sub, sizeof(sub), "port:%d", probe_port);
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_FRIDA_PORT, sub, ev);
|
||||
#else
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_FRIDA_PORT, NULL, NULL);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* IGAntiInject.h — 代码注入与 Frida 运行时检测探针。
|
||||
*
|
||||
* 覆盖(docs/05 §5.C「镜像/白名单」「已知工具线索」+ §4 P1 DYLD 逐项解析):
|
||||
* 1. 镜像扫描:已加载镜像匹配已知注入/调试框架特征(substrate/frida/cycript/reveal…)→ 强证据。
|
||||
* 2. Bundle 外非系统镜像:弱信号(可能是合法 dylib),作为组合证据上报。
|
||||
* 3. DYLD_INSERT_LIBRARIES:逐条解析(非整串前缀),任何条目指向 Bundle 外路径即上报。
|
||||
* 4. Frida 运行时:线程名特征(gum-js-loop/gmain/pool-frida…)+ 默认端口(弱信号)。
|
||||
*
|
||||
* 只采集证据,不处置。单一端口/名称命中不作独立判定,交上层组合。
|
||||
*/
|
||||
#ifndef IG_ANTI_INJECT_H
|
||||
#define IG_ANTI_INJECT_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* 注入检测:镜像特征扫描 + Bundle 外镜像 + DYLD_INSERT_LIBRARIES 逐项解析。
|
||||
* bundle_path:App 主 bundle 路径(.app 目录);用于判定镜像/插入库是否在 Bundle 内。
|
||||
* 传 NULL 则跳过「Bundle 外」判定,仅做特征匹配与 dyld env。
|
||||
* 返回 DETECTED 条数。
|
||||
*/
|
||||
int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx);
|
||||
|
||||
/*
|
||||
* Frida 运行时检测:线程名特征 + 默认端口探测(弱信号)。
|
||||
* probe_port 非 0 时才做端口连接探测(默认 27042);0 表示只做线程名扫描。
|
||||
* 返回 DETECTED 条数。
|
||||
*/
|
||||
int ig_anti_frida_check(int probe_port, IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_ANTI_INJECT_H */
|
||||
@@ -0,0 +1,34 @@
|
||||
/* IGInjectSignatures.inc — 由 tools/gen_jb_paths.py 生成,请勿手改。 */
|
||||
/* 注入/Frida 特征串 XOR 混淆表(§7.1):enc[j]=plain[j]^((K0+idx*K1+j*K2)&0xFF)。 */
|
||||
#define IG_INJ_XOR_K0 0x3cu
|
||||
#define IG_INJ_XOR_K1 0x47u
|
||||
#define IG_INJ_XOR_K2 0x1du
|
||||
|
||||
static const unsigned char kIGInjEnc0[] = { 0x5a, 0x2b, 0x1f, 0xf7, 0xd1 }; /* len=5 */
|
||||
static const unsigned char kIGInjEnc1[] = { 0xe4, 0xc1, 0xd9, 0xbd, 0x92, 0x60 }; /* len=6 */
|
||||
static const unsigned char kIGInjEnc2[] = { 0xa9, 0x9e, 0x6a, 0x4b, 0x5b, 0x38, 0x0c }; /* len=7 */
|
||||
static const unsigned char kIGInjEnc3[] = { 0x72, 0x57, 0x28, 0x1a, 0xec, 0xd2, 0xcb }; /* len=7 */
|
||||
static const unsigned char kIGInjEnc4[] = { 0x34, 0x1c, 0xf0, 0xcc, 0xb5, 0x8a, 0x74, 0x4a, 0x30, 0x29 }; /* len=10 */
|
||||
static const unsigned char kIGInjEnc5[] = { 0xec, 0xc9, 0xbb, 0x85, 0x67, 0x42, 0x2c, 0x1e, 0xe2 }; /* len=9 */
|
||||
static const unsigned char kIGInjEnc6[] = { 0x95, 0x76, 0x42, 0x4e, 0x2e, 0x1e, 0xe0, 0xc4, 0xba, 0x8e }; /* len=10 */
|
||||
static const unsigned char kIGInjEnc7[] = { 0x41, 0x23, 0x05, 0xf7, 0xd4, 0xdc, 0xa8, 0x8c, 0x67, 0x53, 0x3b, 0x09 }; /* len=12 */
|
||||
static const unsigned char kIGInjEnc8[] = { 0x00, 0xe6, 0xcb, 0xaa, 0x83, 0x6c, 0x4c, 0x55, 0x39, 0x1a, 0xe2 }; /* len=11 */
|
||||
static const unsigned char kIGInjEnc9[] = { 0xc9, 0xb7, 0x96, 0x79, 0x4a, 0x38, 0x0b, 0xe9, 0xcc, 0xb4, 0xae, 0x8e, 0x65, 0x55, 0x21 }; /* len=15 */
|
||||
static const unsigned char kIGInjEnc10[] = { 0x70, 0x7a, 0x4a, 0x3c, 0x17, 0xff }; /* len=6 */
|
||||
static const unsigned char kIGInjEnc11[] = { 0x2f, 0x0a, 0xe6, 0xd8, 0xd1, 0xb5, 0x96, 0x70, 0x54, 0x3c }; /* len=10 */
|
||||
static const unsigned char kIGInjEnc12[] = { 0xfc, 0xc4, 0xa8, 0x8f, 0x6b, 0x4e, 0x55, 0x3e, 0x0a }; /* len=9 */
|
||||
static const unsigned char kIGInjEnc13[] = { 0xa4, 0x9c, 0x70, 0x4a, 0x24, 0x1f, 0xed, 0xcd, 0xd0, 0xb7 }; /* len=10 */
|
||||
static const unsigned char kIGInjEnc14[] = { 0x7a, 0x54, 0x3a, 0x17, 0xeb }; /* len=5 */
|
||||
static const unsigned char kIGInjEnc15[] = { 0x03, 0xeb, 0xec, 0xd4, 0xb1, 0x99, 0x7c, 0x5b }; /* len=8 */
|
||||
static const struct { const unsigned char *b; unsigned char n; } kIGInjEnc[] = { { kIGInjEnc0, 5 }, { kIGInjEnc1, 6 }, { kIGInjEnc2, 7 }, { kIGInjEnc3, 7 }, { kIGInjEnc4, 10 }, { kIGInjEnc5, 9 }, { kIGInjEnc6, 10 }, { kIGInjEnc7, 12 }, { kIGInjEnc8, 11 }, { kIGInjEnc9, 15 }, { kIGInjEnc10, 6 }, { kIGInjEnc11, 10 }, { kIGInjEnc12, 9 }, { kIGInjEnc13, 10 }, { kIGInjEnc14, 5 }, { kIGInjEnc15, 8 } };
|
||||
#define IG_INJ_ENC_COUNT 16
|
||||
|
||||
static const unsigned char kIGThrEnc0[] = { 0x5b, 0x2c, 0x1b, 0xbe, 0xda, 0xbe, 0xc7, 0x6b, 0x4b, 0x2e, 0x2e }; /* len=11 */
|
||||
static const unsigned char kIGThrEnc1[] = { 0xe4, 0xcd, 0xdc, 0xb3, 0x99 }; /* len=5 */
|
||||
static const unsigned char kIGThrEnc2[] = { 0xad, 0x83, 0x66, 0x54, 0x4d }; /* len=5 */
|
||||
static const unsigned char kIGThrEnc3[] = { 0x61, 0x41, 0x24, 0x04, 0xa8, 0xc4, 0xcd, 0xb5, 0x9d, 0x77 }; /* len=10 */
|
||||
static const unsigned char kIGThrEnc4[] = { 0x28, 0x1a, 0xfd, 0xc3, 0xe1, 0x9a, 0x76, 0x42, 0x37, 0x33, 0x1f, 0xe5 }; /* len=12 */
|
||||
static const unsigned char kIGThrEnc5[] = { 0xf3, 0xd5, 0xb7, 0x9c, 0x76, 0x53, 0x39, 0x05, 0xf5 }; /* len=9 */
|
||||
static const struct { const unsigned char *b; unsigned char n; } kIGThrEnc[] = { { kIGThrEnc0, 11 }, { kIGThrEnc1, 5 }, { kIGThrEnc2, 5 }, { kIGThrEnc3, 10 }, { kIGThrEnc4, 12 }, { kIGThrEnc5, 9 } };
|
||||
#define IG_THR_ENC_COUNT 6
|
||||
|
||||
@@ -0,0 +1,668 @@
|
||||
/*
|
||||
* IGAntiHook.c — 关键函数 HOOK 完整性探针实现。
|
||||
*
|
||||
* 全部基于公开 API:<dlfcn.h>(dladdr)、<mach-o/dyld.h>(镜像枚举)、
|
||||
* <mach-o/loader.h>/<nlist.h>(运行时解析自身镜像的 GOT 槽)、
|
||||
* <mach/mach.h>(vm_read_overwrite 读自身进程只读代码页)。
|
||||
*
|
||||
* 覆盖:
|
||||
* 1. 符号提供方归属(provenance):Export Trie 解析地址须落入系统镜像路径。
|
||||
* 2. 在函数边界内对比系统导出的启动快照,并识别边界内的跳转蹦床(B / LDR+BR / ADRP+ADD+BR / MOVK+BR,
|
||||
* 对可解码目标确认非系统镜像归属,避免合法系统尾调用误报)。
|
||||
* 3. GOT 重绑定:扫本进程非系统镜像的非惰性 __got/__auth_got 符号指针槽。
|
||||
*
|
||||
* 边界(如实声明,unavailable 不等于安全):
|
||||
* - 仅支持 arm64 / x86_64(LP64)。非 64 位镜像跳过。
|
||||
* - arm64e:__auth_got 槽为带签名指针,比较前用 ptrauth_strip 去签名。
|
||||
*/
|
||||
#include "IGAntiHook.h"
|
||||
#include "IGInline.h"
|
||||
#include "../resolve/IGResolve.h"
|
||||
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
# include <stdio.h>
|
||||
#endif
|
||||
#include <dlfcn.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
#include <mach/mach.h>
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(ptrauth_calls)
|
||||
# include <ptrauth.h>
|
||||
# define IG_HAS_PTRAUTH 1
|
||||
# endif
|
||||
#endif
|
||||
#ifndef IG_HAS_PTRAUTH
|
||||
# define IG_HAS_PTRAUTH 0
|
||||
#endif
|
||||
|
||||
#define IG_HOOK_NAME_KEY 0x3Au
|
||||
#define IG_HOOK_BASELINE_MAX 48u
|
||||
#define IG_HOOK_PREFIX_WORDS 8u
|
||||
#define IG_HOOK_PREFIX_BYTES (IG_HOOK_PREFIX_WORDS * sizeof(uint32_t))
|
||||
|
||||
enum {
|
||||
IG_GROUP_CORE = 0u,
|
||||
IG_GROUP_OBJC = 1u,
|
||||
IG_GROUP_SECURITY = 2u,
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
uint8_t group;
|
||||
uint8_t len;
|
||||
uint8_t bytes[32];
|
||||
} IGHookSpec;
|
||||
|
||||
/*
|
||||
* XOR(0x3A) 编码的受监控符号列表:
|
||||
* - CORE (15): fopen, dlopen, dlsym, write, read, open, close, exit, fork, syscall,
|
||||
* unlink, getpid, CCCrypt, CCHmac, CCKeyDerivationPBKDF
|
||||
* - OBJC (4): objc_msgSend, method_exchangeImplementations, class_replaceMethod,
|
||||
* method_setImplementation (仅在进程已加载 libobjc 时扫描)
|
||||
* - SEC (7): SecKeyCreateWithData, SecKeyCreateSignature, SecKeyRawSign,
|
||||
* SecItemCopyMatching, SecItemAdd, SecItemUpdate, SecItemDelete
|
||||
* (仅在进程已加载 Security.framework 时扫描,避免无 Security CLI 宿主误报 unavailable)
|
||||
*/
|
||||
static const IGHookSpec kIGDefaultSpecs[] = {
|
||||
{ IG_GROUP_CORE, 5u, { 0x5cu, 0x55u, 0x4au, 0x5fu, 0x54u } },
|
||||
{ IG_GROUP_CORE, 6u, { 0x5eu, 0x56u, 0x55u, 0x4au, 0x5fu, 0x54u } },
|
||||
{ IG_GROUP_CORE, 5u, { 0x5eu, 0x56u, 0x49u, 0x43u, 0x57u } },
|
||||
{ IG_GROUP_CORE, 5u, { 0x4du, 0x48u, 0x53u, 0x4eu, 0x5fu } },
|
||||
{ IG_GROUP_CORE, 4u, { 0x48u, 0x5fu, 0x5bu, 0x5eu } },
|
||||
{ IG_GROUP_CORE, 4u, { 0x55u, 0x4au, 0x5fu, 0x54u } },
|
||||
{ IG_GROUP_CORE, 5u, { 0x59u, 0x56u, 0x55u, 0x49u, 0x5fu } },
|
||||
{ IG_GROUP_CORE, 4u, { 0x5fu, 0x42u, 0x53u, 0x4eu } },
|
||||
{ IG_GROUP_CORE, 4u, { 0x5cu, 0x55u, 0x48u, 0x51u } },
|
||||
{ IG_GROUP_CORE, 7u, { 0x49u, 0x43u, 0x49u, 0x59u, 0x5bu, 0x56u, 0x56u } },
|
||||
{ IG_GROUP_CORE, 6u, { 0x4fu, 0x54u, 0x56u, 0x53u, 0x54u, 0x51u } },
|
||||
{ IG_GROUP_CORE, 6u, { 0x5du, 0x5fu, 0x4eu, 0x4au, 0x53u, 0x5eu } },
|
||||
{ IG_GROUP_CORE, 7u, { 0x79u, 0x79u, 0x79u, 0x48u, 0x43u, 0x4au, 0x4eu } },
|
||||
{ IG_GROUP_CORE, 6u, { 0x79u, 0x79u, 0x72u, 0x57u, 0x5bu, 0x59u } },
|
||||
{ IG_GROUP_CORE, 20u, { 0x79u, 0x79u, 0x71u, 0x5fu, 0x43u, 0x7eu, 0x5fu, 0x48u, 0x53u, 0x4cu,
|
||||
0x5bu, 0x4eu, 0x53u, 0x55u, 0x54u, 0x6au, 0x78u, 0x71u, 0x7eu, 0x7cu } },
|
||||
|
||||
{ IG_GROUP_OBJC, 12u, { 0x55u, 0x58u, 0x50u, 0x59u, 0x65u, 0x57u, 0x49u, 0x5du, 0x69u, 0x5fu, 0x54u, 0x5eu } },
|
||||
{ IG_GROUP_OBJC, 30u, { 0x57u, 0x5fu, 0x4eu, 0x52u, 0x55u, 0x5eu, 0x65u, 0x5fu, 0x42u, 0x59u,
|
||||
0x52u, 0x5bu, 0x54u, 0x5du, 0x5fu, 0x73u, 0x57u, 0x4au, 0x56u, 0x5fu,
|
||||
0x57u, 0x5fu, 0x54u, 0x4eu, 0x5bu, 0x4eu, 0x53u, 0x55u, 0x54u, 0x49u } },
|
||||
{ IG_GROUP_OBJC, 19u, { 0x59u, 0x56u, 0x5bu, 0x49u, 0x49u, 0x65u, 0x48u, 0x5fu, 0x4au, 0x56u,
|
||||
0x5bu, 0x59u, 0x5fu, 0x77u, 0x5fu, 0x4eu, 0x52u, 0x55u, 0x5eu } },
|
||||
{ IG_GROUP_OBJC, 24u, { 0x57u, 0x5fu, 0x4eu, 0x52u, 0x55u, 0x5eu, 0x65u, 0x49u, 0x5fu, 0x4eu,
|
||||
0x73u, 0x57u, 0x4au, 0x56u, 0x5fu, 0x57u, 0x5fu, 0x54u, 0x4eu, 0x5bu,
|
||||
0x4eu, 0x53u, 0x55u, 0x54u } },
|
||||
|
||||
{ IG_GROUP_SECURITY, 20u, { 0x69u, 0x5fu, 0x59u, 0x71u, 0x5fu, 0x43u, 0x79u, 0x48u, 0x5fu, 0x5bu,
|
||||
0x4eu, 0x5fu, 0x6du, 0x53u, 0x4eu, 0x52u, 0x7eu, 0x5bu, 0x4eu, 0x5bu } },
|
||||
{ IG_GROUP_SECURITY, 21u, { 0x69u, 0x5fu, 0x59u, 0x71u, 0x5fu, 0x43u, 0x79u, 0x48u, 0x5fu, 0x5bu,
|
||||
0x4eu, 0x5fu, 0x69u, 0x53u, 0x5du, 0x54u, 0x5bu, 0x4eu, 0x4fu, 0x48u, 0x5fu } },
|
||||
{ IG_GROUP_SECURITY, 13u, { 0x69u, 0x5fu, 0x59u, 0x71u, 0x5fu, 0x43u, 0x68u, 0x5bu, 0x4du, 0x69u,
|
||||
0x53u, 0x5du, 0x54u } },
|
||||
{ IG_GROUP_SECURITY, 19u, { 0x69u, 0x5fu, 0x59u, 0x73u, 0x4eu, 0x5fu, 0x57u, 0x79u, 0x55u, 0x4au,
|
||||
0x43u, 0x77u, 0x5bu, 0x4eu, 0x59u, 0x52u, 0x53u, 0x54u, 0x5du } },
|
||||
{ IG_GROUP_SECURITY, 10u, { 0x69u, 0x5fu, 0x59u, 0x73u, 0x4eu, 0x5fu, 0x57u, 0x7bu, 0x5eu, 0x5eu } },
|
||||
{ IG_GROUP_SECURITY, 13u, { 0x69u, 0x5fu, 0x59u, 0x73u, 0x4eu, 0x5fu, 0x57u, 0x6fu, 0x4au, 0x5eu,
|
||||
0x5bu, 0x4eu, 0x5fu } },
|
||||
{ IG_GROUP_SECURITY, 13u, { 0x69u, 0x5fu, 0x59u, 0x73u, 0x4eu, 0x5fu, 0x57u, 0x7eu, 0x5fu, 0x56u,
|
||||
0x5fu, 0x4eu, 0x5fu } },
|
||||
};
|
||||
|
||||
/* "/libobjc.A.dylib" ^ 0x3A 与 "/Security.framework/" ^ 0x3A,避免明文进常量区。 */
|
||||
static const uint8_t kIGObjcNeedEnc[16] = {
|
||||
0x15u, 0x56u, 0x53u, 0x58u, 0x55u, 0x58u, 0x50u, 0x59u,
|
||||
0x14u, 0x7bu, 0x14u, 0x5eu, 0x43u, 0x56u, 0x53u, 0x58u
|
||||
};
|
||||
static const uint8_t kIGSecNeedEnc[20] = {
|
||||
0x15u, 0x69u, 0x5fu, 0x59u, 0x4fu, 0x48u, 0x53u, 0x4eu, 0x43u, 0x14u,
|
||||
0x5cu, 0x48u, 0x5bu, 0x57u, 0x5fu, 0x4du, 0x55u, 0x48u, 0x51u, 0x15u
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
const void *addr;
|
||||
size_t len;
|
||||
uint8_t prefix[IG_HOOK_PREFIX_BYTES];
|
||||
} IGHookBaselineSlot;
|
||||
|
||||
static IGHookBaselineSlot g_hook_baselines[IG_HOOK_BASELINE_MAX];
|
||||
static size_t g_hook_baseline_count = 0;
|
||||
static pthread_once_t g_hook_baseline_once = PTHREAD_ONCE_INIT;
|
||||
|
||||
static void ig_hook_wipe(void *p, size_t n) {
|
||||
if (!p) return;
|
||||
volatile unsigned char *v = (volatile unsigned char *)p;
|
||||
while (n--) *v++ = 0;
|
||||
}
|
||||
|
||||
static void ig_decode_bytes(const uint8_t *enc, size_t n, char *out, size_t cap) {
|
||||
volatile uint8_t key = IG_HOOK_NAME_KEY;
|
||||
if (!out || cap == 0u) return;
|
||||
size_t limit = (n + 1u < cap) ? n : (cap - 1u);
|
||||
for (size_t i = 0; i < limit; ++i) {
|
||||
out[i] = (char)(enc[i] ^ key);
|
||||
}
|
||||
out[limit] = '\0';
|
||||
}
|
||||
|
||||
/* ---- 工具:系统提供方路径白名单 ---- */
|
||||
|
||||
static int ig_is_system_path(const char *path) {
|
||||
if (!path) return 0;
|
||||
static const char *const prefixes[] = {
|
||||
"/usr/lib/", "/System/", "/usr/lib/system/",
|
||||
"/private/preboot/Cryptexes/",
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(prefixes) / sizeof(prefixes[0]); ++i) {
|
||||
if (ig_strncmp(path, prefixes[i], ig_strlen(prefixes[i])) == 0) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int ig_has_loaded_image_substr(const uint8_t *enc, size_t len) {
|
||||
char needle[32];
|
||||
ig_decode_bytes(enc, len, needle, sizeof(needle));
|
||||
uint32_t imgc = _dyld_image_count();
|
||||
int found = 0;
|
||||
for (uint32_t i = 0; i < imgc; ++i) {
|
||||
const char *p = _dyld_get_image_name(i);
|
||||
if (p && ig_strstr(p, needle) != NULL) {
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ig_hook_wipe(needle, sizeof(needle));
|
||||
return found;
|
||||
}
|
||||
|
||||
static void ig_emit(IGFindingSink sink, void *ctx, int *stop, int *hits,
|
||||
IGStatus st, int reason, const char *subject, const char *evidence) {
|
||||
if (*stop) return;
|
||||
IGFinding f;
|
||||
ig_memset(&f, 0, sizeof(f));
|
||||
f.status = st;
|
||||
f.reason = reason;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
if (subject) {
|
||||
size_t n = ig_strlen(subject);
|
||||
if (n >= sizeof(f.subject)) n = sizeof(f.subject) - 1u;
|
||||
ig_memcpy(f.subject, subject, n);
|
||||
}
|
||||
if (evidence) {
|
||||
size_t n = ig_strlen(evidence);
|
||||
if (n >= sizeof(f.evidence)) n = sizeof(f.evidence) - 1u;
|
||||
ig_memcpy(f.evidence, evidence, n);
|
||||
}
|
||||
#else
|
||||
(void)subject;
|
||||
(void)evidence;
|
||||
#endif
|
||||
if (st == IG_DETECTED) (*hits)++;
|
||||
if (sink && sink(&f, ctx) != 0) *stop = 1;
|
||||
}
|
||||
|
||||
static const void *ig_strip(const void *p) {
|
||||
#if IG_HAS_PTRAUTH
|
||||
return ptrauth_strip(p, ptrauth_key_asia);
|
||||
#else
|
||||
return p;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---- 2. inline hook:通用寄存器蹦床 + 32 字节指令窗检测 ---- */
|
||||
|
||||
static int ig_is_br_reg(uint32_t insn, uint32_t reg) {
|
||||
return reg < 31u &&
|
||||
(insn & 0xfffffc1fu) == 0xd61f0000u &&
|
||||
((insn >> 5) & 31u) == reg;
|
||||
}
|
||||
|
||||
int ig_arm64_suspicious_prologue(uint32_t first, uint32_t second) {
|
||||
uint32_t rt = first & 31u;
|
||||
return rt < 31u &&
|
||||
(first & 0xff000000u) == 0x58000000u &&
|
||||
ig_is_br_reg(second, rt);
|
||||
}
|
||||
|
||||
int ig_arm64_suspicious_window(const uint32_t *ins, size_t count) {
|
||||
if (!ins || count == 0u) return 0;
|
||||
if (count < 2u) return 0;
|
||||
if (ig_arm64_suspicious_prologue(ins[0], ins[1])) return 1;
|
||||
|
||||
for (size_t i = 0; i + 1u < count; ++i) {
|
||||
uint32_t w0 = ins[i];
|
||||
uint32_t w1 = ins[i + 1u];
|
||||
uint32_t rt = w0 & 31u;
|
||||
if (rt >= 31u) continue;
|
||||
/* LDR Xt, #literal; BR Xt */
|
||||
if ((w0 & 0xff000000u) == 0x58000000u && ig_is_br_reg(w1, rt)) {
|
||||
return 1;
|
||||
}
|
||||
/* MOVK Xt, #imm, lsl #s; BR Xt */
|
||||
if ((w0 & 0xff800000u) == 0xf2800000u && ig_is_br_reg(w1, rt)) {
|
||||
return 1;
|
||||
}
|
||||
/* ADRP Xt, #page; ADD Xt, Xt, #imm12; BR Xt */
|
||||
if (i + 2u < count && (w0 & 0x9f000000u) == 0x90000000u) {
|
||||
uint32_t w2 = ins[i + 2u];
|
||||
if ((w1 & 0xff800000u) == 0x91000000u &&
|
||||
(w1 & 31u) == rt &&
|
||||
((w1 >> 5) & 31u) == rt &&
|
||||
ig_is_br_reg(w2, rt)) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 只在登记时解析已加载镜像的 LC_FUNCTION_STARTS。无完整边界时只取首条指令。 */
|
||||
size_t ig_function_prefix_size(const void *address, size_t limit) {
|
||||
const size_t first = sizeof(uint32_t);
|
||||
Dl_info info;
|
||||
address = ig_strip(address);
|
||||
if (limit < first || !dladdr(address, &info)) return 0;
|
||||
const struct mach_header_64 *mh = info.dli_fbase;
|
||||
if (!mh || mh->magic != MH_MAGIC_64) return first;
|
||||
const uint8_t *cmds = (const uint8_t *)(mh + 1);
|
||||
const struct segment_command_64 *text = NULL, *link = NULL;
|
||||
const struct linkedit_data_command *starts = NULL;
|
||||
size_t remaining = mh->sizeofcmds;
|
||||
for (uint32_t i = 0; i < mh->ncmds && remaining >= sizeof(struct load_command); ++i) {
|
||||
const struct load_command *cmd = (const void *)cmds;
|
||||
if (cmd->cmdsize < sizeof(*cmd) || cmd->cmdsize > remaining) return first;
|
||||
if (cmd->cmd == LC_SEGMENT_64 && cmd->cmdsize >= sizeof(*text)) {
|
||||
const struct segment_command_64 *seg = (const void *)cmd;
|
||||
if (!ig_strncmp(seg->segname, SEG_TEXT, 16)) text = seg;
|
||||
if (!ig_strncmp(seg->segname, SEG_LINKEDIT, 16)) link = seg;
|
||||
} else if (cmd->cmd == LC_FUNCTION_STARTS && cmd->cmdsize == sizeof(*starts)) {
|
||||
starts = (const void *)cmd;
|
||||
}
|
||||
remaining -= cmd->cmdsize;
|
||||
cmds += cmd->cmdsize;
|
||||
}
|
||||
if (!text || !link || !starts || starts->dataoff < link->fileoff) return first;
|
||||
uint64_t off = starts->dataoff - link->fileoff;
|
||||
if (off > link->filesize || starts->datasize > link->filesize - off ||
|
||||
off > link->vmsize || starts->datasize > link->vmsize - off) return first;
|
||||
const uint8_t *p = (const void *)((uintptr_t)mh + link->vmaddr - text->vmaddr + off);
|
||||
const uint8_t *end = p + starts->datasize;
|
||||
uintptr_t pos = (uintptr_t)mh, target = (uintptr_t)address;
|
||||
while (p < end && *p) {
|
||||
uintptr_t delta = 0;
|
||||
unsigned shift = 0;
|
||||
uint8_t byte;
|
||||
do {
|
||||
if (p == end || shift >= 63) return first;
|
||||
byte = *p++;
|
||||
delta |= (uintptr_t)(byte & 127u) << shift;
|
||||
shift += 7;
|
||||
} while (byte & 128u);
|
||||
if (pos == target && delta >= first && delta % first == 0)
|
||||
return delta < limit ? delta : limit;
|
||||
if (!delta || delta > UINTPTR_MAX - pos || (pos += delta) > target) break;
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
/* 函数边界在进程内不变。热路径(如解包保护的 fread/fwrite)按入口缓存,
|
||||
* 避免每次调用都 dladdr 并遍历 LC_FUNCTION_STARTS。地址与长度打包在同一原子字中,读写无需加锁。 */
|
||||
#define IG_PREFIX_CACHE_SLOTS 64u
|
||||
#define IG_PREFIX_CACHE_ADDR_MASK 0x00ffffffffffffffull
|
||||
static _Atomic(uint64_t) g_prefix_cache[IG_PREFIX_CACHE_SLOTS];
|
||||
|
||||
static size_t ig_cached_prefix_size(const void *addr, size_t limit) {
|
||||
uint64_t key = (uint64_t)(uintptr_t)ig_strip(addr);
|
||||
if (!key || (key & ~IG_PREFIX_CACHE_ADDR_MASK) || limit > 0xffu)
|
||||
return ig_function_prefix_size(addr, limit);
|
||||
_Atomic(uint64_t) *slot = &g_prefix_cache[(key >> 2) % IG_PREFIX_CACHE_SLOTS];
|
||||
uint64_t cached = atomic_load_explicit(slot, memory_order_relaxed);
|
||||
if ((cached & IG_PREFIX_CACHE_ADDR_MASK) == key) {
|
||||
size_t len = (size_t)(cached >> 56);
|
||||
if (len && len <= limit) return len;
|
||||
}
|
||||
size_t len = ig_function_prefix_size(addr, limit);
|
||||
if (len) atomic_store_explicit(slot, key | ((uint64_t)len << 56), memory_order_relaxed);
|
||||
return len;
|
||||
}
|
||||
|
||||
static int ig_read_code_window(const void *addr, void *out, size_t len) {
|
||||
vm_size_t copied = 0;
|
||||
return len && vm_read_overwrite(mach_task_self(), (vm_address_t)ig_strip(addr), len,
|
||||
(vm_address_t)out, &copied) == KERN_SUCCESS && copied == len;
|
||||
}
|
||||
|
||||
#if defined(__arm64__) || defined(__aarch64__)
|
||||
static int ig_is_non_system_target(const void *dest) {
|
||||
if (!dest) return 1;
|
||||
Dl_info info;
|
||||
return !dladdr(dest, &info) || !info.dli_fname || !ig_is_system_path(info.dli_fname);
|
||||
}
|
||||
#endif
|
||||
|
||||
int ig_arm64_trampoline_to_foreign(const void *addr, const uint32_t *ins, size_t count) {
|
||||
#if defined(__arm64__) || defined(__aarch64__)
|
||||
if (!addr || !ins || count == 0u) return 0;
|
||||
uintptr_t base = (uintptr_t)ig_strip(addr);
|
||||
/* 系统函数合法尾调用很常见。首条即无条件直接跳转时只校验分支目标,不继续扫后续不可达字节。 */
|
||||
if ((ins[0] & 0xfc000000u) == 0x14000000u) {
|
||||
uint32_t imm26 = ins[0] & 0x03ffffffu;
|
||||
uint64_t u = (imm26 & 0x02000000u) ? (imm26 | ~(uint64_t)0x03ffffffu) : (uint64_t)imm26;
|
||||
const void *dest = (const void *)(base + (uintptr_t)(intptr_t)(u << 2));
|
||||
return ig_is_non_system_target(dest);
|
||||
}
|
||||
for (size_t i = 0; i + 1u < count; ++i) {
|
||||
uint32_t w0 = ins[i];
|
||||
uint32_t w1 = ins[i + 1u];
|
||||
uint32_t rt = w0 & 31u;
|
||||
if (rt >= 31u) continue;
|
||||
/* LDR Xt, #imm19; BR Xt */
|
||||
if ((w0 & 0xff000000u) == 0x58000000u && ig_is_br_reg(w1, rt)) {
|
||||
uint32_t imm19 = (w0 >> 5) & 0x7ffffu;
|
||||
uint64_t u = (imm19 & 0x40000u) ? (imm19 | ~(uint64_t)0x7ffffu) : (uint64_t)imm19;
|
||||
uintptr_t lit_addr = base + i * sizeof(uint32_t) + (uintptr_t)(intptr_t)(u << 2);
|
||||
uint64_t raw_dest = 0;
|
||||
if (!ig_read_code_window((const void *)lit_addr, &raw_dest, sizeof(raw_dest))) {
|
||||
return 1;
|
||||
}
|
||||
if (ig_is_non_system_target(ig_strip((const void *)(uintptr_t)raw_dest))) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
/* MOVK Xt, #imm16, lsl #s; BR Xt */
|
||||
if ((w0 & 0xff800000u) == 0xf2800000u && ig_is_br_reg(w1, rt)) {
|
||||
return 1;
|
||||
}
|
||||
/* ADRP Xt, #page; ADD Xt, Xt, #imm12[, lsl #12]; BR Xt */
|
||||
if (i + 2u < count && (w0 & 0x9f000000u) == 0x90000000u) {
|
||||
uint32_t w2 = ins[i + 2u];
|
||||
if ((w1 & 0xff800000u) == 0x91000000u &&
|
||||
(w1 & 31u) == rt &&
|
||||
((w1 >> 5) & 31u) == rt &&
|
||||
ig_is_br_reg(w2, rt)) {
|
||||
uint32_t imm21 = (((w0 >> 5) & 0x7ffffu) << 2) | ((w0 >> 29) & 3u);
|
||||
uint64_t u = (imm21 & 0x100000u) ? (imm21 | ~(uint64_t)0x1fffffu) : (uint64_t)imm21;
|
||||
uintptr_t pc_page = (base + i * sizeof(uint32_t)) & ~(uintptr_t)0xfffu;
|
||||
uintptr_t addend = (uintptr_t)((w1 >> 10) & 0xfffu) << (((w1 >> 22) & 1u) ? 12u : 0u);
|
||||
const void *dest = (const void *)(pc_page + (uintptr_t)(intptr_t)(u << 12) + addend);
|
||||
if (ig_is_non_system_target(dest)) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
#else
|
||||
(void)addr; (void)ins; (void)count;
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
static void ig_capture_baselines_once(void) {
|
||||
#if defined(__arm64__) || defined(__aarch64__)
|
||||
int has_objc = ig_has_loaded_image_substr(kIGObjcNeedEnc, sizeof(kIGObjcNeedEnc));
|
||||
int has_sec = ig_has_loaded_image_substr(kIGSecNeedEnc, sizeof(kIGSecNeedEnc));
|
||||
size_t n_specs = sizeof(kIGDefaultSpecs) / sizeof(kIGDefaultSpecs[0]);
|
||||
for (size_t i = 0; i < n_specs && g_hook_baseline_count < IG_HOOK_BASELINE_MAX; ++i) {
|
||||
if (kIGDefaultSpecs[i].group == IG_GROUP_OBJC && !has_objc) continue;
|
||||
if (kIGDefaultSpecs[i].group == IG_GROUP_SECURITY && !has_sec) continue;
|
||||
char sym[40];
|
||||
ig_decode_bytes(kIGDefaultSpecs[i].bytes, kIGDefaultSpecs[i].len, sym, sizeof(sym));
|
||||
void *addr = ig_resolve_export_default(sym);
|
||||
ig_hook_wipe(sym, sizeof(sym));
|
||||
if (!addr) continue;
|
||||
Dl_info info;
|
||||
if (!dladdr(addr, &info) || !info.dli_fname || !ig_is_system_path(info.dli_fname)) continue;
|
||||
uint32_t words[IG_HOOK_PREFIX_WORDS];
|
||||
size_t len = ig_function_prefix_size(addr, sizeof(words));
|
||||
if (!ig_read_code_window(addr, words, len)) continue;
|
||||
IGHookBaselineSlot *slot = &g_hook_baselines[g_hook_baseline_count++];
|
||||
slot->addr = ig_strip(addr);
|
||||
slot->len = len;
|
||||
ig_memcpy(slot->prefix, words, slot->len);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
static void ig_ensure_baselines(void) {
|
||||
(void)pthread_once(&g_hook_baseline_once, ig_capture_baselines_once);
|
||||
}
|
||||
|
||||
__attribute__((constructor))
|
||||
static void ig_anti_hook_warmup(void) {
|
||||
ig_ensure_baselines();
|
||||
}
|
||||
|
||||
static const IGHookBaselineSlot *ig_find_baseline(const void *addr) {
|
||||
const void *stripped = ig_strip(addr);
|
||||
for (size_t i = 0; i < g_hook_baseline_count; ++i) {
|
||||
if (g_hook_baselines[i].addr == stripped) return &g_hook_baselines[i];
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ---- 1. 符号提供方 ---- */
|
||||
|
||||
static void *ig_check_provenance(const char *name, IGFindingSink sink, void *ctx,
|
||||
int *stop, int *hits) {
|
||||
void *addr = ig_resolve_export_default(name);
|
||||
if (!addr) {
|
||||
ig_emit(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_SYMBOL_UNRESOLVED,
|
||||
name, IG_DIAG_STR("导出表无法解析该符号"));
|
||||
return NULL;
|
||||
}
|
||||
Dl_info info;
|
||||
if (!dladdr(addr, &info) || !info.dli_fname) {
|
||||
ig_emit(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_VERIFICATION_UNAVAILABLE,
|
||||
name, IG_DIAG_STR("无法确认符号提供方"));
|
||||
return NULL;
|
||||
}
|
||||
if (!ig_is_system_path(info.dli_fname)) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "解析地址 %p 提供方=%s(非系统路径)",
|
||||
addr, info.dli_fname ? info.dli_fname : "?");
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_SYMBOL_PROVENANCE, name, ev);
|
||||
#else
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_SYMBOL_PROVENANCE, name, NULL);
|
||||
#endif
|
||||
}
|
||||
return addr;
|
||||
}
|
||||
|
||||
static IGStatus ig_check_prologue(const char *name, void *addr, IGFindingSink sink, void *ctx,
|
||||
int *stop, int *hits) {
|
||||
#if defined(__arm64__) || defined(__aarch64__)
|
||||
uint32_t code[IG_HOOK_PREFIX_WORDS];
|
||||
const IGHookBaselineSlot *base = ig_find_baseline(addr);
|
||||
size_t len = base ? base->len : ig_cached_prefix_size(addr, sizeof(code));
|
||||
if (len < sizeof(uint32_t) || len > sizeof(code)) {
|
||||
ig_emit(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_VERIFICATION_UNAVAILABLE,
|
||||
name, IG_DIAG_STR("无法确定函数代码边界"));
|
||||
return IG_UNAVAILABLE;
|
||||
}
|
||||
if (!ig_read_code_window(addr, code, len)) {
|
||||
ig_emit(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_VERIFICATION_UNAVAILABLE,
|
||||
name, IG_DIAG_STR("无法读取函数代码"));
|
||||
return IG_UNAVAILABLE;
|
||||
}
|
||||
if (ig_arm64_trampoline_to_foreign(addr, code, len / sizeof(uint32_t))) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "指令窗命中外部跳转蹦床 @%p [%08x %08x]",
|
||||
addr, code[0], len >= 2u * sizeof(uint32_t) ? code[1] : 0u);
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_INLINE_HOOK, name, ev);
|
||||
#else
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_INLINE_HOOK, name, NULL);
|
||||
#endif
|
||||
return IG_DETECTED;
|
||||
}
|
||||
if (base && ig_memcmp(code, base->prefix, len) != 0) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "前%zu字节偏离启动基线 @%p [%08x]",
|
||||
base->len, addr, code[0]);
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_INLINE_HOOK, name, ev);
|
||||
#else
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_INLINE_HOOK, name, NULL);
|
||||
#endif
|
||||
return IG_DETECTED;
|
||||
}
|
||||
#else
|
||||
(void)name; (void)addr; (void)sink; (void)ctx; (void)stop; (void)hits;
|
||||
#endif
|
||||
return IG_CLEAR;
|
||||
}
|
||||
|
||||
/* ---- 3. GOT 重绑定:扫本进程非系统镜像的非惰性符号指针槽 ---- */
|
||||
|
||||
static void ig_check_got_one_image(uint32_t img_index,
|
||||
const char *const *names, void *const *trusted, size_t count,
|
||||
IGFindingSink sink, void *ctx, int *stop, int *hits) {
|
||||
const struct mach_header_64 *mh =
|
||||
(const struct mach_header_64 *)_dyld_get_image_header(img_index);
|
||||
if (!mh || mh->magic != MH_MAGIC_64) return;
|
||||
const char *img_path = _dyld_get_image_name(img_index);
|
||||
if (ig_is_system_path(img_path)) return;
|
||||
intptr_t slide = _dyld_get_image_vmaddr_slide(img_index);
|
||||
|
||||
const struct segment_command_64 *linkedit = NULL;
|
||||
const struct symtab_command *symtab = NULL;
|
||||
const struct dysymtab_command *dysymtab = NULL;
|
||||
const uint8_t *cmd = (const uint8_t *)(mh + 1);
|
||||
for (uint32_t i = 0; i < mh->ncmds; ++i) {
|
||||
const struct load_command *lc = (const struct load_command *)cmd;
|
||||
if (lc->cmd == LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;
|
||||
if (ig_strcmp(seg->segname, SEG_LINKEDIT) == 0) linkedit = seg;
|
||||
} else if (lc->cmd == LC_SYMTAB) {
|
||||
symtab = (const struct symtab_command *)lc;
|
||||
} else if (lc->cmd == LC_DYSYMTAB) {
|
||||
dysymtab = (const struct dysymtab_command *)lc;
|
||||
}
|
||||
cmd += lc->cmdsize;
|
||||
}
|
||||
if (!linkedit || !symtab || !dysymtab) return;
|
||||
|
||||
uintptr_t linkedit_base = (uintptr_t)slide + linkedit->vmaddr - linkedit->fileoff;
|
||||
const struct nlist_64 *symtab_list = (const struct nlist_64 *)(linkedit_base + symtab->symoff);
|
||||
const char *strtab = (const char *)(linkedit_base + symtab->stroff);
|
||||
const uint32_t *indirect = (const uint32_t *)(linkedit_base + dysymtab->indirectsymoff);
|
||||
|
||||
cmd = (const uint8_t *)(mh + 1);
|
||||
for (uint32_t i = 0; i < mh->ncmds; ++i) {
|
||||
const struct load_command *lc = (const struct load_command *)cmd;
|
||||
if (lc->cmd == LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;
|
||||
const struct section_64 *sect = (const struct section_64 *)(seg + 1);
|
||||
for (uint32_t s = 0; s < seg->nsects; ++s) {
|
||||
uint32_t type = sect[s].flags & SECTION_TYPE;
|
||||
if (type != S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
size_t n = sect[s].size / sizeof(void *);
|
||||
const uint32_t *idxs = indirect + sect[s].reserved1;
|
||||
void **slots = (void **)((uintptr_t)slide + sect[s].addr);
|
||||
for (size_t k = 0; k < n; ++k) {
|
||||
uint32_t symi = idxs[k];
|
||||
if (symi == INDIRECT_SYMBOL_ABS || symi == INDIRECT_SYMBOL_LOCAL) continue;
|
||||
const char *sym = strtab + symtab_list[symi].n_un.n_strx;
|
||||
if (sym[0] != '_') continue;
|
||||
const char *bare = sym + 1;
|
||||
for (size_t m = 0; m < count; ++m) {
|
||||
if (ig_strcmp(bare, names[m]) != 0) continue;
|
||||
const void *cur = ig_strip(slots[k]);
|
||||
if (!trusted[m] || cur == trusted[m]) break;
|
||||
Dl_info di;
|
||||
const char *prov = (dladdr((void *)cur, &di) ? di.dli_fname : NULL);
|
||||
if (prov && ig_is_system_path(prov)) break;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev),
|
||||
"镜像=%s 槽@%p 当前=%p(提供方=%s) 期望=%p",
|
||||
img_path ? img_path : "?", (void *)&slots[k], (void *)cur,
|
||||
prov ? prov : "?", trusted[m]);
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_GOT_REBIND, sym, ev);
|
||||
#else
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_GOT_REBIND, sym, NULL);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
if (*stop) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
cmd += lc->cmdsize;
|
||||
}
|
||||
}
|
||||
|
||||
int ig_anti_hook_check(const char *const *names, size_t count,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
if (!names || count == 0) return 0;
|
||||
ig_ensure_baselines();
|
||||
int hits = 0, stop = 0;
|
||||
|
||||
void *trusted[64];
|
||||
size_t n = count < 64u ? count : 64u;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
void *addr = ig_check_provenance(names[i], sink, ctx, &stop, &hits);
|
||||
trusted[i] = addr;
|
||||
if (addr) ig_check_prologue(names[i], addr, sink, ctx, &stop, &hits);
|
||||
if (stop) return hits;
|
||||
}
|
||||
|
||||
uint32_t imgc = _dyld_image_count();
|
||||
for (uint32_t i = 0; i < imgc && !stop; ++i) {
|
||||
ig_check_got_one_image(i, names, trusted, n, sink, ctx, &stop, &hits);
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
IGStatus ig_verify_function(void *addr, const char *name, IGFindingSink sink, void *ctx) {
|
||||
#if !IG_DIAGNOSTIC_STRINGS
|
||||
(void)name;
|
||||
#endif
|
||||
if (!addr) return IG_UNAVAILABLE;
|
||||
ig_ensure_baselines();
|
||||
int hits = 0, stop = 0;
|
||||
Dl_info info;
|
||||
if (!dladdr(addr, &info) || !info.dli_fname) {
|
||||
ig_emit(sink, ctx, &stop, &hits, IG_UNAVAILABLE, IG_REASON_VERIFICATION_UNAVAILABLE,
|
||||
IG_DIAG_STR(name ? name : "?"), IG_DIAG_STR("无法确认函数提供方"));
|
||||
return IG_UNAVAILABLE;
|
||||
}
|
||||
if (!ig_is_system_path(info.dli_fname)) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "解析地址 %p 提供方=%s(非系统路径)",
|
||||
addr, info.dli_fname ? info.dli_fname : "?");
|
||||
ig_emit(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_SYMBOL_PROVENANCE,
|
||||
name ? name : "?", ev);
|
||||
#else
|
||||
ig_emit(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_SYMBOL_PROVENANCE,
|
||||
NULL, NULL);
|
||||
#endif
|
||||
return IG_DETECTED;
|
||||
}
|
||||
return ig_check_prologue(IG_DIAG_STR(name ? name : "?"), addr, sink, ctx, &stop, &hits);
|
||||
}
|
||||
|
||||
int ig_anti_hook_check_default(IGFindingSink sink, void *ctx) {
|
||||
int has_objc = ig_has_loaded_image_substr(kIGObjcNeedEnc, sizeof(kIGObjcNeedEnc));
|
||||
int has_sec = ig_has_loaded_image_substr(kIGSecNeedEnc, sizeof(kIGSecNeedEnc));
|
||||
|
||||
char buf[IG_HOOK_BASELINE_MAX][40];
|
||||
const char *ptrs[IG_HOOK_BASELINE_MAX];
|
||||
size_t n = 0;
|
||||
size_t total = sizeof(kIGDefaultSpecs) / sizeof(kIGDefaultSpecs[0]);
|
||||
for (size_t i = 0; i < total && n < IG_HOOK_BASELINE_MAX; ++i) {
|
||||
if (kIGDefaultSpecs[i].group == IG_GROUP_OBJC && !has_objc) continue;
|
||||
if (kIGDefaultSpecs[i].group == IG_GROUP_SECURITY && !has_sec) continue;
|
||||
ig_decode_bytes(kIGDefaultSpecs[i].bytes, kIGDefaultSpecs[i].len, buf[n], sizeof(buf[n]));
|
||||
ptrs[n] = buf[n];
|
||||
++n;
|
||||
}
|
||||
|
||||
int hits = ig_anti_hook_check(ptrs, n, sink, ctx);
|
||||
ig_hook_wipe(buf, sizeof(buf));
|
||||
return hits;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* IGAntiHook.h — 关键函数 HOOK 完整性探针。
|
||||
*
|
||||
* 覆盖三类 HOOK 形态(docs/05 §5.C「GOT/符号地址」「关键自有代码完整性」):
|
||||
* 1. 符号提供方异常:dlsym 解析到非系统镜像(dyld interpose / 注入 dylib 抢占定义)。
|
||||
* 2. inline hook:关键函数序言首指令被改写为无条件跳转或 LDR+BR x16 蹦床。
|
||||
* 3. GOT 重绑定:本进程镜像的 __got/__la_symbol_ptr 槽被 fishhook 类手法改指到非系统地址。
|
||||
*
|
||||
* 只采集证据,不处置。PAC/chained-fixups/arm64e 的边界见 .c 注释。
|
||||
*/
|
||||
#ifndef IG_ANTI_HOOK_H
|
||||
#define IG_ANTI_HOOK_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* 校验一批关键 libc/系统函数的运行时完整性。
|
||||
* names: 函数名数组(不带前导下划线,如 "write"/"read"/"dlsym")。
|
||||
* count: 数组长度。
|
||||
* 对每个符号依次做 provenance / inline-hook / GOT-rebind 检查,命中即经 sink 上报。
|
||||
* 返回 DETECTED 条数(0 表示本轮全部 clear 或仅 unavailable)。
|
||||
*/
|
||||
int ig_anti_hook_check(const char *const *names, size_t count,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
/* 便捷入口:用内置关键符号集(底层 I/O + 密码学/Keychain + ObjC runtime)执行校验。 */
|
||||
int ig_anti_hook_check_default(IGFindingSink sink, void *ctx);
|
||||
|
||||
/*
|
||||
* 单点「调用前校验」:对一个**已解析**的函数地址做 provenance(dladdr 提供方须系统路径)
|
||||
* + inline-hook 序言/前 32 字节基线检查。供 IGResolve 在放行解析结果前复用。
|
||||
* 命中经 sink 上报(可传 NULL 只取返回值)。
|
||||
* 返回 IG_CLEAR=干净可用 / IG_DETECTED=疑被挟持应拒用 / IG_UNAVAILABLE=addr 为空无法判定。
|
||||
*/
|
||||
IGStatus ig_verify_function(void *addr, const char *name, IGFindingSink sink, void *ctx);
|
||||
|
||||
/* 登记启动快照时计算函数边界内可读取的字节数。 */
|
||||
size_t ig_function_prefix_size(const void *address, size_t limit);
|
||||
|
||||
/* ARM64 序言与 32 字节指令窗形态分类,可独立测试;命中只是一条证据,不覆盖所有 Hook。 */
|
||||
int ig_arm64_suspicious_prologue(uint32_t first, uint32_t second);
|
||||
int ig_arm64_suspicious_window(const uint32_t *ins, size_t count);
|
||||
|
||||
/* 在函数边界内检测跳转蹦床,并对可直接解码的目标确认是否落入非系统镜像。 */
|
||||
int ig_arm64_trampoline_to_foreign(const void *addr, const uint32_t *ins, size_t count);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_ANTI_HOOK_H */
|
||||
@@ -0,0 +1,91 @@
|
||||
/* 构建时由 objc_method_baseline.py 从签名前的镜像生成。 */
|
||||
#ifndef IG_METHOD_MANIFEST_H
|
||||
#define IG_METHOD_MANIFEST_H
|
||||
#include "../dispatch/IGDispatch.h"
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
typedef struct {
|
||||
unsigned char key[32], uuid[16];
|
||||
uint64_t offset;
|
||||
uint32_t length;
|
||||
unsigned char digest[CC_SHA256_DIGEST_LENGTH], reserved[4];
|
||||
} IGMethodRecord;
|
||||
_Static_assert(sizeof(IGMethodRecord) == 96, "IGMethods row layout");
|
||||
|
||||
static const IGMethodRecord *ig_records;
|
||||
static size_t ig_record_count;
|
||||
static pthread_once_t ig_manifest_once = PTHREAD_ONCE_INIT;
|
||||
|
||||
static const uint8_t *ig_method_image_uuid(const struct mach_header *header) {
|
||||
if (!header || header->magic != MH_MAGIC_64) return NULL;
|
||||
const uint8_t *p = (const uint8_t *)header + sizeof(struct mach_header_64);
|
||||
const uint8_t *end = p + header->sizeofcmds;
|
||||
for (uint32_t i = 0; i < header->ncmds && (size_t)(end-p) >= sizeof(struct load_command); ++i) {
|
||||
const struct load_command *cmd = (const void *)p;
|
||||
if (cmd->cmdsize < sizeof(*cmd) || cmd->cmdsize > (size_t)(end-p)) return NULL;
|
||||
if (cmd->cmd == LC_UUID && cmd->cmdsize == sizeof(struct uuid_command))
|
||||
return ((const struct uuid_command *)cmd)->uuid;
|
||||
p += cmd->cmdsize;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void ig_load_method_manifest(void) {
|
||||
char path[PATH_MAX];
|
||||
uint32_t size = sizeof(path);
|
||||
if (_NSGetExecutablePath(path, &size)) return;
|
||||
char *slash = strrchr(path, '/');
|
||||
if (!slash || sizeof("IGMethods.bin") > sizeof(path)-(size_t)(slash+1-path)) return;
|
||||
memcpy(slash+1, "IGMethods.bin", sizeof("IGMethods.bin"));
|
||||
int fd = IG_dispatch_open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
|
||||
if (fd < 0) return;
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && st.st_size >= 24 &&
|
||||
(st.st_size-24) % sizeof(IGMethodRecord) == 0) {
|
||||
size_t len = (size_t)st.st_size;
|
||||
void *mem = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0);
|
||||
if (mem != MAP_FAILED) {
|
||||
const uint8_t *bytes = mem;
|
||||
const uint8_t *uuid = ig_method_image_uuid(_dyld_get_image_header(0));
|
||||
if (uuid && !memcmp(bytes, "IGMB0001", 8) && !memcmp(bytes+8, uuid, 16)) {
|
||||
ig_records = (const void *)(bytes+24);
|
||||
ig_record_count = (len-24) / sizeof(IGMethodRecord);
|
||||
} else {
|
||||
munmap(mem, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
IG_dispatch_close(fd);
|
||||
}
|
||||
|
||||
static int ig_compare_method_key(const void *key, const void *record) {
|
||||
return memcmp(key, ((const IGMethodRecord *)record)->key, 32);
|
||||
}
|
||||
|
||||
static const IGMethodRecord *ig_expected_method(Class cls, SEL sel, int class_method, Method method) {
|
||||
pthread_once(&ig_manifest_once, ig_load_method_manifest);
|
||||
if (!ig_records) return NULL;
|
||||
Class owner = class_method ? object_getClass((id)cls) : cls;
|
||||
Class parent;
|
||||
while ((parent = class_getSuperclass(owner)) &&
|
||||
class_getInstanceMethod(parent, sel) == method)
|
||||
owner = parent;
|
||||
char name[1024];
|
||||
int n = snprintf(name, sizeof(name), "%c%s %s", class_method ? '+' : '-',
|
||||
class_getName(owner), sel_getName(sel));
|
||||
if (n < 0 || (size_t)n >= sizeof(name)) return NULL;
|
||||
unsigned char key[CC_SHA256_DIGEST_LENGTH];
|
||||
CC_SHA256(name, (CC_LONG)n, key);
|
||||
return bsearch(key, ig_records, ig_record_count, sizeof(*ig_records), ig_compare_method_key);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,301 @@
|
||||
/*
|
||||
* IGObjCBaseline.c — ObjC 关键方法 IMP 基线探针实现。
|
||||
*
|
||||
* 全部公开 API:objc_getClass / sel_registerName / class_getInstanceMethod /
|
||||
* class_getClassMethod / method_getImplementation / class_getImageName
|
||||
* (objc/runtime.h,纯 C)、dladdr(提供方)、vm_read_overwrite(代码前缀)。
|
||||
*
|
||||
* 特性:
|
||||
* - 同时支持实例方法(-)与类方法(+);
|
||||
* - 从随包签名的基线校验镜像、方法入口与函数边界内的指令。
|
||||
*/
|
||||
#include "IGObjCBaseline.h"
|
||||
#include "IGAntiHook.h"
|
||||
#include "IGInline.h"
|
||||
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
# include <stdio.h>
|
||||
#endif
|
||||
#include <dlfcn.h>
|
||||
#include <mach/mach.h>
|
||||
#include <objc/objc.h>
|
||||
#include <objc/runtime.h>
|
||||
#include "IGMethodManifest.h"
|
||||
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(ptrauth_calls)
|
||||
# include <ptrauth.h>
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#define IG_OBJC_MAX_WATCH 64u
|
||||
#define IG_PREFIX_BYTES 32u
|
||||
|
||||
typedef struct {
|
||||
const char *cls;
|
||||
const char *sel;
|
||||
uint8_t is_cls_method;
|
||||
uint8_t pre_hooked;
|
||||
void *imp;
|
||||
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
|
||||
size_t prefix_len;
|
||||
} IGObjCSlot;
|
||||
|
||||
static IGObjCSlot g_slots[IG_OBJC_MAX_WATCH];
|
||||
static size_t g_nslots = 0;
|
||||
static IGObjCWatch g_unresolved[IG_OBJC_MAX_WATCH];
|
||||
static size_t g_unresolved_count;
|
||||
|
||||
static void ig_set_unresolved(IGObjCWatch watch, int missing) {
|
||||
for (size_t i = 0; i < g_unresolved_count; ++i) {
|
||||
if (ig_strcmp(watch.class_name, g_unresolved[i].class_name) == 0 &&
|
||||
ig_strcmp(watch.selector, g_unresolved[i].selector) == 0) {
|
||||
if (!missing) g_unresolved[i] = g_unresolved[--g_unresolved_count];
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (missing && g_unresolved_count < IG_OBJC_MAX_WATCH)
|
||||
g_unresolved[g_unresolved_count++] = watch;
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
#include <sys/sysctl.h>
|
||||
/* 仅 Debug:lldb 软断点会把入口指令改成 brk,构建摘要必然不一致。
|
||||
* 调试器附加时不据摘要判定改写;IMP 替换与登记前替换仍照常检测。 */
|
||||
static int ig_objc_debugger_attached(void) {
|
||||
pid_t pid = IG_dispatch_getpid();
|
||||
if (pid <= 0) return 0;
|
||||
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
|
||||
struct kinfo_proc info;
|
||||
size_t size = sizeof(info);
|
||||
ig_memset(&info, 0, sizeof(info));
|
||||
return sysctl(mib, 4, &info, &size, NULL, 0) == 0 && (info.kp_proc.p_flag & P_TRACED) != 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
static const void *ig_strip(const void *p) {
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(ptrauth_calls)
|
||||
return ptrauth_strip(p, ptrauth_key_asia);
|
||||
# else
|
||||
return p;
|
||||
# endif
|
||||
#else
|
||||
return p;
|
||||
#endif
|
||||
}
|
||||
|
||||
static void ig_emit_objc(IGFindingSink sink, void *ctx, int *stop, int *hits,
|
||||
IGStatus st, const char *subject, const char *evidence) {
|
||||
if (*stop) return;
|
||||
IGFinding f;
|
||||
ig_memset(&f, 0, sizeof(f));
|
||||
f.status = st;
|
||||
f.reason = IG_REASON_OBJC_IMP_CHANGED;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
if (subject) {
|
||||
size_t n = ig_strlen(subject);
|
||||
if (n >= sizeof(f.subject)) n = sizeof(f.subject) - 1u;
|
||||
ig_memcpy(f.subject, subject, n);
|
||||
}
|
||||
if (evidence) {
|
||||
size_t n = ig_strlen(evidence);
|
||||
if (n >= sizeof(f.evidence)) n = sizeof(f.evidence) - 1u;
|
||||
ig_memcpy(f.evidence, evidence, n);
|
||||
}
|
||||
#else
|
||||
(void)subject;
|
||||
(void)evidence;
|
||||
#endif
|
||||
if (st == IG_DETECTED) (*hits)++;
|
||||
if (sink && sink(&f, ctx) != 0) *stop = 1;
|
||||
}
|
||||
|
||||
static size_t ig_read_prefix(const void *addr, unsigned char *out, size_t length) {
|
||||
vm_size_t copied = 0;
|
||||
if (!length || length > IG_PREFIX_BYTES) return 0;
|
||||
if (vm_read_overwrite(mach_task_self(), (vm_address_t)ig_strip(addr), length,
|
||||
(vm_address_t)out, &copied) == KERN_SUCCESS && copied == length)
|
||||
return length;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static Method ig_resolve_method(Class c, const char *raw_sel, uint8_t *is_cls_out, const char **bare_sel_out) {
|
||||
const char *bare = raw_sel;
|
||||
if (bare[0] == '+' || bare[0] == '-') {
|
||||
int want_cls = (bare[0] == '+');
|
||||
++bare;
|
||||
if (!bare[0]) return NULL;
|
||||
*bare_sel_out = bare;
|
||||
*is_cls_out = want_cls ? 1u : 0u;
|
||||
SEL s = sel_registerName(bare);
|
||||
return want_cls ? class_getClassMethod(c, s) : class_getInstanceMethod(c, s);
|
||||
}
|
||||
*bare_sel_out = bare;
|
||||
SEL s = sel_registerName(bare);
|
||||
Method m = class_getInstanceMethod(c, s);
|
||||
if (m) {
|
||||
*is_cls_out = 0u;
|
||||
return m;
|
||||
}
|
||||
m = class_getClassMethod(c, s);
|
||||
if (m) {
|
||||
*is_cls_out = 1u;
|
||||
return m;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int ig_slot_exists(const char *cls, const char *bare_sel, uint8_t is_cls) {
|
||||
for (size_t i = 0; i < g_nslots; ++i) {
|
||||
if (g_slots[i].is_cls_method == is_cls &&
|
||||
ig_strcmp(g_slots[i].cls, cls) == 0 &&
|
||||
ig_strcmp(g_slots[i].sel, bare_sel) == 0) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t ig_objc_baseline_append(const IGObjCWatch *watches, size_t count) {
|
||||
if (!watches) return 0u;
|
||||
size_t added = 0u;
|
||||
for (size_t i = 0; i < count && g_nslots < IG_OBJC_MAX_WATCH; ++i) {
|
||||
if (!watches[i].class_name || !watches[i].selector) continue;
|
||||
Class c = objc_getClass(watches[i].class_name);
|
||||
uint8_t is_cls = 0u;
|
||||
const char *bare_sel = NULL;
|
||||
Method m = c ? ig_resolve_method(c, watches[i].selector, &is_cls, &bare_sel) : NULL;
|
||||
IMP imp = m ? method_getImplementation(m) : NULL;
|
||||
ig_set_unresolved(watches[i], imp == NULL);
|
||||
if (!imp) continue;
|
||||
if (ig_slot_exists(watches[i].class_name, bare_sel, is_cls)) continue;
|
||||
|
||||
const void *stripped = ig_strip((const void *)imp);
|
||||
IGObjCSlot *slot = &g_slots[g_nslots++];
|
||||
ig_memset(slot, 0, sizeof(*slot));
|
||||
slot->cls = watches[i].class_name;
|
||||
slot->sel = bare_sel;
|
||||
slot->is_cls_method = is_cls;
|
||||
slot->imp = (void *)stripped;
|
||||
|
||||
const IGMethodRecord *expected = ig_expected_method(c, sel_registerName(bare_sel), is_cls, m);
|
||||
Dl_info info;
|
||||
if (expected && expected->length && expected->length % 4 == 0 && expected->length <= IG_PREFIX_BYTES) {
|
||||
const uint8_t *uuid = dladdr(stripped, &info) ? ig_method_image_uuid(info.dli_fbase) : NULL;
|
||||
if (!uuid) {
|
||||
slot->pre_hooked = 1u;
|
||||
} else {
|
||||
uintptr_t offset = (uintptr_t)stripped - (uintptr_t)info.dli_fbase;
|
||||
slot->pre_hooked = ig_memcmp(uuid, expected->uuid, 16) != 0 ||
|
||||
offset != expected->offset;
|
||||
slot->prefix_len = expected->length;
|
||||
ig_memcpy(slot->digest, expected->digest, sizeof(slot->digest));
|
||||
}
|
||||
}
|
||||
++added;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
size_t ig_objc_baseline_capture(const IGObjCWatch *watches, size_t count) {
|
||||
g_nslots = 0u;
|
||||
g_unresolved_count = 0u;
|
||||
if (!watches || count == 0u) return 0u;
|
||||
return ig_objc_baseline_append(watches, count);
|
||||
}
|
||||
|
||||
size_t ig_objc_baseline_count(void) {
|
||||
return g_nslots;
|
||||
}
|
||||
|
||||
int ig_objc_baseline_check(IGFindingSink sink, void *ctx) {
|
||||
int hits = 0, stop = 0;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char subject[192], ev[256];
|
||||
#else
|
||||
const char *subject = NULL;
|
||||
#endif
|
||||
for (size_t i = 0; i < g_unresolved_count && !stop; ++i) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
snprintf(subject, sizeof(subject), "%s %s", g_unresolved[i].class_name, g_unresolved[i].selector);
|
||||
#endif
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_UNAVAILABLE, subject, IG_DIAG_STR("登记时无法解析方法"));
|
||||
}
|
||||
for (size_t i = 0; i < g_nslots && !stop; ++i) {
|
||||
const IGObjCSlot *b = &g_slots[i];
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
snprintf(subject, sizeof(subject), "%c[%s %s]", b->is_cls_method ? '+' : '-', b->cls, b->sel);
|
||||
#endif
|
||||
if (b->pre_hooked) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
snprintf(ev, sizeof(ev), "实现偏离构建基线(@%p)", b->imp);
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_DETECTED, subject, ev);
|
||||
#else
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_DETECTED, subject, NULL);
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
Class c = objc_getClass(b->cls);
|
||||
if (!c) {
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_UNAVAILABLE, subject,
|
||||
IG_DIAG_STR("基线登记后类不可解析(被卸载或运行时异常)"));
|
||||
continue;
|
||||
}
|
||||
SEL s = sel_registerName(b->sel);
|
||||
Method m = b->is_cls_method ? class_getClassMethod(c, s) : class_getInstanceMethod(c, s);
|
||||
if (!m || !method_getImplementation(m)) {
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_UNAVAILABLE, subject,
|
||||
IG_DIAG_STR("方法实现不可解析(转发桩或已移除)"));
|
||||
continue;
|
||||
}
|
||||
IMP imp = method_getImplementation(m);
|
||||
const void *cur = ig_strip((const void *)imp);
|
||||
if (cur != b->imp) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char cur_prov[192] = "?";
|
||||
Dl_info info;
|
||||
if (dladdr(cur, &info) && info.dli_fname) {
|
||||
size_t plen = ig_strlen(info.dli_fname);
|
||||
if (plen >= sizeof(cur_prov)) plen = sizeof(cur_prov) - 1u;
|
||||
ig_memcpy(cur_prov, info.dli_fname, plen);
|
||||
cur_prov[plen] = '\0';
|
||||
}
|
||||
snprintf(ev, sizeof(ev), "IMP %p → %p(%s)(实现被替换)",
|
||||
b->imp, cur, cur_prov);
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_DETECTED, subject, ev);
|
||||
#else
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_DETECTED, subject, NULL);
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
if (!b->prefix_len) {
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_UNAVAILABLE, subject,
|
||||
IG_DIAG_STR("缺少可验证的构建基线"));
|
||||
continue;
|
||||
}
|
||||
{
|
||||
unsigned char now[IG_PREFIX_BYTES];
|
||||
size_t now_len = ig_read_prefix(cur, now, b->prefix_len);
|
||||
if (now_len < b->prefix_len) {
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_UNAVAILABLE, subject,
|
||||
IG_DIAG_STR("代码前缀不可读"));
|
||||
continue;
|
||||
}
|
||||
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
|
||||
CC_SHA256(now, (CC_LONG)b->prefix_len, digest);
|
||||
if (ig_memcmp(digest, b->digest, sizeof(digest)) != 0) {
|
||||
#ifdef DEBUG
|
||||
if (ig_objc_debugger_attached()) continue;
|
||||
#endif
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
snprintf(ev, sizeof(ev), "IMP %p 不变但代码前缀变化(函数体被改写)", cur);
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_DETECTED, subject, ev);
|
||||
#else
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_DETECTED, subject, NULL);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* IGObjCBaseline.h — ObjC 关键方法 IMP 基线探针(swizzle / 方法替换检测)。
|
||||
*
|
||||
* 背景(docs/05 §4 P1):IGAntiHook 只覆盖 C 符号层(序言/GOT/提供方),对 ObjC 层
|
||||
* method_exchangeImplementations / class_replaceMethod / method_setImplementation
|
||||
* 等劫持手段此前零覆盖。本模块由策略层指定关键方法清单,登记时记录 IMP,并加载同一构建的镜像 UUID、
|
||||
* 入口偏移与函数边界内的指令,扫描时比对——IMP 换人或函数体被改即上报。
|
||||
*
|
||||
* 边界(如实声明):
|
||||
* - 合法 swizzle(统计/广告 SDK 常见)也会改变 IMP:本探针只给证据,是否处置由
|
||||
* 策略层决定;基线采集时机本身是策略选择(早采集会把业务自身的合法交换计入)。
|
||||
* - 只比对策略层显式登记的方法,不做全类扫(误报面不可控)。
|
||||
* - 纯 C 调 objc runtime API,不引入 ObjC 编译依赖;未 capture 过时 check 为 no-op。
|
||||
*/
|
||||
#ifndef IG_OBJC_BASELINE_H
|
||||
#define IG_OBJC_BASELINE_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 观察项:类名 + 选择子(如 { "RDOrderViewController", "payOrder" })。 */
|
||||
typedef struct {
|
||||
const char *class_name;
|
||||
const char *selector;
|
||||
} IGObjCWatch;
|
||||
|
||||
/*
|
||||
* 重置观察项,按方法的声明类和选择子查询构建基线。指令比较最多 32 字节。
|
||||
* 支持实例方法(默认或 '-' 前缀)与类方法(自动回退或 '+' 前缀)。
|
||||
* 幂等,重复调用以最后一次为准;count==0 清空基线。返回当前累计成功登记的条数。
|
||||
*/
|
||||
size_t ig_objc_baseline_capture(const IGObjCWatch *watches, size_t count);
|
||||
|
||||
/*
|
||||
* 增量追加基线:在不清空既有登记项的前提下追加新的观察项(同类名+选择子自动去重)。
|
||||
* 适用于 C ctor 提前锁存核心 ObjC 方法,Swift 层启动后再追加 Swift `@objc` 方法。
|
||||
*/
|
||||
size_t ig_objc_baseline_append(const IGObjCWatch *watches, size_t count);
|
||||
|
||||
/* 返回当前已锁存的 ObjC 方法基线条数。 */
|
||||
size_t ig_objc_baseline_count(void);
|
||||
|
||||
/*
|
||||
* 扫描:IMP 地址变化,或 IMP 相同但代码前缀变化 → DETECTED(110);
|
||||
* 已登记方法无法解析、缺少可信构建记录或代码页不可读 → UNAVAILABLE(110)。
|
||||
* 未 capture 过时为 clear no-op(不惩罚未接入的调用方)。
|
||||
* 返回 DETECTED 条数;只采集证据不处置。
|
||||
*/
|
||||
int ig_objc_baseline_check(IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_OBJC_BASELINE_H */
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
* IGAntiJailbreak.c — 越狱检测探针实现。见 .h 的定位与边界。
|
||||
*
|
||||
* 全部文件探测经 IGSyscall 直发(access/open/close/unlink),不经 libc——规避 Shadow/Liberty
|
||||
* 等对 stat/access 的 hook。证据经 sink 上报,不做处置。
|
||||
*/
|
||||
#include "IGAntiJailbreak.h"
|
||||
#include "syscall/IGSyscall.h"
|
||||
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
# include <stdio.h>
|
||||
#endif
|
||||
|
||||
/* access 的 amode:F_OK=0(仅测存在/可访问)。open 标志(BSD/Darwin 值)。 */
|
||||
#define IG_F_OK 0
|
||||
#define IG_O_RDWR 0x0002
|
||||
#define IG_O_CREAT 0x0200
|
||||
#define IG_O_EXCL 0x0800
|
||||
|
||||
/*
|
||||
* 内置 iOS 越狱特征(强信号)。沙盒内正常 App 对这些路径 access 应得 -ENOENT/-EPERM;
|
||||
* 能访问即越狱。rootless 越狱重点在 /var/jb。
|
||||
*
|
||||
* §7.1 IG_ENC:路径不再明文驻留——由 tools/gen_jb_paths.py 生成的 XOR 混淆表引入,
|
||||
* 运行期解码进栈缓冲、用完擦除,`strings` 捞不到 /var/jb、Cydia、substrate 等常量。
|
||||
*/
|
||||
#include "IGJailbreakPaths.inc"
|
||||
|
||||
/* 解码单条混淆路径到 out(容量 cap,含结尾 0)。返回长度,失败返回 0。
|
||||
* k0 取 volatile:阻止 -O2 把「常量 enc + 常量 key」整条折叠回明文存入 __const
|
||||
* (否则混淆被优化器击穿,strings 又能捞出)。强制运行期解码。 */
|
||||
static size_t ig_jb_decode(const unsigned char *enc, size_t n, int idx,
|
||||
char *out, size_t cap) {
|
||||
volatile unsigned k0 = IG_JB_XOR_K0;
|
||||
if (n + 1 > cap) return 0;
|
||||
for (size_t j = 0; j < n; ++j) {
|
||||
unsigned ks = ((unsigned)k0 + (unsigned)idx * IG_JB_XOR_K1 + j * IG_JB_XOR_K2) & 0xFFu;
|
||||
out[j] = (char)(enc[j] ^ ks);
|
||||
}
|
||||
out[n] = '\0';
|
||||
return n;
|
||||
}
|
||||
|
||||
static void ig_jb_emit(IGFindingSink sink, void *ctx, int *hits,
|
||||
IGStatus st, int reason, const char *subject, const char *evidence) {
|
||||
IGFinding f;
|
||||
__builtin_memset(&f, 0, sizeof(f));
|
||||
f.status = st;
|
||||
f.reason = reason;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
if (subject) snprintf(f.subject, sizeof(f.subject), "%s", subject);
|
||||
if (evidence) snprintf(f.evidence, sizeof(f.evidence), "%s", evidence);
|
||||
#else
|
||||
(void)subject;
|
||||
(void)evidence;
|
||||
#endif
|
||||
if (st == IG_DETECTED) (*hits)++;
|
||||
if (sink) sink(&f, ctx);
|
||||
}
|
||||
|
||||
int ig_anti_jb_check_paths(const char *const *paths, size_t count,
|
||||
const char *sandbox_probe_path,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
int hits = 0;
|
||||
|
||||
/* 1) 越狱特征文件:直发 access(path, F_OK)==0 即可访问。 */
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (!paths[i]) continue;
|
||||
if (ig_sys_access(paths[i], IG_F_OK) == 0) {
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "直发 access 可访问越狱特征:%s", paths[i]);
|
||||
ig_jb_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_JAILBREAK_FILE, paths[i], ev);
|
||||
#else
|
||||
ig_jb_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_JAILBREAK_FILE, NULL, NULL);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/* 2) 沙盒逃逸:在沙盒外路径直发 open(O_CREAT|O_EXCL) 创建文件,成功=越狱强信号。 */
|
||||
if (sandbox_probe_path) {
|
||||
ig_sys_unlink(sandbox_probe_path); /* 清理上次残留(忽略错误) */
|
||||
int fd = ig_sys_open(sandbox_probe_path, IG_O_RDWR | IG_O_CREAT | IG_O_EXCL, 0600);
|
||||
if (fd >= 0) {
|
||||
ig_sys_close(fd);
|
||||
ig_sys_unlink(sandbox_probe_path); /* 立即清理,不留痕 */
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "能在沙盒外创建文件:%s", sandbox_probe_path);
|
||||
ig_jb_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_JAILBREAK_SANDBOX,
|
||||
sandbox_probe_path, ev);
|
||||
#else
|
||||
ig_jb_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_JAILBREAK_SANDBOX,
|
||||
NULL, NULL);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
return hits;
|
||||
}
|
||||
|
||||
int ig_anti_jb_check(IGFindingSink sink, void *ctx) {
|
||||
/* §7.1:把混淆表运行期解码进栈,构建 ptr 数组喂给通用入口,用完擦除,不留明文。 */
|
||||
char storage[IG_JB_ENC_COUNT][128];
|
||||
const char *ptrs[IG_JB_ENC_COUNT];
|
||||
for (int i = 0; i < IG_JB_ENC_COUNT; ++i) {
|
||||
ig_jb_decode(kIGJbEnc[i].b, kIGJbEnc[i].n, i, storage[i], sizeof(storage[i]));
|
||||
ptrs[i] = storage[i];
|
||||
}
|
||||
char probe[128];
|
||||
ig_jb_decode(kIGJbProbeEnc, IG_JB_PROBE_LEN, IG_JB_PROBE_IDX, probe, sizeof(probe));
|
||||
|
||||
int hits = ig_anti_jb_check_paths(ptrs, IG_JB_ENC_COUNT, probe, sink, ctx);
|
||||
|
||||
/* 擦除解码后的明文,缩短其在内存驻留窗口(动态分析仍可抓,但抬高被动 dump 成本)。 */
|
||||
__builtin_memset(storage, 0, sizeof(storage));
|
||||
__builtin_memset(probe, 0, sizeof(probe));
|
||||
return hits;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* IGAntiJailbreak.h — 越狱检测探针(走 IGSyscall 直发 svc,绕过 libc 层 hook)。
|
||||
*
|
||||
* 定位:Shadow / Liberty / A-Bypass 这类反越狱检测插件主要 hook 在 libc/ObjC 层
|
||||
* (stat/access/fopen/NSFileManager)。本探针用 IGSyscall 的 svc #0x80 直发
|
||||
* access(2)/open(2),那条可被 hook 的 libSystem 入口在此路径上不存在——检测点下沉到
|
||||
* bypass 够不到的层。这是纯客户端对抗里"抬高绕过成本"的关键一环(非根治)。
|
||||
*
|
||||
* 只采集证据、不处置:命中经 sink 上报,是否毒化/降级由策略层([[iosguard-disposition-strategy]]
|
||||
* 的 ig_poison_mark)按强信号组合决定。本探针绝不自行 exit。
|
||||
*
|
||||
* 边界:
|
||||
* - 路径特征可被 rootless 越狱改位;未命中不等于干净(组合判定原则不变)。
|
||||
* - 当前骨架路径字符串为明文,静态可见、bypass 可针对——TODO 用 IGResolve 的 XOR 混淆
|
||||
* (IG_ENC),与 svc 号混淆同理。svc 直发本身已是主要价值,字符串混淆是第二层。
|
||||
* - 仅 arm64 直发;非 arm64(宿主 x86_64)syscall 退化 unavailable。
|
||||
*/
|
||||
#ifndef IG_ANTI_JAILBREAK_H
|
||||
#define IG_ANTI_JAILBREAK_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 默认检测:内置 iOS 越狱特征表 + 沙盒逃逸探测。返回 DETECTED 条数。 */
|
||||
int ig_anti_jb_check(IGFindingSink sink, void *ctx);
|
||||
|
||||
/*
|
||||
* 可注入版本(供自测/定制)。
|
||||
* paths/count:要探测可访问性的路径表(access F_OK);命中记 reason=400。
|
||||
* sandbox_probe_path:非 NULL 时尝试在该(应在沙盒外的)路径创建文件,成功=沙盒逃逸,记 401
|
||||
* 并立即清理;NULL 跳过逃逸探测。
|
||||
*/
|
||||
int ig_anti_jb_check_paths(const char *const *paths, size_t count,
|
||||
const char *sandbox_probe_path,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_ANTI_JAILBREAK_H */
|
||||
@@ -0,0 +1,28 @@
|
||||
/* IGJailbreakPaths.inc — 由 tools/gen_jb_paths.py 生成,请勿手改。 */
|
||||
/* 越狱路径 XOR 混淆表(§7.1):enc[j]=plain[j]^((K0+idx*K1+j*K2)&0xFF)。 */
|
||||
#define IG_JB_XOR_K0 0x5au
|
||||
#define IG_JB_XOR_K1 0x2fu
|
||||
#define IG_JB_XOR_K2 0x13u
|
||||
|
||||
static const unsigned char kIGJbEnc0[] = { 0x75, 0x1b, 0xe1, 0xe1, 0x89, 0xd3, 0xae }; /* len=7 */
|
||||
static const unsigned char kIGJbEnc1[] = { 0xa6, 0xdd, 0xdf, 0xb2, 0xb9, 0x81, 0x98, 0x6f, 0x55, 0x5d, 0x28, 0x34, 0x1e, 0xaf, 0xd0, 0xdf, 0xdd, 0xa5, 0xbe, 0xdc, 0x64, 0x68, 0x5b }; /* len=23 */
|
||||
static const unsigned char kIGJbEnc2[] = { 0x97, 0x8a, 0xae, 0x81, 0x68, 0x7e, 0x49, 0x5c, 0x24, 0x0a, 0x19, 0xe7, 0xef, 0x80, 0x91, 0xbc, 0x84, 0x9e, 0x61, 0x0f, 0x55, 0x37, 0x2a }; /* len=23 */
|
||||
static const unsigned char kIGJbEnc3[] = { 0xc8, 0xbb, 0x7d, 0x50, 0x5f, 0x2f, 0x3a, 0x0d, 0x0b, 0xfb, 0xca, 0xd6, 0xb8, 0xf1, 0xab, 0x61, 0x75, 0x58, 0x5c, 0x7e, 0x02, 0x06, 0xf9 }; /* len=23 */
|
||||
static const unsigned char kIGJbEnc4[] = { 0x39, 0x5c, 0x4f, 0x3d, 0x4d, 0x06, 0xea, 0xf2, 0xc0, 0xee, 0xa7, 0x94, 0x92, 0x69 }; /* len=14 */
|
||||
static const unsigned char kIGJbEnc5[] = { 0x6a, 0x2d, 0x18, 0x0c, 0xbe, 0xc6, 0xde, 0xa4, 0xf2, 0x83, 0x70, 0x7e }; /* len=12 */
|
||||
static const unsigned char kIGJbEnc6[] = { 0x5b, 0xe5, 0xf3, 0xc3, 0xef, 0xb1, 0x87, 0x8a, 0x64 }; /* len=9 */
|
||||
static const unsigned char kIGJbEnc7[] = { 0x8c, 0xd4, 0xa0, 0xb2, 0xc0, 0x71, 0x7d }; /* len=7 */
|
||||
static const unsigned char kIGJbEnc8[] = { 0xfd, 0x80, 0x8c, 0x68, 0x31, 0x50, 0x34, 0x23 }; /* len=8 */
|
||||
static const unsigned char kIGJbEnc9[] = { 0x2e, 0x64, 0x55, 0x53, 0x3b, 0x01, 0x07, 0xe3, 0xb6, 0xda, 0xde, 0xa0, 0xca, 0x94, 0x62, 0x7c, 0x1e, 0x25, 0x27, 0x1e }; /* len=20 */
|
||||
static const unsigned char kIGJbEnc10[] = { 0x1f, 0x36, 0x25, 0x1b, 0x53, 0xe3, 0xcb, 0xd7, 0xe7, 0xa8, 0x9b, 0x63, 0x67, 0x53, 0x48, 0x2c, 0x14, 0x16 }; /* len=18 */
|
||||
static const unsigned char kIGJbEnc11[] = { 0x70, 0x3e, 0xec, 0xfa, 0xd9, 0xdf, 0xa3, 0x9d, 0xd8, 0x47, 0x72, 0x52, 0x2a, 0x3a, 0x0c, 0x2f, 0xfa, 0xc0, 0xc6, 0xbc, 0xa9, 0x8f, 0x75, 0x71, 0x08, 0x77, 0x22, 0x02, 0x1a, 0xea, 0xfc, 0xff, 0xca, 0xb0, 0x96, 0x8c, 0x79, 0x7f, 0x45, 0x21, 0x79, 0x0e, 0x04, 0xfc, 0xca, 0xd4 }; /* len=46 */
|
||||
static const unsigned char kIGJbEnc12[] = { 0xa1, 0xd4, 0xc7, 0xb5, 0xf5, 0x81, 0x69, 0x71, 0x09, 0x6d, 0x3b, 0x3a, 0x13, 0xee, 0xd1, 0xc5, 0xd4, 0xb4, 0x87, 0x83 }; /* len=20 */
|
||||
|
||||
static const struct { const unsigned char *b; unsigned char n; } kIGJbEnc[] = { { kIGJbEnc0, 7 }, { kIGJbEnc1, 23 }, { kIGJbEnc2, 23 }, { kIGJbEnc3, 23 }, { kIGJbEnc4, 14 }, { kIGJbEnc5, 12 }, { kIGJbEnc6, 9 }, { kIGJbEnc7, 7 }, { kIGJbEnc8, 8 }, { kIGJbEnc9, 20 }, { kIGJbEnc10, 18 }, { kIGJbEnc11, 46 }, { kIGJbEnc12, 20 } };
|
||||
#define IG_JB_ENC_COUNT 13
|
||||
|
||||
/* 沙盒逃逸探测路径(idx 用一个与上表不冲突的独立下标)。 */
|
||||
static const unsigned char kIGJbProbeEnc[] = { 0x8a, 0xc8, 0xb9, 0xb7, 0x87, 0x65, 0x63, 0x4f, 0x12, 0x7e, 0x0a, 0x11, 0xd6, 0xf6, 0xcd, 0x9d, 0xa5, 0x9a, 0x94, 0x6c, 0x44 }; /* len=21 */
|
||||
#define IG_JB_PROBE_LEN 21
|
||||
#define IG_JB_PROBE_IDX 0xa5
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* IGAntiTamper.c — 二进制完整性 / 防重打包探针实现。见 .h 的定位与误报底线。
|
||||
*
|
||||
* 只采集证据经 sink 上报,不处置。两条检查均按 expect_* 构建上下文开关,dev/诊断构建传 0
|
||||
* → 返回 UNAVAILABLE,绝不在非分发构建上报 DETECTED。
|
||||
*/
|
||||
#include "IGAntiTamper.h"
|
||||
|
||||
#include <mach-o/dyld.h>
|
||||
#include <unistd.h>
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
# include <stdio.h>
|
||||
#endif
|
||||
|
||||
/* csops(2):读本进程代码签名状态。手工声明(<sys/codesign.h> 非 SDK 公共头)。 */
|
||||
#define IG_CS_OPS_STATUS 0
|
||||
#define IG_CS_VALID 0x00000001u /* 动态有效(代码页签名校验通过) */
|
||||
#define IG_CS_ADHOC 0x00000002u /* ad-hoc 签名(无开发者证书) */
|
||||
#define IG_CS_GET_TASK_ALLOW 0x00000004u /* 允许被 task_for_pid/调试器附着 */
|
||||
extern int csops(pid_t pid, unsigned int ops, void *useraddr, size_t usersize);
|
||||
|
||||
static void ig_tamper_emit(IGFindingSink sink, void *ctx, int *hits,
|
||||
IGStatus st, int reason, const char *subject, const char *evidence) {
|
||||
IGFinding f;
|
||||
__builtin_memset(&f, 0, sizeof(f));
|
||||
f.status = st;
|
||||
f.reason = reason;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
if (subject) snprintf(f.subject, sizeof(f.subject), "%s", subject);
|
||||
if (evidence) snprintf(f.evidence, sizeof(f.evidence), "%s", evidence);
|
||||
#else
|
||||
(void)subject;
|
||||
(void)evidence;
|
||||
#endif
|
||||
if (st == IG_DETECTED && hits) (*hits)++;
|
||||
if (sink) sink(&f, ctx);
|
||||
}
|
||||
|
||||
int ig_tamper_scan_cryptid(const struct mach_header_64 *mh, int expect_encrypted,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
int hits = 0;
|
||||
|
||||
/* 非分发构建:未 FairPlay 加密是正常的,无法据此断言篡改。 */
|
||||
if (!expect_encrypted) {
|
||||
ig_tamper_emit(sink, ctx, &hits, IG_UNAVAILABLE, IG_REASON_BINARY_DECRYPTED,
|
||||
IG_DIAG_STR("cryptid"), IG_DIAG_STR("非分发构建(expect_encrypted=0),跳过加密校验"));
|
||||
return hits;
|
||||
}
|
||||
if (!mh || mh->magic != MH_MAGIC_64) {
|
||||
ig_tamper_emit(sink, ctx, &hits, IG_UNAVAILABLE, IG_REASON_BINARY_DECRYPTED,
|
||||
IG_DIAG_STR("cryptid"), IG_DIAG_STR("主镜像 Mach-O 头不可用"));
|
||||
return hits;
|
||||
}
|
||||
|
||||
/* 遍历 load command 找 LC_ENCRYPTION_INFO_64。 */
|
||||
const struct load_command *lc = (const struct load_command *)(mh + 1);
|
||||
int found = 0;
|
||||
uint32_t cryptid = 0;
|
||||
for (uint32_t i = 0; i < mh->ncmds; ++i) {
|
||||
if (lc->cmdsize == 0) break; /* 防御畸形头导致的死循环 */
|
||||
if (lc->cmd == LC_ENCRYPTION_INFO_64) {
|
||||
const struct encryption_info_command_64 *e =
|
||||
(const struct encryption_info_command_64 *)lc;
|
||||
found = 1;
|
||||
cryptid = e->cryptid;
|
||||
break;
|
||||
}
|
||||
lc = (const struct load_command *)((const uint8_t *)lc + lc->cmdsize);
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
/* 应加密的分发包却整条没有加密命令:被剥除/重打包的强信号。 */
|
||||
ig_tamper_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_BINARY_DECRYPTED,
|
||||
IG_DIAG_STR("cryptid"), IG_DIAG_STR("应加密分发包无 LC_ENCRYPTION_INFO(加密命令被剥除/重打包)"));
|
||||
} else if (cryptid == 0) {
|
||||
/* 标准脱壳(Clutch/frida-ios-dump)会把 cryptid 改 0。 */
|
||||
ig_tamper_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_BINARY_DECRYPTED,
|
||||
IG_DIAG_STR("cryptid"), IG_DIAG_STR("cryptid==0:二进制已脱壳解密(dump/重打包)"));
|
||||
}
|
||||
/* cryptid != 0 → CLEAR,保持安静不上报。 */
|
||||
return hits;
|
||||
}
|
||||
|
||||
static int ig_tamper_scan_codesign(int expect_distribution,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
int hits = 0;
|
||||
|
||||
/* 非分发构建:dev/诊断签名本就带 get-task-allow、可能 ad-hoc,不据此断言。 */
|
||||
if (!expect_distribution) {
|
||||
ig_tamper_emit(sink, ctx, &hits, IG_UNAVAILABLE, IG_REASON_CODESIGN_INVALID,
|
||||
IG_DIAG_STR("codesign"), IG_DIAG_STR("非分发构建(expect_distribution=0),跳过签名校验"));
|
||||
return hits;
|
||||
}
|
||||
|
||||
uint32_t status = 0;
|
||||
/* pid=0 在 XNU 内核直接指向当前进程,避免引入对 _getpid 的显式调用。 */
|
||||
if (csops(0, IG_CS_OPS_STATUS, &status, sizeof(status)) != 0) {
|
||||
ig_tamper_emit(sink, ctx, &hits, IG_UNAVAILABLE, IG_REASON_CODESIGN_INVALID,
|
||||
IG_DIAG_STR("codesign"), IG_DIAG_STR("csops(CS_OPS_STATUS) 调用失败"));
|
||||
return hits;
|
||||
}
|
||||
|
||||
if (!(status & IG_CS_VALID)) {
|
||||
ig_tamper_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_CODESIGN_INVALID,
|
||||
IG_DIAG_STR("codesign"), IG_DIAG_STR("CS_VALID 失效:代码页签名校验未通过(内存/磁盘被 patch)"));
|
||||
}
|
||||
if (status & IG_CS_ADHOC) {
|
||||
ig_tamper_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_CODESIGN_INVALID,
|
||||
IG_DIAG_STR("codesign"), IG_DIAG_STR("ad-hoc 签名:无开发者证书的重签(典型破解重打包)"));
|
||||
}
|
||||
if (status & IG_CS_GET_TASK_ALLOW) {
|
||||
ig_tamper_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_CODESIGN_INVALID,
|
||||
IG_DIAG_STR("codesign"), IG_DIAG_STR("分发包却带 get-task-allow:被重签成可调试"));
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
static const struct mach_header_64 *ig_main_image_header(void) {
|
||||
uint32_t n = _dyld_image_count();
|
||||
for (uint32_t i = 0; i < n; ++i) {
|
||||
const struct mach_header *h = _dyld_get_image_header(i);
|
||||
if (h && h->magic == MH_MAGIC_64 &&
|
||||
((const struct mach_header_64 *)h)->filetype == MH_EXECUTE) {
|
||||
return (const struct mach_header_64 *)h;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int ig_anti_tamper_check(int expect_encrypted, int expect_distribution,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
int hits = 0;
|
||||
hits += ig_tamper_scan_cryptid(ig_main_image_header(), expect_encrypted, sink, ctx);
|
||||
hits += ig_tamper_scan_codesign(expect_distribution, sink, ctx);
|
||||
return hits;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* IGAntiTamper.h — 二进制完整性 / 防重打包探针。
|
||||
*
|
||||
* 定位:anti_hook 只校验固定一批关键函数的序言/GOT——攻击者 patch 这批之外的任意指令(含
|
||||
* NOP 掉某条检测/毒化调用边、改业务层比较)它看不见。本模块从「镜像整体」角度补这个空洞,
|
||||
* 正面反制 App Store 应用的标准破解链:**脱壳解密(Clutch/frida-ios-dump)→ patch → 重签**。
|
||||
*
|
||||
* 两条检查(均只采集证据、不处置,经 sink 上报;判级交 policy):
|
||||
* 1. FairPlay cryptid:App Store 分发包由 Apple 加密(LC_ENCRYPTION_INFO_64.cryptid=1)。
|
||||
* 脱壳 dump 会把 cryptid 改 0;重打包可能整条剥除加密命令。→ IG_REASON_BINARY_DECRYPTED。
|
||||
* 2. 代码签名状态(csops CS_OPS_STATUS):ad-hoc 重签、分发包却带 get-task-allow(被重签成
|
||||
* 可调试)、CS_VALID 失效。→ IG_REASON_CODESIGN_INVALID。
|
||||
*
|
||||
* 【误报底线】这两条都**依赖构建上下文**:dev/TestFlight/诊断构建本就未 FairPlay 加密、且带
|
||||
* get-task-allow——那是正常的,不是篡改。故由调用方按构建类型传 expect_* 开关:只有
|
||||
* 「本应是 App Store 分发包」时才判 DETECTED;否则返回 UNAVAILABLE(无法断言,不上报 DETECTED)。
|
||||
* expect 开关应由 Release/App Store 构建配置注入(见 docs/18),绝不在 dev 构建置 1。
|
||||
*
|
||||
* 【边界】csops 经 libc 调用,可被 hook 伪造(若攻击者已能 hook csops,说明环境已失陷,
|
||||
* 届时 anti_hook/anti_inject 会先命中);cryptid 读的是进程内 Mach-O 头,patch 头部也能伪装,
|
||||
* 但那要求攻击者已定位该检查——与整体「抬成本、非不可破」哲学一致,不作为唯一安全锚点。
|
||||
*/
|
||||
#ifndef IG_ANTI_TAMPER_H
|
||||
#define IG_ANTI_TAMPER_H
|
||||
|
||||
#include <mach-o/loader.h>
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* 真机入口:对当前进程主可执行镜像做 cryptid + 代码签名检查。
|
||||
* expect_encrypted:本构建是否「本应 FairPlay 加密」(App Store 分发=1,dev/诊断=0)。
|
||||
* expect_distribution:本构建是否「本应分发签名」(不含 get-task-allow;App Store=1,dev=0)。
|
||||
* 两者为 0 时对应检查返回 UNAVAILABLE(不误报)。返回 DETECTED 证据条数。
|
||||
*/
|
||||
int ig_anti_tamper_check(int expect_encrypted, int expect_distribution,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
/*
|
||||
* 可测核心:对给定 Mach-O 头做 cryptid 检查(与真机入口共用逻辑,便于用合成头单测)。
|
||||
* mh:指向 mach_header_64。expect_encrypted:同上。
|
||||
* 返回 DETECTED 条数(0=CLEAR 或 UNAVAILABLE)。
|
||||
*/
|
||||
int ig_tamper_scan_cryptid(const struct mach_header_64 *mh, int expect_encrypted,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_ANTI_TAMPER_H */
|
||||
@@ -0,0 +1,52 @@
|
||||
#include "IGFileBridge.h"
|
||||
#include <unistd.h>
|
||||
|
||||
#if !defined(__clang__)
|
||||
#error "此验证实现需要 Clang 的 optnone 属性"
|
||||
#endif
|
||||
|
||||
// 仅 SDK 的未定义引用重定向到此函数;本文件不能参与符号重定向。
|
||||
// 无日志、检测或全局可变状态,直接返回系统 FILE * 并保留 errno。
|
||||
// 间接调用不代表 GOT/Inline Hook 防护,仍须对最终 Release 单独验收。
|
||||
__attribute__((optnone, noinline))
|
||||
FILE *IG_fopen(const char *path, const char *mode) {
|
||||
FILE *(*function)(const char *, const char *) = fopen;
|
||||
return function(path, mode);
|
||||
}
|
||||
|
||||
// 各入口单独保持真实类型;不进行自动重试或短读短写补齐。
|
||||
__attribute__((optnone, noinline))
|
||||
int IG_fclose(FILE *stream) {
|
||||
int (*function)(FILE *) = fclose;
|
||||
return function(stream);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
size_t IG_fread(void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
size_t (*function)(void *, size_t, size_t, FILE *) = fread;
|
||||
return function(buffer, size, count, stream);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
size_t IG_fwrite(const void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
size_t (*function)(const void *, size_t, size_t, FILE *) = fwrite;
|
||||
return function(buffer, size, count, stream);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
ssize_t IG_read(int descriptor, void *buffer, size_t count) {
|
||||
ssize_t (*function)(int, void *, size_t) = read;
|
||||
return function(descriptor, buffer, count);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
ssize_t IG_write(int descriptor, const void *buffer, size_t count) {
|
||||
ssize_t (*function)(int, const void *, size_t) = write;
|
||||
return function(descriptor, buffer, count);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
int IG_close(int descriptor) {
|
||||
int (*function)(int) = close;
|
||||
return function(descriptor);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef IG_FILE_BRIDGE_H
|
||||
#define IG_FILE_BRIDGE_H
|
||||
|
||||
#include <stdio.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
FILE *IG_fopen(const char *path, const char *mode);
|
||||
int IG_fclose(FILE *stream);
|
||||
size_t IG_fread(void *buffer, size_t size, size_t count, FILE *stream);
|
||||
size_t IG_fwrite(const void *buffer, size_t size, size_t count, FILE *stream);
|
||||
ssize_t IG_read(int descriptor, void *buffer, size_t count);
|
||||
ssize_t IG_write(int descriptor, const void *buffer, size_t count);
|
||||
int IG_close(int descriptor);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,22 @@
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* 仅用于已核实只查询当前线程 ID 的 SDK 引用。保留 Darwin syscall 的 int 返回 ABI。 */
|
||||
int IG_sdk_thread_selfid(int operation) {
|
||||
if (operation != 372) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint64_t thread_id = 0;
|
||||
int incoming = errno;
|
||||
int status = pthread_threadid_np(NULL, &thread_id);
|
||||
if (status != 0) {
|
||||
errno = status;
|
||||
return -1;
|
||||
}
|
||||
|
||||
errno = incoming;
|
||||
return (int)(uint32_t)thread_id;
|
||||
}
|
||||
@@ -0,0 +1,521 @@
|
||||
#define IG_ARCHIVE_IMPL 1
|
||||
#include "IGArchiveGuard.h"
|
||||
#if __has_include("../include/IGHookResponse.h")
|
||||
#include "../include/IGHookResponse.h"
|
||||
#define IG_ARCHIVE_HAS_RESPONSE 1
|
||||
#else
|
||||
#define IG_ARCHIVE_HAS_RESPONSE 0
|
||||
#endif
|
||||
#include "../resolve/IGResolve.h"
|
||||
#include "../anti_hook/IGAntiHook.h"
|
||||
#include "../primitives/IGInline.h"
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdatomic.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(ptrauth_calls)
|
||||
# include <ptrauth.h>
|
||||
# define IG_ARCHIVE_STRIP(p) ptrauth_strip((p), ptrauth_key_asia)
|
||||
# endif
|
||||
#endif
|
||||
#ifndef IG_ARCHIVE_STRIP
|
||||
# define IG_ARCHIVE_STRIP(p) (p)
|
||||
#endif
|
||||
|
||||
#if !IG_ARCHIVE_HAS_RESPONSE
|
||||
static inline int ig_response_capture(const IGFinding *finding, void *ctx) {
|
||||
if (finding->status == IG_DETECTED) *(int *)ctx = finding->reason;
|
||||
return 0;
|
||||
}
|
||||
static inline void ig_response_handle(IGStatus status, int reason) {
|
||||
(void)status;
|
||||
(void)reason;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* 仅混淆常量,不作为秘密。SDK GOT/Lazy 槽由 dyld 在独立镜像滑移后绑定。 */
|
||||
static const unsigned char names[IG_ARCHIVE_FUNCTION_COUNT][6] = {
|
||||
{0x5a,0x53,0x4c,0x59,0x52},
|
||||
{0x5a,0x4e,0x59,0x5d,0x58},
|
||||
{0x5a,0x4b,0x4e,0x55,0x48,0x59},
|
||||
{0x5a,0x5f,0x50,0x53,0x4f,0x59},
|
||||
{0x49,0x52,0x50,0x55,0x52,0x57},
|
||||
{0x53,0x4c,0x59,0x52},
|
||||
{0x4e,0x59,0x5d,0x58},
|
||||
{0x4b,0x4e,0x55,0x48,0x59},
|
||||
{0x5f,0x50,0x53,0x4f,0x59},
|
||||
{0x5b,0x59,0x48,0x4c,0x55,0x58},
|
||||
{0x59,0x44,0x55,0x48},
|
||||
{0x5a,0x53,0x4e,0x57},
|
||||
{0x58,0x50,0x53,0x4c,0x59,0x52},
|
||||
{0x58,0x50,0x4f,0x45,0x51}
|
||||
};
|
||||
static const uint8_t name_lengths[IG_ARCHIVE_FUNCTION_COUNT] = {
|
||||
5, 5, 6, 6, 6, 4, 4, 5, 5, 6, 4, 4, 6, 5
|
||||
};
|
||||
|
||||
enum { IG_ARCHIVE_MAX_SLOTS = 1024 };
|
||||
typedef struct {
|
||||
uintptr_t slot_addr;
|
||||
uintptr_t expected_fn;
|
||||
uintptr_t text_lo;
|
||||
uintptr_t text_hi;
|
||||
uint8_t is_lazy;
|
||||
} IGArchiveSlot;
|
||||
|
||||
static pthread_once_t once = PTHREAD_ONCE_INIT;
|
||||
static _Thread_local int resolving;
|
||||
static _Atomic(uintptr_t) targets[IG_ARCHIVE_FUNCTION_COUNT];
|
||||
static uintptr_t expected[IG_ARCHIVE_FUNCTION_COUNT];
|
||||
static size_t prefix_lengths[IG_ARCHIVE_FUNCTION_COUNT];
|
||||
static unsigned char prefixes[IG_ARCHIVE_FUNCTION_COUNT][16];
|
||||
static IGStatus initial[IG_ARCHIVE_FUNCTION_COUNT];
|
||||
static int initialReason[IG_ARCHIVE_FUNCTION_COUNT];
|
||||
static IGArchiveSlot trackedSlots[IG_ARCHIVE_MAX_SLOTS];
|
||||
static size_t trackedCount;
|
||||
static int bindingReady;
|
||||
|
||||
#ifdef IG_OBSERVATION
|
||||
static _Atomic(uint64_t) counters[IG_ARCHIVE_FUNCTION_COUNT * 3];
|
||||
#define COUNT(i, k) atomic_fetch_add_explicit(&counters[(i)*3+(k)], 1, memory_order_relaxed)
|
||||
#else
|
||||
#define COUNT(i, k) ((void)0)
|
||||
#endif
|
||||
|
||||
static int read_bytes(uintptr_t address, void *out, size_t size) {
|
||||
vm_size_t copied = 0;
|
||||
return vm_read_overwrite(mach_task_self(), address, size, (vm_address_t)out, &copied) == KERN_SUCCESS
|
||||
&& copied == size;
|
||||
}
|
||||
|
||||
static int is_system_image(const char *path) {
|
||||
if (!path) return 0;
|
||||
return ig_strncmp(path, "/usr/lib/", 9) == 0 ||
|
||||
ig_strncmp(path, "/System/", 8) == 0 ||
|
||||
ig_strncmp(path, "/private/preboot/Cryptexes/", 27) == 0;
|
||||
}
|
||||
|
||||
static int has_suffix(const char *path, const char *suffix) {
|
||||
if (!path || !suffix) return 0;
|
||||
size_t len = ig_strlen(path), tail = ig_strlen(suffix);
|
||||
return len >= tail && ig_strcmp(path + len - tail, suffix) == 0;
|
||||
}
|
||||
|
||||
static uintptr_t expected_wrapper_for_symbol(const char *name) {
|
||||
struct { const char *sym; uintptr_t fn; } table[] = {
|
||||
{"_rd_a0", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_a0)},
|
||||
{"_rd_f", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_f)},
|
||||
{"_rd_a1", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_a1)},
|
||||
{"_rd_a2", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_a2)},
|
||||
{"_rd_a3", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_a3)},
|
||||
{"_rd_a4", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_a4)},
|
||||
{"_rd_u00", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_u00)},
|
||||
{"_rd_o", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_o)},
|
||||
{"_rdo", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rdo)},
|
||||
{"_rd_r", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_r)},
|
||||
{"_rdr", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rdr)},
|
||||
{"_rd_w0", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_w0)},
|
||||
{"_rd_w", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_w)},
|
||||
{"_rd_c0", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_c0)},
|
||||
{"_rd_c", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_c)},
|
||||
{"_rd_p00", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_p00)},
|
||||
{"_rd_p0", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_p0)},
|
||||
{"_rd_e", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_e)},
|
||||
{"_rd_k", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_k)},
|
||||
{"_rd_l00", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_l00)},
|
||||
{"_rd_s0", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_s0)},
|
||||
{"_rd_s", (uintptr_t)IG_ARCHIVE_STRIP((const void *)&rd_s)},
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i++) {
|
||||
if (ig_strcmp(name, table[i].sym) == 0) return table[i].fn;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 扫描所有已加载非系统动态库的非认证 arm64 GOT/Lazy 槽;缺槽或表结构异常标为不可验证。 */
|
||||
static int locate_bindings(void) {
|
||||
trackedCount = 0;
|
||||
uint32_t image_total = _dyld_image_count();
|
||||
for (uint32_t index = 0; index < image_total; index++) {
|
||||
const char *path = _dyld_get_image_name(index);
|
||||
if (!path || is_system_image(path) || has_suffix(path, "/RDCoreIO.framework/RDCoreIO")) continue;
|
||||
const struct mach_header_64 *header = (const void *)_dyld_get_image_header(index);
|
||||
if (!header || header->magic != MH_MAGIC_64 || header->filetype != MH_DYLIB) continue;
|
||||
if (header->cputype != CPU_TYPE_ARM64 || (header->cpusubtype & 0xffffff) == 2) return 0;
|
||||
uintptr_t slide = (uintptr_t)_dyld_get_image_vmaddr_slide(index);
|
||||
const struct segment_command_64 *linkedit = NULL, *text_seg = NULL;
|
||||
const struct symtab_command *symtab = NULL;
|
||||
const struct dysymtab_command *dysymtab = NULL;
|
||||
const uint8_t *command = (const void *)(header + 1);
|
||||
const uint8_t *end = command + header->sizeofcmds;
|
||||
for (uint32_t i = 0; i < header->ncmds; i++) {
|
||||
if (command + sizeof(struct load_command) > end) return 0;
|
||||
const struct load_command *lc = (const void *)command;
|
||||
if (lc->cmdsize < 8 || lc->cmdsize % 8 || lc->cmdsize > (size_t)(end - command)) return 0;
|
||||
if (lc->cmd == LC_SEGMENT_64) {
|
||||
if (lc->cmdsize < sizeof(struct segment_command_64)) return 0;
|
||||
const struct segment_command_64 *seg = (const void *)lc;
|
||||
if (sizeof(*seg) + (uint64_t)seg->nsects * sizeof(struct section_64) != lc->cmdsize) return 0;
|
||||
if (!ig_strcmp(seg->segname, SEG_LINKEDIT)) linkedit = seg;
|
||||
else if (!ig_strcmp(seg->segname, SEG_TEXT)) text_seg = seg;
|
||||
} else if (lc->cmd == LC_SYMTAB && lc->cmdsize == sizeof(*symtab)) symtab = (const void *)lc;
|
||||
else if (lc->cmd == LC_DYSYMTAB && lc->cmdsize == sizeof(*dysymtab)) dysymtab = (const void *)lc;
|
||||
command += lc->cmdsize;
|
||||
}
|
||||
if (!linkedit || !text_seg || !symtab || !dysymtab || command != end) continue;
|
||||
uint64_t lo = linkedit->fileoff, hi = lo + linkedit->filesize;
|
||||
if (hi < lo || symtab->symoff < lo || (uint64_t)symtab->symoff + (uint64_t)symtab->nsyms * 16 > hi
|
||||
|| symtab->stroff < lo || (uint64_t)symtab->stroff + symtab->strsize > hi
|
||||
|| dysymtab->indirectsymoff < lo
|
||||
|| (uint64_t)dysymtab->indirectsymoff + (uint64_t)dysymtab->nindirectsyms * 4 > hi) return 0;
|
||||
uintptr_t base = slide + (uintptr_t)(linkedit->vmaddr - lo);
|
||||
uintptr_t text_lo = slide + (uintptr_t)text_seg->vmaddr;
|
||||
uintptr_t text_hi = text_lo + (uintptr_t)text_seg->vmsize;
|
||||
const struct nlist_64 *symbols = (const void *)(base + symtab->symoff);
|
||||
const char *strings = (const void *)(base + symtab->stroff);
|
||||
const uint32_t *indirect = (const void *)(base + dysymtab->indirectsymoff);
|
||||
command = (const void *)(header + 1);
|
||||
for (uint32_t i = 0; i < header->ncmds; i++) {
|
||||
const struct load_command *lc = (const void *)command;
|
||||
if (lc->cmd == LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg = (const void *)lc;
|
||||
const struct section_64 *sections = (const void *)(seg + 1);
|
||||
for (uint32_t j = 0; j < seg->nsects; j++) {
|
||||
const struct section_64 *s = sections + j;
|
||||
uint32_t stype = s->flags & SECTION_TYPE;
|
||||
if (stype != S_NON_LAZY_SYMBOL_POINTERS && stype != S_LAZY_SYMBOL_POINTERS) continue;
|
||||
if (s->size % 8 || (uint64_t)s->reserved1 + s->size / 8 > dysymtab->nindirectsyms) return 0;
|
||||
for (uint64_t k = 0; k < s->size / 8; k++) {
|
||||
uint32_t symbol = indirect[s->reserved1 + k];
|
||||
if (symbol & (INDIRECT_SYMBOL_LOCAL | INDIRECT_SYMBOL_ABS)) continue;
|
||||
if (symbol >= symtab->nsyms) return 0;
|
||||
uint32_t strx = symbols[symbol].n_un.n_strx;
|
||||
if (strx >= symtab->strsize) return 0;
|
||||
const char *name = strings + strx;
|
||||
if (!memchr(name, 0, symtab->strsize - strx)) return 0;
|
||||
uintptr_t expected_fn = expected_wrapper_for_symbol(name);
|
||||
if (!expected_fn) continue;
|
||||
if (trackedCount >= IG_ARCHIVE_MAX_SLOTS) return 0;
|
||||
uintptr_t slot_addr = slide + (uintptr_t)s->addr + (uintptr_t)(k * 8);
|
||||
uintptr_t probe = 0;
|
||||
if (!read_bytes(slot_addr, &probe, sizeof(probe))) return 0;
|
||||
trackedSlots[trackedCount++] = (IGArchiveSlot){
|
||||
.slot_addr = slot_addr,
|
||||
.expected_fn = expected_fn,
|
||||
.text_lo = text_lo,
|
||||
.text_hi = text_hi,
|
||||
.is_lazy = (uint8_t)(stype == S_LAZY_SYMBOL_POINTERS)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
command += lc->cmdsize;
|
||||
}
|
||||
}
|
||||
return trackedCount > 0;
|
||||
}
|
||||
|
||||
static void initialize(void) {
|
||||
bindingReady = locate_bindings();
|
||||
for (unsigned i = 0; i < IG_ARCHIVE_FUNCTION_COUNT; i++) {
|
||||
IGResolveResult result = ig_resolve_verified(NULL, names[i], name_lengths[i], ig_response_capture, &initialReason[i]);
|
||||
initial[i] = result.status;
|
||||
if (result.status != IG_CLEAR || !result.address) continue;
|
||||
prefix_lengths[i] = ig_function_prefix_size(result.address, sizeof(prefixes[i]));
|
||||
if (!prefix_lengths[i] || !read_bytes((uintptr_t)IG_ARCHIVE_STRIP(result.address), prefixes[i], prefix_lengths[i])) {
|
||||
initial[i] = IG_UNAVAILABLE;
|
||||
continue;
|
||||
}
|
||||
expected[i] = (uintptr_t)result.address;
|
||||
atomic_store_explicit(&targets[i], expected[i], memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
static int prepare(void) {
|
||||
if (resolving) return 0;
|
||||
resolving = 1;
|
||||
int result = pthread_once(&once, initialize);
|
||||
resolving = 0;
|
||||
return result == 0;
|
||||
}
|
||||
|
||||
__attribute__((constructor))
|
||||
static void ig_archive_warmup(void) {
|
||||
(void)prepare();
|
||||
}
|
||||
|
||||
static IGStatus validate(unsigned index, uintptr_t *address, int *reason) {
|
||||
*reason = initialReason[index];
|
||||
if (initial[index] != IG_CLEAR) return initial[index];
|
||||
*reason = 107;
|
||||
uintptr_t current = atomic_load_explicit(&targets[index], memory_order_acquire);
|
||||
if (!current || current != expected[index]) return IG_DETECTED;
|
||||
unsigned char bytes[16];
|
||||
if (!read_bytes((uintptr_t)IG_ARCHIVE_STRIP((const void *)current), bytes, prefix_lengths[index])) return IG_UNAVAILABLE;
|
||||
if (ig_memcmp(bytes, prefixes[index], prefix_lengths[index])) return IG_DETECTED;
|
||||
*reason = IG_REASON_VERIFICATION_UNAVAILABLE;
|
||||
IGStatus status = ig_verify_function((void *)current, IG_DIAG_STR("archive-target"), ig_response_capture, reason);
|
||||
if (status != IG_CLEAR) return status;
|
||||
*address = current;
|
||||
return IG_CLEAR;
|
||||
}
|
||||
|
||||
static IGStatus check_bindings(void) {
|
||||
#ifdef IG_ARCHIVE_TESTING
|
||||
/* 宿主 ABI fixture 不装载外部动态 SDK;此豁免不能编入业务包。 */
|
||||
return IG_CLEAR;
|
||||
#else
|
||||
if (!bindingReady || trackedCount == 0) return IG_UNAVAILABLE;
|
||||
for (size_t i = 0; i < trackedCount; i++) {
|
||||
const IGArchiveSlot *slot = &trackedSlots[i];
|
||||
uintptr_t raw = *(const volatile uintptr_t *)slot->slot_addr;
|
||||
uintptr_t cur = (uintptr_t)IG_ARCHIVE_STRIP((const void *)raw);
|
||||
if (cur == slot->expected_fn) continue;
|
||||
if (slot->is_lazy && cur >= slot->text_lo && cur < slot->text_hi) continue;
|
||||
return IG_DETECTED;
|
||||
}
|
||||
return IG_CLEAR;
|
||||
#endif
|
||||
}
|
||||
|
||||
__attribute__((noinline))
|
||||
static uintptr_t checked(unsigned index) {
|
||||
COUNT(index, 0);
|
||||
if (!prepare()) { COUNT(index, 2); errno = EDEADLK; return 0; }
|
||||
uintptr_t address = 0;
|
||||
int reason = 107;
|
||||
IGStatus status = check_bindings();
|
||||
if (status == IG_CLEAR) status = validate(index, &address, &reason);
|
||||
if (status != IG_CLEAR) {
|
||||
COUNT(index, 2);
|
||||
ig_response_handle(status, reason);
|
||||
errno = status == IG_DETECTED ? EACCES : ENOSYS;
|
||||
return 0;
|
||||
}
|
||||
COUNT(index, 1);
|
||||
return address;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) FILE *rd_a0(const char *path, const char *mode) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(0);
|
||||
if (!address) return NULL;
|
||||
errno = incoming;
|
||||
return ((FILE *(*)(const char *, const char *))address)(path, mode);
|
||||
}
|
||||
__attribute__((noinline)) FILE *rd_f(const char *path, const char *mode) {
|
||||
return rd_a0(path, mode);
|
||||
}
|
||||
__attribute__((noinline)) size_t rd_a1(void *ptr, size_t size, size_t count, FILE *stream) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(1);
|
||||
if (!address) return 0;
|
||||
errno = incoming;
|
||||
return ((size_t (*)(void *, size_t, size_t, FILE *))address)(ptr, size, count, stream);
|
||||
}
|
||||
__attribute__((noinline)) size_t rd_a2(const void *ptr, size_t size, size_t count, FILE *stream) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(2);
|
||||
if (!address) return 0;
|
||||
errno = incoming;
|
||||
return ((size_t (*)(const void *, size_t, size_t, FILE *))address)(ptr, size, count, stream);
|
||||
}
|
||||
__attribute__((noinline)) int rd_a3(FILE *stream) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(3);
|
||||
if (!address) return EOF;
|
||||
errno = incoming;
|
||||
return ((int (*)(FILE *))address)(stream);
|
||||
}
|
||||
__attribute__((noinline)) int rd_a4(const char *path) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(4);
|
||||
if (!address) return -1;
|
||||
errno = incoming;
|
||||
return ((int (*)(const char *))address)(path);
|
||||
}
|
||||
__attribute__((noinline)) int rd_u00(const char *path) {
|
||||
return rd_a4(path);
|
||||
}
|
||||
|
||||
static int ig_open_impl(const char *path, int flags, int mode) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(5);
|
||||
if (!address) return -1;
|
||||
errno = incoming;
|
||||
int (*fn)(const char *, int, ...) = (void *)address;
|
||||
return (flags & O_CREAT) ? fn(path, flags, mode) : fn(path, flags);
|
||||
}
|
||||
__attribute__((noinline)) int rd_o(const char *path, int flags, ...) {
|
||||
int mode = 0;
|
||||
if (flags & O_CREAT) {
|
||||
va_list args;
|
||||
va_start(args, flags);
|
||||
mode = va_arg(args, int);
|
||||
va_end(args);
|
||||
}
|
||||
return ig_open_impl(path, flags, mode);
|
||||
}
|
||||
__attribute__((noinline)) int rdo(const char *path, int flags, ...) {
|
||||
int mode = 0;
|
||||
if (flags & O_CREAT) {
|
||||
va_list args;
|
||||
va_start(args, flags);
|
||||
mode = va_arg(args, int);
|
||||
va_end(args);
|
||||
}
|
||||
return ig_open_impl(path, flags, mode);
|
||||
}
|
||||
|
||||
__attribute__((noinline)) ssize_t rd_r(int fd, void *buffer, size_t count) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(6);
|
||||
if (!address) return -1;
|
||||
errno = incoming;
|
||||
return ((ssize_t (*)(int, void *, size_t))address)(fd, buffer, count);
|
||||
}
|
||||
__attribute__((noinline)) ssize_t rdr(int fd, void *buffer, size_t count) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(6);
|
||||
if (!address) return -1;
|
||||
errno = incoming;
|
||||
return ((ssize_t (*)(int, void *, size_t))address)(fd, buffer, count);
|
||||
}
|
||||
__attribute__((noinline)) ssize_t rd_w0(int fd, const void *buffer, size_t count) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(7);
|
||||
if (!address) return -1;
|
||||
errno = incoming;
|
||||
return ((ssize_t (*)(int, const void *, size_t))address)(fd, buffer, count);
|
||||
}
|
||||
__attribute__((noinline)) ssize_t rd_w(int fd, const void *buffer, size_t count) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(7);
|
||||
if (!address) return -1;
|
||||
errno = incoming;
|
||||
return ((ssize_t (*)(int, const void *, size_t))address)(fd, buffer, count);
|
||||
}
|
||||
__attribute__((noinline)) int rd_c0(int fd) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(8);
|
||||
if (!address) return -1;
|
||||
errno = incoming;
|
||||
return ((int (*)(int))address)(fd);
|
||||
}
|
||||
__attribute__((noinline)) int rd_c(int fd) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(8);
|
||||
if (!address) return -1;
|
||||
errno = incoming;
|
||||
return ((int (*)(int))address)(fd);
|
||||
}
|
||||
__attribute__((noinline)) pid_t rd_p00(void) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(9);
|
||||
if (!address) return (pid_t)-1;
|
||||
errno = incoming;
|
||||
return ((pid_t (*)(void))address)();
|
||||
}
|
||||
__attribute__((noinline)) pid_t rd_p0(void) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(9);
|
||||
if (!address) return (pid_t)-1;
|
||||
errno = incoming;
|
||||
return ((pid_t (*)(void))address)();
|
||||
}
|
||||
__attribute__((noinline, noreturn)) void rd_e(int status) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(10);
|
||||
if (address) {
|
||||
errno = incoming;
|
||||
((void (*)(int))address)(status);
|
||||
}
|
||||
_exit(status);
|
||||
__builtin_trap();
|
||||
}
|
||||
__attribute__((noinline)) pid_t rd_k(void) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(11);
|
||||
if (!address) return (pid_t)-1;
|
||||
errno = incoming;
|
||||
return ((pid_t (*)(void))address)();
|
||||
}
|
||||
__attribute__((noinline)) void *rd_l00(const char *path, int mode) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(12);
|
||||
if (!address) return NULL;
|
||||
errno = incoming;
|
||||
return ((void *(*)(const char *, int))address)(path, mode);
|
||||
}
|
||||
__attribute__((noinline)) void *rd_s0(void *handle, const char *symbol) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(13);
|
||||
if (!address) return NULL;
|
||||
errno = incoming;
|
||||
return ((void *(*)(void *, const char *))address)(handle, symbol);
|
||||
}
|
||||
__attribute__((noinline)) void *rd_s(void *handle, const char *symbol) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(13);
|
||||
if (!address) return NULL;
|
||||
errno = incoming;
|
||||
return ((void *(*)(void *, const char *))address)(handle, symbol);
|
||||
}
|
||||
|
||||
/* 返回具体原因,避免把启动时的跳转形态启发式误升级为已确认篡改。 */
|
||||
int rd_io_ev(void) {
|
||||
int incoming = errno, result = 0;
|
||||
if (!prepare()) { errno = incoming; return -1; }
|
||||
IGStatus binding = check_bindings();
|
||||
if (binding == IG_DETECTED) result = 107;
|
||||
else if (binding == IG_UNAVAILABLE) result = -1;
|
||||
for (unsigned i = 0; i < IG_ARCHIVE_FUNCTION_COUNT; i++) {
|
||||
uintptr_t address;
|
||||
int reason;
|
||||
IGStatus current = validate(i, &address, &reason);
|
||||
if (current == IG_DETECTED) {
|
||||
if (reason == 100 || reason == 107) result = reason;
|
||||
else if (result <= 0) result = 101;
|
||||
} else if (current == IG_UNAVAILABLE && result == 0) result = -1;
|
||||
}
|
||||
errno = incoming;
|
||||
return result;
|
||||
}
|
||||
|
||||
int rd_io_chk(void) {
|
||||
int result = rd_io_ev();
|
||||
return result > 0 ? 1 : result;
|
||||
}
|
||||
|
||||
void rd_io_cfg(int enabled, int fd) {
|
||||
#if IG_ARCHIVE_HAS_RESPONSE
|
||||
ig_response_configure(enabled, fd);
|
||||
#else
|
||||
(void)enabled;
|
||||
(void)fd;
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef IG_OBSERVATION
|
||||
uint64_t ig_archive_counter(unsigned index) {
|
||||
return index < IG_ARCHIVE_FUNCTION_COUNT * 3
|
||||
? atomic_load_explicit(&counters[index], memory_order_relaxed) : 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef IG_ARCHIVE_TESTING
|
||||
void ig_archive_test_override(unsigned index, void *address) {
|
||||
if (index < IG_ARCHIVE_FUNCTION_COUNT && prepare())
|
||||
atomic_store_explicit(&targets[index], (uintptr_t)address, memory_order_release);
|
||||
}
|
||||
void ig_archive_test_reentry(int enabled) { resolving = enabled; }
|
||||
#endif
|
||||
@@ -0,0 +1,73 @@
|
||||
#ifndef IG_ARCHIVE_GUARD_H
|
||||
#define IG_ARCHIVE_GUARD_H
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
enum { IG_ARCHIVE_FUNCTION_COUNT = 14 };
|
||||
#define IG_ARCHIVE_EXPORT __attribute__((visibility("default")))
|
||||
|
||||
IG_ARCHIVE_EXPORT FILE *rd_a0(const char *path, const char *mode);
|
||||
IG_ARCHIVE_EXPORT FILE *rd_f(const char *path, const char *mode);
|
||||
IG_ARCHIVE_EXPORT size_t rd_a1(void *ptr, size_t size, size_t count, FILE *stream);
|
||||
IG_ARCHIVE_EXPORT size_t rd_a2(const void *ptr, size_t size, size_t count, FILE *stream);
|
||||
IG_ARCHIVE_EXPORT int rd_a3(FILE *stream);
|
||||
IG_ARCHIVE_EXPORT int rd_a4(const char *path);
|
||||
IG_ARCHIVE_EXPORT int rd_u00(const char *path);
|
||||
IG_ARCHIVE_EXPORT int rd_o(const char *path, int flags, ...);
|
||||
IG_ARCHIVE_EXPORT int rdo(const char *path, int flags, ...);
|
||||
IG_ARCHIVE_EXPORT ssize_t rd_r(int fd, void *buffer, size_t count);
|
||||
IG_ARCHIVE_EXPORT ssize_t rdr(int fd, void *buffer, size_t count);
|
||||
IG_ARCHIVE_EXPORT ssize_t rd_w0(int fd, const void *buffer, size_t count);
|
||||
IG_ARCHIVE_EXPORT ssize_t rd_w(int fd, const void *buffer, size_t count);
|
||||
IG_ARCHIVE_EXPORT int rd_c0(int fd);
|
||||
IG_ARCHIVE_EXPORT int rd_c(int fd);
|
||||
IG_ARCHIVE_EXPORT pid_t rd_p00(void);
|
||||
IG_ARCHIVE_EXPORT pid_t rd_p0(void);
|
||||
IG_ARCHIVE_EXPORT __attribute__((noreturn)) void rd_e(int status);
|
||||
IG_ARCHIVE_EXPORT pid_t rd_k(void);
|
||||
IG_ARCHIVE_EXPORT void *rd_l00(const char *path, int mode);
|
||||
IG_ARCHIVE_EXPORT void *rd_s0(void *handle, const char *symbol);
|
||||
IG_ARCHIVE_EXPORT void *rd_s(void *handle, const char *symbol);
|
||||
|
||||
/* 0=正常,1=检测异常,-1=不可验证;保留 errno。 */
|
||||
IG_ARCHIVE_EXPORT void rd_io_cfg(int enabled, int fd);
|
||||
IG_ARCHIVE_EXPORT int rd_io_chk(void);
|
||||
/* 0=正常,-1=不可用,正值=具体原因;101 为启发式,不触发退出。 */
|
||||
IG_ARCHIVE_EXPORT int rd_io_ev(void);
|
||||
#ifdef IG_OBSERVATION
|
||||
/* index/3 为函数,index%3 为 attempted/dispatched/rejected。 */
|
||||
IG_ARCHIVE_EXPORT uint64_t ig_archive_counter(unsigned index);
|
||||
#endif
|
||||
#ifdef IG_ARCHIVE_TESTING
|
||||
void ig_archive_test_override(unsigned index, void *address);
|
||||
void ig_archive_test_reentry(int enabled);
|
||||
#endif
|
||||
|
||||
#ifndef IG_ARCHIVE_IMPL
|
||||
#define ig_a0 rd_a0
|
||||
#define ig_f rd_f
|
||||
#define ig_a1 rd_a1
|
||||
#define ig_a2 rd_a2
|
||||
#define ig_a3 rd_a3
|
||||
#define ig_a4 rd_a4
|
||||
#define ig_u00 rd_u00
|
||||
#define ig_o rd_o
|
||||
#define igo rdo
|
||||
#define ig_r rd_r
|
||||
#define igr rdr
|
||||
#define ig_w0 rd_w0
|
||||
#define ig_w rd_w
|
||||
#define ig_c0 rd_c0
|
||||
#define ig_c rd_c
|
||||
#define ig_p00 rd_p00
|
||||
#define ig_p0 rd_p0
|
||||
#define ig_e rd_e
|
||||
#define ig_k rd_k
|
||||
#define ig_l00 rd_l00
|
||||
#define ig_s0 rd_s0
|
||||
#define ig_s rd_s
|
||||
#define ig_archive_response_configure rd_io_cfg
|
||||
#define ig_archive_check rd_io_chk
|
||||
#define ig_archive_assess rd_io_ev
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,283 @@
|
||||
#include "IGDispatch.h"
|
||||
#include "../resolve/IGResolve.h"
|
||||
#include "../anti_hook/IGAntiHook.h"
|
||||
#include "../primitives/IGInline.h"
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdarg.h>
|
||||
#include <unistd.h>
|
||||
#include <mach/mach.h>
|
||||
|
||||
/* 编码只减少常量区明文,不作为秘密或强加密。缓存与基线仍可被同进程攻击者修改。 */
|
||||
enum { IG_DISPATCH_COUNT = 11 };
|
||||
static const unsigned char kNames[IG_DISPATCH_COUNT][6] = {
|
||||
{0x4b,0x4e,0x55,0x48,0x59},
|
||||
{0x5f,0x50,0x53,0x4f,0x59},
|
||||
{0x4e,0x59,0x5d,0x58},
|
||||
{0x53,0x4c,0x59,0x52},
|
||||
{0x49,0x52,0x50,0x55,0x52,0x57},
|
||||
{0x5b,0x59,0x48,0x4c,0x55,0x58},
|
||||
{0x5a,0x53,0x4c,0x59,0x52},
|
||||
{0x59,0x44,0x55,0x48},
|
||||
{0x5a,0x53,0x4e,0x57},
|
||||
{0x58,0x50,0x53,0x4c,0x59,0x52},
|
||||
{0x58,0x50,0x4f,0x45,0x51},
|
||||
};
|
||||
static const size_t kLengths[IG_DISPATCH_COUNT] = {5,5,4,4,6,6,5,4,4,6,5};
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
static const char *const kLabels[IG_DISPATCH_COUNT] = {
|
||||
"dispatch-write", "dispatch-close", "dispatch-read",
|
||||
"dispatch-open", "dispatch-unlink", "dispatch-getpid", "dispatch-fopen",
|
||||
"dispatch-exit", "dispatch-fork", "dispatch-dlopen", "dispatch-dlsym"
|
||||
};
|
||||
#endif
|
||||
static pthread_once_t gOnce=PTHREAD_ONCE_INIT;
|
||||
static _Atomic(uintptr_t) gSlots[IG_DISPATCH_COUNT];
|
||||
static uintptr_t gExpected[IG_DISPATCH_COUNT];
|
||||
static unsigned char gPrefixes[IG_DISPATCH_COUNT][16];
|
||||
static size_t gPrefixLengths[IG_DISPATCH_COUNT];
|
||||
static IGStatus gInitialStatus[IG_DISPATCH_COUNT];
|
||||
static _Thread_local int gResolving;
|
||||
#ifdef IG_OBSERVATION
|
||||
static _Atomic(uint64_t) gAttempted[IG_DISPATCH_COUNT], gDispatched[IG_DISPATCH_COUNT];
|
||||
#define IG_COUNT(slot,index) atomic_fetch_add_explicit(&(slot)[index],1,memory_order_relaxed)
|
||||
#else
|
||||
#define IG_COUNT(slot,index) ((void)0)
|
||||
#endif
|
||||
|
||||
static int read_prefix(uintptr_t address, unsigned char out[16], size_t len) {
|
||||
vm_size_t copied=0;
|
||||
return len && vm_read_overwrite(mach_task_self(),address,len,(vm_address_t)out,&copied)==KERN_SUCCESS
|
||||
&& copied==len;
|
||||
}
|
||||
|
||||
static void initialize(void) {
|
||||
for (unsigned i=0;i<IG_DISPATCH_COUNT;i++) {
|
||||
IGResolveResult r=ig_resolve_verified(NULL,kNames[i],kLengths[i],NULL,NULL);
|
||||
gInitialStatus[i]=r.status;
|
||||
if (r.status!=IG_CLEAR || !r.address) continue;
|
||||
uintptr_t address=(uintptr_t)r.address;
|
||||
gPrefixLengths[i]=ig_function_prefix_size(r.address,sizeof(gPrefixes[i]));
|
||||
if (!read_prefix(address,gPrefixes[i],gPrefixLengths[i])) { gInitialStatus[i]=IG_UNAVAILABLE; continue; }
|
||||
gExpected[i]=address;
|
||||
atomic_store_explicit(&gSlots[i],address,memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
static int prepare(void) {
|
||||
/* dlsym/装载初始化过程中若重入受保护入口,拒绝而不是等待自身 once 锁。 */
|
||||
if (gResolving) return 0;
|
||||
gResolving=1;
|
||||
int rc=pthread_once(&gOnce,initialize);
|
||||
gResolving=0;
|
||||
return rc==0;
|
||||
}
|
||||
|
||||
static IGStatus validate(unsigned i, uintptr_t *address, int *reason) {
|
||||
if (gInitialStatus[i]!=IG_CLEAR) {
|
||||
*reason=IG_REASON_DISPATCH_UNAVAILABLE;
|
||||
return gInitialStatus[i];
|
||||
}
|
||||
uintptr_t current=atomic_load_explicit(&gSlots[i],memory_order_acquire);
|
||||
if (!current || current!=gExpected[i]) {
|
||||
*reason=IG_REASON_DISPATCH_TAMPER;
|
||||
return IG_DETECTED;
|
||||
}
|
||||
IGStatus status=ig_verify_function((void *)current,IG_DIAG_STR("dispatch-target"),NULL,NULL);
|
||||
if (status!=IG_CLEAR) {
|
||||
*reason=status==IG_DETECTED ? IG_REASON_INLINE_HOOK : IG_REASON_VERIFICATION_UNAVAILABLE;
|
||||
return status;
|
||||
}
|
||||
unsigned char bytes[16];
|
||||
if (!read_prefix(current,bytes,gPrefixLengths[i])) {
|
||||
*reason=IG_REASON_VERIFICATION_UNAVAILABLE;
|
||||
return IG_UNAVAILABLE;
|
||||
}
|
||||
if (ig_memcmp(bytes,gPrefixes[i],gPrefixLengths[i])!=0) {
|
||||
*reason=IG_REASON_DISPATCH_TAMPER;
|
||||
return IG_DETECTED;
|
||||
}
|
||||
*address=current;
|
||||
return IG_CLEAR;
|
||||
}
|
||||
|
||||
__attribute__((noinline))
|
||||
static uintptr_t checked_address(unsigned i) {
|
||||
if (!prepare()) { errno=EDEADLK; return 0; }
|
||||
uintptr_t address=0; int reason=0;
|
||||
IGStatus status=validate(i,&address,&reason);
|
||||
if (status!=IG_CLEAR) { errno=status==IG_DETECTED ? EACCES : ENOSYS; return 0; }
|
||||
return address;
|
||||
}
|
||||
|
||||
__attribute__((constructor))
|
||||
static void ig_dispatch_warmup(void) {
|
||||
(void)prepare();
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
ssize_t IG_dispatch_write(int fd, const void *buffer, size_t count) {
|
||||
int incoming=errno;
|
||||
IG_COUNT(gAttempted,0);
|
||||
uintptr_t address=checked_address(0);
|
||||
if (!address) return -1;
|
||||
IG_COUNT(gDispatched,0);
|
||||
errno=incoming;
|
||||
ssize_t (*function)(int,const void *,size_t)=(void *)address;
|
||||
return function(fd,buffer,count);
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
int IG_dispatch_close(int fd) {
|
||||
int incoming=errno;
|
||||
IG_COUNT(gAttempted,1);
|
||||
uintptr_t address=checked_address(1);
|
||||
if (!address) return -1;
|
||||
IG_COUNT(gDispatched,1);
|
||||
errno=incoming;
|
||||
int (*function)(int)=(void *)address;
|
||||
return function(fd);
|
||||
}
|
||||
|
||||
/* Each typed entry preserves libc results and errno; no retry or short-I/O loop.
|
||||
* Not async-signal-safe: validation uses pthread_once/dlsym/Mach APIs. */
|
||||
__attribute__((used,noinline))
|
||||
ssize_t IG_dispatch_read(int fd, void *buffer, size_t count) {
|
||||
int incoming=errno;
|
||||
uintptr_t address=checked_address(2);
|
||||
if (!address) return -1;
|
||||
errno=incoming;
|
||||
ssize_t (*function)(int,void *,size_t)=(void *)address;
|
||||
return function(fd,buffer,count);
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
int IG_dispatch_open(const char *path, int flags, ...) {
|
||||
int incoming=errno;
|
||||
/* Darwin mode_t is promoted to int in the variadic argument list.
|
||||
* Do not read a nonexistent third argument for ordinary two-argument open. */
|
||||
int mode=0;
|
||||
if (flags & O_CREAT) {
|
||||
va_list args; va_start(args,flags); mode=va_arg(args,int); va_end(args);
|
||||
}
|
||||
uintptr_t address=checked_address(3);
|
||||
if (!address) return -1;
|
||||
errno=incoming;
|
||||
int (*function)(const char *,int,...)=(void *)address;
|
||||
return (flags & O_CREAT) ? function(path,flags,mode) : function(path,flags);
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
int IG_dispatch_unlink(const char *path) {
|
||||
int incoming=errno;
|
||||
uintptr_t address=checked_address(4);
|
||||
if (!address) return -1;
|
||||
errno=incoming;
|
||||
int (*function)(const char *)=(void *)address;
|
||||
return function(path);
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
pid_t IG_dispatch_getpid(void) {
|
||||
int incoming=errno;
|
||||
uintptr_t address=checked_address(5);
|
||||
if (!address) return (pid_t)-1;
|
||||
errno=incoming;
|
||||
pid_t (*function)(void)=(void *)address;
|
||||
return function();
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
FILE *IG_dispatch_fopen(const char *path, const char *mode) {
|
||||
int incoming=errno;
|
||||
uintptr_t address=checked_address(6);
|
||||
if (!address) return NULL;
|
||||
errno=incoming;
|
||||
FILE *(*function)(const char *,const char *)=(void *)address;
|
||||
return function(path,mode);
|
||||
}
|
||||
|
||||
__attribute__((used,noinline,noreturn))
|
||||
void IG_dispatch_exit(int status) {
|
||||
int incoming=errno;
|
||||
uintptr_t address=checked_address(7);
|
||||
if (address) {
|
||||
errno=incoming;
|
||||
void (*function)(int)=(void *)address;
|
||||
function(status);
|
||||
}
|
||||
_exit(status);
|
||||
__builtin_trap();
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
pid_t IG_dispatch_fork(void) {
|
||||
int incoming=errno;
|
||||
uintptr_t address=checked_address(8);
|
||||
if (!address) return (pid_t)-1;
|
||||
errno=incoming;
|
||||
pid_t (*function)(void)=(void *)address;
|
||||
return function();
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
void *IG_dispatch_dlopen(const char *path, int mode) {
|
||||
int incoming=errno;
|
||||
uintptr_t address=checked_address(9);
|
||||
if (!address) return NULL;
|
||||
errno=incoming;
|
||||
void *(*function)(const char *,int)=(void *)address;
|
||||
return function(path,mode);
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
void *IG_dispatch_dlsym(void *handle, const char *symbol) {
|
||||
int incoming=errno;
|
||||
uintptr_t address=checked_address(10);
|
||||
if (!address) return NULL;
|
||||
errno=incoming;
|
||||
void *(*function)(void *,const char *)=(void *)address;
|
||||
return function(handle,symbol);
|
||||
}
|
||||
|
||||
int ig_dispatch_check(IGFindingSink sink, void *ctx) {
|
||||
int saved=errno, hits=0;
|
||||
int ready=prepare();
|
||||
for (unsigned i=0;i<IG_DISPATCH_COUNT;i++) {
|
||||
uintptr_t address=0; int reason=IG_REASON_DISPATCH_UNAVAILABLE;
|
||||
IGStatus status=ready ? validate(i,&address,&reason) : IG_UNAVAILABLE;
|
||||
if (status==IG_CLEAR) continue;
|
||||
IGFinding f={0}; f.status=status; f.reason=reason;
|
||||
#if IG_DIAGNOSTIC_STRINGS
|
||||
const char *label=kLabels[i];
|
||||
strncpy(f.subject,label,sizeof(f.subject)-1);
|
||||
strncpy(f.evidence,"调度地址、提供方或代码前缀校验未通过",sizeof(f.evidence)-1);
|
||||
#endif
|
||||
if (status==IG_DETECTED) hits++;
|
||||
if (sink && sink(&f,ctx)!=0) break;
|
||||
}
|
||||
errno=saved;
|
||||
return hits;
|
||||
}
|
||||
|
||||
#ifdef IG_OBSERVATION
|
||||
IGDispatchObservation ig_dispatch_observation(void) {
|
||||
IGDispatchObservation value={
|
||||
atomic_load_explicit(&gAttempted[0],memory_order_relaxed),
|
||||
atomic_load_explicit(&gDispatched[0],memory_order_relaxed),
|
||||
atomic_load_explicit(&gAttempted[1],memory_order_relaxed),
|
||||
atomic_load_explicit(&gDispatched[1],memory_order_relaxed)
|
||||
};
|
||||
return value;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef IG_DISPATCH_TESTING
|
||||
void ig_dispatch_test_override(unsigned i, void *address) {
|
||||
if (i<IG_DISPATCH_COUNT && prepare()) atomic_store_explicit(&gSlots[i],(uintptr_t)address,memory_order_release);
|
||||
}
|
||||
void ig_dispatch_test_reentry(int enabled) { gResolving=enabled; }
|
||||
#endif
|
||||
@@ -0,0 +1,47 @@
|
||||
#ifndef IG_DISPATCH_H
|
||||
#define IG_DISPATCH_H
|
||||
#include <sys/types.h>
|
||||
#include <stdio.h>
|
||||
#include "../include/IGDefender.h"
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 线程安全解析并缓存目标;每次调用前校验,失败不调用目标。
|
||||
* 检查依赖 pthread/dlsym/Mach,不可用于异步信号处理器或 fork 后的子进程。
|
||||
* 仅供逐调用点接入,不能作为全局 libc interpose 实现。 */
|
||||
ssize_t IG_dispatch_write(int fd, const void *buffer, size_t count);
|
||||
int IG_dispatch_close(int fd);
|
||||
/* Only redirect reviewed ordinary call sites, never signal handlers or post-fork
|
||||
* child paths. getpid returns -1 with errno if validation fails (unlike libc).
|
||||
* These declarations do not automatically redirect existing IPA imports. */
|
||||
ssize_t IG_dispatch_read(int fd, void *buffer, size_t count);
|
||||
int IG_dispatch_open(const char *path, int flags, ...);
|
||||
int IG_dispatch_unlink(const char *path);
|
||||
pid_t IG_dispatch_getpid(void);
|
||||
FILE *IG_dispatch_fopen(const char *path, const char *mode);
|
||||
__attribute__((noreturn)) void IG_dispatch_exit(int status);
|
||||
pid_t IG_dispatch_fork(void);
|
||||
void *IG_dispatch_dlopen(const char *path, int mode);
|
||||
void *IG_dispatch_dlsym(void *handle, const char *symbol);
|
||||
int ig_dispatch_check(IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef IG_OBSERVATION
|
||||
/* 保留原 write/close 试点计数 ABI;新增入口不计入这四个字段。
|
||||
* 仅观察构建导出只读计数,不提供地址覆盖或关闭校验的接口。 */
|
||||
typedef struct {
|
||||
uint64_t write_attempted, write_dispatched;
|
||||
uint64_t close_attempted, close_dispatched;
|
||||
} IGDispatchObservation;
|
||||
IGDispatchObservation ig_dispatch_observation(void);
|
||||
#endif
|
||||
|
||||
#ifdef IG_DISPATCH_TESTING
|
||||
/* 只编入宿主测试,不允许在 App 发布包定义此宏。 */
|
||||
void ig_dispatch_test_override(unsigned index, void *address);
|
||||
void ig_dispatch_test_reentry(int enabled);
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* IGDefender.h — iOSGuard 运行时防护公共结果模型。
|
||||
*
|
||||
* 设计遵循 docs/05 §5.C:探针(probe)与处置(policy)分离。
|
||||
* 探针只采集证据并通过回调上报,绝不自行 exit/中断业务;是否限制功能由上层策略决定(观察模式优先)。
|
||||
* 状态三态 clear/detected/unavailable——unavailable(平台/架构不支持、数据缺失)不得当作安全。
|
||||
*
|
||||
* 纯 C,无 Objective-C / Swift 依赖,可直接编入任意 iOS target(也可在 macOS 宿主上编译自测)。
|
||||
*/
|
||||
#ifndef IG_DEFENDER_H
|
||||
#define IG_DEFENDER_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include "IGVisibility.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#if defined(DEBUG) || defined(IG_OBSERVATION)
|
||||
#define IG_DIAGNOSTIC_STRINGS 1
|
||||
#define IG_DIAG_STR(s) (s)
|
||||
#else
|
||||
#define IG_DIAGNOSTIC_STRINGS 0
|
||||
#define IG_DIAG_STR(s) ((const char *)0)
|
||||
#endif
|
||||
|
||||
typedef enum {
|
||||
IG_CLEAR = 0, /* 未发现异常证据 */
|
||||
IG_DETECTED = 1, /* 命中威胁证据 */
|
||||
IG_UNAVAILABLE = 2, /* 无法判定:架构/平台不支持或数据缺失——不得视为安全 */
|
||||
} IGStatus;
|
||||
|
||||
/* 原因码按模块分段:1xx = anti_hook,2xx = 注入/Frida。 */
|
||||
typedef enum {
|
||||
IG_REASON_NONE = 0,
|
||||
/* anti_hook */
|
||||
IG_REASON_SYMBOL_PROVENANCE = 100, /* 符号解析到非系统提供方(dyld interpose / 注入覆盖) */
|
||||
IG_REASON_INLINE_HOOK = 101, /* 关键函数序言被改写为跳转蹦床(Frida/Dobby inline hook) */
|
||||
IG_REASON_GOT_REBIND = 102, /* 自身镜像 GOT/符号指针槽被重绑定到非系统地址(fishhook 类) */
|
||||
IG_REASON_SYMBOL_UNRESOLVED = 103, /* dlsym 无法解析该符号(unavailable) */
|
||||
IG_REASON_VERIFICATION_UNAVAILABLE = 104, /* 提供方/代码页无法确认 */
|
||||
IG_REASON_DISPATCH_TAMPER = 105, /* 私有调度地址或初始化后的代码前缀变化 */
|
||||
IG_REASON_DISPATCH_UNAVAILABLE = 106, /* 调度入口无法安全使用 */
|
||||
/* 107 已分配:Swift 观察层 archive-dispatch 不可用(RDRuntimeDefender.swift),C 侧不占用 */
|
||||
IG_REASON_OBJC_IMP_CHANGED = 110, /* ObjC 关键方法 IMP 相对基线变化(swizzle/替换/函数体改写) */
|
||||
/* 注入 / Frida */
|
||||
IG_REASON_INJECTED_IMAGE = 200, /* 加载了已知注入/调试框架镜像(substrate/frida/cycript…) */
|
||||
IG_REASON_FOREIGN_IMAGE = 201, /* Bundle 外且非系统路径的镜像(弱信号,需结合其它证据) */
|
||||
IG_REASON_DYLD_INSERT = 202, /* DYLD_INSERT_LIBRARIES 指向 Bundle 外路径 */
|
||||
IG_REASON_FRIDA_THREAD = 203, /* 线程名命中 frida 运行时特征(gum-js-loop 等) */
|
||||
IG_REASON_FRIDA_PORT = 204, /* 默认 frida 端口可连接(弱信号) */
|
||||
/* anti_debug */
|
||||
IG_REASON_DEBUGGER_ATTACHED = 300, /* 直发 sysctl 检出 P_TRACED:进程被调试器跟踪 */
|
||||
/* anti_jailbreak(4xx)——均走 IGSyscall 直发 svc,绕过 libc 层对 stat/access 的 hook */
|
||||
IG_REASON_JAILBREAK_FILE = 400, /* 越狱特征文件/目录可访问(Cydia/Sileo/apt/substrate/var-jb…) */
|
||||
IG_REASON_JAILBREAK_SANDBOX = 401, /* 能在 App 沙盒外创建文件:沙盒逃逸=越狱强信号 */
|
||||
/* anti_tamper(5xx)——二进制完整性/防重打包。正面反制「脱壳解密+patch+重签」破解链,
|
||||
* 补 anti_hook 只盯固定函数之外的空洞。按构建上下文开关,dev/诊断构建不参与(UNAVAILABLE)。 */
|
||||
IG_REASON_BINARY_DECRYPTED = 500, /* 应加密的 App Store 包 cryptid==0 或 LC_ENCRYPTION_INFO 被剥除:脱壳/重打包强信号 */
|
||||
IG_REASON_CODESIGN_INVALID = 501, /* 代码签名异常:ad-hoc 重签 / 分发包却带 get-task-allow / CS_VALID 失效 */
|
||||
} IGReason;
|
||||
|
||||
typedef struct {
|
||||
IGStatus status; /* 本条发现的状态 */
|
||||
int reason; /* IGReason */
|
||||
char subject[128]; /* 受检对象:符号名 / 镜像路径 / 线程名 */
|
||||
char evidence[256];/* 证据详情:地址、提供方路径、端口等人读文本 */
|
||||
} IGFinding;
|
||||
|
||||
/*
|
||||
* 发现回调。探针对每条 DETECTED/UNAVAILABLE 证据调用一次(CLEAR 不上报,保持安静)。
|
||||
* sink 返回非 0 表示请求提前停止该探针的后续扫描;返回 0 继续。
|
||||
* ctx 由调用方透传(可用于计数、聚合、打点)。
|
||||
*/
|
||||
typedef int (*IGFindingSink)(const IGFinding *finding, void *ctx);
|
||||
|
||||
/*
|
||||
* 聚合入口:一次性运行 anti_hook(provenance/inline/GOT)+ 注入/Frida 全部探针。
|
||||
* bundle_path:App 主 bundle(.app)路径,用于 Bundle 外镜像/插入库判定;NULL 则跳过该判定。
|
||||
* probe_port:非 0 时才做 frida 端口弱探测(典型 27042);0 表示跳过。
|
||||
* 返回 DETECTED 证据总条数。本函数只采集不处置,绝不 exit。
|
||||
*/
|
||||
IG_PUBLIC int ig_defender_scan(const char *bundle_path, int probe_port,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_DEFENDER_H */
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* IGGuard.h — iOSGuard Defender 对外统一公共头(umbrella)。
|
||||
*
|
||||
* 接入方(如 readoor)只需在 bridging header 里 `#import "IGGuard.h"`,即可拿到:
|
||||
* - 结果模型:IGStatus / IGReason / IGFinding / IGFindingSink(见 IGDefender.h)
|
||||
* - 聚合扫描:ig_defender_scan(只采集证据,绝不处置)
|
||||
* - 策略层:ig_policy_scan_and_mark(扫描→分级→命中强信号组合则毒化,守误报底线)
|
||||
* - 毒化原语:ig_poison_init / ig_poison_apply(数据依赖处置,接到解密密钥派生)
|
||||
*
|
||||
* Header Search Paths 需同时包含 defender/ 与 defender/include/(IGGuard.h 内部按此相对路径引用)。
|
||||
* 典型用法见 docs/18_READOOR_DEFENDER_INTEGRATION.md。
|
||||
*/
|
||||
#ifndef IG_GUARD_H
|
||||
#define IG_GUARD_H
|
||||
|
||||
#include "IGDefender.h" /* IGStatus/IGReason/IGFinding/IGFindingSink + ig_defender_scan */
|
||||
#include "poison/IGPoison.h" /* ig_poison_init / ig_poison_mark / ig_poison_apply */
|
||||
#include "policy/IGPolicy.h" /* ig_policy_scan_and_mark / ig_policy_sink / IGPolicyState */
|
||||
|
||||
#endif /* IG_GUARD_H */
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* IGInline.h — 强制内联的自实现 str/mem 原语(落地方案第一优先级)。
|
||||
*
|
||||
* 目的:核心校验/鉴权/加解密逻辑里避免直接调用 strcmp/memcmp/memcpy/strstr/getenv 等
|
||||
* 被攻击者重点监控的 libc 函数——这些调用会在 __la_symbol_ptr/__got 留下符号引用,
|
||||
* 既是 Fishhook rebind 的靶点,也是静态分析的锚点。
|
||||
*
|
||||
* 本头提供 __attribute__((always_inline)) 版本:使用处直接展开为离散汇编指令,
|
||||
* 不生成 bl 跳转、不产生导入表项,从而从导入表中抹除这些符号。
|
||||
*
|
||||
* 用法:在安全逻辑中用 ig_memcmp/ig_strcmp/... 替换 libc 同名函数。纯头文件,零依赖。
|
||||
* 注意:这是“隐藏特征”,非“更安全的实现”——不做常量时间比较;需防时序侧信道时另行处理。
|
||||
*/
|
||||
#ifndef IG_INLINE_H
|
||||
#define IG_INLINE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define IG_AINLINE static inline __attribute__((always_inline))
|
||||
|
||||
IG_AINLINE size_t ig_strlen(const char *s) {
|
||||
const char *p = s;
|
||||
while (*p) ++p;
|
||||
return (size_t)(p - s);
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_memcmp(const void *a, const void *b, size_t n) {
|
||||
const unsigned char *x = (const unsigned char *)a;
|
||||
const unsigned char *y = (const unsigned char *)b;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (x[i] != y[i]) return (int)x[i] - (int)y[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
IG_AINLINE void *ig_memcpy(void *dst, const void *src, size_t n) {
|
||||
unsigned char *d = (unsigned char *)dst;
|
||||
const unsigned char *s = (const unsigned char *)src;
|
||||
for (size_t i = 0; i < n; ++i) d[i] = s[i];
|
||||
return dst;
|
||||
}
|
||||
|
||||
IG_AINLINE void *ig_memset(void *dst, int c, size_t n) {
|
||||
unsigned char *d = (unsigned char *)dst;
|
||||
for (size_t i = 0; i < n; ++i) d[i] = (unsigned char)c;
|
||||
return dst;
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_strcmp(const char *a, const char *b) {
|
||||
while (*a && (*a == *b)) { ++a; ++b; }
|
||||
return (int)(unsigned char)*a - (int)(unsigned char)*b;
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_strncmp(const char *a, const char *b, size_t n) {
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
unsigned char ca = (unsigned char)a[i], cb = (unsigned char)b[i];
|
||||
if (ca != cb) return (int)ca - (int)cb;
|
||||
if (ca == 0) break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 朴素子串匹配,避免引用 libc strstr。 */
|
||||
IG_AINLINE const char *ig_strstr(const char *hay, const char *needle) {
|
||||
if (!needle[0]) return hay;
|
||||
for (; *hay; ++hay) {
|
||||
const char *h = hay, *n = needle;
|
||||
while (*h && *n && (*h == *n)) { ++h; ++n; }
|
||||
if (!*n) return hay;
|
||||
}
|
||||
return (const char *)0;
|
||||
}
|
||||
|
||||
#endif /* IG_INLINE_H */
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* IGVisibility.h — 符号可见性控制(抗静态调用关系分析,§7 硬化)。
|
||||
*
|
||||
* 背景:静态库 .a 里所有全局函数默认都是导出符号(nm 显示 T),接入方链进 App 后,
|
||||
* 若不 strip,_ig_poison_mark / _ig_poison_mask / _ig_policy_* 等**内部**符号名
|
||||
* 会留在符号表,成为「nm 一把定位 → 找调用点 → NOP」的锚点。
|
||||
*
|
||||
* 策略:
|
||||
* - 整个 defender 库用 -fvisibility=hidden 编译:默认所有符号隐藏(private extern)。
|
||||
* - 只有接入方跨 bridging header 真正引用的入口用 IG_PUBLIC 显式导出:
|
||||
* ig_defender_scan / ig_policy_scan_and_mark / ig_poison_init / ig_poison_apply。
|
||||
* - 其余(mark/mask/sink/reset/evaluate/anti_jb_* 及各探针内部)保持 hidden,
|
||||
* 最终 App 链接 + strip 后从符号表消失,nm 再也捞不到名字。
|
||||
*
|
||||
* 边界(如实声明):
|
||||
* - 这不消除调用图的「边」(bl 仍在),只抹掉「节点的名字」——把定位成本从
|
||||
* 「nm 一把」抬到「靠交叉引用 + 语义猜」。真正删边要靠内联(apply 揉进解密)
|
||||
* 与间接化调用点,见 docs/18 §7。
|
||||
* - 在 .a 阶段 hidden 符号仍可能以 private-extern 出现在**静态**符号表(nm 无 -g);
|
||||
* 决定性的一步是最终镜像 strip。故接入方必须保持 Release 的 strip(见 docs/18 §7.0)。
|
||||
*/
|
||||
#ifndef IG_VISIBILITY_H
|
||||
#define IG_VISIBILITY_H
|
||||
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
#define IG_PUBLIC __attribute__((visibility("default")))
|
||||
#define IG_INTERNAL __attribute__((visibility("hidden")))
|
||||
/*
|
||||
* IG_ALWAYS_INLINE:强制内联。用于「删调用图的边」——把毒化读取/应用的核心做成
|
||||
* always_inline,接入方在解密 TU 内联后反汇编里不留 `bl ig_poison_*` 调用边可 NOP。
|
||||
* 见 defender/poison/IGPoisonInline.h 与 docs/18 §7。
|
||||
*/
|
||||
#define IG_ALWAYS_INLINE static inline __attribute__((always_inline))
|
||||
#else
|
||||
#define IG_PUBLIC
|
||||
#define IG_INTERNAL
|
||||
#define IG_ALWAYS_INLINE static inline
|
||||
#endif
|
||||
|
||||
#endif /* IG_VISIBILITY_H */
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* IGPoison.c — 毒化状态机实现。见 IGPoison.h 的设计与边界声明。
|
||||
*
|
||||
* 本文件只负责:① 定义跨 TU 共享的匿名状态存储 ig_pstate[];② 写入侧(init/mark,
|
||||
* 由检测线程调用,不在解密热路径);③ out-of-line 公共入口 ig_poison_mask/apply。
|
||||
* 读取/应用的**算术核心**(baseline / lane_k / spread / mask / apply)统一来自
|
||||
* IGPoisonInline.h —— **单一真源**,库路径与接入方内联路径永不漂移。
|
||||
*
|
||||
* §7 硬化(已落地):
|
||||
* - §7.4 基线运行期派生(见 IGPoisonInline.h ig_pbaseline_inline,不明文驻留)。
|
||||
* - §7.2 匿名数组分散存储(无命名 section——命名 section 会留在 load command、strip 抹不掉,
|
||||
* 等于挂牌毒化副本位置;见 IGPoisonInline.h 顶部说明)。
|
||||
* - §7「断边」:apply/mask 核心做成 always_inline,接入方在解密 TU 内联后不留
|
||||
* `bl ig_poison_*` 调用边;推荐用 ig_poison_mix_key_inline 把毒化揉进 key schedule。
|
||||
*
|
||||
* §7 硬化(仍 TODO,需额外工具链,见 docs/18 §7.3):
|
||||
* - mark / mask / apply 用 OLLVM(Fla+BCF) + 常量加密盖住;预留 IG_OBFUSCATOR 钩子。
|
||||
*/
|
||||
#include "IGPoison.h"
|
||||
#include "poison/IGPoisonInline.h"
|
||||
|
||||
/*
|
||||
* §7.2 分散存储:一个看起来普通的匿名状态数组。跨 TU 共享(接入方内联 mask/apply 时直读),
|
||||
* 故为非 static 的 hidden 全局(中性名、无 poison 字样,strip 后无符号名)。
|
||||
* 进程级(非 TLS)——毒化态须跨线程一致:检测线程 mark 后解密线程读到的掩码必须同为非零,
|
||||
* TLS 会各线程各看各的、破坏处置闭环,故**刻意不用 TLS**。下标/长度定义在 IGPoisonInline.h。
|
||||
*/
|
||||
volatile uint64_t ig_pstate[IG_PSTATE_N];
|
||||
|
||||
void ig_poison_init(void) {
|
||||
uint64_t b = ig_pbaseline_inline();
|
||||
/* 全数组都填成「健康值」表示 (b ^ lane_k(i)):真副本、诱饵、陪衬槽写法一致,
|
||||
* 各槽值互不相同,静态看不出哪几槽是喂掩码的真副本。 */
|
||||
for (unsigned i = 0; i < IG_PSTATE_N; ++i) {
|
||||
ig_pstate[i] = b ^ ig_plane_k_inline(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* 构造期兜底初始化(若宿主未显式调用 ig_poison_init)。 */
|
||||
__attribute__((constructor))
|
||||
static void ig_poison_ctor(void) { ig_poison_init(); }
|
||||
|
||||
void ig_poison_mark(uint64_t entropy) {
|
||||
/* entropy 为 0 时仍强制非 0,避免“混入 0 = 不生效”。写入侧不内联:由检测线程调用,
|
||||
* 不在解密热路径,无需删边。 */
|
||||
uint64_t e = entropy ? entropy : 0xD1B54A32D192ED03ULL;
|
||||
/* 三路真副本各自偏离健康值(任一偏离即令掩码非零);诱饵也动,混淆“哪几槽生效”。 */
|
||||
ig_pstate[IG_PSTATE_L0] ^= ig_pspread_inline(e, 0);
|
||||
ig_pstate[IG_PSTATE_DECOY] ^= ig_pspread_inline(e, 3);
|
||||
ig_pstate[IG_PSTATE_L1] ^= ig_pspread_inline(e, 1);
|
||||
ig_pstate[IG_PSTATE_L2] ^= ig_pspread_inline(e, 2);
|
||||
}
|
||||
|
||||
/*
|
||||
* out-of-line 公共入口:直接委托给单一真源的内联核心。
|
||||
* 接入方若想删掉对这两个函数的调用边,改 #include "IGPoisonInline.h" 调用
|
||||
* ig_poison_mask_inline / ig_poison_mix_key_inline(见 docs/18 §7)。
|
||||
*/
|
||||
uint64_t ig_poison_mask(void) {
|
||||
return ig_poison_mask_inline();
|
||||
}
|
||||
|
||||
void ig_poison_apply(const uint8_t *in, uint8_t *out, size_t n) {
|
||||
ig_poison_apply_inline(in, out, n);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* IGPoison.h — 毒化状态机(数据依赖处置,纯 C,可编入业务 target)。
|
||||
*
|
||||
* 设计核心(对应纯客户端反 Hook 的处置哲学):
|
||||
* 不写 `if (越狱) exit()`。检测到强信号组合时,只把一段熵混进一个多副本冗余的
|
||||
* “健康值”,把它破坏掉;之后由业务关键数据的**密钥派生**消费这个健康值——
|
||||
* 健康 → 掩码为 0 → 密钥不变 → 解密正常;毒化 → 掩码非 0 → 密钥被扰动 → 解出乱码。
|
||||
* 全程**没有可被 patch 的控制流分支**,攻击者 nop 不掉“判断”,因为判断不存在,
|
||||
* 只有数据流污染。要绕过得逆向整条密钥推导 + 搞清健康值怎么混入,成本量级抬高。
|
||||
*
|
||||
* 天花板(如实声明):纯客户端无法根治。多副本 + 混淆 + VMP 只是把“找到并写回健康值”
|
||||
* 从几分钟抬到几天;有耐心有能力的定向攻击者最终仍可破。安全锚点不在这。
|
||||
*
|
||||
* 处置形态(App Store 上架约束):只做数据污染 / 功能静默降级,不触发随机崩溃。
|
||||
*
|
||||
* 误报底线(极重要):处置是隐蔽且体验不可逆的,误伤一个非越狱正常用户=差评卸载且难排查。
|
||||
* 因此 ig_poison_mark 只允许由**高置信强信号组合**触发(见 IGPoison.c 注释),
|
||||
* 弱信号(FOREIGN_IMAGE / FRIDA_PORT 等)绝不参与。上线前必须在多机型验证非越狱零毒化。
|
||||
*/
|
||||
#ifndef IG_POISON_H
|
||||
#define IG_POISON_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include "IGVisibility.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 把多副本健康值置为基线。应在尽早的构造期调用一次(也有构造函数兜底)。 */
|
||||
IG_PUBLIC void ig_poison_init(void);
|
||||
|
||||
/*
|
||||
* 命中强信号组合时调用:把 entropy(必须非 0)混进所有健康值副本,使其偏离基线。
|
||||
* 幂等累积——多次调用只会持续偏离,不会“洗白”。此函数只写状态,不产生任何可见后果。
|
||||
*/
|
||||
void ig_poison_mark(uint64_t entropy);
|
||||
|
||||
/*
|
||||
* 返回处置掩码:健康=0,毒化=非 0(由多副本交叉推导,无分支)。
|
||||
* 业务侧不直接判它,而是把它揉进密钥/偏移等数据,见 ig_poison_apply。
|
||||
*/
|
||||
uint64_t ig_poison_mask(void);
|
||||
|
||||
/*
|
||||
* 数据依赖处置原语:把 in[0..n) 揉以当前掩码写入 out[0..n)(允许 in==out 原地)。
|
||||
* 健康时 out 与 in 逐字节相等(掩码 0,异或 0);毒化时每字节被掩码扰动。
|
||||
* 业务用法:对解密 key 的字节调用本函数后再传给解密器——健康照常、毒化解出乱码。
|
||||
*
|
||||
* 【断边】本函数是一条可被 NOP 的调用边(`bl ig_poison_apply`)。要删掉这条边,
|
||||
* 接入方改 #include "IGPoisonInline.h",在解密 TU 内直接调用 always_inline 的
|
||||
* ig_poison_mix_key_inline(key, n)——编译器把毒化揉进解密函数自身,反汇编里不留调用边,
|
||||
* 且毒化落在 key schedule(比后置改输出更难摘)。两条路径共用同一真源,语义等价。见 docs/18 §7。
|
||||
*/
|
||||
IG_PUBLIC void ig_poison_apply(const uint8_t *in, uint8_t *out, size_t n);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_POISON_H */
|
||||
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* IGPoisonInline.h — 毒化「读取/应用」核心(always_inline,单一真源)。
|
||||
*
|
||||
* 为什么存在(docs/18 §7「断边」):
|
||||
* 符号隐藏只抹掉节点名字,调用图的边(`bl ig_poison_apply` / `bl ig_poison_mask`)
|
||||
* 仍在——攻击者靠交叉引用定位到这条边,NOP 掉调用、或把被调函数 stub 成恒等,毒化即失效。
|
||||
* 本头把「读健康值 → 推掩码 → 扰动密钥」整段做成 always_inline:接入方(readoor 解密 TU)
|
||||
* #include 后在密钥派生处调用 ig_poison_mix_key_inline(),编译器把这段揉进解密函数自身,
|
||||
* 反汇编里**没有这条调用边**可 NOP,毒化藏进 key schedule,与真实密钥推导混在一起。
|
||||
*
|
||||
* 单一真源:库内 IGPoison.c 的 out-of-line 公共入口(ig_poison_mask/apply)也复用本头的
|
||||
* core,baseline / lane_k / 下标只此一处定义,内联路径与库路径永不漂移。
|
||||
*
|
||||
* 跨 TU 唯一共享的是「数据」ig_pstate[](中性名匿名数组,hidden,最终 strip 后无符号名),
|
||||
* 不是「调用边」——读它是 data 重定位,不是 call。即便漏 strip,名字也不含 poison 字样、不 telegraph。
|
||||
*
|
||||
* 注意:写入侧(init / mark)不在本头内联——它们由检测线程调用、不在解密热路径,
|
||||
* 无需删边,留在 IGPoison.c。本头只内联**读取/应用**侧。
|
||||
*/
|
||||
#ifndef IG_POISON_INLINE_H
|
||||
#define IG_POISON_INLINE_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include "IGVisibility.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 匿名状态数组长度与真副本/诱饵下标(非相邻)。写入侧(IGPoison.c)须与此一致。 */
|
||||
#define IG_PSTATE_N 12
|
||||
#define IG_PSTATE_L0 2u
|
||||
#define IG_PSTATE_L1 7u
|
||||
#define IG_PSTATE_L2 11u
|
||||
#define IG_PSTATE_DECOY 5u
|
||||
|
||||
/* 存储定义在 IGPoison.c。hidden + 中性名:最终 strip 后无符号名,漏 strip 也不 telegraph。 */
|
||||
__attribute__((visibility("hidden")))
|
||||
extern volatile uint64_t ig_pstate[IG_PSTATE_N];
|
||||
|
||||
/* 基线运行期派生(与 IGPoison.c 删除的 IG_POISON_BASELINE 魔数等价,但不明文驻留)。 */
|
||||
IG_ALWAYS_INLINE uint64_t ig_pbaseline_inline(void) {
|
||||
volatile uint64_t seed = 0x243F6A88ULL; /* 分片种子,非最终值 */
|
||||
uint64_t x = (uint64_t)seed;
|
||||
x ^= 0x85A308D3ULL;
|
||||
x *= 0xFF51AFD7ED558CCDULL;
|
||||
x ^= x >> 33;
|
||||
x += 0x2545F4914F6CDD1DULL;
|
||||
x ^= x >> 29;
|
||||
return x | 1ULL; /* 保证非零 */
|
||||
}
|
||||
|
||||
/* per-槽掩码常量:使各槽健康值互不相同,消除「数组里几个相同的字=一组健康值」的 tell。 */
|
||||
IG_ALWAYS_INLINE uint64_t ig_plane_k_inline(unsigned i) {
|
||||
return 0x9E3779B97F4A7C15ULL * (uint64_t)(i * 2u + 1u);
|
||||
}
|
||||
|
||||
/* 把 entropy 扩散成每路互不相同、必非 0 的偏移(写入侧用;放这里供单一真源)。 */
|
||||
IG_ALWAYS_INLINE uint64_t ig_pspread_inline(uint64_t e, unsigned lane) {
|
||||
e ^= 0x9E3779B97F4A7C15ULL * (lane + 1u);
|
||||
e ^= e >> 30; e *= 0xBF58476D1CE4E5B9ULL;
|
||||
e ^= e >> 27; e *= 0x94D049BB133111EBULL;
|
||||
e ^= e >> 31;
|
||||
return e | 1ULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* 掩码核心:健康=0,毒化=非 0,无分支。只读三真副本(诱饵/陪衬槽不读)。
|
||||
* 健康态每真副本存 (baseline ^ lane_k(i)),解回 ^lane_k ^baseline == 0。
|
||||
*/
|
||||
IG_ALWAYS_INLINE uint64_t ig_poison_mask_inline(void) {
|
||||
uint64_t b = ig_pbaseline_inline();
|
||||
return (ig_pstate[IG_PSTATE_L0] ^ ig_plane_k_inline(IG_PSTATE_L0) ^ b)
|
||||
| (ig_pstate[IG_PSTATE_L1] ^ ig_plane_k_inline(IG_PSTATE_L1) ^ b)
|
||||
| (ig_pstate[IG_PSTATE_L2] ^ ig_plane_k_inline(IG_PSTATE_L2) ^ b);
|
||||
}
|
||||
|
||||
/*
|
||||
* 应用核心(等价 ig_poison_apply):健康 out==in(异或 0),毒化逐字节被掩码扰动。
|
||||
* 允许 in==out 原地。
|
||||
*/
|
||||
IG_ALWAYS_INLINE void ig_poison_apply_inline(const uint8_t *in, uint8_t *out, size_t n) {
|
||||
if (!in || !out) return;
|
||||
uint64_t m = ig_poison_mask_inline();
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
uint8_t d = (uint8_t)((m >> ((i & 7u) * 8u)) & 0xFFu);
|
||||
out[i] = (uint8_t)(in[i] ^ d);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 推荐接入形态:把掩码揉进密钥字节(原地)。健康 → 密钥不变 → 解密正常;
|
||||
* 毒化 → 密钥被扰动 → 解出乱码。比后置改输出更难摘:毒化落在 key schedule,
|
||||
* 攻击者要在不破坏正常解密的前提下摘掉它,得先逆清整条密钥推导。
|
||||
* 用法:在解密 TU 取得明文密钥后、喂给解密器前,对 key 调用一次。
|
||||
*/
|
||||
IG_ALWAYS_INLINE void ig_poison_mix_key_inline(uint8_t *key, size_t n) {
|
||||
ig_poison_apply_inline(key, key, n);
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_POISON_INLINE_H */
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* IGPolicy.c — 策略层实现。见 .h 的分级与误报底线。
|
||||
*/
|
||||
#include "IGPolicy.h"
|
||||
#include "poison/IGPoison.h"
|
||||
|
||||
typedef enum { IG_TIER_IGNORE = 0, IG_TIER_WEAK, IG_TIER_MEDIUM, IG_TIER_STRONG } IGTier;
|
||||
|
||||
/* reason → 档位。未列出的 DETECTED 按 WEAK 处理(保守,不触发毒化)。 */
|
||||
static IGTier ig_reason_tier(int reason) {
|
||||
switch (reason) {
|
||||
/* STRONG:单条即可判定(误报概率极低) */
|
||||
case IG_REASON_JAILBREAK_SANDBOX: /* 401 沙盒逃逸 */
|
||||
case IG_REASON_JAILBREAK_FILE: /* 400 越狱特征文件 */
|
||||
case IG_REASON_GOT_REBIND: /* 102 */
|
||||
case IG_REASON_INLINE_HOOK: /* 101 */
|
||||
case IG_REASON_INJECTED_IMAGE: /* 200 */
|
||||
case IG_REASON_DEBUGGER_ATTACHED: /* 300 */
|
||||
return IG_TIER_STRONG;
|
||||
/* MEDIUM:需组合(含合法 swizzling 会误报的 ObjC IMP) */
|
||||
case IG_REASON_SYMBOL_PROVENANCE: /* 100 */
|
||||
case IG_REASON_OBJC_IMP_CHANGED: /* 110 */
|
||||
case IG_REASON_FRIDA_THREAD: /* 203 */
|
||||
return IG_TIER_MEDIUM;
|
||||
/* WEAK:仅观察,永不触发毒化 */
|
||||
case IG_REASON_FOREIGN_IMAGE: /* 201 */
|
||||
case IG_REASON_FRIDA_PORT: /* 204 */
|
||||
return IG_TIER_WEAK;
|
||||
default:
|
||||
return IG_TIER_WEAK;
|
||||
}
|
||||
}
|
||||
|
||||
void ig_policy_reset(IGPolicyState *st, IGFindingSink observer, void *observer_ctx) {
|
||||
if (!st) return;
|
||||
st->strong_count = 0;
|
||||
st->medium_bitmap = 0;
|
||||
st->medium_distinct = 0;
|
||||
st->entropy = 0;
|
||||
st->detected_total = 0;
|
||||
st->observer = observer;
|
||||
st->observer_ctx = observer_ctx;
|
||||
}
|
||||
|
||||
/* 把 reason 映射到 medium_bitmap 的一个位(三个 MEDIUM reason 分别占位)。 */
|
||||
static uint32_t ig_medium_bit(int reason) {
|
||||
switch (reason) {
|
||||
case IG_REASON_SYMBOL_PROVENANCE: return 1u << 0;
|
||||
case IG_REASON_OBJC_IMP_CHANGED: return 1u << 1;
|
||||
case IG_REASON_FRIDA_THREAD: return 1u << 2;
|
||||
default: return 0u;
|
||||
}
|
||||
}
|
||||
|
||||
int ig_policy_sink(const IGFinding *f, void *ctx) {
|
||||
IGPolicyState *st = (IGPolicyState *)ctx;
|
||||
if (!st || !f) return 0;
|
||||
|
||||
/* 先转发观察打点(无论档位),便于量化误报面。 */
|
||||
if (st->observer) st->observer(f, st->observer_ctx);
|
||||
|
||||
/* 误报底线:只有 DETECTED 参与判定;UNAVAILABLE/CLEAR 忽略。 */
|
||||
if (f->status != IG_DETECTED) return 0;
|
||||
st->detected_total++;
|
||||
|
||||
IGTier tier = ig_reason_tier(f->reason);
|
||||
if (tier == IG_TIER_STRONG) {
|
||||
st->strong_count++;
|
||||
st->entropy ^= 0x100000001b3ULL * (uint64_t)(f->reason + 1);
|
||||
} else if (tier == IG_TIER_MEDIUM) {
|
||||
uint32_t bit = ig_medium_bit(f->reason);
|
||||
if (bit && !(st->medium_bitmap & bit)) {
|
||||
st->medium_bitmap |= bit;
|
||||
st->medium_distinct++;
|
||||
}
|
||||
st->entropy ^= 0x100000001b3ULL * (uint64_t)(f->reason + 1);
|
||||
}
|
||||
/* WEAK/IGNORE:不计入判定,也不进熵。 */
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ig_policy_evaluate_and_mark(IGPolicyState *st) {
|
||||
if (!st) return 0;
|
||||
int trigger = (st->strong_count >= 1) || (st->medium_distinct >= 2);
|
||||
if (trigger) {
|
||||
uint64_t e = st->entropy ? st->entropy : 0xA24BAED4963EE407ULL;
|
||||
ig_poison_mark(e);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ig_policy_scan_and_mark(const char *bundle_path, int probe_port,
|
||||
IGFindingSink observer, void *observer_ctx) {
|
||||
IGPolicyState st;
|
||||
ig_policy_reset(&st, observer, observer_ctx);
|
||||
ig_defender_scan(bundle_path, probe_port, ig_policy_sink, &st);
|
||||
return ig_policy_evaluate_and_mark(&st);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* IGPolicy.h — 策略层:把探针证据按强弱分级,组合判定后决定是否毒化(ig_poison_mark)。
|
||||
*
|
||||
* 连接 [[iosguard-disposition-strategy]]:ig_defender_scan 流式上报 IGFinding,本层做 sink,
|
||||
* 累积一次扫描的全部 DETECTED 证据;扫描结束后 evaluate 按组合规则决定是否触发毒化。
|
||||
*
|
||||
* 误报底线(最重要):毒化隐蔽且不可逆,误伤非越狱正常用户=差评卸载难排查。故:
|
||||
* - 只有 DETECTED 参与;UNAVAILABLE(架构/平台不支持)与 CLEAR 一律忽略,绝不当攻击。
|
||||
* - 信号分三档:
|
||||
* STRONG(单条即判定):越狱文件/沙盒逃逸、GOT 重绑、inline hook、注入镜像、调试器跟踪。
|
||||
* MEDIUM(需 ≥2 个不同 MEDIUM,或与任一 STRONG 同现才判定):符号提供方、ObjC IMP 变化、
|
||||
* frida 线程——其中 ObjC IMP 合法 swizzling 会误报,故不单条定罪。
|
||||
* WEAK(永不触发毒化,仅观察):Bundle 外镜像、frida 端口等弱证据。
|
||||
*
|
||||
* 本层不自行 exit;唯一处置是数据依赖毒化。可选把 finding 转发给观察打点(observer)。
|
||||
*/
|
||||
#ifndef IG_POLICY_H
|
||||
#define IG_POLICY_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
int strong_count; /* STRONG 档命中条数 */
|
||||
uint32_t medium_bitmap; /* MEDIUM 档已命中的不同 reason(去重用) */
|
||||
int medium_distinct; /* MEDIUM 档不同 reason 数 */
|
||||
uint64_t entropy; /* 命中 reason 聚合出的毒化熵(非 0) */
|
||||
int detected_total; /* 累计 DETECTED 条数(观察用) */
|
||||
IGFindingSink observer; /* 可选:每条 finding 透传给它做打点;NULL 跳过 */
|
||||
void *observer_ctx; /* observer 的上下文 */
|
||||
} IGPolicyState;
|
||||
|
||||
/* 重置状态;observer/observer_ctx 可传 NULL。 */
|
||||
void ig_policy_reset(IGPolicyState *st, IGFindingSink observer, void *observer_ctx);
|
||||
|
||||
/* 作为 ig_defender_scan 的 sink:ctx 必须是 IGPolicyState*。只累积、不处置。 */
|
||||
int ig_policy_sink(const IGFinding *finding, void *ctx);
|
||||
|
||||
/*
|
||||
* 扫描结束后调用:按组合规则判定。满足即 ig_poison_mark(entropy) 并返回 1;否则返回 0。
|
||||
* 规则:strong_count>=1 || medium_distinct>=2。
|
||||
*/
|
||||
int ig_policy_evaluate_and_mark(IGPolicyState *st);
|
||||
|
||||
/*
|
||||
* 便捷封装:reset → ig_defender_scan → evaluate_and_mark 一次完成。
|
||||
* 返回 1 表示本次触发了毒化。observer/observer_ctx 可 NULL。
|
||||
*/
|
||||
IG_PUBLIC int ig_policy_scan_and_mark(const char *bundle_path, int probe_port,
|
||||
IGFindingSink observer, void *observer_ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_POLICY_H */
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* IGInline.h — 强制内联的自实现 str/mem 原语(落地方案第一优先级)。
|
||||
*
|
||||
* 目的:核心校验/鉴权/加解密逻辑里避免直接调用 strcmp/memcmp/memcpy/strstr/getenv 等
|
||||
* 被攻击者重点监控的 libc 函数——这些调用会在 __la_symbol_ptr/__got 留下符号引用,
|
||||
* 既是 Fishhook rebind 的靶点,也是静态分析的锚点。
|
||||
*
|
||||
* 本头提供 __attribute__((always_inline)) 版本:使用处直接展开为离散汇编指令,
|
||||
* 不生成 bl 跳转、不产生导入表项,从而从导入表中抹除这些符号。
|
||||
*
|
||||
* 用法:在安全逻辑中用 ig_memcmp/ig_strcmp/... 替换 libc 同名函数。纯头文件,零依赖。
|
||||
* 注意:这是“隐藏特征”,非“更安全的实现”——不做常量时间比较;需防时序侧信道时另行处理。
|
||||
*/
|
||||
#ifndef IG_INLINE_H
|
||||
#define IG_INLINE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define IG_AINLINE static inline __attribute__((always_inline))
|
||||
|
||||
IG_AINLINE size_t ig_strlen(const char *s) {
|
||||
const char *p = s;
|
||||
while (*p) ++p;
|
||||
return (size_t)(p - s);
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_memcmp(const void *a, const void *b, size_t n) {
|
||||
const unsigned char *x = (const unsigned char *)a;
|
||||
const unsigned char *y = (const unsigned char *)b;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (x[i] != y[i]) return (int)x[i] - (int)y[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
IG_AINLINE void *ig_memcpy(void *dst, const void *src, size_t n) {
|
||||
unsigned char *d = (unsigned char *)dst;
|
||||
const unsigned char *s = (const unsigned char *)src;
|
||||
for (size_t i = 0; i < n; ++i) d[i] = s[i];
|
||||
return dst;
|
||||
}
|
||||
|
||||
IG_AINLINE void *ig_memset(void *dst, int c, size_t n) {
|
||||
unsigned char *d = (unsigned char *)dst;
|
||||
for (size_t i = 0; i < n; ++i) d[i] = (unsigned char)c;
|
||||
return dst;
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_strcmp(const char *a, const char *b) {
|
||||
while (*a && (*a == *b)) { ++a; ++b; }
|
||||
return (int)(unsigned char)*a - (int)(unsigned char)*b;
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_strncmp(const char *a, const char *b, size_t n) {
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
unsigned char ca = (unsigned char)a[i], cb = (unsigned char)b[i];
|
||||
if (ca != cb) return (int)ca - (int)cb;
|
||||
if (ca == 0) break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 朴素子串匹配,避免引用 libc strstr。 */
|
||||
IG_AINLINE const char *ig_strstr(const char *hay, const char *needle) {
|
||||
if (!needle[0]) return hay;
|
||||
for (; *hay; ++hay) {
|
||||
const char *h = hay, *n = needle;
|
||||
while (*h && *n && (*h == *n)) { ++h; ++n; }
|
||||
if (!*n) return hay;
|
||||
}
|
||||
return (const char *)0;
|
||||
}
|
||||
|
||||
#endif /* IG_INLINE_H */
|
||||
@@ -0,0 +1,273 @@
|
||||
/*
|
||||
* IGResolve.c — 加密名 + 无 dlsym Export Trie + 带校验的符号解析实现。
|
||||
*
|
||||
* 复用 IGAntiHook 的 ig_verify_function 做「放行前校验」:从 Mach-O Export Trie 解析地址后,
|
||||
* 必须 provenance(提供方系统路径)+ 序言(非 inline-hook 蹦床)双过,否则返回 NULL。
|
||||
*/
|
||||
#include "IGResolve.h"
|
||||
#include "../anti_hook/IGAntiHook.h"
|
||||
#include "../primitives/IGInline.h"
|
||||
|
||||
#include <crt_externs.h> /* _NSGetEnviron */
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
|
||||
#ifndef LC_DYLD_EXPORTS_TRIE
|
||||
#define LC_DYLD_EXPORTS_TRIE (0x33 | LC_REQ_DYLD)
|
||||
#endif
|
||||
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(ptrauth_calls)
|
||||
# include <ptrauth.h>
|
||||
# define IG_RESOLVE_SIGN_FN(p) ptrauth_sign_unauthenticated((p), ptrauth_key_asia, 0)
|
||||
# endif
|
||||
#endif
|
||||
#ifndef IG_RESOLVE_SIGN_FN
|
||||
# define IG_RESOLVE_SIGN_FN(p) (p)
|
||||
#endif
|
||||
|
||||
static int ig_is_system_image_path(const char *path) {
|
||||
if (!path) return 0;
|
||||
return ig_strncmp(path, "/usr/lib/", 9) == 0 ||
|
||||
ig_strncmp(path, "/System/", 8) == 0 ||
|
||||
ig_strncmp(path, "/private/preboot/Cryptexes/", 27) == 0;
|
||||
}
|
||||
|
||||
static int ig_ends_with(const char *str, const char *suffix) {
|
||||
if (!str || !suffix) return 0;
|
||||
size_t slen = ig_strlen(str), tlen = ig_strlen(suffix);
|
||||
return slen >= tlen && ig_strcmp(str + slen - tlen, suffix) == 0;
|
||||
}
|
||||
|
||||
static uint64_t ig_read_uleb128(const uint8_t **cursor, const uint8_t *end, int *ok) {
|
||||
uint64_t val = 0;
|
||||
int shift = 0;
|
||||
while (*cursor < end && shift < 64) {
|
||||
uint8_t byte = *(*cursor)++;
|
||||
val |= (uint64_t)(byte & 0x7fu) << shift;
|
||||
if (!(byte & 0x80u)) {
|
||||
*ok = 1;
|
||||
return val;
|
||||
}
|
||||
shift += 7;
|
||||
}
|
||||
*ok = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const uint8_t *ig_walk_export_trie(const uint8_t *start, const uint8_t *end, const char *sym) {
|
||||
const uint8_t *p = start;
|
||||
for (int step = 0; p < end && step < 512; ++step) {
|
||||
int ok = 0;
|
||||
uint64_t term_size = ig_read_uleb128(&p, end, &ok);
|
||||
if (!ok || term_size > (uint64_t)(end - p)) return NULL;
|
||||
if (*sym == '\0') return term_size ? p : NULL;
|
||||
const uint8_t *children = p + term_size;
|
||||
if (children >= end) return NULL;
|
||||
uint8_t count = *children++;
|
||||
p = children;
|
||||
int matched = 0;
|
||||
for (uint8_t i = 0; i < count; ++i) {
|
||||
const char *s = sym;
|
||||
const uint8_t *edge_start = p;
|
||||
while (p < end && *p != 0 && *s == (char)*p) {
|
||||
++p;
|
||||
++s;
|
||||
}
|
||||
if (p < end && *p == 0 && p != edge_start) {
|
||||
++p;
|
||||
uint64_t next_off = ig_read_uleb128(&p, end, &ok);
|
||||
if (!ok || next_off >= (uint64_t)(end - start)) return NULL;
|
||||
sym = s;
|
||||
p = start + next_off;
|
||||
matched = 1;
|
||||
break;
|
||||
}
|
||||
while (p < end && *p != 0) ++p;
|
||||
if (p >= end) return NULL;
|
||||
++p;
|
||||
(void)ig_read_uleb128(&p, end, &ok);
|
||||
if (!ok) return NULL;
|
||||
}
|
||||
if (!matched) return NULL;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void *ig_lookup_concrete_export(const struct mach_header_64 *mh, intptr_t slide, const char *macho_sym) {
|
||||
if (!mh || mh->magic != MH_MAGIC_64) return NULL;
|
||||
const struct segment_command_64 *linkedit = NULL;
|
||||
uint32_t trie_off = 0, trie_size = 0;
|
||||
const uint8_t *cmd = (const uint8_t *)(mh + 1);
|
||||
const uint8_t *end_cmds = cmd + mh->sizeofcmds;
|
||||
for (uint32_t i = 0; i < mh->ncmds; ++i) {
|
||||
if (cmd + sizeof(struct load_command) > end_cmds) return NULL;
|
||||
const struct load_command *lc = (const struct load_command *)cmd;
|
||||
if (lc->cmdsize < 8 || lc->cmdsize % 8 || cmd + lc->cmdsize > end_cmds) return NULL;
|
||||
if (lc->cmd == LC_SEGMENT_64 && lc->cmdsize >= sizeof(struct segment_command_64)) {
|
||||
const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;
|
||||
if (ig_strcmp(seg->segname, SEG_LINKEDIT) == 0) linkedit = seg;
|
||||
} else if (lc->cmd == LC_DYLD_EXPORTS_TRIE && lc->cmdsize >= sizeof(struct linkedit_data_command)) {
|
||||
const struct linkedit_data_command *d = (const struct linkedit_data_command *)lc;
|
||||
trie_off = d->dataoff;
|
||||
trie_size = d->datasize;
|
||||
} else if ((lc->cmd == LC_DYLD_INFO || lc->cmd == LC_DYLD_INFO_ONLY)
|
||||
&& lc->cmdsize >= sizeof(struct dyld_info_command)) {
|
||||
const struct dyld_info_command *d = (const struct dyld_info_command *)lc;
|
||||
if (!trie_off) {
|
||||
trie_off = d->export_off;
|
||||
trie_size = d->export_size;
|
||||
}
|
||||
}
|
||||
cmd += lc->cmdsize;
|
||||
}
|
||||
if (!linkedit || !trie_off || !trie_size) return NULL;
|
||||
if (trie_off < linkedit->fileoff || trie_size > linkedit->filesize ||
|
||||
(uint64_t)(trie_off - linkedit->fileoff) > linkedit->filesize - trie_size) {
|
||||
return NULL;
|
||||
}
|
||||
uintptr_t linkedit_base = (uintptr_t)slide + (uintptr_t)(linkedit->vmaddr - linkedit->fileoff);
|
||||
const uint8_t *start = (const uint8_t *)(linkedit_base + trie_off);
|
||||
const uint8_t *end = start + trie_size;
|
||||
const uint8_t *node = ig_walk_export_trie(start, end, macho_sym);
|
||||
if (!node) return NULL;
|
||||
int ok = 0;
|
||||
uint64_t flags = ig_read_uleb128(&node, end, &ok);
|
||||
if (!ok) return NULL;
|
||||
if (flags & EXPORT_SYMBOL_FLAGS_REEXPORT) return NULL;
|
||||
if ((flags & EXPORT_SYMBOL_FLAGS_KIND_MASK) != EXPORT_SYMBOL_FLAGS_KIND_REGULAR) return NULL;
|
||||
if (flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
|
||||
(void)ig_read_uleb128(&node, end, &ok);
|
||||
if (!ok) return NULL;
|
||||
uint64_t resolver_off = ig_read_uleb128(&node, end, &ok);
|
||||
if (!ok) return NULL;
|
||||
void *(*resolver)(void) = (void *(*)(void))IG_RESOLVE_SIGN_FN((void *)((uintptr_t)mh + (uintptr_t)resolver_off));
|
||||
return resolver();
|
||||
}
|
||||
uint64_t sym_off = ig_read_uleb128(&node, end, &ok);
|
||||
if (!ok) return NULL;
|
||||
return IG_RESOLVE_SIGN_FN((void *)((uintptr_t)mh + (uintptr_t)sym_off));
|
||||
}
|
||||
|
||||
void *ig_resolve_export_default(const char *bare_name) {
|
||||
if (!bare_name || !bare_name[0]) return NULL;
|
||||
size_t len = ig_strlen(bare_name);
|
||||
if (len >= 254) return NULL;
|
||||
char macho_sym[256];
|
||||
macho_sym[0] = '_';
|
||||
ig_memcpy(macho_sym + 1, bare_name, len);
|
||||
macho_sym[1 + len] = '\0';
|
||||
|
||||
uint32_t count = _dyld_image_count();
|
||||
/* 两阶段:Pass 0 检查非系统动态库抢占(跳过主程序和保护库自身),Pass 1 查系统镜像。 */
|
||||
for (int pass = 0; pass < 2; ++pass) {
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
const struct mach_header_64 *mh = (const struct mach_header_64 *)_dyld_get_image_header(i);
|
||||
if (!mh || mh->magic != MH_MAGIC_64 || mh->filetype == MH_EXECUTE) continue;
|
||||
const char *path = _dyld_get_image_name(i);
|
||||
if (!path) continue;
|
||||
int sys = ig_is_system_image_path(path);
|
||||
if (pass == 0) {
|
||||
if (sys || ig_ends_with(path, "/RDCoreIO.framework/RDCoreIO")) continue;
|
||||
} else {
|
||||
if (!sys) continue;
|
||||
}
|
||||
void *addr = ig_lookup_concrete_export(mh, _dyld_get_image_vmaddr_slide(i), macho_sym);
|
||||
if (addr) {
|
||||
ig_wipe(macho_sym, sizeof(macho_sym));
|
||||
return addr;
|
||||
}
|
||||
}
|
||||
}
|
||||
ig_wipe(macho_sym, sizeof(macho_sym));
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void *ig_resolve_image_export(const char *image_suffix, const char *bare_name) {
|
||||
if (!image_suffix || !image_suffix[0] || !bare_name || !bare_name[0]) return NULL;
|
||||
size_t len = ig_strlen(bare_name);
|
||||
if (len >= 254) return NULL;
|
||||
char macho_sym[256];
|
||||
macho_sym[0] = '_';
|
||||
ig_memcpy(macho_sym + 1, bare_name, len);
|
||||
macho_sym[1 + len] = '\0';
|
||||
|
||||
const struct mach_header_64 *matched_mh = NULL;
|
||||
intptr_t matched_slide = 0;
|
||||
uint32_t matches = 0;
|
||||
uint32_t count = _dyld_image_count();
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
const char *path = _dyld_get_image_name(i);
|
||||
if (!ig_ends_with(path, image_suffix)) continue;
|
||||
const struct mach_header_64 *mh = (const struct mach_header_64 *)_dyld_get_image_header(i);
|
||||
if (!mh || mh->magic != MH_MAGIC_64 || mh->filetype != MH_DYLIB) continue;
|
||||
matched_mh = mh;
|
||||
matched_slide = _dyld_get_image_vmaddr_slide(i);
|
||||
++matches;
|
||||
}
|
||||
void *addr = (matches == 1) ? ig_lookup_concrete_export(matched_mh, matched_slide, macho_sym) : NULL;
|
||||
ig_wipe(macho_sym, sizeof(macho_sym));
|
||||
return addr;
|
||||
}
|
||||
|
||||
char *ig_decrypt(const unsigned char *enc, size_t len, char *out, size_t cap) {
|
||||
if (!out || cap==0) return NULL;
|
||||
out[0]='\0';
|
||||
if (!enc || len==0 || len>=cap) return NULL;
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
out[i] = (char)(enc[i] ^ IG_ENC_KEY);
|
||||
if (out[i]=='\0') { ig_wipe(out,cap); return NULL; }
|
||||
}
|
||||
out[len] = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
void ig_wipe(void *p, size_t n) {
|
||||
if (!p) return;
|
||||
volatile unsigned char *v = (volatile unsigned char *)p;
|
||||
while (n--) *v++ = 0; /* volatile:防编译器把清零 DCE 掉 */
|
||||
}
|
||||
|
||||
IGResolveResult ig_resolve_verified(void *handle, const unsigned char *enc_name, size_t sym_len,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
char name[256];
|
||||
IGResolveResult result={IG_UNAVAILABLE,NULL};
|
||||
if (!ig_decrypt(enc_name, sym_len, name, sizeof(name))) return result;
|
||||
#ifdef dlsym
|
||||
extern void *dlsym(void *, const char *);
|
||||
void *addr = dlsym(handle ? handle : (void *)-2, name);
|
||||
#else
|
||||
(void)handle;
|
||||
void *addr = ig_resolve_export_default(name);
|
||||
#endif
|
||||
if (addr) {
|
||||
/* 放行前校验:provenance + inline-hook。不过即判被挟持,返回 NULL。 */
|
||||
result.status=ig_verify_function(addr,name,sink,ctx);
|
||||
if (result.status==IG_CLEAR) result.address=addr;
|
||||
} else if (sink) {
|
||||
IGFinding f={0};
|
||||
f.status=IG_UNAVAILABLE; f.reason=IG_REASON_SYMBOL_UNRESOLVED;
|
||||
sink(&f,ctx);
|
||||
}
|
||||
ig_wipe(name, sizeof(name)); /* 明文符号名用后清零,不驻留栈 */
|
||||
return result;
|
||||
}
|
||||
|
||||
void *ig_dlsym_verified(void *handle, const unsigned char *enc_name, size_t sym_len) {
|
||||
return ig_resolve_verified(handle,enc_name,sym_len,NULL,NULL).address;
|
||||
}
|
||||
|
||||
const char *ig_getenv(const char *name) {
|
||||
char ***environment = _NSGetEnviron();
|
||||
if (!environment || !*environment || !name || !name[0]) return NULL;
|
||||
char *const *envp = *environment;
|
||||
size_t nlen = ig_strlen(name);
|
||||
for (; *envp; ++envp) {
|
||||
const char *e = *envp;
|
||||
/* 匹配 "name=" 前缀 */
|
||||
if (ig_strncmp(e, name, nlen) == 0 && e[nlen] == '=') {
|
||||
return e + nlen + 1;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* IGResolve.h — 加密名 + 带校验的自定义符号解析(落地方案第二优先级)。
|
||||
*
|
||||
* 问题:核心逻辑直接 dlopen("…")/dlsym(h,"…") 会在 __cstring 留下明文库名/符号名,
|
||||
* 既暴露意图(攻击者 grep 字符串即知你在找什么),__got 里的 dlopen/dlsym 本身也是 hook 靶点。
|
||||
*
|
||||
* 本模块:
|
||||
* 1) 编译期 XOR 混淆字符串(IG_ENC 宏),运行期在**栈上**解密、用完即清零,明文不驻留常量区。
|
||||
* 2) 解析后**校验再放行**:dladdr 确认提供方在系统路径白名单内 + 校验函数序言首字节不是
|
||||
* inline-hook 蹦床(B / LDR-literal+BR x16/x17),命中则返回 NULL(视作被挟持,拒绝使用)。
|
||||
* 3) ig_getenv 经 _NSGetEnviron 手工遍历,规避对 getenv 的 hook/特征。
|
||||
*
|
||||
* 边界:dlopen/dlsym 本身仍会被解析/调用(仅隐藏其**参数**与**对结果验真**);若需连 dlsym 调用
|
||||
* 也抹除,改走 Export Trie 手工遍历(本头预留 ig_resolve_in_image,当前实现以 dlsym 为主路径)。
|
||||
* 字符串混淆是“抬高静态分析成本”,非加密强度;密钥在二进制内,决心足够者可还原——与 svc 号混淆同理。
|
||||
*/
|
||||
#ifndef IG_RESOLVE_H
|
||||
#define IG_RESOLVE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "../include/IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 单字节 XOR 密钥(与 IGSyscall 的掩码独立)。 */
|
||||
#define IG_ENC_KEY 0x3Cu
|
||||
|
||||
/*
|
||||
* 栈上解密:把 enc(已 XOR)解到调用方缓冲 out(容量 cap),返回 out。
|
||||
* 用完务必 ig_wipe 清零,避免解密后的明文在栈/寄存器残留被 dump。
|
||||
*/
|
||||
char *ig_decrypt(const unsigned char *enc, size_t len, char *out, size_t cap);
|
||||
void ig_wipe(void *p, size_t n);
|
||||
|
||||
/*
|
||||
* 走 Mach-O Export Trie(LC_DYLD_EXPORTS_TRIE / LC_DYLD_INFO)无 dlsym 解析符号:
|
||||
* - ig_resolve_export_default:优先检查非系统动态库是否抢占定义,再查系统动态库,
|
||||
* 既彻底消除对 _dlsym 的显式调用/导入,又保持对 dyld interpose/注入抢占的检出能力。
|
||||
* - ig_resolve_image_export:按镜像路径后缀从指定已加载动态库导出表解析符号。
|
||||
*/
|
||||
#ifdef IG_ARCHIVE_INTERNAL_RESOLVE
|
||||
void *ig_resolve_export_default(const char *bare_name);
|
||||
void *ig_resolve_image_export(const char *image_suffix, const char *bare_name);
|
||||
#else
|
||||
IG_PUBLIC void *ig_resolve_export_default(const char *bare_name);
|
||||
IG_PUBLIC void *ig_resolve_image_export(const char *image_suffix, const char *bare_name);
|
||||
#endif
|
||||
|
||||
/*
|
||||
* 带校验的符号解析:在已加载系统镜像(或测试注入 handle)中解析名为 enc_name(XOR 编码) 的符号,
|
||||
* 成功后对结果做 provenance + 序言校验;任一不过返回 NULL。sym_len 为编码串长度(不含结尾)。
|
||||
*/
|
||||
void *ig_dlsym_verified(void *handle, const unsigned char *enc_name, size_t sym_len);
|
||||
|
||||
typedef struct { IGStatus status; void *address; } IGResolveResult;
|
||||
IGResolveResult ig_resolve_verified(void *handle, const unsigned char *enc_name, size_t sym_len,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
/* 经 _NSGetEnviron 手工查环境变量,规避 getenv 符号。未命中返回 NULL。name 为明文(短、非敏感)。 */
|
||||
const char *ig_getenv(const char *name);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_RESOLVE_H */
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* IGSyscall.c — ARM64 混淆直发系统调用实现。
|
||||
*
|
||||
* ABI(本会话真机/宿主实测):调用号入 x16(arm64 BSD 调用**不加** 0x2000000 掩码,那是 x86_64 的
|
||||
* class 位);参数 x0..x5;`svc #0x80`;返回值在 x0,出错时 carry 置位、x0=errno。
|
||||
* 本封装对出错统一返回 -errno,便于调用方判负。
|
||||
*/
|
||||
#include "IGSyscall.h"
|
||||
|
||||
/* 运行期密钥,volatile 防止编译器把 enc^key 折叠回明文立即数。构造函数置值,提供默认兜底。 */
|
||||
volatile long ig_sc_key = IG_SC_CMASK;
|
||||
|
||||
__attribute__((constructor))
|
||||
static void ig_sc_init(void) {
|
||||
/* 显式再置一次:即使该 TU 的 constructor 被裁剪,静态初值也保证正确。 */
|
||||
ig_sc_key = IG_SC_CMASK;
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
|
||||
/*
|
||||
* 直发核心。真实调用号 = enc_num ^ ig_sc_key,在运行期于寄存器内还原后载入 x16,
|
||||
* 二进制里既无 `movz x16,#<真实号>` 立即数,也无该号的明文常量。
|
||||
* carry 置位(出错)时返回 -x0(errno),否则返回 x0。
|
||||
*/
|
||||
long ig_syscall6(long enc_num, long a0, long a1, long a2, long a3, long a4, long a5) {
|
||||
register long x16 __asm__("x16") = enc_num ^ ig_sc_key;
|
||||
register long x0 __asm__("x0") = a0;
|
||||
register long x1 __asm__("x1") = a1;
|
||||
register long x2 __asm__("x2") = a2;
|
||||
register long x3 __asm__("x3") = a3;
|
||||
register long x4 __asm__("x4") = a4;
|
||||
register long x5 __asm__("x5") = a5;
|
||||
register long cc __asm__("x8"); /* 承接 carry 标志 */
|
||||
__asm__ __volatile__(
|
||||
"svc #0x80\n"
|
||||
"cset %[cc], cs\n" /* carry set → 出错 */
|
||||
: "+r"(x0), [cc] "=r"(cc)
|
||||
: "r"(x16), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5)
|
||||
: "cc", "memory");
|
||||
return cc ? -x0 : x0;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
/* 非 arm64(宿主自测可能是 x86_64):退化为 unavailable 语义,返回 -1。 */
|
||||
long ig_syscall6(long enc_num, long a0, long a1, long a2, long a3, long a4, long a5) {
|
||||
(void)enc_num; (void)a0; (void)a1; (void)a2; (void)a3; (void)a4; (void)a5;
|
||||
return -1;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/* BSD 调用号(arm64,无 class 掩码)。本会话实测:getpid=20、write=4 已验证。 */
|
||||
#define IG_NR_EXIT 1
|
||||
#define IG_NR_READ 3
|
||||
#define IG_NR_WRITE 4
|
||||
#define IG_NR_OPEN 5
|
||||
#define IG_NR_CLOSE 6
|
||||
#define IG_NR_UNLINK 10
|
||||
#define IG_NR_GETPID 20
|
||||
#define IG_NR_ACCESS 33
|
||||
#define IG_NR_SYSCTL 202
|
||||
|
||||
int ig_sys_getpid(void) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_GETPID), 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
long ig_sys_write(int fd, const void *buf, size_t n) {
|
||||
return ig_syscall6(IG_SC(IG_NR_WRITE), (long)fd, (long)buf, (long)n, 0, 0, 0);
|
||||
}
|
||||
|
||||
long ig_sys_read(int fd, void *buf, size_t n) {
|
||||
return ig_syscall6(IG_SC(IG_NR_READ), (long)fd, (long)buf, (long)n, 0, 0, 0);
|
||||
}
|
||||
|
||||
int ig_sys_open(const char *path, int flags, int mode) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_OPEN), (long)path, (long)flags, (long)mode, 0, 0, 0);
|
||||
}
|
||||
|
||||
int ig_sys_close(int fd) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_CLOSE), (long)fd, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
int ig_sys_access(const char *path, int amode) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_ACCESS), (long)path, (long)amode, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
int ig_sys_unlink(const char *path) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_UNLINK), (long)path, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
void ig_sys_exit(int code) {
|
||||
ig_syscall6(IG_SC(IG_NR_EXIT), (long)code, 0, 0, 0, 0, 0);
|
||||
for (;;) { } /* 不返回 */
|
||||
}
|
||||
|
||||
/*
|
||||
* 调试器检测:sysctl(mib={CTL_KERN,KERN_PROC,KERN_PROC_PID,pid}) 读 kinfo_proc.kp_proc.p_flag,
|
||||
* P_TRACED(0x800) 置位即被调试。直发 svc,不经 libc 的 sysctl(避开对其的 hook)。
|
||||
* 为避免依赖 <sys/sysctl.h>/<sys/proc.h> 的完整布局,这里用常量与偏移手工构造。
|
||||
*/
|
||||
#define IG_CTL_KERN 1
|
||||
#define IG_KERN_PROC 14
|
||||
#define IG_KERN_PROC_PID 1
|
||||
#define IG_P_TRACED 0x00000800
|
||||
|
||||
int ig_sys_is_debugged(void) {
|
||||
#if defined(__aarch64__)
|
||||
/*
|
||||
* struct kinfo_proc 在 arm64 iOS/macOS 上,kp_proc.p_flag 为结构体起始处的第一个 int(偏移 0)。
|
||||
* 该布局自 BSD 以来稳定:extern_proc 以 p_un(union,8B) 起,随后 p_flag。为稳妥,取足够大的缓冲,
|
||||
* 并从 p_flag 的已知偏移读取。extern_proc:前 8B 为 union 指针/ru,接着 struct timeval(16B? ) —
|
||||
* 不同平台有差异,故用保守做法:定位 p_flag 偏移为 extern_proc 内 0x10。
|
||||
*/
|
||||
unsigned char buf[648]; /* sizeof(struct kinfo_proc)==648(本机 offsetof 实测) */
|
||||
for (size_t i = 0; i < sizeof(buf); ++i) buf[i] = 0;
|
||||
|
||||
int mib[4];
|
||||
mib[0] = IG_CTL_KERN;
|
||||
mib[1] = IG_KERN_PROC;
|
||||
mib[2] = IG_KERN_PROC_PID;
|
||||
mib[3] = ig_sys_getpid();
|
||||
|
||||
size_t len = sizeof(buf);
|
||||
/* sysctl(name, namelen, oldp, oldlenp, newp, newlen) */
|
||||
long r = ig_syscall6(IG_SC(IG_NR_SYSCTL), (long)mib, 4, (long)buf, (long)&len, 0, 0);
|
||||
if (r < 0) return -1; /* unavailable */
|
||||
|
||||
/*
|
||||
* p_flag 在 kinfo_proc 内的字节偏移:kp_proc 位于 kinfo_proc 偏移 0,extern_proc.p_flag 偏移 32——
|
||||
* 两者均由本机 `offsetof(struct kinfo_proc, kp_proc)==0` + `offsetof(struct extern_proc, p_flag)==32`
|
||||
* 实测得到(见 scratchpad/off.c)。故 p_flag 偏移 = 0x20。LP64 ABI 稳定。
|
||||
*/
|
||||
int p_flag;
|
||||
const unsigned char *pf = buf + 0x20;
|
||||
p_flag = (int)((unsigned)pf[0] | ((unsigned)pf[1] << 8) |
|
||||
((unsigned)pf[2] << 16) | ((unsigned)pf[3] << 24));
|
||||
return (p_flag & IG_P_TRACED) ? 1 : 0;
|
||||
#else
|
||||
return -1;
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* IGSyscall.h — ARM64 混淆直发系统调用(落地方案第一优先级)。
|
||||
*
|
||||
* 文件/进程/安全类系统调用若经 libsystem_kernel.dylib 走,libSystem 的函数入口可被 inline hook、
|
||||
* __got 槽可被 fishhook 重绑定。本模块用内联汇编 `svc #0x80` 直接进内核,绕过 C 库封装层——
|
||||
* 那条可被 hook 的 libSystem 入口在这条路径上根本不存在。
|
||||
*
|
||||
* 反静态特征:IDA 等常搜索 `svc #0x80` 并读 x16 的立即数识别调用号。本模块不把真实调用号写成
|
||||
* `movz x16,#n` 立即数,而是调用方传入 XOR 编码值(IG_SC 宏),运行期与 ig_sc_key 异或还原后
|
||||
* 由寄存器载入 x16,使静态扫描读不到真实号。
|
||||
*
|
||||
* 边界(如实声明,与 docs/05 §2 一致):
|
||||
* - 仅 arm64。直发系统调用绕过 libSystem,跨 iOS 版本的调用号/ABI 稳定性由调用方负责;
|
||||
* Apple 审核对直发 svc 可能关注,非 App Store 主线,用于确需防 hook 的关键路径。
|
||||
* - 错误语义:返回值 <0 不自动转 errno;错误时内核置 carry、x0=errno,本封装统一返回 -errno。
|
||||
* - 变参/取消点/EINTR 等 libc 语义不代为处理,调用方按需补。
|
||||
*/
|
||||
#ifndef IG_SYSCALL_H
|
||||
#define IG_SYSCALL_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 编译期 XOR 编码掩码:调用方用 IG_SC(真实号) 传参,真实号不以明文/立即数进入二进制。 */
|
||||
#define IG_SC_CMASK 0x5Al
|
||||
#define IG_SC(n) ((long)((long)(n) ^ IG_SC_CMASK))
|
||||
|
||||
/* 运行期密钥(构造函数置为 IG_SC_CMASK,经 volatile 存取避免被常量折叠回立即数)。 */
|
||||
extern volatile long ig_sc_key;
|
||||
|
||||
/*
|
||||
* 通用直发。enc_num:IG_SC(真实调用号)。a0..a5:参数(不足补 0)。
|
||||
* 成功返回内核结果(x0);失败返回 -errno。
|
||||
*/
|
||||
long ig_syscall6(long enc_num, long a0, long a1, long a2, long a3, long a4, long a5);
|
||||
|
||||
/* 常用封装(均走 ig_syscall6,调用号经 IG_SC 编码)。 */
|
||||
int ig_sys_getpid(void);
|
||||
long ig_sys_write(int fd, const void *buf, size_t n);
|
||||
long ig_sys_read(int fd, void *buf, size_t n);
|
||||
int ig_sys_open(const char *path, int flags, int mode);
|
||||
int ig_sys_close(int fd);
|
||||
int ig_sys_access(const char *path, int amode); /* 直发 access(2);0=可访问,<0=-errno */
|
||||
int ig_sys_unlink(const char *path); /* 直发 unlink(2);0=成功,<0=-errno */
|
||||
void ig_sys_exit(int code) __attribute__((noreturn));
|
||||
|
||||
/*
|
||||
* 调试器检测:直发 sysctl(KERN_PROC/KERN_PROC_PID) 读 kinfo_proc.p_flag & P_TRACED。
|
||||
* 返回 1=被跟踪,0=未跟踪,-1=unavailable(sysctl 失败)。不经 libc,规避对 sysctl 的 hook。
|
||||
*/
|
||||
int ig_sys_is_debugged(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_SYSCALL_H */
|
||||
@@ -1,151 +0,0 @@
|
||||
# iOS 混淆加固工具(iOSGuard)技术全景与实现路线图
|
||||
|
||||
本路线图对标 **小蟹 iOS 混淆 (Crab iOS)** 核心架构与功能体系,针对 iOS 应用的 **App Store 过审差异化(应对 4.3 / 2.3.1 审查)** 和 **应用代码安全加固(防逆向 / 防 Dump / 防重打包)** 需求,制定从 0 到 1 的工程实现方案。
|
||||
|
||||
---
|
||||
|
||||
## 一、 系统架构全景
|
||||
|
||||
Crab iOS 并非单纯的源码文本替换工具,而是一套**“LLVM IR 级编译加固 + 源码预处理 + 运行时动态桥接 (COSDK) + 资产透明加密 + dSYM 逆向还原 + IPA 差异度度量”**的复合系统。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Input["输入工程"]
|
||||
A1["Objective-C / Swift / C / C++ 源码"]
|
||||
A2["Unity (IL2CPP) / Flutter (Dart) / Cocos"]
|
||||
A3["资源文件 (.png / .storyboard / .bundle / .xcassets)"]
|
||||
A4["静态依赖 (.a / static .framework / .xcframework)"]
|
||||
end
|
||||
|
||||
subgraph PreProcess["源码与工程预处理层 (AST & Project Rewriter)"]
|
||||
B1["PBXProject / xcconfig 自动化注入"]
|
||||
B2["符号提取与静态分析 (AST Parsing)"]
|
||||
B3["源码代码膨胀 (Junk Code / 假调用)"]
|
||||
B4["Dart / Unity IL2CPP 前置特征擦除"]
|
||||
end
|
||||
|
||||
subgraph CompilerPass["LLVM 编译级加固引擎 (Compiler Toolchain / Clang Plugin)"]
|
||||
C1["字符串常量动态加密 Pass"]
|
||||
C2["控制流平坦化 (Control Flow Flattening)"]
|
||||
C3["虚假控制流 (Bogus Control Flow) 与指令替换"]
|
||||
C4["Objective-C Selector / Method 加密 Pass"]
|
||||
C5["防 Class-Dump 结构抹除"]
|
||||
end
|
||||
|
||||
subgraph RuntimeBridge["运行时支撑框架 (COSDK)"]
|
||||
D1["C API 拦截 (Fishhook: open, stat, access)"]
|
||||
D2["ObjC Runtime 反射桥接 (NSClassFromString / sel_registerName)"]
|
||||
D3["内存透明资源解密 (In-Memory Asset Decryption)"]
|
||||
D4["随机特征签名隔离 (Per-Build Unique Fingerprint)"]
|
||||
end
|
||||
|
||||
subgraph BinaryPostProcess["产物后处理与双符号表还原"]
|
||||
E1["Mach-O 二进制混淆 (Section 混淆 / 符号 Strip)"]
|
||||
E2["资源哈希混淆 (破坏文件哈希 / 元数据注入)"]
|
||||
E3["双符号表数据库构建 (Mapping DB)"]
|
||||
E4["dSYM 反向还原引擎 (适配 Bugly / Crashlytics / Sentry)"]
|
||||
end
|
||||
|
||||
subgraph Analysis["质量与过审检测中心"]
|
||||
F1["IPA 对比与特征相似度评估 (SSDEEP / AST Diff / 4.3 预检)"]
|
||||
F2["Xcode Debug 联调辅助与符号映射支持"]
|
||||
end
|
||||
|
||||
Input --> PreProcess
|
||||
PreProcess --> CompilerPass
|
||||
CompilerPass --> RuntimeBridge
|
||||
CompilerPass --> BinaryPostProcess
|
||||
RuntimeBridge --> BinaryPostProcess
|
||||
BinaryPostProcess --> Analysis
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、 核心子系统关键技术方案
|
||||
|
||||
### 1. 语言与符号混淆子系统 (AST & LLVM)
|
||||
* **符号重命名策略**:
|
||||
* 支持类名 (Class)、分类名 (Category)、协议 (Protocol)、属性 (Property)、实例变量 (Ivar)、方法名/选择器 (Selector)、全局函数、结构体、枚举。
|
||||
* **符号库隔离策略 (Symbol Profiles)**:维护不同的随机伪随机种子库与词典库,确保同一份源码使用不同策略编译出的符号特征完全隔离。
|
||||
* **黑白名单排除机制**:支持系统 API 继承链自动穿透分析(如继承自 `UITableViewCell`、遵从 `NSCoding` 协议的类成员必须排除)、支持 KVC/JSON 反序列化(`YYModel` / `MJExtension`)通用规则排除。
|
||||
* **常量与字符串加密 (LLVM IR Pass)**:
|
||||
* 在 LLVM IR 阶段匹配全局字符串(`ConstantDataSequential`),将其替换为加密数组,并在每个函数入口或 `.init_array` / `+load` 动态解密,防止 IDA / Hopper 静态分析直接搜索到敏感 URL、Key 或特征字。
|
||||
* **调用栈混淆与代码膨胀**:
|
||||
* 插入多层蹦床代理函数(Trampoline Calls)、不透明谓词(Opaque Predicates)与无害控制流分支。
|
||||
* 混淆调用栈(Call Stack),破坏调用拓扑,使得 Apple 静态代码相似度对比(AST 树结构比对)无法匹配。
|
||||
|
||||
### 2. 运行时拦截与支撑库 (COSDK)
|
||||
* **动态反射修复**:
|
||||
* 当符号被重命名后,运行时的动态反射调用(如 `NSClassFromString(@"UserViewController")`、`NSSelectorFromString(@"clickLogin:")`)默认会返回 `nil`。
|
||||
* COSDK 注入动态映射表,使用 `fishhook` 拦截 C 运行时及 Method Swizzling 拦截 ObjC Runtime API:
|
||||
* `objc_getClass` / `NSClassFromString`
|
||||
* `NSStringFromClass` / `NSStringFromSelector`
|
||||
* `sel_registerName` / `NSSelectorFromString`
|
||||
* `class_getInstanceMethod` / `class_getMethodImplementation`
|
||||
* 拦截后自动执行“原始符号 ↔ 混淆符号”的双向查表转换,保证业务反射逻辑完全正常。
|
||||
* **SDK 每次打包特征隔离**:
|
||||
* 运行时支撑库(COSDK)每次构建时动态随机命名库文件名、重构内部函数符号、生成随机校验密钥,防止 Apple 将加固 SDK 本身标记为“马甲包公共特征”。
|
||||
|
||||
### 3. 资源文件混淆与透明解密
|
||||
* **资源名混淆与代码关联重写**:
|
||||
* 提取 `.png`、`.jpg`、`.webp`、`.plist`、`.json`、`.sks` 等资源,生成混淆文件名(如 `a8f9b2c.png`)。
|
||||
* 自动化遍历扫描与改写:
|
||||
* 代码中的硬编码字符串 `[UIImage imageNamed:@"old_icon"]`。
|
||||
* `.storyboard`、`.xib`、`.xcassets` 的引用关系。
|
||||
* **文件哈希混淆 (Hash Distortion)**:
|
||||
* 针对免加密的静态图片资源,修改 PNG 的自定义无用 Chunk(如增加 `tEXt` 随机注释)或尾部无害填充字节,确保文件 MD5/SHA256 改变,但图像显示完全一致。
|
||||
* **深度资源加密与虚拟文件系统 Hook**:
|
||||
* 资源采用高强度流加密(如 ChaCha20/AES-CTR)加密存放在 Bundle 中。
|
||||
* 运行时在底层拦截 POSIX 文件 API:`open`、`fopen`、`stat`、`lstat`、`access` 以及 Cocoa 层 `[NSBundle pathForResource:ofType:]`、`[NSData dataWithContentsOfFile:]`、`[UIImage imageNamed:]`,在内存流中即时解密,外部工具无法解压直接提取。
|
||||
|
||||
### 4. 双符号表策略与 dSYM 崩溃还原 (Crash Restoration)
|
||||
* **痛点**:源码符号被混淆后,上架 App 产生的崩溃日志通过 Bugly、Firebase Crashlytics、Sentry 解析出来的全是一串乱码(如 `a8b9c()`),严重阻碍生产运维。
|
||||
* **解决技术路径**:
|
||||
1. 编译混淆时输出全局符号双向映射映射表:`mapping.json / mapping.db`(记录 `OriginalSymbol -> ObfuscatedSymbol` 及其签名、文件名)。
|
||||
2. 生成两份 dSYM 文件:
|
||||
* **混淆 dSYM**:匹配 App Store 提审的 Mach-O,用于苹果机审或基础定位。
|
||||
* **还原工具 / 还原后的 dSYM**:读取原始 DWARF 调试节,利用 `llvm-dwarfdump` / 自研 DWARF 重构器,遍历 `.debug_info`、`.debug_str`,将里面的混淆符号批量替换回原始符号。
|
||||
3. 还原后的 dSYM 可直接上传至 Bugly / Sentry,实现线上崩溃栈无感还原。
|
||||
|
||||
### 5. 跨跨端框架专项适配 (Flutter / Unity / Cocos)
|
||||
* **Flutter / Dart**:
|
||||
* Dart AOT 编译成 `App.framework` 中的快照(Snapshot 二进制代码段),传统 LLVM 无法直接处理 Dart 符号。
|
||||
* 采用“Dart 源码前置 AST 处理”与“Dart 方法转发”方案,混淆 Dart 类名与方法名,并阻断 Dart 与原生通信的 MethodChannel 字符串特征。
|
||||
* **Unity (IL2CPP)**:
|
||||
* Unity 导出为 Xcode 工程后,核心 C# 代码已转为 C++(`Classes/Native` 目录)。
|
||||
* 直接利用 C/C++ 语言混淆能力与控制流加固,对 IL2CPP 生成的 C++ 函数符号、元数据字符串表格、全局结构体进行混淆。
|
||||
* **Cocos / Cocos2d-x / Quick-Cocos**:
|
||||
* 混淆 C++ 底层驱动层,并对 JS/Lua 脚本资产进行加密打包与 Loader 注入解密。
|
||||
|
||||
### 6. 马甲包与 4.3 审核对抗分析器 (IPA Diff Tool)
|
||||
* **Mach-O 静态分析**:分析 `__TEXT,__text` 段机器码相似度(采用 SSDEEP 模糊哈希、TLSH、SimHash)。
|
||||
* **符号表相似度**:导出符号表(Exports / Imports / Objective-C Class Ro/Rw),计算 Jaccard 相似度。
|
||||
* **资产重复度检测**:对比图片直方图、感知哈希(pHash)、结构相似度(SSIM)。
|
||||
* **自动化生成风控报告**:量化输出与母包/前置版本的相似百分比,低于安全阈值(如 < 30% 相似度)方可提审。
|
||||
|
||||
---
|
||||
|
||||
## 三、 分阶段实施路线图 (Phase 1 ~ Phase 5)
|
||||
|
||||
| 阶段 | 周期 | 核心目标 | 交付产物 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Phase 1: 基础工程体系与基础符号/资源混淆 (MVP)** | 4~6 周 | 跑通 Xcode 工程解析、基础符号重命名、资源重命名与 Hash 扰动、简单的 ObjC 反射拦截 | 基础 CLI 工具、可混淆纯 ObjC/Swift 工程并在真机运行通过 |
|
||||
| **Phase 2: LLVM 编译级加固核心 (定向加固)** | 6~8 周 | 搭建定制 Clang 插件/Toolchain,实现控制流平坦化、虚假控制流、常量字符串加密、防 Dump | 独立编译插件、集成至 Xcode Target 的加固能力 |
|
||||
| **Phase 3: 运行时支撑 (COSDK) 与透明解密** | 4~6 周 | 完善动态库/静态库运行时 SDK,完成 C/ObjC API 全量 Hook,实现文件透明加解密 | 生产级 COSDK 库、动态特征重签名器 |
|
||||
| **Phase 4: 双符号表 dSYM 还原与生态适配** | 4~6 周 | 攻克 DWARF 调试节符号还原、打通 Unity/Flutter/Cocos 适配流程 | dSYM 还原工具、跨跨端构建脚本与配置模板 |
|
||||
| **Phase 5: IPA 相似度分析工具与桌面客户端** | 4~6 周 | 研发基于 Qt / Electron / SwiftUI 的跨平台客户端,集成 IPA 相似度比对引擎 | 桌面应用 (GUI)、完整商业化闭环、自动化测试套件 |
|
||||
|
||||
---
|
||||
|
||||
## 四、 核心技术难点与规避策略
|
||||
|
||||
1. **Apple 审核红线规避 (2.5.2 / 2.3.1 / 3.3.1)**
|
||||
* 严禁引入已知的私有 API(Private Frameworks / Undocumented Selectors)。
|
||||
* 严禁使用动态下载执行机器码(JIT / Dynamic Executable Memory)。
|
||||
* 加固支撑库本身的代码特征必须**每次打包均动态生成**,避免成为苹果机审黑名单特征。
|
||||
2. **Swift 静态派发与 Name Mangling 兼容**
|
||||
* Swift 5+ 具备稳定的 ABI,符号名有严格的 Mangling 规则(如 `_$s...`)。
|
||||
* 对 Swift 处理时,优先在 AST 层面或中间文件处理,并处理好 `@objc` 桥接方法与模块导出接口。
|
||||
3. **运行时崩溃与第三方库冲突**
|
||||
* 严禁盲目混淆第三方成熟开源库(如 AFNetworking, SDWebImage, Masonry 等),否则反而会增加相似度聚集特征,且极易引发系统调用崩溃。
|
||||
* 必须内置智能扫描器,自动识别 Pods / Carthage / SPM 并建立默认豁免名单。
|
||||
@@ -1,165 +0,0 @@
|
||||
# 企业级 iOS 安全加固系统(对标网易易盾)技术架构与实现方案
|
||||
|
||||
## 一、 产品定位对比:小蟹加固 vs 网易易盾
|
||||
|
||||
| 维度 | 小蟹加固 (Crab iOS) | 网易易盾 (NetEase YiDun iOS) |
|
||||
| :--- | :--- | :--- |
|
||||
| **核心业务诉求** | **App Store 审核对抗**(4.3 相似度、2.3.1 误导、马甲包矩阵) | **业务安全与资产保护**(防黑产逆向、防外挂、防篡改二次打包、金融级合规等保) |
|
||||
| **防护重心** | 符号重命名、代码膨胀、资源 Hash 扰动、调用栈拓扑重组、dSYM 崩溃还原 | **指令虚拟化 (VMP)、二进制壳保护、全维度主动防御 (反调试/反 Hook/反越狱)、白盒加密** |
|
||||
| **加固介入形式** | 深度依赖源码工程与 Xcode 编译管线 | **支持双模式**:① 源码级编译插件;② **无源码 IPA 纯二进制后处理** |
|
||||
| **主要目标客群** | 出海业务、游戏推广买量包、工具类矩阵 App | 头部游戏、银行金融 App、大型电商、高价值版权数字资产 |
|
||||
|
||||
---
|
||||
|
||||
## 二、 易盾级加固系统的五大核心技术支柱
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph MachO["1. Mach-O 二进制保护与代码虚拟化 (VMP)"]
|
||||
M1["Native 代码虚拟化 (VMP: 自定义字节码 + 虚拟机解释器)"]
|
||||
M2["Class-Dump 彻底防御 (抹除/加密 __objc_methname / __objc_class)"]
|
||||
M3["函数体级动态抽取与内存解密 (合规解密技术)"]
|
||||
M4["符号彻底剥离与重定位表混淆"]
|
||||
end
|
||||
|
||||
subgraph Defense["2. 全维度主动防御与反逆向矩阵 (Active Defense)"]
|
||||
D1["内核级反调试 (Syscall SVC 0x80 ptrace / 硬件断点 DR0-DR7 / 异常端口抢占)"]
|
||||
D2["反 Hook 引擎 (检测 Frida / Dobby / CydiaSubstrate / Fishhook)"]
|
||||
D3["反注入与反调试器 (DYLD_INSERT_LIBRARIES 监测 / 动态库签名校验)"]
|
||||
D4["高敏反越狱 (沙盒穿透 / 底层特征文件 / fork 与内核调用探测)"]
|
||||
end
|
||||
|
||||
subgraph Integrity["3. 完整性校验与防二次打包 (Anti-Tamper)"]
|
||||
I1["Mach-O __TEXT 段运行时内存散列校验 (Anti-Patch)"]
|
||||
I2["Code Directory Hash (CDHash) 签名链路比对"]
|
||||
I3["Bundle ID / Team ID / embedded.mobileprovision 强绑定"]
|
||||
end
|
||||
|
||||
subgraph GameAndResource["4. 游戏与核心资产保护 (Game & Assets)"]
|
||||
G1["Unity IL2CPP: global-metadata.dat 混淆与字符串段加密"]
|
||||
G2["Cocos / Quick-Cocos: Lua 字节码 (luac/LuaJIT) 与 JS (jsc) 加密"]
|
||||
G3["AssetBundle (AB) 资源包动态内存流解密"]
|
||||
end
|
||||
|
||||
subgraph Crypto["5. 数据安全与白盒密码学 (Whitebox Crypto)"]
|
||||
C1["白盒 AES / SM4 (密钥隐藏于查找表,内存不可 Dump)"]
|
||||
C2["敏感数据安全内存池 (Anti-Memory Scanning / ReadProcessMemory)"]
|
||||
end
|
||||
|
||||
MachO --> Defense
|
||||
Defense --> Integrity
|
||||
Integrity --> GameAndResource
|
||||
GameAndResource --> Crypto
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、 核心技术深入剖析与实现原理
|
||||
|
||||
### 1. iOS 代码虚拟化 (Code Virtualization / VMP)
|
||||
* **核心原理**:
|
||||
* 将关键敏感函数(如充值校验、加密算法、核心战斗逻辑)的原生 ARM64 汇编指令抽取。
|
||||
* 转化为**专有的私有字节码 (Bytecode)**,并在二进制中嵌入一个小型混淆过的 VM 虚拟机解释执行引擎。
|
||||
* 逆向人员在 IDA Pro / Ghidra 中看到的不再是连续的汇编指令或反编译伪代码,而是进入了 `VM_Interpreter_Dispatch(opcode)` 的庞大状态机,逆向成本成几何级数增加。
|
||||
* **iOS 环境适配约束**:
|
||||
* iOS 平台强制执行 W^X(Write XOR Execute)安全策略,普通 App 无法使用 JIT 动态申请可执行内存(无 `CS_DEBUGGED` 或特定 entitlement 时调用 `mprotect(PROT_EXEC)` 会被系统直接杀掉)。
|
||||
* 易盾方案采用**纯解释型 VM(Interpreter-based VMP)**,由原生的固定代码段指令去解释静态保存在数据段中的私有操作码,完全符合 Apple AMFI 签名校验与审核标准。
|
||||
|
||||
### 2. 全方位主动防御机制 (Active Defense)
|
||||
#### (1) 反调试 (Anti-Debug)
|
||||
* **SVC 内联汇编调用 ptrace**:普通调用 `ptrace(PT_DENY_ATTACH, 0, 0, 0)` 容易被 Frida / Dobby 符号 Hook。必须使用内联汇编直接触发软中断:
|
||||
```assembly
|
||||
mov x0, #31 // PT_DENY_ATTACH
|
||||
mov x1, #0
|
||||
mov x2, #0
|
||||
mov x3, #0
|
||||
mov x16, #26 // SYS_ptrace (syscall 26)
|
||||
svc #0x80
|
||||
```
|
||||
* **硬件断点检测**:获取当前线程上下文,检查 ARM64 架构特有的调试寄存器(`thread_get_state` 检查 `ARM_DEBUG_STATE64` 的 `bvr` 和 `bcr`,判断是否命中硬件断点)。
|
||||
* **Mach 异常端口劫持**:通过 `task_set_exception_ports` 注册自身为异常处理者,抢占 LLDB 的调试断点异常消息(`EXC_BREAKPOINT`)。
|
||||
|
||||
#### (2) 反 Hook 与反 Frida (Anti-Frida / Anti-Hook)
|
||||
* **检测 Frida 运行时特征**:
|
||||
* 扫描并枚举当前加载的所有 dylib (`_dyld_get_image_name`),匹配 `frida-agent`、`FridaGadget` 等特征库。
|
||||
* 检查默认调试通信端口(`27042`)及高频动态端口。
|
||||
* 遍历所有运行线程,检查线程名称(如 `gum-js-loop`、`gmain`)及堆栈地址是否位于未签名的内存段。
|
||||
* **检测 Inline Hook (Dobby / Substrate) 与 GOT Hook (Fishhook)**:
|
||||
* 校验关键系统 API(如 `open`, `mprotect`, `dlsym`, `ptrace`)的函数头机器码前 8~16 字节,检测是否存在 `LDR PC, [PC, #0]`、`BR X16` 等跳转跳板。
|
||||
* 检查 Mach-O 动态符号表(`__la_symbol_ptr`, `__got`)中的指针,确认其指向地址必须在系统 Dyld 共享缓存(Dyld Shared Cache)的合法边界内,若被篡改则立即熔断。
|
||||
|
||||
#### (3) 越狱与沙盒穿透检测 (Anti-Jailbreak)
|
||||
* 避免单点检测,构建多点投票机制:
|
||||
1. 检测特征路径(`/Applications/Cydia.app`, `/bin/bash`, `/usr/sbin/sshd`, `/var/jb` 等);
|
||||
2. 尝试沙盒逃逸操作(在 `/private` 目录创建临时文件);
|
||||
3. 检测环境变量 `DYLD_INSERT_LIBRARIES` 是否被注入;
|
||||
4. 底层探测 `fork()` 系统调用(非越狱系统下沙盒限制禁止 fork,返回值必为 -1)。
|
||||
|
||||
### 3. Mach-O 无源码 IPA 级加固 (Post-build Reinforce)
|
||||
易盾最大的商业优势之一是支持**直接上传 IPA 包即可一键加固**,其技术链条如下:
|
||||
1. **Mach-O 解析与重构**:
|
||||
* 解析 IPA 中的主二进制与 Dynamic Frameworks。
|
||||
* 读取 Load Commands(`LC_SEGMENT_64`, `LC_DYLD_INFO_ONLY`, `LC_CODE_SIGNATURE`)。
|
||||
2. **符号与元数据抹除 (Anti Class-Dump)**:
|
||||
* 抹除 `__objc_classname`, `__objc_methname`, `__objc_methtype`,通过随机化重构或加密存入自定义 Section。
|
||||
* 在二进制入口点 (`LC_MAIN` 或 `+load` 之前) 注入加固守护 dylib,负责在内存加载时动态还原 ObjC 查找元数据。
|
||||
3. **函数抽取与动态加解密**:
|
||||
* 将选定敏感函数体(ARM64 机器码)从 `__TEXT,__text` 段抽离并填充无害 `NOP`。
|
||||
* 抽取出的函数数据加密存放在新增的自定义 Segment。
|
||||
4. **重新签名与重打包**:
|
||||
* 修正 Mach-O 头部偏移与段对齐。
|
||||
* 剥除原签名,调用 `codesign` 或自研签名器,使用开发者的 Enterprise / Ad-Hoc / App Store 证书重签名。
|
||||
|
||||
### 4. 游戏与核心资源保护 (Unity / Cocos)
|
||||
* **Unity IL2CPP 核心加固**:
|
||||
* 攻击者常规手段是使用 `Il2CppDumper` 恢复 `global-metadata.dat`,配合 IDA 还原 C# 类结构。
|
||||
* 易盾方案:
|
||||
1. 加密 `global-metadata.dat` 文件;
|
||||
2. 对 IL2CPP 导出的二进制符号进行深度代码混淆;
|
||||
3. Hook `il2cpp::vm::MetadataCache::Initialize()`,在内存中动态受控解密,防止内存直接 dump 出完整元数据。
|
||||
* **Cocos 脚本与资源加密**:
|
||||
* 针对 Lua(`.lua`, `.luac`)进行自定义字节码变换并加密;
|
||||
* 针对 JS(`.jsc`)进行自定义混淆与秘钥派生;
|
||||
* Hook 引擎底层的 Asset 加载流(`FileUtils::getDataFromFile`),实现透明流式解密。
|
||||
|
||||
### 5. 白盒加密 (White-box Cryptography)
|
||||
* **解决痛点**:传统 AES/SM4 即使代码经过混淆,逆向人员在调试时只需在加密函数入口断点,即可在内存寄存器中直接提取出明文密钥(AES Key)。
|
||||
* **实现方案**:
|
||||
* 采用 Chow 等经典白盒构造体系,将 AES 轮密钥与 S-Box 替换、行移位、列混合等计算融合成一系列庞大的查找表(Look-up Tables, LUT,通常为数百 KB 到数 MB)。
|
||||
* 静态分析只能看到大量查表逻辑,动态调试即使 dump 内存也无法还原出原本的 128/256 位原始 Key。
|
||||
|
||||
---
|
||||
|
||||
## 四、 研发实施路线图 (Phase 1 ~ Phase 4)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
P1["Phase 1: 主动防御与环境检测内核 (4~6周)"] --> P2["Phase 2: Mach-O 元数据抹除与游戏脚本保护 (6~8周)"]
|
||||
P2 --> P3["Phase 3: 代码虚拟化 (VMP) 引擎 (8~10周)"]
|
||||
P3 --> P4["Phase 4: IPA 无源码重构流水线与商业平台 (4~6周)"]
|
||||
```
|
||||
|
||||
### 阶段 1:主动防御内核库 (Defender SDK) —— 基础防线
|
||||
* 编写纯 C/汇编的独立安全防护库。
|
||||
* 完成内联 SVC 系统调用反调试、硬件断点轮询监测。
|
||||
* 完成反 Frida(端口扫描、线程枚举、动态库监测)与反 Hook(Inline 探测、GOT 边界检测)。
|
||||
* 实现多维度沙盒与越狱环境感知。
|
||||
* 实现代码段内存 CRC/SHA256 完整性检测。
|
||||
|
||||
### 阶段 2:Mach-O 深度处理与游戏资产防护 —— 静态对抗
|
||||
* 攻克 Objective-C 元数据抹除(防 class-dump),实现运行时动态重映射。
|
||||
* 实现 Unity `global-metadata.dat` 加密与内存加载 Hook。
|
||||
* 实现 Cocos Lua / JS 资产包加解密体系。
|
||||
* 实现白盒 AES / SM4 加密模块。
|
||||
|
||||
### 3 阶段 3:代码虚拟化 (VMP) 编译器研发 —— 核心技术壁垒
|
||||
* 基于 LLVM 构建自定义 VMP 编译插件:
|
||||
* 识别被标记的敏感函数(如 `__attribute__((annotate("vmp")))`)。
|
||||
* 将 LLVM IR 翻译为自定义指令集(定制 Bytecode 规范)。
|
||||
* 生成随机混淆的虚拟机解释器运行时(VM Interpreter)。
|
||||
* 完成 VMP 在 ARM64 架构上的寄存器映射与栈帧维护,确保多线程安全性。
|
||||
|
||||
### 阶段 4:IPA 纯二进制加固工程化与平台交付 —— 商业化
|
||||
* 开发无源码 IPA Mach-O 二进制解析、段插入、代码抽取重构引擎。
|
||||
* 开发自动化签名工具,无缝支持个人、企业、App Store 证书重签。
|
||||
* 建设加固 SaaS Web 服务或本地 CLI/GUI,提供配置策略面板。
|
||||
@@ -1,288 +0,0 @@
|
||||
# iOSGuard:企业级 iOS 加固与安全防护系统完整实现方案
|
||||
|
||||
---
|
||||
|
||||
## 方案定位与设计目标
|
||||
|
||||
本项目(代号 **iOSGuard**)融合 **小蟹加固(Crab iOS)** 的“App Store 审核对抗、差异化混淆、dSYM 崩溃还原”与 **网易易盾(NetEase YiDun)** 的“Mach-O 深度加固、原生代码虚拟化 (VMP)、全维度主动防御、无源码 IPA 二进制处理与跨平台重签名”能力,构建一套工业级双模加固平台:
|
||||
|
||||
1. **双加固入口**:
|
||||
* **源码级加固(Compiler Pipeline)**:对接 Xcode,通过 LLVM Pass 实施深度混淆与代码虚拟化。
|
||||
* **无源码 IPA 加固(Binary Pipeline)**:直接上传打好的 `.ipa` 包,由 Mach-O 重构引擎进行二进制级加固与自动重签名。
|
||||
2. **零运行时破坏**:通过双符号表与 DWARF 重构技术,完全兼容 Bugly / Crashlytics / Sentry 等线上崩溃收集;通过智能反射桥接保证 KVC/JSON 反序列化零闪退。
|
||||
3. **App Store 提审合规**:不依赖 JIT 动态内存分配,完全满足苹果 AMFI 代码签名、W^X 内存防护以及 App Review Guidelines 审核要求。
|
||||
|
||||
---
|
||||
|
||||
## 一、 系统总体架构与工作流
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Input["1. 输入层 (Input)"]
|
||||
In1["源码工程 (Xcode / Flutter / Unity / Cocos)"]
|
||||
In2["已打包无源码 IPA (Binary Input)"]
|
||||
In3["开发者证书与描述文件 (.p12 / .mobileprovision)"]
|
||||
end
|
||||
|
||||
subgraph Pipeline["2. 加固调度核心流水线 (Guard Orchestrator)"]
|
||||
P1["工程解析与 xcconfig / Build Phase 自动化注入"]
|
||||
P2["IPA 解包与 Mach-O 静态解构器"]
|
||||
P3["加固策略配置路由器 (Rules & Exclusions Engine)"]
|
||||
end
|
||||
|
||||
subgraph Engines["3. 核心加固与对抗引擎"]
|
||||
direction TB
|
||||
E1["Mach-O 二进制重构器\n(Header扩容 / 段平移 / LC_LOAD_DYLIB 注入)"]
|
||||
E2["Class-Dump 彻底抹除\n(__objc_methname 清空 / 动态重映射)"]
|
||||
E3["代码虚拟化 (VMP) 引擎\n(ARM64 抽离 / 自定义字节码 / 解释器)"]
|
||||
E4["LLVM 编译混淆 Pass\n(控制流平坦化 / 虚假分支 / 字符串加密)"]
|
||||
E5["主动防御内核 (Defender Core)\n(SVC内联反调试 / 反Hook / 反Frida / 越狱感知)"]
|
||||
E6["资源与游戏资产保护\n(PNG Hash扰动 / 深度透明解密 / Unity IL2CPP)"]
|
||||
end
|
||||
|
||||
subgraph RestoreAndSign["4. 恢复与重签发布引擎"]
|
||||
R1["双符号表与 dSYM 崩溃逆向还原 (DWARF 重写)"]
|
||||
R2["跨平台重签名流水线 (Linux zsign / macOS codesign, DER 支持)"]
|
||||
R3["IPA 4.3 相似度静态预检 (SSDEEP / 符号比对 / 风险报告)"]
|
||||
end
|
||||
|
||||
subgraph Output["5. 交付产物 (Output)"]
|
||||
Out1["加固且重签名后 IPA (可直接提审 / 分发)"]
|
||||
Out2["还原后 dSYM 文件 (上传崩溃分析平台)"]
|
||||
Out3["加固与安全审计报告 (PDF / HTML)"]
|
||||
end
|
||||
|
||||
Input --> Pipeline
|
||||
Pipeline --> Engines
|
||||
Engines --> RestoreAndSign
|
||||
RestoreAndSign --> Output
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、 八大核心子系统详细实现方案
|
||||
|
||||
### 1. Mach-O 深度重构与二进制引擎 (Mach-O Rewriter)
|
||||
|
||||
* **模块目标**:在不依赖源码的前提下,解析并重写 IPA 主 Mach-O 及动态库,插入防护逻辑。
|
||||
* **关键算法与技术点**:
|
||||
1. **Header 扩容与段平移算法**:
|
||||
* 读取 `mach_header_64`,计算 `sizeofcmds`。
|
||||
* 检测 `load_commands` 结束位置与首个 Section(通常为 `__TEXT,__text`)之间的空白填充(Padding)。
|
||||
* 若 Padding $\ge sizeof(dylib\_command)$,直接原地追加 `LC_LOAD_DYLIB` 指令,并递增 `ncmds` 和 `sizeofcmds`。
|
||||
* 若 Padding 不足,触发**全局平移(Segment Shift)**:将首个 Section 起始偏移向后推移一个页面对齐大小(ARM64 为 `0x4000` / 16KB),递归修复所有后续 Segment/Section 的 `fileoff`、`offset`,以及重定位表、导出树(Export Trie)与符号表偏移。
|
||||
2. **新增私有防护段 (`__PROTECT`)**:
|
||||
* 写入一个全新的 `LC_SEGMENT_64`,段名为 `__PROTECT`,权限设为 `VM_PROT_READ`。
|
||||
* 确保其 `fileoff` 与 `vmaddr` 严格满足 `0x4000`(16KB)对齐。
|
||||
* 用于存放抽取出的加密代码、加密 Objective-C 元数据及白盒秘钥表。
|
||||
3. **修复 `LC_CODE_SIGNATURE` 边界**:
|
||||
* 修改前先抹除旧签名指令,加固完成后将 `LC_CODE_SIGNATURE` 重新定位至文件尾部。
|
||||
|
||||
### 2. Class-Dump 彻底防御与动态重映射 (Metadata Protector)
|
||||
|
||||
* **模块目标**:让 `class-dump`、`dscli`、IDA、Hopper 无法导出任何业务类名、属性名和方法名。
|
||||
* **加固实现链路**:
|
||||
1. **静态扫描与元数据序列化**:
|
||||
* 定位 `__DATA,__objc_classlist` 段,遍历每个 `objc_class` 结构体,沿着指针提取 `class_ro_t`:
|
||||
* `const char *name`(类名)
|
||||
* `method_list_t *baseMethods`(方法列表:包含 `SEL name`, `const char *types`, `IMP imp`)
|
||||
* `ivar_list_t *ivars`、`property_list_t *baseProperties`、`protocol_list_t *baseProtocols`
|
||||
* 扫描 `__TEXT,__objc_methname`、`__TEXT,__objc_classname`。
|
||||
* 将这些数据序列化为私有二进制格式,使用 ChaCha20-Poly1305 加密存入 `__PROTECT` 段。
|
||||
2. **Mach-O 元数据清洗与置空**:
|
||||
* 将 `__TEXT,__objc_methname` 节内的所有 ASCII 字符串重置为 `\0` 或覆盖为伪造的无害字符(如系统库常见名称)。
|
||||
* 将 `class_ro_t` 的 `baseMethods` 指针置为 `NULL`,或指向一个仅包含假初始化方法的假列表。
|
||||
3. **运行时受控动态还原 (Dynamic Relocation)**:
|
||||
* 守护库 `libDefender.dylib` 注册在 Mach-O 的 `LC_LOAD_DYLIB` 列表最顶部,拥有最优先加载权。
|
||||
* 在 `+load` 执行前的 `__mod_init_func`(C++ 全局构造器阶段):
|
||||
1. 从 `__PROTECT` 内存段解密元数据;
|
||||
2. 遍历类对象,调用 Objective-C 底层 API(如 `class_addMethod`)或直接在内存中修正 `class_rw_t` 的方法切片(Method Slice);
|
||||
3. 建立内存映射快速索引表,确保 `objc_msgSend` 消息分发完全正常。
|
||||
|
||||
### 3. 原生代码虚拟化 (VMP) 引擎 (Code Virtualization)
|
||||
|
||||
* **模块目标**:对抗 IDA/Ghidra 反编译,将关键 ARM64 机器码逻辑编译或抽取为自定义私有字节码,通过内嵌解释器执行。
|
||||
* **架构设计**:
|
||||
```
|
||||
原始 ARM64 函数逻辑 ===> [ VMP Compiler ] ===> 私有字节码 (Bytecode Stream)
|
||||
+
|
||||
[ VM 解释器状态机 (C/汇编) ]
|
||||
```
|
||||
* **核心组件设计**:
|
||||
1. **私有指令集设计 (Custom IR / ISA)**:
|
||||
* 设计约 30~45 条紧凑指令:`VM_NOP`, `VM_LOAD`, `VM_STORE`, `VM_ADD`, `VM_SUB`, `VM_XOR`, `VM_CMP`, `VM_JMP`, `VM_JZ`, `VM_CALL`, `VM_RET` 等。
|
||||
* 操作码(Opcode)每次构建随机重映射(例如构建 A 中 `0x1A` 代表加法,构建 B 中 `0x7F` 代表加法)。
|
||||
2. **上下文栈帧与寄存器映射 (Context Simulation)**:
|
||||
* 定义 `VMContext` 结构体,模拟通用寄存器(`X0`~`X30`)、栈指针(`SP`)、状态标志寄存器(`NZCV`)。
|
||||
* 当进入加固函数时,跳板代码(Trampoline)将真实 CPU 寄存器压入栈,并将其值拷贝至 `VMContext`。
|
||||
3. **纯解释型分发器(不破坏 W^X 合规红线)**:
|
||||
* 严禁调用 `mprotect(PROT_EXEC)`。
|
||||
* 采用 **Direct-Threaded Code(直接线程代码 / 间接跳转表)** 循环:
|
||||
```c
|
||||
void VM_Execute(VMContext *ctx, const uint8_t *bytecode) {
|
||||
static const void *dispatch_table[] = { &&do_nop, &&do_load, &&do_add, ... };
|
||||
#define DISPATCH() goto *dispatch_table[*pc++]
|
||||
// ... 寄存器状态机流转 ...
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 全维度内核级主动防御对抗矩阵 (Defender Core)
|
||||
|
||||
* **模块目标**:以静态库或注入动态库形式驻留进程,全面压制逆向与动态分析工具。
|
||||
* **五大防御维度实现细节**:
|
||||
|
||||
```
|
||||
主动防御矩阵 (Defender Core)
|
||||
├── 1. 内核级反调试 (Anti-Debug)
|
||||
│ ├── 内联汇编 SVC 0x80 调用 ptrace(PT_DENY_ATTACH, 0, 0, 0)
|
||||
│ ├── sysctl 轮询检查 kinfo_proc.kp_proc.p_flag 包含 P_TRACED
|
||||
│ ├── 硬件断点探测:thread_get_state 获取 ARM_DEBUG_STATE64,比对 bvr/bcr 寄存器
|
||||
│ └── Mach 异常端口劫持:task_set_exception_ports 抢占 EXC_BREAKPOINT / EXC_BAD_ACCESS
|
||||
├── 2. 反 Hook 与反 Frida (Anti-Hook & Anti-Frida)
|
||||
│ ├── 扫描加载模块:_dyld_get_image_name 校验是否存在 frida-agent, CydiaSubstrate, Dobby
|
||||
│ ├── 检测默认端口 (27042) 与探测本地 loopback 反向 socket 连接
|
||||
│ ├── 线程检测:遍历 task_threads,检测线程名为 "gum-js-loop"、"gmain"
|
||||
│ ├── 函数头 Inline Hook 探测:校验关键函数(open, ptrace, exit)前 16 字节是否包含 "LDR PC, [PC, #0]" 或 "BR X16"
|
||||
│ └── GOT 表边界检测:校验 __la_symbol_ptr / __got 内函数指针是否位于合法 Dyld Shared Cache 内存空间
|
||||
├── 3. 越狱与沙盒感知 (Anti-Jailbreak)
|
||||
│ ├── 特征路径扫描:/Applications/Cydia.app, /bin/sh, /usr/sbin/sshd, /var/jb 等
|
||||
│ ├── 沙盒逃逸写入探测:尝试向 /private/jailbreak_test 写入文件
|
||||
│ ├── 环境变量检查:getenv("DYLD_INSERT_LIBRARIES")
|
||||
│ └── 内核限制探测:调用 fork(),未越狱沙盒环境必返回 -1 (errno=EPERM)
|
||||
├── 4. 内存完整性保护 (Anti-Patch)
|
||||
│ ├── 运行时读取 Mach-O 的 __TEXT,__text 内存页
|
||||
│ └── 计算 SHA256 模糊哈希并与静态基线比对,防止内存被动态打补丁 (Memory Patch)
|
||||
└── 5. 白盒密码学 (Whitebox Cryptography)
|
||||
└── 实现白盒 AES-128 / SM4 算法,将密钥彻底融合至预计算查找表 (LUT),防止内存 Dump Key
|
||||
```
|
||||
|
||||
### 5. 双符号表体系与 dSYM 崩溃逆向还原 (Dual-Symbol & Crash Restorer)
|
||||
|
||||
* **痛点**:加固导致线上崩溃日志(Sentry / Bugly / Crashlytics)堆栈全为无意义字符(如 `_a8f9bc71()`),严重影响线上问题排查。
|
||||
* **实现方案**:
|
||||
1. **构建双向映射数据库 (`mapping.sqlite` / `mapping.json`)**:
|
||||
* 记录格式:`{ MD5(Raw_Signature): { raw_name: "LoginManager", obfuscated_name: "a7c2d8", type: "class", file: "LoginManager.m" } }`。
|
||||
2. **DWARF 调试文件反向重写引擎 (dSYM Restorer)**:
|
||||
* 解析 Release 构建生成的原始 `App.app.dSYM` 中的 Mach-O(DWARF 结构)。
|
||||
* 解析 `.debug_info` 节中的编译单元(Compilation Units)和调试信息条目(DIE)。
|
||||
* 解析 `.debug_str`(字符串池)与 `.debug_line`(行号状态机)。
|
||||
* 建立 DWARF 字符串重映射管道,将里面的混淆名批量替换回 `raw_name`。
|
||||
* 产出无缝还原后的 `Restored_App.app.dSYM`,直接上传至 Bugly/Sentry。
|
||||
|
||||
### 6. 资源与游戏资产保护 (Assets & Game Protection)
|
||||
|
||||
1. **静态免加密文件 Hash 扰动**:
|
||||
* 针对 PNG:向 PNG 插入合规私有 chunk(如 `tEXt` 注入随机 UUID),MD5 彻底改变,渲染完全正常。
|
||||
* 针对 MP3/MP4/PDF:文件末尾追加随机长度的填充字节(Padding)。
|
||||
2. **深度资源透明加密与虚拟文件系统 Hook**:
|
||||
* 加密算法:ChaCha20-Poly1305。
|
||||
* Hook 拦截层:
|
||||
* 底层 C API(POSIX):`open`、`fopen`、`stat`、`lstat`、`read`、`fread`(基于 `fishhook`)。
|
||||
* Cocoa 框架层:`[NSData dataWithContentsOfFile:]`、`[UIImage imageNamed:]`、`[NSBundle pathForResource:ofType:]`(基于 Method Swizzling)。
|
||||
* 拦截后在内存中执行无落盘解密(In-Memory Decryption),外部工具解压 IPA 只能看到乱码文件。
|
||||
3. **Unity 与 Cocos 专项防护**:
|
||||
* **Unity IL2CPP**:加密 `global-metadata.dat`,Hook `il2cpp::vm::MetadataCache::Initialize()` 动态解密;对 `Classes/Native` 的 C++ 符号深度平坦化。
|
||||
* **Cocos**:对 `src` 目录下的 LuaJIT 字节码或 JS 脚本添加自定义文件头混淆,Hook 引擎底层 `FileUtils::getDataFromFile`。
|
||||
|
||||
### 7. 跨平台自动化重签名流水线 (Cross-Platform Signer Engine)
|
||||
|
||||
* **模块目标**:支持在 **macOS(本地终端)** 与 **Linux/Docker(SaaS 云端服务器)** 两种环境下全自动完成加固后 IPA 的重签名。
|
||||
* **签名核心算法实现流程 (严格顺序)**:
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
participant Runner as 签名调度器
|
||||
participant Prov as Mobileprovision 与 Entitlements 协调
|
||||
participant Dylibs as Frameworks/PlugIns (内部组件)
|
||||
participant Res as CodeResources 资源清单
|
||||
participant MachO as 主可执行文件 Header 与 CodeDirectory
|
||||
participant CMS as OpenSSL 签名核
|
||||
|
||||
Runner->>Prov: 解析 embedded.mobileprovision 提取授权范围
|
||||
Runner->>Prov: 协调生成目标所需 Entitlements (XML + DER 编码)
|
||||
Runner->>Dylibs: 先行签名内部 Frameworks/*.dylib 与 *.framework
|
||||
Runner->>Dylibs: 先行签名 PlugIns/*.appex (独立 Entitlements 与 BundleID)
|
||||
Runner->>Res: 扫描 Bundle 全部文件生成 _CodeSignature/CodeResources
|
||||
Runner->>MachO: 预先计算 SuperBlob 大小,在 Header 预设 LC_CODE_SIGNATURE (dataoff=codeLimit, datasize=blob_size)
|
||||
Runner->>MachO: 将 CodeResources 的 SHA256 填入 CodeDirectory Slot -3 (极关键)
|
||||
Runner->>MachO: 将 Info.plist、Entitlements 哈希填入 Slot -1, -2, -5, -7
|
||||
Runner->>MachO: 按 16KB 页面计算 0..codeLimit 范围内的代码页 SHA256 填入 Slot 0..N
|
||||
Runner->>CMS: 传入完整的 CodeDirectory 序列化字节数据,由 OpenSSL 生成 PKCS#7 签名
|
||||
Runner->>MachO: 组装 SuperBlob (包含 0, 2, 5, 7, 0x10000 槽位) 回写至 dataoff 偏移
|
||||
Runner->>Runner: 重新打包为 Payload 结构并压缩为 .ipa
|
||||
```
|
||||
* **跨平台工具选型**:
|
||||
* **macOS 环境**:直接调用系统 `codesign -f -s ... --entitlements ... --generate-entitlement-der`。
|
||||
* **Linux / Docker 环境**:集成自研 C++ 签名模块(基于 `zsign` 内核改造),使用 OpenSSL 3.0 解析 `.p12` 证书私钥,手动构建完整的 Apple `SuperBlob` 二进制数据结构。
|
||||
|
||||
### 8. IPA 相似度预检中心 (App Store 4.3 预检器)
|
||||
|
||||
* **模块目标**:在提审前评估加固包与母包(或老版本)的相似度,规避 App Store 4.3 / 2.3.1 拒审。
|
||||
* **算法度量指标**:
|
||||
1. **代码段模糊哈希(SSDEEP / TLSH)**:提取主 Mach-O `__TEXT,__text` 段,计算基于上下文触发分段哈希(CTPH),比对机器码序列相似度。
|
||||
2. **符号表 Jaccard 相似系数**:计算两包之间导出的类名、方法名集合交并比:$J(A, B) = \frac{|A \cap B|}{|A \cup B|}$。
|
||||
3. **资源感知哈希(pHash & SSIM)**:对所有图片计算感知哈希与结构相似性,检测图片指纹重合度。
|
||||
4. **内部风控基准评分**:内部相似度 $< 35\%$ 判定为低相似度;$35\% \sim 50\%$ 建议调换混淆特征库;$> 50\%$ 建议内部阻断提审。(注:苹果 4.3 条款为人工审查与机审结合的行为政策,指标仅作内部风控参考,不构成绝对过审保证)。
|
||||
|
||||
---
|
||||
|
||||
## 三、 工程代码组织与目录结构 (Repository Layout)
|
||||
|
||||
```
|
||||
iOSGuard/
|
||||
├── bin/ # 编译输出的可执行文件 (cli, zsign-mod)
|
||||
├── core/ # 核心 C/C++ / Rust 跨平台加固引擎
|
||||
│ ├── macho/ # Mach-O 解析与重构器
|
||||
│ │ ├── macho_parser.cpp # Header, Load Commands, Section 解析
|
||||
│ │ ├── macho_rewriter.cpp # Header扩容、段平移、LC_LOAD_DYLIB 注入
|
||||
│ │ └── macho_align.cpp # 0x4000 页面对齐校准
|
||||
│ ├── metadata/ # Objective-C 元数据清洗与加密
|
||||
│ │ ├── objc_extractor.cpp # 抽取 __objc_classlist, class_ro_t
|
||||
│ │ └── objc_scrambler.cpp # 符号置空与加密段生成
|
||||
│ ├── vmp/ # 原生代码虚拟化引擎
|
||||
│ │ ├── vmp_compiler.cpp # 汇编 -> 私有字节码翻译器
|
||||
│ │ ├── vmp_isa.h # 私有指令集定义
|
||||
│ │ └── vm_interpreter.c # 运行时解释器状态机
|
||||
│ └── signer/ # 跨平台重签名核心 (基于 zsign 扩展)
|
||||
│ ├── codesign_engine.cpp# CodeDirectory, SuperBlob, CMS 构建
|
||||
│ ├── der_encoder.cpp # DER-encoded Entitlements 编码器
|
||||
│ └── resource_signer.cpp# _CodeSignature/CodeResources 生成器
|
||||
├── defender/ # 注入的运行时防护库源码 (输出 libDefender.dylib)
|
||||
│ ├── anti_debug/ # 内联 SVC 汇编、硬件断点轮询
|
||||
│ ├── anti_hook/ # Inline Hook 校验、Dyld GOT 范围比对
|
||||
│ ├── anti_frida/ # 端口探测、线程扫描、动态库匹配
|
||||
│ ├── anti_jailbreak/ # 沙盒感知、fork 检测、关键路径
|
||||
│ ├── vfs_crypto/ # 资源透明解密 Hook (open/read/imageNamed)
|
||||
│ └── dynamic_loader/ # 元数据内存解密与动态注册 (+load 前执行)
|
||||
├── llvm-plugins/ # 源码加固 LLVM Pass (集成至 Xcode)
|
||||
│ ├── Flattening.cpp # 控制流平坦化 Pass
|
||||
│ ├── BogusControlFlow.cpp # 虚假控制流 Pass
|
||||
│ ├── StringEncryption.cpp # 常量字符串加密 Pass
|
||||
│ └── CallStackObfuscate.cpp # 调用栈蹦床代理 Pass
|
||||
├── tools/ # 辅助工具链
|
||||
│ ├── dsym_restorer/ # dSYM 崩溃逆向还原工具 (DWARF 重写)
|
||||
│ ├── ipa_diff_analyzer/ # IPA 4.3 相似度静态评估分析器
|
||||
│ └── pbx_injector/ # Xcode 工程配置与 Build Phase 自动化注入
|
||||
├── cli/ # 命令行交互工具 (Go / Python 实现)
|
||||
└── web/ # SaaS 云端管理后台 (前端 Vue / 后端 Go)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、 实施路线图与阶段性交付物
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M1["里程碑 1 (MVP)\nPadding充足下注入\n+ macOS 原生签名闭环"] --> M2["里程碑 2\n段平移与Fixup修复\n+ ObjC 动态元数据恢复"]
|
||||
M2 --> M3["里程碑 3\nLLVM 编译混淆\n+ dSYM 崩溃符号化还原"]
|
||||
M3 --> M4["里程碑 4\n代码虚拟化 (VMP)\n+ 游戏资产保护"]
|
||||
M4 --> M5["里程碑 5\n4.3 预检分析器\n+ 商业平台化"]
|
||||
```
|
||||
|
||||
| 阶段 | 周期 | 研发重点与技术验证 | 关键交付产物 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **M1: 极简闭环验证 (MVP 收敛范围)** | 3~4 周 | 1. **目标载体**:自有简单 arm64 测试 App(UIKit/SwiftUI);<br>2. **注入约束**:仅在 Header Padding 充足条件下验证 `LC_LOAD_DYLIB` 原地注入(空间不足直接拒绝,不盲目平移);<br>3. **依赖与路径**:物理嵌入 `libDefender.dylib` 至 `Payload/App.app/Frameworks/`,解析并验证 `@rpath` 依赖链;<br>4. **签名验证**:使用 macOS 原生 `codesign`(带 `--generate-entitlement-der`);<br>5. **真机闭环**:验证真机安装、冷启动通过、`libDefender` 基础合规反调试生效、制造崩溃并跑通 dSYM 符号化还原。 | 1. 自建 arm64 测试工程<br>2. `libDefender.dylib` 最小原型<br>3. 原地注入脚本与重签流水线<br>4. 真机冷启与崩溃还原验证报告 |
|
||||
| **M2: Mach-O 进阶加固与重定位修复** | 5 周 | 1. 攻克全局段平移(Segment Shift)与 `LC_DYLD_CHAINED_FIXUPS` 重定位链表重构;<br>2. 实施 Objective-C 元数据精细化抽取与 ASLR 动态还原;<br>3. 验证 Linux 端 `zsign` 无 Mac 依赖签名闭环。 | 1. 支持段平移的 `macho_rewriter`<br>2. 保持语义的 `objc_scrambler`<br>3. Linux Docker 自动化签名工具 |
|
||||
| **M3: LLVM 编译管线与 dSYM 深度还原** | 5 周 | 1. 研发控制流平坦化、虚假分支与常量字符串加密 LLVM Pass;<br>2. 完善 DWARF 重写工具,确保 UUID 严格匹配。 | 1. Xcode 自定义 LLVM Toolchain / Plugin<br>2. `dsym_restorer` 崩溃堆栈还原器 |
|
||||
| **M4: 原生代码虚拟化 (VMP) 与游戏加固** | 6 周 | 1. 完善基于 ARM64 的私有解释型虚拟机 (VMP),补充边界安全检查与异常退出;<br>2. 实现 Unity `global-metadata.dat` 加密与 Cocos 脚本内存流解密。 | 1. 包含安全防御的 `vmp_compiler` 与 `vm_interpreter`<br>2. Unity / Cocos 游戏专用加固套件 |
|
||||
| **M5: 4.3 审核预检与商业化平台** | 4 周 | 1. 实现基于 SSDEEP 与符号图谱的内部风控评分算法;<br>2. 构建 SaaS 网页端控制台或跨平台桌面客户端 (macOS/Windows)。 | 1. `ipa_diff` 相似度检测中心<br>2. 完整的商业级加固发布包 |
|
||||
@@ -1,890 +0,0 @@
|
||||
# iOSGuard 八大核心子系统详细设计与实现方案
|
||||
|
||||
本文档为 **iOSGuard** 企业级加固系统的八大核心子系统技术白皮书。每个子系统均提供:**设计目标、核心数据结构与接口、底层算法与实现流程、汇编与代码原型、技术陷阱与规避策略**。
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
1. [子系统 1:Mach-O 深度重构与二进制引擎 (Mach-O Rewriter)](#1-mach-o-深度重构与二进制引擎-mach-o-rewriter)
|
||||
2. [子系统 2:Class-Dump 彻底防御与动态重映射 (Metadata Protector)](#2-class-dump-彻底防御与动态重映射-metadata-protector)
|
||||
3. [子系统 3:原生代码虚拟化 (VMP) 引擎 (Code Virtualization)](#3-原生代码虚拟化-vmp-引擎-code-virtualization)
|
||||
4. [子系统 4:全维度内核级主动防御对抗矩阵 (Defender Core)](#4-全维度内核级主动防御对抗矩阵-defender-core)
|
||||
5. [子系统 5:双符号表体系与 dSYM 崩溃逆向还原 (Dual-Symbol & Crash Restorer)](#5-双符号表体系与-dsym-崩溃逆向还原-dual-symbol--crash-restorer)
|
||||
6. [子系统 6:资产保护与无感透明解密 (Virtual File System & Assets Protector)](#6-资产保护与无感透明解密-virtual-file-system--assets-protector)
|
||||
7. [子系统 7:跨平台自动化重签名流水线 (Cross-Platform Signer Engine)](#7-跨平台自动化重签名流水线-cross-platform-signer-engine)
|
||||
8. [子系统 8:IPA 相似度预检中心 (App Store 4.3 预检器)](#8-ipa-相似度预检中心-app-store-43-预检器)
|
||||
|
||||
---
|
||||
|
||||
## 1. Mach-O 深度重构与二进制引擎 (Mach-O Rewriter)
|
||||
|
||||
### 1.1 设计目标
|
||||
在无源码条件下解析 IPA 中的主 Mach-O 与 Dynamic Frameworks,完成:
|
||||
1. 安全注入 `LC_LOAD_DYLIB` 加载加固守护动态库 `libDefender.dylib`;
|
||||
2. 新增私有加密段 `__PROTECT`(存放抽取函数、加密元数据、白盒查找表);
|
||||
3. 严格遵循 ARM64 `0x4000`(16KB)页面对齐规范,保证重签名后 AMFI 校验通过。
|
||||
|
||||
### 1.2 核心数据结构
|
||||
```cpp
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
struct MachOBinary {
|
||||
mach_header_64 header;
|
||||
std::vector<uint8_t> raw_data;
|
||||
std::vector<load_command*> load_commands;
|
||||
segment_command_64* text_segment;
|
||||
segment_command_64* linkedit_segment;
|
||||
linkedit_data_command* code_signature_cmd;
|
||||
uint32_t header_padding_size;
|
||||
};
|
||||
```
|
||||
|
||||
### 1.3 底层算法与 M1 注入逻辑
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["读取并校验 Mach-O 边界\nbinary.size >= sizeof(mach_header_64)"] --> B["遍历与校验 load_commands\n边界检查: cmdsize >= 8 且在 cmds_end 范围内"]
|
||||
B --> C["遍历 LC_SEGMENT_64 与 sections\n统计真实存在的第一节最小 offset (found_valid_section)"]
|
||||
C --> D{"有效性安全检查\nfound_valid_section && first_section_offset >= header_and_cmds && <= binary.size"}
|
||||
D -- "检查不通过" --> D1["退出拒绝处理 (防御非法头部/下溢/越界)"]
|
||||
D -- "通过" --> E{"检测可用 Padding 空间\navailable_padding = first_section_offset - header_and_cmds"}
|
||||
E -- "available_padding >= cmd_size" --> F["M1 MVP 路径: 原地追加 LC_LOAD_DYLIB\n更新 ncmds & sizeofcmds 并写入 @rpath 路径"]
|
||||
E -- "available_padding 不足" --> G["M1 策略: 直接拒绝,报错退出\n(段平移与 Fixup 重构隔离至 M2 研发)"]
|
||||
```
|
||||
|
||||
#### 代码实现原型:严格边界防御的 LC_LOAD_DYLIB 原地注入
|
||||
```cpp
|
||||
bool InjectDylib(std::vector<uint8_t>& binary, const std::string& dylib_path) {
|
||||
// 1. 基础头部尺寸校验
|
||||
if (binary.size() < sizeof(mach_header_64)) return false;
|
||||
auto* header = reinterpret_cast<mach_header_64*>(binary.data());
|
||||
if (header->magic != MH_MAGIC_64) return false;
|
||||
|
||||
// 2. sizeofcmds 边界校验
|
||||
uint32_t header_and_cmds = sizeof(mach_header_64) + header->sizeofcmds;
|
||||
if (binary.size() < header_and_cmds) return false;
|
||||
|
||||
// 3. 计算对齐后的 dylib_command 大小 (8 字节对齐)
|
||||
uint32_t cmd_size = sizeof(dylib_command) + dylib_path.length() + 1;
|
||||
cmd_size = (cmd_size + 7) & ~7;
|
||||
|
||||
uint8_t* cmds_start = binary.data() + sizeof(mach_header_64);
|
||||
uint8_t* cmds_end = cmds_start + header->sizeofcmds;
|
||||
|
||||
// 4. 遍历所有 Load Commands 并严格检查边界,查找首个 Section 偏移
|
||||
uint32_t first_section_offset = UINT32_MAX;
|
||||
bool found_valid_section = false;
|
||||
uint8_t* cur_cmd = cmds_start;
|
||||
|
||||
for (uint32_t i = 0; i < header->ncmds; i++) {
|
||||
if (cur_cmd + sizeof(load_command) > cmds_end) return false;
|
||||
auto* lc = reinterpret_cast<load_command*>(cur_cmd);
|
||||
if (lc->cmdsize < sizeof(load_command) || cur_cmd + lc->cmdsize > cmds_end) {
|
||||
return false; // 非法 cmdsize
|
||||
}
|
||||
|
||||
if (lc->cmd == LC_SEGMENT_64) {
|
||||
if (cur_cmd + sizeof(segment_command_64) > cmds_end) return false;
|
||||
auto* sc = reinterpret_cast<segment_command_64*>(cur_cmd);
|
||||
if (cur_cmd + sizeof(segment_command_64) + sc->nsects * sizeof(section_64) > cmds_end) {
|
||||
return false; // Section 数组超出 load commands 边界
|
||||
}
|
||||
auto* sec = reinterpret_cast<section_64*>(cur_cmd + sizeof(segment_command_64));
|
||||
for (uint32_t j = 0; j < sc->nsects; j++) {
|
||||
// 仅统计实际存在于文件内的有效非零偏移 Section
|
||||
if (sec[j].offset > 0 && sec[j].size > 0) {
|
||||
if (sec[j].offset < first_section_offset) {
|
||||
first_section_offset = sec[j].offset;
|
||||
found_valid_section = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cur_cmd += lc->cmdsize;
|
||||
}
|
||||
|
||||
// 5. 严格防御:无 Section、偏移异常或首节偏移超出文件长度时直接拒绝,彻底杜绝下溢
|
||||
if (!found_valid_section || first_section_offset < header_and_cmds || first_section_offset > binary.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t available_padding = first_section_offset - header_and_cmds;
|
||||
|
||||
// 6. M1 策略:Padding 空间充足时原地写入,不足时直接拒绝处理
|
||||
if (available_padding < cmd_size || header_and_cmds + cmd_size > binary.size()) {
|
||||
// 空间不足,在 M1 阶段明确拒绝,不隐式调用段平移
|
||||
return false;
|
||||
}
|
||||
|
||||
// 原地写入 LC_LOAD_DYLIB
|
||||
auto* new_cmd = reinterpret_cast<dylib_command*>(cmds_start + header->sizeofcmds);
|
||||
memset(new_cmd, 0, cmd_size);
|
||||
new_cmd->cmd = LC_LOAD_DYLIB;
|
||||
new_cmd->cmdsize = cmd_size;
|
||||
new_cmd->dylib.name.offset = sizeof(dylib_command);
|
||||
new_cmd->dylib.timestamp = 2;
|
||||
new_cmd->dylib.current_version = 0x10000;
|
||||
new_cmd->dylib.compatibility_version = 0x10000;
|
||||
memcpy(reinterpret_cast<char*>(new_cmd) + sizeof(dylib_command), dylib_path.c_str(), dylib_path.length() + 1);
|
||||
|
||||
header->ncmds += 1;
|
||||
header->sizeofcmds += cmd_size;
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
### 1.4 M1 运行环境与 @rpath 依赖解析
|
||||
在 M1 真机验收中,注入的 `libDefender.dylib` 必须满足动态链接器解析路径:
|
||||
1. **注入路径规范**:推荐使用 `@rpath/libDefender.dylib`;
|
||||
2. **实际物理嵌入**:IPA 解包后,必须将 `libDefender.dylib` 拷贝至 `Payload/App.app/Frameworks/libDefender.dylib`;
|
||||
3. **LC_RPATH 校验**:主二进制必须包含 `LC_RPATH` 指向 `@executable_path/Frameworks`,若不存在需在注入时同步检测并补齐。
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 2. Class-Dump 彻底防御与动态重映射 (Metadata Protector)
|
||||
|
||||
### 2.1 设计目标
|
||||
消除 Mach-O 静态暴露的所有 Objective-C 类名、分类、选择器和属性元数据,使 `class-dump`、`dscli`、Hopper、IDA 彻底无法还原符号;同时通过运行时受控动态注册,确保 `objc_msgSend` 与 KVC 正常运作。
|
||||
|
||||
### 2.2 Objective-C 64位运行时结构体解构
|
||||
```c
|
||||
struct objc_class_64 {
|
||||
uint64_t isa;
|
||||
uint64_t superclass;
|
||||
uint64_t cache;
|
||||
uint64_t vtable;
|
||||
uint64_t data; // 指向 class_rw_t 或 class_ro_t
|
||||
};
|
||||
|
||||
struct class_ro_t_64 {
|
||||
uint32_t flags;
|
||||
uint32_t instanceStart;
|
||||
uint32_t instanceSize;
|
||||
uint32_t reserved;
|
||||
uint64_t ivarLayout;
|
||||
uint64_t name; // 指向 __objc_classname 字符串
|
||||
uint64_t baseMethods; // 指向 method_list_t
|
||||
uint64_t baseProtocols;
|
||||
uint64_t ivars;
|
||||
uint64_t weakIvarLayout;
|
||||
uint64_t baseProperties;
|
||||
};
|
||||
|
||||
struct method_t_64 {
|
||||
uint64_t name; // 指向 __objc_methname
|
||||
uint64_t types; // 指向 __objc_methtype (真实类型编码,如 "@16@0:8")
|
||||
uint64_t imp; // 函数虚拟地址 (相对Mach-O vmaddr基地址)
|
||||
};
|
||||
|
||||
// iOS 14+ 广泛采用的小方法列表 (Relative Method List)
|
||||
struct method_list_t_relative {
|
||||
uint32_t entsizeAndFlags; // 包含 0x80000000 相对寻址标记
|
||||
uint32_t count;
|
||||
// 相对偏移结构体: 每个字段为相对于字段自身地址的 int32_t 偏移
|
||||
struct method_relative_t {
|
||||
int32_t name_offset;
|
||||
int32_t types_offset;
|
||||
int32_t imp_offset;
|
||||
} methods[];
|
||||
};
|
||||
```
|
||||
|
||||
### 2.3 加固与还原流程
|
||||
|
||||
```
|
||||
[编译加固期 (Mach-O 离线重写)]
|
||||
1. 扫描 __DATA,__objc_classlist 提取 class_ro_t 与元类 (Meta-Class)
|
||||
2. 序列化 {ClassName, [is_meta, Selector, ImpVMAddr, TypeEncoding]} 为私有二进制
|
||||
3. 使用 ChaCha20-Poly1305 加密存入 __PROTECT,__meta 节
|
||||
4. 清空非白名单的 __TEXT,__objc_methname (填 '\0'),将 class_ro_t->baseMethods 置空
|
||||
│
|
||||
▼
|
||||
[运行时阶段 (libDefender 早期构造器 __mod_init_func)]
|
||||
1. 获取目标 Mach-O 的 ASLR 偏移 (Slide = _dyld_get_image_vmaddr_slide(index))
|
||||
2. 解密元数据,准确按类型注回:
|
||||
- 实例方法注回目标类 cls
|
||||
- 类方法注回元类 object_getClass(cls)
|
||||
3. 使用真实 TypeEncoding 与 (ImpVMAddr + Slide) 动态注册
|
||||
4. 对 +load、KVC 敏感类与系统协议建立白名单豁免机制
|
||||
```
|
||||
|
||||
#### 运行时动态重映射 Hook 原型 (严格流同步与边界防御版)
|
||||
```objc
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <objc/runtime.h>
|
||||
#import <mach-o/dyld.h>
|
||||
|
||||
void RestoreObjcMetadata(const uint8_t *decrypted_meta, size_t size, intptr_t slide) {
|
||||
if (!decrypted_meta || size == 0) return;
|
||||
|
||||
size_t offset = 0;
|
||||
while (offset + 2 <= size) {
|
||||
// 1. 安全读取类名长度与字符串
|
||||
uint16_t name_len = *(uint16_t*)(decrypted_meta + offset);
|
||||
offset += 2;
|
||||
if (name_len == 0 || name_len >= 256 || offset + name_len > size) {
|
||||
break; // 数据流受损,安全终止
|
||||
}
|
||||
char class_name[256] = {0};
|
||||
memcpy(class_name, decrypted_meta + offset, name_len);
|
||||
offset += name_len;
|
||||
|
||||
// 查找目标类 (即便类不存在,游标也必须完整跳过后续方法体,绝不可直接 continue 导致流失步)
|
||||
Class cls = objc_getClass(class_name);
|
||||
Class meta_cls = cls ? object_getClass(cls) : nil;
|
||||
|
||||
// 2. 读取方法数量
|
||||
if (offset + 4 > size) break;
|
||||
uint32_t method_count = *(uint32_t*)(decrypted_meta + offset);
|
||||
offset += 4;
|
||||
|
||||
for (uint32_t i = 0; i < method_count; i++) {
|
||||
if (offset + 1 > size) break;
|
||||
uint8_t is_meta = *(uint8_t*)(decrypted_meta + offset++);
|
||||
|
||||
// 读取 Selector 名字
|
||||
if (offset + 2 > size) break;
|
||||
uint16_t sel_len = *(uint16_t*)(decrypted_meta + offset);
|
||||
offset += 2;
|
||||
if (sel_len >= 256 || offset + sel_len > size) break;
|
||||
char sel_name[256] = {0};
|
||||
memcpy(sel_name, decrypted_meta + offset, sel_len);
|
||||
offset += sel_len;
|
||||
|
||||
// 读取真实类型编码 (如 "@16@0:8" 或 "i24@0:8@16")
|
||||
if (offset + 2 > size) break;
|
||||
uint16_t type_len = *(uint16_t*)(decrypted_meta + offset);
|
||||
offset += 2;
|
||||
if (type_len >= 128 || offset + type_len > size) break;
|
||||
char type_encoding[128] = {0};
|
||||
memcpy(type_encoding, decrypted_meta + offset, type_len);
|
||||
offset += type_len;
|
||||
|
||||
// 读取静态 VM 地址并结合 ASLR Slide 计算真实函数入口
|
||||
if (offset + 8 > size) break;
|
||||
uint64_t imp_vmaddr = *(uint64_t*)(decrypted_meta + offset);
|
||||
offset += 8;
|
||||
|
||||
// 仅在类存在时执行注回;即使类缺失,游标也已完整解析完当前方法,下一记录依然对齐
|
||||
if (cls) {
|
||||
IMP real_imp = (IMP)(imp_vmaddr + slide);
|
||||
SEL sel = sel_registerName(sel_name);
|
||||
Class target_cls = is_meta ? meta_cls : cls;
|
||||
class_addMethod(target_cls, sel, real_imp, type_encoding);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.4 语义保持、分类顺序与共享 Selector 防线
|
||||
> [!IMPORTANT]
|
||||
> **Objective-C 进阶语义约束**:
|
||||
> 1. **分类 (Category) 覆盖顺序保持**:在 Objective-C 运行时中,分类的方法会被追加到类方法列表前端(优先命中)。元数据序列化时,必须保证**主类记录在前、分类记录在后**,运行时按序注回,以维持既有的分类覆盖优先级。
|
||||
> 2. **共享与系统 Selector 保护**:若某个 Selector 仍被系统 Framework(如 `UITableViewDelegate` 回调)、KVO 或未加固模块显式调用,**其 `__TEXT,__objc_methname` 字符串绝不可盲目抹除**,必须建立静态交叉引用扫描(Xref),只抹除非暴露、纯内部调用的私有 Selector。
|
||||
> 3. **`+load` 时序限制**:`+load` 在 dyld 加载镜像时由 `libobjc` 的 `prepare_load_methods` 内部直接读取并调用,早于 C++ 动态库构造器。因此**带有 `+load` 的类方法必须保留在静态结构中或采用动态桥接白名单**,不可盲目抹除。
|
||||
> 4. **JSON 反序列化与 KVC**:`YYModel` / `MJExtension` 依赖 `class_copyPropertyList` 和 `class_copyIvarList`。加固系统必须建立基于类的排除规则,对 Model 数据模型对象豁免元数据抹除。
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 3. 原生代码虚拟化 (VMP) 引擎 (Code Virtualization)
|
||||
|
||||
### 3.1 设计目标
|
||||
针对高敏感函数(如充值校验、密钥派生、核心通信协议),将其 ARM64 指令编译或抽取为私有字节码,通过纯解释型虚拟机(Interpreter-based VM)执行。**绝对不使用 `mprotect(PROT_EXEC)`,100% 遵从苹果 AMFI 与 W^X 规范**。
|
||||
|
||||
### 3.2 私有指令集 (Custom ISA) 规范设计
|
||||
指令格式采用 4 字节定长指令:`[Opcode 8bit] [Dest_Reg 8bit] [Src_Reg 8bit] [Immediate / Offset 8bit]`。
|
||||
|
||||
| Opcode | 汇编助记符 | 描述 | 操作数含义 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `0x11` | `VM_MOV_IMM` | 将立即数写入虚拟寄存器 | `dst = imm` |
|
||||
| `0x12` | `VM_MOV_REG` | 寄存器传值 | `dst = src` |
|
||||
| `0x21` | `VM_ADD` | 虚拟寄存器加法 | `dst = dst + src` |
|
||||
| `0x22` | `VM_SUB` | 虚拟寄存器减法 | `dst = dst - src` |
|
||||
| `0x25` | `VM_XOR` | 异或运算 | `dst = dst ^ src` |
|
||||
| `0x31` | `VM_LOAD64` | 内存加载 64 位值 | `dst = *(uint64_t*)(src + imm)` |
|
||||
| `0x32` | `VM_STORE64`| 写入内存 64 位值 | `*(uint64_t*)(dst + imm) = src` |
|
||||
| `0x41` | `VM_CMP` | 比较并更新标志位 | `flags = cmp(dst, src)` |
|
||||
| `0x51` | `VM_JMP` | 无条件跳转 | `pc += imm` |
|
||||
| `0x52` | `VM_JZ` | 为零跳转 | `if (flags.Z) pc += imm` |
|
||||
| `0x61` | `VM_CALL` | 调用原生 C 函数 | 调度真实函数指针 |
|
||||
| `0xFF` | `VM_RET` | 退出虚拟机并还原上下文 | 返回上层原生栈 |
|
||||
|
||||
### 3.3 解释器 Direct-Threaded 跳转循环实现原型 (含完整安全与异常边界)
|
||||
```c
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
// 执行结果结构体,区分正常返回值与执行错误
|
||||
typedef struct {
|
||||
bool success;
|
||||
uint64_t ret_val;
|
||||
uint32_t error_code; // 0: 正常, 1: 未知操作码, 2: 非法内存越界, 3: 指令跳转越界
|
||||
} VMResult;
|
||||
|
||||
typedef struct {
|
||||
uint64_t r[31]; // ARM64 x0 - x30 通用虚拟寄存器
|
||||
uint64_t sp; // 当前栈指针
|
||||
uint64_t sp_base; // 虚拟栈底边界 (安全检查)
|
||||
uint64_t sp_top; // 虚拟栈顶边界 (安全检查)
|
||||
uint64_t flags; // 标志位 NZCV
|
||||
} VMContext;
|
||||
|
||||
// 校验地址是否落在合法的虚拟栈或有效数据内存区内
|
||||
static inline bool is_vm_memory_accessible(const VMContext *ctx, uint64_t addr, size_t size) {
|
||||
if (addr < 4096) return false; // 严防空指针及低地址零页异常 (如 0x1)
|
||||
if (addr >= ctx->sp_base && addr + size <= ctx->sp_top) return true;
|
||||
return false; // 原型阶段严格限制在虚拟栈内存空间,后续扩展堆区白名单
|
||||
}
|
||||
|
||||
VMResult VMP_Execute(const uint8_t *bytecode, size_t bytecode_len, uint64_t arg0, uint64_t arg1) {
|
||||
VMResult result = {false, 0, 0};
|
||||
if (!bytecode || bytecode_len < 4) {
|
||||
result.error_code = 1;
|
||||
return result;
|
||||
}
|
||||
|
||||
VMContext ctx = {0};
|
||||
ctx.r[0] = arg0;
|
||||
ctx.r[1] = arg1;
|
||||
|
||||
size_t stack_size = 4096;
|
||||
void *stack_mem = malloc(stack_size);
|
||||
if (!stack_mem) {
|
||||
result.error_code = 2;
|
||||
return result;
|
||||
}
|
||||
ctx.sp_base = (uint64_t)stack_mem;
|
||||
ctx.sp_top = ctx.sp_base + stack_size;
|
||||
ctx.sp = ctx.sp_top; // 栈自顶向下生长
|
||||
|
||||
const uint8_t *pc = bytecode;
|
||||
const uint8_t *pc_end = bytecode + bytecode_len;
|
||||
|
||||
static const void *dispatch_table[256] = {
|
||||
[0x11] = &&op_mov_imm,
|
||||
[0x12] = &&op_mov_reg,
|
||||
[0x21] = &&op_add,
|
||||
[0x25] = &&op_xor,
|
||||
[0x31] = &&op_load64,
|
||||
[0x32] = &&op_store64,
|
||||
[0x41] = &&op_cmp,
|
||||
[0x52] = &&op_jz,
|
||||
[0xFF] = &&op_ret
|
||||
};
|
||||
|
||||
#define DISPATCH() \
|
||||
do { \
|
||||
if (pc + 4 > pc_end) { \
|
||||
result.error_code = 1; \
|
||||
goto vm_exit; \
|
||||
} \
|
||||
void *target = (void*)dispatch_table[*pc]; \
|
||||
if (!target) { \
|
||||
result.error_code = 1; /* 未知操作码,明确报错,绝不伪装正常返回 */ \
|
||||
goto vm_exit; \
|
||||
} \
|
||||
goto *target; \
|
||||
} while(0)
|
||||
|
||||
DISPATCH();
|
||||
|
||||
op_mov_imm: {
|
||||
uint8_t dst = pc[1];
|
||||
uint8_t imm = pc[3];
|
||||
if (dst < 31) ctx.r[dst] = imm;
|
||||
pc += 4;
|
||||
DISPATCH();
|
||||
}
|
||||
op_mov_reg: {
|
||||
uint8_t dst = pc[1];
|
||||
uint8_t src = pc[2];
|
||||
if (dst < 31 && src < 31) ctx.r[dst] = ctx.r[src];
|
||||
pc += 4;
|
||||
DISPATCH();
|
||||
}
|
||||
op_add: {
|
||||
uint8_t dst = pc[1];
|
||||
uint8_t src = pc[2];
|
||||
if (dst < 31 && src < 31) ctx.r[dst] += ctx.r[src];
|
||||
pc += 4;
|
||||
DISPATCH();
|
||||
}
|
||||
op_xor: {
|
||||
uint8_t dst = pc[1];
|
||||
uint8_t src = pc[2];
|
||||
if (dst < 31 && src < 31) ctx.r[dst] ^= ctx.r[src];
|
||||
pc += 4;
|
||||
DISPATCH();
|
||||
}
|
||||
op_load64: {
|
||||
uint8_t dst = pc[1];
|
||||
uint8_t src = pc[2];
|
||||
int8_t imm = (int8_t)pc[3]; // 正确计入 ISA 规范中定义的 imm 偏移
|
||||
if (dst < 31 && src < 31) {
|
||||
uint64_t target_addr = ctx.r[src] + imm;
|
||||
if (!is_vm_memory_accessible(&ctx, target_addr, 8)) {
|
||||
result.error_code = 2; // 内存越界/非法指针,明确捕获异常
|
||||
goto vm_exit;
|
||||
}
|
||||
ctx.r[dst] = *(uint64_t*)target_addr;
|
||||
}
|
||||
pc += 4;
|
||||
DISPATCH();
|
||||
}
|
||||
op_store64: {
|
||||
uint8_t dst = pc[1];
|
||||
uint8_t src = pc[2];
|
||||
int8_t imm = (int8_t)pc[3]; // 正确计入 ISA 规范中定义的 imm 偏移
|
||||
if (dst < 31 && src < 31) {
|
||||
uint64_t target_addr = ctx.r[dst] + imm;
|
||||
if (!is_vm_memory_accessible(&ctx, target_addr, 8)) {
|
||||
result.error_code = 2; // 内存越界/非法指针,明确捕获异常
|
||||
goto vm_exit;
|
||||
}
|
||||
*(uint64_t*)target_addr = ctx.r[src];
|
||||
}
|
||||
pc += 4;
|
||||
DISPATCH();
|
||||
}
|
||||
op_cmp: {
|
||||
uint8_t dst = pc[1];
|
||||
uint8_t src = pc[2];
|
||||
if (dst < 31 && src < 31) {
|
||||
ctx.flags = (ctx.r[dst] == ctx.r[src]) ? 1 : 0;
|
||||
}
|
||||
pc += 4;
|
||||
DISPATCH();
|
||||
}
|
||||
op_jz: {
|
||||
int8_t offset = (int8_t)pc[3];
|
||||
if (ctx.flags == 1) {
|
||||
const uint8_t *next_pc = pc + offset * 4;
|
||||
if (next_pc >= bytecode && next_pc + 4 <= pc_end) {
|
||||
pc = next_pc;
|
||||
} else {
|
||||
result.error_code = 3; // 跳转目标越界,明确报错
|
||||
goto vm_exit;
|
||||
}
|
||||
} else {
|
||||
pc += 4;
|
||||
}
|
||||
DISPATCH();
|
||||
}
|
||||
op_ret: {
|
||||
result.success = true;
|
||||
result.ret_val = ctx.r[0];
|
||||
result.error_code = 0;
|
||||
goto vm_exit;
|
||||
}
|
||||
|
||||
vm_exit:
|
||||
free(stack_mem);
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
### 3.4 虚拟化适用范围与验收边界
|
||||
> [!NOTE]
|
||||
> **VMP 研发边界与验收范围**:
|
||||
> 当前原型用于验证自定义字节码指令调度与寄存器映射机制。通用 C/C++/Swift 函数若包含浮点/SIMD(NEON `Q0~Q31`)、C++ 异常栈解退(`eh_frame`)、动态栈分配(`alloca`)或变长参数(`va_list`),需要完备的编译器后端支持。
|
||||
> **工程策略**:VMP 首期仅用于保护加固关键的算法、鉴权校验与密钥派生纯整型逻辑函数,不作为通用全量函数虚拟化方案。
|
||||
|
||||
---
|
||||
|
||||
## 4. 全维度内核级主动防御对抗矩阵 (Defender Core)
|
||||
|
||||
### 4.1 反调试机制与 App Store §2.5.1 公开 API 边界
|
||||
> [!CAUTION]
|
||||
> **iPhoneOS SDK 真实接口与提审红线**:
|
||||
> 在 iOS 官方 SDK(`iPhoneOS.platform`)中,**苹果并未提供公开的 `<sys/ptrace.h>` 头文件**。
|
||||
> `ptrace` 在 iOS 底层 `libSystem.dylib` 中被视作私有未公开符号。无论是直接调用、还是通过 `dlsym(RTLD_DEFAULT, "ptrace")` 动态查找并混淆符号名,均属于调用非公开 API,直接违反 **App Store Review Guideline §2.5.1**。
|
||||
>
|
||||
> **方案修正与合规边界**:
|
||||
> 1. **提审产物必须物理排除**:通过预编译宏 `#ifndef APPSTORE_RELEASE`,在生成提审包时**将 `PT_DENY_ATTACH`、`dlsym("ptrace")` 以及裸汇编 `svc #0x80` 源码彻底编译排除**,绝不残留任何私有符号或未文档化系统调用路径;
|
||||
> 2. **提审版反调试方案**:仅使用苹果公开文档许可的标准接口,即通过 `sysctl` 检查进程 `P_TRACED` 标志位;
|
||||
> 3. **内核级软中断定位**:裸汇编 `svc #0x80` 与 `PT_DENY_ATTACH` 仅供**企业内部分发 (Enterprise) / Ad-Hoc / 内部反作弊测试**使用,收回此前“可直接提审”和“完全合规”的不严谨表述。
|
||||
|
||||
```c
|
||||
#include <sys/types.h>
|
||||
#include <sys/sysctl.h>
|
||||
#include <unistd.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
// 1. App Store 提审合规反调试:仅依赖公开 documented sysctl API
|
||||
bool is_debugger_attached_appstore_compliant(void) {
|
||||
int name[4];
|
||||
struct kinfo_proc info;
|
||||
size_t info_size = sizeof(info);
|
||||
info.kp_proc.p_flag = 0;
|
||||
|
||||
name[0] = CTL_KERN;
|
||||
name[1] = KERN_PROC;
|
||||
name[2] = KERN_PROC_PID;
|
||||
name[3] = getpid();
|
||||
|
||||
if (sysctl(name, 4, &info, &info_size, NULL, 0) == -1) {
|
||||
return false;
|
||||
}
|
||||
// 检查进程标志位中的 P_TRACED
|
||||
return ((info.kp_proc.p_flag & P_TRACED) != 0);
|
||||
}
|
||||
|
||||
// 2. 企业版/内测专用反调试:裸汇编软中断 (提审构建时由预处理器物理排除)
|
||||
#ifndef APPSTORE_RELEASE
|
||||
__attribute__((always_inline)) static inline void anti_debug_enterprise_svc(void) {
|
||||
#if defined(__arm64__) || defined(__aarch64__)
|
||||
__asm__ volatile(
|
||||
"mov x0, #31\n" // PT_DENY_ATTACH (0x1f)
|
||||
"mov x1, #0\n"
|
||||
"mov x2, #0\n"
|
||||
"mov x3, #0\n"
|
||||
"mov x16, #26\n" // SYS_ptrace = 26
|
||||
"svc #0x80\n" // 仅用于企业签/反作弊对抗环境
|
||||
:
|
||||
:
|
||||
: "x0", "x1", "x2", "x3", "x16"
|
||||
);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
```
|
||||
|
||||
### 4.2 硬件断点 (DR0-DR7) 探测
|
||||
攻击者在 LLDB 或调试器中下硬件断点时,会写入 ARM64 调试寄存器。通过 `thread_get_state` 轮询检查:
|
||||
```c
|
||||
#include <mach/mach.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
bool check_hardware_breakpoints() {
|
||||
mach_port_t this_thread = mach_thread_self();
|
||||
arm_debug_state64_t state;
|
||||
mach_msg_type_number_t count = ARM_DEBUG_STATE64_COUNT;
|
||||
|
||||
kern_return_t kr = thread_get_state(this_thread, ARM_DEBUG_STATE64,
|
||||
(thread_state_t)&state, &count);
|
||||
mach_port_deallocate(mach_task_self(), this_thread);
|
||||
|
||||
if (kr == KERN_SUCCESS) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
// bvr 为断点地址寄存器,bcr 为控制寄存器 (bit 0 为启用位)
|
||||
if (state.__bcr[i] & 1) {
|
||||
return true; // 发现硬件执行断点!
|
||||
}
|
||||
if (state.__wcr[i] & 1) {
|
||||
return true; // 发现硬件观察点 (Watchpoint)!
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3 关键函数头 Inline Hook 探测 (Anti-Dobby / Anti-Substrate)
|
||||
Dobby / CydiaSubstrate 对 ARM64 函数 Hook 时,会在前 16 字节写入跳板指令(如 `LDR X16, #8; BR X16` 机器码 `0x58000050, 0xd61f0200`):
|
||||
```c
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
bool is_function_inline_hooked(void *func_ptr) {
|
||||
uint32_t *instructions = (uint32_t *)func_ptr;
|
||||
// 检查是否为 LDR X16, [PC, #8] (0x58000050) 紧跟 BR X16 (0xd61f0200)
|
||||
if (instructions[0] == 0x58000050 && instructions[1] == 0xd61f0200) {
|
||||
return true;
|
||||
}
|
||||
// 检查直接 B / BL 跳转 (0x14000000 掩码)
|
||||
if ((instructions[0] & 0xFC000000) == 0x14000000) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 双符号表体系与 dSYM 崩溃逆向还原 (Dual-Symbol & Crash Restorer)
|
||||
|
||||
### 5.1 设计目标
|
||||
解决代码混淆后 Bugly、Sentry 堆栈崩溃无法定位代码行号的问题。
|
||||
加固期生成 `mapping.db`,离线重写 Release 产生的 `App.app.dSYM`,将 DWARF 调试符号批量恢复为原始符号。
|
||||
|
||||
### 5.2 DWARF 调试格式解析与重写流程
|
||||
Mach-O dSYM 文件包含三个关键调试 Section:
|
||||
1. `__DWARF,__debug_info`:树状结构的 DIE(Debugging Information Entries),包含 `DW_TAG_subprogram`(函数)和属性 `DW_AT_name`、`DW_AT_linkage_name`。
|
||||
2. `__DWARF,__debug_str`:字符串常量池(以 `\0` 分隔)。DIE 中的 `DW_FORM_strp` 属性存储指向该池的文件偏移。
|
||||
3. `__DWARF,__debug_line`:行号状态机字节码,映射机器指令地址与源码行号。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["读取原始 dSYM DWARF"] --> B["解析 __debug_str 字符串池"]
|
||||
B --> C["查询 mapping.sqlite\nObfuscated -> Original"]
|
||||
C --> D{"新字符串长度 <= 原始混淆名?"}
|
||||
D -- 是 --> E["就地改写字符串并补 \\0 填充"]
|
||||
D -- 否 --> F["重建 __debug_str 并在末尾追加\n更新 __debug_info 中对应 DW_FORM_strp 偏移"]
|
||||
E --> G["输出 Restored.dSYM (上传至 Sentry/Bugly)"]
|
||||
F --> G
|
||||
```
|
||||
|
||||
#### DWARF 定点引用解析与重构伪代码 (杜绝全局子串误替)
|
||||
```python
|
||||
def restore_dsym_targeted(dsym_path, mapping_dict, output_path):
|
||||
# 严禁在 __debug_str 中执行全文 replace!
|
||||
# 必须通过 __debug_info 树定位具体 DIE 的 DW_FORM_strp 偏移进行定点更新
|
||||
with open(dsym_path, "r+b") as f:
|
||||
macho = MachO(f)
|
||||
debug_str = bytearray(macho.get_section("__DWARF", "__debug_str").data)
|
||||
debug_info = macho.get_section("__DWARF", "__debug_info").data
|
||||
|
||||
# 1. 遍历 .debug_info 中的 Compilation Units 与 DIE 树
|
||||
die_offsets = parse_dwarf_die_string_offsets(debug_info) # 提取 (die_id, attr_type, str_offset)
|
||||
|
||||
# 2. 定点校验与改写
|
||||
for str_offset in die_offsets:
|
||||
# 读取当前位置以 \0 结尾的完整原始字符串
|
||||
end_idx = debug_str.find(b'\x00', str_offset)
|
||||
if end_idx == -1: continue
|
||||
current_sym = debug_str[str_offset:end_idx].decode('utf-8', errors='ignore')
|
||||
|
||||
# 精确匹配(非子串模糊替换)
|
||||
if current_sym in mapping_dict:
|
||||
restored_sym = mapping_dict[current_sym].encode('utf-8')
|
||||
orig_len = end_idx - str_offset
|
||||
if len(restored_sym) <= orig_len:
|
||||
# 原位填充并截断,严格保证不越界污染相邻字符串
|
||||
debug_str[str_offset:str_offset + len(restored_sym)] = restored_sym
|
||||
debug_str[str_offset + len(restored_sym):end_idx] = b'\x00' * (orig_len - len(restored_sym))
|
||||
else:
|
||||
# 超长符号追加至表尾,并同步校准该 DIE 的 DW_FORM_strp 指针值
|
||||
new_offset = append_debug_str(debug_str, restored_sym)
|
||||
update_die_strp_offset(debug_info, str_offset, new_offset)
|
||||
|
||||
macho.get_section("__DWARF", "__debug_str").write(debug_str)
|
||||
macho.save(output_path)
|
||||
```
|
||||
|
||||
### 5.3 崩溃符号化适用边界与限制说明
|
||||
> [!IMPORTANT]
|
||||
> **dSYM 还原的适用边界与客观约束**:
|
||||
> 1. **符号混淆场景**:仅在函数体指令未发生偏移(仅改名)且通过 DIE 引用定点恢复时,堆栈可获得良好还原。但需注意:编译器内联优化(Inlining)或尾调用消除可能使部分行号产生轻微漂移,收回“100% 精确还原”的绝对表述;同时必须严格校验新产物与原始构建的 `LC_UUID` 严格匹配。
|
||||
> 2. **代码虚拟化 (VMP) / 函数抽取场景**:一旦函数体被抽离为私有字节码或替换为跳板(Trampoline),原机器指令在二进制中已不复存在。崩溃发生时,系统捕获的堆栈顶帧将必然是 `VMP_Execute`。
|
||||
> * **解决路径**:对此类函数,无法仅靠静态 dSYM 还原;必须在 `VMPContext` 中维护虚拟 PC,并在崩溃捕获回调中输出虚拟栈帧,结合离线的 `vmp_pc_mapping.json` 完成混合回溯还原。
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 6. 资产保护与无感透明解密 (Virtual File System & Assets Protector)
|
||||
|
||||
### 6.1 PNG 免解密 Hash 扰动(应对 2.3.1 / 4.3 静态排查)
|
||||
在不破坏图片展示的前提下修改图片 MD5/SHA256。PNG 格式由固定 8 字节签名加上多个 Chunk 组成。规范允许插入合规私有辅助 Chunk(如 `tEXt`):
|
||||
```cpp
|
||||
void PerturbPNGHash(std::vector<uint8_t>& png_data) {
|
||||
// PNG Header: 89 50 4E 47 0D 0A 1A 0A
|
||||
std::string key = "Comment";
|
||||
std::string value = GenerateRandomUUID(); // 随机特征串
|
||||
|
||||
// 构造 tEXt Chunk: [Length 4B] [ChunkType 4B "tEXt"] [Data] [CRC 4B]
|
||||
std::vector<uint8_t> chunk;
|
||||
uint32_t data_len = key.length() + 1 + value.length();
|
||||
AppendBigEndian(chunk, data_len);
|
||||
chunk.insert(chunk.end(), {'t', 'E', 'X', 't'});
|
||||
chunk.insert(chunk.end(), key.begin(), key.end());
|
||||
chunk.push_back(0); // 分隔符
|
||||
chunk.insert(chunk.end(), value.begin(), value.end());
|
||||
|
||||
uint32_t crc = CalculateCRC32(chunk.data() + 4, data_len + 4);
|
||||
AppendBigEndian(chunk, crc);
|
||||
|
||||
// 插入在 IHDR Chunk (偏移 8 + 25 字节) 之后
|
||||
png_data.insert(png_data.begin() + 33, chunk.begin(), chunk.end());
|
||||
}
|
||||
```
|
||||
|
||||
### 6.2 深度加密与底层 POSIX 透明内存解密
|
||||
* 加密格式:`[Magic 4B: 'G','U','A','D'] [Nonce 12B] [Tag 16B] [Ciphertext]`
|
||||
* 拦截 API:使用 `fishhook` 拦截 `fopen`、`open`、`stat`。
|
||||
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
static FILE *(*orig_fopen)(const char *path, const char *mode);
|
||||
|
||||
FILE *hook_fopen(const char *path, const char *mode) {
|
||||
FILE *fp = orig_fopen(path, mode);
|
||||
if (!fp) return NULL;
|
||||
|
||||
// 读取前 4 字节判断是否为加密资产
|
||||
char magic[4];
|
||||
if (fread(magic, 1, 4, fp) == 4 && memcmp(magic, "GUAD", 4) == 0) {
|
||||
// 读取密文长度并在内存解密
|
||||
fseek(fp, 0, SEEK_END);
|
||||
long sz = ftell(fp) - 32;
|
||||
fseek(fp, 32, SEEK_SET);
|
||||
|
||||
uint8_t *decrypted_buf = malloc(sz);
|
||||
// 执行 ChaCha20-Poly1305 解密 ...
|
||||
|
||||
// 创建内存文件句柄 (fmemopen) 使得上层读取无感
|
||||
FILE *mem_fp = fmemopen(decrypted_buf, sz, mode);
|
||||
fclose(fp);
|
||||
return mem_fp;
|
||||
}
|
||||
|
||||
fseek(fp, 0, SEEK_SET); // 非加固资源重置指针
|
||||
return fp;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 跨平台自动化重签名流水线 (Cross-Platform Signer Engine)
|
||||
|
||||
### 7.1 签名核心数据结构:Apple SuperBlob 与 CodeDirectory
|
||||
```cpp
|
||||
#include <stdint.h>
|
||||
|
||||
#define CSMAGIC_CODEDIRECTORY 0xfade0c02
|
||||
#define CSMAGIC_EMBEDDED_SIGNATURE 0xfade0cc0
|
||||
#define CSMAGIC_REQUIREMENTS 0xfade0c01
|
||||
#define CSMAGIC_BLOBWRAPPER 0xfade0b01
|
||||
#define CSMAGIC_ENTITLEMENTS 0xfade7171
|
||||
#define CSMAGIC_DER_ENTITLEMENTS 0xfade7172
|
||||
|
||||
// 1. SuperBlob 索引类型 (BlobIndex.type,均为正数或标准常量)
|
||||
#define CSSLOT_CODEDIRECTORY 0 // 0x0: 主 CodeDirectory
|
||||
#define CSSLOT_REQUIREMENTS 2 // 0x2: Requirements 规则
|
||||
#define CSSLOT_ENTITLEMENTS 5 // 0x5: XML Entitlements
|
||||
#define CSSLOT_DER_ENTITLEMENTS 7 // 0x7: DER-encoded Entitlements
|
||||
#define CSSLOT_SIGNATURESLOT 0x10000 // 0x10000: CMS 签名块 (BlobWrapper)
|
||||
|
||||
// 2. CodeDirectory 负数特殊散列槽位 (Special Slots,相对于 hashOffset 的负索引)
|
||||
#define CD_SLOT_INFOPLIST -1 // Info.plist SHA256
|
||||
#define CD_SLOT_REQUIREMENTS -2 // Requirements SHA256
|
||||
#define CD_SLOT_RESOURCEDIR -3 // _CodeSignature/CodeResources SHA256 (关键依赖)
|
||||
#define CD_SLOT_APPLICATION -4 // 预留
|
||||
#define CD_SLOT_ENTITLEMENTS -5 // XML Entitlements SHA256
|
||||
#define CD_SLOT_DER_ENTITLEMENTS -7 // DER Entitlements SHA256
|
||||
|
||||
struct BlobIndex {
|
||||
uint32_t type; // 必须为上述正数常量: 0, 2, 5, 7, 0x10000
|
||||
uint32_t offset; // 指向 Blob 距离 SuperBlob 起始处的字节偏移
|
||||
};
|
||||
|
||||
struct SuperBlob {
|
||||
uint32_t magic; // CSMAGIC_EMBEDDED_SIGNATURE
|
||||
uint32_t length; // 整个 SuperBlob 大小 (包含所有子 Blob)
|
||||
uint32_t count; // 包含的子 Blob 数量
|
||||
BlobIndex index[];
|
||||
};
|
||||
|
||||
struct CodeDirectory {
|
||||
uint32_t magic; // CSMAGIC_CODEDIRECTORY
|
||||
uint32_t length; // CodeDirectory 自身结构及前后哈希数组大小
|
||||
uint32_t version; // 0x20400 (支持 SHA256 及负数槽)
|
||||
uint32_t flags; // 0
|
||||
uint32_t hashOffset; // 代码正数哈希数组起始偏移 (负数特殊槽位于其左侧)
|
||||
uint32_t identOffset; // Bundle ID 字符串距头部的偏移
|
||||
uint32_t nSpecialSlots; // 负数槽位数量 (通常为 7)
|
||||
uint32_t nCodeSlots; // 页面正数槽位数量 (ceil(codeLimit / 16384))
|
||||
uint32_t codeLimit; // 签名覆盖的文件大小 (即 SuperBlob 起始偏移)
|
||||
uint8_t hashSize; // 32 (SHA256)
|
||||
uint8_t hashType; // 2 (CS_HASHTYPE_SHA256)
|
||||
uint8_t platform; // 0
|
||||
uint8_t pageSize; // 14 (表示 1 << 14 = 16384 = 16KB)
|
||||
uint32_t spare2;
|
||||
};
|
||||
```
|
||||
|
||||
### 7.2 严格合规的重签名流水线算法时序 (包含 LC_CODE_SIGNATURE 预占位)
|
||||
> [!CAUTION]
|
||||
> **两大签名底层陷阱**:
|
||||
> 1. **`LC_CODE_SIGNATURE` 命令属于 Page 0**:`load_commands` 位于二进制头部,属于 Page 0(0 ~ 16KB 范围)。如果在计算代码页哈希之后再更新 `LC_CODE_SIGNATURE` 的 `dataoff` 和 `datasize`,会导致 Page 0 哈希瞬间失效!因此**必须预先在 Header 中完成 `LC_CODE_SIGNATURE` 的位置与大小占位**,再执行分页代码哈希!
|
||||
> 2. **CMS 签名的真实入参**:苹果规范中,CMS `signedData` 签名封装的是**完整的 `CodeDirectory` 序列化二进制字节数据**(作为 SignedContent 或 Authenticated Attributes),绝非仅对 32 字节的 CDHash 做简单签名。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
participant Runner as 签名调度器
|
||||
participant Prov as Mobileprovision 与 Entitlements 协调
|
||||
participant Dylibs as Frameworks/PlugIns (内部组件)
|
||||
participant Res as CodeResources 资源清单
|
||||
participant MachO as 主可执行文件 Header
|
||||
participant CMS as OpenSSL 签名核
|
||||
|
||||
Runner->>Prov: 解析 embedded.mobileprovision 提取授权范围
|
||||
Runner->>Prov: 协调并生成目标所需 Entitlements (XML + DER 编码)
|
||||
Runner->>Dylibs: 先行签名内部 Frameworks/*.dylib 与 *.framework
|
||||
Runner->>Dylibs: 先行签名 PlugIns/*.appex (独立 Entitlements 与 BundleID)
|
||||
Runner->>Res: 扫描 Bundle 全部文件生成 _CodeSignature/CodeResources
|
||||
Runner->>MachO: 预先计算 SuperBlob 大小,在 Mach-O Header 预设 LC_CODE_SIGNATURE (dataoff=codeLimit, datasize=blob_size)
|
||||
Runner->>MachO: 将 CodeResources 哈希填入 CodeDirectory Slot -3
|
||||
Runner->>MachO: 将 Info.plist、Entitlements 哈希填入 Slot -1, -2, -5, -7
|
||||
Runner->>MachO: 计算 0..codeLimit 范围内的每 16KB 代码页 SHA256,填入 Slot 0..N
|
||||
Runner->>CMS: 传入完整的 CodeDirectory 序列化字节,由 OpenSSL 使用私钥生成 CMS PKCS#7 签名
|
||||
Runner->>MachO: 组装 SuperBlob (包含 0, 2, 5, 7, 0x10000 槽位),写入 dataoff
|
||||
Runner->>Runner: 重新打包压缩为 .ipa
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 8. IPA 相似度预检中心 (App Store 4.3 预检器)
|
||||
|
||||
### 8.1 算法模型设计与免责边界
|
||||
App Store 4.3 审核(Design: Spam)属于苹果人工审核与机审结合的行为规范策略,旨在遏制重复马甲包与克隆 App。**任何静态相似度工具均无法保证 100% 过审**。
|
||||
|
||||
iOSGuard 的相似度模型定位于**企业内部风控与差异化基准度量工具**:
|
||||
|
||||
$$\text{InternalRiskScore} = 0.45 \cdot \text{Sim}_{\text{Code}} + 0.35 \cdot \text{Sim}_{\text{Symbol}} + 0.20 \cdot \text{Sim}_{\text{Asset}}$$
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A["待测 IPA vs 基线母包 IPA"] --> B["Mach-O __text 提取\nSSDEEP (CTPH) 模糊哈希"]
|
||||
A --> C["符号表导出\nJaccard 集合交并比计算"]
|
||||
A --> D["图片媒体提取\n感知哈希 (pHash) 汉明距离计算"]
|
||||
B --> E["加权综合评分算法"]
|
||||
C --> E
|
||||
D --> E
|
||||
E --> F{"内部风控基准评分"}
|
||||
F -- "< 35%" --> G["内部低相似度 (特征分化充分)"]
|
||||
F -- "35% ~ 50%" --> H["内部中度相似 (建议调换混淆特征库)"]
|
||||
F -- "> 50%" --> I["内部高相似度风险 (建议阻断提审)"]
|
||||
```
|
||||
|
||||
|
||||
### 8.2 核心算法实现:基于 SSDEEP 的机器码片段比对
|
||||
```python
|
||||
import ssdeep
|
||||
|
||||
def calculate_macho_code_similarity(macho_path_a, macho_path_b):
|
||||
# 提取 __TEXT, __text 机器指令二进制段
|
||||
bytes_a = extract_text_section(macho_path_a)
|
||||
bytes_b = extract_text_section(macho_path_b)
|
||||
|
||||
# 计算 CTPH 模糊哈希
|
||||
hash_a = ssdeep.hash(bytes_a)
|
||||
hash_b = ssdeep.hash(bytes_b)
|
||||
|
||||
# 计算相似度 (0 ~ 100)
|
||||
score = ssdeep.compare(hash_a, hash_b)
|
||||
return score
|
||||
```
|
||||
|
||||
### 8.3 符号表 Jaccard 系数计算
|
||||
```python
|
||||
def calculate_symbol_similarity(symbols_a: set, symbols_b: set) -> float:
|
||||
intersection = len(symbols_a.intersection(symbols_b))
|
||||
union = len(symbols_a.union(symbols_b))
|
||||
if union == 0:
|
||||
return 0.0
|
||||
return (intersection / union) * 100.0
|
||||
```
|
||||
@@ -0,0 +1,19 @@
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
|
||||
add_llvm_pass_plugin(IGObfuscator
|
||||
src/IGPluginMain.cpp
|
||||
src/IGPolicyConfig.cpp
|
||||
src/IGStringEncryption.cpp
|
||||
src/IGFunctionOutline.cpp
|
||||
src/IGOpaqueFieldAccess.cpp
|
||||
src/IGOpaqueConstants.cpp
|
||||
src/IGArithmetic.cpp
|
||||
src/IGIndirectCall.cpp
|
||||
src/IGBasicBlockSplit.cpp
|
||||
src/IGFlattening.cpp
|
||||
src/IGIndirectBranch.cpp
|
||||
src/IGAntiHooking.cpp
|
||||
DEPENDS
|
||||
intrinsics_gen
|
||||
BUILDTREE_ONLY
|
||||
)
|
||||
@@ -0,0 +1,142 @@
|
||||
#ifndef IG_OBFUSCATOR_PASS_UTILS_H
|
||||
#define IG_OBFUSCATOR_PASS_UTILS_H
|
||||
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/ArrayRef.h"
|
||||
#include "llvm/ADT/StringExtras.h"
|
||||
#include "llvm/ADT/StringRef.h"
|
||||
#include "llvm/IR/DebugInfoMetadata.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/GlobalValue.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/Support/SHA256.h"
|
||||
#include "llvm/TargetParser/Triple.h"
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace igobf {
|
||||
|
||||
inline llvm::StringRef stripObjCMarker(llvm::StringRef Name) {
|
||||
if (!Name.empty() && Name.front() == '\x01')
|
||||
return Name.drop_front(1);
|
||||
return Name;
|
||||
}
|
||||
|
||||
inline bool isMachOAArch64NonArm64e(const llvm::Module &M) {
|
||||
if (M.getTargetTriple().empty())
|
||||
return true;
|
||||
llvm::Triple TT(M.getTargetTriple());
|
||||
return TT.isOSBinFormatMachO() && TT.isAArch64() &&
|
||||
TT.getArchName() != "arm64e";
|
||||
}
|
||||
|
||||
inline std::string computeShortModuleTag(llvm::StringRef Seed,
|
||||
llvm::StringRef ModId,
|
||||
llvm::StringRef SourcePath) {
|
||||
llvm::SHA256 Hasher;
|
||||
Hasher.update(Seed);
|
||||
Hasher.update("|");
|
||||
Hasher.update(ModId);
|
||||
Hasher.update("|");
|
||||
Hasher.update(SourcePath);
|
||||
auto Digest = Hasher.final();
|
||||
return llvm::toHex(llvm::ArrayRef<uint8_t>(Digest.data(), 4),
|
||||
/*LowerCase=*/true);
|
||||
}
|
||||
|
||||
inline bool isCompilerSynthesizedFunction(const llvm::Function &F,
|
||||
const IGPolicyConfig &Policy) {
|
||||
if (Policy.hasAnnotation(F, "ig_flatten"))
|
||||
return false;
|
||||
llvm::StringRef Name = stripObjCMarker(F.getName());
|
||||
|
||||
if (Name.starts_with("block_copy_helper") ||
|
||||
Name.starts_with("block_destroy_helper") ||
|
||||
Name.starts_with("__copy_helper_block_") ||
|
||||
Name.starts_with("___copy_helper_block_") ||
|
||||
Name.starts_with("__destroy_helper_block_") ||
|
||||
Name.starts_with("___destroy_helper_block_") ||
|
||||
Name.starts_with("objectdestroy") ||
|
||||
Name.ends_with(" .cxx_destruct]") ||
|
||||
Name.contains(".resume.")) {
|
||||
return true;
|
||||
}
|
||||
if (Name.starts_with("$s") || Name.starts_with("_$s")) {
|
||||
if (Name.ends_with("Tm") || Name.ends_with("Wl") ||
|
||||
Name.ends_with("WL") || Name.ends_with("CMa") ||
|
||||
Name.ends_with("VMa") || Name.ends_with("OMa") ||
|
||||
Name.ends_with("WOh") || Name.ends_with("WOy") ||
|
||||
Name.ends_with("WOe") || Name.ends_with("WOc") ||
|
||||
Name.ends_with("WOb") || Name.ends_with("WOd") ||
|
||||
Name.ends_with("TR") || Name.ends_with("TA")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (const llvm::Module *M = F.getParent()) {
|
||||
if (M->getNamedMetadata("llvm.dbg.cu") != nullptr) {
|
||||
const llvm::DISubprogram *SP = F.getSubprogram();
|
||||
if (!SP || SP->isArtificial() ||
|
||||
SP->getFilename().contains("<compiler-generated>")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool matchesAnySubstring(const llvm::Function &F,
|
||||
const std::vector<std::string> &Patterns) {
|
||||
llvm::StringRef CleanName = stripObjCMarker(F.getName());
|
||||
for (const std::string &Pat : Patterns) {
|
||||
if (!Pat.empty() &&
|
||||
(CleanName.contains(Pat) || F.getName().contains(Pat))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool isFunctionSafeForTransform(
|
||||
const llvm::Function &F, const IGPolicyConfig &Policy,
|
||||
const std::vector<std::string> *ExtraExemptSubstrings = nullptr) {
|
||||
if (F.isDeclaration() || Policy.isFunctionExempt(F))
|
||||
return false;
|
||||
if (llvm::GlobalValue::isWeakForLinker(F.getLinkage()) ||
|
||||
F.hasAvailableExternallyLinkage()) {
|
||||
return false;
|
||||
}
|
||||
if (F.isPresplitCoroutine() || F.hasFnAttribute(llvm::Attribute::Naked))
|
||||
return false;
|
||||
if (F.getCallingConv() == llvm::CallingConv::SwiftTail)
|
||||
return false;
|
||||
if (F.hasSection()) {
|
||||
llvm::StringRef Sec = F.getSection();
|
||||
if (Sec.contains("__mod_init_func") || Sec.contains("__objc_init_func") ||
|
||||
Sec.contains("__mod_term_func")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (isCompilerSynthesizedFunction(F, Policy))
|
||||
return false;
|
||||
if (ExtraExemptSubstrings &&
|
||||
matchesAnySubstring(F, *ExtraExemptSubstrings)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline llvm::DebugLoc resolveInstDebugLoc(const llvm::Instruction *I,
|
||||
const llvm::Function &F) {
|
||||
if (I && I->getDebugLoc())
|
||||
return I->getDebugLoc();
|
||||
if (llvm::DISubprogram *SP = F.getSubprogram()) {
|
||||
unsigned Line = SP->getScopeLine() ? SP->getScopeLine() : SP->getLine();
|
||||
return llvm::DILocation::get(F.getContext(), Line, 0, SP);
|
||||
}
|
||||
return llvm::DebugLoc();
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,314 @@
|
||||
#ifndef IG_OBFUSCATOR_POLICY_CONFIG_H
|
||||
#define IG_OBFUSCATOR_POLICY_CONFIG_H
|
||||
|
||||
#include "llvm/ADT/SmallPtrSet.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/ADT/StringRef.h"
|
||||
#include "llvm/ADT/StringSet.h"
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace llvm {
|
||||
class Function;
|
||||
class Module;
|
||||
} // namespace llvm
|
||||
|
||||
namespace igobf {
|
||||
|
||||
enum class ObfMode {
|
||||
Off,
|
||||
Noop,
|
||||
StrOnly,
|
||||
Full,
|
||||
};
|
||||
|
||||
enum class PassFilter {
|
||||
All,
|
||||
StrOnly,
|
||||
FlaOnly,
|
||||
IcallOnly,
|
||||
OpaqueConstOnly,
|
||||
ArithOnly,
|
||||
IbrOnly,
|
||||
AntiHookOnly,
|
||||
OutlineOnly,
|
||||
FieldOnly,
|
||||
BBSplitOnly,
|
||||
};
|
||||
|
||||
enum class FlattenTopology {
|
||||
Polymorphic,
|
||||
StarSwitch,
|
||||
};
|
||||
|
||||
struct TargetRule {
|
||||
std::string Id;
|
||||
std::string PathContains;
|
||||
std::string FunctionContains;
|
||||
bool WholeModuleIfNoDebug = false;
|
||||
std::optional<unsigned> Rounds;
|
||||
std::optional<unsigned> MaxPerFn;
|
||||
std::optional<unsigned> Probability;
|
||||
std::optional<bool> NonlinearMBA;
|
||||
std::optional<bool> OpaqueZero;
|
||||
};
|
||||
|
||||
struct StringReplaceRule {
|
||||
std::string Exact;
|
||||
std::string Replace;
|
||||
};
|
||||
|
||||
struct SkippedFunctionRecord {
|
||||
std::string Name;
|
||||
std::string Reason;
|
||||
};
|
||||
|
||||
struct FlattenedFunctionDetail {
|
||||
std::string Name;
|
||||
std::string Topology;
|
||||
std::string Encoding;
|
||||
unsigned Blocks = 0;
|
||||
};
|
||||
|
||||
struct IGAuditRecord {
|
||||
std::string Mode;
|
||||
std::string PassFilter;
|
||||
std::string Seed;
|
||||
std::string SourcePath;
|
||||
std::string ModuleId;
|
||||
std::vector<std::string> FunctionsFlattened;
|
||||
std::vector<FlattenedFunctionDetail> FunctionsFlattenedDetails;
|
||||
std::vector<SkippedFunctionRecord> FunctionsSkipped;
|
||||
unsigned StringsEncryptedCount = 0;
|
||||
std::vector<std::string> StringsEncryptedFunctions;
|
||||
unsigned StringsStackEncryptedCount = 0;
|
||||
unsigned ObjCStringsEncryptedCount = 0;
|
||||
unsigned SwiftStringsEncryptedCount = 0;
|
||||
unsigned StringsReplacedCount = 0;
|
||||
unsigned StringsSkippedCount = 0;
|
||||
unsigned PathsScrubbedCount = 0;
|
||||
unsigned IndirectCallsCount = 0;
|
||||
std::vector<std::string> IndirectCallsFunctions;
|
||||
bool IndirectCallDualTable = false;
|
||||
unsigned OpaqueConstantsCount = 0;
|
||||
std::vector<std::string> OpaqueConstantsFunctions;
|
||||
unsigned ArithmeticRewritesCount = 0;
|
||||
std::vector<std::string> ArithmeticFunctions;
|
||||
unsigned IndirectBranchesCount = 0;
|
||||
std::vector<std::string> IndirectBranchesFunctions;
|
||||
unsigned AntiHookFunctionsCount = 0;
|
||||
std::vector<std::string> AntiHookFunctions;
|
||||
unsigned FunctionsOutlinedCount = 0;
|
||||
std::vector<std::string> OutlinedFunctions;
|
||||
unsigned OpaqueFieldAccessCount = 0;
|
||||
std::vector<std::string> OpaqueFieldFunctions;
|
||||
unsigned BBSplitCount = 0;
|
||||
std::vector<std::string> BBSplitFunctions;
|
||||
unsigned NonlinearMBACount = 0;
|
||||
unsigned OpaqueZeroCount = 0;
|
||||
std::vector<std::string> AnnotatedTargets;
|
||||
|
||||
bool writeToFile(llvm::StringRef OutPath) const;
|
||||
};
|
||||
|
||||
class IGDeterministicRNG {
|
||||
public:
|
||||
IGDeterministicRNG(llvm::StringRef Seed, llvm::StringRef ModuleId,
|
||||
llvm::StringRef ItemId);
|
||||
|
||||
std::array<uint8_t, 32> nextBlock();
|
||||
uint32_t nextU32();
|
||||
uint32_t nextNonZeroU32();
|
||||
uint64_t nextU64();
|
||||
uint64_t nextNonZeroU64();
|
||||
uint8_t nextNonZeroByte();
|
||||
|
||||
template <typename VecT> void shuffle(VecT &Items) {
|
||||
if (Items.size() < 2)
|
||||
return;
|
||||
for (size_t i = Items.size() - 1; i > 0; --i) {
|
||||
size_t j = static_cast<size_t>(nextU32() % static_cast<uint32_t>(i + 1));
|
||||
if (i != j)
|
||||
std::swap(Items[i], Items[j]);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::string Prefix_;
|
||||
uint64_t Counter_ = 0;
|
||||
std::array<uint8_t, 32> Buffer_{};
|
||||
size_t Offset_ = 32;
|
||||
};
|
||||
|
||||
class IGPolicyConfig {
|
||||
public:
|
||||
static IGPolicyConfig loadFromCLI(const llvm::Module &M,
|
||||
IGAuditRecord &AuditOut);
|
||||
|
||||
ObfMode mode() const { return Mode_; }
|
||||
PassFilter passFilter() const { return Filter_; }
|
||||
llvm::StringRef seed() const { return Seed_; }
|
||||
llvm::StringRef sourcePath() const { return SourcePath_; }
|
||||
llvm::StringRef swiftModuleName() const { return SwiftModuleName_; }
|
||||
llvm::StringRef auditOutPath() const { return AuditOutPath_; }
|
||||
|
||||
bool isStringEncryptionEnabled() const;
|
||||
bool isIndirectCallEnabled() const;
|
||||
bool isFlatteningEnabled() const;
|
||||
bool isOpaqueConstantsEnabled() const;
|
||||
bool isArithmeticEnabled() const;
|
||||
bool isIndirectBranchEnabled() const;
|
||||
bool isAntiHookingEnabled() const;
|
||||
bool isFunctionOutlineEnabled() const;
|
||||
bool isOpaqueFieldEnabled() const;
|
||||
bool isBBSplitEnabled() const;
|
||||
|
||||
FlattenTopology flattenTopology() const { return FlattenTopology_; }
|
||||
unsigned bogusBlockCount() const { return BogusBlockCount_; }
|
||||
bool splitLinearBlocks() const { return SplitLinearBlocks_; }
|
||||
|
||||
unsigned opaqueConstMaxPerFn() const { return OpaqueConstMaxPerFn_; }
|
||||
bool opaqueConstOpaqueZero() const { return OpaqueConstOpaqueZero_; }
|
||||
unsigned arithmeticRounds() const { return ArithmeticRounds_; }
|
||||
unsigned arithmeticMaxPerFn() const { return ArithmeticMaxPerFn_; }
|
||||
bool arithmeticNonlinearMBA() const { return ArithmeticNonlinearMBA_; }
|
||||
unsigned stringEncryptStackMaxLen() const { return StringEncryptStackMaxLen_; }
|
||||
bool isIndirectCallDualTableEnabled() const { return IndirectCallDualTable_; }
|
||||
unsigned functionOutlineMaxPerFn() const { return FunctionOutlineMaxPerFn_; }
|
||||
unsigned functionOutlineMinInsts() const { return FunctionOutlineMinInsts_; }
|
||||
unsigned opaqueFieldMaxPerFn() const { return OpaqueFieldMaxPerFn_; }
|
||||
unsigned bbSplitMaxPerFn() const { return BBSplitMaxPerFn_; }
|
||||
unsigned bbSplitMinInsts() const { return BBSplitMinInsts_; }
|
||||
|
||||
bool isModuleExempt(const llvm::Module &M) const;
|
||||
bool isFunctionExempt(const llvm::Function &F) const;
|
||||
bool shouldEncryptStringsInFunction(const llvm::Function &F) const;
|
||||
bool shouldEncryptObjCStringsInFunction(const llvm::Function &F) const;
|
||||
bool shouldEncryptSwiftStringsInFunction(const llvm::Function &F) const;
|
||||
bool shouldStackEncryptStringsInFunction(const llvm::Function &F) const;
|
||||
const std::vector<StringReplaceRule> &stringReplaceRules() const {
|
||||
return StringReplaceRules_;
|
||||
}
|
||||
bool shouldIndirectCallInFunction(const llvm::Function &F) const;
|
||||
bool shouldFlattenFunction(const llvm::Function &F) const;
|
||||
bool shouldObfuscateConstantsInFunction(const llvm::Function &F) const;
|
||||
bool shouldObfuscateArithmeticInFunction(const llvm::Function &F) const;
|
||||
bool shouldIndirectBranchInFunction(const llvm::Function &F) const;
|
||||
bool shouldAntiHookFunction(const llvm::Function &F) const;
|
||||
bool shouldOutlineFunction(const llvm::Function &F) const;
|
||||
bool shouldObfuscateFieldAccessInFunction(const llvm::Function &F) const;
|
||||
bool shouldSplitBasicBlocksInFunction(const llvm::Function &F) const;
|
||||
const TargetRule *findArithmeticRule(const llvm::Function &F) const;
|
||||
const TargetRule *findOpaqueConstRule(const llvm::Function &F) const;
|
||||
const TargetRule *findBBSplitRule(const llvm::Function &F) const;
|
||||
|
||||
const std::vector<std::string> &indirectCallSameImagePrefixes() const {
|
||||
return IndirectCallSameImagePrefixes_;
|
||||
}
|
||||
const std::vector<std::string> &exemptFunctionPrefixes() const {
|
||||
return ExemptFunctionPrefixes_;
|
||||
}
|
||||
const std::vector<std::string> &scrubPathSubstrings() const {
|
||||
return ScrubPathSubstrings_;
|
||||
}
|
||||
const std::vector<std::string> &opaqueConstExemptFunctions() const {
|
||||
return OpaqueConstExemptFunctions_;
|
||||
}
|
||||
const std::vector<std::string> &arithmeticExemptFunctions() const {
|
||||
return ArithmeticExemptFunctions_;
|
||||
}
|
||||
const std::vector<std::string> &indirectBranchExemptFunctions() const {
|
||||
return IndirectBranchExemptFunctions_;
|
||||
}
|
||||
const std::vector<std::string> &antiHookingExemptFunctions() const {
|
||||
return AntiHookingExemptFunctions_;
|
||||
}
|
||||
const std::vector<std::string> &functionOutlineExemptFunctions() const {
|
||||
return FunctionOutlineExemptFunctions_;
|
||||
}
|
||||
const std::vector<std::string> &opaqueFieldExemptFunctions() const {
|
||||
return OpaqueFieldExemptFunctions_;
|
||||
}
|
||||
const std::vector<std::string> &bbSplitExemptFunctions() const {
|
||||
return BBSplitExemptFunctions_;
|
||||
}
|
||||
|
||||
void collectAnnotations(const llvm::Module &M);
|
||||
bool hasAnnotation(const llvm::Function &F, llvm::StringRef Tag) const;
|
||||
|
||||
static std::string resolveFunctionSourcePath(const llvm::Function &F,
|
||||
llvm::StringRef FallbackPath);
|
||||
|
||||
private:
|
||||
const TargetRule *findMatchingRule(const std::vector<TargetRule> &Rules,
|
||||
const llvm::Function &F) const;
|
||||
bool matchesAnyRule(const std::vector<TargetRule> &Rules,
|
||||
const llvm::Function &F) const;
|
||||
|
||||
ObfMode Mode_ = ObfMode::Full;
|
||||
PassFilter Filter_ = PassFilter::All;
|
||||
FlattenTopology FlattenTopology_ = FlattenTopology::Polymorphic;
|
||||
unsigned BogusBlockCount_ = 0;
|
||||
bool SplitLinearBlocks_ = false;
|
||||
unsigned OpaqueConstMaxPerFn_ = 64;
|
||||
bool OpaqueConstOpaqueZero_ = false;
|
||||
unsigned ArithmeticRounds_ = 1;
|
||||
unsigned ArithmeticMaxPerFn_ = 128;
|
||||
bool ArithmeticNonlinearMBA_ = false;
|
||||
unsigned StringEncryptStackMaxLen_ = 128;
|
||||
bool IndirectCallDualTable_ = false;
|
||||
unsigned FunctionOutlineMaxPerFn_ = 2;
|
||||
unsigned FunctionOutlineMinInsts_ = 6;
|
||||
unsigned OpaqueFieldMaxPerFn_ = 32;
|
||||
unsigned BBSplitMaxPerFn_ = 4;
|
||||
unsigned BBSplitMinInsts_ = 8;
|
||||
std::string Seed_ = "m0_seed_20261119_v1";
|
||||
std::string SourcePath_;
|
||||
std::string SwiftModuleName_;
|
||||
std::string AuditOutPath_;
|
||||
|
||||
std::vector<std::string> ExemptPathSubstrings_;
|
||||
std::vector<std::string> ExemptFunctionPrefixes_;
|
||||
std::vector<std::string> ScrubPathSubstrings_;
|
||||
std::vector<TargetRule> StringEncryptTargets_;
|
||||
std::vector<TargetRule> StringEncryptObjCTargets_;
|
||||
std::vector<TargetRule> StringEncryptSwiftTargets_;
|
||||
std::vector<TargetRule> StringEncryptStackTargets_;
|
||||
std::vector<StringReplaceRule> StringReplaceRules_;
|
||||
std::vector<TargetRule> IndirectCallTargets_;
|
||||
std::vector<std::string> IndirectCallSameImagePrefixes_;
|
||||
std::vector<TargetRule> FlattenTargets_;
|
||||
std::vector<TargetRule> OpaqueConstTargets_;
|
||||
std::vector<std::string> OpaqueConstExemptFunctions_;
|
||||
std::vector<TargetRule> ArithmeticTargets_;
|
||||
std::vector<std::string> ArithmeticExemptFunctions_;
|
||||
std::vector<TargetRule> IndirectBranchTargets_;
|
||||
std::vector<std::string> IndirectBranchExemptFunctions_;
|
||||
std::vector<TargetRule> AntiHookingTargets_;
|
||||
std::vector<std::string> AntiHookingExemptFunctions_;
|
||||
std::vector<TargetRule> FunctionOutlineTargets_;
|
||||
std::vector<std::string> FunctionOutlineExemptFunctions_;
|
||||
std::vector<TargetRule> OpaqueFieldTargets_;
|
||||
std::vector<std::string> OpaqueFieldExemptFunctions_;
|
||||
std::vector<TargetRule> BBSplitTargets_;
|
||||
std::vector<std::string> BBSplitExemptFunctions_;
|
||||
|
||||
llvm::StringSet<> AnnotatedFlatten_;
|
||||
llvm::StringSet<> AnnotatedStr_;
|
||||
llvm::StringSet<> AnnotatedIcall_;
|
||||
llvm::StringSet<> AnnotatedConst_;
|
||||
llvm::StringSet<> AnnotatedArith_;
|
||||
llvm::StringSet<> AnnotatedIbr_;
|
||||
llvm::StringSet<> AnnotatedAntiHook_;
|
||||
llvm::StringSet<> AnnotatedOutline_;
|
||||
llvm::StringSet<> AnnotatedField_;
|
||||
llvm::StringSet<> AnnotatedBBSplit_;
|
||||
llvm::StringSet<> AnnotatedExempt_;
|
||||
};
|
||||
|
||||
} // namespace igobf
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,76 @@
|
||||
#include "IGPassUtils.h"
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/ArrayRef.h"
|
||||
#include "llvm/IR/Attributes.h"
|
||||
#include "llvm/IR/CallingConv.h"
|
||||
#include "llvm/IR/Constants.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Verifier.h"
|
||||
#include "llvm/Support/ErrorHandling.h"
|
||||
#include <cstdint>
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
|
||||
bool runAntiHooking(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isAntiHookingEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
if (!isMachOAArch64NonArm64e(M))
|
||||
return false;
|
||||
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
bool Changed = false;
|
||||
|
||||
// AArch64 AAPCS64 IP0/IP1 (x16/x17) harmless 8-byte prologue:
|
||||
// mov x17, x17 -> orr x17, xzr, x17 -> 0xAA1103F1
|
||||
// mov x16, x16 -> orr x16, xzr, x16 -> 0xAA1003F0
|
||||
// Breaks naive inline-hook trampolines (Substrate/Dobby/Frida 16-byte patch
|
||||
// assumptions or instruction-decoding prologues) without clobbering state.
|
||||
static constexpr uint8_t kPrologueX17X16[8] = {
|
||||
0xf1, 0x03, 0x11, 0xaa, 0xf0, 0x03, 0x10, 0xaa,
|
||||
};
|
||||
static constexpr uint8_t kPrologueX16X17[8] = {
|
||||
0xf0, 0x03, 0x10, 0xaa, 0xf1, 0x03, 0x11, 0xaa,
|
||||
};
|
||||
|
||||
for (Function &F : M) {
|
||||
if (!Policy.shouldAntiHookFunction(F))
|
||||
continue;
|
||||
if (!isFunctionSafeForTransform(F, Policy,
|
||||
&Policy.antiHookingExemptFunctions())) {
|
||||
continue;
|
||||
}
|
||||
if (F.empty() || F.hasPrologueData() || !F.doesNotThrow() ||
|
||||
F.hasPersonalityFn()) {
|
||||
continue;
|
||||
}
|
||||
if (F.hasFnAttribute(Attribute::Naked) ||
|
||||
F.hasFnAttribute("branch-target-enforcement") ||
|
||||
F.getCallingConv() == CallingConv::SwiftTail) {
|
||||
continue;
|
||||
}
|
||||
|
||||
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(), F.getName());
|
||||
const uint8_t *Seq =
|
||||
((RNG.nextU32() & 1U) == 0) ? kPrologueX17X16 : kPrologueX16X17;
|
||||
Constant *Prologue =
|
||||
ConstantDataVector::get(Ctx, ArrayRef<uint8_t>(Seq, 8));
|
||||
F.setPrologueData(Prologue);
|
||||
|
||||
if (verifyFunction(F, &errs())) {
|
||||
report_fatal_error(Twine("[IGAntiHooking] IR verification failed on ") +
|
||||
F.getName());
|
||||
}
|
||||
|
||||
++Audit.AntiHookFunctionsCount;
|
||||
Audit.AntiHookFunctions.push_back(F.getName().str());
|
||||
Changed = true;
|
||||
}
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,299 @@
|
||||
#include "IGPassUtils.h"
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/IR/Constants.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/IRBuilder.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Verifier.h"
|
||||
#include "llvm/Support/ErrorHandling.h"
|
||||
#include <cassert>
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
uint64_t bitMaskForWidth(unsigned BW) {
|
||||
return (BW == 32) ? 0xFFFFFFFFULL : 0xFFFFFFFFFFFFFFFFULL;
|
||||
}
|
||||
|
||||
// Compute modular inverse A^{-1} mod 2^W (W in {32, 64}) via Newton-Raphson.
|
||||
uint64_t modInverseU64(uint64_t A, unsigned BW) {
|
||||
uint64_t Mask = bitMaskForWidth(BW);
|
||||
uint64_t Inv = 1;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
Inv = (Inv * (2ULL - A * Inv)) & Mask;
|
||||
}
|
||||
assert(((A * Inv) & Mask) == 1ULL && "A must be odd");
|
||||
return Inv;
|
||||
}
|
||||
|
||||
bool isEligibleBinaryOp(const BinaryOperator *BO) {
|
||||
if (!BO || BO->getParent()->isEHPad())
|
||||
return false;
|
||||
auto *IntTy = dyn_cast<IntegerType>(BO->getType());
|
||||
if (!IntTy)
|
||||
return false;
|
||||
unsigned BW = IntTy->getBitWidth();
|
||||
if (BW != 32 && BW != 64)
|
||||
return false;
|
||||
switch (BO->getOpcode()) {
|
||||
case Instruction::Add:
|
||||
case Instruction::Sub:
|
||||
case Instruction::Xor:
|
||||
case Instruction::And:
|
||||
case Instruction::Or:
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
// Skip trivial two-constant folding leftovers (should not exist after -O2).
|
||||
if (isa<ConstantInt>(BO->getOperand(0)) &&
|
||||
isa<ConstantInt>(BO->getOperand(1))) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Rewrites integer ops with bit-exact mod-2^W Mixed Boolean-Arithmetic formulas.
|
||||
// Note: NSW/NUW flags are intentionally omitted on generated ops so intermediate
|
||||
// modulo-2^W wraps never introduce LLVM poison.
|
||||
Value *emitLinearMBAForPair(IRBuilder<> &B, unsigned Opcode, Value *X,
|
||||
Value *Y, unsigned Variant) {
|
||||
Type *Ty = X->getType();
|
||||
Value *One = ConstantInt::get(Ty, 1);
|
||||
|
||||
switch (Opcode) {
|
||||
case Instruction::Add:
|
||||
switch (Variant % 3) {
|
||||
case 0:
|
||||
// x + y == (x ^ y) + 2 * (x & y)
|
||||
return B.CreateAdd(B.CreateXor(X, Y),
|
||||
B.CreateShl(B.CreateAnd(X, Y), One));
|
||||
case 1:
|
||||
// x + y == (x | y) + (x & y)
|
||||
return B.CreateAdd(B.CreateOr(X, Y), B.CreateAnd(X, Y));
|
||||
default:
|
||||
// x + y == 2 * (x | y) - (x ^ y)
|
||||
return B.CreateSub(B.CreateShl(B.CreateOr(X, Y), One),
|
||||
B.CreateXor(X, Y));
|
||||
}
|
||||
|
||||
case Instruction::Sub:
|
||||
switch (Variant % 3) {
|
||||
case 0:
|
||||
// x - y == (x ^ y) - 2 * (~x & y)
|
||||
return B.CreateSub(B.CreateXor(X, Y),
|
||||
B.CreateShl(B.CreateAnd(B.CreateNot(X), Y), One));
|
||||
case 1:
|
||||
// x - y == (x & ~y) - (~x & y)
|
||||
return B.CreateSub(B.CreateAnd(X, B.CreateNot(Y)),
|
||||
B.CreateAnd(B.CreateNot(X), Y));
|
||||
default: {
|
||||
// x - y == ((x ^ ~y) + 2 * (x & ~y)) + 1
|
||||
Value *NotY = B.CreateNot(Y);
|
||||
Value *AddNotY = B.CreateAdd(B.CreateXor(X, NotY),
|
||||
B.CreateShl(B.CreateAnd(X, NotY), One));
|
||||
return B.CreateAdd(AddNotY, One);
|
||||
}
|
||||
}
|
||||
|
||||
case Instruction::Xor:
|
||||
switch (Variant % 3) {
|
||||
case 0:
|
||||
// x ^ y == (x | y) - (x & y)
|
||||
return B.CreateSub(B.CreateOr(X, Y), B.CreateAnd(X, Y));
|
||||
case 1:
|
||||
// x ^ y == (x + y) - 2 * (x & y)
|
||||
return B.CreateSub(B.CreateAdd(X, Y),
|
||||
B.CreateShl(B.CreateAnd(X, Y), One));
|
||||
default:
|
||||
// x ^ y == (x & ~y) | (~x & y)
|
||||
return B.CreateOr(B.CreateAnd(X, B.CreateNot(Y)),
|
||||
B.CreateAnd(B.CreateNot(X), Y));
|
||||
}
|
||||
|
||||
case Instruction::And:
|
||||
switch (Variant % 3) {
|
||||
case 0:
|
||||
// x & y == (x + y) - (x | y)
|
||||
return B.CreateSub(B.CreateAdd(X, Y), B.CreateOr(X, Y));
|
||||
case 1:
|
||||
// x & y == ~(~x | ~y)
|
||||
return B.CreateNot(B.CreateOr(B.CreateNot(X), B.CreateNot(Y)));
|
||||
default:
|
||||
// x & y == (x | y) - (x ^ y)
|
||||
return B.CreateSub(B.CreateOr(X, Y), B.CreateXor(X, Y));
|
||||
}
|
||||
|
||||
case Instruction::Or:
|
||||
switch (Variant % 3) {
|
||||
case 0:
|
||||
// x | y == (x ^ y) + (x & y)
|
||||
return B.CreateAdd(B.CreateXor(X, Y), B.CreateAnd(X, Y));
|
||||
case 1:
|
||||
// x | y == ~(~x & ~y)
|
||||
return B.CreateNot(B.CreateAnd(B.CreateNot(X), B.CreateNot(Y)));
|
||||
default:
|
||||
// x | y == (x + y) - (x & y)
|
||||
return B.CreateSub(B.CreateAdd(X, Y), B.CreateAnd(X, Y));
|
||||
}
|
||||
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
Value *emitLinearMBA(IRBuilder<> &B, BinaryOperator *BO, unsigned Variant) {
|
||||
return emitLinearMBAForPair(B, BO->getOpcode(), BO->getOperand(0),
|
||||
BO->getOperand(1), Variant);
|
||||
}
|
||||
|
||||
// Self-inverse mod-2^W quadratic half-Feistel codec:
|
||||
// T(v) = v ^ (((v * v) + Key) << (W/2)). Since the low W/2 bits are unchanged,
|
||||
// T(T(v)) == v identically across all bit patterns without NSW/NUW flags.
|
||||
Value *emitQuadraticHalfFeistel(IRBuilder<> &B, Value *V, uint64_t Key,
|
||||
unsigned BW) {
|
||||
Type *Ty = V->getType();
|
||||
Value *One = ConstantInt::get(Ty, 1);
|
||||
Value *HalfC = ConstantInt::get(Ty, BW / 2);
|
||||
Value *KeyC = ConstantInt::get(Ty, Key);
|
||||
|
||||
Value *Sq1 = B.CreateMul(V, V);
|
||||
Value *T1 = B.CreateShl(B.CreateAdd(Sq1, KeyC), HalfC);
|
||||
// U = V ^ T1 written via non-xor MBA identity (V | T1) - (V & T1)
|
||||
Value *U = B.CreateSub(B.CreateOr(V, T1), B.CreateAnd(V, T1));
|
||||
|
||||
Value *Sq2 = B.CreateMul(U, U);
|
||||
Value *T2 = B.CreateShl(B.CreateAdd(Sq2, KeyC), HalfC);
|
||||
// Out = U ^ T2 written via (U + T2) - 2*(U & T2)
|
||||
return B.CreateSub(B.CreateAdd(U, T2), B.CreateShl(B.CreateAnd(U, T2), One));
|
||||
}
|
||||
|
||||
Value *emitNonlinearMBA(IRBuilder<> &B, BinaryOperator *BO,
|
||||
IGDeterministicRNG &RNG) {
|
||||
unsigned Opcode = BO->getOpcode();
|
||||
Type *Ty = BO->getType();
|
||||
unsigned BW = Ty->getIntegerBitWidth();
|
||||
uint64_t Mask = bitMaskForWidth(BW);
|
||||
Value *X = BO->getOperand(0);
|
||||
Value *Y = BO->getOperand(1);
|
||||
|
||||
if (Opcode == Instruction::Add || Opcode == Instruction::Sub) {
|
||||
uint64_t A = (RNG.nextNonZeroU64() | 1ULL) & Mask;
|
||||
uint64_t AInv = modInverseU64(A, BW);
|
||||
uint64_t B1 = RNG.nextNonZeroU64() & Mask;
|
||||
uint64_t B2 = RNG.nextNonZeroU64() & Mask;
|
||||
|
||||
Value *AC = ConstantInt::get(Ty, A);
|
||||
Value *AInvC = ConstantInt::get(Ty, AInv);
|
||||
Value *U = B.CreateAdd(B.CreateMul(X, AC), ConstantInt::get(Ty, B1));
|
||||
Value *V = B.CreateAdd(B.CreateMul(Y, AC), ConstantInt::get(Ty, B2));
|
||||
Value *Comb = emitLinearMBAForPair(B, Opcode, U, V, RNG.nextU32());
|
||||
uint64_t BDelta = (Opcode == Instruction::Add) ? ((B1 + B2) & Mask)
|
||||
: ((B1 - B2) & Mask);
|
||||
Value *Res =
|
||||
B.CreateMul(B.CreateSub(Comb, ConstantInt::get(Ty, BDelta)), AInvC);
|
||||
if ((RNG.nextU32() & 1U) == 0) {
|
||||
Res = emitQuadraticHalfFeistel(B, Res, RNG.nextNonZeroU64() & Mask, BW);
|
||||
}
|
||||
return Res;
|
||||
}
|
||||
|
||||
Value *Lin = emitLinearMBA(B, BO, RNG.nextU32());
|
||||
if (!Lin)
|
||||
return nullptr;
|
||||
return emitQuadraticHalfFeistel(B, Lin, RNG.nextNonZeroU64() & Mask, BW);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runArithmeticObfuscation(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isArithmeticEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
if (!isMachOAArch64NonArm64e(M))
|
||||
return false;
|
||||
|
||||
bool Changed = false;
|
||||
const unsigned DefaultRounds = Policy.arithmeticRounds();
|
||||
const unsigned DefaultMaxPerFn = Policy.arithmeticMaxPerFn();
|
||||
const bool DefaultNonlinear = Policy.arithmeticNonlinearMBA();
|
||||
|
||||
for (Function &F : M) {
|
||||
if (!Policy.shouldObfuscateArithmeticInFunction(F))
|
||||
continue;
|
||||
if (!isFunctionSafeForTransform(F, Policy,
|
||||
&Policy.arithmeticExemptFunctions())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const TargetRule *Rule = Policy.findArithmeticRule(F);
|
||||
unsigned Rounds = (Rule && Rule->Rounds) ? *Rule->Rounds : DefaultRounds;
|
||||
unsigned MaxPerFn =
|
||||
(Rule && Rule->MaxPerFn) ? *Rule->MaxPerFn : DefaultMaxPerFn;
|
||||
unsigned Prob =
|
||||
(Rule && Rule->Probability) ? *Rule->Probability : 100U;
|
||||
bool UseNonlinear =
|
||||
(Rule && Rule->NonlinearMBA) ? *Rule->NonlinearMBA : DefaultNonlinear;
|
||||
|
||||
if (MaxPerFn == 0 || Prob == 0)
|
||||
continue;
|
||||
|
||||
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
|
||||
(F.getName() + "|arith").str());
|
||||
unsigned FnRewrites = 0;
|
||||
|
||||
for (unsigned Round = 0; Round < Rounds && FnRewrites < MaxPerFn; ++Round) {
|
||||
SmallVector<BinaryOperator *, 32> Candidates;
|
||||
for (BasicBlock &BB : F) {
|
||||
for (Instruction &I : BB) {
|
||||
if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
|
||||
if (isEligibleBinaryOp(BO))
|
||||
Candidates.push_back(BO);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Candidates.empty())
|
||||
break;
|
||||
|
||||
for (BinaryOperator *BO : Candidates) {
|
||||
if (FnRewrites >= MaxPerFn)
|
||||
break;
|
||||
if (Prob < 100U && (RNG.nextU32() % 100U) >= Prob)
|
||||
continue;
|
||||
IRBuilder<> B(BO);
|
||||
B.SetCurrentDebugLocation(resolveInstDebugLoc(BO, F));
|
||||
Value *Replacement = nullptr;
|
||||
if (UseNonlinear && Round == 0) {
|
||||
Replacement = emitNonlinearMBA(B, BO, RNG);
|
||||
if (Replacement)
|
||||
++Audit.NonlinearMBACount;
|
||||
} else {
|
||||
Replacement = emitLinearMBA(B, BO, RNG.nextU32());
|
||||
}
|
||||
if (!Replacement)
|
||||
continue;
|
||||
BO->replaceAllUsesWith(Replacement);
|
||||
BO->eraseFromParent();
|
||||
++FnRewrites;
|
||||
++Audit.ArithmeticRewritesCount;
|
||||
Changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (FnRewrites > 0) {
|
||||
if (verifyFunction(F, &errs())) {
|
||||
report_fatal_error(Twine("[IGArithmetic] IR verification failed on ") +
|
||||
F.getName());
|
||||
}
|
||||
Audit.ArithmeticFunctions.push_back(F.getName().str());
|
||||
}
|
||||
}
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,175 @@
|
||||
#include "IGPassUtils.h"
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/IR/Attributes.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/IntrinsicInst.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Verifier.h"
|
||||
#include "llvm/Support/ErrorHandling.h"
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
bool isBlockSafeToSplit(const BasicBlock &BB) {
|
||||
if (BB.isEHPad() || isa<CatchSwitchInst>(BB.getTerminator()))
|
||||
return false;
|
||||
for (const Instruction &I : BB) {
|
||||
if (I.getType()->isTokenTy())
|
||||
return false;
|
||||
if (const auto *AI = dyn_cast<AllocaInst>(&I)) {
|
||||
if (AI->isSwiftError())
|
||||
return false;
|
||||
}
|
||||
if (const auto *CB = dyn_cast<CallBase>(&I)) {
|
||||
if (CB->isInlineAsm() || CB->isMustTailCall() ||
|
||||
CB->getCallingConv() == CallingConv::SwiftTail) {
|
||||
return false;
|
||||
}
|
||||
if (const Function *Callee = CB->getCalledFunction()) {
|
||||
StringRef Name = Callee->getName();
|
||||
if (Name.starts_with("llvm.coro."))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isDangerousSplitPoint(const Instruction &I) {
|
||||
if (I.isTerminator() || isa<PHINode>(I) || isa<AllocaInst>(I) ||
|
||||
isa<LandingPadInst>(I) || isa<DbgInfoIntrinsic>(I)) {
|
||||
return true;
|
||||
}
|
||||
if (const auto *CB = dyn_cast<CallBase>(&I)) {
|
||||
if (const Function *Callee = CB->getCalledFunction()) {
|
||||
StringRef Name = Callee->getName();
|
||||
if (Name.contains("objc_retainAutoreleasedReturnValue") ||
|
||||
Name.contains("objc_unsafeClaimAutoreleasedReturnValue") ||
|
||||
Name.starts_with("llvm.objc.clang.arc.use")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runBasicBlockSplit(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isBBSplitEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
if (!isMachOAArch64NonArm64e(M))
|
||||
return false;
|
||||
|
||||
const unsigned DefaultMaxPerFn = Policy.bbSplitMaxPerFn();
|
||||
const unsigned MinInsts = Policy.bbSplitMinInsts();
|
||||
bool Changed = false;
|
||||
|
||||
for (Function &F : M) {
|
||||
if (!Policy.shouldSplitBasicBlocksInFunction(F))
|
||||
continue;
|
||||
if (!isFunctionSafeForTransform(F, Policy,
|
||||
&Policy.bbSplitExemptFunctions())) {
|
||||
continue;
|
||||
}
|
||||
if (F.isVarArg() || F.hasPersonalityFn() || F.empty())
|
||||
continue;
|
||||
|
||||
const TargetRule *Rule = Policy.findBBSplitRule(F);
|
||||
unsigned MaxPerFn =
|
||||
(Rule && Rule->MaxPerFn) ? *Rule->MaxPerFn : DefaultMaxPerFn;
|
||||
unsigned Prob =
|
||||
(Rule && Rule->Probability) ? *Rule->Probability : 100U;
|
||||
if (MaxPerFn == 0 || Prob == 0)
|
||||
continue;
|
||||
|
||||
SmallVector<BasicBlock *, 16> WorkBlocks;
|
||||
for (BasicBlock &BB : F)
|
||||
WorkBlocks.push_back(&BB);
|
||||
|
||||
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
|
||||
(F.getName() + "|bbsplit").str());
|
||||
unsigned FnSplits = 0;
|
||||
|
||||
for (size_t wi = 0; wi < WorkBlocks.size() && FnSplits < MaxPerFn; ++wi) {
|
||||
BasicBlock *BB = WorkBlocks[wi];
|
||||
if (!BB || !isBlockSafeToSplit(*BB))
|
||||
continue;
|
||||
|
||||
AllocaInst *LastAlloca = nullptr;
|
||||
for (Instruction &Inst : *BB) {
|
||||
if (auto *AI = dyn_cast<AllocaInst>(&Inst))
|
||||
LastAlloca = AI;
|
||||
}
|
||||
BasicBlock::iterator FirstSplittable =
|
||||
LastAlloca ? std::next(LastAlloca->getIterator())
|
||||
: BB->getFirstInsertionPt();
|
||||
while (FirstSplittable != BB->end() &&
|
||||
(isa<AllocaInst>(*FirstSplittable) ||
|
||||
isa<DbgInfoIntrinsic>(*FirstSplittable))) {
|
||||
++FirstSplittable;
|
||||
}
|
||||
|
||||
SmallVector<Instruction *, 32> SplittableInsts;
|
||||
for (auto It = FirstSplittable; It != BB->end(); ++It) {
|
||||
Instruction &I = *It;
|
||||
if (!I.isTerminator() && !isa<DbgInfoIntrinsic>(I))
|
||||
SplittableInsts.push_back(&I);
|
||||
}
|
||||
if (SplittableInsts.size() < MinInsts)
|
||||
continue;
|
||||
|
||||
SmallVector<Instruction *, 16> CandidateTargets;
|
||||
// Start at index 1 so the upper block retains at least 1 real instruction.
|
||||
for (size_t idx = 1; idx < SplittableInsts.size(); ++idx) {
|
||||
if (!isDangerousSplitPoint(*SplittableInsts[idx]))
|
||||
CandidateTargets.push_back(SplittableInsts[idx]);
|
||||
}
|
||||
if (CandidateTargets.empty())
|
||||
continue;
|
||||
if (Prob < 100U && (RNG.nextU32() % 100U) >= Prob)
|
||||
continue;
|
||||
|
||||
size_t Mid = CandidateTargets.size() / 2;
|
||||
int Jitter = static_cast<int>(RNG.nextU32() % 3U) - 1;
|
||||
ptrdiff_t Chosen = static_cast<ptrdiff_t>(Mid) + Jitter;
|
||||
if (Chosen < 0)
|
||||
Chosen = 0;
|
||||
if (Chosen >= static_cast<ptrdiff_t>(CandidateTargets.size()))
|
||||
Chosen = static_cast<ptrdiff_t>(CandidateTargets.size()) - 1;
|
||||
|
||||
Instruction *SplitBefore = CandidateTargets[static_cast<size_t>(Chosen)];
|
||||
BasicBlock *NewBB = BB->splitBasicBlock(SplitBefore->getIterator(),
|
||||
BB->getName() + ".ig.spl");
|
||||
if (F.getSubprogram() && BB->getTerminator() &&
|
||||
!BB->getTerminator()->getDebugLoc()) {
|
||||
BB->getTerminator()->setDebugLoc(
|
||||
resolveInstDebugLoc(&*NewBB->begin(), F));
|
||||
}
|
||||
++FnSplits;
|
||||
++Audit.BBSplitCount;
|
||||
Changed = true;
|
||||
if (FnSplits < MaxPerFn) {
|
||||
WorkBlocks.push_back(BB);
|
||||
WorkBlocks.push_back(NewBB);
|
||||
}
|
||||
}
|
||||
|
||||
if (FnSplits > 0) {
|
||||
if (verifyFunction(F, &errs())) {
|
||||
report_fatal_error(Twine("[IGBasicBlockSplit] IR verification failed on ") +
|
||||
F.getName());
|
||||
}
|
||||
Audit.BBSplitFunctions.push_back(F.getName().str());
|
||||
}
|
||||
}
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,832 @@
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/DenseMap.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/IR/CFG.h"
|
||||
#include "llvm/IR/DebugInfoMetadata.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/IRBuilder.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/IntrinsicInst.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Verifier.h"
|
||||
#include "llvm/Transforms/Utils/Local.h"
|
||||
#include "llvm/Support/raw_ostream.h"
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
DebugLoc pickBlockDebugLoc(const BasicBlock &BB, const Function &F) {
|
||||
for (const Instruction &I : BB) {
|
||||
if (I.getDebugLoc())
|
||||
return I.getDebugLoc();
|
||||
}
|
||||
if (DISubprogram *SP = F.getSubprogram()) {
|
||||
unsigned Line = SP->getScopeLine() ? SP->getScopeLine() : SP->getLine();
|
||||
return DILocation::get(F.getContext(), Line, 0, SP);
|
||||
}
|
||||
return DebugLoc();
|
||||
}
|
||||
|
||||
bool isCompilerSynthesizedGlue(const Function &F,
|
||||
const IGPolicyConfig &Policy) {
|
||||
if (Policy.hasAnnotation(F, "ig_flatten"))
|
||||
return false;
|
||||
StringRef Name = F.getName();
|
||||
if (!Name.empty() && Name.front() == '\x01')
|
||||
Name = Name.drop_front();
|
||||
|
||||
if (Name.starts_with("block_copy_helper") ||
|
||||
Name.starts_with("block_destroy_helper") ||
|
||||
Name.starts_with("__copy_helper_block_") ||
|
||||
Name.starts_with("___copy_helper_block_") ||
|
||||
Name.starts_with("__destroy_helper_block_") ||
|
||||
Name.starts_with("___destroy_helper_block_") ||
|
||||
Name.starts_with("objectdestroy") ||
|
||||
Name.ends_with(" .cxx_destruct]") ||
|
||||
Name.contains(".resume.")) {
|
||||
return true;
|
||||
}
|
||||
if (Name.starts_with("$s") || Name.starts_with("_$s")) {
|
||||
if (Name.ends_with("Tm") || Name.ends_with("Wl") ||
|
||||
Name.ends_with("WL") || Name.ends_with("CMa") ||
|
||||
Name.ends_with("VMa") || Name.ends_with("OMa") ||
|
||||
Name.ends_with("WOh") || Name.ends_with("WOy") ||
|
||||
Name.ends_with("WOe") || Name.ends_with("WOc") ||
|
||||
Name.ends_with("WOb") || Name.ends_with("WOd") ||
|
||||
Name.ends_with("TR") || Name.ends_with("TA")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (const Module *M = F.getParent()) {
|
||||
if (M->getNamedMetadata("llvm.dbg.cu") != nullptr) {
|
||||
const DISubprogram *SP = F.getSubprogram();
|
||||
if (!SP || SP->isArtificial() ||
|
||||
SP->getFilename().contains("<compiler-generated>")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool checkFlatteningSafety(Function &F, const IGPolicyConfig &Policy,
|
||||
std::string &SkipReason, bool &HasMustTailOut) {
|
||||
HasMustTailOut = false;
|
||||
if (GlobalValue::isWeakForLinker(F.getLinkage()) ||
|
||||
F.hasAvailableExternallyLinkage()) {
|
||||
SkipReason = "weak_or_linkonce_odr";
|
||||
return false;
|
||||
}
|
||||
if (isCompilerSynthesizedGlue(F, Policy)) {
|
||||
SkipReason = "compiler_synthesized_thunk";
|
||||
return false;
|
||||
}
|
||||
if (!Policy.splitLinearBlocks() && F.size() < 3) {
|
||||
SkipReason = "too_few_blocks";
|
||||
return false;
|
||||
}
|
||||
|
||||
const BasicBlock *EntryBB = &F.getEntryBlock();
|
||||
const DataLayout &DL = F.getDataLayout();
|
||||
uint64_t NonEntryAllocaBytes = 0;
|
||||
|
||||
for (BasicBlock &BB : F) {
|
||||
if (BB.isEHPad()) {
|
||||
SkipReason = "eh_pad";
|
||||
return false;
|
||||
}
|
||||
Instruction *Term = BB.getTerminator();
|
||||
if (!Term || isa<InvokeInst>(Term) || isa<ResumeInst>(Term) ||
|
||||
isa<CatchSwitchInst>(Term) || isa<CatchReturnInst>(Term) ||
|
||||
isa<CleanupReturnInst>(Term) || isa<IndirectBrInst>(Term) ||
|
||||
isa<CallBrInst>(Term)) {
|
||||
SkipReason = "eh_or_indirect_terminator";
|
||||
return false;
|
||||
}
|
||||
|
||||
for (Instruction &I : BB) {
|
||||
if (I.getType()->isTokenTy()) {
|
||||
SkipReason = "token_type";
|
||||
return false;
|
||||
}
|
||||
if (auto *AI = dyn_cast<AllocaInst>(&I)) {
|
||||
if (!AI->isStaticAlloca() || AI->isUsedWithInAlloca()) {
|
||||
SkipReason = "dynamic_alloca";
|
||||
return false;
|
||||
}
|
||||
if (AI->isSwiftError()) {
|
||||
if (&BB != EntryBB) {
|
||||
SkipReason = "non_entry_swifterror";
|
||||
return false;
|
||||
}
|
||||
for (const User *U : AI->users()) {
|
||||
const auto *UI = dyn_cast<Instruction>(U);
|
||||
if (!UI || UI->getType()->isTokenTy()) {
|
||||
SkipReason = "swifterror_complex_use";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (&BB != EntryBB) {
|
||||
TypeSize AllocSz = DL.getTypeAllocSize(AI->getAllocatedType());
|
||||
if (AllocSz.isScalable()) {
|
||||
SkipReason = "dynamic_alloca";
|
||||
return false;
|
||||
}
|
||||
NonEntryAllocaBytes += AllocSz.getFixedValue();
|
||||
if (NonEntryAllocaBytes > 4096u) {
|
||||
SkipReason = "large_non_entry_alloca";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
|
||||
if (II->getIntrinsicID() == Intrinsic::stacksave) {
|
||||
for (const User *U : II->users()) {
|
||||
const auto *Restore = dyn_cast<IntrinsicInst>(U);
|
||||
if (!Restore ||
|
||||
Restore->getIntrinsicID() != Intrinsic::stackrestore) {
|
||||
SkipReason = "complex_stacksave";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (auto *CB = dyn_cast<CallBase>(&I)) {
|
||||
if (CB->isInlineAsm()) {
|
||||
SkipReason = "inline_asm";
|
||||
return false;
|
||||
}
|
||||
if (Function *Callee = CB->getCalledFunction()) {
|
||||
if (Callee->getName().starts_with("llvm.coro.")) {
|
||||
SkipReason = "unsplit_coroutine";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (auto *CI = dyn_cast<CallInst>(&I)) {
|
||||
if (CI->isMustTailCall()) {
|
||||
HasMustTailOut = true;
|
||||
Instruction *Next = CI->getNextNonDebugInstruction();
|
||||
if (Next != Term || !isa<ReturnInst>(Term)) {
|
||||
SkipReason = "non_terminal_musttail";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool splitLinearBlocksIfNeeded(Function &F, Instruction *FirstNonAlloca,
|
||||
std::string &SkipReason) {
|
||||
if (F.size() >= 3)
|
||||
return true;
|
||||
|
||||
SmallVector<Instruction *, 32> SplitCandidates;
|
||||
for (BasicBlock &BB : F) {
|
||||
bool SeenBodyInst = false;
|
||||
for (Instruction &I : BB) {
|
||||
if (isa<AllocaInst>(I) || isa<PHINode>(I) || I.isDebugOrPseudoInst() ||
|
||||
I.isLifetimeStartOrEnd()) {
|
||||
continue;
|
||||
}
|
||||
if (&I == FirstNonAlloca) {
|
||||
SeenBodyInst = true;
|
||||
continue;
|
||||
}
|
||||
if (!SeenBodyInst) {
|
||||
SeenBodyInst = true;
|
||||
continue;
|
||||
}
|
||||
if (I.isTerminator())
|
||||
continue;
|
||||
if (auto *CI = dyn_cast<CallInst>(&I)) {
|
||||
if (CI->isMustTailCall())
|
||||
continue;
|
||||
}
|
||||
SplitCandidates.push_back(&I);
|
||||
}
|
||||
}
|
||||
|
||||
if (SplitCandidates.size() < 2) {
|
||||
if (F.size() == 2 && FirstNonAlloca != F.getEntryBlock().getTerminator())
|
||||
return true;
|
||||
SkipReason = "too_few_blocks";
|
||||
return false;
|
||||
}
|
||||
|
||||
SmallVector<Instruction *, 4> Chosen;
|
||||
size_t N = SplitCandidates.size();
|
||||
size_t Desired = (F.size() == 1) ? std::min<size_t>(3, N) : 1;
|
||||
if (Desired >= N) {
|
||||
for (size_t i = 0; i < N; ++i)
|
||||
Chosen.push_back(SplitCandidates[i]);
|
||||
} else {
|
||||
for (size_t k = 1; k <= Desired; ++k) {
|
||||
size_t Idx = ((k * N) / (Desired + 1));
|
||||
if (Idx >= N)
|
||||
Idx = N - 1;
|
||||
Instruction *Inst = SplitCandidates[Idx];
|
||||
if (std::find(Chosen.begin(), Chosen.end(), Inst) == Chosen.end())
|
||||
Chosen.push_back(Inst);
|
||||
}
|
||||
}
|
||||
|
||||
// Split from back to front so earlier candidate pointers stay in valid blocks
|
||||
for (auto It = Chosen.rbegin(); It != Chosen.rend(); ++It) {
|
||||
Instruction *SplitAt = *It;
|
||||
SplitAt->getParent()->splitBasicBlock(SplitAt->getIterator(),
|
||||
"ig.lin.split");
|
||||
}
|
||||
return F.size() >= 2;
|
||||
}
|
||||
|
||||
struct StateCipherParams {
|
||||
unsigned Kind = 0; // 0=xor_rot, 1=odd_affine_mul, 2=add_xor
|
||||
uint32_t MaskKey = 0;
|
||||
uint32_t AddKey = 0;
|
||||
uint32_t MulKey = 1;
|
||||
uint32_t InvMulKey = 1;
|
||||
uint32_t Rot = 7;
|
||||
|
||||
const char *encodingName() const {
|
||||
switch (Kind) {
|
||||
case 0:
|
||||
return "xor_rot";
|
||||
case 1:
|
||||
return "odd_affine_mul";
|
||||
default:
|
||||
return "add_xor";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
StateCipherParams makeCipherParams(IGDeterministicRNG &RNG) {
|
||||
StateCipherParams P;
|
||||
P.Kind = RNG.nextU32() % 3u;
|
||||
P.MaskKey = RNG.nextNonZeroU32();
|
||||
P.AddKey = RNG.nextNonZeroU32();
|
||||
P.Rot = 1u + (RNG.nextU32() % 31u);
|
||||
// Guarantee odd multiplier != 1 (low 2 bits = 0b11) and invert mod 2^32
|
||||
P.MulKey = RNG.nextU32() | 3u;
|
||||
uint32_t Inv = 1u;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
Inv *= static_cast<uint32_t>(2u - P.MulKey * Inv);
|
||||
P.InvMulKey = Inv;
|
||||
return P;
|
||||
}
|
||||
|
||||
uint32_t encodeState(uint32_t RawState, const StateCipherParams &P) {
|
||||
if (P.Kind == 0) {
|
||||
uint32_t X = RawState ^ P.MaskKey;
|
||||
return (X << P.Rot) | (X >> (32u - P.Rot));
|
||||
}
|
||||
if (P.Kind == 1)
|
||||
return static_cast<uint32_t>(RawState * P.MulKey + P.AddKey);
|
||||
return static_cast<uint32_t>(RawState + P.AddKey) ^ P.MaskKey;
|
||||
}
|
||||
|
||||
Value *emitDecodeState(IRBuilder<> &B, Value *Encoded, Type *I32Ty,
|
||||
const StateCipherParams &P) {
|
||||
if (P.Kind == 0) {
|
||||
Value *R1 =
|
||||
B.CreateLShr(Encoded, ConstantInt::get(I32Ty, P.Rot), "ig.dec.r1");
|
||||
Value *R2 = B.CreateShl(Encoded, ConstantInt::get(I32Ty, 32u - P.Rot),
|
||||
"ig.dec.r2");
|
||||
Value *Unrot = B.CreateOr(R1, R2, "ig.dec.unrot");
|
||||
return B.CreateXor(Unrot, ConstantInt::get(I32Ty, P.MaskKey), "ig.dec.xor");
|
||||
}
|
||||
if (P.Kind == 1) {
|
||||
Value *Sub =
|
||||
B.CreateSub(Encoded, ConstantInt::get(I32Ty, P.AddKey), "ig.dec.sub");
|
||||
return B.CreateMul(Sub, ConstantInt::get(I32Ty, P.InvMulKey),
|
||||
"ig.dec.mul");
|
||||
}
|
||||
Value *X =
|
||||
B.CreateXor(Encoded, ConstantInt::get(I32Ty, P.MaskKey), "ig.dec.xor");
|
||||
return B.CreateSub(X, ConstantInt::get(I32Ty, P.AddKey), "ig.dec.sub");
|
||||
}
|
||||
|
||||
bool flattenSingleFunction(Function &F, const IGPolicyConfig &Policy,
|
||||
FlattenedFunctionDetail &DetailOut,
|
||||
std::string &SkipReason) {
|
||||
bool HasMustTail = false;
|
||||
if (!checkFlatteningSafety(F, Policy, SkipReason, HasMustTail))
|
||||
return false;
|
||||
|
||||
LLVMContext &Ctx = F.getContext();
|
||||
IntegerType *I32Ty = Type::getInt32Ty(Ctx);
|
||||
BasicBlock &EntryBB = F.getEntryBlock();
|
||||
|
||||
// 1. Drop redundant stacksave/stackrestore (verified static-alloca-only) and
|
||||
// hoist all static allocas across F before the first non-alloca in EntryBB.
|
||||
SmallVector<IntrinsicInst *, 8> StackRestores;
|
||||
SmallVector<IntrinsicInst *, 8> StackSaves;
|
||||
SmallVector<AllocaInst *, 16> Allocas;
|
||||
for (BasicBlock &BB : F) {
|
||||
for (Instruction &I : BB) {
|
||||
if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
|
||||
if (II->getIntrinsicID() == Intrinsic::stackrestore)
|
||||
StackRestores.push_back(II);
|
||||
else if (II->getIntrinsicID() == Intrinsic::stacksave)
|
||||
StackSaves.push_back(II);
|
||||
} else if (auto *AI = dyn_cast<AllocaInst>(&I)) {
|
||||
Allocas.push_back(AI);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (IntrinsicInst *SR : StackRestores)
|
||||
SR->eraseFromParent();
|
||||
for (IntrinsicInst *SS : StackSaves) {
|
||||
if (SS->use_empty())
|
||||
SS->eraseFromParent();
|
||||
}
|
||||
|
||||
Instruction *FirstNonAlloca = nullptr;
|
||||
for (Instruction &I : EntryBB) {
|
||||
if (!isa<AllocaInst>(I)) {
|
||||
FirstNonAlloca = &I;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!FirstNonAlloca) {
|
||||
SkipReason = "malformed_entry";
|
||||
return false;
|
||||
}
|
||||
for (AllocaInst *AI : Allocas) {
|
||||
if (AI->getParent() == &EntryBB && AI->comesBefore(FirstNonAlloca))
|
||||
continue;
|
||||
AI->moveBefore(FirstNonAlloca->getIterator());
|
||||
}
|
||||
|
||||
// Recompute split point cleanly after hoisting allocas.
|
||||
Instruction *SplitInst = nullptr;
|
||||
for (Instruction &I : EntryBB) {
|
||||
if (!isa<AllocaInst>(I)) {
|
||||
SplitInst = &I;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!SplitInst) {
|
||||
SkipReason = "no_split_point";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Policy.splitLinearBlocks() && F.size() < 3) {
|
||||
if (!splitLinearBlocksIfNeeded(F, SplitInst, SkipReason))
|
||||
return false;
|
||||
}
|
||||
|
||||
// If SplitInst is already the terminator and EntryBB has an unconditional br,
|
||||
// avoid creating a degenerate empty body block unless there are already >= 2
|
||||
// blocks outside EntryBB.
|
||||
if (SplitInst == EntryBB.getTerminator() && F.size() < 3) {
|
||||
SkipReason = "too_few_body_blocks";
|
||||
return false;
|
||||
}
|
||||
|
||||
BasicBlock *FirstBodyBB =
|
||||
EntryBB.splitBasicBlock(SplitInst->getIterator(), "ig.entry.body");
|
||||
|
||||
SmallVector<BasicBlock *, 32> OrigBBs;
|
||||
for (BasicBlock &BB : F) {
|
||||
if (&BB != &EntryBB)
|
||||
OrigBBs.push_back(&BB);
|
||||
}
|
||||
if (OrigBBs.size() < 2) {
|
||||
SkipReason = "too_few_body_blocks";
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. Demote all PHINodes and cross-block SSA instructions to EntryBB allocas
|
||||
SmallVector<PHINode *, 16> Phis;
|
||||
for (BasicBlock &BB : F) {
|
||||
for (PHINode &PN : BB.phis())
|
||||
Phis.push_back(&PN);
|
||||
}
|
||||
for (PHINode *PN : Phis) {
|
||||
DemotePHIToStack(PN, EntryBB.getTerminator()->getIterator());
|
||||
}
|
||||
|
||||
SmallVector<Instruction *, 32> CrossBlockRegs;
|
||||
for (BasicBlock *BB : OrigBBs) {
|
||||
for (Instruction &I : *BB) {
|
||||
if (I.isTerminator() || I.getType()->isVoidTy() || isa<AllocaInst>(I))
|
||||
continue;
|
||||
if (auto *CI = dyn_cast<CallInst>(&I)) {
|
||||
if (CI->isMustTailCall())
|
||||
continue;
|
||||
}
|
||||
bool UsedOutside = false;
|
||||
for (const User *U : I.users()) {
|
||||
const auto *UI = dyn_cast<Instruction>(U);
|
||||
if (!UI || UI->getParent() != BB || isa<PHINode>(UI)) {
|
||||
UsedOutside = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (UsedOutside)
|
||||
CrossBlockRegs.push_back(&I);
|
||||
}
|
||||
}
|
||||
for (Instruction *I : CrossBlockRegs) {
|
||||
DemoteRegToStack(*I, /*VolatileLoads=*/false,
|
||||
EntryBB.getTerminator()->getIterator());
|
||||
}
|
||||
|
||||
// 3. Deterministic per-function RNG for layout, states, encoding, topology
|
||||
IGDeterministicRNG RNG(Policy.seed(), F.getParent()->getModuleIdentifier(),
|
||||
F.getName());
|
||||
|
||||
SmallVector<BasicBlock *, 32> ShuffledBBs(OrigBBs.begin(), OrigBBs.end());
|
||||
RNG.shuffle(ShuffledBBs);
|
||||
|
||||
DenseMap<BasicBlock *, uint32_t> StateMap;
|
||||
DenseMap<uint32_t, bool> UsedIds;
|
||||
for (BasicBlock *BB : ShuffledBBs) {
|
||||
uint32_t Id = 0;
|
||||
do {
|
||||
Id = RNG.nextNonZeroU32();
|
||||
} while (UsedIds.contains(Id));
|
||||
UsedIds[Id] = true;
|
||||
StateMap[BB] = Id;
|
||||
}
|
||||
|
||||
StateCipherParams Cipher = makeCipherParams(RNG);
|
||||
unsigned TopologyKind = 0;
|
||||
if (Policy.flattenTopology() == FlattenTopology::StarSwitch) {
|
||||
TopologyKind = 0;
|
||||
} else if (ShuffledBBs.size() >= 4) {
|
||||
TopologyKind = RNG.nextU32() % 3u;
|
||||
} else if (ShuffledBBs.size() >= 2) {
|
||||
TopologyKind = (RNG.nextU32() % 2u == 0) ? 0u : 2u;
|
||||
}
|
||||
|
||||
const char *TopologyName = "sparse_switch";
|
||||
if (TopologyKind == 1)
|
||||
TopologyName = "cascaded_subdisp";
|
||||
else if (TopologyKind == 2)
|
||||
TopologyName = "asymmetric_cmp_tree";
|
||||
|
||||
DebugLoc EntryLoc = pickBlockDebugLoc(*FirstBodyBB, F);
|
||||
|
||||
// Physically reorder ShuffledBBs in the Function to vary binary block layout
|
||||
BasicBlock *Anchor = &EntryBB;
|
||||
for (BasicBlock *BB : ShuffledBBs) {
|
||||
BB->moveAfter(Anchor);
|
||||
Anchor = BB;
|
||||
}
|
||||
|
||||
// 4. Create state slot in EntryBB and replace EntryBB terminator
|
||||
auto *StateSlot = new AllocaInst(I32Ty, 0, "ig.state",
|
||||
EntryBB.getTerminator()->getIterator());
|
||||
StateSlot->setAlignment(Align(4));
|
||||
|
||||
bool HasReturnInst = false;
|
||||
for (BasicBlock *BB : ShuffledBBs) {
|
||||
if (isa<ReturnInst>(BB->getTerminator())) {
|
||||
HasReturnInst = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
bool UseUnifiedRet =
|
||||
(TopologyKind == 0) && HasReturnInst && !HasMustTail &&
|
||||
(F.getReturnType()->isVoidTy() || F.getReturnType()->isSized());
|
||||
|
||||
AllocaInst *RetSlot = nullptr;
|
||||
Align RetAlign(1);
|
||||
BasicBlock *UnifiedRetBB = nullptr;
|
||||
uint32_t ExitStateId = 0;
|
||||
if (UseUnifiedRet) {
|
||||
if (!F.getReturnType()->isVoidTy()) {
|
||||
RetAlign =
|
||||
F.getParent()->getDataLayout().getABITypeAlign(F.getReturnType());
|
||||
RetSlot = new AllocaInst(F.getReturnType(), 0, "ig.ret.slot",
|
||||
EntryBB.getTerminator()->getIterator());
|
||||
RetSlot->setAlignment(RetAlign);
|
||||
}
|
||||
do {
|
||||
ExitStateId = RNG.nextNonZeroU32();
|
||||
} while (UsedIds.contains(ExitStateId));
|
||||
UsedIds[ExitStateId] = true;
|
||||
UnifiedRetBB = BasicBlock::Create(Ctx, "ig.unified.ret", &F);
|
||||
IRBuilder<> UB(UnifiedRetBB);
|
||||
UB.SetCurrentDebugLocation(EntryLoc);
|
||||
if (RetSlot) {
|
||||
LoadInst *RetVal =
|
||||
UB.CreateLoad(F.getReturnType(), RetSlot, false, "ig.ret.val");
|
||||
RetVal->setAlignment(RetAlign);
|
||||
UB.CreateRet(RetVal);
|
||||
} else {
|
||||
UB.CreateRetVoid();
|
||||
}
|
||||
}
|
||||
|
||||
BasicBlock *LoopEntryBB = BasicBlock::Create(Ctx, "ig.loop.entry", &F);
|
||||
BasicBlock *LoopEndBB = BasicBlock::Create(Ctx, "ig.loop.end", &F);
|
||||
BasicBlock *SwitchDefaultBB =
|
||||
BasicBlock::Create(Ctx, "ig.switch.default", &F);
|
||||
|
||||
LoopEntryBB->moveAfter(&EntryBB);
|
||||
if (UnifiedRetBB) {
|
||||
UnifiedRetBB->moveAfter(LoopEndBB);
|
||||
}
|
||||
|
||||
SmallVector<std::pair<uint32_t, BasicBlock *>, 8> BogusCases;
|
||||
unsigned BogusCount = (TopologyKind == 0) ? Policy.bogusBlockCount() : 0u;
|
||||
for (unsigned b = 0; b < BogusCount; ++b) {
|
||||
uint32_t BogusId = 0;
|
||||
do {
|
||||
BogusId = RNG.nextNonZeroU32();
|
||||
} while (UsedIds.contains(BogusId));
|
||||
UsedIds[BogusId] = true;
|
||||
BasicBlock *BogusBB =
|
||||
BasicBlock::Create(Ctx, "ig.bogus." + Twine(b), &F, SwitchDefaultBB);
|
||||
IRBuilder<> BBBuilder(BogusBB);
|
||||
BBBuilder.SetCurrentDebugLocation(EntryLoc);
|
||||
LoadInst *BLoad = BBBuilder.CreateLoad(I32Ty, StateSlot, /*isVolatile=*/true,
|
||||
"ig.bogus.st");
|
||||
BLoad->setAlignment(Align(4));
|
||||
BasicBlock *T1 = ShuffledBBs[RNG.nextU32() % ShuffledBBs.size()];
|
||||
BasicBlock *T2 = ShuffledBBs[RNG.nextU32() % ShuffledBBs.size()];
|
||||
uint32_t C1 = encodeState(StateMap[T1], Cipher);
|
||||
uint32_t C2 = encodeState(StateMap[T2], Cipher);
|
||||
Value *M = BBBuilder.CreateMul(BLoad, ConstantInt::get(I32Ty, RNG.nextU32() | 1u),
|
||||
"ig.bm");
|
||||
Value *X = BBBuilder.CreateXor(
|
||||
M, ConstantInt::get(I32Ty, RNG.nextNonZeroU32()), "ig.bx");
|
||||
Value *Cond = BBBuilder.CreateICmpUGT(
|
||||
X, ConstantInt::get(I32Ty, RNG.nextU32()), "ig.bc");
|
||||
Value *Sel = BBBuilder.CreateSelect(
|
||||
Cond, ConstantInt::get(I32Ty, C1), ConstantInt::get(I32Ty, C2),
|
||||
"ig.bsel");
|
||||
StoreInst *BStore =
|
||||
BBBuilder.CreateStore(Sel, StateSlot, /*isVolatile=*/true);
|
||||
BStore->setAlignment(Align(4));
|
||||
BBBuilder.CreateBr(LoopEndBB);
|
||||
BasicBlock *InsertAfter = ShuffledBBs[RNG.nextU32() % ShuffledBBs.size()];
|
||||
BogusBB->moveAfter(InsertAfter);
|
||||
BogusCases.emplace_back(BogusId, BogusBB);
|
||||
}
|
||||
|
||||
DetailOut.Name = F.getName().str();
|
||||
DetailOut.Topology = TopologyName;
|
||||
DetailOut.Encoding = Cipher.encodingName();
|
||||
DetailOut.Blocks = static_cast<unsigned>(
|
||||
ShuffledBBs.size() + BogusCases.size() + (UnifiedRetBB ? 1u : 0u));
|
||||
|
||||
EntryBB.getTerminator()->eraseFromParent();
|
||||
{
|
||||
IRBuilder<> EB(&EntryBB);
|
||||
EB.SetCurrentDebugLocation(EntryLoc);
|
||||
uint32_t InitEnc = encodeState(StateMap[FirstBodyBB], Cipher);
|
||||
StoreInst *InitStore =
|
||||
EB.CreateStore(ConstantInt::get(I32Ty, InitEnc), StateSlot, true);
|
||||
InitStore->setAlignment(Align(4));
|
||||
EB.CreateBr(LoopEntryBB);
|
||||
}
|
||||
|
||||
{
|
||||
IRBuilder<> DB(SwitchDefaultBB);
|
||||
DB.SetCurrentDebugLocation(EntryLoc);
|
||||
DB.CreateBr(LoopEndBB);
|
||||
}
|
||||
|
||||
{
|
||||
IRBuilder<> LB(LoopEndBB);
|
||||
LB.SetCurrentDebugLocation(EntryLoc);
|
||||
LB.CreateBr(LoopEntryBB);
|
||||
}
|
||||
|
||||
// 5. Build polymorphic dispatcher (sparse switch / cascaded sub-dispatchers /
|
||||
// asymmetric comparison tree)
|
||||
{
|
||||
IRBuilder<> DB(LoopEntryBB);
|
||||
DB.SetCurrentDebugLocation(EntryLoc);
|
||||
LoadInst *EncState = DB.CreateLoad(I32Ty, StateSlot, /*isVolatile=*/true,
|
||||
"ig.state.enc");
|
||||
EncState->setAlignment(Align(4));
|
||||
Value *CurState = emitDecodeState(DB, EncState, I32Ty, Cipher);
|
||||
|
||||
if (TopologyKind == 1) {
|
||||
size_t N = ShuffledBBs.size();
|
||||
if (N >= 9) {
|
||||
size_t S1 = std::max<size_t>(2, (N / 3) + (RNG.nextU32() % 2u));
|
||||
size_t S2 = S1 + std::max<size_t>(2, ((N - S1) / 2));
|
||||
BasicBlock *SubDisp1BB =
|
||||
BasicBlock::Create(Ctx, "ig.loop.subdisp1", &F, SwitchDefaultBB);
|
||||
BasicBlock *SubDisp2BB =
|
||||
BasicBlock::Create(Ctx, "ig.loop.subdisp2", &F, SwitchDefaultBB);
|
||||
SwitchInst *SW1 =
|
||||
DB.CreateSwitch(CurState, SubDisp1BB, static_cast<unsigned>(S1));
|
||||
for (size_t i = 0; i < S1; ++i) {
|
||||
SW1->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
|
||||
ShuffledBBs[i]);
|
||||
}
|
||||
IRBuilder<> SB1(SubDisp1BB);
|
||||
SB1.SetCurrentDebugLocation(EntryLoc);
|
||||
SwitchInst *SW2 = SB1.CreateSwitch(CurState, SubDisp2BB,
|
||||
static_cast<unsigned>(S2 - S1));
|
||||
for (size_t i = S1; i < S2; ++i) {
|
||||
SW2->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
|
||||
ShuffledBBs[i]);
|
||||
}
|
||||
IRBuilder<> SB2(SubDisp2BB);
|
||||
SB2.SetCurrentDebugLocation(EntryLoc);
|
||||
SwitchInst *SW3 = SB2.CreateSwitch(CurState, SwitchDefaultBB,
|
||||
static_cast<unsigned>(N - S2));
|
||||
for (size_t i = S2; i < N; ++i) {
|
||||
SW3->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
|
||||
ShuffledBBs[i]);
|
||||
}
|
||||
} else {
|
||||
size_t SplitIdx = 1 + (RNG.nextU32() % static_cast<uint32_t>(N - 1));
|
||||
BasicBlock *SubDispBB =
|
||||
BasicBlock::Create(Ctx, "ig.loop.subdisp", &F, SwitchDefaultBB);
|
||||
SwitchInst *SW1 = DB.CreateSwitch(CurState, SubDispBB,
|
||||
static_cast<unsigned>(SplitIdx));
|
||||
for (size_t i = 0; i < SplitIdx; ++i) {
|
||||
SW1->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
|
||||
ShuffledBBs[i]);
|
||||
}
|
||||
IRBuilder<> SB(SubDispBB);
|
||||
SB.SetCurrentDebugLocation(EntryLoc);
|
||||
SwitchInst *SW2 = SB.CreateSwitch(CurState, SwitchDefaultBB,
|
||||
static_cast<unsigned>(N - SplitIdx));
|
||||
for (size_t i = SplitIdx; i < N; ++i) {
|
||||
SW2->addCase(ConstantInt::get(I32Ty, StateMap[ShuffledBBs[i]]),
|
||||
ShuffledBBs[i]);
|
||||
}
|
||||
}
|
||||
} else if (TopologyKind == 2) {
|
||||
SmallVector<std::pair<uint32_t, BasicBlock *>, 32> Sorted;
|
||||
Sorted.reserve(ShuffledBBs.size());
|
||||
for (BasicBlock *BB : ShuffledBBs)
|
||||
Sorted.emplace_back(StateMap[BB], BB);
|
||||
std::sort(Sorted.begin(), Sorted.end(),
|
||||
[](const auto &A, const auto &B) { return A.first < B.first; });
|
||||
|
||||
auto emitCmpTree = [&](auto &Self, BasicBlock *NodeBB, size_t Lo,
|
||||
size_t Hi) -> void {
|
||||
IRBuilder<> CB(NodeBB);
|
||||
CB.SetCurrentDebugLocation(EntryLoc);
|
||||
if (Hi - Lo == 1) {
|
||||
Value *Eq = CB.CreateICmpEQ(
|
||||
CurState, ConstantInt::get(I32Ty, Sorted[Lo].first), "ig.eq");
|
||||
CB.CreateCondBr(Eq, Sorted[Lo].second, SwitchDefaultBB);
|
||||
return;
|
||||
}
|
||||
size_t Mid =
|
||||
(Hi - Lo == 2)
|
||||
? (Lo + 1)
|
||||
: (Lo + 1 +
|
||||
static_cast<size_t>(RNG.nextU32() %
|
||||
static_cast<uint32_t>(Hi - Lo - 1)));
|
||||
uint32_t PivotState = Sorted[Mid].first;
|
||||
BasicBlock *LeftBB =
|
||||
BasicBlock::Create(Ctx, "ig.cmp.l", &F, SwitchDefaultBB);
|
||||
BasicBlock *RightBB =
|
||||
BasicBlock::Create(Ctx, "ig.cmp.r", &F, SwitchDefaultBB);
|
||||
Value *Ult = CB.CreateICmpULT(
|
||||
CurState, ConstantInt::get(I32Ty, PivotState), "ig.ult");
|
||||
CB.CreateCondBr(Ult, LeftBB, RightBB);
|
||||
Self(Self, LeftBB, Lo, Mid);
|
||||
Self(Self, RightBB, Mid, Hi);
|
||||
};
|
||||
emitCmpTree(emitCmpTree, LoopEntryBB, 0, Sorted.size());
|
||||
} else {
|
||||
SmallVector<std::pair<uint32_t, BasicBlock *>, 40> DispatchCases;
|
||||
DispatchCases.reserve(ShuffledBBs.size() + BogusCases.size() +
|
||||
(UnifiedRetBB ? 1 : 0));
|
||||
for (BasicBlock *Target : ShuffledBBs)
|
||||
DispatchCases.emplace_back(StateMap[Target], Target);
|
||||
for (const auto &BC : BogusCases)
|
||||
DispatchCases.push_back(BC);
|
||||
if (UnifiedRetBB)
|
||||
DispatchCases.emplace_back(ExitStateId, UnifiedRetBB);
|
||||
RNG.shuffle(DispatchCases);
|
||||
|
||||
SwitchInst *SW = DB.CreateSwitch(
|
||||
CurState, SwitchDefaultBB, static_cast<unsigned>(DispatchCases.size()));
|
||||
for (const auto &DC : DispatchCases) {
|
||||
SW->addCase(ConstantInt::get(I32Ty, DC.first), DC.second);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Rewrite non-exit terminators (and ReturnInst when unified return block is active)
|
||||
for (BasicBlock *BB : ShuffledBBs) {
|
||||
Instruction *Term = BB->getTerminator();
|
||||
if (isa<UnreachableInst>(Term))
|
||||
continue;
|
||||
if (auto *RI = dyn_cast<ReturnInst>(Term)) {
|
||||
if (!UnifiedRetBB)
|
||||
continue;
|
||||
DebugLoc Loc = RI->getDebugLoc() ? RI->getDebugLoc() : EntryLoc;
|
||||
IRBuilder<> RB(BB);
|
||||
RB.SetCurrentDebugLocation(Loc);
|
||||
if (RetSlot && RI->getReturnValue()) {
|
||||
StoreInst *RSt = RB.CreateStore(RI->getReturnValue(), RetSlot, false);
|
||||
RSt->setAlignment(RetAlign);
|
||||
}
|
||||
RI->eraseFromParent();
|
||||
StoreInst *SSt = RB.CreateStore(
|
||||
ConstantInt::get(I32Ty, encodeState(ExitStateId, Cipher)),
|
||||
StateSlot, true);
|
||||
SSt->setAlignment(Align(4));
|
||||
RB.CreateBr(LoopEndBB);
|
||||
continue;
|
||||
}
|
||||
|
||||
DebugLoc Loc = Term->getDebugLoc() ? Term->getDebugLoc() : EntryLoc;
|
||||
|
||||
if (auto *Br = dyn_cast<BranchInst>(Term)) {
|
||||
IRBuilder<> TB(BB);
|
||||
TB.SetCurrentDebugLocation(Loc);
|
||||
if (Br->isUnconditional()) {
|
||||
BasicBlock *Succ = Br->getSuccessor(0);
|
||||
uint32_t NextEnc = encodeState(StateMap[Succ], Cipher);
|
||||
Term->eraseFromParent();
|
||||
StoreInst *St =
|
||||
TB.CreateStore(ConstantInt::get(I32Ty, NextEnc), StateSlot, true);
|
||||
St->setAlignment(Align(4));
|
||||
TB.CreateBr(LoopEndBB);
|
||||
} else {
|
||||
Value *Cond = Br->getCondition();
|
||||
BasicBlock *TrueBB = Br->getSuccessor(0);
|
||||
BasicBlock *FalseBB = Br->getSuccessor(1);
|
||||
uint32_t TrueEnc = encodeState(StateMap[TrueBB], Cipher);
|
||||
uint32_t FalseEnc = encodeState(StateMap[FalseBB], Cipher);
|
||||
Term->eraseFromParent();
|
||||
Value *Sel = TB.CreateSelect(Cond, ConstantInt::get(I32Ty, TrueEnc),
|
||||
ConstantInt::get(I32Ty, FalseEnc),
|
||||
"ig.next");
|
||||
StoreInst *St = TB.CreateStore(Sel, StateSlot, true);
|
||||
St->setAlignment(Align(4));
|
||||
TB.CreateBr(LoopEndBB);
|
||||
}
|
||||
} else if (auto *SW = dyn_cast<SwitchInst>(Term)) {
|
||||
auto makeEdgeBlock = [&](BasicBlock *Dest) -> BasicBlock * {
|
||||
BasicBlock *EdgeBB =
|
||||
BasicBlock::Create(Ctx, "ig.sw.edge", &F, SwitchDefaultBB);
|
||||
IRBuilder<> EB(EdgeBB);
|
||||
EB.SetCurrentDebugLocation(Loc);
|
||||
uint32_t NextEnc = encodeState(StateMap[Dest], Cipher);
|
||||
StoreInst *St =
|
||||
EB.CreateStore(ConstantInt::get(I32Ty, NextEnc), StateSlot, true);
|
||||
St->setAlignment(Align(4));
|
||||
EB.CreateBr(LoopEndBB);
|
||||
return EdgeBB;
|
||||
};
|
||||
BasicBlock *OrigDef = SW->getDefaultDest();
|
||||
SW->setDefaultDest(makeEdgeBlock(OrigDef));
|
||||
for (unsigned idx = 1, e = SW->getNumSuccessors(); idx < e; ++idx) {
|
||||
SW->setSuccessor(idx, makeEdgeBlock(SW->getSuccessor(idx)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (verifyFunction(F, &errs())) {
|
||||
report_fatal_error(Twine("[IGFlattening] IR verification failed on ") +
|
||||
F.getName());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runControlFlowFlattening(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isFlatteningEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
|
||||
SmallVector<Function *, 16> Targets;
|
||||
for (Function &F : M) {
|
||||
if (F.isDeclaration())
|
||||
continue;
|
||||
if (Policy.shouldFlattenFunction(F))
|
||||
Targets.push_back(&F);
|
||||
}
|
||||
|
||||
bool Changed = false;
|
||||
for (Function *F : Targets) {
|
||||
FlattenedFunctionDetail Detail;
|
||||
std::string SkipReason;
|
||||
if (flattenSingleFunction(*F, Policy, Detail, SkipReason)) {
|
||||
Audit.FunctionsFlattened.push_back(F->getName().str());
|
||||
Audit.FunctionsFlattenedDetails.push_back(std::move(Detail));
|
||||
Changed = true;
|
||||
} else {
|
||||
Audit.FunctionsSkipped.push_back({F->getName().str(), SkipReason});
|
||||
}
|
||||
}
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,232 @@
|
||||
#include "IGPassUtils.h"
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/SetVector.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/IR/Attributes.h"
|
||||
#include "llvm/IR/DebugInfo.h"
|
||||
#include "llvm/IR/Dominators.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/IntrinsicInst.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Verifier.h"
|
||||
#include "llvm/Support/ErrorHandling.h"
|
||||
#include "llvm/Transforms/Utils/CodeExtractor.h"
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
bool isSwiftABIHazardValue(const Value *V) {
|
||||
if (!V)
|
||||
return false;
|
||||
if (V->getType()->isTokenTy() || V->getType()->isLabelTy() ||
|
||||
V->getType()->isMetadataTy()) {
|
||||
return true;
|
||||
}
|
||||
if (const auto *AI = dyn_cast<AllocaInst>(V)) {
|
||||
if (AI->isSwiftError())
|
||||
return true;
|
||||
}
|
||||
if (const auto *Arg = dyn_cast<Argument>(V)) {
|
||||
if (Arg->hasAttribute(Attribute::SwiftError) ||
|
||||
Arg->hasAttribute(Attribute::SwiftAsync) ||
|
||||
Arg->hasAttribute(Attribute::SwiftSelf)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isBlockEligibleForOutline(BasicBlock &BB, const Function &F,
|
||||
unsigned MinInsts) {
|
||||
if (&BB == &F.getEntryBlock() || BB.isEHPad() || BB.hasAddressTaken() ||
|
||||
pred_empty(&BB)) {
|
||||
return false;
|
||||
}
|
||||
if (isa<PHINode>(BB.front()))
|
||||
return false;
|
||||
if (!isa<BranchInst>(BB.getTerminator()))
|
||||
return false;
|
||||
|
||||
unsigned WorkInsts = 0;
|
||||
for (const Instruction &I : BB) {
|
||||
if (isa<DbgInfoIntrinsic>(I))
|
||||
continue;
|
||||
if (isa<AllocaInst>(I) || isa<InvokeInst>(I) || isa<CallBrInst>(I) ||
|
||||
isa<LandingPadInst>(I) || isa<CatchSwitchInst>(I) ||
|
||||
isa<CatchReturnInst>(I) || isa<CleanupReturnInst>(I) ||
|
||||
isa<IndirectBrInst>(I) || isa<VAArgInst>(I) || I.isAtomic()) {
|
||||
return false;
|
||||
}
|
||||
if (I.getType()->isTokenTy())
|
||||
return false;
|
||||
for (const Use &U : I.operands()) {
|
||||
if (isa<BlockAddress>(U.get()))
|
||||
return false;
|
||||
if (isa<BasicBlock>(U.get()))
|
||||
continue;
|
||||
if (isSwiftABIHazardValue(U.get()))
|
||||
return false;
|
||||
}
|
||||
if (const auto *CB = dyn_cast<CallBase>(&I)) {
|
||||
if (CB->isInlineAsm() || CB->isMustTailCall() ||
|
||||
CB->getCallingConv() == CallingConv::SwiftTail) {
|
||||
return false;
|
||||
}
|
||||
for (unsigned i = 0, e = CB->arg_size(); i != e; ++i) {
|
||||
if (CB->paramHasAttr(i, Attribute::SwiftError) ||
|
||||
CB->paramHasAttr(i, Attribute::SwiftAsync) ||
|
||||
CB->paramHasAttr(i, Attribute::SwiftSelf) ||
|
||||
CB->paramHasAttr(i, Attribute::InAlloca) ||
|
||||
CB->paramHasAttr(i, Attribute::Preallocated) ||
|
||||
CB->paramHasAttr(i, Attribute::ImmArg)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (const Function *Callee = CB->getCalledFunction()) {
|
||||
StringRef CName = Callee->getName();
|
||||
if (CName.starts_with("llvm.coro.") ||
|
||||
CName.starts_with("llvm.objc.clang.arc.use") ||
|
||||
CName.starts_with("llvm.va_")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isa<DbgInfoIntrinsic>(I) && !I.isTerminator())
|
||||
++WorkInsts;
|
||||
}
|
||||
return WorkInsts >= MinInsts;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runFunctionOutline(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isFunctionOutlineEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
if (!isMachOAArch64NonArm64e(M))
|
||||
return false;
|
||||
|
||||
const unsigned MaxPerFn = Policy.functionOutlineMaxPerFn();
|
||||
const unsigned MinInsts = Policy.functionOutlineMinInsts();
|
||||
if (MaxPerFn == 0)
|
||||
return false;
|
||||
|
||||
SmallVector<Function *, 32> OrigFuncs;
|
||||
for (Function &F : M)
|
||||
OrigFuncs.push_back(&F);
|
||||
|
||||
std::string Tag = computeShortModuleTag(Policy.seed(), M.getModuleIdentifier(),
|
||||
Policy.sourcePath());
|
||||
unsigned GlobalOutlineIdx = 0;
|
||||
bool Changed = false;
|
||||
|
||||
for (Function *F : OrigFuncs) {
|
||||
if (!F || !Policy.shouldOutlineFunction(*F))
|
||||
continue;
|
||||
if (!isFunctionSafeForTransform(*F, Policy,
|
||||
&Policy.functionOutlineExemptFunctions())) {
|
||||
continue;
|
||||
}
|
||||
if (F->isVarArg() || F->hasPersonalityFn() || F->size() < 2)
|
||||
continue;
|
||||
|
||||
SmallVector<BasicBlock *, 16> OrigBlocks;
|
||||
for (BasicBlock &BB : *F)
|
||||
OrigBlocks.push_back(&BB);
|
||||
|
||||
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
|
||||
(F->getName() + "|outline").str());
|
||||
RNG.shuffle(OrigBlocks);
|
||||
|
||||
unsigned FnOutlined = 0;
|
||||
for (BasicBlock *BB : OrigBlocks) {
|
||||
if (FnOutlined >= MaxPerFn)
|
||||
break;
|
||||
if (!BB || BB->getParent() != F)
|
||||
continue;
|
||||
if (!isBlockEligibleForOutline(*BB, *F, MinInsts))
|
||||
continue;
|
||||
|
||||
DominatorTree DT(*F);
|
||||
CodeExtractorAnalysisCache CEAC(*F);
|
||||
SmallVector<BasicBlock *, 1> Region{BB};
|
||||
CodeExtractor CE(Region, &DT, /*AggregateArgs=*/false);
|
||||
if (!CE.isEligible())
|
||||
continue;
|
||||
|
||||
SetVector<Value *> Inputs, Outputs, Allocas;
|
||||
CE.findInputsOutputs(Inputs, Outputs, Allocas);
|
||||
if (Inputs.size() > 5 || Outputs.size() > 2)
|
||||
continue;
|
||||
|
||||
bool Hazard = false;
|
||||
for (const Value *V : Inputs) {
|
||||
if (isSwiftABIHazardValue(V)) {
|
||||
Hazard = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!Hazard) {
|
||||
for (const Value *V : Outputs) {
|
||||
if (isSwiftABIHazardValue(V)) {
|
||||
Hazard = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Hazard)
|
||||
continue;
|
||||
|
||||
Function *OutF = CE.extractCodeRegion(CEAC);
|
||||
if (!OutF)
|
||||
continue;
|
||||
|
||||
OutF->setName("ig_sub_" + Tag + "_" + Twine(GlobalOutlineIdx++));
|
||||
OutF->setLinkage(GlobalValue::InternalLinkage);
|
||||
OutF->setVisibility(GlobalValue::DefaultVisibility);
|
||||
OutF->addFnAttr(Attribute::NoInline);
|
||||
OutF->removeFnAttr(Attribute::AlwaysInline);
|
||||
OutF->removeFnAttr(Attribute::InlineHint);
|
||||
|
||||
llvm::stripDebugInfo(*OutF);
|
||||
for (BasicBlock &OBB : *OutF) {
|
||||
for (Instruction &OI : make_early_inc_range(OBB)) {
|
||||
if (isa<DbgInfoIntrinsic>(OI))
|
||||
OI.eraseFromParent();
|
||||
}
|
||||
}
|
||||
|
||||
if (F->getSubprogram()) {
|
||||
for (BasicBlock &FBB : *F) {
|
||||
for (Instruction &FI : FBB) {
|
||||
if (!FI.getDebugLoc())
|
||||
FI.setDebugLoc(resolveInstDebugLoc(&FI, *F));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (verifyFunction(*OutF, &errs())) {
|
||||
report_fatal_error(Twine("[IGFunctionOutline] IR verification failed on ") +
|
||||
OutF->getName());
|
||||
}
|
||||
if (verifyFunction(*F, &errs())) {
|
||||
report_fatal_error(Twine("[IGFunctionOutline] IR verification failed on ") +
|
||||
F->getName());
|
||||
}
|
||||
|
||||
++FnOutlined;
|
||||
++Audit.FunctionsOutlinedCount;
|
||||
Changed = true;
|
||||
}
|
||||
|
||||
if (FnOutlined > 0)
|
||||
Audit.OutlinedFunctions.push_back(F->getName().str());
|
||||
}
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,274 @@
|
||||
#include "IGPassUtils.h"
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/DenseMap.h"
|
||||
#include "llvm/ADT/SmallPtrSet.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/IR/Constants.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/GlobalVariable.h"
|
||||
#include "llvm/IR/IRBuilder.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/Intrinsics.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Verifier.h"
|
||||
#include "llvm/Support/Alignment.h"
|
||||
#include "llvm/Support/ErrorHandling.h"
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
bool isFunctionCFGSafeForIBR(Function &F) {
|
||||
if (F.size() < 3)
|
||||
return false;
|
||||
for (BasicBlock &BB : F) {
|
||||
if (BB.isEHPad())
|
||||
return false;
|
||||
Instruction *Term = BB.getTerminator();
|
||||
if (!Term || isa<InvokeInst>(Term) || isa<ResumeInst>(Term) ||
|
||||
isa<CatchSwitchInst>(Term) || isa<CatchReturnInst>(Term) ||
|
||||
isa<CleanupReturnInst>(Term) || isa<IndirectBrInst>(Term) ||
|
||||
isa<CallBrInst>(Term)) {
|
||||
return false;
|
||||
}
|
||||
for (Instruction &I : BB) {
|
||||
if (I.getType()->isTokenTy())
|
||||
return false;
|
||||
if (auto *CI = dyn_cast<CallInst>(&I)) {
|
||||
if (CI->isMustTailCall())
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool obfuscateSingleFunctionIBR(Function &F, const IGPolicyConfig &Policy,
|
||||
StringRef Tag, unsigned FnIndex,
|
||||
unsigned &OutRewritten) {
|
||||
if (!isFunctionCFGSafeForIBR(F))
|
||||
return false;
|
||||
|
||||
SmallVector<BranchInst *, 24> Branches;
|
||||
SmallVector<BasicBlock *, 24> Targets;
|
||||
SmallPtrSet<BasicBlock *, 24> SeenTargets;
|
||||
|
||||
BasicBlock *EntryBB = &F.getEntryBlock();
|
||||
SmallPtrSet<BasicBlock *, 32> Reachable;
|
||||
SmallVector<BasicBlock *, 32> Worklist;
|
||||
Reachable.insert(EntryBB);
|
||||
Worklist.push_back(EntryBB);
|
||||
while (!Worklist.empty()) {
|
||||
BasicBlock *Cur = Worklist.pop_back_val();
|
||||
Instruction *Term = Cur->getTerminator();
|
||||
if (!Term)
|
||||
continue;
|
||||
if (auto *CBr = dyn_cast<BranchInst>(Term); CBr && CBr->isConditional()) {
|
||||
if (auto *CondCI = dyn_cast<ConstantInt>(CBr->getCondition())) {
|
||||
BasicBlock *LiveSucc =
|
||||
CondCI->isZero() ? CBr->getSuccessor(1) : CBr->getSuccessor(0);
|
||||
if (Reachable.insert(LiveSucc).second)
|
||||
Worklist.push_back(LiveSucc);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
for (unsigned i = 0, e = Term->getNumSuccessors(); i < e; ++i) {
|
||||
BasicBlock *Succ = Term->getSuccessor(i);
|
||||
if (Reachable.insert(Succ).second)
|
||||
Worklist.push_back(Succ);
|
||||
}
|
||||
}
|
||||
|
||||
bool NeedDecoy = false;
|
||||
for (BasicBlock &BB : F) {
|
||||
if (!Reachable.contains(&BB))
|
||||
continue;
|
||||
auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
|
||||
if (!Br)
|
||||
continue;
|
||||
if (Br->isUnconditional()) {
|
||||
BasicBlock *Dest = Br->getSuccessor(0);
|
||||
if (Dest == EntryBB)
|
||||
continue;
|
||||
NeedDecoy = true;
|
||||
Branches.push_back(Br);
|
||||
if (SeenTargets.insert(Dest).second)
|
||||
Targets.push_back(Dest);
|
||||
} else {
|
||||
if (isa<ConstantInt>(Br->getCondition()))
|
||||
continue;
|
||||
BasicBlock *T = Br->getSuccessor(0);
|
||||
BasicBlock *FBB = Br->getSuccessor(1);
|
||||
if (T == EntryBB || FBB == EntryBB)
|
||||
continue;
|
||||
if (T == FBB && !T->phis().empty())
|
||||
continue;
|
||||
if (T == FBB)
|
||||
NeedDecoy = true;
|
||||
Branches.push_back(Br);
|
||||
if (SeenTargets.insert(T).second)
|
||||
Targets.push_back(T);
|
||||
if (SeenTargets.insert(FBB).second)
|
||||
Targets.push_back(FBB);
|
||||
}
|
||||
}
|
||||
|
||||
if (Branches.empty() || (Targets.size() + (NeedDecoy ? 1 : 0)) < 2)
|
||||
return false;
|
||||
|
||||
if (F.hasPrivateLinkage())
|
||||
F.setLinkage(GlobalValue::InternalLinkage);
|
||||
|
||||
LLVMContext &Ctx = F.getContext();
|
||||
Module &M = *F.getParent();
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
PointerType *PtrTy = PointerType::getUnqual(Ctx);
|
||||
|
||||
// Only emit ig.ibr.decoy when at least one unconditional/degenerate indirectbr
|
||||
// lists it; otherwise UnreachableBlockElim deletes it and leaves a dangling blockaddress.
|
||||
BasicBlock *DecoyBB = nullptr;
|
||||
if (NeedDecoy) {
|
||||
DecoyBB = BasicBlock::Create(Ctx, "ig.ibr.decoy", &F);
|
||||
IRBuilder<> DB(DecoyBB);
|
||||
DB.SetCurrentDebugLocation(resolveInstDebugLoc(nullptr, F));
|
||||
Function *TrapFn = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::trap);
|
||||
DB.CreateCall(TrapFn);
|
||||
DB.CreateUnreachable();
|
||||
Targets.push_back(DecoyBB);
|
||||
}
|
||||
|
||||
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
|
||||
(F.getName() + "|ibr").str());
|
||||
|
||||
DenseMap<BasicBlock *, unsigned> SlotMap;
|
||||
for (unsigned Idx = 0; Idx < Targets.size(); ++Idx)
|
||||
SlotMap[Targets[Idx]] = Idx;
|
||||
RNG.shuffle(Targets);
|
||||
|
||||
SmallVector<Constant *, 24> DeltaEntries;
|
||||
SmallVector<Constant *, 24> IndexEntries(Targets.size());
|
||||
DeltaEntries.reserve(Targets.size());
|
||||
uint64_t IndexKey = RNG.nextNonZeroU64();
|
||||
Constant *FnInt = ConstantExpr::getPtrToInt(&F, I64Ty);
|
||||
for (unsigned Idx = 0; Idx < Targets.size(); ++Idx) {
|
||||
BasicBlock *BB = Targets[Idx];
|
||||
Constant *BBAddrInt = ConstantExpr::getPtrToInt(BlockAddress::get(&F, BB), I64Ty);
|
||||
// Keep the encoded indices out of the Mach-O symbol-difference relocations.
|
||||
DeltaEntries.push_back(ConstantExpr::getSub(BBAddrInt, FnInt));
|
||||
IndexEntries[SlotMap.lookup(BB)] = ConstantInt::get(I64Ty, Idx ^ IndexKey);
|
||||
}
|
||||
|
||||
ArrayType *TableTy = ArrayType::get(I64Ty, Targets.size());
|
||||
std::string Suffix = Tag.str() + "_" + std::to_string(FnIndex);
|
||||
auto *DeltaGV = new GlobalVariable(
|
||||
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
|
||||
ConstantArray::get(TableTy, DeltaEntries), "__ig_ibt1_" + Suffix);
|
||||
DeltaGV->setAlignment(Align(8));
|
||||
DeltaGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
|
||||
|
||||
auto *IndexGV = new GlobalVariable(
|
||||
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
|
||||
ConstantArray::get(TableTy, IndexEntries), "__ig_ibt2_" + Suffix);
|
||||
IndexGV->setAlignment(Align(8));
|
||||
IndexGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
|
||||
|
||||
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
|
||||
auto ResolveTarget = [&](IRBuilder<> &B, Value *Slot) {
|
||||
Value *IndexPtr = B.CreateInBoundsGEP(TableTy, IndexGV, {Zero64, Slot});
|
||||
Value *EncodedIndex =
|
||||
B.CreateAlignedLoad(I64Ty, IndexPtr, Align(8), /*isVolatile=*/true);
|
||||
Value *Index = B.CreateXor(EncodedIndex, ConstantInt::get(I64Ty, IndexKey));
|
||||
Value *DeltaPtr = B.CreateInBoundsGEP(TableTy, DeltaGV, {Zero64, Index});
|
||||
Value *Delta =
|
||||
B.CreateAlignedLoad(I64Ty, DeltaPtr, Align(8), /*isVolatile=*/true);
|
||||
Value *Addr = B.CreateAdd(B.CreatePtrToInt(&F, I64Ty), Delta);
|
||||
return B.CreateIntToPtr(Addr, PtrTy);
|
||||
};
|
||||
unsigned RewrittenHere = 0;
|
||||
|
||||
for (BranchInst *Br : Branches) {
|
||||
BasicBlock *ParentBB = Br->getParent();
|
||||
DebugLoc Loc = resolveInstDebugLoc(Br, F);
|
||||
IRBuilder<> B(Br);
|
||||
B.SetCurrentDebugLocation(Loc);
|
||||
|
||||
if (Br->isUnconditional() || Br->getSuccessor(0) == Br->getSuccessor(1)) {
|
||||
BasicBlock *Dest = Br->getSuccessor(0);
|
||||
Value *DstPtr = ResolveTarget(B, ConstantInt::get(I64Ty, SlotMap.lookup(Dest)));
|
||||
|
||||
Br->eraseFromParent();
|
||||
IRBuilder<> EndB(ParentBB);
|
||||
EndB.SetCurrentDebugLocation(Loc);
|
||||
IndirectBrInst *IBr = EndB.CreateIndirectBr(DstPtr, 2);
|
||||
IBr->addDestination(Dest);
|
||||
IBr->addDestination(DecoyBB);
|
||||
++RewrittenHere;
|
||||
} else {
|
||||
BasicBlock *TrueBB = Br->getSuccessor(0);
|
||||
BasicBlock *FalseBB = Br->getSuccessor(1);
|
||||
Value *Cond = Br->getCondition();
|
||||
Value *IdxVal = B.CreateSelect(
|
||||
Cond, ConstantInt::get(I64Ty, SlotMap.lookup(TrueBB)),
|
||||
ConstantInt::get(I64Ty, SlotMap.lookup(FalseBB)), "ig.ibr.idx");
|
||||
Value *DstPtr = ResolveTarget(B, IdxVal);
|
||||
|
||||
Br->eraseFromParent();
|
||||
IRBuilder<> EndB(ParentBB);
|
||||
EndB.SetCurrentDebugLocation(Loc);
|
||||
IndirectBrInst *IBr = EndB.CreateIndirectBr(DstPtr, 2);
|
||||
IBr->addDestination(TrueBB);
|
||||
IBr->addDestination(FalseBB);
|
||||
++RewrittenHere;
|
||||
}
|
||||
}
|
||||
|
||||
if (verifyFunction(F, &errs())) {
|
||||
report_fatal_error(Twine("[IGIndirectBranch] IR verification failed on ") +
|
||||
F.getName());
|
||||
}
|
||||
OutRewritten += RewrittenHere;
|
||||
return RewrittenHere > 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runIndirectBranchObfuscation(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isIndirectBranchEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
if (!isMachOAArch64NonArm64e(M))
|
||||
return false;
|
||||
|
||||
SmallVector<Function *, 16> Targets;
|
||||
for (Function &F : M) {
|
||||
if (!Policy.shouldIndirectBranchInFunction(F))
|
||||
continue;
|
||||
if (!isFunctionSafeForTransform(F, Policy,
|
||||
&Policy.indirectBranchExemptFunctions())) {
|
||||
continue;
|
||||
}
|
||||
Targets.push_back(&F);
|
||||
}
|
||||
|
||||
if (Targets.empty())
|
||||
return false;
|
||||
|
||||
std::string Tag = computeShortModuleTag(Policy.seed(), M.getModuleIdentifier(),
|
||||
Policy.sourcePath());
|
||||
bool Changed = false;
|
||||
unsigned FnIndex = 0;
|
||||
|
||||
for (Function *F : Targets) {
|
||||
unsigned Rewritten = 0;
|
||||
if (obfuscateSingleFunctionIBR(*F, Policy, Tag, FnIndex++, Rewritten)) {
|
||||
Audit.IndirectBranchesCount += Rewritten;
|
||||
Audit.IndirectBranchesFunctions.push_back(F->getName().str());
|
||||
Changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,471 @@
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/DenseMap.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/ADT/StringExtras.h"
|
||||
#include "llvm/ADT/StringMap.h"
|
||||
#include "llvm/ADT/StringRef.h"
|
||||
#include "llvm/IR/CallingConv.h"
|
||||
#include "llvm/IR/Constants.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/GlobalValue.h"
|
||||
#include "llvm/IR/GlobalVariable.h"
|
||||
#include "llvm/IR/IRBuilder.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/Support/Alignment.h"
|
||||
#include "llvm/Support/SHA256.h"
|
||||
#include "llvm/TargetParser/Triple.h"
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
StringRef stripObjCMarkerRef(StringRef Name) {
|
||||
if (!Name.empty() && Name.front() == '\x01')
|
||||
return Name.drop_front(1);
|
||||
return Name;
|
||||
}
|
||||
|
||||
bool isValidSwiftIdentChars(StringRef S) {
|
||||
if (S.empty())
|
||||
return false;
|
||||
for (char C : S) {
|
||||
unsigned char UC = static_cast<unsigned char>(C);
|
||||
if (!isAlnum(UC) && C != '_')
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isBuiltinSwiftModuleName(StringRef ModName) {
|
||||
return ModName == "So" || ModName == "SC" || ModName == "s" ||
|
||||
ModName == "Swift" || ModName == "Foundation" ||
|
||||
ModName == "UIKit" || ModName == "SwiftUI" ||
|
||||
ModName == "Combine" || ModName == "Dispatch" ||
|
||||
ModName == "ObjectiveC" || ModName == "CoreFoundation" ||
|
||||
ModName == "CoreGraphics" || ModName == "CryptoKit" ||
|
||||
ModName == "StoreKit" || ModName == "Security" ||
|
||||
ModName == "WebKit" || ModName == "Darwin";
|
||||
}
|
||||
|
||||
// Parse `<Len><ModChars>` starting at `S[Start]` if valid.
|
||||
// Sets `AfterIdx` to index immediately following `<ModChars>`.
|
||||
StringRef parseLengthPrefixedSwiftIdent(StringRef S, size_t Start,
|
||||
size_t &AfterIdx) {
|
||||
if (Start >= S.size() || !isDigit(static_cast<unsigned char>(S[Start])) ||
|
||||
S[Start] == '0') {
|
||||
return StringRef();
|
||||
}
|
||||
size_t Pos = Start;
|
||||
uint64_t Len = 0;
|
||||
while (Pos < S.size() && isDigit(static_cast<unsigned char>(S[Pos]))) {
|
||||
Len = Len * 10 + static_cast<uint64_t>(S[Pos] - '0');
|
||||
if (Len > 128)
|
||||
return StringRef();
|
||||
++Pos;
|
||||
}
|
||||
if (Len == 0 || Pos + Len > S.size())
|
||||
return StringRef();
|
||||
StringRef Ident = S.substr(Pos, static_cast<size_t>(Len));
|
||||
if (!isValidSwiftIdentChars(Ident) || isBuiltinSwiftModuleName(Ident))
|
||||
return StringRef();
|
||||
AfterIdx = Pos + static_cast<size_t>(Len);
|
||||
return S.substr(Start, AfterIdx - Start);
|
||||
}
|
||||
|
||||
std::string detectSwiftModuleToken(const Module &M) {
|
||||
StringMap<unsigned> Counts;
|
||||
auto InspectFn = [&](const Function &F, unsigned BaseWeight) {
|
||||
StringRef Clean = stripObjCMarkerRef(F.getName());
|
||||
if (!Clean.starts_with("$s"))
|
||||
return;
|
||||
|
||||
size_t AfterIdx = 0;
|
||||
StringRef DirectTok = parseLengthPrefixedSwiftIdent(Clean, 2, AfterIdx);
|
||||
if (!DirectTok.empty()) {
|
||||
Counts[DirectTok] += BaseWeight * 2;
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback for pure extension files (e.g. `$sSo6UIViewC17AppModE...`).
|
||||
for (size_t i = 3; i + 2 < Clean.size(); ++i) {
|
||||
if (isDigit(static_cast<unsigned char>(Clean[i - 1])) ||
|
||||
!isDigit(static_cast<unsigned char>(Clean[i])) || Clean[i] == '0') {
|
||||
continue;
|
||||
}
|
||||
size_t ExtAfter = 0;
|
||||
StringRef ExtTok = parseLengthPrefixedSwiftIdent(Clean, i, ExtAfter);
|
||||
if (!ExtTok.empty() && ExtAfter < Clean.size() && Clean[ExtAfter] == 'E') {
|
||||
Counts[ExtTok] += BaseWeight;
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (const Function &F : M) {
|
||||
if (!F.isDeclaration() && !F.hasLocalLinkage() &&
|
||||
!F.hasAvailableExternallyLinkage() && !F.isWeakForLinker()) {
|
||||
InspectFn(F, 2);
|
||||
} else if (F.isDeclaration() && F.hasHiddenVisibility() &&
|
||||
!F.isWeakForLinker() && !F.hasExternalWeakLinkage()) {
|
||||
InspectFn(F, 1);
|
||||
}
|
||||
}
|
||||
|
||||
std::string Best;
|
||||
unsigned BestScore = 0;
|
||||
for (const auto &KV : Counts) {
|
||||
StringRef Key = KV.getKey();
|
||||
unsigned Score = KV.getValue();
|
||||
if (Score > BestScore || (Score == BestScore && Key < Best)) {
|
||||
Best = Key.str();
|
||||
BestScore = Score;
|
||||
}
|
||||
}
|
||||
return Best;
|
||||
}
|
||||
|
||||
bool hasSwiftMetadataOrWitnessSuffix(StringRef CleanName) {
|
||||
static constexpr StringRef Suffixes[] = {
|
||||
"CMa", "VMa", "OMa", "CMn", "VMn", "OMn", "CN", "VN", "ON", "Wl",
|
||||
"WL", "Tm", "Mr", "Mi", "Ma", "Mc", "Wp", "WG", "WI", "Wr",
|
||||
"Ws", "WT", "WOh", "WOy", "WOe", "WOc", "WOb", "WOd", "WOi", "wCP",
|
||||
"wxx", "wcp", "wca", "wtk", "wta", "wet", "wst", "wug", "wup", "wui",
|
||||
"TQ0_", "TY0_",
|
||||
};
|
||||
for (StringRef Suf : Suffixes) {
|
||||
if (CleanName.ends_with(Suf) ||
|
||||
CleanName.ends_with((Suf + "_").str())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isPlumbingOrRuntimeSymbol(StringRef RawName, StringRef CleanName,
|
||||
const IGPolicyConfig &Policy) {
|
||||
if (RawName.empty() || RawName.starts_with("\x01L") ||
|
||||
RawName.starts_with("\x01l")) {
|
||||
return true;
|
||||
}
|
||||
static constexpr StringRef BuiltinSkipPrefixes[] = {
|
||||
"llvm.", "__ig_", "ig_defender_", "ig_call_",
|
||||
"ig_poison_", "ig_sys_", "ig_a", "ig_archive_",
|
||||
"_IG_dispatch_", "IG_dispatch_", "objc_", "_objc_",
|
||||
"swift_", "_swift_", "__swift_", "___",
|
||||
"__stack_chk", "__clang_", "__cxa_", "__gxx_",
|
||||
"_Unwind_",
|
||||
};
|
||||
for (StringRef P : BuiltinSkipPrefixes) {
|
||||
if (CleanName.starts_with(P))
|
||||
return true;
|
||||
}
|
||||
for (const std::string &P : Policy.exemptFunctionPrefixes()) {
|
||||
if (!P.empty() && CleanName.starts_with(P))
|
||||
return true;
|
||||
}
|
||||
if (CleanName.contains(".resume.") || CleanName.contains(".coro"))
|
||||
return true;
|
||||
if (CleanName.starts_with("$s") && hasSwiftMetadataOrWitnessSuffix(CleanName))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isSameModuleSwiftDeclaration(StringRef CleanName,
|
||||
StringRef SwiftModToken) {
|
||||
if (SwiftModToken.empty() || !CleanName.starts_with("$s"))
|
||||
return false;
|
||||
if (CleanName.drop_front(2).starts_with(SwiftModToken))
|
||||
return true;
|
||||
|
||||
StringRef Base = CleanName;
|
||||
size_t TgPos = Base.find("Tg");
|
||||
if (TgPos != StringRef::npos)
|
||||
Base = Base.substr(0, TgPos);
|
||||
size_t TfPos = Base.find("Tf");
|
||||
if (TfPos != StringRef::npos)
|
||||
Base = Base.substr(0, TfPos);
|
||||
|
||||
size_t SearchFrom = 3;
|
||||
while (SearchFrom < Base.size()) {
|
||||
size_t Pos = Base.find(SwiftModToken, SearchFrom);
|
||||
if (Pos == StringRef::npos)
|
||||
break;
|
||||
size_t EndPos = Pos + SwiftModToken.size();
|
||||
if (Pos >= 3 && !isDigit(static_cast<unsigned char>(Base[Pos - 1])) &&
|
||||
EndPos < Base.size() && Base[EndPos] == 'E') {
|
||||
return true;
|
||||
}
|
||||
SearchFrom = Pos + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isSameImageSafeCallee(const Function &Callee, StringRef SwiftModToken,
|
||||
const IGPolicyConfig &Policy) {
|
||||
if (Callee.isIntrinsic() || Callee.isPresplitCoroutine())
|
||||
return false;
|
||||
if (Callee.getCallingConv() == CallingConv::SwiftTail)
|
||||
return false;
|
||||
if (Callee.hasAvailableExternallyLinkage() ||
|
||||
Callee.hasExternalWeakLinkage() || Callee.hasDLLImportStorageClass()) {
|
||||
return false;
|
||||
}
|
||||
for (const Argument &Arg : Callee.args()) {
|
||||
if (Arg.hasAttribute(Attribute::SwiftAsync) ||
|
||||
Arg.hasAttribute(Attribute::InAlloca) ||
|
||||
Arg.hasAttribute(Attribute::Preallocated)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
StringRef RawName = Callee.getName();
|
||||
StringRef CleanName = stripObjCMarkerRef(RawName);
|
||||
if (isPlumbingOrRuntimeSymbol(RawName, CleanName, Policy))
|
||||
return false;
|
||||
|
||||
if (!Callee.isDeclaration()) {
|
||||
if (GlobalValue::isInterposableLinkage(Callee.getLinkage()))
|
||||
return false;
|
||||
if (Callee.isWeakForLinker()) {
|
||||
return (Callee.hasLinkOnceODRLinkage() || Callee.hasWeakODRLinkage()) &&
|
||||
Callee.hasHiddenVisibility();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Callee.isWeakForLinker())
|
||||
return false;
|
||||
|
||||
if (isSameModuleSwiftDeclaration(CleanName, SwiftModToken))
|
||||
return true;
|
||||
|
||||
for (const std::string &Prefix : Policy.indirectCallSameImagePrefixes()) {
|
||||
if (!Prefix.empty() && CleanName.starts_with(Prefix))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isCallerEligible(const Function &Caller, const IGPolicyConfig &Policy) {
|
||||
if (!Policy.shouldIndirectCallInFunction(Caller))
|
||||
return false;
|
||||
if (Caller.isPresplitCoroutine() ||
|
||||
Caller.hasFnAttribute(Attribute::Naked) ||
|
||||
Caller.getCallingConv() == CallingConv::SwiftTail) {
|
||||
return false;
|
||||
}
|
||||
if (Caller.hasSection()) {
|
||||
StringRef Sec = Caller.getSection();
|
||||
if (Sec.contains("__mod_init_func") || Sec.contains("__objc_init_func") ||
|
||||
Sec.contains("__mod_term_func")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isCallSiteEligible(CallInst *CI, Function *&OutCallee) {
|
||||
OutCallee = nullptr;
|
||||
if (!CI || CI->isInlineAsm() || CI->isMustTailCall() || CI->isNoTailCall())
|
||||
return false;
|
||||
if (CI->getFunctionType()->isVarArg() || CI->getType()->isTokenTy())
|
||||
return false;
|
||||
if (CI->getCallingConv() == CallingConv::SwiftTail)
|
||||
return false;
|
||||
|
||||
for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
|
||||
if (CI->getArgOperand(i)->getType()->isTokenTy())
|
||||
return false;
|
||||
if (CI->paramHasAttr(i, Attribute::SwiftAsync) ||
|
||||
CI->paramHasAttr(i, Attribute::InAlloca) ||
|
||||
CI->paramHasAttr(i, Attribute::Preallocated) ||
|
||||
CI->paramHasAttr(i, Attribute::ImmArg)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (CI->hasOperandBundles()) {
|
||||
for (unsigned i = 0, e = CI->getNumOperandBundles(); i != e; ++i) {
|
||||
if (CI->getOperandBundleAt(i).getTagName() != "clang.arc.attachedcall")
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
auto *Callee = dyn_cast<Function>(CI->getCalledOperand());
|
||||
if (!Callee || Callee->getFunctionType() != CI->getFunctionType())
|
||||
return false;
|
||||
|
||||
OutCallee = Callee;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string computeModuleTag(StringRef Seed, StringRef ModId,
|
||||
StringRef SourcePath) {
|
||||
SHA256 Hasher;
|
||||
Hasher.update(Seed);
|
||||
Hasher.update("|");
|
||||
Hasher.update(ModId);
|
||||
Hasher.update("|");
|
||||
Hasher.update(SourcePath);
|
||||
auto Digest = Hasher.final();
|
||||
return toHex(ArrayRef<uint8_t>(Digest.data(), 4), /*LowerCase=*/true);
|
||||
}
|
||||
|
||||
struct PendingIndirectSite {
|
||||
CallInst *CI = nullptr;
|
||||
Function *Callee = nullptr;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runIndirectCallObfuscation(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isIndirectCallEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
|
||||
if (!M.getTargetTriple().empty()) {
|
||||
Triple TT(M.getTargetTriple());
|
||||
if (!TT.isOSBinFormatMachO() || !TT.isAArch64() ||
|
||||
TT.getArchName() == "arm64e") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string SwiftModToken;
|
||||
if (!Policy.swiftModuleName().empty()) {
|
||||
StringRef ExplicitMod = Policy.swiftModuleName();
|
||||
SwiftModToken =
|
||||
std::to_string(ExplicitMod.size()) + ExplicitMod.str();
|
||||
} else {
|
||||
SwiftModToken = detectSwiftModuleToken(M);
|
||||
}
|
||||
SmallVector<PendingIndirectSite, 32> Sites;
|
||||
SmallVector<Function *, 16> UniqueCallees;
|
||||
DenseMap<Function *, unsigned> SeenCallees;
|
||||
std::vector<std::string> TouchedCallers;
|
||||
|
||||
for (Function &Caller : M) {
|
||||
if (!isCallerEligible(Caller, Policy))
|
||||
continue;
|
||||
|
||||
bool CallerTouched = false;
|
||||
for (BasicBlock &BB : Caller) {
|
||||
for (Instruction &I : BB) {
|
||||
auto *CI = dyn_cast<CallInst>(&I);
|
||||
if (!CI)
|
||||
continue;
|
||||
Function *Callee = nullptr;
|
||||
if (!isCallSiteEligible(CI, Callee))
|
||||
continue;
|
||||
if (!isSameImageSafeCallee(*Callee, SwiftModToken, Policy))
|
||||
continue;
|
||||
|
||||
Sites.push_back({CI, Callee});
|
||||
if (SeenCallees.try_emplace(Callee, UniqueCallees.size()).second)
|
||||
UniqueCallees.push_back(Callee);
|
||||
CallerTouched = true;
|
||||
}
|
||||
}
|
||||
if (CallerTouched)
|
||||
TouchedCallers.push_back(Caller.getName().str());
|
||||
}
|
||||
|
||||
if (Sites.empty())
|
||||
return false;
|
||||
|
||||
for (Function *Callee : UniqueCallees) {
|
||||
if (!Callee->isDeclaration() && Callee->hasPrivateLinkage())
|
||||
Callee->setLinkage(GlobalValue::InternalLinkage);
|
||||
}
|
||||
|
||||
IGDeterministicRNG RNG(Policy.seed(), M.getModuleIdentifier(),
|
||||
"__ig_icall_table");
|
||||
RNG.shuffle(UniqueCallees);
|
||||
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
Type *I8Ty = Type::getInt8Ty(Ctx);
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
PointerType *PtrTy = PointerType::getUnqual(Ctx);
|
||||
|
||||
std::string Tag =
|
||||
computeModuleTag(Policy.seed(), M.getModuleIdentifier(), Policy.sourcePath());
|
||||
|
||||
auto *AnchorGV = new GlobalVariable(
|
||||
M, I8Ty, /*isConstant=*/true, GlobalValue::InternalLinkage,
|
||||
ConstantInt::get(I8Ty, RNG.nextNonZeroByte()), "__ig_ca_" + Tag);
|
||||
AnchorGV->setAlignment(Align(1));
|
||||
AnchorGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
|
||||
|
||||
Constant *AnchorInt = ConstantExpr::getPtrToInt(AnchorGV, I64Ty);
|
||||
bool UseDualTable = Policy.isIndirectCallDualTableEnabled();
|
||||
Audit.IndirectCallDualTable = UseDualTable;
|
||||
|
||||
SmallVector<Constant *, 16> DeltaEntries;
|
||||
SmallVector<Constant *, 16> IndexEntries(UseDualTable ? UniqueCallees.size() : 0);
|
||||
DeltaEntries.reserve(UniqueCallees.size());
|
||||
uint64_t IndexKey = UseDualTable ? RNG.nextNonZeroU64() : 0;
|
||||
|
||||
// Mach-O linkers may truncate addends on symbol differences. Keep the
|
||||
// relocated table to pure differences and encode only the separate indices.
|
||||
for (unsigned Idx = 0; Idx < UniqueCallees.size(); ++Idx) {
|
||||
Function *TargetFn = UniqueCallees[Idx];
|
||||
Constant *CalleeInt = ConstantExpr::getPtrToInt(TargetFn, I64Ty);
|
||||
DeltaEntries.push_back(ConstantExpr::getSub(CalleeInt, AnchorInt));
|
||||
if (UseDualTable) {
|
||||
IndexEntries[SeenCallees.lookup(TargetFn)] =
|
||||
ConstantInt::get(I64Ty, Idx ^ IndexKey);
|
||||
} else {
|
||||
SeenCallees[TargetFn] = Idx;
|
||||
}
|
||||
}
|
||||
|
||||
ArrayType *TableTy = ArrayType::get(I64Ty, DeltaEntries.size());
|
||||
auto *DeltaGV = new GlobalVariable(
|
||||
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
|
||||
ConstantArray::get(TableTy, DeltaEntries),
|
||||
(UseDualTable ? "__ig_cs1_" : "__ig_ct_") + Tag);
|
||||
DeltaGV->setAlignment(Align(8));
|
||||
DeltaGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
|
||||
|
||||
GlobalVariable *IndexGV = nullptr;
|
||||
if (UseDualTable) {
|
||||
IndexGV = new GlobalVariable(
|
||||
M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
|
||||
ConstantArray::get(TableTy, IndexEntries), "__ig_cs2_" + Tag);
|
||||
IndexGV->setAlignment(Align(8));
|
||||
IndexGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
|
||||
}
|
||||
|
||||
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
|
||||
for (const PendingIndirectSite &Site : Sites) {
|
||||
CallInst *CI = Site.CI;
|
||||
IRBuilder<> B(CI);
|
||||
B.SetCurrentDebugLocation(CI->getDebugLoc());
|
||||
Value *Index = ConstantInt::get(I64Ty, SeenCallees.lookup(Site.Callee));
|
||||
if (UseDualTable) {
|
||||
Value *IndexPtr = B.CreateInBoundsGEP(TableTy, IndexGV, {Zero64, Index});
|
||||
Value *EncodedIndex =
|
||||
B.CreateAlignedLoad(I64Ty, IndexPtr, Align(8), /*isVolatile=*/true);
|
||||
Index = B.CreateXor(EncodedIndex, ConstantInt::get(I64Ty, IndexKey));
|
||||
}
|
||||
Value *DeltaPtr = B.CreateInBoundsGEP(TableTy, DeltaGV, {Zero64, Index});
|
||||
Value *Delta =
|
||||
B.CreateAlignedLoad(I64Ty, DeltaPtr, Align(8), /*isVolatile=*/true);
|
||||
Value *AnchorVal = B.CreatePtrToInt(AnchorGV, I64Ty);
|
||||
Value *TargetInt = B.CreateAdd(AnchorVal, Delta);
|
||||
Value *FnPtr = B.CreateIntToPtr(TargetInt, PtrTy);
|
||||
|
||||
CI->setTailCallKind(CallInst::TCK_None);
|
||||
CI->setCalledOperand(FnPtr);
|
||||
++Audit.IndirectCallsCount;
|
||||
}
|
||||
|
||||
Audit.IndirectCallsFunctions.insert(Audit.IndirectCallsFunctions.end(),
|
||||
TouchedCallers.begin(),
|
||||
TouchedCallers.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,348 @@
|
||||
#include "IGPassUtils.h"
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/IR/Constants.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/GlobalVariable.h"
|
||||
#include "llvm/IR/IRBuilder.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Verifier.h"
|
||||
#include "llvm/Support/Alignment.h"
|
||||
#include "llvm/Support/ErrorHandling.h"
|
||||
#include <array>
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
constexpr unsigned kConstPoolSize = 32;
|
||||
|
||||
struct ConstSite {
|
||||
Instruction *Inst = nullptr;
|
||||
unsigned OpIdx = 0;
|
||||
uint64_t Value = 0;
|
||||
unsigned BitWidth = 0;
|
||||
};
|
||||
|
||||
void considerOperand(Instruction *I, unsigned OpIdx,
|
||||
SmallVectorImpl<ConstSite> &Sites, unsigned MaxBudget) {
|
||||
if (Sites.size() >= MaxBudget)
|
||||
return;
|
||||
auto *CI = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
|
||||
if (!CI)
|
||||
return;
|
||||
unsigned BW = CI->getBitWidth();
|
||||
if (BW != 32 && BW != 64)
|
||||
return;
|
||||
Sites.push_back({I, OpIdx, CI->getZExtValue(), BW});
|
||||
}
|
||||
|
||||
void collectConstantSites(Function &F, unsigned MaxBudget,
|
||||
SmallVectorImpl<ConstSite> &Sites) {
|
||||
for (BasicBlock &BB : F) {
|
||||
if (BB.isEHPad())
|
||||
continue;
|
||||
for (Instruction &I : BB) {
|
||||
if (Sites.size() >= MaxBudget)
|
||||
return;
|
||||
if (isa<SwitchInst>(&I) || isa<GetElementPtrInst>(&I) ||
|
||||
isa<CallBase>(&I) || isa<AllocaInst>(&I) || isa<PHINode>(&I) ||
|
||||
isa<LandingPadInst>(&I)) {
|
||||
continue;
|
||||
}
|
||||
if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
|
||||
if (!BO->getType()->isIntegerTy())
|
||||
continue;
|
||||
considerOperand(BO, 0, Sites, MaxBudget);
|
||||
// Preserve constant shift counts to avoid UB / dynamic shift penalties.
|
||||
if (!BO->isShift())
|
||||
considerOperand(BO, 1, Sites, MaxBudget);
|
||||
} else if (auto *Cmp = dyn_cast<ICmpInst>(&I)) {
|
||||
if (!Cmp->getOperand(0)->getType()->isIntegerTy())
|
||||
continue;
|
||||
considerOperand(Cmp, 0, Sites, MaxBudget);
|
||||
considerOperand(Cmp, 1, Sites, MaxBudget);
|
||||
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
|
||||
if (!SI->isAtomic() && !SI->isVolatile() &&
|
||||
SI->getValueOperand()->getType()->isIntegerTy()) {
|
||||
considerOperand(SI, 0, Sites, MaxBudget);
|
||||
}
|
||||
} else if (auto *Sel = dyn_cast<SelectInst>(&I)) {
|
||||
if (Sel->getType()->isIntegerTy()) {
|
||||
considerOperand(Sel, 1, Sites, MaxBudget);
|
||||
considerOperand(Sel, 2, Sites, MaxBudget);
|
||||
}
|
||||
} else if (auto *IV = dyn_cast<InsertValueInst>(&I)) {
|
||||
if (auto *CI = dyn_cast<ConstantInt>(IV->getInsertedValueOperand())) {
|
||||
if (CI->getBitWidth() == 64 && CI->getZExtValue() > 0xFFFFULL) {
|
||||
considerOperand(IV, 1, Sites, MaxBudget);
|
||||
}
|
||||
}
|
||||
} else if (auto *RI = dyn_cast<ReturnInst>(&I)) {
|
||||
if (Value *RV = RI->getReturnValue()) {
|
||||
if (auto *CI = dyn_cast<ConstantInt>(RV)) {
|
||||
if ((CI->getBitWidth() == 32 || CI->getBitWidth() == 64) &&
|
||||
CI->getZExtValue() > 0xFFFFULL) {
|
||||
considerOperand(RI, 0, Sites, MaxBudget);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FnRuntimeSeeds {
|
||||
bool Initialized = false;
|
||||
Value *Seed32 = nullptr;
|
||||
Value *Seed64 = nullptr;
|
||||
|
||||
void init(Function &F, Type *I32Ty, Type *I64Ty) {
|
||||
if (Initialized)
|
||||
return;
|
||||
Initialized = true;
|
||||
BasicBlock &Entry = F.getEntryBlock();
|
||||
|
||||
Value *IntSeed64 = nullptr;
|
||||
for (Argument &Arg : F.args()) {
|
||||
if (auto *IntTy = dyn_cast<IntegerType>(Arg.getType())) {
|
||||
if (IntTy->getBitWidth() >= 16) {
|
||||
IntSeed64 = &Arg;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Value *PtrSeed = nullptr;
|
||||
if (!IntSeed64) {
|
||||
for (Argument &Arg : F.args()) {
|
||||
if (Arg.getType()->isPointerTy()) {
|
||||
PtrSeed = &Arg;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
AllocaInst *Slot = nullptr;
|
||||
if (!IntSeed64 && !PtrSeed) {
|
||||
Instruction *AllocaPt = &*Entry.getFirstInsertionPt();
|
||||
IRBuilder<> AllocaB(AllocaPt);
|
||||
AllocaB.SetCurrentDebugLocation(resolveInstDebugLoc(AllocaPt, F));
|
||||
Slot = AllocaB.CreateAlloca(Type::getInt8Ty(F.getContext()), nullptr,
|
||||
"ig.oz.seed");
|
||||
}
|
||||
|
||||
// Keep all static allocas strictly grouped before non-alloca seed ops.
|
||||
AllocaInst *LastAlloca = nullptr;
|
||||
for (Instruction &Inst : Entry) {
|
||||
if (auto *AI = dyn_cast<AllocaInst>(&Inst))
|
||||
LastAlloca = AI;
|
||||
}
|
||||
Instruction *SeedPt =
|
||||
LastAlloca ? LastAlloca->getNextNode() : &*Entry.getFirstInsertionPt();
|
||||
IRBuilder<> EB(SeedPt);
|
||||
EB.SetCurrentDebugLocation(resolveInstDebugLoc(SeedPt, F));
|
||||
|
||||
Value *Chosen64 = nullptr;
|
||||
if (IntSeed64) {
|
||||
unsigned BW = IntSeed64->getType()->getIntegerBitWidth();
|
||||
Chosen64 = (BW == 64) ? IntSeed64 : EB.CreateZExt(IntSeed64, I64Ty);
|
||||
} else if (PtrSeed) {
|
||||
Value *P2I = EB.CreatePtrToInt(PtrSeed, I64Ty);
|
||||
Chosen64 = EB.CreateLShr(P2I, ConstantInt::get(I64Ty, 4));
|
||||
} else {
|
||||
Value *P2I = EB.CreatePtrToInt(Slot, I64Ty);
|
||||
Chosen64 = EB.CreateLShr(P2I, ConstantInt::get(I64Ty, 4));
|
||||
}
|
||||
|
||||
Seed64 = Chosen64;
|
||||
Seed32 = EB.CreateTrunc(Chosen64, I32Ty);
|
||||
}
|
||||
|
||||
Value *get(Function &F, bool Is32, Type *I32Ty, Type *I64Ty) {
|
||||
init(F, I32Ty, I64Ty);
|
||||
return Is32 ? Seed32 : Seed64;
|
||||
}
|
||||
};
|
||||
|
||||
Value *emitOpaqueZero(IRBuilder<> &B, Value *SeedVal, unsigned Variant,
|
||||
uint64_t MixK) {
|
||||
Type *Ty = SeedVal->getType();
|
||||
Value *RawZero = nullptr;
|
||||
if ((Variant & 1U) == 0) {
|
||||
// ((s | 1)^2 - 1) & 7 == 0 for every integer (odd^2 - 1 is divisible by 8).
|
||||
Value *Odd = B.CreateOr(SeedVal, ConstantInt::get(Ty, 1));
|
||||
Value *Sq = B.CreateMul(Odd, Odd);
|
||||
Value *Diff = B.CreateSub(Sq, ConstantInt::get(Ty, 1));
|
||||
RawZero = B.CreateAnd(Diff, ConstantInt::get(Ty, 7));
|
||||
} else {
|
||||
// (s * (s + 1)) & 1 == 0 for every integer (product of consecutive ints is even).
|
||||
Value *Plus1 = B.CreateAdd(SeedVal, ConstantInt::get(Ty, 1));
|
||||
Value *Prod = B.CreateMul(SeedVal, Plus1);
|
||||
RawZero = B.CreateAnd(Prod, ConstantInt::get(Ty, 1));
|
||||
}
|
||||
return B.CreateMul(RawZero, ConstantInt::get(Ty, MixK));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runOpaqueConstants(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isOpaqueConstantsEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
if (!isMachOAArch64NonArm64e(M))
|
||||
return false;
|
||||
|
||||
struct FunctionSites {
|
||||
Function *Fn = nullptr;
|
||||
SmallVector<ConstSite, 16> Sites;
|
||||
unsigned Prob = 100;
|
||||
bool UseOpaqueZero = false;
|
||||
};
|
||||
SmallVector<FunctionSites, 8> Worklist;
|
||||
const unsigned DefaultMaxPerFn = Policy.opaqueConstMaxPerFn();
|
||||
const bool DefaultOpaqueZero = Policy.opaqueConstOpaqueZero();
|
||||
bool NeedsPool = false;
|
||||
|
||||
for (Function &F : M) {
|
||||
if (!Policy.shouldObfuscateConstantsInFunction(F))
|
||||
continue;
|
||||
if (!isFunctionSafeForTransform(F, Policy,
|
||||
&Policy.opaqueConstExemptFunctions())) {
|
||||
continue;
|
||||
}
|
||||
const TargetRule *Rule = Policy.findOpaqueConstRule(F);
|
||||
unsigned MaxPerFn =
|
||||
(Rule && Rule->MaxPerFn) ? *Rule->MaxPerFn : DefaultMaxPerFn;
|
||||
unsigned Prob =
|
||||
(Rule && Rule->Probability) ? *Rule->Probability : 100U;
|
||||
bool UseOpaqueZero =
|
||||
(Rule && Rule->OpaqueZero) ? *Rule->OpaqueZero : DefaultOpaqueZero;
|
||||
if (MaxPerFn == 0 || Prob == 0)
|
||||
continue;
|
||||
|
||||
SmallVector<ConstSite, 16> Sites;
|
||||
collectConstantSites(F, MaxPerFn, Sites);
|
||||
if (!Sites.empty()) {
|
||||
if (!UseOpaqueZero)
|
||||
NeedsPool = true;
|
||||
Worklist.push_back({&F, std::move(Sites), Prob, UseOpaqueZero});
|
||||
}
|
||||
}
|
||||
|
||||
if (Worklist.empty())
|
||||
return false;
|
||||
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
Type *I32Ty = Type::getInt32Ty(Ctx);
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
std::string Tag = computeShortModuleTag(Policy.seed(), M.getModuleIdentifier(),
|
||||
Policy.sourcePath());
|
||||
|
||||
std::array<uint64_t, kConstPoolSize> PoolMasks{};
|
||||
ArrayType *PoolTy = ArrayType::get(I64Ty, kConstPoolSize);
|
||||
GlobalVariable *PoolGV = nullptr;
|
||||
if (NeedsPool) {
|
||||
IGDeterministicRNG PoolRNG(Policy.seed(), M.getModuleIdentifier(),
|
||||
"__ig_oc_pool");
|
||||
SmallVector<Constant *, kConstPoolSize> PoolConsts;
|
||||
PoolConsts.reserve(kConstPoolSize);
|
||||
for (unsigned i = 0; i < kConstPoolSize; ++i) {
|
||||
uint64_t MaskVal = PoolRNG.nextNonZeroU64();
|
||||
PoolMasks[i] = MaskVal;
|
||||
PoolConsts.push_back(ConstantInt::get(I64Ty, MaskVal));
|
||||
}
|
||||
PoolGV = new GlobalVariable(
|
||||
M, PoolTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
|
||||
ConstantArray::get(PoolTy, PoolConsts), "__ig_ocp_" + Tag);
|
||||
PoolGV->setAlignment(Align(8));
|
||||
PoolGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
|
||||
}
|
||||
|
||||
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
|
||||
bool Changed = false;
|
||||
|
||||
for (FunctionSites &Item : Worklist) {
|
||||
Function *F = Item.Fn;
|
||||
IGDeterministicRNG FnRNG(Policy.seed(), M.getModuleIdentifier(),
|
||||
F->getName());
|
||||
FnRuntimeSeeds Seeds;
|
||||
unsigned FnHits = 0;
|
||||
|
||||
for (const ConstSite &Site : Item.Sites) {
|
||||
if (Item.Prob < 100U && (FnRNG.nextU32() % 100U) >= Item.Prob)
|
||||
continue;
|
||||
|
||||
bool Is32 = (Site.BitWidth == 32);
|
||||
Type *ValTy = Is32 ? I32Ty : I64Ty;
|
||||
uint64_t BitMask = Is32 ? 0xFFFFFFFFULL : 0xFFFFFFFFFFFFFFFFULL;
|
||||
uint64_t TargetVal = Site.Value & BitMask;
|
||||
uint64_t RemA = (Is32 ? static_cast<uint64_t>(FnRNG.nextNonZeroU32())
|
||||
: FnRNG.nextNonZeroU64()) &
|
||||
BitMask;
|
||||
bool UseXorAdd = (FnRNG.nextU32() & 1U) == 0;
|
||||
|
||||
Value *SeedVal = nullptr;
|
||||
if (Item.UseOpaqueZero) {
|
||||
SeedVal = Seeds.get(*F, Is32, I32Ty, I64Ty);
|
||||
}
|
||||
|
||||
IRBuilder<> B(Site.Inst);
|
||||
B.SetCurrentDebugLocation(resolveInstDebugLoc(Site.Inst, *F));
|
||||
|
||||
Value *Encoded = nullptr;
|
||||
if (Item.UseOpaqueZero) {
|
||||
uint64_t MixK = (FnRNG.nextNonZeroU64() | 1ULL) & BitMask;
|
||||
Value *OZero = emitOpaqueZero(B, SeedVal, FnRNG.nextU32(), MixK);
|
||||
if (UseXorAdd) {
|
||||
uint64_t PartB = (TargetVal ^ RemA) & BitMask;
|
||||
Value *T1 = B.CreateAdd(OZero, ConstantInt::get(ValTy, RemA));
|
||||
Encoded = B.CreateXor(T1, ConstantInt::get(ValTy, PartB));
|
||||
} else {
|
||||
uint64_t PartB = (TargetVal - RemA) & BitMask;
|
||||
Value *T1 = B.CreateXor(OZero, ConstantInt::get(ValTy, RemA));
|
||||
Encoded = B.CreateAdd(T1, ConstantInt::get(ValTy, PartB));
|
||||
}
|
||||
++Audit.OpaqueZeroCount;
|
||||
} else {
|
||||
unsigned Slot = FnRNG.nextU32() % kConstPoolSize;
|
||||
uint64_t Mask64 = PoolMasks[Slot];
|
||||
uint64_t MaskedM = Mask64 & BitMask;
|
||||
Value *SlotPtr = B.CreateInBoundsGEP(
|
||||
PoolTy, PoolGV, {Zero64, ConstantInt::get(I64Ty, Slot)});
|
||||
LoadInst *Loaded64 =
|
||||
B.CreateAlignedLoad(I64Ty, SlotPtr, Align(8), /*isVolatile=*/true);
|
||||
Value *Base = Is32 ? B.CreateTrunc(Loaded64, I32Ty)
|
||||
: static_cast<Value *>(Loaded64);
|
||||
|
||||
if (UseXorAdd) {
|
||||
// Mod-2^W inverse of ((M ^ RemA) + RemB) prevents Add/Xor folding.
|
||||
uint64_t RemB = (TargetVal - (MaskedM ^ RemA)) & BitMask;
|
||||
Value *T1 = B.CreateXor(Base, ConstantInt::get(ValTy, RemA));
|
||||
Encoded = B.CreateAdd(T1, ConstantInt::get(ValTy, RemB));
|
||||
} else {
|
||||
uint64_t RemB = ((MaskedM + RemA) ^ TargetVal) & BitMask;
|
||||
Value *T1 = B.CreateAdd(Base, ConstantInt::get(ValTy, RemA));
|
||||
Encoded = B.CreateXor(T1, ConstantInt::get(ValTy, RemB));
|
||||
}
|
||||
}
|
||||
|
||||
Site.Inst->setOperand(Site.OpIdx, Encoded);
|
||||
++Audit.OpaqueConstantsCount;
|
||||
++FnHits;
|
||||
Changed = true;
|
||||
}
|
||||
|
||||
if (FnHits > 0) {
|
||||
if (verifyFunction(*F, &errs())) {
|
||||
report_fatal_error(Twine("[IGOpaqueConstants] IR verification failed on ") +
|
||||
F->getName());
|
||||
}
|
||||
Audit.OpaqueConstantsFunctions.push_back(F->getName().str());
|
||||
}
|
||||
}
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,297 @@
|
||||
#include "IGPassUtils.h"
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/DenseMap.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/IR/Constants.h"
|
||||
#include "llvm/IR/DataLayout.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/GlobalVariable.h"
|
||||
#include "llvm/IR/IRBuilder.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/IntrinsicInst.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Verifier.h"
|
||||
#include "llvm/Support/Alignment.h"
|
||||
#include "llvm/Support/ErrorHandling.h"
|
||||
#include <array>
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
constexpr unsigned kFieldPoolSize = 32;
|
||||
|
||||
bool isSensitiveGlobalSymbol(const GlobalVariable *GV) {
|
||||
if (!GV)
|
||||
return true;
|
||||
if (GV->isThreadLocal() || GV->isExternallyInitialized() ||
|
||||
GV->hasAppendingLinkage() || GV->hasExternalWeakLinkage() ||
|
||||
GV->getAddressSpace() != 0) {
|
||||
return true;
|
||||
}
|
||||
if (GV->hasSection()) {
|
||||
StringRef Sec = GV->getSection();
|
||||
if (Sec.contains("__objc") || Sec.contains("__swift") ||
|
||||
Sec.contains("__cfstring") || Sec.contains("__LLVM") ||
|
||||
Sec.contains("__mod_init") || Sec.contains("__mod_term")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
StringRef Clean = stripObjCMarker(GV->getName());
|
||||
if (Clean.starts_with("llvm.") || Clean.starts_with("__ig_") ||
|
||||
Clean.starts_with(".ig.") || Clean.starts_with("L_OBJC_") ||
|
||||
Clean.starts_with("l_OBJC_") || Clean.starts_with("OBJC_") ||
|
||||
Clean.starts_with("_OBJC_") || Clean.starts_with("L_.str")) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isSensitiveBasePtr(const Value *Ptr) {
|
||||
if (!Ptr)
|
||||
return true;
|
||||
const Value *Stripped = Ptr->stripPointerCasts();
|
||||
if (const auto *GV = dyn_cast<GlobalVariable>(Stripped)) {
|
||||
if (GV->isConstant() || isSensitiveGlobalSymbol(GV))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
struct GEPSite {
|
||||
GetElementPtrInst *GEP = nullptr;
|
||||
int64_t ConstOffset = 0;
|
||||
};
|
||||
|
||||
struct GlobalAccessSite {
|
||||
Instruction *Inst = nullptr;
|
||||
unsigned PtrOpIdx = 0;
|
||||
GlobalVariable *GV = nullptr;
|
||||
};
|
||||
|
||||
struct FieldFnWork {
|
||||
Function *Fn = nullptr;
|
||||
SmallVector<GEPSite, 16> GEPs;
|
||||
SmallVector<GlobalAccessSite, 16> Globals;
|
||||
};
|
||||
|
||||
void collectFieldSites(Function &F, const DataLayout &DL, unsigned MaxPerFn,
|
||||
SmallVectorImpl<GEPSite> &GEPs,
|
||||
SmallVectorImpl<GlobalAccessSite> &Globals) {
|
||||
unsigned Total = 0;
|
||||
for (BasicBlock &BB : F) {
|
||||
if (BB.isEHPad())
|
||||
continue;
|
||||
for (Instruction &I : BB) {
|
||||
if (Total >= MaxPerFn)
|
||||
return;
|
||||
|
||||
if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
|
||||
if (GEP->getType()->isVectorTy() || GEP->getPointerAddressSpace() != 0)
|
||||
continue;
|
||||
if (!GEP->hasAllConstantIndices())
|
||||
continue;
|
||||
if (isSensitiveBasePtr(GEP->getPointerOperand()))
|
||||
continue;
|
||||
if (any_of(GEP->users(), [](const User *U) {
|
||||
return isa<LifetimeIntrinsic>(U) || isa<DbgInfoIntrinsic>(U) ||
|
||||
isa<AssumeInst>(U);
|
||||
})) {
|
||||
continue;
|
||||
}
|
||||
unsigned IdxBits = DL.getIndexTypeSizeInBits(GEP->getType());
|
||||
if (IdxBits == 0 || IdxBits > 64)
|
||||
continue;
|
||||
APInt ConstOff(IdxBits, 0);
|
||||
if (!GEP->accumulateConstantOffset(DL, ConstOff))
|
||||
continue;
|
||||
int64_t SignedOff = ConstOff.getSExtValue();
|
||||
if (SignedOff == 0)
|
||||
continue;
|
||||
GEPs.push_back({GEP, SignedOff});
|
||||
++Total;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (auto *LI = dyn_cast<LoadInst>(&I)) {
|
||||
if (LI->isVolatile() || LI->isAtomic())
|
||||
continue;
|
||||
if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand())) {
|
||||
if (!GV->isConstant() && !isSensitiveGlobalSymbol(GV)) {
|
||||
Globals.push_back({LI, 0, GV});
|
||||
++Total;
|
||||
}
|
||||
}
|
||||
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
|
||||
if (SI->isVolatile() || SI->isAtomic())
|
||||
continue;
|
||||
if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) {
|
||||
if (!GV->isConstant() && !isSensitiveGlobalSymbol(GV)) {
|
||||
Globals.push_back({SI, 1, GV});
|
||||
++Total;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Value *emitMaskedOffset64(IRBuilder<> &B, GlobalVariable *PoolGV,
|
||||
ArrayType *PoolTy, uint64_t TargetSigned64,
|
||||
const std::array<uint64_t, kFieldPoolSize> &PoolMasks,
|
||||
IGDeterministicRNG &RNG) {
|
||||
Type *I64Ty = B.getInt64Ty();
|
||||
Value *Zero64 = ConstantInt::get(I64Ty, 0);
|
||||
unsigned Slot = RNG.nextU32() % kFieldPoolSize;
|
||||
uint64_t Mask = PoolMasks[Slot];
|
||||
uint64_t RemA = RNG.nextNonZeroU64();
|
||||
bool UseXorAdd = (RNG.nextU32() & 1U) == 0;
|
||||
|
||||
Value *SlotPtr =
|
||||
B.CreateInBoundsGEP(PoolTy, PoolGV, {Zero64, ConstantInt::get(I64Ty, Slot)});
|
||||
Value *LoadedMask =
|
||||
B.CreateAlignedLoad(I64Ty, SlotPtr, Align(8), /*isVolatile=*/true);
|
||||
|
||||
if (UseXorAdd) {
|
||||
uint64_t RemB = TargetSigned64 - (Mask ^ RemA);
|
||||
Value *T1 = B.CreateXor(LoadedMask, ConstantInt::get(I64Ty, RemA));
|
||||
return B.CreateAdd(T1, ConstantInt::get(I64Ty, RemB));
|
||||
}
|
||||
uint64_t RemB = (Mask + RemA) ^ TargetSigned64;
|
||||
Value *T1 = B.CreateAdd(LoadedMask, ConstantInt::get(I64Ty, RemA));
|
||||
return B.CreateXor(T1, ConstantInt::get(I64Ty, RemB));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runOpaqueFieldAccess(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isOpaqueFieldEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
if (!isMachOAArch64NonArm64e(M))
|
||||
return false;
|
||||
|
||||
const DataLayout &DL = M.getDataLayout();
|
||||
const unsigned MaxPerFn = Policy.opaqueFieldMaxPerFn();
|
||||
if (MaxPerFn == 0)
|
||||
return false;
|
||||
|
||||
SmallVector<FieldFnWork, 8> Worklist;
|
||||
DenseMap<GlobalVariable *, unsigned> AnchorSlotMap;
|
||||
SmallVector<Constant *, 32> AnchorPtrs;
|
||||
|
||||
for (Function &F : M) {
|
||||
if (!Policy.shouldObfuscateFieldAccessInFunction(F))
|
||||
continue;
|
||||
if (!isFunctionSafeForTransform(F, Policy,
|
||||
&Policy.opaqueFieldExemptFunctions())) {
|
||||
continue;
|
||||
}
|
||||
SmallVector<GEPSite, 16> GEPs;
|
||||
SmallVector<GlobalAccessSite, 16> Globals;
|
||||
collectFieldSites(F, DL, MaxPerFn, GEPs, Globals);
|
||||
if (GEPs.empty() && Globals.empty())
|
||||
continue;
|
||||
|
||||
for (const GlobalAccessSite &GS : Globals) {
|
||||
if (AnchorSlotMap.try_emplace(GS.GV, static_cast<unsigned>(AnchorPtrs.size()))
|
||||
.second) {
|
||||
AnchorPtrs.push_back(GS.GV);
|
||||
}
|
||||
}
|
||||
Worklist.push_back({&F, std::move(GEPs), std::move(Globals)});
|
||||
}
|
||||
|
||||
if (Worklist.empty())
|
||||
return false;
|
||||
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
Type *I8Ty = Type::getInt8Ty(Ctx);
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
PointerType *PtrTy = PointerType::getUnqual(Ctx);
|
||||
std::string Tag = computeShortModuleTag(Policy.seed(), M.getModuleIdentifier(),
|
||||
Policy.sourcePath());
|
||||
|
||||
IGDeterministicRNG PoolRNG(Policy.seed(), M.getModuleIdentifier(),
|
||||
"__ig_fop_pool");
|
||||
std::array<uint64_t, kFieldPoolSize> PoolMasks{};
|
||||
SmallVector<Constant *, kFieldPoolSize> PoolConsts;
|
||||
PoolConsts.reserve(kFieldPoolSize);
|
||||
for (unsigned i = 0; i < kFieldPoolSize; ++i) {
|
||||
uint64_t V = PoolRNG.nextNonZeroU64();
|
||||
PoolMasks[i] = V;
|
||||
PoolConsts.push_back(ConstantInt::get(I64Ty, V));
|
||||
}
|
||||
|
||||
ArrayType *PoolTy = ArrayType::get(I64Ty, kFieldPoolSize);
|
||||
auto *PoolGV = new GlobalVariable(
|
||||
M, PoolTy, /*isConstant=*/true, GlobalValue::InternalLinkage,
|
||||
ConstantArray::get(PoolTy, PoolConsts), "__ig_fop_" + Tag);
|
||||
PoolGV->setAlignment(Align(8));
|
||||
PoolGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
|
||||
|
||||
ArrayType *AnchorArrTy = nullptr;
|
||||
GlobalVariable *AnchorGV = nullptr;
|
||||
if (!AnchorPtrs.empty()) {
|
||||
AnchorArrTy = ArrayType::get(PtrTy, AnchorPtrs.size());
|
||||
AnchorGV = new GlobalVariable(
|
||||
M, AnchorArrTy, /*isConstant=*/false, GlobalValue::InternalLinkage,
|
||||
ConstantArray::get(AnchorArrTy, AnchorPtrs), "__ig_gba_" + Tag);
|
||||
AnchorGV->setAlignment(Align(8));
|
||||
AnchorGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
|
||||
}
|
||||
|
||||
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
|
||||
bool Changed = false;
|
||||
|
||||
for (FieldFnWork &Item : Worklist) {
|
||||
Function *F = Item.Fn;
|
||||
IGDeterministicRNG FnRNG(Policy.seed(), M.getModuleIdentifier(),
|
||||
(F->getName() + "|field").str());
|
||||
unsigned FnHits = 0;
|
||||
|
||||
for (const GEPSite &Site : Item.GEPs) {
|
||||
GetElementPtrInst *GEP = Site.GEP;
|
||||
IRBuilder<> B(GEP);
|
||||
B.SetCurrentDebugLocation(resolveInstDebugLoc(GEP, *F));
|
||||
Value *DynOff = emitMaskedOffset64(
|
||||
B, PoolGV, PoolTy, static_cast<uint64_t>(Site.ConstOffset), PoolMasks,
|
||||
FnRNG);
|
||||
Value *NewPtr = B.CreateGEP(I8Ty, GEP->getPointerOperand(), DynOff);
|
||||
GEP->replaceAllUsesWith(NewPtr);
|
||||
GEP->eraseFromParent();
|
||||
++FnHits;
|
||||
}
|
||||
|
||||
for (const GlobalAccessSite &Site : Item.Globals) {
|
||||
unsigned AnchorIdx = AnchorSlotMap[Site.GV];
|
||||
IRBuilder<> B(Site.Inst);
|
||||
B.SetCurrentDebugLocation(resolveInstDebugLoc(Site.Inst, *F));
|
||||
Value *SlotPtr = B.CreateInBoundsGEP(
|
||||
AnchorArrTy, AnchorGV, {Zero64, ConstantInt::get(I64Ty, AnchorIdx)});
|
||||
Value *LoadedBase =
|
||||
B.CreateAlignedLoad(PtrTy, SlotPtr, Align(8), /*isVolatile=*/true);
|
||||
Value *OpaqueZero =
|
||||
emitMaskedOffset64(B, PoolGV, PoolTy, 0ULL, PoolMasks, FnRNG);
|
||||
Value *NewPtr = B.CreateGEP(I8Ty, LoadedBase, OpaqueZero);
|
||||
Site.Inst->setOperand(Site.PtrOpIdx, NewPtr);
|
||||
++FnHits;
|
||||
}
|
||||
|
||||
if (FnHits > 0) {
|
||||
if (verifyFunction(*F, &errs())) {
|
||||
report_fatal_error(
|
||||
Twine("[IGOpaqueFieldAccess] IR verification failed on ") +
|
||||
F->getName());
|
||||
}
|
||||
Audit.OpaqueFieldAccessCount += FnHits;
|
||||
Audit.OpaqueFieldFunctions.push_back(F->getName().str());
|
||||
Changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,94 @@
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/PassManager.h"
|
||||
#include "llvm/IR/Verifier.h"
|
||||
#include "llvm/Passes/PassBuilder.h"
|
||||
#include "llvm/Passes/PassPlugin.h"
|
||||
#include "llvm/Support/ErrorHandling.h"
|
||||
#include "llvm/Support/raw_ostream.h"
|
||||
|
||||
namespace igobf {
|
||||
bool runSourcePathScrubbing(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runStringEncryption(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runFunctionOutline(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runOpaqueFieldAccess(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runOpaqueConstants(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runArithmeticObfuscation(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runIndirectCallObfuscation(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runBasicBlockSplit(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runControlFlowFlattening(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runIndirectBranchObfuscation(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
bool runAntiHooking(llvm::Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit);
|
||||
} // namespace igobf
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace {
|
||||
|
||||
struct IGObfuscateModulePass : public PassInfoMixin<IGObfuscateModulePass> {
|
||||
PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
|
||||
igobf::IGAuditRecord Audit;
|
||||
igobf::IGPolicyConfig Policy = igobf::IGPolicyConfig::loadFromCLI(M, Audit);
|
||||
|
||||
bool Changed = false;
|
||||
if (Policy.mode() != igobf::ObfMode::Off &&
|
||||
Policy.mode() != igobf::ObfMode::Noop) {
|
||||
Changed |= igobf::runSourcePathScrubbing(M, Policy, Audit);
|
||||
Changed |= igobf::runStringEncryption(M, Policy, Audit);
|
||||
Changed |= igobf::runOpaqueFieldAccess(M, Policy, Audit);
|
||||
Changed |= igobf::runFunctionOutline(M, Policy, Audit);
|
||||
Changed |= igobf::runOpaqueConstants(M, Policy, Audit);
|
||||
Changed |= igobf::runArithmeticObfuscation(M, Policy, Audit);
|
||||
Changed |= igobf::runIndirectCallObfuscation(M, Policy, Audit);
|
||||
Changed |= igobf::runBasicBlockSplit(M, Policy, Audit);
|
||||
Changed |= igobf::runControlFlowFlattening(M, Policy, Audit);
|
||||
Changed |= igobf::runIndirectBranchObfuscation(M, Policy, Audit);
|
||||
Changed |= igobf::runAntiHooking(M, Policy, Audit);
|
||||
|
||||
if (Changed && verifyModule(M, &errs())) {
|
||||
report_fatal_error("[IGPass] Module verification failed after passes");
|
||||
}
|
||||
}
|
||||
|
||||
if (!Audit.writeToFile(Policy.auditOutPath())) {
|
||||
report_fatal_error("[IGPass] Failed to persist module audit JSON");
|
||||
}
|
||||
|
||||
return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
llvm::PassPluginLibraryInfo getIGObfuscatorPluginInfo() {
|
||||
return {LLVM_PLUGIN_API_VERSION, "IGObfuscator", LLVM_VERSION_STRING,
|
||||
[](PassBuilder &PB) {
|
||||
PB.registerPipelineParsingCallback(
|
||||
[](StringRef Name, ModulePassManager &MPM,
|
||||
ArrayRef<PassBuilder::PipelineElement>) {
|
||||
if (Name == "ig-obfuscate") {
|
||||
MPM.addPass(IGObfuscateModulePass());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}};
|
||||
}
|
||||
|
||||
#ifndef LLVM_IGOBFUSCATOR_LINK_INTO_TOOLS
|
||||
extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
|
||||
llvmGetPassPluginInfo() {
|
||||
return getIGObfuscatorPluginInfo();
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,805 @@
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/IR/Constants.h"
|
||||
#include "llvm/IR/DebugInfoMetadata.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/GlobalVariable.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/Support/CommandLine.h"
|
||||
#include "llvm/Support/FileSystem.h"
|
||||
#include "llvm/Support/JSON.h"
|
||||
#include "llvm/Support/MemoryBuffer.h"
|
||||
#include "llvm/Support/Path.h"
|
||||
#include "llvm/Support/SHA256.h"
|
||||
#include "llvm/Support/raw_ostream.h"
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace {
|
||||
|
||||
cl::opt<std::string>
|
||||
IGPolicyPath("ig-policy", cl::init(""),
|
||||
cl::desc("Path to iOSGuard LLVM obfuscation policy JSON"));
|
||||
|
||||
cl::opt<std::string>
|
||||
IGModeOpt("ig-mode", cl::init("full"),
|
||||
cl::desc("iOSGuard obfuscation mode: full|str|noop|off"));
|
||||
|
||||
cl::opt<std::string> IGPassFilterOpt(
|
||||
"ig-pass-filter", cl::init("all"),
|
||||
cl::desc("iOSGuard pass filter: all|str|fla|icall|const|arith|ibr|antihook|outline|field|bbsplit"));
|
||||
|
||||
cl::opt<std::string>
|
||||
IGSeedOpt("ig-seed", cl::init("m0_seed_20261119_v1"),
|
||||
cl::desc("iOSGuard deterministic obfuscation seed"));
|
||||
|
||||
cl::opt<std::string>
|
||||
IGSourcePathOpt("ig-source-path", cl::init(""),
|
||||
cl::desc("Original source path hint for policy matching"));
|
||||
|
||||
cl::opt<std::string>
|
||||
IGSwiftModuleOpt("ig-swift-module", cl::init(""),
|
||||
cl::desc("Authoritative Swift module name of current target"));
|
||||
|
||||
cl::opt<std::string>
|
||||
IGAuditOutOpt("ig-audit-out", cl::init(""),
|
||||
cl::desc("Output path for module obfuscation audit JSON"));
|
||||
|
||||
std::string stripLeadingObjCMarker(StringRef Name) {
|
||||
if (!Name.empty() && Name.front() == '\x01')
|
||||
return Name.drop_front(1).str();
|
||||
return Name.str();
|
||||
}
|
||||
|
||||
igobf::ObfMode parseMode(StringRef S) {
|
||||
if (S == "off")
|
||||
return igobf::ObfMode::Off;
|
||||
if (S == "noop")
|
||||
return igobf::ObfMode::Noop;
|
||||
if (S == "str")
|
||||
return igobf::ObfMode::StrOnly;
|
||||
return igobf::ObfMode::Full;
|
||||
}
|
||||
|
||||
igobf::PassFilter parseFilter(StringRef S) {
|
||||
if (S == "str")
|
||||
return igobf::PassFilter::StrOnly;
|
||||
if (S == "fla")
|
||||
return igobf::PassFilter::FlaOnly;
|
||||
if (S == "icall")
|
||||
return igobf::PassFilter::IcallOnly;
|
||||
if (S == "const")
|
||||
return igobf::PassFilter::OpaqueConstOnly;
|
||||
if (S == "arith")
|
||||
return igobf::PassFilter::ArithOnly;
|
||||
if (S == "ibr")
|
||||
return igobf::PassFilter::IbrOnly;
|
||||
if (S == "antihook")
|
||||
return igobf::PassFilter::AntiHookOnly;
|
||||
if (S == "outline")
|
||||
return igobf::PassFilter::OutlineOnly;
|
||||
if (S == "field")
|
||||
return igobf::PassFilter::FieldOnly;
|
||||
if (S == "bbsplit")
|
||||
return igobf::PassFilter::BBSplitOnly;
|
||||
return igobf::PassFilter::All;
|
||||
}
|
||||
|
||||
unsigned parseClampedUInt(const json::Object &Obj, StringRef Key,
|
||||
unsigned DefaultVal, int64_t MinVal,
|
||||
int64_t MaxVal) {
|
||||
if (auto V = Obj.getInteger(Key)) {
|
||||
int64_t Raw = *V;
|
||||
if (Raw < MinVal)
|
||||
Raw = MinVal;
|
||||
if (Raw > MaxVal)
|
||||
Raw = MaxVal;
|
||||
return static_cast<unsigned>(Raw);
|
||||
}
|
||||
return DefaultVal;
|
||||
}
|
||||
|
||||
void appendStringArray(const json::Object &Obj, StringRef Key,
|
||||
std::vector<std::string> &Out) {
|
||||
if (const json::Array *Arr = Obj.getArray(Key)) {
|
||||
for (const json::Value &V : *Arr) {
|
||||
if (auto S = V.getAsString()) {
|
||||
if (!S->empty())
|
||||
Out.push_back(S->str());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void appendRuleArray(const json::Object &Obj, StringRef Key,
|
||||
std::vector<igobf::TargetRule> &Out) {
|
||||
if (const json::Array *Arr = Obj.getArray(Key)) {
|
||||
for (const json::Value &V : *Arr) {
|
||||
const json::Object *RuleObj = V.getAsObject();
|
||||
if (!RuleObj)
|
||||
continue;
|
||||
igobf::TargetRule Rule;
|
||||
if (auto S = RuleObj->getString("id"))
|
||||
Rule.Id = S->str();
|
||||
if (auto S = RuleObj->getString("path_contains"))
|
||||
Rule.PathContains = S->str();
|
||||
if (auto S = RuleObj->getString("function_contains"))
|
||||
Rule.FunctionContains = S->str();
|
||||
if (auto B = RuleObj->getBoolean("whole_module_if_no_debug"))
|
||||
Rule.WholeModuleIfNoDebug = *B;
|
||||
if (RuleObj->getInteger("rounds"))
|
||||
Rule.Rounds = parseClampedUInt(*RuleObj, "rounds", 1, 1, 4);
|
||||
if (RuleObj->getInteger("max_per_fn"))
|
||||
Rule.MaxPerFn = parseClampedUInt(*RuleObj, "max_per_fn", 64, 0, 1024);
|
||||
if (RuleObj->getInteger("probability"))
|
||||
Rule.Probability = parseClampedUInt(*RuleObj, "probability", 100, 0, 100);
|
||||
if (auto B = RuleObj->getBoolean("nonlinear_mba"))
|
||||
Rule.NonlinearMBA = *B;
|
||||
if (auto B = RuleObj->getBoolean("opaque_zero"))
|
||||
Rule.OpaqueZero = *B;
|
||||
if (!Rule.PathContains.empty() || !Rule.FunctionContains.empty())
|
||||
Out.push_back(std::move(Rule));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void appendStringReplaceRules(const json::Object &Obj, StringRef Key,
|
||||
std::vector<igobf::StringReplaceRule> &Out) {
|
||||
if (const json::Array *Arr = Obj.getArray(Key)) {
|
||||
for (const json::Value &V : *Arr) {
|
||||
const json::Object *RuleObj = V.getAsObject();
|
||||
if (!RuleObj)
|
||||
continue;
|
||||
igobf::StringReplaceRule Rule;
|
||||
if (auto S = RuleObj->getString("exact"))
|
||||
Rule.Exact = S->str();
|
||||
if (auto S = RuleObj->getString("replace"))
|
||||
Rule.Replace = S->str();
|
||||
if (!Rule.Exact.empty())
|
||||
Out.push_back(std::move(Rule));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void writeStringArrayAttr(json::OStream &J, StringRef Key,
|
||||
const std::vector<std::string> &Items) {
|
||||
J.attributeArray(Key, [&] {
|
||||
for (const auto &Item : Items)
|
||||
J.value(Item);
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace igobf {
|
||||
|
||||
IGDeterministicRNG::IGDeterministicRNG(StringRef Seed, StringRef ModuleId,
|
||||
StringRef ItemId) {
|
||||
Prefix_.reserve(Seed.size() + ModuleId.size() + ItemId.size() + 4);
|
||||
Prefix_.append(Seed.begin(), Seed.end());
|
||||
Prefix_.push_back('|');
|
||||
Prefix_.append(ModuleId.begin(), ModuleId.end());
|
||||
Prefix_.push_back('|');
|
||||
Prefix_.append(ItemId.begin(), ItemId.end());
|
||||
Prefix_.push_back('|');
|
||||
}
|
||||
|
||||
std::array<uint8_t, 32> IGDeterministicRNG::nextBlock() {
|
||||
SHA256 Hasher;
|
||||
Hasher.update(StringRef(Prefix_));
|
||||
std::string CntStr = std::to_string(Counter_++);
|
||||
Hasher.update(StringRef(CntStr));
|
||||
return Hasher.final();
|
||||
}
|
||||
|
||||
uint32_t IGDeterministicRNG::nextU32() {
|
||||
if (Offset_ + 4 > Buffer_.size()) {
|
||||
Buffer_ = nextBlock();
|
||||
Offset_ = 0;
|
||||
}
|
||||
uint32_t V = (static_cast<uint32_t>(Buffer_[Offset_]) << 24) |
|
||||
(static_cast<uint32_t>(Buffer_[Offset_ + 1]) << 16) |
|
||||
(static_cast<uint32_t>(Buffer_[Offset_ + 2]) << 8) |
|
||||
static_cast<uint32_t>(Buffer_[Offset_ + 3]);
|
||||
Offset_ += 4;
|
||||
return V;
|
||||
}
|
||||
|
||||
uint32_t IGDeterministicRNG::nextNonZeroU32() {
|
||||
uint32_t V = 0;
|
||||
do {
|
||||
V = nextU32();
|
||||
} while (V == 0);
|
||||
return V;
|
||||
}
|
||||
|
||||
uint64_t IGDeterministicRNG::nextU64() {
|
||||
uint64_t Hi = static_cast<uint64_t>(nextU32());
|
||||
uint64_t Lo = static_cast<uint64_t>(nextU32());
|
||||
return (Hi << 32) | Lo;
|
||||
}
|
||||
|
||||
uint64_t IGDeterministicRNG::nextNonZeroU64() {
|
||||
uint64_t V = 0;
|
||||
do {
|
||||
V = nextU64();
|
||||
} while (V == 0);
|
||||
return V;
|
||||
}
|
||||
|
||||
uint8_t IGDeterministicRNG::nextNonZeroByte() {
|
||||
uint8_t B = 0;
|
||||
do {
|
||||
if (Offset_ >= Buffer_.size()) {
|
||||
Buffer_ = nextBlock();
|
||||
Offset_ = 0;
|
||||
}
|
||||
B = Buffer_[Offset_++];
|
||||
} while (B == 0);
|
||||
return B;
|
||||
}
|
||||
|
||||
bool IGAuditRecord::writeToFile(StringRef OutPath) const {
|
||||
if (OutPath.empty())
|
||||
return true;
|
||||
SmallString<256> Parent = sys::path::parent_path(OutPath);
|
||||
if (!Parent.empty()) {
|
||||
std::error_code EC = sys::fs::create_directories(Parent);
|
||||
if (EC) {
|
||||
errs() << "[IGPass] Failed to create audit directory " << Parent << ": "
|
||||
<< EC.message() << "\n";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::error_code EC;
|
||||
raw_fd_ostream OS(OutPath, EC, sys::fs::OF_Text);
|
||||
if (EC) {
|
||||
errs() << "[IGPass] Failed to open audit output " << OutPath << ": "
|
||||
<< EC.message() << "\n";
|
||||
return false;
|
||||
}
|
||||
json::OStream J(OS, 2);
|
||||
J.object([&] {
|
||||
J.attribute("mode", Mode);
|
||||
J.attribute("pass_filter", PassFilter);
|
||||
J.attribute("seed", Seed);
|
||||
J.attribute("source_path", SourcePath);
|
||||
J.attribute("module_id", ModuleId);
|
||||
J.attribute("strings_encrypted_count",
|
||||
static_cast<int64_t>(StringsEncryptedCount));
|
||||
J.attribute("strings_stack_encrypted_count",
|
||||
static_cast<int64_t>(StringsStackEncryptedCount));
|
||||
J.attribute("objc_strings_encrypted_count",
|
||||
static_cast<int64_t>(ObjCStringsEncryptedCount));
|
||||
J.attribute("swift_strings_encrypted_count",
|
||||
static_cast<int64_t>(SwiftStringsEncryptedCount));
|
||||
J.attribute("strings_replaced_count",
|
||||
static_cast<int64_t>(StringsReplacedCount));
|
||||
J.attribute("strings_skipped_count",
|
||||
static_cast<int64_t>(StringsSkippedCount));
|
||||
J.attribute("paths_scrubbed_count",
|
||||
static_cast<int64_t>(PathsScrubbedCount));
|
||||
J.attribute("indirect_calls_count",
|
||||
static_cast<int64_t>(IndirectCallsCount));
|
||||
J.attribute("indirect_call_dual_table", IndirectCallDualTable);
|
||||
J.attribute("opaque_constants_count",
|
||||
static_cast<int64_t>(OpaqueConstantsCount));
|
||||
J.attribute("arithmetic_rewrites_count",
|
||||
static_cast<int64_t>(ArithmeticRewritesCount));
|
||||
J.attribute("indirect_branches_count",
|
||||
static_cast<int64_t>(IndirectBranchesCount));
|
||||
J.attribute("anti_hook_functions_count",
|
||||
static_cast<int64_t>(AntiHookFunctionsCount));
|
||||
J.attribute("functions_outlined_count",
|
||||
static_cast<int64_t>(FunctionsOutlinedCount));
|
||||
J.attribute("opaque_field_access_count",
|
||||
static_cast<int64_t>(OpaqueFieldAccessCount));
|
||||
J.attribute("bb_split_count", static_cast<int64_t>(BBSplitCount));
|
||||
J.attribute("nonlinear_mba_count",
|
||||
static_cast<int64_t>(NonlinearMBACount));
|
||||
J.attribute("opaque_zero_count", static_cast<int64_t>(OpaqueZeroCount));
|
||||
writeStringArrayAttr(J, "functions_flattened", FunctionsFlattened);
|
||||
J.attributeArray("functions_flattened_details", [&] {
|
||||
for (const auto &D : FunctionsFlattenedDetails) {
|
||||
J.object([&] {
|
||||
J.attribute("name", D.Name);
|
||||
J.attribute("topology", D.Topology);
|
||||
J.attribute("encoding", D.Encoding);
|
||||
J.attribute("blocks", static_cast<int64_t>(D.Blocks));
|
||||
});
|
||||
}
|
||||
});
|
||||
writeStringArrayAttr(J, "strings_encrypted_functions",
|
||||
StringsEncryptedFunctions);
|
||||
writeStringArrayAttr(J, "indirect_calls_functions", IndirectCallsFunctions);
|
||||
writeStringArrayAttr(J, "opaque_constants_functions",
|
||||
OpaqueConstantsFunctions);
|
||||
writeStringArrayAttr(J, "arithmetic_functions", ArithmeticFunctions);
|
||||
writeStringArrayAttr(J, "indirect_branches_functions",
|
||||
IndirectBranchesFunctions);
|
||||
writeStringArrayAttr(J, "anti_hook_functions", AntiHookFunctions);
|
||||
writeStringArrayAttr(J, "outlined_functions", OutlinedFunctions);
|
||||
writeStringArrayAttr(J, "opaque_field_functions", OpaqueFieldFunctions);
|
||||
writeStringArrayAttr(J, "bb_split_functions", BBSplitFunctions);
|
||||
J.attributeArray("functions_skipped", [&] {
|
||||
for (const auto &S : FunctionsSkipped) {
|
||||
J.object([&] {
|
||||
J.attribute("name", S.Name);
|
||||
J.attribute("reason", S.Reason);
|
||||
});
|
||||
}
|
||||
});
|
||||
writeStringArrayAttr(J, "annotated_targets", AnnotatedTargets);
|
||||
});
|
||||
OS << "\n";
|
||||
return true;
|
||||
}
|
||||
|
||||
IGPolicyConfig IGPolicyConfig::loadFromCLI(const Module &M,
|
||||
IGAuditRecord &AuditOut) {
|
||||
IGPolicyConfig Cfg;
|
||||
Cfg.Mode_ = parseMode(IGModeOpt);
|
||||
Cfg.Filter_ = parseFilter(IGPassFilterOpt);
|
||||
Cfg.Seed_ = IGSeedOpt;
|
||||
Cfg.SourcePath_ = !IGSourcePathOpt.empty() ? std::string(IGSourcePathOpt)
|
||||
: M.getSourceFileName();
|
||||
Cfg.SwiftModuleName_ = IGSwiftModuleOpt;
|
||||
Cfg.AuditOutPath_ = IGAuditOutOpt;
|
||||
|
||||
// Baseline function exemptions protecting runtime/linker/defender hooks
|
||||
Cfg.ExemptFunctionPrefixes_ = {
|
||||
"__ig_", "ig_defender_", "ig_call_", "ig_poison_",
|
||||
"ig_sys_", "ig_a", "ig_archive_", "_IG_dispatch_",
|
||||
"IG_dispatch_", "llvm.", "__swift_",
|
||||
};
|
||||
|
||||
if (!IGPolicyPath.empty()) {
|
||||
auto BufOrErr = MemoryBuffer::getFile(IGPolicyPath);
|
||||
if (!BufOrErr) {
|
||||
report_fatal_error(Twine("[IGPass] Cannot read policy JSON: ") +
|
||||
IGPolicyPath + ": " +
|
||||
BufOrErr.getError().message());
|
||||
}
|
||||
Expected<json::Value> Parsed = json::parse(BufOrErr.get()->getBuffer());
|
||||
if (!Parsed) {
|
||||
report_fatal_error(Twine("[IGPass] Invalid policy JSON: ") +
|
||||
IGPolicyPath + ": " + toString(Parsed.takeError()));
|
||||
}
|
||||
if (const json::Object *Root = Parsed->getAsObject()) {
|
||||
if (auto Topo = Root->getString("flatten_topology")) {
|
||||
if (*Topo == "sparse_switch" || *Topo == "star_switch")
|
||||
Cfg.FlattenTopology_ = igobf::FlattenTopology::StarSwitch;
|
||||
}
|
||||
Cfg.BogusBlockCount_ =
|
||||
parseClampedUInt(*Root, "flatten_bogus_blocks", 0, 0, 8);
|
||||
if (auto SplitLin = Root->getBoolean("flatten_split_linear_blocks")) {
|
||||
Cfg.SplitLinearBlocks_ = *SplitLin;
|
||||
}
|
||||
Cfg.OpaqueConstMaxPerFn_ =
|
||||
parseClampedUInt(*Root, "opaque_const_max_per_fn", 64, 1, 512);
|
||||
Cfg.ArithmeticRounds_ =
|
||||
parseClampedUInt(*Root, "arithmetic_rounds", 1, 1, 3);
|
||||
Cfg.ArithmeticMaxPerFn_ =
|
||||
parseClampedUInt(*Root, "arithmetic_max_per_fn", 128, 1, 1024);
|
||||
Cfg.StringEncryptStackMaxLen_ =
|
||||
parseClampedUInt(*Root, "string_encrypt_stack_max_len", 128, 16, 512);
|
||||
if (auto DualTbl = Root->getBoolean("indirect_call_dual_table")) {
|
||||
Cfg.IndirectCallDualTable_ = *DualTbl;
|
||||
}
|
||||
Cfg.FunctionOutlineMaxPerFn_ =
|
||||
parseClampedUInt(*Root, "function_outline_max_per_fn", 2, 0, 8);
|
||||
Cfg.FunctionOutlineMinInsts_ =
|
||||
parseClampedUInt(*Root, "function_outline_min_insts", 6, 3, 64);
|
||||
Cfg.OpaqueFieldMaxPerFn_ =
|
||||
parseClampedUInt(*Root, "opaque_field_max_per_fn", 32, 0, 256);
|
||||
Cfg.BBSplitMaxPerFn_ =
|
||||
parseClampedUInt(*Root, "bb_split_max_per_fn", 4, 0, 16);
|
||||
Cfg.BBSplitMinInsts_ =
|
||||
parseClampedUInt(*Root, "bb_split_min_insts", 8, 4, 64);
|
||||
if (auto NlMba = Root->getBoolean("arithmetic_nonlinear_mba")) {
|
||||
Cfg.ArithmeticNonlinearMBA_ = *NlMba;
|
||||
}
|
||||
if (auto Oz = Root->getBoolean("opaque_const_opaque_zero")) {
|
||||
Cfg.OpaqueConstOpaqueZero_ = *Oz;
|
||||
}
|
||||
|
||||
appendStringArray(*Root, "exempt_path_substrings",
|
||||
Cfg.ExemptPathSubstrings_);
|
||||
appendStringArray(*Root, "exempt_function_prefixes",
|
||||
Cfg.ExemptFunctionPrefixes_);
|
||||
appendStringArray(*Root, "scrub_path_substrings",
|
||||
Cfg.ScrubPathSubstrings_);
|
||||
appendRuleArray(*Root, "string_encrypt_targets",
|
||||
Cfg.StringEncryptTargets_);
|
||||
appendRuleArray(*Root, "string_encrypt_objc_targets",
|
||||
Cfg.StringEncryptObjCTargets_);
|
||||
appendRuleArray(*Root, "string_encrypt_swift_targets",
|
||||
Cfg.StringEncryptSwiftTargets_);
|
||||
appendRuleArray(*Root, "string_encrypt_stack_targets",
|
||||
Cfg.StringEncryptStackTargets_);
|
||||
appendStringReplaceRules(*Root, "string_replace_rules",
|
||||
Cfg.StringReplaceRules_);
|
||||
appendRuleArray(*Root, "indirect_call_targets",
|
||||
Cfg.IndirectCallTargets_);
|
||||
appendStringArray(*Root, "indirect_call_same_image_prefixes",
|
||||
Cfg.IndirectCallSameImagePrefixes_);
|
||||
appendRuleArray(*Root, "flatten_targets", Cfg.FlattenTargets_);
|
||||
appendRuleArray(*Root, "opaque_const_targets", Cfg.OpaqueConstTargets_);
|
||||
appendStringArray(*Root, "opaque_const_exempt_functions",
|
||||
Cfg.OpaqueConstExemptFunctions_);
|
||||
appendRuleArray(*Root, "arithmetic_targets", Cfg.ArithmeticTargets_);
|
||||
appendStringArray(*Root, "arithmetic_exempt_functions",
|
||||
Cfg.ArithmeticExemptFunctions_);
|
||||
appendRuleArray(*Root, "indirect_branch_targets",
|
||||
Cfg.IndirectBranchTargets_);
|
||||
appendStringArray(*Root, "indirect_branch_exempt_functions",
|
||||
Cfg.IndirectBranchExemptFunctions_);
|
||||
appendRuleArray(*Root, "anti_hooking_targets", Cfg.AntiHookingTargets_);
|
||||
appendStringArray(*Root, "anti_hooking_exempt_functions",
|
||||
Cfg.AntiHookingExemptFunctions_);
|
||||
appendRuleArray(*Root, "function_outline_targets",
|
||||
Cfg.FunctionOutlineTargets_);
|
||||
appendStringArray(*Root, "function_outline_exempt_functions",
|
||||
Cfg.FunctionOutlineExemptFunctions_);
|
||||
appendRuleArray(*Root, "opaque_field_targets", Cfg.OpaqueFieldTargets_);
|
||||
appendStringArray(*Root, "opaque_field_exempt_functions",
|
||||
Cfg.OpaqueFieldExemptFunctions_);
|
||||
appendRuleArray(*Root, "bb_split_targets", Cfg.BBSplitTargets_);
|
||||
appendStringArray(*Root, "bb_split_exempt_functions",
|
||||
Cfg.BBSplitExemptFunctions_);
|
||||
}
|
||||
}
|
||||
|
||||
Cfg.collectAnnotations(M);
|
||||
|
||||
AuditOut.Mode = IGModeOpt;
|
||||
AuditOut.PassFilter = IGPassFilterOpt;
|
||||
AuditOut.Seed = Cfg.Seed_;
|
||||
AuditOut.SourcePath = Cfg.SourcePath_;
|
||||
AuditOut.ModuleId = M.getModuleIdentifier();
|
||||
AuditOut.IndirectCallDualTable = Cfg.IndirectCallDualTable_;
|
||||
for (const auto *SetPtr :
|
||||
{&Cfg.AnnotatedFlatten_, &Cfg.AnnotatedStr_, &Cfg.AnnotatedIcall_,
|
||||
&Cfg.AnnotatedConst_, &Cfg.AnnotatedArith_, &Cfg.AnnotatedIbr_,
|
||||
&Cfg.AnnotatedAntiHook_, &Cfg.AnnotatedOutline_,
|
||||
&Cfg.AnnotatedField_, &Cfg.AnnotatedBBSplit_}) {
|
||||
for (const auto &Item : *SetPtr)
|
||||
AuditOut.AnnotatedTargets.push_back(Item.getKey().str());
|
||||
}
|
||||
|
||||
return Cfg;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isStringEncryptionEnabled() const {
|
||||
if (Mode_ == ObfMode::Off || Mode_ == ObfMode::Noop)
|
||||
return false;
|
||||
if (Mode_ == ObfMode::StrOnly)
|
||||
return true;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::StrOnly;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isIndirectCallEnabled() const {
|
||||
if (Mode_ != ObfMode::Full)
|
||||
return false;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::IcallOnly;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isFlatteningEnabled() const {
|
||||
if (Mode_ != ObfMode::Full)
|
||||
return false;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::FlaOnly;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isOpaqueConstantsEnabled() const {
|
||||
if (Mode_ != ObfMode::Full)
|
||||
return false;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::OpaqueConstOnly;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isArithmeticEnabled() const {
|
||||
if (Mode_ != ObfMode::Full)
|
||||
return false;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::ArithOnly;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isIndirectBranchEnabled() const {
|
||||
if (Mode_ != ObfMode::Full)
|
||||
return false;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::IbrOnly;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isAntiHookingEnabled() const {
|
||||
if (Mode_ != ObfMode::Full)
|
||||
return false;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::AntiHookOnly;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isFunctionOutlineEnabled() const {
|
||||
if (Mode_ != ObfMode::Full)
|
||||
return false;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::OutlineOnly;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isOpaqueFieldEnabled() const {
|
||||
if (Mode_ != ObfMode::Full)
|
||||
return false;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::FieldOnly;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isBBSplitEnabled() const {
|
||||
if (Mode_ != ObfMode::Full)
|
||||
return false;
|
||||
return Filter_ == PassFilter::All || Filter_ == PassFilter::BBSplitOnly;
|
||||
}
|
||||
|
||||
std::string IGPolicyConfig::resolveFunctionSourcePath(const Function &F,
|
||||
StringRef FallbackPath) {
|
||||
if (const DISubprogram *SP = F.getSubprogram()) {
|
||||
StringRef File = SP->getFilename();
|
||||
StringRef Dir = SP->getDirectory();
|
||||
if (!File.empty()) {
|
||||
if (sys::path::is_absolute(File) || Dir.empty())
|
||||
return File.str();
|
||||
SmallString<256> Joined(Dir);
|
||||
sys::path::append(Joined, File);
|
||||
return Joined.str().str();
|
||||
}
|
||||
}
|
||||
if (!FallbackPath.empty())
|
||||
return FallbackPath.str();
|
||||
if (const Module *M = F.getParent())
|
||||
return M->getSourceFileName();
|
||||
return "";
|
||||
}
|
||||
|
||||
void IGPolicyConfig::collectAnnotations(const Module &M) {
|
||||
const GlobalVariable *GA = M.getNamedGlobal("llvm.global.annotations");
|
||||
if (!GA || !GA->hasInitializer())
|
||||
return;
|
||||
const auto *CA = dyn_cast<ConstantArray>(GA->getInitializer());
|
||||
if (!CA)
|
||||
return;
|
||||
for (const Use &Op : CA->operands()) {
|
||||
const auto *CS = dyn_cast<ConstantStruct>(Op.get());
|
||||
if (!CS || CS->getNumOperands() < 2)
|
||||
continue;
|
||||
const Value *FnVal = CS->getOperand(0)->stripPointerCasts();
|
||||
const Value *AnnVal = CS->getOperand(1)->stripPointerCasts();
|
||||
const auto *Fn = dyn_cast<Function>(FnVal);
|
||||
const auto *AnnGV = dyn_cast<GlobalVariable>(AnnVal);
|
||||
if (!Fn || !AnnGV || !AnnGV->hasInitializer())
|
||||
continue;
|
||||
const auto *CDS = dyn_cast<ConstantDataSequential>(AnnGV->getInitializer());
|
||||
if (!CDS || !CDS->isString())
|
||||
continue;
|
||||
StringRef Tag = CDS->getAsCString();
|
||||
StringRef Name = Fn->getName();
|
||||
if (Tag == "ig_exempt")
|
||||
AnnotatedExempt_.insert(Name);
|
||||
else if (Tag == "ig_flatten")
|
||||
AnnotatedFlatten_.insert(Name);
|
||||
else if (Tag == "ig_str")
|
||||
AnnotatedStr_.insert(Name);
|
||||
else if (Tag == "ig_icall")
|
||||
AnnotatedIcall_.insert(Name);
|
||||
else if (Tag == "ig_const")
|
||||
AnnotatedConst_.insert(Name);
|
||||
else if (Tag == "ig_arith")
|
||||
AnnotatedArith_.insert(Name);
|
||||
else if (Tag == "ig_ibr")
|
||||
AnnotatedIbr_.insert(Name);
|
||||
else if (Tag == "ig_antihook")
|
||||
AnnotatedAntiHook_.insert(Name);
|
||||
else if (Tag == "ig_outline")
|
||||
AnnotatedOutline_.insert(Name);
|
||||
else if (Tag == "ig_field")
|
||||
AnnotatedField_.insert(Name);
|
||||
else if (Tag == "ig_bbsplit")
|
||||
AnnotatedBBSplit_.insert(Name);
|
||||
}
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::hasAnnotation(const Function &F, StringRef Tag) const {
|
||||
if (Tag == "ig_exempt")
|
||||
return AnnotatedExempt_.contains(F.getName());
|
||||
if (Tag == "ig_flatten")
|
||||
return AnnotatedFlatten_.contains(F.getName());
|
||||
if (Tag == "ig_str")
|
||||
return AnnotatedStr_.contains(F.getName());
|
||||
if (Tag == "ig_icall")
|
||||
return AnnotatedIcall_.contains(F.getName());
|
||||
if (Tag == "ig_const")
|
||||
return AnnotatedConst_.contains(F.getName());
|
||||
if (Tag == "ig_arith")
|
||||
return AnnotatedArith_.contains(F.getName());
|
||||
if (Tag == "ig_ibr")
|
||||
return AnnotatedIbr_.contains(F.getName());
|
||||
if (Tag == "ig_antihook")
|
||||
return AnnotatedAntiHook_.contains(F.getName());
|
||||
if (Tag == "ig_outline")
|
||||
return AnnotatedOutline_.contains(F.getName());
|
||||
if (Tag == "ig_field")
|
||||
return AnnotatedField_.contains(F.getName());
|
||||
if (Tag == "ig_bbsplit")
|
||||
return AnnotatedBBSplit_.contains(F.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isModuleExempt(const Module &M) const {
|
||||
StringRef Candidate =
|
||||
!SourcePath_.empty() ? StringRef(SourcePath_) : M.getSourceFileName();
|
||||
for (const std::string &Ex : ExemptPathSubstrings_) {
|
||||
if (!Candidate.empty() && Candidate.contains(Ex))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::isFunctionExempt(const Function &F) const {
|
||||
if (F.isDeclaration())
|
||||
return true;
|
||||
if (hasAnnotation(F, "ig_exempt"))
|
||||
return true;
|
||||
std::string CleanName = stripLeadingObjCMarker(F.getName());
|
||||
for (const std::string &Prefix : ExemptFunctionPrefixes_) {
|
||||
if (StringRef(CleanName).starts_with(Prefix))
|
||||
return true;
|
||||
}
|
||||
std::string FuncPath = resolveFunctionSourcePath(F, SourcePath_);
|
||||
for (const std::string &Ex : ExemptPathSubstrings_) {
|
||||
if ((!FuncPath.empty() && StringRef(FuncPath).contains(Ex)) ||
|
||||
(!SourcePath_.empty() && StringRef(SourcePath_).contains(Ex))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const TargetRule *
|
||||
IGPolicyConfig::findMatchingRule(const std::vector<TargetRule> &Rules,
|
||||
const Function &F) const {
|
||||
std::string FuncPath = resolveFunctionSourcePath(F, SourcePath_);
|
||||
std::string CleanName = stripLeadingObjCMarker(F.getName());
|
||||
StringRef ModuleSrc =
|
||||
F.getParent() ? StringRef(F.getParent()->getSourceFileName())
|
||||
: StringRef();
|
||||
for (const TargetRule &R : Rules) {
|
||||
bool PathOk = R.PathContains.empty() ||
|
||||
StringRef(FuncPath).contains(R.PathContains) ||
|
||||
StringRef(SourcePath_).contains(R.PathContains) ||
|
||||
StringRef(ModuleSrc).contains(R.PathContains);
|
||||
if (!PathOk)
|
||||
continue;
|
||||
bool FnOk = R.FunctionContains.empty() ||
|
||||
StringRef(CleanName).contains(R.FunctionContains) ||
|
||||
F.getName().contains(R.FunctionContains);
|
||||
if (FnOk)
|
||||
return &R;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::matchesAnyRule(const std::vector<TargetRule> &Rules,
|
||||
const Function &F) const {
|
||||
return findMatchingRule(Rules, F) != nullptr;
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldEncryptStringsInFunction(const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_str") || hasAnnotation(F, "ig_flatten"))
|
||||
return true;
|
||||
return matchesAnyRule(StringEncryptTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldEncryptObjCStringsInFunction(
|
||||
const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
return matchesAnyRule(StringEncryptObjCTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldEncryptSwiftStringsInFunction(
|
||||
const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
return matchesAnyRule(StringEncryptSwiftTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldStackEncryptStringsInFunction(
|
||||
const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
return matchesAnyRule(StringEncryptStackTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldIndirectCallInFunction(const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_icall"))
|
||||
return true;
|
||||
return matchesAnyRule(IndirectCallTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldFlattenFunction(const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_flatten"))
|
||||
return true;
|
||||
return matchesAnyRule(FlattenTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldObfuscateConstantsInFunction(
|
||||
const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_const"))
|
||||
return true;
|
||||
return matchesAnyRule(OpaqueConstTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldObfuscateArithmeticInFunction(
|
||||
const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_arith"))
|
||||
return true;
|
||||
return matchesAnyRule(ArithmeticTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldIndirectBranchInFunction(const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_ibr"))
|
||||
return true;
|
||||
return matchesAnyRule(IndirectBranchTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldAntiHookFunction(const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_antihook"))
|
||||
return true;
|
||||
return matchesAnyRule(AntiHookingTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldOutlineFunction(const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_outline"))
|
||||
return true;
|
||||
return matchesAnyRule(FunctionOutlineTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldObfuscateFieldAccessInFunction(
|
||||
const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_field"))
|
||||
return true;
|
||||
return matchesAnyRule(OpaqueFieldTargets_, F);
|
||||
}
|
||||
|
||||
bool IGPolicyConfig::shouldSplitBasicBlocksInFunction(const Function &F) const {
|
||||
if (isFunctionExempt(F))
|
||||
return false;
|
||||
if (hasAnnotation(F, "ig_bbsplit"))
|
||||
return true;
|
||||
return matchesAnyRule(BBSplitTargets_, F);
|
||||
}
|
||||
|
||||
const TargetRule *
|
||||
IGPolicyConfig::findArithmeticRule(const Function &F) const {
|
||||
return findMatchingRule(ArithmeticTargets_, F);
|
||||
}
|
||||
|
||||
const TargetRule *
|
||||
IGPolicyConfig::findOpaqueConstRule(const Function &F) const {
|
||||
return findMatchingRule(OpaqueConstTargets_, F);
|
||||
}
|
||||
|
||||
const TargetRule *
|
||||
IGPolicyConfig::findBBSplitRule(const Function &F) const {
|
||||
return findMatchingRule(BBSplitTargets_, F);
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,983 @@
|
||||
#include "IGPolicyConfig.h"
|
||||
#include "llvm/ADT/DenseMap.h"
|
||||
#include "llvm/ADT/SmallPtrSet.h"
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/ADT/StringExtras.h"
|
||||
#include "llvm/ADT/StringSet.h"
|
||||
#include "llvm/IR/Constants.h"
|
||||
#include "llvm/IR/DebugInfoMetadata.h"
|
||||
#include "llvm/IR/Function.h"
|
||||
#include "llvm/IR/GlobalAlias.h"
|
||||
#include "llvm/IR/GlobalVariable.h"
|
||||
#include "llvm/IR/IRBuilder.h"
|
||||
#include "llvm/IR/Instructions.h"
|
||||
#include "llvm/IR/IntrinsicsAArch64.h"
|
||||
#include "llvm/IR/Module.h"
|
||||
#include "llvm/IR/Operator.h"
|
||||
#include "llvm/Support/SHA256.h"
|
||||
#include "llvm/TargetParser/Triple.h"
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace igobf {
|
||||
namespace {
|
||||
|
||||
void collectCompilerUsed(const Module &M, StringRef Name,
|
||||
SmallPtrSetImpl<const GlobalValue *> &Out) {
|
||||
const GlobalVariable *GV = M.getNamedGlobal(Name);
|
||||
if (!GV || !GV->hasInitializer())
|
||||
return;
|
||||
const auto *CA = dyn_cast<ConstantArray>(GV->getInitializer());
|
||||
if (!CA)
|
||||
return;
|
||||
for (const Use &U : CA->operands()) {
|
||||
if (const auto *Target = dyn_cast<GlobalValue>(U.get()->stripPointerCasts()))
|
||||
Out.insert(Target);
|
||||
}
|
||||
}
|
||||
|
||||
bool isPassThroughConstantExpr(const ConstantExpr *CE) {
|
||||
unsigned Op = CE->getOpcode();
|
||||
if (Op == Instruction::BitCast || Op == Instruction::AddrSpaceCast)
|
||||
return true;
|
||||
if (Op == Instruction::GetElementPtr) {
|
||||
if (const auto *GEP = dyn_cast<GEPOperator>(CE))
|
||||
return GEP->hasAllZeroIndices();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool containsRootValue(const Value *V, const GlobalVariable *Root,
|
||||
bool AllowSwiftBias) {
|
||||
if (V == Root)
|
||||
return true;
|
||||
const auto *CE = dyn_cast<ConstantExpr>(V);
|
||||
if (!CE)
|
||||
return false;
|
||||
if (isPassThroughConstantExpr(CE))
|
||||
return containsRootValue(CE->getOperand(0), Root, AllowSwiftBias);
|
||||
if (!AllowSwiftBias)
|
||||
return false;
|
||||
switch (CE->getOpcode()) {
|
||||
case Instruction::PtrToInt:
|
||||
case Instruction::IntToPtr:
|
||||
return containsRootValue(CE->getOperand(0), Root, true);
|
||||
case Instruction::Sub:
|
||||
return isa<ConstantInt>(CE->getOperand(1)) &&
|
||||
containsRootValue(CE->getOperand(0), Root, true);
|
||||
case Instruction::Add:
|
||||
case Instruction::Or: {
|
||||
bool LeftRoot = isa<ConstantInt>(CE->getOperand(1)) &&
|
||||
containsRootValue(CE->getOperand(0), Root, true);
|
||||
bool RightRoot = isa<ConstantInt>(CE->getOperand(0)) &&
|
||||
containsRootValue(CE->getOperand(1), Root, true);
|
||||
return LeftRoot || RightRoot;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const Value *unwrapBaseValue(const Value *V) {
|
||||
while (const auto *CE = dyn_cast<ConstantExpr>(V)) {
|
||||
if (!isPassThroughConstantExpr(CE))
|
||||
break;
|
||||
V = CE->getOperand(0);
|
||||
}
|
||||
return V;
|
||||
}
|
||||
|
||||
bool isSafePhiPredBlock(const BasicBlock *PredBB) {
|
||||
if (!PredBB || PredBB->isEHPad())
|
||||
return false;
|
||||
const Instruction *Term = PredBB->getTerminator();
|
||||
if (!Term || isa<CatchSwitchInst>(Term) || isa<IndirectBrInst>(Term))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Verify that EVERY transitive user of Root is a controlled instruction inside
|
||||
// a function matching FnPred (or safe predecessor edges of PHINodes).
|
||||
bool collectControlledUsersEx(const GlobalVariable *Root, bool AllowSwiftBias,
|
||||
function_ref<bool(const Function &)> FnPred,
|
||||
SmallVectorImpl<Instruction *> &OutInsts) {
|
||||
SmallVector<const Value *, 8> Worklist{Root};
|
||||
SmallPtrSet<const Value *, 8> Visited{Root};
|
||||
SmallPtrSet<Instruction *, 8> SeenInsts;
|
||||
|
||||
while (!Worklist.empty()) {
|
||||
const Value *Cur = Worklist.pop_back_val();
|
||||
for (const Use &U : Cur->uses()) {
|
||||
const User *Usr = U.getUser();
|
||||
if (const auto *CE = dyn_cast<ConstantExpr>(Usr)) {
|
||||
if (!containsRootValue(CE, Root, AllowSwiftBias))
|
||||
return false;
|
||||
if (Visited.insert(CE).second)
|
||||
Worklist.push_back(CE);
|
||||
continue;
|
||||
}
|
||||
if (isa<Constant>(Usr))
|
||||
return false;
|
||||
|
||||
const auto *Inst = dyn_cast<Instruction>(Usr);
|
||||
if (!Inst || !Inst->getParent() || Inst->getParent()->isEHPad())
|
||||
return false;
|
||||
if (isa<LandingPadInst>(Inst) || Inst->isEHPad())
|
||||
return false;
|
||||
if (const auto *CB = dyn_cast<CallBase>(Inst)) {
|
||||
if (&U == &CB->getCalledOperandUse())
|
||||
return false;
|
||||
}
|
||||
|
||||
if (const auto *PN = dyn_cast<PHINode>(Inst)) {
|
||||
for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
|
||||
if (PN->getIncomingValue(i) == Cur &&
|
||||
!isSafePhiPredBlock(PN->getIncomingBlock(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const Function *ParentF = Inst->getFunction();
|
||||
if (!ParentF || !FnPred(*ParentF))
|
||||
return false;
|
||||
|
||||
Instruction *MutableInst = const_cast<Instruction *>(Inst);
|
||||
if (SeenInsts.insert(MutableInst).second)
|
||||
OutInsts.push_back(MutableInst);
|
||||
}
|
||||
}
|
||||
return !OutInsts.empty();
|
||||
}
|
||||
|
||||
Value *materializeValueForRoot(IRBuilder<> &B, Value *Orig,
|
||||
const GlobalVariable *Root, Value *Replacement) {
|
||||
if (Orig == Root)
|
||||
return Replacement;
|
||||
auto *CE = dyn_cast<ConstantExpr>(Orig);
|
||||
if (!CE)
|
||||
return Orig;
|
||||
switch (CE->getOpcode()) {
|
||||
case Instruction::BitCast: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return (Inner->getType() == CE->getType())
|
||||
? Inner
|
||||
: B.CreateBitCast(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::AddrSpaceCast: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return (Inner->getType() == CE->getType())
|
||||
? Inner
|
||||
: B.CreateAddrSpaceCast(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::GetElementPtr: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return (Inner->getType() == CE->getType())
|
||||
? Inner
|
||||
: B.CreateBitCast(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::PtrToInt: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreatePtrToInt(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::IntToPtr: {
|
||||
Value *Inner =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreateIntToPtr(Inner, CE->getType());
|
||||
}
|
||||
case Instruction::Sub: {
|
||||
Value *LHS =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreateSub(LHS, CE->getOperand(1));
|
||||
}
|
||||
case Instruction::Add: {
|
||||
if (containsRootValue(CE->getOperand(0), Root, true)) {
|
||||
Value *LHS =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreateAdd(LHS, CE->getOperand(1));
|
||||
}
|
||||
Value *RHS =
|
||||
materializeValueForRoot(B, CE->getOperand(1), Root, Replacement);
|
||||
return B.CreateAdd(CE->getOperand(0), RHS);
|
||||
}
|
||||
case Instruction::Or: {
|
||||
if (containsRootValue(CE->getOperand(0), Root, true)) {
|
||||
Value *LHS =
|
||||
materializeValueForRoot(B, CE->getOperand(0), Root, Replacement);
|
||||
return B.CreateOr(LHS, CE->getOperand(1));
|
||||
}
|
||||
Value *RHS =
|
||||
materializeValueForRoot(B, CE->getOperand(1), Root, Replacement);
|
||||
return B.CreateOr(CE->getOperand(0), RHS);
|
||||
}
|
||||
default:
|
||||
return Orig;
|
||||
}
|
||||
}
|
||||
|
||||
void rewriteUsersWithDecryptFn(
|
||||
GlobalVariable *RootGV, Function *DecFn, bool AllowSwiftBias,
|
||||
ArrayRef<Instruction *> LeafInsts, StringSet<> &SeenFunctions,
|
||||
std::vector<std::string> &TouchedFunctions) {
|
||||
for (Instruction *UI : LeafInsts) {
|
||||
if (auto *PN = dyn_cast<PHINode>(UI)) {
|
||||
DenseMap<std::pair<BasicBlock *, Value *>, Value *> EdgeCache;
|
||||
for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
|
||||
Value *InVal = PN->getIncomingValue(i);
|
||||
if (!containsRootValue(InVal, RootGV, AllowSwiftBias))
|
||||
continue;
|
||||
BasicBlock *PredBB = PN->getIncomingBlock(i);
|
||||
auto CacheKey = std::make_pair(PredBB, InVal);
|
||||
Value *ReplVal = nullptr;
|
||||
auto It = EdgeCache.find(CacheKey);
|
||||
if (It != EdgeCache.end()) {
|
||||
ReplVal = It->second;
|
||||
} else {
|
||||
Instruction *Term = PredBB->getTerminator();
|
||||
IRBuilder<> EdgeB(Term);
|
||||
CallInst *DecCall = EdgeB.CreateCall(DecFn, {}, "ig.str");
|
||||
DecCall->setDebugLoc(Term->getDebugLoc());
|
||||
ReplVal = AllowSwiftBias
|
||||
? materializeValueForRoot(EdgeB, InVal, RootGV, DecCall)
|
||||
: static_cast<Value *>(DecCall);
|
||||
EdgeCache[CacheKey] = ReplVal;
|
||||
}
|
||||
PN->setIncomingValue(i, ReplVal);
|
||||
}
|
||||
} else {
|
||||
IRBuilder<> B(UI);
|
||||
CallInst *DecCall = B.CreateCall(DecFn, {}, "ig.str");
|
||||
DecCall->setDebugLoc(UI->getDebugLoc());
|
||||
for (unsigned i = 0, e = UI->getNumOperands(); i < e; ++i) {
|
||||
Value *Op = UI->getOperand(i);
|
||||
if (containsRootValue(Op, RootGV, AllowSwiftBias)) {
|
||||
Value *ReplVal = AllowSwiftBias
|
||||
? materializeValueForRoot(B, Op, RootGV, DecCall)
|
||||
: static_cast<Value *>(DecCall);
|
||||
UI->setOperand(i, ReplVal);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (const Function *ParentF = UI->getFunction()) {
|
||||
if (SeenFunctions.insert(ParentF->getName()).second)
|
||||
TouchedFunctions.push_back(ParentF->getName().str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Function *createDecryptFunction(Module &M, uint64_t Id, StringRef FnPrefix,
|
||||
GlobalVariable *EncGV, GlobalVariable *KeyGV,
|
||||
GlobalVariable *BufGV, GlobalVariable *StateGV,
|
||||
GlobalVariable *RetGV, uint64_t Len,
|
||||
Align BufAlign) {
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
Type *PtrTy = PointerType::getUnqual(Ctx);
|
||||
Type *I32Ty = Type::getInt32Ty(Ctx);
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
Type *I8Ty = Type::getInt8Ty(Ctx);
|
||||
ArrayType *ArrTy = ArrayType::get(I8Ty, Len);
|
||||
|
||||
FunctionType *FnTy = FunctionType::get(PtrTy, false);
|
||||
std::string FnName = (FnPrefix + Twine(Id)).str();
|
||||
Function *Fn =
|
||||
Function::Create(FnTy, GlobalValue::InternalLinkage, FnName, &M);
|
||||
Fn->addFnAttr(Attribute::NoInline);
|
||||
Fn->addFnAttr(Attribute::NoBuiltin);
|
||||
Fn->addFnAttr(Attribute::NoUnwind);
|
||||
Fn->setDSOLocal(true);
|
||||
|
||||
BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Fn);
|
||||
BasicBlock *CasBB = BasicBlock::Create(Ctx, "cas", Fn);
|
||||
BasicBlock *WaitBB = BasicBlock::Create(Ctx, "wait", Fn);
|
||||
BasicBlock *LoopBB = BasicBlock::Create(Ctx, "loop", Fn);
|
||||
BasicBlock *DoneBB = BasicBlock::Create(Ctx, "done", Fn);
|
||||
BasicBlock *RetBB = BasicBlock::Create(Ctx, "ret", Fn);
|
||||
|
||||
// Entry: fast path acquire load == 2
|
||||
IRBuilder<> B(EntryBB);
|
||||
LoadInst *FastState = B.CreateLoad(I32Ty, StateGV, false, "st.fast");
|
||||
FastState->setAlignment(Align(4));
|
||||
FastState->setAtomic(AtomicOrdering::Acquire);
|
||||
Value *Ready =
|
||||
B.CreateICmpEQ(FastState, ConstantInt::get(I32Ty, 2), "is.ready");
|
||||
B.CreateCondBr(Ready, RetBB, CasBB);
|
||||
|
||||
// CAS: try claiming 0 -> 1
|
||||
B.SetInsertPoint(CasBB);
|
||||
AtomicCmpXchgInst *CX = B.CreateAtomicCmpXchg(
|
||||
StateGV, ConstantInt::get(I32Ty, 0), ConstantInt::get(I32Ty, 1),
|
||||
Align(4), AtomicOrdering::AcquireRelease, AtomicOrdering::Acquire);
|
||||
Value *Won = B.CreateExtractValue(CX, 1, "won");
|
||||
B.CreateCondBr(Won, LoopBB, WaitBB);
|
||||
|
||||
// Wait: spin with optional AArch64 yield hint until winner releases 2
|
||||
B.SetInsertPoint(WaitBB);
|
||||
if (Triple(M.getTargetTriple()).isAArch64()) {
|
||||
Function *HintFn =
|
||||
Intrinsic::getOrInsertDeclaration(&M, Intrinsic::aarch64_hint);
|
||||
B.CreateCall(HintFn, {ConstantInt::get(I32Ty, 1)});
|
||||
}
|
||||
LoadInst *WaitState = B.CreateLoad(I32Ty, StateGV, false, "st.wait");
|
||||
WaitState->setAlignment(Align(4));
|
||||
WaitState->setAtomic(AtomicOrdering::Acquire);
|
||||
Value *NowReady =
|
||||
B.CreateICmpEQ(WaitState, ConstantInt::get(I32Ty, 2), "wait.ready");
|
||||
B.CreateCondBr(NowReady, RetBB, WaitBB);
|
||||
|
||||
// Loop: volatile decrypt bytes from enc ^ key into internal global buffer
|
||||
B.SetInsertPoint(LoopBB);
|
||||
PHINode *Idx = B.CreatePHI(I64Ty, 2, "idx");
|
||||
Idx->addIncoming(ConstantInt::get(I64Ty, 0), CasBB);
|
||||
Value *Zero64 = ConstantInt::get(I64Ty, 0);
|
||||
Value *EncPtr = B.CreateInBoundsGEP(ArrTy, EncGV, {Zero64, Idx}, "enc.ptr");
|
||||
Value *KeyPtr = B.CreateInBoundsGEP(ArrTy, KeyGV, {Zero64, Idx}, "key.ptr");
|
||||
Value *BufPtr = B.CreateInBoundsGEP(ArrTy, BufGV, {Zero64, Idx}, "buf.ptr");
|
||||
LoadInst *EncByte = B.CreateLoad(I8Ty, EncPtr, /*isVolatile=*/true, "eb");
|
||||
LoadInst *KeyByte = B.CreateLoad(I8Ty, KeyPtr, /*isVolatile=*/true, "kb");
|
||||
Value *PlainByte = B.CreateXor(EncByte, KeyByte, "pb");
|
||||
StoreInst *St = B.CreateStore(PlainByte, BufPtr, /*isVolatile=*/true);
|
||||
St->setAlignment(Align(1));
|
||||
(void)BufAlign;
|
||||
Value *NextIdx =
|
||||
B.CreateAdd(Idx, ConstantInt::get(I64Ty, 1), "next", /*HasNUW=*/true);
|
||||
Idx->addIncoming(NextIdx, LoopBB);
|
||||
Value *LoopDone =
|
||||
B.CreateICmpEQ(NextIdx, ConstantInt::get(I64Ty, Len), "loop.done");
|
||||
B.CreateCondBr(LoopDone, DoneBB, LoopBB);
|
||||
|
||||
// Done: release store 2 so waiting and future callers observe decrypted bytes
|
||||
B.SetInsertPoint(DoneBB);
|
||||
StoreInst *Publish =
|
||||
B.CreateStore(ConstantInt::get(I32Ty, 2), StateGV, false);
|
||||
Publish->setAlignment(Align(4));
|
||||
Publish->setAtomic(AtomicOrdering::Release);
|
||||
B.CreateBr(RetBB);
|
||||
|
||||
// Ret: return target object base pointer (BufGV or CFConstantString)
|
||||
B.SetInsertPoint(RetBB);
|
||||
B.CreateRet(RetGV);
|
||||
|
||||
return Fn;
|
||||
}
|
||||
|
||||
bool isStackAllowlistedCallee(StringRef RawName, bool &OutIsStrstr,
|
||||
bool &OutIsMemcpySrc) {
|
||||
OutIsStrstr = false;
|
||||
OutIsMemcpySrc = false;
|
||||
StringRef Name = RawName;
|
||||
if (Name.starts_with("\x01_"))
|
||||
Name = Name.drop_front(2);
|
||||
else if (Name.starts_with("\x01"))
|
||||
Name = Name.drop_front(1);
|
||||
if (Name == "strstr") {
|
||||
OutIsStrstr = true;
|
||||
return true;
|
||||
}
|
||||
if (Name.starts_with("llvm.memcpy.")) {
|
||||
OutIsMemcpySrc = true;
|
||||
return true;
|
||||
}
|
||||
static constexpr const char *kAllowed[] = {
|
||||
"strcmp", "strncmp",
|
||||
"strcasecmp", "strncasecmp",
|
||||
"strlen", "memcmp",
|
||||
"access", "stat",
|
||||
"lstat", "open",
|
||||
"fopen", "dlopen",
|
||||
"dlsym", "getenv",
|
||||
"sysctlbyname", "IG_dispatch_open",
|
||||
"IG_dispatch_stat", "IG_dispatch_lstat",
|
||||
"IG_dispatch_access", "ig_ends_with",
|
||||
"ig_strncmp", "ig_strcmp",
|
||||
"ig_strlen",
|
||||
};
|
||||
for (const char *Allowed : kAllowed) {
|
||||
if (Name == Allowed)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool canUseMultiFnStackDecrypt(const GlobalVariable *GV, uint64_t Len,
|
||||
const IGPolicyConfig &Policy,
|
||||
ArrayRef<Instruction *> LeafInsts) {
|
||||
uint64_t MaxStackLen = Policy.stringEncryptStackMaxLen();
|
||||
if (MaxStackLen == 0 || Len == 0 || Len > MaxStackLen || LeafInsts.empty())
|
||||
return false;
|
||||
|
||||
for (Instruction *UI : LeafInsts) {
|
||||
auto *CI = dyn_cast<CallInst>(UI);
|
||||
if (!CI || CI->isMustTailCall() || CI->isInlineAsm())
|
||||
return false;
|
||||
Function *ParentF = CI->getFunction();
|
||||
if (!ParentF || ParentF->empty() || ParentF->getEntryBlock().isEHPad() ||
|
||||
!Policy.shouldStackEncryptStringsInFunction(*ParentF)) {
|
||||
return false;
|
||||
}
|
||||
Function *Callee = CI->getCalledFunction();
|
||||
if (!Callee)
|
||||
return false;
|
||||
bool IsStrstr = false;
|
||||
bool IsMemcpySrc = false;
|
||||
if (!isStackAllowlistedCallee(Callee->getName(), IsStrstr, IsMemcpySrc))
|
||||
return false;
|
||||
|
||||
bool FoundOp = false;
|
||||
for (unsigned i = 0, e = CI->getNumOperands(); i < e; ++i) {
|
||||
Value *Op = CI->getOperand(i);
|
||||
if (unwrapBaseValue(Op) == GV) {
|
||||
if (!CI->isArgOperand(&CI->getOperandUse(i)) ||
|
||||
!Op->getType()->isPointerTy() ||
|
||||
Op->stripPointerCasts() != GV) {
|
||||
return false;
|
||||
}
|
||||
if ((IsStrstr || IsMemcpySrc) && i != 1)
|
||||
return false;
|
||||
FoundOp = true;
|
||||
}
|
||||
}
|
||||
if (!FoundOp)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Function *getOrCreateStackDecryptFn(Module &M) {
|
||||
if (Function *Existing = M.getFunction("__ig_str_dec_stack"))
|
||||
return Existing;
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
Type *PtrTy = PointerType::getUnqual(Ctx);
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
Type *I8Ty = Type::getInt8Ty(Ctx);
|
||||
FunctionType *FnTy = FunctionType::get(Type::getVoidTy(Ctx),
|
||||
{PtrTy, PtrTy, PtrTy, I64Ty}, false);
|
||||
Function *Fn = Function::Create(FnTy, GlobalValue::InternalLinkage,
|
||||
"__ig_str_dec_stack", &M);
|
||||
Fn->addFnAttr(Attribute::NoInline);
|
||||
Fn->addFnAttr(Attribute::NoUnwind);
|
||||
|
||||
BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Fn);
|
||||
BasicBlock *LoopBB = BasicBlock::Create(Ctx, "loop", Fn);
|
||||
BasicBlock *ExitBB = BasicBlock::Create(Ctx, "exit", Fn);
|
||||
|
||||
Value *Dst = Fn->getArg(0);
|
||||
Value *Enc = Fn->getArg(1);
|
||||
Value *Key = Fn->getArg(2);
|
||||
Value *LenArg = Fn->getArg(3);
|
||||
|
||||
IRBuilder<> EB(EntryBB);
|
||||
Value *HasBytes = EB.CreateICmpUGT(LenArg, ConstantInt::get(I64Ty, 0));
|
||||
EB.CreateCondBr(HasBytes, LoopBB, ExitBB);
|
||||
|
||||
IRBuilder<> LB(LoopBB);
|
||||
PHINode *Idx = LB.CreatePHI(I64Ty, 2, "idx");
|
||||
Idx->addIncoming(ConstantInt::get(I64Ty, 0), EntryBB);
|
||||
Value *EncPtr = LB.CreateInBoundsGEP(I8Ty, Enc, Idx);
|
||||
Value *KeyPtr = LB.CreateInBoundsGEP(I8Ty, Key, Idx);
|
||||
Value *DstPtr = LB.CreateInBoundsGEP(I8Ty, Dst, Idx);
|
||||
Value *EncByte = LB.CreateAlignedLoad(I8Ty, EncPtr, Align(1));
|
||||
Value *KeyByte = LB.CreateAlignedLoad(I8Ty, KeyPtr, Align(1));
|
||||
Value *DecByte = LB.CreateXor(EncByte, KeyByte);
|
||||
LB.CreateAlignedStore(DecByte, DstPtr, Align(1));
|
||||
Value *NextIdx = LB.CreateAdd(Idx, ConstantInt::get(I64Ty, 1));
|
||||
Idx->addIncoming(NextIdx, LoopBB);
|
||||
Value *Cont = LB.CreateICmpULT(NextIdx, LenArg);
|
||||
LB.CreateCondBr(Cont, LoopBB, ExitBB);
|
||||
|
||||
IRBuilder<> XB(ExitBB);
|
||||
XB.CreateRetVoid();
|
||||
return Fn;
|
||||
}
|
||||
|
||||
void emitEncryptedKeyPair(Module &M, uint64_t CurId, StringRef RawBytes,
|
||||
StringRef Seed, StringRef ItemId, Align BufAlign,
|
||||
bool EmitGlobalBuf, GlobalVariable *&OutEncGV,
|
||||
GlobalVariable *&OutKeyGV,
|
||||
GlobalVariable *&OutBufGV,
|
||||
GlobalVariable *&OutStateGV) {
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
uint64_t Len = RawBytes.size();
|
||||
IGDeterministicRNG RNG(Seed, M.getModuleIdentifier(), ItemId);
|
||||
SmallVector<uint8_t, 64> KeyBytes(Len);
|
||||
SmallVector<uint8_t, 64> EncBytes(Len);
|
||||
for (size_t i = 0; i < Len; ++i) {
|
||||
uint8_t K = RNG.nextNonZeroByte();
|
||||
KeyBytes[i] = K;
|
||||
EncBytes[i] = static_cast<uint8_t>(RawBytes[i]) ^ K;
|
||||
}
|
||||
|
||||
ArrayType *ArrTy = ArrayType::get(Type::getInt8Ty(Ctx), Len);
|
||||
OutEncGV = new GlobalVariable(
|
||||
M, ArrTy, /*isConstant=*/true, GlobalValue::PrivateLinkage,
|
||||
ConstantDataArray::get(Ctx, EncBytes), ".ig.enc." + Twine(CurId));
|
||||
OutEncGV->setAlignment(Align(1));
|
||||
OutEncGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
|
||||
|
||||
OutKeyGV = new GlobalVariable(
|
||||
M, ArrTy, /*isConstant=*/true, GlobalValue::PrivateLinkage,
|
||||
ConstantDataArray::get(Ctx, KeyBytes), ".ig.key." + Twine(CurId));
|
||||
OutKeyGV->setAlignment(Align(1));
|
||||
OutKeyGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
|
||||
|
||||
OutBufGV = nullptr;
|
||||
OutStateGV = nullptr;
|
||||
if (EmitGlobalBuf) {
|
||||
OutBufGV = new GlobalVariable(
|
||||
M, ArrTy, /*isConstant=*/false, GlobalValue::InternalLinkage,
|
||||
ConstantAggregateZero::get(ArrTy), ".ig.buf." + Twine(CurId));
|
||||
OutBufGV->setAlignment(BufAlign);
|
||||
|
||||
Type *I32Ty = Type::getInt32Ty(Ctx);
|
||||
OutStateGV = new GlobalVariable(
|
||||
M, I32Ty, /*isConstant=*/false, GlobalValue::InternalLinkage,
|
||||
ConstantInt::get(I32Ty, 0), ".ig.state." + Twine(CurId));
|
||||
OutStateGV->setAlignment(Align(4));
|
||||
}
|
||||
}
|
||||
|
||||
void applyStackDecryptAndWipe(Module &M, GlobalVariable *GV, uint64_t CurId,
|
||||
GlobalVariable *EncGV, GlobalVariable *KeyGV,
|
||||
uint64_t Len, ArrayRef<Instruction *> LeafInsts,
|
||||
StringSet<> &SeenFunctions,
|
||||
std::vector<std::string> &TouchedFunctions) {
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
ArrayType *ArrTy = ArrayType::get(Type::getInt8Ty(Ctx), Len);
|
||||
Function *StackDecFn = getOrCreateStackDecryptFn(M);
|
||||
Type *I64Ty = Type::getInt64Ty(Ctx);
|
||||
Type *I8Ty = Type::getInt8Ty(Ctx);
|
||||
Constant *Zero64 = ConstantInt::get(I64Ty, 0);
|
||||
Constant *Zero8 = ConstantInt::get(I8Ty, 0);
|
||||
Constant *LenConst = ConstantInt::get(I64Ty, Len);
|
||||
|
||||
DenseMap<Function *, AllocaInst *> FuncBufs;
|
||||
for (Instruction *UI : LeafInsts) {
|
||||
auto *CI = cast<CallInst>(UI);
|
||||
Function *ParentF = CI->getFunction();
|
||||
AllocaInst *&StackBuf = FuncBufs[ParentF];
|
||||
if (!StackBuf) {
|
||||
BasicBlock &TargetEntry = ParentF->getEntryBlock();
|
||||
BasicBlock::iterator AllocaInsPt = TargetEntry.begin();
|
||||
while (AllocaInsPt != TargetEntry.end() && isa<AllocaInst>(AllocaInsPt))
|
||||
++AllocaInsPt;
|
||||
IRBuilder<> AllocaB(&TargetEntry, AllocaInsPt);
|
||||
StackBuf = AllocaB.CreateAlloca(ArrTy, nullptr, "ig.sbuf." + Twine(CurId));
|
||||
StackBuf->setAlignment(Align(1));
|
||||
if (SeenFunctions.insert(ParentF->getName()).second)
|
||||
TouchedFunctions.push_back(ParentF->getName().str());
|
||||
}
|
||||
|
||||
DebugLoc DbgLoc = CI->getDebugLoc();
|
||||
IRBuilder<> PreB(CI);
|
||||
CallInst *DecCall =
|
||||
PreB.CreateCall(StackDecFn, {StackBuf, EncGV, KeyGV, LenConst});
|
||||
DecCall->setDebugLoc(DbgLoc);
|
||||
|
||||
for (unsigned i = 0, e = CI->getNumOperands(); i < e; ++i) {
|
||||
if (unwrapBaseValue(CI->getOperand(i)) == GV)
|
||||
CI->setOperand(i, StackBuf);
|
||||
}
|
||||
|
||||
if (Len <= 64) {
|
||||
IRBuilder<> AfterB(CI->getNextNode());
|
||||
for (uint64_t k = 0; k < Len; ++k) {
|
||||
Value *BytePtr = AfterB.CreateInBoundsGEP(
|
||||
ArrTy, StackBuf, {Zero64, ConstantInt::get(I64Ty, k)});
|
||||
StoreInst *WipeStore = AfterB.CreateAlignedStore(
|
||||
Zero8, BytePtr, Align(1), /*isVolatile=*/true);
|
||||
WipeStore->setDebugLoc(DbgLoc);
|
||||
}
|
||||
} else {
|
||||
BasicBlock *CurBB = CI->getParent();
|
||||
BasicBlock *ContBB = CurBB->splitBasicBlock(
|
||||
CI->getNextNode(), "ig.wipe.cont." + Twine(CurId));
|
||||
BasicBlock *WipeBB = BasicBlock::Create(
|
||||
Ctx, "ig.wipe.loop." + Twine(CurId), ParentF, ContBB);
|
||||
CurBB->getTerminator()->eraseFromParent();
|
||||
IRBuilder<> BrB(CurBB);
|
||||
BrB.SetCurrentDebugLocation(DbgLoc);
|
||||
BrB.CreateBr(WipeBB);
|
||||
|
||||
IRBuilder<> WB(WipeBB);
|
||||
WB.SetCurrentDebugLocation(DbgLoc);
|
||||
PHINode *WIdx = WB.CreatePHI(I64Ty, 2, "widx");
|
||||
WIdx->addIncoming(Zero64, CurBB);
|
||||
Value *BytePtr = WB.CreateInBoundsGEP(ArrTy, StackBuf, {Zero64, WIdx});
|
||||
WB.CreateAlignedStore(Zero8, BytePtr, Align(1), /*isVolatile=*/true);
|
||||
Value *NextWIdx = WB.CreateAdd(WIdx, ConstantInt::get(I64Ty, 1));
|
||||
WIdx->addIncoming(NextWIdx, WipeBB);
|
||||
Value *More = WB.CreateICmpULT(NextWIdx, LenConst);
|
||||
WB.CreateCondBr(More, WipeBB, ContBB);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool hasAnyNonZeroBytes(StringRef Raw) {
|
||||
for (unsigned char C : Raw) {
|
||||
if (C != 0)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool tryEncryptCFConstantString(
|
||||
Module &M, GlobalVariable *CFGV, const IGPolicyConfig &Policy,
|
||||
const SmallPtrSet<const GlobalValue *, 16> &PreservedUsed,
|
||||
const SmallPtrSet<const GlobalVariable *, 16> &AliasedGlobals,
|
||||
uint64_t &NextId, StringSet<> &SeenFunctions,
|
||||
std::vector<std::string> &TouchedFunctions, IGAuditRecord &Audit) {
|
||||
if (!CFGV->hasInitializer() || !CFGV->hasLocalLinkage() ||
|
||||
CFGV->isThreadLocal() || CFGV->getSection() != "__DATA,__cfstring") {
|
||||
return false;
|
||||
}
|
||||
if (PreservedUsed.contains(CFGV) || AliasedGlobals.contains(CFGV))
|
||||
return false;
|
||||
|
||||
const auto *CS = dyn_cast<ConstantStruct>(CFGV->getInitializer());
|
||||
if (!CS || CS->getNumOperands() != 4)
|
||||
return false;
|
||||
|
||||
const auto *ClassGV =
|
||||
dyn_cast<GlobalValue>(CS->getOperand(0)->stripPointerCasts());
|
||||
if (!ClassGV || ClassGV->getName() != "__CFConstantStringClassReference")
|
||||
return false;
|
||||
|
||||
const auto *FlagsCI = dyn_cast<ConstantInt>(CS->getOperand(1));
|
||||
const auto *LenCI = dyn_cast<ConstantInt>(CS->getOperand(3));
|
||||
if (!FlagsCI || !LenCI)
|
||||
return false;
|
||||
uint64_t Flags = FlagsCI->getZExtValue();
|
||||
uint64_t CharCount = LenCI->getZExtValue();
|
||||
if ((Flags != 1992 && Flags != 2000) || CharCount < 4)
|
||||
return false;
|
||||
|
||||
auto *StrGV = dyn_cast<GlobalVariable>(CS->getOperand(2)->stripPointerCasts());
|
||||
if (!StrGV || !StrGV->hasInitializer() || !StrGV->isConstant() ||
|
||||
!StrGV->hasLocalLinkage() || PreservedUsed.contains(StrGV) ||
|
||||
AliasedGlobals.contains(StrGV) || !StrGV->hasOneUse()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto *CDS = dyn_cast<ConstantDataSequential>(StrGV->getInitializer());
|
||||
if (!CDS || CDS->getNumElements() != CharCount + 1)
|
||||
return false;
|
||||
bool IsUTF16 = (Flags == 2000);
|
||||
if (IsUTF16 && !CDS->getElementType()->isIntegerTy(16))
|
||||
return false;
|
||||
if (!IsUTF16 && !CDS->getElementType()->isIntegerTy(8))
|
||||
return false;
|
||||
if (CDS->getElementAsInteger(CharCount) != 0)
|
||||
return false;
|
||||
|
||||
StringRef Raw = CDS->getRawDataValues();
|
||||
if (Raw.empty() || !hasAnyNonZeroBytes(Raw))
|
||||
return false;
|
||||
|
||||
SmallVector<Instruction *, 8> LeafInsts;
|
||||
auto FnPred = [&](const Function &F) {
|
||||
return Policy.shouldEncryptObjCStringsInFunction(F) ||
|
||||
Policy.shouldEncryptSwiftStringsInFunction(F);
|
||||
};
|
||||
if (!collectControlledUsersEx(CFGV, /*AllowSwiftBias=*/false, FnPred,
|
||||
LeafInsts)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint64_t CurId = NextId++;
|
||||
Align BufAlign(IsUTF16 ? 2 : 1);
|
||||
GlobalVariable *EncGV = nullptr;
|
||||
GlobalVariable *KeyGV = nullptr;
|
||||
GlobalVariable *BufGV = nullptr;
|
||||
GlobalVariable *StateGV = nullptr;
|
||||
emitEncryptedKeyPair(M, CurId, Raw, Policy.seed(), StrGV->getName(), BufAlign,
|
||||
/*EmitGlobalBuf=*/true, EncGV, KeyGV, BufGV, StateGV);
|
||||
|
||||
Constant *NewCFInit = ConstantStruct::get(
|
||||
CS->getType(),
|
||||
{CS->getOperand(0), CS->getOperand(1), BufGV, CS->getOperand(3)});
|
||||
CFGV->setInitializer(NewCFInit);
|
||||
|
||||
Function *DecFn =
|
||||
createDecryptFunction(M, CurId, "__ig_dec_cf_", EncGV, KeyGV, BufGV,
|
||||
StateGV, CFGV, Raw.size(), BufAlign);
|
||||
|
||||
rewriteUsersWithDecryptFn(CFGV, DecFn, /*AllowSwiftBias=*/false, LeafInsts,
|
||||
SeenFunctions, TouchedFunctions);
|
||||
|
||||
StrGV->removeDeadConstantUsers();
|
||||
if (StrGV->use_empty())
|
||||
StrGV->eraseFromParent();
|
||||
|
||||
Audit.StringsEncryptedCount++;
|
||||
Audit.ObjCStringsEncryptedCount++;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool runSourcePathScrubbing(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isStringEncryptionEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
|
||||
const auto &Substrings = Policy.scrubPathSubstrings();
|
||||
std::string SwiftModPrefix;
|
||||
if (!Policy.swiftModuleName().empty())
|
||||
SwiftModPrefix = Policy.swiftModuleName().str() + "/";
|
||||
|
||||
if (Substrings.empty() && SwiftModPrefix.empty())
|
||||
return false;
|
||||
|
||||
bool Changed = false;
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
|
||||
for (GlobalVariable &GV : M.globals()) {
|
||||
if (!GV.hasInitializer() || !GV.isConstant() || !GV.hasLocalLinkage())
|
||||
continue;
|
||||
if (GV.hasSection() || GV.isThreadLocal())
|
||||
continue;
|
||||
StringRef Name = GV.getName();
|
||||
if (Name == "llvm.global.annotations" || Name.starts_with(".ig.") ||
|
||||
Name.starts_with("__ig_"))
|
||||
continue;
|
||||
|
||||
const auto *CDS = dyn_cast<ConstantDataSequential>(GV.getInitializer());
|
||||
if (!CDS || !CDS->isCString() || !CDS->getElementType()->isIntegerTy(8))
|
||||
continue;
|
||||
|
||||
StringRef S = CDS->getAsCString();
|
||||
if (S.empty())
|
||||
continue;
|
||||
|
||||
bool IsSourceExt = S.ends_with(".swift") || S.ends_with(".m") ||
|
||||
S.ends_with(".mm") || S.ends_with(".c") ||
|
||||
S.ends_with(".h");
|
||||
bool Matched = false;
|
||||
for (const std::string &Sub : Substrings) {
|
||||
if (!Sub.empty() && S.contains(Sub)) {
|
||||
Matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!Matched && IsSourceExt &&
|
||||
(S.starts_with("./readoor/") || S.starts_with("readoor/") ||
|
||||
S.contains("/readoor/"))) {
|
||||
Matched = true;
|
||||
}
|
||||
if (!Matched && !SwiftModPrefix.empty() &&
|
||||
S.starts_with(SwiftModPrefix) && S.ends_with(".swift")) {
|
||||
Matched = true;
|
||||
}
|
||||
if (!Matched)
|
||||
continue;
|
||||
|
||||
SHA256 Hasher;
|
||||
Hasher.update(Policy.seed());
|
||||
Hasher.update("|");
|
||||
Hasher.update(S);
|
||||
auto Digest = Hasher.final();
|
||||
std::string Tag8 = toHex(ArrayRef<uint8_t>(Digest.data(), 4), /*LowerCase=*/true);
|
||||
|
||||
std::string Repl = "ig_p_" + Tag8;
|
||||
if (Repl.size() < S.size())
|
||||
Repl.append(S.size() - Repl.size(), ' ');
|
||||
else if (Repl.size() > S.size())
|
||||
Repl.resize(S.size());
|
||||
|
||||
Constant *NewInit = ConstantDataArray::getString(Ctx, Repl, /*AddNull=*/true);
|
||||
if (NewInit->getType() != GV.getValueType())
|
||||
continue;
|
||||
|
||||
GV.setInitializer(NewInit);
|
||||
Audit.PathsScrubbedCount++;
|
||||
Changed = true;
|
||||
}
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
bool runStringEncryption(Module &M, const IGPolicyConfig &Policy,
|
||||
IGAuditRecord &Audit) {
|
||||
if (!Policy.isStringEncryptionEnabled() || Policy.isModuleExempt(M))
|
||||
return false;
|
||||
|
||||
SmallPtrSet<const GlobalValue *, 16> PreservedUsed;
|
||||
collectCompilerUsed(M, "llvm.used", PreservedUsed);
|
||||
collectCompilerUsed(M, "llvm.compiler.used", PreservedUsed);
|
||||
|
||||
SmallPtrSet<const GlobalVariable *, 16> AliasedGlobals;
|
||||
for (const GlobalAlias &GA : M.aliases()) {
|
||||
if (const auto *AliaseeGV =
|
||||
dyn_cast<GlobalVariable>(GA.getAliasee()->stripPointerCasts())) {
|
||||
AliasedGlobals.insert(AliaseeGV);
|
||||
}
|
||||
}
|
||||
|
||||
SmallVector<GlobalVariable *, 32> Candidates;
|
||||
for (GlobalVariable &GV : M.globals()) {
|
||||
Candidates.push_back(&GV);
|
||||
}
|
||||
|
||||
bool Changed = false;
|
||||
uint64_t NextId = 0;
|
||||
StringSet<> SeenFunctions;
|
||||
std::vector<std::string> TouchedFunctions;
|
||||
LLVMContext &Ctx = M.getContext();
|
||||
|
||||
const auto &ReplaceRules = Policy.stringReplaceRules();
|
||||
if (!ReplaceRules.empty()) {
|
||||
for (GlobalVariable *GV : Candidates) {
|
||||
if (!GV->hasInitializer() || !GV->isConstant() ||
|
||||
!GV->hasLocalLinkage() || GV->hasSection() || GV->isThreadLocal() ||
|
||||
GV->getName().starts_with(".ig.") ||
|
||||
GV->getName().starts_with("__ig_") ||
|
||||
PreservedUsed.contains(GV) || AliasedGlobals.contains(GV)) {
|
||||
continue;
|
||||
}
|
||||
const auto *CDS = dyn_cast<ConstantDataSequential>(GV->getInitializer());
|
||||
if (!CDS || !CDS->isCString() || !CDS->getElementType()->isIntegerTy(8))
|
||||
continue;
|
||||
StringRef CStr = CDS->getAsCString();
|
||||
for (const StringReplaceRule &Rule : ReplaceRules) {
|
||||
if (Rule.Exact == CStr) {
|
||||
uint64_t TotalLen = CDS->getNumElements();
|
||||
if (TotalLen < 2)
|
||||
break;
|
||||
SmallVector<uint8_t, 64> Buf(TotalLen, 0);
|
||||
size_t CopyLen = std::min<size_t>(Rule.Replace.size(), TotalLen - 1);
|
||||
if (CopyLen > 0)
|
||||
std::memcpy(Buf.data(), Rule.Replace.data(), CopyLen);
|
||||
GV->setInitializer(ConstantDataArray::get(Ctx, Buf));
|
||||
Audit.StringsReplacedCount++;
|
||||
Changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (GlobalVariable *GV : Candidates) {
|
||||
if (tryEncryptCFConstantString(M, GV, Policy, PreservedUsed, AliasedGlobals,
|
||||
NextId, SeenFunctions, TouchedFunctions,
|
||||
Audit)) {
|
||||
Changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!GV->hasInitializer() || !GV->isConstant())
|
||||
continue;
|
||||
if (!GV->hasLocalLinkage())
|
||||
continue;
|
||||
if (GV->hasSection() || GV->isThreadLocal())
|
||||
continue;
|
||||
if (GV->getName().starts_with(".ig.") ||
|
||||
GV->getName().starts_with("__ig_"))
|
||||
continue;
|
||||
if (PreservedUsed.contains(GV) || AliasedGlobals.contains(GV)) {
|
||||
Audit.StringsSkippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto *CDS = dyn_cast<ConstantDataSequential>(GV->getInitializer());
|
||||
if (!CDS || (!CDS->isString() && !CDS->isCString()) ||
|
||||
!CDS->getElementType()->isIntegerTy(8)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
StringRef Raw = CDS->getRawDataValues();
|
||||
if (Raw.size() < 5) // Require >= 4 non-trivial bytes (+ optional NUL)
|
||||
continue;
|
||||
if (!hasAnyNonZeroBytes(Raw))
|
||||
continue;
|
||||
|
||||
SmallVector<Instruction *, 8> LeafInsts;
|
||||
bool MatchedC = collectControlledUsersEx(
|
||||
GV, /*AllowSwiftBias=*/false,
|
||||
[&](const Function &F) {
|
||||
return Policy.shouldEncryptStringsInFunction(F);
|
||||
},
|
||||
LeafInsts);
|
||||
|
||||
if (MatchedC) {
|
||||
uint64_t CurId = NextId++;
|
||||
bool UseStack = canUseMultiFnStackDecrypt(GV, Raw.size(), Policy, LeafInsts);
|
||||
GlobalVariable *EncGV = nullptr;
|
||||
GlobalVariable *KeyGV = nullptr;
|
||||
GlobalVariable *BufGV = nullptr;
|
||||
GlobalVariable *StateGV = nullptr;
|
||||
emitEncryptedKeyPair(M, CurId, Raw, Policy.seed(), GV->getName(), Align(1),
|
||||
/*EmitGlobalBuf=*/!UseStack, EncGV, KeyGV, BufGV,
|
||||
StateGV);
|
||||
|
||||
if (UseStack) {
|
||||
applyStackDecryptAndWipe(M, GV, CurId, EncGV, KeyGV, Raw.size(),
|
||||
LeafInsts, SeenFunctions, TouchedFunctions);
|
||||
Audit.StringsStackEncryptedCount++;
|
||||
} else {
|
||||
Function *DecFn =
|
||||
createDecryptFunction(M, CurId, "__ig_dec_str_", EncGV, KeyGV,
|
||||
BufGV, StateGV, BufGV, Raw.size(), Align(1));
|
||||
rewriteUsersWithDecryptFn(GV, DecFn, /*AllowSwiftBias=*/false,
|
||||
LeafInsts, SeenFunctions, TouchedFunctions);
|
||||
}
|
||||
|
||||
GV->removeDeadConstantUsers();
|
||||
if (GV->use_empty())
|
||||
GV->eraseFromParent();
|
||||
|
||||
Audit.StringsEncryptedCount++;
|
||||
Changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
LeafInsts.clear();
|
||||
bool MatchedSwift =
|
||||
!GV->use_empty() && Raw.size() >= 16 &&
|
||||
collectControlledUsersEx(
|
||||
GV, /*AllowSwiftBias=*/true,
|
||||
[&](const Function &F) {
|
||||
return Policy.shouldEncryptSwiftStringsInFunction(F);
|
||||
},
|
||||
LeafInsts);
|
||||
|
||||
if (MatchedSwift) {
|
||||
uint64_t CurId = NextId++;
|
||||
GlobalVariable *EncGV = nullptr;
|
||||
GlobalVariable *KeyGV = nullptr;
|
||||
GlobalVariable *BufGV = nullptr;
|
||||
GlobalVariable *StateGV = nullptr;
|
||||
emitEncryptedKeyPair(M, CurId, Raw, Policy.seed(), GV->getName(), Align(8),
|
||||
/*EmitGlobalBuf=*/true, EncGV, KeyGV, BufGV, StateGV);
|
||||
|
||||
Function *DecFn =
|
||||
createDecryptFunction(M, CurId, "__ig_dec_sw_", EncGV, KeyGV, BufGV,
|
||||
StateGV, BufGV, Raw.size(), Align(8));
|
||||
rewriteUsersWithDecryptFn(GV, DecFn, /*AllowSwiftBias=*/true, LeafInsts,
|
||||
SeenFunctions, TouchedFunctions);
|
||||
|
||||
GV->removeDeadConstantUsers();
|
||||
if (GV->use_empty())
|
||||
GV->eraseFromParent();
|
||||
|
||||
Audit.StringsEncryptedCount++;
|
||||
Audit.SwiftStringsEncryptedCount++;
|
||||
Changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!GV->use_empty())
|
||||
Audit.StringsSkippedCount++;
|
||||
}
|
||||
|
||||
for (const std::string &FnName : TouchedFunctions)
|
||||
Audit.StringsEncryptedFunctions.push_back(FnName);
|
||||
|
||||
return Changed;
|
||||
}
|
||||
|
||||
} // namespace igobf
|
||||
@@ -0,0 +1,231 @@
|
||||
import XCTest
|
||||
import UIKit
|
||||
|
||||
/// 访问真实观察包;不使用 --UITesting,不注入 token,不调用购买接口。
|
||||
final class IGBusinessRegressionTests: XCTestCase {
|
||||
private let bundleID = "cn.touchv.iosguard.observe.20261110"
|
||||
|
||||
override func setUpWithError() throws { continueAfterFailure = false }
|
||||
|
||||
private func capture(_ app: XCUIApplication, _ name: String) {
|
||||
// 截图遮盖输入框,文本树移除输入值,避免登录排查留存凭证。
|
||||
let source = app.screenshot().image
|
||||
let fields = app.textFields.allElementsBoundByIndex + app.secureTextFields.allElementsBoundByIndex
|
||||
let screenshotImage = UIGraphicsImageRenderer(size: source.size).image { context in
|
||||
source.draw(at: .zero)
|
||||
UIColor.lightGray.setFill()
|
||||
let sx = source.size.width / app.frame.width
|
||||
let sy = source.size.height / app.frame.height
|
||||
for field in fields {
|
||||
let frame = field.frame
|
||||
context.fill(CGRect(x: frame.minX * sx, y: frame.minY * sy,
|
||||
width: frame.width * sx, height: frame.height * sy))
|
||||
}
|
||||
}
|
||||
let screenshot = XCTAttachment(image: screenshotImage)
|
||||
screenshot.name = name
|
||||
screenshot.lifetime = .keepAlways
|
||||
add(screenshot)
|
||||
let redactedTree = app.debugDescription.components(separatedBy: "\n").map { line in
|
||||
guard line.contains("TextField"), let value = line.range(of: ", value:") else { return line }
|
||||
return String(line[..<value.lowerBound]) + ", value: [redacted]"
|
||||
}.joined(separator: "\n")
|
||||
let tree = XCTAttachment(string: redactedTree)
|
||||
tree.name = name + "-accessibility"
|
||||
tree.lifetime = .keepAlways
|
||||
add(tree)
|
||||
}
|
||||
|
||||
func testInspectLaunch() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.launch()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 30))
|
||||
capture(app, "observation-launch")
|
||||
}
|
||||
|
||||
func testInspectCurrentPage() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
capture(app, "observation-current")
|
||||
}
|
||||
|
||||
func testAllowWifiAndInspect() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
|
||||
let wifi = springboard.buttons["仅限无线局域网"]
|
||||
if wifi.waitForExistence(timeout: 5) { wifi.tap() }
|
||||
app.activate()
|
||||
_ = app.images["splash"].waitForNonExistence(timeout: 20)
|
||||
capture(app, "after-network-permission")
|
||||
}
|
||||
|
||||
func testHomeResourceAndForeground() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let home = app.otherElements["home_page_anchor"]
|
||||
XCTAssertTrue(home.waitForExistence(timeout: 30), "需先完成真实登录与启动流程")
|
||||
// 实际首页资源由 TableCell 内自绘卡片承载,使用已观察到的资源标题。
|
||||
let resource = app.staticTexts["[pdf]MW书籍测试读"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 20))
|
||||
capture(app, "home-before-resource")
|
||||
resource.tap()
|
||||
let detail = app.otherElements["detail_page_anchor"]
|
||||
XCTAssertTrue(detail.waitForExistence(timeout: 20), "首个首页卡片未进入商品详情")
|
||||
capture(app, "resource-detail")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(detail.waitForExistence(timeout: 10))
|
||||
capture(app, "resource-after-foreground")
|
||||
}
|
||||
|
||||
func testTrialResourceAndInspect() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let trial = app.buttons["试读"].firstMatch
|
||||
XCTAssertTrue(trial.waitForExistence(timeout: 15))
|
||||
trial.tap()
|
||||
// 入口可能先展示课件/规格选择,先留存真实页面再决定下一步。
|
||||
capture(app, "after-trial-entry")
|
||||
}
|
||||
|
||||
func testColdRestartAndInspect() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 30))
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
capture(app, "after-cold-restart")
|
||||
}
|
||||
|
||||
func testPDFTrialAndPageTurn() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
let resource = app.staticTexts["[pdf]MW书籍测试读"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 15))
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
let trial = app.buttons["试读"].firstMatch
|
||||
XCTAssertTrue(trial.waitForExistence(timeout: 15))
|
||||
trial.tap()
|
||||
XCTAssertTrue(app.buttons["titlebar return phone"].waitForExistence(timeout: 20))
|
||||
_ = app.progressIndicators["进度"].waitForNonExistence(timeout: 30)
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 5))
|
||||
capture(app, "pdf-before-page-turn")
|
||||
app.swipeLeft()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 5), "PDF 翻页后进程退出")
|
||||
capture(app, "pdf-after-page-turn")
|
||||
}
|
||||
|
||||
func testEPUBResourceAndForeground() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
let resource = app.staticTexts["【epub】会员免费书籍"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 15))
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
capture(app, "epub-detail")
|
||||
let read = app.buttons["开始阅读"].firstMatch
|
||||
let trial = app.buttons["试读"].firstMatch
|
||||
if read.exists { read.tap() }
|
||||
else {
|
||||
XCTAssertTrue(trial.waitForExistence(timeout: 10), "本账号没有可用阅读入口")
|
||||
trial.tap()
|
||||
}
|
||||
capture(app, "epub-entry")
|
||||
XCTAssertTrue(app.webViews.firstMatch.waitForExistence(timeout: 30), "尚未出现 EPUB 内容视图")
|
||||
capture(app, "epub-content")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(app.webViews.firstMatch.waitForExistence(timeout: 15))
|
||||
capture(app, "epub-after-foreground")
|
||||
}
|
||||
func testWordbookOpenAndInspect() {
|
||||
openWordbook(replayStyle: true)
|
||||
}
|
||||
|
||||
private func openWordbook(replayStyle: Bool) {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.launchArguments = replayStyle ? ["--IGArchiveReplayStyle"] : []
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
let popupClose = app.buttons["rd pop close"]
|
||||
if popupClose.waitForExistence(timeout: 5) { popupClose.tap() }
|
||||
capture(app, "wordbook-home")
|
||||
let resource = app.staticTexts["31单词书(稳操胜券)-勿动"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 20))
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
capture(app, "wordbook-detail")
|
||||
}
|
||||
|
||||
func testWordbookReadAndForeground() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let read = app.buttons["开始阅读"].firstMatch
|
||||
let section = app.staticTexts["稳操胜券"].firstMatch
|
||||
XCTAssertTrue(section.waitForExistence(timeout: 20), "需先打开指定单词书详情")
|
||||
capture(app, "wordbook-loaded-detail")
|
||||
if read.exists { read.tap() } else { section.tap() }
|
||||
capture(app, "wordbook-after-read-entry")
|
||||
let ready = app.staticTexts["今日学习单词了吗?"].firstMatch
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 120), "单词书未准备完成")
|
||||
XCTAssertTrue(ready.isHittable, "单词书就绪内容不可见")
|
||||
capture(app, "wordbook-ready")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 15))
|
||||
capture(app, "wordbook-after-foreground")
|
||||
}
|
||||
|
||||
func testWordbookReentryAndCache() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let back = app.buttons["mw backBar img"].firstMatch
|
||||
XCTAssertTrue(back.waitForExistence(timeout: 10))
|
||||
back.tap()
|
||||
let section = app.staticTexts["稳操胜券"].firstMatch
|
||||
XCTAssertTrue(section.waitForExistence(timeout: 15))
|
||||
section.tap()
|
||||
let ready = app.staticTexts["今日学习单词了吗?"].firstMatch
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 60))
|
||||
XCTAssertTrue(ready.isHittable)
|
||||
capture(app, "wordbook-reentry-cache")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 15))
|
||||
capture(app, "wordbook-reentry-foreground")
|
||||
}
|
||||
|
||||
func testWordbookFreshExtraction() {
|
||||
testWordbookOpenAndInspect()
|
||||
testWordbookReadAndForeground()
|
||||
}
|
||||
|
||||
func testWordbookCachedEntryAndReentry() {
|
||||
// 由单独无参数启动步骤进入首页,避免将短暂营销弹窗的自动消失误记为业务失败。
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 20))
|
||||
let resource = app.staticTexts["31单词书(稳操胜券)-勿动"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 15))
|
||||
XCTAssertTrue(resource.isHittable)
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
testWordbookReadAndForeground()
|
||||
testWordbookReentryAndCache()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
import XCTest
|
||||
import UIKit
|
||||
|
||||
/// 反 Hook 门禁按钮级回归(强制模式 dev 包 cn.touchv.a4YX061)。
|
||||
///
|
||||
/// 相位(按方法名字典序执行):
|
||||
/// A1 干净启动勘察;A2 登出到登录页(个人中心 退出登录);
|
||||
/// B1 注入启动·密码登录门禁;B2 注入启动·第三方登录门禁;
|
||||
/// C1 干净启动·密码登录放行(DEBUG 预填测试账号真实登录);
|
||||
/// D1 注入启动·VIP 购买门禁(会员页);E1 注入启动·激活码门禁(我的页探测入口)。
|
||||
///
|
||||
/// 注入:编排器(run_gate_regression.sh)以 devicectl `-e DYLD_INSERT_LIBRARIES`
|
||||
/// 调试启动通道预先注入启动(空壳 libfrida-sim.dylib),注入相位测试仅 activate()
|
||||
/// attach 到该进程——v4 教训:XCUITest launchEnvironment 的 DYLD_INSERT 经
|
||||
/// SpringBoard 启动链被剥离,门禁不触发。各相位以 -only-testing 分批执行(v6 序,
|
||||
/// XCUITest↔devicectl 切换仅 2 次):干净批 A1/A2(游客态)→ 注入批 B1/B2(游客)
|
||||
/// → 干净批 C1(放行证明)→ 注入批 D1/E1(登录态,未登成则游客守卫跳过)。
|
||||
/// v5e 教训:devicectl `--console` 通道在连续会话后整体卡死(零输出+进程即死),
|
||||
/// 注入启动不用 console,注入生效由测试内门禁 toast 端到端自证。
|
||||
/// 教训(B2 首版崩溃):营销弹窗自动消失瞬间盲点「rd pop close」会落到其下方的
|
||||
/// 首页搜索按钮,触发路由重复注册 assertion 崩溃(业务既有 bug)——先等自然消失再点,
|
||||
/// 且点击前复核存在与可点性。
|
||||
/// 凭证不入日志:截图遮盖输入框、文本树脱敏(沿用业务观察 Runner 做法)。
|
||||
final class IGGateRegressionTests: XCTestCase {
|
||||
private let bundleID = "cn.touchv.a4YX061"
|
||||
private var injectLib: String? { ProcessInfo.processInfo.environment["INJECT_LIB"] }
|
||||
private let blockLoginToast = "当前环境暂时无法登录,请稍后重试"
|
||||
private let blockVipToast = "当前环境暂时无法购买,请稍后重试"
|
||||
private let blockActivationToast = "当前环境暂时无法激活,请稍后重试"
|
||||
|
||||
override func setUpWithError() throws { continueAfterFailure = false }
|
||||
|
||||
// MARK: - 工具
|
||||
|
||||
/// 脱敏截图(遮盖输入框)+ 脱敏文本树,全部 keepAlways 留证。
|
||||
private func capture(_ app: XCUIApplication, _ name: String) {
|
||||
let source = app.screenshot().image
|
||||
let fields = app.textFields.allElementsBoundByIndex + app.secureTextFields.allElementsBoundByIndex
|
||||
let screenshotImage = UIGraphicsImageRenderer(size: source.size).image { context in
|
||||
source.draw(at: .zero)
|
||||
UIColor.lightGray.setFill()
|
||||
let sx = source.size.width / app.frame.width
|
||||
let sy = source.size.height / app.frame.height
|
||||
for field in fields {
|
||||
let frame = field.frame
|
||||
context.fill(CGRect(x: frame.minX * sx, y: frame.minY * sy,
|
||||
width: frame.width * sx, height: frame.height * sy))
|
||||
}
|
||||
}
|
||||
let screenshot = XCTAttachment(image: screenshotImage)
|
||||
screenshot.name = name
|
||||
screenshot.lifetime = .keepAlways
|
||||
add(screenshot)
|
||||
let redactedTree = app.debugDescription.components(separatedBy: "\n").map { line in
|
||||
guard line.contains("TextField"), let value = line.range(of: ", value:") else { return line }
|
||||
return String(line[..<value.lowerBound]) + ", value: [redacted]"
|
||||
}.joined(separator: "\n")
|
||||
let tree = XCTAttachment(string: redactedTree)
|
||||
tree.name = name + "-accessibility"
|
||||
tree.lifetime = .keepAlways
|
||||
add(tree)
|
||||
}
|
||||
|
||||
private func step(_ message: String) {
|
||||
NSLog("[GateRegression] %@", message)
|
||||
}
|
||||
|
||||
private func launchApp(_ app: XCUIApplication, injected: Bool) throws {
|
||||
if injected {
|
||||
// v4 教训:XCUITest launchEnvironment 的 DYLD_INSERT_LIBRARIES 经 SpringBoard
|
||||
// 启动链被剥离(B1 门禁 toast 不出现)——注入进程由编排器以 devicectl
|
||||
// `-e` 调试启动通道预先启动,测试只 attach(activate 不重启,注入保持)。
|
||||
guard app.state == .runningForeground || app.state == .runningBackground else {
|
||||
try skipAndCapture("注入进程未运行(编排器须先 devicectl 注入启动本 App)")
|
||||
}
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 30), "注入进程未进前台")
|
||||
return
|
||||
}
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 40), "应用未进入前台")
|
||||
}
|
||||
|
||||
private func skipAndCapture(_ reason: String) throws -> Never {
|
||||
step("SKIP: \(reason)")
|
||||
throw XCTSkip(reason)
|
||||
}
|
||||
|
||||
/// 等待登录页或首页锚点,返回 "login" / "home" / "unknown"。
|
||||
private func waitLoginOrHome(_ app: XCUIApplication, timeout: TimeInterval = 25) -> String {
|
||||
if app.otherElements["login_page_anchor"].waitForExistence(timeout: timeout) { return "login" }
|
||||
if app.otherElements["home_page_anchor"].waitForExistence(timeout: 10) { return "home" }
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
/// 关闭可能遮挡的营销弹窗:先等自然消失(约 6 秒),仍在且可点才点关闭。
|
||||
/// 不盲点:弹窗消失瞬间点击会落到其下方控件(首版曾误触首页搜索引发路由崩溃)。
|
||||
private func dismissPopups(_ app: XCUIApplication) {
|
||||
let popupClose = app.buttons["rd pop close"]
|
||||
if popupClose.waitForNonExistence(timeout: 6) { return }
|
||||
if popupClose.exists && popupClose.isHittable {
|
||||
popupClose.tap()
|
||||
_ = popupClose.waitForNonExistence(timeout: 3)
|
||||
}
|
||||
}
|
||||
|
||||
/// 勾选登录协议(v3 登录页树:勾选框暴露 identifier login_agreement_checkbox)。
|
||||
private func selectAgreementIfNeeded(_ app: XCUIApplication) {
|
||||
let agreement = app.otherElements["login_agreement_view"]
|
||||
_ = agreement.waitForExistence(timeout: 10)
|
||||
let checkbox = app.buttons["login_agreement_checkbox"].firstMatch
|
||||
if checkbox.exists {
|
||||
if checkbox.isHittable { checkbox.tap() }
|
||||
step("已点击协议勾选框")
|
||||
} else {
|
||||
let fallback = agreement.buttons.firstMatch
|
||||
if fallback.exists, fallback.isHittable {
|
||||
fallback.tap()
|
||||
step("勾选框无 identifier,已点协议视图内按钮")
|
||||
} else {
|
||||
step("协议勾选框未暴露,跳过勾选")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 断言门禁 toast 出现并等其消失。
|
||||
private func assertToast(_ app: XCUIApplication, text: String, label: String) {
|
||||
let toast = app.staticTexts[text].firstMatch
|
||||
XCTAssertTrue(toast.waitForExistence(timeout: 6), "\(label):未出现门禁 toast「\(text)」")
|
||||
capture(app, label + "-toast")
|
||||
_ = toast.waitForNonExistence(timeout: 8)
|
||||
}
|
||||
|
||||
/// 首页就绪并稳定(弹窗处理完成)。
|
||||
private func waitHomeStable(_ app: XCUIApplication, timeout: TimeInterval = 30) throws {
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: timeout), "未进入首页")
|
||||
dismissPopups(app)
|
||||
}
|
||||
|
||||
/// 游客态从首页导航到登录页:「我的」页「登录/注册」按钮(v2 勘察树确认)。
|
||||
/// 返回 false 表示入口不可达(多为已登录态),由调用方决定跳过或走既有会话判定。
|
||||
/// v3 教训:启动偶发落在无 tab bar 的推广落地页(AllTypes 书城页)——
|
||||
/// 先等待/返回自救,仍无 tab 则重启一次重抽落地页。
|
||||
private func navigateToLoginFromHome(_ app: XCUIApplication, allowRelaunch: Bool = true) -> Bool {
|
||||
func attempt() -> Bool {
|
||||
let mineTab = app.tabBars.buttons["我的"].firstMatch
|
||||
if !mineTab.waitForExistence(timeout: 12) {
|
||||
// 落地页自救:点导航返回键(若在二级页)后再等 tab。
|
||||
let back = app.buttons["nav black goback"].firstMatch
|
||||
if back.exists, back.isHittable {
|
||||
back.tap()
|
||||
step("落地页无 tab,已点返回")
|
||||
}
|
||||
if !mineTab.waitForExistence(timeout: 12) { return false }
|
||||
}
|
||||
mineTab.tap()
|
||||
_ = app.otherElements["personal_center_page_anchor"].waitForExistence(timeout: 10)
|
||||
dismissPopups(app)
|
||||
let guestEntry = app.buttons["登录/注册"].firstMatch
|
||||
guard guestEntry.waitForExistence(timeout: 8), guestEntry.isHittable else { return false }
|
||||
guestEntry.tap()
|
||||
return app.otherElements["login_page_anchor"].waitForExistence(timeout: 20)
|
||||
}
|
||||
if attempt() { return true }
|
||||
guard allowRelaunch else { return false }
|
||||
step("首轮导航失败,重启重抽落地页")
|
||||
app.terminate()
|
||||
app.launch()
|
||||
guard app.wait(for: .runningForeground, timeout: 40) else { return false }
|
||||
_ = app.otherElements["home_page_anchor"].waitForExistence(timeout: 25)
|
||||
dismissPopups(app)
|
||||
return attempt()
|
||||
}
|
||||
|
||||
// MARK: - A 勘察与登出
|
||||
|
||||
func testA1InspectCleanState() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("A1 干净启动勘察开始,INJECT_LIB=\(injectLib ?? "未传入")")
|
||||
try launchApp(app, injected: false)
|
||||
let state = waitLoginOrHome(app)
|
||||
step("A1 启动状态=\(state)")
|
||||
if state == "home" { dismissPopups(app) }
|
||||
capture(app, "a1-clean-\(state)")
|
||||
}
|
||||
|
||||
func testA2LogoutIfNeeded() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("A2 确保登录页可达(游客直进;登录态经设置页登出)")
|
||||
try launchApp(app, injected: false)
|
||||
let state = waitLoginOrHome(app)
|
||||
if state == "login" {
|
||||
step("A2 已在登录页")
|
||||
capture(app, "a2-already-login")
|
||||
return
|
||||
}
|
||||
guard state == "home" else { try skipAndCapture("A2 首页不可达(状态 \(state))") }
|
||||
dismissPopups(app)
|
||||
let mineTab = app.tabBars.buttons["我的"].firstMatch
|
||||
XCTAssertTrue(mineTab.waitForExistence(timeout: 10), "未找到「我的」页签")
|
||||
mineTab.tap()
|
||||
_ = app.otherElements["personal_center_page_anchor"].waitForExistence(timeout: 10)
|
||||
sleep(2)
|
||||
dismissPopups(app)
|
||||
capture(app, "a2-mine-page")
|
||||
// 游客态(v2 树:登录/注册按钮)直接进登录页,B 阶段即可测登录门禁。
|
||||
let guestEntry = app.buttons["登录/注册"].firstMatch
|
||||
if guestEntry.exists, guestEntry.isHittable {
|
||||
guestEntry.tap()
|
||||
XCTAssertTrue(app.otherElements["login_page_anchor"].waitForExistence(timeout: 20), "游客点「登录/注册」未进入登录页")
|
||||
step("A2 游客态进入登录页")
|
||||
capture(app, "a2-guest-login-page")
|
||||
return
|
||||
}
|
||||
// 登录态:右上角设置图标(v2 树:personalCenter setting)→ 设置页底部「退出登录」。
|
||||
let settingIcon = app.buttons["personalCenter setting"].firstMatch
|
||||
XCTAssertTrue(settingIcon.exists && settingIcon.isHittable, "未找到设置入口(见 a2 勘察树)")
|
||||
settingIcon.tap()
|
||||
sleep(2)
|
||||
capture(app, "a2-settings-page")
|
||||
// 退出登录在设置列表尾部,滚动查找(cell 标签为文本)。
|
||||
var confirmedLogout = false
|
||||
for _ in 0..<4 where !confirmedLogout {
|
||||
let logoutBtn = app.buttons.containing(NSPredicate(format: "label CONTAINS '退出登录'")).firstMatch
|
||||
let logoutText = app.staticTexts.containing(NSPredicate(format: "label CONTAINS '退出登录'")).firstMatch
|
||||
if logoutBtn.exists { logoutBtn.tap(); confirmedLogout = true }
|
||||
else if logoutText.exists { logoutText.tap(); confirmedLogout = true }
|
||||
else { app.swipeUp() }
|
||||
}
|
||||
XCTAssertTrue(confirmedLogout, "设置页未找到退出登录入口(见 a2-settings-page 树)")
|
||||
sleep(1)
|
||||
capture(app, "a2-logout-confirm")
|
||||
// 确认弹窗(自定义两键弹窗,右侧确认键常见文案逐个尝试)。
|
||||
for confirm in ["确定", "退出", "确认", "退出登录"] {
|
||||
let button = app.buttons[confirm].firstMatch
|
||||
if button.waitForExistence(timeout: 2) && button.isHittable {
|
||||
button.tap()
|
||||
step("A2 确认退出(「\(confirm)」)")
|
||||
break
|
||||
}
|
||||
}
|
||||
let back = waitLoginOrHome(app, timeout: 30)
|
||||
step("A2 登出后状态=\(back)")
|
||||
capture(app, "a2-after-logout-\(back)")
|
||||
XCTAssertEqual(back, "login", "登出后未回到登录页")
|
||||
}
|
||||
|
||||
// MARK: - B 拦截相位(注入启动·登录入口)
|
||||
|
||||
func testB1BlockPasswordLogin() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("B1 注入启动·密码登录门禁")
|
||||
try launchApp(app, injected: true)
|
||||
// 注入相位严禁 clean 重启(activate 之外的 launch 会丢 DYLD 注入),
|
||||
// navigate 不带 relaunch 自救;导航失败即跳过留证。
|
||||
var state = waitLoginOrHome(app)
|
||||
if state == "home", navigateToLoginFromHome(app, allowRelaunch: false) { state = "login" }
|
||||
capture(app, "b1-inject-\(state)")
|
||||
guard state == "login" else {
|
||||
try skipAndCapture("B1 登录页不可达(状态 \(state),游客入口缺失)")
|
||||
}
|
||||
capture(app, "b1-login-page")
|
||||
// 门禁在输入校验之前:空输入点击提交也必须先命中门禁 toast。
|
||||
let submit = app.buttons["login_submit_button"]
|
||||
XCTAssertTrue(submit.waitForExistence(timeout: 10), "未找到登录提交按钮")
|
||||
submit.tap()
|
||||
assertToast(app, text: blockLoginToast, label: "b1-block-password-login")
|
||||
// 门禁 toast 之外不应出现协议弹窗(出现说明执行越过了门禁)。
|
||||
let agreementAlert = app.alerts["请先阅读并同意协议"]
|
||||
XCTAssertFalse(agreementAlert.waitForExistence(timeout: 2), "点击越过了门禁(出现协议弹窗)")
|
||||
capture(app, "b1-block-after")
|
||||
}
|
||||
|
||||
func testB2BlockOtherLogins() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("B2 注入启动·第三方登录门禁(微信/QQ/Apple/Weread)")
|
||||
try launchApp(app, injected: true)
|
||||
var state = waitLoginOrHome(app)
|
||||
if state == "home", navigateToLoginFromHome(app, allowRelaunch: false) { state = "login" }
|
||||
guard state == "login" else {
|
||||
try skipAndCapture("B2 登录页不可达(状态 \(state),游客入口缺失)")
|
||||
}
|
||||
selectAgreementIfNeeded(app)
|
||||
capture(app, "b2-login-page")
|
||||
// v3 登录页树:第三方按钮为纯图片,label 即图片名(rd login wechat/qq/apple/wjOauth2)。
|
||||
var tapped = 0
|
||||
for label in ["rd login wechat", "rd login qq", "rd login apple", "rd login wjOauth2"] {
|
||||
let entry = app.buttons[label].firstMatch
|
||||
guard entry.waitForExistence(timeout: 3), entry.isHittable else { continue }
|
||||
entry.tap()
|
||||
tapped += 1
|
||||
step("B2 点击第三方入口「\(label)」")
|
||||
assertToast(app, text: blockLoginToast, label: "b2-block-\(label)")
|
||||
}
|
||||
if tapped == 0 {
|
||||
capture(app, "b2-no-third-party-buttons")
|
||||
try skipAndCapture("登录页未暴露可识别的第三方登录按钮(见 b2-login-page 树)")
|
||||
}
|
||||
step("B2 完成,拦截入口数=\(tapped)")
|
||||
}
|
||||
|
||||
// MARK: - C 放行相位(干净启动·真实登录)
|
||||
|
||||
func testC1AllowPasswordLogin() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("C1 干净启动·密码登录放行")
|
||||
try launchApp(app, injected: false)
|
||||
let bootState = waitLoginOrHome(app)
|
||||
var loginReached = bootState == "login"
|
||||
if !loginReached, bootState == "home" {
|
||||
// 游客态(home ≠ 已登录)也从「我的」页进入登录页做真实登录。
|
||||
loginReached = navigateToLoginFromHome(app)
|
||||
}
|
||||
if !loginReached {
|
||||
step("C1 登录页不可达且我的页无「登录/注册」(已登录态),放行以启动期零拦截与既有会话为证")
|
||||
capture(app, "c1-already-home")
|
||||
return
|
||||
}
|
||||
capture(app, "c1-login-page")
|
||||
selectAgreementIfNeeded(app)
|
||||
let submit = app.buttons["login_submit_button"]
|
||||
XCTAssertTrue(submit.waitForExistence(timeout: 10), "未找到登录提交按钮")
|
||||
if !submit.isEnabled {
|
||||
// 提交钮不可用才尝试补输入(v5d 教训:验证码框存在不代表必填,
|
||||
// 盲填占位值反而制造服务端拒绝)。先补图形验证码占位值,再退化到账号框刷新。
|
||||
let captcha = app.textFields.containing(NSPredicate(format: "placeholderValue CONTAINS '验证码'")).firstMatch
|
||||
if captcha.exists {
|
||||
captcha.tap()
|
||||
captcha.typeText("1111")
|
||||
step("C1 提交钮不可用,已补图形验证码占位值 isEnabled=\(submit.isEnabled)")
|
||||
}
|
||||
if !submit.isEnabled {
|
||||
let account = app.textFields["login_phone_input"].firstMatch
|
||||
if account.exists { account.tap(); account.typeText("1") }
|
||||
step("C1 仍不可用,已触发账号输入刷新 isEnabled=\(submit.isEnabled)")
|
||||
}
|
||||
}
|
||||
capture(app, "c1-before-submit")
|
||||
submit.tap()
|
||||
// 放行判定(v6 修订):核心断言 = 门禁 toast 不出现(门禁放行)。
|
||||
// 业务进展尽力而为留证:DEBUG 预填账号的图形验证码无法自动识别,服务端
|
||||
// 拒绝时停留登录页属业务侧限制而非门禁问题(v5e 留证:干净提交后门禁
|
||||
// toast 与协议弹窗均未出现)。登录态若未建立,D1/E1 以游客守卫跳过。
|
||||
let gateToast = app.staticTexts[blockLoginToast].firstMatch
|
||||
XCTAssertFalse(gateToast.waitForExistence(timeout: 6), "干净环境出现门禁 toast(误拦截)")
|
||||
let home = app.otherElements["home_page_anchor"]
|
||||
let agreementAlert = app.alerts["请先阅读并同意协议"]
|
||||
let progress = home.waitForExistence(timeout: 45)
|
||||
|| agreementAlert.waitForExistence(timeout: 5)
|
||||
step("C1 门禁放行成立;业务进展标记=\(progress)(验证码服务端拒绝属业务侧限制)")
|
||||
capture(app, "c1-after-login-attempt")
|
||||
}
|
||||
|
||||
// MARK: - D/E 拦截相位(注入启动·VIP 与激活入口)
|
||||
|
||||
func testD1BlockVipPurchase() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("D1 注入启动·VIP 购买门禁")
|
||||
try launchApp(app, injected: true)
|
||||
try waitHomeStable(app, timeout: 90)
|
||||
let vipTab = app.tabBars.buttons["会员"].firstMatch
|
||||
XCTAssertTrue(vipTab.waitForExistence(timeout: 10), "未找到「会员」页签")
|
||||
vipTab.tap()
|
||||
// v3 树:会员页用户区游客显示「游客」——登录态缺失时购买被业务游客检查
|
||||
// 拦在 sendPayVip 门禁之前,skip 留证而不误判门禁失效。
|
||||
_ = app.staticTexts["游客"].waitForExistence(timeout: 5)
|
||||
if app.staticTexts["游客"].firstMatch.exists {
|
||||
capture(app, "d1-guest-state")
|
||||
try skipAndCapture("会员页为游客态(C1 未建立登录态),VIP 门禁需登录后重跑")
|
||||
}
|
||||
// v2 树:购买按钮为富文本 label(如「立即购买 · ¥6.00 100.00」),已会员时为「立即续费 …」。
|
||||
let buyPred = NSPredicate(format: "label BEGINSWITH '立即购买' OR label BEGINSWITH '立即续费'")
|
||||
let buyBtn = app.buttons.containing(buyPred).firstMatch
|
||||
XCTAssertTrue(buyBtn.waitForExistence(timeout: 15), "会员页未出现购买按钮(见 d1 勘察树)")
|
||||
sleep(2)
|
||||
dismissPopups(app)
|
||||
capture(app, "d1-vip-page")
|
||||
// 先勾选 VIP 协议(未勾选时点购买先弹协议提示,越不过门禁汇合点)。
|
||||
let checkbox = app.buttons["rd vip checkbox unselect"].firstMatch
|
||||
if checkbox.exists, checkbox.isHittable {
|
||||
checkbox.tap()
|
||||
step("D1 已勾选 VIP 协议")
|
||||
} else {
|
||||
capture(app, "d1-checkbox-missing")
|
||||
}
|
||||
buyBtn.tap()
|
||||
step("D1 点击购买按钮「\(buyBtn.label)」")
|
||||
assertToast(app, text: blockVipToast, label: "d1-block-vip")
|
||||
}
|
||||
|
||||
func testE1BlockActivation() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("E1 注入启动·激活码门禁")
|
||||
try launchApp(app, injected: true)
|
||||
try waitHomeStable(app, timeout: 90)
|
||||
let mineTab = app.tabBars.buttons["我的"].firstMatch
|
||||
XCTAssertTrue(mineTab.waitForExistence(timeout: 10), "未找到「我的」页签")
|
||||
mineTab.tap()
|
||||
sleep(2)
|
||||
dismissPopups(app)
|
||||
capture(app, "e1-mine-page")
|
||||
// 激活入口探测(标签以勘察树为准)。
|
||||
var activationEntered = false
|
||||
for keyword in ["激活码", "激活"] {
|
||||
let entryBtn = app.buttons.containing(NSPredicate(format: "label CONTAINS %@", keyword)).firstMatch
|
||||
let entryText = app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", keyword)).firstMatch
|
||||
if entryBtn.exists { entryBtn.tap(); activationEntered = true; step("E1 点击「\(keyword)」按钮入口"); break }
|
||||
if entryText.exists { entryText.tap(); activationEntered = true; step("E1 点击「\(keyword)」文本入口"); break }
|
||||
}
|
||||
guard activationEntered else {
|
||||
capture(app, "e1-no-activation-entry")
|
||||
try skipAndCapture("「我的」页未找到激活入口,需按勘察树修正导航")
|
||||
}
|
||||
sleep(2)
|
||||
// v3 教训:游客点「激活码」被带到登录页(激活需登录态)——先判定落点。
|
||||
if app.otherElements["login_page_anchor"].waitForExistence(timeout: 5) {
|
||||
capture(app, "e1-guest-to-login")
|
||||
try skipAndCapture("激活入口要求登录态(C1 未建立登录会话),激活门禁需登录后重跑")
|
||||
}
|
||||
capture(app, "e1-activation-page")
|
||||
// 激活码输入(被拦截环境填占位值即可,请求不会发出)。
|
||||
let codeField = (app.textFields.firstMatch.exists ? app.textFields : app.secureTextFields).firstMatch
|
||||
if codeField.exists {
|
||||
codeField.tap()
|
||||
codeField.typeText("1")
|
||||
}
|
||||
var activated = false
|
||||
for label in ["立即激活", "激活", "确定"] {
|
||||
let button = app.buttons[label].firstMatch
|
||||
if button.exists, button.isHittable { button.tap(); activated = true; step("E1 点击激活按钮「\(label)」"); break }
|
||||
}
|
||||
XCTAssertTrue(activated, "激活页未找到激活按钮(见 e1-activation-page 树)")
|
||||
assertToast(app, text: blockActivationToast, label: "e1-block-activation")
|
||||
}
|
||||
}
|
||||
Vendored
+111
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* anti_tamper_host.c — IGAntiTamper cryptid 核心的宿主自测。
|
||||
*
|
||||
* 用合成 Mach-O 头(header + 可选 LC_ENCRYPTION_INFO_64)驱动 ig_tamper_scan_cryptid,
|
||||
* 覆盖四种情形:加密正常(cryptid=1)、脱壳(cryptid=0)、加密命令被剥除、非分发构建跳过。
|
||||
* 退出码 0 = 全部用例通过。不依赖真机(csops/真实镜像那部分由设备测试覆盖)。
|
||||
*/
|
||||
#include "anti_tamper/IGAntiTamper.h"
|
||||
|
||||
#include <mach-o/loader.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct {
|
||||
int detected; /* DETECTED 条数 */
|
||||
int unavailable; /* UNAVAILABLE 条数 */
|
||||
int last_reason; /* 最后一条 DETECTED 的 reason */
|
||||
} Counter;
|
||||
|
||||
static int sink(const IGFinding *f, void *ctx) {
|
||||
Counter *c = (Counter *)ctx;
|
||||
if (f->status == IG_DETECTED) { c->detected++; c->last_reason = f->reason; }
|
||||
if (f->status == IG_UNAVAILABLE) { c->unavailable++; }
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 构造一个带 ncmds 的最小 mach_header_64;commands 由调用方填好拼在后面。 */
|
||||
typedef struct {
|
||||
struct mach_header_64 mh;
|
||||
union {
|
||||
struct encryption_info_command_64 enc;
|
||||
unsigned char raw[256];
|
||||
} cmds;
|
||||
} FakeImage;
|
||||
|
||||
static void init_header(FakeImage *img, uint32_t ncmds, uint32_t sizeofcmds) {
|
||||
memset(img, 0, sizeof(*img));
|
||||
img->mh.magic = MH_MAGIC_64;
|
||||
img->mh.cputype = CPU_TYPE_ARM64;
|
||||
img->mh.filetype = MH_EXECUTE;
|
||||
img->mh.ncmds = ncmds;
|
||||
img->mh.sizeofcmds = sizeofcmds;
|
||||
}
|
||||
|
||||
static int failures = 0;
|
||||
|
||||
static void check(const char *name, int cond) {
|
||||
if (!cond) { printf("FAIL: %s\n", name); failures++; }
|
||||
else { printf("ok: %s\n", name); }
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
/* 1) cryptid=1:正常加密分发包 → CLEAR,不上报 DETECTED。 */
|
||||
{
|
||||
FakeImage img;
|
||||
init_header(&img, 1, sizeof(struct encryption_info_command_64));
|
||||
img.cmds.enc.cmd = LC_ENCRYPTION_INFO_64;
|
||||
img.cmds.enc.cmdsize = sizeof(struct encryption_info_command_64);
|
||||
img.cmds.enc.cryptid = 1;
|
||||
Counter c = {0, 0, 0};
|
||||
int hits = ig_tamper_scan_cryptid(&img.mh, /*expect_encrypted=*/1, sink, &c);
|
||||
check("cryptid=1 → 0 detected", hits == 0 && c.detected == 0);
|
||||
}
|
||||
|
||||
/* 2) cryptid=0:已脱壳 dump → DETECTED reason=500。 */
|
||||
{
|
||||
FakeImage img;
|
||||
init_header(&img, 1, sizeof(struct encryption_info_command_64));
|
||||
img.cmds.enc.cmd = LC_ENCRYPTION_INFO_64;
|
||||
img.cmds.enc.cmdsize = sizeof(struct encryption_info_command_64);
|
||||
img.cmds.enc.cryptid = 0;
|
||||
Counter c = {0, 0, 0};
|
||||
int hits = ig_tamper_scan_cryptid(&img.mh, 1, sink, &c);
|
||||
check("cryptid=0 → detected 500",
|
||||
hits == 1 && c.detected == 1 && c.last_reason == IG_REASON_BINARY_DECRYPTED);
|
||||
}
|
||||
|
||||
/* 3) 无 LC_ENCRYPTION_INFO(加密命令被剥除)→ DETECTED reason=500。 */
|
||||
{
|
||||
FakeImage img;
|
||||
init_header(&img, 0, 0); /* 零条 load command */
|
||||
Counter c = {0, 0, 0};
|
||||
int hits = ig_tamper_scan_cryptid(&img.mh, 1, sink, &c);
|
||||
check("no-enc-cmd → detected 500",
|
||||
hits == 1 && c.detected == 1 && c.last_reason == IG_REASON_BINARY_DECRYPTED);
|
||||
}
|
||||
|
||||
/* 4) expect_encrypted=0:dev/诊断构建跳过 → UNAVAILABLE,无 DETECTED。 */
|
||||
{
|
||||
FakeImage img;
|
||||
init_header(&img, 1, sizeof(struct encryption_info_command_64));
|
||||
img.cmds.enc.cmd = LC_ENCRYPTION_INFO_64;
|
||||
img.cmds.enc.cmdsize = sizeof(struct encryption_info_command_64);
|
||||
img.cmds.enc.cryptid = 0; /* 即便 0,非分发构建也不判篡改 */
|
||||
Counter c = {0, 0, 0};
|
||||
int hits = ig_tamper_scan_cryptid(&img.mh, /*expect_encrypted=*/0, sink, &c);
|
||||
check("expect_encrypted=0 → unavailable, 0 detected",
|
||||
hits == 0 && c.detected == 0 && c.unavailable == 1);
|
||||
}
|
||||
|
||||
/* 5) NULL 头 + expect=1 → UNAVAILABLE(不崩、不误报)。 */
|
||||
{
|
||||
Counter c = {0, 0, 0};
|
||||
int hits = ig_tamper_scan_cryptid(NULL, 1, sink, &c);
|
||||
check("null header → unavailable, 0 detected",
|
||||
hits == 0 && c.detected == 0 && c.unavailable == 1);
|
||||
}
|
||||
|
||||
printf("%s (%d failures)\n", failures ? "FAILED" : "PASSED", failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 3);
|
||||
void *sdk = dlopen(argv[1], RTLD_NOW); if (!sdk) { puts(dlerror()); return 1; }
|
||||
int (*io)(const char *,const char *,size_t) = dlsym(sdk,"archive_fixture_io");
|
||||
int (*check)(void) = dlsym(sdk,"rd_io_chk");
|
||||
uint64_t (*counter)(unsigned) = dlsym(sdk,"ig_archive_counter");
|
||||
assert(io && check && counter && check() == 0);
|
||||
assert(!io(argv[2],"abcdef",6));
|
||||
for (unsigned i=0;i<4;i++) assert(counter(i*3)>0 && counter(i*3)==counter(i*3+1) && !counter(i*3+2));
|
||||
const struct mach_header_64 *header = NULL;
|
||||
intptr_t slide = 0;
|
||||
for (uint32_t i=0;i<_dyld_image_count();i++) {
|
||||
const char *name = _dyld_get_image_name(i);
|
||||
if (name && strstr(name,"/SSZipArchive.framework/SSZipArchive")) {
|
||||
header=(const void *)_dyld_get_image_header(i); slide=_dyld_get_image_vmaddr_slide(i); break;
|
||||
}
|
||||
}
|
||||
assert(header);
|
||||
const struct symtab_command *symtab=NULL;
|
||||
const struct dysymtab_command *dysymtab=NULL;
|
||||
uintptr_t base=0;
|
||||
const uint8_t *command=(const void *)(header+1);
|
||||
for (uint32_t i=0;i<header->ncmds;i++) {
|
||||
const struct load_command *lc=(const void *)command;
|
||||
if (lc->cmd==LC_SYMTAB) symtab=(const void *)lc;
|
||||
if (lc->cmd==LC_DYSYMTAB) dysymtab=(const void *)lc;
|
||||
if (lc->cmd==LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg=(const void *)lc;
|
||||
if (!strcmp(seg->segname,SEG_LINKEDIT)) base=slide+seg->vmaddr-seg->fileoff;
|
||||
}
|
||||
command+=lc->cmdsize;
|
||||
}
|
||||
assert(base && symtab && dysymtab);
|
||||
const struct nlist_64 *symbols=(const void *)(base+symtab->symoff);
|
||||
const char *strings=(const void *)(base+symtab->stroff);
|
||||
const uint32_t *indirect=(const void *)(base+dysymtab->indirectsymoff);
|
||||
uintptr_t *slot=NULL;
|
||||
command=(const void *)(header+1);
|
||||
for (uint32_t i=0;i<header->ncmds;i++) {
|
||||
const struct load_command *lc=(const void *)command;
|
||||
if (lc->cmd==LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg=(const void *)lc;
|
||||
const struct section_64 *sections=(const void *)(seg+1);
|
||||
for (uint32_t j=0;j<seg->nsects;j++) {
|
||||
const struct section_64 *s=sections+j;
|
||||
if ((s->flags&SECTION_TYPE)!=S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
for (uint64_t k=0;k<s->size/8;k++) {
|
||||
uint32_t n=indirect[s->reserved1+k];
|
||||
if (n&(INDIRECT_SYMBOL_LOCAL|INDIRECT_SYMBOL_ABS)) continue;
|
||||
if (!strcmp(strings+symbols[n].n_un.n_strx,"_rd_a0")) slot=(void *)(slide+s->addr+k*8);
|
||||
}
|
||||
}
|
||||
}
|
||||
command+=lc->cmdsize;
|
||||
}
|
||||
assert(slot);
|
||||
uintptr_t original=*slot;
|
||||
vm_address_t page=(uintptr_t)slot & ~((uintptr_t)vm_page_size-1);
|
||||
assert(vm_protect(mach_task_self(),page,vm_page_size,0,VM_PROT_READ|VM_PROT_WRITE|VM_PROT_COPY)==KERN_SUCCESS);
|
||||
*slot=(uintptr_t)dlsym(RTLD_DEFAULT,"fopen");
|
||||
assert(check()==1);
|
||||
FILE *(*close_entry)(const char *,const char *) = dlsym(sdk,"rd_a0");
|
||||
assert(close_entry && !close_entry("unused","rb") && errno==EACCES);
|
||||
*slot=original;
|
||||
assert(check()==0);
|
||||
assert(!io(argv[2],"ghijkl",6)); unlink(argv[2]);
|
||||
puts("真实 chained binding 转发、GOT 篡改检测及拒绝、恢复均通过");
|
||||
return 0;
|
||||
}
|
||||
Vendored
+59
@@ -0,0 +1,59 @@
|
||||
#include "dispatch/IGArchiveGuard.h"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static unsigned fake_calls;
|
||||
static FILE *fake_open(const char *a, const char *b) { (void)a; (void)b; fake_calls++; return NULL; }
|
||||
static void semantics(void) {
|
||||
char path[] = "/tmp/ig-archive-XXXXXX";
|
||||
int fd = mkstemp(path); assert(fd >= 0); close(fd);
|
||||
errno = EDOM;
|
||||
FILE *out = ig_a0(path, "wb"); assert(out && errno == EDOM);
|
||||
assert(ig_a2("abcdef", 2, 3, out) == 3);
|
||||
assert(ig_a2("", 0, 4, out) == 0);
|
||||
assert(ig_a3(out) == 0);
|
||||
FILE *in = ig_a0(path, "rb"); assert(in);
|
||||
char buffer[16] = {0};
|
||||
assert(ig_a1(buffer, 2, 4, in) == 3);
|
||||
assert(!memcmp(buffer, "abcdef", 6) && feof(in) && !ferror(in));
|
||||
assert(ig_a1(buffer, 1, 1, in) == 0);
|
||||
assert(ig_a3(in) == 0); unlink(path);
|
||||
errno = 0; assert(!ig_a0(path, "rb") && errno == ENOENT);
|
||||
FILE *system = tmpfile(); assert(system);
|
||||
assert(ig_a2("abc", 1, 3, system) == 3);
|
||||
rewind(system); assert(ig_a1(buffer, 1, 3, system) == 3); assert(ig_a3(system) == 0);
|
||||
assert(ig_archive_check() == 0);
|
||||
}
|
||||
static void *thread_run(void *ctx) { (void)ctx; semantics(); return NULL; }
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
if (!strcmp(argv[1], "semantics")) semantics();
|
||||
else if (!strcmp(argv[1], "threads")) {
|
||||
pthread_t t[6];
|
||||
for (unsigned i=0;i<6;i++) assert(!pthread_create(t+i,NULL,thread_run,NULL));
|
||||
for (unsigned i=0;i<6;i++) assert(!pthread_join(t[i],NULL));
|
||||
} else if (!strcmp(argv[1], "tamper")) {
|
||||
ig_archive_test_override(0, (void *)fake_open);
|
||||
assert(ig_a0("unused", "rb") == NULL && errno == EACCES && !fake_calls);
|
||||
errno = EDOM; assert(ig_archive_check() == 1 && errno == EDOM);
|
||||
assert(ig_archive_counter(0) == 1 && ig_archive_counter(1) == 0 && ig_archive_counter(2) == 1);
|
||||
} else if (!strcmp(argv[1], "reentry")) {
|
||||
ig_archive_test_reentry(1);
|
||||
assert(!ig_a0("unused", "rb") && errno == EDEADLK);
|
||||
assert(ig_archive_check() == -1);
|
||||
ig_archive_test_reentry(0); semantics();
|
||||
} else if (!strcmp(argv[1], "rejection")) {
|
||||
FILE *f = tmpfile(); assert(f);
|
||||
char b;
|
||||
for (unsigned i=1;i<4;i++) ig_archive_test_override(i, (void *)fake_open);
|
||||
assert(ig_a1(&b,1,1,f)==0 && errno==EACCES);
|
||||
assert(ig_a2(&b,1,1,f)==0 && errno==EACCES);
|
||||
assert(ig_a3(f)==EOF && errno==EACCES);
|
||||
assert(!fake_calls); fclose(f);
|
||||
} else assert(0);
|
||||
return 0;
|
||||
}
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
/* 动态 SDK fixture:必须通过真实的四个导入完成一次 stdio 往返。 */
|
||||
int archive_fixture_io(const char *path, const char *bytes, size_t count) {
|
||||
FILE *file = fopen(path, "wb");
|
||||
if (!file) return 1;
|
||||
size_t written = fwrite(bytes, 1, count, file);
|
||||
if (fclose(file) || written != count) return 2;
|
||||
file = fopen(path, "rb");
|
||||
if (!file) return 3;
|
||||
char buffer[64] = {0};
|
||||
size_t read = fread(buffer, 1, sizeof(buffer), file);
|
||||
int closed = fclose(file);
|
||||
return closed || read != count || memcmp(bytes, buffer, count) ? 4 : 0;
|
||||
}
|
||||
Vendored
+181
@@ -0,0 +1,181 @@
|
||||
/* 仅宿主测试进程内操作;不修改系统函数代码。 */
|
||||
#include "IGDefender.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include "anti_hook/IGObjCBaseline.h"
|
||||
#include "anti_debug/IGAntiDebug.h"
|
||||
#include "anti_frida/IGAntiInject.h"
|
||||
#include <dlfcn.h>
|
||||
#include <objc/objc.h>
|
||||
#include <objc/runtime.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
|
||||
typedef struct { int reasons[512]; int detected; int unavailable; } Findings;
|
||||
static int collect(const IGFinding *f, void *context) {
|
||||
Findings *out = context;
|
||||
if (f->reason >= 0 && f->reason < 512) out->reasons[f->reason]++;
|
||||
if (f->status == IG_DETECTED) out->detected++;
|
||||
if (f->status == IG_UNAVAILABLE) out->unavailable++;
|
||||
printf("status=%d reason=%d subject=%s evidence=%s\n",
|
||||
f->status, f->reason, f->subject, f->evidence);
|
||||
return 0;
|
||||
}
|
||||
static int fake_getpid(void) { return 123; }
|
||||
/* 函数地址表达式确保本测试镜像包含 getpid 的 GOT 引用。 */
|
||||
__attribute__((noinline)) static void *getpid_address(void) { return (void *)getpid; }
|
||||
|
||||
/* ---- ObjC IMP 基线 fixture:运行期创建类,两条实现可互换 ---- */
|
||||
static int imp_original(void *self, SEL _cmd) { (void)self; (void)_cmd; return 1; }
|
||||
static int imp_replaced(void *self, SEL _cmd) { (void)self; (void)_cmd; return 2; }
|
||||
static Class make_fixture_class(void) {
|
||||
Class existing = objc_getClass("IGFixtureHookTarget");
|
||||
if (existing) return existing;
|
||||
Class c = objc_allocateClassPair(objc_getClass("NSObject"), "IGFixtureHookTarget", 0);
|
||||
if (!c) return NULL;
|
||||
if (!class_addMethod(c, sel_registerName("value"), (IMP)imp_original, "i16@0:8")) {
|
||||
objc_disposeClassPair(c);
|
||||
return NULL;
|
||||
}
|
||||
Class meta = object_getClass((id)c);
|
||||
if (!meta || !class_addMethod(meta, sel_registerName("classValue"), (IMP)imp_original, "i16@0:8")) {
|
||||
objc_disposeClassPair(c);
|
||||
return NULL;
|
||||
}
|
||||
objc_registerClassPair(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
static void **getpid_slot(void) {
|
||||
const struct mach_header_64 *h = (const void *)_dyld_get_image_header(0);
|
||||
intptr_t slide = _dyld_get_image_vmaddr_slide(0);
|
||||
const struct segment_command_64 *le = NULL;
|
||||
const struct symtab_command *sy = NULL;
|
||||
const struct dysymtab_command *dy = NULL;
|
||||
const unsigned char *p = (const void *)(h+1);
|
||||
for (unsigned i=0; i<h->ncmds; i++) {
|
||||
const struct load_command *lc=(const void *)p;
|
||||
if (lc->cmd==LC_SEGMENT_64 && !strcmp(((const struct segment_command_64 *)p)->segname,"__LINKEDIT")) le=(const void *)p;
|
||||
if (lc->cmd==LC_SYMTAB) sy=(const void *)p;
|
||||
if (lc->cmd==LC_DYSYMTAB) dy=(const void *)p;
|
||||
p+=lc->cmdsize;
|
||||
}
|
||||
if (!le || !sy || !dy) return NULL;
|
||||
uintptr_t base=slide+le->vmaddr-le->fileoff;
|
||||
const struct nlist_64 *symbols=(const void *)(base+sy->symoff);
|
||||
const char *strings=(const void *)(base+sy->stroff);
|
||||
const uint32_t *indirect=(const void *)(base+dy->indirectsymoff);
|
||||
p=(const void *)(h+1);
|
||||
for (unsigned i=0; i<h->ncmds; i++) {
|
||||
const struct load_command *lc=(const void *)p;
|
||||
if (lc->cmd==LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg=(const void *)p;
|
||||
const struct section_64 *s=(const void *)(seg+1);
|
||||
for (unsigned j=0; j<seg->nsects; j++) {
|
||||
if ((s[j].flags & SECTION_TYPE)!=S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
for (unsigned k=0; k<s[j].size/sizeof(void *); k++) {
|
||||
uint32_t n=indirect[s[j].reserved1+k];
|
||||
if (n & (INDIRECT_SYMBOL_LOCAL|INDIRECT_SYMBOL_ABS)) continue;
|
||||
if (!strcmp(strings+symbols[n].n_un.n_strx,"_getpid"))
|
||||
return (void **)(slide+s[j].addr)+k;
|
||||
}
|
||||
}
|
||||
}
|
||||
p+=lc->cmdsize;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc<2) return 2;
|
||||
Findings f={0};
|
||||
if (!strcmp(argv[1],"clean")) {
|
||||
int hits=ig_defender_scan(NULL,0,collect,&f);
|
||||
/* 越狱文件探针(400/401)在 macOS 宿主必然命中:mac 自带完整 Unix userland
|
||||
* (/usr/sbin/sshd、/bin/bash、/bin/sh…),按 iOS 标准宿主本身即“越狱”。
|
||||
* 这是宿主/iOS 环境差异,非真实误报——iOS 非越狱设备上这些路径不存在/沙盒不可达,
|
||||
* 其反向零命中由真机 R 组验证(docs/19)。故宿主 clean 只对非越狱探针断言零 DETECTED。 */
|
||||
int jb = f.reasons[IG_REASON_JAILBREAK_FILE] + f.reasons[IG_REASON_JAILBREAK_SANDBOX];
|
||||
int non_jb_detected = f.detected - jb;
|
||||
return hits!=f.detected || non_jb_detected || f.unavailable;
|
||||
}
|
||||
if (!strcmp(argv[1],"unresolved")) {
|
||||
const char *names[]={"IG_fixture_symbol_that_does_not_exist_123"};
|
||||
int hits=ig_anti_hook_check(names,1,collect,&f);
|
||||
return hits || f.unavailable!=1 || f.reasons[IG_REASON_SYMBOL_UNRESOLVED]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"verify")) {
|
||||
if (ig_verify_function(NULL,"null",collect,&f)!=IG_UNAVAILABLE) return 3;
|
||||
if (ig_verify_function(getpid_address(),"getpid",collect,&f)!=IG_CLEAR) return 4;
|
||||
return ig_verify_function((void *)fake_getpid,"local_fixture",collect,&f)!=IG_DETECTED
|
||||
|| f.reasons[IG_REASON_SYMBOL_PROVENANCE]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"env")) {
|
||||
setenv("DYLD_INSERT_LIBRARIES","/tmp/ig_fixture_a:/tmp/ig_fixture_b",1);
|
||||
ig_anti_inject_check(NULL,collect,&f);
|
||||
unsetenv("DYLD_INSERT_LIBRARIES");
|
||||
return f.reasons[IG_REASON_DYLD_INSERT]!=2;
|
||||
}
|
||||
if (!strcmp(argv[1],"image")) {
|
||||
if (argc<3 || !dlopen(argv[2],RTLD_NOW)) return 5;
|
||||
ig_anti_inject_check(NULL,collect,&f);
|
||||
return f.reasons[IG_REASON_INJECTED_IMAGE]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"got")) {
|
||||
const char *names[]={"getpid"};
|
||||
if (!getpid_address() || ig_anti_hook_check(names,1,collect,&f)!=0) return 6;
|
||||
void **slot=getpid_slot();
|
||||
if (!slot) { fprintf(stderr,"未找到测试 GOT 槽\n"); return 7; }
|
||||
void *original=*slot;
|
||||
vm_size_t size=getpagesize();
|
||||
vm_address_t page=(uintptr_t)slot & ~(size-1);
|
||||
if (vm_protect(mach_task_self(),page,size,0,VM_PROT_READ|VM_PROT_WRITE|VM_PROT_COPY)!=KERN_SUCCESS) return 8;
|
||||
*slot=(void *)fake_getpid;
|
||||
int hits=ig_anti_hook_check(names,1,collect,&f);
|
||||
*slot=original;
|
||||
return hits!=1 || f.reasons[IG_REASON_GOT_REBIND]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"debugger")) {
|
||||
/* 正常(无调试器)环境:clear 且 sysctl 可判定。
|
||||
* 正向(P_TRACED 命中)由 lldb 场景验证,docs/12 已实测。 */
|
||||
ig_anti_debug_check(collect,&f);
|
||||
return f.detected || f.unavailable;
|
||||
}
|
||||
if (!strcmp(argv[1],"objc-clean")) {
|
||||
if (!make_fixture_class()) return 9;
|
||||
const IGObjCWatch watch[] = { { "IGFixtureHookTarget", "value" } };
|
||||
if (ig_objc_baseline_capture(watch,1)!=1) return 10;
|
||||
const IGObjCWatch cls_watch[] = { { "IGFixtureHookTarget", "classValue" } };
|
||||
if (ig_objc_baseline_append(cls_watch,1)!=1 || ig_objc_baseline_count()!=2) return 12;
|
||||
if (ig_objc_baseline_append(watch,1)!=0 || ig_objc_baseline_count()!=2) return 13;
|
||||
/* 无法解析的观察项独立报告 unavailable。 */
|
||||
const IGObjCWatch none[] = { { "IGClassThatNeverExists123", "x" } };
|
||||
ig_objc_baseline_capture(none,1);
|
||||
if (ig_objc_baseline_check(collect,&f)!=0 || f.unavailable!=1) return 11;
|
||||
f.unavailable=0;
|
||||
ig_objc_baseline_capture(watch,1);
|
||||
ig_objc_baseline_append(cls_watch,1);
|
||||
int hits=ig_objc_baseline_check(collect,&f);
|
||||
return hits!=0 || f.detected || f.unavailable!=2; /* 动态创建的类没有构建基线。 */
|
||||
}
|
||||
if (!strcmp(argv[1],"objc-swap")) {
|
||||
Class c=make_fixture_class();
|
||||
if (!c) return 9;
|
||||
const IGObjCWatch watch[] = {
|
||||
{ "IGFixtureHookTarget", "value" },
|
||||
{ "IGFixtureHookTarget", "+classValue" }
|
||||
};
|
||||
if (ig_objc_baseline_capture(watch,2)!=2) return 10;
|
||||
/* class_replaceMethod:实例方法与类方法同时换人 → 期望 DETECTED(110) x2。 */
|
||||
class_replaceMethod(c, sel_registerName("value"), (IMP)imp_replaced, "i16@0:8");
|
||||
class_replaceMethod(object_getClass((id)c), sel_registerName("classValue"), (IMP)imp_replaced, "i16@0:8");
|
||||
int hits=ig_objc_baseline_check(collect,&f);
|
||||
return hits!=2 || f.reasons[IG_REASON_OBJC_IMP_CHANGED]!=2;
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
/* 独立诊断进程:只在自身进程测试,不连接业务、不改系统代码。 */
|
||||
#import <Foundation/Foundation.h>
|
||||
#include "IGDefender.h"
|
||||
#include <stdio.h>
|
||||
|
||||
int ig_dispatch_fixture_main(int argc, char **argv);
|
||||
static int findings, unavailable;
|
||||
static int collect(const IGFinding *f, void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->status==IG_DETECTED) findings++;
|
||||
if (f->status==IG_UNAVAILABLE) unavailable++;
|
||||
NSLog(@"IG_DEVICE_FINDING status=%d reason=%d subject=%s evidence=%s",
|
||||
f->status,f->reason,f->subject,f->evidence);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc,char **argv) {
|
||||
(void)argc;(void)argv;
|
||||
@autoreleasepool {
|
||||
NSLog(@"IG_DEVICE_MAIN");
|
||||
const char *modes[]={"semantics","short-write","eintr","threads","reentry","resolver","prologue","tamper"};
|
||||
int hits=ig_defender_scan(NSBundle.mainBundle.bundlePath.UTF8String,0,collect,NULL);
|
||||
NSLog(@"IG_DEVICE_BASELINE detected=%d unavailable=%d hits=%d",findings,unavailable,hits);
|
||||
for (unsigned i=0;i<sizeof(modes)/sizeof(modes[0]);i++) {
|
||||
char *args[]={"dispatch-device",(char *)modes[i],NULL};
|
||||
int rc=ig_dispatch_fixture_main(2,args);
|
||||
NSLog(@"IG_DEVICE_CASE %s %s",modes[i],rc==0 ? "PASS" : "FAIL");
|
||||
if (rc) return rc;
|
||||
}
|
||||
NSLog(@"IG_DEVICE_SUITE PASS cases=8 baseline_detected=%d baseline_unavailable=%d",findings,unavailable);
|
||||
/* 诊断进程退出便于 console 收集退出码;不编入业务 App。 */
|
||||
return findings || unavailable ? 3 : 0;
|
||||
}
|
||||
}
|
||||
Vendored
+246
@@ -0,0 +1,246 @@
|
||||
#include "dispatch/IGDispatch.h"
|
||||
#include "resolve/IGResolve.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
static int early_ok;
|
||||
__attribute__((constructor)) static void early(void) {
|
||||
#ifdef IG_EXPECT_INIT_FAILURE
|
||||
early_ok=1;
|
||||
#else
|
||||
int fd=open("/dev/null",O_WRONLY);
|
||||
early_ok=fd>=0 && IG_dispatch_write(fd,"early",5)==5 && IG_dispatch_close(fd)==0;
|
||||
#endif
|
||||
}
|
||||
void *ig_fixture_missing_resolve(void *handle, const char *name) { (void)handle; (void)name; return NULL; }
|
||||
static int reasons[256], unavailable;
|
||||
static int collect(const IGFinding *f,void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->reason>=0 && f->reason<256) reasons[f->reason]++;
|
||||
if (f->status==IG_UNAVAILABLE) unavailable++;
|
||||
return 0;
|
||||
}
|
||||
static int fake_close(int fd) { (void)fd; abort(); }
|
||||
static void *writer(void *ctx) {
|
||||
(void)ctx;
|
||||
int fd=open("/dev/null",O_WRONLY);
|
||||
assert(fd>=0);
|
||||
for (int i=0;i<100;i++) assert(IG_dispatch_write(fd,"abc",3)==3);
|
||||
assert(IG_dispatch_close(fd)==0);
|
||||
return NULL;
|
||||
}
|
||||
static void signal_handler(int sig) { (void)sig; }
|
||||
static pthread_t main_thread;
|
||||
static void *interruptor(void *ctx) { (void)ctx; usleep(30000); pthread_kill(main_thread,SIGUSR1); return NULL; }
|
||||
|
||||
int main(int argc,char **argv) {
|
||||
assert(argc==2 && early_ok);
|
||||
if (!strcmp(argv[1],"observation")) {
|
||||
#ifdef IG_OBSERVATION
|
||||
IGDispatchObservation before=ig_dispatch_observation();
|
||||
errno=0; assert(IG_dispatch_write(-1,"x",1)==-1 && errno==EBADF);
|
||||
errno=0; assert(IG_dispatch_close(-1)==-1 && errno==EBADF);
|
||||
IGDispatchObservation after=ig_dispatch_observation();
|
||||
assert(after.write_attempted==before.write_attempted+1);
|
||||
assert(after.write_dispatched==before.write_dispatched+1);
|
||||
assert(after.close_attempted==before.close_attempted+1);
|
||||
assert(after.close_dispatched==before.close_dispatched+1);
|
||||
ig_dispatch_test_override(1,(void *)fake_close);
|
||||
assert(IG_dispatch_close(-1)==-1 && errno==EACCES);
|
||||
IGDispatchObservation rejected=ig_dispatch_observation();
|
||||
assert(rejected.close_attempted==after.close_attempted+1);
|
||||
assert(rejected.close_dispatched==after.close_dispatched);
|
||||
#else
|
||||
return 2;
|
||||
#endif
|
||||
} else if (!strcmp(argv[1],"init-failure")) {
|
||||
assert(IG_dispatch_write(-1,"x",1)==-1 && errno==ENOSYS);
|
||||
assert(IG_dispatch_close(-1)==-1 && errno==ENOSYS);
|
||||
char b;
|
||||
assert(IG_dispatch_read(-1,&b,1)==-1 && errno==ENOSYS);
|
||||
assert(IG_dispatch_open("/dev/null",O_RDONLY)==-1 && errno==ENOSYS);
|
||||
assert(IG_dispatch_unlink("/tmp/ig-must-not-remove")==-1 && errno==ENOSYS);
|
||||
assert(IG_dispatch_getpid()==-1 && errno==ENOSYS);
|
||||
assert(IG_dispatch_fork()==-1 && errno==ENOSYS);
|
||||
assert(IG_dispatch_dlopen(NULL,RTLD_LAZY)==NULL && errno==ENOSYS);
|
||||
assert(IG_dispatch_dlsym(RTLD_DEFAULT,"getpid")==NULL && errno==ENOSYS);
|
||||
assert(ig_dispatch_check(collect,NULL)==0 && unavailable==11);
|
||||
assert(reasons[IG_REASON_DISPATCH_UNAVAILABLE]==11);
|
||||
} else if (!strcmp(argv[1],"extended")) {
|
||||
char path[]="/tmp/ig-dispatch-XXXXXX";
|
||||
int fd=mkstemp(path); assert(fd>=0); close(fd); unlink(path);
|
||||
mode_t mask=umask(0);
|
||||
errno=EDOM; fd=IG_dispatch_open(path,O_CREAT|O_EXCL|O_RDWR,0600);
|
||||
umask(mask);
|
||||
assert(fd>=0 && errno==EDOM);
|
||||
struct stat st; assert(fstat(fd,&st)==0 && (st.st_mode & 0777)==0600);
|
||||
assert(IG_dispatch_write(fd,"abc",3)==3); assert(lseek(fd,0,SEEK_SET)==0);
|
||||
char bytes[16]={0}; errno=ERANGE;
|
||||
assert(IG_dispatch_read(fd,bytes,sizeof(bytes))==3 && !memcmp(bytes,"abc",3) && errno==ERANGE);
|
||||
assert(IG_dispatch_read(fd,bytes,sizeof(bytes))==0);
|
||||
assert(IG_dispatch_close(fd)==0);
|
||||
fd=IG_dispatch_open(path,O_RDONLY); assert(fd>=0); assert(IG_dispatch_close(fd)==0);
|
||||
assert(IG_dispatch_open(path,O_CREAT|O_EXCL|O_RDWR,0600)==-1 && errno==EEXIST);
|
||||
FILE *stream=IG_dispatch_fopen(path,"r");
|
||||
assert(stream && fgetc(stream)=='a' && fclose(stream)==0);
|
||||
assert(IG_dispatch_unlink(path)==0);
|
||||
assert(IG_dispatch_fopen(path,"r")==NULL && errno==ENOENT);
|
||||
assert(IG_dispatch_open(path,O_RDONLY)==-1 && errno==ENOENT);
|
||||
assert(IG_dispatch_unlink(path)==-1 && errno==ENOENT);
|
||||
assert(IG_dispatch_read(-1,bytes,1)==-1 && errno==EBADF);
|
||||
errno=EDOM; assert(IG_dispatch_getpid()==getpid() && errno==EDOM);
|
||||
void *self_handle=IG_dispatch_dlopen(NULL,RTLD_LAZY);
|
||||
assert(self_handle!=NULL);
|
||||
assert(IG_dispatch_dlsym(RTLD_DEFAULT,"getpid")==dlsym(RTLD_DEFAULT,"getpid"));
|
||||
pid_t child=IG_dispatch_fork();
|
||||
assert(child>=0);
|
||||
if (child==0) IG_dispatch_exit(42);
|
||||
int wstatus=0;
|
||||
assert(waitpid(child,&wstatus,0)==child && WIFEXITED(wstatus) && WEXITSTATUS(wstatus)==42);
|
||||
} else if (!strcmp(argv[1],"extended-tamper")) {
|
||||
pid_t child=fork();
|
||||
assert(child>=0);
|
||||
if (child==0) {
|
||||
ig_dispatch_test_override(7,(void *)fake_close);
|
||||
IG_dispatch_exit(37);
|
||||
}
|
||||
int wstatus=0;
|
||||
assert(waitpid(child,&wstatus,0)==child && WIFEXITED(wstatus) && WEXITSTATUS(wstatus)==37);
|
||||
for (unsigned i=2;i<11;i++) ig_dispatch_test_override(i,(void *)fake_close);
|
||||
char bytes[1];
|
||||
assert(IG_dispatch_read(-1,bytes,1)==-1 && errno==EACCES);
|
||||
assert(IG_dispatch_open("/dev/null",O_RDONLY)==-1 && errno==EACCES);
|
||||
assert(IG_dispatch_unlink("/tmp/ig-must-not-remove")==-1 && errno==EACCES);
|
||||
assert(IG_dispatch_getpid()==-1 && errno==EACCES);
|
||||
assert(IG_dispatch_fopen("/dev/null","r")==NULL && errno==EACCES);
|
||||
assert(IG_dispatch_fork()==-1 && errno==EACCES);
|
||||
assert(IG_dispatch_dlopen(NULL,RTLD_LAZY)==NULL && errno==EACCES);
|
||||
assert(IG_dispatch_dlsym(RTLD_DEFAULT,"getpid")==NULL && errno==EACCES);
|
||||
assert(ig_dispatch_check(collect,NULL)==9 && reasons[IG_REASON_DISPATCH_TAMPER]==9);
|
||||
} else if (!strcmp(argv[1],"read-eintr")) {
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
struct sigaction action={0};action.sa_handler=signal_handler;sigemptyset(&action.sa_mask);
|
||||
assert(sigaction(SIGUSR1,&action,NULL)==0);
|
||||
main_thread=pthread_self();pthread_t thread;
|
||||
assert(pthread_create(&thread,NULL,interruptor,NULL)==0);
|
||||
char b; assert(IG_dispatch_read(p[0],&b,1)==-1 && errno==EINTR);
|
||||
pthread_join(thread,NULL);IG_dispatch_close(p[1]);IG_dispatch_close(p[0]);
|
||||
} else if (!strcmp(argv[1],"semantics")) {
|
||||
assert(ig_dispatch_check(collect,NULL)==0 && unavailable==0);
|
||||
errno=0; assert(IG_dispatch_write(-1,"x",1)==-1 && errno==EBADF);
|
||||
errno=0; assert(IG_dispatch_close(-1)==-1 && errno==EBADF);
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
errno=EDOM; assert(IG_dispatch_write(p[1],"abc",3)==3 && errno==EDOM);
|
||||
char b[4]={0}; assert(read(p[0],b,3)==3 && !memcmp(b,"abc",3));
|
||||
assert(IG_dispatch_close(p[1])==0 && IG_dispatch_close(p[0])==0);
|
||||
} else if (!strcmp(argv[1],"short-write")) {
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
assert(fcntl(p[1],F_SETFL,O_NONBLOCK)==0);
|
||||
const size_t count=1024*1024;
|
||||
char *bytes=calloc(count,1);assert(bytes);
|
||||
ssize_t n=IG_dispatch_write(p[1],bytes,count);
|
||||
assert(n>0 && n<(ssize_t)count);
|
||||
while (IG_dispatch_write(p[1],bytes,count)>0) {}
|
||||
assert(errno==EAGAIN);
|
||||
IG_dispatch_close(p[1]); IG_dispatch_close(p[0]);
|
||||
free(bytes);
|
||||
} else if (!strcmp(argv[1],"eintr")) {
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
assert(fcntl(p[1],F_SETFL,O_NONBLOCK)==0);
|
||||
char bytes[4096]={0}; while (write(p[1],bytes,sizeof(bytes))>0) {}
|
||||
assert(errno==EAGAIN && fcntl(p[1],F_SETFL,0)==0);
|
||||
struct sigaction action={0};action.sa_handler=signal_handler;sigemptyset(&action.sa_mask);
|
||||
assert(sigaction(SIGUSR1,&action,NULL)==0);
|
||||
main_thread=pthread_self();pthread_t thread;
|
||||
assert(pthread_create(&thread,NULL,interruptor,NULL)==0);
|
||||
assert(IG_dispatch_write(p[1],bytes,sizeof(bytes))==-1 && errno==EINTR);
|
||||
pthread_join(thread,NULL);IG_dispatch_close(p[1]);IG_dispatch_close(p[0]);
|
||||
} else if (!strcmp(argv[1],"threads")) {
|
||||
pthread_t threads[8];
|
||||
for (unsigned i=0;i<8;i++) assert(pthread_create(&threads[i],NULL,writer,NULL)==0);
|
||||
for (unsigned i=0;i<8;i++) pthread_join(threads[i],NULL);
|
||||
} else if (!strcmp(argv[1],"tamper")) {
|
||||
ig_dispatch_test_override(1,(void *)fake_close);
|
||||
errno=0; assert(IG_dispatch_close(-1)==-1 && errno==EACCES);
|
||||
assert(ig_dispatch_check(collect,NULL)==1 && reasons[IG_REASON_DISPATCH_TAMPER]==1);
|
||||
} else if (!strcmp(argv[1],"reentry")) {
|
||||
ig_dispatch_test_reentry(1);
|
||||
assert(IG_dispatch_close(-1)==-1 && errno==EDEADLK);
|
||||
ig_dispatch_test_reentry(0);
|
||||
} else if (!strcmp(argv[1],"resolver")) {
|
||||
unsigned char encoded[300];memset(encoded,'x',sizeof(encoded));char out[4];
|
||||
assert(!ig_decrypt(encoded,1,out,0));assert(!ig_decrypt(NULL,1,out,sizeof(out)));
|
||||
assert(!ig_decrypt(encoded,4,out,sizeof(out)) && out[0]==0);
|
||||
encoded[0]=IG_ENC_KEY;assert(!ig_decrypt(encoded,1,out,sizeof(out)));
|
||||
assert(ig_resolve_verified(NULL,encoded,300,NULL,NULL).status==IG_UNAVAILABLE);
|
||||
const char *name="IG_missing_symbol_774444";
|
||||
for (unsigned i=0;i<strlen(name);i++) encoded[i]=name[i]^IG_ENC_KEY;
|
||||
assert(ig_resolve_verified(NULL,encoded,strlen(name),collect,NULL).status==IG_UNAVAILABLE);
|
||||
assert(reasons[IG_REASON_SYMBOL_UNRESOLVED]==1);
|
||||
assert(ig_verify_function((void *)1,"invalid",collect,NULL)==IG_UNAVAILABLE);
|
||||
assert(reasons[IG_REASON_VERIFICATION_UNAVAILABLE]==1);
|
||||
} else if (!strcmp(argv[1],"prologue")) {
|
||||
assert(!ig_arm64_suspicious_prologue(0x14000001,0));
|
||||
assert(ig_arm64_suspicious_prologue(0x58000050,0xd61f0200));
|
||||
assert(ig_arm64_suspicious_prologue(0x58000049,0xd61f0120)); /* ldr x9; br x9 */
|
||||
assert(!ig_arm64_suspicious_prologue(0x58000050,0xd61f0220));
|
||||
assert(!ig_arm64_suspicious_prologue(0x18000050,0xd61f0200));
|
||||
assert(!ig_arm64_suspicious_prologue(0xd503245f,0xd65f03c0));
|
||||
const uint32_t clean_win[8] = {
|
||||
0xd503237fu, 0xa9bf7bfdu, 0x910003fdu, 0xaa0003f3u,
|
||||
0xf100001fu, 0x54000080u, 0xd503201fu, 0xd65f03c0u
|
||||
};
|
||||
assert(!ig_arm64_suspicious_window(clean_win, 8));
|
||||
const uint32_t adrp_win[8] = {
|
||||
0xd503237fu, 0x9000000au, 0x9100414au, 0xd61f0140u,
|
||||
0xd503201fu, 0xd503201fu, 0xd503201fu, 0xd503201fu
|
||||
};
|
||||
assert(ig_arm64_suspicious_window(adrp_win, 8));
|
||||
const uint32_t movk_win[8] = {
|
||||
0xd280000bu, 0xf2c2468bu, 0xd61f0160u, 0xd503201fu,
|
||||
0xd503201fu, 0xd503201fu, 0xd503201fu, 0xd503201fu
|
||||
};
|
||||
assert(ig_arm64_suspicious_window(movk_win, 8));
|
||||
const uint32_t mid_ldr_win[8] = {
|
||||
0xd503237fu, 0xa9bf7bfdu, 0x910003fdu, 0x58000050u,
|
||||
0xd61f0200u, 0xd503201fu, 0xd503201fu, 0xd503201fu
|
||||
};
|
||||
assert(ig_arm64_suspicious_window(mid_ldr_win, 8));
|
||||
#if defined(__arm64__) || defined(__aarch64__)
|
||||
void *sys_getpid = dlsym(RTLD_DEFAULT, "getpid");
|
||||
void *sys_ftell = dlsym(RTLD_DEFAULT, "ftell");
|
||||
assert(sys_getpid != NULL && sys_ftell != NULL);
|
||||
const uint32_t local_b[1] = {0x14000000u};
|
||||
assert(ig_arm64_trampoline_to_foreign(local_b, local_b, 1));
|
||||
assert(ig_verify_function(sys_ftell, "ftell", collect, NULL) == IG_CLEAR);
|
||||
struct { uint32_t ins[2]; uint64_t dst; } __attribute__((aligned(8))) ldr_tramp = {
|
||||
{0x58000050u, 0xd61f0200u}, (uint64_t)(uintptr_t)collect
|
||||
};
|
||||
assert(ig_arm64_trampoline_to_foreign(ldr_tramp.ins, ldr_tramp.ins, 2));
|
||||
ldr_tramp.dst = (uint64_t)(uintptr_t)sys_getpid;
|
||||
assert(!ig_arm64_trampoline_to_foreign(ldr_tramp.ins, ldr_tramp.ins, 2));
|
||||
uintptr_t foreign_dst = (uintptr_t)collect;
|
||||
uint32_t adrp_foreign[3];
|
||||
intptr_t page_delta = ((intptr_t)(foreign_dst & ~(uintptr_t)0xfffu) -
|
||||
(intptr_t)((uintptr_t)adrp_foreign & ~(uintptr_t)0xfffu)) >> 12;
|
||||
uint32_t imm21 = (uint32_t)page_delta & 0x1fffffu;
|
||||
adrp_foreign[0] = 0x90000010u | ((imm21 & 3u) << 29) | ((imm21 >> 2) << 5);
|
||||
adrp_foreign[1] = 0x91000210u | ((uint32_t)(foreign_dst & 0xfffu) << 10);
|
||||
adrp_foreign[2] = 0xd61f0200u;
|
||||
assert(ig_arm64_trampoline_to_foreign(adrp_foreign, adrp_foreign, 3));
|
||||
assert(ig_arm64_trampoline_to_foreign(movk_win, movk_win, 8));
|
||||
assert(!ig_arm64_trampoline_to_foreign(clean_win, clean_win, 8));
|
||||
#endif
|
||||
} else return 2;
|
||||
return 0;
|
||||
}
|
||||
Vendored
+112
@@ -0,0 +1,112 @@
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern FILE *sdk_open(const char *path, const char *mode);
|
||||
|
||||
#ifdef IG_TEST_ALL_BRIDGES
|
||||
extern int sdk_fclose(FILE *);
|
||||
extern size_t sdk_fread(void *, size_t, size_t, FILE *);
|
||||
extern size_t sdk_fwrite(const void *, size_t, size_t, FILE *);
|
||||
extern ssize_t sdk_read(int, void *, size_t);
|
||||
extern ssize_t sdk_write(int, const void *, size_t);
|
||||
extern int sdk_close(int);
|
||||
#define fclose sdk_fclose
|
||||
#define fread sdk_fread
|
||||
#define fwrite sdk_fwrite
|
||||
|
||||
static void exercise_posix(void) {
|
||||
int descriptors[2];
|
||||
char buffer[4096] = {0};
|
||||
assert(pipe(descriptors) == 0);
|
||||
assert(sdk_write(descriptors[1], "X", 1) == 1);
|
||||
assert(sdk_read(descriptors[0], buffer, sizeof(buffer)) == 1);
|
||||
assert(buffer[0] == 'X');
|
||||
assert(sdk_write(descriptors[1], buffer, 0) == 0);
|
||||
assert(sdk_read(descriptors[0], buffer, 0) == 0);
|
||||
assert(sdk_close(descriptors[1]) == 0);
|
||||
assert(sdk_read(descriptors[0], buffer, sizeof(buffer)) == 0);
|
||||
assert(sdk_close(descriptors[0]) == 0);
|
||||
assert(sdk_close(-1) == -1 && errno == EBADF);
|
||||
assert(sdk_read(-1, buffer, 1) == -1 && errno == EBADF);
|
||||
assert(sdk_write(-1, buffer, 1) == -1 && errno == EBADF);
|
||||
|
||||
assert(pipe(descriptors) == 0);
|
||||
int flags = fcntl(descriptors[1], F_GETFL);
|
||||
assert(flags >= 0 && fcntl(descriptors[1], F_SETFL, flags | O_NONBLOCK) == 0);
|
||||
ssize_t result = 0;
|
||||
for (int i = 0; i < 1024; ++i) {
|
||||
result = sdk_write(descriptors[1], buffer, sizeof(buffer));
|
||||
if (result < 0) break;
|
||||
}
|
||||
assert(result == -1 && (errno == EAGAIN || errno == EWOULDBLOCK));
|
||||
assert(sdk_close(descriptors[0]) == 0);
|
||||
assert(sdk_close(descriptors[1]) == 0);
|
||||
}
|
||||
#endif
|
||||
|
||||
static void exercise(const char *path) {
|
||||
FILE *file = sdk_open(path, "wb");
|
||||
assert(file != NULL);
|
||||
const unsigned char payload[] = {0, 1, 255, 10};
|
||||
assert(fwrite(payload, 1, sizeof(payload), file) == sizeof(payload));
|
||||
assert(fclose(file) == 0);
|
||||
|
||||
file = sdk_open(path, "ab");
|
||||
assert(file != NULL);
|
||||
assert(fwrite("X", 1, 1, file) == 1);
|
||||
assert(fclose(file) == 0);
|
||||
|
||||
file = sdk_open(path, "rb");
|
||||
assert(file != NULL);
|
||||
unsigned char result[8] = {0};
|
||||
assert(fread(result, 1, sizeof(result), file) == 5);
|
||||
assert(memcmp(result, payload, sizeof(payload)) == 0);
|
||||
assert(result[4] == 'X');
|
||||
assert(feof(file));
|
||||
assert(fclose(file) == 0);
|
||||
|
||||
file = sdk_open(path, "wb");
|
||||
assert(file != NULL);
|
||||
assert(fclose(file) == 0);
|
||||
file = sdk_open(path, "rb");
|
||||
assert(file != NULL);
|
||||
assert(fgetc(file) == EOF);
|
||||
assert(fclose(file) == 0);
|
||||
assert(unlink(path) == 0);
|
||||
|
||||
FILE *system_result = fopen(path, "rb");
|
||||
int system_error = errno;
|
||||
assert(system_result == NULL);
|
||||
errno = 0;
|
||||
FILE *bridge_result = sdk_open(path, "rb");
|
||||
int bridge_error = errno;
|
||||
assert(bridge_result == NULL);
|
||||
assert(bridge_error == system_error && bridge_error == ENOENT);
|
||||
}
|
||||
|
||||
static void *thread_test(void *path) {
|
||||
for (int i = 0; i < 20; ++i) exercise(path);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
#ifdef IG_TEST_ALL_BRIDGES
|
||||
exercise_posix();
|
||||
#endif
|
||||
pthread_t threads[4];
|
||||
char paths[4][4096];
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
int length = snprintf(paths[i], sizeof(paths[i]), "%s/文件-%d.bin", argv[1], i);
|
||||
assert(length > 0 && (size_t)length < sizeof(paths[i]));
|
||||
assert(pthread_create(&threads[i], NULL, thread_test, paths[i]) == 0);
|
||||
}
|
||||
for (int i = 0; i < 4; ++i) assert(pthread_join(threads[i], NULL) == 0);
|
||||
puts("file semantics: passed");
|
||||
return 0;
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "GCDWebServerPrivate.h"
|
||||
#include "dispatch/IGDispatch.h"
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void forbidden(void) { abort(); }
|
||||
|
||||
static GCDWebServerFileRequest *request(void) {
|
||||
return [[GCDWebServerFileRequest alloc] initWithMethod:@"POST"
|
||||
url:[NSURL URLWithString:@"http://localhost/upload"]
|
||||
headers:@{@"Content-Type": @"application/octet-stream", @"Content-Length": @"10"}
|
||||
path:@"/upload" query:nil];
|
||||
}
|
||||
|
||||
static void multipart(BOOL reject) {
|
||||
NSString *path = nil;
|
||||
@autoreleasepool {
|
||||
GCDWebServerMultiPartFormRequest *upload = [[GCDWebServerMultiPartFormRequest alloc]
|
||||
initWithMethod:@"POST" url:[NSURL URLWithString:@"http://localhost/upload"]
|
||||
headers:@{@"Content-Type": @"multipart/form-data; boundary=ig-test-boundary",
|
||||
@"Content-Length": @"1024"} path:@"/upload" query:nil];
|
||||
assert([upload open:NULL]);
|
||||
NSString *body = [@"0123456789" stringByPaddingToLength:512 withString:@"abcdefghij" startingAtIndex:0];
|
||||
NSString *first = [@"--ig-test-boundary\r\nContent-Disposition: form-data; name=\"file\"; filename=\"sample.txt\"\r\n\r\n"
|
||||
stringByAppendingString:body];
|
||||
assert([upload writeData:[first dataUsingEncoding:NSUTF8StringEncoding] error:NULL]);
|
||||
if (reject) ig_dispatch_test_override(0, (void *)forbidden);
|
||||
NSError *error = nil;
|
||||
NSData *last = [@"\r\n--ig-test-boundary--\r\n" dataUsingEncoding:NSUTF8StringEncoding];
|
||||
if (reject) {
|
||||
assert(![upload writeData:last error:&error] && error);
|
||||
assert(upload.files.count == 0);
|
||||
assert(![upload close:NULL]);
|
||||
} else {
|
||||
assert([upload writeData:last error:&error]);
|
||||
assert([upload close:&error]);
|
||||
assert(upload.files.count == 1);
|
||||
path = [upload.files.firstObject.temporaryPath copy];
|
||||
assert([[NSData dataWithContentsOfFile:path] isEqualToData:[body dataUsingEncoding:NSUTF8StringEncoding]]);
|
||||
}
|
||||
}
|
||||
if (path) assert(![[NSFileManager defaultManager] fileExistsAtPath:path]);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
@autoreleasepool {
|
||||
NSString *mode = @(argv[1]);
|
||||
ig_dispatch_response_configure(0, -1);
|
||||
if ([mode hasPrefix:@"multipart"]) {
|
||||
multipart([mode isEqualToString:@"multipart-tamper"]);
|
||||
return 0;
|
||||
}
|
||||
NSString *path;
|
||||
@autoreleasepool {
|
||||
GCDWebServerFileRequest *upload = request();
|
||||
path = [upload.temporaryPath copy];
|
||||
NSError *error = nil;
|
||||
if ([mode isEqualToString:@"open-tamper"]) {
|
||||
ig_dispatch_test_override(3, (void *)forbidden);
|
||||
assert(![upload open:&error] && error.code == EACCES);
|
||||
assert(![[NSFileManager defaultManager] fileExistsAtPath:path]);
|
||||
return 0;
|
||||
}
|
||||
int stdinCopy = -1;
|
||||
if ([mode isEqualToString:@"fd-zero"]) {
|
||||
stdinCopy = dup(STDIN_FILENO);
|
||||
close(STDIN_FILENO);
|
||||
}
|
||||
assert([upload open:&error]);
|
||||
NSData *body = [@"0123456789" dataUsingEncoding:NSUTF8StringEncoding];
|
||||
if ([mode isEqualToString:@"write-tamper"]) {
|
||||
ig_dispatch_test_override(0, (void *)forbidden);
|
||||
assert(![upload writeData:body error:&error] && error.code == EACCES);
|
||||
assert([NSData dataWithContentsOfFile:path].length == 0);
|
||||
assert([upload close:NULL]);
|
||||
return 0;
|
||||
}
|
||||
assert([upload writeData:body error:&error]);
|
||||
assert([upload close:&error]);
|
||||
if (stdinCopy >= 0) { assert(dup2(stdinCopy, STDIN_FILENO) >= 0); close(stdinCopy); }
|
||||
assert([[NSData dataWithContentsOfFile:path] isEqualToData:body]);
|
||||
|
||||
GCDWebServerFileResponse *response = [GCDWebServerFileResponse
|
||||
responseWithFile:path byteRange:NSMakeRange(2, 4)];
|
||||
assert(response && [response open:&error]);
|
||||
if ([mode isEqualToString:@"read-tamper"] || [mode isEqualToString:@"terminate"]) {
|
||||
ig_dispatch_test_override(2, (void *)forbidden);
|
||||
if ([mode isEqualToString:@"terminate"]) ig_dispatch_response_configure(1, -1);
|
||||
assert([response readData:&error] == nil && error.code == EACCES);
|
||||
assert(![mode isEqualToString:@"terminate"]);
|
||||
} else {
|
||||
NSData *chunk = [response readData:&error];
|
||||
assert([chunk isEqualToData:[@"2345" dataUsingEncoding:NSUTF8StringEncoding]]);
|
||||
assert([response readData:&error].length == 0);
|
||||
}
|
||||
[response close];
|
||||
}
|
||||
// 请求生命周期结束后仍通过受保护 unlink 清理临时文件。
|
||||
assert(![[NSFileManager defaultManager] fileExistsAtPath:path]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Vendored
+393
@@ -0,0 +1,393 @@
|
||||
/*
|
||||
* hook_device.m — 真机 HOOK 正向验证诊断进程(step11)。
|
||||
*
|
||||
* 目的:在非越狱真机的自身进程内构造四种受控攻击形态,验证 Defender 探针
|
||||
* 在真机环境(真实 dyld、真实内存权限、真实线程/镜像枚举)下能命中对应 reason:
|
||||
* 1. GOT 重绑定(fishhook 同款页权限改写自身 __got 槽)→ 期望 reason=102
|
||||
* 2. 蹦床序言(导出符号首指令为 B / LDR-literal+BR x16)→ 期望 reason=100+101
|
||||
* 3. frida 特征线程名(gum-js-loop)→ 期望 reason=203
|
||||
* 4. 容器外注入 dylib(Documents 下 dlopen;或宿主以 DYLD_INSERT_LIBRARIES 启动)
|
||||
* → 期望 reason=200(+201)(dlopen 路径)/ reason=202(插入库路径)
|
||||
*
|
||||
* 边界(如实声明):
|
||||
* - 不修改任何系统代码页(非越狱不可行):inline-hook 用例针对受控导出符号的
|
||||
* 真实代码字节验证「读取+分类」,不等同于对系统函数的真实 patch。
|
||||
* - 攻击操作(可写 GOT、装载模拟 dylib、特征线程名)只存在于本诊断源码,
|
||||
* 绝不编入业务库;诊断进程结束即退出,不触碰业务 App。
|
||||
*/
|
||||
#import <Foundation/Foundation.h>
|
||||
#include "IGDefender.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include "anti_hook/IGObjCBaseline.h"
|
||||
#include "anti_frida/IGAntiInject.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach/mach_time.h>
|
||||
#include <objc/objc.h>
|
||||
#include <objc/runtime.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* ---------- 发现收集:只记 DETECTED,逐条打日志 ---------- */
|
||||
|
||||
#define IG_MAXF 64
|
||||
static IGFinding g_findings[IG_MAXF];
|
||||
static int g_nfindings;
|
||||
|
||||
static int collect(const IGFinding *f, void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->status == IG_DETECTED && g_nfindings < IG_MAXF)
|
||||
g_findings[g_nfindings++] = *f;
|
||||
NSLog(@"IG_HOOK_FINDING status=%d reason=%d subject=%s evidence=%s",
|
||||
f->status, f->reason, f->subject, f->evidence);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void reset_findings(void) { g_nfindings = 0; }
|
||||
static const IGFinding *first_reason(int reason) {
|
||||
for (int i = 0; i < g_nfindings; ++i)
|
||||
if (g_findings[i].reason == reason) return &g_findings[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static const char *g_bundle; /* 主 bundle 路径,供各探针使用 */
|
||||
|
||||
/* 完整聚合扫描(anti_hook + 注入 + frida 线程)。 */
|
||||
static int scan_all(void) {
|
||||
reset_findings();
|
||||
return ig_defender_scan(g_bundle, 0, collect, NULL);
|
||||
}
|
||||
|
||||
/* ---------- 用例 1:GOT 重绑定(102)----------
|
||||
* fishhook 同款走法:定位主可执行文件 __got 中绑定 getpid 的槽,
|
||||
* 临时以 VM_PROT_COPY 改页为可写,写入本进程函数地址,恢复只读。
|
||||
* 只写自身进程数据页,不改任何代码。 */
|
||||
|
||||
static int ig_rebind_stub(void) { return 4242; } /* 指给 GOT 的假实现 */
|
||||
|
||||
static void **find_main_got_slot(const char *bare_name) {
|
||||
const struct mach_header_64 *mh =
|
||||
(const struct mach_header_64 *)_dyld_get_image_header(0);
|
||||
if (!mh || mh->magic != MH_MAGIC_64) return NULL;
|
||||
intptr_t slide = _dyld_get_image_vmaddr_slide(0);
|
||||
const struct segment_command_64 *linkedit = NULL;
|
||||
const struct symtab_command *symtab = NULL;
|
||||
const struct dysymtab_command *dysymtab = NULL;
|
||||
const uint8_t *cmd = (const uint8_t *)(mh + 1);
|
||||
for (uint32_t i = 0; i < mh->ncmds; ++i, cmd += ((const struct load_command *)cmd)->cmdsize) {
|
||||
const struct load_command *lc = (const struct load_command *)cmd;
|
||||
if (lc->cmd == LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;
|
||||
if (strcmp(seg->segname, SEG_LINKEDIT) == 0) linkedit = seg;
|
||||
} else if (lc->cmd == LC_SYMTAB) {
|
||||
symtab = (const struct symtab_command *)lc;
|
||||
} else if (lc->cmd == LC_DYSYMTAB) {
|
||||
dysymtab = (const struct dysymtab_command *)lc;
|
||||
}
|
||||
}
|
||||
if (!linkedit || !symtab || !dysymtab) return NULL;
|
||||
uintptr_t le_base = (uintptr_t)slide + linkedit->vmaddr - linkedit->fileoff;
|
||||
const struct nlist_64 *syms = (const struct nlist_64 *)(le_base + symtab->symoff);
|
||||
const char *strtab = (const char *)(le_base + symtab->stroff);
|
||||
const uint32_t *indirect = (const uint32_t *)(le_base + dysymtab->indirectsymoff);
|
||||
size_t nlen = strlen(bare_name);
|
||||
cmd = (const uint8_t *)(mh + 1);
|
||||
for (uint32_t i = 0; i < mh->ncmds; ++i, cmd += ((const struct load_command *)cmd)->cmdsize) {
|
||||
const struct load_command *lc = (const struct load_command *)cmd;
|
||||
if (lc->cmd != LC_SEGMENT_64) continue;
|
||||
const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;
|
||||
const struct section_64 *sect = (const struct section_64 *)(seg + 1);
|
||||
for (uint32_t s = 0; s < seg->nsects; ++s) {
|
||||
if ((sect[s].flags & SECTION_TYPE) != S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
size_t n = sect[s].size / sizeof(void *);
|
||||
const uint32_t *idxs = indirect + sect[s].reserved1;
|
||||
void **slots = (void **)((uintptr_t)slide + sect[s].addr);
|
||||
for (size_t k = 0; k < n; ++k) {
|
||||
uint32_t si = idxs[k];
|
||||
if (si == INDIRECT_SYMBOL_ABS || si == INDIRECT_SYMBOL_LOCAL) continue;
|
||||
const char *sym = strtab + syms[si].n_un.n_strx;
|
||||
/* sym 形如 "_getpid":比较去下划线后的部分 */
|
||||
if (sym[0] == '_' && strncmp(sym + 1, bare_name, nlen) == 0 &&
|
||||
sym[1 + nlen] == '\0')
|
||||
return &slots[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* 改写自身 GOT 槽:VM_PROT_COPY 写副本页,写完恢复只读。返回 0 成功。 */
|
||||
static int rebind_got_slot(void **slot, void *to) {
|
||||
vm_address_t page = (vm_address_t)(uintptr_t)slot & ~0xfffull;
|
||||
if (vm_protect(mach_task_self(), page, 0x1000, 0,
|
||||
VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY) != KERN_SUCCESS)
|
||||
return -1;
|
||||
*slot = to;
|
||||
vm_protect(mach_task_self(), page, 0x1000, 0, VM_PROT_READ);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---------- 用例 2:蹦床序言导出符号(100+101)----------
|
||||
* 两个文件级汇编符号,首指令分别是「无条件 B」与「LDR-literal x16 + BR x16」,
|
||||
* 与 Frida/Dobby 蹦床形态一致。仅被 dlsym 解析和字节读取,从不执行。 */
|
||||
|
||||
asm(".globl _ig_hook_target_b\n"
|
||||
".align 2\n"
|
||||
"_ig_hook_target_b:\n"
|
||||
" b .+64\n"
|
||||
" ret\n");
|
||||
|
||||
asm(".globl _ig_hook_target_lb\n"
|
||||
".align 2\n"
|
||||
"_ig_hook_target_lb:\n"
|
||||
" ldr x16, #8\n"
|
||||
" br x16\n"
|
||||
" .quad 0\n");
|
||||
|
||||
/* ---------- 用例 3:frida 特征线程名(203)---------- */
|
||||
|
||||
static void *gum_thread(void *arg) {
|
||||
(void)arg;
|
||||
pthread_setname_np("gum-js-loop");
|
||||
usleep(600000); /* 确保扫描期间线程存活 */
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ---------- 用例 6:ObjC 方法 IMP 基线(110)----------
|
||||
* 运行期创建类并采集基线,class_replaceMethod 换实现后扫描 → 期望 110。 */
|
||||
|
||||
static int ig_objc_imp_original(void *self, SEL _cmd) { (void)self; (void)_cmd; return 1; }
|
||||
static int ig_objc_imp_swapped(void *self, SEL _cmd) { (void)self; (void)_cmd; return 2; }
|
||||
|
||||
static Class make_objc_fixture_class(void) {
|
||||
Class c = objc_allocateClassPair(objc_getClass("NSObject"), "IGHookFixtureTarget", 0);
|
||||
if (!c) return NULL;
|
||||
if (!class_addMethod(c, sel_registerName("value"), (IMP)ig_objc_imp_original, "i16@0:8")) {
|
||||
objc_disposeClassPair(c);
|
||||
return NULL;
|
||||
}
|
||||
objc_registerClassPair(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
/* ---------- 输出协议(宿主 run_hook_device.py 解析)---------- */
|
||||
|
||||
static int g_pass = 0, g_fail = 0;
|
||||
static void mark(const char *name, int pass, const char *detail) {
|
||||
NSLog(@"IG_HOOK_CASE %s %s%s%s", name, pass ? "PASS" : "FAIL",
|
||||
detail && *detail ? " detail=" : "", detail ? detail : "");
|
||||
if (pass) ++g_pass; else ++g_fail;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
(void)argc; (void)argv;
|
||||
@autoreleasepool {
|
||||
NSLog(@"IG_HOOK_MAIN");
|
||||
g_bundle = NSBundle.mainBundle.bundlePath.UTF8String;
|
||||
const char *insert = getenv("DYLD_INSERT_LIBRARIES");
|
||||
|
||||
if (insert && insert[0]) {
|
||||
/* 相位 B:宿主经 DYLD_INSERT_LIBRARIES 启动本进程 → 真实 dyld 注入。 */
|
||||
NSLog(@"IG_HOOK_INSERT_MODE value=%s", insert);
|
||||
int hits = scan_all();
|
||||
int r202 = first_reason(IG_REASON_DYLD_INSERT) != NULL;
|
||||
int r200 = first_reason(IG_REASON_INJECTED_IMAGE) != NULL;
|
||||
NSLog(@"IG_HOOK_INSERT_SUMMARY detected=%d hits=%d reason202=%d reason200=%d",
|
||||
g_nfindings, hits, r202, r200);
|
||||
mark("dyld_insert", r202 || r200,
|
||||
r202 ? "202+环境注入命中" : (r200 ? "200(插入镜像命中特征名)" : "未命中"));
|
||||
NSLog(@"IG_HOOK_SUITE %s cases=1", g_fail ? "FAIL" : "PASS");
|
||||
return g_fail ? 4 : 0;
|
||||
}
|
||||
|
||||
/* ---- 相位 A:干净进程内的受控攻击形态 ---- */
|
||||
|
||||
/* 0. 基线:干净环境 0 命中。 */
|
||||
int base = scan_all();
|
||||
int base_unavail = 0; /* unavailable 已在 sink 日志逐条体现,不判失败 */
|
||||
NSLog(@"IG_HOOK_BASELINE detected=%d", base);
|
||||
mark("baseline_clean", g_nfindings == 0,
|
||||
g_nfindings ? "干净环境出现 DETECTED(误报)" : "");
|
||||
|
||||
/* 1. 耗时小样本(5 次完整聚合扫描)。 */
|
||||
{
|
||||
mach_timebase_info_data_t tb;
|
||||
mach_timebase_info(&tb);
|
||||
double scale = (double)tb.numer / (double)tb.denom / 1e6; /* → ms */
|
||||
double total = 0, best = 1e9;
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
uint64_t t0 = mach_absolute_time();
|
||||
scan_all();
|
||||
double ms = (mach_absolute_time() - t0) * scale;
|
||||
total += ms;
|
||||
if (ms < best) best = ms;
|
||||
}
|
||||
NSLog(@"IG_HOOK_TIMING n=5 avg_ms=%.2f min_ms=%.2f", total / 5.0, best);
|
||||
}
|
||||
|
||||
/* 2. GOT 重绑定 → 102;恢复 → 干净。 */
|
||||
{
|
||||
/* 确保可执行文件真实导入 getpid(否则 __got 无该槽)。 */
|
||||
if (getpid() == -7) NSLog(@"unreachable");
|
||||
void **slot = find_main_got_slot("getpid");
|
||||
if (!slot) {
|
||||
mark("got_rebind", 0, "未找到主程序 getpid 的 __got 槽(构建异常)");
|
||||
} else {
|
||||
void *orig = *slot;
|
||||
NSLog(@"IG_HOOK_GOT slot=%p orig=%p", (void *)slot, orig);
|
||||
if (rebind_got_slot(slot, (void *)ig_rebind_stub) != 0) {
|
||||
mark("got_rebind", 0, "vm_protect 改写失败");
|
||||
} else {
|
||||
scan_all();
|
||||
const IGFinding *f = first_reason(IG_REASON_GOT_REBIND);
|
||||
int hit = f && strstr(f->subject, "getpid") != NULL;
|
||||
mark("got_rebind", hit, f ? f->evidence : "未命中 102");
|
||||
rebind_got_slot(slot, orig); /* 恢复,双写均经同一权限路径 */
|
||||
int again = scan_all();
|
||||
int clean = g_nfindings == 0;
|
||||
NSLog(@"IG_HOOK_GOT_RESTORE detected=%d hits=%d", g_nfindings, again);
|
||||
if (!clean)
|
||||
mark("got_restore_clean", 0, "恢复后仍有 DETECTED");
|
||||
else
|
||||
mark("got_restore_clean", 1, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 3. 蹦床序言(经 dlsym+vm_read_overwrite 的完整探针链)→ 100+101。 */
|
||||
{
|
||||
const char *const names[] = {"ig_hook_target_b", "ig_hook_target_lb"};
|
||||
reset_findings();
|
||||
ig_anti_hook_check(names, 2, collect, NULL);
|
||||
int b100 = 0, b101 = 0, lb100 = 0, lb101 = 0;
|
||||
for (int i = 0; i < g_nfindings; ++i) {
|
||||
const char *subj = g_findings[i].subject;
|
||||
if (strstr(subj, "ig_hook_target_b")) {
|
||||
b100 |= g_findings[i].reason == IG_REASON_SYMBOL_PROVENANCE;
|
||||
b101 |= g_findings[i].reason == IG_REASON_INLINE_HOOK;
|
||||
} else if (strstr(subj, "ig_hook_target_lb")) {
|
||||
lb100 |= g_findings[i].reason == IG_REASON_SYMBOL_PROVENANCE;
|
||||
lb101 |= g_findings[i].reason == IG_REASON_INLINE_HOOK;
|
||||
}
|
||||
}
|
||||
mark("prologue_b_branch", b100 && b101, b101 ? "首指令 B 被识别" : "未命中 101");
|
||||
mark("prologue_ldr_br", lb100 && lb101, lb101 ? "LDR+BR 蹦床被识别" : "未命中 101");
|
||||
}
|
||||
|
||||
/* 4. frida 特征线程名 → 203;join 后 → 干净。
|
||||
* join 后内核回收线程对象存在延迟(task_threads 短期内仍可能列出已终止
|
||||
* 线程),在 2s 窗口内轮询重扫:既能容忍回收延迟,又验证探针无粘滞缓存。 */
|
||||
{
|
||||
pthread_t t;
|
||||
pthread_create(&t, NULL, gum_thread, NULL);
|
||||
usleep(200000); /* 等线程命名完成 */
|
||||
reset_findings();
|
||||
ig_anti_frida_check(0, collect, NULL);
|
||||
mark("frida_thread", first_reason(IG_REASON_FRIDA_THREAD) != NULL, "");
|
||||
pthread_join(t, NULL);
|
||||
int clean = 0;
|
||||
for (int i = 0; i < 10 && !clean; ++i) {
|
||||
usleep(200000);
|
||||
reset_findings();
|
||||
ig_anti_frida_check(0, collect, NULL);
|
||||
clean = (g_nfindings == 0);
|
||||
}
|
||||
mark("frida_thread_gone", clean,
|
||||
clean ? "join 后 2s 内恢复干净" : "join 后 2s 仍残留线程名(回收异常缓慢)");
|
||||
}
|
||||
|
||||
/* 5. 注入证据两种形态:
|
||||
* a) Documents/libfrida-sim.dylib —— 文件名命中注入特征 → 期望 200;
|
||||
* (探针对命中特征的镜像即上报 200,不再重复报 Bundle 外,故不期望 201)
|
||||
* b) Documents/libiosutil-sim.dylib —— 无特征命名的 Bundle 外镜像 → 期望 201。
|
||||
* 相位 A 成功路径回显给宿主,供相位 B 的 DYLD_INSERT 使用。 */
|
||||
{
|
||||
NSString *res = [[NSBundle mainBundle] pathForResource:@"libfrida-sim"
|
||||
ofType:@"dylib"];
|
||||
NSString *docs = [NSHomeDirectory()
|
||||
stringByAppendingPathComponent:@"Documents"];
|
||||
NSString *dstA = [docs stringByAppendingPathComponent:@"libfrida-sim.dylib"];
|
||||
NSString *dstB = [docs stringByAppendingPathComponent:@"libiosutil-sim.dylib"];
|
||||
const char *chosen = NULL;
|
||||
NSFileManager *fm = [NSFileManager defaultManager];
|
||||
if (res) {
|
||||
[fm removeItemAtPath:dstA error:nil];
|
||||
[fm removeItemAtPath:dstB error:nil];
|
||||
if ([fm copyItemAtPath:res toPath:dstA error:nil] &&
|
||||
[fm copyItemAtPath:res toPath:dstB error:nil]) {
|
||||
void *ha = dlopen(dstA.fileSystemRepresentation, RTLD_LOCAL);
|
||||
if (ha) {
|
||||
chosen = dstA.fileSystemRepresentation;
|
||||
reset_findings();
|
||||
ig_anti_inject_check(g_bundle, collect, NULL);
|
||||
mark("injected_image",
|
||||
first_reason(IG_REASON_INJECTED_IMAGE) != NULL,
|
||||
"Documents 特征名装载命中 200");
|
||||
} else {
|
||||
const char *e = dlerror();
|
||||
NSLog(@"IG_HOOK_DLOPEN_DOC_FAIL %s", e ? e : "?");
|
||||
}
|
||||
void *hb = dlopen(dstB.fileSystemRepresentation, RTLD_LOCAL);
|
||||
if (hb) {
|
||||
reset_findings();
|
||||
ig_anti_inject_check(g_bundle, collect, NULL);
|
||||
mark("foreign_image",
|
||||
first_reason(IG_REASON_FOREIGN_IMAGE) != NULL,
|
||||
"Documents 无特征名装载命中 201(弱信号)");
|
||||
}
|
||||
} else {
|
||||
NSLog(@"IG_HOOK_COPY_FAIL %@", docs);
|
||||
}
|
||||
}
|
||||
if (!chosen) {
|
||||
/* 回退:从 .app 内 dlopen(Bundle 内只应命中 200)。 */
|
||||
void *h = dlopen(res.fileSystemRepresentation, RTLD_LOCAL);
|
||||
if (h) {
|
||||
chosen = res.fileSystemRepresentation;
|
||||
reset_findings();
|
||||
ig_anti_inject_check(g_bundle, collect, NULL);
|
||||
int r200 = first_reason(IG_REASON_INJECTED_IMAGE) != NULL;
|
||||
int r201 = first_reason(IG_REASON_FOREIGN_IMAGE) != NULL;
|
||||
mark("injected_image", r200 && !r201,
|
||||
"容器外装载不可用,回退 Bundle 内(200 命中、201 不应命中)");
|
||||
} else {
|
||||
const char *e = dlerror();
|
||||
mark("injected_image", 0, e ? e : "装载失败");
|
||||
}
|
||||
}
|
||||
NSLog(@"IG_HOOK_DYLIB_PATH %s", chosen ? chosen : "none");
|
||||
}
|
||||
|
||||
/* 6. ObjC IMP 基线:采集 → class_replaceMethod → 期望 110;未接入时聚合为 no-op。 */
|
||||
{
|
||||
Class c = make_objc_fixture_class();
|
||||
if (!c) {
|
||||
mark("objc_imp_baseline", 0, "运行期建类失败");
|
||||
} else {
|
||||
const IGObjCWatch watch[] = { { "IGHookFixtureTarget", "value" } };
|
||||
size_t n = ig_objc_baseline_capture(watch, 1);
|
||||
reset_findings();
|
||||
int before = ig_objc_baseline_check(collect, NULL);
|
||||
class_replaceMethod(c, sel_registerName("value"),
|
||||
(IMP)ig_objc_imp_swapped, "i16@0:8");
|
||||
reset_findings();
|
||||
int after = ig_objc_baseline_check(collect, NULL);
|
||||
mark("objc_imp_baseline", n == 1 && before == 0 && after == 1 &&
|
||||
first_reason(IG_REASON_OBJC_IMP_CHANGED) != NULL,
|
||||
after == 1 ? "替换后命中 110" : "未命中 110");
|
||||
}
|
||||
}
|
||||
|
||||
NSLog(@"IG_HOOK_SUITE %s cases=%d baseline_unavailable_logged=%d",
|
||||
g_fail ? "FAIL" : "PASS", g_pass + g_fail, base_unavail);
|
||||
/* 诊断进程退出便于 console 收集退出码;不编入业务 App。 */
|
||||
return g_fail ? 4 : 0;
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* hook_sim_dylib.c — 空壳模拟 dylib(step11 诊断专用)。
|
||||
*
|
||||
* 唯一用途:被诊断进程 dlopen / 被 DYLD_INSERT_LIBRARIES 加载,构成
|
||||
* 「注入镜像 / Bundle 外镜像 / 插入库」探针的受控证据源。不实现任何业务功能,
|
||||
* 不导出会被业务引用的符号。仅用于诊断 App,绝不编入业务库。
|
||||
*/
|
||||
#include <stddef.h>
|
||||
|
||||
__attribute__((visibility("default")))
|
||||
int ig_frida_sim_marker(void) { return 0x46726461; /* "Frda" */ }
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
/* 无 SDK 头依赖的 iOS 链接样本:两个外部调用和一个本地改写目标。 */
|
||||
extern int getpid(void);
|
||||
extern long write(int, const void *, unsigned long);
|
||||
int fixture_calls(void) { return getpid() + (int)write(-1, "x", 1); }
|
||||
int fixture_redirect(void) { return 123; }
|
||||
Vendored
+83
@@ -0,0 +1,83 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <dlfcn.h>
|
||||
#import <objc/runtime.h>
|
||||
#import <sys/mman.h>
|
||||
#import <sys/ptrace.h>
|
||||
#include "anti_hook/IGObjCBaseline.h"
|
||||
|
||||
// 优化器能把实例方法编译成一条合法的尾调用。
|
||||
__attribute__((noinline)) static int readValue(void) {
|
||||
static volatile int value = 7;
|
||||
return value;
|
||||
}
|
||||
|
||||
@interface IGManifestParent : NSObject
|
||||
- (int)value;
|
||||
+ (int)classValue;
|
||||
- (int)other;
|
||||
@end
|
||||
@implementation IGManifestParent
|
||||
- (int)value { return readValue(); }
|
||||
+ (int)classValue { return readValue(); }
|
||||
- (int)other { return 42; }
|
||||
@end
|
||||
@interface IGManifestChild : IGManifestParent
|
||||
@end
|
||||
@implementation IGManifestChild
|
||||
@end
|
||||
@interface IGManifestChild (Extra)
|
||||
- (int)extra;
|
||||
@end
|
||||
@implementation IGManifestChild (Extra)
|
||||
- (int)extra { return readValue(); }
|
||||
@end
|
||||
|
||||
typedef struct { int changed, unavailable; } Counts;
|
||||
static int collect(const IGFinding *finding, void *ctx) {
|
||||
Counts *counts = ctx;
|
||||
counts->changed += finding->status == IG_DETECTED;
|
||||
counts->unavailable += finding->status == IG_UNAVAILABLE;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, const char **argv) {
|
||||
if (argc != 2) return 1;
|
||||
// 强制 dyld 装入 Swift 类,与真实应用一致地通过运行时名称登记。
|
||||
extern void ig_load_swift_fixture(void);
|
||||
extern const char *ig_swift_nested_name(void);
|
||||
extern const char *ig_swift_private_name(void);
|
||||
ig_load_swift_fixture();
|
||||
IGObjCWatch watches[] = {
|
||||
{"IGManifestChild", "-value"}, {"IGManifestChild", "+classValue"},
|
||||
{"IGManifestChild", "extra"}, {"Fixture.SwiftProbe", "swiftValue"},
|
||||
{ig_swift_nested_name(), "nestedValue"}, {ig_swift_private_name(), "privateValue"},
|
||||
};
|
||||
Method method = class_getInstanceMethod(IGManifestParent.class, @selector(value));
|
||||
IMP other = class_getMethodImplementation(IGManifestParent.class, @selector(other));
|
||||
BOOL before = !strcmp(argv[1], "before"), after = !strcmp(argv[1], "after");
|
||||
BOOL before_block = !strcmp(argv[1], "before-block"), before_anon = !strcmp(argv[1], "before-anon");
|
||||
void *anon = NULL;
|
||||
if (before) method_setImplementation(method, other);
|
||||
if (before_block) {
|
||||
IMP blk = imp_implementationWithBlock(^int(id self) { (void)self; return 99; });
|
||||
method_setImplementation(method, blk);
|
||||
}
|
||||
if (before_anon) {
|
||||
anon = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANON, -1, 0);
|
||||
if (anon == MAP_FAILED) return 3;
|
||||
Dl_info di;
|
||||
if (dladdr(anon, &di)) return 4;
|
||||
method_setImplementation(method, (IMP)anon);
|
||||
}
|
||||
if (ig_objc_baseline_capture(watches, 6) != 6) return 2;
|
||||
if (after) method_setImplementation(method, other);
|
||||
BOOL traced = !strcmp(argv[1], "different-bytes-traced");
|
||||
if (traced && ptrace(PT_TRACE_ME, 0, NULL, 0) != 0) return 5;
|
||||
Counts counts = {0};
|
||||
ig_objc_baseline_check(collect, &counts);
|
||||
if (anon) munmap(anon, 4096);
|
||||
fprintf(stderr, "changed=%d unavailable=%d\n", counts.changed, counts.unavailable);
|
||||
int expect_changed = before || before_block || before_anon || after || !strcmp(argv[1], "different-bytes");
|
||||
return counts.changed != expect_changed ||
|
||||
counts.unavailable != (!strcmp(argv[1], "unavailable") ? 6 : 0);
|
||||
}
|
||||
Vendored
+289
@@ -0,0 +1,289 @@
|
||||
/*
|
||||
* poison_device.m — 处置链真机验证诊断进程(step12,见 docs/19)。
|
||||
*
|
||||
* 在真机自身进程内运行真实的「检测→分级→数据毒化」链,分两类用例:
|
||||
*
|
||||
* A. 环境无关不变量(两组设备都必须 PASS,构成套件门槛):
|
||||
* D4 poison_identity 健康态 apply 恒等(out==key)——证不误伤解密
|
||||
* D5 poison_mark_corrupt mark 后 apply 坏 key(out!=key)——证毒化真的生效
|
||||
* D6 ctor_clean_start 进程启动未 mark 时 mask==0——证构造期初始化干净、无启动即毒化
|
||||
* D7 policy_grades 合成 finding 复核分级(弱/单MEDIUM不触发;双MEDIUM/单STRONG触发)
|
||||
* D8 svc_access_live 在自身沙盒建真实可访问文件,证 svc 直发 access(2) 在真机能命中
|
||||
* reason=400——坐实 D2 的 0 命中是「无越狱文件」而非「探针静默失败」,
|
||||
* 无需越狱设备即可验证检测机制在 iOS arm64 上是活的。
|
||||
*
|
||||
* B. 环境相关观察(不写死 PASS/FAIL,输出命中供人按 R/J 组判定,见 docs/19 §4):
|
||||
* D1 baseline_scan ig_policy_scan_and_mark(bundle) 的返回/mask
|
||||
* D2 jb_file 内置越狱特征表 access 直发命中数(reason=400)
|
||||
* D3 jb_sandbox 默认沙盒逃逸探测(reason=401)
|
||||
* 并据 D2/D3 是否命中输出环境判定 IG_POISON_ENV jailbroken=yes|no。
|
||||
*
|
||||
* 边界:攻击/构造代码只存在于本诊断源码,绝不编入业务库;越狱特征文件的“存在性”
|
||||
* 在 J 组由设备本身提供,诊断进程只做被动 access/open 探测,不自己造越狱文件。
|
||||
* 每例结束前调 ig_poison_init() 复位,避免跨例污染。
|
||||
*/
|
||||
#import <Foundation/Foundation.h>
|
||||
#include "IGDefender.h"
|
||||
#include "poison/IGPoison.h"
|
||||
#include "policy/IGPolicy.h"
|
||||
#include "anti_jailbreak/IGAntiJailbreak.h"
|
||||
#include "anti_tamper/IGAntiTamper.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
|
||||
/* 原始 csops(与 IGAntiTamper 同,供 .m 直读状态字作真机观察,坐实 csops 活性) */
|
||||
#ifndef CS_OPS_STATUS
|
||||
#define CS_OPS_STATUS 0
|
||||
#endif
|
||||
#define IG_CS_VALID 0x00000001u
|
||||
#define IG_CS_ADHOC 0x00000002u
|
||||
#define IG_CS_GET_TASK_ALLOW 0x00000004u
|
||||
extern int csops(pid_t pid, unsigned int ops, void *useraddr, size_t usersize);
|
||||
|
||||
/* 进程主可执行镜像头(与 IGAntiTamper 内部同逻辑,便于直接喂给可测核心) */
|
||||
static const struct mach_header_64 *dev_main_image_header(void) {
|
||||
uint32_t n = _dyld_image_count();
|
||||
for (uint32_t i = 0; i < n; ++i) {
|
||||
const struct mach_header *h = _dyld_get_image_header(i);
|
||||
if (h && h->magic == MH_MAGIC_64 &&
|
||||
((const struct mach_header_64 *)h)->filetype == MH_EXECUTE) {
|
||||
return (const struct mach_header_64 *)h;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ---------- 发现收集 ---------- */
|
||||
#define IG_MAXF 64
|
||||
static IGFinding g_f[IG_MAXF];
|
||||
static int g_nf;
|
||||
static int g_detected;
|
||||
|
||||
static int collect(const IGFinding *f, void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->status == IG_DETECTED) {
|
||||
if (g_nf < IG_MAXF) g_f[g_nf++] = *f;
|
||||
g_detected++;
|
||||
}
|
||||
NSLog(@"IG_POISON_FINDING status=%d reason=%d subject=%s evidence=%s",
|
||||
f->status, f->reason, f->subject, f->evidence);
|
||||
return 0;
|
||||
}
|
||||
static void reset_findings(void) { g_nf = 0; g_detected = 0; }
|
||||
static int count_reason(int reason) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < g_nf; ++i) if (g_f[i].reason == reason) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ---------- PASS/FAIL 汇总 ---------- */
|
||||
static int g_pass = 0, g_fail = 0;
|
||||
static void mark_case(const char *name, int pass, const char *detail) {
|
||||
if (pass) g_pass++; else g_fail++;
|
||||
NSLog(@"IG_POISON_CASE %s %s detail=%s", name, pass ? "PASS" : "FAIL", detail ? detail : "");
|
||||
}
|
||||
static void observe(const char *name, const char *detail) {
|
||||
NSLog(@"IG_POISON_OBS %s %s", name, detail ? detail : "");
|
||||
}
|
||||
|
||||
/* ---------- policy 合成输入 ---------- */
|
||||
static void feed(IGPolicyState *st, IGStatus status, int reason) {
|
||||
IGFinding f; memset(&f, 0, sizeof(f));
|
||||
f.status = status; f.reason = reason;
|
||||
ig_policy_sink(&f, st);
|
||||
}
|
||||
static int run_policy_weak(void) {
|
||||
ig_poison_init();
|
||||
IGPolicyState st; ig_policy_reset(&st, NULL, NULL);
|
||||
feed(&st, IG_DETECTED, IG_REASON_FOREIGN_IMAGE);
|
||||
feed(&st, IG_DETECTED, IG_REASON_FRIDA_PORT);
|
||||
return ig_policy_evaluate_and_mark(&st);
|
||||
}
|
||||
static int run_policy_single_medium(void) {
|
||||
ig_poison_init();
|
||||
IGPolicyState st; ig_policy_reset(&st, NULL, NULL);
|
||||
feed(&st, IG_DETECTED, IG_REASON_OBJC_IMP_CHANGED);
|
||||
return ig_policy_evaluate_and_mark(&st);
|
||||
}
|
||||
static int run_policy_two_medium(void) {
|
||||
ig_poison_init();
|
||||
IGPolicyState st; ig_policy_reset(&st, NULL, NULL);
|
||||
feed(&st, IG_DETECTED, IG_REASON_OBJC_IMP_CHANGED);
|
||||
feed(&st, IG_DETECTED, IG_REASON_SYMBOL_PROVENANCE);
|
||||
return ig_policy_evaluate_and_mark(&st);
|
||||
}
|
||||
static int run_policy_single_strong(void) {
|
||||
ig_poison_init();
|
||||
IGPolicyState st; ig_policy_reset(&st, NULL, NULL);
|
||||
feed(&st, IG_DETECTED, IG_REASON_JAILBREAK_SANDBOX);
|
||||
return ig_policy_evaluate_and_mark(&st);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
(void)argc; (void)argv;
|
||||
@autoreleasepool {
|
||||
const char *bundle = [[[NSBundle mainBundle] bundlePath] fileSystemRepresentation];
|
||||
|
||||
/* ===== D6 ctor_clean_start:进程启动早期、任何 mark 之前,mask 必须为 0 =====
|
||||
* 放最前,尽量贴近启动态(构造器已跑,但本进程尚未触发任何检测/mark)。 */
|
||||
{
|
||||
uint64_t m = ig_poison_mask();
|
||||
char d[64]; snprintf(d, sizeof(d), "mask=0x%llx", (unsigned long long)m);
|
||||
mark_case("ctor_clean_start", m == 0, d);
|
||||
}
|
||||
|
||||
/* ===== D4 poison_identity:健康态 apply 恒等 ===== */
|
||||
{
|
||||
ig_poison_init();
|
||||
const uint8_t key[] = { 's','t','a','r','t','i','a','s','o','f','t',0x11,0x22 };
|
||||
size_t n = sizeof(key); uint8_t out[sizeof(key)];
|
||||
memset(out, 0xAB, n);
|
||||
ig_poison_apply(key, out, n);
|
||||
mark_case("poison_identity", memcmp(out, key, n) == 0, "healthy apply must be identity");
|
||||
}
|
||||
|
||||
/* ===== D5 poison_mark_corrupt:mark 后 apply 坏 key ===== */
|
||||
{
|
||||
ig_poison_init();
|
||||
const uint8_t key[] = { 's','t','a','r','t','i','a','s','o','f','t',0x11,0x22 };
|
||||
size_t n = sizeof(key); uint8_t out[sizeof(key)];
|
||||
ig_poison_mark(0xC0FFEE);
|
||||
int nonzero = (ig_poison_mask() != 0);
|
||||
ig_poison_apply(key, out, n);
|
||||
int corrupted = (memcmp(out, key, n) != 0);
|
||||
mark_case("poison_mark_corrupt", nonzero && corrupted, "marked apply must differ");
|
||||
ig_poison_init();
|
||||
}
|
||||
|
||||
/* ===== D7 policy_grades:真机复核分级 ===== */
|
||||
{
|
||||
int weak = run_policy_weak(); /* 期望 0 */
|
||||
int med1 = run_policy_single_medium(); /* 期望 0 */
|
||||
int med2 = run_policy_two_medium(); /* 期望 1 */
|
||||
int strong = run_policy_single_strong(); /* 期望 1 */
|
||||
int ok = (weak == 0 && med1 == 0 && med2 == 1 && strong == 1);
|
||||
char d[96];
|
||||
snprintf(d, sizeof(d), "weak=%d single_medium=%d two_medium=%d single_strong=%d",
|
||||
weak, med1, med2, strong);
|
||||
mark_case("policy_grades", ok, d);
|
||||
ig_poison_init();
|
||||
}
|
||||
|
||||
/* ===== D8 svc_access_live:合成正向,不依赖越狱 =====
|
||||
* 非越狱设备上内置越狱表必然 0 命中——但那可能是「svc 直发在 iOS 上静默失败、
|
||||
* 永远返回 0」的假阴性。此例在自身沙盒 Documents 建一个真实可访问文件,喂给
|
||||
* ig_anti_jb_check_paths,确认 svc #0x80 access(2) 在真机 iOS arm64 上能真正命中
|
||||
* (reason=400)。坐实 D2 的 0 命中是「无越狱文件」而非「探针坏了」。环境无关不变量。 */
|
||||
{
|
||||
reset_findings();
|
||||
NSString *docs = NSSearchPathForDirectoriesInDomains(
|
||||
NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
|
||||
NSString *probe = [docs stringByAppendingPathComponent:@".ig_svc_live_probe"];
|
||||
[@"x" writeToFile:probe atomically:YES encoding:NSUTF8StringEncoding error:nil];
|
||||
const char *cpath = [probe fileSystemRepresentation];
|
||||
const char *paths[] = { cpath };
|
||||
ig_anti_jb_check_paths(paths, 1, NULL, collect, NULL);
|
||||
int live = count_reason(IG_REASON_JAILBREAK_FILE);
|
||||
[[NSFileManager defaultManager] removeItemAtPath:probe error:nil];
|
||||
char d[96]; snprintf(d, sizeof(d), "accessible_file_hits=%d svc_access_fires_on_device", live);
|
||||
mark_case("svc_access_live", live >= 1, d);
|
||||
reset_findings();
|
||||
}
|
||||
|
||||
/* ===== D9 anti_tamper:二进制完整性探针真机验证 =====
|
||||
* dev 签名包是环境无关不变量:本地编译=无 FairPlay 加密(无 LC_ENCRYPTION_INFO
|
||||
* 或 cryptid=0)、且带 get-task-allow。据此双向验证 IGAntiTamper:
|
||||
* expect=0(dev 正确配置)→ 全 UNAVAILABLE、零 DETECTED(误报底线);
|
||||
* expect=1(假装分发)→ cryptid 命中 500、csops 读到 get-task-allow 命中 501
|
||||
* (坐实探针真读到真实镜像头/签名状态,逻辑正确)。 */
|
||||
const struct mach_header_64 *mh = dev_main_image_header();
|
||||
|
||||
/* D9a cryptid_expect0_clean:非分发构建跳过,零 DETECTED(误报底线) */
|
||||
{
|
||||
reset_findings();
|
||||
int hits = ig_tamper_scan_cryptid(mh, /*expect_encrypted=*/0, collect, NULL);
|
||||
mark_case("at_cryptid_expect0_clean", hits == 0 && g_detected == 0,
|
||||
"dev build, expect_encrypted=0 must not flag");
|
||||
reset_findings();
|
||||
}
|
||||
|
||||
/* D9b cryptid_expect1_detects:dev 包无 FairPlay 加密 → 命中 500(探针真读主镜像头) */
|
||||
{
|
||||
reset_findings();
|
||||
int hits = ig_tamper_scan_cryptid(mh, /*expect_encrypted=*/1, collect, NULL);
|
||||
int r500 = count_reason(IG_REASON_BINARY_DECRYPTED);
|
||||
char d[96]; snprintf(d, sizeof(d), "hits=%d reason500=%d mh=%p", hits, r500, (void *)mh);
|
||||
mark_case("at_cryptid_expect1_detects", hits >= 1 && r500 >= 1, d);
|
||||
reset_findings();
|
||||
}
|
||||
|
||||
/* D9c tamper_gated_off:两检查都 expect=0 → 零 DETECTED(误报底线整入口) */
|
||||
{
|
||||
reset_findings();
|
||||
int hits = ig_anti_tamper_check(/*expect_encrypted=*/0, /*expect_distribution=*/0,
|
||||
collect, NULL);
|
||||
mark_case("at_tamper_gated_off", hits == 0 && g_detected == 0,
|
||||
"dev build, expect_*=0 whole-entry must not flag");
|
||||
reset_findings();
|
||||
}
|
||||
|
||||
/* D9d tamper_on_detects:expect_*=1 → 至少 cryptid 500 命中(整入口贯通真机) */
|
||||
{
|
||||
reset_findings();
|
||||
int hits = ig_anti_tamper_check(/*expect_encrypted=*/1, /*expect_distribution=*/1,
|
||||
collect, NULL);
|
||||
int r500 = count_reason(IG_REASON_BINARY_DECRYPTED);
|
||||
int r501 = count_reason(IG_REASON_CODESIGN_INVALID);
|
||||
char d[112]; snprintf(d, sizeof(d), "hits=%d reason500=%d reason501=%d", hits, r500, r501);
|
||||
mark_case("at_tamper_on_detects", hits >= 1 && r500 >= 1, d);
|
||||
/* 501(csops 代码签名)作观察:dev 包带 get-task-allow 应命中,但 csops 语义真机坐实为准 */
|
||||
char o[64]; snprintf(o, sizeof(o), "reason501_codesign_hits=%d", r501);
|
||||
observe("at_codesign_501", o);
|
||||
reset_findings();
|
||||
}
|
||||
|
||||
/* D9e csops_status(观察):直读 csops 状态字,坐实 csops 在真机 iOS arm64 活着 */
|
||||
{
|
||||
uint32_t st = 0;
|
||||
int rc = csops(getpid(), CS_OPS_STATUS, &st, sizeof(st));
|
||||
char o[128];
|
||||
snprintf(o, sizeof(o), "rc=%d status=0x%x valid=%d adhoc=%d get_task_allow=%d",
|
||||
rc, st, (st & IG_CS_VALID) != 0, (st & IG_CS_ADHOC) != 0,
|
||||
(st & IG_CS_GET_TASK_ALLOW) != 0);
|
||||
observe("csops_status", o);
|
||||
}
|
||||
|
||||
/* ===== D2 jb_file(观察):内置越狱特征表直发 access ===== */
|
||||
reset_findings();
|
||||
ig_anti_jb_check(collect, NULL);
|
||||
int hit400 = count_reason(IG_REASON_JAILBREAK_FILE);
|
||||
int hit401_default = count_reason(IG_REASON_JAILBREAK_SANDBOX);
|
||||
{
|
||||
char d[96]; snprintf(d, sizeof(d), "reason400=%d reason401=%d", hit400, hit401_default);
|
||||
observe("jb_file", d);
|
||||
}
|
||||
|
||||
/* ===== D1 baseline_scan(观察):聚合策略扫描的返回与 mask ===== */
|
||||
{
|
||||
ig_poison_init();
|
||||
int triggered = ig_policy_scan_and_mark(bundle, 0, NULL, NULL);
|
||||
uint64_t m = ig_poison_mask();
|
||||
char d[96]; snprintf(d, sizeof(d), "triggered=%d mask=0x%llx",
|
||||
triggered, (unsigned long long)m);
|
||||
observe("baseline_scan", d);
|
||||
ig_poison_init();
|
||||
}
|
||||
|
||||
/* ===== 环境判定:D2/D3 任一命中即视作越狱环境(J 组)===== */
|
||||
int jailbroken = (hit400 > 0) || (hit401_default > 0);
|
||||
NSLog(@"IG_POISON_ENV jailbroken=%s reason400=%d reason401=%d",
|
||||
jailbroken ? "yes" : "no", hit400, hit401_default);
|
||||
|
||||
/* 套件判定只看环境无关不变量(D4–D7)。 */
|
||||
NSLog(@"IG_POISON_SUITE %s pass=%d fail=%d", g_fail ? "FAIL" : "PASS", g_pass, g_fail);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Vendored
+169
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* poison_host.c — 处置链宿主自测(poison + policy + anti_jailbreak)。
|
||||
*
|
||||
* 固化此前只在 /tmp 临时跑过的「检测→分级→数据毒化」闭环为可复现基线,
|
||||
* 作为真机验证(docs/19)之前的宿主绿灯。覆盖:
|
||||
* A. poison:健康恒等、毒化破坏 key、mask 非分支语义、apply 逐字节扩散。
|
||||
* B. policy:弱信号/UNAVAILABLE/CLEAR 不触发、单 MEDIUM 不触发、双 MEDIUM 去重后触发、
|
||||
* 单 STRONG 触发——且触发后 mask 必非 0(真正接到了毒化)。
|
||||
* C. anti_jailbreak:可注入路径版本——不存在路径零命中(反向零误报)、
|
||||
* 存在路径命中 400、沙盒逃逸探测命中 401。
|
||||
*
|
||||
* 只用 ig_anti_jb_check_paths 的可注入入口,不依赖真机越狱特征文件,故宿主可跑。
|
||||
* 退出码 0=全绿;非 0=有用例失败(stderr 打印失败项)。
|
||||
*/
|
||||
#include "IGDefender.h"
|
||||
#include "poison/IGPoison.h"
|
||||
#include "policy/IGPolicy.h"
|
||||
#include "anti_jailbreak/IGAntiJailbreak.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int g_pass = 0, g_fail = 0;
|
||||
static void ok(const char *name, int cond) {
|
||||
if (cond) { g_pass++; printf(" PASS %s\n", name); }
|
||||
else { g_fail++; fprintf(stderr, " FAIL %s\n", name); }
|
||||
}
|
||||
|
||||
/* ---- 构造 policy sink 的输入:手工喂 finding 走 ig_policy_sink ---- */
|
||||
static void feed(IGPolicyState *st, IGStatus status, int reason) {
|
||||
IGFinding f;
|
||||
memset(&f, 0, sizeof(f));
|
||||
f.status = status;
|
||||
f.reason = reason;
|
||||
ig_policy_sink(&f, st);
|
||||
}
|
||||
|
||||
/* 跑一组 finding,返回 evaluate 是否触发毒化(并断言 mask 的一致性)。 */
|
||||
static int run_policy(void (*feeder)(IGPolicyState *)) {
|
||||
ig_poison_init(); /* 每例从健康态起 */
|
||||
IGPolicyState st;
|
||||
ig_policy_reset(&st, NULL, NULL);
|
||||
feeder(&st);
|
||||
int triggered = ig_policy_evaluate_and_mark(&st);
|
||||
return triggered;
|
||||
}
|
||||
|
||||
/* ---- A. poison ---- */
|
||||
static void test_poison(void) {
|
||||
printf("[A] poison\n");
|
||||
const uint8_t key[] = { 's','t','a','r','t','i','a','s','o','f','t', 0x11, 0x22 };
|
||||
const size_t n = sizeof(key);
|
||||
uint8_t out[sizeof(key)];
|
||||
|
||||
/* A1 健康:mask==0,apply 恒等 */
|
||||
ig_poison_init();
|
||||
ok("healthy_mask_zero", ig_poison_mask() == 0);
|
||||
memset(out, 0xAB, n);
|
||||
ig_poison_apply(key, out, n);
|
||||
ok("healthy_apply_identity", memcmp(out, key, n) == 0);
|
||||
|
||||
/* A2 毒化:mask!=0,apply 破坏 key(至少一字节不同) */
|
||||
ig_poison_mark(0xC0FFEE);
|
||||
ok("poisoned_mask_nonzero", ig_poison_mask() != 0);
|
||||
ig_poison_apply(key, out, n);
|
||||
ok("poisoned_key_corrupted", memcmp(out, key, n) != 0);
|
||||
|
||||
/* A3 毒化不可逆回健康(再 mark 不会抵消;只有 init 能清) */
|
||||
ig_poison_mark(0x1234);
|
||||
ok("poisoned_still_nonzero_after_second_mark", ig_poison_mask() != 0);
|
||||
ig_poison_init();
|
||||
ok("init_restores_healthy", ig_poison_mask() == 0);
|
||||
|
||||
/* A4 entropy==0 仍生效(防“混 0 = 不生效”) */
|
||||
ig_poison_init();
|
||||
ig_poison_mark(0);
|
||||
ok("zero_entropy_still_poisons", ig_poison_mask() != 0);
|
||||
}
|
||||
|
||||
/* ---- B. policy 分级 ---- */
|
||||
static void f_weak_only(IGPolicyState *st) {
|
||||
feed(st, IG_DETECTED, IG_REASON_FOREIGN_IMAGE); /* 201 WEAK */
|
||||
feed(st, IG_DETECTED, IG_REASON_FRIDA_PORT); /* 204 WEAK */
|
||||
}
|
||||
static void f_unavailable_clear(IGPolicyState *st) {
|
||||
feed(st, IG_UNAVAILABLE, IG_REASON_INLINE_HOOK); /* STRONG reason 但 UNAVAILABLE→忽略 */
|
||||
feed(st, IG_CLEAR, IG_REASON_GOT_REBIND); /* CLEAR→忽略 */
|
||||
}
|
||||
static void f_single_medium(IGPolicyState *st) {
|
||||
feed(st, IG_DETECTED, IG_REASON_OBJC_IMP_CHANGED); /* 110 单 MEDIUM */
|
||||
}
|
||||
static void f_medium_dup(IGPolicyState *st) {
|
||||
feed(st, IG_DETECTED, IG_REASON_OBJC_IMP_CHANGED); /* 110 */
|
||||
feed(st, IG_DETECTED, IG_REASON_OBJC_IMP_CHANGED); /* 110 重复 → 去重后仍算 1 */
|
||||
}
|
||||
static void f_two_medium(IGPolicyState *st) {
|
||||
feed(st, IG_DETECTED, IG_REASON_OBJC_IMP_CHANGED); /* 110 */
|
||||
feed(st, IG_DETECTED, IG_REASON_SYMBOL_PROVENANCE); /* 100 → 2 个不同 MEDIUM */
|
||||
}
|
||||
static void f_single_strong(IGPolicyState *st) {
|
||||
feed(st, IG_DETECTED, IG_REASON_JAILBREAK_SANDBOX); /* 401 STRONG */
|
||||
}
|
||||
|
||||
static void test_policy(void) {
|
||||
printf("[B] policy\n");
|
||||
ok("weak_only_no_trigger", run_policy(f_weak_only) == 0);
|
||||
ok("unavailable_clear_no_trigger",run_policy(f_unavailable_clear) == 0);
|
||||
ok("single_medium_no_trigger", run_policy(f_single_medium) == 0);
|
||||
ok("medium_dup_no_trigger", run_policy(f_medium_dup) == 0); /* 去重:同 reason×2 ≠ 2 distinct */
|
||||
ok("two_distinct_medium_trigger", run_policy(f_two_medium) == 1);
|
||||
ok("single_strong_trigger", run_policy(f_single_strong) == 1);
|
||||
|
||||
/* 触发后 mask 必非 0(策略真的接到了毒化,不只是返回值) */
|
||||
run_policy(f_single_strong);
|
||||
ok("strong_trigger_sets_mask", ig_poison_mask() != 0);
|
||||
ig_poison_init();
|
||||
run_policy(f_weak_only);
|
||||
ok("weak_leaves_mask_zero", ig_poison_mask() == 0);
|
||||
}
|
||||
|
||||
/* ---- C. anti_jailbreak(可注入) ---- */
|
||||
static int g_jb_hits;
|
||||
static int jb_sink(const IGFinding *f, void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->status == IG_DETECTED) g_jb_hits++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void test_jailbreak(void) {
|
||||
printf("[C] anti_jailbreak\n");
|
||||
|
||||
/* C1 反向:全是不存在的路径 + 不做逃逸探测 → 零命中(守误报底线) */
|
||||
const char *absent[] = {
|
||||
"/var/jb/__ig_absent_a", "/Applications/__ig_absent.app", "/usr/bin/__ig_absent"
|
||||
};
|
||||
g_jb_hits = 0;
|
||||
ig_anti_jb_check_paths(absent, sizeof(absent)/sizeof(absent[0]), NULL, jb_sink, NULL);
|
||||
ok("absent_paths_zero_hit", g_jb_hits == 0);
|
||||
|
||||
/* C2 正向 400:构造一个真实存在的临时文件冒充越狱特征文件 → 命中 */
|
||||
char tmpl[] = "/tmp/ig_jb_fileXXXXXX";
|
||||
int fd = mkstemp(tmpl);
|
||||
ok("tmpfile_created", fd >= 0);
|
||||
if (fd >= 0) close(fd);
|
||||
const char *present[] = { tmpl };
|
||||
g_jb_hits = 0;
|
||||
ig_anti_jb_check_paths(present, 1, NULL, jb_sink, NULL);
|
||||
ok("present_path_hits_400", g_jb_hits >= 1);
|
||||
unlink(tmpl);
|
||||
|
||||
/* C3 正向 401:宿主上 /tmp 可写,沙盒逃逸探测应成功创建→命中(真机非越狱则失败=反向) */
|
||||
char probe[] = "/tmp/ig_jb_probeXXXXXX";
|
||||
int pfd = mkstemp(probe); if (pfd >= 0) { close(pfd); unlink(probe); } /* 腾出路径给探测自建 */
|
||||
g_jb_hits = 0;
|
||||
ig_anti_jb_check_paths(absent, sizeof(absent)/sizeof(absent[0]), probe, jb_sink, NULL);
|
||||
ok("sandbox_probe_hits_401_on_host", g_jb_hits >= 1);
|
||||
unlink(probe);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
printf("== poison_host self-test ==\n");
|
||||
test_poison();
|
||||
test_policy();
|
||||
test_jailbreak();
|
||||
printf("== %d pass, %d fail ==\n", g_pass, g_fail);
|
||||
return g_fail == 0 ? 0 : 1;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* poison_inline_caller.c — 模拟接入方(readoor)解密 TU 的「断边」验证夹具。
|
||||
*
|
||||
* rd_derive_key 代表解密前取得明文密钥、喂给解密器前揉入毒化的那一步。它 #include
|
||||
* IGPoisonInline.h 并调用 always_inline 的 ig_poison_mix_key_inline——编译后反汇编本函数
|
||||
* 应**不含任何 `bl ig_poison_*` 调用边**(原语已内联进来),只有对数据 ig_pstate 的读取。
|
||||
* 由 tests/test_poison_inline.py 反汇编断言。
|
||||
*/
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include "poison/IGPoisonInline.h"
|
||||
|
||||
/* 非 static extern:保证不被优化掉,反汇编里能定位到本函数。 */
|
||||
void rd_derive_key(uint8_t *key, size_t n) {
|
||||
ig_poison_mix_key_inline(key, n);
|
||||
}
|
||||
Vendored
+58
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* poison_inline_host.c — 验证 IGPoisonInline.h 内联核心与 IGPoison.c out-of-line 公共入口
|
||||
* 语义等价(单一真源不漂移),且推荐接入形态 ig_poison_mix_key_inline 行为正确:
|
||||
* 健康→密钥不变(解密正常),毒化→密钥被扰动(解出乱码)。
|
||||
* 退出码 0=全部用例通过。由 tests/test_poison_inline.py 编译运行。
|
||||
*/
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "poison/IGPoison.h"
|
||||
#include "poison/IGPoisonInline.h"
|
||||
|
||||
static int fails = 0;
|
||||
static void check(int cond, const char *msg) {
|
||||
printf("%s: %s\n", cond ? "ok" : "FAIL", msg);
|
||||
if (!cond) fails++;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
ig_poison_init();
|
||||
|
||||
/* —— 健康态 —— */
|
||||
check(ig_poison_mask() == 0, "healthy: public mask==0");
|
||||
check(ig_poison_mask_inline() == 0, "healthy: inline mask==0");
|
||||
check(ig_poison_mask_inline() == ig_poison_mask(), "healthy: inline mask==public mask");
|
||||
|
||||
uint8_t ref[16];
|
||||
for (int i = 0; i < 16; ++i) ref[i] = (uint8_t)(i * 7 + 1);
|
||||
|
||||
uint8_t key[16];
|
||||
memcpy(key, ref, 16);
|
||||
ig_poison_mix_key_inline(key, 16);
|
||||
check(memcmp(key, ref, 16) == 0, "healthy: mix_key 恒等(密钥不变→解密正常)");
|
||||
|
||||
uint8_t o1[16], o2[16];
|
||||
ig_poison_apply(ref, o1, 16);
|
||||
ig_poison_apply_inline(ref, o2, 16);
|
||||
check(memcmp(o1, o2, 16) == 0, "healthy: inline apply == public apply");
|
||||
check(memcmp(o1, ref, 16) == 0, "healthy: apply 恒等");
|
||||
|
||||
/* —— 毒化态 —— */
|
||||
ig_poison_mark(0xDEADBEEF12345678ULL);
|
||||
check(ig_poison_mask() != 0, "poisoned: public mask!=0");
|
||||
check(ig_poison_mask_inline() == ig_poison_mask(), "poisoned: inline mask==public mask");
|
||||
|
||||
memcpy(key, ref, 16);
|
||||
ig_poison_mix_key_inline(key, 16);
|
||||
check(memcmp(key, ref, 16) != 0, "poisoned: mix_key 扰动密钥(→解出乱码)");
|
||||
|
||||
ig_poison_apply(ref, o1, 16);
|
||||
ig_poison_apply_inline(ref, o2, 16);
|
||||
check(memcmp(o1, o2, 16) == 0, "poisoned: inline apply == public apply");
|
||||
check(memcmp(o1, ref, 16) != 0, "poisoned: apply 扰动输出");
|
||||
|
||||
printf("%d fail\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
FILE *sdk_open(const char *path, const char *mode) { return fopen(path, mode); }
|
||||
int sdk_fclose(FILE *stream) { return fclose(stream); }
|
||||
size_t sdk_fread(void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
return fread(buffer, size, count, stream);
|
||||
}
|
||||
size_t sdk_fwrite(const void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
return fwrite(buffer, size, count, stream);
|
||||
}
|
||||
ssize_t sdk_read(int fd, void *buffer, size_t count) { return read(fd, buffer, count); }
|
||||
ssize_t sdk_write(int fd, const void *buffer, size_t count) { return write(fd, buffer, count); }
|
||||
int sdk_close(int fd) { return close(fd); }
|
||||
@@ -0,0 +1,315 @@
|
||||
"""Unit tests for M4 features: IGAntiHooking prologue & IGStringEncryption stack-decrypt + volatile wipe."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf'
|
||||
sys.path.insert(0, str(TOOLS_LLVM_OBF))
|
||||
|
||||
from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402
|
||||
|
||||
|
||||
def require_host_opt() -> str:
|
||||
tc = resolve_opt(require_obf=False)
|
||||
opt_path = tc.get('opt_path')
|
||||
if not opt_path:
|
||||
raise unittest.SkipTest(f"Standalone opt not built yet: {tc.get('warning')}")
|
||||
return opt_path
|
||||
|
||||
|
||||
def macos_sdk_path() -> str:
|
||||
return subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip()
|
||||
|
||||
|
||||
def iphoneos_sdk_path() -> str:
|
||||
return subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip()
|
||||
|
||||
|
||||
class TestAntiHookingAndStackStringPass(unittest.TestCase):
|
||||
def test_anti_hooking_prologue_ios_link_and_host_exec(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
sdk_host = macos_sdk_path()
|
||||
sdk_ios = iphoneos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-m4-antihook-') as td:
|
||||
p = Path(td)
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [],
|
||||
'anti_hooking_targets': [{'path_contains': 'hook_target'}],
|
||||
'anti_hooking_exempt_functions': ['exempt_hook_fn'],
|
||||
}), encoding='utf-8')
|
||||
|
||||
src_cpp = p / 'hook_target.cpp'
|
||||
src_cpp.write_text(
|
||||
'''#include <stdint.h>
|
||||
|
||||
extern "C" __attribute__((noinline, used))
|
||||
int safe_c_guard(int x) noexcept {
|
||||
int acc = x ^ 0x33;
|
||||
if (acc < 0) acc += 19;
|
||||
return acc * 3 + 7;
|
||||
}
|
||||
|
||||
__attribute__((noinline))
|
||||
int may_throw_worker(int x) {
|
||||
if (x < 0) throw 42;
|
||||
return x + 11;
|
||||
}
|
||||
|
||||
extern "C" __attribute__((noinline, used))
|
||||
int exempt_hook_fn(int x) noexcept {
|
||||
return x + 5;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int a = safe_c_guard(9);
|
||||
int b = exempt_hook_fn(4);
|
||||
int c = 0;
|
||||
try {
|
||||
c = may_throw_worker(-1);
|
||||
} catch (int v) {
|
||||
c = v;
|
||||
}
|
||||
if (a != ((9 ^ 0x33) * 3 + 7) || b != 9 || c != 42) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
''',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
# 1. Verify iOS arm64 compilation + -Wl,-dead_strip dynamic link + dsymutil + otool -tV
|
||||
bc_ios = p / 'hook_ios.bc'
|
||||
obf_ios = p / 'hook_ios.obf.bc'
|
||||
obj_ios = p / 'hook_ios.o'
|
||||
dylib_ios = p / 'libhook_ios.dylib'
|
||||
aud_ios_p = p / 'hook_ios.audit.json'
|
||||
subprocess.run([
|
||||
clang, '-x', 'c++', '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios,
|
||||
'-Os', '-g', '-fexceptions', '-emit-llvm', '-c', str(src_cpp), '-o', str(bc_ios),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
'--ig-pass-filter=antihook',
|
||||
'--ig-seed=antihook_ios_1',
|
||||
f'--ig-source-path={src_cpp}',
|
||||
f'--ig-audit-out={aud_ios_p}',
|
||||
str(bc_ios), '-o', str(obf_ios),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios,
|
||||
'-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module',
|
||||
'-g', '-x', 'ir', '-c', str(obf_ios), '-o', str(obj_ios),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-dynamiclib',
|
||||
str(obj_ios), '-lc++', '-Wl,-dead_strip', '-o', str(dylib_ios),
|
||||
], check=True)
|
||||
subprocess.run(['xcrun', 'dsymutil', str(dylib_ios), '-o', str(p / 'libhook_ios.dylib.dSYM')], check=True)
|
||||
|
||||
aud_ios = json.loads(aud_ios_p.read_text(encoding='utf-8'))
|
||||
self.assertGreaterEqual(aud_ios['anti_hook_functions_count'], 1)
|
||||
hooked_fns = aud_ios['anti_hook_functions']
|
||||
self.assertIn('safe_c_guard', hooked_fns)
|
||||
self.assertNotIn('exempt_hook_fn', hooked_fns)
|
||||
self.assertFalse(any('may_throw_worker' in fn for fn in hooked_fns), hooked_fns)
|
||||
|
||||
otool_txt = subprocess.check_output(['xcrun', 'otool', '-tV', str(dylib_ios)], text=True)
|
||||
m = re.search(r'^_safe_c_guard:\n([^\n]+)\n([^\n]+)', otool_txt, re.MULTILINE)
|
||||
self.assertIsNotNone(m, otool_txt)
|
||||
first_two = f"{m.group(1)}\n{m.group(2)}"
|
||||
self.assertIn('mov\tx17, x17', first_two)
|
||||
self.assertIn('mov\tx16, x16', first_two)
|
||||
|
||||
# 2. Verify host macOS arm64 execution (both nounwind + throwing catch path run cleanly)
|
||||
bc_host = p / 'hook_host.bc'
|
||||
obf_host = p / 'hook_host.obf.bc'
|
||||
obj_host = p / 'hook_host.o'
|
||||
exe_host = p / 'hook_host_exe'
|
||||
aud_host_p = p / 'hook_host.audit.json'
|
||||
subprocess.run([
|
||||
clang, '-x', 'c++', '-isysroot', sdk_host,
|
||||
'-Os', '-g', '-fexceptions', '-emit-llvm', '-c', str(src_cpp), '-o', str(bc_host),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
'--ig-pass-filter=antihook',
|
||||
'--ig-seed=antihook_host_1',
|
||||
f'--ig-source-path={src_cpp}',
|
||||
f'--ig-audit-out={aud_host_p}',
|
||||
str(bc_host), '-o', str(obf_host),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk_host,
|
||||
'-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module',
|
||||
'-g', '-x', 'ir', '-c', str(obf_host), '-o', str(obj_host),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk_host, str(obj_host), '-lc++', '-Wl,-dead_strip', '-o', str(exe_host),
|
||||
], check=True)
|
||||
rc = subprocess.run([str(exe_host)]).returncode
|
||||
self.assertEqual(rc, 0)
|
||||
|
||||
# 3. Verify -ig-pass-filter=fla skips IGAntiHooking cleanly
|
||||
aud_fla_p = p / 'hook_fla.audit.json'
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
'--ig-pass-filter=fla',
|
||||
'--ig-seed=antihook_fla_1',
|
||||
f'--ig-source-path={src_cpp}',
|
||||
f'--ig-audit-out={aud_fla_p}',
|
||||
str(bc_host), '-o', str(p / 'hook_fla.obf.bc'),
|
||||
], check=True)
|
||||
aud_fla = json.loads(aud_fla_p.read_text(encoding='utf-8'))
|
||||
self.assertEqual(aud_fla['anti_hook_functions_count'], 0)
|
||||
|
||||
def test_stack_string_encryption_volatile_wipe_and_fallbacks(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
sdk_host = macos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-m4-stackstr-') as td:
|
||||
p = Path(td)
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [],
|
||||
'string_encrypt_targets': [{'path_contains': 'stack_str.c'}],
|
||||
'string_encrypt_stack_targets': [{'path_contains': 'stack_str.c'}],
|
||||
'string_encrypt_stack_max_len': 20,
|
||||
}), encoding='utf-8')
|
||||
|
||||
src_c = p / 'stack_str.c'
|
||||
src_c.write_text(
|
||||
'''#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
__attribute__((noinline))
|
||||
void store_global_fallback(const char **out) {
|
||||
*out = "STORE_GLOBAL_OK";
|
||||
}
|
||||
|
||||
__attribute__((noinline))
|
||||
const char *strstr_arg0_fallback(const char *needle) {
|
||||
return strstr("HAYSTACK_GLOBAL_ALPHA", needle);
|
||||
}
|
||||
|
||||
__attribute__((noinline))
|
||||
int too_long_fallback(const char *probe) {
|
||||
return strcmp(probe, "OVER_MAX_LEN_GLOBAL_STRING_12345");
|
||||
}
|
||||
|
||||
__attribute__((noinline))
|
||||
int stack_checks(const char *s1, const char *s2) {
|
||||
int ok = 1;
|
||||
if (strcmp(s1, "STACK_TOK_1") != 0) ok = 0;
|
||||
if (strstr(s2, "NEEDLE_2") == NULL) ok = 0;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
if (strcmp(s1, "STACK_TOK_1") != 0) ok = 0;
|
||||
}
|
||||
const char *envv = getenv("IG_UNSET_STACK_ENV");
|
||||
if (envv != NULL) ok = 0;
|
||||
return ok;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
volatile char b1[] = {'S','T','A','C','K','_','T','O','K','_','X',0};
|
||||
b1[10] = '1';
|
||||
char s1[16];
|
||||
for (int i = 0; i < 12; ++i) s1[i] = b1[i];
|
||||
if (!stack_checks(s1, "prefix_NEEDLE_2_suffix")) return 1;
|
||||
|
||||
const char *stored = NULL;
|
||||
store_global_fallback(&stored);
|
||||
if (!stored || strcmp(stored, "STORE_GLOBAL_OK") != 0) return 2;
|
||||
|
||||
volatile char nb[] = {'A','L','P','H','X',0};
|
||||
nb[4] = 'A';
|
||||
char needle[8];
|
||||
for (int i = 0; i < 6; ++i) needle[i] = nb[i];
|
||||
const char *found = strstr_arg0_fallback(needle);
|
||||
if (!found || strcmp(found, "ALPHA") != 0) return 3;
|
||||
|
||||
volatile char lb[] = {
|
||||
'O','V','E','R','_','M','A','X','_','L','E','N','_',
|
||||
'G','L','O','B','A','L','_','S','T','R','I','N','G','_',
|
||||
'1','2','3','4','X',0
|
||||
};
|
||||
lb[31] = '5';
|
||||
char long_probe[40];
|
||||
for (int i = 0; i < 33; ++i) long_probe[i] = lb[i];
|
||||
if (too_long_fallback(long_probe) != 0) return 4;
|
||||
return 0;
|
||||
}
|
||||
''',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
bc_p = p / 'stack_str.bc'
|
||||
obf_ll = p / 'stack_str.obf.ll'
|
||||
obj_o = p / 'stack_str.o'
|
||||
exe_p = p / 'stack_str_exe'
|
||||
aud_p = p / 'stack_str.audit.json'
|
||||
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_p),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-S', '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=str',
|
||||
'--ig-seed=stackstr_seed_1',
|
||||
f'--ig-source-path={src_c}',
|
||||
f'--ig-audit-out={aud_p}',
|
||||
str(bc_p), '-o', str(obf_ll),
|
||||
], check=True)
|
||||
|
||||
ir_txt = obf_ll.read_text(encoding='utf-8')
|
||||
aud = json.loads(aud_p.read_text(encoding='utf-8'))
|
||||
|
||||
# 3 stack-only short literals in stack_checks ("STACK_TOK_1", "NEEDLE_2", "IG_UNSET_STACK_ENV"),
|
||||
# plus global fallback literals (stored pointer, strstr arg-0, over-max-len string, etc.)
|
||||
self.assertGreaterEqual(aud['strings_stack_encrypted_count'], 3, aud)
|
||||
self.assertGreaterEqual(aud['strings_encrypted_count'], aud['strings_stack_encrypted_count'] + 3, aud)
|
||||
self.assertIn('alloca [12 x i8]', ir_txt) # "STACK_TOK_1\0" -> 12 bytes
|
||||
self.assertIn('store volatile i8 0,', ir_txt)
|
||||
self.assertIn('@__ig_str_dec_stack', ir_txt)
|
||||
# Global fallback strings must still create .ig.buf. / .ig.state.
|
||||
self.assertIn('.ig.buf.', ir_txt)
|
||||
# Plaintext literals must not remain in IR
|
||||
self.assertNotIn('STACK_TOK_1', ir_txt)
|
||||
self.assertNotIn('NEEDLE_2', ir_txt)
|
||||
self.assertNotIn('IG_UNSET_STACK_ENV', ir_txt)
|
||||
self.assertNotIn('STORE_GLOBAL_OK', ir_txt)
|
||||
self.assertNotIn('HAYSTACK_GLOBAL_ALPHA', ir_txt)
|
||||
self.assertNotIn('OVER_MAX_LEN_GLOBAL_STRING_12345', ir_txt)
|
||||
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes',
|
||||
'-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ll), '-o', str(obj_o),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk_host, str(obj_o), '-Wl,-dead_strip', '-o', str(exe_p),
|
||||
], check=True)
|
||||
rc = subprocess.run([str(exe_p)]).returncode
|
||||
self.assertEqual(rc, 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,38 @@
|
||||
"""IGAntiTamper 宿主自测:cryptid 核心逻辑(合成 Mach-O 头)。
|
||||
|
||||
真机的 csops 代码签名检查与真实主镜像 cryptid 由设备测试覆盖;此处固化可复现的
|
||||
cryptid 判定基线(加密正常/脱壳/剥除/非分发跳过/NULL),退出码 0 = 全过。
|
||||
"""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCES = ['anti_tamper/IGAntiTamper.c']
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin' and shutil.which('xcrun'), '需要 Xcode/macOS')
|
||||
class AntiTamperCryptidTests(unittest.TestCase):
|
||||
def test_cryptid_core(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
exe = Path(d) / 'anti-tamper-host'
|
||||
env = dict(os.environ)
|
||||
env.pop('DYLD_INSERT_LIBRARIES', None)
|
||||
args = ['xcrun', '--sdk', 'macosx', 'clang', '-O2',
|
||||
'-I', str(ROOT / 'defender/include'), '-I', str(ROOT / 'defender'),
|
||||
str(ROOT / 'tests/fixtures/anti_tamper_host.c'),
|
||||
*(str(ROOT / 'defender' / p) for p in SOURCES),
|
||||
'-o', str(exe)]
|
||||
build = subprocess.run(args, capture_output=True, text=True, env=env)
|
||||
self.assertEqual(build.returncode, 0, build.stdout + build.stderr)
|
||||
run = subprocess.run([str(exe)], capture_output=True, text=True, env=env)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
self.assertIn('PASSED', run.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,140 @@
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import os
|
||||
import platform
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'tools/macho_guard'))
|
||||
from redirect_framework_imports import rewrite, DEPENDENCY
|
||||
from machox import Macho, LC_DYLD_CHAINED_FIXUPS
|
||||
|
||||
SDK = ROOT/'readoor-test/readoor/BookShelf/Classes/Factorys/SSZipArchive/SSZipArchive.framework/SSZipArchive'
|
||||
SHA = '485c0c95b4701a4e51625e16b6c2a9781c1a8a6f6c9b9cbe392709ecfc95191a'
|
||||
|
||||
|
||||
@unittest.skipUnless(SDK.exists(), '需要已审核 SDK 副本')
|
||||
class FrameworkRewriteTests(unittest.TestCase):
|
||||
def setUp(self): self.data = SDK.read_bytes()
|
||||
def rejected(self, data):
|
||||
with self.assertRaises((ValueError, struct.error)):
|
||||
rewrite(data, hashlib.sha256(data).hexdigest())
|
||||
def test_real_sdk(self):
|
||||
data, report = rewrite(self.data, SHA)
|
||||
self.assertEqual(len(data), len(self.data))
|
||||
self.assertEqual(len(report['changes']), 8)
|
||||
self.assertTrue(report['machine_code_unchanged'])
|
||||
self.assertIn(DEPENDENCY.encode(), data[:32768])
|
||||
m = Macho(data)
|
||||
self.assertEqual(m.ncmds, Macho(self.data).ncmds+1)
|
||||
self.assertEqual(data[32768:212992], self.data[32768:212992])
|
||||
def test_explicit_fopen_subset(self):
|
||||
data, report = rewrite(self.data, SHA, {'_fopen': '_rd_a0'})
|
||||
self.assertEqual(report['total_symbols'], 1)
|
||||
self.assertEqual(len(report['changes']), 2)
|
||||
self.assertEqual({r['source'] for r in report['changes']}, {'_fopen'})
|
||||
self.assertIn(b'_fread\0', data)
|
||||
self.assertIn(b'_fwrite\0', data)
|
||||
self.assertIn(b'_fclose\0', data)
|
||||
self.assertTrue(report['machine_code_unchanged'])
|
||||
|
||||
def test_unknown_or_empty_subset_rejected(self):
|
||||
for mapping in ({}, {'_fopen': '_unexpected'}, {'_open': '_rd_a0'}):
|
||||
with self.subTest(mapping=mapping), self.assertRaises(ValueError):
|
||||
rewrite(self.data, SHA, mapping)
|
||||
|
||||
def test_wrong_hash(self):
|
||||
with self.assertRaises(ValueError): rewrite(self.data, '0'*64)
|
||||
def test_repeat_rejected(self):
|
||||
data, _ = rewrite(self.data, SHA); self.rejected(data)
|
||||
def test_no_padding(self):
|
||||
data = bytearray(self.data); data[32+Macho(data).sizeofcmds] = 1; self.rejected(data)
|
||||
def test_unsupported_import_format(self):
|
||||
data = bytearray(self.data); m = Macho(data)
|
||||
off = next(o for c,_,o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS)
|
||||
fixoff = struct.unpack_from('<I',data,off+8)[0]
|
||||
struct.pack_into('<I',data,fixoff+20,3); self.rejected(data)
|
||||
def test_wrong_provider_and_weak(self):
|
||||
m = Macho(self.data); off = next(o for c,_,o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS)
|
||||
fixoff = struct.unpack_from('<I',self.data,off+8)[0]
|
||||
imports = struct.unpack_from('<I',self.data,fixoff+8)[0]
|
||||
for mask in (0x100, 1):
|
||||
with self.subTest(mask=mask):
|
||||
data = bytearray(self.data); pos = fixoff+imports+43*4
|
||||
word = struct.unpack_from('<I',data,pos)[0]
|
||||
struct.pack_into('<I',data,pos,word^mask); self.rejected(data)
|
||||
def test_truncated(self): self.rejected(self.data[:3000])
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin', '需要 Apple 工具链')
|
||||
class ArchiveABITests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory(); cls.exe = Path(cls.tmp.name)/'archive-host'
|
||||
cls.env = dict(os.environ); cls.env.pop('DYLD_INSERT_LIBRARIES',None)
|
||||
cls.sources = [str(ROOT/'defender'/s) for s in
|
||||
('dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c')]
|
||||
command = ['xcrun','--sdk','macosx','clang','-O2','-Wall','-Wextra','-Werror',
|
||||
'-DIG_ARCHIVE_TESTING','-DIG_OBSERVATION','-I',str(ROOT/'defender'),
|
||||
'-I',str(ROOT/'defender/include'),str(ROOT/'tests/fixtures/archive_host.c'),
|
||||
*cls.sources,'-o',str(cls.exe)]
|
||||
r = subprocess.run(command,capture_output=True,text=True,env=cls.env)
|
||||
if r.returncode: raise RuntimeError(r.stderr)
|
||||
@classmethod
|
||||
def tearDownClass(cls): cls.tmp.cleanup()
|
||||
def run_mode(self,mode):
|
||||
r = subprocess.run([self.exe,mode],capture_output=True,text=True,env=self.env,timeout=30)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
def test_stdio_semantics(self): self.run_mode('semantics')
|
||||
def test_concurrent_initialization(self): self.run_mode('threads')
|
||||
def test_tamper_refuses_before_call(self): self.run_mode('tamper')
|
||||
def test_reentry(self): self.run_mode('reentry')
|
||||
def test_read_write_close_reject(self): self.run_mode('rejection')
|
||||
def test_release_has_no_test_or_observation_api(self):
|
||||
output = Path(self.tmp.name)/'release.dylib'
|
||||
r = subprocess.run(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-O2','-fvisibility=hidden','-dynamiclib',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),*self.sources,
|
||||
'-o',str(output)],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
nm = subprocess.run(['xcrun','nm','-g',output],capture_output=True,text=True,check=True).stdout
|
||||
self.assertNotIn('ig_archive_test_',nm); self.assertNotIn('_ig_archive_counter',nm)
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin' and platform.machine() == 'arm64', '需要 Apple Silicon')
|
||||
class ArchiveBindingIntegrationTests(unittest.TestCase):
|
||||
def test_real_dyld_binding_and_got_tamper(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
guard = root/'RDCoreIO.framework/RDCoreIO'
|
||||
sdk = root/'SSZipArchive.framework/SSZipArchive'
|
||||
guard.parent.mkdir(); sdk.parent.mkdir()
|
||||
common = ['xcrun','--sdk','macosx','clang','-arch','arm64','-mmacosx-version-min=13.0','-O2']
|
||||
env = dict(os.environ); env.pop('DYLD_INSERT_LIBRARIES',None)
|
||||
def command(args):
|
||||
r = subprocess.run(args,capture_output=True,text=True,env=env,timeout=40)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
return r
|
||||
command(common+['-dynamiclib','-DIG_OBSERVATION','-fvisibility=hidden',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
*(str(ROOT/'defender'/s) for s in
|
||||
('dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c')),
|
||||
'-Wl,-install_name,'+DEPENDENCY,'-o',str(guard)])
|
||||
command(common+['-dynamiclib',str(ROOT/'tests/fixtures/archive_sdk.c'),
|
||||
'-Wl,-install_name,@rpath/SSZipArchive.framework/SSZipArchive',
|
||||
'-Wl,-headerpad,0x4000','-Wl,-rpath,@loader_path/..','-o',str(sdk)])
|
||||
data = sdk.read_bytes(); changed, _ = rewrite(data,hashlib.sha256(data).hexdigest())
|
||||
sdk.write_bytes(changed)
|
||||
command(['codesign','--force','--sign','-',str(guard)])
|
||||
command(['codesign','--force','--sign','-',str(sdk)])
|
||||
exe = root/'binding-test'
|
||||
command(common+[str(ROOT/'tests/fixtures/archive_binding_host.c'),'-o',str(exe)])
|
||||
result = command([str(exe),str(sdk),str(root/'stdio.bin')])
|
||||
self.assertIn('均通过',result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,72 @@
|
||||
"""宿主探针正反例与 iOS 编译验证;不替代真机 inline Hook 测试。"""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCES = ['IGDefender.c','anti_hook/IGAntiHook.c','anti_hook/IGObjCBaseline.c',
|
||||
'anti_frida/IGAntiInject.c','anti_debug/IGAntiDebug.c',
|
||||
'anti_jailbreak/IGAntiJailbreak.c',
|
||||
'syscall/IGSyscall.c','resolve/IGResolve.c','dispatch/IGDispatch.c']
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform=='darwin' and shutil.which('xcrun'), '需要 Xcode/macOS')
|
||||
class DefenderTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.folder = Path(cls.tmp.name)
|
||||
cls.exe = cls.folder/'defender-host'
|
||||
cls.env = dict(os.environ)
|
||||
cls.env.pop('DYLD_INSERT_LIBRARIES', None)
|
||||
cls.compile(['xcrun','--sdk','macosx','clang','-O2',
|
||||
'-I',str(ROOT/'defender/include'),'-I',str(ROOT/'defender'),
|
||||
str(ROOT/'tests/fixtures/defender_host.c'),
|
||||
*(str(ROOT/'defender'/p) for p in SOURCES),
|
||||
'-lobjc','-o',str(cls.exe)])
|
||||
fixture = cls.folder/'empty.c'
|
||||
fixture.write_text('int ig_fixture_marker(void) { return 1; }\n')
|
||||
cls.image = cls.folder/'fixture_frida.dylib'
|
||||
cls.compile(['xcrun','--sdk','macosx','clang','-dynamiclib',str(fixture),'-o',str(cls.image)])
|
||||
|
||||
@classmethod
|
||||
def compile(cls, args):
|
||||
p = subprocess.run(args,capture_output=True,text=True,env=cls.env)
|
||||
if p.returncode:
|
||||
raise RuntimeError(p.stdout+p.stderr)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def check_mode(self, mode, *args):
|
||||
p = subprocess.run([str(self.exe),mode,*map(str,args)],
|
||||
capture_output=True,text=True,env=self.env)
|
||||
self.assertEqual(p.returncode,0,p.stdout+p.stderr)
|
||||
# 保留各探针证据到 unittest 日志。
|
||||
print(mode+': '+p.stdout.strip(), flush=True)
|
||||
|
||||
def test_clean(self): self.check_mode('clean')
|
||||
def test_unavailable(self): self.check_mode('unresolved')
|
||||
def test_function_provenance(self): self.check_mode('verify')
|
||||
def test_environment_entries(self): self.check_mode('env')
|
||||
def test_loaded_image(self): self.check_mode('image',self.image)
|
||||
def test_got_rebinding(self): self.check_mode('got')
|
||||
def test_debugger_clean(self): self.check_mode('debugger')
|
||||
def test_objc_baseline_clean(self): self.check_mode('objc-clean')
|
||||
def test_objc_baseline_swap(self): self.check_mode('objc-swap')
|
||||
|
||||
def test_iphoneos_cross_compile(self):
|
||||
for i, source in enumerate(SOURCES):
|
||||
self.compile(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-O2',
|
||||
'-I',str(ROOT/'defender/include'),'-I',str(ROOT/'defender'),
|
||||
'-c',str(ROOT/'defender'/source),'-o',str(self.folder/f'{i}.o')])
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,82 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
SOURCES=['dispatch/IGDispatch.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c']
|
||||
|
||||
@unittest.skipUnless(sys.platform=='darwin','需要 Apple 工具链')
|
||||
class DispatchTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp=tempfile.TemporaryDirectory()
|
||||
cls.exe=Path(cls.tmp.name)/'dispatch-test'
|
||||
cls.env=dict(os.environ);cls.env.pop('DYLD_INSERT_LIBRARIES',None)
|
||||
p=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-Wall','-Wextra','-Werror',
|
||||
'-DIG_DISPATCH_TESTING','-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
str(ROOT/'tests/fixtures/dispatch_host.c'),*(str(ROOT/'defender'/p) for p in SOURCES),
|
||||
'-o',str(cls.exe)],capture_output=True,text=True,env=cls.env)
|
||||
if p.returncode:raise RuntimeError(p.stderr)
|
||||
@classmethod
|
||||
def tearDownClass(cls):cls.tmp.cleanup()
|
||||
def run_mode(self,mode):
|
||||
p=subprocess.run([str(self.exe),mode],capture_output=True,text=True,env=self.env,timeout=30)
|
||||
self.assertEqual(p.returncode,0,p.stdout+p.stderr)
|
||||
def test_extended_file_semantics(self):self.run_mode('extended')
|
||||
def test_extended_tamper_rejected(self):self.run_mode('extended-tamper')
|
||||
def test_read_eintr(self):self.run_mode('read-eintr')
|
||||
def test_semantics(self):self.run_mode('semantics')
|
||||
def test_short_write(self):self.run_mode('short-write')
|
||||
def test_eintr(self):self.run_mode('eintr')
|
||||
def test_concurrency(self):self.run_mode('threads')
|
||||
def test_tamper_rejected(self):self.run_mode('tamper')
|
||||
def test_reentry(self):self.run_mode('reentry')
|
||||
def test_resolver_errors(self):self.run_mode('resolver')
|
||||
def test_prologue_patterns(self):self.run_mode('prologue')
|
||||
def test_observation_counters_and_release_exclusion(self):
|
||||
exe=Path(self.tmp.name)/'observation'
|
||||
r=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-Wall','-Wextra','-Werror',
|
||||
'-DIG_DISPATCH_TESTING','-DIG_OBSERVATION',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
str(ROOT/'tests/fixtures/dispatch_host.c'),*(str(ROOT/'defender'/p) for p in SOURCES),
|
||||
'-o',str(exe)],capture_output=True,text=True,env=self.env)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
r=subprocess.run([str(exe),'observation'],capture_output=True,text=True,env=self.env,timeout=30)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
r=subprocess.run(['xcrun','nm',str(self.exe)],capture_output=True,text=True,check=True)
|
||||
self.assertNotIn('_ig_dispatch_observation',r.stdout)
|
||||
def test_ios_compile(self):
|
||||
for i,p in enumerate(SOURCES):
|
||||
r=subprocess.run(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-O2','-I',str(ROOT/'defender/include'),
|
||||
'-c',str(ROOT/'defender'/p),'-o',str(Path(self.tmp.name)/f'{i}.o')],
|
||||
capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
# The Release objects must not introduce direct references to
|
||||
# any of the 12 report symbols they shield or use internally.
|
||||
forbidden = {'_write','_close','_read','_open','_unlink','_getpid','_fopen',
|
||||
'_exit','_fork','_dlopen','_dlsym','_syscall'}
|
||||
for i in range(len(SOURCES)):
|
||||
r=subprocess.run(['xcrun','nm','-u',str(Path(self.tmp.name)/f'{i}.o')],
|
||||
capture_output=True,text=True,check=True)
|
||||
undefined={line.split()[-1] for line in r.stdout.splitlines() if line.split()}
|
||||
self.assertFalse(undefined & forbidden, f'{SOURCES[i]}: {r.stdout}')
|
||||
def test_initialization_failure(self):
|
||||
obj=Path(self.tmp.name)/'missing-resolver.o'
|
||||
exe=Path(self.tmp.name)/'init-failure'
|
||||
r=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-Ddlsym=ig_fixture_missing_resolve',
|
||||
'-I',str(ROOT/'defender/include'),
|
||||
'-c',str(ROOT/'defender/resolve/IGResolve.c'),'-o',str(obj)],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
r=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-DIG_DISPATCH_TESTING','-DIG_EXPECT_INIT_FAILURE',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
str(ROOT/'tests/fixtures/dispatch_host.c'),str(ROOT/'defender/dispatch/IGDispatch.c'),
|
||||
str(ROOT/'defender/anti_hook/IGAntiHook.c'),str(obj),'-o',str(exe)],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
r=subprocess.run([str(exe),'init-failure'],capture_output=True,text=True,timeout=30)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,82 @@
|
||||
"""编译 App 副本的真实 GCDWebServer 和 Defender,验证文件流程与异常处置。"""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
APP = ROOT / 'readoor-test/readoor'
|
||||
GCD = APP / 'BookShelf/Classes/Factorys/GCDWebServer'
|
||||
DEFENDER = APP / '3.0/Base/Security/IGDefender'
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin' and GCD.exists(), '需要 macOS 和 App 副本')
|
||||
class GCDFileIntegrationTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.exe = Path(cls.tmp.name) / 'gcd-file-test'
|
||||
cls.env = dict(os.environ)
|
||||
cls.env.pop('DYLD_INSERT_LIBRARIES', None)
|
||||
cls.includes = [arg for p in (GCD/'Core', GCD/'Requests', GCD/'Responses',
|
||||
DEFENDER, DEFENDER/'include') for arg in ('-I', str(p))]
|
||||
sources = [str(p) for p in GCD.rglob('*.m')]
|
||||
sources += [str(DEFENDER/p) for p in ('dispatch/IGDispatch.c', 'resolve/IGResolve.c',
|
||||
'anti_hook/IGAntiHook.c')]
|
||||
command = ['xcrun', '--sdk', 'macosx', 'clang', '-O2', '-fobjc-arc',
|
||||
'-DIG_DISPATCH_TESTING', '-DIG_HOOK_TERMINATE_DEFAULT=0',
|
||||
*cls.includes, str(ROOT/'tests/fixtures/gcd_file_integration.m'), *sources,
|
||||
'-framework', 'Foundation', '-framework', 'CFNetwork',
|
||||
'-framework', 'SystemConfiguration', '-framework', 'Security',
|
||||
'-framework', 'CoreServices',
|
||||
'-lz', '-o', str(cls.exe)]
|
||||
result = subprocess.run(command, capture_output=True, text=True, env=cls.env)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stderr)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_mode(self, mode, expected=0):
|
||||
result = subprocess.run([str(self.exe), mode], capture_output=True, text=True,
|
||||
env=self.env, timeout=30)
|
||||
self.assertEqual(result.returncode, expected, result.stdout + result.stderr)
|
||||
|
||||
def test_upload_range_read_and_cleanup(self): self.run_mode('normal')
|
||||
def test_multipart_stream_and_cleanup(self): self.run_mode('multipart-normal')
|
||||
def test_multipart_failed_write(self): self.run_mode('multipart-tamper')
|
||||
def test_descriptor_zero_is_valid(self): self.run_mode('fd-zero')
|
||||
def test_open_tamper_creates_no_file(self): self.run_mode('open-tamper')
|
||||
def test_write_tamper_writes_no_data(self): self.run_mode('write-tamper')
|
||||
def test_read_tamper_returns_error(self): self.run_mode('read-tamper')
|
||||
def test_existing_termination_policy_is_preserved(self):
|
||||
result = subprocess.run([str(self.exe), 'terminate'], capture_output=True, text=True,
|
||||
env=self.env, timeout=30)
|
||||
self.assertIn(result.returncode, (-signal.SIGTRAP, -signal.SIGILL), result.stdout + result.stderr)
|
||||
|
||||
def test_ios_release_objects_use_protected_entries(self):
|
||||
for relative, protected in [
|
||||
('Core/GCDWebServer.m', {'close'}),
|
||||
('Core/GCDWebServerConnection.m', {'close'}),
|
||||
('Requests/GCDWebServerMultiPartFormRequest.m', {'open', 'write', 'close', 'unlink'}),
|
||||
('Requests/GCDWebServerFileRequest.m', {'open', 'write', 'close', 'unlink'}),
|
||||
('Responses/GCDWebServerFileResponse.m', {'open', 'read', 'close'})
|
||||
]:
|
||||
obj = Path(self.tmp.name) / (Path(relative).stem + '.o')
|
||||
result = subprocess.run(['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
|
||||
'-miphoneos-version-min=15.0', '-O2', '-fobjc-arc', *self.includes,
|
||||
'-c', str(GCD/relative), '-o', str(obj)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
result = subprocess.run(['xcrun', 'nm', '-u', str(obj)],
|
||||
capture_output=True, text=True, check=True)
|
||||
symbols = {line.split()[-1] for line in result.stdout.splitlines() if line.split()}
|
||||
self.assertTrue({'_IG_dispatch_' + n for n in protected} <= symbols, symbols)
|
||||
self.assertFalse({'_' + n for n in protected} & symbols, symbols)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,417 @@
|
||||
"""Unit tests for M3 pass: IGIndirectBranch (encrypted jump-table indirectbr)."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf'
|
||||
sys.path.insert(0, str(TOOLS_LLVM_OBF))
|
||||
|
||||
from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402
|
||||
import verify_macho_indirect_branches # noqa: E402
|
||||
import verify_macho_star_cfg # noqa: E402
|
||||
|
||||
|
||||
def require_host_opt() -> str:
|
||||
tc = resolve_opt(require_obf=False)
|
||||
opt_path = tc.get('opt_path')
|
||||
if not opt_path:
|
||||
raise unittest.SkipTest(f"Standalone opt not built yet: {tc.get('warning')}")
|
||||
return opt_path
|
||||
|
||||
|
||||
def macos_sdk_path() -> str:
|
||||
return subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip()
|
||||
|
||||
|
||||
def iphoneos_sdk_path() -> str:
|
||||
return subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip()
|
||||
|
||||
|
||||
class TestIndirectBranchPass(unittest.TestCase):
|
||||
def test_c_flattened_and_unflattened_indirect_branch_link_and_exec(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
sdk_host = macos_sdk_path()
|
||||
sdk_ios = iphoneos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-m3-ibr-c-') as td:
|
||||
p = Path(td)
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [],
|
||||
'flatten_topology': 'sparse_switch',
|
||||
'flatten_bogus_blocks': 2,
|
||||
'flatten_split_linear_blocks': True,
|
||||
'flatten_targets': [{'path_contains': 'ibr_c.c', 'function_contains': 'compute_flow'}],
|
||||
'indirect_branch_targets': [{'path_contains': 'ibr_c.c'}],
|
||||
'indirect_branch_exempt_functions': ['exempt_branch_fn'],
|
||||
}), encoding='utf-8')
|
||||
|
||||
src_c = p / 'ibr_c.c'
|
||||
src_c.write_text(
|
||||
'''#include <stdint.h>
|
||||
|
||||
__attribute__((noinline))
|
||||
int compute_flow(int x, int mode) {
|
||||
int acc = 17;
|
||||
if (x < 0) {
|
||||
acc = (acc * 3) ^ (-x);
|
||||
} else if (x == 0) {
|
||||
acc = 91;
|
||||
} else {
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
acc = (acc + (x ^ i)) ^ (mode + i);
|
||||
}
|
||||
}
|
||||
switch (mode & 3) {
|
||||
case 0: acc += 11; break;
|
||||
case 1: acc ^= 0x55; break;
|
||||
case 2: acc -= 7; break;
|
||||
default: acc += 3; break;
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
__attribute__((noinline))
|
||||
static int internal_helper(int v) {
|
||||
if (v > 10) return v * 2 + 1;
|
||||
if (v < 0) return -v + 3;
|
||||
return v + 9;
|
||||
}
|
||||
|
||||
__attribute__((noinline))
|
||||
static int dead_unused_helper(int v) {
|
||||
if (v > 5) return v + 100;
|
||||
return v - 100;
|
||||
}
|
||||
|
||||
__attribute__((noinline))
|
||||
int exempt_branch_fn(int v) {
|
||||
if (v > 0) return v + 2;
|
||||
return v - 2;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int inputs[][2] = {{-5, 0}, {0, 1}, {7, 2}, {13, 3}, {4, 0}};
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
sum ^= compute_flow(inputs[i][0], inputs[i][1]);
|
||||
sum += internal_helper(inputs[i][0]);
|
||||
}
|
||||
sum += exempt_branch_fn(5);
|
||||
// Expected deterministic value computed directly from reference:
|
||||
// i=0: compute_flow(-5,0)=71, internal(-5)=8
|
||||
// i=1: compute_flow(0,1)=14 (91 ^ 0x55), internal(0)=9
|
||||
// i=2: compute_flow(7,2): acc starts 17; i=0:(24^2=26),i=1:(32^3=35),i=2:(40^4=44),i=3:(48^5=53) =>53-7=46? Wait: use exact volatile compare in test or exact oracle!
|
||||
(void)dead_unused_helper;
|
||||
return (sum != 0) ? sum : 0;
|
||||
}
|
||||
''',
|
||||
encoding='utf-8',
|
||||
)
|
||||
# Compile un-obfuscated reference binary on host to get exact golden return value
|
||||
ref_exe = p / 'ref_host'
|
||||
subprocess.run([clang, '-isysroot', sdk_host, '-O2', str(src_c), '-o', str(ref_exe)], check=True)
|
||||
ref_rc = subprocess.run([str(ref_exe)]).returncode
|
||||
|
||||
bc_host = p / 'ibr_host.bc'
|
||||
subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_host)], check=True)
|
||||
|
||||
def build_host(tag: str, seed: str, pass_filter: str):
|
||||
obf_bc = p / f'{tag}.obf.bc'
|
||||
obj_o = p / f'{tag}.o'
|
||||
aud_p = p / f'{tag}.audit.json'
|
||||
exe_p = p / f'{tag}.exe'
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
f'--ig-pass-filter={pass_filter}',
|
||||
f'--ig-seed={seed}',
|
||||
f'--ig-source-path={src_c}',
|
||||
f'--ig-audit-out={aud_p}',
|
||||
str(bc_host), '-o', str(obf_bc),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk_host, '-O2',
|
||||
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
|
||||
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
|
||||
], check=True)
|
||||
subprocess.run([clang, '-isysroot', sdk_host, str(obj_o), '-Wl,-dead_strip', '-o', str(exe_p)], check=True)
|
||||
return obj_o, exe_p, json.loads(aud_p.read_text(encoding='utf-8'))
|
||||
|
||||
o1, exe1, aud1 = build_host('h1', 'ibr_seed_1', 'all')
|
||||
o2, _, _ = build_host('h2', 'ibr_seed_1', 'all')
|
||||
o3, exe3, _ = build_host('h3', 'ibr_seed_2', 'all')
|
||||
_, exe_ibr_only, aud_ibr_only = build_host('ibr_only', 'ibr_seed_1', 'ibr')
|
||||
|
||||
self.assertEqual(hashlib.sha256(o1.read_bytes()).hexdigest(), hashlib.sha256(o2.read_bytes()).hexdigest())
|
||||
self.assertNotEqual(hashlib.sha256(o1.read_bytes()).hexdigest(), hashlib.sha256(o3.read_bytes()).hexdigest())
|
||||
|
||||
self.assertGreaterEqual(aud1['indirect_branches_count'], 4, aud1)
|
||||
self.assertIn('compute_flow', aud1['indirect_branches_functions'])
|
||||
self.assertNotIn('exempt_branch_fn', aud1['indirect_branches_functions'])
|
||||
self.assertEqual(aud_ibr_only['functions_flattened'], [])
|
||||
self.assertGreaterEqual(aud_ibr_only['indirect_branches_count'], 2)
|
||||
|
||||
for exe in (exe1, exe3, exe_ibr_only):
|
||||
self.assertEqual(subprocess.run([str(exe)]).returncode, ref_rc)
|
||||
|
||||
# Verify StarCFGGate + IndirectBranchGate on linked host Mach-O + dSYM
|
||||
dsym1 = p / 'h1.dSYM'
|
||||
subprocess.run(['xcrun', 'dsymutil', str(exe1), '-o', str(dsym1)], check=True)
|
||||
dwarf1 = dsym1 / 'Contents/Resources/DWARF' / exe1.name
|
||||
audit_wrapper = {'module_audits': [{
|
||||
'source_path': str(src_c),
|
||||
'functions_flattened_details': aud1['functions_flattened_details'],
|
||||
'indirect_branches_functions': aud1['indirect_branches_functions'],
|
||||
}]}
|
||||
star_res = verify_macho_star_cfg.verify_binary_star_cfg(
|
||||
exe1, dwarf1, audit_wrapper, require_topology=''
|
||||
)
|
||||
self.assertEqual(star_res['failed_count'], 0)
|
||||
ibr_res = verify_macho_indirect_branches.verify_binary_indirect_branches(
|
||||
exe1, dwarf1, audit_wrapper, required_sources=[src_c.name]
|
||||
)
|
||||
self.assertEqual(ibr_res['failed_count'], 0)
|
||||
self.assertGreaterEqual(ibr_res['verified_ibr_count'], 2)
|
||||
self.assertEqual(ibr_res['required_sources_verified'], {src_c.name: ibr_res['verified_ibr_count']})
|
||||
audit_with_unlinked = {'module_audits': [
|
||||
*audit_wrapper['module_audits'],
|
||||
{'source_path': 'required.c', 'indirect_branches_functions': ['unlinked_func']},
|
||||
]}
|
||||
with self.assertRaisesRegex(AssertionError, r'required\.c'):
|
||||
verify_macho_indirect_branches.verify_binary_indirect_branches(
|
||||
exe1, dwarf1, audit_with_unlinked, required_sources=['required.c']
|
||||
)
|
||||
nm_exe = subprocess.check_output(['xcrun', 'nm', str(exe1)], text=True)
|
||||
self.assertNotIn('dead_unused_helper', nm_exe)
|
||||
|
||||
# Cross-compile & link for arm64-apple-ios15.0 with -Wl,-dead_strip to validate ld64 PIC relocations
|
||||
bc_ios = p / 'ibr_ios.bc'
|
||||
obf_ios = p / 'ibr_ios.obf.ll'
|
||||
obj_ios = p / 'ibr_ios.o'
|
||||
bin_ios = p / 'ibr_ios.bin'
|
||||
subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Os', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_ios)], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-S', '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
'--ig-pass-filter=all',
|
||||
'--ig-seed=ios_ibr_seed',
|
||||
f'--ig-source-path={src_c}',
|
||||
str(bc_ios), '-o', str(obf_ios),
|
||||
], check=True)
|
||||
delta_tables = [
|
||||
line for line in obf_ios.read_text(encoding='utf-8').splitlines()
|
||||
if line.startswith('@__ig_ibt1_')
|
||||
]
|
||||
self.assertTrue(delta_tables)
|
||||
for table in delta_tables:
|
||||
self.assertIn('i64 sub (', table)
|
||||
self.assertNotIn('i64 add (', table)
|
||||
subprocess.run([
|
||||
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Os',
|
||||
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
|
||||
'-x', 'ir', '-c', str(obf_ios), '-o', str(obj_ios),
|
||||
], check=True)
|
||||
subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Wl,-dead_strip', str(obj_ios), '-o', str(bin_ios)], check=True)
|
||||
dis_ios = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(bin_ios)], text=True)
|
||||
self.assertIsNotNone(re.search(r'\bbr\s+x\d+\b', dis_ios))
|
||||
|
||||
def test_objc_and_swift_async_throws_indirect_branch(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
swiftc = detect_stock_tool('swiftc')
|
||||
sdk_host = macos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-m3-ibr-mix-') as td:
|
||||
p = Path(td).resolve()
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'flatten_topology': 'sparse_switch',
|
||||
'flatten_targets': [{'path_contains': 'ibr_'}],
|
||||
'indirect_branch_targets': [{'path_contains': 'ibr_'}],
|
||||
}), encoding='utf-8')
|
||||
|
||||
objc_m = p / 'ibr_objc.m'
|
||||
objc_m.write_text(
|
||||
'''#import <Foundation/Foundation.h>
|
||||
@interface IBRBox : NSObject
|
||||
- (NSInteger)computeScore:(NSInteger)x flag:(BOOL)flag;
|
||||
@end
|
||||
@implementation IBRBox
|
||||
- (NSInteger)computeScore:(NSInteger)x flag:(BOOL)flag {
|
||||
NSInteger r = 5;
|
||||
if (flag) r += x * 3;
|
||||
else r -= x;
|
||||
if (r > 20) return r ^ 0x12;
|
||||
return r + 4;
|
||||
}
|
||||
@end
|
||||
int main(void) {
|
||||
@autoreleasepool {
|
||||
IBRBox *b = [[IBRBox alloc] init];
|
||||
return ([b computeScore:8 flag:YES] == (29 ^ 0x12) && [b computeScore:3 flag:NO] == 6) ? 0 : 1;
|
||||
}
|
||||
}
|
||||
''',
|
||||
encoding='utf-8',
|
||||
)
|
||||
bc_m = p / 'ibr_objc.bc'
|
||||
obf_m = p / 'ibr_objc.obf.bc'
|
||||
o_m = p / 'ibr_objc.o'
|
||||
exe_m = p / 'ibr_objc.exe'
|
||||
aud_m = p / 'aud_m.json'
|
||||
subprocess.run([clang, '-isysroot', sdk_host, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(objc_m), '-o', str(bc_m)], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full',
|
||||
'--ig-seed=m3_objc', f'--ig-source-path={objc_m}', f'--ig-audit-out={aud_m}',
|
||||
str(bc_m), '-o', str(obf_m),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes',
|
||||
'-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_m), '-o', str(o_m),
|
||||
], check=True)
|
||||
subprocess.run([clang, '-isysroot', sdk_host, '-framework', 'Foundation', '-Wl,-dead_strip', str(o_m), '-o', str(exe_m)], check=True)
|
||||
self.assertEqual(subprocess.run([str(exe_m)]).returncode, 0)
|
||||
aud_m_j = json.loads(aud_m.read_text(encoding='utf-8'))
|
||||
self.assertGreaterEqual(aud_m_j['indirect_branches_count'], 1)
|
||||
|
||||
sw_file = p / 'ibr_swift.swift'
|
||||
sw_file.write_text(
|
||||
'''import Foundation
|
||||
@inline(never)
|
||||
func swEval(_ a: Int) -> Int {
|
||||
var acc = a + 3
|
||||
if acc > 10 { acc ^= 0x1F }
|
||||
else { acc += 7 }
|
||||
if acc < 5 { return acc - 2 }
|
||||
return acc + 1
|
||||
}
|
||||
@main
|
||||
struct Runner {
|
||||
static func main() {
|
||||
let v = swEval(12) ^ swEval(1)
|
||||
if v != ((15 ^ 0x1F) + 1) ^ ((4 + 7) + 1) {
|
||||
exit(4)
|
||||
}
|
||||
}
|
||||
}
|
||||
''',
|
||||
encoding='utf-8',
|
||||
)
|
||||
bc_s = p / 'ibr_sw.bc'
|
||||
obf_s = p / 'ibr_sw.obf.bc'
|
||||
o_s = p / 'ibr_sw.o'
|
||||
exe_s = p / 'ibr_sw.exe'
|
||||
aud_s = p / 'aud_s.json'
|
||||
subprocess.run([swiftc, '-sdk', sdk_host, '-O', '-g', '-lto=llvm-thin', '-parse-as-library', '-c', str(sw_file), '-o', str(bc_s)], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-passes=default<O2>,ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full',
|
||||
'--ig-seed=m3_sw', f'--ig-source-path={sw_file}', f'--ig-audit-out={aud_s}',
|
||||
str(bc_s), '-o', str(obf_s),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes',
|
||||
'-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_s), '-o', str(o_s),
|
||||
], check=True)
|
||||
subprocess.run([swiftc, '-sdk', sdk_host, str(o_s), '-Xlinker', '-dead_strip', '-o', str(exe_s)], check=True)
|
||||
self.assertEqual(subprocess.run([str(exe_s)]).returncode, 0)
|
||||
aud_s_j = json.loads(aud_s.read_text(encoding='utf-8'))
|
||||
self.assertGreaterEqual(aud_s_j['indirect_branches_count'], 1)
|
||||
|
||||
def test_only_conditional_branches_and_dead_blocks_ios_codegen(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
sdk_ios = iphoneos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-m3-ibr-edge-') as td:
|
||||
p = Path(td)
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [],
|
||||
'indirect_branch_targets': [{'path_contains': 'ibr_edge.ll'}],
|
||||
}), encoding='utf-8')
|
||||
|
||||
ll_p = p / 'ibr_edge.ll'
|
||||
ll_p.write_text(
|
||||
'''target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128"
|
||||
target triple = "arm64-apple-ios15.0.0"
|
||||
|
||||
define i32 @only_cond_branches(i32 %x) {
|
||||
entry:
|
||||
%c1 = icmp sgt i32 %x, 0
|
||||
br i1 %c1, label %pos, label %neg
|
||||
pos:
|
||||
%c2 = icmp sgt i32 %x, 10
|
||||
br i1 %c2, label %big, label %small
|
||||
big:
|
||||
ret i32 100
|
||||
small:
|
||||
ret i32 10
|
||||
neg:
|
||||
ret i32 -1
|
||||
}
|
||||
|
||||
define i32 @dead_block_and_const_cond(i32 %x) {
|
||||
entry:
|
||||
br i1 true, label %live_branch, label %dead_arm
|
||||
live_branch:
|
||||
%c1 = icmp sgt i32 %x, 5
|
||||
br i1 %c1, label %gt, label %le
|
||||
gt:
|
||||
ret i32 1
|
||||
le:
|
||||
ret i32 2
|
||||
dead_arm:
|
||||
%c2 = icmp eq i32 %x, 99
|
||||
br i1 %c2, label %gt, label %dead_unr
|
||||
dead_unr:
|
||||
ret i32 -999
|
||||
}
|
||||
''',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
obf_ll = p / 'ibr_edge.obf.ll'
|
||||
obj_o = p / 'ibr_edge.o'
|
||||
aud_p = p / 'ibr_edge.audit.json'
|
||||
subprocess.run([
|
||||
opt_path, '-S', '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
'--ig-pass-filter=ibr',
|
||||
'--ig-seed=ibr_edge_1',
|
||||
f'--ig-source-path={ll_p}',
|
||||
f'--ig-audit-out={aud_p}',
|
||||
str(ll_p), '-o', str(obf_ll),
|
||||
], check=True)
|
||||
|
||||
ir_txt = obf_ll.read_text(encoding='utf-8')
|
||||
aud = json.loads(aud_p.read_text(encoding='utf-8'))
|
||||
self.assertGreaterEqual(aud['indirect_branches_count'], 3, aud)
|
||||
self.assertIn('only_cond_branches', aud['indirect_branches_functions'])
|
||||
self.assertIn('dead_block_and_const_cond', aud['indirect_branches_functions'])
|
||||
self.assertNotIn('ig.ibr.decoy', ir_txt)
|
||||
self.assertNotIn('blockaddress(@dead_block_and_const_cond, %dead_arm)', ir_txt)
|
||||
self.assertNotIn('blockaddress(@dead_block_and_const_cond, %dead_unr)', ir_txt)
|
||||
|
||||
res = subprocess.run([
|
||||
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios,
|
||||
'-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module',
|
||||
'-x', 'ir', '-c', str(obf_ll), '-o', str(obj_o),
|
||||
], capture_output=True, text=True)
|
||||
self.assertEqual(res.returncode, 0, res.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,530 @@
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf'
|
||||
sys.path.insert(0, str(TOOLS_LLVM_OBF))
|
||||
|
||||
from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402
|
||||
from verify_macho_indirect_calls import parse_macho_sections # noqa: E402
|
||||
|
||||
|
||||
def require_host_opt() -> str:
|
||||
tc = resolve_opt(require_obf=False)
|
||||
opt_path = tc.get('opt_path')
|
||||
if not opt_path:
|
||||
raise unittest.SkipTest(f"Standalone opt not built yet: {tc.get('warning')}")
|
||||
return opt_path
|
||||
|
||||
|
||||
def macos_sdk_path() -> str:
|
||||
return subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip()
|
||||
|
||||
|
||||
class TestIndirectCallPass(unittest.TestCase):
|
||||
def test_ios_linker_preserves_indirect_call_destinations(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
sdk = subprocess.check_output(
|
||||
['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True,
|
||||
).strip()
|
||||
target = ['-target', 'arm64-apple-ios15.0', '-isysroot', sdk]
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-icall-ios-link-') as td:
|
||||
p = Path(td)
|
||||
source = p / 'ios_call.c'
|
||||
source.write_text(
|
||||
'__attribute__((noinline)) int ios_add(int x) { return x + 7; }\n'
|
||||
'__attribute__((noinline)) int ios_sub(int x) { return x - 9; }\n'
|
||||
'int main(int argc, char **argv) { return ios_add(argc) + ios_sub(argc); }\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
bc = p / 'ios_call.bc'
|
||||
subprocess.run([
|
||||
clang, *target, '-O2', '-emit-llvm', '-c', str(source), '-o', str(bc),
|
||||
], check=True)
|
||||
for dual in (False, True):
|
||||
with self.subTest(dual=dual):
|
||||
policy = p / 'policy.json'
|
||||
policy.write_text(json.dumps({
|
||||
'indirect_call_targets': [{'path_contains': source.name}],
|
||||
'indirect_call_dual_table': dual,
|
||||
}), encoding='utf-8')
|
||||
obf = p / 'obf.bc'
|
||||
obj = p / 'obf.o'
|
||||
binary = p / 'app'
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy}',
|
||||
'--ig-mode=full', '--ig-pass-filter=icall',
|
||||
'--ig-seed=ios_call_relocation_regression',
|
||||
f'--ig-source-path={source}', str(bc), '-o', str(obf),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, *target, '-O2', '-Xclang', '-disable-llvm-passes',
|
||||
'-x', 'ir', '-c', str(obf), '-o', str(obj),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, *target, '-Wl,-dead_strip', str(obj), '-o', str(binary),
|
||||
], check=True)
|
||||
|
||||
nm = subprocess.check_output(['xcrun', 'nm', '-n', str(binary)], text=True)
|
||||
symbols = {}
|
||||
for line in nm.splitlines():
|
||||
fields = line.split()
|
||||
if len(fields) == 3:
|
||||
address, _, name = fields
|
||||
symbols[name] = int(address, 16)
|
||||
anchor, = [addr for name, addr in symbols.items() if name.startswith('___ig_ca_')]
|
||||
prefix = '___ig_cs1_' if dual else '___ig_ct_'
|
||||
table, = [addr for name, addr in symbols.items() if name.startswith(prefix)]
|
||||
section = next(
|
||||
section for name, section in parse_macho_sections(binary).items()
|
||||
if not name.endswith(',*')
|
||||
and section['addr'] <= table
|
||||
and table + 16 <= section['addr'] + section['size']
|
||||
)
|
||||
offset = section['offset'] + table - section['addr']
|
||||
deltas = struct.unpack_from('<2q', binary.read_bytes(), offset)
|
||||
self.assertCountEqual(
|
||||
[anchor + delta for delta in deltas],
|
||||
[symbols['_ios_add'], symbols['_ios_sub']],
|
||||
)
|
||||
|
||||
def test_c_same_tu_cross_tu_dead_strip_and_dylib_safety(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
sdk = macos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-icall-c-') as td:
|
||||
p = Path(td)
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [],
|
||||
'string_encrypt_targets': [{'path_contains': 'caller.c'}],
|
||||
'indirect_call_targets': [{'path_contains': 'caller.c'}],
|
||||
'indirect_call_same_image_prefixes': ['rd_ext_'],
|
||||
'flatten_targets': [{'path_contains': 'caller.c'}],
|
||||
}), encoding='utf-8')
|
||||
|
||||
(p / 'ext_callee.c').write_text(
|
||||
'int rd_ext_compute(int a, int b) {\n'
|
||||
' return (a * 3) + (b ^ 0x11);\n'
|
||||
'}\n'
|
||||
'int rd_ext_unused(int x) {\n'
|
||||
' return x * 999;\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
(p / 'caller.c').write_text(
|
||||
'#include <stdlib.h>\n'
|
||||
'#include <unistd.h>\n'
|
||||
'extern int rd_ext_compute(int a, int b);\n'
|
||||
'__attribute__((noinline)) static int local_step(int v) {\n'
|
||||
' return v + 19;\n'
|
||||
'}\n'
|
||||
'__attribute__((noinline)) int run_pipeline(int x) {\n'
|
||||
' const char *env = getenv("IG_NONEXISTENT_ENV_TEST");\n'
|
||||
' int pid_bit = (getpid() > 0) ? 1 : 0;\n'
|
||||
' int a = local_step(x + pid_bit);\n'
|
||||
' int b = rd_ext_compute(a, env ? 7 : 5);\n'
|
||||
' return local_step(b);\n'
|
||||
'}\n'
|
||||
'int main(void) {\n'
|
||||
' int got = run_pipeline(10);\n'
|
||||
' return (got == 129) ? 0 : 2;\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
# Verify expected math: pid_bit=1 -> a=local_step(11)=30 -> b=30*3+(5^0x11)=90+20=110 -> local_step(110)=129
|
||||
subprocess.run([clang, '-isysroot', sdk, '-O2', '-c', str(p / 'ext_callee.c'), '-o', str(p / 'ext.o')], check=True)
|
||||
subprocess.run([clang, '-isysroot', sdk, '-O2', '-g', '-emit-llvm', '-c', str(p / 'caller.c'), '-o', str(p / 'caller.bc')], check=True)
|
||||
|
||||
def build_with(seed: str, pass_filter: str, tag: str):
|
||||
obf_bc = p / f'caller_{tag}.bc'
|
||||
obj_o = p / f'caller_{tag}.o'
|
||||
audit_p = p / f'audit_{tag}.json'
|
||||
exe_p = p / f'exe_{tag}'
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
f'--ig-pass-filter={pass_filter}',
|
||||
f'--ig-seed={seed}',
|
||||
f'--ig-source-path={p / "caller.c"}',
|
||||
f'--ig-audit-out={audit_p}',
|
||||
str(p / 'caller.bc'), '-o', str(obf_bc),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk, '-O2',
|
||||
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
|
||||
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk, str(obj_o), str(p / 'ext.o'),
|
||||
'-Wl,-dead_strip', '-o', str(exe_p),
|
||||
], check=True)
|
||||
return obj_o, exe_p, json.loads(audit_p.read_text(encoding='utf-8'))
|
||||
|
||||
o_a1, exe_a1, aud_a1 = build_with('seed_alpha', 'all', 'a1')
|
||||
o_a2, _, aud_a2 = build_with('seed_alpha', 'all', 'a2')
|
||||
o_b1, exe_b1, aud_b1 = build_with('seed_beta', 'all', 'b1')
|
||||
_, exe_icall, aud_icall = build_with('seed_alpha', 'icall', 'icall_only')
|
||||
_, _, aud_str = build_with('seed_alpha', 'str', 'str_only')
|
||||
|
||||
# Determinism & polymorphism
|
||||
self.assertEqual(hashlib.sha256(o_a1.read_bytes()).hexdigest(), hashlib.sha256(o_a2.read_bytes()).hexdigest())
|
||||
self.assertNotEqual(hashlib.sha256(o_a1.read_bytes()).hexdigest(), hashlib.sha256(o_b1.read_bytes()).hexdigest())
|
||||
self.assertEqual(aud_a1['indirect_calls_count'], 4) # 2x local_step + 1x rd_ext_compute + 1x main->run_pipeline
|
||||
self.assertEqual(aud_a2['indirect_calls_count'], 4)
|
||||
self.assertEqual(aud_b1['indirect_calls_count'], 4)
|
||||
|
||||
# Pass filter isolation
|
||||
self.assertEqual(aud_icall['indirect_calls_count'], 4)
|
||||
self.assertEqual(aud_icall['strings_encrypted_count'], 0)
|
||||
self.assertEqual(len(aud_icall['functions_flattened']), 0)
|
||||
self.assertEqual(aud_str['indirect_calls_count'], 0)
|
||||
|
||||
# Runtime execution on host arm64
|
||||
for exe in (exe_a1, exe_b1, exe_icall):
|
||||
rc = subprocess.run([str(exe)]).returncode
|
||||
self.assertEqual(rc, 0)
|
||||
|
||||
# Disassembly & dead_strip checks
|
||||
nm_exe = subprocess.check_output(['xcrun', 'nm', str(exe_a1)], text=True)
|
||||
self.assertIn('_rd_ext_compute', nm_exe)
|
||||
self.assertNotIn('_rd_ext_unused', nm_exe) # dead_strip still strips unreferenced function
|
||||
|
||||
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(exe_a1)], text=True)
|
||||
self.assertIsNone(re.search(r'\bbl\s+.*_rd_ext_compute\b', dis))
|
||||
self.assertIsNone(re.search(r'\bbl\s+.*_local_step\b', dis))
|
||||
self.assertIsNone(re.search(r'\bbl\s+.*_run_pipeline\b', dis))
|
||||
self.assertIsNotNone(re.search(r'\bblr\s+x\d+\b', dis))
|
||||
|
||||
def test_objc_arc_attachedcall_rv_preservation(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
sdk = macos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-icall-arc-') as td:
|
||||
p = Path(td)
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'indirect_call_targets': [{'path_contains': 'arc_caller.m'}],
|
||||
'indirect_call_same_image_prefixes': ['rd_arc_'],
|
||||
'flatten_targets': [{'path_contains': 'arc_caller.m'}],
|
||||
}), encoding='utf-8')
|
||||
|
||||
(p / 'arc_provider.m').write_text(
|
||||
'#import <Foundation/Foundation.h>\n'
|
||||
'NSString *rd_arc_make_token(int idx) {\n'
|
||||
' return [NSString stringWithFormat:@"tok_%d_ok", idx ^ 0x2a];\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
(p / 'arc_caller.m').write_text(
|
||||
'#import <Foundation/Foundation.h>\n'
|
||||
'extern NSString *rd_arc_make_token(int idx);\n'
|
||||
'__attribute__((noinline)) static NSUInteger verify_batch(int n) {\n'
|
||||
' NSUInteger total = 0;\n'
|
||||
' for (int i = 0; i < n; ++i) {\n'
|
||||
' NSString *s = rd_arc_make_token(i);\n'
|
||||
' total += s.length;\n'
|
||||
' }\n'
|
||||
' return total;\n'
|
||||
'}\n'
|
||||
'int main(void) {\n'
|
||||
' @autoreleasepool {\n'
|
||||
' NSUInteger got = verify_batch(500);\n'
|
||||
' return (got > 3000) ? 0 : 3;\n'
|
||||
' }\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
subprocess.run([clang, '-isysroot', sdk, '-fobjc-arc', '-O2', '-c', str(p / 'arc_provider.m'), '-o', str(p / 'prov.o')], check=True)
|
||||
subprocess.run([clang, '-isysroot', sdk, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(p / 'arc_caller.m'), '-o', str(p / 'caller.bc')], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
'--ig-seed=arc_seed_1',
|
||||
f'--ig-source-path={p / "arc_caller.m"}',
|
||||
f'--ig-audit-out={p / "audit.json"}',
|
||||
str(p / 'caller.bc'), '-o', str(p / 'caller.obf.bc'),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk, '-O2',
|
||||
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
|
||||
'-x', 'ir', '-c', str(p / 'caller.obf.bc'), '-o', str(p / 'caller.o'),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk, '-framework', 'Foundation',
|
||||
str(p / 'caller.o'), str(p / 'prov.o'), '-Wl,-dead_strip', '-o', str(p / 'arc_exe'),
|
||||
], check=True)
|
||||
|
||||
audit = json.loads((p / 'audit.json').read_text(encoding='utf-8'))
|
||||
self.assertGreaterEqual(audit['indirect_calls_count'], 2)
|
||||
rc = subprocess.run([str(p / 'arc_exe')]).returncode
|
||||
self.assertEqual(rc, 0)
|
||||
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(p / 'arc_exe')], text=True)
|
||||
self.assertIsNone(re.search(r'\bbl\s+.*_rd_arc_make_token\b', dis))
|
||||
|
||||
def test_swift_cross_file_throws_and_extension_indirect_calls(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
swiftc = detect_stock_tool('swiftc')
|
||||
sdk = macos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-icall-swift-') as td:
|
||||
p = Path(td).resolve()
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'indirect_call_targets': [{'path_contains': '.swift'}],
|
||||
'flatten_targets': [{'path_contains': '.swift'}],
|
||||
}), encoding='utf-8')
|
||||
|
||||
(p / 'Callee.swift').write_text(
|
||||
'import Foundation\n'
|
||||
'enum DemoErr: Error { case bad }\n'
|
||||
'public struct KeyWorker {\n'
|
||||
' @inline(never)\n'
|
||||
' public static func derive(_ x: Int) throws -> Int {\n'
|
||||
' if x < 0 { throw DemoErr.bad }\n'
|
||||
' return (x * 7) ^ 0x33\n'
|
||||
' }\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
(p / 'ExtOnly.swift').write_text(
|
||||
'import Foundation\n'
|
||||
'extension NSString {\n'
|
||||
' @inline(never)\n'
|
||||
' func callModuleWorker(_ v: Int) -> Int {\n'
|
||||
' return ((try? KeyWorker.derive(v)) ?? -1) + self.length\n'
|
||||
' }\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
(p / 'Main.swift').write_text(
|
||||
'import Foundation\n'
|
||||
'@main\n'
|
||||
'struct Runner {\n'
|
||||
' static func main() {\n'
|
||||
' let s: NSString = "hello"\n'
|
||||
' let r1 = s.callModuleWorker(6)\n'
|
||||
' let r2 = (try? KeyWorker.derive(-3)) ?? 99\n'
|
||||
' if r1 != ((42 ^ 0x33) + 5) || r2 != 99 {\n'
|
||||
' exit(4)\n'
|
||||
' }\n'
|
||||
' }\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
# Compile multi-file Swift module with -lto=llvm-thin to produce per-file bitcode just like Xcode Release
|
||||
ofm = {
|
||||
str(p / 'Callee.swift'): {'object': str(p / 'Callee.bc')},
|
||||
str(p / 'ExtOnly.swift'): {'object': str(p / 'ExtOnly.bc')},
|
||||
str(p / 'Main.swift'): {'object': str(p / 'Main.bc')},
|
||||
}
|
||||
(p / 'ofm.json').write_text(json.dumps(ofm), encoding='utf-8')
|
||||
subprocess.run([
|
||||
swiftc, '-sdk', sdk, '-module-name', 'IcallDemoApp',
|
||||
'-O', '-whole-module-optimization', '-num-threads', '3',
|
||||
'-g', '-lto=llvm-thin', '-parse-as-library',
|
||||
'-output-file-map', str(p / 'ofm.json'),
|
||||
'-c', str(p / 'Callee.swift'), str(p / 'ExtOnly.swift'), str(p / 'Main.swift'),
|
||||
], cwd=p, check=True)
|
||||
|
||||
objs = []
|
||||
audits = {}
|
||||
for stem in ('Callee', 'ExtOnly', 'Main'):
|
||||
bc_p = p / f'{stem}.bc'
|
||||
obf_bc = p / f'{stem}.obf.bc'
|
||||
obj_o = p / f'{stem}.o'
|
||||
aud_p = p / f'{stem}.audit.json'
|
||||
subprocess.run([
|
||||
opt_path, '-passes=default<O2>,ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
'--ig-seed=swift_icall_seed',
|
||||
f'--ig-source-path={p / (stem + ".swift")}',
|
||||
'--ig-swift-module=IcallDemoApp',
|
||||
f'--ig-audit-out={aud_p}',
|
||||
str(bc_p), '-o', str(obf_bc),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk, '-O2',
|
||||
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
|
||||
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
|
||||
], check=True)
|
||||
objs.append(str(obj_o))
|
||||
audits[stem] = json.loads(aud_p.read_text(encoding='utf-8'))
|
||||
|
||||
subprocess.run([
|
||||
swiftc, '-sdk', sdk, *objs, '-Xlinker', '-dead_strip', '-o', str(p / 'swift_exe'),
|
||||
], check=True)
|
||||
|
||||
# Both ExtOnly.swift (extension-only file!) and Main.swift must indirect-call cross-file Swift targets
|
||||
self.assertGreaterEqual(audits['ExtOnly']['indirect_calls_count'], 1)
|
||||
self.assertGreaterEqual(audits['Main']['indirect_calls_count'], 2)
|
||||
|
||||
rc = subprocess.run([str(p / 'swift_exe')]).returncode
|
||||
self.assertEqual(rc, 0)
|
||||
|
||||
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(p / 'swift_exe')], text=True)
|
||||
self.assertIsNone(re.search(r'\bbl\s+.*KeyWorker.*derive', dis))
|
||||
self.assertIsNone(re.search(r'\bbl\s+.*callModuleWorker', dis))
|
||||
|
||||
def test_source_path_scrubbing_pass(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
sdk = macos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-scrub-') as td:
|
||||
p = Path(td)
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [],
|
||||
'scrub_path_substrings': ['/tmp/ig-ipa-work/', '/Users/shenlei/', '/src/readoor/'],
|
||||
'string_encrypt_targets': [{'path_contains': 'TargetFile.c'}],
|
||||
'indirect_call_targets': [],
|
||||
'flatten_targets': [],
|
||||
}), encoding='utf-8')
|
||||
|
||||
(p / 'TargetFile.c').write_text(
|
||||
'#include <stdio.h>\n'
|
||||
'const char *get_paths(int idx) {\n'
|
||||
' static const char *const kPaths[] = {\n'
|
||||
' "/tmp/ig-ipa-work/src/readoor/3.0/Secret.swift",\n'
|
||||
' "/Users/shenlei/Work/Secret.m",\n'
|
||||
' "./readoor/BookView/Reader.swift",\n'
|
||||
' "readoorApp/OnlyFile.swift",\n'
|
||||
' "KEEP_NON_PATH_TOKEN",\n'
|
||||
' };\n'
|
||||
' return kPaths[idx % 5];\n'
|
||||
'}\n'
|
||||
'int main(void) {\n'
|
||||
' puts(get_paths(0));\n'
|
||||
' puts(get_paths(3));\n'
|
||||
' puts(get_paths(4));\n'
|
||||
' return 0;\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
bc_p = p / 'TargetFile.bc'
|
||||
obf_bc = p / 'TargetFile.obf.bc'
|
||||
obj_o = p / 'TargetFile.o'
|
||||
audit_p = p / 'scrub.audit.json'
|
||||
subprocess.run([clang, '-isysroot', sdk, '-O2', '-emit-llvm', '-c', str(p / 'TargetFile.c'), '-o', str(bc_p)], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
'--ig-pass-filter=all',
|
||||
'--ig-seed=scrub_seed_1',
|
||||
'--ig-source-path=TargetFile.c',
|
||||
'--ig-swift-module=readoorApp',
|
||||
f'--ig-audit-out={audit_p}',
|
||||
str(bc_p), '-o', str(obf_bc),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk, '-O2', '-Xclang', '-disable-llvm-passes',
|
||||
'-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
|
||||
], check=True)
|
||||
|
||||
audit = json.loads(audit_p.read_text(encoding='utf-8'))
|
||||
self.assertGreaterEqual(audit.get('paths_scrubbed_count', 0), 4, audit)
|
||||
obj_raw = obj_o.read_bytes()
|
||||
for leaked in (b'/tmp/ig-ipa-work/', b'/Users/shenlei/', b'Secret.swift', b'OnlyFile.swift'):
|
||||
self.assertNotIn(leaked, obj_raw)
|
||||
self.assertIn(b'ig_p_', obj_raw)
|
||||
|
||||
def test_indirect_call_dual_table_mode(self):
|
||||
opt_path = require_host_opt()
|
||||
clang = detect_stock_tool('clang')
|
||||
sdk = macos_sdk_path()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-icall-dual-') as td:
|
||||
p = Path(td)
|
||||
policy_path = p / 'policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [],
|
||||
'indirect_call_targets': [{'path_contains': 'dual_icall.c'}],
|
||||
'indirect_call_same_image_prefixes': ['dt_'],
|
||||
'indirect_call_dual_table': True,
|
||||
}), encoding='utf-8')
|
||||
|
||||
src_c = p / 'dual_icall.c'
|
||||
src_c.write_text(
|
||||
'''#include <stdint.h>
|
||||
|
||||
__attribute__((noinline))
|
||||
int dt_helper_add(int a, int b) { return a + b + 3; }
|
||||
|
||||
__attribute__((noinline))
|
||||
int dt_helper_mul(int a, int b) { return a * b ^ 0x17; }
|
||||
|
||||
int main(void) {
|
||||
int x = dt_helper_add(5, 9);
|
||||
int y = dt_helper_mul(x, 4);
|
||||
if (x != 17 || y != (68 ^ 0x17)) return 1;
|
||||
return 0;
|
||||
}
|
||||
''',
|
||||
encoding='utf-8',
|
||||
)
|
||||
bc_p = p / 'dual_icall.bc'
|
||||
obf_ll = p / 'dual_icall.obf.ll'
|
||||
obj_o = p / 'dual_icall.o'
|
||||
exe_p = p / 'dual_icall_exe'
|
||||
audit_p = p / 'dual_icall.audit.json'
|
||||
|
||||
subprocess.run([clang, '-isysroot', sdk, '-O2', '-emit-llvm', '-c', str(src_c), '-o', str(bc_p)], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-S', '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
'--ig-mode=full',
|
||||
'--ig-seed=dual_table_seed_1',
|
||||
f'--ig-source-path={src_c}',
|
||||
f'--ig-audit-out={audit_p}',
|
||||
str(bc_p), '-o', str(obf_ll),
|
||||
], check=True)
|
||||
|
||||
ir_txt = obf_ll.read_text(encoding='utf-8')
|
||||
audit = json.loads(audit_p.read_text(encoding='utf-8'))
|
||||
self.assertTrue(audit.get('indirect_call_dual_table'), audit)
|
||||
self.assertGreaterEqual(audit.get('indirect_calls_count', 0), 2, audit)
|
||||
self.assertIn('__ig_cs1_', ir_txt)
|
||||
self.assertIn('__ig_cs2_', ir_txt)
|
||||
self.assertNotIn('__ig_ct_', ir_txt)
|
||||
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk, '-O2', '-Xclang', '-disable-llvm-passes',
|
||||
'-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_ll), '-o', str(obj_o),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
clang, '-isysroot', sdk, str(obj_o), '-Wl,-dead_strip', '-o', str(exe_p),
|
||||
], check=True)
|
||||
|
||||
rc = subprocess.run([str(exe_p)]).returncode
|
||||
self.assertEqual(rc, 0)
|
||||
|
||||
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(exe_p)], text=True)
|
||||
self.assertIsNone(re.search(r'\bbl\s+.*dt_helper_add', dis), dis)
|
||||
self.assertIsNone(re.search(r'\bbl\s+.*dt_helper_mul', dis), dis)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Exercise legacy lazy binding on the reviewed AliyunPlayer arm64 SDK."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tools/macho_guard'))
|
||||
from batch import arm64_slices, Slice
|
||||
from redirect_legacy_fopen import rewrite
|
||||
from machox import Macho
|
||||
|
||||
IPA = ROOT / 'appstore.ipa'
|
||||
|
||||
|
||||
@unittest.skipUnless(IPA.exists(), '需要归档 IPA 中的 AliyunPlayer')
|
||||
class LegacyFopenTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
with zipfile.ZipFile(IPA) as archive:
|
||||
names = [n for n in archive.namelist() if n.endswith('/AliyunPlayer.framework/AliyunPlayer')]
|
||||
if len(names) != 1:
|
||||
raise ValueError('需要唯一 AliyunPlayer')
|
||||
data = archive.read(names[0])
|
||||
offset, size = arm64_slices(data)[0]
|
||||
cls.data = data[offset:offset + size]
|
||||
|
||||
def apply(self, data):
|
||||
return rewrite(data, hashlib.sha256(data).hexdigest())
|
||||
|
||||
def test_real_lazy_binding(self):
|
||||
result, report = self.apply(self.data)
|
||||
self.assertTrue(report['lazy_offsets_preserved'])
|
||||
self.assertTrue(report['section_bytes_unchanged'])
|
||||
self.assertEqual(Slice(self.data, 0).scan()['_fopen'], 28)
|
||||
self.assertEqual(Slice(result, 0).scan()['_fopen'], 0)
|
||||
self.assertEqual(len(result), len(self.data))
|
||||
before = Macho(self.data)
|
||||
after = Macho(result)
|
||||
old = next(o for c, _, o in before.cmds if c == 0x80000022)
|
||||
new = next(o for c, _, o in after.cmds if c == 0x80000022)
|
||||
self.assertEqual(self.data[old + 8:old + 48], result[new + 8:new + 48])
|
||||
self.assertEqual(report['new_ordinal'], 33)
|
||||
|
||||
def test_hash_mismatch(self):
|
||||
with self.assertRaises(ValueError):
|
||||
rewrite(self.data, '0' * 64)
|
||||
|
||||
def test_repeat_rejected(self):
|
||||
result, _ = self.apply(self.data)
|
||||
with self.assertRaises(ValueError):
|
||||
self.apply(result)
|
||||
|
||||
def test_no_header_space(self):
|
||||
data = bytearray(self.data)
|
||||
data[32 + Macho(data).sizeofcmds] = 1
|
||||
with self.assertRaises(ValueError):
|
||||
self.apply(bytes(data))
|
||||
|
||||
def test_wrong_lazy_provider(self):
|
||||
data = bytearray(self.data)
|
||||
m = Macho(data)
|
||||
off = next(o for c, _, o in m.cmds if c == 0x80000022)
|
||||
lazy, size = struct.unpack_from('<II', data, off + 32)
|
||||
symbol = data.index(b'_fopen\0', lazy, lazy + size)
|
||||
self.assertEqual(data[symbol - 3:symbol], b'\x20\x20\x40')
|
||||
data[symbol - 2] = 1
|
||||
with self.assertRaises(ValueError):
|
||||
self.apply(bytes(data))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user