From 704ee668346372cdc52bd25f9d0ba84d7eb439f1 Mon Sep 17 00:00:00 2001 From: shenlei Date: Tue, 24 Nov 2026 15:00:07 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=9B=86=E6=88=90=20LLVM=20IR=20?= =?UTF-8?q?=E6=B7=B7=E6=B7=86=E4=BD=93=E7=B3=BB=E3=80=81Route=202=20?= =?UTF-8?q?=E5=85=A8=E9=87=8F=E5=90=88=E8=A7=84=E4=B8=8E=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E8=B0=83=E5=BA=A6=E5=8A=A0=E5=9B=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - defender: 扩展 IGDispatch/IGArchiveGuard/IGAntiHook/IGObjCBaseline/IGResolve,支持 Route 2 静态库桥接 (IGThreadID.c) 与防重签名检测 - llvm_passes: 新增 IGObfuscator LLVM IR 插件源码(控制流平坦化、字符串加密、间接跳转/调用、不透明常量/字段、MBA、函数外提、基本块拆分、反 Hook 序言) - tools & config: 新增 Xcode 归档编译/链接包装器、LLVM 自愈工具链 (ig_toolchain_resolver)、IPA 审计门禁、崩溃符号还原及最新 ig_llvm_policy.json(文件级匹配 + 3.0 全业务 Handler 平坦化) - tests & docs: 补齐 M0~M3、Pass 单测及系统调用调度/Route 2/LLVM 方案文档;.gitignore 忽略 *.bc 与 .obfuscate_extraction_cache.json --- .gitignore | 2 + THIRD_PARTY_NOTICES.md | 14 + config/ig_diag_events.json | 144 ++ config/ig_llvm_policy.json | 857 ++++++++++ config/ig_llvm_policy_m1_group_b.json | 121 ++ config/toolchain_manifest.json | 18 + config/xcode_llvm_map.json | 10 + defender/anti_debug/IGAntiDebug.c | 8 +- defender/anti_frida/IGAntiInject.c | 52 +- defender/anti_hook/IGAntiHook.c | 402 ++++- defender/anti_hook/IGAntiHook.h | 7 +- defender/anti_hook/IGObjCBaseline.c | 235 ++- defender/anti_hook/IGObjCBaseline.h | 15 +- defender/anti_jailbreak/IGAntiJailbreak.c | 18 +- defender/anti_tamper/IGAntiTamper.c | 30 +- defender/call_bridge/IGThreadID.c | 22 + defender/dispatch/IGArchiveGuard.c | 427 ++++- defender/dispatch/IGArchiveGuard.h | 63 +- defender/dispatch/IGDispatch.c | 158 +- defender/dispatch/IGDispatch.h | 20 +- defender/include/IGDefender.h | 8 + defender/resolve/IGResolve.c | 223 ++- defender/resolve/IGResolve.h | 22 +- docs/18_READOOR_DEFENDER_INTEGRATION.md | 11 + docs/20_SYSTEM_CALL_DISPATCH_EXPANSION.md | 215 +++ docs/21_GCD_FILE_DISPATCH_INTEGRATION.md | 58 + docs/22_ROUTE2_COMPLETE_REMEDIATION.md | 121 ++ docs/23_LLVM_IR_OBFUSCATION_PLAN.md | 261 +++ ..._SHORT_LIVED_CREDENTIALS_AND_APP_ATTEST.md | 152 ++ llvm_passes/CMakeLists.txt | 19 + llvm_passes/include/IGPassUtils.h | 142 ++ llvm_passes/include/IGPolicyConfig.h | 314 ++++ llvm_passes/src/IGAntiHooking.cpp | 76 + llvm_passes/src/IGArithmetic.cpp | 299 ++++ llvm_passes/src/IGBasicBlockSplit.cpp | 175 ++ llvm_passes/src/IGFlattening.cpp | 832 ++++++++++ llvm_passes/src/IGFunctionOutline.cpp | 232 +++ llvm_passes/src/IGIndirectBranch.cpp | 280 ++++ llvm_passes/src/IGIndirectCall.cpp | 501 ++++++ llvm_passes/src/IGOpaqueConstants.cpp | 348 ++++ llvm_passes/src/IGOpaqueFieldAccess.cpp | 297 ++++ llvm_passes/src/IGPluginMain.cpp | 94 ++ llvm_passes/src/IGPolicyConfig.cpp | 805 +++++++++ llvm_passes/src/IGStringEncryption.cpp | 983 +++++++++++ tests/fixtures/archive_binding_host.c | 6 +- tests/fixtures/defender_host.c | 23 +- tests/fixtures/dispatch_host.c | 94 +- tests/fixtures/gcd_file_integration.m | 106 ++ tests/test_anti_hooking_pass.py | 315 ++++ tests/test_archive_guard.py | 17 +- tests/test_dispatch.py | 12 + tests/test_gcd_file_integration.py | 82 + tests/test_indirect_branch_pass.py | 398 +++++ tests/test_indirect_call_pass.py | 460 ++++++ tests/test_legacy_fopen.py | 75 + tests/test_llvm_obf_m0.py | 415 +++++ tests/test_llvm_obf_m1.py | 234 +++ tests/test_llvm_obf_m2.py | 251 +++ tests/test_llvm_obf_m3.py | 1077 ++++++++++++ tests/test_m9_nonlinear_and_bbsplit_pass.py | 366 +++++ tests/test_mba_and_opaque_const_pass.py | 248 +++ tests/test_network_and_keybox_hardening.py | 716 ++++++++ tests/test_objc_swift_string_encryption.py | 355 ++++ tests/test_opaque_field_and_outline_pass.py | 248 +++ tests/test_route2_dispatch.py | 361 ++++ tests/test_security_policy.py | 246 +++ tests/test_static_framework_obf.py | 205 +++ tests/test_static_hardening.py | 69 + tests/test_toolchain_self_heal.py | 286 ++++ .../prepare_observation_app.py | 15 +- tools/crash_restore/restore_crash_report.py | 280 ++++ tools/llvm_obf/build_igopt_local.py | 319 ++++ tools/llvm_obf/build_obfuscated_ipa.py | 1118 +++++++++++++ tools/llvm_obf/ig_toolchain_resolver.py | 1385 ++++++++++++++++ tools/llvm_obf/run_m0_readoor_matrix.py | 493 ++++++ tools/llvm_obf/run_m1_epub_eval.py | 620 +++++++ tools/llvm_obf/run_m2_security_eval.py | 648 ++++++++ tools/llvm_obf/run_m3_full_regression.py | 896 ++++++++++ tools/llvm_obf/verify_m0_async_device.py | 543 ++++++ .../verify_macho_indirect_branches.py | 119 ++ tools/llvm_obf/verify_macho_indirect_calls.py | 470 ++++++ tools/llvm_obf/verify_macho_star_cfg.py | 266 +++ tools/macho_guard/attribute_callsites.py | 65 + tools/macho_guard/build_hook_device.py | 2 +- tools/macho_guard/link_with_sdk_inputs.py | 86 + tools/macho_guard/package_route2_app.py | 326 ++++ tools/macho_guard/profiles/alipay_fopen.json | 10 + .../profiles/main_residual_dispatch.json | 70 + .../macho_guard/redirect_framework_imports.py | 84 +- tools/macho_guard/redirect_legacy_fopen.py | 168 ++ tools/macho_guard/redirect_legacy_imports.py | 327 ++++ .../verify_gcd_file_integration.py | 87 + .../verify_redirected_archive_calls.py | 70 + .../mappings/full_dispatch.json | 13 + .../mappings/protected_fopen.json | 1 + .../mappings/zipzap_dispatch.json | 5 + .../prepare_route2_sdks.py | 231 +++ .../prepare_thread_id_sdks.py | 113 ++ .../redirect_bitcode_members.py | 128 ++ tools/static_sdk_redirect/redirect_symbols.py | 16 +- tools/xcode_archive/audit_exported_ipa.py | 484 ++++++ tools/xcode_archive/ig_cc_wrapper.py | 413 +++++ tools/xcode_archive/ig_cxx_wrapper.py | 12 + .../ig_guard_frameworks_phase.py | 599 +++++++ tools/xcode_archive/ig_ld_wrapper.py | 1452 +++++++++++++++++ tools/xcode_archive/route2_archive_common.py | 83 + 106 files changed, 27487 insertions(+), 286 deletions(-) create mode 100644 THIRD_PARTY_NOTICES.md create mode 100644 config/ig_diag_events.json create mode 100644 config/ig_llvm_policy.json create mode 100644 config/ig_llvm_policy_m1_group_b.json create mode 100644 config/toolchain_manifest.json create mode 100644 config/xcode_llvm_map.json create mode 100644 defender/call_bridge/IGThreadID.c create mode 100644 docs/20_SYSTEM_CALL_DISPATCH_EXPANSION.md create mode 100644 docs/21_GCD_FILE_DISPATCH_INTEGRATION.md create mode 100644 docs/22_ROUTE2_COMPLETE_REMEDIATION.md create mode 100644 docs/23_LLVM_IR_OBFUSCATION_PLAN.md create mode 100644 docs/24_SERVER_SHORT_LIVED_CREDENTIALS_AND_APP_ATTEST.md create mode 100644 llvm_passes/CMakeLists.txt create mode 100644 llvm_passes/include/IGPassUtils.h create mode 100644 llvm_passes/include/IGPolicyConfig.h create mode 100644 llvm_passes/src/IGAntiHooking.cpp create mode 100644 llvm_passes/src/IGArithmetic.cpp create mode 100644 llvm_passes/src/IGBasicBlockSplit.cpp create mode 100644 llvm_passes/src/IGFlattening.cpp create mode 100644 llvm_passes/src/IGFunctionOutline.cpp create mode 100644 llvm_passes/src/IGIndirectBranch.cpp create mode 100644 llvm_passes/src/IGIndirectCall.cpp create mode 100644 llvm_passes/src/IGOpaqueConstants.cpp create mode 100644 llvm_passes/src/IGOpaqueFieldAccess.cpp create mode 100644 llvm_passes/src/IGPluginMain.cpp create mode 100644 llvm_passes/src/IGPolicyConfig.cpp create mode 100644 llvm_passes/src/IGStringEncryption.cpp create mode 100644 tests/fixtures/gcd_file_integration.m create mode 100644 tests/test_anti_hooking_pass.py create mode 100644 tests/test_gcd_file_integration.py create mode 100644 tests/test_indirect_branch_pass.py create mode 100644 tests/test_indirect_call_pass.py create mode 100644 tests/test_legacy_fopen.py create mode 100644 tests/test_llvm_obf_m0.py create mode 100644 tests/test_llvm_obf_m1.py create mode 100644 tests/test_llvm_obf_m2.py create mode 100644 tests/test_llvm_obf_m3.py create mode 100644 tests/test_m9_nonlinear_and_bbsplit_pass.py create mode 100644 tests/test_mba_and_opaque_const_pass.py create mode 100644 tests/test_network_and_keybox_hardening.py create mode 100644 tests/test_objc_swift_string_encryption.py create mode 100644 tests/test_opaque_field_and_outline_pass.py create mode 100644 tests/test_route2_dispatch.py create mode 100644 tests/test_static_framework_obf.py create mode 100644 tests/test_toolchain_self_heal.py create mode 100755 tools/crash_restore/restore_crash_report.py create mode 100755 tools/llvm_obf/build_igopt_local.py create mode 100644 tools/llvm_obf/build_obfuscated_ipa.py create mode 100755 tools/llvm_obf/ig_toolchain_resolver.py create mode 100755 tools/llvm_obf/run_m0_readoor_matrix.py create mode 100644 tools/llvm_obf/run_m1_epub_eval.py create mode 100644 tools/llvm_obf/run_m2_security_eval.py create mode 100755 tools/llvm_obf/run_m3_full_regression.py create mode 100755 tools/llvm_obf/verify_m0_async_device.py create mode 100644 tools/llvm_obf/verify_macho_indirect_branches.py create mode 100644 tools/llvm_obf/verify_macho_indirect_calls.py create mode 100644 tools/llvm_obf/verify_macho_star_cfg.py create mode 100644 tools/macho_guard/attribute_callsites.py create mode 100644 tools/macho_guard/link_with_sdk_inputs.py create mode 100644 tools/macho_guard/package_route2_app.py create mode 100644 tools/macho_guard/profiles/alipay_fopen.json create mode 100644 tools/macho_guard/profiles/main_residual_dispatch.json create mode 100644 tools/macho_guard/redirect_legacy_fopen.py create mode 100644 tools/macho_guard/redirect_legacy_imports.py create mode 100644 tools/macho_guard/verify_gcd_file_integration.py create mode 100644 tools/macho_guard/verify_redirected_archive_calls.py create mode 100644 tools/static_sdk_redirect/mappings/full_dispatch.json create mode 100644 tools/static_sdk_redirect/mappings/protected_fopen.json create mode 100644 tools/static_sdk_redirect/mappings/zipzap_dispatch.json create mode 100644 tools/static_sdk_redirect/prepare_route2_sdks.py create mode 100644 tools/static_sdk_redirect/prepare_thread_id_sdks.py create mode 100644 tools/static_sdk_redirect/redirect_bitcode_members.py create mode 100755 tools/xcode_archive/audit_exported_ipa.py create mode 100755 tools/xcode_archive/ig_cc_wrapper.py create mode 100755 tools/xcode_archive/ig_cxx_wrapper.py create mode 100755 tools/xcode_archive/ig_guard_frameworks_phase.py create mode 100755 tools/xcode_archive/ig_ld_wrapper.py create mode 100644 tools/xcode_archive/route2_archive_common.py diff --git a/.gitignore b/.gitignore index cdd9e22..2dffcd7 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ dist/ DerivedData/ *.o *.obj +*.bc *.dylib *.a *.framework @@ -42,6 +43,7 @@ project.xcworkspace/xcuserdata/ *.log *.tmp *.cache +.obfuscate_extraction_cache.json __pycache__/ *.py[cod] diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..f9b8a89 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -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. diff --git a/config/ig_diag_events.json b/config/ig_diag_events.json new file mode 100644 index 0000000..c3fdf1e --- /dev/null +++ b/config/ig_diag_events.json @@ -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" + } +} diff --git a/config/ig_llvm_policy.json b/config/ig_llvm_policy.json new file mode 100644 index 0000000..c611270 --- /dev/null +++ b/config/ig_llvm_policy.json @@ -0,0 +1,857 @@ +{ + "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_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/" } + ], + "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 + } + ] +} diff --git a/config/ig_llvm_policy_m1_group_b.json b/config/ig_llvm_policy_m1_group_b.json new file mode 100644 index 0000000..ecf4cd3 --- /dev/null +++ b/config/ig_llvm_policy_m1_group_b.json @@ -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 + } + ] +} diff --git a/config/toolchain_manifest.json b/config/toolchain_manifest.json new file mode 100644 index 0000000..bc9a440 --- /dev/null +++ b/config/toolchain_manifest.json @@ -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" + } + } +} diff --git a/config/xcode_llvm_map.json b/config/xcode_llvm_map.json new file mode 100644 index 0000000..f940eb8 --- /dev/null +++ b/config/xcode_llvm_map.json @@ -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" + } +} diff --git a/defender/anti_debug/IGAntiDebug.c b/defender/anti_debug/IGAntiDebug.c index 5f7e515..ae6e035 100644 --- a/defender/anti_debug/IGAntiDebug.c +++ b/defender/anti_debug/IGAntiDebug.c @@ -6,7 +6,9 @@ #include "IGAntiDebug.h" #include "syscall/IGSyscall.h" -#include +#if IG_DIAGNOSTIC_STRINGS +# include +#endif int ig_anti_debug_check(IGFindingSink sink, void *ctx) { int traced = ig_sys_is_debugged(); @@ -15,8 +17,10 @@ int ig_anti_debug_check(IGFindingSink sink, void *ctx) { __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; } @@ -25,8 +29,10 @@ int ig_anti_debug_check(IGFindingSink sink, void *ctx) { __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; diff --git a/defender/anti_frida/IGAntiInject.c b/defender/anti_frida/IGAntiInject.c index e7b2a74..cec1728 100644 --- a/defender/anti_frida/IGAntiInject.c +++ b/defender/anti_frida/IGAntiInject.c @@ -11,9 +11,12 @@ */ #include "IGAntiInject.h" #include "IGInline.h" /* ig_strstr/ig_strcmp/ig_strncmp/ig_strlen:抹除探针自身对 libc 匹配函数的依赖 */ +#include "../dispatch/IGDispatch.h" #include -#include +#if IG_DIAGNOSTIC_STRINGS +# include +#endif #include #include #include @@ -68,6 +71,12 @@ static size_t ig_inj_decode(const unsigned char *enc, size_t n, int idx, 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; @@ -75,8 +84,13 @@ static void ig_emit2(IGFindingSink sink, void *ctx, int *stop, int *hits, 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; } @@ -124,9 +138,13 @@ int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx) 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; } @@ -136,12 +154,21 @@ int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx) /* 非系统、非特征命中:若在 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, - "Bundle 外非系统镜像(弱信号,需结合其它证据)"); + IG_DIAG_STR("Bundle 外非系统镜像(弱信号,需结合其它证据)")); } } - /* 3. DYLD_INSERT_LIBRARIES 逐条解析。 */ - const char *dyld = ig_local_getenv("DYLD_INSERT_LIBRARIES"); + /* 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'; @@ -153,9 +180,13 @@ int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx) * /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 } } } @@ -169,7 +200,7 @@ static void ig_scan_threads(IGFindingSink sink, void *ctx, int *stop, int *hits) 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, - "task_threads", "无法枚举线程"); + IG_DIAG_STR("task_threads"), IG_DIAG_STR("无法枚举线程")); return; } /* §7.1:frida 线程名运行期解码进栈,比对后擦除。 */ @@ -185,10 +216,15 @@ static void ig_scan_threads(IGFindingSink sink, void *ctx, int *stop, int *hits) 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; } } @@ -225,7 +261,7 @@ static int ig_port_open(int port) { open = (err == 0); } } - close(fd); + IG_dispatch_close(fd); return open; } @@ -234,10 +270,14 @@ int ig_anti_frida_check(int probe_port, IGFindingSink sink, void *ctx) { 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; diff --git a/defender/anti_hook/IGAntiHook.c b/defender/anti_hook/IGAntiHook.c index b9bfc6e..219dba3 100644 --- a/defender/anti_hook/IGAntiHook.c +++ b/defender/anti_hook/IGAntiHook.c @@ -1,27 +1,33 @@ /* * IGAntiHook.c — 关键函数 HOOK 完整性探针实现。 * - * 全部基于公开 API:(dlsym/dladdr)、(镜像枚举)、 - * /(运行时解析自身镜像的 GOT 槽,fishhook 同款走法,用于「校验」而非改写)。 + * 全部基于公开 API:(dladdr)、(镜像枚举)、 + * /(运行时解析自身镜像的 GOT 槽)、 + * (vm_read_overwrite 读自身进程只读代码页)。 + * + * 覆盖: + * 1. 符号提供方归属(provenance):Export Trie 解析地址须落入系统镜像路径。 + * 2. inline hook(32 字节指令窗 + 启动期基线快照):首指令 B、全通用寄存器 x0~x30 的 + * LDR Xt/BR Xt、ADRP+ADD+BR、MOVK+BR 蹦床,以及相对 constructor 基线前 32 字节变化。 + * 3. GOT 重绑定:扫本进程非系统镜像的非惰性 __got/__auth_got 符号指针槽。 * * 边界(如实声明,unavailable 不等于安全): * - 仅支持 arm64 / x86_64(LP64)。非 64 位镜像跳过。 - * - arm64e:__auth_got 槽为带签名指针,比较前用 ptrauth_strip 去签名;若工具链无 ptrauth, - * 对认证槽的判定标记为 unavailable,不强行比较。 - * - chained fixups:运行时 dyld 绑定完成后,__got 槽持最终(slide 后)地址,本探针读到的即该值; - * 未绑定/惰性未触发的槽会与 trusted 不等——仅对非惰性 __got(S_NON_LAZY_SYMBOL_POINTERS)判 rebind, - * 惰性槽(__la_symbol_ptr)首次调用前可能仍指向 helper,故不判为重绑定,只在 provenance/inline 层兜底。 + * - arm64e:__auth_got 槽为带签名指针,比较前用 ptrauth_strip 去签名。 */ #include "IGAntiHook.h" -#include "IGInline.h" /* ig_strcmp/ig_strncmp/ig_strlen:抹除探针自身对 libc 匹配函数的依赖 */ +#include "IGInline.h" +#include "../resolve/IGResolve.h" -#include -#include +#if IG_DIAGNOSTIC_STRINGS +# include +#endif #include #include #include #include #include +#include #if defined(__has_feature) # if __has_feature(ptrauth_calls) @@ -33,42 +39,168 @@ # define IG_HAS_PTRAUTH 0 #endif -/* 报告命中的 12 个关键符号(不带下划线)。 */ -static const char *const kIGDefaultSymbols[] = { - "fopen", "dlopen", "dlsym", "write", "read", "open", - "close", "exit", "fork", "syscall", "unlink", "getpid", +#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'; +} + /* ---- 工具:系统提供方路径白名单 ---- */ -/* dli_fname 是否落在系统镜像路径(含 dyld 共享缓存里的系统 dylib)。 */ static int ig_is_system_path(const char *path) { if (!path) return 0; static const char *const prefixes[] = { "/usr/lib/", "/System/", "/usr/lib/system/", - /* iOS 16+ 系统库经 Cryptex 挂载,dladdr 报此前缀(非越狱,系统自身)。 */ "/private/preboot/Cryptexes/", }; - for (size_t i = 0; i < sizeof(prefixes)/sizeof(prefixes[0]); ++i) { + 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; - memset(&f, 0, sizeof(f)); + ig_memset(&f, 0, sizeof(f)); f.status = st; f.reason = reason; - if (subject) { strncpy(f.subject, subject, sizeof(f.subject)-1); } - if (evidence) { strncpy(f.evidence, evidence, sizeof(f.evidence)-1); } +#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; } -/* 去 PAC(arm64e 认证指针);无 ptrauth 时原样返回。 */ static const void *ig_strip(const void *p) { #if IG_HAS_PTRAUTH return ptrauth_strip(p, ptrauth_key_asia); @@ -77,59 +209,177 @@ static const void *ig_strip(const void *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) { + if ((first & 0xfc000000u) == 0x14000000u) return 1; + 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 ((ins[0] & 0xfc000000u) == 0x14000000u) return 1; + 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; +} + +static size_t ig_read_code_window(const void *addr, uint32_t words[IG_HOOK_PREFIX_WORDS]) { + vm_size_t copied = 0; + vm_address_t target = (vm_address_t)ig_strip(addr); + if (vm_read_overwrite(mach_task_self(), target, IG_HOOK_PREFIX_BYTES, + (vm_address_t)words, &copied) == KERN_SUCCESS && + copied == IG_HOOK_PREFIX_BYTES) { + return IG_HOOK_PREFIX_WORDS; + } + copied = 0; + if (vm_read_overwrite(mach_task_self(), target, 2u * sizeof(uint32_t), + (vm_address_t)words, &copied) == KERN_SUCCESS && + copied == 2u * sizeof(uint32_t)) { + return 2u; + } + return 0u; +} + +/* ---- 启动期 32 字节基线快照 ---- */ + +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 nwords = ig_read_code_window(addr, words); + if (nwords < 2u || ig_arm64_suspicious_window(words, nwords)) continue; + IGHookBaselineSlot *slot = &g_hook_baselines[g_hook_baseline_count++]; + slot->addr = ig_strip(addr); + slot->len = nwords * sizeof(uint32_t); + 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. 符号提供方 ---- */ -/* trusted = dlsym(RTLD_DEFAULT,name);其宿主镜像若非系统路径,说明被 interpose/注入抢占。 */ + static void *ig_check_provenance(const char *name, IGFindingSink sink, void *ctx, int *stop, int *hits) { - void *addr = dlsym(RTLD_DEFAULT, name); + void *addr = ig_resolve_export_default(name); if (!addr) { ig_emit(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_SYMBOL_UNRESOLVED, - name, "dlsym(RTLD_DEFAULT) 返回 NULL"); + 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, "无法确认符号提供方"); + 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; } -/* ---- 2. inline hook:序言首指令 ---- */ -int ig_arm64_suspicious_prologue(uint32_t first, uint32_t second) { - if ((first & 0xfc000000u)==0x14000000u) return 1; - uint32_t rt=first & 31u, rn=(second>>5)&31u; - return (first & 0xff000000u)==0x58000000u && (rt==16 || rt==17) - && (second & 0xfffffc1fu)==0xd61f0000u && rn==rt; -} -/* arm64:首指令为无条件 B,或 (LDR-literal → x16/x17) + (BR x16/x17) 蹦床,判为 inline hook。 */ static IGStatus ig_check_prologue(const char *name, void *addr, IGFindingSink sink, void *ctx, - int *stop, int *hits) { + int *stop, int *hits) { #if defined(__arm64__) || defined(__aarch64__) - uint32_t code[2]; - vm_size_t copied=0; - if (vm_read_overwrite(mach_task_self(), (vm_address_t)ig_strip(addr), - sizeof(code), (vm_address_t)code, &copied) != KERN_SUCCESS || copied!=sizeof(code)) { + uint32_t code[IG_HOOK_PREFIX_WORDS]; + size_t nwords = ig_read_code_window(addr, code); + if (nwords < 2u) { ig_emit(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_VERIFICATION_UNAVAILABLE, - name, "无法读取函数代码"); + name, IG_DIAG_STR("无法读取函数代码")); return IG_UNAVAILABLE; } - const uint32_t *ins = code; - uint32_t w0 = ins[0]; - uint32_t w1 = ins[1]; - int hook = ig_arm64_suspicious_prologue(w0,w1); - const char *kind = "首指令 B 或 LDR literal + 同寄存器 BR 蹦床"; - if (hook) { + if (ig_arm64_suspicious_window(code, nwords)) { +#if IG_DIAGNOSTIC_STRINGS char ev[256]; - snprintf(ev, sizeof(ev), "%s @%p 指令[%08x %08x]", kind, addr, w0, w1); + snprintf(ev, sizeof(ev), "指令窗命中跳转蹦床 @%p [%08x %08x]", addr, code[0], code[1]); 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; + } + const IGHookBaselineSlot *base = ig_find_baseline(addr); + if (base && nwords * sizeof(uint32_t) >= base->len && + ig_memcmp(code, base->prefix, base->len) != 0) { +#if IG_DIAGNOSTIC_STRINGS + char ev[256]; + snprintf(ev, sizeof(ev), "前%zu字节偏离启动基线 @%p [%08x %08x]", + base->len, addr, code[0], code[1]); + 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 @@ -139,8 +389,7 @@ static IGStatus ig_check_prologue(const char *name, void *addr, IGFindingSink si } /* ---- 3. GOT 重绑定:扫本进程非系统镜像的非惰性符号指针槽 ---- */ -/* trusted_map:name→trusted addr 的平行数组。对每个镜像的 __got 槽,若其绑定符号在集合内 - * 且当前值去 PAC 后既不等于 trusted、宿主又非系统路径,则判 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) { @@ -148,10 +397,9 @@ static void ig_check_got_one_image(uint32_t img_index, (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; /* 只查自有镜像(app/嵌入 framework) */ + if (ig_is_system_path(img_path)) return; intptr_t slide = _dyld_get_image_vmaddr_slide(img_index); - /* 先定位 __LINKEDIT、LC_SYMTAB、LC_DYSYMTAB。 */ const struct segment_command_64 *linkedit = NULL; const struct symtab_command *symtab = NULL; const struct dysymtab_command *dysymtab = NULL; @@ -175,7 +423,6 @@ static void ig_check_got_one_image(uint32_t img_index, const char *strtab = (const char *)(linkedit_base + symtab->stroff); const uint32_t *indirect = (const uint32_t *)(linkedit_base + dysymtab->indirectsymoff); - /* 遍历各 section,挑非惰性符号指针段(__got / __auth_got)。 */ 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; @@ -197,16 +444,20 @@ static void ig_check_got_one_image(uint32_t img_index, 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; /* 一致=正常转发 */ + 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; /* 仍指向系统实现,放行 */ + 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, + 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; @@ -220,11 +471,11 @@ static void ig_check_got_one_image(uint32_t img_index, 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; - /* 逐符号:provenance + inline-hook,并收集 trusted 地址表供 GOT 检查复用。 */ void *trusted[64]; - size_t n = count < 64 ? count : 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; @@ -232,7 +483,6 @@ int ig_anti_hook_check(const char *const *names, size_t count, if (stop) return hits; } - /* GOT 重绑定:遍历全部镜像,内部只查非系统镜像。 */ 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); @@ -241,29 +491,51 @@ int ig_anti_hook_check(const char *const *names, size_t count, } 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; - /* provenance:地址提供方须在系统路径白名单内。 */ Dl_info info; if (!dladdr(addr, &info) || !info.dli_fname) { ig_emit(sink, ctx, &stop, &hits, IG_UNAVAILABLE, IG_REASON_VERIFICATION_UNAVAILABLE, - name ? name : "?", "无法确认函数提供方"); + 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; } - /* inline-hook 序言。 */ - return ig_check_prologue(name ? name : "?", addr, sink, ctx, &stop, &hits); + return ig_check_prologue(IG_DIAG_STR(name ? name : "?"), addr, sink, ctx, &stop, &hits); } int ig_anti_hook_check_default(IGFindingSink sink, void *ctx) { - return ig_anti_hook_check(kIGDefaultSymbols, - sizeof(kIGDefaultSymbols)/sizeof(kIGDefaultSymbols[0]), - sink, 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; } diff --git a/defender/anti_hook/IGAntiHook.h b/defender/anti_hook/IGAntiHook.h index af977dc..5674b05 100644 --- a/defender/anti_hook/IGAntiHook.h +++ b/defender/anti_hook/IGAntiHook.h @@ -27,19 +27,20 @@ extern "C" { int ig_anti_hook_check(const char *const *names, size_t count, IGFindingSink sink, void *ctx); -/* 便捷入口:用内置关键符号集(报告命中的 12 个)执行 ig_anti_hook_check。 */ +/* 便捷入口:用内置关键符号集(底层 I/O + 密码学/Keychain + ObjC runtime)执行校验。 */ int ig_anti_hook_check_default(IGFindingSink sink, void *ctx); /* * 单点「调用前校验」:对一个**已解析**的函数地址做 provenance(dladdr 提供方须系统路径) - * + inline-hook 序言检查。供 IGResolve 在放行解析结果前复用。 + * + 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); -/* ARM64 序言形态分类,可独立测试;命中只是一条证据,不覆盖所有 Hook。 */ +/* 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); #ifdef __cplusplus } diff --git a/defender/anti_hook/IGObjCBaseline.c b/defender/anti_hook/IGObjCBaseline.c index 9d7f8c0..756ac35 100644 --- a/defender/anti_hook/IGObjCBaseline.c +++ b/defender/anti_hook/IGObjCBaseline.c @@ -1,39 +1,51 @@ /* * IGObjCBaseline.c — ObjC 关键方法 IMP 基线探针实现。 * - * 全部公开 API:objc_getClass / sel_registerName / class_getMethodImplementation + * 全部公开 API:objc_getClass / sel_registerName / class_getInstanceMethod / + * class_getClassMethod / method_getImplementation / class_getImageName * (objc/runtime.h,纯 C)、dladdr(提供方)、vm_read_overwrite(代码前缀)。 - * method_getImplementation 返回"当前会被实际调用的实现"(已解析 swizzle), - * 与基线不一致即说明方法被交换/替换——这正是要抓的形态。 * - * 线程模型:capture 由策略层在确定时点(如首帧后)调用一次;check 在扫描时点调用。 - * 两者并发属策略层误用,本模块不加锁(保持零依赖、可嵌入任意 target)。 + * 特性: + * - 同时支持实例方法(-)与类方法(+); + * - 前缀快照扩大到 32 字节(4 字节对齐读取,兼容最小 16 字节回退); + * - 支持早晚双段登记(C ctor + Swift 运行期追加去重 ig_objc_baseline_append); + * - 登记瞬间同步检测「前置劫持」(IMP 已落入非声明宿主镜像,或函数窗已被改为跳转蹦床)。 */ #include "IGObjCBaseline.h" +#include "IGAntiHook.h" #include "IGInline.h" -#include -#include +#if IG_DIAGNOSTIC_STRINGS +# include +#endif #include #include #include #include +#if defined(__has_feature) +# if __has_feature(ptrauth_calls) +# include +# endif +#endif -#define IG_OBJC_MAX_WATCH 64 -#define IG_PREFIX_BYTES 16 +#define IG_OBJC_MAX_WATCH 64u +#define IG_PREFIX_BYTES 32u +#define IG_PREFIX_FALLBACK 16u typedef struct { - const char *cls; /* 登记时的类名 */ - const char *sel; /* 登记时的选择子 */ - void *imp; /* 基线 IMP(去 PAC 后) */ - char prov[192]; /* 基线 IMP 提供方镜像路径 */ + const char *cls; + const char *sel; + uint8_t is_cls_method; + uint8_t pre_hooked; + void *imp; + char prov[192]; unsigned char prefix[IG_PREFIX_BYTES]; - int have_prefix; + size_t prefix_len; } IGObjCSlot; static IGObjCSlot g_slots[IG_OBJC_MAX_WATCH]; -static size_t g_nslots; +static size_t g_nslots = 0; static const void *ig_strip(const void *p) { #if defined(__has_feature) @@ -51,94 +63,211 @@ 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; - memset(&f, 0, sizeof(f)); + ig_memset(&f, 0, sizeof(f)); f.status = st; f.reason = IG_REASON_OBJC_IMP_CHANGED; - strncpy(f.subject, subject, sizeof(f.subject) - 1); - strncpy(f.evidence, evidence, sizeof(f.evidence) - 1); +#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; } -/* 读取函数前 N 字节;失败返回 0(调用方按 unavailable 语义处理)。 */ -static int ig_read_prefix(const void *addr, unsigned char *out) { +static size_t ig_read_prefix(const void *addr, unsigned char *out) { vm_size_t copied = 0; - if (vm_read_overwrite(mach_task_self(), (vm_address_t)ig_strip(addr), - IG_PREFIX_BYTES, (vm_address_t)out, &copied) != KERN_SUCCESS - || copied != IG_PREFIX_BYTES) - return 0; - return 1; + vm_address_t target = (vm_address_t)ig_strip(addr); + if (vm_read_overwrite(mach_task_self(), target, + IG_PREFIX_BYTES, (vm_address_t)out, &copied) == KERN_SUCCESS && + copied == IG_PREFIX_BYTES) { + return IG_PREFIX_BYTES; + } + copied = 0; + if (vm_read_overwrite(mach_task_self(), target, + IG_PREFIX_FALLBACK, (vm_address_t)out, &copied) == KERN_SUCCESS && + copied == IG_PREFIX_FALLBACK) { + return IG_PREFIX_FALLBACK; + } + return 0u; } -size_t ig_objc_baseline_capture(const IGObjCWatch *watches, size_t count) { - g_nslots = 0; - if (!watches) return 0; - size_t ok = 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); if (!c) continue; - Method m = class_getInstanceMethod(c, sel_registerName(watches[i].selector)); - if (!m) continue; /* 类存在但方法不可解析:不登记(check 语义与登记时一致) */ + uint8_t is_cls = 0u; + const char *bare_sel = NULL; + Method m = ig_resolve_method(c, watches[i].selector, &is_cls, &bare_sel); + if (!m) continue; + if (ig_slot_exists(watches[i].class_name, bare_sel, is_cls)) continue; IMP imp = method_getImplementation(m); if (!imp) 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 = watches[i].selector; - slot->imp = (void *)imp; - slot->prov[0] = '\0'; + slot->sel = bare_sel; + slot->is_cls_method = is_cls; + slot->imp = (void *)stripped; + Dl_info info; - if (dladdr((void *)imp, &info) && info.dli_fname) - strncpy(slot->prov, info.dli_fname, sizeof(slot->prov) - 1); - slot->have_prefix = ig_read_prefix((void *)imp, slot->prefix); - ++ok; + if (dladdr(stripped, &info) && info.dli_fname) { + size_t plen = ig_strlen(info.dli_fname); + if (plen >= sizeof(slot->prov)) plen = sizeof(slot->prov) - 1u; + ig_memcpy(slot->prov, info.dli_fname, plen); + } + + const char *cls_img = class_getImageName(c); + if (cls_img && slot->prov[0] && ig_strcmp(cls_img, slot->prov) != 0) { + slot->pre_hooked = 1u; + } + + slot->prefix_len = ig_read_prefix(stripped, slot->prefix); + if (slot->prefix_len >= 8u) { + uint32_t words[IG_PREFIX_BYTES / sizeof(uint32_t)]; + size_t nwords = slot->prefix_len / sizeof(uint32_t); + ig_memcpy(words, slot->prefix, nwords * sizeof(uint32_t)); + if (ig_arm64_suspicious_window(words, nwords)) { + slot->pre_hooked = 1u; + } + } + ++added; } - return ok; + return added; +} + +size_t ig_objc_baseline_capture(const IGObjCWatch *watches, size_t count) { + g_nslots = 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) { - if (g_nslots == 0) return 0; /* 未接入:clear no-op */ + if (g_nslots == 0u) return 0; 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_nslots && !stop; ++i) { const IGObjCSlot *b = &g_slots[i]; - snprintf(subject, sizeof(subject), "-[%s %s]", b->cls, b->sel); +#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), "基线捕获时已异常(%s @%p)", b->prov[0] ? b->prov : "?", 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; } - Method m = class_getInstanceMethod(c, sel_registerName(b->sel)); + 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(imp); + const void *cur = ig_strip((const void *)imp); if (cur != b->imp) { - /* IMP 换人:典型 swizzle / class_replaceMethod / exchange。 */ +#if IG_DIAGNOSTIC_STRINGS char cur_prov[192] = "?"; Dl_info info; - if (dladdr((void *)cur, &info) && info.dli_fname) - strncpy(cur_prov, info.dli_fname, sizeof(cur_prov) - 1); + 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(%s) → %p(%s)(实现被替换)", b->imp, b->prov[0] ? b->prov : "?", 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; } - /* IMP 未变但代码前缀变:实现函数体被 inline patch。 */ - if (b->have_prefix) { + if (b->prefix_len > 0u) { unsigned char now[IG_PREFIX_BYTES]; - if (!ig_read_prefix((void *)cur, now)) { + size_t now_len = ig_read_prefix(cur, now); + if (now_len < b->prefix_len) { ig_emit_objc(sink, ctx, &stop, &hits, IG_UNAVAILABLE, subject, - "代码前缀不可读"); + IG_DIAG_STR("代码前缀不可读")); continue; } - if (memcmp(now, b->prefix, IG_PREFIX_BYTES) != 0) { + if (ig_memcmp(now, b->prefix, b->prefix_len) != 0) { +#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 } } } diff --git a/defender/anti_hook/IGObjCBaseline.h b/defender/anti_hook/IGObjCBaseline.h index 645f547..30213b9 100644 --- a/defender/anti_hook/IGObjCBaseline.h +++ b/defender/anti_hook/IGObjCBaseline.h @@ -28,12 +28,21 @@ typedef struct { } IGObjCWatch; /* - * 采集基线:对每个观察项记录当前 IMP 地址、提供方镜像路径与代码前缀 16 字节。 - * 幂等,重复调用以最后一次为准;count==0 清空基线。返回成功登记的条数 - * (类/选择子当时不可解析的条目不登记,check 时按 unavailable 上报)。 + * 采集基线(重置并重建):对每个观察项记录当前 IMP 地址、提供方镜像路径与代码前缀 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); * 类不可解析 / IMP 为转发桩 / 代码页不可读 → UNAVAILABLE(110)。 diff --git a/defender/anti_jailbreak/IGAntiJailbreak.c b/defender/anti_jailbreak/IGAntiJailbreak.c index 5c2b622..4380869 100644 --- a/defender/anti_jailbreak/IGAntiJailbreak.c +++ b/defender/anti_jailbreak/IGAntiJailbreak.c @@ -7,7 +7,9 @@ #include "IGAntiJailbreak.h" #include "syscall/IGSyscall.h" -#include +#if IG_DIAGNOSTIC_STRINGS +# include +#endif /* access 的 amode:F_OK=0(仅测存在/可访问)。open 标志(BSD/Darwin 值)。 */ #define IG_F_OK 0 @@ -45,8 +47,13 @@ static void ig_jb_emit(IGFindingSink sink, void *ctx, int *hits, __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); } @@ -60,9 +67,13 @@ int ig_anti_jb_check_paths(const char *const *paths, size_t count, 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 } } @@ -73,10 +84,15 @@ int ig_anti_jb_check_paths(const char *const *paths, size_t count, 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 } } diff --git a/defender/anti_tamper/IGAntiTamper.c b/defender/anti_tamper/IGAntiTamper.c index 4b3b373..34911d6 100644 --- a/defender/anti_tamper/IGAntiTamper.c +++ b/defender/anti_tamper/IGAntiTamper.c @@ -8,7 +8,9 @@ #include #include -#include +#if IG_DIAGNOSTIC_STRINGS +# include +#endif /* csops(2):读本进程代码签名状态。手工声明( 非 SDK 公共头)。 */ #define IG_CS_OPS_STATUS 0 @@ -23,8 +25,13 @@ static void ig_tamper_emit(IGFindingSink sink, void *ctx, int *hits, __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); } @@ -36,12 +43,12 @@ int ig_tamper_scan_cryptid(const struct mach_header_64 *mh, int expect_encrypted /* 非分发构建:未 FairPlay 加密是正常的,无法据此断言篡改。 */ if (!expect_encrypted) { ig_tamper_emit(sink, ctx, &hits, IG_UNAVAILABLE, IG_REASON_BINARY_DECRYPTED, - "cryptid", "非分发构建(expect_encrypted=0),跳过加密校验"); + 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, - "cryptid", "主镜像 Mach-O 头不可用"); + IG_DIAG_STR("cryptid"), IG_DIAG_STR("主镜像 Mach-O 头不可用")); return hits; } @@ -64,11 +71,11 @@ int ig_tamper_scan_cryptid(const struct mach_header_64 *mh, int expect_encrypted if (!found) { /* 应加密的分发包却整条没有加密命令:被剥除/重打包的强信号。 */ ig_tamper_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_BINARY_DECRYPTED, - "cryptid", "应加密分发包无 LC_ENCRYPTION_INFO(加密命令被剥除/重打包)"); + 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, - "cryptid", "cryptid==0:二进制已脱壳解密(dump/重打包)"); + IG_DIAG_STR("cryptid"), IG_DIAG_STR("cryptid==0:二进制已脱壳解密(dump/重打包)")); } /* cryptid != 0 → CLEAR,保持安静不上报。 */ return hits; @@ -81,28 +88,29 @@ static int ig_tamper_scan_codesign(int expect_distribution, /* 非分发构建:dev/诊断签名本就带 get-task-allow、可能 ad-hoc,不据此断言。 */ if (!expect_distribution) { ig_tamper_emit(sink, ctx, &hits, IG_UNAVAILABLE, IG_REASON_CODESIGN_INVALID, - "codesign", "非分发构建(expect_distribution=0),跳过签名校验"); + IG_DIAG_STR("codesign"), IG_DIAG_STR("非分发构建(expect_distribution=0),跳过签名校验")); return hits; } uint32_t status = 0; - if (csops(getpid(), IG_CS_OPS_STATUS, &status, sizeof(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, - "codesign", "csops(CS_OPS_STATUS) 调用失败"); + 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, - "codesign", "CS_VALID 失效:代码页签名校验未通过(内存/磁盘被 patch)"); + 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, - "codesign", "ad-hoc 签名:无开发者证书的重签(典型破解重打包)"); + 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, - "codesign", "分发包却带 get-task-allow:被重签成可调试"); + IG_DIAG_STR("codesign"), IG_DIAG_STR("分发包却带 get-task-allow:被重签成可调试")); } return hits; } diff --git a/defender/call_bridge/IGThreadID.c b/defender/call_bridge/IGThreadID.c new file mode 100644 index 0000000..a13d69b --- /dev/null +++ b/defender/call_bridge/IGThreadID.c @@ -0,0 +1,22 @@ +#include +#include +#include + +/* 仅用于已核实只查询当前线程 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; +} diff --git a/defender/dispatch/IGArchiveGuard.c b/defender/dispatch/IGArchiveGuard.c index 68dd4ea..727588c 100644 --- a/defender/dispatch/IGArchiveGuard.c +++ b/defender/dispatch/IGArchiveGuard.c @@ -1,30 +1,90 @@ +#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 +#include #include +#include #include #include +#include #include #include #include #include -/* 仅混淆常量,不作为秘密。SDK GOT 由 dyld 在独立镜像滑移后绑定。 */ -static const unsigned char names[4][6] = { - {0x5a,0x53,0x4c,0x59,0x52}, {0x5a,0x4e,0x59,0x5d,0x58}, - {0x5a,0x4b,0x4e,0x55,0x48,0x59}, {0x5a,0x5f,0x50,0x53,0x4f,0x59} +#if defined(__has_feature) +# if __has_feature(ptrauth_calls) +# include +# 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[4]; -static uintptr_t expected[4], bindingSlots[4]; -static unsigned char prefixes[4][16]; -static IGStatus initial[4]; +static _Atomic(uintptr_t) targets[IG_ARCHIVE_FUNCTION_COUNT]; +static uintptr_t expected[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[12]; +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) @@ -36,20 +96,62 @@ static int read_bytes(uintptr_t address, void *out, size_t size) { && copied == size; } -/* 仅支持打包工具已审核的非认证 arm64 GOT;缺槽/重复槽均标为不可验证。 */ +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) { - unsigned found = 0, images = 0; - for (uint32_t index = 0; index < _dyld_image_count(); index++) { + 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); - const char *suffix = "/SSZipArchive.framework/SSZipArchive"; - size_t length = path ? ig_strlen(path) : 0, tail = ig_strlen(suffix); - if (length < tail || ig_strcmp(path + length - tail, suffix)) continue; - if (++images != 1) return 0; + 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->cputype != CPU_TYPE_ARM64 - || (header->cpusubtype & 0xffffff) != 0) return 0; - uintptr_t slide = _dyld_get_image_vmaddr_slide(index); - const struct segment_command_64 *linkedit = NULL; + 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); @@ -57,23 +159,26 @@ static int locate_bindings(void) { 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->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 || !symtab || !dysymtab || command != end) return 0; + 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 + 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 + linkedit->vmaddr - 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); @@ -85,40 +190,49 @@ static int locate_bindings(void) { 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; - 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 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; - for (unsigned n = 0; n < 4; n++) { - char expectedName[] = "_ig_a0"; - expectedName[5] += n; - if (ig_strcmp(name, expectedName)) continue; - if (found & (1u << n)) return 0; - bindingSlots[n] = slide + s->addr + k*8; - found |= 1u << n; - } + 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 found == 15 && images == 1; + return trackedCount > 0; } static void initialize(void) { bindingReady = locate_bindings(); - for (unsigned i = 0; i < 4; i++) { - IGResolveResult result = ig_resolve_verified(NULL, names[i], i < 2 ? 5 : 6, NULL, NULL); + 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; - if (!read_bytes((uintptr_t)result.address, prefixes[i], 16)) { initial[i] = IG_UNAVAILABLE; continue; } + if (!read_bytes((uintptr_t)IG_ARCHIVE_STRIP(result.address), prefixes[i], 16)) { + initial[i] = IG_UNAVAILABLE; + continue; + } expected[i] = (uintptr_t)result.address; atomic_store_explicit(&targets[i], expected[i], memory_order_release); } @@ -132,95 +246,274 @@ static int prepare(void) { return result == 0; } -static IGStatus validate(unsigned index, uintptr_t *address) { +__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; - IGStatus status = ig_verify_function((void *)current, "archive-target", NULL, NULL); - if (status != IG_CLEAR) return status; unsigned char bytes[16]; - if (!read_bytes(current, bytes, 16)) return IG_UNAVAILABLE; + if (!read_bytes((uintptr_t)IG_ARCHIVE_STRIP((const void *)current), bytes, 16)) return IG_UNAVAILABLE; if (ig_memcmp(bytes, prefixes[index], 16)) 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 不装载 SSZipArchive;此豁免不能编入业务包。 */ + /* 宿主 ABI fixture 不装载外部动态 SDK;此豁免不能编入业务包。 */ return IG_CLEAR; #else - if (!bindingReady) return IG_UNAVAILABLE; - uintptr_t correct[4] = {(uintptr_t)&ig_a0, (uintptr_t)&ig_a1, (uintptr_t)&ig_a2, (uintptr_t)&ig_a3}; - for (unsigned i = 0; i < 4; i++) { - uintptr_t current; - if (!read_bytes(bindingSlots[i], ¤t, sizeof(current))) return IG_UNAVAILABLE; - if (current != correct[i]) return IG_DETECTED; + 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); - if (status != IG_CLEAR) { COUNT(index, 2); errno = status == IG_DETECTED ? EACCES : ENOSYS; return 0; } + 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 *ig_a0(const char *path, const char *mode) { +__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)) size_t ig_a1(void *ptr, size_t size, size_t count, FILE *stream) { +__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 ig_a2(const void *ptr, size_t size, size_t count, FILE *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 ig_a3(FILE *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); } - -int ig_archive_check(void) { +__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 status = check_bindings(); - for (unsigned i = 0; i < 4; i++) { + 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; - IGStatus current = validate(i, &address); - if (current == IG_DETECTED || (current == IG_UNAVAILABLE && status == IG_CLEAR)) status = current; + 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 status == IG_CLEAR ? 0 : status == IG_DETECTED ? 1 : -1; + 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 < 12 ? atomic_load_explicit(&counters[index], memory_order_relaxed) : 0; + 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 < 4 && prepare()) atomic_store_explicit(&targets[index], (uintptr_t)address, memory_order_release); + 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 diff --git a/defender/dispatch/IGArchiveGuard.h b/defender/dispatch/IGArchiveGuard.h index b4e7625..b6e7a4a 100644 --- a/defender/dispatch/IGArchiveGuard.h +++ b/defender/dispatch/IGArchiveGuard.h @@ -2,13 +2,38 @@ #define IG_ARCHIVE_GUARD_H #include #include +#include +enum { IG_ARCHIVE_FUNCTION_COUNT = 14 }; #define IG_ARCHIVE_EXPORT __attribute__((visibility("default"))) -IG_ARCHIVE_EXPORT FILE *ig_a0(const char *path, const char *mode); -IG_ARCHIVE_EXPORT size_t ig_a1(void *ptr, size_t size, size_t count, FILE *stream); -IG_ARCHIVE_EXPORT size_t ig_a2(const void *ptr, size_t size, size_t count, FILE *stream); -IG_ARCHIVE_EXPORT int ig_a3(FILE *stream); + +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 int ig_archive_check(void); +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); @@ -17,4 +42,32 @@ IG_ARCHIVE_EXPORT uint64_t ig_archive_counter(unsigned index); 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 diff --git a/defender/dispatch/IGDispatch.c b/defender/dispatch/IGDispatch.c index e6a9fd1..a590a6d 100644 --- a/defender/dispatch/IGDispatch.c +++ b/defender/dispatch/IGDispatch.c @@ -6,19 +6,42 @@ #include #include #include +#include +#include +#include #include /* 编码只减少常量区明文,不作为秘密或强加密。缓存与基线仍可被同进程攻击者修改。 */ -static const unsigned char kNames[2][5] = {{0x4b,0x4e,0x55,0x48,0x59}, - {0x5f,0x50,0x53,0x4f,0x59}}; +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[2]; -static uintptr_t gExpected[2]; -static unsigned char gPrefixes[2][16]; -static IGStatus gInitialStatus[2]={IG_UNAVAILABLE,IG_UNAVAILABLE}; +static _Atomic(uintptr_t) gSlots[IG_DISPATCH_COUNT]; +static uintptr_t gExpected[IG_DISPATCH_COUNT]; +static unsigned char gPrefixes[IG_DISPATCH_COUNT][16]; +static IGStatus gInitialStatus[IG_DISPATCH_COUNT]; static _Thread_local int gResolving; #ifdef IG_OBSERVATION -static _Atomic(uint64_t) gAttempted[2], gDispatched[2]; +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) @@ -31,8 +54,8 @@ static int read_prefix(uintptr_t address, unsigned char out[16]) { } static void initialize(void) { - for (unsigned i=0;i<2;i++) { - IGResolveResult r=ig_resolve_verified(NULL,kNames[i],5,NULL,NULL); + for (unsigned i=0;i +#include #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; diff --git a/defender/include/IGDefender.h b/defender/include/IGDefender.h index 7a84027..ba45fc4 100644 --- a/defender/include/IGDefender.h +++ b/defender/include/IGDefender.h @@ -19,6 +19,14 @@ 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, /* 命中威胁证据 */ diff --git a/defender/resolve/IGResolve.c b/defender/resolve/IGResolve.c index 991955f..047e905 100644 --- a/defender/resolve/IGResolve.c +++ b/defender/resolve/IGResolve.c @@ -1,15 +1,214 @@ /* - * IGResolve.c — 加密名 + 带校验的符号解析实现。 + * IGResolve.c — 加密名 + 无 dlsym Export Trie + 带校验的符号解析实现。 * - * 复用 IGAntiHook 的 ig_verify_function 做「放行前校验」:dlsym 得到地址后,必须 provenance - * (提供方系统路径)+ 序言(非 inline-hook 蹦床)双过,否则返回 NULL——把「被挟持的实现」挡在调用前。 + * 复用 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 #include /* _NSGetEnviron */ +#include +#include + +#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 +# 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; @@ -34,7 +233,13 @@ IGResolveResult ig_resolve_verified(void *handle, const unsigned char *enc_name, char name[256]; IGResolveResult result={IG_UNAVAILABLE,NULL}; if (!ig_decrypt(enc_name, sym_len, name, sizeof(name))) return result; - void *addr = dlsym(handle ? handle : RTLD_DEFAULT, name); +#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); @@ -52,14 +257,6 @@ void *ig_dlsym_verified(void *handle, const unsigned char *enc_name, size_t sym_ return ig_resolve_verified(handle,enc_name,sym_len,NULL,NULL).address; } -void *ig_dlopen_hidden(const unsigned char *enc_path, size_t path_len, int mode) { - char path[512]; - if (!ig_decrypt(enc_path, path_len, path, sizeof(path))) return NULL; - void *h = dlopen(path, mode); - ig_wipe(path, sizeof(path)); - return h; -} - const char *ig_getenv(const char *name) { char ***environment = _NSGetEnviron(); if (!environment || !*environment || !name || !name[0]) return NULL; diff --git a/defender/resolve/IGResolve.h b/defender/resolve/IGResolve.h index db9b00b..d3c9a48 100644 --- a/defender/resolve/IGResolve.h +++ b/defender/resolve/IGResolve.h @@ -36,7 +36,21 @@ char *ig_decrypt(const unsigned char *enc, size_t len, char *out, size_t cap); void ig_wipe(void *p, size_t n); /* - * 带校验的 dlsym:在 handle(NULL=RTLD_DEFAULT)中解析名为 enc_name(XOR 编码) 的符号, + * 走 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); @@ -45,12 +59,6 @@ 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); -/* - * 带隐藏名的 dlopen:以 enc_path(XOR 编码) 打开库,返回 handle 或 NULL。 - * 仅隐藏库路径字符串;是否可信由后续 ig_dlsym_verified 的校验保证。 - */ -void *ig_dlopen_hidden(const unsigned char *enc_path, size_t path_len, int mode); - /* 经 _NSGetEnviron 手工查环境变量,规避 getenv 符号。未命中返回 NULL。name 为明文(短、非敏感)。 */ const char *ig_getenv(const char *name); diff --git a/docs/18_READOOR_DEFENDER_INTEGRATION.md b/docs/18_READOOR_DEFENDER_INTEGRATION.md index 9a73649..3ed5b2e 100644 --- a/docs/18_READOOR_DEFENDER_INTEGRATION.md +++ b/docs/18_READOOR_DEFENDER_INTEGRATION.md @@ -319,3 +319,14 @@ private func eventName(_ event: RDSecurityEvent) -> String { 三项达标 → 按 §4 在 `RDEncryptedEpubResourceProvider.decrypt` 接 `ig_poison_apply`,并把 `observeWithDefender` 里「不据 triggered 处置」的注释解除、改为真正消费(或让毒化在解密侧随 mask 自然生效,二选一,推荐后者=解耦)。 > **为什么并行而非立刻替换 `forceExit`**:灰度期保留现有 Swift 检测路径(哪怕已停用 exit),让新旧两套检测的 reason 分布能在同一批设备上对照,确认 C 侧探针不是凭空多报。待毒化开启、稳定后,再按 §3 用策略扫描收口、下线 `forceExit`。 + +--- + +## 8. 接入落地记录(2026-11-13) + +骨架接线 + 真机 Debug 编译通过(`** BUILD SUCCEEDED **`)。readoor 侧完整记录见 `readoor-test/Doc/FeatureSolution/Security_运行时Defender接入与处置策略_实现方案.md` §4.11。要点与**对本文方案的偏离/升级**: + +- **接入点二(毒化)用 §7.6 断边内联形态,而非 §4 的 `ig_poison_apply` 后置形态**:新建 `Base/Security/RDEpubKeyGuard.{c,h}`,`rd_epub_key_transform` 内联 `ig_poison_mix_key_inline`,毒化揉进 key schedule。真机 `otool` 核实该函数内无 `bl ig_poison_*` 调用边、`nm -u` 无 poison 未定义符号=断边成立。epub key 为 ASCII(`doubled("startiasoft"+id)` 与 MD5 hex),健康态 UTF-8 往返无损(§4 的二进制 key 警告不适用本场景)。 +- **毒化判定在 Swift `RDSecurityPolicy.applyPoisonDisposition`,不同步 C `policy/IGPolicy.c`**:readoor 分级权威在 Swift,越狱信号来自 Swift `RDJailbreakDetector`(C `ig_defender_scan` 不产 400/401),同步 C policy 会二次扫描 + 分级漂移。毒化门**严于 terminate 门**(STRONG 单条:901/900/101/102/200/202;MEDIUM ≥2:100/110/203),`observe` 模式绝不毒化。`rd_epub_poison_mark` 为写入侧薄桥(检测线程调用,不需断边)。 +- **anti_tamper(§7.7)已挂 observer**:`RDRuntimeDefender.scan` 追加 `ig_anti_tamper_check`,`expect_*` 由 **仅 Release** 注入的 `IG_APPSTORE_DISTRIBUTION` 置 1(Debug/dev 为 0→UNAVAILABLE 零误报)。500/501 本轮纯观察,未接处置、未并入毒化门。 +- **未覆盖**:真机「越狱→毒化→解乱码」正向路径(需越狱设备);多机型非越狱零毒化上线验证(设计强制项);`IG_APPSTORE_DISTRIBUTION` 真分发包 500/501 正反向(需 App Store Connect 上传);`terminateConfirmed` 默认模式下启动期 exit 仍遮蔽毒化,待处置策略按 disposition-strategy 收敛 exit 后毒化转主。 diff --git a/docs/20_SYSTEM_CALL_DISPATCH_EXPANSION.md b/docs/20_SYSTEM_CALL_DISPATCH_EXPANSION.md new file mode 100644 index 0000000..7cb259d --- /dev/null +++ b/docs/20_SYSTEM_CALL_DISPATCH_EXPANSION.md @@ -0,0 +1,215 @@ +# 上架 IPA 系统调用整改第一阶段 + +日期:2026-11-17。状态:受保护调用层扩展完成,尚未接入最终 IPA。 + +## 输入与边界 + +输入为根目录 `appstore.ipa`,版本 2.199.0 / 2.199.0.3,Bundle ID +`com.ecnup.aSCLdl2`,SHA-256: +`ddb89e30c2259b45d3f09dbc825e70c4e84c682a3c23510ceb3aa6f93d891771`。 +43 个未加密 Mach-O;文档九类系统函数的直接调用共 401 处,分布在 12 个二进制中。 +这些计数来自 arm64 `__text` 内 BL/B 到符号 stub 的扫描,不是所有间接调用的完整证明。 + +## 已实现 + +`defender/dispatch/IGDispatch` 从 write/close 扩展到 read/open/unlink/getpid,共六个类型明确的入口。 +沿用线程安全的首次解析、私有地址缓存、提供方验证、序言及 16 字节前缀检查。 +验证失败不转发到可疑地址,不回退到原 GOT。保留 libc 的返回值和 errno,不自动补齐短读写或重试 EINTR。 +open 仅在 O_CREAT 时读取第三个参数,其他路径保持两参数调用。 + +新增入口适用于经过审查的普通业务调用点。校验依赖 pthread/dlsym/Mach,不能用于信号处理器或 +fork 后子进程,不应做全局 libc interpose。getpid 校验失败会返回 -1 并设置 errno,接入方必须处理此扩展失败语义。 +观察计数结构继续只包含既有 write/close 字段,未改变其 ABI。 + +这六类在当前 IPA 中共 299 个直接调用点,但这里只完成保护层实现,**299 个点尚未接线,不能计为已修复**。 +新库也不是可直接上架的完整产物;完整 Defender 既有的 SVC/csops 分发配置问题没有在本轮消除。 + +## syscall 与 fork 定位 + +主程序 syscall 调用地址:`0x102366700`、`0x102433728`。 +两处紧邻调用前均为 `mov w0, #372`,Apple XNU 的系统调用表将 372 定义为 thread_selfid: +https://github.com/apple-oss-distributions/xnu/blob/main/bsd/kern/syscalls.master + +因此不能把这两处当作 ptrace,也不能一律删除。可进一步评估 pthread_threadid_np 适配,需验证返回值截断、错误语义和最终调用者契约。 +fork 调用位于 `0x10213f43c`,附近存在父子进程与失败分支,未删除。 +反汇编工具输出的最近可见符号不是函数归属证明,不能按远距离符号标题归因为 ZipZap。 + +检查副本中 19 个候选设备静态库发现:iflyMSC 多个对象引用 syscall;StsFreetypeLib 的 ftrandom.o、 +libskegn 的 sgn_net.o/CNLM.o 引用 fork。这只是候选依赖证据,不能证明这三处 IPA 地址归属。 +找到的 readoor31 Link Map 与 IPA 的 readoor31OtherPay 目标不同,不用于直接地址归因;未找到匹配的 xcarchive。 + +## 验证与产物 + +- 全套宿主和工具测试:76 项通过。 +- 覆盖 open 创建权限/排他创建/两参数打开、read 短读/EOF/EBADF/EINTR、unlink/ENOENT、getpid、errno 保留。 +- 覆盖新增四槽篡改拒绝、解析失败,以及既有并发、重入、write 短写测试。 +- iphoneos arm64 Release 编译通过;nm 检查 dispatch 对象未引入六个受保护 libc 函数的直接未定义引用。 +- 静态库构建成功;未运行新库的真机测试,未修改或重签原 IPA。 + +证据目录:`test-results/20261117-system-call-dispatch/`,含 manifest、测试/构建日志、三处反汇编片段和 dist。 +完整调用点表:`test-results/20261117-ipa-system-call-audit/callsites.csv`。 + +## 后续接入 + +需对六类调用按调用上下文接线并逐项验证,而非全包盲目替换。 +剩余 exit 99 处、syscall 2 处、fork 1 处需要分别处理终止、线程标识、进程控制语义。 +最终需重新构建或完成受支持的二进制接入、正式签名、逐指令及业务/Hook 真机验证。 +当前阶段不代表原检测机构复测通过,也不代表系统函数无法被 Hook。 + +## OtherPay 语音 SDK 的线程 ID 查询 + +OtherPay Release 的同次 Link Map 定位到两处直接 `syscall(372)`。分别属于 +TIWLogger 的 `Util.o` 和 libspeechsdk 的 `alog_util.o`。候选方案使用 +`pthread_threadid_np` 读取当前线程 ID,并保留既有 32 位返回值和成功时的 errno。 + +从仓库根目录运行下列命令生成候选链接输入。输出目录须为新目录。 + +```sh +python3 tools/static_sdk_redirect/prepare_thread_id_sdks.py readoor-test test-results/thread-id-inputs +``` + +工具按已审计的两个 SDK SHA-256 校验输入,确认每个归档只有一条重定向引用, +并校验 `alog_util.o` 从 bitcode 编译前后的导出符号。候选仅包含 iPhoneOS arm64。 +重新链接时将输出目录放在原框架搜索目录前,使用其中的 `libspeechsdk.a` 替代 +`-lspeechsdk`,并链接 `IGThreadID.o`。最终应依据同次 Link Map 检查两个对象来源, +复扫主程序的直接调用和未定义符号。 + +bitcode 编译日志随产物保留。当前编译器会报告覆盖目标三元组和忽略部分目标特性, +语音录制、识别和日志仍需在签名测试包上做真机回归。 + +## 2026-11-18 SDK 文件打开接入 + +候选 OtherPay Release 在原有 19 处保护调用边基础上,先完成 NBReaderSDK 22 处 +fopen 调用替换,再完成 TIWLogger、PDF、FreeType、StsFc 共 13 处。 +驰声归档采用选择性成员转换工具,匹配 fopen 的 LLVM 对象编译后核对导出符号, +再重定向到 IG_dispatch_fopen。最新候选主程序的直接 fopen 由 53 处降到 33 处。 + +驰声仍保留 certificate.o 的一处扩展 ABI 引用 fopen$DARWIN_EXTSN,最终被链接器表示为 +fopen。普通 fopen 映射未覆盖此入口,需核实扩展行为再接入。 +工具保留未匹配的归档成员及 bitcode,不承诺所有 LLVM 格式均可转换。 +源码在 tools/static_sdk_redirect/redirect_bitcode_members.py。 +编译告警和 Link Map 保存在 test-results/20261118-skegn-stdio/。 +以上均为未签名 Release 链接候选,语音、模型加载、PDF 的真机业务验证待执行。 + + +## 语音 SDK 文件打开候选 + +2026-11-18 在驰声候选基础上,libspeechsdk 的 16 处 fopen 和 STKouyuEngine 的 4 处 fopen +均转向 IG_dispatch_fopen。每次候选重新链接后,以同次 Link Map 选取前一成品的调用者, +逐条检查分支目标和调用次数,并拒绝保留直接调用的成品。 +通用核验命令为 tools/macho_guard/verify_redirected_archive_calls.py。 +该工具已用 TIWLogger 四处正向样本及仍含四处直接调用的原始样本完成正反检查。 +候选路径分别为 test-results/20261118-speech-stdio 和 test-results/20261118-stkouyu-stdio。 +这些替换仍需整合到正式发布流程以及签名包的识别、录音、模型加载真机回归。 + +## 发布构建的覆盖率依赖 + +OtherPay Release 的实际链接参数含 -fprofile-instr-generate,构建环境输出 +ENABLE_CODE_COVERAGE=YES。移除此链接选项的候选能够成功链接,同次 Link Map 和扫描 +确认 libclang_rt.profile_ios.a 的文件打开与退出调用消失。 +readoor31 和 readoor31OtherPay 的 Release 配置显式关闭 ENABLE_CODE_COVERAGE +及 CLANG_COVERAGE_MAPPING,完整构建日志位于 /private/tmp/iosguard-release-no-coverage-build.log。 +静态 SDK 候选仍需独立整合,源码构建的覆盖率配置调整不会自动替换候选 SDK。 + +## 腾讯日志文件打开 + +2026-11-18 腾讯 QQApiLog.o 中存在可提取的完整嵌入式 bitcode。 +选择性转换工具支持读取该 __LLVM,__bitcode 节并用目标 iOS 编译器生成本机对象, +校验导出符号后重定向 fopen。OtherPay 候选链接成功,逐调用工具确认原日志调用 +已转向 IG_dispatch_fopen。证据位于 test-results/20261118-qq-stdio/。 +覆盖率关闭后的前一候选主程序有八处直接 fopen,腾讯替换进一步减少一处。 +最终分发与真机 QQ 分享、授权和日志行为仍需验证。 + + +## 支付宝的六处文件打开 + +2026-11-18 使用同次 Link Map 精确选择支付宝 __isJailbreak,六处 fopen 分支改为 +IG_dispatch_fopen,配置为 tools/macho_guard/profiles/alipay_fopen.json。 +逐调用验证及完整字节差异核对通过,改动限定在六条分支指令。 +候选主程序剩一处来自 Apple libclang_rt.ios.a 的 __initializeAvailabilityCheck。 +保留其启动期系统版本查询语义,继续作为剩余风险跟踪。 +候选位于 test-results/20261118-alipay-stdio,尚待重新签名及支付业务回归。 +覆盖率关闭后的源码 OtherPay Release 完整构建已成功。 + +覆盖率配置复扫补充:首次设置 ENABLE_CODE_COVERAGE 与 CLANG_COVERAGE_MAPPING +后完整构建虽成功,实际链接仍含 -fprofile-instr-generate,整包统计未减少。 +因此该轮源码构建不作为覆盖率依赖已移除的证据。已补充 +CLANG_ENABLE_CODE_COVERAGE=NO 再构建,日志位于 /private/tmp/iosguard-release-coverage-fix.log。 +手工重新链接候选的运行库移除结果仍有独立 Link Map 支持。 + + +覆盖率第二次配置补充:CLANG_ENABLE_CODE_COVERAGE=NO 的增量构建没有重新链接, +现有主程序仍含运行库。xcodebuild 的 -enableCodeCoverage 只支持测试操作,该命令被拒绝, +未用于发布构建。已显式设置 CLANG_COVERAGE_MAPPING_LINKER_ARGS=NO 触发链接选项更新, +当前验证日志为 /private/tmp/iosguard-release-coverage-linker.log。应以实际链接命令与成品为准。 + +覆盖率最终验证:显式关闭 CLANG_COVERAGE_MAPPING_LINKER_ARGS 后 OtherPay Release +完整构建成功,实际链接命令无 coverage/profile 参数,同次 Link Map 归属扫描中 +libclang_rt.profile_ios.a 调用为零。源码构建证据位于 +test-results/20261118-source-release-coverage-fixed/,不混同于已应用 SDK 替换的候选。 + +## 汇总候选的可复现链接 + +2026-11-18 新增 tools/macho_guard/link_with_sdk_inputs.py,从实际 Release 构建日志读取唯一 +主程序链接命令。SDK 替换、线程 ID 对象及支付宝改写配置由哈希清单约束, +覆盖率链接参数残留、匹配项缺失或重复、输入哈希变化都会中止。 +从最新关闭覆盖率的源码构建重新链接全部 SDK 候选成功,证据位于 +test-results/20261118-release-integrated/result/。成品直接 syscall 为零,直接 fopen +仅剩编译器运行库的一处,覆盖率运行库未回归。既有 GCD、WAV、ZipZap 保护边和 +支付宝六处改写复验通过。该阶段输出为主可执行文件,后续需组装 App、签名及真机验证。 + +## 完整候选组装与真机启动 + +2026-11-18 汇总主程序嵌入 OtherPay Release App,并新增业务版 IGArchiveGuard.framework。 +SSZipArchive 的五个导入按既有哈希审计规则接入保护库。完整 App 共 44 个 Mach-O, +全包直接 fopen 仍有 168 处,说明嵌入 Framework 仍需整改。全包直接 syscall 为零。 + +使用通配开发 profile 和独立 Bundle ID cn.touchv.iosguard.integrated.20261118 签名, +嵌套签名检查通过并安装 iPhone 16 Plus。首次启动以 173 退出,终止日志 reason=900。 +核对原白名单 HMAC 后确认新增保护库未登记,且主程序路径带多余 .app 前缀。 +生成器 scan_bundled_images 已将主程序路径规范为 bundle 内文件名。 +同密钥重建测试包白名单后重新签名安装,PID 11458 在随后进程快照中仍运行, +控制台记录 Success unzip。启动可运行不替代页面与 SDK 真机业务回归。 + +独立测试包移除原 URL schemes,使用独立 Keychain 访问组。 +关联域、第三方登录和支付回调需要匹配正式应用配置后再验。 +当前有效包为 test-results/20261118-integrated-app/integrated-development-v2.ipa, +早期 integrated-development.ipa 包含白名单缺陷,不能用于验证。 + +## Framework 覆盖率整改 + +2026-11-18 从已安装测试包的 Framework 与同次构建 Link Map 对照, +29 个可匹配 Framework 中确认 87 处 fopen 属于 libclang_rt.profile_ios.a, +三个调用者分别为 writeFile、truncateCurrentFile 和 initializeProfileForContinuousMode。 +逐 Framework 记录及匹配 Map 位于 test-results/20261118-framework-coverage-audit/。 +无法匹配的库在 JSON 中明确标记 unverified,不纳入确认数量。 + +Podfile post_install 在所有依赖目标的 Release 配置关闭 ENABLE_CODE_COVERAGE、 +CLANG_ENABLE_CODE_COVERAGE、CLANG_COVERAGE_MAPPING 和 +CLANG_COVERAGE_MAPPING_LINKER_ARGS。当前生成工程也同步设置,Ruby 语法检查通过。 +完整构建使用 /private/tmp/iosguard-all-targets-no-coverage.log。 +最终是否移除这些调用仍须在构建完成后重新扫描。 + +## Framework 绑定子集与全依赖重建结果 + +2026-11-18 现有 chained-import 工具新增显式四入口子集参数,默认行为保留, +仅允许映射到已实现的 ig_a0–ig_a3。映射子集/非法映射与既有保护库测试合计 16 项通过。 +ZIPFoundation 旧测试构建中 11 处 fopen 引用已转向 ig_a0,段内机器代码保持一致, +共享保护库已经由 SSZipArchive 接入验证。候选证据在 +test-results/20261118-zipfoundation-stdio/。此阶段只检查整包签名、安装和启动存活, +实际压缩业务仍待验证。AliyunPlayer 采用传统 dyld 绑定,当前工具拒绝处理,仍待整改。 + +关闭全部 Release 依赖覆盖率后的完整构建成功。源码整包直接 fopen 从 258 降到 162, +直接 getpid 从 195 降到 35、exit 从 130 降到 98。 +证据在 test-results/20261118-all-targets-no-coverage/summary.json。 +该源码包尚未套用本轮 SDK 候选,不能与此前已替换主程序的测试包混作同一产物。 + +## 同一产物的整合结果 + +2026-11-18 使用关闭全部依赖覆盖率后的最新 Release 链接命令重建 SDK 汇总候选, +组装最新 Framework,再应用 SSZipArchive 五入口与 ZIPFoundation fopen 的保护绑定。 +独立测试包位于 test-results/20261118-integrated-no-coverage/。 +主程序保护边复验通过,44 个 Mach-O 的全包直接 fopen 为 67、直接 syscall 为零。 +上一独立测试包对应计数为 168。所有这些计数均按相同直接 BL/B→stub 规则获得。 +剩余最多来自 AliyunPlayer 28 处、AliyunMediaDownloader 10 处、 +TTNetworkManager 5 处,其他还有库内代码及编译器运行库入口。 diff --git a/docs/21_GCD_FILE_DISPATCH_INTEGRATION.md b/docs/21_GCD_FILE_DISPATCH_INTEGRATION.md new file mode 100644 index 0000000..af689d8 --- /dev/null +++ b/docs/21_GCD_FILE_DISPATCH_INTEGRATION.md @@ -0,0 +1,58 @@ +# GCDWebServer 文件流程保护层接入 + +## 范围与行为 + +本轮将保护层接入 `readoor-test` 的真实 GCDWebServer 文件请求与响应类。 +原始 `appstore.ipa` 未修改;这是源码构建路径上的首批接入,不代表整个 IPA 的 401 处整改完成。 + +- GCDWebServerFileRequest:open、write、close、unlink。 +- GCDWebServerFileResponse:open、read、两个 close 调用点(失败清理及正常关闭)。 +- 使用现有 `IGDispatch`,同步六入口扩展,同时保留 App 副本原有的初始化原因采集、同步终止和配置接口。 +- 可找到 `dispatch/IGDispatch.h` 的集成目标使用保护入口;未集成的历史目标保持 libc 路径。 + 最终产物需运行本轮新增校验工具,不能仅凭条件编译存在就认为接入成功。 +- 修正两个类将合法描述符 0 当成失败的判断(`<= 0` 改为 `< 0`)。 + +真实消费链:`RDWordLearnWebViewController.loadWebView` → `STSWebServerHandler.addHandlerForMethod:path:contentType:` +→ `GCDWebServer.addGETHandlerForBasePath` → `GCDWebServerFileResponse`。 +请求类的文件落盘路径用真实类实例测试,不声称已验证完整网络上传页面。 +本轮修改旧目录的原因是它直接对应报告列出的 GCDWebServer 风险,并由当前 3.0 单词书页面使用。 + +## 验证 + +`tests/test_gcd_file_integration.py` 编译 App 副本中的真实 GCDWebServer 全部实现及 Defender,未用替身替代业务类。 +宿主运行七项场景:内容写入、范围读取与 EOF、请求销毁删除文件、描述符 0、open/write/read 篡改拒绝、强制模式退出码 173。 +篡改目标若被实际调用会 abort;因此测试不仅验证错误码,也验证没有执行被替换的目标。 + +两份业务源的 iphoneos arm64 `-O2` 对象检查:预期保护符号存在,所替换的 libc 未定义引用消失。 +专项七项和全套 83 项测试通过。宿主运行不能替代 App 真机页面测试。 + +标准构建 `readoor31 / iphoneos / Debug` 首次成功,但共享 `/private/tmp/readoor-derived` 后被原 readoor 工程覆盖, +其 info.plist 的 WorkspacePath 已改为原工程路径,二进制时间也晚于本次日志。 +最终验证改用独立 `/private/tmp/iosguard-gcd-derived-20261117`,不对被覆盖的产物作本轮结论。 + +最终二进制验证工具:`tools/macho_guard/verify_gcd_file_integration.py`。 +工具要求七个业务方法及对应保护入口的可核验符号存在,检查直接分支实际指向保护入口且不再直达对应系统 stub。 +未知或缺失符号报错,不能以零结果作为成功。工具检查的是列出的调用边,不是整个调用图。 + +独立完整构建已成功(readoor31 / Debug / iphoneos)。签名检查在沙箱内因证书信任失败, +在系统钥匙串访问权限下重验 codesign --verify --strict 通过。 +最终可执行文件检查确认七个方法的八条调用边全部指向保护入口,未再直达对应系统 stub。 + +构建与最终二进制证据归档于 `test-results/20261117-gcd-file-integration/`。 + +## 尚未覆盖 + +- App 内单词书页面的真机加载、网络上传、长时间性能和多机型误报测试。 +- readoor31OtherPay 整包构建和最终分发签名;本轮完整 App 构建目标为 readoor31。 +- 其余 SDK 调用点、exit/syscall/fork 的替代。 +- 保护层仍依赖运行时 API 和运行时采集的基线,不保证抵抗所有进程内篡改。 +- 既有 anti_tamper 不可用状态的业务策略问题未在本轮改动。 + +## multipart 流式上传接入 + +文件分段的创建、分块及尾块写入、关闭和清理改用受保护入口,共七个源码调用点。 +解析失败立即结束当前请求的解析并释放临时对象,保留失败文件的路径供清理;描述符 0 按合法值处理。 +新增测试使用真实 multipart 请求类,验证跨数据块内容、生命周期清理和写入被拒后的请求失败。 +全套测试 85 项通过,iOS arm64 优化对象确认 multipart 文件操作已引用保护层。 + +readoor31 的 iphoneos Debug 构建通过。成品验证确认 multipart 新增七条保护调用边,连同首批共十五条。下一轮仍需完成发布包和真机回归。证据见 test-results/20261117-gcd-multipart-integration/final-call-edges.json。 diff --git a/docs/22_ROUTE2_COMPLETE_REMEDIATION.md b/docs/22_ROUTE2_COMPLETE_REMEDIATION.md new file mode 100644 index 0000000..af9cdc1 --- /dev/null +++ b/docs/22_ROUTE2_COMPLETE_REMEDIATION.md @@ -0,0 +1,121 @@ +# 路线二全量合规整改记录(44 个 Mach-O 直接调用清零) + +- **日期**:2026-11-18 +- **目标**:在不删除任何第三方库、不注入自定义 Mach-O 可执行段(`__IGUARD`)、不使用裸 `svc #0x80`(保持 App Store 上架合规)的前提下,消除 `readoor-test`(`readoor31OtherPay`)在《ECNUP外语 IOS安全检测报告》(V4.6.6)中列出的全部 **12 项**高危/系统调用直接桩分支: + - **外部函数显式调用风险(3 项)**:`_fopen`(含 `_fopen$DARWIN_EXTSN`)、`_dlopen`、`_dlsym` + - **系统调用暴露风险(9 项)**:`_write`、`_read`、`_open`、`_close`、`_exit`、`_fork`、`_syscall`、`_unlink`、`_getpid` +- **最终产物**:`test-results/20261118-route2-complete/Payload/readoor31OtherPay.app`(44 个 Mach-O)与 `test-results/20261118-route2-complete/route2-adhoc.ipa` + +--- + +## 1. 整体架构与分工 + +1. **无 `dlsym` 的 Mach-O Export Trie 解析器(`defender/resolve/IGResolve.{h,c}`)** + - 新增 `ig_resolve_export_default(const char *bare_name)` 与 `ig_resolve_image_export(const char *image_suffix, const char *bare_name)`,直接解析已加载镜像的 `LC_DYLD_EXPORTS_TRIE` / `LC_DYLD_INFO(_ONLY)` 导出 Trie 并处理 Export Flag(Regular / Re-export / Stub-and-Resolver)与 `ptrauth` 签名。 + - `ig_resolve_export_default` 两趟扫描(Pass 0 优先查非系统动态库检测 `dyld interpose` / 注入抢占并跳过 `MH_EXECUTE` 与 `IGArchiveGuard`,Pass 1 在 `/usr/lib/`、`/System/`、`/private/preboot/Cryptexes/` 解析可信系统导出),取代原 `dlsym(RTLD_DEFAULT, ...)`。 + - `IGAntiHook.c` 中 `ig_check_provenance` 同步切换至 `ig_resolve_export_default`,从而消除 `IGResolve.o`、`IGAntiHook.o` 与 `IGArchiveGuard` 对 `_dlsym` 的未定义导入。 + +2. **11 入口运行时受保护调度表(`defender/dispatch/IGDispatch.{h,c}`)与探针收敛** + - 在原 7 入口(`write`、`close`、`read`、`open`、`unlink`、`getpid`、`fopen`)基础上扩展 `IG_DISPATCH_COUNT = 11`,新增: + - `IG_dispatch_exit`(`__attribute__((noreturn))`,校验失败/不可用时回退 POSIX `__exit` + `__builtin_trap()`) + - `IG_dispatch_fork` + - `IG_dispatch_dlopen` + - `IG_dispatch_dlsym` + - `checked_address` 标记 `__attribute__((noinline))`,配合 arm64 `-O2` 使 `IG_dispatch_dlopen`/`IG_dispatch_dlsym` 生成 `br` 尾调用以保留调用方 `LR`;新增 `__attribute__((constructor))` 预热函数 `ig_dispatch_warmup`。 + - `IGAntiTamper.c` 改用 `csops(0, ...)`(XNU 内核 `pid=0` 指向当前进程)消除 `_getpid` 导入;`IGAntiInject.c` 的 `close(fd)` 改为 `IG_dispatch_close(fd)`。 + +3. **业务源码直接调用点收敛(`readoor-test`)** + - `RDRuntimeDefender.swift`、`RDSecurityGuard.swift`:`dlsym(RTLD_DEFAULT, ...)` 改为 `ig_resolve_image_export("/IGArchiveGuard.framework/IGArchiveGuard", ...)`。 + - `RDJailbreakDetector.swift`:`close(sock)` 改为 `IG_dispatch_close(sock)`。 + - `RDRouterDebugTool.swift`:`getpid()` 改为 `IG_dispatch_getpid()`。 + - `GCDWebServer.m`、`GCDWebServerConnection.m`:经 `#if __has_include("dispatch/IGDispatch.h")` 映射 `RD_GWS_close/open/write/read/unlink -> IG_dispatch_*`(仅清理 C 函数直接调用,不动 `dispatch_read`/`dispatch_write` 与 ObjC 方法)。 + - `STSShaderHelper.m`:`exit(1)` 经 `RD_STS_exit` 映射到 `IG_dispatch_exit(1)`。 + +4. **全量静态 SDK 重定向与主二进制重链接(不覆写仓库原厂 SDK)** + - `tools/static_sdk_redirect/mappings/full_dispatch.json`(11 符号 `-> _IG_dispatch_*`)。 + - `tools/static_sdk_redirect/redirect_symbols.py` 与 `redirect_bitcode_members.py` 增加显式选择项 `allow_darwin_extsn=False`(仅开启时允许源键 `_fopen$DARWIN_EXTSN`,保持既有严格校验默认行为不变)。 + - `tools/static_sdk_redirect/prepare_route2_sdks.py` 针对 12 份 arm64 静态库生成哈希校验候选包(含 `TIWLogger` 与 `libspeechsdk.a` 的 `_syscall -> _IG_sdk_thread_selfid` 及 `libspeechsdk.a` 内置 bitcode 原地编译以消除 LTO 内联残留;并对 `libskegn-iphoneos.a` 的 7 个 `_fopen$DARWIN_EXTSN` 成员做二次定向至 `_IG_dispatch_fopen`),再由 `tools/macho_guard/link_with_sdk_inputs.py` 重链接,并用 `tools/macho_guard/profiles/main_residual_dispatch.json` 在主二进制内改写非静态归档 / Apple xar-bitcode / 工具链运行库调用点(`AlipaySDK`、`UMCommon`、`libclang_rt.ios.a`、`libswiftCompatibility56.a` 共 11 条规则)。 + +5. **14 目标 / 22 包装入口 `IGArchiveGuard.framework` 与全量动态库导入重定向** + - `IGArchiveGuard.{h,c}` 扩展至 14 个受检系统函数、22 个导出包装符号(`_ig_a0`..`_ig_a4`、`_ig_f`、`_ig_u00`、`_ig_o`/`_igo`、`_ig_r`/`_igr`、`_ig_w0`/`_ig_w`、`_ig_c0`/`_ig_c`、`_ig_p00`/`_ig_p0`、`_ig_e`、`_ig_k`、`_ig_l00`、`_ig_s0`/`_ig_s`)+ 3 个控制/评估接口(连同 `IGResolve.h` 显式导出共 27 个导出符号),`locate_bindings`/`check_bindings` 扩展为同时核验所有非系统 `MH_DYLIB` 的 `__got`(非惰性)与 `__la_symbol_ptr`(惰性,仅校验非 stub-helper 绑定槽)。 + - 构建时显式关闭代码覆盖率(`ENABLE_CODE_COVERAGE=NO CLANG_ENABLE_CODE_COVERAGE=NO CLANG_COVERAGE_MAPPING=NO CLANG_COVERAGE_MAPPING_LINKER_ARGS=NO`)彻底消除所有自建 Pod Framework 对 `libclang_rt.profile_ios.a` 的覆盖率引入。 + - `tools/macho_guard/package_route2_app.py` 统一打包:先对 3 个单架构 fat 包装动态库(`AliyunPlayer`、`AliyunMediaDownloader`、`alivcffmpeg`)执行 `lipo -thin arm64`,随后按加载器绑定格式分别调用 `redirect_framework_imports.py`(24 个 `LC_DYLD_CHAINED_FIXUPS` 动态库,含 `SSZipArchive` 5 入口)与 `redirect_legacy_imports.py`(6 个 `LC_DYLD_INFO(_ONLY)` 动态库:`ATAuthSDK_D`、`AliyunMediaDownloader`、`AliyunPlayer`、`STSExtension`、`TTNetworkManager`、`alivcffmpeg`;`lazy_bind` 记录偏移保持零位移,涵盖 `TTNetworkManager` 序号 10 -> 19 的 `SHRINK1_MAPPING`),连同 12 个无目标调用动态库(总计 42 个三方/Pod 动态库 + `IGArchiveGuard.framework` + 主程序 = 44 个 Mach-O),共改写 30 个动态库、零修改机器码与 section 字节,并重新生成 `RDKnownImages.plist`(44 条镜像 HMAC 白名单)。 + +--- + +## 2. 整改前后审计对比 + +| 维度 | 历史带覆盖率集成基线 (`20261118-integrated-app`) | 同次构建关闭覆盖率裸基线 (`Release`, 43 Mach-O) | Route 2 完整整改产物 (`20261118-route2-complete`, 44 Mach-O) | +| --- | --- | --- | --- | +| Mach-O 二进制总数 | 44 | 43 | **44** | +| 删除第三方库数 | 0 | 0 | **0** | +| 注入 `__IGUARD` 自定义段 | 无 | 无 | **无(0 个)** | +| 外部函数直接调用 (`_fopen`/`_dlopen`/`_dlsym`) | 489(168 / 2 / 319) | 476(162 / 2 / 312)+ 12 (`_fopen$DARWIN_EXTSN`) | **0(含 `_fopen$DARWIN_EXTSN` 为 0)** | +| 系统调用直接调用(其余 9 项) | 599 | 377 | **0** | +| 直接调用总计 | **1,088** | **853(含 `$DARWIN_EXTSN` 为 865)** | **0** | +| 嵌套及主包签名校验 (`codesign --verify --strict`) | 44/44(开发者签名) | — | **44/44(ad-hoc 严格校验通过)** | + +> 补充说明(如实陈述剩余静态表项): +> - 主可执行文件 `readoor31OtherPay` 通过后链接跳转表改写的 `AlipaySDK`/`UMCommon`/`libclang_rt.ios.a`/`libswiftCompatibility56.a` 保留未引用死桩及 `nm -u` 条目 `_dlsym`、`_fopen`、`_getpid`(`__text` 内 **0 处** `bl/b` 调用边指向它们);`IGDispatch.o` / `IGHookResponse.h` 的防篡改强制终止与 `exit` 兜底保留对 POSIX `__exit` 的调用(3 处)。 +> - `IGArchiveGuard.framework` 的 `nm -u` 不含 12 项报告符号中的任何一项。 +> - 本轮完成 macOS 宿主/工具链全量测试、iOS Release 编译重链接、全包 44 Mach-O 静态扫零及 ad-hoc 严格签名;如须安装真机验证或重签分发 IPA,可复用开发证书与描述文件(参考 `test-results/20261118-integrated-app/sign.sh`)后用 `devicectl` 执行实机验证。 + +--- + +## 3. 可复现构建与验证命令 + +```sh +# 1. 宿主与工具链全套单元测试 +python3 -m unittest discover -s /Users/shenlei/Work/ReadBook/iOSGuard/tests -p "test_*.py" + +# 2. 目标项目 readoor31 验证构建(AGENTS.md 默认门禁) +xcodebuild build -workspace /Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor.xcworkspace \ + -scheme readoor31 -sdk iphoneos -derivedDataPath /private/tmp/iosguard-readoor31-verify CODE_SIGNING_ALLOWED=NO + +# 3. readoor31OtherPay Release 构建(关闭代码覆盖率插桩) +xcodebuild build -workspace /Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor.xcworkspace \ + -scheme readoor31OtherPay -configuration Release -sdk iphoneos -derivedDataPath /private/tmp/iosguard-route2-release \ + ENABLE_CODE_COVERAGE=NO CLANG_ENABLE_CODE_COVERAGE=NO CLANG_COVERAGE_MAPPING=NO CLANG_COVERAGE_MAPPING_LINKER_ARGS=NO + +# 4. 生成静态 SDK 候选包与主二进制重链接 +python3 /Users/shenlei/Work/ReadBook/iOSGuard/tools/static_sdk_redirect/prepare_route2_sdks.py \ + /Users/shenlei/Work/ReadBook/iOSGuard/readoor-test \ + /Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261118-route2-sdk-inputs + +python3 /Users/shenlei/Work/ReadBook/iOSGuard/tools/macho_guard/link_with_sdk_inputs.py \ + /private/tmp/iosguard-route2-release.log \ + /Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261118-route2-sdk-inputs/sdk-inputs.json \ + /Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261118-route2-main-link \ + /Users/shenlei/Work/ReadBook/iOSGuard/readoor-test + +# 5. 全包打包、IGArchiveGuard 编译、30 个动态库重绑定、44 项白名单重签与零调用扫检 +python3 /Users/shenlei/Work/ReadBook/iOSGuard/tools/macho_guard/package_route2_app.py \ + --source-app /private/tmp/iosguard-route2-release/Build/Products/Release-iphoneos/readoor31OtherPay.app \ + --relinked-main /Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261118-route2-main-link/readoor31OtherPay \ + --app-repo /Users/shenlei/Work/ReadBook/iOSGuard/readoor-test \ + --output /Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261118-route2-complete +``` + +### 关键产物目录 +- `test-results/20261118-route2-sdk-inputs/`:12 份 arm64 静态 SDK 候选包、`IGThreadID.o` 与 `sdk-inputs.json` +- `test-results/20261118-route2-main-link/`:重链接主可执行文件、`LinkMap.txt`、`patch.json`、`gcd-file-edges.json`、`xcodebuild-release.log` +- `test-results/20261118-route2-complete/`:`Payload/readoor31OtherPay.app`、`route2-adhoc.ipa`、`route2-summary.json`、`route2-binaries.json`、`route2-callsites.csv`、`framework-rewrites.json` +- `test-results/20261118-xcode-archive-verification/`:Xcode 默认 Archive 双 Target(`readoor31` 40 Mach-O、`readoor31OtherPay` 44 Mach-O)审计清单与汇总 `summary.json` + +## Xcode 默认 Archive 流程集成(双 3.0 主 Target) + +为消除手工多步后处理,已将 Route 2 全流程直接融合进 `readoor31` 与 `readoor31OtherPay` 的 Xcode 默认 `Release` + `iphoneos` Archive 构建(`Debug` 配置保持零改动): + +1. **自包含工具链(`readoor-test/iOSGuardIntegration/toolchain/`)** + - 独立同步 `IGThreadID.c`、Route 2 静态重定向 / Mach-O 重绑定 / 基线扫检脚本及配置,兼容 Xcode `/bin/sh` 默认 `/usr/bin/python3`(3.9+)。 + - 新增 `tools/xcode_archive/ig_ld_wrapper.py`、`ig_guard_frameworks_phase.py` 与 `route2_archive_common.py`。 +2. **链接器包装(`ALTERNATE_LINKER_PATH[sdk=iphoneos*]`)** + - Xcode 在链接可执行文件时通过 `clang++ --ld-path=.../ig_ld_wrapper.py` 调用链接器;对非 `.app` / `-r` / `-dylib` / `-bundle` / `-preload` 链接直接 `os.execv` 透传真实 `ld`。 + - 对主 App `Release` arm64 链接:基于源码与 Tool 哈希在 `Intermediates.noindex/ig-route2-sdk-cache/` 进程加锁复用(双 Target 共享同一份静态 SDK 重定向缓存)按 Target 实际链接项替换静态库、`IGThreadID.o` 与 `-F `,并在 `real_ld` 产出 Link Map 后筛选命中该 Target 的 `main_residual_dispatch.json` 规则完成主程序残余调用修补与 0 调用门禁校验(同时拒绝接入 `clang_rt.profile_` 覆盖率运行时)。 +3. **动态库重绑定与整包审计 Build Phase(`IG Route 2 Guard Frameworks & Audit`)** + - 位于 `[CP] Embed Pods Frameworks` 之后、`Generate Image Whitelist` 之前(仅 `CONFIGURATION == Release` 且 `PLATFORM_NAME == iphoneos` 执行)。 + - 分步编译 `.o` 后生成 `IGArchiveGuard.framework` 及 `IGArchiveGuard.framework.dSYM`(再执行 `strip -x`,并从宿主 `Info.plist` 继承 `DT*`/`UIDeviceFamily` 等上架元数据),随后幂等瘦身与重绑定嵌入动态库、在启用签名时用 `EXPANDED_CODE_SIGN_IDENTITY` 重签变更模块、执行整包 0 直接调用 / 0 `$DARWIN_EXTSN` 桩扫检,最后由 `Generate Image Whitelist` 生成包含 `IGArchiveGuard` 的 `RDKnownImages.plist`。 +4. **双 Target 验证结论与回滚开关** + - 幂等脚本:`ruby readoor-test/scripts/integrate_route2_archive.rb`。 + - `xcodebuild archive -configuration Release -destination generic/platform=iOS` 实测:`readoor31` 全包 `40` 个 Mach-O(静态命中 7 项、主程序规则 9 条 / 18 处、动态库重写 29/38、白名单 40 项、dSYM UUID 匹配、Ad-Hoc `codesign --verify --strict` 40/40)与 `readoor31OtherPay` 全包 `44` 个 Mach-O(静态命中 11 项、主程序规则 11 条 / 25 处、动态库重写 30/42、白名单 44 项、dSYM UUID 匹配、Ad-Hoc `codesign --verify --strict` 44/44)均一次 `ARCHIVE SUCCEEDED`,`external_call_total=0`、`system_call_total=0`。 + - 紧急回滚:构建环境设置 `IG_DISABLE_ROUTE2_ARCHIVE=1` 可无损旁路,无需修改 `project.pbxproj`。 diff --git a/docs/23_LLVM_IR_OBFUSCATION_PLAN.md b/docs/23_LLVM_IR_OBFUSCATION_PLAN.md new file mode 100644 index 0000000..a1c4504 --- /dev/null +++ b/docs/23_LLVM_IR_OBFUSCATION_PLAN.md @@ -0,0 +1,261 @@ +# Readoor + iOSGuard + iOSBuildServer 编译级代码混淆与加固方案 + +> **文档状态**:已全量落地并通过双 Target 真机投产验收(Production-Verified Final Spec, M0–M3 Completed) +> **当前阶段定位**:已完成 L1(源码级符号/方法混淆 `obfuscate_symbols.py`)+ L2(LLVM IR `IGStringCryptPass` / `IGControlFlowFlattenPass` + `ig_cc_wrapper.py` / `ig_ld_wrapper.py`)+ L3(Route 2 40/44 Mach-O 系统调用间接化与运行时完整性守护)全链路集成、`iOSBuildServer`(`feat/llvm-obf-m3`)投产对接,以及 `readoor31`(40 Mach-O)与 `readoor31OtherPay`(44 Mach-O)在物理真机 `iPhone 16 Plus` 上的全量回归验收。 +> **适用范围**:`iOSGuard`(混淆与加固底座)、`readoor-test`(宿主业务工程 `feat/llvm-obf-m0`)、`iOSBuildServer`(自动化打包平台 `feat/llvm-obf-m3`) + +--- + +## 1. 设计目标、客观边界与总体架构 + +### 1.1 安全目标与职责边界划分 + +本方案严格区分“客户端逆向对抗”与“服务端内容/权益鉴权”两类职责: + +1. **客户端代码混淆与加固目标(本方案范围)**: + - **拔除静态定位路标**:清理最终二进制中可直接交叉定位核心业务入口的明文盐值、语义化错误日志、调试队列名、宿主机源码路径及历史双轨残留代码; + - **抬高控制流分析与补丁篡改成本**:通过版本种子驱动的多形态控制流改写与受控常量加密,增加静态反编译理解难度,降低单一规则去平坦化脚本及跨版本 `BinDiff` 的直接复用率; + - **动静防线联动**:与已验收的 **Route 2 系统调用收敛**、**`IGDefender` 运行时检测** 及 **`RDEpubKeyGuard` 内联密钥毒化** 配合,压缩静态直读与动态系统 API 挂钩两条低成本路径。 +2. **付费内容防盗与防伪请求边界(服务端协同方向)**: + - 客户端本地参与计算的密钥材料(如离线签名私钥解密派生参数、固定规则书籍密钥),客户端混淆仅能消除静态明文并拉长逆向周期,**无法替代服务端秘密保护**; + - 防止篡改客户端后获取付费内容的高收益措施,是由服务端独立验证用户权益并按会话/单书下发短期凭据,同时对登录、验单、凭据获取等高价值请求结合 Apple **App Attest** 验证客户端实例合法性。 + +--- + +### 1.2 本机实测事实与统一独立 `opt` 架构 + +基于本机 Xcode 27.1(`swiftlang-6.4.0.34.1`、`ld-27037.1`、`iPhoneOS27.1.sdk`)的命令级实测结论: +- **链接器约束**:Xcode 27 已移除 `-ld_classic`;`ld_prime` 通过 Mach-O `LC_LOAD_DYLIB` 在进程启动期直接加载工具链自身的 `@rpath/libLTO.dylib`,不再根据 `-lto_library` 参数动态 `dlopen` 外部路径(且拒绝非 `libLTO.dylib` 文件名)。因此**不采用替换 `libLTO.dylib` 的路线**; +- **Swift Bitcode 产出条件**:必须在 **Swift Driver 层**传入 `-lto=llvm-thin`(不可置于 `-Xfrontend` 后),Driver 才会调度 `swift-frontend -emit-bc` 产出 LLVM Bitcode wrapper 格式的 `.o`; +- **C 编译链两步降级实测**:对工程内 [IGDefender](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Base/Security/IGDefender) 目录下的 11 个 C 文件实测,`clang -Os -emit-llvm -c` 配合后端 `clang -Os -Xclang -disable-llvm-passes -x ir -c`(跳过重复的第二轮中端 IR Pass、保留后端寄存器分配优化)产出的 `__TEXT` 段体积与原装一步编译均为 `24,447 bytes`(注:该 `+0 bytes` 结论仅覆盖上述 C 样例;Swift 经独立 `opt` 转换后的体积与性能变化必须在 Milestone 0 原型中专项实测)。 + +据此,方案将 Swift 与 OC/C/C++ 统一收敛至**单一独立 `opt` 工具(静态编入 `IGObfuscator` Pass)+ 原装 Xcode 编译/链接链**: + +```mermaid +flowchart TD + subgraph L1["第一层:编译前调用链线索清理与符号改名 (仅作用于打包副本)"] + C1["调用链线索清理 (事件码替代明文日志 / 收口双轨代码 / 路径映射)"] + C2["修复版 obfuscate_symbols.py (自然词根重命名 + NSCoding 豁免)"] + end + + subgraph L2["第二层:统一独立 opt 双通道 IR 转换与混淆 (Release iphoneos)"] + direction LR + OC1["OC / C / C++ 源码"] --> OC2["ig_cc_wrapper.py (Stage 1: 原装 clang -Os -emit-llvm)"] + OC2 --> OC3["Stage 2: 独立 opt 执行 IGObfuscator"] + OC3 --> OC4["Stage 3: 原装 clang 继承平台参数 -disable-llvm-passes -x ir -c"] + + SW1["Swift 源码"] --> SW2["原装 swiftc -O -g -lto=llvm-thin (产出 Target Bitcode .o)"] + SW2 --> SW3["ig_ld_wrapper.py 取 (Target Swift 输出清单 ∩ LinkFileList) 识别目标"] + SW3 --> SW4["独立 opt (执行目标版本验证通过的协程降级 + IGObfuscator)"] + SW4 --> SW5["原装 clang 继承 triple/SDK/部署版本 -disable-llvm-passes -x ir -c"] + end + + subgraph L3["第三层:Route 2 系统调用收敛 + 双重产物门禁"] + OC4 --> LD["原装 Apple ld (按剩余输入决定是否保留 LTO 参数)"] + SW5 --> LD + LD --> R2["Route 2 静态 SDK 重写 + 主二进制残余补丁 + 动态库注入 IGArchiveGuard"] + R2 --> GATE["双重发布门禁 (1. 必命中目标非零且改写留存 2. Route 2 外部敏感调用 0 直连)"] + end + + L1 --> L2 +``` + +--- + +## 2. 核心设计:线索清理、Pass 语义边界与多态改写 + +### 2.1 沿核心业务调用链清理交叉定位线索 + +以最终二进制的静态交叉引用(Xref)检查为准,优先拔除三大核心调用链上的明文路标,同时保留内部故障诊断能力: + +| 业务调用链 | 源码核查确认的暴露线索 | 整改措施与验收口径 | +| :--- | :--- | :--- | +| **1. EPUB 解密调用链**
([RDEpubReaderLauncher.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Features/ReadView/Epub/RDEpubReaderLauncher.swift) -> [RDEncryptedEpubResourceProvider.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Features/ReadView/Epub/RDEncryptedEpubResourceProvider.swift) / [STSEpubWebResourceLoader.m](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/BookView/EPUB/Core/Classes/newEpub/URLProtocol/STSEpubWebResourceLoader.m)) | 1. 新版 Swift [RDEncryptedEpubResourceProvider.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Features/ReadView/Epub/RDEncryptedEpubResourceProvider.swift#L41-L73) 与旧版 OC `STSEpubWebResourceLoader.m:23-104` 同时存有 `"startiasoft"` 明文盐与重复推导公式;
2. 两处末尾均通过 ObjC 选择子调用预编译库 [StsSimpleCrypt.h](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/BookShelf/Classes/Factorys/StsFcLib/StsSimpleCrypt.h#L22) 的 `sfc_SimpleDeCrypt:pass:`。 | 1. 新旧两处密钥推导统一收口至单一 C 模块 `RDEpubKeyBox.c`(使用模块私有字节数组存储材料并衔接 [RDEpubKeyGuard.c](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Base/Security/RDEpubKeyGuard.c) 内联毒化),删除 Swift/OC 层明文盐;
2. 收敛 `StsSimpleCrypt` 调用点至单一内部封装,减少多处 Selector 交叉引用暴露。 | +| **2. SD 3.2 私钥与签名调用链**
([RDSDAuthV32Signer.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Network/RDSDAuthV32Signer.swift) -> [RDSDPrivateKeyManager.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Network/RDSDPrivateKeyManager.swift#L25-L108)) | 1. 明文 PBKDF2 参数 `"readoor_sd_v32_ci_key_2026"`、`"readoor_sd_v32_salt_fixed"`;
2. 队列标签 `"com.readoor.sdauthv32.privatekey"` 与资源名 `"encrypted_private_key.bin"`;
3. 4 条带类名与算法名的中文错误日志。 | 1. PBKDF2 材料改由受控 C 字节数组提供并交由 IR 加密;
2. 队列名与包内资源文件名改为无业务语义的中性名称(Keychain 键名 `"KSDPrivateKeyPEM"` 保持值兼容以保障老用户升级直读);
3. 生产诊断日志统一替换为稳定事件编号(如 `E-4101`~`E-4104`),离线维护映射表保障排障。 | +| **3. 安全守卫与编译路径残留**
([RDSecurityGuard.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Base/Security/RDSecurityGuard.swift#L80-L83)) | 1. `RDSecurityGuard.swift:80-83` 手写字符串 `"RDLoginView"`、`"submitButtonTap"`,源码改名后会失配;
2. 二进制断言/调试表可能残留宿主机路径 `/Users/...`。 | 1. 改为 `NSStringFromClass` 与 `#selector` 编译期推导。**验收口径**:源码重命名后运行期 `IGObjCBaseline` 仍准确完成 `2/2` 条 IMP 基线登记(注:ObjC 运行时仍需保留混淆后符号的 selector 元数据,不承诺对 selector 元数据做 IR 加密);
2. 全局启用 `-ffile-prefix-map=${SRCROOT}=.` 与 Swift `-file-prefix-map ${SRCROOT}=.`。 | + +--- + +### 2.2 独立 `opt` 构建规范与 Pass 语义安全边界(`iOSGuard/llvm_passes/`) + +M0 首次构建先选定与本机 Swift 工具链对应的候选 LLVM 提交,将仓库地址、完整 commit SHA、Xcode Build、CMake 和 Ninja 版本写入构建清单。后续构建按 SHA 检出并核对 HEAD。候选提交通过 Swift 和 OC bitcode 的独立 opt 空操作读写、原装 Clang 回读及 M0 Archive 后,才能加入已验证工具链清单。当前兼容提交待原型实测。 + +构建机准备 CMake、Ninja 和输出目录后,通过全大写 LLVM_EXTERNAL_IGOBFUSCATOR_SOURCE_DIR 配置独立 Pass 工程。 + +```bash +cmake -G Ninja -S llvm-project/llvm -B build-igopt \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_OSX_ARCHITECTURES="arm64" \ + -DCMAKE_OSX_DEPLOYMENT_TARGET="13.0" \ + -DLLVM_TARGETS_TO_BUILD="AArch64" \ + -DLLVM_ENABLE_ZSTD=OFF \ + -DLLVM_ENABLE_TERMINFO=OFF \ + -DLLVM_ENABLE_LIBXML2=OFF \ + -DLLVM_ENABLE_LIBEDIT=OFF \ + -DLLVM_INCLUDE_TESTS=OFF \ + -DLLVM_INCLUDE_BENCHMARKS=OFF \ + -DLLVM_EXTERNAL_PROJECTS="IGObfuscator" \ + -DLLVM_EXTERNAL_IGOBFUSCATOR_SOURCE_DIR="/Users/shenlei/Work/ReadBook/iOSGuard/llvm_passes" \ + -DLLVM_IGOBFUSCATOR_LINK_INTO_TOOLS=ON + +ninja -C build-igopt opt +mkdir -p dist +strip -x build-igopt/bin/opt -o dist/opt +codesign --force --sign - dist/opt +``` + +#### 1. 字符串与字节常量加密准入边界(消除常量对象后备存储矛盾) +为避免“门闩外直读后备存储”或破坏运行时元数据,首版严格收紧候选准入范围: +- **强制豁免范围(绝不改写)**: + 1. 任何带显式运行时/元数据 Section 的全局变量(`__objc_*`、`__swift5_*`、`llvm.metadata` 等); + 2. **所有常量对象后备存储**(包括被 `__DATA,__cfstring` `CFString` 结构体、Swift 静态对象头或其他全局变量静态初始化器 Constant Initializer 引用的底层字节),以及含 `GlobalAlias` 别名的全局变量——此类对象可被系统库在门闩之外直接读取,一律豁免; +- **合法接纳范围(仅限读取路径 100% 受控的候选)**: + - 仅接纳模块内部链接属性(`private` / `internal`)、无静态常量结构体引用、且经 Use-Def 分析证明**所有读取指令均位于当前模块可改写函数内**的纯 C 字符串或字节数组全局变量(对于原本写成 `@"..."` / Swift 字面量的高敏常量,需先在源码/C 封装层转为局部字节数组或受控 C 函数加载,再由 Pass 加密): + - *指针不逃逸场景*:在当前函数栈帧按需还原,返回前清零; + - *指针跨调用保留场景*:所有读取点统一改写为经过三态原子初始化门闩(`0=未初始化 -> 1=还原中自旋等待 -> 2=已完成`,配 `acquire/release` 屏障)访问模块私有缓冲区; +- **防合成外部调用**:还原循环插入编译器优化栅栏并配合后端 `-fno-builtin`,并在最终 Mach-O 上实测验证未引入 `_memcpy` 或任何违反 Route 2 门禁的外部符号。 + +#### 2. 种子驱动的多形态控制流改写与可复现范围 +- **函数级差异化**:通过 `HMAC_DRBG(ReleaseSeed, ModuleID + FunctionName)` 为选定函数在多种分发拓扑(稀疏 `switch` 分发、多子分发器切换、非对称条件比较树)与状态编码(异或旋转、奇素数仿射变换)间伪随机选择,避免所有函数生成单一星型模板; +- **可复现性准确定义**:在相同源码、相同 Xcode 与 `opt` 工具链、相同构建参数及相同 `ReleaseSeed` 下,保证 **`opt` Pass 改写后的 IR 与单个目标文件(`.o`)编译产物确定性可复现**;更换 `ReleaseSeed` 后,必须通过反汇编对比验证目标函数的机器码与控制流拓扑发生实质变化(注:最终签名 `.ipa` 包含签名时间戳与归档容器元数据,不将“整包 IPA 字节一致”作为承诺指标)。 + +#### 3. 异常、Swift 协程与底层桩安全规则 +- **异常展开豁免**:含 `InvokeInst` / `LandingPadInst` / `CleanupRetInst` 的函数首版跳过控制流平坦化与虚假块插入; +- **Swift 协程实测准入**:Swift `async/await` 生成的 Bitcode 含 `%llvm.coro.*` 内建指令。目标分支 `opt` 必须通过**跨文件、`async throws`(含挂起恢复函数、任务取消与异常抛出路径)**的真机测试样例验证其完整协程降级流水线与 `.dSYM` 行号映射,未经验证通过前不对含协程内建指令的函数启用控制流改写; +- **守卫桩豁免**:`IGDefender` 信号安全处理函数、内联汇编函数及 `ig_call_*` 桥接层强制豁免。 + +--- + +### 2.3 性能与体积待测预算(Target Budgets) + +所有性能与体积指标均列为**待测目标预算**,以**同一台测试真机(指定机型与 iOS 版本)、同一份未开启 IR 混淆的 `readoor31` Release Archive** 为对照基线实测验收: +- **Tier 0(`Pods/**`、`Vendor/**`、`IGDefender/call_bridge/**`、高频列表与排版渲染路径)**:不执行 IR 改写; +- **Tier 1(核心调用链上下游封装)** & **Tier 2(EPUB/PDF 密钥、SD 签名、IAP 验单、安全策略核心函数)**: + - *体积预算*:主二进制 `__TEXT` 增量与最终压缩 `.ipa` 增量控制在 **待测预算 `<= 1.5 MB`**; + - *延迟预算*:加密 EPUB 首章打开耗时及连续翻页 50 次的 P50 / P95 延迟相比基线退化 **待测预算 `<= 5%`(且无肉眼可感知卡顿)**。 + +--- + +## 3. 准确的对象识别、平台参数继承与无残留回滚体系 + +### 3.1 OC / C / C++ 编译包装器(`ig_cc_wrapper.py` & `ig_cxx_wrapper.py`) + +1. 预编译头(`-x *-header`)、预处理(`-E`/`-M`)或关闭 IR 混淆模式时原样透传原装 `clang`; +2. 命中保护范围时: + - Stage 1:原装 `clang` 保留原 `-Os`/`-O2`、`-g`、`-target`、`-isysroot`、`-include *.pch`、`-MF *.d`、`--serialize-diagnostics *.dia`,加 `-emit-llvm -c` 输出 `.bc`; + - Stage 2:独立 `opt` 按策略与 `IG_LLVM_PASS_FILTER` 执行改写; + - Stage 3:原装 `clang` **完整继承 Stage 1 解析出的 `-target`(含部署版本)、`-isysroot`、`-miphoneos-version-min`、栈保护与 ABI 参数**,附加 `-Os -Xclang -disable-llvm-passes -fno-builtin -g -x ir -c` 生成原生 `arm64` Mach-O `.o`。 + +### 3.2 Swift 目标对象精确交集识别与平台参数继承(升级 [ig_ld_wrapper.py](file:///Users/shenlei/Work/ReadBook/iOSGuard/tools/xcode_archive/ig_ld_wrapper.py)) + +修正“仅凭文件魔数盲扫 `LinkFileList` 及无条件剔除 LTO 参数”的缺陷: + +1. **精确确定待转换的 Swift 对象集合**: + - Release (`sdk=iphoneos*`) 通过 Xcode 原生 `SWIFT_LTO[sdk=iphoneos*] = YES_THIN`(而非硬编码 `-Xfrontend`)开启 Bitcode 产出,并在总熔断/关闭时切回 `NO`;实测 Xcode 27 开启 `SWIFT_LTO=YES_THIN` 时会在 `-OutputFileMap.json` 中同时写入 `"llvm-bc"`(`.bc`)与 `"object"`(`.o`)条目,且 `.LinkFileList` 传入的是 `.bc` 路径; + - 从当前 Target 的 `*-OutputFileMap.json` 读取 `"llvm-bc"` / `"object"` 归属映射,与 `LinkFileList` 求交集后再校验 Bitcode 魔数与策略保护范围;覆盖分文件编译与全模块优化(WMO)的输出布局,未识别或跳过的输入明确记录原因。 +2. **精确继承平台与 ABI 参数**: + - 从 Bitcode 模块自身的 `TargetTriple` / `SDK Version` 元数据及当前 `ld` 命令行中的 `-platform_version ios `、`-syslibroot ` 提取精确参数,向后端 `clang -x ir -c` 显式传递 `-target arm64-apple-ios`、`-isysroot ` 等完整目标平台标志; + - 转换后校验生成的 `.o` 含合法的 `LC_BUILD_VERSION`(`platform = IOSSIMULATOR/IOS`, `minos`, `sdk` 与同 Target 原生对象一致); +3. **保序替换与按需保留 LTO 链接参数**: + - 在新生成的 `LinkFileList.ig` 中**仅原位保序替换已成功转换的条目**; + - 扫描替换后剩余的全部链接输入(其他 `.o` 与静态库成员):若剩余输入中仍存在未转换的 Bitcode 对象,**完整保留**原 `ld` 命令中的 `-flto=thin`、`-lto_library`、`-cache_path_lto`、`-object_path_lto` 参数;仅当全部链接输入均为原生 Mach-O 时才省略 LTO 标志; + - 在审计报告中如实记录 `expected_swift_count`、`converted_count`、`skipped_count`。 + +--- + +### 3.3 防零命中门禁、Xcode 可见指纹与三档无残留回滚 + +#### 1. 防止“工具链存在但零函数命中(Silent Zero-Hit)” +- 在 `ig_llvm_policy.json` 中定义 `required_targets`(必命中目标清单:Milestone 0 指定 Swift 与 OC 各至少 1 个测试目标;投产策略指定各核心调用链的关键入口符号/特征); +- 对象缓存同时落盘 `.o` 与对应的 `.audit.json`(记录该对象内实际改写的函数名、应用的 Pass 与常量数),确保**命中缓存时审计数据不丢失**; +- 链接收尾按有效模式核对缓存或本次生成的对象审计和最终 Mach-O。M0 空操作要求 Swift 与 OC 均实际经过转换、业务改写数为零。full 和 str 分别校验该模式启用的每个必选目标和对应产物特征,任一缺失则构建失败。off 和总熔断允许零命中,验收已知测试函数恢复基线。 + +#### 2. 让策略与开关变化对 Xcode 增量构建系统(`llbuild`)100% 可见 +单纯修改外部 JSON 或环境变量不会自动触发 Xcode 重跑 `CompileC` 或 `Ld`。解决方案: +- 在调用 xcodebuild 前生成本次构建使用的 xcconfig。先解析有效配置:总熔断优先;旧 IG_DISABLE_ROUTE2_ARCHIVE=1 只关闭 Route 2。编译、链接和 Framework 阶段共享同一份有效配置。IG_BUILD_STAMP 对有效 IR 模式(含测试空操作)、Pass 过滤器、Route 2 模式、总熔断状态、工具及包装器摘要、策略摘要和种子求哈希。关闭 IR 时使用固定的停用标识,可在缺少 opt 时回滚。 +- xcconfig 将摘要写入 C 和 Swift 编译参数;在目标中加入引用该宏的编译单元作为真实链接输入,使摘要变化重编该对象并触发重链接。M0 以构建日志确认摘要变化会重新调度 Ld。Framework 阶段显式读取同一配置;从开启切至关闭时须重新嵌入原始框架,并移除前次构建生成的守卫产物。 +- 同步修复 [ig_ld_wrapper.py](file:///Users/shenlei/Work/ReadBook/iOSGuard/tools/xcode_archive/ig_ld_wrapper.py#L98-L116) 的 `compute_sdk_fingerprint()`,将 `Xcode Build 号 + SDK 版本 + wrapper_sha256` 纳入 Route 2 静态 SDK 缓存键;`opt` 对象缓存键纳入 `input_bc_sha256 + IG_BUILD_STAMP + effective_backend_flags + xcode_build + sdk_ver`。 + +#### 3. 职责清晰的三档回滚开关与不 Clean 连续切换验收 +明确区分三个独立控制维度,消除“只关了一半”的歧义: + +| 开关配置 | C/OC 编译期 (`ig_cc_wrapper`) | Swift 预链接 (`ig_ld_wrapper`) | Route 2 收敛与动态库注入 | 适用场景 | +| :--- | :--- | :--- | :--- | :--- | +| **`IG_OBF_MODE=full`**(默认) | 执行完整策略 Pass | 执行完整策略 Pass | 开启 | 正常混淆加固出包 | +| **`IG_OBF_MODE=str`**(或 `IG_LLVM_PASS_FILTER=str`) | 仅执行受控字符串加密,关闭控制流改写 | 仅执行受控字符串加密,关闭控制流改写 | 开启 | 排查控制流改写引发的性能或边界问题 | +| **`IG_OBF_MODE=off`** | 原装编译直通 | 撤回本方案附加的 Swift LTO 参数,原生对象直通 | 开启 | 回到既有 Route 2 基线 | +| **`IG_ROUTE2_MODE=off`** | 按 `IG_OBF_MODE` 执行 | 按 `IG_OBF_MODE` 执行 | **旁路 Route 2 静态库替换、主二进制补丁与动态库注入** | 单独排查系统调用收敛问题 | +| **`IG_ALL_GUARD_OFF=1`**(总熔断) | **100% 原装 `clang` 直通** | **100% 原装链接直通** | **全部旁路** | 一键彻底回退纯原装 Xcode Archive | + +> **回滚硬验收标准**:同一 DerivedData 内不 clean,依次执行 full → str → off → 总熔断,再单独测试 IR 开启、Route 2 关闭。逐次检查 Swift/OC 测试函数、主程序 Route 2 改写、嵌入框架与守卫产物,并核对构建日志中的编译、重链接与嵌入动作。 + +--- + +## 4. 符号混淆修复、`iOSBuildServer` 对接与双格式崩溃还原 + +### 4.1 `obfuscate_symbols.py` 五项修复与历史归档回归 +1. **豁免 `NSCoding` / `NSSecureCoding` 归档类**:自动识别并豁免 [STSPayOrderInfoObject](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/BookShelf/Classes/Features/IAP/Handler/STSIAPKeyChainHandler.m#L140-L150)、`RBCorePenLineData`、`STSPaintModel` 等持久化模型;**回归要求**:使用上一生产版本真实生成的订单与批注归档数据执行覆盖安装解档验证; +2. **修复双反斜杠正则**:修正 `obfuscate_symbols.py` 第 `833`、`1035` 行的 `r"\\boverride\\b|\\bdynamic\\b"` 为单反斜杠; +3. **跳过字符串字面量替换**:词法扫描跳过单/多行字符串字面量、注释与 `import`/`#import` 语句; +4. **自然词根确定性生成**:按种子生成自然驼峰词组,修正 `obfuscation_self_check.sh` 大小写规则; +5. **统一映射表格式**:规范 `symbol_map_*.json` 与 `method_map_*.json` 输出结构,同步更新至 `readoor-test` 与 `iOSBuildServer`。 + +### 4.2 多机工具链匹配与 `iOSBuildServer` 对接 +1. **工具链清单精确绑定**:`config/toolchain_manifest.json` 按 **`已验证 Xcode Build 号 + 主机架构 (arm64) + opt 二进制 SHA256`** 精确匹配(LLVM 主版本仅用于构建脚本拉取源码分支初筛);`iOSBuildServer` 对要求执行 IR 改写的发布任务设置 `IG_REQUIRE_LLVM_OBF=1`,未命中已验证工具链立即失败。显式 IR 关闭与总熔断任务跳过 opt 解析,并记录实际发布模式; +2. **`iOSBuildServer` 三处修改**: + - [config.py](file:///Users/shenlei/Work/ReadBook/iOSBuildServer/backend/config.py#L105-L115) 与 [projects.py](file:///Users/shenlei/Work/ReadBook/iOSBuildServer/backend/projects.py#L57-L69) 的 `COPY_ITEMS` 补入 `"iOSGuardIntegration"`(兼容已有 `data/config.json` 自动补拷); + - [build_service.py](file:///Users/shenlei/Work/ReadBook/iOSBuildServer/backend/services/build_service.py#L676) 的 `shutil.copytree` 补齐 `symlinks=True`; + - [build_service.py](file:///Users/shenlei/Work/ReadBook/iOSBuildServer/backend/services/build_service.py#L984-L1026) 注入持久化缓存路径与 `IG_OBF_MODE`,归档 `.dSYM`、符号映射表、事件码表与 `ig_obfuscation_audit.json`;针对其每任务执行 `xcodebuild clean` 的现状,分别实测记录**冷构建**与**热缓存构建**耗时。 + +### 4.3 区分 `.ips`(JSON)与 `.crash`(文本)的崩溃符号化还原 +`tools/crash_restore/restore_crash_report.py` 分别实现两种 Apple 崩溃格式解析器: +1. **现代 JSON `.ips` 解析器**:跳过首行摘要 JSON 头,解析主体 JSON 的 `usedImages[]`(获取各镜像 `uuid`、`base` 加载基址、`arch` 与路径)及 `threads[].frames[]`(通过 `imageIndex` 关联镜像,以 `base + imageOffset` 计算待符号化地址); +2. **传统文本 `.crash` 解析器**:解析堆栈行运行期地址与底部 `Binary Images:` 段落的起止基址及 ``; +3. **严格 UUID 校验与符号化**:对主二进制及应用内嵌 Framework 分别校验 `.dSYM` UUID 一致后,调用 `atos -arch arm64 -o -l -inlineFrames` 还原源码行号,再串联 `symbol_map` 与 `method_map` 还原重命名前符号。**验收要求**:使用各一份包含**主程序帧 + 内嵌 Framework 帧**的真实 `.ips` 与 `.crash` 报告完成还原验证。 + +--- + +## 5. 演进里程碑与逐级准入门禁 + +将“真实 `readoor31` Archive 端到端转换、改写留存、符号化与不清缓存回滚验证”提前为最高优先级的 **Milestone 0**,通过后再开展业务盲测与扩面: + +### Milestone 0:编译转换链空操作与单点闭环原型验证(第一优先级) + +在不改动业务逻辑的前提下,于本机 Xcode 27.1 上打通 `llvm_passes/`(最小单 Pass)+ `ig_cc_wrapper.py` + `ig_ld_wrapper.py`,对真实 `readoor31` Target 依次执行三步同配置对照: + +1. **M0-1 原装基线构建**:当前 Release Archive(含既有 Route 2,对照 [summary.json](file:///Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261118-xcode-archive-verification/summary.json) 的 40 Mach-O 基线),记录构建耗时与体积,归档 Swift 输出映射、实际编译任务和 LinkFileList; +2. **M0-2 转换链空操作(No-Op Pass)对照**:Swift 与 OC 均完整走通 `Bitcode -> 独立 opt(空操作) -> clang -x ir -> ld` 转换链,验证: + - 单独由“对象转换链”引入的耗时与二进制体积变化; + - 跨文件 Swift `async throws`(含恢复、取消、抛错路径)在转换后 `LC_BUILD_VERSION` 正确、真机正常/异常路径运行正确; +3. **M0-3 指定单点改写 + 符号化 + 不清缓存连续回滚门禁**: + - Swift、OC 各设一个必选测试函数。在开启模式跑正例,再故意使其中一个必选目标失配,验证单语言漏处理也会阻断。恢复配置后确认两处改写均留存,Route 2 保持 external=0、system=0; + - 构造包含主程序帧与 Framework 帧的真实 `.ips` / `.crash`,经 `restore_crash_report.py`(`atos -o`)精确还原至源码行号; + - 在同一 `DerivedData` **不执行 `clean`** 条件下连续切换 `full -> str -> off -> IG_ALL_GUARD_OFF=1`,逐次验证最终 Mach-O 精确回退、无缓存残留。 + +### Milestone 1:EPUB 调用链分层对照盲测与种子多态验证 + +Milestone 0 通过后,围绕 EPUB 解密调用链分步叠加变量,量化每一层的真实成本与防护收益: +- **轮次 1(转换链基线 vs 仅多态平坦化 vs 平坦化 + 调用链线索清理)**:每次仅叠加一层变更,记录静态可定位线索清单、内部匿名盲测(定位入口耗时、输入输出关系理解准确率、所借用的残留线索)以及真机首章打开/连续翻页 50 次 P50/P95 延迟; +- **轮次 2(种子变化复现验证)**:固定组 C 源码与配置,验证相同 `ReleaseSeed` 单对象产物可复现;更换 `ReleaseSeed` 后对比目标函数的机器码与控制流图拓扑变化。 + +### Milestone 2:SD 3.2 签名与 IAP 验单调用链推广 + +将 Milestone 1 实测证明有效的组合推广至 SD 3.2 签名与 IAP 验单链路: +- 落地生产诊断事件码映射与参数下沉; +- 在真机上分别验证 **① 全新安装(无 Keychain)**、**② 老版本覆盖升级(已有 `KSDPrivateKeyPEM`)**、**③ 清空 Keychain 后恢复** 三条路径的签名正确性。 + +### Milestone 3:符号混淆合并、`iOSBuildServer` 投产与双 Target 全量回归 + +- 合并修复版 `obfuscate_symbols.py`,使用上一生产版本真实订单与批注归档验证覆盖安装反序列化; +- 完成 `iOSBuildServer` 对接并实测冷/热构建耗时;完成 `readoor31`(40 Mach-O)与 `readoor31OtherPay`(44 Mach-O)全链路真机回归,并输出服务端短期凭据与 App Attest 协同方案。 + +### 5.1 Milestone 0–3 实测验收结论汇总(2026-11-20) + +- **Milestone 0(编译转换链原型与连续回滚门禁)**:已通过验收([m0_summary.json](file:///Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261119-m0-prototype-verification/m0_summary.json))。`readoor31` 765/765 Swift 对象与 1,073 ObjC 对象完整走通 `Bitcode -> opt -> clang -x ir -> ld`;必选目标失配强阻断、`.ips`/`.crash` 行号级 `atos` 还原,以及不清 `DerivedData` 连续切换 `full -> str -> off -> IG_ALL_GUARD_OFF=1` 精确回退全部通过。 +- **Milestone 1(EPUB 分层消融、匿名盲测与种子多态验证)**:已通过验收([m1_summary.json](file:///Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261119-m1-epub-evaluation/m1_summary.json))。Group C 叠加平坦化与静态线索清理后,`iPhone 16 Plus` 首章打开 P50 延迟变化仅 `+0.28%`~`+0.71%`、翻页 P50 `5.55ms`(远低于 `5%` 预算),主包体积变化 `< +17 KB`(远低于 `1.5 MB` 预算),同 `ReleaseSeed` 产物字节级确定性复现、异种子 CFG 拓扑多态验证通过。 +- **Milestone 2(SD 3.2 签名与 IAP 验单调用链推广)**:已通过验收([m2_summary.json](file:///Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261119-m2-sd-iap-evaluation/m2_summary.json))。9 项必选规则(65 个函数平坦化、10 个模块字符串加密)全部命中,主二进制敏感明文线索 `0` 残留;真机全新安装、老版本 Keychain 覆盖升级、清空 Keychain 恢复三条路径 RSA 签名一致性全部通过。 +- **Milestone 3(L1+L2+L3 全量合并、`iOSBuildServer` 投产与双 Target 真机回归)**:已通过验收([m3_summary.json](file:///Users/shenlei/Work/ReadBook/iOSGuard/test-results/20261119-m3-production-regression/m3_summary.json)): + - **L1 符号与方法混淆**:混淆 `2,166` 个类型与 `6,792` 个方法/Selector(v2 统一映射协议),自动豁免 `STSPayOrderInfoObject`、`RBCorePenLineData`、`STSPaintModel` 系列及 `RDPlayerCacheMedia` 等持久化归档类,支持 Bridging-Header 跨语言后缀裁剪类与多段 Selector 自动保护及 `.plist` / `UIApplicationMain` 运行时类名保护,并与 L2 策略自动联动翻译(`l1_translation_active = true`)。 + - **双 Target 全量投产包审计**:`readoor31`(`40` Mach-O,`768/768` Swift 转换,`direct_call_total = 0`,主二进制 `24,715,920 B`,较 M2 `-16,208 B`)与 `readoor31OtherPay`(`44` Mach-O,`773/773` Swift 转换,`direct_call_total = 0`,主二进制 `57,315,696 B`)全部通过静态敏感线索清零审计及 `.ips`/`.crash` v2 二阶段符号还原验证。 + - **真机三阶段覆盖升级与双 Target 实测(`iPhone 16 Plus`, `00008140-000960811493001C`)**:`seed_legacy_v1 -> verify_upgrade_l123 -> verify_otherpay_l123` 三阶段全部 `status = ok`,覆盖升级后 `KSDPrivateKeyPEM` SHA-256 与确定性 `X-Sig` 完全一致,历史 IAP 订单、PDF/EPUB 手写批注(`STSPaintPageLayerModel`/`STSPaintLayerModel`)与 Swift 媒体缓存反序列化 `100%` 成功,EPUB 解密与运行时守护正常。 + - **打包平台与服务端演进规格**:`iOSBuildServer`(`feat/llvm-obf-m3`)已完成投产对接并通过 `195` 项自动化测试;服务端短期凭据与 App Attest 协同方案已沉淀至 [24_SERVER_SHORT_LIVED_CREDENTIALS_AND_APP_ATTEST.md](file:///Users/shenlei/Work/ReadBook/iOSGuard/docs/24_SERVER_SHORT_LIVED_CREDENTIALS_AND_APP_ATTEST.md)。 diff --git a/docs/24_SERVER_SHORT_LIVED_CREDENTIALS_AND_APP_ATTEST.md b/docs/24_SERVER_SHORT_LIVED_CREDENTIALS_AND_APP_ATTEST.md new file mode 100644 index 0000000..487daa7 --- /dev/null +++ b/docs/24_SERVER_SHORT_LIVED_CREDENTIALS_AND_APP_ATTEST.md @@ -0,0 +1,152 @@ +# Readoor 服务端短期凭据(SD 4.0 / 按书 CEK)与 Apple App Attest 协同方案 + +> **文档定位**:客户端与服务端纵深防御演进设计规格(配套 [23_LLVM_IR_OBFUSCATION_PLAN.md](file:///Users/shenlei/Work/ReadBook/iOSGuard/docs/23_LLVM_IR_OBFUSCATION_PLAN.md) Milestone 3 输出) +> **适用端**:`readoor31` / `readoor31OtherPay` iOS 客户端、Readoor API 网关与内容授权服务 +> **前置基线**:客户端已落地 L1 符号重命名 + L2 控制流平坦化/受控常量加密 + L3 Route 2 系统调用收敛及 `IGDefender` 运行时防护;当前协议基线为 `SD 3.2`([RDSDAuthV32Signer.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Network/RDSDAuthV32Signer.swift)、[RDSDPrivateKeyManager.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Network/RDSDPrivateKeyManager.swift))与本地统一书籍密钥派生([RDEncryptedEpubResourceProvider.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Features/ReadView/Epub/RDEncryptedEpubResourceProvider.swift)、[RDEpubKeyBox.c](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Base/Security/RDEpubKeyBox.c))。 + +--- + +## 1. 客户端防护边界与服务端协同的必要性 + +客户端 L1+L2+L3 加固消除了二进制中的明文盐值、语义符号名、中文业务日志与外部 C API 直连,显著抬高了静态逆向与自动化脚本的破解门槛,但受限于端侧执行模型的客观物理边界,仍存在两类高收益攻击面必须由服务端架构收口: + +| 现有链路 | 客户端混淆可解决的问题 | 客户端混淆无法消除的残余风险 | 服务端协同收口方向 | +| :--- | :--- | :--- | :--- | +| **SD 3.2 签名([RDSDAuthV32Signer.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Network/RDSDAuthV32Signer.swift))** | 隐藏 `rd_net_cfg_v1.dat` 解密参数、消除 `/Users/...` 路径与明文 `logDiag` 字符串 | 包内所有安装实例共享同一全局 RSA-2048 私钥;一旦攻击者在越狱/调试环境下于内存或 `SecKeyCreateSignature` 出口捕获 `PEM` 一次,即可离线批量签发任意设备请求 | **`SD 4.0` 短期会话签名凭据 + Secure Enclave 不可导出硬件私钥** | +| **EPUB 内容解密([RDEpubKeyBox.c](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Base/Security/RDEpubKeyBox.c))** | 隐藏 `"startiasoft"` 算法字面量、`RDEpubKeyGuard` 篡改毒化、Route 2 防简单 `open`/`read` hook | 所有版本共享同一输入(`bookIdentifier` / `fileName`)→ 密钥的确定性映射关系,离线批量解包工具可复用单次提取的派生器 | **单书/单会话包装 CEK(Content Encryption Key)+ 服务端权益授权** | +| **高价值 API 鉴权(登录、IAP 验单、拿密钥)** | `RDSecurityGuard` 监测动态库注入/越狱与 ObjC IMP 基线,`logDiag` 上报诊断码 | 纯软件端检测逻辑仍运行在攻击者可控设备上;重打包伪造客户端或 Hook 返回 `.normal` 可欺骗普通鉴权接口 | **Apple `DCAppAttestService` 硬件证书链 attestation + 逐次递增计数器 assertion** | + +--- + +## 2. `SD 4.0`:Secure Enclave 设备绑定与短期会话签名凭据(`X-CT: 4.0`) + +### 2.1 目标原则 +1. **私钥不出硬件**:客户端不再内置全量用户共享的通用 RSA 私钥用于新会话签名;高版本客户端在 Secure Enclave 内生成不可导出的 **P-256 (NIST secp256r1)** 硬件私钥(仅在 Keychain 存引用 `SecAccessControl` + `kSecAttrTokenIDSecureEnclave`)。 +2. **会话短期化**:每次登录/令牌刷新由服务端签发带 TTL(建议 2~4 小时)的会话密钥绑定凭据,泄露单一会话仅影响该账号在 TTL 窗口内的请求。 +3. **双轨平滑迁移**:服务端网关同时支持 `X-CT: 3.2` 与 `X-CT: 4.0`;老版本 App 覆盖升级后继续兼容 `KSDPrivateKeyPEM` 历史逻辑,待低版本自然淘汰后对敏感接口逐步收紧 `3.2` 配额。 + +### 2.2 密钥注册与会话签发协议 + +```mermaid +sequenceDiagram + participant App as 客户端 (iOS Secure Enclave) + participant GW as Readoor API 网关 + participant Redis as 会话/防重放存储 + + App->>GW: 1. GET /v4/auth/attest-challenge + GW-->>App: { challenge_id, nonce_b64, ttl: 120 } + + Note over App: 生成或复用 SE P-256 密钥对 + DCAppAttest Assertion + App->>GW: 2. POST /v4/auth/session-key
(token, device_pub_jwk, app_attest_assertion, challenge_id) + GW->>GW: 校验 App Attest 证书链/计数器 + 用户 JWT + GW->>Redis: 写入 session_jti -> { user_id, device_id, device_pub_pem, exp } + GW-->>App: 3. { session_jti, key_id, alg: "ES256", expires_at, lease_policy } +``` + +### 2.3 `X-CT: 4.0` 请求头与规范签名串 +每次业务请求携带: +- `X-CT: 4.0` +- `X-KEY-VER: se-p256-v4` +- `X-KEY-ID: ` +- `X-TS: `(网关允许 ±300s 时钟偏移) +- `X-NO: <16+ char CSPRNG nonce>`(网关存入 Redis `NX EX 300`,防止重放) +- `X-OS`、`X-VER`、`X-APPGUID` +- `X-SIG: ` + +规范签名串(按字段字典序固定拼接,消除 HTTP 方法/路径复用攻击): +```text +method=&path=&query_sha256=&body_sha256=&device_id=&key_id=&nonce=&ts=&ver=&token= +``` +> 注:若设备不支持 Secure Enclave(极老设备或 Simulator),可结合下文 §4 的设备分级策略由 `/v4/auth/session-key` 下发服务端生成、有效期更短(如 30 分钟)的 **HKDF 会话 HMAC-SHA256 子密钥** 存于 Keychain `.accessibleWhenUnlockedThisDeviceOnly` 过渡,绝不退回静态全局 PEM。 + +--- + +## 3. 按书/按会话包装 EPUB CEK 方案(`/v4/epub/cek`) + +### 3.1 目标架构 +消除所有书目仅依赖 `"startiasoft" + bookId` 本地固定推导的全局弱点:书籍文件对称密钥(**CEK, 256-bit**)由服务端托管(或按书独立生成后存入 KMS / 数据库加密字段),客户端仅在确认当次订阅/购买权益与 App Attest 合规后获取用**本次设备会话公钥包裹(Key Wrapping)**的短期密钥信封。 + +```mermaid +flowchart LR + KMS["服务端 KMS / 书籍主密钥"] -->|"Per-Book CEK (AES-256)"| AUTH["权益与 Attest 校验 (/v4/epub/cek)"] + SE["客户端 SE P-256 临时公钥 (epk)"] --> AUTH + AUTH -->|"ECDH-ES + A256KW 信封 + 租约(exp, watermark_uid)"| STORE["本地沙盒/Keychain密文缓存"] + STORE -->|"内存解包 CEK (使用后 memset_s 清零)"| PROV["RDEncryptedEpubResourceProvider"] +``` + +### 3.2 下发与解包数据结构 +1. **请求**:`POST /v4/epub/cek` + - Body:`{ "book_id": "10086", "epk_jwk": { ...P-256 公钥... }, "format_version": 2 }` + - Headers:携带 `SD 4.0` 签名头 + `X-Apple-App-Attest-Assertion` +2. **服务端校验与响应**: + - 验证用户对 `book_id` 的有效权益(已购买 / VIP 有效期内 / 限免试读章节白名单); + - 通过 **ECDH-ES + A256KW (RFC 7518 §4.6)** 或 **HKDF-SHA256 + AES-256-GCM**,利用服务端临时密钥对 `(srv_epk_jwk)` 与客户端 `epk_jwk` 派生 `KEK`,加密包裹真实 `CEK`(试读场景仅下发试读章节范围加密的独立 `Trial-CEK`); + - 响应信封: + ```json + { + "book_id": "10086", + "cek_version": 2, + "srv_epk_jwk": { "kty": "EC", "crv": "P-256", "x": "...", "y": "..." }, + "wrapped_cek_b64": "...", + "iv_b64": "...", + "tag_b64": "...", + "lease_expires_at": 1764140400, + "max_offline_days": 7, + "allowed_spine_indices": [0, 1, 2], + "watermark_seed": "sha256_hmac_uid_device" + } + ``` +3. **客户端集成落点**: + - 新增密钥会话管理器(与 [RDEncryptedEpubResourceProvider.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Features/ReadView/Epub/RDEncryptedEpubResourceProvider.swift) 对接):打开 V2 加密书籍前在内存解包 `cek_v2`,仅保留当次阅读器实例生命周期(不再落盘明文,退出阅读器即清零内存); + - **离线租约(Offline Lease)**:已下载正版书支持 7 天内无网阅读(随网联静默续签租约),`lease_expires_at` 过期后本地阻断解包并引导联网续约,兼顾火车/飞行模式体验与账号退订/退单回收能力; + - **双版本平滑兼容**:若资源头文件或 `.opf` 仍标记旧版 `v1`(存量已分发加密 EPUB 资源),保留 [RDEpubKeyBox.c](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Base/Security/RDEpubKeyBox.c) 既有毒化通道直至全量书籍完成 V2 重压转码。 + +--- + +## 4. Apple `DCAppAttestService` 认证与逐次 Assertion 校验流程 + +### 4.1 两阶段硬件证明架构 + +| 阶段 | 客户端 Apple Framework API | 服务端交互与密码学校验项 | 状态持久化 | +| :--- | :--- | :--- | :--- | +| **1. 设备密钥 Attestation** | 1. 检查 `DCAppAttestService.shared.isSupported`
2. 生成 `keyId = try await service.generateKey()`(首次或换机)
3. 拉取 challenge,计算 `clientDataHash = SHA256(challenge \|\| bundle_id \|\| device_id)`
4. `attestObj = try await service.attestKey(keyId, clientDataHash: hash)` | `POST /v4/auth/attest-verify`:
① CBOR 解码 `fmt == "apple-appattest"`、`attStmt.x5c`、`attStmt.receipt`、`authData`;
② 验证 `x5c` 证书链直达 Apple App Attest Root CA;
③ 校验 leaf cert 扩展 `OID 1.2.840.113635.100.8.2` 八位字节等于 `SHA256(authData \|\| clientDataHash)`;
④ 校验 `authData.rpIdHash == SHA256(".")` 且 **`signCount == 0`**;
⑤ 校验 `aaguid`(生产仅放行 `"appattest\x00..."`;测试/AdHoc 才可配 `"appattestdevelop"`);
⑥ 提取 `credentialId == SHA256(pubKey)` 并校验等于 `keyId`,保存公钥 COSE EC2 P-256。 | 表 `device_app_attest`:
`key_id`、`pub_key_pem`、`sign_count=0`、`receipt_b64`、`env`、`fraud_risk_score`、`last_verified_at` | +| **2. 敏感接口逐次 Assertion** | 高价值请求前获取或复用短期 server nonce,构造 `clientData = canonical_req_sha256 + "|" + challenge`,调用 `service.generateAssertion(keyId, clientDataHash: SHA256(clientData))` | 目标 API 携带 `X-Apple-Attest-KeyId` 与 `X-Apple-Attest-Assertion`:
① 校验 `challenge` 未过期、未使用;
② CBOR 解码 `signature` + `authenticatorData`;
③ 计算 `nonce = SHA256(authenticatorData \|\| clientDataHash)`,用服务端存储的 `pub_key_pem` 验签 ECDSA-SHA256;
④ 校验 **`newSignCount > stored_sign_count`** 并原子递增更新(`UPDATE ... WHERE sign_count < newSignCount`);
⑤ 周期调用 Apple `/v2/verifyReceipt` 接口刷新设备欺诈评估指标。 | 原子递增 `sign_count`;计数器回退或并发碰撞立即拒绝 | + +### 4.2 覆盖接口优先级矩阵 + +| 接口分组 | 典型路径 / 业务对应 | Assertion 要求 | 说明 | +| :--- | :--- | :--- | :--- | +| **P0:内购与凭据** | `/v4/iap/verify`([STSIAPVerifyHandler.m](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/BookShelf/Classes/Features/IAP/Handler/STSIAPVerifyHandler.m) / [RDIAPPurchaseManager.swift](file:///Users/shenlei/Work/ReadBook/iOSGuard/readoor-test/readoor/3.0/Features/IAP/RDIAPPurchaseManager.swift))、`/v4/epub/cek`、`/v4/auth/session-key` | **必需(Enforced 阶段强制拒绝)** | 直接对应真金白银验单、内容密钥与会话签发最高收益点 | +| **P1:账号与激活码** | `/v4/auth/login`、`/v4/auth/sms-code`、`/v4/card/activate` | **必需(限频 + Assertion 双约束)** | 防止撞库、短信接口刷量、批卡脚本攻击 | +| **P2:普通浏览查询** | 书架列表、书城详情、阅读进度同步 | **免 Assertion,仅校验 `SD 4.0` 会话签名** | 避免高频请求耗尽 SE 配额或增加常规页面延迟 | + +### 4.3 异常与非恶意降级处理策略 +禁止简单粗暴一刀切导致正常用户无法登录或购书;服务端及客户端须区分 4 类异常并联动新增生产诊断事件码(建议接续 [ig_diag_events.json](file:///Users/shenlei/Work/ReadBook/iOSGuard/config/ig_diag_events.json) `E-71xx` 号段): + +| 场景 / 错因 | 诊断码 | 客户端与服务端处置策略 | +| :--- | :--- | :--- | +| **硬件/系统不支持**(< iOS 14 或 `isSupported == false` 的 Simulator/特殊机型) | `E-7101` | 允许携带 `X-Attest-Status: unsupported` 走低信任通道(缩短 CEK 离线租约至 24 小时 + 收紧设备单日兑换/拿钥频控);`Enforced` 阶段生产实机 Simulator UA 直接阻断。 | +| **本地 `keyId` 丢失或 iCloud 恢复新机未同步** | `E-7102` | 客户端自动清除旧 `keyId` 标记并无感重新执行一次 `generateKey()` + `attestKey()`(每账号限制 3 次/24h 重建阈值防刷)。 | +| **`signCount` 回退 / 并发乱序**(重放或双端克隆) | `E-7103` | 客户端按串行队列持有单次 Assertion 生成锁防本地并发乱序;服务端检测到 `new <= stored` 时拒绝该次请求,如连续 3 次返回 `E-7103` 则触发重新 Attest 或冻结可疑 `session_jti`。 | +| **Apple `DCAppAttest` / `verifyReceipt` 服务端超时或 5xx** | `E-7104` | 客户端遵循 Apple `DCError.serverUnavailable` 指数退避(最多 2 次);网关维护熔断窗口:Apple 侧连续抖动超过阈值时,已通过历史验证的合法设备可降级依赖 `SD 4.0` 短期会话放行 1 小时窗口,记录审计告警。 | +| **`RDSecurityGuard` 高风险(`highRisk`)与 Attest 联动** | `E-7105` | 端侧检测到注入/越狱时停止新签发 `SD 4.0` 与 Assertion 并退出/降级;服务端若发现某 `keyId` 对应 `receipt` 的 Apple `metric` 骤增(关联多账号批量行为),强制吊销全部 `session_jti` 与离线租约。 | + +*其余预留服务端细化诊断码:`E-7106`(`attest_challenge_expired`)、`E-7107`(`attest_x5c_or_nonce_invalid`)、`E-7108`(`attest_aaguid_env_mismatch`)、`E-7109`(`cek_entitlement_denied`)、`E-7110`(`sd40_replay_nonce_reused`)。* + +--- + +## 5. 分阶段灰度上线与监控验收方案 + +为避免在双端接口割接与 Apple 服务抖动期间影响线上正常购买与阅读,严格按三阶段灰度推进: + +1. **Phase A — Observe(观察采集期,1~2 周)** + - 客户端上线 `SD 4.0` 注册 + `DCAppAttestService` 采集逻辑,`P0/P1` 接口异步附加 `X-Apple-App-Attest-*` 与 `X-Attest-Status` 头部; + - 服务端完整执行证书链、签名、递增计数器与 CEK 权属校验逻辑,**验证失败仅记 `E-7101..E-7110` 指标告警,业务请求仍按 `SD 3.2` 兼容放行**; + - **准出指标**:在线活跃实机 Attestation 首登成功率 ≥ `99.2%`,P95 Assertion 生成额外延迟 < `60 ms`,无误杀率异常峰值。 +2. **Phase B — Soft-Challenge(分级风控与租约收紧期,1~2 周)** + - 对有效通过 `SD 4.0 + App Attest` 的请求发放完整 `7 天` EPUB 离线租约与常规频控; + - 对未提供合法 Assertion 或 `fraud_risk_score` 偏高的请求,逐步下调离线租约 TTL(仅允许 `2 小时`在线鉴权播放/阅读),对 `/v4/card/activate` 等高频羊毛接口触发滑块/验证码或限流; + - 同步完成存量 V1 EPUB 资产分批重压迁移至 V2 Per-Book CEK。 +3. **Phase C — Enforced(强校验全量拦截期)** + - 针对支持版本(App Version ≥ V4.0),对 `/v4/iap/verify`、`/v4/epub/cek`、`/v4/auth/session-key` 强制校验合法 `SD 4.0 + App Attest Assertion`,阻断绕过客户端验证的协议重放与未授权批量解包; + - 旧版客户端(< V4.0)通过版本策略与强制升级节奏平滑退场后,下线 `X-CT: 3.2` 全局私钥签名受理入口并轮换废止历史 `v1` 凭据。 diff --git a/llvm_passes/CMakeLists.txt b/llvm_passes/CMakeLists.txt new file mode 100644 index 0000000..ee8bc92 --- /dev/null +++ b/llvm_passes/CMakeLists.txt @@ -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 +) diff --git a/llvm_passes/include/IGPassUtils.h b/llvm_passes/include/IGPassUtils.h new file mode 100644 index 0000000..a5eb60c --- /dev/null +++ b/llvm_passes/include/IGPassUtils.h @@ -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 +#include +#include + +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(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("")) { + return true; + } + } + } + return false; +} + +inline bool matchesAnySubstring(const llvm::Function &F, + const std::vector &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 *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 diff --git a/llvm_passes/include/IGPolicyConfig.h b/llvm_passes/include/IGPolicyConfig.h new file mode 100644 index 0000000..20132d7 --- /dev/null +++ b/llvm_passes/include/IGPolicyConfig.h @@ -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 +#include +#include +#include +#include + +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 Rounds; + std::optional MaxPerFn; + std::optional Probability; + std::optional NonlinearMBA; + std::optional 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 FunctionsFlattened; + std::vector FunctionsFlattenedDetails; + std::vector FunctionsSkipped; + unsigned StringsEncryptedCount = 0; + std::vector StringsEncryptedFunctions; + unsigned StringsStackEncryptedCount = 0; + unsigned ObjCStringsEncryptedCount = 0; + unsigned SwiftStringsEncryptedCount = 0; + unsigned StringsReplacedCount = 0; + unsigned StringsSkippedCount = 0; + unsigned PathsScrubbedCount = 0; + unsigned IndirectCallsCount = 0; + std::vector IndirectCallsFunctions; + bool IndirectCallDualTable = false; + unsigned OpaqueConstantsCount = 0; + std::vector OpaqueConstantsFunctions; + unsigned ArithmeticRewritesCount = 0; + std::vector ArithmeticFunctions; + unsigned IndirectBranchesCount = 0; + std::vector IndirectBranchesFunctions; + unsigned AntiHookFunctionsCount = 0; + std::vector AntiHookFunctions; + unsigned FunctionsOutlinedCount = 0; + std::vector OutlinedFunctions; + unsigned OpaqueFieldAccessCount = 0; + std::vector OpaqueFieldFunctions; + unsigned BBSplitCount = 0; + std::vector BBSplitFunctions; + unsigned NonlinearMBACount = 0; + unsigned OpaqueZeroCount = 0; + std::vector AnnotatedTargets; + + bool writeToFile(llvm::StringRef OutPath) const; +}; + +class IGDeterministicRNG { +public: + IGDeterministicRNG(llvm::StringRef Seed, llvm::StringRef ModuleId, + llvm::StringRef ItemId); + + std::array nextBlock(); + uint32_t nextU32(); + uint32_t nextNonZeroU32(); + uint64_t nextU64(); + uint64_t nextNonZeroU64(); + uint8_t nextNonZeroByte(); + + template void shuffle(VecT &Items) { + if (Items.size() < 2) + return; + for (size_t i = Items.size() - 1; i > 0; --i) { + size_t j = static_cast(nextU32() % static_cast(i + 1)); + if (i != j) + std::swap(Items[i], Items[j]); + } + } + +private: + std::string Prefix_; + uint64_t Counter_ = 0; + std::array 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 &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 &indirectCallSameImagePrefixes() const { + return IndirectCallSameImagePrefixes_; + } + const std::vector &exemptFunctionPrefixes() const { + return ExemptFunctionPrefixes_; + } + const std::vector &scrubPathSubstrings() const { + return ScrubPathSubstrings_; + } + const std::vector &opaqueConstExemptFunctions() const { + return OpaqueConstExemptFunctions_; + } + const std::vector &arithmeticExemptFunctions() const { + return ArithmeticExemptFunctions_; + } + const std::vector &indirectBranchExemptFunctions() const { + return IndirectBranchExemptFunctions_; + } + const std::vector &antiHookingExemptFunctions() const { + return AntiHookingExemptFunctions_; + } + const std::vector &functionOutlineExemptFunctions() const { + return FunctionOutlineExemptFunctions_; + } + const std::vector &opaqueFieldExemptFunctions() const { + return OpaqueFieldExemptFunctions_; + } + const std::vector &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 &Rules, + const llvm::Function &F) const; + bool matchesAnyRule(const std::vector &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 ExemptPathSubstrings_; + std::vector ExemptFunctionPrefixes_; + std::vector ScrubPathSubstrings_; + std::vector StringEncryptTargets_; + std::vector StringEncryptObjCTargets_; + std::vector StringEncryptSwiftTargets_; + std::vector StringEncryptStackTargets_; + std::vector StringReplaceRules_; + std::vector IndirectCallTargets_; + std::vector IndirectCallSameImagePrefixes_; + std::vector FlattenTargets_; + std::vector OpaqueConstTargets_; + std::vector OpaqueConstExemptFunctions_; + std::vector ArithmeticTargets_; + std::vector ArithmeticExemptFunctions_; + std::vector IndirectBranchTargets_; + std::vector IndirectBranchExemptFunctions_; + std::vector AntiHookingTargets_; + std::vector AntiHookingExemptFunctions_; + std::vector FunctionOutlineTargets_; + std::vector FunctionOutlineExemptFunctions_; + std::vector OpaqueFieldTargets_; + std::vector OpaqueFieldExemptFunctions_; + std::vector BBSplitTargets_; + std::vector 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 diff --git a/llvm_passes/src/IGAntiHooking.cpp b/llvm_passes/src/IGAntiHooking.cpp new file mode 100644 index 0000000..5181d81 --- /dev/null +++ b/llvm_passes/src/IGAntiHooking.cpp @@ -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 + +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(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 diff --git a/llvm_passes/src/IGArithmetic.cpp b/llvm_passes/src/IGArithmetic.cpp new file mode 100644 index 0000000..0c0c65e --- /dev/null +++ b/llvm_passes/src/IGArithmetic.cpp @@ -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 + +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(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(BO->getOperand(0)) && + isa(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 Candidates; + for (BasicBlock &BB : F) { + for (Instruction &I : BB) { + if (auto *BO = dyn_cast(&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 diff --git a/llvm_passes/src/IGBasicBlockSplit.cpp b/llvm_passes/src/IGBasicBlockSplit.cpp new file mode 100644 index 0000000..bcd23d0 --- /dev/null +++ b/llvm_passes/src/IGBasicBlockSplit.cpp @@ -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(BB.getTerminator())) + return false; + for (const Instruction &I : BB) { + if (I.getType()->isTokenTy()) + return false; + if (const auto *AI = dyn_cast(&I)) { + if (AI->isSwiftError()) + return false; + } + if (const auto *CB = dyn_cast(&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(I) || isa(I) || + isa(I) || isa(I)) { + return true; + } + if (const auto *CB = dyn_cast(&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 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(&Inst)) + LastAlloca = AI; + } + BasicBlock::iterator FirstSplittable = + LastAlloca ? std::next(LastAlloca->getIterator()) + : BB->getFirstInsertionPt(); + while (FirstSplittable != BB->end() && + (isa(*FirstSplittable) || + isa(*FirstSplittable))) { + ++FirstSplittable; + } + + SmallVector SplittableInsts; + for (auto It = FirstSplittable; It != BB->end(); ++It) { + Instruction &I = *It; + if (!I.isTerminator() && !isa(I)) + SplittableInsts.push_back(&I); + } + if (SplittableInsts.size() < MinInsts) + continue; + + SmallVector 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(RNG.nextU32() % 3U) - 1; + ptrdiff_t Chosen = static_cast(Mid) + Jitter; + if (Chosen < 0) + Chosen = 0; + if (Chosen >= static_cast(CandidateTargets.size())) + Chosen = static_cast(CandidateTargets.size()) - 1; + + Instruction *SplitBefore = CandidateTargets[static_cast(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 diff --git a/llvm_passes/src/IGFlattening.cpp b/llvm_passes/src/IGFlattening.cpp new file mode 100644 index 0000000..d0fdcf2 --- /dev/null +++ b/llvm_passes/src/IGFlattening.cpp @@ -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 +#include + +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("")) { + 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(Term) || isa(Term) || + isa(Term) || isa(Term) || + isa(Term) || isa(Term) || + isa(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(&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(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(&I)) { + if (II->getIntrinsicID() == Intrinsic::stacksave) { + for (const User *U : II->users()) { + const auto *Restore = dyn_cast(U); + if (!Restore || + Restore->getIntrinsicID() != Intrinsic::stackrestore) { + SkipReason = "complex_stacksave"; + return false; + } + } + } + } + if (auto *CB = dyn_cast(&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(&I)) { + if (CI->isMustTailCall()) { + HasMustTailOut = true; + Instruction *Next = CI->getNextNonDebugInstruction(); + if (Next != Term || !isa(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 SplitCandidates; + for (BasicBlock &BB : F) { + bool SeenBodyInst = false; + for (Instruction &I : BB) { + if (isa(I) || isa(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(&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 Chosen; + size_t N = SplitCandidates.size(); + size_t Desired = (F.size() == 1) ? std::min(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(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(RawState * P.MulKey + P.AddKey); + return static_cast(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 StackRestores; + SmallVector StackSaves; + SmallVector Allocas; + for (BasicBlock &BB : F) { + for (Instruction &I : BB) { + if (auto *II = dyn_cast(&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(&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(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(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 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 Phis; + for (BasicBlock &BB : F) { + for (PHINode &PN : BB.phis()) + Phis.push_back(&PN); + } + for (PHINode *PN : Phis) { + DemotePHIToStack(PN, EntryBB.getTerminator()->getIterator()); + } + + SmallVector CrossBlockRegs; + for (BasicBlock *BB : OrigBBs) { + for (Instruction &I : *BB) { + if (I.isTerminator() || I.getType()->isVoidTy() || isa(I)) + continue; + if (auto *CI = dyn_cast(&I)) { + if (CI->isMustTailCall()) + continue; + } + bool UsedOutside = false; + for (const User *U : I.users()) { + const auto *UI = dyn_cast(U); + if (!UI || UI->getParent() != BB || isa(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 ShuffledBBs(OrigBBs.begin(), OrigBBs.end()); + RNG.shuffle(ShuffledBBs); + + DenseMap StateMap; + DenseMap 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(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, 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( + 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(2, (N / 3) + (RNG.nextU32() % 2u)); + size_t S2 = S1 + std::max(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(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(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(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(N - 1)); + BasicBlock *SubDispBB = + BasicBlock::Create(Ctx, "ig.loop.subdisp", &F, SwitchDefaultBB); + SwitchInst *SW1 = DB.CreateSwitch(CurState, SubDispBB, + static_cast(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(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, 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(RNG.nextU32() % + static_cast(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, 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(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(Term)) + continue; + if (auto *RI = dyn_cast(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(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(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 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 diff --git a/llvm_passes/src/IGFunctionOutline.cpp b/llvm_passes/src/IGFunctionOutline.cpp new file mode 100644 index 0000000..5e4c6b1 --- /dev/null +++ b/llvm_passes/src/IGFunctionOutline.cpp @@ -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(V)) { + if (AI->isSwiftError()) + return true; + } + if (const auto *Arg = dyn_cast(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(BB.front())) + return false; + if (!isa(BB.getTerminator())) + return false; + + unsigned WorkInsts = 0; + for (const Instruction &I : BB) { + if (isa(I)) + continue; + if (isa(I) || isa(I) || isa(I) || + isa(I) || isa(I) || + isa(I) || isa(I) || + isa(I) || isa(I) || I.isAtomic()) { + return false; + } + if (I.getType()->isTokenTy()) + return false; + for (const Use &U : I.operands()) { + if (isa(U.get())) + return false; + if (isa(U.get())) + continue; + if (isSwiftABIHazardValue(U.get())) + return false; + } + if (const auto *CB = dyn_cast(&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(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 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 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 Region{BB}; + CodeExtractor CE(Region, &DT, /*AggregateArgs=*/false); + if (!CE.isEligible()) + continue; + + SetVector 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(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 diff --git a/llvm_passes/src/IGIndirectBranch.cpp b/llvm_passes/src/IGIndirectBranch.cpp new file mode 100644 index 0000000..ff88905 --- /dev/null +++ b/llvm_passes/src/IGIndirectBranch.cpp @@ -0,0 +1,280 @@ +#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(Term) || isa(Term) || + isa(Term) || isa(Term) || + isa(Term) || isa(Term) || + isa(Term)) { + return false; + } + for (Instruction &I : BB) { + if (I.getType()->isTokenTy()) + return false; + if (auto *CI = dyn_cast(&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 Branches; + SmallVector Targets; + SmallPtrSet SeenTargets; + + BasicBlock *EntryBB = &F.getEntryBlock(); + SmallPtrSet Reachable; + SmallVector 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(Term); CBr && CBr->isConditional()) { + if (auto *CondCI = dyn_cast(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(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(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()); + RNG.shuffle(Targets); + + DenseMap SlotMap; + SmallVector Share1Entries; + SmallVector Share2Entries; + Share1Entries.reserve(Targets.size()); + Share2Entries.reserve(Targets.size()); + + Constant *FnInt = ConstantExpr::getPtrToInt(&F, I64Ty); + for (unsigned Idx = 0; Idx < Targets.size(); ++Idx) { + BasicBlock *BB = Targets[Idx]; + SlotMap[BB] = Idx; + uint64_t Salt = RNG.nextNonZeroU64(); + Constant *BBAddrInt = ConstantExpr::getPtrToInt(BlockAddress::get(&F, BB), I64Ty); + Constant *RelOffset = ConstantExpr::getSub(BBAddrInt, FnInt); + Constant *Share1 = ConstantExpr::getAdd(RelOffset, ConstantInt::get(I64Ty, Salt)); + Share1Entries.push_back(Share1); + Share2Entries.push_back(ConstantInt::get(I64Ty, Salt)); + } + + ArrayType *TableTy = ArrayType::get(I64Ty, Targets.size()); + std::string Suffix = Tag.str() + "_" + std::to_string(FnIndex); + auto *Share1GV = new GlobalVariable( + M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage, + ConstantArray::get(TableTy, Share1Entries), "__ig_ibt1_" + Suffix); + Share1GV->setAlignment(Align(8)); + Share1GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None); + + auto *Share2GV = new GlobalVariable( + M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage, + ConstantArray::get(TableTy, Share2Entries), "__ig_ibt2_" + Suffix); + Share2GV->setAlignment(Align(8)); + Share2GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None); + + Constant *Zero64 = ConstantInt::get(I64Ty, 0); + 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); + unsigned SlotIdx = SlotMap[Dest]; + Value *IdxVal = ConstantInt::get(I64Ty, SlotIdx); + Value *P1 = B.CreateInBoundsGEP(TableTy, Share1GV, {Zero64, IdxVal}); + Value *P2 = B.CreateInBoundsGEP(TableTy, Share2GV, {Zero64, IdxVal}); + LoadInst *S1 = B.CreateAlignedLoad(I64Ty, P1, Align(8), /*isVolatile=*/true); + LoadInst *S2 = B.CreateAlignedLoad(I64Ty, P2, Align(8), /*isVolatile=*/true); + Value *BaseInt = B.CreatePtrToInt(&F, I64Ty); + Value *Delta = B.CreateSub(S1, S2); + Value *Addr = B.CreateAdd(BaseInt, Delta); + Value *DstPtr = B.CreateIntToPtr(Addr, PtrTy); + + 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[TrueBB]), + ConstantInt::get(I64Ty, SlotMap[FalseBB]), "ig.ibr.idx"); + Value *P1 = B.CreateInBoundsGEP(TableTy, Share1GV, {Zero64, IdxVal}); + Value *P2 = B.CreateInBoundsGEP(TableTy, Share2GV, {Zero64, IdxVal}); + LoadInst *S1 = B.CreateAlignedLoad(I64Ty, P1, Align(8), /*isVolatile=*/true); + LoadInst *S2 = B.CreateAlignedLoad(I64Ty, P2, Align(8), /*isVolatile=*/true); + Value *BaseInt = B.CreatePtrToInt(&F, I64Ty); + Value *Delta = B.CreateSub(S1, S2); + Value *Addr = B.CreateAdd(BaseInt, Delta); + Value *DstPtr = B.CreateIntToPtr(Addr, PtrTy); + + 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 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 diff --git a/llvm_passes/src/IGIndirectCall.cpp b/llvm_passes/src/IGIndirectCall.cpp new file mode 100644 index 0000000..07ae166 --- /dev/null +++ b/llvm_passes/src/IGIndirectCall.cpp @@ -0,0 +1,501 @@ +#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(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 `` starting at `S[Start]` if valid. +// Sets `AfterIdx` to index immediately following ``. +StringRef parseLengthPrefixedSwiftIdent(StringRef S, size_t Start, + size_t &AfterIdx) { + if (Start >= S.size() || !isDigit(static_cast(S[Start])) || + S[Start] == '0') { + return StringRef(); + } + size_t Pos = Start; + uint64_t Len = 0; + while (Pos < S.size() && isDigit(static_cast(S[Pos]))) { + Len = Len * 10 + static_cast(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(Len)); + if (!isValidSwiftIdentChars(Ident) || isBuiltinSwiftModuleName(Ident)) + return StringRef(); + AfterIdx = Pos + static_cast(Len); + return S.substr(Start, AfterIdx - Start); +} + +std::string detectSwiftModuleToken(const Module &M) { + StringMap 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(Clean[i - 1])) || + !isDigit(static_cast(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(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(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(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 Sites; + SmallVector UniqueCallees; + DenseMap SeenCallees; + std::vector 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(&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; + + DenseMap> SlotMap; + SmallVector Table1Entries; + SmallVector Table2Entries; + Table1Entries.reserve(UniqueCallees.size()); + if (UseDualTable) + Table2Entries.reserve(UniqueCallees.size()); + + for (unsigned Idx = 0; Idx < UniqueCallees.size(); ++Idx) { + Function *TargetFn = UniqueCallees[Idx]; + // [2 GiB, 4 GiB) salt shifts static delta outside Mach-O VM range while + // allowing per-call-site split immediates SiteA + SiteB == SlotSalt in u32. + uint64_t SlotSalt = + 0x80000000ULL | static_cast(RNG.nextU32() & 0x7FFFFFFFU); + Constant *CalleeInt = ConstantExpr::getPtrToInt(TargetFn, I64Ty); + Constant *Diff = ConstantExpr::getSub(CalleeInt, AnchorInt); + if (UseDualTable) { + uint64_t Share2 = RNG.nextNonZeroU64(); + uint64_t CombinedSalt = Share2 + SlotSalt; + Constant *Encoded1 = + ConstantExpr::getAdd(Diff, ConstantInt::get(I64Ty, CombinedSalt)); + Table1Entries.push_back(Encoded1); + Table2Entries.push_back(ConstantInt::get(I64Ty, Share2)); + } else { + Constant *Encoded = + ConstantExpr::getAdd(Diff, ConstantInt::get(I64Ty, SlotSalt)); + Table1Entries.push_back(Encoded); + } + SlotMap[TargetFn] = {Idx, SlotSalt}; + } + + ArrayType *TableTy = ArrayType::get(I64Ty, Table1Entries.size()); + GlobalVariable *Table1GV = nullptr; + GlobalVariable *Table2GV = nullptr; + if (UseDualTable) { + Table1GV = new GlobalVariable( + M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage, + ConstantArray::get(TableTy, Table1Entries), "__ig_cs1_" + Tag); + Table1GV->setAlignment(Align(8)); + Table1GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None); + + Table2GV = new GlobalVariable( + M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage, + ConstantArray::get(TableTy, Table2Entries), "__ig_cs2_" + Tag); + Table2GV->setAlignment(Align(8)); + Table2GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None); + } else { + Table1GV = new GlobalVariable( + M, TableTy, /*isConstant=*/true, GlobalValue::InternalLinkage, + ConstantArray::get(TableTy, Table1Entries), "__ig_ct_" + Tag); + Table1GV->setAlignment(Align(8)); + Table1GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None); + } + + Constant *Zero64 = ConstantInt::get(I64Ty, 0); + for (const PendingIndirectSite &Site : Sites) { + CallInst *CI = Site.CI; + auto It = SlotMap.find(Site.Callee); + if (It == SlotMap.end()) + continue; + unsigned SlotIdx = It->second.first; + uint64_t SlotSalt = It->second.second; + + uint64_t SiteA = + 1ULL + (static_cast(RNG.nextU32()) % (SlotSalt - 1ULL)); + uint64_t SiteB = SlotSalt - SiteA; + + IRBuilder<> B(CI); + B.SetCurrentDebugLocation(CI->getDebugLoc()); + Constant *IdxConst = ConstantInt::get(I64Ty, SlotIdx); + Value *SlotPtr1 = B.CreateInBoundsGEP(TableTy, Table1GV, {Zero64, IdxConst}); + LoadInst *Load1 = + B.CreateAlignedLoad(I64Ty, SlotPtr1, Align(8), /*isVolatile=*/true); + Value *RawDelta = Load1; + if (UseDualTable) { + Value *SlotPtr2 = B.CreateInBoundsGEP(TableTy, Table2GV, {Zero64, IdxConst}); + LoadInst *Load2 = + B.CreateAlignedLoad(I64Ty, SlotPtr2, Align(8), /*isVolatile=*/true); + RawDelta = B.CreateSub(Load1, Load2); + } + Value *AnchorVal = B.CreatePtrToInt(AnchorGV, I64Ty); + Value *Step1 = B.CreateSub(RawDelta, ConstantInt::get(I64Ty, SiteA)); + Value *Step2 = B.CreateAdd(AnchorVal, Step1); + Value *TargetInt = B.CreateSub(Step2, ConstantInt::get(I64Ty, SiteB)); + 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 diff --git a/llvm_passes/src/IGOpaqueConstants.cpp b/llvm_passes/src/IGOpaqueConstants.cpp new file mode 100644 index 0000000..151506e --- /dev/null +++ b/llvm_passes/src/IGOpaqueConstants.cpp @@ -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 + +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 &Sites, unsigned MaxBudget) { + if (Sites.size() >= MaxBudget) + return; + auto *CI = dyn_cast(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 &Sites) { + for (BasicBlock &BB : F) { + if (BB.isEHPad()) + continue; + for (Instruction &I : BB) { + if (Sites.size() >= MaxBudget) + return; + if (isa(&I) || isa(&I) || + isa(&I) || isa(&I) || isa(&I) || + isa(&I)) { + continue; + } + if (auto *BO = dyn_cast(&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(&I)) { + if (!Cmp->getOperand(0)->getType()->isIntegerTy()) + continue; + considerOperand(Cmp, 0, Sites, MaxBudget); + considerOperand(Cmp, 1, Sites, MaxBudget); + } else if (auto *SI = dyn_cast(&I)) { + if (!SI->isAtomic() && !SI->isVolatile() && + SI->getValueOperand()->getType()->isIntegerTy()) { + considerOperand(SI, 0, Sites, MaxBudget); + } + } else if (auto *Sel = dyn_cast(&I)) { + if (Sel->getType()->isIntegerTy()) { + considerOperand(Sel, 1, Sites, MaxBudget); + considerOperand(Sel, 2, Sites, MaxBudget); + } + } else if (auto *IV = dyn_cast(&I)) { + if (auto *CI = dyn_cast(IV->getInsertedValueOperand())) { + if (CI->getBitWidth() == 64 && CI->getZExtValue() > 0xFFFFULL) { + considerOperand(IV, 1, Sites, MaxBudget); + } + } + } else if (auto *RI = dyn_cast(&I)) { + if (Value *RV = RI->getReturnValue()) { + if (auto *CI = dyn_cast(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(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(&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 Sites; + unsigned Prob = 100; + bool UseOpaqueZero = false; + }; + SmallVector 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 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 PoolMasks{}; + ArrayType *PoolTy = ArrayType::get(I64Ty, kConstPoolSize); + GlobalVariable *PoolGV = nullptr; + if (NeedsPool) { + IGDeterministicRNG PoolRNG(Policy.seed(), M.getModuleIdentifier(), + "__ig_oc_pool"); + SmallVector 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(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(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 diff --git a/llvm_passes/src/IGOpaqueFieldAccess.cpp b/llvm_passes/src/IGOpaqueFieldAccess.cpp new file mode 100644 index 0000000..3321c2f --- /dev/null +++ b/llvm_passes/src/IGOpaqueFieldAccess.cpp @@ -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 + +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(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 GEPs; + SmallVector Globals; +}; + +void collectFieldSites(Function &F, const DataLayout &DL, unsigned MaxPerFn, + SmallVectorImpl &GEPs, + SmallVectorImpl &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(&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(U) || isa(U) || + isa(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(&I)) { + if (LI->isVolatile() || LI->isAtomic()) + continue; + if (auto *GV = dyn_cast(LI->getPointerOperand())) { + if (!GV->isConstant() && !isSensitiveGlobalSymbol(GV)) { + Globals.push_back({LI, 0, GV}); + ++Total; + } + } + } else if (auto *SI = dyn_cast(&I)) { + if (SI->isVolatile() || SI->isAtomic()) + continue; + if (auto *GV = dyn_cast(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 &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 Worklist; + DenseMap AnchorSlotMap; + SmallVector AnchorPtrs; + + for (Function &F : M) { + if (!Policy.shouldObfuscateFieldAccessInFunction(F)) + continue; + if (!isFunctionSafeForTransform(F, Policy, + &Policy.opaqueFieldExemptFunctions())) { + continue; + } + SmallVector GEPs; + SmallVector 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(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 PoolMasks{}; + SmallVector 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(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 diff --git a/llvm_passes/src/IGPluginMain.cpp b/llvm_passes/src/IGPluginMain.cpp new file mode 100644 index 0000000..f4df638 --- /dev/null +++ b/llvm_passes/src/IGPluginMain.cpp @@ -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 { + 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) { + 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 diff --git a/llvm_passes/src/IGPolicyConfig.cpp b/llvm_passes/src/IGPolicyConfig.cpp new file mode 100644 index 0000000..d94a17d --- /dev/null +++ b/llvm_passes/src/IGPolicyConfig.cpp @@ -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 + IGPolicyPath("ig-policy", cl::init(""), + cl::desc("Path to iOSGuard LLVM obfuscation policy JSON")); + +cl::opt + IGModeOpt("ig-mode", cl::init("full"), + cl::desc("iOSGuard obfuscation mode: full|str|noop|off")); + +cl::opt 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 + IGSeedOpt("ig-seed", cl::init("m0_seed_20261119_v1"), + cl::desc("iOSGuard deterministic obfuscation seed")); + +cl::opt + IGSourcePathOpt("ig-source-path", cl::init(""), + cl::desc("Original source path hint for policy matching")); + +cl::opt + IGSwiftModuleOpt("ig-swift-module", cl::init(""), + cl::desc("Authoritative Swift module name of current target")); + +cl::opt + 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(Raw); + } + return DefaultVal; +} + +void appendStringArray(const json::Object &Obj, StringRef Key, + std::vector &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 &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 &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 &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 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(Buffer_[Offset_]) << 24) | + (static_cast(Buffer_[Offset_ + 1]) << 16) | + (static_cast(Buffer_[Offset_ + 2]) << 8) | + static_cast(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(nextU32()); + uint64_t Lo = static_cast(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(StringsEncryptedCount)); + J.attribute("strings_stack_encrypted_count", + static_cast(StringsStackEncryptedCount)); + J.attribute("objc_strings_encrypted_count", + static_cast(ObjCStringsEncryptedCount)); + J.attribute("swift_strings_encrypted_count", + static_cast(SwiftStringsEncryptedCount)); + J.attribute("strings_replaced_count", + static_cast(StringsReplacedCount)); + J.attribute("strings_skipped_count", + static_cast(StringsSkippedCount)); + J.attribute("paths_scrubbed_count", + static_cast(PathsScrubbedCount)); + J.attribute("indirect_calls_count", + static_cast(IndirectCallsCount)); + J.attribute("indirect_call_dual_table", IndirectCallDualTable); + J.attribute("opaque_constants_count", + static_cast(OpaqueConstantsCount)); + J.attribute("arithmetic_rewrites_count", + static_cast(ArithmeticRewritesCount)); + J.attribute("indirect_branches_count", + static_cast(IndirectBranchesCount)); + J.attribute("anti_hook_functions_count", + static_cast(AntiHookFunctionsCount)); + J.attribute("functions_outlined_count", + static_cast(FunctionsOutlinedCount)); + J.attribute("opaque_field_access_count", + static_cast(OpaqueFieldAccessCount)); + J.attribute("bb_split_count", static_cast(BBSplitCount)); + J.attribute("nonlinear_mba_count", + static_cast(NonlinearMBACount)); + J.attribute("opaque_zero_count", static_cast(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(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 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(GA->getInitializer()); + if (!CA) + return; + for (const Use &Op : CA->operands()) { + const auto *CS = dyn_cast(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(FnVal); + const auto *AnnGV = dyn_cast(AnnVal); + if (!Fn || !AnnGV || !AnnGV->hasInitializer()) + continue; + const auto *CDS = dyn_cast(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 &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 &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 diff --git a/llvm_passes/src/IGStringEncryption.cpp b/llvm_passes/src/IGStringEncryption.cpp new file mode 100644 index 0000000..48678bd --- /dev/null +++ b/llvm_passes/src/IGStringEncryption.cpp @@ -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 +#include + +using namespace llvm; + +namespace igobf { +namespace { + +void collectCompilerUsed(const Module &M, StringRef Name, + SmallPtrSetImpl &Out) { + const GlobalVariable *GV = M.getNamedGlobal(Name); + if (!GV || !GV->hasInitializer()) + return; + const auto *CA = dyn_cast(GV->getInitializer()); + if (!CA) + return; + for (const Use &U : CA->operands()) { + if (const auto *Target = dyn_cast(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(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(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(CE->getOperand(1)) && + containsRootValue(CE->getOperand(0), Root, true); + case Instruction::Add: + case Instruction::Or: { + bool LeftRoot = isa(CE->getOperand(1)) && + containsRootValue(CE->getOperand(0), Root, true); + bool RightRoot = isa(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(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(Term) || isa(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 FnPred, + SmallVectorImpl &OutInsts) { + SmallVector Worklist{Root}; + SmallPtrSet Visited{Root}; + SmallPtrSet 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(Usr)) { + if (!containsRootValue(CE, Root, AllowSwiftBias)) + return false; + if (Visited.insert(CE).second) + Worklist.push_back(CE); + continue; + } + if (isa(Usr)) + return false; + + const auto *Inst = dyn_cast(Usr); + if (!Inst || !Inst->getParent() || Inst->getParent()->isEHPad()) + return false; + if (isa(Inst) || Inst->isEHPad()) + return false; + if (const auto *CB = dyn_cast(Inst)) { + if (&U == &CB->getCalledOperandUse()) + return false; + } + + if (const auto *PN = dyn_cast(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(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(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 LeafInsts, StringSet<> &SeenFunctions, + std::vector &TouchedFunctions) { + for (Instruction *UI : LeafInsts) { + if (auto *PN = dyn_cast(UI)) { + DenseMap, 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(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(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 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(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 KeyBytes(Len); + SmallVector EncBytes(Len); + for (size_t i = 0; i < Len; ++i) { + uint8_t K = RNG.nextNonZeroByte(); + KeyBytes[i] = K; + EncBytes[i] = static_cast(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 LeafInsts, + StringSet<> &SeenFunctions, + std::vector &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 FuncBufs; + for (Instruction *UI : LeafInsts) { + auto *CI = cast(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(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 &PreservedUsed, + const SmallPtrSet &AliasedGlobals, + uint64_t &NextId, StringSet<> &SeenFunctions, + std::vector &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(CFGV->getInitializer()); + if (!CS || CS->getNumOperands() != 4) + return false; + + const auto *ClassGV = + dyn_cast(CS->getOperand(0)->stripPointerCasts()); + if (!ClassGV || ClassGV->getName() != "__CFConstantStringClassReference") + return false; + + const auto *FlagsCI = dyn_cast(CS->getOperand(1)); + const auto *LenCI = dyn_cast(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(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(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 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(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(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 PreservedUsed; + collectCompilerUsed(M, "llvm.used", PreservedUsed); + collectCompilerUsed(M, "llvm.compiler.used", PreservedUsed); + + SmallPtrSet AliasedGlobals; + for (const GlobalAlias &GA : M.aliases()) { + if (const auto *AliaseeGV = + dyn_cast(GA.getAliasee()->stripPointerCasts())) { + AliasedGlobals.insert(AliaseeGV); + } + } + + SmallVector Candidates; + for (GlobalVariable &GV : M.globals()) { + Candidates.push_back(&GV); + } + + bool Changed = false; + uint64_t NextId = 0; + StringSet<> SeenFunctions; + std::vector 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(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 Buf(TotalLen, 0); + size_t CopyLen = std::min(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(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 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 diff --git a/tests/fixtures/archive_binding_host.c b/tests/fixtures/archive_binding_host.c index 8906e46..924f999 100644 --- a/tests/fixtures/archive_binding_host.c +++ b/tests/fixtures/archive_binding_host.c @@ -14,7 +14,7 @@ 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,"ig_archive_check"); + 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)); @@ -59,7 +59,7 @@ int main(int argc, char **argv) { for (uint64_t k=0;ksize/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,"_ig_a0")) slot=(void *)(slide+s->addr+k*8); + if (!strcmp(strings+symbols[n].n_un.n_strx,"_rd_a0")) slot=(void *)(slide+s->addr+k*8); } } } @@ -71,7 +71,7 @@ int main(int argc, char **argv) { 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,"ig_a0"); + 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); diff --git a/tests/fixtures/defender_host.c b/tests/fixtures/defender_host.c index be69e59..865013a 100644 --- a/tests/fixtures/defender_host.c +++ b/tests/fixtures/defender_host.c @@ -34,12 +34,19 @@ __attribute__((noinline)) static void *getpid_address(void) { return (void *)get 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; } @@ -143,23 +150,31 @@ int main(int argc, char **argv) { 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; /* 未登记的方法在 check 中不产生条目;登记方法未变 → 0 detected。 */ const IGObjCWatch none[] = { { "IGClassThatNeverExists123", "x" } }; ig_objc_baseline_capture(none,1); if (ig_objc_baseline_check(collect,&f)!=0) return 11; /* 类不可解析不登记 → 仍 no-op */ 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; } if (!strcmp(argv[1],"objc-swap")) { Class c=make_fixture_class(); if (!c) return 9; - const IGObjCWatch watch[] = { { "IGFixtureHookTarget", "value" } }; - if (ig_objc_baseline_capture(watch,1)!=1) return 10; - /* class_replaceMethod:IMP 换人(等价 swizzle 效果)→ 期望 DETECTED(110)。 */ + 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!=1 || f.reasons[IG_REASON_OBJC_IMP_CHANGED]!=1; + return hits!=2 || f.reasons[IG_REASON_OBJC_IMP_CHANGED]!=2; } return 2; } diff --git a/tests/fixtures/dispatch_host.c b/tests/fixtures/dispatch_host.c index 0d9fea3..c86b213 100644 --- a/tests/fixtures/dispatch_host.c +++ b/tests/fixtures/dispatch_host.c @@ -10,6 +10,8 @@ #include #include #include +#include +#include static int early_ok; __attribute__((constructor)) static void early(void) { @@ -64,8 +66,75 @@ int main(int argc,char **argv) { } 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); - assert(ig_dispatch_check(collect,NULL)==0 && unavailable==2); - assert(reasons[IG_REASON_DISPATCH_UNAVAILABLE]==2); + 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); @@ -123,9 +192,30 @@ int main(int argc,char **argv) { } 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)); } else return 2; return 0; } diff --git a/tests/fixtures/gcd_file_integration.m b/tests/fixtures/gcd_file_integration.m new file mode 100644 index 0000000..a580b14 --- /dev/null +++ b/tests/fixtures/gcd_file_integration.m @@ -0,0 +1,106 @@ +#import +#import "GCDWebServerPrivate.h" +#include "dispatch/IGDispatch.h" +#include +#include +#include +#include + +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; +} diff --git a/tests/test_anti_hooking_pass.py b/tests/test_anti_hooking_pass.py new file mode 100644 index 0000000..9fb3160 --- /dev/null +++ b/tests/test_anti_hooking_pass.py @@ -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 + +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 +#include +#include + +__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() diff --git a/tests/test_archive_guard.py b/tests/test_archive_guard.py index 3929d48..0eb6738 100644 --- a/tests/test_archive_guard.py +++ b/tests/test_archive_guard.py @@ -32,6 +32,21 @@ class FrameworkRewriteTests(unittest.TestCase): 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): @@ -95,7 +110,7 @@ class ArchiveBindingIntegrationTests(unittest.TestCase): def test_real_dyld_binding_and_got_tamper(self): with tempfile.TemporaryDirectory() as folder: root = Path(folder) - guard = root/'IGArchiveGuard.framework/IGArchiveGuard' + 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'] diff --git a/tests/test_dispatch.py b/tests/test_dispatch.py index 0ef6beb..74ed5f0 100644 --- a/tests/test_dispatch.py +++ b/tests/test_dispatch.py @@ -25,6 +25,9 @@ class DispatchTests(unittest.TestCase): 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') @@ -52,6 +55,15 @@ class DispatchTests(unittest.TestCase): '-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' diff --git a/tests/test_gcd_file_integration.py b/tests/test_gcd_file_integration.py new file mode 100644 index 0000000..01632c0 --- /dev/null +++ b/tests/test_gcd_file_integration.py @@ -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() diff --git a/tests/test_indirect_branch_pass.py b/tests/test_indirect_branch_pass.py new file mode 100644 index 0000000..123e073 --- /dev/null +++ b/tests/test_indirect_branch_pass.py @@ -0,0 +1,398 @@ +"""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 + +__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) + self.assertEqual(ibr_res['failed_count'], 0) + self.assertGreaterEqual(ibr_res['verified_ibr_count'], 2) + 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.bc' + 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, '-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) + 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 +@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,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() diff --git a/tests/test_indirect_call_pass.py b/tests/test_indirect_call_pass.py new file mode 100644 index 0000000..45ef64d --- /dev/null +++ b/tests/test_indirect_call_pass.py @@ -0,0 +1,460 @@ +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 + + +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_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 \n' + '#include \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 \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 \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,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 \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 + +__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() diff --git a/tests/test_legacy_fopen.py b/tests/test_legacy_fopen.py new file mode 100644 index 0000000..50dcdbe --- /dev/null +++ b/tests/test_legacy_fopen.py @@ -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('\n' + '#include \n' + 'static const char *g_table[] = { "TABLE_ENTRY_LITERAL_ONE", "TABLE_ENTRY_LITERAL_TWO" };\n' + 'const char *read_table(int idx) { return g_table[idx & 1]; }\n' + 'NSString *get_cfstr(void) { return @"OBJC_CFSTRING_LITERAL_VALUE"; }\n' + 'const char *get_controlled(void) { return getenv("CONTROLLED_M0_ENV_KEY_VAR"); }\n', + encoding='utf-8', + ) + subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-fobjc-arc', '-emit-llvm', '-c', str(src), '-o', str(p / 'in.bc')], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_p}', '--ig-mode=str', '--ig-seed=ud_seed', + f'--ig-source-path={src}', f'--ig-audit-out={p / "audit.json"}', + str(p / 'in.bc'), '-o', str(p / 'out.bc'), + ], check=True) + subprocess.run([ + clang, '-S', '-emit-llvm', '-Xclang', '-disable-llvm-passes', + '-x', 'ir', str(p / 'out.bc'), '-o', str(p / 'out.ll'), + ], check=True) + audit = json.loads((p / 'audit.json').read_text(encoding='utf-8')) + ll = (p / 'out.ll').read_text(encoding='utf-8') + self.assertEqual(audit['strings_encrypted_count'], 1) + self.assertGreaterEqual(audit['strings_skipped_count'], 1) + self.assertIn('__ig_dec_str_0', ll) + self.assertNotIn('CONTROLLED_M0_ENV_KEY_VAR', ll) + self.assertIn('TABLE_ENTRY_LITERAL_ONE', ll) + self.assertIn('OBJC_CFSTRING_LITERAL_VALUE', ll) + + def test_concurrent_string_decryption_and_flattening_host_stress(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() + with tempfile.TemporaryDirectory() as td: + p = Path(td) + policy_p = p / 'policy.json' + policy_p.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'string_encrypt_targets': [{'path_contains': 'stress.c'}], + 'flatten_targets': [{'path_contains': 'stress.c', 'function_contains': 'branchy_secret'}], + }), encoding='utf-8') + src = p / 'stress.c' + src.write_text( + '#include \n' + '#include \n' + '#include \n' + '#include \n' + 'static atomic_int g_go = 0;\n' + '__attribute__((noinline)) void consume_a(const char *s, char *out) { snprintf(out, 64, "%s", s); }\n' + '__attribute__((noinline)) void consume_b(const char *s, char *out) { snprintf(out, 64, "%s!", s); }\n' + '__attribute__((noinline)) void consume_c(const char *s, char *out) { snprintf(out, 64, "%s?", s); }\n' + '__attribute__((noinline)) void consume_d(const char *s, char *out) { snprintf(out, 64, "%s.", s); }\n' + '__attribute__((noinline)) int branchy_secret(int mode, char *out) {\n' + ' if (mode == 1) { consume_a("MULTI_THREAD_CONCURRENT_TOKEN_A", out); return 11; }\n' + ' if (mode == 2) { consume_b("MULTI_THREAD_CONCURRENT_TOKEN_B", out); return 22; }\n' + ' if (mode == 3) { consume_c("MULTI_THREAD_CONCURRENT_TOKEN_C", out); return 33; }\n' + ' consume_d("MULTI_THREAD_CONCURRENT_TOKEN_D", out); return 44;\n' + '}\n' + 'static void *worker(void *arg) {\n' + ' int idx = (int)(long)arg;\n' + ' while (!atomic_load_explicit(&g_go, memory_order_acquire)) {}\n' + ' char buf[64];\n' + ' int rc = branchy_secret((idx % 4) + 1, buf);\n' + ' if (rc == 11 && strncmp(buf, "MULTI_THREAD_CONCURRENT_TOKEN_A", 31) == 0) return (void *)1;\n' + ' if (rc == 22 && strncmp(buf, "MULTI_THREAD_CONCURRENT_TOKEN_B!", 32) == 0) return (void *)1;\n' + ' if (rc == 33 && strncmp(buf, "MULTI_THREAD_CONCURRENT_TOKEN_C?", 32) == 0) return (void *)1;\n' + ' if (rc == 44 && strncmp(buf, "MULTI_THREAD_CONCURRENT_TOKEN_D.", 32) == 0) return (void *)1;\n' + ' return (void *)0;\n' + '}\n' + 'int main(void) {\n' + ' pthread_t th[8];\n' + ' for (long i = 0; i < 8; ++i) pthread_create(&th[i], NULL, worker, (void *)i);\n' + ' atomic_store_explicit(&g_go, 1, memory_order_release);\n' + ' for (int i = 0; i < 8; ++i) {\n' + ' void *res = NULL; pthread_join(th[i], &res);\n' + ' if (res != (void *)1) return 2;\n' + ' }\n' + ' return 0;\n' + '}\n', + encoding='utf-8', + ) + subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-emit-llvm', '-c', str(src), '-o', str(p / 's.bc')], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_p}', '--ig-mode=full', '--ig-seed=stress_seed', + f'--ig-source-path={src}', f'--ig-audit-out={p / "s_audit.json"}', + str(p / 's.bc'), '-o', str(p / 's_obf.bc'), + ], check=True) + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', + '-x', 'ir', '-c', str(p / 's_obf.bc'), '-o', str(p / 's.o'), + ], check=True) + subprocess.run([clang, '-isysroot', macos_sdk, str(p / 's.o'), '-lpthread', '-o', str(p / 'stress_bin')], check=True) + audit = json.loads((p / 's_audit.json').read_text(encoding='utf-8')) + self.assertIn('branchy_secret', audit['functions_flattened'][0] if audit['functions_flattened'] else '') + self.assertGreaterEqual(audit['strings_encrypted_count'], 4) + # Confirm encrypted binary omits original plain tokens (Note: worker strcmp also uses them? Wait: only branchy_secret was obfuscated unless strcmp tokens in main/worker also encrypted since whole stress.c matches!) + raw_bin = (p / 'stress_bin').read_bytes() + self.assertNotIn(b'MULTI_THREAD_CONCURRENT_TOKEN_A', raw_bin) + for _ in range(15): + subprocess.run([str(p / 'stress_bin')], check=True) + + def test_flattening_seed_determinism_and_diversity(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() + with tempfile.TemporaryDirectory() as td: + p = Path(td) + policy_p = p / 'policy.json' + policy_p.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'string_encrypt_targets': [], + 'flatten_targets': [{'path_contains': 'det.c', 'function_contains': 'det_fn'}], + }), encoding='utf-8') + src = p / 'det.c' + src.write_text( + 'extern int det_ext_a(int);\n' + 'extern int det_ext_b(int);\n' + 'extern int det_ext_c(int);\n' + 'int det_fn(int a, int b) {\n' + ' int r = a;\n' + ' if (a > 10) r += det_ext_a(b * 3);\n' + ' else r -= det_ext_b(b);\n' + ' if (r & 1) r ^= det_ext_c(0x5a5a);\n' + ' else r += 17;\n' + ' if (r < 0) return -r;\n' + ' return r;\n' + '}\n', + encoding='utf-8', + ) + subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-emit-llvm', '-c', str(src), '-o', str(p / 'det.bc')], check=True) + + def compile_with_seed(tag, seed): + obf_bc = p / f'{tag}.bc' + obj = p / f'{tag}.o' + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_p}', '--ig-mode=full', f'--ig-seed={seed}', + f'--ig-source-path={src}', str(p / 'det.bc'), '-o', str(obf_bc), + ], check=True) + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', + '-x', 'ir', '-c', str(obf_bc), '-o', str(obj), + ], check=True) + dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble-symbols=_det_fn', str(obj)], text=True) + dis_body = '\n'.join(dis.splitlines()[2:]) + return hashlib.sha256(obj.read_bytes()).hexdigest(), dis_body + + h_a1, dis_a1 = compile_with_seed('a1', 'seed_alpha') + h_a2, dis_a2 = compile_with_seed('a2', 'seed_alpha') + h_b, dis_b = compile_with_seed('b', 'seed_beta') + self.assertEqual(h_a1, h_a2) + self.assertEqual(dis_a1, dis_a2) + self.assertNotEqual(h_a1, h_b) + self.assertNotEqual(dis_a1, dis_b) + + def test_restore_crash_report_dual_formats_and_uuid_guard(self): + clang = detect_stock_tool('clang') + macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() + with tempfile.TemporaryDirectory() as td: + p = Path(td) + (p / 'fw.c').write_text('int fw_work(int x) {\n return x * 7 + 3;\n}\n', encoding='utf-8') + (p / 'main.c').write_text('int fw_work(int x);\nint main(void) {\n return fw_work(6);\n}\n', encoding='utf-8') + fw = p / 'libDummyKit.dylib' + app = p / 'DummyApp' + subprocess.run([clang, '-isysroot', macos_sdk, '-g', '-O0', '-c', str(p / 'fw.c'), '-o', str(p / 'fw.o')], check=True) + subprocess.run([clang, '-isysroot', macos_sdk, '-g', '-O0', '-c', str(p / 'main.c'), '-o', str(p / 'main.o')], check=True) + subprocess.run([clang, '-isysroot', macos_sdk, '-g', '-dynamiclib', str(p / 'fw.o'), '-Wl,-install_name,@rpath/libDummyKit.dylib', '-o', str(fw)], check=True) + subprocess.run([clang, '-isysroot', macos_sdk, '-g', str(p / 'main.o'), str(fw), '-o', str(app)], check=True) + dsym_dir = p / 'dsyms' + dsym_dir.mkdir() + subprocess.run(['xcrun', 'dsymutil', str(fw), '-o', str(dsym_dir / 'libDummyKit.dylib.dSYM')], check=True) + subprocess.run(['xcrun', 'dsymutil', str(app), '-o', str(dsym_dir / 'DummyApp.dSYM')], check=True) + + idx = restore_crash_report.index_dsyms(dsym_dir) + self.assertEqual(len(idx), 2) + + def get_uuid_and_sym(bin_p, sym): + out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(bin_p)], text=True) + uid = out.split()[1] + nm = subprocess.check_output(['nm', str(bin_p)], text=True) + addr = next(int(l.split()[0], 16) for l in nm.splitlines() if f' {sym}' in l or l.endswith(f' {sym}')) + return uid, addr + + app_uid, main_vm = get_uuid_and_sym(app, '_main') + fw_uid, fw_vm = get_uuid_and_sym(fw, '_fw_work') + + # Real VM layout check from otool -l __TEXT vmaddr + def text_vmaddr(bin_p): + ot = subprocess.check_output(['otool', '-l', str(bin_p)], text=True).splitlines() + for i, l in enumerate(ot): + if 'segname __TEXT' in l: + for j in range(i + 1, min(i + 6, len(ot))): + if 'vmaddr' in ot[j]: + return int(ot[j].split()[1], 16) + return 0 + + app_base_static = text_vmaddr(app) + fw_base_static = text_vmaddr(fw) + app_load = 0x104000000 + fw_load = 0x108000000 + app_off = main_vm - app_base_static + 4 + fw_off = fw_vm - fw_base_static + 4 + + ips_path = p / 'sample.ips' + ips_header = json.dumps({'app_name': 'DummyApp', 'bug_type': '309'}) + ips_body = json.dumps({ + 'usedImages': [ + {'base': app_load, 'size': 16384, 'uuid': app_uid, 'name': 'DummyApp', 'arch': 'arm64', 'path': '/private/var/DummyApp.app/DummyApp'}, + {'base': fw_load, 'size': 16384, 'uuid': fw_uid, 'name': 'libDummyKit.dylib', 'arch': 'arm64', 'path': '/private/var/DummyApp.app/Frameworks/libDummyKit.dylib'}, + ], + 'threads': [{ + 'triggered': True, + 'frames': [ + {'imageIndex': 0, 'imageOffset': app_off}, + {'imageIndex': 1, 'imageOffset': fw_off}, + ], + }], + }) + ips_path.write_text(ips_header + '\n' + ips_body + '\n', encoding='utf-8') + res_ips = restore_crash_report.restore_report(ips_path, dsym_dir) + self.assertEqual(res_ips['format'], 'ips_json') + frames = res_ips['threads'][0]['frames'] + self.assertIn('main.c:', frames[0]['restored_frames'][0]) + self.assertIn('fw.c:', frames[1]['restored_frames'][0]) + + crash_path = p / 'sample.crash' + crash_path.write_text( + 'Thread 0 Crashed:\n' + f'0 DummyApp {hex(app_load + app_off)} {hex(app_load)} + {app_off}\n' + f'1 libDummyKit.dylib {hex(fw_load + fw_off)} {hex(fw_load)} + {fw_off}\n\n' + 'Binary Images:\n' + f' {hex(app_load)} - {hex(app_load + 0x4000)} DummyApp arm64 <{app_uid}> /private/var/DummyApp.app/DummyApp\n' + f' {hex(fw_load)} - {hex(fw_load + 0x4000)} libDummyKit.dylib arm64 <{fw_uid}> /private/var/DummyApp.app/Frameworks/libDummyKit.dylib\n', + encoding='utf-8', + ) + res_crash = restore_crash_report.restore_report(crash_path, dsym_dir) + self.assertEqual(res_crash['format'], 'crash_text') + self.assertIn('main.c:', res_crash['frames'][0]['restored_frames'][0]) + self.assertIn('fw.c:', res_crash['frames'][1]['restored_frames'][0]) + + # Negative UUID mismatch check + bad_ips = p / 'bad.ips' + bad_ips.write_text( + ips_header + '\n' + ips_body.replace(app_uid, '00000000-0000-0000-0000-000000000000') + '\n', + encoding='utf-8', + ) + with self.assertRaisesRegex(RuntimeError, 'UUID mismatch'): + restore_crash_report.restore_report(bad_ips, dsym_dir) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_llvm_obf_m1.py b/tests/test_llvm_obf_m1.py new file mode 100644 index 0000000..2bea853 --- /dev/null +++ b/tests/test_llvm_obf_m1.py @@ -0,0 +1,234 @@ +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf' +APP_REPO = ROOT / 'readoor-test' + +sys.path.insert(0, str(TOOLS_LLVM_OBF)) + +from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402 + + +def require_host_opt(): + 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 + + +class TestLLVMObfM1(unittest.TestCase): + def test_polymorphic_flattening_topologies_encodings_and_inline_asm_skip(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() + + with tempfile.TemporaryDirectory() as td: + p = Path(td) + policy_p = p / 'policy.json' + policy_p.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'string_encrypt_targets': [], + 'flatten_targets': [{'path_contains': 'poly_test.c'}], + }), encoding='utf-8') + + src = p / 'poly_test.c' + src.write_text( + '#include \n' + '#include \n' + '__attribute__((noinline)) int leaf_fn(int a, int b) { return a * 17 + b * 31; }\n' + 'int poly_multi_branch(int x, int y) {\n' + ' int acc = 7;\n' + ' if (x & 1) acc += leaf_fn(x, 1);\n' + ' if (x & 2) acc ^= leaf_fn(y, 2);\n' + ' if (x & 4) acc += leaf_fn(x + y, 3);\n' + ' if (x & 8) acc -= leaf_fn(y - x, 4);\n' + ' if (x > 12) acc += leaf_fn(x, y);\n' + ' if (y < 0) acc ^= 0x5A5A;\n' + ' if (acc > 200) acc -= 19;\n' + ' return acc;\n' + '}\n' + 'int has_inline_asm(int v) {\n' + ' int out = v;\n' + ' if (v > 3) { __asm__ volatile("" : "+r"(out)); }\n' + ' return out + 1;\n' + '}\n' + 'int main(void) {\n' + ' uint32_t h = 2166136261u;\n' + ' for (int x = -4; x < 24; ++x) {\n' + ' for (int y = -3; y < 5; ++y) {\n' + ' uint32_t v = (uint32_t)poly_multi_branch(x, y);\n' + ' h = (h ^ v) * 16777619u;\n' + ' }\n' + ' }\n' + ' printf("HASH=%08x ASM=%d\\n", h, has_inline_asm(5));\n' + ' return 0;\n' + '}\n', + encoding='utf-8', + ) + bc_p = p / 'poly.bc' + subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-g', '-emit-llvm', '-c', str(src), '-o', str(bc_p)], check=True) + + # Reference un-obfuscated output + ref_bin = p / 'poly_ref' + subprocess.run([clang, '-isysroot', macos_sdk, '-Os', str(src), '-o', str(ref_bin)], check=True) + ref_out = subprocess.check_output([str(ref_bin)], text=True).strip() + + seen_topos = set() + seen_encs = set() + asm_skip_seen = False + + for idx in range(24): + seed = f'm1_poly_probe_{idx}' + obf_bc = p / f'poly_{idx}.obf.bc' + obj_o = p / f'poly_{idx}.o' + bin_p = p / f'poly_{idx}' + audit_p = p / f'audit_{idx}.json' + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_p}', '--ig-mode=full', + f'--ig-seed={seed}', f'--ig-source-path={src}', + f'--ig-audit-out={audit_p}', str(bc_p), '-o', str(obf_bc), + ], check=True) + audit = json.loads(audit_p.read_text(encoding='utf-8')) + for det in audit.get('functions_flattened_details') or []: + if 'poly_multi_branch' in det['name']: + seen_topos.add(det['topology']) + seen_encs.add(det['encoding']) + for sk in audit.get('functions_skipped') or []: + if 'has_inline_asm' in sk['name'] and sk['reason'] == 'inline_asm': + asm_skip_seen = True + + # Execute every topology/encoding variant and check exact semantic output! + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', + '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', + '-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o), + ], check=True) + subprocess.run([clang, '-isysroot', macos_sdk, str(obj_o), '-o', str(bin_p)], check=True) + out = subprocess.check_output([str(bin_p)], text=True).strip() + self.assertEqual(out, ref_out, f'Semantic mismatch on seed={seed}: {out} vs {ref_out}') + + self.assertEqual(seen_topos, {'sparse_switch', 'cascaded_subdisp', 'asymmetric_cmp_tree'}, f'Missing topologies: {seen_topos}') + self.assertEqual(seen_encs, {'xor_rot', 'odd_affine_mul', 'add_xor'}, f'Missing encodings: {seen_encs}') + self.assertTrue(asm_skip_seen, 'Expected inline_asm skip reason for has_inline_asm') + + def test_epub_keybox_derivation_obfuscation_and_poisoning(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() + + keybox_c = APP_REPO / 'readoor/3.0/Base/Security/RDEpubKeyBox.c' + keybox_h = APP_REPO / 'readoor/3.0/Base/Security/RDEpubKeyBox.h' + defender_dir = ROOT / 'defender' + poison_c = defender_dir / 'poison/IGPoison.c' + policy_path = ROOT / 'config/ig_llvm_policy.json' + self.assertTrue(keybox_c.is_file() and keybox_h.is_file()) + + with tempfile.TemporaryDirectory() as td: + p = Path(td) + kb_bc = p / 'RDEpubKeyBox.bc' + kb_obf_bc = p / 'RDEpubKeyBox.obf.bc' + kb_o = p / 'RDEpubKeyBox.o' + audit_p = p / 'kb.audit.json' + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', '-g', '-fvisibility=hidden', + '-I', str(defender_dir), '-I', str(defender_dir / 'include'), + '-I', str(keybox_c.parent), + '-emit-llvm', '-c', str(keybox_c), '-o', str(kb_bc), + ], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', + '--ig-seed=m1_unit_kb_seed', f'--ig-source-path={keybox_c}', + f'--ig-audit-out={audit_p}', str(kb_bc), '-o', str(kb_obf_bc), + ], check=True) + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', + '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', + '-x', 'ir', '-c', str(kb_obf_bc), '-o', str(kb_o), + ], check=True) + + audit = json.loads(audit_p.read_text(encoding='utf-8')) + self.assertGreaterEqual(audit['strings_encrypted_count'], 2, audit) + self.assertGreaterEqual(len(audit['functions_flattened']), 2, audit) + self.assertTrue(audit['functions_flattened_details']) + + raw_o = kb_o.read_bytes() + self.assertNotIn(b'startiasoft', raw_o) + self.assertNotIn(b'_rdep_', raw_o) + nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(kb_o)], text=True) + self.assertNotIn('_CC_MD5', nm_u) + + harness_c = p / 'harness.c' + harness_c.write_text( + '#include \n' + '#include \n' + '#include "RDEpubKeyBox.h"\n' + '#include "poison/IGPoison.h"\n' + 'int main(void) {\n' + ' char out[512];\n' + ' const char *books[] = {"", "BK2026", "book-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};\n' + ' for (int i = 0; i < 3; ++i) {\n' + ' size_t n = rd_epub_derive_book_key(books[i], strlen(books[i]), out, sizeof(out));\n' + ' printf("BOOK|%d|%zu|%s\\n", i, n, out);\n' + ' }\n' + ' const char *imgs[] = {"", "fig1.jpg", "章节图_01_45678901234567890123456789012345678901234567890.png"};\n' + ' for (int i = 0; i < 3; ++i) {\n' + ' size_t n = rd_epub_derive_media_key(imgs[i], strlen(imgs[i]), out, sizeof(out));\n' + ' printf("MEDIA|%d|%zu|%s\\n", i, n, out);\n' + ' }\n' + ' size_t pn = rd_epub_legacy_url_prefix(out, sizeof(out));\n' + ' printf("PREFIX|%zu|%s\\n", pn, out);\n' + ' ig_poison_mark(0x1122334455667788ULL);\n' + ' size_t bn = rd_epub_derive_book_key("BK2026", 6, out, sizeof(out));\n' + ' printf("POISON_BOOK|%zu|", bn);\n' + ' for (size_t k = 0; k < bn; ++k) printf("%02x", (unsigned char)out[k]);\n' + ' printf("\\n");\n' + ' return 0;\n' + '}\n', + encoding='utf-8', + ) + bin_p = p / 'kb_runner' + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', + '-I', str(defender_dir), '-I', str(defender_dir / 'include'), + '-I', str(keybox_c.parent), + str(harness_c), str(poison_c), str(kb_o), '-o', str(bin_p), + ], check=True) + lines = subprocess.check_output([str(bin_p)], text=True).splitlines() + salt = 'startiasoft' + books = ['', 'BK2026', 'book-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'] + imgs = ['', 'fig1.jpg', '章节图_01_45678901234567890123456789012345678901234567890.png'] + expected_bk = None + for line in lines: + parts = line.split('|') + if parts[0] == 'BOOK': + i = int(parts[1]) + exp = (salt + books[i]) * 2 + self.assertEqual(int(parts[2]), len(exp)) + self.assertEqual(parts[3], exp) + if i == 1: + expected_bk = exp.encode('utf-8').hex() + elif parts[0] == 'MEDIA': + i = int(parts[1]) + digest = hashlib.md5((imgs[i] + salt).encode('utf-8')).hexdigest() + exp = (salt + digest) * 2 + self.assertEqual(int(parts[2]), len(exp)) + self.assertEqual(parts[3], exp) + elif parts[0] == 'PREFIX': + self.assertEqual(int(parts[1]), 6) + self.assertEqual(parts[2], '_rdep_') + elif parts[0] == 'POISON_BOOK': + self.assertNotEqual(parts[2], expected_bk) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_llvm_obf_m2.py b/tests/test_llvm_obf_m2.py new file mode 100644 index 0000000..ef1c4c5 --- /dev/null +++ b/tests/test_llvm_obf_m2.py @@ -0,0 +1,251 @@ +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf' +APP_REPO = ROOT / 'readoor-test' + +sys.path.insert(0, str(TOOLS_LLVM_OBF)) + +from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402 + + +def require_host_opt(): + 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 sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def file_sha256(path: Path) -> str: + return sha256_bytes(path.read_bytes()) + + +class TestLLVMObfM2(unittest.TestCase): + def test_m2_policy_and_diag_events_config(self): + diag_path = ROOT / 'config' / 'ig_diag_events.json' + policy_path = ROOT / 'config' / 'ig_llvm_policy.json' + diag = json.loads(diag_path.read_text(encoding='utf-8')) + policy = json.loads(policy_path.read_text(encoding='utf-8')) + + events = diag.get('events') or {} + expected_codes = ( + [f'E-41{i:02d}' for i in range(1, 12)] + + [f'E-51{i:02d}' for i in range(1, 37)] + + [f'E-519{i}' for i in range(1, 5)] + + [f'E-61{i:02d}' for i in range(1, 13)] + ) + missing = [c for c in expected_codes if c not in events] + self.assertEqual(missing, [], f'Missing M2 diagnostic codes in ig_diag_events.json: {missing}') + + required_ids = {t.get('id') for t in (policy.get('required_targets') or [])} + expected_req = { + 'c_rd_sd_keybox', + 'swift_sd_key_manager', + 'swift_sd_signer', + 'swift_iap_handler', + 'objc_iap_verify_handler', + } + self.assertTrue(expected_req.issubset(required_ids), f'Missing required_targets: {expected_req - required_ids}') + + def test_sd_keybox_obfuscation_derivation_and_seed_polymorphism(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() + + keybox_c = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.c' + keybox_h = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.h' + defender_dir = ROOT / 'defender' + poison_c = defender_dir / 'poison/IGPoison.c' + policy_path = ROOT / 'config/ig_llvm_policy.json' + self.assertTrue(keybox_c.is_file() and keybox_h.is_file()) + + with tempfile.TemporaryDirectory(prefix='ig-m2-unit-') as td: + p = Path(td) + raw_bc = p / 'RDSDKeyBox.bc' + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', '-g', '-fvisibility=hidden', + '-I', str(defender_dir), '-I', str(defender_dir / 'include'), + '-I', str(keybox_c.parent), + '-emit-llvm', '-c', str(keybox_c), '-o', str(raw_bc), + ], check=True) + + def compile_variant(tag: str, seed: str): + obf_bc = p / f'{tag}.obf.bc' + obj_o = p / f'{tag}.o' + audit_p = p / f'{tag}.audit.json' + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', + '--ig-mode=full', + '--ig-pass-filter=all', + f'--ig-seed={seed}', + f'--ig-source-path={keybox_c}', + f'--ig-audit-out={audit_p}', + str(raw_bc), '-o', str(obf_bc), + ], check=True) + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', + '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', + '-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o), + ], check=True) + disasm = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(obj_o)], text=True) + return { + 'obf_bc': obf_bc, + 'obj_o': obj_o, + 'obf_bc_sha256': file_sha256(obf_bc), + 'obj_sha256': file_sha256(obj_o), + 'text_disasm_sha256': sha256_bytes(disasm.encode('utf-8')), + 'audit': json.loads(audit_p.read_text(encoding='utf-8')), + } + + unit = compile_variant('unit', 'm2_unit_kb_seed') + audit = unit['audit'] + self.assertGreaterEqual(audit.get('strings_encrypted_count', 0), 6, audit) + flattened = audit.get('functions_flattened') or [] + self.assertGreaterEqual(len(flattened), 6, audit) + self.assertTrue(any('rd_sd_derive_aes256_key' in name for name in flattened), audit) + self.assertTrue(any('rd_sd_derive_v31_seed' in name for name in flattened), audit) + self.assertTrue(any('rd_sd_derive_v31_dt_pwd' in name for name in flattened), audit) + + raw_o = unit['obj_o'].read_bytes() + for leaked in ( + b'readoor_sd_v32', + b'KSDPrivateKeyPEM', + b'rd_net_cfg_v1', + b'rd_glyph_lut_v2', + b'encrypted_private_key', + b'cn.touchv.payment.models.keychain', + b'7ARrksiF7AoWXXBlmxfz9suSmTka7A', + ): + self.assertNotIn(leaked, raw_o, f'Plaintext {leaked!r} leaked into RDSDKeyBox.o') + + harness_c = p / 'harness.c' + harness_c.write_text( + '#include \n' + '#include \n' + '#include \n' + '#include "RDSDKeyBox.h"\n' + '#include "poison/IGPoison.h"\n' + 'int main(void) {\n' + ' uint8_t key[32];\n' + ' int null_rc = rd_sd_derive_aes256_key(NULL);\n' + ' int ok_rc = rd_sd_derive_aes256_key(key);\n' + ' printf("DERIVE|%d|%d|", null_rc, ok_rc);\n' + ' for (size_t i = 0; i < sizeof(key); ++i) printf("%02x", key[i]);\n' + ' printf("\\n");\n' + ' char buf[128];\n' + ' size_t n_slot = rd_sd_keychain_slot_name(buf, sizeof(buf));\n' + ' printf("SLOT|%zu|%s\\n", n_slot, buf);\n' + ' size_t n_stem = rd_sd_bundle_asset_stem(buf, sizeof(buf));\n' + ' printf("STEM|%zu|%s\\n", n_stem, buf);\n' + ' size_t n_acct = rd_iap_keychain_account_name(buf, sizeof(buf));\n' + ' printf("ACCT|%zu|%s\\n", n_acct, buf);\n' + ' size_t n_v31 = rd_sd_derive_v31_seed(buf, sizeof(buf));\n' + ' printf("V31SEED|%zu|%s\\n", n_v31, buf);\n' + ' const char *nonce = "n1234567890";\n' + ' const char *suffix = "1700000000000GUID_V1iOS";\n' + ' size_t n_dt = rd_sd_derive_v31_dt_pwd(nonce, strlen(nonce), suffix, strlen(suffix), buf, sizeof(buf));\n' + ' printf("V31DT|%zu|%s\\n", n_dt, buf);\n' + ' printf("SMALL|%zu|%zu|%zu\\n",\n' + ' rd_sd_keychain_slot_name(NULL, 10),\n' + ' rd_sd_bundle_asset_stem(buf, 0),\n' + ' rd_iap_keychain_account_name(buf, 4));\n' + ' ig_poison_mark(0xCAFEBABE12345678ULL);\n' + ' char pbuf[64], pdt[64];\n' + ' size_t pn_v31 = rd_sd_derive_v31_seed(pbuf, sizeof(pbuf));\n' + ' size_t pn_dt = rd_sd_derive_v31_dt_pwd(nonce, strlen(nonce), suffix, strlen(suffix), pdt, sizeof(pdt));\n' + ' printf("PV31SEED|%zu|%zu|%s\\n", pn_v31, strlen(pbuf), strcmp(pbuf, "7ARrksiF7AoWXXBlmxfz9suSmTka7A") != 0 ? "CHANGED" : "SAME");\n' + ' printf("PV31DT|%zu|%s\\n", pn_dt, pdt);\n' + ' return 0;\n' + '}\n', + encoding='utf-8', + ) + runner = p / 'kb_runner' + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', + '-I', str(defender_dir), '-I', str(defender_dir / 'include'), + '-I', str(keybox_c.parent), + str(harness_c), + str(poison_c), + str(defender_dir / 'resolve/IGResolve.c'), + str(defender_dir / 'anti_hook/IGAntiHook.c'), + str(defender_dir / 'dispatch/IGDispatch.c'), + str(unit['obj_o']), + '-framework', 'Security', '-framework', 'CoreFoundation', + '-o', str(runner), + ], check=True) + lines = subprocess.check_output([str(runner)], text=True).splitlines() + expected_key = hashlib.pbkdf2_hmac( + 'sha256', + b'readoor_sd_v32_ci_key_2026', + b'readoor_sd_v32_salt_fixed', + 100_000, + 32, + ).hex() + expected_v31_seed = '7ARrksiF7AoWXXBlmxfz9suSmTka7A' + expected_v31_dt = hashlib.md5( + ('n1234567890' + expected_v31_seed + '1700000000000GUID_V1iOS').encode('utf-8') + ).hexdigest() + + seen_tags = set() + for line in lines: + parts = line.split('|') + seen_tags.add(parts[0]) + if parts[0] == 'DERIVE': + self.assertEqual(parts[1], '-1') + self.assertEqual(parts[2], '0') + self.assertEqual(parts[3], expected_key) + elif parts[0] == 'SLOT': + self.assertEqual(int(parts[1]), 16) + self.assertEqual(parts[2], 'KSDPrivateKeyPEM') + elif parts[0] == 'STEM': + self.assertEqual(int(parts[1]), 15) + self.assertEqual(parts[2], 'rd_glyph_lut_v2') + elif parts[0] == 'ACCT': + self.assertEqual(int(parts[1]), 33) + self.assertEqual(parts[2], 'cn.touchv.payment.models.keychain') + elif parts[0] == 'V31SEED': + self.assertEqual(int(parts[1]), 30) + self.assertEqual(parts[2], expected_v31_seed) + elif parts[0] == 'V31DT': + self.assertEqual(int(parts[1]), 32) + self.assertEqual(parts[2], expected_v31_dt) + elif parts[0] == 'PV31SEED': + self.assertEqual(parts[1], '30') + self.assertEqual(parts[2], '30') + self.assertEqual(parts[3], 'CHANGED') + elif parts[0] == 'PV31DT': + self.assertEqual(parts[1], '32') + self.assertEqual(len(parts[2]), 32) + self.assertNotEqual(parts[2], expected_v31_dt) + elif parts[0] == 'SMALL': + self.assertEqual(parts[1:], ['0', '0', '0']) + self.assertEqual( + seen_tags, + {'DERIVE', 'SLOT', 'STEM', 'ACCT', 'V31SEED', 'V31DT', 'PV31SEED', 'PV31DT', 'SMALL'}, + ) + + # Same-seed determinism & cross-seed polymorphism + det_a = compile_variant('det_a', 'm2_seed_alpha') + det_b = compile_variant('det_b', 'm2_seed_alpha') + self.assertEqual(det_a['obf_bc_sha256'], det_b['obf_bc_sha256']) + self.assertEqual(det_a['obj_sha256'], det_b['obj_sha256']) + + seeds = ['m2_seed_alpha', 'm2_seed_beta', 'm2_seed_gamma'] + variants = {s: compile_variant(f'seed_{s}', s) for s in seeds} + self.assertEqual(len({variants[s]['text_disasm_sha256'] for s in seeds}), len(seeds)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_llvm_obf_m3.py b/tests/test_llvm_obf_m3.py new file mode 100644 index 0000000..f97d733 --- /dev/null +++ b/tests/test_llvm_obf_m3.py @@ -0,0 +1,1077 @@ +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parent.parent +APP_REPO = ROOT / 'readoor-test' +OBF_DIR = APP_REPO / 'AutoPacking' / 'obfuscation' +TOOLS_CRASH = ROOT / 'tools' / 'crash_restore' +TOOLS_OBF = ROOT / 'tools' / 'llvm_obf' + +sys.path.insert(0, str(OBF_DIR)) +sys.path.insert(0, str(TOOLS_CRASH)) +sys.path.insert(0, str(TOOLS_OBF)) + +import ig_toolchain_resolver # noqa: E402 +import obfuscate_symbols as obf # noqa: E402 +import restore_crash_report # noqa: E402 +import verify_macho_star_cfg # noqa: E402 + + +class TestMilestone3ObfuscationAndPolicy(unittest.TestCase): + def _stage_obf_runtime(self, dst_repo: Path): + dst_obf = dst_repo / 'AutoPacking' / 'obfuscation' + dst_obf.mkdir(parents=True, exist_ok=True) + shutil.copy2(OBF_DIR / 'obfuscate_symbols.py', dst_obf / 'obfuscate_symbols.py') + shutil.copytree(OBF_DIR / 'obfuscation_runtime', dst_obf / 'obfuscation_runtime', dirs_exist_ok=True) + (dst_obf / 'scripts').mkdir(parents=True, exist_ok=True) + shutil.copy2(OBF_DIR / 'scripts' / 'obfuscation_self_check.sh', dst_obf / 'scripts' / 'obfuscation_self_check.sh') + return dst_obf + + def test_nscoding_auto_exemption_on_real_readoor_sources(self): + real_files_to_check = [ + APP_REPO / 'readoor/BookShelf/Classes/Models/STSPayOrderInfoObject.h', + APP_REPO / 'readoor/BookShelf/Classes/Models/STSPayOrderInfoObject.m', + APP_REPO / 'readoor/BookView/PDF/Core/Classes/Stage/SubViews/PaintingViews/RBCorePenLineData.h', + APP_REPO / 'readoor/BookView/PDF/Core/Classes/Stage/SubViews/PaintingViews/RBCorePenLineData.m', + APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintModel.h', + APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintModel.m', + APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintLayerModel.h', + APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintPageLayerModel.h', + APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintStack.h', + APP_REPO / 'readoor/3.0/Base/MediaCache/RDPlayerCacheMedia.swift', + APP_REPO / 'readoor/3.0/Base/MediaCache/RDPlayerCacheMediaConfiguration.swift', + APP_REPO / 'readoor/3.0/Features/Account/Login/Views/RDLoginView.swift', + ] + # 清空内存 cache / 直接测解析逻辑以确认非仅靠 seed 命中 + swift_detected = set() + objc_detected = set() + parents = {} + for fp in real_files_to_check: + txt = fp.read_text(encoding='utf-8') + is_sw = fp.suffix == '.swift' + masked = obf._mask_non_code_preserving_lines(txt, is_swift=is_sw, mask_imports=False) + info = obf._extract_nscoding_info_from_code(masked, is_swift=is_sw) + if is_sw: + swift_detected.update(info['direct']) + else: + objc_detected.update(info['direct']) + for k, vs in info['parents'].items(): + parents.setdefault(k, []).extend(vs) + + # synthetic subclasses + sub_swift = obf._extract_nscoding_info_from_code( + 'class RDCustomCacheMedia: RDPlayerCacheMedia { var tag: String = "" }', + is_swift=True, + ) + sub_objc = obf._extract_nscoding_info_from_code( + '@interface STSCustomOrder : STSPayOrderInfoObject\n@end', + is_swift=False, + ) + for pdict in (sub_swift['parents'], sub_objc['parents']): + for k, vs in pdict.items(): + parents.setdefault(k, []).extend(vs) + + detected = swift_detected | objc_detected + changed = True + while changed: + changed = False + for child, supers in parents.items(): + if child not in detected and any(s in detected for s in supers): + detected.add(child) + changed = True + + for expected in ( + 'STSPayOrderInfoObject', + 'RBCorePenLineData', # 头文件中未声明 ,靠 .m 中 encodeWithCoder:/initWithCoder: 识别 + 'STSPaintModel', + 'STSPaintLayerModel', + 'STSPaintPageLayerModel', + 'STSPaintStack', + 'RDPlayerCacheMedia', + 'RDPlayerCacheMediaConfiguration', + 'RDCustomCacheMedia', + 'STSCustomOrder', + ): + self.assertIn(expected, detected, f'Missing auto-detected NSCoding class: {expected}') + self.assertNotIn('RDLoginView', detected, 'UIView subclass with only required init?(coder:) must not be exempted as NSCoding') + + def test_real_binary_over_install_nscoding_unarchiving(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + dst_obf = self._stage_obf_runtime(root) + src = root / 'Sources' + src.mkdir() + + (src / 'STSModels.h').write_text( + '#import \n' + '@interface STSPayOrderInfoObject : NSObject\n' + '@property (nonatomic, copy) NSString *orderId;\n' + '@property (nonatomic, copy) NSString *receiptData;\n' + '@end\n' + '@interface RBCorePenLineData : NSObject\n' + '@property (nonatomic, copy) NSString *lineKey;\n' + '@property (nonatomic, assign) double lineWidth;\n' + '@end\n' + '@interface STSPaintModel : NSObject\n' + '@property (nonatomic, copy) NSString *brushName;\n' + '@end\n' + '@interface STSOrderTransientNote : NSObject\n' + '- (NSString *)renderSummary:(NSString *)tag stepMarker:(NSInteger)marker;\n' + '@end\n', + encoding='utf-8', + ) + (src / 'STSModels.m').write_text( + '#import "STSModels.h"\n' + '@implementation STSPayOrderInfoObject\n' + '- (void)encodeWithCoder:(NSCoder *)coder {\n' + ' [coder encodeObject:self.orderId forKey:@"orderId"];\n' + ' [coder encodeObject:self.receiptData forKey:@"receiptData"];\n' + '}\n' + '- (instancetype)initWithCoder:(NSCoder *)coder {\n' + ' if (self = [super init]) {\n' + ' self.orderId = [coder decodeObjectForKey:@"orderId"];\n' + ' self.receiptData = [coder decodeObjectForKey:@"receiptData"];\n' + ' }\n' + ' return self;\n' + '}\n' + '@end\n' + '@implementation RBCorePenLineData\n' + '- (void)encodeWithCoder:(NSCoder *)coder {\n' + ' [coder encodeObject:self.lineKey forKey:@"lineKey"];\n' + ' [coder encodeDouble:self.lineWidth forKey:@"lineWidth"];\n' + '}\n' + '- (instancetype)initWithCoder:(NSCoder *)coder {\n' + ' if (self = [super init]) {\n' + ' self.lineKey = [coder decodeObjectForKey:@"lineKey"];\n' + ' self.lineWidth = [coder decodeDoubleForKey:@"lineWidth"];\n' + ' }\n' + ' return self;\n' + '}\n' + '@end\n' + '@implementation STSPaintModel\n' + '+ (BOOL)supportsSecureCoding { return YES; }\n' + '- (void)encodeWithCoder:(NSCoder *)coder {\n' + ' [coder encodeObject:self.brushName forKey:@"brushName"];\n' + '}\n' + '- (instancetype)initWithCoder:(NSCoder *)coder {\n' + ' if (self = [super init]) {\n' + ' self.brushName = [coder decodeObjectForKey:@"brushName"];\n' + ' }\n' + ' return self;\n' + '}\n' + '@end\n' + '@implementation STSOrderTransientNote\n' + '- (NSString *)renderSummary:(NSString *)tag stepMarker:(NSInteger)marker {\n' + ' return [NSString stringWithFormat:@"%@:%ld", tag, (long)marker];\n' + '}\n' + '@end\n', + encoding='utf-8', + ) + (src / 'RDTransientHelper.swift').write_text( + 'import Foundation\n' + 'class RDCodedConfig: NSObject, NSCoding {\n' + ' var endpoint: String\n' + ' init(endpoint: String) { self.endpoint = endpoint }\n' + ' func encode(with coder: NSCoder) { coder.encode(endpoint, forKey: "endpoint") }\n' + ' required init?(coder: NSCoder) {\n' + ' guard let ep = coder.decodeObject(forKey: "endpoint") as? String else { return nil }\n' + ' self.endpoint = ep\n' + ' }\n' + '}\n' + 'final class RDTransientHelper {\n' + ' func computeSummary() -> String {\n' + ' let n = STSOrderTransientNote()\n' + ' return n.renderSummary("ok", stepMarker: 42)\n' + ' }\n' + '}\n' + '@main struct Harness {\n' + ' static func main() {\n' + ' let args = CommandLine.arguments\n' + ' let outDir = URL(fileURLWithPath: args[2])\n' + ' if args[1] == "archive" {\n' + ' let order = STSPayOrderInfoObject()\n' + ' order.orderId = "ORD_991"\n' + ' order.receiptData = "RCPT_XYZ"\n' + ' let d1 = try! NSKeyedArchiver.archivedData(withRootObject: order, requiringSecureCoding: false)\n' + ' try! d1.write(to: outDir.appendingPathComponent("order.dat"))\n' + ' let pen = RBCorePenLineData()\n' + ' pen.lineKey = "PEN_7"\n' + ' pen.lineWidth = 3.25\n' + ' let d2 = try! NSKeyedArchiver.archivedData(withRootObject: pen, requiringSecureCoding: false)\n' + ' try! d2.write(to: outDir.appendingPathComponent("pen.dat"))\n' + ' let paint = STSPaintModel()\n' + ' paint.brushName = "marker_gold"\n' + ' let d3 = try! NSKeyedArchiver.archivedData(withRootObject: paint, requiringSecureCoding: true)\n' + ' try! d3.write(to: outDir.appendingPathComponent("paint.dat"))\n' + ' let cfg = RDCodedConfig(endpoint: "https://api.example.com")\n' + ' let d4 = try! NSKeyedArchiver.archivedData(withRootObject: cfg, requiringSecureCoding: false)\n' + ' try! d4.write(to: outDir.appendingPathComponent("cfg.dat"))\n' + ' } else {\n' + ' let d1 = try! Data(contentsOf: outDir.appendingPathComponent("order.dat"))\n' + ' let order = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(d1) as! STSPayOrderInfoObject\n' + ' let d2 = try! Data(contentsOf: outDir.appendingPathComponent("pen.dat"))\n' + ' let pen = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(d2) as! RBCorePenLineData\n' + ' let d3 = try! Data(contentsOf: outDir.appendingPathComponent("paint.dat"))\n' + ' let paint = try! NSKeyedUnarchiver.unarchivedObject(ofClass: STSPaintModel.self, from: d3)!\n' + ' let d4 = try! Data(contentsOf: outDir.appendingPathComponent("cfg.dat"))\n' + ' let cfg = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(d4) as! RDCodedConfig\n' + ' let payload: [String: Any] = [\n' + ' "orderId": order.orderId ?? "",\n' + ' "receiptData": order.receiptData ?? "",\n' + ' "lineKey": pen.lineKey ?? "",\n' + ' "lineWidth": pen.lineWidth,\n' + ' "brushName": paint.brushName ?? "",\n' + ' "endpoint": cfg.endpoint,\n' + ' "helper": RDTransientHelper().computeSummary(),\n' + ' "transientCls": NSStringFromClass(STSOrderTransientNote.self),\n' + ' ]\n' + ' let jd = try! JSONSerialization.data(withJSONObject: payload)\n' + ' print(String(data: jd, encoding: .utf8)!)\n' + ' }\n' + ' }\n' + '}\n', + encoding='utf-8', + ) + + archives = root / 'archives' + archives.mkdir() + + def compile_binary(out_bin: Path): + obj = root / 'STSModels.o' + subprocess.run( + ['xcrun', 'clang', '-fobjc-arc', '-c', str(src / 'STSModels.m'), '-o', str(obj)], + check=True, + ) + subprocess.run( + [ + 'xcrun', 'swiftc', + '-parse-as-library', + '-module-name', 'AppTest', + '-import-objc-header', str(src / 'STSModels.h'), + str(src / 'RDTransientHelper.swift'), + str(obj), + '-o', str(out_bin), + ], + check=True, + ) + + v1 = root / 'bin_v1' + compile_binary(v1) + subprocess.run([str(v1), 'archive', str(archives)], check=True) + + # Apply obfuscation in-place in isolated root + subprocess.run( + [ + sys.executable, + str(dst_obf / 'obfuscate_symbols.py'), + '--archive-mode', + '--target-name', 'readoor31', + '--timestamp', '20261119_unit', + '--salt', 'm3_unit_seed_01', + ], + cwd=root, + check=True, + ) + + sym_map_p = root / 'obfuscation_maps' / 'symbol_map_readoor31_20261119_unit.json' + meth_map_p = root / 'obfuscation_maps' / 'method_map_readoor31_20261119_unit.json' + self.assertTrue(sym_map_p.is_file()) + self.assertTrue(meth_map_p.is_file()) + sym_json = json.loads(sym_map_p.read_text(encoding='utf-8')) + meth_json = json.loads(meth_map_p.read_text(encoding='utf-8')) + self.assertEqual(sym_json['schema_version'], 2) + self.assertEqual(meth_json['schema_version'], 2) + for kept in ('STSPayOrderInfoObject', 'RBCorePenLineData', 'STSPaintModel', 'RDCodedConfig'): + self.assertNotIn(kept, sym_json['mappings']) + self.assertIn('STSOrderTransientNote', sym_json['mappings']) + self.assertIn('RDTransientHelper', sym_json['mappings']) + self.assertIn('renderSummary:stepMarker:', meth_json['mappings']) + self.assertNotRegex(sym_json['mappings']['RDTransientHelper']['obfuscated'], r'^(?:YMH|ymh)[0-9a-f]+$') + + v2 = root / 'bin_v2' + compile_binary(v2) + out_v2 = subprocess.check_output([str(v2), 'unarchive', str(archives)], text=True).strip() + decoded = json.loads(out_v2) + self.assertEqual(decoded['orderId'], 'ORD_991') + self.assertEqual(decoded['receiptData'], 'RCPT_XYZ') + self.assertEqual(decoded['lineKey'], 'PEN_7') + self.assertAlmostEqual(decoded['lineWidth'], 3.25) + self.assertEqual(decoded['brushName'], 'marker_gold') + self.assertEqual(decoded['endpoint'], 'https://api.example.com') + self.assertEqual(decoded['helper'], 'ok:42') + self.assertEqual( + decoded['transientCls'], + sym_json['mappings']['STSOrderTransientNote']['obfuscated'], + ) + + def test_double_backslash_regex_and_override_dynamic_fixes(self): + self.assertIsNotNone(obf.OBJC_SELECTOR_RE.search('@selector(foo:bar:)')) + self.assertEqual(obf.OBJC_SELECTOR_RE.search('@selector( submitButtonTap )').group(1), 'submitButtonTap') + self.assertFalse(obf.is_safe_to_rename_method('customLayoutPass', ' override func customLayoutPass() {')) + self.assertFalse(obf.is_safe_to_rename_method('observableAction', ' dynamic func observableAction() {')) + self.assertTrue(obf.is_safe_to_rename_method('computeToken', ' private func computeToken() {')) + + def test_lexical_scanner_preserves_strings_comments_imports_interpolations(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + dst_obf = self._stage_obf_runtime(root) + (root / 'STSWorker.h').write_text( + '#import \n' + '// RDAlphaService secretNote\n' + '@interface STSWorker : NSObject\n' + '- (void)performTask:(NSString *)a withMode:(int)b;\n' + '- (void)triggerPing;\n' + '@end\n', + encoding='utf-8', + ) + (root / 'STSWorker.m').write_text( + '#import "STSWorker.h"\n' + '// STSWorker triggerPing performTask:withMode:\n' + '/* class RDAlphaService {} @selector(triggerPing) */\n' + '@implementation STSWorker\n' + '- (void)performTask:(NSString *)a withMode:(int)b {\n' + ' NSString *s1 = @"STSWorker triggerPing performTask:withMode:";\n' + ' SEL sel = @selector(triggerPing);\n' + ' SEL sel2 = @selector(performTask:withMode:);\n' + ' if (sel && sel2 && s1) { [self triggerPing]; }\n' + '}\n' + '- (void)triggerPing {}\n' + '@end\n', + encoding='utf-8', + ) + (root / 'RDAlphaService.swift').write_text( + 'import Foundation\n' + 'import RDAlphaService\n' + '// RDAlphaService runCore\n' + '/*\n' + ' class RDAlphaService {}\n' + ' func runCore() {}\n' + '*/\n' + 'class RDAlphaService {\n' + ' let literal = "RDAlphaService runCore"\n' + ' let multi = """\n' + ' RDAlphaService\n' + ' func runCore() {}\n' + ' """\n' + ' let raw = #"RDAlphaService runCore"#\n' + ' func runCore() -> String {\n' + ' return "prefix-\\(RDAlphaService.helperTag())-RDAlphaService"\n' + ' }\n' + ' static func helperTag() -> String { return "STSWorker" }\n' + '}\n', + encoding='utf-8', + ) + subprocess.run( + [ + sys.executable, + str(dst_obf / 'obfuscate_symbols.py'), + '--archive-mode', + '--target-name', 'readoor31', + '--timestamp', '20261119_lex', + '--salt', 'lex_seed_01', + ], + cwd=root, + check=True, + ) + sw_after = (root / 'RDAlphaService.swift').read_text(encoding='utf-8') + m_after = (root / 'STSWorker.m').read_text(encoding='utf-8') + sym_map = json.loads((root / 'obfuscation_maps' / 'symbol_map_readoor31_20261119_lex.json').read_text())['mappings'] + meth_map = json.loads((root / 'obfuscation_maps' / 'method_map_readoor31_20261119_lex.json').read_text())['mappings'] + + obf_cls = sym_map['RDAlphaService']['obfuscated'] + obf_worker = sym_map['STSWorker']['obfuscated'] + obf_tag = meth_map['helperTag']['obfuscated'] + obf_ping = meth_map['triggerPing']['obfuscated'] + obf_perf = meth_map['performTask:withMode:']['obfuscated'] + + # Imports, comments, and literals preserved verbatim + self.assertIn('#import "STSWorker.h"', m_after) + self.assertIn('// STSWorker triggerPing performTask:withMode:', m_after) + self.assertIn('/* class RDAlphaService {} @selector(triggerPing) */', m_after) + self.assertIn('NSString *s1 = @"STSWorker triggerPing performTask:withMode:";', m_after) + self.assertIn(f'@interface {obf_worker} : NSObject', (root / 'STSWorker.h').read_text()) + self.assertIn(f'@selector({obf_ping})', m_after) + self.assertIn(f'@selector({obf_perf})', m_after) + + self.assertIn('import RDAlphaService', sw_after) + self.assertIn('// RDAlphaService runCore', sw_after) + self.assertIn(' class RDAlphaService {}', sw_after) + self.assertIn('let literal = "RDAlphaService runCore"', sw_after) + self.assertIn(' RDAlphaService\n', sw_after) + self.assertIn('let raw = #"RDAlphaService runCore"#', sw_after) + self.assertIn('return "STSWorker"', sw_after) + # Interpolation code WAS rewritten while trailing literal suffix stayed intact + self.assertIn(f'return "prefix-\\({obf_cls}.{obf_tag}())-RDAlphaService"', sw_after) + + def test_natural_camelcase_determinism_self_check_and_source_restore(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + r1 = root / 'r1' + r2 = root / 'r2' + r3 = root / 'r3' + for r in (r1, r2, r3): + self._stage_obf_runtime(r) + (r / 'RDSampleBox.swift').write_text( + 'import Foundation\n' + 'final class RDSampleBox {\n' + ' func computeHash() -> Int { return 7 }\n' + '}\n', + encoding='utf-8', + ) + (r / 'STSBoxHelper.h').write_text( + '#import \n' + '@interface STSBoxHelper : NSObject\n' + '- (void)applyRule:(NSString *)r count:(int)c;\n' + '@end\n', + encoding='utf-8', + ) + (r / 'STSBoxHelper.m').write_text( + '#import "STSBoxHelper.h"\n' + '@implementation STSBoxHelper\n' + '- (void)applyRule:(NSString *)r count:(int)c {}\n' + '@end\n', + encoding='utf-8', + ) + + # Clean self check passes + res_clean = subprocess.run( + ['bash', str(r1 / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh'), str(r1)], + capture_output=True, text=True, + ) + self.assertEqual(res_clean.returncode, 0, res_clean.stdout + res_clean.stderr) + + orig_swift = (r1 / 'RDSampleBox.swift').read_text(encoding='utf-8') + orig_objc = (r1 / 'STSBoxHelper.m').read_text(encoding='utf-8') + + for r, salt in ((r1, 'seed_same'), (r2, 'seed_same'), (r3, 'seed_other')): + subprocess.run( + [ + sys.executable, + str(r / 'AutoPacking/obfuscation/obfuscate_symbols.py'), + '--archive-mode', + '--target-name', 'readoor31', + '--timestamp', '20261119_det', + '--salt', salt, + ], + cwd=r, + check=True, + ) + + m1 = json.loads((r1 / 'obfuscation_maps/symbol_map_readoor31_20261119_det.json').read_text())['mappings'] + m2 = json.loads((r2 / 'obfuscation_maps/symbol_map_readoor31_20261119_det.json').read_text())['mappings'] + m3 = json.loads((r3 / 'obfuscation_maps/symbol_map_readoor31_20261119_det.json').read_text())['mappings'] + self.assertEqual(m1, m2) + self.assertNotEqual(m1, m3) + + # Self-check catches obfuscated natural tokens + res_obf = subprocess.run( + ['bash', str(r1 / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh'), str(r1)], + capture_output=True, text=True, + ) + self.assertNotEqual(res_obf.returncode, 0) + + # Self-check catches legacy lowercase ymh too + (r1 / 'RDSampleBox.swift').write_text('func ymh1234567890() {}\n', encoding='utf-8') + res_legacy = subprocess.run( + ['bash', str(r1 / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh'), str(r1)], + capture_output=True, text=True, + ) + self.assertNotEqual(res_legacy.returncode, 0) + + # Restore r2 back from obfuscation_maps + subprocess.run( + [ + sys.executable, + str(r2 / 'AutoPacking/obfuscation/obfuscate_symbols.py'), + '--restore-source-from-map-dir', 'obfuscation_maps', + ], + cwd=r2, + check=True, + ) + self.assertEqual((r2 / 'RDSampleBox.swift').read_text(encoding='utf-8'), orig_swift) + self.assertEqual((r2 / 'STSBoxHelper.m').read_text(encoding='utf-8'), orig_objc) + res_restored = subprocess.run( + ['bash', str(r2 / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh'), str(r2)], + capture_output=True, text=True, + ) + self.assertEqual(res_restored.returncode, 0, res_restored.stdout + res_restored.stderr) + + def test_v2_crash_restoration_and_l1_to_l2_policy_translation(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + maps = root / 'obfuscation_maps' + maps.mkdir() + sym_p = maps / 'symbol_map_readoor31_20261119_t.json' + meth_p = maps / 'method_map_readoor31_20261119_t.json' + sym_p.write_text(json.dumps({ + 'schema_version': 2, + 'kind': 'symbol_map', + 'target': 'readoor31', + 'timestamp': '20261119_t', + 'seed': 's1', + 'mappings': { + 'RDInjectionDetector': {'obfuscated': 'LumenCipherEngine', 'language': 'swift'}, + 'STSJailbreakDetectTool': {'obfuscated': 'CanopyShieldBroker', 'language': 'objc'}, + 'STSIAPVerifyHandler': {'obfuscated': 'HarborRelayAgent', 'language': 'objc'}, + }, + }), encoding='utf-8') + meth_p.write_text(json.dumps({ + 'schema_version': 2, + 'kind': 'method_map', + 'target': 'readoor31', + 'timestamp': '20261119_t', + 'seed': 's1', + 'mappings': { + 'hasSuspiciousDyldInsertLibraries': { + 'kind': 'direct_method', + 'token': 'auditCobaltSignal', + 'obfuscated': 'auditCobaltSignal', + }, + 'detectCurrentDeviceIsJailbroken': { + 'kind': 'direct_method', + 'token': 'verifyKestrelPulse', + 'obfuscated': 'verifyKestrelPulse', + }, + 'transactionDidStoreInKeyChainWithTransactionIdentifier:count:': { + 'kind': 'objc_selector', + 'token': 'alignBirchLedger', + 'obfuscated': 'alignBirchLedger:phaseCobalt:', + 'parts': ['alignBirchLedger:', 'phaseCobalt:'], + 'swift_alias': 'alignBirchLedger(_:phaseCobalt:)', + }, + }, + }), encoding='utf-8') + + cls_rev, sel_rev = restore_crash_report.load_reverse_maps(sym_p, meth_p) + restored_objc = restore_crash_report.deobfuscate_symbol_text( + '-[HarborRelayAgent alignBirchLedger:phaseCobalt:] (in readoor31)', + cls_rev, + sel_rev, + ) + self.assertIn('-[STSIAPVerifyHandler transactionDidStoreInKeyChainWithTransactionIdentifier:count:]', restored_objc) + restored_swift = restore_crash_report.deobfuscate_symbol_text( + 'LumenCipherEngine.auditCobaltSignal() -> Bool', + cls_rev, + sel_rev, + ) + self.assertIn('RDInjectionDetector.hasSuspiciousDyldInsertLibraries() -> Bool', restored_swift) + + eff_path, eff_policy = ig_toolchain_resolver.resolve_effective_policy( + str(ROOT / 'config' / 'ig_llvm_policy.json'), + root, + root / 'cache', + ) + self.assertTrue(Path(eff_path).is_file()) + flat_subs = {r.get('function_contains') for r in eff_policy['flatten_targets'] if r.get('function_contains')} + self.assertIn('17auditCobaltSignal', flat_subs) + self.assertIn('verifyKestrelPulse', flat_subs) + self.assertIn('alignBirchLedger', flat_subs) + req_map = {r['id']: r for r in eff_policy['required_targets']} + self.assertIn('17auditCobaltSignal', req_map['swift_rd_injection_dyld_check']['symbol_contains_any']) + self.assertIn('17LumenCipherEngineC', req_map['swift_rd_injection_dyld_check']['str_symbol_contains_any']) + + def test_generic_overloads_first_class_func_refs_and_dotted_sdk_types(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + dst_obf = self._stage_obf_runtime(root) + mock_sdk = root / 'Factorys' / 'MockAuthSDK' + mock_sdk.mkdir(parents=True) + (mock_sdk / 'TXCommonHandler.h').write_text( + '#import \n' + '@interface TXCommonHandler : NSObject\n' + '- (void)accelerateLoginPageWithTimeout:(double)timeout;\n' + '@end\n', + encoding='utf-8', + ) + src = root / 'Sources' + src.mkdir() + (src / 'STSWebServerHandler.h').write_text( + '#import \n' + '@interface STSWebServerHandler : NSObject\n' + '- (void)addHandlerForMethod:(NSString *)method path:(NSString *)path;\n' + '@end\n', + encoding='utf-8', + ) + (src / 'STSWebServerHandler.m').write_text( + '#import "STSWebServerHandler.h"\n' + '@implementation STSWebServerHandler\n' + '- (void)addHandlerForMethod:(NSString *)method path:(NSString *)path {}\n' + '@end\n', + encoding='utf-8', + ) + (src / 'RDRouterDynamicParamsMapping.h').write_text( + '#import \n' + '@interface RDRouterDynamicParamsMapping : NSObject\n' + '+ (instancetype)router;\n' + '- (id)routerGetInstanceWithClassName:(NSString *)className;\n' + '@end\n', + encoding='utf-8', + ) + (src / 'RDRouterDynamicParamsMapping.m').write_text( + '#import "RDRouterDynamicParamsMapping.h"\n' + '@implementation RDRouterDynamicParamsMapping\n' + '+ (instancetype)router { return [[self alloc] init]; }\n' + '- (id)routerGetInstanceWithClassName:(NSString *)className { return nil; }\n' + '@end\n', + encoding='utf-8', + ) + (src / 'App-Bridging-Header.h').write_text( + '#import "STSWebServerHandler.h"\n' + '#import "RDRouterDynamicParamsMapping.h"\n', + encoding='utf-8', + ) + (src / 'Info.plist').write_text( + '' + 'UISceneDelegateClassName' + '$(PRODUCT_MODULE_NAME).RBCoreSceneDelegate' + '\n', + encoding='utf-8', + ) + + # 同时包含:public struct Configuration(应全局取消混淆 Configuration)、 + # UIButton.Configuration / EncodingError.Context 点号后系统嵌套类型、 + # generic 重载 static func stableIdentifier(for:)、 + # 无括号一等公民函数值引用 compactMap(clampedNormalizedRect) / sorted(by: isBeforeInReadingOrder)、 + # 同名局部变量 guard let helperKey 与方法 helperKey() 消歧、 + # public protocol 内方法要求不得重命名。 + (src / 'RDPublicContract.swift').write_text( + 'import Foundation\n' + 'import UIKit\n' + 'public protocol RDPublicStore {\n' + ' func persistItem(_ item: String)\n' + '}\n' + 'public class RDPublicViewer: UIViewController {\n' + ' public struct Configuration {\n' + ' public var scale: CGFloat = 1.0\n' + ' }\n' + '}\n', + encoding='utf-8', + ) + (src / 'RDEpubPanelHelper.swift').write_text( + 'import Foundation\n' + 'import UIKit\n' + 'import WebKit\n' + 'final class RDEpubPanelHelper {\n' + ' struct Configuration { var label: String }\n' + ' private struct ItemRow { let rank: Int; let text: String }\n' + ' func configureButton() -> UIButton.Configuration {\n' + ' var cfg = UIButton.Configuration.filled()\n' + ' cfg.title = Configuration(label: "x").label\n' + ' return cfg\n' + ' }\n' + ' static func stableIdentifier(for value: String) -> String {\n' + ' stableIdentifier(for: Array(value.utf8))\n' + ' }\n' + ' static func stableIdentifier(for bytes: Bytes) -> String where Bytes.Element == UInt8 {\n' + ' var h: UInt64 = 14695981039346656037\n' + ' for b in bytes { h ^= UInt64(b); h &*= 1099511628211 }\n' + ' return String(h, radix: 16)\n' + ' }\n' + ' func sortValues(_ raw: [Int?]) -> [Int] {\n' + ' let clamped = raw.compactMap(clampedRank)\n' + ' let rows = clamped.map { ItemRow(rank: $0, text: RDEpubPanelHelper.stableIdentifier(for: "k")) }\n' + ' return Self.sortRows(rows)\n' + ' }\n' + ' private static func sortRows(_ rows: [ItemRow]) -> [Int] {\n' + ' rows.sorted(by: isBeforeInReadingOrder).map { $0.rank }\n' + ' }\n' + ' private func clampedRank(_ v: Int?) -> Int? { guard let v, v >= 0 else { return nil }; return v }\n' + ' private static func isBeforeInReadingOrder(_ a: ItemRow, _ b: ItemRow) -> Bool { a.rank < b.rank }\n' + ' func resolveKey() -> String {\n' + ' guard let helperKey = Self.buildSecretKey() else { return "" }\n' + ' return consumeKey(helperKey)\n' + ' }\n' + ' private func consumeKey(_ s: String) -> String { s }\n' + ' private static func buildSecretKey() -> String? { "k" }\n' + '}\n' + 'final class RDLocalKeyHolder {\n' + ' func helperKey() -> String { "other" }\n' + '}\n' + 'struct Environment { let name: String }\n' + 'enum RDActionRoute { case fetchItem; case payload(Int) }\n' + 'final class RDReflectedService: NSObject {}\n' + 'final class RDEnumAndStdlibProbe {\n' + ' func flatMap(_ transform: (Int) -> T) -> T { transform(1) }\n' + ' static func fetchItem() -> RDActionRoute {\n' + ' _ = [1, 2].flatMap { [$0, $0] }\n' + ' _ = Optional(3).flatMap { $0 + 1 }\n' + ' _ = Environment(name: "prod")\n' + ' _ = NSClassFromString("RDReflectedService")\n' + ' return .payload(computePayload())\n' + ' }\n' + ' private static func computePayload() -> Int { 7 }\n' + ' func callCustomFlatMap() -> Int { flatMap { $0 + 1 } }\n' + ' func removeScriptMessageHandler() {}\n' + ' func tidyWeb(_ c: WKUserContentController) {\n' + ' c.removeScriptMessageHandler(forName: "b")\n' + ' removeScriptMessageHandler()\n' + ' }\n' + ' private func scopedItem(_ v: Int) -> Int? { v > 0 ? v : nil }\n' + ' func checkScoped() -> Int {\n' + ' let pre = scopedItem(1) ?? 0\n' + ' guard let scopedItem = scopedItem(3) else { return pre }\n' + ' return scopedItem + pre\n' + ' }\n' + ' func accelerateLoginPage() {}\n' + ' struct Box { static func snapPhoto(_ flag: Bool) -> Int { flag ? 1 : 0 } }\n' + ' static func snapPhoto() -> Int { RDEnumAndStdlibProbe.Box.snapPhoto(true) }\n' + ' static func navDiagnosticName(_ value: Int) -> String { "\\(value)" }\n' + ' static func checkBridgingAndNewlineFuncValue() -> (String, String, Any?) {\n' + ' let fnBare = navDiagnosticName\n' + ' let fnQualified = RDEnumAndStdlibProbe.navDiagnosticName\n' + ' STSWebServerHandler().add(forMethod: "GET", path: "/")\n' + ' let obj = RDRouterDynamicParamsMapping.router().routerGetInstance(withClassName: "Foo")\n' + ' return (fnBare(1), fnQualified(2), obj)\n' + ' }\n' + ' private let rotateCfg: RDRotateCfg = .defaultConfigure()\n' + '}\n' + 'class RDRotateCfg {\n' + ' fileprivate class func defaultConfigure() -> RDRotateCfg { RDRotateCfg() }\n' + '}\n' + 'final class RBCoreSceneDelegate: UIResponder, UIWindowSceneDelegate {}\n', + encoding='utf-8', + ) + + subprocess.run( + [ + 'python3', str(dst_obf / 'obfuscate_symbols.py'), + '--archive-mode', + '--target-name', 'readoor31', + '--timestamp', '20261119_ast', + '--salt', 'm3_ast_seed_01', + ], + cwd=root, check=True, + ) + + sym_map = json.loads((root / 'obfuscation_maps/symbol_map_readoor31_20261119_ast.json').read_text())['mappings'] + meth_map = json.loads((root / 'obfuscation_maps/method_map_readoor31_20261119_ast.json').read_text())['mappings'] + # public struct Configuration 不得进入映射;public protocol RDPublicStore.persistItem 不得进入方法映射 + self.assertNotIn('Configuration', sym_map) + self.assertNotIn('Environment', sym_map) + self.assertNotIn('RDReflectedService', sym_map) + self.assertNotIn('persistItem', meth_map) + self.assertNotIn('flatMap', meth_map) + self.assertNotIn('fetchItem', meth_map) + self.assertNotIn('payload', meth_map) + self.assertNotIn('removeScriptMessageHandler', meth_map) + self.assertNotIn('accelerateLoginPage', meth_map) + self.assertIn('RDEpubPanelHelper', sym_map) + self.assertIn('RDActionRoute', sym_map) + self.assertIn('RDEnumAndStdlibProbe', sym_map) + self.assertIn('clampedRank', meth_map) + self.assertIn('isBeforeInReadingOrder', meth_map) + self.assertIn('stableIdentifier', meth_map) + self.assertIn('computePayload', meth_map) + self.assertIn('scopedItem', meth_map) + self.assertIn('snapPhoto', meth_map) + self.assertNotIn('STSWebServerHandler', sym_map) + self.assertIn('router', meth_map) + self.assertNotIn('routerGetInstanceWithClassName:', meth_map) + self.assertNotIn('addHandlerForMethod:path:', meth_map) + self.assertIn('navDiagnosticName', meth_map) + self.assertNotIn('RBCoreSceneDelegate', sym_map) + self.assertIn('defaultConfigure', meth_map) + + obf_src = (src / 'RDEpubPanelHelper.swift').read_text(encoding='utf-8') + self.assertIn('UIButton.Configuration.filled()', obf_src) + self.assertNotIn('clampedRank', obf_src) + self.assertNotIn('isBeforeInReadingOrder', obf_src) + self.assertNotIn('stableIdentifier', obf_src) + self.assertIn('guard let helperKey =', obf_src) + self.assertIn(f'{meth_map["consumeKey"]["obfuscated"]}(helperKey)', obf_src) + self.assertIn('.flatMap {', obf_src) + self.assertIn('Environment(name: "prod")', obf_src) + self.assertIn(f'.payload({meth_map["computePayload"]["obfuscated"]}())', obf_src) + obf_scoped = meth_map['scopedItem']['obfuscated'] + self.assertIn(f'let pre = {obf_scoped}(1) ?? 0', obf_src) + self.assertIn(f'guard let scopedItem = {obf_scoped}(3) else', obf_src) + self.assertIn('return scopedItem + pre', obf_src) + obf_box = sym_map['Box']['obfuscated'] if 'Box' in sym_map else 'Box' + self.assertIn(f'{obf_box}.{meth_map["snapPhoto"]["obfuscated"]}(true)', obf_src) + obf_nav = meth_map['navDiagnosticName']['obfuscated'] + obf_probe = sym_map['RDEnumAndStdlibProbe']['obfuscated'] + self.assertIn(f'let fnBare = {obf_nav}\n', obf_src) + self.assertIn(f'let fnQualified = {obf_probe}.{obf_nav}\n', obf_src) + self.assertIn(f'= .{meth_map["defaultConfigure"]["obfuscated"]}()', obf_src) + + sdk_path = subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip() + subprocess.run( + [ + 'xcrun', '--sdk', 'iphoneos', 'swiftc', + '-typecheck', + '-target', 'arm64-apple-ios16.0', + '-sdk', sdk_path, + '-import-objc-header', str(src / 'App-Bridging-Header.h'), + str(src / 'RDPublicContract.swift'), + str(src / 'RDEpubPanelHelper.swift'), + ], + check=True, + ) + + def test_effective_policy_disk_cache_early_return_and_9k_scale(self): + import time + + with tempfile.TemporaryDirectory() as td: + root = Path(td) + maps_dir = root / 'obfuscation_maps' + maps_dir.mkdir(parents=True) + cache_dir = root / 'cache' + + sym_entries = {f'RDMockType{i:04d}': {'obfuscated': f'CobaltType{i:04d}', 'language': 'swift'} for i in range(2199)} + sym_entries['RDInjectionDetector'] = {'obfuscated': 'LumenCipherEngine', 'language': 'swift'} + meth_entries = {f'mockAction{i:04d}': {'obfuscated': f'traceAction{i:04d}', 'language': 'swift'} for i in range(6799)} + meth_entries['hasSuspiciousDyldInsertLibraries'] = {'obfuscated': 'auditCobaltSignal', 'language': 'swift'} + + sym_path = maps_dir / 'symbol_map_readoor31_bench.json' + meth_path = maps_dir / 'method_map_readoor31_bench.json' + sym_path.write_text(json.dumps({'schema_version': 2, 'kind': 'symbol_map', 'mappings': sym_entries}), encoding='utf-8') + meth_path.write_text(json.dumps({'schema_version': 2, 'kind': 'method_map', 'mappings': meth_entries}), encoding='utf-8') + + policy_src = str(ROOT / 'config' / 'ig_llvm_policy.json') + t0 = time.perf_counter() + eff_path, eff_policy = ig_toolchain_resolver.resolve_effective_policy(policy_src, root, cache_dir) + cold_s = time.perf_counter() - t0 + + self.assertTrue(eff_policy['l1_translation_active']) + req_map = {r['id']: r for r in eff_policy['required_targets']} + self.assertIn('17auditCobaltSignal', req_map['swift_rd_injection_dyld_check']['symbol_contains_any']) + self.assertIn('17LumenCipherEngineC', req_map['swift_rd_injection_dyld_check']['str_symbol_contains_any']) + + # Clear in-process sha cache to simulate 1,072 fresh subprocess invocations hitting disk cache + t1 = time.perf_counter() + for _ in range(1072): + ig_toolchain_resolver._MEM_SHA_CACHE.clear() + p2, pol2 = ig_toolchain_resolver.resolve_effective_policy(policy_src, root, cache_dir) + self.assertEqual(p2, eff_path) + warm_total_s = time.perf_counter() - t1 + total_s = cold_s + warm_total_s + print(f'[perf] resolve_effective_policy 9k maps: cold={cold_s:.4f}s, 1072_warm={warm_total_s:.4f}s, total_1073={total_s:.4f}s') + + self.assertLess(cold_s, 0.2) + self.assertLess(total_s, 2.5) + self.assertTrue(pol2['l1_translation_active']) + + # Mutate L1 map -> cache key must invalidate immediately and produce updated translation + sym_entries['RDInjectionDetector'] = {'obfuscated': 'OspreyBeaconVault', 'language': 'swift'} + sym_path.write_text(json.dumps({'schema_version': 2, 'kind': 'symbol_map', 'mappings': sym_entries}), encoding='utf-8') + eff_path2, eff_policy2 = ig_toolchain_resolver.resolve_effective_policy(policy_src, root, cache_dir) + self.assertNotEqual(eff_path2, eff_path) + req_map2 = {r['id']: r for r in eff_policy2['required_targets']} + self.assertIn('17OspreyBeaconVaultC', req_map2['swift_rd_injection_dyld_check']['str_symbol_contains_any']) + + def test_star_switch_bogus_linear_split_odr_and_macho_gate(self): + tc = ig_toolchain_resolver.resolve_opt(require_obf=False) + opt_path = tc.get('opt_path') + if not opt_path: + self.skipTest(f"Standalone opt unavailable: {tc.get('warning')}") + + clang = ig_toolchain_resolver.detect_stock_tool('clang') + macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() + + with tempfile.TemporaryDirectory() as td: + p = Path(td) + policy_p = p / 'star_policy.json' + policy_p.write_text(json.dumps({ + 'flatten_topology': 'sparse_switch', + 'flatten_bogus_blocks': 2, + 'flatten_split_linear_blocks': True, + 'exempt_path_substrings': [], + 'exempt_function_prefixes': ['__swift_'], + 'string_encrypt_targets': [{'path_contains': 'star_probe'}], + 'flatten_targets': [{'path_contains': 'star_probe'}], + }), encoding='utf-8') + + src = p / 'star_probe.cpp' + src.write_text( + '#include \n' + '#include \n' + 'static inline __attribute__((always_inline)) uint32_t mix_step(uint32_t v, uint32_t k) {\n' + ' uint32_t x = v ^ k;\n' + ' return (x << 5) | (x >> 27);\n' + '}\n' + '__attribute__((noinline)) uint32_t linear_hash(uint32_t a, uint32_t b) {\n' + ' uint32_t acc = a + 0x9e3779b9u;\n' + ' acc = mix_step(acc, b);\n' + ' acc *= 0x85ebca6bu;\n' + ' acc = mix_step(acc, a ^ 0x13572468u);\n' + ' acc += 0xc2b2ae35u;\n' + ' return acc ^ (acc >> 16);\n' + '}\n' + 'inline uint32_t weak_odr_helper(uint32_t x) { return x * 3u + 1u; }\n' + '__attribute__((noinline)) int branch_calc(int x, uint32_t (*fn)(uint32_t)) {\n' + ' if (x > 10) return (int)(fn((uint32_t)x) + 7u);\n' + ' if (x < 0) return (int)(linear_hash((uint32_t)(-x), 9u));\n' + ' return (int)linear_hash((uint32_t)x, 3u);\n' + '}\n' + 'int main(void) {\n' + ' printf("%u|%d|%d\\n", linear_hash(11u, 22u), branch_calc(-3, &weak_odr_helper), branch_calc(12, &weak_odr_helper));\n' + ' return 0;\n' + '}\n', + encoding='utf-8', + ) + bc_p = p / 'star_probe.bc' + obf_bc = p / 'star_probe.obf.bc' + obj_p = p / 'star_probe.o' + bin_p = p / 'star_probe' + audit_p = p / 'star.audit.json' + dsym_p = p / 'star_probe.dSYM' + + subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-g', '-emit-llvm', '-c', str(src), '-o', str(bc_p)], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_p}', '--ig-mode=full', + '--ig-seed=star_unit_seed_1', f'--ig-source-path={src}', + f'--ig-audit-out={audit_p}', str(bc_p), '-o', str(obf_bc), + ], check=True) + subprocess.run([ + clang, '-isysroot', macos_sdk, '-Os', '-g', + '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', + '-x', 'ir', '-c', str(obf_bc), '-o', str(obj_p), + ], check=True) + subprocess.run([clang, '-isysroot', macos_sdk, '-g', str(obj_p), '-o', str(bin_p)], check=True) + subprocess.run(['xcrun', 'dsymutil', str(bin_p), '-o', str(dsym_p)], check=True) + + audit = json.loads(audit_p.read_text(encoding='utf-8')) + details = audit.get('functions_flattened_details') or [] + self.assertTrue(details) + for det in details: + self.assertEqual(det['topology'], 'sparse_switch', det) + self.assertNotIn('weak_odr_helper', det['name']) + self.assertTrue(any('linear_hash' in det['name'] for det in details), details) + self.assertTrue(any( + 'weak_odr_helper' in sk['name'] and sk['reason'] == 'weak_or_linkonce_odr' + for sk in (audit.get('functions_skipped') or []) + ), audit.get('functions_skipped')) + + ref_bin = p / 'star_ref' + subprocess.run([clang, '-isysroot', macos_sdk, '-Os', str(src), '-o', str(ref_bin)], check=True) + self.assertEqual( + subprocess.check_output([str(bin_p)], text=True), + subprocess.check_output([str(ref_bin)], text=True), + ) + + dwarf_bin = dsym_p / 'Contents/Resources/DWARF/star_probe' + gate = verify_macho_star_cfg.verify_binary_star_cfg( + bin_p, + dwarf_bin, + {'module_audits': [{'source_path': str(src), 'functions_flattened_details': details}]}, + require_topology='sparse_switch', + fail_on_missing=True, + ) + self.assertEqual(gate['failed_count'], 0) + self.assertGreaterEqual(gate['verified_star_count'], 3) + + # Verify Swift multi-TU bitcode pipeline skips compiler-synthesized internal glue + # (block_copy_helper, *Tm, *CMa) so unflattened UI TUs cannot collide in dSYM. + swift_frontend = subprocess.check_output(['xcrun', '--sdk', 'macosx', '-f', 'swift-frontend'], text=True).strip() + swiftc_bin = subprocess.check_output(['xcrun', '--sdk', 'macosx', '-f', 'swiftc'], text=True).strip() + arch_triple = 'arm64-apple-macosx13.0' if os.uname().machine == 'arm64' else 'x86_64-apple-macosx13.0' + sw_prot = p / 'ProtectedSvc.swift' + sw_ui = p / 'UnprotectedUI.swift' + sw_prot.write_text( + 'import Foundation\n' + 'public final class ProtectedSvc {\n' + ' public var tag: String = "sec"\n' + ' public init() {}\n' + ' @inline(never)\n' + ' public func dispatchWork() {\n' + ' let q = DispatchQueue.main\n' + ' q.async { [weak self] in\n' + ' self?.tag = "done"\n' + ' }\n' + ' }\n' + ' @inline(never)\n' + ' public func compute(v: Int) -> Int {\n' + ' let a = (v &+ 13) &* 7\n' + ' let b = a ^ 0x5a5a\n' + ' return b &- 3\n' + ' }\n' + '}\n', + encoding='utf-8', + ) + sw_ui.write_text( + 'import Foundation\n' + 'public final class UnprotectedUI {\n' + ' public var label: String = "ui"\n' + ' public init() {}\n' + ' @inline(never)\n' + ' public func render() -> Int {\n' + ' let q = DispatchQueue.main\n' + ' q.async { [weak self] in\n' + ' self?.label = "shown"\n' + ' }\n' + ' return label.count\n' + ' }\n' + '}\n', + encoding='utf-8', + ) + sw_pol = p / 'sw_policy.json' + sw_pol.write_text(json.dumps({ + 'flatten_topology': 'sparse_switch', + 'flatten_bogus_blocks': 2, + 'flatten_split_linear_blocks': True, + 'exempt_path_substrings': [], + 'exempt_function_prefixes': ['__swift_'], + 'string_encrypt_targets': [], + 'flatten_targets': [{'path_contains': 'ProtectedSvc.swift'}], + }), encoding='utf-8') + sw_bc1 = p / 'ProtectedSvc.bc' + sw_bc2 = p / 'UnprotectedUI.bc' + for cur, other, bc_out in [(sw_prot, sw_ui, sw_bc1), (sw_ui, sw_prot, sw_bc2)]: + subprocess.run([ + swift_frontend, '-target', arch_triple, '-sdk', macos_sdk, + '-O', '-g', '-module-name', 'StarSwiftMod', + '-primary-file', str(cur), str(other), + '-emit-bc', '-o', str(bc_out), + ], check=True) + sw_obf1 = p / 'ProtectedSvc.obf.bc' + sw_aud1 = p / 'ProtectedSvc.audit.json' + subprocess.run([ + opt_path, '-passes=default,ig-obfuscate', + f'--ig-policy={sw_pol}', '--ig-mode=full', + '--ig-seed=star_sw_unit_1', f'--ig-source-path={sw_prot}', + f'--ig-audit-out={sw_aud1}', str(sw_bc1), '-o', str(sw_obf1), + ], check=True) + sw_o1 = p / 'ProtectedSvc.o' + sw_o2 = p / 'UnprotectedUI.o' + for b_in, o_out in [(sw_obf1, sw_o1), (sw_bc2, sw_o2)]: + subprocess.run([ + clang, '-target', arch_triple, '-isysroot', macos_sdk, + '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', + '-x', 'ir', '-c', str(b_in), '-o', str(o_out), + ], check=True) + sw_bin = p / 'StarSwiftBin' + sw_dsym = p / 'StarSwiftBin.dSYM' + subprocess.run([ + swiftc_bin, '-target', arch_triple, '-sdk', macos_sdk, + '-Xlinker', '-e', '-Xlinker', '__mh_execute_header', + str(sw_o1), str(sw_o2), '-o', str(sw_bin), + ], check=True) + subprocess.run(['xcrun', 'dsymutil', str(sw_bin), '-o', str(sw_dsym)], check=True) + + sw_audit = json.loads(sw_aud1.read_text(encoding='utf-8')) + sw_flat_names = sw_audit.get('functions_flattened') or [] + self.assertTrue(any('ProtectedSvc' in n and 'compute' in n for n in sw_flat_names), sw_flat_names) + for forbidden in ('block_copy_helper', 'block_destroy_helper'): + self.assertFalse(any(forbidden in n for n in sw_flat_names), sw_flat_names) + self.assertFalse(any(n.endswith(('Tm', 'CMa', 'Wl', 'TA')) for n in sw_flat_names), sw_flat_names) + if os.uname().machine == 'arm64': + sw_gate = verify_macho_star_cfg.verify_binary_star_cfg( + sw_bin, + sw_dsym / 'Contents/Resources/DWARF/StarSwiftBin', + {'module_audits': [sw_audit]}, + require_topology='sparse_switch', + ) + self.assertEqual(sw_gate['failed_count'], 0) + self.assertGreaterEqual(sw_gate['verified_star_count'], 1) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_m9_nonlinear_and_bbsplit_pass.py b/tests/test_m9_nonlinear_and_bbsplit_pass.py new file mode 100644 index 0000000..1c318ae --- /dev/null +++ b/tests/test_m9_nonlinear_and_bbsplit_pass.py @@ -0,0 +1,366 @@ +"""Unit tests for M9: nonlinear MBA, table-free OpaqueZero, IGBasicBlockSplit, and per-rule overrides.""" +import json +from pathlib import Path +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 + + +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 TestM9NonlinearAndBBSplitPass(unittest.TestCase): + def test_nonlinear_mba_32_and_64_bit_exact_and_mul_survives(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-m9-nlmba-') as td: + p = Path(td) + policy_path = p / 'policy.json' + policy_path.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'arithmetic_rounds': 1, + 'arithmetic_max_per_fn': 64, + 'arithmetic_targets': [ + { + 'id': 'nl_test', + 'path_contains': 'nlmba.c', + 'function_contains': 'nl_ops', + 'nonlinear_mba': True, + 'rounds': 1, + 'max_per_fn': 64, + 'probability': 100, + } + ], + }), encoding='utf-8') + + src_c = p / 'nlmba.c' + src_c.write_text( + '''#include +#include +#include + +__attribute__((noinline)) +uint32_t nl_ops32(uint32_t x, uint32_t y) { + uint32_t s = x + y; + uint32_t d = s - (y ^ 0xA55A3C19u); + uint32_t m = (d ^ x) & (s | 0x5A3C96E1u); + uint32_t o = m | (d + 0x13579BDFu); + return s ^ d ^ m ^ o; +} + +__attribute__((noinline)) +uint64_t nl_ops64(uint64_t x, uint64_t y) { + uint64_t s = x + y; + uint64_t d = s - (y ^ 0xA5C3F10E7B2D4968ULL); + uint64_t m = (d ^ x) & (s | 0x0F1E2D3C4B5A6978ULL); + uint64_t o = m | (d + 0x0102030405060708ULL); + return s ^ d ^ m ^ o; +} + +__attribute__((noinline)) +static uint32_t ref_ops32(uint32_t x, uint32_t y) { + uint32_t s = x + y; + uint32_t d = s - (y ^ 0xA55A3C19u); + uint32_t m = (d ^ x) & (s | 0x5A3C96E1u); + uint32_t o = m | (d + 0x13579BDFu); + return s ^ d ^ m ^ o; +} + +__attribute__((noinline)) +static uint64_t ref_ops64(uint64_t x, uint64_t y) { + uint64_t s = x + y; + uint64_t d = s - (y ^ 0xA5C3F10E7B2D4968ULL); + uint64_t m = (d ^ x) & (s | 0x0F1E2D3C4B5A6978ULL); + uint64_t o = m | (d + 0x0102030405060708ULL); + return s ^ d ^ m ^ o; +} + +int main(void) { + const uint32_t v32[] = {0u, 1u, 0xFFFFFFFFu, (uint32_t)INT32_MIN, (uint32_t)INT32_MAX, 0x12345678u, 0x80000001u}; + const uint64_t v64[] = {0ULL, 1ULL, UINT64_MAX, (uint64_t)INT64_MIN, (uint64_t)INT64_MAX, 0xDEADBEEFCAFEBABEULL}; + for (unsigned i = 0; i < sizeof(v32) / sizeof(v32[0]); ++i) { + for (unsigned j = 0; j < sizeof(v32) / sizeof(v32[0]); ++j) { + if (nl_ops32(v32[i], v32[j]) != ref_ops32(v32[i], v32[j])) return 1; + } + } + for (unsigned i = 0; i < sizeof(v64) / sizeof(v64[0]); ++i) { + for (unsigned j = 0; j < sizeof(v64) / sizeof(v64[0]); ++j) { + if (nl_ops64(v64[i], v64[j]) != ref_ops64(v64[i], v64[j])) return 2; + } + } + uint64_t state = 0x9E3779B97F4A7C15ULL; + for (int k = 0; k < 200; ++k) { + state = state * 6364136223846793005ULL + 1442695040888963407ULL; + uint64_t y = (state >> 17) ^ (state << 29); + if (nl_ops64(state, y) != ref_ops64(state, y)) return 3; + if (nl_ops32((uint32_t)state, (uint32_t)y) != ref_ops32((uint32_t)state, (uint32_t)y)) return 4; + } + return 0; +} +''', + encoding='utf-8', + ) + + bc_h = p / 'nl_h.bc' + obf_h = p / 'nl_h.obf.bc' + obj_h = p / 'nl_h.o' + exe_h = p / 'nl_h_exe' + aud_h = p / 'nl_h.audit.json' + subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_h)], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_nl_1', + f'--ig-source-path={src_c}', f'--ig-audit-out={aud_h}', + str(bc_h), '-o', str(obf_h), + ], check=True) + audit = json.loads(aud_h.read_text(encoding='utf-8')) + self.assertGreaterEqual(audit['nonlinear_mba_count'], 5) + + subprocess.run([ + clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes', + '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_h), '-o', str(obj_h), + ], check=True) + subprocess.run([clang, '-isysroot', sdk_host, str(obj_h), '-o', str(exe_h)], check=True) + rc = subprocess.run([str(exe_h)]).returncode + self.assertEqual(rc, 0) + + # iOS arm64 check + objdump verifying mul instruction survives backend CodeGen + bc_ios = p / 'nl_ios.bc' + obf_ios = p / 'nl_ios.obf.bc' + obj_ios = p / 'nl_ios.o' + aud_ios = p / 'nl_ios.audit.json' + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, + '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_ios), + ], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_nl_ios', + f'--ig-source-path={src_c}', f'--ig-audit-out={aud_ios}', + str(bc_ios), '-o', str(obf_ios), + ], check=True) + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, + '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', + '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ios), '-o', str(obj_ios), + ], check=True) + disasm = subprocess.check_output(['xcrun', 'objdump', '-d', str(obj_ios)], text=True) + self.assertIn('\tmul\t', disasm) + + def test_opaque_zero_hides_literals_without_data_pool(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-m9-oz-') as td: + p = Path(td) + policy_path = p / 'policy.json' + policy_path.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'opaque_const_targets': [ + {'id': 'oz_rule', 'path_contains': 'oz.c', 'function_contains': 'oz_', 'opaque_zero': True} + ], + }), encoding='utf-8') + + src_c = p / 'oz.c' + src_c.write_text( + '''#include +#include + +__attribute__((noinline)) +uint32_t oz_magic32(uint32_t x) { + uint32_t h = x ^ 0x13579BDFu; + if (h == 0x2468ACE0u) { + return h + 0x55AA1122u; + } + return h + 0x76543211u; +} + +__attribute__((noinline)) +uint64_t oz_magic64(void) { + return (uint64_t)0x5A3C96F12468ACE0ULL; +} + +__attribute__((noinline)) +uint64_t oz_magic64_arg(uint64_t seed) { + return (seed + 0x1020304050607080ULL) ^ 0x5A3C96F12468ACE0ULL; +} + +int main(void) { + if (oz_magic32(0x13579BDFu ^ 0x2468ACE0u) != (0x2468ACE0u + 0x55AA1122u)) return 1; + if (oz_magic32(123u) != ((123u ^ 0x13579BDFu) + 0x76543211u)) return 2; + if (oz_magic64() != 0x5A3C96F12468ACE0ULL) return 3; + if (oz_magic64_arg(0x1111111111111111ULL) != ((0x1111111111111111ULL + 0x1020304050607080ULL) ^ 0x5A3C96F12468ACE0ULL)) return 4; + return 0; +} +''', + encoding='utf-8', + ) + + bc_h = p / 'oz_h.bc' + obf_ll = p / 'oz_h.obf.ll' + obj_h = p / 'oz_h.o' + exe_h = p / 'oz_h_exe' + aud_h = p / 'oz_h.audit.json' + subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_h)], check=True) + subprocess.run([ + opt_path, '-S', '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_oz_1', + f'--ig-source-path={src_c}', f'--ig-audit-out={aud_h}', + str(bc_h), '-o', str(obf_ll), + ], check=True) + + ir_text = obf_ll.read_text(encoding='utf-8') + non_dbg_ir = '\n'.join(l for l in ir_text.splitlines() if '#dbg_' not in l) + self.assertNotIn('__ig_ocp_', non_dbg_ir, 'Table-free OpaqueZero should not allocate __ig_ocp_ pool') + self.assertNotIn('324508639', non_dbg_ir) # 0x13579BDF + self.assertNotIn('6502235449435991264', non_dbg_ir) # 0x5A3C96F12468ACE0 + + audit = json.loads(aud_h.read_text(encoding='utf-8')) + self.assertGreaterEqual(audit['opaque_zero_count'], 2) + + 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_h), + ], check=True) + subprocess.run([clang, '-isysroot', sdk_host, str(obj_h), '-o', str(exe_h)], check=True) + self.assertEqual(subprocess.run([str(exe_h)]).returncode, 0) + + # iOS arm64 check: verify literal chunks of 0x13579BDF and 0x5A3C96F12468ACE0 absent in disasm + bc_ios = p / 'oz_ios.bc' + obf_ios = p / 'oz_ios.obf.bc' + obj_ios = p / 'oz_ios.o' + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, + '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_ios), + ], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_oz_ios', + f'--ig-source-path={src_c}', f'--ig-audit-out={p / "oz_ios.audit.json"}', + str(bc_ios), '-o', str(obf_ios), + ], check=True) + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, + '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', + '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ios), '-o', str(obj_ios), + ], check=True) + disasm = subprocess.check_output(['xcrun', 'objdump', '-d', str(obj_ios)], text=True) + # Low 16-bit of 0x13579BDF = 0x9bdf, high = 0x1357 + self.assertNotIn('#0x9bdf', disasm.lower()) + self.assertNotIn('#0x1357', disasm.lower()) + self.assertNotIn('#0x5a3c', disasm.lower()) + + def test_bbsplit_and_per_rule_overrides_with_flattening(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + sdk_host = macos_sdk_path() + + with tempfile.TemporaryDirectory(prefix='ig-m9-bb-') as td: + p = Path(td) + policy_path = p / 'policy.json' + policy_path.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'bb_split_max_per_fn': 4, + 'bb_split_min_insts': 4, + 'bb_split_targets': [ + {'id': 'bb_rule', 'path_contains': 'bbs.c', 'function_contains': 'long_linear_fn', 'max_per_fn': 2} + ], + 'flatten_targets': [{'path_contains': 'bbs.c', 'function_contains': 'long_linear_fn'}], + 'opaque_const_targets': [ + {'id': 'cap_const', 'path_contains': 'bbs.c', 'function_contains': 'long_linear_fn', 'max_per_fn': 2} + ], + 'arithmetic_targets': [ + {'id': 'cap_arith', 'path_contains': 'bbs.c', 'function_contains': 'long_linear_fn', 'rounds': 2, 'max_per_fn': 3} + ], + }), encoding='utf-8') + + src_c = p / 'bbs.c' + src_c.write_text( + '''#include + +__attribute__((noinline)) +uint32_t long_linear_fn(uint32_t x, uint32_t y) { + uint32_t a = (x * 7u) ^ 0x11111111u; + uint32_t b = (y * 13u) + 0x22222222u; + uint32_t c = (a + b) ^ (x >> 3); + uint32_t d = (c - y) + (a & 0x33333333u); + uint32_t e = (d ^ b) | (c & 0x44444444u); + uint32_t f = (e + a) ^ (d * 5u); + return f + c; +} + +int main(void) { + uint32_t r = long_linear_fn(0x1234u, 0x5678u); + uint32_t x = 0x1234u, y = 0x5678u; + uint32_t a = (x * 7u) ^ 0x11111111u; + uint32_t b = (y * 13u) + 0x22222222u; + uint32_t c = (a + b) ^ (x >> 3); + uint32_t d = (c - y) + (a & 0x33333333u); + uint32_t e = (d ^ b) | (c & 0x44444444u); + uint32_t f = (e + a) ^ (d * 5u); + return (r == (f + c)) ? 0 : 1; +} +''', + encoding='utf-8', + ) + + bc_h = p / 'bb.bc' + obf_h = p / 'bb.obf.bc' + obj_h = p / 'bb.o' + exe_h = p / 'bb_exe' + aud_h = p / 'bb.audit.json' + subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_h)], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_bb_1', + f'--ig-source-path={src_c}', f'--ig-audit-out={aud_h}', + str(bc_h), '-o', str(obf_h), + ], check=True) + + audit = json.loads(aud_h.read_text(encoding='utf-8')) + self.assertGreaterEqual(audit['bb_split_count'], 1) + self.assertLessEqual(audit['bb_split_count'], 2) + # Single linear block was split so flattening should now transform it cleanly! + self.assertIn('long_linear_fn', audit['functions_flattened']) + self.assertLessEqual(audit['opaque_constants_count'], 2) + self.assertLessEqual(audit['arithmetic_rewrites_count'], 3) + + subprocess.run([ + clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes', + '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_h), '-o', str(obj_h), + ], check=True) + subprocess.run([clang, '-isysroot', sdk_host, str(obj_h), '-o', str(exe_h)], check=True) + self.assertEqual(subprocess.run([str(exe_h)]).returncode, 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_mba_and_opaque_const_pass.py b/tests/test_mba_and_opaque_const_pass.py new file mode 100644 index 0000000..7db6d3f --- /dev/null +++ b/tests/test_mba_and_opaque_const_pass.py @@ -0,0 +1,248 @@ +"""Unit tests for M2 passes: IGOpaqueConstants and IGArithmetic (Linear MBA).""" +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' +APP_REPO = ROOT / 'readoor-test' +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() + + +class TestMbaAndOpaqueConstantsPass(unittest.TestCase): + def test_mba_all_ops_edge_values_and_const_hiding_execution(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + sdk = macos_sdk_path() + + with tempfile.TemporaryDirectory(prefix='ig-m2-mba-') as td: + p = Path(td) + policy_path = p / 'policy.json' + policy_path.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'opaque_const_max_per_fn': 64, + 'arithmetic_rounds': 2, + 'arithmetic_max_per_fn': 256, + 'opaque_const_targets': [{'path_contains': 'mba_test.c'}], + 'arithmetic_targets': [{'path_contains': 'mba_test.c'}], + 'opaque_const_exempt_functions': ['rd_sd_sha256_transform'], + 'arithmetic_exempt_functions': ['rd_sd_sha256_transform'], + }), encoding='utf-8') + + src_c = p / 'mba_test.c' + src_c.write_text( + '''#include +#include +#include + +__attribute__((noinline)) +uint32_t mba_ops32(uint32_t x, uint32_t y) { + uint32_t a = x + y; + uint32_t b = a - (y ^ 0xA55A3C19u); + uint32_t c = (b ^ x) | (a & 0x5A3C96E1u); + uint32_t d = (c + 0x13579BDFu) & (b + 1u); + if (d == 0x2468ACE0u) { + return d ^ 0x77777777u; + } + return a ^ b ^ c ^ d ^ 0xCAFEBABEu; +} + +__attribute__((noinline)) +uint64_t mba_ops64(uint64_t x, uint64_t y) { + uint64_t a = x + y; + uint64_t b = a - (y ^ 0xA5C3F10E7B2D4968ULL); + uint64_t c = (b ^ x) | (a & 0x0F1E2D3C4B5A6978ULL); + uint64_t d = (c + 0x0102030405060708ULL) & (b + 3ULL); + return a ^ b ^ c ^ d ^ 0xFEDCBA9876543210ULL; +} + +__attribute__((noinline)) +uint32_t rd_sd_sha256_transform(uint32_t x, uint32_t y) { + return (x + y) ^ 0x428A2F98u; +} + +__attribute__((noinline)) +static uint32_t ref_ops32(uint32_t x, uint32_t y) { + uint32_t a = x + y; + uint32_t b = a - (y ^ 0xA55A3C19u); + uint32_t c = (b ^ x) | (a & 0x5A3C96E1u); + uint32_t d = (c + 0x13579BDFu) & (b + 1u); + if (d == 0x2468ACE0u) { + return d ^ 0x77777777u; + } + return a ^ b ^ c ^ d ^ 0xCAFEBABEu; +} + +__attribute__((noinline)) +static uint64_t ref_ops64(uint64_t x, uint64_t y) { + uint64_t a = x + y; + uint64_t b = a - (y ^ 0xA5C3F10E7B2D4968ULL); + uint64_t c = (b ^ x) | (a & 0x0F1E2D3C4B5A6978ULL); + uint64_t d = (c + 0x0102030405060708ULL) & (b + 3ULL); + return a ^ b ^ c ^ d ^ 0xFEDCBA9876543210ULL; +} + +int main(void) { + const uint32_t vals32[] = { + 0u, 1u, 2u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu, + 0x12345678u, 0xA55A3C19u, 0x5A3C96E1u, 0xCAFEBABEu + }; + const uint64_t vals64[] = { + 0ULL, 1ULL, 2ULL, 0x7FFFFFFFFFFFFFFFULL, 0x8000000000000000ULL, + 0xFFFFFFFFFFFFFFFFULL, 0xA5C3F10E7B2D4968ULL, 0x0123456789ABCDEFULL + }; + size_t n32 = sizeof(vals32) / sizeof(vals32[0]); + for (size_t i = 0; i < n32; ++i) { + for (size_t j = 0; j < n32; ++j) { + if (mba_ops32(vals32[i], vals32[j]) != ref_ops32(vals32[i], vals32[j])) { + fprintf(stderr, "32-bit mismatch at %zu,%zu\\n", i, j); + return 2; + } + } + } + size_t n64 = sizeof(vals64) / sizeof(vals64[0]); + for (size_t i = 0; i < n64; ++i) { + for (size_t j = 0; j < n64; ++j) { + if (mba_ops64(vals64[i], vals64[j]) != ref_ops64(vals64[i], vals64[j])) { + fprintf(stderr, "64-bit mismatch at %zu,%zu\\n", i, j); + return 3; + } + } + } + if (rd_sd_sha256_transform(17u, 29u) != ((17u + 29u) ^ 0x428A2F98u)) { + return 4; + } + return 0; +} +''', + encoding='utf-8', + ) + bc_p = p / 'mba.bc' + subprocess.run([clang, '-isysroot', sdk, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_p)], check=True) + + def compile_mode(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_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) + subprocess.run([clang, '-isysroot', sdk, 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')) + + o_a1, exe_a1, aud_a1 = compile_mode('a1', 'seed_m2_1', 'all') + o_a2, _, _ = compile_mode('a2', 'seed_m2_1', 'all') + o_b1, exe_b1, aud_b1 = compile_mode('b1', 'seed_m2_2', 'all') + _, exe_const, aud_const = compile_mode('const_only', 'seed_m2_1', 'const') + _, exe_arith, aud_arith = compile_mode('arith_only', 'seed_m2_1', 'arith') + + # Determinism and seed 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()) + + # Pass filter isolation & exemptions + self.assertGreaterEqual(aud_a1['opaque_constants_count'], 4) + self.assertGreaterEqual(aud_a1['arithmetic_rewrites_count'], 8) + self.assertEqual(aud_const['arithmetic_rewrites_count'], 0) + self.assertEqual(aud_const['functions_flattened'], []) + self.assertEqual(aud_arith['opaque_constants_count'], 0) + self.assertEqual(aud_arith['functions_flattened'], []) + self.assertNotIn('rd_sd_sha256_transform', aud_a1['opaque_constants_functions']) + self.assertNotIn('rd_sd_sha256_transform', aud_a1['arithmetic_functions']) + + # Execute obfuscated arm64 binaries to confirm 100% bit-exact arithmetic equivalence + for exe in (exe_a1, exe_b1, exe_const, exe_arith): + self.assertEqual(subprocess.run([str(exe)]).returncode, 0, f'{exe} execution failed') + + # Verify plaintext magic constants disappeared from mba_ops32 / mba_ops64 disassembly + dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(exe_a1)], text=True) + m32_dis = dis.split('<_mba_ops32>:', 1)[1].split('<_mba_ops64>:', 1)[0].lower() + for needle in ('a55a', '3c19', 'babe'): + self.assertNotIn(needle, m32_dis) + m64_dis = dis.split('<_mba_ops64>:', 1)[1].split('<_rd_sd_sha256_transform>:', 1)[0].lower() + for needle in ('7b2d', '4968', 'fedc'): + self.assertNotIn(needle, m64_dis) + + def test_sd_keybox_real_file_with_m2_passes(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + sdk = macos_sdk_path() + keybox_c = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.c' + defender_dir = ROOT / 'defender' + policy_path = ROOT / 'config/ig_llvm_policy.json' + + with tempfile.TemporaryDirectory(prefix='ig-m2-kb-') as td: + p = Path(td) + raw_bc = p / 'RDSDKeyBox.bc' + obf_bc = p / 'RDSDKeyBox.obf.bc' + aud_p = p / 'audit.json' + obj_o = p / 'RDSDKeyBox.o' + subprocess.run([ + clang, '-isysroot', sdk, '-Os', '-g', '-fvisibility=hidden', + '-I', str(defender_dir), '-I', str(defender_dir / 'include'), + '-I', str(keybox_c.parent), + '-emit-llvm', '-c', str(keybox_c), '-o', str(raw_bc), + ], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', + '--ig-mode=full', + '--ig-pass-filter=all', + '--ig-seed=m2_kb_test_seed', + f'--ig-source-path={keybox_c}', + f'--ig-audit-out={aud_p}', + str(raw_bc), '-o', str(obf_bc), + ], check=True) + subprocess.run([ + clang, '-isysroot', sdk, '-Os', + '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', + '-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o), + ], check=True) + aud = json.loads(aud_p.read_text(encoding='utf-8')) + self.assertGreaterEqual(aud.get('opaque_constants_count', 0), 10, aud) + self.assertGreaterEqual(aud.get('arithmetic_rewrites_count', 0), 10, aud) + self.assertNotIn('_rd_sd_sha256_transform', aud.get('arithmetic_functions', [])) + self.assertNotIn('rd_sd_sha256_transform', aud.get('arithmetic_functions', [])) + self.assertNotIn('rd_sd_md5_hex', aud.get('arithmetic_functions', [])) + dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(obj_o)], text=True) + # 0xA55A3C19 should not appear as literal immediate operands in non-exempt _rd_sd_sha256_init + init_dis = dis.split('<_rd_sd_sha256_init>:', 1)[1].split('<_rd_sd_sha256_update>:', 1)[0].lower() + self.assertNotIn('0x3c19', init_dis) + self.assertNotIn('0xa55a', init_dis) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_network_and_keybox_hardening.py b/tests/test_network_and_keybox_hardening.py new file mode 100644 index 0000000..e48a67b --- /dev/null +++ b/tests/test_network_and_keybox_hardening.py @@ -0,0 +1,716 @@ +"""Regressions for RDBaseNetworkService plaintext-bypass fix, v3.1 C KeyBox, and Release diagnostic stripping.""" +import hashlib +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest +import zlib + +ROOT = Path(__file__).resolve().parents[1] +APP_REPO = ROOT / 'readoor-test' +NETWORK_SVC = APP_REPO / 'readoor/3.0/Network/RDBaseNetworkService.swift' +API_RESULT = APP_REPO / 'readoor/3.0/Network/RDRequestApiResult.swift' +SD_KEYBOX_C = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.c' +SD_KEYBOX_H = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.h' +POISON_C = ROOT / 'defender/poison/IGPoison.c' +DEFENDER_DIR = ROOT / 'defender' + +DEFENDER_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', +] + + +def _have_macos_tools() -> bool: + return sys.platform == 'darwin' and shutil.which('xcrun') is not None + + +@unittest.skipUnless(_have_macos_tools(), '需要 Xcode/macOS 工具链') +class NetworkAndKeyBoxHardeningTests(unittest.TestCase): + def test_parse_response_data_blocks_all_plaintext_bypasses(self): + self.assertTrue(NETWORK_SVC.is_file() and API_RESULT.is_file()) + with tempfile.TemporaryDirectory(prefix='ig-net-test-') as td: + p = Path(td) + mod_dir = p / 'modules' + mod_dir.mkdir() + macos_sdk = subprocess.check_output( + ['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True + ).strip() + + swifty_json_swift = p / 'SwiftyJSON.swift' + swifty_json_swift.write_text( + ''' +import Foundation + +public struct JSON { + private let raw: Any? + private let present: Bool + + public init(_ object: Any) { + self.raw = object + self.present = !(object is NSNull) + } + + private init(raw: Any?, present: Bool) { + self.raw = raw + self.present = present + } + + public init(data: Data) throws { + let obj = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) + self.init(obj) + } + + public func exists() -> Bool { + return present + } + + public subscript(key: String) -> JSON { + if let dict = raw as? [String: Any], let val = dict[key] { + return JSON(raw: val, present: !(val is NSNull)) + } + return JSON(raw: nil, present: false) + } + + public var intValue: Int { + if let n = raw as? NSNumber { + return n.intValue + } + if let s = raw as? String { + return Int(s) ?? 0 + } + return 0 + } + + public var stringValue: String { + if let s = raw as? String { + return s + } + if let n = raw as? NSNumber { + return n.stringValue + } + return "" + } +} +''', + encoding='utf-8', + ) + + alamofire_swift = p / 'Alamofire.swift' + alamofire_swift.write_text( + ''' +import Foundation + +public typealias Parameters = [String: Any] + +public protocol URLConvertible {} +extension String: URLConvertible {} +extension URL: URLConvertible {} + +public struct HTTPMethod { + public let rawValue: String + public static let post = HTTPMethod(rawValue: "POST") + public static let get = HTTPMethod(rawValue: "GET") +} + +public struct HTTPHeaders { + public init() {} + public mutating func add(name: String, value: String) {} +} + +public enum AFError: Error { + case sessionTaskFailed(error: Error) + case responseValidationFailed(reason: ResponseValidationFailureReason) + public enum ResponseValidationFailureReason { + case unacceptableStatusCode(code: Int) + } + public var isSessionTaskError: Bool { + if case .sessionTaskFailed = self { return true } + return false + } +} + +public struct AFDataResponse { + public let result: Result = .failure(NSError(domain: "test", code: -1)) + public let response: HTTPURLResponse? = nil +} + +public final class AFRequest { + public func responseData(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) {} + public func responseData() -> AFDataResponse { return AFDataResponse() } + public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping (Progress) -> Void) -> AFRequest { return self } +} + +public final class MultipartFormData { + public func append(_ data: Data, withName: String, fileName: String? = nil, mimeType: String? = nil) {} +} + +public enum AF { + public static func request(_ convertible: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, headers: HTTPHeaders? = nil) -> AFRequest { + return AFRequest() + } + public static func upload(multipartFormData: (MultipartFormData) -> Void, to: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> AFRequest { + return AFRequest() + } +} + +public final class NetworkReachabilityManager { + public init?() {} + public var isReachable: Bool { return true } +} +''', + encoding='utf-8', + ) + + jk_swift = p / 'JKSwiftExtension.swift' + jk_swift.write_text('import Foundation\npublic let ig_jk_shim = 1\n', encoding='utf-8') + + for mod_name, src in ( + ('SwiftyJSON', swifty_json_swift), + ('Alamofire', alamofire_swift), + ('JKSwiftExtension', jk_swift), + ): + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'swiftc', '-parse-as-library', + '-emit-module', '-emit-module-path', str(mod_dir / f'{mod_name}.swiftmodule'), + '-module-name', mod_name, '-sdk', macos_sdk, + '-c', str(src), '-o', str(p / f'{mod_name}.o'), + ], check=True) + + main_swift = p / 'main.swift' + main_swift.write_text( + r''' +import Foundation +import Compression +import SwiftyJSON +import Alamofire + +final class RDAccountLoginModel { + static let shared = RDAccountLoginModel() + var token: String? = "tok" +} + +enum RDOSLogManager { + static var diagCodes: [String] = [] + static func logDebug(_ msg: String) {} + static func logError(_ msg: String) {} + static func logDiag(_ code: String) { diagCodes.append(code) } +} + +enum RDRequestParamsFormat { + static func fdkldftierjkfioemcop(_ param: Any) -> [String: Any] { return [:] } + static func fdjkweiojcxmewkqw(_ paramDic: [String: Any], ct: String) -> (parameters: [String: Any]?, key: String, headers: [String: String]?) { + return (paramDic, "", nil) + } +} + +enum StsSimpleCrypt { + static func sfc_strDecrypt(_ key1: String, key2: String, str: String) -> String! { + let prefix = "ENC:\(key1):" + guard str.hasPrefix(prefix) else { return nil } + return String(str.dropFirst(prefix.count)) + } +} + +extension NSData { + func uncompressZipped() -> Data? { + let marker = Data("GZ:".utf8) + let raw = self as Data + guard raw.starts(with: marker) else { return nil } + return raw.dropFirst(marker.count) + } +} + +extension RDBaseNetworkService { + static func printRequestStartLog(convertible: URLConvertible, method: HTTPMethod) {} + static func printRequestMetadataLog(convertible: URLConvertible, action: String, statusCode: Int? = nil, failed: Bool = false) {} + static func printRequestLog(convertible: URLConvertible, httpHeaders: HTTPHeaders?, parameters: Parameters?, responseData: Any) {} + static func printRequestErrorLog(convertible: URLConvertible, method: HTTPMethod, httpHeaders: HTTPHeaders?, parameters: Parameters?, statusCode: Int?, businessCode: String? = nil, error: Error? = nil, message: String? = nil) {} +} + +func assertRejectsDataError(_ label: String, _ work: () throws -> JSON) { + do { + _ = try work() + fatalError("Expected failure on case: \(label)") + } catch RDRequestApiError.dataError { + print("REJECT_OK|\(label)") + } catch { + fatalError("Unexpected error \(error) on case: \(label)") + } +} + +// 1) key == "" allows plaintext JSON +let j1 = try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":1,"data":{"ok":1}}"#.utf8), key: "") +assert(j1["status"].intValue == 1) +print("PASS|plain_key_empty") + +// 2) key != "" + valid encrypted JSON +let j2 = try RDBaseNetworkService.parseResponseData(responseData: Data(#"ENC:k31:{"status":1,"msg":"ok"}"#.utf8), key: "k31") +assert(j2["status"].intValue == 1 && j2["msg"].stringValue == "ok") +print("PASS|enc_plain_json") + +// 3) key != "" + valid encrypted base64+gzipped JSON +let gzPayload = Data("GZ:".utf8) + Data(#"{"status":1,"book":"ok"}"#.utf8) +let b64 = gzPayload.base64EncodedString() +let j3 = try RDBaseNetworkService.parseResponseData(responseData: Data("ENC:k31:\(b64)".utf8), key: "k31") +assert(j3["status"].intValue == 1 && j3["book"].stringValue == "ok") +print("PASS|enc_b64_gz_json") + +// 4) key != "" + plaintext error status == 0 is allowed +let j4 = try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":0,"message":"无权访问"}"#.utf8), key: "k31") +assert(j4["status"].intValue == 0 && j4["message"].stringValue == "无权访问") +print("PASS|plain_err_status0") + +// 5) key != "" + plaintext err_code error without status is allowed +let j5 = try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"err_code":"TOKEN_EXPIRED","message":"expired"}"#.utf8), key: "k31") +assert(j5["err_code"].stringValue == "TOKEN_EXPIRED") +print("PASS|plain_err_code") + +// 6) key != "" + plaintext status == 1 MUST BE REJECTED +assertRejectsDataError("plain_status_int_1") { + try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":1,"data":{"vip":1}}"#.utf8), key: "k31") +} + +// 7) key != "" + string "1", whitespace " 1 ", and boolean true MUST BE REJECTED +assertRejectsDataError("plain_status_str_1") { + try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":"1","data":{"vip":1}}"#.utf8), key: "k31") +} +assertRejectsDataError("plain_status_ws_1") { + try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":" 1 ","data":{"vip":1}}"#.utf8), key: "k31") +} +assertRejectsDataError("plain_status_bool_true") { + try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":true,"data":{"vip":1}}"#.utf8), key: "k31") +} + +// 8) key != "" + err_code / HTML bypass trick MUST BE REJECTED (not fall through to raw JSON parse) +assertRejectsDataError("bypass_err_code_with_status1") { + try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":1,"err_code":"","note":"
"}"#.utf8), key: "k31") +} + +// 9) key != "" + top-level array / empty JSON / malformed HTML error MUST BE REJECTED +assertRejectsDataError("plain_top_array") { + try RDBaseNetworkService.parseResponseData(responseData: Data(#"[{"status":1}]"#.utf8), key: "k31") +} +assertRejectsDataError("plain_empty_obj") { + try RDBaseNetworkService.parseResponseData(responseData: Data(#"{}"#.utf8), key: "k31") +} +assertRejectsDataError("malformed_html_error") { + try RDBaseNetworkService.parseResponseData(responseData: Data(#"
fatal.php
"#.utf8), key: "k31") +} +assertRejectsDataError("decrypt_nil") { + try RDBaseNetworkService.parseResponseData(responseData: Data(#"CORRUPT_CIPHER"#.utf8), key: "k31") +} +print("DIAG|\(RDOSLogManager.diagCodes.joined(separator: ","))") +''', + encoding='utf-8', + ) + + exe = p / 'net_test' + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'swiftc', + '-I', str(mod_dir), '-sdk', macos_sdk, + str(API_RESULT), str(NETWORK_SVC), str(main_swift), + str(p / 'SwiftyJSON.o'), str(p / 'Alamofire.o'), str(p / 'JKSwiftExtension.o'), + '-o', str(exe), + ], check=True) + out = subprocess.check_output([str(exe)], text=True).splitlines() + self.assertIn('PASS|plain_key_empty', out) + self.assertIn('PASS|enc_plain_json', out) + self.assertIn('PASS|enc_b64_gz_json', out) + self.assertIn('PASS|plain_err_status0', out) + self.assertIn('PASS|plain_err_code', out) + for tag in ( + 'plain_status_int_1', + 'plain_status_str_1', + 'plain_status_ws_1', + 'plain_status_bool_true', + 'bypass_err_code_with_status1', + 'plain_top_array', + 'plain_empty_obj', + 'malformed_html_error', + 'decrypt_nil', + ): + self.assertIn(f'REJECT_OK|{tag}', out) + diag_line = [ln for ln in out if ln.startswith('DIAG|')][0] + self.assertIn('E-4112', diag_line) + self.assertIn('E-4113', diag_line) + self.assertIn('E-4114', diag_line) + + def test_v31_keybox_md5_boundaries_poison_and_zero_call_edges(self): + self.assertTrue(SD_KEYBOX_C.is_file() and SD_KEYBOX_H.is_file()) + with tempfile.TemporaryDirectory(prefix='ig-v31-kb-') as td: + p = Path(td) + macos_sdk = subprocess.check_output( + ['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True + ).strip() + kb_o = p / 'RDSDKeyBox.o' + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'clang', '-isysroot', macos_sdk, + '-Os', '-Wall', '-Wextra', '-Werror', '-fvisibility=hidden', + '-I', str(DEFENDER_DIR), '-I', str(DEFENDER_DIR / 'include'), + '-I', str(SD_KEYBOX_C.parent), + '-c', str(SD_KEYBOX_C), '-o', str(kb_o), + ], check=True) + + nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(kb_o)], text=True) + for forbidden_u in ( + '_CC_MD5', + '_ig_poison_', + '_CCKeyDerivationPBKDF', + '_SecKeyCreateWithData', + '_SecKeyCreateSignature', + '_CCCrypt', + '_CCHmac', + '_sysctl', + ): + self.assertNotIn(forbidden_u, nm_u) + self.assertIn('_ig_pstate', nm_u) + self.assertIn('_ig_resolve_verified', nm_u) + + raw_kb_o = kb_o.read_bytes() + raw_kb_lower = raw_kb_o.lower() + kb_strings_lower = subprocess.check_output(['strings', '-a', str(kb_o)], text=True, errors='replace').lower() + for leaked in ( + b'7ARrksiF7AoWXXBlmxfz9suSmTka7A', + b'startiasoftstartiasoft', + b'startiasoftvvportal', + b'readoorstartiasoft', + b'd9800fb39d16c3f1cc0ddb5618af8378', + b'rd_glyph_lut_v2', + b'rd_net_cfg_v1', + ): + self.assertNotIn(leaked, raw_kb_o) + for jb_needle in ( + 'cydia', + 'mobilesubstrate', + 'trollstore', + '/var/jb', + 'jailbreak', + '/user/applications', + 'frida', + '.rd_eprobe', + '127.0.0.1', + ): + self.assertNotIn(jb_needle.encode('ascii'), raw_kb_lower) + self.assertNotIn(jb_needle, kb_strings_lower) + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + pem_path = APP_REPO / 'AutoPacking/sd_priv_ios_v1.pem' + plain_pem = pem_path.read_bytes() + pbkdf_key = hashlib.pbkdf2_hmac('sha256', b'readoor_sd_v32_ci_key_2026', b'readoor_sd_v32_salt_fixed', 100_000, 32) + nonce12 = b'\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc' + sealed_asset = nonce12 + AESGCM(pbkdf_key).encrypt(nonce12, plain_pem, None) + (p / 'asset.bin').write_bytes(sealed_asset) + tampered_asset = bytearray(sealed_asset) + tampered_asset[-1] ^= 0xFF + (p / 'asset_tamper.bin').write_bytes(bytes(tampered_asset)) + from cryptography.hazmat.primitives import serialization + der_path = p / 'priv_pkcs1.der' + priv_obj = serialization.load_pem_private_key(plain_pem, password=None) + der_path.write_bytes( + priv_obj.private_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PrivateFormat.TraditionalOpenSSL, + encryption_algorithm=serialization.NoEncryption(), + ) + ) + + harness = p / 'harness.c' + harness.write_text( + r''' +#include +#include +#include +#include +#include "RDSDKeyBox.h" +#include "poison/IGPoison.h" + +static void fill_pattern(char *buf, size_t n, char ch) { + for (size_t i = 0; i < n; ++i) buf[i] = (char)(ch + (i % 10)); + buf[n] = '\0'; +} + +static uint8_t *read_all(const char *path, size_t *out_len) { + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + long n = ftell(f); + fseek(f, 0, SEEK_SET); + uint8_t *buf = (uint8_t *)malloc((size_t)n); + if (!buf || fread(buf, 1, (size_t)n, f) != (size_t)n) { fclose(f); free(buf); return NULL; } + fclose(f); + *out_len = (size_t)n; + return buf; +} + +int main(int argc, char **argv) { + if (argc < 4) return 99; + char out[64]; + if (rd_sd_derive_v31_seed(NULL, 32) != 0) return 1; + if (rd_sd_derive_v31_seed(out, 30) != 0) return 2; + if (rd_sd_derive_v31_dt_pwd("a", 1, "b", 1, out, 32) != 0) return 3; + if (rd_sd_derive_v31_dt_pwd(NULL, 2, "b", 1, out, 33) != 0) return 4; + + size_t slen = rd_sd_derive_v31_seed(out, 31); + printf("SEED|%zu|%s\n", slen, out); + + char sbuf64[64]; + size_t n_stem = rd_sd_bundle_asset_stem(sbuf64, sizeof(sbuf64)); + printf("STEM|%zu|%s\n", n_stem, sbuf64); + size_t n_m = rd_sd_media_decrypt_pwd(sbuf64, sizeof(sbuf64)); + printf("MEDIA|%zu|%s\n", n_m, sbuf64); + size_t n_db = rd_sd_db_secret_key(sbuf64, sizeof(sbuf64)); + printf("DBKEY|%zu|%s\n", n_db, sbuf64); + size_t n_tk = rd_sd_device_token_key(sbuf64, sizeof(sbuf64)); + printf("TOKEN|%zu|%s\n", n_tk, sbuf64); + size_t n_cs = rd_sd_course_sign_prefix(sbuf64, sizeof(sbuf64)); + printf("COURSE|%zu|%s\n", n_cs, sbuf64); + size_t n_wx = rd_sd_wx_pay_secret(sbuf64, sizeof(sbuf64)); + printf("WXSEC|%zu|%s\n", n_wx, sbuf64); + + size_t asset_len = 0, tamper_len = 0, der_len = 0; + uint8_t *asset = read_all(argv[1], &asset_len); + uint8_t *tamper = read_all(argv[2], &tamper_len); + uint8_t *der = read_all(argv[3], &der_len); + if (!asset || !tamper || !der) return 5; + uint8_t *dec = (uint8_t *)malloc(asset_len); + size_t dec_len = 0; + int gcm_ok = rd_sd_decrypt_bundled_asset(asset, asset_len, dec, asset_len, &dec_len); + size_t bad_len = 999; + int gcm_bad = rd_sd_decrypt_bundled_asset(tamper, tamper_len, dec, tamper_len, &bad_len); + printf("GCM|%d|%zu|%zu|%d|%zu\n", gcm_ok, dec_len, asset_len - 28u, gcm_bad, bad_len); + + CFDataRef derData = CFDataCreate(kCFAllocatorDefault, der, (CFIndex)der_len); + const void *keys[] = { kSecAttrKeyType, kSecAttrKeyClass }; + const void *vals[] = { kSecAttrKeyTypeRSA, kSecAttrKeyClassPrivate }; + CFDictionaryRef attrs = CFDictionaryCreate(kCFAllocatorDefault, keys, vals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFErrorRef err = NULL; + SecKeyRef privKey = rd_sd_seckey_create_with_data(derData, attrs, &err); + const char *msg = "ig_test_msg"; + CFDataRef msgData = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)msg, (CFIndex)strlen(msg)); + CFDataRef sig = privKey ? rd_sd_seckey_create_signature(privKey, kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA256, msgData, &err) : NULL; + printf("SECKEY|%d|%ld\n", privKey != NULL ? 1 : 0, sig ? (long)CFDataGetLength(sig) : -1L); + if (sig) CFRelease(sig); + if (privKey) CFRelease(privKey); + CFRelease(msgData); CFRelease(attrs); CFRelease(derData); + + const uint8_t hkey[4] = { 'k', 'e', 'y', '1' }; + const uint8_t hmsg[3] = { 'a', 'b', 'c' }; + uint8_t mac[32]; + int hrc = rd_sd_cc_hmac(2u, hkey, sizeof(hkey), hmsg, sizeof(hmsg), mac); + printf("HMAC|%d|", hrc); + for (int i = 0; i < 32; ++i) printf("%02x", mac[i]); + printf("\n"); + + const uint8_t aes_key[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; + const uint8_t aes_iv[16] = {15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0}; + const uint8_t plain16[17] = "0123456789abcdef"; + uint8_t ct[32], pt[32]; + size_t ct_moved = 0, pt_moved = 0; + int enc_rc = rd_sd_cc_crypt(0u, 0u, 1u, aes_key, 16u, aes_iv, plain16, 16u, ct, sizeof(ct), &ct_moved); + int dec_rc = rd_sd_cc_crypt(1u, 0u, 1u, aes_key, 16u, aes_iv, ct, ct_moved, pt, sizeof(pt), &pt_moved); + printf("CCCRYPT|%d|%zu|%d|%zu|%d\n", enc_rc, ct_moved, dec_rc, pt_moved, (pt_moved == 16u && memcmp(pt, plain16, 16u) == 0) ? 1 : 0); + + int traced = rd_sd_is_traced(); + printf("TRACED|%d\n", traced); + free(asset); free(tamper); free(der); free(dec); + + size_t extra_lens[] = {0, 24, 25, 26, 34, 98}; + for (size_t i = 0; i < sizeof(extra_lens) / sizeof(extra_lens[0]); ++i) { + size_t total = extra_lens[i]; + size_t nl = total / 2; + size_t sl = total - nl; + char nbuf[128], sbuf[128]; + fill_pattern(nbuf, nl, 'a'); + fill_pattern(sbuf, sl, 'A'); + size_t r = rd_sd_derive_v31_dt_pwd(nbuf, nl, sbuf, sl, out, sizeof(out)); + printf("MD5|%zu|%s|%s|%zu|%s\n", total, nbuf, sbuf, r, out); + } + + ig_poison_mark(0x123456789ABCDEF0ULL); + char pseed[64], pdt[64]; + size_t pslen = rd_sd_derive_v31_seed(pseed, sizeof(pseed)); + size_t pdtlen = rd_sd_derive_v31_dt_pwd("n0", 2, "s0", 2, pdt, sizeof(pdt)); + printf("POISON|%zu|%zu|", pslen, strlen(pseed)); + for (size_t i = 0; i < pslen; ++i) printf("%02x", (unsigned char)pseed[i]); + printf("|%zu|%s\n", pdtlen, pdt); + + size_t hash_lens[] = {0, 3, 55, 56, 63, 64, 128}; + for (size_t i = 0; i < sizeof(hash_lens) / sizeof(hash_lens[0]); ++i) { + size_t hl = hash_lens[i]; + uint8_t hbuf[128]; + for (size_t j = 0; j < hl; ++j) hbuf[j] = (uint8_t)('a' + (j % 26)); + char s256[80], md5h[64]; + size_t s256_rc = rd_sd_sha256_hex(hl ? hbuf : NULL, hl, s256, sizeof(s256)); + size_t md5_rc = rd_sd_md5_hex(hl ? hbuf : NULL, hl, md5h, sizeof(md5h)); + printf("SHA256HEX|%zu|%zu|%s\n", hl, s256_rc, s256); + printf("MD5HEX|%zu|%zu|%s\n", hl, md5_rc, md5h); + } + uint8_t chunk_buf[128]; + for (size_t j = 0; j < 128; ++j) chunk_buf[j] = (uint8_t)('a' + (j % 26)); + rd_sd_sha256_ctx sctx; + rd_sd_sha256_init(&sctx); + rd_sd_sha256_update(&sctx, chunk_buf, 10); + rd_sd_sha256_update(&sctx, chunk_buf + 10, 54); + rd_sd_sha256_update(&sctx, chunk_buf + 64, 1); + rd_sd_sha256_update(&sctx, chunk_buf + 65, 63); + uint8_t sraw[32]; + rd_sd_sha256_final(&sctx, sraw); + printf("SHA256STREAM|"); + for (size_t j = 0; j < 32; ++j) printf("%02x", sraw[j]); + printf("\n"); + + int32_t env0 = rd_sd_probe_env_artifacts(0u); + int32_t env1 = rd_sd_probe_env_artifacts(0x1u); + printf("ENVPROBE|%d|%d\n", (int)env0, (int)env1); + return 0; +} +''', + encoding='utf-8', + ) + exe = p / 'kb_boundary' + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'clang', '-isysroot', macos_sdk, + '-Os', '-Wall', '-Wextra', '-Werror', + '-I', str(DEFENDER_DIR), '-I', str(DEFENDER_DIR / 'include'), + '-I', str(SD_KEYBOX_C.parent), + str(harness), str(kb_o), str(POISON_C), + str(DEFENDER_DIR / 'resolve/IGResolve.c'), + str(DEFENDER_DIR / 'anti_hook/IGAntiHook.c'), + str(DEFENDER_DIR / 'dispatch/IGDispatch.c'), + '-framework', 'Security', '-framework', 'CoreFoundation', + '-o', str(exe), + ], check=True) + lines = subprocess.check_output([str(exe), str(p / 'asset.bin'), str(p / 'asset_tamper.bin'), str(der_path)], text=True).splitlines() + expected_seed = '7ARrksiF7AoWXXBlmxfz9suSmTka7A' + import hmac as py_hmac + expected_hmac = py_hmac.new(b'key1', b'abc', hashlib.sha256).hexdigest() + for line in lines: + parts = line.split('|') + if parts[0] == 'SEED': + self.assertEqual(parts[1], '30') + self.assertEqual(parts[2], expected_seed) + elif parts[0] == 'STEM': + self.assertEqual(parts[1:], ['15', 'rd_glyph_lut_v2']) + elif parts[0] == 'MEDIA': + self.assertEqual(parts[1:], ['22', 'startiasoftstartiasoft']) + elif parts[0] == 'DBKEY': + self.assertEqual(parts[1:], ['19', 'startiasoftvvportal']) + elif parts[0] == 'TOKEN': + self.assertEqual(parts[1:], ['18', 'readoorstartiasoft']) + elif parts[0] == 'COURSE': + self.assertEqual(parts[1:], ['11', 'startiasoft']) + elif parts[0] == 'WXSEC': + self.assertEqual(parts[1:], ['32', 'd9800fb39d16c3f1cc0ddb5618af8378']) + elif parts[0] == 'GCM': + self.assertEqual(parts[1], '0') + self.assertEqual(int(parts[2]), len(plain_pem)) + self.assertEqual(parts[2], parts[3]) + self.assertEqual(parts[4], '-2') + self.assertEqual(parts[5], '0') + elif parts[0] == 'SECKEY': + self.assertEqual(parts[1], '1') + self.assertGreater(int(parts[2]), 100) + elif parts[0] == 'HMAC': + self.assertEqual(parts[1], '0') + self.assertEqual(parts[2], expected_hmac) + elif parts[0] == 'CCCRYPT': + self.assertEqual(parts[1:], ['0', '32', '0', '16', '1']) + elif parts[0] == 'TRACED': + self.assertIn(parts[1], ('0', '1')) + elif parts[0] == 'MD5': + nonce_val, suffix_val, rc, got_hex = parts[2], parts[3], parts[4], parts[5] + self.assertEqual(rc, '32') + exp_hex = hashlib.md5( + (nonce_val + expected_seed + suffix_val).encode('utf-8') + ).hexdigest() + self.assertEqual(got_hex, exp_hex, f'Mismatch at total={parts[1]}') + elif parts[0] == 'POISON': + self.assertEqual(parts[1], '30') + self.assertEqual(parts[2], '30') + self.assertNotEqual(parts[3], expected_seed.encode('ascii').hex()) + self.assertEqual(parts[4], '32') + exp_clean = hashlib.md5(f'n0{expected_seed}s0'.encode('utf-8')).hexdigest() + self.assertNotEqual(parts[5], exp_clean) + self.assertTrue(all(c in '0123456789abcdef' for c in parts[5])) + elif parts[0] == 'SHA256HEX': + hl = int(parts[1]) + self.assertEqual(parts[2], '64') + payload = bytes((ord('a') + (j % 26)) for j in range(hl)) + self.assertEqual(parts[3], hashlib.sha256(payload).hexdigest()) + elif parts[0] == 'MD5HEX': + hl = int(parts[1]) + self.assertEqual(parts[2], '32') + payload = bytes((ord('a') + (j % 26)) for j in range(hl)) + self.assertEqual(parts[3], hashlib.md5(payload).hexdigest()) + elif parts[0] == 'SHA256STREAM': + payload = bytes((ord('a') + (j % 26)) for j in range(128)) + self.assertEqual(parts[1], hashlib.sha256(payload).hexdigest()) + elif parts[0] == 'ENVPROBE': + self.assertEqual(parts[1], '0') + self.assertNotEqual(int(parts[2]) & 1, 0) + + def test_defender_diagnostic_gating_release_vs_observation(self): + with tempfile.TemporaryDirectory(prefix='ig-diag-gate-') as td: + p = Path(td) + macos_sdk = subprocess.check_output( + ['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True + ).strip() + + def build_and_probe(tag: str, extra_flags: list[str]): + objs = [] + for idx, src_rel in enumerate(DEFENDER_SOURCES): + obj = p / f'{tag}-{idx}.o' + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'clang', '-isysroot', macos_sdk, + '-O2', '-Wall', '-Wextra', '-Werror', + *extra_flags, + '-I', str(DEFENDER_DIR / 'include'), '-I', str(DEFENDER_DIR), + '-c', str(DEFENDER_DIR / src_rel), '-o', str(obj), + ], check=True) + objs.append(obj) + exe = p / f'defender-{tag}' + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'clang', '-isysroot', macos_sdk, + '-O2', '-Wall', '-Wextra', '-Werror', + '-I', str(DEFENDER_DIR / 'include'), '-I', str(DEFENDER_DIR), + str(ROOT / 'tests/fixtures/defender_host.c'), + *(str(o) for o in objs), + '-lobjc', '-o', str(exe), + ], check=True) + out_unres = subprocess.check_output([str(exe), 'unresolved'], text=True).strip() + out_env = subprocess.check_output([str(exe), 'env'], text=True).strip() + return objs, out_unres, out_env + + rel_objs, rel_unres, rel_env = build_and_probe('release', []) + _, obs_unres, obs_env = build_and_probe('observe', ['-DIG_OBSERVATION=1']) + + self.assertEqual(rel_unres, 'status=2 reason=103 subject= evidence=') + self.assertIn('status=1 reason=202 subject= evidence=', rel_env) + self.assertNotIn('ig_fixture_a', rel_env) + + rel_cstrings = b'\n'.join( + subprocess.check_output(['strings', '-a', str(o)]) + for o in rel_objs + ).decode('utf-8', errors='replace') + for forbidden in ('DYLD_INSERT_LIBRARIES', 'P_TRACED', 'dispatch-write', '导出表无法解析'): + self.assertNotIn(forbidden, rel_cstrings) + + self.assertIn('subject=IG_fixture_symbol_that_does_not_exist_123', obs_unres) + self.assertIn('evidence=导出表无法解析该符号', obs_unres) + self.assertIn('subject=/tmp/ig_fixture_a', obs_env) + self.assertIn('DYLD_INSERT_LIBRARIES 条目=/tmp/ig_fixture_a', obs_env) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_objc_swift_string_encryption.py b/tests/test_objc_swift_string_encryption.py new file mode 100644 index 0000000..831fb65 --- /dev/null +++ b/tests/test_objc_swift_string_encryption.py @@ -0,0 +1,355 @@ +"""Unit tests for M6: ObjC CFConstantString, Swift String, multi-fn memcpy stack decrypt, and string replace rules.""" +import json +from pathlib import Path +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 + + +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 TestObjCSwiftStringEncryption(unittest.TestCase): + def test_objc_cfconstantstring_ascii_utf16_phi_and_ios_link(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-m6-objcstr-') 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': 'objc_str.m'}], + 'string_encrypt_objc_targets': [ + {'path_contains': 'objc_str.m', 'function_contains': 'obf_'} + ], + }), encoding='utf-8') + + src_m = p / 'objc_str.m' + src_m.write_text( + '''#import + +__attribute__((noinline)) +NSString *obf_ascii_tok(void) { + return @"OBJC_SECRET_ASCII_TOKEN"; +} + +__attribute__((noinline)) +NSString *obf_utf16_tok(void) { + return @"OBJC_中文密钥_UTF16"; +} + +__attribute__((noinline)) +NSString *obf_branch_tok(int flag) { + NSString *s = nil; + if (flag > 0) { + s = @"OBJC_PHI_TRUE_KEY"; + } else { + s = @"OBJC_PHI_FALSE_KEY"; + } + return [s copy]; +} + +__attribute__((noinline)) +NSString *untouched_fn(void) { + return @"OBJC_UNTOUCHED_OK"; +} + +int main(void) { + @autoreleasepool { + NSString *a = obf_ascii_tok(); + NSString *u = obf_utf16_tok(); + NSString *bt = obf_branch_tok(1); + NSString *bf = obf_branch_tok(0); + NSString *ut = untouched_fn(); + + NSDictionary *dict = @{ a: @10, u: @20, bt: @30 }; + if (![a isEqualToString:[@"OBJC_SECRET_ASCII_" stringByAppendingString:@"TOKEN"]] || a.length != 23) return 1; + const unichar encoded_u[] = { + 'O'^1,'B'^1,'J'^1,'C'^1,'_'^1,0x4E2D^1,0x6587^1,0x5BC6^1,0x94A5^1,'_'^1,'U'^1,'T'^1,'F'^1,'1'^1,'6'^1 + }; + volatile unichar mask = 1; + unichar expected_u[15]; + for (int i = 0; i < 15; ++i) expected_u[i] = encoded_u[i] ^ mask; + NSString *expU = [NSString stringWithCharacters:expected_u length:15]; + if (![u isEqualToString:expU] || u.length != 15) return 2; + if ([dict[a] intValue] != 10 || [dict[u] intValue] != 20 || [dict[bt] intValue] != 30) return 3; + if (![bt hasSuffix:@"TRUE_KEY"] || ![bf hasSuffix:@"FALSE_KEY"]) return 4; + if (![ut isEqualToString:@"OBJC_UNTOUCHED_OK"]) return 5; + } + return 0; +} +''', + encoding='utf-8', + ) + + # Host macOS compile, verify IR/binary bytes & run + bc_h = p / 'objc_h.bc' + obf_ll = p / 'objc_h.obf.ll' + obj_h = p / 'objc_h.o' + exe_h = p / 'objc_h_exe' + aud_p = p / 'objc_h.audit.json' + subprocess.run([clang, '-isysroot', sdk_host, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(src_m), '-o', str(bc_h)], check=True) + subprocess.run([ + opt_path, '-S', '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=str', '--ig-seed=m6_objc_1', + f'--ig-source-path={src_m}', f'--ig-audit-out={aud_p}', + str(bc_h), '-o', str(obf_ll), + ], check=True) + + aud = json.loads(aud_p.read_text(encoding='utf-8')) + self.assertGreaterEqual(aud.get('objc_strings_encrypted_count', 0), 4, aud) + ir_txt = obf_ll.read_text(encoding='utf-8') + self.assertIn('@__ig_dec_cf_', ir_txt) + + subprocess.run([ + clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes', + '-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_ll), '-o', str(obj_h), + ], check=True) + obj_raw = obj_h.read_bytes() + for needle in (b'OBJC_SECRET_ASCII_TOKEN', b'OBJC_PHI_TRUE_KEY', b'OBJC_PHI_FALSE_KEY'): + self.assertNotIn(needle, obj_raw) + self.assertNotIn('中文密钥'.encode('utf-16-le'), obj_raw) + self.assertIn(b'OBJC_UNTOUCHED_OK', obj_raw) + + subprocess.run([clang, '-isysroot', sdk_host, '-framework', 'Foundation', '-Wl,-dead_strip', str(obj_h), '-o', str(exe_h)], check=True) + self.assertEqual(subprocess.run([str(exe_h)]).returncode, 0) + + # iOS arm64 link verification + bc_i = p / 'objc_i.bc' + obf_i = p / 'objc_i.obf.bc' + obj_i = p / 'objc_i.o' + dylib_i = p / 'libobjc_i.dylib' + subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(src_m), '-o', str(bc_i)], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=str', '--ig-seed=m6_objc_ios', + f'--ig-source-path={src_m}', f'--ig-audit-out={p / "objc_i.audit.json"}', + str(bc_i), '-o', str(obf_i), + ], check=True) + 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_i), '-o', str(obj_i), + ], check=True) + subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-dynamiclib', str(obj_i), '-framework', 'Foundation', '-Wl,-dead_strip', '-o', str(dylib_i)], check=True) + + def test_swift_large_immortal_and_small_string_encryption(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + swiftc = detect_stock_tool('swiftc') + sdk_host = macos_sdk_path() + sdk_ios = iphoneos_sdk_path() + + with tempfile.TemporaryDirectory(prefix='ig-m6-swiftstr-') as td: + p = Path(td) + policy_path = p / 'policy.json' + policy_path.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': ['__ig_', 'llvm.', '__swift_'], + 'string_encrypt_targets': [{'path_contains': 'sw_str.swift'}], + 'string_encrypt_swift_targets': [{'path_contains': 'sw_str.swift', 'function_contains': 'secret'}], + 'opaque_const_targets': [{'path_contains': 'sw_str.swift', 'function_contains': 'secret'}], + 'opaque_const_max_per_fn': 64, + }), encoding='utf-8') + + src_sw = p / 'sw_str.swift' + src_sw.write_text( + '''import Foundation + +@inline(never) +public func secretBranch(_ flag: Bool) -> String { + let s: String + if flag { + s = "SWIFT_IMMORTAL_BRANCH_ALPHA_01" + } else { + s = "SWIFT_IMMORTAL_BRANCH_BETA_002" + } + return s +} + +@inline(never) +public func secretUtf8AndSmall(_ v: Int) -> (String, String) { + let large = "SWIFT_中文密钥_LARGE_IMMORTAL_888" + let small = "SML_KEY_1234" + return v > 0 ? (large, small) : (small, large) +} + +@main +struct Runner { + static func main() { + let a = secretBranch(true) + let b = secretBranch(false) + let (l, s) = secretUtf8AndSmall(1) + let dict = [a: 11, b: 22, l: 33, s: 44] + let ns: NSString = a as NSString + if a.count != 30 || ns.length != 30 || dict[a] != 11 || dict[b] != 22 { exit(1) } + if !a.hasSuffix("ALPHA_01") || !b.hasSuffix("BETA_002") { exit(2) } + if dict[l] != 33 || dict[s] != 44 || s.count != 12 { exit(3) } + if !l.contains("中文密钥") || !s.hasPrefix("SML_KEY_") { exit(4) } + } +} +''', + encoding='utf-8', + ) + + bc_h = p / 'sw_h.bc' + obf_ll = p / 'sw_h.obf.ll' + obj_h = p / 'sw_h.o' + exe_h = p / 'sw_h_exe' + aud_p = p / 'sw_h.audit.json' + subprocess.run([swiftc, '-sdk', sdk_host, '-O', '-g', '-lto=llvm-thin', '-parse-as-library', '-c', str(src_sw), '-o', str(bc_h)], check=True) + subprocess.run([ + opt_path, '-S', '-passes=default,ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m6_sw_1', + f'--ig-source-path={src_sw}', f'--ig-audit-out={aud_p}', + str(bc_h), '-o', str(obf_ll), + ], check=True) + + aud = json.loads(aud_p.read_text(encoding='utf-8')) + self.assertGreaterEqual(aud.get('swift_strings_encrypted_count', 0), 3, aud) + self.assertGreaterEqual(aud.get('opaque_constants_count', 0), 1, aud) + ir_txt = obf_ll.read_text(encoding='utf-8') + self.assertIn('@__ig_dec_sw_', 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_h), + ], check=True) + obj_raw = obj_h.read_bytes() + for needle in (b'SWIFT_IMMORTAL_BRANCH_ALPHA_01', b'SWIFT_IMMORTAL_BRANCH_BETA_002', 'SWIFT_中文密钥_LARGE_IMMORTAL_888'.encode('utf-8')): + self.assertNotIn(needle, obj_raw) + # Packed small-string i64 word "SML_KEY_" must be obfuscated away + small_qword = struct.pack(',ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m6_sw_ios', + f'--ig-source-path={src_sw}', f'--ig-audit-out={p / "sw_i.audit.json"}', + str(bc_i), '-o', str(obf_i), + ], check=True) + 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_i), '-o', str(obj_i), + ], check=True) + subprocess.run([swiftc, '-sdk', sdk_ios, '-target', 'arm64-apple-ios15.0', '-emit-library', str(obj_i), '-Xlinker', '-dead_strip', '-o', str(p / 'libsw_i.dylib')], check=True) + + def test_stack_decrypt_memcpy_multifn_and_string_replace(self): + opt_path = require_host_opt() + clang = detect_stock_tool('clang') + sdk_host = macos_sdk_path() + + with tempfile.TemporaryDirectory(prefix='ig-m6-stackrep-') 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_rep.c'}], + 'string_encrypt_stack_targets': [{'path_contains': 'stack_rep.c'}], + 'string_encrypt_stack_max_len': 64, + 'string_replace_rules': [{'exact': 'REPLACE_ME_SECRET_99', 'replace': 'CLEANED'}], + }), encoding='utf-8') + + src_c = p / 'stack_rep.c' + src_c.write_text( + '''#include + +__attribute__((noinline)) +int copy_shared_a(char *out) { + memcpy(out, "MULTI_FN_STACK_TOKEN", 21); + return 1; +} + +__attribute__((noinline)) +int copy_shared_b(const char *probe) { + return strcmp(probe, "MULTI_FN_STACK_TOKEN") == 0; +} + +__attribute__((noinline)) +int read_replaced(char *out) { + memcpy(out, "REPLACE_ME_SECRET_99", 21); + return 1; +} + +int main(void) { + char buf1[32] = {0}; + char buf2[32] = {0}; + copy_shared_a(buf1); + if (!copy_shared_b(buf1)) return 1; + read_replaced(buf2); + if (strcmp(buf2, "CLEANED") != 0) return 2; + return 0; +} +''', + encoding='utf-8', + ) + + bc_p = p / 'stack_rep.bc' + obf_ll = p / 'stack_rep.obf.ll' + obj_o = p / 'stack_rep.o' + exe_p = p / 'stack_rep_exe' + aud_p = p / 'stack_rep.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=m6_stackrep_1', + f'--ig-source-path={src_c}', f'--ig-audit-out={aud_p}', + str(bc_p), '-o', str(obf_ll), + ], check=True) + + aud = json.loads(aud_p.read_text(encoding='utf-8')) + self.assertEqual(aud.get('strings_replaced_count'), 1, aud) + self.assertGreaterEqual(aud.get('strings_stack_encrypted_count'), 2, aud) + self.assertEqual(aud.get('strings_encrypted_count'), aud.get('strings_stack_encrypted_count'), aud) + ir_txt = obf_ll.read_text(encoding='utf-8') + self.assertNotIn('.ig.buf.', ir_txt) + self.assertNotIn('REPLACE_ME_SECRET_99', ir_txt) + self.assertNotIn('MULTI_FN_STACK_TOKEN', ir_txt) + self.assertNotIn('CLEANED', ir_txt) + self.assertIn('store volatile i8 0,', ir_txt) + + subprocess.run([ + clang, '-isysroot', sdk_host, '-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_host, str(obj_o), '-Wl,-dead_strip', '-o', str(exe_p)], check=True) + self.assertEqual(subprocess.run([str(exe_p)]).returncode, 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_opaque_field_and_outline_pass.py b/tests/test_opaque_field_and_outline_pass.py new file mode 100644 index 0000000..64c7409 --- /dev/null +++ b/tests/test_opaque_field_and_outline_pass.py @@ -0,0 +1,248 @@ +"""Unit tests for M8: IGFunctionOutline (CodeExtractor -> ig_sub_*) and IGOpaqueFieldAccess.""" +import json +from pathlib import Path +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 + + +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 TestOpaqueFieldAndOutlinePass(unittest.TestCase): + def test_c_outline_routed_via_icall_field_masking_and_runtime_exact(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-m8-c-') as td: + p = Path(td) + policy_path = p / 'policy.json' + policy_path.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'function_outline_max_per_fn': 2, + 'function_outline_min_insts': 4, + 'function_outline_targets': [{'path_contains': 'm8_field.c', 'function_contains': 'compute_box_digest'}], + 'opaque_field_max_per_fn': 32, + 'opaque_field_targets': [{'path_contains': 'm8_field.c', 'function_contains': 'compute_box_digest'}], + 'indirect_call_targets': [{'path_contains': 'm8_field.c', 'function_contains': 'compute_box_digest'}], + 'indirect_call_same_image_prefixes': ['ig_sub_'], + 'flatten_targets': [{'path_contains': 'm8_field.c', 'function_contains': 'compute_box_digest'}], + }), encoding='utf-8') + + src_c = p / 'm8_field.c' + src_c.write_text( + '''#include +#include + +struct BoxState { + uint32_t header; + uint32_t salt; + uint64_t quota; + uint32_t flags; + uint32_t checksum; +}; + +uint32_t g_secret_multiplier = 0x9E3779B1u; +static uint64_t g_secret_offset = 0x123456789ABCDEF0ULL; + +__attribute__((noinline)) +uint64_t compute_box_digest(struct BoxState *st, uint32_t mode) { + uint64_t acc = st->quota ^ g_secret_offset; + if (mode > 0) { + uint32_t a = st->header * g_secret_multiplier; + uint32_t b = (st->salt ^ 0xA55AA55Au) + mode; + uint32_t c = (a ^ b) + st->flags; + uint64_t d = ((uint64_t)c << 17) ^ ((uint64_t)st->checksum * 33ULL); + acc += d + (uint64_t)a * 7ULL + (uint64_t)b; + } else { + acc ^= ((uint64_t)st->flags << 3) + st->salt + 19ULL; + } + if ((acc & 1ULL) != 0ULL) { + g_secret_multiplier ^= (uint32_t)(mode & 3u); + } + return acc ^ ((uint64_t)st->checksum + 0x55AAULL); +} + +int main(void) { + struct BoxState s1 = {0x11223344u, 0x55667788u, 0xCAFEBABE00112233ULL, 7u, 0x99AABBCCu}; + struct BoxState s2 = {0xDEADBEEFu, 0x10203040u, 0x0102030405060708ULL, 13u, 0x0A0B0C0Du}; + uint64_t r1 = compute_box_digest(&s1, 0); + uint64_t r2 = compute_box_digest(&s1, 5); + uint64_t r3 = compute_box_digest(&s2, 12); + printf("%016llx:%016llx:%016llx\\n", + (unsigned long long)r1, (unsigned long long)r2, (unsigned long long)r3); + return 0; +} +''', + encoding='utf-8', + ) + + # Reference un-obfuscated output + ref_exe = p / 'ref_exe' + subprocess.run([clang, '-isysroot', sdk_host, '-O2', str(src_c), '-o', str(ref_exe)], check=True) + ref_out = subprocess.check_output([str(ref_exe)], text=True).strip() + + # Obfuscated host build + bc_h = p / 'm8_h.bc' + obf_ll_h = p / 'm8_h.obf.ll' + aud_h = p / 'm8_h.audit.json' + obj_h = p / 'm8_h.o' + exe_h = p / 'm8_h_exe' + subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_h)], check=True) + subprocess.run([ + opt_path, '-S', '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m8_c_seed_1', + f'--ig-source-path={src_c}', f'--ig-audit-out={aud_h}', + str(bc_h), '-o', str(obf_ll_h), + ], check=True) + ir_text = obf_ll_h.read_text(encoding='utf-8') + self.assertIn('define internal ', ir_text) + self.assertIn('ig_sub_', ir_text) + self.assertIn('__ig_fop_', ir_text) + self.assertIn('__ig_gba_', ir_text) + + audit = json.loads(aud_h.read_text(encoding='utf-8')) + self.assertGreaterEqual(audit['functions_outlined_count'], 1) + self.assertGreaterEqual(audit['opaque_field_access_count'], 2) + self.assertGreaterEqual(audit['indirect_calls_count'], 1) + + subprocess.run([ + clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes', + '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ll_h), '-o', str(obj_h), + ], check=True) + subprocess.run([clang, '-isysroot', sdk_host, str(obj_h), '-o', str(exe_h)], check=True) + obf_out = subprocess.check_output([str(exe_h)], text=True).strip() + self.assertEqual(obf_out, ref_out) + + # iOS arm64 bitcode lowering verification + bc_ios = p / 'm8_ios.bc' + obf_ios = p / 'm8_ios.obf.bc' + obj_ios = p / 'm8_ios.o' + aud_ios = p / 'm8_ios.audit.json' + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, + '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_ios), + ], check=True) + subprocess.run([ + opt_path, '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m8_ios_seed_1', + f'--ig-source-path={src_c}', f'--ig-audit-out={aud_ios}', + str(bc_ios), '-o', str(obf_ios), + ], check=True) + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, + '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', + '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ios), '-o', str(obj_ios), + ], check=True) + magic = struct.unpack_from(' UInt64 { + var acc = rec.watermarkSeed ^ UInt64(gTrialCounter) + if page > rec.readablePages { + let a = UInt64(rec.bookId &* 131) ^ UInt64(rec.bonusPages &* 17) + let b = (acc &+ a) ^ 0x55AA33CC11223344 + let c = b &* 3 &+ UInt64(page ^ 0x77) + acc = (c ^ a) &+ UInt64(rec.readablePages) + } else { + acc = acc &+ UInt64(rec.bookId + page) + } + if (acc & 1) == 0 { + gTrialCounter += 1 + } + return acc +} +''', + encoding='utf-8', + ) + policy_path = p / 'policy.json' + policy_path.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'function_outline_max_per_fn': 2, + 'function_outline_min_insts': 4, + 'function_outline_targets': [{'path_contains': 'm8_swift.swift'}], + 'opaque_field_max_per_fn': 32, + 'opaque_field_targets': [{'path_contains': 'm8_swift.swift'}], + 'indirect_call_targets': [{'path_contains': 'm8_swift.swift'}], + 'indirect_call_same_image_prefixes': ['ig_sub_'], + 'flatten_targets': [{'path_contains': 'm8_swift.swift'}], + }), encoding='utf-8') + + bc_sw = p / 'm8_sw.bc' + obf_sw = p / 'm8_sw.obf.bc' + obj_sw = p / 'm8_sw.o' + aud_sw = p / 'm8_sw.audit.json' + subprocess.run([ + swiftc, '-target', 'arm64-apple-ios15.0', '-sdk', sdk_ios, + '-O', '-lto=llvm-thin', '-g', '-module-name', 'M8Mod', + '-parse-as-library', '-c', str(src_sw), '-o', str(bc_sw), + ], check=True) + subprocess.run([ + opt_path, '-passes=default,ig-obfuscate', + f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m8_sw_1', + f'--ig-source-path={src_sw}', '--ig-swift-module=M8Mod', + f'--ig-audit-out={aud_sw}', str(bc_sw), '-o', str(obf_sw), + ], check=True) + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, + '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', + '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_sw), '-o', str(obj_sw), + ], check=True) + + audit = json.loads(aud_sw.read_text(encoding='utf-8')) + self.assertGreaterEqual(audit['functions_outlined_count'], 1) + self.assertGreaterEqual(audit['opaque_field_access_count'], 1) + magic = struct.unpack_from(' +#include +#include +#include + +int main(int argc, char **argv) { + assert(argc == 2); + const char *syms[] = { + "fopen","fread","fwrite","fclose","dlopen","dlsym", + "write","read","open","close","exit","fork","syscall","unlink","getpid" + }; + for (int i = 0; i < 15; i++) { + void *a = dlsym(RTLD_DEFAULT, syms[i]); + void *b = ig_resolve_export_default(syms[i]); + assert(a && b && a == b); + } + assert(ig_resolve_image_export("/RDCoreIO.framework/RDCoreIO", "rd_a0") == NULL); + void *handle = dlopen(argv[1], RTLD_NOW); + assert(handle); + void *exp_check = ig_resolve_image_export("/RDCoreIO.framework/RDCoreIO", "rd_io_chk"); + assert(exp_check && exp_check == dlsym(handle, "rd_io_chk")); + assert(ig_resolve_image_export("/RDCoreIO.framework/RDCoreIO", "no_such_sym_123") == NULL); + return 0; +} +''') + guard = root / 'RDCoreIO.framework/RDCoreIO' + guard.parent.mkdir() + guard_srcs = [str(ROOT / 'defender' / s) for s in ( + 'dispatch/IGArchiveGuard.c', 'resolve/IGResolve.c', 'anti_hook/IGAntiHook.c' + )] + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=13.0', + '-O2', '-dynamiclib', '-fvisibility=hidden', + '-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'), + *guard_srcs, '-Wl,-install_name,' + DEPENDENCY, '-o', str(guard) + ], check=True, env=env, capture_output=True, text=True) + exe = root / 'trie-host' + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=13.0', + '-O2', '-Wall', '-Wextra', '-Werror', + '-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'), + str(host_c), str(ROOT / 'defender/resolve/IGResolve.c'), + str(ROOT / 'defender/anti_hook/IGAntiHook.c'), '-o', str(exe) + ], check=True, env=env, capture_output=True, text=True) + run = subprocess.run([str(exe), str(guard)], check=True, env=env, capture_output=True, text=True) + self.assertEqual(run.returncode, 0) + + forbidden = { + '_fopen', '_dlopen', '_dlsym', '_write', '_read', '_open', + '_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid', + } + ios_guard = root / 'RDCoreIO_ios' + subprocess.run([ + 'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0', + '-O2', '-dynamiclib', '-fvisibility=hidden', + '-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'), + *guard_srcs, '-Wl,-install_name,' + DEPENDENCY, '-o', str(ios_guard) + ], check=True, env=env, capture_output=True, text=True) + nm_out = subprocess.check_output(['xcrun', 'nm', '-u', str(ios_guard)], text=True) + undef = {line.split()[-1] for line in nm_out.splitlines() if line.split()} + self.assertFalse(undef & forbidden, nm_out) + + # Check IGAntiInject.o & IGAntiTamper.o as well + for rel in ('anti_frida/IGAntiInject.c', 'anti_tamper/IGAntiTamper.c'): + obj = root / (Path(rel).stem + '.o') + subprocess.run([ + 'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0', + '-O2', '-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'), + '-c', str(ROOT / 'defender' / rel), '-o', str(obj) + ], check=True, env=env, capture_output=True, text=True) + nm_obj = subprocess.check_output(['xcrun', 'nm', '-u', str(obj)], text=True) + obj_undef = {line.split()[-1] for line in nm_obj.splitlines() if line.split()} + self.assertFalse(obj_undef & forbidden, f'{rel}: {nm_obj}') + + app_defender = ROOT / 'readoor-test/readoor/3.0/Base/Security/IGDefender' + if app_defender.exists(): + for rel in ('resolve/IGResolve.c', 'anti_hook/IGAntiHook.c', + 'anti_tamper/IGAntiTamper.c', 'anti_frida/IGAntiInject.c'): + obj = root / ('app_' + Path(rel).stem + '.o') + subprocess.run([ + 'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0', + '-O2', '-I', str(app_defender), '-I', str(app_defender / 'include'), + '-c', str(app_defender / rel), '-o', str(obj) + ], check=True, env=env, capture_output=True, text=True) + nm_obj = subprocess.check_output(['xcrun', 'nm', '-u', str(obj)], text=True) + obj_undef = {line.split()[-1] for line in nm_obj.splitlines() if line.split()} + self.assertFalse(obj_undef & forbidden, f'app {rel}: {nm_obj}') + + shader = ROOT / 'readoor-test/readoor/BookView/GLPaintView/Utils/STSShaderHelper.m' + shader_obj = root / 'STSShaderHelper.o' + subprocess.run([ + 'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0', + '-O2', '-fobjc-arc', '-include', 'UIKit/UIKit.h', + '-I', str(app_defender), '-I', str(app_defender / 'include'), + '-c', str(shader), '-o', str(shader_obj) + ], check=True, env=env, capture_output=True, text=True) + nm_shader = subprocess.check_output(['xcrun', 'nm', '-u', str(shader_obj)], text=True) + shader_undef = {line.split()[-1] for line in nm_shader.splitlines() if line.split()} + self.assertIn('_IG_dispatch_exit', shader_undef) + self.assertFalse(shader_undef & forbidden, nm_shader) + + @unittest.skipUnless(platform.machine() == 'arm64', '需要 Apple Silicon') + def test_legacy_dyld_info_lazy_rebinding_and_runtime_execution(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + env = dict(os.environ) + env.pop('DYLD_INSERT_LIBRARIES', None) + guard = root / 'RDCoreIO.framework/RDCoreIO' + sdk = root / 'LegacyFixture.framework/LegacyFixture' + guard.parent.mkdir() + sdk.parent.mkdir() + guard_srcs = [str(ROOT / 'defender' / s) for s in ( + 'dispatch/IGArchiveGuard.c', 'resolve/IGResolve.c', 'anti_hook/IGAntiHook.c' + )] + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=13.0', + '-O2', '-dynamiclib', '-fvisibility=hidden', '-DIG_OBSERVATION', + '-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'), + *guard_srcs, '-Wl,-install_name,' + DEPENDENCY, '-o', str(guard) + ], check=True, env=env, capture_output=True, text=True) + + sdk_c = root / 'legacy_sdk.c' + sdk_c.write_text(''' +#include +#include +#include +#include +#include + +int legacy_exercise(const char *path) { + int fd = open(path, O_CREAT | O_TRUNC | O_RDWR, 0600); + if (fd < 0) return 1; + if (write(fd, "hello", 5) != 5) return 2; + lseek(fd, 0, SEEK_SET); + char buf[16] = {0}; + if (read(fd, buf, 5) != 5 || memcmp(buf, "hello", 5) != 0) return 3; + if (close(fd) != 0) return 4; + FILE *f = fopen(path, "rb"); + if (!f) return 5; + fclose(f); + if (unlink(path) != 0) return 6; + if (getpid() <= 0) return 7; + if (!dlsym(RTLD_DEFAULT, "getpid")) return 8; + return 0; +} +''') + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=11.0', + '-O2', '-dynamiclib', str(sdk_c), + '-Wl,-install_name,@rpath/LegacyFixture.framework/LegacyFixture', + '-Wl,-headerpad,0x4000', '-Wl,-rpath,@loader_path/..', '-o', str(sdk) + ], check=True, env=env, capture_output=True, text=True) + + raw = sdk.read_bytes() + sha = hashlib.sha256(raw).hexdigest() + mapping = detect_legacy_target_mapping(raw) + self.assertEqual(set(mapping.keys()), { + '_open', '_write', '_read', '_close', '_fopen', '_unlink', '_getpid', '_dlsym' + }) + rewritten, report = rewrite_legacy(raw, sha, mapping) + self.assertTrue(report['lazy_offsets_preserved']) + self.assertTrue(report['section_bytes_unchanged']) + sdk.write_bytes(rewritten) + subprocess.run(['codesign', '--force', '--sign', '-', str(guard)], check=True, capture_output=True) + subprocess.run(['codesign', '--force', '--sign', '-', str(sdk)], check=True, capture_output=True) + + driver_c = root / 'driver.c' + driver_c.write_text(''' +#include +#include +#include + +int main(int argc, char **argv) { + assert(argc == 3); + void *sdk = dlopen(argv[1], RTLD_NOW); + assert(sdk); + int (*check)(void) = dlsym(sdk, "rd_io_chk"); + int (*exercise)(const char *) = dlsym(sdk, "legacy_exercise"); + assert(check && exercise); + /* Before lazy symbols are triggered, lazy slots point to __stub_helper in __TEXT -> must still be CLEAR! */ + assert(check() == 0); + assert(exercise(argv[2]) == 0); + /* After lazy slots bind to RDCoreIO wrappers -> still CLEAR! */ + assert(check() == 0); + return 0; +} +''') + driver = root / 'driver' + subprocess.run([ + 'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=13.0', + '-O2', str(driver_c), '-o', str(driver) + ], check=True, env=env, capture_output=True, text=True) + res = subprocess.run([str(driver), str(sdk), str(root / 'test.bin')], + check=True, env=env, capture_output=True, text=True) + self.assertEqual(res.returncode, 0) + + def test_ttnetworkmanager_ordinal_width_jump_if_present(self): + tt = ROOT / 'readoor-test/Pods/TTNetworkManager/TTNetworkManager/TTNetworkManager.xcframework/ios-arm64/TTNetworkManager.framework/TTNetworkManager' + if not tt.exists(): + self.skipTest('需要 TTNetworkManager 副本') + raw = tt.read_bytes() + mapping = detect_legacy_target_mapping(raw) + self.assertEqual(mapping['_fopen'], '_rd_f') + self.assertEqual(mapping['_open'], '_rdo') + out, rep = rewrite_legacy(raw, hashlib.sha256(raw).hexdigest(), mapping) + self.assertEqual(rep['ordinal_width_delta'], 1) + self.assertTrue(rep['section_bytes_unchanged']) + self.assertEqual(len(out), len(raw)) + + def test_darwin_extsn_source_redirection_opt_in(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + c_src = root / 'extsn.c' + c_src.write_text('extern void *fopen_ext(const char *p, const char *m) __asm("_fopen$DARWIN_EXTSN");\n' + 'void *call_ext(const char *p, const char *m) { return fopen_ext(p, m); }\n') + obj, lib, out_a = root / 'extsn.o', root / 'extsn.a', root / 'extsn_out.a' + subprocess.run(['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', + '-miphoneos-version-min=15.0', '-O2', '-c', str(c_src), '-o', str(obj)], check=True) + subprocess.run(['xcrun', 'ar', 'rcs', str(lib), str(obj)], check=True) + sys.path.insert(0, str(ROOT / 'tools/static_sdk_redirect')) + from redirect_symbols import validate_mapping + from redirect_bitcode_members import rewrite as rewrite_ar + with self.assertRaises(ValueError): + validate_mapping({'_fopen$DARWIN_EXTSN': '_IG_dispatch_fopen'}) + rep = rewrite_ar(lib, out_a, {'_fopen$DARWIN_EXTSN': '_IG_dispatch_fopen'}, allow_darwin_extsn=True) + self.assertEqual(sum(m['references'] for m in rep['members']), 1) + nm_out = subprocess.check_output(['xcrun', 'nm', '-u', str(out_a)], text=True) + self.assertIn('_IG_dispatch_fopen', nm_out) + self.assertNotIn('_fopen$DARWIN_EXTSN', nm_out) + + + def test_xcode_archive_ld_wrapper_passthrough_and_arg_rewrite(self): + tools_xa = ROOT / 'tools/xcode_archive' + sys.path.insert(0, str(tools_xa)) + import ig_ld_wrapper + + self.assertTrue(ig_ld_wrapper.should_passthrough(['-dylib', '-o', '/tmp/Foo.app/Foo'], '/tmp/Foo.app/Foo')[0]) + self.assertTrue(ig_ld_wrapper.should_passthrough(['-o', '/tmp/Foo.xctest/Foo'], '/tmp/Foo.xctest/Foo')[0]) + self.assertFalse(ig_ld_wrapper.should_passthrough(['-arch', 'arm64', '-o', '/tmp/Foo.app/Foo'], '/tmp/Foo.app/Foo')[0]) + lto_args = ['-o', '/tmp/Foo.app/Foo', '-object_path_lto', '/tmp/Foo_lto.o'] + self.assertEqual(ig_ld_wrapper.parse_flag_value(lto_args, '-o'), '/tmp/Foo.app/Foo') + self.assertFalse(ig_ld_wrapper.should_passthrough(lto_args, ig_ld_wrapper.parse_flag_value(lto_args, '-o'))[0]) + with self.assertRaises(RuntimeError): + ig_ld_wrapper.check_coverage_absent(['/tmp/libclang_rt.profile_ios.a']) + + with tempfile.TemporaryDirectory() as tmp: + t = Path(tmp) + stage = t / 'stage' + stage.mkdir() + (stage / 'libZipZap.a').write_bytes(b'stub') + (stage / 'TencentOpenAPI').write_bytes(b'stub') + app_repo = t / 'repo' + (app_repo / 'readoor/BookShelf/Classes/Factorys/ZipZap').mkdir(parents=True) + (app_repo / 'readoor/BookShelf/Classes/Factorys/ZipZap/libZipZap.a').write_bytes(b'orig') + + args = ['-arch', 'arm64', '-F/some/fw', '-framework', 'TencentOpenAPI', '-lZipZap', '-o', str(t / 'App.app/App')] + rewritten, replaced = ig_ld_wrapper.build_rewritten_ld_args( + args, app_repo, stage, t / 'unpatched', t / 'map.txt', False, + ) + self.assertEqual(replaced, ['-framework TencentOpenAPI', '-lZipZap']) + self.assertIn('-F', rewritten) + self.assertLess(rewritten.index(str(stage)), rewritten.index('-F/some/fw')) + self.assertIn(str(stage / 'TencentOpenAPI'), rewritten) + self.assertIn(str(stage / 'libZipZap.a'), rewritten) + self.assertIn(str(stage / 'IGThreadID.o'), rewritten) + self.assertIn('-map', rewritten) + + def test_xcode_archive_frameworks_phase_idempotent(self): + tools_xa = ROOT / 'tools/xcode_archive' + sys.path.insert(0, str(tools_xa)) + import ig_guard_frameworks_phase as phase + + with tempfile.TemporaryDirectory() as tmp: + t = Path(tmp) + app_dir = t / 'Demo.app' + fw_root = app_dir / 'Frameworks' + fw_dir = fw_root / 'DemoKit.framework' + fw_dir.mkdir(parents=True) + + main_c = t / 'main.c' + main_c.write_text('int main(void) { return 0; }\n') + main_bin = app_dir / 'Demo' + subprocess.run([ + 'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0', + str(main_c), '-o', str(main_bin), + ], check=True) + + fw_c = t / 'demokit.c' + fw_c.write_text('#include \nFILE *demo_open(const char *p, const char *m) { return fopen(p, m); }\n') + fw_bin = fw_dir / 'DemoKit' + subprocess.run([ + 'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0', + '-dynamiclib', '-Wl,-install_name,@rpath/DemoKit.framework/DemoKit', + str(fw_c), '-o', str(fw_bin), + ], check=True) + (fw_dir / '_CodeSignature').mkdir() + (fw_dir / '_CodeSignature/CodeResources').write_text('stale') + + first = phase.process_framework(fw_dir) + self.assertTrue(first['modified']) + self.assertGreater(first['symbols_redirected'], 0) + self.assertFalse((fw_dir / '_CodeSignature').exists()) + + (fw_dir / '_CodeSignature').mkdir() + (fw_dir / '_CodeSignature/CodeResources').write_text('signed') + second = phase.process_framework(fw_dir) + self.assertEqual(second['mode'], 'already_guarded') + self.assertFalse(second['modified']) + self.assertEqual(second['sign_status'], 'preserved') + self.assertTrue((fw_dir / '_CodeSignature/CodeResources').is_file()) + + guard_fw = fw_root / 'RDCoreIO.framework' + dsym_root = t / 'dSYMs' + report = phase.build_archive_guard( + ROOT / 'readoor-test/readoor/3.0/Base/Security/IGDefender', + guard_fw, + dsym_folder=dsym_root, + debug_info_format='dwarf-with-dsym', + ) + dwarf = dsym_root / 'RDCoreIO.framework.dSYM/Contents/Resources/DWARF/RDCoreIO' + self.assertTrue(dwarf.is_file()) + self.assertEqual(Path(report['dsym']), dsym_root / 'RDCoreIO.framework.dSYM') + bin_uuid = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(guard_fw / 'RDCoreIO')], text=True).split()[1] + dsym_uuid = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(dwarf)], text=True).split()[1] + self.assertEqual(bin_uuid, dsym_uuid) + guard_exports = subprocess.check_output(['xcrun', 'nm', '-gU', str(guard_fw / 'RDCoreIO')], text=True) + guard_export_syms = {ln.split()[-1] for ln in guard_exports.splitlines() if ln.split()} + self.assertFalse(any(sym.startswith('_ig_') for sym in guard_export_syms), guard_exports) + self.assertIn('_rd_io_chk', guard_export_syms) + self.assertIn('_rd_a0', guard_export_syms) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_security_policy.py b/tests/test_security_policy.py index aa163fc..5c778be 100644 --- a/tests/test_security_policy.py +++ b/tests/test_security_policy.py @@ -1,11 +1,17 @@ """用真实策略源码做宿主测试,覆盖观察/强制模式和 unavailable。""" +import hashlib +import hmac from pathlib import Path +import plistlib +import re import subprocess import tempfile import unittest ROOT=Path(__file__).resolve().parents[1] POLICY=ROOT/'readoor-test/readoor/3.0/Base/Security/RDSecurityPolicy.swift' +INJECTION=ROOT/'readoor-test/readoor/3.0/Base/Security/RDInjectionDetector.swift' +SECRET=ROOT/'readoor-test/readoor/3.0/Base/Security/Generated/RDWhitelistSecret.swift' @unittest.skipUnless(POLICY.exists(),'需要 App 副本中的策略源码') class SecurityPolicyTests(unittest.TestCase): @@ -14,6 +20,7 @@ class SecurityPolicyTests(unittest.TestCase): main=Path(td)/'main.swift';exe=Path(td)/'policy' main.write_text(''' import Foundation +import CommonCrypto struct RDDefenderFinding { let status: Int32; let reason: Int32 var isDetected: Bool { status == 1 } @@ -22,6 +29,13 @@ struct RDDefenderFinding { struct RDSecurityRiskContext { let debuggerDetected: Bool; let injectedDylibDetected: Bool; let jailbreakDetected: Bool } +// 毒化写入侧 C 桥的宿主桩:记录调用次数与最后熵,供断言毒化门行为。 +var poisonMarkCount = 0 +var lastPoisonEntropy: UInt64 = 0 +func rd_epub_poison_mark(_ entropy: UInt64) { poisonMarkCount += 1; lastPoisonEntropy = entropy } +func dz(_ r: Int32) -> RDDefenderFinding { RDDefenderFinding(status:1,reason:r) } // detected 便捷构造 +func jb() -> RDSecurityRiskContext { RDSecurityRiskContext(debuggerDetected:false,injectedDylibDetected:false,jailbreakDetected:true) } + let legacy=RDSecurityRiskContext(debuggerDetected:false,injectedDylibDetected:false,jailbreakDetected:false) let policy=RDSecurityPolicy.shared let clean=policy.evaluate(findings:[],legacy:legacy) @@ -34,9 +48,241 @@ assert(tamper.action == .restrictSensitive && tamper.shouldRestrict(in:.enforce) assert(!tamper.shouldRestrict(in:.observe)) let weak=policy.evaluate(findings:[RDDefenderFinding(status:1,reason:201)],legacy:legacy) assert(weak.action == .monitor && !weak.shouldRestrict(in:.enforce)) + +// ---- 毒化门(applyPoisonDisposition):严于 terminate 门,守误报底线 ---- +// observe 模式绝不毒化(即便 STRONG inline-hook 101 命中)。 +policy.mode = .observe +assert(policy.applyPoisonDisposition(findings:[dz(101)],legacy:legacy) == false) +assert(poisonMarkCount == 0) +// enforce:STRONG 单条即触发(inline-hook 101),熵非 0。 +policy.mode = .enforce +assert(policy.applyPoisonDisposition(findings:[dz(101)],legacy:legacy) == true) +assert(poisonMarkCount == 1 && lastPoisonEntropy != 0) +// 单个 MEDIUM(符号提供方 100)不触发——需 ≥2 个不同 MEDIUM。 +assert(policy.applyPoisonDisposition(findings:[dz(100)],legacy:legacy) == false) +assert(poisonMarkCount == 1) +// 两个不同 MEDIUM(100 + Frida 线程 203)触发。 +assert(policy.applyPoisonDisposition(findings:[dz(100),dz(203)],legacy:legacy) == true) +assert(poisonMarkCount == 2) +// 弱信号(201/204)永不触发毒化。 +assert(policy.applyPoisonDisposition(findings:[dz(201),dz(204)],legacy:legacy) == false) +assert(poisonMarkCount == 2) +// 二进制篡改 500/501 本轮不参与毒化(仅观察)。 +assert(policy.applyPoisonDisposition(findings:[dz(500),dz(501)],legacy:legacy) == false) +assert(poisonMarkCount == 2) +// legacy 越狱即 STRONG,单条触发。 +assert(policy.applyPoisonDisposition(findings:[],legacy:jb()) == true) +assert(poisonMarkCount == 3) ''') p=subprocess.run(['xcrun','--sdk','macosx','swiftc','-module-cache-path',str(Path(td)/'module-cache'),str(main),str(POLICY),'-o',str(exe)],capture_output=True,text=True) self.assertEqual(p.returncode,0,p.stderr) subprocess.run([str(exe)],check=True,capture_output=True) + @unittest.skipUnless(INJECTION.exists() and SECRET.exists() and POLICY.exists(), '需要 App 注入检测源码') + def test_injection_detector_whitelist_tamper_and_dyld_insert(self): + secret_bytes = bytes(int(x, 16) for x in re.findall(r'0x([0-9a-fA-F]{2})', SECRET.read_text())) + self.assertGreaterEqual(len(secret_bytes), 16) + + with tempfile.TemporaryDirectory() as td: + t = Path(td) + entries = [ + {'name': 'RDCoreIO', 'path': 'Frameworks/RDCoreIO.framework/RDCoreIO'}, + {'name': 'Alamofire', 'path': 'Frameworks/Alamofire.framework/Alamofire'}, + {'name': 'readoor31', 'path': 'readoor31'}, + ] + msg = '\n'.join(f"{e['name']}|{e['path']}" for e in sorted(entries, key=lambda x: (x['name'], x['path']))) + digest = hmac.new(secret_bytes, msg.encode('utf-8'), hashlib.sha256).hexdigest() + + valid_plist = t / 'valid.plist' + with valid_plist.open('wb') as f: + plistlib.dump({'known_images': entries, 'digest': digest}, f) + + tampered_plist = t / 'tampered.plist' + tampered_entries = entries + [{'name': 'HelperKit', 'path': 'Frameworks/HelperKit.dylib'}] + with tampered_plist.open('wb') as f: + plistlib.dump({'known_images': tampered_entries, 'digest': digest}, f) + + main = t / 'main.swift' + main.write_text(f''' +import Foundation +import CommonCrypto + +struct RDDefenderFinding {{ + let status: Int32; let reason: Int32 + var isDetected: Bool {{ status == 1 }} + var isUnavailable: Bool {{ status == 2 }} +}} +struct RDSecurityRiskContext {{ + let debuggerDetected: Bool; let injectedDylibDetected: Bool; let jailbreakDetected: Bool +}} +enum RDOSLogManager {{ + enum LogLevel {{ case debug, info, warning, error }} + static func logWarning(_ message: String) {{}} + static func logInfo(_ message: String) {{}} + static func logDiag(_ code: String, level: LogLevel = .error) {{}} +}} +var poisonMarkCount = 0 +func rd_epub_poison_mark(_ entropy: UInt64) {{ poisonMarkCount += 1 }} +func rd_sd_cc_hmac( + _ alg: UInt32, + _ key: UnsafeRawPointer?, + _ keyLen: Int, + _ data: UnsafeRawPointer?, + _ dataLen: Int, + _ macOut: UnsafeMutableRawPointer? +) -> Int32 {{ + CCHmac(CCHmacAlgorithm(alg), key, keyLen, data, dataLen, macOut) + return 0 +}} + +let detector = RDInjectionDetector.shared +let bundle = "/tmp/FakeApp.app" +let validImages = [ + "/usr/lib/libSystem.B.dylib", + "\\(bundle)/readoor31", + "\\(bundle)/Frameworks/Alamofire.framework/Alamofire", + "\\(bundle)/Frameworks/RDCoreIO.framework/RDCoreIO" +] +let helperImages = validImages + ["\\(bundle)/Frameworks/HelperKit.dylib"] + +let missingWL = detector.loadWhitelist(from: nil) +let tamperedWL = detector.loadWhitelist(from: URL(fileURLWithPath: "{tampered_plist}")) +let validWL = detector.loadWhitelist(from: URL(fileURLWithPath: "{valid_plist}")) + +assert(!missingWL.isValid) +assert(!tamperedWL.isValid) +assert(validWL.isValid) + +#if DEBUG +let expectedInvalidDefault = false +assert(RDInjectionDetector.defaultFailClosedOnInvalidWhitelist == false) +#else +let expectedInvalidDefault = true +assert(RDInjectionDetector.defaultFailClosedOnInvalidWhitelist == true) +#endif + +// 1. 缺失 RDKnownImages.plist: Debug 放行,Release fail-closed 拦截 +assert(detector.evaluate( + whitelistResult: missingWL, dyldInsertEnv: nil, loadedImagePaths: validImages, + bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist +) == expectedInvalidDefault) + +// 2. 篡改 RDKnownImages.plist(HMAC 不匹配): Debug 放行,Release fail-closed 拦截 +assert(detector.evaluate( + whitelistResult: tamperedWL, dyldInsertEnv: nil, loadedImagePaths: validImages, + bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist +) == expectedInvalidDefault) + +// 无论 Debug/Release,显式 failClosed=true(hasSecurityRisk 同语义)在缺失/篡改时均告警 +assert(detector.evaluate(whitelistResult: missingWL, dyldInsertEnv: nil, loadedImagePaths: validImages, bundlePath: bundle, failClosedOnInvalidWhitelist: true)) + +// 3. 合法白名单 + 匹配镜像: Debug/Release 均通过 +assert(!detector.evaluate( + whitelistResult: validWL, dyldInsertEnv: nil, loadedImagePaths: validImages, + bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist +)) + +// 4. 合法白名单 + 未授权包内库 HelperKit.dylib: Debug/Release 均拦截 +assert(detector.evaluate( + whitelistResult: validWL, dyldInsertEnv: nil, loadedImagePaths: helperImages, + bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist +)) + +// 5. 白名单失效下,DYLD_INSERT_LIBRARIES(单条或冒号拼接)仍先于白名单校验被拦截 +assert(detector.evaluate( + whitelistResult: missingWL, dyldInsertEnv: "/tmp/evil.dylib", loadedImagePaths: validImages, + bundlePath: bundle, failClosedOnInvalidWhitelist: false +)) +assert(detector.evaluate( + whitelistResult: tamperedWL, dyldInsertEnv: "/usr/lib/libSystem.B.dylib:/tmp/evil.dylib", loadedImagePaths: validImages, + bundlePath: bundle, failClosedOnInvalidWhitelist: false +)) + +// 6. 合法系统与 Cryptex 路径 DYLD_INSERT_LIBRARIES 放行 +assert(!detector.evaluate( + whitelistResult: validWL, + dyldInsertEnv: "/usr/lib/libViewDebuggerSupport.dylib:/private/preboot/Cryptexes/OS/usr/lib/libfoo.dylib", + loadedImagePaths: validImages, + bundlePath: bundle, + failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist +)) + +// 7. Release fail-closed 结果并入 RDSecurityPolicy:触发 reason=900 与密钥毒化 +if RDInjectionDetector.defaultFailClosedOnInvalidWhitelist {{ + let detected = detector.evaluate( + whitelistResult: missingWL, dyldInsertEnv: nil, loadedImagePaths: validImages, + bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist + ) + let ctx = RDSecurityRiskContext(debuggerDetected: false, injectedDylibDetected: detected, jailbreakDetected: false) + let policy = RDSecurityPolicy.shared + policy.mode = .enforce + let decision = policy.evaluate(findings: [], legacy: ctx) + assert(decision.action == .restrictSensitive && decision.strongReasons == [900]) + assert(policy.applyPoisonDisposition(findings: [], legacy: ctx)) + assert(poisonMarkCount == 1) +}} +''') + + mcache = t / 'module-cache' + for label, extra_flags in [('debug', ['-DDEBUG']), ('release', [])]: + exe = t / f'inject_{label}' + cmd = [ + 'xcrun', '--sdk', 'macosx', 'swiftc', + *extra_flags, + '-module-cache-path', str(mcache), + str(main), str(INJECTION), str(SECRET), str(POLICY), + '-o', str(exe), + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + self.assertEqual(proc.returncode, 0, f'{label} compile failed:\n{proc.stderr}') + subprocess.run([str(exe)], check=True, capture_output=True) + + def test_appstore_distribution_anti_tamper_enforcement(self): + with tempfile.TemporaryDirectory() as td: + t = Path(td) + main = t / 'main.swift' + exe = t / 'appstore_policy' + main.write_text(''' +import Foundation +import CommonCrypto +struct RDDefenderFinding { + let status: Int32; let reason: Int32 + var isDetected: Bool { status == 1 } + var isUnavailable: Bool { status == 2 } +} +struct RDSecurityRiskContext { + let debuggerDetected: Bool; let injectedDylibDetected: Bool; let jailbreakDetected: Bool +} +var poisonMarkCount = 0 +var lastPoisonEntropy: UInt64 = 0 +func rd_epub_poison_mark(_ entropy: UInt64) { poisonMarkCount += 1; lastPoisonEntropy = entropy } +func dz(_ r: Int32) -> RDDefenderFinding { RDDefenderFinding(status: 1, reason: r) } + +let legacy = RDSecurityRiskContext(debuggerDetected: false, injectedDylibDetected: false, jailbreakDetected: false) +let policy = RDSecurityPolicy.shared +// Release 默认已收敛为 .enforce(不直接暴露 .terminateConfirmed 秒退与明文 jsonl) +assert(policy.mode == .enforce) + +let dec = policy.evaluate(findings: [dz(500)], legacy: legacy) +assert(dec.action == .restrictSensitive) +assert(dec.strongReasons == [500]) +assert(dec.terminationReasons == [500]) +assert(policy.applyPoisonDisposition(findings: [dz(500)], legacy: legacy) == true) +assert(poisonMarkCount == 1 && lastPoisonEntropy != 0) + +let signDec = policy.evaluate(findings: [dz(501)], legacy: legacy) +assert(signDec.strongReasons == [501]) +assert(policy.applyPoisonDisposition(findings: [dz(501)], legacy: legacy) == true) +assert(poisonMarkCount == 2) +''') + cmd = [ + 'xcrun', '--sdk', 'macosx', 'swiftc', + '-DIG_APPSTORE_DISTRIBUTION', + '-module-cache-path', str(t / 'module-cache'), + str(main), str(POLICY), '-o', str(exe), + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + self.assertEqual(proc.returncode, 0, proc.stderr) + subprocess.run([str(exe)], check=True, capture_output=True) + if __name__=='__main__':unittest.main() diff --git a/tests/test_static_framework_obf.py b/tests/test_static_framework_obf.py new file mode 100644 index 0000000..afdaa30 --- /dev/null +++ b/tests/test_static_framework_obf.py @@ -0,0 +1,205 @@ +"""Unit tests for M7: static framework ThinLTO bitcode extraction, obfuscation & repacking.""" +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf' +TOOLS_XCODE_ARCHIVE = ROOT / 'tools' / 'xcode_archive' +sys.path.insert(0, str(TOOLS_LLVM_OBF)) +sys.path.insert(0, str(TOOLS_XCODE_ARCHIVE)) + +from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402 +import ig_ld_wrapper # 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 iphoneos_sdk_path() -> str: + return subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip() + + +class TestStaticFrameworkObfuscation(unittest.TestCase): + def test_convert_static_framework_bitcode_repacks_arm64_macho_and_audits(self): + require_host_opt() + swiftc = detect_stock_tool('swiftc') + clang = detect_stock_tool('clang') + sdk_ios = iphoneos_sdk_path() + + with tempfile.TemporaryDirectory(prefix='ig-m7-staticfw-') as td: + root = Path(td) + repo = root / 'repo' + trial_dir = repo / 'Vendor/RDPDFReaderView/Sources' + trial_dir.mkdir(parents=True) + trial_swift = trial_dir / 'RDPDFReaderTrial.swift' + trial_swift.write_text( + '''import Foundation + +public struct RDPDFReaderTrialPolicy { + public var readablePageCount: Int + public init(readablePageCount: Int) { + self.readablePageCount = readablePageCount + } +} + +@inline(never) +public func evaluateTrialQuota(_ page: Int, _ policy: RDPDFReaderTrialPolicy) -> Int { + let secretTag = "RD_PDF_TRIAL_WALL_SECRET_GATE_12345" + var res = page ^ 0x1357 + if policy.readablePageCount > 0 && page >= policy.readablePageCount { + res = (res + secretTag.count) & 0x7fff + } else if page < 0 { + res = 0x2468 + } + if res > 100 { + return res ^ 0x55 + } + return res + 17 +} +''', + encoding='utf-8', + ) + + dummy_c = root / 'RDPDFReaderView-dummy.c' + dummy_c.write_text('int rd_pdf_dummy_marker(void) { return 42; }\n', encoding='utf-8') + + obj_dir = root / 'objs' + obj_dir.mkdir() + bc_o = obj_dir / 'RDPDFReaderTrial.o' + dummy_o = obj_dir / 'RDPDFReaderView-dummy.o' + + subprocess.run([ + swiftc, + '-target', 'arm64-apple-ios15.0', + '-sdk', sdk_ios, + '-O', '-lto=llvm-thin', + '-g', '-file-prefix-map', f'{repo}=.', + '-module-name', 'RDPDFReaderView', + '-parse-as-library', '-c', + str(trial_swift), '-o', str(bc_o), + ], check=True) + subprocess.run([ + clang, + '-target', 'arm64-apple-ios15.0', + '-isysroot', sdk_ios, + '-O2', '-c', str(dummy_c), '-o', str(dummy_o), + ], check=True) + + self.assertTrue(ig_ld_wrapper.is_bitcode_wrapper(bc_o), 'Expected Swift -lto=llvm-thin to emit bitcode wrapper') + + fw_dir = root / 'frameworks/RDPDFReaderView.framework' + fw_dir.mkdir(parents=True) + arch_bin = fw_dir / 'RDPDFReaderView' + subprocess.run(['xcrun', 'libtool', '-static', '-o', str(arch_bin), str(bc_o), str(dummy_o)], check=True) + + policy_path = root / 'policy.json' + policy = { + 'exempt_path_substrings': ['/Pods/'], + 'exempt_function_prefixes': [], + 'obfuscate_static_frameworks': ['RDPDFReaderView'], + 'string_encrypt_targets': [{'id': 'pdf_str', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}], + 'string_encrypt_swift_targets': [{'id': 'pdf_swstr', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}], + 'flatten_targets': [{'id': 'pdf_fla', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}], + 'opaque_const_targets': [{'id': 'pdf_const', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}], + 'arithmetic_targets': [{'id': 'pdf_arith', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}], + 'indirect_branch_targets': [{'id': 'pdf_ibr', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}], + 'required_targets': [ + { + 'id': 'vendor_pdf_trial', + 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift', + 'min_flattened': 1, + 'min_strings_encrypted': 0, + } + ], + } + policy_path.write_text(json.dumps(policy), encoding='utf-8') + + out_bin = root / 'build/readoor31OtherPay.app/readoor31OtherPay' + out_bin.parent.mkdir(parents=True) + linkmap = root / 'build/LinkMap.txt' + ld_args = [ + '-arch', 'arm64', + '-platform_version', 'ios', '15.0', '18.0', + '-syslibroot', sdk_ios, + '-F', str(fw_dir.parent), + '-framework', 'RDPDFReaderView', + '-flto=thin', + '-object_path_lto', str(root / 'build/lto.o'), + '-o', str(out_bin), + ] + ctl = { + 'mode': 'full', + 'filter': 'all', + 'route2': 'on', + 'all_off': '0', + 'seed': 'm7_fw_seed_1', + 'stamp': 'test_stamp', + 'policy_profile': 'default', + } + conv_report = { + 'expected_swift_count': 0, + 'converted_swift_count': 0, + 'skipped_swift_count': 0, + 'skipped_swift': [], + 'swift_audits': [], + 'objc_audits': [], + 'replaced_entries': [], + 'static_frameworks_obfuscated': [], + } + + new_args, updated_report = ig_ld_wrapper.convert_static_framework_bitcode( + ld_args, out_bin, str(linkmap), ctl, str(policy_path), policy, repo, conv_report + ) + if not ig_ld_wrapper.args_contain_remaining_bitcode(new_args, updated_report['replaced_entries']): + new_args = ig_ld_wrapper.strip_lto_link_flags(new_args) + + self.assertNotIn('-framework', new_args) + self.assertNotIn('-flto=thin', new_args) + self.assertNotIn('-object_path_lto', new_args) + + fw_recs = updated_report['static_frameworks_obfuscated'] + self.assertEqual(len(fw_recs), 1) + self.assertEqual(fw_recs[0]['framework'], 'RDPDFReaderView') + self.assertEqual(fw_recs[0]['bitcode_members'], 1) + self.assertEqual(fw_recs[0]['passthrough_members'], 1) + + obf_archive = Path(fw_recs[0]['output_archive']) + self.assertTrue(obf_archive.is_file()) + self.assertIn(str(obf_archive), new_args) + + # Inspect repacked archive members: zero bitcode remains, all Mach-O arm64 objects. + repacked_members = ig_ld_wrapper._parse_bsd_ar_members(obf_archive) + self.assertIsNotNone(repacked_members) + self.assertEqual(len(repacked_members), 2) + for m_name, payload in repacked_members: + self.assertNotIn(payload[:4], ig_ld_wrapper.BITCODE_MAGICS, f'Member {m_name} still bitcode!') + magic = struct.unpack_from('= 30 条,高敏 OC 扩展进入压平与串加密策略,核心 OC 类锁定 L1。""" + bridge_src = (ROOT / 'readoor-test/readoor/3.0/Base/Security/RDEpubCryptBridge.m').read_text(encoding='utf-8') + watch_count = len(re.findall(r'sel_getName\(@selector\(', bridge_src)) + self.assertGreaterEqual(watch_count, 30, f'Expected >= 30 baseline watches, got {watch_count}') + + policy = json.loads((ROOT / 'config/ig_llvm_policy.json').read_text(encoding='utf-8')) + expected_paths = [ + 'BookShelf/Classes/Features/IAP/Extension/', + 'BookShelf/Classes/Features/Login/Extension/', + 'BookShelf/Classes/Extension/ControllersExtension/STSBaseViewController+STSReadOrPayExtension.m', + 'BookView/EPUB/Core/Classes/STSBaseViewController+STSEpubViewLoginOrPayExtension.m', + 'BookView/PDF/Core/Classes/Stage/STSBaseViewController+STSPDFViewLoginOrPayExtension.m', + ] + str_paths = {r.get('path_contains') for r in policy.get('string_encrypt_targets', [])} + fla_paths = {r.get('path_contains') for r in policy.get('flatten_targets', [])} + for p in expected_paths: + self.assertIn(p, str_paths, f'Missing from string_encrypt_targets: {p}') + self.assertIn(p, fla_paths, f'Missing from flatten_targets: {p}') + + build_py = (ROOT / 'tools/llvm_obf/build_obfuscated_ipa.py').read_text(encoding='utf-8') + for cls_name in ( + 'STSIAPHandler', 'STSIAPVerifyHandler', 'STSIAPKeyChainHandler', + 'STSIAPVerifyTask', 'STSJailbreakDetectTool', + ): + self.assertIn(f"'{cls_name}'", build_py, f'Missing from unobfuscated_watch_classes: {cls_name}') + if __name__ == '__main__': unittest.main() diff --git a/tests/test_toolchain_self_heal.py b/tests/test_toolchain_self_heal.py new file mode 100644 index 0000000..75a404e --- /dev/null +++ b/tests/test_toolchain_self_heal.py @@ -0,0 +1,286 @@ +import hashlib +import json +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf' +sys.path.insert(0, str(TOOLS_LLVM_OBF)) + +import build_igopt_local # noqa: E402 +import ig_toolchain_resolver as resolver # noqa: E402 + + +def _make_fake_opt(path: Path, body: bytes = b'#!/bin/sh\nexit 0\n') -> str: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(body) + path.chmod(0o755) + return hashlib.sha256(body).hexdigest() + + +class TestToolchainSelfHeal(unittest.TestCase): + def test_parse_swift_version_output_and_real_detect(self): + sample = 'Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1)\nTarget: arm64-apple-macosx26.0\n' + parsed = resolver.parse_swift_version_output(sample) + self.assertEqual(parsed['swift_version'], '6.4') + self.assertEqual(parsed['swiftlang_version'], '6.4.0') + self.assertEqual(parsed['swift_major_minor'], '6.4') + self.assertEqual(parsed['clang_version'], '2100.3.34.1') + + live = resolver.detect_swift_info() + self.assertTrue(live['swift_version']) + self.assertTrue(live['swift_major_minor']) + + def test_compute_passes_hash_deterministic_and_sensitive(self): + with tempfile.TemporaryDirectory() as td: + pdir = Path(td) / 'llvm_passes' + self.assertEqual(resolver.compute_passes_hash(pdir), 'legacy') + (pdir / 'src').mkdir(parents=True) + (pdir / 'CMakeLists.txt').write_text('project(IG)\n', encoding='utf-8') + cpp = pdir / 'src' / 'IGPass.cpp' + cpp.write_text('int f() { return 1; }\n', encoding='utf-8') + h1 = resolver.compute_passes_hash(pdir) + h2 = resolver.compute_passes_hash(pdir) + self.assertEqual(h1, h2) + self.assertEqual(len(h1), 64) + + cpp.write_text('int f() { return 2; }\n', encoding='utf-8') + h3 = resolver.compute_passes_hash(pdir) + self.assertNotEqual(h1, h3) + + def test_resolve_llvm_branch_for_swift_override_and_ls_remote(self): + with tempfile.TemporaryDirectory() as td: + map_p = Path(td) / 'map.json' + map_p.write_text(json.dumps({ + 'by_xcode_build': {'99Z999': 'custom/xcode-branch'}, + 'by_swiftlang': {'6.5.1': 'custom/swiftlang-branch'}, + 'by_swift_major_minor': {'6.5': 'custom/mm-branch'}, + }), encoding='utf-8') + + self.assertEqual( + resolver.resolve_llvm_branch_for_swift( + {'swiftlang_version': '6.5.1', 'swift_major_minor': '6.5'}, + {'xcode_build': '99Z999'}, + map_path=map_p, + ), + 'custom/xcode-branch', + ) + self.assertEqual( + resolver.resolve_llvm_branch_for_swift( + {'swiftlang_version': '6.5.1', 'swift_major_minor': '6.5'}, + {'xcode_build': '28A100'}, + map_path=map_p, + ), + 'custom/swiftlang-branch', + ) + + ls_out = '\n'.join([ + 'aaa\trefs/heads/swift/release/6.4.0', + 'bbb\trefs/heads/swift/release/6.5', + 'ccc\trefs/heads/swift/release/6.6.1', + 'ddd\trefs/heads/swift/release/6.6.2', + 'eee\trefs/tags/swift-6.7.0-RELEASE', + 'fff\trefs/tags/swift-6.7.0-RELEASE^{}', + ]) + empty_map = Path(td) / 'missing_map.json' + with patch('ig_toolchain_resolver.subprocess.check_output', return_value=ls_out): + self.assertEqual( + resolver.resolve_llvm_branch_for_swift( + {'swiftlang_version': '6.5.3', 'swift_major_minor': '6.5'}, + {'xcode_build': '28A200'}, + map_path=empty_map, + ), + 'swift/release/6.5', + ) + self.assertEqual( + resolver.resolve_llvm_branch_for_swift( + {'swiftlang_version': '6.6.9', 'swift_major_minor': '6.6'}, + {'xcode_build': '28B100'}, + map_path=empty_map, + ), + 'swift/release/6.6.2', + ) + self.assertEqual( + resolver.resolve_llvm_branch_for_swift( + {'swiftlang_version': '6.7.0', 'swift_major_minor': '6.7'}, + {'xcode_build': '29A100'}, + map_path=empty_map, + ), + 'swift-6.7.0-RELEASE', + ) + + def test_ensure_opt_l1_hit_l2_reuse_pruning_and_circuit_breaker(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + cache_dir = root / 'toolchains' + pdir = root / 'llvm_passes' + (pdir / 'src').mkdir(parents=True) + (pdir / 'CMakeLists.txt').write_text('project(IG)\n', encoding='utf-8') + (pdir / 'src' / 'IGPass.cpp').write_text('int pass = 1;\n', encoding='utf-8') + passes_hash = resolver.compute_passes_hash(pdir) + h8 = passes_hash[:8] + + # Seed 3 older versioned toolchains in cache_dir (one matching swift 6.4) + older_builds = ['26A100', '27A100', '27A9000'] + for idx, bld in enumerate(older_builds): + d = cache_dir / f'{bld}-arm64-{h8}' + sha = _make_fake_opt(d / 'bin' / 'opt', f'#!/bin/sh\necho opt-{bld}\n'.encode('utf-8')) + (d / 'meta.json').write_text(json.dumps({ + 'schema_version': 1, + 'xcode_build': bld, + 'swift_major_minor': '6.3' if idx == 0 else '6.4', + 'arch': 'arm64', + 'passes_hash': passes_hash, + 'opt_sha256': sha, + }), encoding='utf-8') + t_val = 1_700_000_000 + idx * 100 + os.utime(d / 'meta.json', (t_val, t_val)) + + xc_new = {'xcode_version': '27.2', 'xcode_build': '27B100', 'developer_dir': '/Dev'} + sw_new = {'swift_version': '6.4', 'swiftlang_version': '6.4.0', 'swift_major_minor': '6.4', 'clang_version': '2100', 'raw': 'Apple Swift version 6.4'} + + # 1) L2 reuse succeeds for 27B100, promotes newest compatible (27A9000), prunes oldest down to keep_versions=3 + with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_new), \ + patch('ig_toolchain_resolver.detect_swift_info', return_value=sw_new), \ + patch('ig_toolchain_resolver.verify_portability') as mock_port, \ + patch('ig_toolchain_resolver.smoke_test_opt', return_value={'c_audit': {}, 'swift_audit': {}}) as mock_smoke: + res_reused = resolver.ensure_opt( + cache_root=cache_dir, + passes_dir=pdir, + keep_versions=3, + manifest_path=root / 'no_manifest.json', + default_cache_root=cache_dir, + ) + self.assertEqual(res_reused['source_mode'], 'reused') + self.assertTrue(res_reused['updated']) + self.assertIn('27A9000', res_reused['reused_from']) + self.assertEqual(mock_port.call_count, 1) + self.assertEqual(mock_smoke.call_count, 1) + self.assertFalse((cache_dir / f'26A100-arm64-{h8}').exists()) + self.assertTrue((cache_dir / f'27B100-arm64-{h8}' / 'meta.json').is_file()) + + # 2) L1 exact hit returns fast without calling smoke test + with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_new), \ + patch('ig_toolchain_resolver.detect_swift_info', return_value=sw_new), \ + patch('ig_toolchain_resolver.smoke_test_opt') as should_not_smoke: + res_cached = resolver.ensure_opt( + cache_root=cache_dir, + passes_dir=pdir, + manifest_path=root / 'no_manifest.json', + default_cache_root=cache_dir, + ) + self.assertEqual(res_cached['source_mode'], 'cached') + self.assertFalse(res_cached['updated']) + self.assertEqual(should_not_smoke.call_count, 0) + + # Fast read-only resolve_opt hits the newly promoted dir + with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_new): + fast_res = resolver.resolve_opt( + manifest_path=root / 'no_manifest.json', + cache_root=cache_dir, + passes_dir=pdir, + require_obf=True, + ) + self.assertEqual(fast_res['source_mode'], 'cached') + self.assertEqual(fast_res['opt_path'], res_reused['opt_path']) + + # Editing llvm_passes source invalidates resolve_opt lookup + (pdir / 'src' / 'IGPass.cpp').write_text('int pass = 2;\n', encoding='utf-8') + with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_new): + miss_res = resolver.resolve_opt( + manifest_path=root / 'no_manifest.json', + cache_root=cache_dir, + passes_dir=pdir, + require_obf=False, + ) + self.assertIsNone(miss_res['opt_path']) + + # 3) L4 failure triggers circuit breaker; repeated call fails fast; force_rebuild clears breaker + xc_major = {'xcode_version': '28.0', 'xcode_build': '28A50', 'developer_dir': '/Dev28'} + sw_major = {'swift_version': '6.5', 'swiftlang_version': '6.5.0', 'swift_major_minor': '6.5', 'clang_version': '2200', 'raw': 'Apple Swift version 6.5'} + pdir2 = root / 'llvm_passes_v2' + pdir2.mkdir() + (pdir2 / 'CMakeLists.txt').write_text('project(IG2)\n', encoding='utf-8') + + with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_major), \ + patch('ig_toolchain_resolver.detect_swift_info', return_value=sw_major), \ + patch('ig_toolchain_resolver.find_cli_tool', return_value='/usr/bin/cmake'), \ + patch('ig_toolchain_resolver.resolve_llvm_branch_for_swift', return_value='swift/release/6.5'), \ + patch.object(build_igopt_local, 'build_opt', side_effect=RuntimeError('cmake boom')) as mock_build: + with self.assertRaisesRegex(RuntimeError, 'cmake boom'): + resolver.ensure_opt( + cache_root=cache_dir, + passes_dir=pdir2, + manifest_path=root / 'no_manifest.json', + default_cache_root=cache_dir, + ) + self.assertEqual(mock_build.call_count, 1) + + # Immediate retry blocked by circuit breaker without calling build_opt + with self.assertRaisesRegex(RuntimeError, 'Circuit breaker active'): + resolver.ensure_opt( + cache_root=cache_dir, + passes_dir=pdir2, + manifest_path=root / 'no_manifest.json', + default_cache_root=cache_dir, + ) + self.assertEqual(mock_build.call_count, 1) + + # Force rebuild clears breaker and succeeds + h8_v2 = resolver.compute_passes_hash(pdir2)[:8] + built_target = cache_dir / f'28A50-arm64-{h8_v2}' + built_sha = _make_fake_opt(built_target / 'bin' / 'opt', b'#!/bin/sh\necho built\n') + built_meta = { + 'schema_version': 1, + 'xcode_build': '28A50', + 'swift_major_minor': '6.5', + 'arch': 'arm64', + 'passes_hash': resolver.compute_passes_hash(pdir2), + 'opt_sha256': built_sha, + 'source_mode': 'built', + } + (built_target / 'meta.json').write_text(json.dumps(built_meta), encoding='utf-8') + + with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_major), \ + patch('ig_toolchain_resolver.detect_swift_info', return_value=sw_major), \ + patch('ig_toolchain_resolver.find_cli_tool', return_value='/usr/bin/cmake'), \ + patch('ig_toolchain_resolver.resolve_llvm_branch_for_swift', return_value='swift/release/6.5'), \ + patch.object(build_igopt_local, 'build_opt', return_value={'opt_sha256': built_sha, 'meta': built_meta}) as mock_build_ok: + res_built = resolver.ensure_opt( + cache_root=cache_dir, + passes_dir=pdir2, + force_rebuild=True, + manifest_path=root / 'no_manifest.json', + default_cache_root=cache_dir, + ) + self.assertEqual(mock_build_ok.call_count, 1) + self.assertEqual(res_built['source_mode'], 'built') + self.assertTrue(res_built['updated']) + + def test_resolve_effective_policy_injects_dynamic_home_scrub_without_hardcoding(self): + with tempfile.TemporaryDirectory() as td: + p = Path(td) + repo = p / 'app_repo' + repo.mkdir() + (repo / 'readoor.xcodeproj').mkdir() + cache_dir = p / 'cache' + policy_p = p / 'policy.json' + policy_p.write_text(json.dumps({ + 'scrub_path_substrings': ['/tmp/ig-ipa-work/', '/src/readoor/'], + 'flatten_targets': [], + }), encoding='utf-8') + + eff_p, eff = resolver.resolve_effective_policy(str(policy_p), repo, cache_dir) + self.assertNotEqual(eff_p, str(policy_p)) + self.assertTrue(Path(eff_p).is_file()) + self.assertFalse(eff['l1_translation_active']) + self.assertIn(f'{Path.home()}/', eff['scrub_path_substrings']) + self.assertIn(f'{repo.resolve()}/', eff['scrub_path_substrings']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/business_regression/prepare_observation_app.py b/tools/business_regression/prepare_observation_app.py index bf29e09..a869a4f 100644 --- a/tools/business_regression/prepare_observation_app.py +++ b/tools/business_regression/prepare_observation_app.py @@ -21,24 +21,25 @@ ARCHIVE_SHA='485c0c95b4701a4e51625e16b6c2a9781c1a8a6f6c9b9cbe392709ecfc95191a' def prepare_archive(guarded,output,command,baseline): sdk=guarded/'Frameworks/SSZipArchive.framework/SSZipArchive' if sha(sdk)!=ARCHIVE_SHA:raise ValueError('SSZipArchive 版本变化,须重新审核绑定规则') - folder=guarded/'Frameworks/IGArchiveGuard.framework' + folder=guarded/'Frameworks/RDCoreIO.framework' if folder.exists():raise ValueError('保护 Framework 已存在') folder.mkdir() (folder/'Info.plist').write_bytes(plistlib.dumps(dict( - CFBundleExecutable='IGArchiveGuard',CFBundleIdentifier='cn.touchv.iosguard.archiveguard', - CFBundleName='IGArchiveGuard',CFBundlePackageType='FMWK',CFBundleVersion='1', + CFBundleExecutable='RDCoreIO',CFBundleIdentifier='cn.touchv.readoor.coreio', + CFBundleName='RDCoreIO',CFBundlePackageType='FMWK',CFBundleVersion='1', CFBundleShortVersionString='1.0',MinimumOSVersion='15.0',CFBundleSupportedPlatforms=['iPhoneOS']))) sources=['dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c'] command(['xcrun','--sdk','iphoneos','clang','-arch','arm64','-miphoneos-version-min=15.0', '-O2','-Wall','-Wextra','-Werror','-fvisibility=hidden','-DIG_OBSERVATION', + '-DIG_ARCHIVE_INTERNAL_RESOLVE=1', '-I',ROOT/'defender','-I',ROOT/'defender/include','-dynamiclib', *(ROOT/'defender'/p for p in sources), - '-Wl,-install_name,@rpath/IGArchiveGuard.framework/IGArchiveGuard', + '-Wl,-install_name,@rpath/RDCoreIO.framework/RDCoreIO', '-Wl,-map,'+str(output/'archive-guard-link.map'), *(f'-Wl,-exported_symbol,_{n}' for n in - ['ig_a0','ig_a1','ig_a2','ig_a3','ig_archive_check','ig_archive_counter']), - '-o',folder/'IGArchiveGuard']) - symbols=command(['xcrun','nm','-g',folder/'IGArchiveGuard']) + ['rd_a0','rd_a1','rd_a2','rd_a3','rd_io_chk','ig_archive_counter']), + '-o',folder/'RDCoreIO']) + symbols=command(['xcrun','nm','-g',folder/'RDCoreIO']) if 'ig_archive_test_' in symbols:raise ValueError('业务保护 Framework 含测试接口') # 基线仍执行完整格式审核,但不保留 SDK 改写;两包主程序完全相同。 temp=output/'ssziparchive-rewritten' diff --git a/tools/crash_restore/restore_crash_report.py b/tools/crash_restore/restore_crash_report.py new file mode 100755 index 0000000..18fe87f --- /dev/null +++ b/tools/crash_restore/restore_crash_report.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +"""Symbolicate modern JSON (.ips) and classic text (.crash) Apple crash reports with UUID enforcement.""" +import argparse +import json +from pathlib import Path +import re +import subprocess +import sys + +FRAME_LINE_RE = re.compile( + r'^(\d+)\s+(\S+)\s+(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)(?:\s*\+\s*(\d+))?(.*)$' +) +BIN_IMAGE_RE = re.compile( + r'^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+(\S+)\s+(\S+)\s+<([0-9a-fA-F-]+)>\s+(.+)$' +) + + +def norm_uuid(u): + return str(u).replace('-', '').upper() + + +def index_dsyms(dsym_root): + """Map normalized UUID -> {'arch': ..., 'dwarf': Path, 'dsym': Path}.""" + mapping = {} + root = Path(dsym_root) + candidates = [] + if root.is_dir() and root.suffix == '.dSYM': + candidates.append(root) + elif root.is_dir(): + candidates.extend(sorted(root.glob('*.dSYM'))) + else: + raise FileNotFoundError(f'dSYM path not found: {root}') + + for dsym in candidates: + dwarf_dir = dsym / 'Contents' / 'Resources' / 'DWARF' + if not dwarf_dir.is_dir(): + continue + out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(dsym)], text=True) + for line in out.splitlines(): + m = re.match(r'^UUID:\s*([0-9A-Fa-f-]+)\s+\(([^)]+)\)\s+(.+)$', line.strip()) + if m: + uid = norm_uuid(m.group(1)) + arch = m.group(2) + dwarf_path = Path(m.group(3).strip()) + mapping[uid] = {'arch': arch, 'dwarf': dwarf_path, 'dsym': dsym} + return mapping + + +def _unwrap_v2_mappings(raw) -> dict: + if not isinstance(raw, dict): + return {} + if isinstance(raw.get('mappings'), dict) and ( + 'schema_version' in raw or raw.get('kind') in ('symbol_map', 'method_map') + ): + return raw['mappings'] + return raw + + +def load_reverse_maps(symbol_map_path=None, method_map_path=None): + cls_rev = {} + sel_rev = {} + if symbol_map_path and Path(symbol_map_path).is_file(): + raw = _unwrap_v2_mappings(json.loads(Path(symbol_map_path).read_text(encoding='utf-8'))) + for orig, obf in raw.items(): + if isinstance(obf, str): + cls_rev[obf] = orig + elif isinstance(obf, dict) and isinstance(obf.get('obfuscated'), str): + cls_rev[obf['obfuscated']] = orig + if method_map_path and Path(method_map_path).is_file(): + raw = _unwrap_v2_mappings(json.loads(Path(method_map_path).read_text(encoding='utf-8'))) + for orig, obf in raw.items(): + if isinstance(obf, str): + sel_rev[obf] = orig + if ':' in orig: + orig_parts = re.findall(r'[A-Za-z_][A-Za-z0-9_]*:', orig) + for idx, orig_part in enumerate(orig_parts, start=1): + sel_rev.setdefault(f'{obf}_{idx}:', orig_part) + if orig_parts: + sel_rev.setdefault(f'{obf}_1', orig_parts[0][:-1]) + elif isinstance(obf, list): + for item in obf: + if isinstance(item, str): + sel_rev[item] = orig + elif isinstance(obf, dict): + full_obf = obf.get('obfuscated') + tok = obf.get('token') + parts = obf.get('parts') + if isinstance(full_obf, str) and full_obf: + sel_rev[full_obf] = orig + if obf.get('kind') == 'objc_selector' and isinstance(parts, list) and ':' in orig: + orig_parts = re.findall(r'[A-Za-z_][A-Za-z0-9_]*:', orig) + if len(orig_parts) == len(parts): + for obf_part, orig_part in zip(parts, orig_parts): + norm_obf = obf_part if obf_part.endswith(':') else f'{obf_part}:' + sel_rev.setdefault(norm_obf, orig_part) + if isinstance(tok, str) and tok and orig_parts: + sel_rev.setdefault(tok, orig_parts[0][:-1]) + elif isinstance(tok, str) and tok: + sel_rev[tok] = orig + return cls_rev, sel_rev + + +def deobfuscate_symbol_text(text, cls_rev, sel_rev): + out = text + combined = {} + combined.update(cls_rev) + combined.update(sel_rev) + for obf, orig in sorted(combined.items(), key=lambda kv: -len(kv[0])): + if not obf or obf not in out: + continue + if ':' in obf: + out = out.replace(obf, orig) + else: + out = re.sub(r'(? 1 else header + return header, body + + +def symbolicate_ips(text, dsym_index, cls_rev, sel_rev): + _, body = parse_ips(text) + used_images = body.get('usedImages') or [] + results = [] + for t_idx, thread in enumerate(body.get('threads') or []): + if not thread.get('triggered') and len(body.get('threads') or []) > 1 and t_idx != 0: + continue + frames_out = [] + for f_idx, frame in enumerate(thread.get('frames') or []): + img_idx = frame.get('imageIndex') + img_off = frame.get('imageOffset') + if img_idx is None or img_off is None or img_idx >= len(used_images): + continue + img = used_images[img_idx] + uid = norm_uuid(img.get('uuid', '')) + base = img.get('base', 0) + name = img.get('name', img.get('path', f'img_{img_idx}')) + addr_hex = hex(base + img_off) + base_hex = hex(base) + dsym_entry = dsym_index.get(uid) + if not dsym_entry: + # Require UUID match for app/embedded bundle binaries + img_path = img.get('path', '') + if '.app/' in img_path: + raise RuntimeError( + f'UUID mismatch or missing dSYM for bundle image {name} (uuid={img.get("uuid")})' + ) + frames_out.append({ + 'frame_index': f_idx, + 'image': name, + 'uuid': img.get('uuid'), + 'address': addr_hex, + 'status': 'system_or_unindexed', + 'inline_frames': [], + }) + continue + raw_syms = atos_lookup(dsym_entry['dwarf'], base_hex, addr_hex, arch=img.get('arch', 'arm64')) + restored = [deobfuscate_symbol_text(s, cls_rev, sel_rev) for s in raw_syms] + frames_out.append({ + 'frame_index': f_idx, + 'image': name, + 'uuid': img.get('uuid'), + 'dsym': str(dsym_entry['dsym']), + 'load_address': base_hex, + 'address': addr_hex, + 'status': 'symbolicated', + 'raw_atos': raw_syms, + 'restored_frames': restored, + }) + results.append({'thread_index': t_idx, 'triggered': bool(thread.get('triggered')), 'frames': frames_out}) + return {'format': 'ips_json', 'threads': results} + + +def symbolicate_crash(text, dsym_index, cls_rev, sel_rev): + images_by_name = {} + in_bin_images = False + for line in text.splitlines(): + if line.strip().startswith('Binary Images:'): + in_bin_images = True + continue + if in_bin_images: + m = BIN_IMAGE_RE.match(line) + if m: + start_hex, _, name, arch, uid_str, path = m.groups() + images_by_name[name] = { + 'base_hex': start_hex, + 'name': name, + 'arch': arch, + 'uuid': uid_str, + 'uuid_norm': norm_uuid(uid_str), + 'path': path.strip(), + } + + frames_out = [] + for line in text.splitlines(): + m = FRAME_LINE_RE.match(line.strip()) + if not m: + continue + f_idx, img_name, addr_hex, base_or_sym, _, _ = m.groups() + img = images_by_name.get(img_name) + if not img: + continue + uid = img['uuid_norm'] + base_hex = img['base_hex'] + dsym_entry = dsym_index.get(uid) + if not dsym_entry: + if '.app/' in img['path']: + raise RuntimeError( + f'UUID mismatch or missing dSYM for bundle image {img_name} (uuid={img["uuid"]})' + ) + frames_out.append({ + 'frame_index': int(f_idx), + 'image': img_name, + 'uuid': img['uuid'], + 'address': addr_hex, + 'status': 'system_or_unindexed', + 'restored_frames': [], + }) + continue + raw_syms = atos_lookup(dsym_entry['dwarf'], base_hex, addr_hex, arch=img['arch']) + restored = [deobfuscate_symbol_text(s, cls_rev, sel_rev) for s in raw_syms] + frames_out.append({ + 'frame_index': int(f_idx), + 'image': img_name, + 'uuid': img['uuid'], + 'dsym': str(dsym_entry['dsym']), + 'load_address': base_hex, + 'address': addr_hex, + 'status': 'symbolicated', + 'raw_atos': raw_syms, + 'restored_frames': restored, + }) + return {'format': 'crash_text', 'images_parsed': len(images_by_name), 'frames': frames_out} + + +def restore_report(report_path, dsym_dir, symbol_map=None, method_map=None): + text = Path(report_path).read_text(encoding='utf-8', errors='replace') + dsym_index = index_dsyms(dsym_dir) + cls_rev, sel_rev = load_reverse_maps(symbol_map, method_map) + + first_nonempty = next((l.strip() for l in text.splitlines() if l.strip()), '') + if first_nonempty.startswith('{'): + return symbolicate_ips(text, dsym_index, cls_rev, sel_rev) + return symbolicate_crash(text, dsym_index, cls_rev, sel_rev) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--report', required=True, type=Path) + p.add_argument('--dsym-dir', required=True, type=Path) + p.add_argument('--symbol-map', type=Path) + p.add_argument('--method-map', type=Path) + p.add_argument('--out', type=Path) + args = p.parse_args() + + res = restore_report(args.report, args.dsym_dir, args.symbol_map, args.method_map) + text = json.dumps(res, ensure_ascii=False, indent=2) + '\n' + if args.out: + args.out.write_text(text, encoding='utf-8') + else: + sys.stdout.write(text) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/llvm_obf/build_igopt_local.py b/tools/llvm_obf/build_igopt_local.py new file mode 100755 index 0000000..5cca175 --- /dev/null +++ b/tools/llvm_obf/build_igopt_local.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""Build portable standalone `opt` (with static IGObfuscator passes) from swiftlang/llvm-project.""" +import argparse +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tarfile +import tempfile + +SCRIPT_DIR = Path(__file__).resolve().parent +REPO_ROOT = SCRIPT_DIR.parents[1] +sys.path.insert(0, str(SCRIPT_DIR)) + +from ig_toolchain_resolver import ( # noqa: E402 + DEFAULT_CACHE_ROOT, + DEFAULT_GIT_REMOTE, + _versioned_dir_name, + _write_verified_marker, + augmented_tool_env, + compute_passes_hash, + detect_sdk_info, + detect_stock_tool, + detect_swift_info, + detect_xcode_info, + file_sha256, + find_cli_tool, + host_arch, + resolve_llvm_branch_for_swift, + smoke_test_opt, + verify_portability, +) + +LLVM_REMOTE = DEFAULT_GIT_REMOTE +DEFAULT_BRANCH = 'auto' +DEFAULT_BUILD_WORK = Path('/tmp/ig-llvm-build') + + +def _emit(log_fn, msg, stream=None): + if log_fn is not None: + log_fn(msg) + else: + target = stream if stream is not None else sys.stdout + target.write(f'{msg}\n') + target.flush() + + +def run(cmd, cwd=None, check=True, env=None, log_fn=None, log_stream=None): + _emit(log_fn, '[build_igopt] ' + ' '.join(map(str, cmd)), stream=log_stream) + target = log_stream if log_stream is not None else sys.stdout + if log_fn is None: + return subprocess.run(list(map(str, cmd)), cwd=cwd, env=env, check=check) + proc = subprocess.Popen( + list(map(str, cmd)), + cwd=cwd, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + errors='replace', + ) + tail = [] + assert proc.stdout is not None + for line in proc.stdout: + s = line.rstrip('\r\n') + if s: + tail.append(s) + if len(tail) > 60: + tail.pop(0) + _emit(log_fn, s, stream=target) + rc = proc.wait() + if check and rc != 0: + raise RuntimeError( + f'Command failed (rc={rc}): {" ".join(map(str, cmd))}\n' + '\n'.join(tail[-30:]) + ) + return subprocess.CompletedProcess(cmd, rc) + + +def _prepare_llvm_source(src_dir, branch, remote, env, log_fn=None, log_stream=None): + src_p = Path(src_dir) + if (src_p / '.git').exists(): + run(['git', 'remote', 'set-url', 'origin', remote], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream) + run(['git', 'fetch', '--depth', '1', 'origin', branch], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream) + run(['git', 'checkout', '-f', 'FETCH_HEAD'], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream) + run(['git', 'sparse-checkout', 'set', 'llvm', 'cmake', 'third-party'], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream) + run(['git', 'clean', '-fdx'], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream) + return + + src_p.parent.mkdir(parents=True, exist_ok=True) + run([ + 'git', 'clone', '--depth', '1', '--filter=blob:none', '--sparse', + '--branch', branch, remote, str(src_p), + ], env=env, log_fn=log_fn, log_stream=log_stream) + run(['git', 'sparse-checkout', 'set', 'llvm', 'cmake', 'third-party'], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream) + + +def build_opt( + branch=DEFAULT_BRANCH, + work_dir=DEFAULT_BUILD_WORK, + keep_work=False, + jobs=None, + git_remote=None, + cache_dir=None, + mirror_dir=None, + passes_dir=None, + developer_dir=None, + update_manifest=True, + log_fn=None, + log_stream=None, +): + env = augmented_tool_env() + if developer_dir: + env['DEVELOPER_DIR'] = str(developer_dir) + + cmake_bin = find_cli_tool('cmake', env) + if not cmake_bin: + raise RuntimeError('cmake not found on PATH (/opt/homebrew/bin, /usr/local/bin)') + ninja_bin = find_cli_tool('ninja', env) + + xc = detect_xcode_info(developer_dir) + sdk = detect_sdk_info(developer_dir=developer_dir) + swift_info = detect_swift_info(developer_dir=developer_dir) + arch = host_arch() + swiftlang_ver = swift_info.get('raw', '') + + remote = (git_remote or os.environ.get('IG_LLVM_GIT_MIRROR') or LLVM_REMOTE).strip() + resolved_branch = ( + resolve_llvm_branch_for_swift(swift_info, xcode_info=xc, git_remote=remote) + if not branch or branch == 'auto' + else branch + ) + + pdir = Path(passes_dir).resolve() if passes_dir is not None else (REPO_ROOT / 'llvm_passes') + if not (pdir / 'CMakeLists.txt').is_file(): + raise FileNotFoundError(f'Missing llvm_passes/CMakeLists.txt at {pdir}') + passes_hash = compute_passes_hash(pdir) + + work = Path(work_dir).resolve() + root_cache = Path(os.path.expanduser(str(cache_dir or os.environ.get('IG_TOOLCHAIN_CACHE_DIR') or DEFAULT_CACHE_ROOT))) + root_cache.mkdir(parents=True, exist_ok=True) + job_count = int(jobs or os.cpu_count() or 8) + + use_persistent_mirror = mirror_dir is not None + src_dir = Path(mirror_dir).resolve() if use_persistent_mirror else (work / 'llvm-project') + temp_build_parent = None + if use_persistent_mirror and not keep_work: + build_dir = Path(tempfile.mkdtemp(prefix='ig-llvm-cmake-')) + temp_build_parent = build_dir + else: + build_dir = work / 'build' + + try: + _prepare_llvm_source(src_dir, resolved_branch, remote, env, log_fn=log_fn, log_stream=log_stream) + + generator_args = ['-G', 'Ninja', f'-DCMAKE_MAKE_PROGRAM={ninja_bin}'] if ninja_bin else ['-G', 'Unix Makefiles'] + cmake_args = [ + cmake_bin, *generator_args, + '-S', str(src_dir / 'llvm'), + '-B', str(build_dir), + '-DCMAKE_BUILD_TYPE=Release', + '-DCMAKE_OSX_ARCHITECTURES=arm64', + '-DCMAKE_OSX_DEPLOYMENT_TARGET=13.0', + '-DCMAKE_IGNORE_PREFIX_PATH=/opt/homebrew;/usr/local', + '-DLLVM_TARGETS_TO_BUILD=AArch64', + '-DLLVM_ENABLE_ZSTD=OFF', + '-DLLVM_ENABLE_TERMINFO=OFF', + '-DLLVM_ENABLE_LIBXML2=OFF', + '-DLLVM_ENABLE_LIBEDIT=OFF', + '-DLLVM_ENABLE_HTTPLIB=OFF', + '-DLLVM_ENABLE_CURL=OFF', + '-DLLVM_INCLUDE_TESTS=OFF', + '-DLLVM_INCLUDE_BENCHMARKS=OFF', + '-DLLVM_INCLUDE_EXAMPLES=OFF', + '-DLLVM_INCLUDE_DOCS=OFF', + '-DLLVM_INCLUDE_UTILS=OFF', + '-DLLVM_BUILD_UTILS=OFF', + '-DLLVM_EXTERNAL_PROJECTS=IGObfuscator', + f'-DLLVM_EXTERNAL_IGOBFUSCATOR_SOURCE_DIR={pdir}', + '-DLLVM_IGOBFUSCATOR_LINK_INTO_TOOLS=ON', + ] + run(cmake_args, env=env, log_fn=log_fn, log_stream=log_stream) + run([cmake_bin, '--build', str(build_dir), '--target', 'opt', f'-j{job_count}'], env=env, log_fn=log_fn, log_stream=log_stream) + + built_opt = build_dir / 'bin' / 'opt' + if not built_opt.is_file(): + raise FileNotFoundError(f'opt was not produced at {built_opt}') + + llvm_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=src_dir, env=env, text=True).strip() + cmake_ver_line = subprocess.check_output([cmake_bin, '--version'], env=env, text=True).splitlines()[0].strip() + + target_name = _versioned_dir_name(xc['xcode_build'], arch, passes_hash) + tc_dir = root_cache / target_name + + with tempfile.TemporaryDirectory(prefix='.igopt-stage-', dir=root_cache) as td: + stage = Path(td) / 'stage' + dist_bin_dir = stage / 'bin' + dist_bin_dir.mkdir(parents=True, exist_ok=True) + stage_opt = dist_bin_dir / 'opt' + + run(['strip', '-x', str(built_opt), '-o', str(stage_opt)], env=env, log_fn=log_fn, log_stream=log_stream) + stage_opt.chmod(0o755) + run(['codesign', '--force', '--sign', '-', str(stage_opt)], env=env, log_fn=log_fn, log_stream=log_stream) + + verify_portability(stage_opt) + smoke_test_opt(stage_opt, developer_dir=developer_dir) + + opt_sha = file_sha256(stage_opt) + meta_out = { + 'schema_version': 1, + 'xcode_version': xc['xcode_version'], + 'xcode_build': xc['xcode_build'], + 'sdk_version': sdk['sdk_version'], + 'swift_version': swift_info.get('swift_version', ''), + 'swiftlang_version': swift_info.get('swiftlang_version', ''), + 'swift_major_minor': swift_info.get('swift_major_minor', ''), + 'arch': arch, + 'passes_hash': passes_hash, + 'opt_sha256': opt_sha, + 'source_mode': 'built', + 'llvm_branch': resolved_branch, + 'llvm_commit': llvm_commit, + 'cmake_version': cmake_ver_line, + 'smoke_passed_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), + } + (stage / 'meta.json').write_text(json.dumps(meta_out, indent=2) + '\n', encoding='utf-8') + _write_verified_marker(stage_opt, opt_sha) + + if tc_dir.exists(): + shutil.rmtree(tc_dir) + stage.rename(tc_dir) + + dist_opt = tc_dir / 'bin' / 'opt' + _emit(log_fn, f'[build_igopt] Installed opt ({opt_sha}) -> {dist_opt}', stream=log_stream) + + if update_manifest: + legacy_dir = root_cache / f"{xc['xcode_build']}-{arch}" + if legacy_dir != tc_dir: + (legacy_dir / 'bin').mkdir(parents=True, exist_ok=True) + legacy_opt = legacy_dir / 'bin' / 'opt' + shutil.copy2(dist_opt, legacy_opt) + legacy_opt.chmod(0o755) + _write_verified_marker(legacy_opt, opt_sha) + + bundles_dir = root_cache.parent / 'bundles' + bundles_dir.mkdir(parents=True, exist_ok=True) + bundle_path = bundles_dir / f"igopt-{xc['xcode_build']}-{arch}.tar.gz" + with tarfile.open(bundle_path, 'w:gz') as tf: + tf.add(dist_opt, arcname='bin/opt') + bundle_sha = file_sha256(bundle_path) + + manifest_path = REPO_ROOT / 'config' / 'toolchain_manifest.json' + manifest_path.parent.mkdir(parents=True, exist_ok=True) + manifest = {'schema_version': 2, 'toolchains': {}} + if manifest_path.is_file(): + manifest = json.loads(manifest_path.read_text(encoding='utf-8')) + manifest.setdefault('toolchains', {})[f"{xc['xcode_build']}:{arch}"] = { + 'xcode_version': xc['xcode_version'], + 'xcode_build': xc['xcode_build'], + 'sdk_version': sdk['sdk_version'], + 'host_arch': arch, + 'swiftlang_version': swiftlang_ver, + 'passes_hash': passes_hash, + 'llvm_branch': resolved_branch, + 'llvm_commit': llvm_commit, + 'cmake_version': cmake_ver_line, + 'opt_sha256': opt_sha, + 'bundle_path': f"~/.cache/iosguard/bundles/{bundle_path.name}", + 'bundle_sha256': bundle_sha, + } + manifest_path.write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8') + _emit(log_fn, f'[build_igopt] Updated manifest: {manifest_path}', stream=log_stream) + + return { + 'opt_path': str(dist_opt), + 'opt_sha256': opt_sha, + 'target_dir': str(tc_dir), + 'llvm_branch': resolved_branch, + 'llvm_commit': llvm_commit, + 'meta': meta_out, + } + finally: + if not keep_work: + if temp_build_parent is not None and temp_build_parent.exists(): + _emit(log_fn, f'[build_igopt] Cleaning temporary CMake build dir {temp_build_parent}...', stream=log_stream) + shutil.rmtree(temp_build_parent, ignore_errors=True) + elif not use_persistent_mirror and work.exists(): + _emit(log_fn, f'[build_igopt] Cleaning temporary LLVM build dir {work} to reclaim disk space...', stream=log_stream) + shutil.rmtree(work, ignore_errors=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--branch', default=DEFAULT_BRANCH) + parser.add_argument('--work-dir', type=Path, default=DEFAULT_BUILD_WORK) + parser.add_argument('--keep-work', action='store_true') + parser.add_argument('--jobs', type=int, default=os.cpu_count() or 8) + parser.add_argument('--git-remote', default=None) + parser.add_argument('--cache-dir', type=Path, default=None) + parser.add_argument('--mirror-dir', type=Path, default=None) + parser.add_argument('--no-update-manifest', action='store_true') + args = parser.parse_args() + + build_opt( + branch=args.branch, + work_dir=args.work_dir, + keep_work=args.keep_work, + jobs=args.jobs, + git_remote=args.git_remote, + cache_dir=args.cache_dir, + mirror_dir=args.mirror_dir, + update_manifest=(not args.no_update_manifest), + ) + + +if __name__ == '__main__': + main() diff --git a/tools/llvm_obf/build_obfuscated_ipa.py b/tools/llvm_obf/build_obfuscated_ipa.py new file mode 100644 index 0000000..7360928 --- /dev/null +++ b/tools/llvm_obf/build_obfuscated_ipa.py @@ -0,0 +1,1118 @@ +#!/usr/bin/env python3 +"""Build a standalone full L1+L2+L3 obfuscated IPA artifact in an isolated temp workspace.""" +import argparse +from concurrent.futures import ThreadPoolExecutor +import datetime +import hashlib +import json +import os +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import sys +import tempfile +import time +import zipfile + +ROOT = Path('/Users/shenlei/Work/ReadBook/iOSGuard') +APP_REPO = ROOT / 'readoor-test' +TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf' +TOOLS_MACHO = ROOT / 'tools' / 'macho_guard' + +sys.path.insert(0, str(TOOLS_LLVM_OBF)) +sys.path.insert(0, str(TOOLS_MACHO)) + +import ig_toolchain_resolver # noqa: E402 +import run_m3_full_regression as m3 # noqa: E402 +import verify_macho_indirect_branches # noqa: E402 +import verify_macho_indirect_calls # noqa: E402 +import verify_macho_star_cfg # noqa: E402 +from verify_baseline import scan as scan_route2 # noqa: E402 + +WORK_ROOT = Path('/tmp/ig-ipa-work') +CACHE_ROOT = Path('/tmp/ig-ipa-cache') +DEFAULT_PROFILE = m3.DEFAULT_PROFILE +DEFAULT_IDENTITY = m3.DEFAULT_IDENTITY + +_ANTI_HOOK_OBJDUMP_RE = re.compile(r'^\s*([0-9a-fA-F]+):\s+([0-9a-fA-F]{8})\s+(.+?)\s*$') +_ANTI_HOOK_MOV_RE = re.compile(r'^(?:mov\s+(x1[67])\s*,\s*\1|orr\s+(x1[67])\s*,\s*xzr\s*,\s*\2)\b') +_ANTI_HOOK_OPCODES = {'aa1103f1': 'x17', 'aa1003f0': 'x16'} + + +def _inspect_anti_hook_range(main_bin: Path, start_addr: int, end_addr: int) -> dict: + if end_addr - start_addr < 8: + return { + 'start_addr': hex(start_addr), + 'end_addr': hex(end_addr), + 'ok': False, + 'insns': [], + 'reason': 'function_shorter_than_8_bytes', + } + dis = subprocess.check_output( + [ + 'xcrun', 'llvm-objdump', '--disassemble', + f'--start-address={hex(start_addr)}', + f'--stop-address={hex(start_addr + 8)}', + str(main_bin), + ], + text=True, + ) + insns = [] + seen_regs = set() + for line in dis.splitlines(): + m = _ANTI_HOOK_OBJDUMP_RE.match(line) + if not m: + continue + addr = int(m.group(1), 16) + ophex = m.group(2).lower() + text = ' '.join(m.group(3).split()) + reg = _ANTI_HOOK_OPCODES.get(ophex) + if reg is None: + mm = _ANTI_HOOK_MOV_RE.match(text) + if mm: + reg = mm.group(1) or mm.group(2) + insns.append({'addr': hex(addr), 'opcode': ophex, 'asm': text, 'reg': reg}) + if reg in ('x16', 'x17'): + seen_regs.add(reg) + ok = ( + len(insns) >= 2 + and insns[0]['addr'] == hex(start_addr) + and insns[1]['addr'] == hex(start_addr + 4) + and insns[0]['reg'] in ('x16', 'x17') + and insns[1]['reg'] in ('x16', 'x17') + and seen_regs == {'x16', 'x17'} + ) + return { + 'start_addr': hex(start_addr), + 'end_addr': hex(end_addr), + 'ok': ok, + 'insns': insns[:2], + } + + +def _verify_binary_anti_hook_prologues(main_bin: Path, dwarf_bin: Path, obf_audit: dict) -> dict: + """Disassemble offset 0..8 of audited anti_hook_functions and verify mov x16/x17 prologues.""" + ranges_map = verify_macho_star_cfg.parse_dwarf_text_ranges(dwarf_bin) + verified = [] + failed = [] + dead_stripped = [] + to_check: list[tuple[str, str, list[tuple[int, int]]]] = [] + + for mod in obf_audit.get('module_audits') or []: + src_name = Path(mod.get('source_path') or 'unknown').name + for raw_name in mod.get('anti_hook_functions') or []: + cand_ranges = [] + for key in verify_macho_star_cfg._candidate_symbol_keys(raw_name): + if key in ranges_map: + cand_ranges = ranges_map[key] + break + if not cand_ranges: + dead_stripped.append({'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'}) + continue + to_check.append((src_name, raw_name, cand_ranges)) + + unique_ranges = sorted({se for _, _, rlist in to_check for se in rlist}) + inspected_by_range: dict[tuple[int, int], dict] = {} + if unique_ranges: + with ThreadPoolExecutor(max_workers=8) as pool: + results = pool.map(lambda se: _inspect_anti_hook_range(main_bin, se[0], se[1]), unique_ranges) + for se, res in zip(unique_ranges, results): + inspected_by_range[se] = res + + for src_name, raw_name, cand_ranges in to_check: + range_results = [inspected_by_range[se] for se in cand_ranges] + bad = [r for r in range_results if not r['ok']] + if bad: + failed.append({ + 'source': src_name, + 'name': raw_name, + 'reason': 'missing_anti_hook_x16_x17_prologue', + 'range_results': range_results, + }) + else: + verified.append({ + 'source': src_name, + 'name': raw_name, + **range_results[0], + }) + + summary = { + 'total_audited': len(verified) + len(failed) + len(dead_stripped), + 'linked_checked_count': len(verified) + len(failed), + 'verified_anti_hook_count': len(verified), + 'dead_stripped_count': len(dead_stripped), + 'failed_count': len(failed), + 'failed': failed, + 'sample_verified': verified[:12], + } + if failed: + preview = json.dumps(failed[:5], ensure_ascii=False, indent=2) + raise AssertionError( + f'[AntiHookGate] {len(failed)} function(s) failed offset-0 x16/x17 prologue check:\n{preview}' + ) + return summary + + +def _create_l1_snapshot(snapshot_src: Path, scheme: str, timestamp: str, seed: str, log_path: Path) -> dict: + """Rsync readoor-test into isolated snapshot and apply L1 symbol/method obfuscation.""" + m3.check_disk_budget() + if snapshot_src.exists(): + shutil.rmtree(snapshot_src) + snapshot_src.parent.mkdir(parents=True, exist_ok=True) + subprocess.run([ + 'rsync', '-a', '--delete', + '--exclude', '/.git', + '--exclude', '/build', + '--exclude', '/DerivedData', + '--exclude', '/build_output', + '--exclude', '/obfuscation_maps', + f'{APP_REPO}/', + f'{snapshot_src}/', + ], check=True) + + pre = subprocess.run( + ['bash', str(snapshot_src / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh')], + cwd=snapshot_src, capture_output=True, text=True, + ) + if pre.returncode != 0: + raise RuntimeError(f'Pre-L1 self-check failed:\n{pre.stdout}\n{pre.stderr}') + + t0 = time.monotonic() + l1_res = subprocess.run([ + 'python3', + str(snapshot_src / 'AutoPacking/obfuscation/obfuscate_symbols.py'), + '--archive-mode', + '--target-name', scheme, + '--timestamp', timestamp, + '--salt', seed, + ], cwd=snapshot_src, capture_output=True, text=True) + l1_elapsed = round(time.monotonic() - t0, 2) + log_path.parent.mkdir(parents=True, exist_ok=True) + log_path.write_text(l1_res.stdout + '\n' + l1_res.stderr, encoding='utf-8') + if l1_res.returncode != 0: + raise RuntimeError(f'obfuscate_symbols.py failed (rc={l1_res.returncode}):\n{l1_res.stdout[-4000:]}\n{l1_res.stderr[-2000:]}') + + sym_map_p = snapshot_src / f'obfuscation_maps/symbol_map_{scheme}_{timestamp}.json' + meth_map_p = snapshot_src / f'obfuscation_maps/method_map_{scheme}_{timestamp}.json' + sym_payload = json.loads(sym_map_p.read_text(encoding='utf-8')) + meth_payload = json.loads(meth_map_p.read_text(encoding='utf-8')) + sym_mappings = sym_payload.get('mappings') or {} + meth_mappings = meth_payload.get('mappings') or {} + + sample_types = {} + for cls_name in ('RDLoginView', 'RDSDAuthV32Signer', 'RDInjectionDetector', 'STSIAPVerifyHandler', 'STSIAPKeyChainHandler', 'RDIAPHandler'): + val = sym_mappings.get(cls_name) + obf = val.get('obfuscated') if isinstance(val, dict) else val + if obf: + sample_types[cls_name] = obf + + sample_methods = {} + for meth_name in ('buildSignatureHeaders(businessBody:headerFields:)', 'hasSuspiciousDyldInsertLibraries', 'logDiag'): + val = meth_mappings.get(meth_name) + obf = val.get('obfuscated') if isinstance(val, dict) else val + if obf: + sample_methods[meth_name] = obf + + return { + 'elapsed_s': l1_elapsed, + 'symbol_map_path': sym_map_p, + 'method_map_path': meth_map_p, + 'type_mappings_count': len(sym_mappings), + 'method_mappings_count': len(meth_mappings), + 'sample_type_mappings': sample_types, + 'sample_method_mappings': sample_methods, + } + + +def _inject_pods_prefix_map(snapshot_src: Path) -> int: + """Inject source-path scrubbing flags into non-aggregate Pod release xcconfigs in-place.""" + support_dir = snapshot_src / 'Pods/Target Support Files' + if not support_dir.is_dir(): + return 0 + roots = list(dict.fromkeys([str(snapshot_src), str(snapshot_src.resolve())])) + c_tokens: list[str] = [] + swift_tokens: list[str] = [] + for root in roots: + c_tokens.extend([ + f'-ffile-prefix-map={root}=.', + f'-fmacro-prefix-map={root}=.', + f'-fdebug-prefix-map={root}=.', + ]) + swift_tokens.append(f'-file-prefix-map {root}=.') + swift_tokens.append('-enable-upcoming-feature ConciseMagicFile') + + c_suffix = ' '.join(c_tokens) + swift_suffix = ' '.join(swift_tokens) + key_re = re.compile(r'^(\s*)(OTHER_CFLAGS|OTHER_CPLUSPLUSFLAGS|OTHER_SWIFT_FLAGS)(\s*=.*)$') + updated = 0 + for cfg in sorted(support_dir.glob('*/*.release.xcconfig')): + if cfg.parent.name.startswith('Pods-'): + continue + lines = cfg.read_text(encoding='utf-8').splitlines() + seen_keys: set[str] = set() + new_lines: list[str] = [] + for ln in lines: + m = key_re.match(ln) + if m: + indent, key, rest = m.groups() + seen_keys.add(key) + extra = swift_suffix if key == 'OTHER_SWIFT_FLAGS' else c_suffix + new_lines.append(f'{indent}{key}{rest} {extra}') + else: + new_lines.append(ln) + if 'OTHER_CFLAGS' not in seen_keys: + new_lines.append(f'OTHER_CFLAGS = $(inherited) {c_suffix}') + if 'OTHER_SWIFT_FLAGS' not in seen_keys: + new_lines.append(f'OTHER_SWIFT_FLAGS = $(inherited) {swift_suffix}') + cfg.write_text('\n'.join(new_lines) + '\n', encoding='utf-8') + updated += 1 + return updated + + +def _is_macho_file(path: Path) -> bool: + if not path.is_file() or path.is_symlink(): + return False + try: + magic = path.read_bytes()[:4] + except OSError: + return False + return magic in ( + b'\xcf\xfa\xed\xfe', + b'\xfe\xed\xfa\xcf', + b'\xce\xfa\xed\xfe', + b'\xfe\xed\xfa\xce', + b'\xca\xfe\xba\xbe', + b'\xbe\xba\xfe\xca', + ) + + +def _strip_embedded_binaries(staged_app: Path) -> list[str]: + stripped: list[str] = [] + candidates = sorted( + {p for p in staged_app.rglob('*') if not p.is_symlink() and p.suffix in ('.framework', '.dylib')}, + key=lambda p: (-len(p.parts), str(p)), + ) + for nested in candidates: + targets: list[Path] = [] + if nested.suffix == '.dylib' and _is_macho_file(nested): + targets.append(nested) + elif nested.suffix == '.framework' and nested.is_dir(): + for doc_name in ('export.txt', 'README.md'): + doc_p = nested / doc_name + if doc_p.is_file() and not doc_p.is_symlink(): + doc_p.unlink() + for sub in sorted(nested.rglob('*')): + rel_parts = sub.relative_to(nested).parts + if any(part.endswith(('.framework', '.dylib')) for part in rel_parts[:-1]): + continue + if sub.suffix == '.dylib' and len(rel_parts) > 1: + continue + if _is_macho_file(sub): + targets.append(sub) + for bin_p in targets: + subprocess.run(['xcrun', 'strip', '-x', str(bin_p)], check=True) + stripped.append(str(bin_p.relative_to(staged_app))) + subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, str(nested)], check=True) + return stripped + + +def _collect_static_hygiene_gate( + ipa_path: Path, + app_dir: Path, + main_bin: Path, + interm: Path, + scheme: str, + symbol_map_path: Path, +) -> dict: + """Verify static-analysis hardening guarantees on the final IPA and object artifacts.""" + main_raw = main_bin.read_bytes() + nm_gu = subprocess.check_output(['xcrun', 'nm', '-gU', str(main_bin)], text=True, errors='replace') + defined_exports = sorted({l.split()[-1] for l in nm_gu.splitlines() if l.strip()}) + dyld_info_out = subprocess.check_output(['xcrun', 'dyld_info', '-exports', str(main_bin)], text=True, errors='replace') + dyld_exports = sorted({ + parts[-1] + for ln in dyld_info_out.splitlines() + if (parts := ln.split()) and parts[0].startswith('0x') + }) + allowed_exports = {'_main', '__mh_execute_header'} + main_exports_locked = ( + set(defined_exports).issubset(allowed_exports) + and set(dyld_exports).issubset(allowed_exports) + ) + + nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(main_bin)], text=True, errors='replace') + nm_u_syms = {l.strip() for l in nm_u.splitlines() if l.strip()} + forbidden_main_u = { + sym: (sym in nm_u_syms) + for sym in ('_SecKeyCreateWithData', '_SecKeyCreateSignature') + } + third_party_main_u = { + sym: (sym in nm_u_syms) + for sym in ('_CCKeyDerivationPBKDF', '_CCCrypt', '_CCHmac', '_sysctl') + } + cryptokit_imports = sorted( + s for s in nm_u_syms if 'CryptoKit' in s or '9CryptoKit' in s + ) + otool_l_lines = subprocess.check_output(['xcrun', 'otool', '-L', str(main_bin)], text=True, errors='replace').splitlines() + cryptokit_load_cmds = [l.strip() for l in otool_l_lines if 'CryptoKit' in l] + + obj_dirs = [interm / 'Objects-normal/arm64', interm / 'Objects-normal/arm64/ig-swift-macho'] + target_obj_prefixes = ( + 'RDSDKeyBox.o', + 'RDEpubCryptBridge.o', + 'RBCoreUtil.o', + 'RDSDPrivateKeyManager', + 'RDSDAuthV32Signer', + 'RDInjectionDetector', + 'RDJailbreakDetector', + 'STSJailbreakDetectTool.o', + 'RDTSParameterSetPatcher', + 'RDRouterDebugTool', + ) + all_jailbreak_needles = ( + b'/Applications/Cydia.app', + b'/Library/MobileSubstrate/MobileSubstrate.dylib', + b'/Library/MobileSubstrate/DynamicLibraries', + b'/private/var/tmp/cydia.log', + b'/private/var/lib/cydia', + b'/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist', + b'/var/jb/usr/lib', + b'com.opa334.TrollStore.plist', + b'.jailbreak_test_', + b'/User/Applications/', + ) + app_obj_stub_hits: dict[str, list[str]] = {} + app_objects_jailbreak_hits: dict[str, list[str]] = {} + app_obj_checked = 0 + core_objs_matched: set[str] = set() + watched_stubs = { + '_SecKeyCreateWithData', + '_SecKeyCreateSignature', + '_CCKeyDerivationPBKDF', + '_CCCrypt', + '_CCHmac', + '_sysctl', + } + for od in obj_dirs: + if not od.is_dir(): + continue + for obj_p in sorted(od.glob('*.o')): + app_obj_checked += 1 + for pfx in target_obj_prefixes: + if obj_p.name == pfx or pfx in obj_p.name: + core_objs_matched.add(pfx) + o_u = subprocess.check_output(['xcrun', 'nm', '-u', str(obj_p)], text=True, errors='replace') + hits = sorted({l.strip() for l in o_u.splitlines() if l.strip()} & watched_stubs) + if hits: + app_obj_stub_hits[obj_p.name] = hits + obj_raw = obj_p.read_bytes() + jb_hits = [pat.decode('ascii', errors='replace') for pat in all_jailbreak_needles if pat in obj_raw] + if jb_hits: + app_objects_jailbreak_hits[obj_p.name] = jb_hits + + sections = verify_macho_indirect_calls.parse_macho_sections(main_bin) + cstr_sec = sections.get('__TEXT,__cstring') or {} + cstrings: list[str] = [] + if cstr_sec.get('size', 0) > 0: + mv = verify_macho_indirect_calls._select_arm64_slice(main_raw) + cstr_bytes = bytes(mv[cstr_sec['offset']:cstr_sec['offset'] + cstr_sec['size']]) + cstrings = [s.decode('utf-8', errors='replace') for s in cstr_bytes.split(b'\x00') if s] + + tmp_work_leaks = main_raw.count(b'/tmp/ig-ipa-work/') + users_path_leaks = main_raw.count(b'/Users/shenlei/') + src_readoor_leaks = main_raw.count(b'/src/readoor/') + readoor_src_re = re.compile(r'^(?:\./|/)?readoor/.*\.(?:swift|m|mm|c|h)$') + readoor_rel_cstrings = [s for s in cstrings if readoor_src_re.match(s)] + swift_mod_file_re = re.compile(rf'^(?:{re.escape(scheme)}|readoor31|readoor)/.*\.swift$') + swift_module_file_cstrings = [s for s in cstrings if swift_mod_file_re.match(s)] + pdf_bridge_cstrings = [s for s in cstrings if '[PDF]' in s or '[Bridge]' in s] + business_debug_needles = ( + 'RDHLSLocalProxy', + '[RDBaseNetworkService]', + 'initializeParser: PDF', + '映射表解密失败', + '缺少 pdfMap 字节偏移', + 'PDF SDK 状态保存失败', + '置换token时签名已过期', + '强制置换一次 token', + '服务端未返回有效 token', + '当前需要置换token', + '当前不需要置换token', + '保存用户 token 失败', + ) + business_debug_cstrings = [ + s for s in cstrings if any(needle in s for needle in business_debug_needles) + ] + jailbreak_needles = { + pat.decode('ascii', errors='replace'): main_raw.count(pat) + for pat in ( + b'/Library/MobileSubstrate/DynamicLibraries', + b'/private/var/tmp/cydia.log', + b'/private/var/lib/cydia', + b'/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist', + b'/var/jb/usr/lib', + b'com.opa334.TrollStore.plist', + b'.jailbreak_test_', + b'/User/Applications/', + ) + } + third_party_jailbreak_needles = { + pat.decode('ascii', errors='replace'): main_raw.count(pat) + for pat in ( + b'/Applications/Cydia.app', + b'/Library/MobileSubstrate/MobileSubstrate.dylib', + ) + } + placeholder_url_count = main_raw.count(b'your-api.com/upload') + + secret_leaks = { + pat.decode('ascii', errors='replace'): main_raw.count(pat) + for pat in ( + b'startiasoftstartiasoft', + b'startiasoftvvportal', + b'readoorstartiasoft', + b'startiasoft%@', + b'd9800fb39d16c3f1cc0ddb5618af8378', + ) + } + dev_domain_leaks = { + pat.decode('ascii'): main_raw.count(pat) + for pat in ( + b'api3-dev.readoor.cn', + b'uc-dev.readoor.cn', + b'statupload-dev.readoor.cn', + ) + } + + otool_ov = subprocess.check_output(['xcrun', 'otool', '-oV', str(main_bin)], text=True, errors='replace') + unobfuscated_watch_classes = ( + 'RDEpubCryptBridge', + 'EpubParser', + 'EpubChapter', + 'LoadEpub', + 'RDSecurityGuard', + 'RDIAPTransactionGate', + 'RD30EpubEntry', + 'RDEpubReaderLauncher', + 'STSIAPHandler', + 'STSIAPVerifyHandler', + 'STSIAPKeyChainHandler', + 'STSIAPVerifyTask', + 'STSJailbreakDetectTool', + ) + unobfuscated_objc_hits = [ + name for name in unobfuscated_watch_classes + if ( + f'_OBJC_CLASS_$_{name}' in otool_ov + or f'_OBJC_METACLASS_$_{name}' in otool_ov + or f'{len(name)}{name}' in otool_ov + ) + ] + unobfuscated_class_raw_hits = { + name: main_raw.count(name.encode('ascii')) + for name in ( + 'RDEpubCryptBridge', + 'RDSecurityGuard', + 'RDIAPTransactionGate', + 'RD30EpubEntry', + 'RDEpubReaderLauncher', + ) + } + + sym_map = json.loads(symbol_map_path.read_text(encoding='utf-8')).get('mappings') or {} + expected_l1_renamed = { + cls: bool((sym_map.get(cls) or {}).get('obfuscated') if isinstance(sym_map.get(cls), dict) else sym_map.get(cls)) + for cls in ( + 'RDRouterDebugTool', + 'RDPlayerControlView', + 'EpubParser', + 'EpubChapter', + 'LoadEpub', + 'RDSecurityGuard', + 'RDIAPTransactionGate', + 'RD30EpubEntry', + 'RDEpubReaderLauncher', + ) + } + + embedded_checked = 0 + embedded_with_locals: dict[str, int] = {} + embedded_with_tmp_leaks: dict[str, int] = {} + rd_coreio_found = False + rd_coreio_ig_exports: list[str] = [] + rd_coreio_ig_name_count: int | None = None + main_ig_archive_guard_count = main_raw.count(b'IGArchiveGuard') + with tempfile.TemporaryDirectory(prefix='ig-ipa-verify-') as td: + vdir = Path(td) + with zipfile.ZipFile(ipa_path, 'r') as zf: + names = set(zf.namelist()) + app_prefix = f'Payload/{scheme}.app/' + plist_member = f'{app_prefix}Info.plist' + info_plist = plistlib.loads(zf.read(plist_member)) + redundant_plist_absent = f'{app_prefix}readoor31.plist' not in names + neutral_asset_present = ( + f'{app_prefix}rd_glyph_lut_v2.dat' in names + and f'{app_prefix}rd_net_cfg_v1.dat' not in names + ) + readme_hits = sorted( + n for n in names + if n == f'{app_prefix}README.md' + or ( + n.startswith(f'{app_prefix}Frameworks/') + and n.rsplit('/', 1)[-1] in ('README.md', 'export.txt') + ) + ) + macosx_junk_entries = sorted( + n for n in names + if n.startswith('__MACOSX/') or '/__MACOSX/' in n or n.rsplit('/', 1)[-1].startswith('._') + ) + dirty_plist_keys_found = sorted( + k for k in ('Appilcation support iTunes file sharing', 'Supports opening documents in place') + if k in info_plist + ) + ig_archive_guard_entries = sorted( + n for n in names if n.startswith(f'{app_prefix}Frameworks/IGArchiveGuard.framework/') + ) + staticized_framework_leaks = sorted( + n for n in names + if n.startswith(f'{app_prefix}Frameworks/RDEpubReaderView.framework/') + or n.startswith(f'{app_prefix}Frameworks/RDPDFReaderView.framework/') + ) + rd_coreio_member = f'{app_prefix}Frameworks/RDCoreIO.framework/RDCoreIO' + for member in sorted(names): + if not member.startswith(f'{app_prefix}Frameworks/') and not member.startswith(f'{app_prefix}PlugIns/'): + continue + if member.endswith('/') or '/_CodeSignature/' in member or member.endswith('.plist'): + continue + zf.extract(member, vdir) + fp = vdir / member + if _is_macho_file(fp): + embedded_checked += 1 + fw_raw = fp.read_bytes() + tmp_cnt = fw_raw.count(b'/tmp/ig-ipa-work/') + if tmp_cnt > 0: + embedded_with_tmp_leaks[member] = tmp_cnt + nm_res = subprocess.run( + ['xcrun', 'nm', str(fp)], + capture_output=True, text=True, errors='replace', + ) + local_cnt = sum( + 1 for ln in nm_res.stdout.splitlines() + if len(ln.split()) >= 2 and ln.split()[-2] in ('t', 'd', 's', 'b') + ) + if local_cnt > 0: + embedded_with_locals[member] = local_cnt + if member == rd_coreio_member: + rd_coreio_found = True + rd_coreio_ig_name_count = fw_raw.count(b'IGArchiveGuard') + coreio_exports = subprocess.check_output( + ['xcrun', 'nm', '-gU', str(fp)], + text=True, errors='replace', + ) + rd_coreio_ig_exports = sorted( + sym for ln in coreio_exports.splitlines() + if ln.strip() and (sym := ln.split()[-1]).startswith('_ig_') + ) + + schemes = {str(s).lower() for s in (info_plist.get('LSApplicationQueriesSchemes') or [])} + jb_schemes_found = sorted(schemes & {'cydia', 'sileo', 'zbra', 'filza'}) + ats = info_plist.get('NSAppTransportSecurity') or {} + ats_arbitrary_disabled = ats.get('NSAllowsArbitraryLoads') is False + + cryptokit_absent = not cryptokit_imports and not cryptokit_load_cmds + checks = { + 'main_exports_locked': main_exports_locked, + 'embedded_frameworks_stripped': embedded_checked > 0 and not embedded_with_locals, + 'embedded_frameworks_tmp_leaks_absent': embedded_checked > 0 and not embedded_with_tmp_leaks, + 'source_paths_scrubbed': ( + tmp_work_leaks == 0 + and users_path_leaks == 0 + and src_readoor_leaks == 0 + and not readoor_rel_cstrings + and not swift_module_file_cstrings + ), + 'pdf_debug_logs_scrubbed': not pdf_bridge_cstrings, + 'business_debug_logs_scrubbed': not business_debug_cstrings, + 'jailbreak_needles_scrubbed': ( + sum(jailbreak_needles.values()) == 0 + and not app_objects_jailbreak_hits + ), + 'placeholder_urls_absent': placeholder_url_count == 0, + 'secrets_scrubbed': sum(secret_leaks.values()) == 0, + 'dev_domains_scrubbed': sum(dev_domain_leaks.values()) == 0, + 'redundant_readoor31_plist_absent': redundant_plist_absent, + 'readme_absent': not readme_hits, + 'macosx_junk_absent': not macosx_junk_entries, + 'plist_dirty_keys_absent': not dirty_plist_keys_found, + 'neutral_asset_present': neutral_asset_present, + 'jailbreak_schemes_absent': not jb_schemes_found, + 'ats_arbitrary_loads_disabled': ats_arbitrary_disabled, + 'cryptokit_completely_absent': cryptokit_absent, + 'main_crypto_stubs_absent': not any(forbidden_main_u.values()) and cryptokit_absent, + 'app_objects_crypto_stubs_absent': ( + len(core_objs_matched) == len(target_obj_prefixes) + and app_obj_checked >= 50 + and not app_obj_stub_hits + ), + 'unobfuscated_classes_absent': ( + not unobfuscated_objc_hits + and all(v == 0 for v in unobfuscated_class_raw_hits.values()) + and all(expected_l1_renamed.values()) + ), + 'guard_framework_neutralized': ( + not ig_archive_guard_entries + and rd_coreio_found + and not rd_coreio_ig_exports + and rd_coreio_ig_name_count == 0 + and main_ig_archive_guard_count == 0 + ), + 'self_frameworks_staticized': not staticized_framework_leaks, + } + return { + 'passed': all(checks.values()), + 'checks': checks, + 'main_exported_defined_symbols': defined_exports, + 'main_exported_defined_symbols_count': len(defined_exports), + 'main_dyld_exports': dyld_exports, + 'main_dyld_exports_count': len(dyld_exports), + 'embedded_frameworks_checked': embedded_checked, + 'embedded_frameworks_with_local_symbols': embedded_with_locals, + 'embedded_frameworks_with_tmp_leaks': embedded_with_tmp_leaks, + 'tmp_work_path_leaks': tmp_work_leaks, + 'users_path_leaks': users_path_leaks, + 'src_readoor_path_leaks': src_readoor_leaks, + 'readoor_rel_cstring_leaks': readoor_rel_cstrings[:10], + 'readoor_rel_cstring_leaks_count': len(readoor_rel_cstrings), + 'swift_module_file_leaks': swift_module_file_cstrings[:10], + 'swift_module_file_leaks_count': len(swift_module_file_cstrings), + 'pdf_bridge_cstrings': pdf_bridge_cstrings[:10], + 'pdf_bridge_cstrings_count': len(pdf_bridge_cstrings), + 'business_debug_cstrings': business_debug_cstrings[:10], + 'business_debug_cstrings_count': len(business_debug_cstrings), + 'jailbreak_needles': jailbreak_needles, + 'third_party_jailbreak_needles': third_party_jailbreak_needles, + 'app_objects_jailbreak_hits': app_objects_jailbreak_hits, + 'placeholder_url_count': placeholder_url_count, + 'readme_hits': readme_hits, + 'macosx_junk_entries_count': len(macosx_junk_entries), + 'dirty_plist_keys_found': dirty_plist_keys_found, + 'secret_leaks': secret_leaks, + 'dev_domain_leaks': dev_domain_leaks, + 'jailbreak_schemes_found': jb_schemes_found, + 'ats_arbitrary_loads': ats.get('NSAllowsArbitraryLoads'), + 'forbidden_main_u': forbidden_main_u, + 'third_party_main_u': third_party_main_u, + 'cryptokit_imports': cryptokit_imports, + 'cryptokit_load_cmds': cryptokit_load_cmds, + 'app_objects_checked': app_obj_checked, + 'core_objects_matched': sorted(core_objs_matched), + 'app_objects_stub_hits': app_obj_stub_hits, + 'unobfuscated_objc_hits': unobfuscated_objc_hits, + 'unobfuscated_class_raw_hits': unobfuscated_class_raw_hits, + 'expected_l1_renamed': expected_l1_renamed, + 'ig_archive_guard_entries': ig_archive_guard_entries, + 'rd_coreio_found': rd_coreio_found, + 'rd_coreio_ig_exports': rd_coreio_ig_exports, + 'rd_coreio_ig_name_count': rd_coreio_ig_name_count, + 'main_ig_archive_guard_count': main_ig_archive_guard_count, + 'staticized_framework_leaks': staticized_framework_leaks, + } + + +def _sign_and_package_ipa(app_dir: Path, stage_dir: Path, ipa_path: Path, scheme: str) -> tuple[str, str]: + """Sign .app preserving its original Info.plist CFBundleIdentifier and archive Payload/ into .ipa.""" + r_prof = subprocess.run( + ['openssl', 'smime', '-inform', 'der', '-verify', '-noverify', '-in', str(DEFAULT_PROFILE)], + capture_output=True, check=True, + ) + pdata = plistlib.loads(r_prof.stdout) + ent = pdata['Entitlements'] + prefix = pdata['ApplicationIdentifierPrefix'][0] + if ent['application-identifier'] != prefix + '.*' or not ent.get('get-task-allow'): + raise RuntimeError('Provisioning profile must be wildcard development profile') + if pdata['ExpirationDate'] <= datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None): + raise RuntimeError('Provisioning profile expired') + if DEFAULT_IDENTITY.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in pdata['DeveloperCertificates']}: + raise RuntimeError('Signing identity does not match provisioning profile') + + if stage_dir.exists(): + shutil.rmtree(stage_dir) + ipa_root = stage_dir / 'ipa_root' + payload_dir = ipa_root / 'Payload' + payload_dir.mkdir(parents=True, exist_ok=True) + staged_app = payload_dir / app_dir.name + subprocess.run(['ditto', str(app_dir), str(staged_app)], check=True) + + info_path = staged_app / 'Info.plist' + info = plistlib.loads(info_path.read_bytes()) + bundle_id = str(info['CFBundleIdentifier']) + shutil.copy2(DEFAULT_PROFILE, staged_app / 'embedded.mobileprovision') + + for appex in sorted({p for p in staged_app.rglob('*.appex') if not p.is_symlink()}, key=lambda p: (-len(p.parts), str(p))): + ext_info_p = appex / 'Info.plist' + ext_info = plistlib.loads(ext_info_p.read_bytes()) + ext_bid = f'{bundle_id}.{appex.stem}' + ext_info['CFBundleIdentifier'] = ext_bid + ext_info_p.write_bytes(plistlib.dumps(ext_info)) + shutil.copy2(DEFAULT_PROFILE, appex / 'embedded.mobileprovision') + ext_ent = dict(ent) + ext_ent['application-identifier'] = f'{prefix}.{ext_bid}' + ext_ent['keychain-access-groups'] = [f'{prefix}.{bundle_id}'] + ext_ent_p = stage_dir / f'ent_{appex.stem}.plist' + ext_ent_p.write_bytes(plistlib.dumps(ext_ent)) + subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, '--entitlements', str(ext_ent_p), str(appex)], check=True) + + _strip_embedded_binaries(staged_app) + + allowed = dict(ent) + allowed['application-identifier'] = f'{prefix}.{bundle_id}' + allowed['keychain-access-groups'] = [f'{prefix}.{bundle_id}'] + ent_path = stage_dir / 'entitlements.plist' + ent_path.write_bytes(plistlib.dumps(allowed)) + subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, '--entitlements', str(ent_path), str(staged_app)], check=True) + subprocess.run(['codesign', '--verify', '--strict', str(staged_app)], check=True) + + ipa_path.parent.mkdir(parents=True, exist_ok=True) + if ipa_path.exists(): + ipa_path.unlink() + subprocess.run(['ditto', '-c', '-k', '--norsrc', str(ipa_root), str(ipa_path)], check=True) + + with zipfile.ZipFile(ipa_path, 'r') as zf: + expected_prefix = f'Payload/{scheme}.app/' + if not any(n.startswith(expected_prefix) for n in zf.namelist()): + raise RuntimeError(f'IPA missing expected {expected_prefix} entries') + + return bundle_id, m3.sha256_bytes(ipa_path.read_bytes()) + + +def build_ipa(scheme: str, output_dir: Path, seed: str, expected_binaries: int, dist_channel: str = 'dev') -> dict: + """Run full L1+L2+L3 archive, verify binary obfuscation & Route 2 audit, and export signed IPA.""" + output_dir.mkdir(parents=True, exist_ok=True) + snapshot_src = WORK_ROOT / 'src' + dd_path = WORK_ROOT / 'dd' + archive_path = WORK_ROOT / 'archives' / f'{scheme}.xcarchive' + stage_dir = WORK_ROOT / 'stage' + obj_cache = CACHE_ROOT / 'obj_cache' + sdk_cache = CACHE_ROOT / 'sdk_cache' + + try: + for d in (WORK_ROOT, CACHE_ROOT): + if d.exists(): + shutil.rmtree(d) + + print('=== [0] Sync toolchain & verify integration ===', flush=True) + m3.sync_toolchain_and_integrate() + policy_path = ROOT / 'config/ig_llvm_policy.json' + policy = json.loads(policy_path.read_text(encoding='utf-8')) + policy_stamp = ig_toolchain_resolver.file_sha256(policy_path)[:12] + + print(f'=== [1] L1 Snapshot & Obfuscation ({scheme}, seed={seed}) ===', flush=True) + l1_info = _create_l1_snapshot(snapshot_src, scheme, '20261120_ipa', seed, output_dir / 'l1_apply.log') + print( + f"[L1] types={l1_info['type_mappings_count']}, methods={l1_info['method_mappings_count']}, elapsed={l1_info['elapsed_s']}s", + flush=True, + ) + pods_cfg_count = _inject_pods_prefix_map(snapshot_src) + print(f'[PodsPrefixMap] injected={pods_cfg_count}', flush=True) + + free_gb = m3.check_disk_budget() + print(f'=== [2] L1+L2+L3 Production Archive ({scheme}, disk_free={free_gb}GB) ===', flush=True) + archive_path.parent.mkdir(parents=True, exist_ok=True) + dd_path.mkdir(parents=True, exist_ok=True) + obj_cache.mkdir(parents=True, exist_ok=True) + sdk_cache.mkdir(parents=True, exist_ok=True) + + env = os.environ.copy() + env['IG_REQUIRE_LLVM_OBF'] = '1' + env['IG_OBF_OBJ_CACHE_DIR'] = str(obj_cache) + env['IG_SDK_CACHE_DIR'] = str(sdk_cache) + + cmd = [ + 'xcodebuild', + '-workspace', str(snapshot_src / 'readoor.xcworkspace'), + '-scheme', scheme, + '-configuration', 'Release', + '-destination', 'generic/platform=iOS', + '-derivedDataPath', str(dd_path), + 'CODE_SIGNING_ALLOWED=NO', + 'IG_OBF_MODE=full', + 'IG_POLICY_PROFILE=default', + f'IG_POLICY_STAMP={policy_stamp}', + f'IG_RELEASE_SEED={seed}', + f'IG_DIST_CHANNEL={dist_channel}', + 'IG_SWIFT_EXTRA_FLAGS=', + 'IG_C_EXTRA_FLAGS=', + '-archivePath', str(archive_path), + 'archive', + ] + t0 = time.monotonic() + res = subprocess.run(cmd, cwd=snapshot_src, env=env, capture_output=True, text=True) + archive_elapsed = round(time.monotonic() - t0, 2) + full_log = res.stdout + '\n' + res.stderr + tail_lines = [ + l for l in full_log.splitlines() + if '[IGRoute2]' in l or '[IGObf]' in l or 'ARCHIVE ' in l or 'error:' in l + or 'ld:' in l or 'fixup' in l or 'Undefined' in l or 'Traceback' in l + ] + (output_dir / 'xcodebuild.log').write_text( + '\n'.join(tail_lines[-160:] + ['', '--- tail ---'] + full_log.splitlines()[-100:]) + '\n', + encoding='utf-8', + ) + if res.returncode != 0: + raise RuntimeError(f'xcodebuild archive failed (rc={res.returncode}):\n' + '\n'.join(full_log.splitlines()[-120:])) + print(f'[Archive] succeeded in {archive_elapsed}s', flush=True) + + print('=== [3] Verify Mach-O UUID, Route 2, L2 Audit & Clues ===', flush=True) + app_dir = archive_path / 'Products/Applications' / f'{scheme}.app' + main_bin = app_dir / scheme + dsyms_dir = archive_path / 'dSYMs' + uuids_bin = m3.uuids_of(main_bin) + uuids_dsym = m3.uuids_of(dsyms_dir / f'{scheme}.app.dSYM') + assert uuids_bin and uuids_bin == uuids_dsym, (uuids_bin, uuids_dsym) + + r2_out_dir = output_dir / 'route2' + r2_out_dir.mkdir(parents=True, exist_ok=True) + binaries, direct_total = scan_route2(app_dir, r2_out_dir, f'{scheme}_ipa') + r2_counts = {} + for info in binaries.values(): + for sl in info['slices']: + for k, v in sl['counts'].items(): + r2_counts[k] = r2_counts.get(k, 0) + v + assert len(binaries) == expected_binaries and direct_total == 0, (len(binaries), direct_total) + + interm = dd_path / f'Build/Intermediates.noindex/ArchiveIntermediates/{scheme}/IntermediateBuildFilesPath/readoor.build/Release-iphoneos/{scheme}.build' + audit_src = interm / 'ig-route2-audit/ig_obfuscation_audit.json' + shutil.copy2(audit_src, output_dir / 'ig_obfuscation_audit.json') + obf_audit = m3.verify_required_targets(audit_src, policy, expect_l1_translation=True) + if policy.get('opaque_const_targets'): + assert int(obf_audit.get('total_opaque_constants') or 0) > 0, obf_audit + if policy.get('arithmetic_targets'): + assert int(obf_audit.get('total_arithmetic_rewrites') or 0) > 0, obf_audit + if policy.get('indirect_branch_targets'): + assert int(obf_audit.get('total_indirect_branches') or 0) > 0, obf_audit + if policy.get('string_encrypt_stack_targets'): + assert int(obf_audit.get('total_strings_stack_encrypted') or 0) > 0, obf_audit + if policy.get('anti_hooking_targets'): + assert int(obf_audit.get('total_anti_hook_functions') or 0) > 0, obf_audit + if policy.get('function_outline_targets'): + assert int(obf_audit.get('total_functions_outlined') or 0) > 0, obf_audit + if policy.get('opaque_field_targets'): + assert int(obf_audit.get('total_opaque_field_access') or 0) > 0, obf_audit + if policy.get('bb_split_targets'): + assert int(obf_audit.get('total_bb_split_count') or 0) > 0, obf_audit + if policy.get('arithmetic_nonlinear_mba') or any(r.get('nonlinear_mba') for r in (policy.get('arithmetic_targets') or [])): + assert int(obf_audit.get('total_nonlinear_mba') or 0) > 0, obf_audit + if policy.get('opaque_const_opaque_zero') or any(r.get('opaque_zero') for r in (policy.get('opaque_const_targets') or [])): + assert int(obf_audit.get('total_opaque_zero') or 0) > 0, obf_audit + clues = m3.audit_m3_static_clues(main_bin, interm / 'Objects-normal/arm64', snapshot_src) + for pat, cnt in clues['main_binary_forbidden_counts'].items(): + assert cnt == 0, f'Forbidden string {pat!r} occurred {cnt}x' + + main_raw = main_bin.read_bytes() + guard_bin = app_dir / 'Frameworks/RDCoreIO.framework/RDCoreIO' + guard_raw = guard_bin.read_bytes() if guard_bin.is_file() else b'' + beacon_absent = { + 'termination_jsonl_main': main_raw.count(b'termination.jsonl') == 0, + 'terminate_json_main': main_raw.count(b'"action":"terminate"') == 0, + 'terminate_json_guard': guard_raw.count(b'"action":"terminate"') == 0, + } + assert all(beacon_absent.values()), f'Unexpected release beacon string: {beacon_absent}' + + diag_needles = { + 'cryptid==0': b'cryptid==0', + 'CS_VALID': b'CS_VALID', + 'kinfo_proc.p_flag': b'kinfo_proc.p_flag', + 'dispatch-write': b'dispatch-write', + 'dispatch-target': b'dispatch-target', + 'archive-target': b'archive-target', + 'DYLD_INSERT_LIBRARIES': b'DYLD_INSERT_LIBRARIES', + 'trampoline_zh': '跳转蹦床'.encode('utf-8'), + 'baseline_zh': '启动基线'.encode('utf-8'), + } + diag_absent = {} + for k, pat in diag_needles.items(): + diag_absent[f'main_{k}'] = main_raw.count(pat) == 0 + diag_absent[f'guard_{k}'] = guard_raw.count(pat) == 0 + assert all(diag_absent.values()), f'Unexpected release diagnostic string: {diag_absent}' + + otool_deps = subprocess.check_output(['xcrun', 'otool', '-L', str(main_bin)], text=True).splitlines() + guard_dep_lines = [l.strip() for l in otool_deps if 'RDCoreIO' in l] + dwarf_bin = dsyms_dir / f'{scheme}.app.dSYM/Contents/Resources/DWARF/{scheme}' + nm_out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_bin)], text=True).splitlines() + star_gate = verify_macho_star_cfg.verify_binary_star_cfg( + main_bin, dwarf_bin, obf_audit, require_topology='sparse_switch' + ) + print( + f"[StarCFGGate] verified={star_gate['verified_star_count']}/{star_gate['linked_checked_count']} " + f"(dead_stripped={star_gate['dead_stripped_count']}, failed={star_gate['failed_count']})", + flush=True, + ) + require_zero_kb_bl = bool(policy.get('indirect_call_targets')) + icall_gate = verify_macho_indirect_calls.analyze_macho_calls( + main_bin, + dwarf_bin, + symbol_map_path=Path(l1_info['symbol_map_path']), + require_zero_keybox_direct_bl=require_zero_kb_bl, + ) + print( + f"[IndirectCallGate] internal_bl={icall_gate['text_call_summary']['internal_text_bl']} " + f"blr={icall_gate['text_call_summary']['indirect_blr_total']} " + f"keybox_direct_xrefs={icall_gate['keybox_and_bridge_15_symbols']['total_direct_call_xrefs']}", + flush=True, + ) + assert icall_gate['gate_passed'], f"IndirectCallGate failed: {icall_gate['violations']}" + ibr_gate = verify_macho_indirect_branches.verify_binary_indirect_branches( + main_bin, dwarf_bin, obf_audit + ) + print( + f"[IndirectBranchGate] verified={ibr_gate['verified_ibr_count']}/{ibr_gate['linked_checked_count']} " + f"(dead_stripped={ibr_gate['dead_stripped_count']}, failed={ibr_gate['failed_count']})", + flush=True, + ) + if policy.get('indirect_branch_targets'): + assert ibr_gate['verified_ibr_count'] > 0, ibr_gate + anti_hook_gate = _verify_binary_anti_hook_prologues(main_bin, dwarf_bin, obf_audit) + print( + f"[AntiHookGate] verified={anti_hook_gate['verified_anti_hook_count']}/{anti_hook_gate['linked_checked_count']} " + f"(dead_stripped={anti_hook_gate['dead_stripped_count']}, failed={anti_hook_gate['failed_count']})", + flush=True, + ) + if policy.get('anti_hooking_targets'): + assert anti_hook_gate['verified_anti_hook_count'] > 0, anti_hook_gate + inlined_c_helpers_absent = {} + for helper_sym in ( + '_rd_kb_unmask_seed', '_rd_kb_unmask_prefix', + '_rd_kb_md5_transform', '_rd_kb_md5_lower_hex', + '_rd_sd_unmask_rolling', '_rd_sd_md5_transform', + '_rd_sd_md5_3part_lower_hex', + ): + inlined_c_helpers_absent[helper_sym] = not any(l.split()[-1] == helper_sym for l in nm_out if l.strip()) + assert inlined_c_helpers_absent[helper_sym], f'Expected C helper {helper_sym} to be inlined' + + obf_symbol_samples = [] + for orig, obf in list(l1_info['sample_type_mappings'].items()): + hits = [l.split()[-1] for l in nm_out if obf in l][:3] + obf_symbol_samples.append({'original': orig, 'obfuscated': obf, 'dwarf_hits': hits}) + + print('=== [4] Strip Frameworks, Sign & Export IPA + dSYMs + Maps ===', flush=True) + ipa_path = output_dir / f'{scheme}.ipa' + bundle_id, ipa_sha = _sign_and_package_ipa(app_dir, stage_dir, ipa_path, scheme) + hygiene_gate = _collect_static_hygiene_gate( + ipa_path, app_dir, main_bin, interm, scheme, Path(l1_info['symbol_map_path']) + ) + print( + f"[StaticHygieneGate] passed={hygiene_gate['passed']} " + f"exports={hygiene_gate['main_exported_defined_symbols_count']} " + f"fw_unstripped={len(hygiene_gate['embedded_frameworks_with_local_symbols'])}/{hygiene_gate['embedded_frameworks_checked']} " + f"tmp_leaks={hygiene_gate['tmp_work_path_leaks']} rel_leaks={hygiene_gate['readoor_rel_cstring_leaks_count']}", + flush=True, + ) + dsyms_zip = output_dir / 'dSYMs.zip' + if dsyms_zip.exists(): + dsyms_zip.unlink() + subprocess.run(['ditto', '-c', '-k', '--norsrc', str(dsyms_dir), str(dsyms_zip)], check=True) + + maps_dst = output_dir / 'obfuscation_maps' + if maps_dst.exists(): + shutil.rmtree(maps_dst) + maps_dst.mkdir(parents=True, exist_ok=True) + shutil.copy2(l1_info['symbol_map_path'], maps_dst / l1_info['symbol_map_path'].name) + shutil.copy2(l1_info['method_map_path'], maps_dst / l1_info['method_map_path'].name) + + summary = { + 'scheme': scheme, + 'dist_channel': dist_channel, + 'bundle_id': bundle_id, + 'seed': seed, + 'policy_stamp': policy_stamp, + 'ipa_path': str(ipa_path), + 'ipa_bytes': ipa_path.stat().st_size, + 'ipa_sha256': ipa_sha, + 'dsyms_zip_path': str(dsyms_zip), + 'main_binary_bytes': main_bin.stat().st_size, + 'main_text_bytes': m3.text_section_bytes(main_bin), + 'main_uuids': sorted(uuids_bin), + 'timings_s': { + 'l1_apply': l1_info['elapsed_s'], + 'xcode_archive': archive_elapsed, + 'total_build': round(l1_info['elapsed_s'] + archive_elapsed, 2), + }, + 'l1_obfuscation': { + 'type_mappings_count': l1_info['type_mappings_count'], + 'method_mappings_count': l1_info['method_mappings_count'], + 'sample_type_mappings': l1_info['sample_type_mappings'], + 'sample_method_mappings': l1_info['sample_method_mappings'], + 'dwarf_symbol_samples': obf_symbol_samples, + }, + 'route2': { + 'binaries': len(binaries), + 'direct_call_total': direct_total, + 'direct_call_counts': r2_counts, + 'guard_framework_deps': guard_dep_lines, + }, + 'l2_obf_audit': { + 'l1_translation_active': obf_audit.get('l1_translation_active'), + 'expected_swift_count': obf_audit.get('expected_swift_count'), + 'converted_swift_count': obf_audit.get('converted_swift_count'), + 'objc_audited_count': obf_audit.get('objc_audited_count'), + 'total_flattened': obf_audit.get('total_flattened'), + 'total_strings_encrypted': obf_audit.get('total_strings_encrypted'), + 'total_strings_stack_encrypted': int(obf_audit.get('total_strings_stack_encrypted') or 0), + 'total_objc_strings_encrypted': int(obf_audit.get('total_objc_strings_encrypted') or 0), + 'total_swift_strings_encrypted': int(obf_audit.get('total_swift_strings_encrypted') or 0), + 'total_strings_replaced': int(obf_audit.get('total_strings_replaced') or 0), + 'total_paths_scrubbed': int(obf_audit.get('total_paths_scrubbed') or 0), + 'total_indirect_calls': int(obf_audit.get('total_indirect_calls') or 0), + 'total_opaque_constants': int(obf_audit.get('total_opaque_constants') or 0), + 'total_arithmetic_rewrites': int(obf_audit.get('total_arithmetic_rewrites') or 0), + 'total_indirect_branches': int(obf_audit.get('total_indirect_branches') or 0), + 'total_anti_hook_functions': int(obf_audit.get('total_anti_hook_functions') or 0), + 'total_functions_outlined': int(obf_audit.get('total_functions_outlined') or 0), + 'total_opaque_field_access': int(obf_audit.get('total_opaque_field_access') or 0), + 'total_bb_split_count': int(obf_audit.get('total_bb_split_count') or 0), + 'total_bb_split_functions': int(obf_audit.get('total_bb_split_functions') or 0), + 'total_nonlinear_mba': int(obf_audit.get('total_nonlinear_mba') or 0), + 'total_opaque_zero': int(obf_audit.get('total_opaque_zero') or 0), + 'required_targets': obf_audit.get('required_targets'), + 'static_frameworks_obfuscated': obf_audit.get('static_frameworks_obfuscated') or [], + }, + 'macho_star_cfg_gate': star_gate, + 'macho_indirect_branch_gate': ibr_gate, + 'macho_anti_hook_gate': anti_hook_gate, + 'macho_indirect_call_gate': { + 'text_call_summary': icall_gate['text_call_summary'], + 'keybox_total_direct_call_xrefs': icall_gate['keybox_and_bridge_15_symbols']['total_direct_call_xrefs'], + 'gate_passed': icall_gate['gate_passed'], + }, + 'keybox_helpers_inlined_absent_in_dwarf': inlined_c_helpers_absent, + 'release_beacon_absent': beacon_absent, + 'defender_diag_absent': diag_absent, + 'static_clues': clues, + 'static_hygiene_gate': hygiene_gate, + } + (output_dir / 'build_summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') + if not hygiene_gate['passed']: + raise RuntimeError(f"StaticHygieneGate failed: {json.dumps(hygiene_gate, ensure_ascii=False)}") + print(f"[DONE] IPA={ipa_path} ({summary['ipa_bytes']} bytes), archive_elapsed={archive_elapsed}s", flush=True) + return summary + finally: + for d in (WORK_ROOT, CACHE_ROOT): + if d.exists(): + shutil.rmtree(d) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--scheme', default='readoor31OtherPay') + parser.add_argument('--output-dir', default=str(ROOT / 'test-results' / '20261120-readoor31OtherPay-obf-ipa')) + parser.add_argument('--seed', default='prod_otherpay_20261120') + parser.add_argument('--expected-binaries', type=int, default=42) + parser.add_argument('--dist-channel', choices=['dev', 'appstore'], default='dev') + args = parser.parse_args() + build_ipa(args.scheme, Path(args.output_dir), args.seed, args.expected_binaries, dist_channel=args.dist_channel) + + +if __name__ == '__main__': + main() diff --git a/tools/llvm_obf/ig_toolchain_resolver.py b/tools/llvm_obf/ig_toolchain_resolver.py new file mode 100755 index 0000000..22926a7 --- /dev/null +++ b/tools/llvm_obf/ig_toolchain_resolver.py @@ -0,0 +1,1385 @@ +#!/usr/bin/env python3 +"""Resolve verified standalone `opt` toolchain, self-heal on Xcode upgrades, and translate policy maps.""" +import argparse +import datetime +import fcntl +import hashlib +import json +import os +from pathlib import Path +import platform +import plistlib +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile + +SCRIPT_DIR = Path(__file__).resolve().parent +TOOLS_DIR = SCRIPT_DIR.parent +REPO_ROOT = TOOLS_DIR.parent + +DEFAULT_MANIFEST_PATH = REPO_ROOT / 'config' / 'toolchain_manifest.json' +DEFAULT_LLVM_MAP_PATH = REPO_ROOT / 'config' / 'xcode_llvm_map.json' +DEFAULT_CACHE_ROOT = Path.home() / '.cache' / 'iosguard' / 'toolchains' +DEFAULT_GIT_REMOTE = 'https://github.com/swiftlang/llvm-project.git' +_MEM_SHA_CACHE = {} + +_PASS_SOURCE_SUFFIXES = {'.cpp', '.cc', '.c', '.h', '.hpp', '.td', '.def', '.cmake', '.txt'} +_PASS_SKIP_DIR_NAMES = {'build', '__pycache__', '.git'} + + +def _log(log_fn, msg): + if log_fn is not None: + log_fn(msg) + else: + sys.stderr.write(f'{msg}\n') + sys.stderr.flush() + + +def augmented_tool_env(base_env=None): + """Return environment with Homebrew/local CLI dirs appended so launchd daemons find cmake/ninja.""" + env = dict(os.environ if base_env is None else base_env) + parts = [p for p in env.get('PATH', '').split(':') if p] + for extra in ('/opt/homebrew/bin', '/usr/local/bin'): + if extra not in parts and Path(extra).is_dir(): + parts.append(extra) + env['PATH'] = ':'.join(parts) + env.setdefault('GIT_TERMINAL_PROMPT', '0') + return env + + +def find_cli_tool(name, env=None): + """Locate CLI binary even under minimal launchd PATH.""" + eff_env = augmented_tool_env(env) + found = shutil.which(name, path=eff_env.get('PATH', '')) + if found: + return found + for cand in (Path('/opt/homebrew/bin') / name, Path('/usr/local/bin') / name, Path('/usr/bin') / name): + if cand.is_file() and os.access(cand, os.X_OK): + return str(cand) + return None + + +def file_sha256(path): + p = Path(path) + st = p.stat() + key = (str(p), st.st_mtime_ns, st.st_size) + cached = _MEM_SHA_CACHE.get(key) + if cached: + return cached + h = hashlib.sha256() + with p.open('rb') as stream: + for chunk in iter(lambda: stream.read(1 << 20), b''): + h.update(chunk) + digest = h.hexdigest() + _MEM_SHA_CACHE[key] = digest + return digest + + +def _read_plist(path): + p = Path(path) + if not p.is_file(): + return None + with p.open('rb') as f: + return plistlib.load(f) + + +def resolve_developer_dir(): + env_dev = os.environ.get('DEVELOPER_DIR', '').strip() + if env_dev and Path(env_dev).is_dir(): + return Path(env_dev) + active = subprocess.check_output(['xcode-select', '-p'], text=True).strip() + return Path(active) + + +def detect_xcode_info(developer_dir=None): + dev_dir = Path(developer_dir) if developer_dir else resolve_developer_dir() + for candidate in (dev_dir.parent / 'version.plist', dev_dir / 'version.plist'): + pl = _read_plist(candidate) + if pl and pl.get('ProductBuildVersion'): + return { + 'xcode_version': str(pl.get('CFBundleShortVersionString', '')), + 'xcode_build': str(pl.get('ProductBuildVersion', '')), + 'developer_dir': str(dev_dir), + } + env = dict(os.environ) + if developer_dir: + env['DEVELOPER_DIR'] = str(developer_dir) + out = subprocess.check_output(['xcodebuild', '-version'], env=env, text=True).splitlines() + ver = out[0].split()[-1] if out else '' + build = out[1].split()[-1] if len(out) > 1 else '' + return { + 'xcode_version': ver, + 'xcode_build': build, + 'developer_dir': str(dev_dir), + } + + +def detect_sdk_info(sdk_path=None, developer_dir=None): + if sdk_path: + p = Path(sdk_path) + pl = _read_plist(p / 'SDKSettings.plist') + if pl: + return { + 'sdk_path': str(p), + 'sdk_name': str(pl.get('CanonicalName', '')), + 'sdk_version': str(pl.get('Version', '')), + 'sdk_build': str( + pl.get('ProductBuildVersion', '') + or pl.get('DefaultProperties', {}).get('PLATFORM_PRODUCT_BUILD_VERSION', '') + ), + } + env = dict(os.environ) + if developer_dir: + env['DEVELOPER_DIR'] = str(developer_dir) + if not sdk_path: + sdk_path = subprocess.check_output( + ['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], env=env, text=True + ).strip() + pl = _read_plist(Path(sdk_path) / 'SDKSettings.plist') or {} + return { + 'sdk_path': str(sdk_path), + 'sdk_name': str(pl.get('CanonicalName', 'iphoneos')), + 'sdk_version': str(pl.get('Version', '')), + 'sdk_build': str(pl.get('ProductBuildVersion', '')), + } + + +def detect_stock_tool(tool_name, developer_dir=None, sdk=None): + dev_dir = Path(developer_dir) if developer_dir else resolve_developer_dir() + tc_bin = dev_dir / 'Toolchains' / 'XcodeDefault.xctoolchain' / 'usr' / 'bin' / tool_name + if tc_bin.is_file() and os.access(tc_bin, os.X_OK): + return str(tc_bin) + env = dict(os.environ) + if developer_dir: + env['DEVELOPER_DIR'] = str(developer_dir) + cmd = ['xcrun'] + if sdk: + cmd.extend(['--sdk', sdk]) + cmd.extend(['-f', tool_name]) + return subprocess.check_output(cmd, env=env, text=True).strip() + + +def parse_swift_version_output(text): + """Parse `swiftc --version` output into structured Swift/SwiftLang/Clang metadata.""" + first_line = next((ln.strip() for ln in (text or '').splitlines() if ln.strip()), '') + m_sw = re.search(r'Apple Swift version\s+(\d+\.\d+(?:\.\d+)?)', first_line) + if not m_sw: + m_sw = re.search(r'Swift version\s+(\d+\.\d+(?:\.\d+)?)', first_line) + swift_version = m_sw.group(1) if m_sw else '' + + m_sl = re.search(r'swiftlang-(\d+\.\d+\.\d+(?:\.\d+)*)', first_line) + raw_sl = m_sl.group(1) if m_sl else '' + sl_parts = raw_sl.split('.') + swiftlang_version = '.'.join(sl_parts[:3]) if len(sl_parts) >= 3 else raw_sl + + m_cl = re.search(r'clang-(\d+(?:\.\d+)*)', first_line) + clang_version = m_cl.group(1) if m_cl else '' + + mm_source = swift_version or swiftlang_version + mm_parts = mm_source.split('.') + swift_major_minor = '.'.join(mm_parts[:2]) if len(mm_parts) >= 2 else mm_source + + return { + 'swift_version': swift_version, + 'swiftlang_version': swiftlang_version, + 'swift_major_minor': swift_major_minor, + 'clang_version': clang_version, + 'raw': first_line, + } + + +def detect_swift_info(developer_dir=None): + swiftc_bin = detect_stock_tool('swiftc', developer_dir=developer_dir) + env = dict(os.environ) + if developer_dir: + env['DEVELOPER_DIR'] = str(developer_dir) + out = subprocess.check_output([swiftc_bin, '--version'], env=env, stderr=subprocess.DEVNULL, text=True) + return parse_swift_version_output(out) + + +def host_arch(): + m = platform.machine().lower() + if m in ('arm64', 'aarch64'): + return 'arm64' + return m + + +def compute_passes_hash(passes_dir=None): + """Compute deterministic SHA256 digest of llvm_passes C++/CMake sources; 'legacy' if absent.""" + pdir = Path(passes_dir) if passes_dir is not None else (REPO_ROOT / 'llvm_passes') + if not pdir.is_dir(): + return 'legacy' + + entries = [] + for path in pdir.rglob('*'): + if not path.is_file(): + continue + rel = path.relative_to(pdir) + if any(part.startswith('.') or part in _PASS_SKIP_DIR_NAMES for part in rel.parts): + continue + if path.suffix not in _PASS_SOURCE_SUFFIXES: + continue + entries.append((rel.as_posix(), path)) + + if not entries: + return 'legacy' + + entries.sort(key=lambda item: item[0]) + h = hashlib.sha256() + for rel_posix, path in entries: + h.update(rel_posix.encode('utf-8')) + h.update(b'\x00') + h.update(path.read_bytes()) + return h.hexdigest() + + +def verify_portability(opt_path): + out = subprocess.check_output(['otool', '-L', str(opt_path)], text=True) + bad = [] + for line in out.splitlines()[1:]: + dep = line.strip().split(' ', 1)[0] + if not dep: + continue + if not dep.startswith('/usr/lib/'): + bad.append(dep) + if bad: + raise RuntimeError(f'Built opt links non-system dylibs: {bad}\nFull otool -L:\n{out}') + + +def _run_smoke_cmd(cmd, env): + res = subprocess.run(cmd, env=env, capture_output=True, text=True) + if res.returncode != 0: + raise RuntimeError( + f'Smoke command failed (rc={res.returncode}): {" ".join(cmd)}\n' + f'{res.stdout[-1000:]}\n{res.stderr[-1500:]}' + ) + return res + + +def smoke_test_opt(opt_path, developer_dir=None): + """Run C + Swift async/ThinLTO bitcode obfuscation & backend lowering smoke test.""" + clang_bin = detect_stock_tool('clang', developer_dir=developer_dir) + swiftc_bin = detect_stock_tool('swiftc', developer_dir=developer_dir) + sdk = detect_sdk_info(developer_dir=developer_dir)['sdk_path'] + env = dict(os.environ) + if developer_dir: + env['DEVELOPER_DIR'] = str(developer_dir) + + with tempfile.TemporaryDirectory(prefix='igopt-smoke-') 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': 'smoke'}], + 'string_encrypt_stack_targets': [{'path_contains': 'smoke'}], + 'opaque_const_targets': [{'path_contains': 'smoke', 'opaque_zero': True}], + 'arithmetic_targets': [{'path_contains': 'smoke', 'nonlinear_mba': True}], + 'indirect_call_targets': [{'path_contains': 'smoke'}], + 'indirect_call_dual_table': True, + 'indirect_call_same_image_prefixes': ['ext_'], + 'flatten_targets': [{'path_contains': 'smoke'}], + 'indirect_branch_targets': [{'path_contains': 'smoke'}], + 'anti_hooking_targets': [{'path_contains': 'smoke'}], + 'function_outline_min_insts': 2, + 'function_outline_targets': [{'path_contains': 'smoke'}], + 'opaque_field_targets': [{'path_contains': 'smoke'}], + 'bb_split_min_insts': 4, + 'bb_split_targets': [{'path_contains': 'smoke'}], + }), encoding='utf-8') + + # 1. C smoke test + (p / 'smoke.c').write_text( + '#include \n' + 'extern int ext_a(int);\n' + 'extern int ext_b(int);\n' + 'struct smoke_box { int tag; int val; int acc; };\n' + 'static int g_smoke_state = 11;\n' + 'int check_flag(int x, struct smoke_box *box) {\n' + ' const char *v = getenv("DYLD_INSERT_LIBRARIES");\n' + ' int r = g_smoke_state;\n' + ' if (v && x > 10) {\n' + ' int t = (box->val * 3) ^ (box->acc + 7);\n' + ' r += ext_a(x + t);\n' + ' }\n' + ' if (x < 0) r += ext_b(x);\n' + ' if (r > 5) return r;\n' + ' return r + 1;\n' + '}\n', + encoding='utf-8', + ) + _run_smoke_cmd([ + clang_bin, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, + '-Os', '-g', '-emit-llvm', '-c', str(p / 'smoke.c'), '-o', str(p / 'smoke_c.bc'), + ], env=env) + _run_smoke_cmd([ + str(opt_path), + '-passes=ig-obfuscate', + f'--ig-policy={policy_path}', + '--ig-mode=full', + '--ig-seed=smoke_seed_1', + f'--ig-source-path={p / "smoke.c"}', + f'--ig-audit-out={p / "audit_c.json"}', + str(p / 'smoke_c.bc'), + '-o', str(p / 'smoke_c.obf.bc'), + ], env=env) + _run_smoke_cmd([ + clang_bin, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, + '-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', + '-x', 'ir', '-c', str(p / 'smoke_c.obf.bc'), '-o', str(p / 'smoke_c.o'), + ], env=env) + audit_c = json.loads((p / 'audit_c.json').read_text(encoding='utf-8')) + assert audit_c['strings_encrypted_count'] >= 1, 'Expected >=1 C string encrypted' + assert audit_c['opaque_constants_count'] >= 1, 'Expected >=1 C opaque constant' + assert audit_c['arithmetic_rewrites_count'] >= 1, 'Expected >=1 C MBA arithmetic rewrite' + assert audit_c['indirect_calls_count'] >= 2, 'Expected >=2 C indirect calls' + assert len(audit_c['functions_flattened']) >= 1, 'Expected >=1 C function flattened' + assert audit_c['indirect_branches_count'] >= 1, 'Expected >=1 C indirect branch' + assert audit_c['anti_hook_functions_count'] >= 1, 'Expected >=1 C anti-hook function' + assert audit_c['functions_outlined_count'] >= 1, 'Expected >=1 C function outlined' + assert audit_c['opaque_field_access_count'] >= 2, 'Expected >=2 C opaque field/global accesses' + assert audit_c['nonlinear_mba_count'] >= 1, 'Expected >=1 C nonlinear MBA rewrite' + assert audit_c['opaque_zero_count'] >= 1, 'Expected >=1 C OpaqueZero constant' + assert audit_c['bb_split_count'] >= 1, 'Expected >=1 C basic block split' + + # 2. Swift async throws smoke test + (p / 'smoke.swift').write_text( + 'import Foundation\n' + '@inline(never) public func sw_sink(_ x: Int) -> Int { return x ^ 0x55 }\n' + 'public func swiftDecision(_ a: Int) -> Int {\n' + ' let r = getenv("DYLD_INSERT_LIBRARIES")\n' + ' var acc = 0\n' + ' if r != nil && a > 5 { acc += sw_sink(a) }\n' + ' if a < 0 { acc -= sw_sink(-a) }\n' + ' if acc > 10 { return acc }\n' + ' return acc + 1\n' + '}\n' + 'public func swiftAsync(_ v: Int) async throws -> Int {\n' + ' try await Task.sleep(nanoseconds: 1000)\n' + ' return swiftDecision(v)\n' + '}\n', + encoding='utf-8', + ) + _run_smoke_cmd([ + swiftc_bin, '-sdk', sdk, '-target', 'arm64-apple-ios15.0', + '-O', '-g', '-lto=llvm-thin', '-parse-as-library', + '-c', str(p / 'smoke.swift'), '-o', str(p / 'smoke_sw.bc'), + ], env=env) + _run_smoke_cmd([ + str(opt_path), + '-passes=default,ig-obfuscate', + f'--ig-policy={policy_path}', + '--ig-mode=full', + '--ig-seed=smoke_seed_1', + f'--ig-source-path={p / "smoke.swift"}', + f'--ig-audit-out={p / "audit_sw.json"}', + str(p / 'smoke_sw.bc'), + '-o', str(p / 'smoke_sw.obf.bc'), + ], env=env) + _run_smoke_cmd([ + clang_bin, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, + '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', + '-x', 'ir', '-c', str(p / 'smoke_sw.obf.bc'), '-o', str(p / 'smoke_sw.o'), + ], env=env) + audit_sw = json.loads((p / 'audit_sw.json').read_text(encoding='utf-8')) + assert audit_sw['strings_encrypted_count'] >= 1, 'Expected >=1 Swift C string encrypted' + assert audit_sw['opaque_constants_count'] >= 1, 'Expected >=1 Swift opaque constant' + assert audit_sw['arithmetic_rewrites_count'] >= 1, 'Expected >=1 Swift MBA arithmetic rewrite' + assert audit_sw['indirect_calls_count'] >= 1, 'Expected >=1 Swift indirect call' + assert len(audit_sw['functions_flattened']) >= 1, 'Expected >=1 Swift function flattened' + assert audit_sw['indirect_branches_count'] >= 1, 'Expected >=1 Swift indirect branch' + + return {'c_audit': audit_c, 'swift_audit': audit_sw} + + +def _semver_key(ver_str): + return tuple(int(p) if p.isdigit() else 0 for p in re.findall(r'\d+', ver_str or '')) + + +def resolve_llvm_branch_for_swift(swift_info, xcode_info=None, map_path=None, git_remote=None): + """Resolve `swiftlang/llvm-project` release branch or tag matching active Swift compiler.""" + map_p = Path(map_path) if map_path is not None else DEFAULT_LLVM_MAP_PATH + xc_build = str((xcode_info or {}).get('xcode_build', '') or '') + swiftlang = str((swift_info or {}).get('swiftlang_version', '') or '') + swift_mm = str((swift_info or {}).get('swift_major_minor', '') or '') + + if map_p.is_file(): + try: + ovr = json.loads(map_p.read_text(encoding='utf-8')) + if xc_build and xc_build in (ovr.get('by_xcode_build') or {}): + return ovr['by_xcode_build'][xc_build] + if swiftlang and swiftlang in (ovr.get('by_swiftlang') or {}): + return ovr['by_swiftlang'][swiftlang] + if swift_mm and swift_mm in (ovr.get('by_swift_major_minor') or {}): + return ovr['by_swift_major_minor'][swift_mm] + except Exception: + pass + + remote = (git_remote or os.environ.get('IG_LLVM_GIT_MIRROR') or DEFAULT_GIT_REMOTE).strip() + env = augmented_tool_env() + ls_out = subprocess.check_output( + ['git', 'ls-remote', '--heads', '--tags', remote], + env=env, + text=True, + timeout=30, + ) + heads = set() + tags = set() + for line in ls_out.splitlines(): + parts = line.split() + if len(parts) < 2: + continue + ref = parts[1] + if ref.endswith('^{}'): + continue + if ref.startswith('refs/heads/'): + heads.add(ref[len('refs/heads/'):]) + elif ref.startswith('refs/tags/'): + tags.add(ref[len('refs/tags/'):]) + + for cand in ( + f'swift/release/{swiftlang}' if swiftlang else '', + f'swift/release/{swift_mm}' if swift_mm else '', + f'swift/release/{swift_mm}.0' if swift_mm else '', + ): + if cand and cand in heads: + return cand + + if swift_mm: + head_pat = re.compile(rf'^swift/release/{re.escape(swift_mm)}(?:\.(\d+))?$') + matched_heads = [h for h in heads if head_pat.match(h)] + if matched_heads: + return max(matched_heads, key=_semver_key) + + if swiftlang: + tag_exact = f'swift-{swiftlang}-RELEASE' + if tag_exact in tags: + return tag_exact + if swift_mm: + tag_pat = re.compile(rf'^swift-{re.escape(swift_mm)}(?:\.\d+)*-RELEASE$') + matched_tags = [t for t in tags if tag_pat.match(t)] + if matched_tags: + return max(matched_tags, key=_semver_key) + + raise RuntimeError( + f'Unable to resolve matching swiftlang/llvm-project branch for swift={swift_info} (xcode_build={xc_build}) from {remote}' + ) + + +def _verify_cached_binary(opt_path, expected_sha256): + if not opt_path.is_file() or not os.access(opt_path, os.X_OK): + return False + marker = opt_path.parent.parent / '.verified.json' + st = opt_path.stat() + if marker.is_file(): + try: + meta = json.loads(marker.read_text(encoding='utf-8')) + if ( + meta.get('sha256') == expected_sha256 + and meta.get('size') == st.st_size + and meta.get('mtime_ns') == st.st_mtime_ns + ): + return True + except Exception: + pass + actual = file_sha256(opt_path) + if actual != expected_sha256: + return False + marker.write_text( + json.dumps( + { + 'sha256': actual, + 'size': st.st_size, + 'mtime_ns': st.st_mtime_ns, + }, + indent=2, + ) + + '\n', + encoding='utf-8', + ) + return True + + +def _write_verified_marker(opt_path, expected_sha256): + st = opt_path.stat() + marker = opt_path.parent.parent / '.verified.json' + marker.write_text( + json.dumps( + { + 'sha256': expected_sha256, + 'size': st.st_size, + 'mtime_ns': st.st_mtime_ns, + }, + indent=2, + ) + + '\n', + encoding='utf-8', + ) + + +def _versioned_dir_name(xcode_build, arch, passes_hash): + if passes_hash and passes_hash != 'legacy': + return f'{xcode_build}-{arch}-{passes_hash[:8]}' + return f'{xcode_build}-{arch}' + + +def _verify_meta_dir(target_dir, expected_passes_hash=None): + meta_p = Path(target_dir) / 'meta.json' + opt_bin = Path(target_dir) / 'bin' / 'opt' + if not meta_p.is_file(): + return None + try: + meta = json.loads(meta_p.read_text(encoding='utf-8')) + except Exception: + return None + if not isinstance(meta, dict): + return None + expected_sha = meta.get('opt_sha256') + if not expected_sha: + return None + if expected_passes_hash is not None and meta.get('passes_hash') != expected_passes_hash: + return None + if not _verify_cached_binary(opt_bin, expected_sha): + return None + return meta + + +def _extract_bundle(bundle_path, target_dir, expected_sha256): + bundle_p = Path(os.path.expanduser(str(bundle_path))) + if not bundle_p.is_file(): + raise FileNotFoundError(f'Missing igopt bundle at {bundle_p}') + target_dir.parent.mkdir(parents=True, exist_ok=True) + lock_path = target_dir.parent / f'.{target_dir.name}.lock' + with lock_path.open('w') as lockf: + fcntl.flock(lockf, fcntl.LOCK_EX) + opt_bin = target_dir / 'bin' / 'opt' + if _verify_cached_binary(opt_bin, expected_sha256): + return opt_bin + with tempfile.TemporaryDirectory(prefix='.igopt-extract-', dir=target_dir.parent) as tmp: + stage = Path(tmp) / 'stage' + stage.mkdir() + with tarfile.open(bundle_p, 'r:gz') as tf: + for member in tf.getmembers(): + mp = Path(member.name) + if mp.is_absolute() or '..' in mp.parts or member.issym() or member.islnk(): + raise ValueError(f'Unsafe archive member in {bundle_p}: {member.name}') + tf.extractall(stage) + stage_opt = stage / 'bin' / 'opt' + if not stage_opt.is_file(): + raise FileNotFoundError(f'Extracted bundle missing bin/opt: {bundle_p}') + stage_opt.chmod(0o755) + actual = file_sha256(stage_opt) + if actual != expected_sha256: + raise RuntimeError( + f'Extracted opt SHA256 mismatch: expected {expected_sha256}, got {actual}' + ) + if target_dir.exists(): + shutil.rmtree(target_dir) + stage.rename(target_dir) + if not _verify_cached_binary(opt_bin, expected_sha256): + raise RuntimeError(f'Failed to verify extracted opt at {opt_bin}') + return opt_bin + + +def _resolve_manifest_path(manifest_path=None): + if manifest_path is not None: + return Path(manifest_path) + manifest_p = Path(os.environ.get('IG_TOOLCHAIN_MANIFEST') or DEFAULT_MANIFEST_PATH) + if not manifest_p.is_file(): + alt = REPO_ROOT / 'config' / 'toolchain_manifest.json' + if alt.is_file(): + manifest_p = alt + return manifest_p + + +def prune_old_toolchains(cache_root, keep=3, current_dir_name=None): + """Delete oldest cached toolchain directories beyond `keep` while preserving current_dir_name.""" + root = Path(cache_root) + if not root.is_dir(): + return [] + keep_n = max(1, int(keep)) + candidates = [] + for entry in root.iterdir(): + if not entry.is_dir() or entry.name.startswith('.'): + continue + if current_dir_name and entry.name == current_dir_name: + continue + meta_p = entry / 'meta.json' + try: + mtime = meta_p.stat().st_mtime_ns if meta_p.is_file() else entry.stat().st_mtime_ns + except OSError: + mtime = 0 + candidates.append((mtime, entry)) + + candidates.sort(key=lambda item: item[0], reverse=True) + retain_others = max(0, keep_n - (1 if current_dir_name else 0)) + removed = [] + for _, old_dir in candidates[retain_others:]: + shutil.rmtree(old_dir, ignore_errors=True) + removed.append(old_dir.name) + return removed + + +def _failure_marker_path(cache_root, xcode_build, arch, passes_hash): + h8 = passes_hash[:8] if passes_hash != 'legacy' else 'legacy' + return Path(cache_root) / '.locks' / f'failed_{xcode_build}_{arch}_{h8}.json' + + +def _gather_l2_candidates(root, xcode_build, arch, swift_mm, passes_hash, manifest_p, default_cache_root): + """Collect candidate opt binaries matching passes_hash ordered by Swift compatibility & recency.""" + h8 = passes_hash[:8] if passes_hash != 'legacy' else 'legacy' + scored = [] + if root.is_dir(): + suffix = f'-{arch}-{h8}' if passes_hash != 'legacy' else f'-{arch}' + for entry in root.iterdir(): + if not entry.is_dir() or entry.name.startswith('.'): + continue + if not entry.name.endswith(suffix): + continue + meta = _verify_meta_dir(entry, expected_passes_hash=passes_hash) + if not meta: + continue + same_mm = 1 if (swift_mm and meta.get('swift_major_minor') == swift_mm) else 0 + try: + mtime = (entry / 'meta.json').stat().st_mtime_ns + except OSError: + mtime = 0 + scored.append((same_mm, mtime, entry / 'bin' / 'opt', meta['opt_sha256'], entry.name, None)) + + scored.sort(key=lambda item: (item[0], item[1]), reverse=True) + results = [] + seen_sha = set() + for _, _, opt_bin, opt_sha, label, legacy_info in scored: + if opt_sha not in seen_sha: + seen_sha.add(opt_sha) + results.append((opt_bin, opt_sha, label, legacy_info)) + + # Legacy toolchain_manifest.json seed support (exact build dir in root or default_cache_root) + if manifest_p and manifest_p.is_file(): + try: + manifest = json.loads(manifest_p.read_text(encoding='utf-8')) + toolchains = manifest.get('toolchains') or {} + seed_bases = [root] + def_root = Path(default_cache_root) if default_cache_root else DEFAULT_CACHE_ROOT + if def_root != root: + seed_bases.append(def_root) + for tc_key, entry in toolchains.items(): + if not isinstance(entry, dict): + continue + if entry.get('host_arch', 'arm64') != arch: + continue + if entry.get('passes_hash') and entry['passes_hash'] != passes_hash: + continue + xc_b = entry.get('xcode_build') or tc_key.split(':', 1)[0] + exp_sha = entry.get('opt_sha256') + if not exp_sha or exp_sha in seen_sha: + continue + for base in seed_bases: + cand_dir = base / f'{xc_b}-{arch}' + cand_opt = cand_dir / 'bin' / 'opt' + if _verify_cached_binary(cand_opt, exp_sha): + seen_sha.add(exp_sha) + results.append((cand_opt, exp_sha, f'legacy:{cand_dir.name}', entry)) + break + bundle_loc = entry.get('bundle_path') or '' + if bundle_loc and base == def_root: + bp = Path(os.path.expanduser(str(bundle_loc))) + if bp.is_file(): + try: + extracted = _extract_bundle(bp, cand_dir, exp_sha) + seen_sha.add(exp_sha) + results.append((extracted, exp_sha, f'bundle:{cand_dir.name}', entry)) + break + except Exception: + pass + except Exception: + pass + + return results + + +def ensure_opt( + cache_root=None, + developer_dir=None, + passes_dir=None, + git_remote=None, + jobs=None, + keep_versions=3, + force_rebuild=False, + allow_rebuild=True, + log_fn=None, + manifest_path=None, + default_cache_root=None, +): + """Ensure a smoke-tested `opt` matching active Xcode & llvm_passes is ready in cache_root.""" + root = Path(os.path.expanduser(str(cache_root or os.environ.get('IG_TOOLCHAIN_CACHE_DIR') or DEFAULT_CACHE_ROOT))) + pdir = Path(passes_dir) if passes_dir is not None else (REPO_ROOT / 'llvm_passes') + xc = detect_xcode_info(developer_dir) + swift_info = detect_swift_info(developer_dir) + arch = host_arch() + passes_hash = compute_passes_hash(pdir) + xc_build = xc['xcode_build'] + target_name = _versioned_dir_name(xc_build, arch, passes_hash) + target_dir = root / target_name + key = f'{xc_build}:{arch}' + manifest_p = _resolve_manifest_path(manifest_path) + + locks_dir = root / '.locks' + locks_dir.mkdir(parents=True, exist_ok=True) + lock_path = locks_dir / 'toolchain_update.lock' + fail_marker = _failure_marker_path(root, xc_build, arch, passes_hash) + + with lock_path.open('w') as lockf: + fcntl.flock(lockf, fcntl.LOCK_EX) + + # L1: Exact cached match + if not force_rebuild: + meta = _verify_meta_dir(target_dir, expected_passes_hash=passes_hash) + if meta: + return { + 'opt_path': str(target_dir / 'bin' / 'opt'), + 'opt_sha256': meta['opt_sha256'], + 'xcode': xc, + 'swift': swift_info, + 'arch': arch, + 'key': key, + 'passes_hash': passes_hash, + 'passes_hash8': passes_hash[:8], + 'target_dir': str(target_dir), + 'source_mode': 'cached', + 'updated': False, + 'meta': meta, + } + + if force_rebuild and fail_marker.is_file(): + fail_marker.unlink(missing_ok=True) + elif fail_marker.is_file(): + try: + finfo = json.loads(fail_marker.read_text(encoding='utf-8')) + raise RuntimeError( + f"[IGLLVM] Circuit breaker active for {key} (passes={passes_hash[:8]}) " + f"since {finfo.get('failed_at')}: {finfo.get('error_summary')}. " + f"Fix llvm_passes or run with --force-rebuild to retry." + ) + except json.JSONDecodeError: + fail_marker.unlink(missing_ok=True) + + # L2: Compatible opt reuse + real C & Swift Bitcode smoke test + if not force_rebuild: + candidates = _gather_l2_candidates( + root, xc_build, arch, swift_info.get('swift_major_minor', ''), passes_hash, manifest_p, default_cache_root + ) + for cand_opt, cand_sha, cand_label, legacy_entry in candidates: + _log(log_fn, f'[IGLLVM] Testing cached opt candidate ({cand_label}) for Xcode {xc_build}...') + try: + verify_portability(cand_opt) + smoke_test_opt(cand_opt, developer_dir=developer_dir) + except Exception as exc: + _log(log_fn, f'[IGLLVM] Candidate {cand_label} failed compatibility smoke test: {exc}') + continue + + with tempfile.TemporaryDirectory(prefix='.igopt-stage-', dir=root) as td: + stage = Path(td) / 'stage' + (stage / 'bin').mkdir(parents=True) + stage_opt = stage / 'bin' / 'opt' + shutil.copy2(cand_opt, stage_opt) + stage_opt.chmod(0o755) + actual_sha = file_sha256(stage_opt) + if actual_sha != cand_sha: + raise RuntimeError(f'Copied opt SHA256 mismatch: {actual_sha} != {cand_sha}') + meta_out = { + 'schema_version': 1, + 'xcode_version': xc['xcode_version'], + 'xcode_build': xc_build, + 'swift_version': swift_info.get('swift_version', ''), + 'swiftlang_version': swift_info.get('swiftlang_version', ''), + 'swift_major_minor': swift_info.get('swift_major_minor', ''), + 'arch': arch, + 'passes_hash': passes_hash, + 'opt_sha256': actual_sha, + 'source_mode': 'reused', + 'reused_from': cand_label, + 'llvm_branch': (legacy_entry or {}).get('llvm_branch', ''), + 'llvm_commit': (legacy_entry or {}).get('llvm_commit', ''), + 'smoke_passed_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), + } + (stage / 'meta.json').write_text(json.dumps(meta_out, indent=2) + '\n', encoding='utf-8') + _write_verified_marker(stage_opt, actual_sha) + if target_dir.exists(): + shutil.rmtree(target_dir) + stage.rename(target_dir) + + fail_marker.unlink(missing_ok=True) + pruned = prune_old_toolchains(root, keep=keep_versions, current_dir_name=target_dir.name) + _log(log_fn, f'[IGLLVM] Reused & verified opt from {cand_label} -> {target_dir}') + return { + 'opt_path': str(target_dir / 'bin' / 'opt'), + 'opt_sha256': actual_sha, + 'xcode': xc, + 'swift': swift_info, + 'arch': arch, + 'key': key, + 'passes_hash': passes_hash, + 'passes_hash8': passes_hash[:8], + 'target_dir': str(target_dir), + 'source_mode': 'reused', + 'reused_from': cand_label, + 'pruned': pruned, + 'updated': True, + 'meta': meta_out, + } + + # L4: Rebuild standalone opt from swiftlang/llvm-project + if not allow_rebuild: + raise RuntimeError(f'[IGLLVM] No compatible cached opt found for {key} (passes={passes_hash[:8]}) and rebuild is disabled') + + if not (pdir / 'CMakeLists.txt').is_file(): + raise FileNotFoundError(f'[IGLLVM] Missing llvm_passes source at {pdir}; cannot rebuild opt') + if not find_cli_tool('cmake'): + raise RuntimeError('[IGLLVM] cmake not found on PATH (/opt/homebrew/bin, /usr/local/bin); cannot rebuild opt') + + remote = (git_remote or os.environ.get('IG_LLVM_GIT_MIRROR') or DEFAULT_GIT_REMOTE).strip() + resolved_branch = '' + try: + resolved_branch = resolve_llvm_branch_for_swift(swift_info, xcode_info=xc, git_remote=remote) + _log(log_fn, f'[IGLLVM] Rebuilding opt for Xcode {xc["xcode_version"]} ({xc_build}) from {remote} @ {resolved_branch}...') + import build_igopt_local # lazy import avoids circular dependency + + mirror_dir = root.parent / 'llvm-src-mirror' + res = build_igopt_local.build_opt( + branch=resolved_branch, + keep_work=False, + jobs=jobs, + git_remote=remote, + cache_dir=root, + mirror_dir=mirror_dir, + passes_dir=pdir, + developer_dir=developer_dir, + update_manifest=False, + log_fn=log_fn, + ) + except Exception as exc: + err_text = str(exc)[-3000:] + fail_marker.write_text( + json.dumps( + { + 'xcode_version': xc['xcode_version'], + 'xcode_build': xc_build, + 'swift': swift_info, + 'arch': arch, + 'passes_hash': passes_hash, + 'llvm_branch': resolved_branch, + 'failed_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'error_summary': err_text, + }, + ensure_ascii=False, + indent=2, + ) + + '\n', + encoding='utf-8', + ) + raise + + fail_marker.unlink(missing_ok=True) + pruned = prune_old_toolchains(root, keep=keep_versions, current_dir_name=target_dir.name) + meta_out = res.get('meta') or _verify_meta_dir(target_dir, expected_passes_hash=passes_hash) or {} + return { + 'opt_path': str(target_dir / 'bin' / 'opt'), + 'opt_sha256': res['opt_sha256'], + 'xcode': xc, + 'swift': swift_info, + 'arch': arch, + 'key': key, + 'passes_hash': passes_hash, + 'passes_hash8': passes_hash[:8], + 'target_dir': str(target_dir), + 'llvm_branch': resolved_branch, + 'source_mode': 'built', + 'pruned': pruned, + 'updated': True, + 'meta': meta_out, + } + + +def check_toolchain_status(cache_root=None, developer_dir=None, passes_dir=None, manifest_path=None): + """Read-only inspection of current Xcode/Swift/opt cache readiness and circuit-breaker state.""" + root = Path(os.path.expanduser(str(cache_root or os.environ.get('IG_TOOLCHAIN_CACHE_DIR') or DEFAULT_CACHE_ROOT))) + pdir = Path(passes_dir) if passes_dir is not None else (REPO_ROOT / 'llvm_passes') + xc = detect_xcode_info(developer_dir) + swift_info = detect_swift_info(developer_dir) + arch = host_arch() + passes_hash = compute_passes_hash(pdir) + target_dir = root / _versioned_dir_name(xc['xcode_build'], arch, passes_hash) + meta = _verify_meta_dir(target_dir, expected_passes_hash=passes_hash) + legacy_info = None + if meta is None: + legacy_res = resolve_opt( + manifest_path=manifest_path, + cache_root=root, + developer_dir=developer_dir, + require_obf=False, + passes_dir=pdir, + allow_auto_update=False, + ) + if legacy_res.get('opt_path'): + legacy_info = legacy_res + + fail_marker = _failure_marker_path(root, xc['xcode_build'], arch, passes_hash) + cb_info = None + if fail_marker.is_file(): + try: + cb_info = json.loads(fail_marker.read_text(encoding='utf-8')) + except Exception: + cb_info = {'raw_path': str(fail_marker)} + + cached_versions = [] + if root.is_dir(): + cached_versions = sorted( + d.name for d in root.iterdir() + if d.is_dir() and not d.name.startswith('.') + ) + + ready = meta is not None + opt_path = str(target_dir / 'bin' / 'opt') if ready else (legacy_info.get('opt_path') if legacy_info else None) + return { + 'xcode': xc, + 'swift': swift_info, + 'arch': arch, + 'passes_hash': passes_hash, + 'passes_hash8': passes_hash[:8], + 'cache_root': str(root), + 'target_dir': str(target_dir), + 'ready': ready, + 'legacy_fallback_ready': legacy_info is not None, + 'opt_path': opt_path, + 'meta': meta, + 'circuit_breaker': cb_info, + 'cached_versions': cached_versions, + } + + +def resolve_opt( + manifest_path=None, + cache_root=None, + developer_dir=None, + require_obf=None, + passes_dir=None, + allow_auto_update=None, +): + if require_obf is None: + require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' + if allow_auto_update is None: + allow_auto_update = os.environ.get('IG_AUTO_UPDATE_OPT') == '1' + + xc = detect_xcode_info(developer_dir) + arch = host_arch() + key = f"{xc['xcode_build']}:{arch}" + root = Path(os.path.expanduser(str(cache_root or os.environ.get('IG_TOOLCHAIN_CACHE_DIR') or DEFAULT_CACHE_ROOT))) + pdir = Path(passes_dir) if passes_dir is not None else (REPO_ROOT / 'llvm_passes') + passes_hash = compute_passes_hash(pdir) + + # 1. Fast read-only versioned cache lookup (<5ms; no lock/smoke/network) + if passes_hash != 'legacy': + v_dir = root / _versioned_dir_name(xc['xcode_build'], arch, passes_hash) + v_meta = _verify_meta_dir(v_dir, expected_passes_hash=passes_hash) + if v_meta: + return { + 'opt_path': str(v_dir / 'bin' / 'opt'), + 'opt_sha256': v_meta['opt_sha256'], + 'xcode': xc, + 'arch': arch, + 'key': key, + 'passes_hash': passes_hash, + 'source_mode': 'cached', + 'meta': v_meta, + } + + # 2. Backward-compatible manifest lookup + manifest_p = _resolve_manifest_path(manifest_path) + if manifest_p.is_file(): + manifest = json.loads(manifest_p.read_text(encoding='utf-8')) + entry = (manifest.get('toolchains') or {}).get(key) + if entry and (not entry.get('passes_hash') or entry.get('passes_hash') == passes_hash): + expected_sha = entry['opt_sha256'] + target_dir = root / f"{xc['xcode_build']}-{arch}" + opt_bin = target_dir / 'bin' / 'opt' + + if _verify_cached_binary(opt_bin, expected_sha): + return { + 'opt_path': str(opt_bin), + 'opt_sha256': expected_sha, + 'xcode': xc, + 'arch': arch, + 'key': key, + 'entry': entry, + 'source_mode': 'manifest_cached', + } + + # Optional read-only bundle fallback if bundle exists on disk + bundle_loc = entry.get('bundle_path') or '' + if bundle_loc and Path(os.path.expanduser(str(bundle_loc))).is_file(): + opt_bin = _extract_bundle(bundle_loc, target_dir, expected_sha) + return { + 'opt_path': str(opt_bin), + 'opt_sha256': expected_sha, + 'xcode': xc, + 'arch': arch, + 'key': key, + 'entry': entry, + 'source_mode': 'bundle_cached', + } + + # 3. Optional explicit self-healing path + if allow_auto_update: + return ensure_opt( + cache_root=root, + developer_dir=developer_dir, + passes_dir=pdir, + manifest_path=manifest_p, + ) + + msg = f'[IGLLVM] No verified opt toolchain ready for {key} (passes={passes_hash[:8]}) in {root}' + if not manifest_p.is_file(): + msg = f'[IGLLVM] Manifest not found at {manifest_p} and no cached versioned opt for {key} (passes={passes_hash[:8]})' + if require_obf: + raise RuntimeError(msg) + return {'opt_path': None, 'xcode': xc, 'arch': arch, 'key': key, 'warning': msg} + + +def discover_active_app_repo(hint_paths=(), fallback_root=None): + """Find active app repo root (SRCROOT or parent holding obfuscation_maps/readoor.xcodeproj).""" + srcroot = os.environ.get('SRCROOT', '').strip() + if srcroot: + p = Path(srcroot).resolve() + if p.is_dir(): + return p + for hint in hint_paths or (): + if not hint: + continue + hp = Path(hint) + parents = [hp] + list(hp.parents) + for parent in parents: + if (parent / 'obfuscation_maps').is_dir() or (parent / 'readoor.xcodeproj').exists(): + return parent + if fallback_root is not None: + return Path(fallback_root) + return None + + +def _unwrap_l1_mappings(raw_payload): + if not isinstance(raw_payload, dict): + return {} + if isinstance(raw_payload.get('mappings'), dict) and ( + 'schema_version' in raw_payload or raw_payload.get('kind') in ('symbol_map', 'method_map') + ): + return raw_payload['mappings'] + return raw_payload + + +def _pick_latest_map(files, target_name=''): + if not files: + return None + if target_name: + exact = [p for p in files if f'_{target_name}_' in p.name or p.name.startswith(f'{target_name}_')] + if exact: + files = exact + return max(files, key=lambda p: (p.stat().st_mtime_ns, p.name)) + + +def _find_l1_map_files(app_repo): + """Locate latest (sym_file, meth_file) under app_repo/obfuscation_maps without parsing JSON.""" + if app_repo is None: + return None, None + maps_dir = Path(app_repo) / 'obfuscation_maps' + if not maps_dir.is_dir(): + return None, None + + target_name = os.environ.get('TARGET_NAME', '').strip() + sym_candidates = [p for p in sorted(maps_dir.glob('symbol_map_*.json')) if p.is_file()] + if not sym_candidates: + sym_candidates = [ + p for p in sorted(maps_dir.glob('*.json')) + if p.is_file() + and not p.name.startswith(('method_map', 'ig_', 'symbol_map')) + and p.name != 'unmapped_mappings.json' + ] + meth_candidates = [p for p in sorted(maps_dir.glob('method_map_*.json')) if p.is_file()] + return _pick_latest_map(sym_candidates, target_name), _pick_latest_map(meth_candidates, target_name) + + +def load_l1_forward_symbol_map(app_repo): + """Build forward map (orig -> obf) from app_repo/obfuscation_maps/{symbol_map,method_map}_*.json.""" + sym_file, meth_file = _find_l1_map_files(app_repo) + if sym_file is None and meth_file is None: + return {}, '' + + forward = {} + if sym_file and sym_file.is_file(): + try: + entries = _unwrap_l1_mappings(json.loads(sym_file.read_text(encoding='utf-8'))) + for orig, val in entries.items(): + if not isinstance(orig, str) or not orig: + continue + if isinstance(val, str) and val: + forward[orig] = val + elif isinstance(val, dict) and isinstance(val.get('obfuscated'), str) and val['obfuscated']: + forward[orig] = val['obfuscated'] + except Exception: + pass + + if meth_file and meth_file.is_file(): + try: + entries = _unwrap_l1_mappings(json.loads(meth_file.read_text(encoding='utf-8'))) + for orig, val in entries.items(): + if not isinstance(orig, str) or not orig: + continue + if isinstance(val, str) and val: + forward[orig] = val + if ':' in orig: + forward.setdefault(orig.split(':', 1)[0], f'{val}_1') + elif isinstance(val, dict): + kind = val.get('kind') + if kind == 'swift_signature': + continue + obf_full = val.get('obfuscated') + tok = val.get('token') + parts = val.get('parts') + if isinstance(obf_full, str) and obf_full: + forward[orig] = obf_full + if ':' in orig: + orig_base = orig.split(':', 1)[0] + if isinstance(parts, list) and parts: + p0 = str(parts[0]).rstrip(':') + if p0: + forward.setdefault(orig_base, p0) + elif isinstance(tok, str) and tok: + forward.setdefault(orig_base, tok) + elif isinstance(tok, str) and tok: + forward.setdefault(orig, tok) + except Exception: + pass + + if not forward: + return {}, '' + map_digest = hashlib.sha256( + json.dumps(forward, ensure_ascii=False, sort_keys=True).encode('utf-8') + ).hexdigest()[:16] + return forward, map_digest + + +def translate_policy_symbol_substring(sub, forward, sorted_items=None): + """Expand a function/symbol match substring with Layer-1 renamed identifier variants.""" + if not sub: + return [] + variants = [sub] + if not forward: + return variants + + def add(v): + if v and v not in variants: + variants.append(v) + + if sub in forward: + add(forward[sub]) + + m = re.match(r'^(\d+)(.+)$', sub) + if m: + n = int(m.group(1)) + rest = m.group(2) + if n > 0 and len(rest) >= n: + ident, suffix = rest[:n], rest[n:] + if ident in forward: + obf_id = forward[ident] + add(f'{len(obf_id)}{obf_id}{suffix}') + + replaced = sub + matched_any = False + candidates = sorted_items + if candidates is None: + candidates = [ + (orig, obf) + for orig, obf in sorted(forward.items(), key=lambda kv: -len(kv[0])) + if len(orig) >= 4 and ':' not in orig + ] + for orig, obf in candidates: + if orig not in replaced: + continue + pat = rf'(?= 4 and ':' not in orig + ] + + for rule_key in ( + 'flatten_targets', + 'indirect_call_targets', + 'string_encrypt_targets', + 'string_encrypt_objc_targets', + 'string_encrypt_swift_targets', + 'string_encrypt_stack_targets', + 'opaque_const_targets', + 'arithmetic_targets', + 'indirect_branch_targets', + 'anti_hooking_targets', + 'function_outline_targets', + 'opaque_field_targets', + 'bb_split_targets', + ): + if rule_key not in eff: + continue + expanded = [] + for rule in eff.get(rule_key) or []: + expanded.append(rule) + fn_sub = rule.get('function_contains', '') + if fn_sub: + for idx, alt in enumerate(translate_policy_symbol_substring(fn_sub, forward, sorted_items=sorted_items)): + if alt != fn_sub: + expanded.append({ + **rule, + 'id': f"{rule.get('id', 'rule')}__l1_{idx}", + 'function_contains': alt, + }) + eff[rule_key] = expanded + + new_required = [] + for req in eff.get('required_targets') or []: + r = dict(req) + if r.get('symbol_contains'): + r['symbol_contains_any'] = translate_policy_symbol_substring( + r['symbol_contains'], forward, sorted_items=sorted_items + ) + if r.get('str_symbol_contains'): + r['str_symbol_contains_any'] = translate_policy_symbol_substring( + r['str_symbol_contains'], forward, sorted_items=sorted_items + ) + new_required.append(r) + eff['required_targets'] = new_required + eff['l1_translation_active'] = True + eff['l1_map_digest'] = map_digest[:12] + else: + eff['l1_translation_active'] = False + eff['l1_map_digest'] = '' + + out_dir.mkdir(parents=True, exist_ok=True) + eff_text = json.dumps(eff, ensure_ascii=False, indent=2) + '\n' + if not eff_path.is_file() or eff_path.read_text(encoding='utf-8') != eff_text: + tmp = out_dir / f'.tmp-{eff_path.name}-{os.getpid()}' + tmp.write_text(eff_text, encoding='utf-8') + tmp.replace(eff_path) + return str(eff_path), eff + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--require-obf', action='store_true') + parser.add_argument('--manifest', default=None) + parser.add_argument('--cache-dir', default=None) + parser.add_argument('--json', action='store_true') + parser.add_argument('--ensure', action='store_true') + parser.add_argument('--check-only', action='store_true') + parser.add_argument('--force-rebuild', action='store_true') + parser.add_argument('--no-rebuild', action='store_true') + parser.add_argument('--git-remote', default=None) + parser.add_argument('--keep-versions', type=int, default=3) + args = parser.parse_args() + + try: + if args.check_only: + res = check_toolchain_status( + cache_root=args.cache_dir, + manifest_path=args.manifest, + ) + elif args.ensure: + res = ensure_opt( + cache_root=args.cache_dir, + git_remote=args.git_remote, + keep_versions=args.keep_versions, + force_rebuild=args.force_rebuild, + allow_rebuild=(not args.no_rebuild), + manifest_path=args.manifest, + ) + else: + res = resolve_opt( + manifest_path=args.manifest, + cache_root=args.cache_dir, + require_obf=(True if args.require_obf else None), + ) + except Exception as exc: + if args.json: + sys.stdout.write(json.dumps({'error': str(exc)}, ensure_ascii=False) + '\n') + else: + sys.stderr.write(f'{exc}\n') + return 1 + + if not args.check_only and args.require_obf and not res.get('opt_path'): + if args.json: + sys.stdout.write(json.dumps(res, ensure_ascii=False) + '\n') + else: + sys.stderr.write(str(res.get('warning', 'opt unavailable')) + '\n') + return 1 + + sys.stdout.write(json.dumps(res, ensure_ascii=False, indent=2) + '\n') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/llvm_obf/run_m0_readoor_matrix.py b/tools/llvm_obf/run_m0_readoor_matrix.py new file mode 100755 index 0000000..e9228f0 --- /dev/null +++ b/tools/llvm_obf/run_m0_readoor_matrix.py @@ -0,0 +1,493 @@ +#!/usr/bin/env python3 +"""Execute Milestone 0 `readoor31` Release Archive verification & non-clean rollback matrix.""" +import json +import os +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import sys +import tempfile +import time + +ROOT = Path('/Users/shenlei/Work/ReadBook/iOSGuard') +APP_REPO = ROOT / 'readoor-test' +TOOLS_CRASH = ROOT / 'tools' / 'crash_restore' +TOOLS_MACHO = ROOT / 'tools' / 'macho_guard' + +sys.path.insert(0, str(TOOLS_CRASH)) +sys.path.insert(0, str(TOOLS_MACHO)) + +import restore_crash_report # noqa: E402 +from verify_baseline import scan # noqa: E402 + +DD_PATH = Path('/tmp/ig-m0-dd') +ARCHIVE_DIR = Path('/tmp/ig-m0-archives') +RESULTS_DIR = ROOT / 'test-results' / '20261119-m0-prototype-verification' +TARGET_BUILD_INTERM = DD_PATH / 'Build/Intermediates.noindex/ArchiveIntermediates/readoor31/IntermediateBuildFilesPath/readoor.build/Release-iphoneos/readoor31.build' +OBJ_BASE = TARGET_BUILD_INTERM / 'Objects-normal/arm64' +AUDIT_DIR = TARGET_BUILD_INTERM / 'ig-route2-audit' +ARCHIVE_PATH = ARCHIVE_DIR / 'readoor31.xcarchive' + + +def check_disk_budget(min_gb=5.0): + free_gb = shutil.disk_usage('/Users/shenlei').free / (1024 ** 3) + if free_gb < min_gb: + raise RuntimeError(f'Free disk space {free_gb:.2f} GB dropped below {min_gb:.1f} GB!') + return round(free_gb, 2) + + +def is_bitcode_wrapper(path): + try: + with Path(path).open('rb') as f: + return f.read(4) in (b'\xde\xc0\x17\x0b', b'BC\xc0\xde') + except OSError: + return False + + +def reconstruct_step_from_artifacts(step_tag, log_name): + bins_path = RESULTS_DIR / step_tag / 'route2' / f'{step_tag}-binaries.json' + bins_data = json.loads(bins_path.read_text(encoding='utf-8')) + main_info = bins_data['readoor31'] + sl = main_info['slices'][0] + ig_ld_lines = [] + log_path = RESULTS_DIR / log_name + if log_path.is_file(): + for line in log_path.read_text(encoding='utf-8', errors='replace').splitlines(): + if '[IGRoute2] ld OK' in line or '[IGRoute2] frameworks audit OK' in line: + ig_ld_lines.append(line.strip()) + return { + 'reconstructed_from_artifacts': True, + 'main_binary_bytes': main_info['size'], + 'main_text_bytes': sl['segments']['__TEXT']['filesize'], + 'route2': { + 'binaries': len(bins_data), + 'direct_call_total': sum( + int(s.get('total', 0)) + for b in bins_data.values() + for s in b.get('slices', []) + ), + 'direct_call_counts': sl.get('counts', {}), + }, + 'linker_and_phase_log': ig_ld_lines, + } + + +def compact_large_logs(results_dir): + prefixes = ('CompileC ', 'SwiftCompile ', 'Ld ', 'PhaseScriptExecution ', 'CreateBuildDirectory ') + for p in sorted(results_dir.glob('m0_*.log')): + if p.name.endswith('_excerpt.log'): + continue + if p.stat().st_size <= 1_000_000: + continue + lines = p.read_text(encoding='utf-8', errors='replace').splitlines() + counts = {k.strip(): 0 for k in prefixes} + ig_lines = [] + for ln in lines: + for k in prefixes: + if ln.startswith(k): + counts[k.strip()] += 1 + break + if '[IGRoute2]' in ln or '[IGObf]' in ln or 'IG_OBF' in ln or 'ARCHIVE SUCCEEDED' in ln: + ig_lines.append(ln) + tail = lines[-80:] if len(lines) > 80 else lines + excerpt = [ + f'# Excerpt generated from {p.name} ({p.stat().st_size} bytes, {len(lines)} lines)', + 'step_counts: ' + json.dumps(counts), + '', + '## IG Lines', + *ig_lines, + '', + '## Tail (last 80 lines)', + *tail, + '', + ] + p.with_name(p.stem + '_excerpt.log').write_text('\n'.join(excerpt), encoding='utf-8') + p.unlink() + + +def text_section_size(bin_path): + out = subprocess.check_output(['size', str(bin_path)], text=True).strip().splitlines() + return int(out[-1].split()[0]) + + +def uuids_of(path): + out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True) + return {line.split()[1] for line in out.splitlines() if line.startswith('UUID:')} + + +def find_symbol_range(dsym_dwarf_path, substring): + """Find (sym_name, start_vm, end_vm) from unstripped dSYM DWARF binary.""" + out = subprocess.check_output(['xcrun', 'nm', '-n', str(dsym_dwarf_path)], text=True).splitlines() + entries = [] + for line in out: + parts = line.strip().split(maxsplit=2) + if len(parts) == 3 and parts[1].lower() == 't': + try: + entries.append((int(parts[0], 16), parts[2])) + except ValueError: + pass + for idx, (addr, name) in enumerate(entries): + if substring in name: + end_addr = entries[idx + 1][0] if idx + 1 < len(entries) else (addr + 0x400) + return name, addr, max(end_addr, addr + 16) + return None, None, None + + +def disassemble_range(bin_path, start_addr, end_addr): + out = subprocess.check_output([ + 'xcrun', 'llvm-objdump', '--disassemble', + f'--start-address={hex(start_addr)}', + f'--stop-address={hex(end_addr)}', + str(bin_path), + ], text=True) + lines = [l for l in out.splitlines() if re.match(r'^\s*[0-9a-f]+:\s', l)] + return out, lines + + +def text_vmaddr(bin_path): + out = subprocess.check_output(['otool', '-l', str(bin_path)], text=True).splitlines() + for i, l in enumerate(out): + if 'segname __TEXT' in l: + for j in range(i + 1, min(i + 6, len(out))): + if 'vmaddr' in out[j]: + return int(out[j].split()[1], 16) + return 0x100000000 + + +def run_archive(step_name, extra_settings, log_path): + free_gb = check_disk_budget() + print(f'\n=== [{step_name}] disk_free={free_gb}GB args={extra_settings} ===', flush=True) + if ARCHIVE_PATH.exists(): + shutil.rmtree(ARCHIVE_PATH) + ARCHIVE_DIR.mkdir(parents=True, exist_ok=True) + cmd = [ + 'xcodebuild', + '-workspace', str(APP_REPO / 'readoor.xcworkspace'), + '-scheme', 'readoor31', + '-configuration', 'Release', + '-destination', 'generic/platform=iOS', + '-derivedDataPath', str(DD_PATH), + '-archivePath', str(ARCHIVE_PATH), + 'CODE_SIGNING_ALLOWED=NO', + *extra_settings, + 'archive', + ] + t0 = time.monotonic() + res = subprocess.run(cmd, cwd=APP_REPO, capture_output=True, text=True) + elapsed = round(time.monotonic() - t0, 2) + log_path.write_text(res.stdout + '\n' + res.stderr, encoding='utf-8') + if res.returncode != 0: + tail = '\n'.join((res.stdout + '\n' + res.stderr).splitlines()[-80:]) + raise RuntimeError(f'[{step_name}] xcodebuild archive failed (rc={res.returncode}):\n{tail}') + return elapsed, res.stdout + '\n' + res.stderr + + +def inspect_app_route2(app_dir, step_tag): + out_dir = RESULTS_DIR / step_tag / 'route2' + out_dir.mkdir(parents=True, exist_ok=True) + binaries, total = scan(app_dir, out_dir, step_tag) + counts = {} + for info in binaries.values(): + for sl in info['slices']: + for k, v in sl['counts'].items(): + counts[k] = counts.get(k, 0) + v + wl_path = app_dir / 'RDKnownImages.plist' + wl = plistlib.loads(wl_path.read_bytes()) if wl_path.is_file() else {} + known = [e['name'] if isinstance(e, dict) else str(e) for e in wl.get('known_images', [])] + return { + 'binaries': len(binaries), + 'direct_call_total': total, + 'direct_call_counts': counts, + 'whitelist_count': len(known), + 'has_ig_archive_guard': ('RDCoreIO' in known) or ('IGArchiveGuard' in known), + } + + +def check_object_pair(swift_obj, oc_obj): + def inspect_o(p): + if not p or not p.is_file(): + return {'exists': False} + data = p.read_bytes() + nm_out = subprocess.check_output(['xcrun', 'nm', str(p)], text=True) + dec_syms = [l.split()[-1] for l in nm_out.splitlines() if '__ig_dec_str_' in l] + has_nul_plain = (b'\x00DYLD_INSERT_LIBRARIES\x00' in data) or data.startswith(b'DYLD_INSERT_LIBRARIES\x00') + return { + 'exists': True, + 'path': str(p), + 'has_plaintext_dyld_cstr': has_nul_plain, + 'ig_dec_symbols': dec_syms, + } + + return {'swift': inspect_o(swift_obj), 'objc': inspect_o(oc_obj)} + + +def find_target_objects(): + oc_obj = OBJ_BASE / 'STSJailbreakDetectTool.o' + swift_machos = list((OBJ_BASE / 'ig-swift-macho').glob('*RDInjectionDetector*.o')) + swift_macho = swift_machos[0] if swift_machos else (OBJ_BASE / 'RDInjectionDetector.o') + return swift_macho, oc_obj + + +def verify_readoor_symbolication(app_dir, dsyms_dir): + main_bin = app_dir / 'readoor31' + main_dwarf = dsyms_dir / 'readoor31.app.dSYM/Contents/Resources/DWARF/readoor31' + guard_bin = app_dir / 'Frameworks' / 'RDCoreIO.framework' / 'RDCoreIO' + sszip_bin = app_dir / 'Frameworks' / 'SSZipArchive.framework' / 'SSZipArchive' + + main_uid = next(iter(uuids_of(main_bin))) + if (dsyms_dir / 'RDCoreIO.framework.dSYM').is_dir() and guard_bin.is_file(): + fw_bin = guard_bin + fw_dwarf = dsyms_dir / 'RDCoreIO.framework.dSYM/Contents/Resources/DWARF/RDCoreIO' + fw_sym, fw_vm, _ = find_symbol_range(fw_dwarf, 'rd_io_chk') + if not fw_sym: + fw_sym, fw_vm, _ = find_symbol_range(fw_dwarf, 'rd_a') + else: + fw_bin = sszip_bin + fw_sym, fw_vm, _ = find_symbol_range(fw_bin, 'unzip') + fw_uid = next(iter(uuids_of(fw_bin))) + + _, swift_vm, _ = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries') + _, oc_vm, _ = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]') + + main_base_static = text_vmaddr(main_bin) + fw_base_static = text_vmaddr(fw_bin) + main_load = 0x104000000 + fw_load = 0x109000000 + main_off = (swift_vm - main_base_static) + 4 + oc_off = (oc_vm - main_base_static) + 4 + fw_off = (fw_vm - fw_base_static) + 4 + + with tempfile.TemporaryDirectory() as td: + p = Path(td) + ips_p = p / 'readoor_m0.ips' + ips_p.write_text( + json.dumps({'app_name': 'readoor31', 'bug_type': '309'}) + '\n' + + json.dumps({ + 'usedImages': [ + {'base': main_load, 'size': 0x4000000, 'uuid': main_uid, 'name': 'readoor31', 'arch': 'arm64', 'path': '/private/var/readoor31.app/readoor31'}, + {'base': fw_load, 'size': 0x400000, 'uuid': fw_uid, 'name': fw_bin.name, 'arch': 'arm64', 'path': f'/private/var/readoor31.app/Frameworks/{fw_bin.name}.framework/{fw_bin.name}'}, + ], + 'threads': [{ + 'triggered': True, + 'frames': [ + {'imageIndex': 0, 'imageOffset': main_off}, + {'imageIndex': 0, 'imageOffset': oc_off}, + {'imageIndex': 1, 'imageOffset': fw_off}, + ], + }], + }) + '\n', + encoding='utf-8', + ) + crash_p = p / 'readoor_m0.crash' + crash_p.write_text( + 'Thread 0 Crashed:\n' + f'0 readoor31 {hex(main_load + main_off)} {hex(main_load)} + {main_off}\n' + f'1 readoor31 {hex(main_load + oc_off)} {hex(main_load)} + {oc_off}\n' + f'2 {fw_bin.name} {hex(fw_load + fw_off)} {hex(fw_load)} + {fw_off}\n\n' + 'Binary Images:\n' + f' {hex(main_load)} - {hex(main_load + 0x4000000)} readoor31 arm64 <{main_uid}> /private/var/readoor31.app/readoor31\n' + f' {hex(fw_load)} - {hex(fw_load + 0x400000)} {fw_bin.name} arm64 <{fw_uid}> /private/var/readoor31.app/Frameworks/{fw_bin.name}.framework/{fw_bin.name}\n', + encoding='utf-8', + ) + res_ips = restore_crash_report.restore_report(ips_p, dsyms_dir) + res_crash = restore_crash_report.restore_report(crash_p, dsyms_dir) + return {'ips': res_ips, 'crash': res_crash} + + +def main(): + resume_3a = '--resume-from-3a' in sys.argv + RESULTS_DIR.mkdir(parents=True, exist_ok=True) + if not resume_3a and DD_PATH.exists(): + shutil.rmtree(DD_PATH) + + summary = {'steps': {}} + app_dir = ARCHIVE_PATH / 'Products/Applications/readoor31.app' + main_bin = app_dir / 'readoor31' + dsyms_dir = ARCHIVE_PATH / 'dSYMs' + main_dwarf = dsyms_dir / 'readoor31.app.dSYM/Contents/Resources/DWARF/readoor31' + sw_insns_1 = None + oc_insns_1 = None + + if resume_3a: + assert ARCHIVE_PATH.is_dir() and DD_PATH.is_dir(), 'Cannot resume from 3a without existing archive and DerivedData' + summary['steps']['M0-1'] = reconstruct_step_from_artifacts('M0-1', 'm0_1.log') + m0_2_rec = reconstruct_step_from_artifacts('M0-2', 'm0_2.log') + m0_2_rec['text_delta_vs_m0_1'] = m0_2_rec['main_text_bytes'] - summary['steps']['M0-1']['main_text_bytes'] + m0_2_rec['binary_delta_vs_m0_1'] = m0_2_rec['main_binary_bytes'] - summary['steps']['M0-1']['main_binary_bytes'] + summary['steps']['M0-2'] = m0_2_rec + t3a = 0.0 + else: + # M0-1: Stock baseline + Route 2 + t1, log1 = run_archive('M0-1', ['IG_OBF_MODE=off', 'IG_SWIFT_LTO_BY_ALL_OFF_0=NO'], RESULTS_DIR / 'm0_1.log') + sw_sym, sw_s1, sw_e1 = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries') + oc_sym, oc_s1, oc_e1 = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]') + assert sw_sym and oc_sym, f'Missing target symbols in dSYM: sw={sw_sym}, oc={oc_sym}' + _, sw_insns_1 = disassemble_range(main_bin, sw_s1, sw_e1) + _, oc_insns_1 = disassemble_range(main_bin, oc_s1, oc_e1) + r2_1 = inspect_app_route2(app_dir, 'M0-1') + assert r2_1['binaries'] == 40 and r2_1['direct_call_total'] == 0, f'M0-1 Route2 failed: {r2_1}' + summary['steps']['M0-1'] = { + 'elapsed_s': t1, + 'main_text_bytes': text_section_size(main_bin), + 'route2': r2_1, + 'swift_symbol': sw_sym, + 'oc_symbol': oc_sym, + 'swift_insn_count': len(sw_insns_1), + 'oc_insn_count': len(oc_insns_1), + 'obf_audit': json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text()), + } + + # M0-2: Conversion-chain No-Op Control + t2, log2 = run_archive('M0-2', ['IG_OBF_MODE=noop'], RESULTS_DIR / 'm0_2.log') + r2_2 = inspect_app_route2(app_dir, 'M0-2') + audit_2 = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text()) + assert audit_2['converted_swift_count'] > 0 and audit_2['objc_audited_count'] > 0 + assert audit_2['total_flattened'] == 0 and audit_2['total_strings_encrypted'] == 0 + assert r2_2['binaries'] == 40 and r2_2['direct_call_total'] == 0 + assert uuids_of(main_bin) == uuids_of(dsyms_dir / 'readoor31.app.dSYM') + _, sw_s2, sw_e2 = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries') + _, oc_s2, oc_e2 = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]') + _, sw_insns_2 = disassemble_range(main_bin, sw_s2, sw_e2) + _, oc_insns_2 = disassemble_range(main_bin, oc_s2, oc_e2) + summary['steps']['M0-2'] = { + 'elapsed_s': t2, + 'main_text_bytes': text_section_size(main_bin), + 'text_delta_vs_m0_1': text_section_size(main_bin) - summary['steps']['M0-1']['main_text_bytes'], + 'swift_insn_count': len(sw_insns_2), + 'oc_insn_count': len(oc_insns_2), + 'route2': r2_2, + 'obf_audit': {k: audit_2[k] for k in ('mode', 'expected_swift_count', 'converted_swift_count', 'skipped_swift_count', 'objc_audited_count', 'total_flattened', 'total_strings_encrypted')}, + } + + # M0-3a: Full single-target Swift + OC obfuscation (NO clean) + t3a, log3a = run_archive('M0-3a', ['IG_OBF_MODE=full'], RESULTS_DIR / 'm0_3a.log') + + r2_3a = inspect_app_route2(app_dir, 'M0-3a') + audit_3a = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text()) + _, sw_s3a, sw_e3a = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries') + _, oc_s3a, oc_e3a = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]') + sw_dis_3a, sw_insns_3a = disassemble_range(main_bin, sw_s3a, sw_e3a) + oc_dis_3a, oc_insns_3a = disassemble_range(main_bin, oc_s3a, oc_e3a) + (RESULTS_DIR / 'm0_3a_swift_disasm.txt').write_text(sw_dis_3a, encoding='utf-8') + (RESULTS_DIR / 'm0_3a_oc_disasm.txt').write_text(oc_dis_3a, encoding='utf-8') + sw_o_3a, oc_o_3a = find_target_objects() + objs_3a = check_object_pair(sw_o_3a, oc_o_3a) + sym_3a = verify_readoor_symbolication(app_dir, dsyms_dir) + assert r2_3a['binaries'] == 40 and r2_3a['direct_call_total'] == 0 + assert uuids_of(main_bin) == uuids_of(dsyms_dir / 'readoor31.app.dSYM') + assert len(sw_insns_3a) > 0 and len(oc_insns_3a) > 0 + if sw_insns_1 is not None and oc_insns_1 is not None: + assert len(sw_insns_3a) > len(sw_insns_1) and len(oc_insns_3a) > len(oc_insns_1) + assert not objs_3a['swift']['has_plaintext_dyld_cstr'] and objs_3a['swift']['ig_dec_symbols'] + assert not objs_3a['objc']['has_plaintext_dyld_cstr'] and objs_3a['objc']['ig_dec_symbols'] + summary['steps']['M0-3a_full'] = { + 'elapsed_s': t3a, + 'resumed_from_3a_archive': resume_3a, + 'main_binary_bytes': main_bin.stat().st_size, + 'main_text_bytes': text_section_size(main_bin), + 'route2': r2_3a, + 'swift_insn_count': len(sw_insns_3a), + 'oc_insn_count': len(oc_insns_3a), + 'target_objects': objs_3a, + 'obf_audit': audit_3a, + 'symbolication': sym_3a, + } + + # M0-3b: str rollback (NO clean!) + t3b, log3b = run_archive('M0-3b', ['IG_OBF_MODE=str'], RESULTS_DIR / 'm0_3b.log') + r2_3b = inspect_app_route2(app_dir, 'M0-3b') + audit_3b = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text()) + _, sw_s3b, sw_e3b = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries') + _, oc_s3b, oc_e3b = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]') + _, sw_insns_3b = disassemble_range(main_bin, sw_s3b, sw_e3b) + _, oc_insns_3b = disassemble_range(main_bin, oc_s3b, oc_e3b) + sw_o_3b, oc_o_3b = find_target_objects() + objs_3b = check_object_pair(sw_o_3b, oc_o_3b) + assert audit_3b['total_flattened'] == 0 and audit_3b['total_strings_encrypted'] >= 2 + assert len(sw_insns_3b) < len(sw_insns_3a) and len(oc_insns_3b) < len(oc_insns_3a) + assert not objs_3b['swift']['has_plaintext_dyld_cstr'] and objs_3b['swift']['ig_dec_symbols'] + assert not objs_3b['objc']['has_plaintext_dyld_cstr'] and objs_3b['objc']['ig_dec_symbols'] + assert r2_3b['binaries'] == 40 and r2_3b['direct_call_total'] == 0 + summary['steps']['M0-3b_str'] = { + 'elapsed_s': t3b, + 'compile_c_ran': 'CompileC ' in log3b, + 'ld_ran': 'Ld ' in log3b, + 'swift_insn_count': len(sw_insns_3b), + 'oc_insn_count': len(oc_insns_3b), + 'target_objects': objs_3b, + 'obf_audit': {k: audit_3b[k] for k in ('mode', 'total_flattened', 'total_strings_encrypted', 'required_targets')}, + 'route2': r2_3b, + } + + # M0-3c: off rollback (NO clean!) + t3c, log3c = run_archive('M0-3c', ['IG_OBF_MODE=off'], RESULTS_DIR / 'm0_3c.log') + r2_3c = inspect_app_route2(app_dir, 'M0-3c') + audit_3c = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text()) + _, sw_s3c, sw_e3c = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries') + _, oc_s3c, oc_e3c = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]') + _, sw_insns_3c = disassemble_range(main_bin, sw_s3c, sw_e3c) + _, oc_insns_3c = disassemble_range(main_bin, oc_s3c, oc_e3c) + sw_o_3c, oc_o_3c = find_target_objects() + objs_3c = check_object_pair(sw_o_3c, oc_o_3c) + assert audit_3c['total_flattened'] == 0 and audit_3c['total_strings_encrypted'] == 0 + assert len(sw_insns_3a) > len(sw_insns_3c) and len(oc_insns_3a) > len(oc_insns_3c) + assert objs_3c['swift']['has_plaintext_dyld_cstr'] and not objs_3c['swift']['ig_dec_symbols'] + assert objs_3c['objc']['has_plaintext_dyld_cstr'] and not objs_3c['objc']['ig_dec_symbols'] + assert r2_3c['binaries'] == 40 and r2_3c['direct_call_total'] == 0 + summary['steps']['M0-3c_off'] = { + 'elapsed_s': t3c, + 'compile_c_ran': 'CompileC ' in log3c, + 'ld_ran': 'Ld ' in log3c, + 'swift_insn_count': len(sw_insns_3c), + 'oc_insn_count': len(oc_insns_3c), + 'target_objects': objs_3c, + 'obf_audit': {k: audit_3c[k] for k in ('mode', 'total_flattened', 'total_strings_encrypted')}, + 'route2': r2_3c, + } + + # M0-3d: IG_ALL_GUARD_OFF=1 total circuit breaker (NO clean!) + t3d, log3d = run_archive('M0-3d', ['IG_ALL_GUARD_OFF=1'], RESULTS_DIR / 'm0_3d.log') + r2_3d = inspect_app_route2(app_dir, 'M0-3d') + swift_native_o = OBJ_BASE / 'RDInjectionDetector.o' + oc_native_o = OBJ_BASE / 'STSJailbreakDetectTool.o' + linkfilelist_path = OBJ_BASE / 'readoor31.LinkFileList' + linkfilelist_lines = [ + line.strip() + for line in linkfilelist_path.read_text(encoding='utf-8').splitlines() + if line.strip() + ] + linkfilelist_bc_count = sum(1 for line in linkfilelist_lines if line.endswith('.bc')) + swift_native_is_bc = is_bitcode_wrapper(swift_native_o) + objs_3d = check_object_pair(swift_native_o, oc_native_o) + assert 'SwiftCompile ' in log3d + assert swift_native_o.is_file() and not swift_native_is_bc + assert linkfilelist_bc_count == 0 + assert r2_3d['binaries'] == 39 and not r2_3d['has_ig_archive_guard'] + assert r2_3d['direct_call_total'] > 0 + assert objs_3d['swift']['has_plaintext_dyld_cstr'] and not objs_3d['swift']['ig_dec_symbols'] + assert objs_3d['objc']['has_plaintext_dyld_cstr'] and not objs_3d['objc']['ig_dec_symbols'] + summary['steps']['M0-3d_all_off'] = { + 'elapsed_s': t3d, + 'swift_compile_ran': 'SwiftCompile ' in log3d, + 'swift_native_o_is_bitcode': swift_native_is_bc, + 'linkfilelist_bc_count': linkfilelist_bc_count, + 'route2': r2_3d, + 'target_objects': objs_3d, + } + + (RESULTS_DIR / 'm0_summary.json').write_text( + json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8' + ) + if ARCHIVE_DIR.exists(): + shutil.rmtree(ARCHIVE_DIR) + if DD_PATH.exists(): + shutil.rmtree(DD_PATH) + compact_large_logs(RESULTS_DIR) + print('\n=== MILESTONE 0 MATRIX COMPLETE ===') + print(json.dumps(summary, ensure_ascii=False, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/llvm_obf/run_m1_epub_eval.py b/tools/llvm_obf/run_m1_epub_eval.py new file mode 100644 index 0000000..bb66a0b --- /dev/null +++ b/tools/llvm_obf/run_m1_epub_eval.py @@ -0,0 +1,620 @@ +#!/usr/bin/env python3 +"""Execute Milestone 1 EPUB layered ablation, physical-device benchmark, static clue audit, and Round 2 seed polymorphism verification.""" +import argparse +import datetime +import hashlib +import json +import os +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import sys +import tempfile +import time + +ROOT = Path('/Users/shenlei/Work/ReadBook/iOSGuard') +APP_REPO = ROOT / 'readoor-test' +TOOLS_CRASH = ROOT / 'tools' / 'crash_restore' +TOOLS_MACHO = ROOT / 'tools' / 'macho_guard' +TOOLS_OBF = ROOT / 'tools' / 'llvm_obf' + +sys.path.insert(0, str(TOOLS_CRASH)) +sys.path.insert(0, str(TOOLS_MACHO)) +sys.path.insert(0, str(TOOLS_OBF)) + +import restore_crash_report # noqa: E402 +from verify_baseline import scan # noqa: E402 +from ig_toolchain_resolver import detect_sdk_info, detect_stock_tool, resolve_opt # noqa: E402 + +DD_PATH = Path('/tmp/ig-m1-dd') +ARCHIVE_PATH = Path('/tmp/ig-m1-archives/readoor31.xcarchive') +BLIND_DIR = Path('/tmp/ig-m1-blind-eval') +RESULTS_DIR = ROOT / 'test-results' / '20261119-m1-epub-evaluation' +TARGET_BUILD_INTERM = DD_PATH / 'Build/Intermediates.noindex/ArchiveIntermediates/readoor31/IntermediateBuildFilesPath/readoor.build/Release-iphoneos/readoor31.build' +OBJ_BASE = TARGET_BUILD_INTERM / 'Objects-normal/arm64' +AUDIT_DIR = TARGET_BUILD_INTERM / 'ig-route2-audit' + +DEFAULT_DEVICE = '00008140-000960811493001C' +DEFAULT_PROFILE = Path('/Users/shenlei/Library/Developer/Xcode/UserData/Provisioning Profiles/e0f18495-668f-4fb1-87e1-4e048fb48d11.mobileprovision') +DEFAULT_IDENTITY = '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8' +BENCH_BUNDLE_ID = 'cn.touchv.iosguard.m1epubbench' + + +def sha256_bytes(data): + return hashlib.sha256(data).hexdigest() + + +def file_sha256(path): + return sha256_bytes(Path(path).read_bytes()) + + +def check_disk_budget(min_gb=5.0): + free_gb = shutil.disk_usage('/Users/shenlei').free / (1024 ** 3) + if free_gb < min_gb: + raise RuntimeError(f'Free disk space {free_gb:.2f} GB dropped below {min_gb:.1f} GB') + return round(free_gb, 2) + + +def sync_toolchain_and_integrate(): + dst_root = APP_REPO / 'iOSGuardIntegration' / 'toolchain' + copies = [ + (ROOT / 'config/ig_llvm_policy.json', dst_root / 'config/ig_llvm_policy.json'), + (ROOT / 'config/ig_llvm_policy_m1_group_b.json', dst_root / 'config/ig_llvm_policy_m1_group_b.json'), + (ROOT / 'config/toolchain_manifest.json', dst_root / 'config/toolchain_manifest.json'), + (ROOT / 'tools/xcode_archive/ig_cc_wrapper.py', dst_root / 'tools/xcode_archive/ig_cc_wrapper.py'), + (ROOT / 'tools/xcode_archive/ig_cxx_wrapper.py', dst_root / 'tools/xcode_archive/ig_cxx_wrapper.py'), + (ROOT / 'tools/xcode_archive/ig_ld_wrapper.py', dst_root / 'tools/xcode_archive/ig_ld_wrapper.py'), + (ROOT / 'tools/xcode_archive/ig_guard_frameworks_phase.py', dst_root / 'tools/xcode_archive/ig_guard_frameworks_phase.py'), + (ROOT / 'tools/llvm_obf/ig_toolchain_resolver.py', dst_root / 'tools/llvm_obf/ig_toolchain_resolver.py'), + (ROOT / 'tools/crash_restore/restore_crash_report.py', dst_root / 'tools/crash_restore/restore_crash_report.py'), + ] + if (ROOT / 'config/ig_diag_events.json').is_file(): + copies.append((ROOT / 'config/ig_diag_events.json', dst_root / 'config/ig_diag_events.json')) + for src, dst in copies: + if src.is_file(): + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + subprocess.run(['ruby', str(APP_REPO / 'scripts/integrate_route2_archive.rb')], cwd=APP_REPO, check=True) + + +def run_archive(step_tag, extra_settings, log_path): + free_gb = check_disk_budget() + print(f'\n=== [{step_tag}] disk_free={free_gb}GB args={extra_settings} ===', flush=True) + if ARCHIVE_PATH.exists(): + shutil.rmtree(ARCHIVE_PATH) + ARCHIVE_PATH.parent.mkdir(parents=True, exist_ok=True) + cmd = [ + 'xcodebuild', + '-workspace', str(APP_REPO / 'readoor.xcworkspace'), + '-scheme', 'readoor31', + '-configuration', 'Release', + '-destination', 'generic/platform=iOS', + '-derivedDataPath', str(DD_PATH), + '-archivePath', str(ARCHIVE_PATH), + 'CODE_SIGNING_ALLOWED=NO', + *extra_settings, + 'archive', + ] + t0 = time.monotonic() + res = subprocess.run(cmd, cwd=APP_REPO, capture_output=True, text=True) + elapsed = round(time.monotonic() - t0, 2) + text_log = res.stdout + '\n' + res.stderr + ig_lines = [l for l in text_log.splitlines() if '[IGRoute2]' in l or '[IGObf]' in l or 'ARCHIVE ' in l or 'error:' in l] + log_path.write_text('\n'.join(ig_lines[-120:] + ['', '--- tail ---'] + text_log.splitlines()[-60:]) + '\n', encoding='utf-8') + if res.returncode != 0: + raise RuntimeError(f'[{step_tag}] xcodebuild failed (rc={res.returncode}):\n' + '\n'.join(text_log.splitlines()[-80:])) + return elapsed + + +def text_section_bytes(bin_path): + out = subprocess.check_output(['size', str(bin_path)], text=True).strip().splitlines() + return int(out[-1].split()[0]) + + +def uuids_of(path): + out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True) + return {line.split()[1] for line in out.splitlines() if line.startswith('UUID:')} + + +def inspect_app_route2(app_dir, step_tag): + out_dir = RESULTS_DIR / step_tag / 'route2' + out_dir.mkdir(parents=True, exist_ok=True) + binaries, total = scan(app_dir, out_dir, step_tag) + counts = {} + for info in binaries.values(): + for sl in info['slices']: + for k, v in sl['counts'].items(): + counts[k] = counts.get(k, 0) + v + return {'binaries': len(binaries), 'direct_call_total': total, 'direct_call_counts': counts} + + +def find_epub_objects(include_keybox=False): + names = [ + 'RDEncryptedEpubResourceProvider', + 'RDEpubReaderLauncher', + 'RD30EpubCoordinator', + 'RD30EpubResourceService', + 'RD30EpubFileStore', + 'RD30EpubDownloadManager', + 'STSEpubWebResourceLoader', + 'EpubParser', + 'EpubChapter', + 'RBCoreEpubLoadController', + ] + if include_keybox: + names.extend(['RDEpubKeyBox', 'RDEpubCryptBridge', 'RDSDKeyBox']) + swift_macho_dir = OBJ_BASE / 'ig-swift-macho' + found = {} + for n in names: + cand_sw = sorted(swift_macho_dir.glob(f'*_{n}.o')) if swift_macho_dir.is_dir() else [] + cand_plain = OBJ_BASE / f'{n}.o' + p = cand_sw[0] if cand_sw else (cand_plain if cand_plain.is_file() else None) + found[n] = p + return found + + +def audit_static_clues(main_bin, include_keybox=False): + objs = find_epub_objects(include_keybox=include_keybox) + patterns = [ + b'startiasoft', + b'[RD30Epub]', + b'com.readoor.rd30epub', + b'ERROR:epub', + ] + obj_hits = {} + undef_xrefs = {} + for name, p in objs.items(): + if not p or not p.is_file(): + obj_hits[name] = {'missing': True} + continue + raw = p.read_bytes() + hits = {} + for pat in patterns: + cnt = raw.count(pat) + if cnt > 0: + hits[pat.decode('ascii', errors='replace')] = cnt + obj_hits[name] = hits + nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(p)], text=True, errors='replace').splitlines() + tracked = [l.strip() for l in nm_u if any(k in l for k in ('_CC_MD5', 'MD5Hash', 'md5Encrypt', 'StsSimpleCrypt', 'rd_content_decrypt', 'rd_epub_derive'))] + if tracked: + undef_xrefs[name] = sorted(set(tracked)) + + main_raw = main_bin.read_bytes() + main_counts = { + 'main_bin_startiasoft_count': main_raw.count(b'startiasoft'), + 'main_bin_RD30Epub_log_count': main_raw.count(b'[RD30Epub]'), + 'main_bin_rd30epub_queue_count': main_raw.count(b'com.readoor.rd30epub'), + 'main_bin_RDDiag_E31_count': main_raw.count(b'[RDDiag] E-31'), + } + return { + 'object_paths': {k: (str(v) if v else None) for k, v in objs.items()}, + 'object_clue_hits': obj_hits, + 'object_xrefs': undef_xrefs, + 'main_binary_counts': main_counts, + } + + +def sign_and_run_bench_on_device(app_dir, work_dir): + r_prof = subprocess.run( + ['openssl', 'smime', '-inform', 'der', '-verify', '-noverify', '-in', str(DEFAULT_PROFILE)], + capture_output=True, check=True, + ) + pdata = plistlib.loads(r_prof.stdout) + ent = pdata['Entitlements'] + prefix = pdata['ApplicationIdentifierPrefix'][0] + if ent['application-identifier'] != prefix + '.*' or not ent.get('get-task-allow'): + raise RuntimeError('Provisioning profile must be wildcard development profile') + if pdata['ExpirationDate'] <= datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None): + raise RuntimeError('Provisioning profile expired') + if DEFAULT_IDENTITY.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in pdata['DeveloperCertificates']}: + raise RuntimeError('Identity does not match provisioning profile') + + if work_dir.exists(): + shutil.rmtree(work_dir) + work_dir.mkdir(parents=True) + staged_app = work_dir / 'readoor31.app' + subprocess.run(['ditto', str(app_dir), str(staged_app)], check=True) + + info_path = staged_app / 'Info.plist' + info = plistlib.loads(info_path.read_bytes()) + info['CFBundleIdentifier'] = BENCH_BUNDLE_ID + info['CFBundleDisplayName'] = 'M1EpubBench' + info.pop('CFBundleURLTypes', None) + info_path.write_bytes(plistlib.dumps(info)) + + shutil.copy2(DEFAULT_PROFILE, staged_app / 'embedded.mobileprovision') + allowed = dict(ent) + allowed['application-identifier'] = f'{prefix}.{BENCH_BUNDLE_ID}' + allowed['keychain-access-groups'] = [f'{prefix}.{BENCH_BUNDLE_ID}'] + ent_path = work_dir / 'entitlements.plist' + ent_path.write_bytes(plistlib.dumps(allowed)) + + nested = sorted( + {p for p in staged_app.rglob('*') if not p.is_symlink() and p.suffix in ('.framework', '.dylib')}, + key=lambda p: (-len(p.parts), str(p)), + ) + for item in nested: + subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, str(item)], check=True) + subprocess.run( + ['codesign', '--force', '--sign', DEFAULT_IDENTITY, '--entitlements', str(ent_path), str(staged_app)], + check=True, + ) + subprocess.run(['codesign', '--verify', '--strict', str(staged_app)], check=True) + + installed = False + bench_json = work_dir / 'm1_epub_bench.json' + done_marker = work_dir / 'm1_epub_bench.done' + try: + print(f'[device] installing {staged_app.name} ({BENCH_BUNDLE_ID}) on {DEFAULT_DEVICE}...', flush=True) + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'install', 'app', + '--device', DEFAULT_DEVICE, '--timeout', '120', str(staged_app), + ], check=True) + installed = True + print(f'[device] launching {BENCH_BUNDLE_ID} with IG_M1_EPUB_BENCH=1...', flush=True) + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'process', 'launch', + '--device', DEFAULT_DEVICE, '--terminate-existing', + '-e', json.dumps({'IG_M1_EPUB_BENCH': '1'}), + BENCH_BUNDLE_ID, + ], check=True) + + print('[device] polling for Documents/m1_epub_bench.done...', flush=True) + + deadline = time.monotonic() + 180.0 + got_done = False + while time.monotonic() < deadline: + if done_marker.is_file(): + done_marker.unlink() + elif done_marker.is_dir(): + shutil.rmtree(done_marker) + r = subprocess.run([ + 'xcrun', 'devicectl', 'device', 'copy', 'from', + '--device', DEFAULT_DEVICE, + '--domain-type', 'appDataContainer', + '--domain-identifier', BENCH_BUNDLE_ID, + '--source', 'Documents/m1_epub_bench.done', + '--destination', str(done_marker), + ], capture_output=True, text=True) + if r.returncode == 0 and done_marker.exists(): + got_done = True + break + time.sleep(2.0) + if not got_done: + raise RuntimeError('Timed out waiting for Documents/m1_epub_bench.done from device') + + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'copy', 'from', + '--device', DEFAULT_DEVICE, + '--domain-type', 'appDataContainer', + '--domain-identifier', BENCH_BUNDLE_ID, + '--source', 'Documents/m1_epub_bench.json', + '--destination', str(bench_json), + ], check=True) + finally: + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'process', 'terminate', + '--device', DEFAULT_DEVICE, BENCH_BUNDLE_ID, + ], capture_output=True) + if installed: + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'uninstall', 'app', + '--device', DEFAULT_DEVICE, '--timeout', '60', BENCH_BUNDLE_ID, + ], check=False) + + return json.loads(bench_json.read_text(encoding='utf-8')) + + +def run_ablation_arm(arm_name, mode, policy_profile, policy_path, seed, blind_sample_name, include_keybox): + RESULTS_DIR.mkdir(parents=True, exist_ok=True) + policy_stamp = hashlib.sha256(policy_path.read_bytes()).hexdigest()[:12] + base_args = [ + f'IG_OBF_MODE={mode}', + f'IG_POLICY_PROFILE={policy_profile}', + f'IG_POLICY_STAMP={policy_stamp}', + f'IG_RELEASE_SEED={seed}', + ] + + # 1. Clean archive (no bench harness compiled in) + t_clean = run_archive(f'{arm_name}_clean', [*base_args, 'IG_SWIFT_EXTRA_FLAGS='], RESULTS_DIR / f'{arm_name}_clean.log') + app_dir = ARCHIVE_PATH / 'Products/Applications/readoor31.app' + main_bin = app_dir / 'readoor31' + dsyms_dir = ARCHIVE_PATH / 'dSYMs' + assert uuids_of(main_bin) == uuids_of(dsyms_dir / 'readoor31.app.dSYM') + r2 = inspect_app_route2(app_dir, arm_name) + assert r2['binaries'] == 40 and r2['direct_call_total'] == 0, f'{arm_name} Route2 failed: {r2}' + obf_audit = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text(encoding='utf-8')) + clues = audit_static_clues(main_bin, include_keybox=include_keybox) + + bin_bytes = main_bin.stat().st_size + txt_bytes = text_section_bytes(main_bin) + + # Save stripped main binary for blind reverse-engineering evaluation + blind_target = BLIND_DIR / blind_sample_name / 'app.bin' + blind_target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(main_bin, blind_target) + + arm_data = { + 'arm': arm_name, + 'mode': mode, + 'policy_profile': policy_profile, + 'seed': seed, + 'clean_archive_elapsed_s': t_clean, + 'main_binary_bytes': bin_bytes, + 'main_text_bytes': txt_bytes, + 'route2': r2, + 'obf_audit_summary': { + 'expected_swift_count': obf_audit.get('expected_swift_count'), + 'converted_swift_count': obf_audit.get('converted_swift_count'), + 'total_flattened': obf_audit.get('total_flattened'), + 'total_strings_encrypted': obf_audit.get('total_strings_encrypted'), + 'required_targets': obf_audit.get('required_targets'), + 'module_audits': obf_audit.get('module_audits'), + }, + 'static_clues': clues, + } + + if include_keybox: + # Preserve Round 2 bitcode & verify symbolication for Group C + r2_dir = RESULTS_DIR / 'round2_inputs' + r2_dir.mkdir(parents=True, exist_ok=True) + prov_bc = OBJ_BASE / 'RDEncryptedEpubResourceProvider.bc' + if prov_bc.is_file(): + shutil.copy2(prov_bc, r2_dir / 'RDEncryptedEpubResourceProvider.bc') + arm_data['symbolication_c'] = verify_group_c_symbolication(app_dir, dsyms_dir) + + if ARCHIVE_PATH.exists(): + shutil.rmtree(ARCHIVE_PATH) + + # 2. Bench archive (#if IG_ENABLE_M1_BENCH enabled) -> run on physical device + t_bench = run_archive( + f'{arm_name}_bench', + [*base_args, 'IG_SWIFT_EXTRA_FLAGS=-DIG_ENABLE_M1_BENCH'], + RESULTS_DIR / f'{arm_name}_bench.log', + ) + bench_work = Path(f'/tmp/ig-m1-dev-{arm_name}') + bench_res = sign_and_run_bench_on_device(app_dir, bench_work) + if bench_work.exists(): + shutil.rmtree(bench_work) + if ARCHIVE_PATH.exists(): + shutil.rmtree(ARCHIVE_PATH) + + if bench_res.get('status') != 'PASS': + raise AssertionError(f'[{arm_name}] Device EPUB bench failed: {bench_res}') + + arm_data['bench_archive_elapsed_s'] = t_bench + arm_data['device_bench'] = bench_res + (RESULTS_DIR / f'{arm_name}.json').write_text(json.dumps(arm_data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') + return arm_data + + +def verify_group_c_symbolication(app_dir, dsyms_dir): + main_bin = app_dir / 'readoor31' + main_dwarf = dsyms_dir / 'readoor31.app.dSYM/Contents/Resources/DWARF/readoor31' + guard_bin = app_dir / 'Frameworks/RDCoreIO.framework/RDCoreIO' + guard_dwarf = dsyms_dir / 'RDCoreIO.framework.dSYM/Contents/Resources/DWARF/RDCoreIO' + + def find_sym(dwarf_p, sub): + out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_p)], text=True).splitlines() + for l in out: + parts = l.strip().split(maxsplit=2) + if len(parts) == 3 and parts[1].lower() == 't' and sub in parts[2]: + return int(parts[0], 16) + raise RuntimeError(f'Symbol matching {sub} not found in {dwarf_p}') + + def text_vm(bin_p): + out = subprocess.check_output(['otool', '-l', str(bin_p)], text=True).splitlines() + for i, l in enumerate(out): + if 'segname __TEXT' in l: + for j in range(i + 1, min(i + 6, len(out))): + if 'vmaddr' in out[j]: + return int(out[j].split()[1], 16) + return 0x100000000 + + kb_vm = find_sym(main_dwarf, 'rd_epub_derive_book_key') + try: + sw_vm = find_sym(main_dwarf, '31RDEncryptedEpubResourceProviderC12resourceData') + except RuntimeError: + sw_vm = find_sym(main_dwarf, '31RDEncryptedEpubResourceProviderC') + fw_vm = find_sym(guard_dwarf, 'rd_io_chk') + + main_uid = next(iter(uuids_of(main_bin))) + fw_uid = next(iter(uuids_of(guard_bin))) + main_base = text_vm(main_bin) + fw_base = text_vm(guard_bin) + main_load, fw_load = 0x104000000, 0x109000000 + kb_off = (kb_vm - main_base) + 4 + sw_off = (sw_vm - main_base) + 4 + fw_off = (fw_vm - fw_base) + 4 + + with tempfile.TemporaryDirectory() as td: + p = Path(td) + ips_p = p / 'group_c.ips' + ips_p.write_text( + json.dumps({'app_name': 'readoor31', 'bug_type': '309'}) + '\n' + + json.dumps({ + 'usedImages': [ + {'base': main_load, 'size': 0x4000000, 'uuid': main_uid, 'name': 'readoor31', 'arch': 'arm64', 'path': '/private/var/readoor31.app/readoor31'}, + {'base': fw_load, 'size': 0x400000, 'uuid': fw_uid, 'name': 'RDCoreIO', 'arch': 'arm64', 'path': '/private/var/readoor31.app/Frameworks/RDCoreIO.framework/RDCoreIO'}, + ], + 'threads': [{ + 'triggered': True, + 'frames': [ + {'imageIndex': 0, 'imageOffset': kb_off}, + {'imageIndex': 0, 'imageOffset': sw_off}, + {'imageIndex': 1, 'imageOffset': fw_off}, + ], + }], + }) + '\n', + encoding='utf-8', + ) + crash_p = p / 'group_c.crash' + crash_p.write_text( + 'Thread 0 Crashed:\n' + f'0 readoor31 {hex(main_load + kb_off)} {hex(main_load)} + {kb_off}\n' + f'1 readoor31 {hex(main_load + sw_off)} {hex(main_load)} + {sw_off}\n' + f'2 RDCoreIO {hex(fw_load + fw_off)} {hex(fw_load)} + {fw_off}\n\n' + 'Binary Images:\n' + f' {hex(main_load)} - {hex(main_load + 0x4000000)} readoor31 arm64 <{main_uid}> /private/var/readoor31.app/readoor31\n' + f' {hex(fw_load)} - {hex(fw_load + 0x400000)} RDCoreIO arm64 <{fw_uid}> /private/var/readoor31.app/Frameworks/RDCoreIO.framework/RDCoreIO\n', + encoding='utf-8', + ) + return { + 'ips': restore_crash_report.restore_report(ips_p, dsyms_dir), + 'crash': restore_crash_report.restore_report(crash_p, dsyms_dir), + } + + +def run_seed_round2(): + RESULTS_DIR.mkdir(parents=True, exist_ok=True) + tc = resolve_opt(require_obf=True) + opt_path = tc['opt_path'] + clang = detect_stock_tool('clang') + sdk = detect_sdk_info()['sdk_path'] + policy_path = ROOT / 'config/ig_llvm_policy.json' + src_c = APP_REPO / 'readoor/3.0/Base/Security/RDEpubKeyBox.c' + defender_inc = APP_REPO / 'readoor/3.0/Base/Security/IGDefender' + prov_bc = RESULTS_DIR / 'round2_inputs/RDEncryptedEpubResourceProvider.bc' + assert src_c.is_file() and prov_bc.is_file(), 'Group C must run before seed-round2' + + seeds = ['m1_seed_alpha', 'm1_seed_beta', 'm1_seed_gamma'] + with tempfile.TemporaryDirectory(prefix='ig-m1-r2-') as td: + work = Path(td) + c_bc = work / 'RDEpubKeyBox.raw.bc' + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, + '-Os', '-g', '-fvisibility=hidden', + '-I', str(defender_inc), '-I', str(defender_inc / 'include'), + '-emit-llvm', '-c', str(src_c), '-o', str(c_bc), + ], check=True) + + def text_sha(obj_path): + out = subprocess.check_output(['xcrun', 'otool', '-s', '__TEXT', '__text', '-v', str(obj_path)], text=True) + lines = [l for l in out.splitlines() if re.match(r'^[0-9a-f]+\s+', l)] + return sha256_bytes('\n'.join(lines).encode('utf-8')) + + def compile_with_seed(tag, bc_in, pipeline, src_hint, seed, opt_level='-Os'): + obf_bc = work / f'{tag}.obf.bc' + obj_o = work / f'{tag}.o' + audit_p = work / f'{tag}.audit.json' + subprocess.run([ + opt_path, f'-passes={pipeline}', + f'--ig-policy={policy_path}', + '--ig-mode=full', + '--ig-pass-filter=all', + f'--ig-seed={seed}', + f'--ig-source-path={src_hint}', + f'--ig-audit-out={audit_p}', + str(bc_in), '-o', str(obf_bc), + ], check=True) + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, + opt_level, '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', + '-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o), + ], check=True) + ll_txt = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(obj_o)], text=True) + bb_names = [] + # Extract IR block labels by running opt -S to check physical block permutation too + ir_ll = subprocess.check_output([ + opt_path, f'-passes={pipeline}', + f'--ig-policy={policy_path}', + '--ig-mode=full', '--ig-pass-filter=all', + f'--ig-seed={seed}', f'--ig-source-path={src_hint}', + str(bc_in), '-S', '-o', '-', + ], text=True) + for l in ir_ll.splitlines(): + if l.endswith(':') and not l.startswith(';'): + bb_names.append(l) + return { + 'obf_bc_sha256': file_sha256(obf_bc), + 'obj_sha256': file_sha256(obj_o), + 'text_disasm_sha256': sha256_bytes(ll_txt.encode('utf-8')), + 'ir_block_layout_sha256': sha256_bytes('\n'.join(bb_names).encode('utf-8')), + 'text_insn_count': len([l for l in ll_txt.splitlines() if re.match(r'^\s*[0-9a-f]+:\s', l)]), + 'audit': json.loads(audit_p.read_text(encoding='utf-8')), + 'ir_block_sample': bb_names[:30], + } + + c_det_1 = compile_with_seed('c_det_1', c_bc, 'ig-obfuscate', str(src_c), 'm1_seed_alpha', '-Os') + c_det_2 = compile_with_seed('c_det_2', c_bc, 'ig-obfuscate', str(src_c), 'm1_seed_alpha', '-Os') + sw_det_1 = compile_with_seed('sw_det_1', prov_bc, 'default,ig-obfuscate', 'RDEncryptedEpubResourceProvider.swift', 'm1_seed_alpha', '-O2') + sw_det_2 = compile_with_seed('sw_det_2', prov_bc, 'default,ig-obfuscate', 'RDEncryptedEpubResourceProvider.swift', 'm1_seed_alpha', '-O2') + + assert c_det_1['obf_bc_sha256'] == c_det_2['obf_bc_sha256'] and c_det_1['obj_sha256'] == c_det_2['obj_sha256'] + assert sw_det_1['obf_bc_sha256'] == sw_det_2['obf_bc_sha256'] and sw_det_1['obj_sha256'] == sw_det_2['obj_sha256'] + + c_seeds = {s: compile_with_seed(f'c_{s}', c_bc, 'ig-obfuscate', str(src_c), s, '-Os') for s in seeds} + sw_seeds = {s: compile_with_seed(f'sw_{s}', prov_bc, 'default,ig-obfuscate', 'RDEncryptedEpubResourceProvider.swift', s, '-O2') for s in seeds} + + assert len({c_seeds[s]['text_disasm_sha256'] for s in seeds}) == len(seeds) + assert len({sw_seeds[s]['text_disasm_sha256'] for s in seeds}) == len(seeds) + + report = { + 'determinism_same_seed': { + 'RDEpubKeyBox_c_obf_bc_match': c_det_1['obf_bc_sha256'] == c_det_2['obf_bc_sha256'], + 'RDEpubKeyBox_c_obj_match': c_det_1['obj_sha256'] == c_det_2['obj_sha256'], + 'SwiftProvider_obf_bc_match': sw_det_1['obf_bc_sha256'] == sw_det_2['obf_bc_sha256'], + 'SwiftProvider_obj_match': sw_det_1['obj_sha256'] == sw_det_2['obj_sha256'], + }, + 'c_cross_seed_variants': { + s: {k: v for k, v in c_seeds[s].items() if k != 'ir_block_sample'} + for s in seeds + }, + 'swift_cross_seed_variants': { + s: {k: v for k, v in sw_seeds[s].items() if k != 'ir_block_sample'} + for s in seeds + }, + } + (RESULTS_DIR / 'round2_seed_polymorphism.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') + print(json.dumps(report, ensure_ascii=False, indent=2)) + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--phase', required=True, choices=['group-a', 'group-b', 'group-c', 'seed-round2']) + args = parser.parse_args() + + if args.phase == 'group-a': + sync_toolchain_and_integrate() + if DD_PATH.exists(): + shutil.rmtree(DD_PATH) + run_ablation_arm( + arm_name='group_a_noop', + mode='noop', + policy_profile='default', + policy_path=ROOT / 'config/ig_llvm_policy.json', + seed='m1_seed_alpha', + blind_sample_name='sample_2', + include_keybox=False, + ) + elif args.phase == 'group-b': + sync_toolchain_and_integrate() + run_ablation_arm( + arm_name='group_b_flatten_only', + mode='full', + policy_profile='m1_group_b', + policy_path=ROOT / 'config/ig_llvm_policy_m1_group_b.json', + seed='m1_seed_alpha', + blind_sample_name='sample_1', + include_keybox=False, + ) + elif args.phase == 'group-c': + sync_toolchain_and_integrate() + run_ablation_arm( + arm_name='group_c_flatten_and_cleanup', + mode='full', + policy_profile='default', + policy_path=ROOT / 'config/ig_llvm_policy.json', + seed='m1_seed_alpha', + blind_sample_name='sample_3', + include_keybox=True, + ) + elif args.phase == 'seed-round2': + run_seed_round2() + + +if __name__ == '__main__': + main() diff --git a/tools/llvm_obf/run_m2_security_eval.py b/tools/llvm_obf/run_m2_security_eval.py new file mode 100644 index 0000000..5441ae6 --- /dev/null +++ b/tools/llvm_obf/run_m2_security_eval.py @@ -0,0 +1,648 @@ +#!/usr/bin/env python3 +"""Execute Milestone 2 SD 3.2, IAP & Security Guard verification and physical-device 3-path test.""" +import argparse +import base64 +import datetime +import hashlib +import json +from pathlib import Path +import plistlib +import shutil +import subprocess +import sys +import tempfile +import time + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.hazmat.primitives.serialization import load_pem_private_key + +ROOT = Path('/Users/shenlei/Work/ReadBook/iOSGuard') +APP_REPO = ROOT / 'readoor-test' +TOOLS_CRASH = ROOT / 'tools' / 'crash_restore' +TOOLS_MACHO = ROOT / 'tools' / 'macho_guard' +TOOLS_OBF = ROOT / 'tools' / 'llvm_obf' + +sys.path.insert(0, str(TOOLS_CRASH)) +sys.path.insert(0, str(TOOLS_MACHO)) +sys.path.insert(0, str(TOOLS_OBF)) + +import restore_crash_report # noqa: E402 +from verify_baseline import scan # noqa: E402 + +DD_PATH = Path('/tmp/ig-m2-dd') +ARCHIVE_PATH = Path('/tmp/ig-m2-archives/readoor31.xcarchive') +STAGE_DIR = Path('/tmp/ig-m2-stage') +RESULTS_DIR = ROOT / 'test-results' / '20261119-m2-sd-iap-evaluation' +TARGET_BUILD_INTERM = DD_PATH / 'Build/Intermediates.noindex/ArchiveIntermediates/readoor31/IntermediateBuildFilesPath/readoor.build/Release-iphoneos/readoor31.build' +OBJ_BASE = TARGET_BUILD_INTERM / 'Objects-normal/arm64' +AUDIT_DIR = TARGET_BUILD_INTERM / 'ig-route2-audit' + +DEFAULT_DEVICE = '00008140-000960811493001C' +DEFAULT_PROFILE = Path('/Users/shenlei/Library/Developer/Xcode/UserData/Provisioning Profiles/e0f18495-668f-4fb1-87e1-4e048fb48d11.mobileprovision') +DEFAULT_IDENTITY = '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8' +BENCH_BUNDLE_ID = 'cn.touchv.iosguard.m2seceval' + +M1_GROUP_A_MAIN_BYTES = 24_748_584 +MAX_SIZE_DELTA_BYTES = 1_572_864 + + +def sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def check_disk_budget(min_gb=5.0): + free_gb = shutil.disk_usage('/Users/shenlei').free / (1024 ** 3) + if free_gb < min_gb: + raise RuntimeError(f'Free disk space {free_gb:.2f} GB dropped below {min_gb:.1f} GB') + return round(free_gb, 2) + + +def text_section_bytes(bin_path: Path) -> int: + out = subprocess.check_output(['size', str(bin_path)], text=True).strip().splitlines() + return int(out[-1].split()[0]) + + +def uuids_of(path: Path) -> set: + out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True) + return {line.split()[1] for line in out.splitlines() if line.startswith('UUID:')} + + +def sync_toolchain_and_integrate(): + dst_root = APP_REPO / 'iOSGuardIntegration' / 'toolchain' + copies = [ + (ROOT / 'config/ig_llvm_policy.json', dst_root / 'config/ig_llvm_policy.json'), + (ROOT / 'config/ig_diag_events.json', dst_root / 'config/ig_diag_events.json'), + (ROOT / 'config/toolchain_manifest.json', dst_root / 'config/toolchain_manifest.json'), + (ROOT / 'tools/xcode_archive/ig_cc_wrapper.py', dst_root / 'tools/xcode_archive/ig_cc_wrapper.py'), + (ROOT / 'tools/xcode_archive/ig_cxx_wrapper.py', dst_root / 'tools/xcode_archive/ig_cxx_wrapper.py'), + (ROOT / 'tools/xcode_archive/ig_ld_wrapper.py', dst_root / 'tools/xcode_archive/ig_ld_wrapper.py'), + (ROOT / 'tools/xcode_archive/ig_guard_frameworks_phase.py', dst_root / 'tools/xcode_archive/ig_guard_frameworks_phase.py'), + (ROOT / 'tools/llvm_obf/ig_toolchain_resolver.py', dst_root / 'tools/llvm_obf/ig_toolchain_resolver.py'), + (ROOT / 'tools/crash_restore/restore_crash_report.py', dst_root / 'tools/crash_restore/restore_crash_report.py'), + ] + for src, dst in copies: + if src.is_file(): + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + subprocess.run(['ruby', str(APP_REPO / 'scripts/integrate_route2_archive.rb')], cwd=APP_REPO, check=True) + + +def run_archive(step_tag: str, extra_settings: list, log_path: Path) -> float: + free_gb = check_disk_budget() + print(f'\n=== [{step_tag}] disk_free={free_gb}GB args={extra_settings} ===', flush=True) + if ARCHIVE_PATH.exists(): + shutil.rmtree(ARCHIVE_PATH) + ARCHIVE_PATH.parent.mkdir(parents=True, exist_ok=True) + cmd = [ + 'xcodebuild', + '-workspace', str(APP_REPO / 'readoor.xcworkspace'), + '-scheme', 'readoor31', + '-configuration', 'Release', + '-destination', 'generic/platform=iOS', + '-derivedDataPath', str(DD_PATH), + '-archivePath', str(ARCHIVE_PATH), + 'CODE_SIGNING_ALLOWED=NO', + *extra_settings, + 'archive', + ] + t0 = time.monotonic() + res = subprocess.run(cmd, cwd=APP_REPO, capture_output=True, text=True) + elapsed = round(time.monotonic() - t0, 2) + text_log = res.stdout + '\n' + res.stderr + ig_lines = [l for l in text_log.splitlines() if '[IGRoute2]' in l or '[IGObf]' in l or 'ARCHIVE ' in l or 'error:' in l] + log_path.write_text('\n'.join(ig_lines[-120:] + ['', '--- tail ---'] + text_log.splitlines()[-80:]) + '\n', encoding='utf-8') + if res.returncode != 0: + raise RuntimeError(f'[{step_tag}] xcodebuild failed (rc={res.returncode}):\n' + '\n'.join(text_log.splitlines()[-80:])) + return elapsed + + +def inspect_app_route2(app_dir: Path, step_tag: str) -> dict: + out_dir = RESULTS_DIR / step_tag / 'route2' + out_dir.mkdir(parents=True, exist_ok=True) + binaries, total = scan(app_dir, out_dir, step_tag) + counts = {} + for info in binaries.values(): + for sl in info['slices']: + for k, v in sl['counts'].items(): + counts[k] = counts.get(k, 0) + v + return {'binaries': len(binaries), 'direct_call_total': total, 'direct_call_counts': counts} + + +def find_m2_objects() -> dict: + names = [ + 'RDSDKeyBox', + 'RDSDPrivateKeyManager', + 'RDSDAuthV32Signer', + 'RDJWTPayloadParser', + 'RDBaseNetworkService', + 'RDSecurityGuard', + 'RDInjectionDetector', + 'RDIAPPurchaseManager', + 'RDIAPHandler', + 'STSIAPVerifyHandler', + 'STSIAPVerifyTask', + 'STSIAPKeyChainHandler', + ] + swift_macho_dir = OBJ_BASE / 'ig-swift-macho' + found = {} + for n in names: + cand_sw = sorted(swift_macho_dir.glob(f'*_{n}.o')) if swift_macho_dir.is_dir() else [] + cand_plain = OBJ_BASE / f'{n}.o' + found[n] = cand_sw[0] if cand_sw else (cand_plain if cand_plain.is_file() else None) + return found + + +def otool_cstring_bytes(obj_path: Path) -> bytes: + out = subprocess.check_output(['xcrun', 'otool', '-s', '__TEXT', '__cstring', str(obj_path)], text=True, errors='replace') + chunks = [] + for line in out.splitlines(): + parts = line.split('\t') + if len(parts) == 2 and parts[0].strip().endswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')): + hex_bytes = parts[1].strip().split() + try: + chunks.append(bytes(int(h, 16) for h in hex_bytes)) + except ValueError: + pass + return b''.join(chunks) + + +def audit_m2_static_clues(main_bin: Path) -> dict: + objs = find_m2_objects() + forbidden_clues = [ + b'readoor_sd_v32', + b'KSDPrivateKeyPEM', + b'encrypted_private_key', + b'cn.touchv.payment.models.keychain', + b'[SDAuthV32]', + b'[IAP]', + b'[Security]', + b'Exception: No product matched', + ] + host_path_clue = b'/Users/shenlei/Work/ReadBook' + + obj_hits = {} + for name, p in objs.items(): + if not p or not p.is_file(): + obj_hits[name] = {'missing': True} + continue + raw = p.read_bytes() + cstring_raw = otool_cstring_bytes(p) + hits = {} + for pat in forbidden_clues: + cnt = raw.count(pat) + if cnt > 0: + hits[pat.decode('ascii', errors='replace')] = cnt + hp_cnt = cstring_raw.count(host_path_clue) + if hp_cnt > 0: + hits['__cstring_host_path'] = hp_cnt + obj_hits[name] = hits + + main_raw = main_bin.read_bytes() + main_forbidden_counts = { + pat.decode('ascii', errors='replace'): main_raw.count(pat) + for pat in forbidden_clues + } + + main_strings = subprocess.run(['strings', str(main_bin)], capture_output=True).stdout.decode('utf-8', errors='replace').splitlines() + protected_module_filenames = ( + 'RDEpubKeyBox.c', + 'RDEpubCryptBridge.m', + 'RDEpubKeyGuard.c', + 'RDEncryptedEpubResourceProvider.swift', + 'RDEpubReaderLauncher.swift', + 'RD30EpubCoordinator.swift', + 'RD30EpubResourceService.swift', + 'RD30EpubFileStore.swift', + 'RD30EpubDownloadManager.swift', + 'RDPDFStsSimpleCryptBridge.swift', + 'STSEpubWebResourceLoader.m', + 'EpubParser.m', + 'EpubChapter.m', + 'RBCoreEpubLoadController.m', + 'RDSDKeyBox.c', + 'RDSDPrivateKeyManager.swift', + 'RDSDAuthV32Signer.swift', + 'RDJWTPayloadParser.swift', + 'RDBaseNetworkService.swift', + 'RDRequestParamsFormat.swift', + 'RDSecurityGuard.swift', + 'RDInjectionDetector.swift', + 'RDIAPPurchaseManager.swift', + 'RDIAPHandler.swift', + 'RDIAPHandler+RDVipExtension.swift', + 'STSIAPVerifyHandler.m', + 'STSIAPVerifyTask.m', + 'STSIAPKeyChainHandler.m', + ) + host_path_lines = [l for l in main_strings if '/Users/shenlei/Work/ReadBook' in l] + protected_host_path_lines = [ + l for l in host_path_lines if any(l.endswith('/' + f) or f in l for f in protected_module_filenames) + ] + + logdiag_swift_objs = [ + 'RDSDPrivateKeyManager', + 'RDSDAuthV32Signer', + 'RDSecurityGuard', + 'RDInjectionDetector', + 'RDIAPPurchaseManager', + 'RDIAPHandler', + ] + logdiag_linked = [] + for n in logdiag_swift_objs: + p = objs.get(n) + if p and p.is_file(): + nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(p)], text=True, errors='replace') + if '7logDiag' in nm_u: + logdiag_linked.append(n) + + main_diag_counts = { + 'E_41_count': main_raw.count(b'E-41'), + 'E_51_count': main_raw.count(b'E-51'), + 'E_61_count': main_raw.count(b'E-61'), + 'logDiag_symbol_linked_objects': logdiag_linked, + 'logDiag_symbol_linked_objects_count': len(logdiag_linked), + } + + return { + 'object_paths': {k: (str(v) if v else None) for k, v in objs.items()}, + 'object_clue_hits': obj_hits, + 'main_binary_forbidden_counts': main_forbidden_counts, + 'protected_module_host_path_hits': protected_host_path_lines, + 'unscoped_snapkit_filepath_count': len(host_path_lines), + 'main_binary_diag_counts': main_diag_counts, + } + + +def verify_m2_symbolication(app_dir: Path, dsyms_dir: Path) -> dict: + main_bin = app_dir / 'readoor31' + main_dwarf = dsyms_dir / 'readoor31.app.dSYM/Contents/Resources/DWARF/readoor31' + guard_bin = app_dir / 'Frameworks/RDCoreIO.framework/RDCoreIO' + guard_dwarf = dsyms_dir / 'RDCoreIO.framework.dSYM/Contents/Resources/DWARF/RDCoreIO' + + def find_sym(dwarf_p: Path, sub: str) -> int: + out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_p)], text=True).splitlines() + for l in out: + parts = l.strip().split(maxsplit=2) + if len(parts) == 3 and parts[1].lower() == 't' and sub in parts[2]: + return int(parts[0], 16) + raise RuntimeError(f'Symbol matching {sub} not found in {dwarf_p}') + + def text_vm(bin_p: Path) -> int: + out = subprocess.check_output(['otool', '-l', str(bin_p)], text=True).splitlines() + for i, l in enumerate(out): + if 'segname __TEXT' in l: + for j in range(i + 1, min(i + 6, len(out))): + if 'vmaddr' in out[j]: + return int(out[j].split()[1], 16) + return 0x100000000 + + kb_vm = find_sym(main_dwarf, 'rd_sd_derive_aes256_key') + signer_vm = find_sym(main_dwarf, 'RDSDAuthV32Signer') + iap_vm = find_sym(main_dwarf, 'STSIAPVerifyHandler') + fw_vm = find_sym(guard_dwarf, 'rd_io_chk') + + main_uid = next(iter(uuids_of(main_bin))) + fw_uid = next(iter(uuids_of(guard_bin))) + main_base = text_vm(main_bin) + fw_base = text_vm(guard_bin) + main_load, fw_load = 0x104000000, 0x109000000 + kb_off = (kb_vm - main_base) + 4 + signer_off = (signer_vm - main_base) + 4 + iap_off = (iap_vm - main_base) + 4 + fw_off = (fw_vm - fw_base) + 4 + + with tempfile.TemporaryDirectory() as td: + p = Path(td) + ips_p = p / 'm2.ips' + ips_p.write_text( + json.dumps({'app_name': 'readoor31', 'bug_type': '309'}) + '\n' + + json.dumps({ + 'usedImages': [ + {'base': main_load, 'size': 0x4000000, 'uuid': main_uid, 'name': 'readoor31', 'arch': 'arm64', 'path': '/private/var/readoor31.app/readoor31'}, + {'base': fw_load, 'size': 0x400000, 'uuid': fw_uid, 'name': 'RDCoreIO', 'arch': 'arm64', 'path': '/private/var/readoor31.app/Frameworks/RDCoreIO.framework/RDCoreIO'}, + ], + 'threads': [{ + 'triggered': True, + 'frames': [ + {'imageIndex': 0, 'imageOffset': kb_off}, + {'imageIndex': 0, 'imageOffset': signer_off}, + {'imageIndex': 0, 'imageOffset': iap_off}, + {'imageIndex': 1, 'imageOffset': fw_off}, + ], + }], + }) + '\n', + encoding='utf-8', + ) + crash_p = p / 'm2.crash' + crash_p.write_text( + 'Thread 0 Crashed:\n' + f'0 readoor31 {hex(main_load + kb_off)} {hex(main_load)} + {kb_off}\n' + f'1 readoor31 {hex(main_load + signer_off)} {hex(main_load)} + {signer_off}\n' + f'2 readoor31 {hex(main_load + iap_off)} {hex(main_load)} + {iap_off}\n' + f'3 RDCoreIO {hex(fw_load + fw_off)} {hex(fw_load)} + {fw_off}\n\n' + 'Binary Images:\n' + f' {hex(main_load)} - {hex(main_load + 0x4000000)} readoor31 arm64 <{main_uid}> /private/var/readoor31.app/readoor31\n' + f' {hex(fw_load)} - {hex(fw_load + 0x400000)} RDCoreIO arm64 <{fw_uid}> /private/var/readoor31.app/Frameworks/RDCoreIO.framework/RDCoreIO\n', + encoding='utf-8', + ) + ips_res = restore_crash_report.restore_report(ips_p, dsyms_dir) + crash_res = restore_crash_report.restore_report(crash_p, dsyms_dir) + + for label, r in [('ips', ips_res), ('crash', crash_res)]: + raw_frames = (r.get('threads', [{}])[0].get('frames', []) if label == 'ips' else r.get('frames', [])) + sym_frames = [' '.join(f.get('restored_frames') or []) for f in raw_frames] + assert len(sym_frames) == 4, f'{label} expected 4 frames, got {raw_frames}' + assert any('rd_sd_derive_aes256_key' in s for s in sym_frames), f'{label} missing RDSDKeyBox: {sym_frames}' + assert any('RDSDAuthV32Signer' in s for s in sym_frames), f'{label} missing RDSDAuthV32Signer: {sym_frames}' + assert any('STSIAPVerifyHandler' in s for s in sym_frames), f'{label} missing STSIAPVerifyHandler: {sym_frames}' + assert any('rd_io_chk' in s for s in sym_frames), f'{label} missing RDCoreIO: {sym_frames}' + + return {'ips': ips_res, 'crash': crash_res} + + +def prepare_signed_app(app_dir: Path, work_dir: Path) -> Path: + r_prof = subprocess.run( + ['openssl', 'smime', '-inform', 'der', '-verify', '-noverify', '-in', str(DEFAULT_PROFILE)], + capture_output=True, check=True, + ) + pdata = plistlib.loads(r_prof.stdout) + ent = pdata['Entitlements'] + prefix = pdata['ApplicationIdentifierPrefix'][0] + if ent['application-identifier'] != prefix + '.*' or not ent.get('get-task-allow'): + raise RuntimeError('Provisioning profile must be wildcard development profile') + if pdata['ExpirationDate'] <= datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None): + raise RuntimeError('Provisioning profile expired') + if DEFAULT_IDENTITY.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in pdata['DeveloperCertificates']}: + raise RuntimeError('Identity does not match provisioning profile') + + if work_dir.exists(): + shutil.rmtree(work_dir) + work_dir.mkdir(parents=True) + staged_app = work_dir / 'readoor31.app' + subprocess.run(['ditto', str(app_dir), str(staged_app)], check=True) + + info_path = staged_app / 'Info.plist' + info = plistlib.loads(info_path.read_bytes()) + info['CFBundleIdentifier'] = BENCH_BUNDLE_ID + info['CFBundleDisplayName'] = 'M2SecEval' + info.pop('CFBundleURLTypes', None) + info_path.write_bytes(plistlib.dumps(info)) + + shutil.copy2(DEFAULT_PROFILE, staged_app / 'embedded.mobileprovision') + allowed = dict(ent) + allowed['application-identifier'] = f'{prefix}.{BENCH_BUNDLE_ID}' + allowed['keychain-access-groups'] = [f'{prefix}.{BENCH_BUNDLE_ID}'] + ent_path = work_dir / 'entitlements.plist' + ent_path.write_bytes(plistlib.dumps(allowed)) + + nested = sorted( + {p for p in staged_app.rglob('*') if not p.is_symlink() and p.suffix in ('.framework', '.dylib')}, + key=lambda p: (-len(p.parts), str(p)), + ) + for item in nested: + subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, str(item)], check=True) + subprocess.run( + ['codesign', '--force', '--sign', DEFAULT_IDENTITY, '--entitlements', str(ent_path), str(staged_app)], + check=True, + ) + subprocess.run(['codesign', '--verify', '--strict', str(staged_app)], check=True) + return staged_app + + +def run_device_stage(staged_app: Path, work_dir: Path, stage: str, do_install: bool) -> dict: + if do_install: + print(f'[device] installing {staged_app.name} ({BENCH_BUNDLE_ID}) for stage={stage}...', flush=True) + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'install', 'app', + '--device', DEFAULT_DEVICE, '--timeout', '120', str(staged_app), + ], check=True) + + print(f'[device] launching {BENCH_BUNDLE_ID} IG_M2_SEC_BENCH=1 IG_M2_STAGE={stage}...', flush=True) + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'process', 'launch', + '--device', DEFAULT_DEVICE, '--terminate-existing', + '-e', json.dumps({'IG_M2_SEC_BENCH': '1', 'IG_M2_STAGE': stage}), + BENCH_BUNDLE_ID, + ], check=True) + + done_marker = work_dir / f'm2_sec_eval_{stage}.done' + result_json = work_dir / f'm2_sec_eval_{stage}.json' + + deadline = time.monotonic() + 120.0 + got_stage_done = False + while time.monotonic() < deadline: + if done_marker.is_file(): + done_marker.unlink() + elif done_marker.is_dir(): + shutil.rmtree(done_marker) + r = subprocess.run([ + 'xcrun', 'devicectl', 'device', 'copy', 'from', + '--device', DEFAULT_DEVICE, + '--domain-type', 'appDataContainer', + '--domain-identifier', BENCH_BUNDLE_ID, + '--source', 'Documents/m2_sec_eval.done', + '--destination', str(done_marker), + ], capture_output=True, text=True) + if r.returncode == 0 and done_marker.is_file(): + if done_marker.read_text(encoding='utf-8', errors='replace').strip() == stage: + got_stage_done = True + break + time.sleep(1.5) + if not got_stage_done: + raise RuntimeError(f'Timed out waiting for Documents/m2_sec_eval.done == {stage!r} from device') + + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'copy', 'from', + '--device', DEFAULT_DEVICE, + '--domain-type', 'appDataContainer', + '--domain-identifier', BENCH_BUNDLE_ID, + '--source', 'Documents/m2_sec_eval.json', + '--destination', str(result_json), + ], check=True) + payload = json.loads(result_json.read_text(encoding='utf-8')) + assert payload.get('stage') == stage, f'Stage mismatch: expected {stage}, got {payload}' + assert payload.get('status') == 'ok', f'Device stage {stage} failed: {payload}' + return payload + + +def run_eval(clean_dd: bool = False): + RESULTS_DIR.mkdir(parents=True, exist_ok=True) + sync_toolchain_and_integrate() + + policy_path = ROOT / 'config/ig_llvm_policy.json' + policy = json.loads(policy_path.read_text(encoding='utf-8')) + policy_stamp = sha256_bytes(policy_path.read_bytes())[:12] + + if clean_dd and DD_PATH.exists(): + shutil.rmtree(DD_PATH) + + base_args = [ + 'IG_OBF_MODE=full', + 'IG_POLICY_PROFILE=default', + f'IG_POLICY_STAMP={policy_stamp}', + 'IG_RELEASE_SEED=m2_seed_alpha', + ] + + # Phase 1: Clean Production Archive + t_clean = run_archive('m2_clean', [*base_args, 'IG_SWIFT_EXTRA_FLAGS='], RESULTS_DIR / 'm2_clean.log') + app_dir = ARCHIVE_PATH / 'Products/Applications/readoor31.app' + main_bin = app_dir / 'readoor31' + dsyms_dir = ARCHIVE_PATH / 'dSYMs' + + main_uuids = uuids_of(main_bin) + dsym_uuids = uuids_of(dsyms_dir / 'readoor31.app.dSYM') + assert main_uuids and main_uuids == dsym_uuids, f'UUID mismatch: bin={main_uuids} dsym={dsym_uuids}' + + r2 = inspect_app_route2(app_dir, 'm2_clean') + assert r2['binaries'] == 40 and r2['direct_call_total'] == 0, f'Route2 check failed: {r2}' + + assert (app_dir / 'rd_glyph_lut_v2.dat').is_file(), 'rd_glyph_lut_v2.dat missing from app bundle' + assert not (app_dir / 'encrypted_private_key.bin').exists(), 'Legacy encrypted_private_key.bin still in app bundle' + + obf_audit = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text(encoding='utf-8')) + req_by_id = {r['id']: r for r in (obf_audit.get('required_targets') or [])} + policy_reqs = policy.get('required_targets') or [] + assert len(req_by_id) == len(policy_reqs), f'Expected {len(policy_reqs)} required_targets, got {list(req_by_id.keys())}' + for req in policy_reqs: + tid = req['id'] + got = req_by_id.get(tid) + assert got is not None, f'Missing required_target audit entry: {tid}' + assert got['flattened_hits'] >= int(req.get('min_flattened', 0)), f'{tid} flattened_hits failed: {got} vs {req}' + assert got['strings_encrypted_hits'] >= int(req.get('min_strings_encrypted', 0)), f'{tid} strings_encrypted_hits failed: {got} vs {req}' + + bin_bytes = main_bin.stat().st_size + txt_bytes = text_section_bytes(main_bin) + size_delta = bin_bytes - M1_GROUP_A_MAIN_BYTES + assert size_delta <= MAX_SIZE_DELTA_BYTES, f'Main binary size delta {size_delta} exceeds {MAX_SIZE_DELTA_BYTES}' + + clues = audit_m2_static_clues(main_bin) + for k, v in clues['main_binary_forbidden_counts'].items(): + assert v == 0, f'Forbidden string {k!r} found {v}x in readoor31 main binary: {clues}' + assert clues['protected_module_host_path_hits'] == [], f"Host path leaked for protected M1/M2 modules: {clues['protected_module_host_path_hits']}" + for obj_name, obj_hits in clues['object_clue_hits'].items(): + assert not obj_hits, f'Clue hits in object {obj_name}: {obj_hits}' + assert clues['main_binary_diag_counts']['E_41_count'] >= 1, clues + assert clues['main_binary_diag_counts']['E_51_count'] >= 1, clues + assert clues['main_binary_diag_counts']['logDiag_symbol_linked_objects_count'] == 6, clues + + symbolication = verify_m2_symbolication(app_dir, dsyms_dir) + + # Phase 2: Bench Archive & Physical iPhone 16 Plus 3-Stage Verification + t_bench = run_archive('m2_bench', [*base_args, 'IG_SWIFT_EXTRA_FLAGS=-DIG_ENABLE_M2_BENCH'], RESULTS_DIR / 'm2_bench.log') + staged_app = prepare_signed_app(ARCHIVE_PATH / 'Products/Applications/readoor31.app', STAGE_DIR) + + # Start clean on device (uninstall prior test bundle if leftover) + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'uninstall', 'app', + '--device', DEFAULT_DEVICE, '--timeout', '60', BENCH_BUNDLE_ID, + ], capture_output=True, check=False) + + stage_results = {} + try: + s1 = run_device_stage(staged_app, STAGE_DIR, 'fresh_seed_v1', do_install=True) + assert s1['keychain_present_before'] is False + assert s1['keychain_present_after'] is True + assert s1['local_verify_ok'] is True + assert s1['guard_baseline_count'] >= 2 + assert s1['guard_eval_ok'] is True + assert s1['iap_keychain_roundtrip_ok'] is True + stage_results['fresh_seed_v1'] = s1 + + # Stage 2: over-install WITHOUT uninstalling first + s2 = run_device_stage(staged_app, STAGE_DIR, 'upgrade_verify', do_install=True) + assert s2['keychain_present_before'] is True, f'Over-install lost Keychain item: {s2}' + assert s2['keychain_present_after'] is True + assert s2['local_verify_ok'] is True + assert s2['guard_baseline_count'] >= 2 + assert s2['guard_eval_ok'] is True + assert s2['iap_keychain_roundtrip_ok'] is True + assert s2['pem_sha256'] == s1['pem_sha256'], 'Over-install changed PEM hash!' + assert s2['x_sig'] == s1['x_sig'], 'Over-install changed X-SIG!' + stage_results['upgrade_verify'] = s2 + + # Stage 3: clear Keychain item & verify recovery from rd_net_cfg_v1.dat + s3 = run_device_stage(staged_app, STAGE_DIR, 'clear_recover', do_install=False) + assert s3.get('had_before_clear') is True + assert s3['keychain_present_before'] is False + assert s3['keychain_present_after'] is True + assert s3['local_verify_ok'] is True + assert s3['guard_baseline_count'] >= 2 + assert s3['guard_eval_ok'] is True + assert s3['iap_keychain_roundtrip_ok'] is True + assert s3['pem_sha256'] == s1['pem_sha256'], 'Recovered PEM hash mismatch!' + assert s3['x_sig'] == s1['x_sig'], 'Recovered X-SIG mismatch!' + stage_results['clear_recover'] = s3 + finally: + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'process', 'terminate', + '--device', DEFAULT_DEVICE, BENCH_BUNDLE_ID, + ], capture_output=True) + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'uninstall', 'app', + '--device', DEFAULT_DEVICE, '--timeout', '60', BENCH_BUNDLE_ID, + ], capture_output=True, check=False) + + # Offline host cryptography RSA-SHA256 verification against repository PEM + pem_path = APP_REPO / 'AutoPacking/sd_priv_ios_v1.pem' + pem_bytes = pem_path.read_bytes() + expected_pem_sha256 = sha256_bytes(pem_bytes) + assert stage_results['fresh_seed_v1']['pem_sha256'] == expected_pem_sha256, ( + f"Device PEM sha256 {stage_results['fresh_seed_v1']['pem_sha256']} != {expected_pem_sha256}" + ) + priv_key = load_pem_private_key(pem_bytes, password=None) + pub_key = priv_key.public_key() + pub_key.verify( + base64.b64decode(stage_results['fresh_seed_v1']['x_sig']), + stage_results['fresh_seed_v1']['sign_string'].encode('utf-8'), + padding.PKCS1v15(), + hashes.SHA256(), + ) + + summary = { + 'milestone': 'M2', + 'clean_archive': { + 'elapsed_s': t_clean, + 'main_binary_bytes': bin_bytes, + 'main_text_bytes': txt_bytes, + 'm1_group_a_main_bytes': M1_GROUP_A_MAIN_BYTES, + 'size_delta_bytes': size_delta, + 'main_uuids': sorted(main_uuids), + 'bundle_has_rd_glyph_lut_v2_dat': True, + 'bundle_has_legacy_encrypted_private_key_bin': False, + 'route2': r2, + 'obf_audit_summary': { + 'expected_swift_count': obf_audit.get('expected_swift_count'), + 'converted_swift_count': obf_audit.get('converted_swift_count'), + 'total_flattened': obf_audit.get('total_flattened'), + 'total_strings_encrypted': obf_audit.get('total_strings_encrypted'), + 'required_targets': obf_audit.get('required_targets'), + }, + 'static_clues': clues, + 'symbolication': symbolication, + }, + 'bench_archive': { + 'elapsed_s': t_bench, + }, + 'device_verification': { + 'device_udid': DEFAULT_DEVICE, + 'bundle_id': BENCH_BUNDLE_ID, + 'stages': stage_results, + 'offline_host_rsa_verify_ok': True, + 'expected_pem_sha256': expected_pem_sha256, + }, + } + summary_path = RESULTS_DIR / 'm2_summary.json' + summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') + print(f'\n[M2] ALL CHECKS PASSED -> {summary_path}', flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--clean-dd', action='store_true', help='Remove DerivedData before archiving') + args = parser.parse_args() + run_eval(clean_dd=args.clean_dd) + + +if __name__ == '__main__': + main() diff --git a/tools/llvm_obf/run_m3_full_regression.py b/tools/llvm_obf/run_m3_full_regression.py new file mode 100755 index 0000000..7f88d22 --- /dev/null +++ b/tools/llvm_obf/run_m3_full_regression.py @@ -0,0 +1,896 @@ +#!/usr/bin/env python3 +"""Execute Milestone 3 L1+L2+L3 dual-target regression, cold/warm cache timing, and iPhone 16 Plus over-install test.""" +import argparse +import base64 +import datetime +import hashlib +import json +import os +from pathlib import Path +import plistlib +import shutil +import subprocess +import sys +import tempfile +import time + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.hazmat.primitives.serialization import load_pem_private_key + +ROOT = Path('/Users/shenlei/Work/ReadBook/iOSGuard') +APP_REPO = ROOT / 'readoor-test' +TOOLS_CRASH = ROOT / 'tools' / 'crash_restore' +TOOLS_MACHO = ROOT / 'tools' / 'macho_guard' +TOOLS_OBF = ROOT / 'tools' / 'llvm_obf' + +sys.path.insert(0, str(TOOLS_CRASH)) +sys.path.insert(0, str(TOOLS_MACHO)) +sys.path.insert(0, str(TOOLS_OBF)) + +import ig_toolchain_resolver # noqa: E402 +import restore_crash_report # noqa: E402 +from verify_baseline import scan # noqa: E402 + +WORK_ROOT = Path('/tmp/ig-m3-work') +SNAPSHOT_SRC = WORK_ROOT / 'src' +DD_PATH = WORK_ROOT / 'dd' +ARCHIVE_DIR = WORK_ROOT / 'archives' +STAGE_DIR = WORK_ROOT / 'stage' +CACHE_ROOT = Path('/tmp/ig-m3-cache') +RESULTS_DIR = ROOT / 'test-results' / '20261119-m3-production-regression' + +DEFAULT_DEVICE = '00008140-000960811493001C' +DEFAULT_PROFILE = Path('/Users/shenlei/Library/Developer/Xcode/UserData/Provisioning Profiles/e0f18495-668f-4fb1-87e1-4e048fb48d11.mobileprovision') +DEFAULT_IDENTITY = '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8' +BUNDLE_READOOR31 = 'cn.touchv.iosguard.m3eval' +BUNDLE_OTHERPAY = 'cn.touchv.iosguard.m3otherpay' + +M2_MAIN_BYTES = 24_732_128 +EXPECTED_NSCODING_CLASSES = ( + 'STSPayOrderInfoObject', + 'RBCorePenLineData', + 'STSPaintModel', + 'STSPaintLayerModel', + 'STSPaintPageLayerModel', + 'STSPaintStack', + 'RDPlayerCacheMedia', + 'RDPlayerCacheMediaConfiguration', +) + + +def sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def check_disk_budget(min_gb: float = 5.0) -> float: + free_gb = shutil.disk_usage('/Users/shenlei').free / (1024 ** 3) + if free_gb < min_gb: + raise RuntimeError(f'Free disk space {free_gb:.2f} GB dropped below {min_gb:.1f} GB') + return round(free_gb, 2) + + +def cleanup_build_artifacts(): + for path in (DD_PATH, ARCHIVE_DIR, STAGE_DIR): + if path.exists(): + shutil.rmtree(path) + + +def text_section_bytes(bin_path: Path) -> int: + out = subprocess.check_output(['size', str(bin_path)], text=True).strip().splitlines() + return int(out[-1].split()[0]) + + +def uuids_of(path: Path) -> set: + out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True) + return {line.split()[1] for line in out.splitlines() if line.startswith('UUID:')} + + +def sync_toolchain_and_integrate(): + dst_root = APP_REPO / 'iOSGuardIntegration' / 'toolchain' + rels = [ + 'config/ig_llvm_policy.json', + 'config/ig_diag_events.json', + 'config/xcode_llvm_map.json', + 'config/toolchain_manifest.json', + 'tools/xcode_archive/route2_archive_common.py', + 'tools/xcode_archive/ig_cc_wrapper.py', + 'tools/xcode_archive/ig_cxx_wrapper.py', + 'tools/xcode_archive/ig_ld_wrapper.py', + 'tools/xcode_archive/ig_guard_frameworks_phase.py', + 'tools/xcode_archive/audit_exported_ipa.py', + 'tools/macho_guard/verify_baseline.py', + 'tools/macho_guard/redirect_framework_imports.py', + 'tools/macho_guard/redirect_legacy_imports.py', + 'tools/macho_guard/machox.py', + 'tools/macho_guard/batch.py', + 'defender/dispatch/IGArchiveGuard.h', + 'defender/dispatch/IGArchiveGuard.c', + 'defender/resolve/IGResolve.h', + 'defender/resolve/IGResolve.c', + 'tools/llvm_obf/ig_toolchain_resolver.py', + 'tools/llvm_obf/build_igopt_local.py', + 'tools/llvm_obf/verify_macho_star_cfg.py', + 'tools/llvm_obf/verify_macho_indirect_branches.py', + 'tools/llvm_obf/verify_macho_indirect_calls.py', + 'tools/crash_restore/restore_crash_report.py', + ] + for rel in rels: + src = ROOT / rel + dst = dst_root / rel + if src.is_file(): + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + passes_src = ROOT / 'llvm_passes' + passes_dst = dst_root / 'llvm_passes' + if passes_src.is_dir(): + if passes_dst.exists(): + shutil.rmtree(passes_dst) + shutil.copytree( + passes_src, + passes_dst, + ignore=shutil.ignore_patterns('__pycache__', '.DS_Store', 'build', '*.pyc'), + ) + subprocess.run(['ruby', str(APP_REPO / 'scripts/integrate_route2_archive.rb')], cwd=APP_REPO, check=True) + + +def create_clean_snapshot_and_apply_l1() -> dict: + check_disk_budget() + if SNAPSHOT_SRC.exists(): + shutil.rmtree(SNAPSHOT_SRC) + SNAPSHOT_SRC.parent.mkdir(parents=True, exist_ok=True) + print('\n=== [L1 Snapshot] rsync readoor-test -> /tmp/ig-m3-work/src ===', flush=True) + subprocess.run([ + 'rsync', '-a', '--delete', + '--exclude', '/.git', + '--exclude', '/build', + '--exclude', '/DerivedData', + '--exclude', '/build_output', + '--exclude', '/obfuscation_maps', + f'{APP_REPO}/', + f'{SNAPSHOT_SRC}/', + ], check=True) + + pre_check = subprocess.run( + ['bash', str(SNAPSHOT_SRC / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh')], + cwd=SNAPSHOT_SRC, capture_output=True, text=True, + ) + if pre_check.returncode != 0: + raise RuntimeError(f'Pre-L1 obfuscation_self_check failed:\n{pre_check.stdout}\n{pre_check.stderr}') + + ts = '20261119_m3' + salt = 'm3_prod_seed_20261119' + l1_res = subprocess.run([ + 'python3', + str(SNAPSHOT_SRC / 'AutoPacking/obfuscation/obfuscate_symbols.py'), + '--archive-mode', + '--target-name', 'readoor31', + '--timestamp', ts, + '--salt', salt, + ], cwd=SNAPSHOT_SRC, capture_output=True, text=True) + l1_log = RESULTS_DIR / 'l1_apply.log' + l1_log.write_text(l1_res.stdout + '\n' + l1_res.stderr, encoding='utf-8') + if l1_res.returncode != 0: + raise RuntimeError(f'obfuscate_symbols.py failed (rc={l1_res.returncode}):\n{l1_res.stdout[-4000:]}\n{l1_res.stderr[-2000:]}') + + sym_map_path = SNAPSHOT_SRC / f'obfuscation_maps/symbol_map_readoor31_{ts}.json' + meth_map_path = SNAPSHOT_SRC / f'obfuscation_maps/method_map_readoor31_{ts}.json' + assert sym_map_path.is_file(), f'Missing {sym_map_path}' + assert meth_map_path.is_file(), f'Missing {meth_map_path}' + + sym_payload = json.loads(sym_map_path.read_text(encoding='utf-8')) + meth_payload = json.loads(meth_map_path.read_text(encoding='utf-8')) + assert sym_payload.get('schema_version') == 2, sym_payload.get('schema_version') + assert meth_payload.get('schema_version') == 2, meth_payload.get('schema_version') + + sym_mappings = sym_payload.get('mappings') or {} + meth_mappings = meth_payload.get('mappings') or {} + + for cls_name in EXPECTED_NSCODING_CLASSES: + assert cls_name not in sym_mappings, f'NSCoding class {cls_name} leaked into obfuscation map' + + key_obf = {} + for expected in ('RDLoginView', 'RDSDAuthV32Signer', 'STSIAPVerifyHandler', 'STSIAPKeyChainHandler', 'RDInjectionDetector'): + raw_entry = sym_mappings.get(expected) + obf_val = raw_entry.get('obfuscated') if isinstance(raw_entry, dict) else raw_entry + assert isinstance(obf_val, str) and obf_val and obf_val != expected, f'{expected} not obfuscated cleanly in L1 map: {raw_entry}' + key_obf[expected] = obf_val + + post_check = subprocess.run( + ['bash', str(SNAPSHOT_SRC / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh')], + cwd=SNAPSHOT_SRC, capture_output=True, text=True, + ) + assert post_check.returncode != 0, 'obfuscation_self_check.sh should fail (non-zero) after L1 apply' + + return { + 'snapshot_src': str(SNAPSHOT_SRC), + 'symbol_map_path': str(sym_map_path), + 'method_map_path': str(meth_map_path), + 'type_mappings_count': len(sym_mappings), + 'method_mappings_count': len(meth_mappings), + 'nscoding_exempt_verified': list(EXPECTED_NSCODING_CLASSES), + 'sample_type_mappings': key_obf, + 'pre_self_check_rc': pre_check.returncode, + 'post_self_check_rc': post_check.returncode, + } + + +def target_interm_dir(scheme: str) -> Path: + return DD_PATH / f'Build/Intermediates.noindex/ArchiveIntermediates/{scheme}/IntermediateBuildFilesPath/readoor.build/Release-iphoneos/{scheme}.build' + + +def run_archive( + repo_dir: Path, + scheme: str, + step_tag: str, + extra_settings: list, + log_path: Path, + clean_first: bool = True, + use_cache: bool = True, + require_llvm_obf: bool = True, +) -> float: + free_gb = check_disk_budget() + print(f'\n=== [{step_tag}] repo={repo_dir.name} scheme={scheme} disk_free={free_gb}GB ===', flush=True) + archive_path = ARCHIVE_DIR / f'{scheme}.xcarchive' + if archive_path.exists(): + shutil.rmtree(archive_path) + archive_path.parent.mkdir(parents=True, exist_ok=True) + DD_PATH.mkdir(parents=True, exist_ok=True) + + env = os.environ.copy() + if require_llvm_obf: + env['IG_REQUIRE_LLVM_OBF'] = '1' + else: + env.pop('IG_REQUIRE_LLVM_OBF', None) + + if use_cache: + obj_cache = CACHE_ROOT / 'obj_cache' + sdk_cache = CACHE_ROOT / 'sdk_cache' + obj_cache.mkdir(parents=True, exist_ok=True) + sdk_cache.mkdir(parents=True, exist_ok=True) + env['IG_OBF_OBJ_CACHE_DIR'] = str(obj_cache) + env['IG_SDK_CACHE_DIR'] = str(sdk_cache) + else: + env.pop('IG_OBF_OBJ_CACHE_DIR', None) + env.pop('IG_SDK_CACHE_DIR', None) + + base_cmd = [ + 'xcodebuild', + '-workspace', str(repo_dir / 'readoor.xcworkspace'), + '-scheme', scheme, + '-configuration', 'Release', + '-destination', 'generic/platform=iOS', + '-derivedDataPath', str(DD_PATH), + 'CODE_SIGNING_ALLOWED=NO', + *extra_settings, + ] + if clean_first: + subprocess.run([*base_cmd, 'clean'], cwd=repo_dir, env=env, capture_output=True, text=True) + + cmd = [*base_cmd, '-archivePath', str(archive_path), 'archive'] + t0 = time.monotonic() + res = subprocess.run(cmd, cwd=repo_dir, env=env, capture_output=True, text=True) + elapsed = round(time.monotonic() - t0, 2) + text_log = res.stdout + '\n' + res.stderr + ig_lines = [l for l in text_log.splitlines() if '[IGRoute2]' in l or '[IGObf]' in l or 'ARCHIVE ' in l or 'error:' in l] + log_path.write_text('\n'.join(ig_lines[-140:] + ['', '--- tail ---'] + text_log.splitlines()[-100:]) + '\n', encoding='utf-8') + if res.returncode != 0: + raise RuntimeError(f'[{step_tag}] xcodebuild failed (rc={res.returncode}):\n' + '\n'.join(text_log.splitlines()[-120:])) + return elapsed + + +def inspect_app_route2(app_dir: Path, step_tag: str) -> dict: + out_dir = RESULTS_DIR / step_tag / 'route2' + out_dir.mkdir(parents=True, exist_ok=True) + binaries, total = scan(app_dir, out_dir, step_tag) + counts = {} + for info in binaries.values(): + for sl in info['slices']: + for k, v in sl['counts'].items(): + counts[k] = counts.get(k, 0) + v + return {'binaries': len(binaries), 'direct_call_total': total, 'direct_call_counts': counts} + + +def verify_required_targets(audit_path: Path, policy: dict, expect_l1_translation: bool = True) -> dict: + obf_audit = json.loads(audit_path.read_text(encoding='utf-8')) + req_by_id = {r['id']: r for r in (obf_audit.get('required_targets') or [])} + policy_reqs = policy.get('required_targets') or [] + assert len(req_by_id) == len(policy_reqs), f'Expected {len(policy_reqs)} required_targets, got {list(req_by_id.keys())}' + for req in policy_reqs: + tid = req['id'] + got = req_by_id.get(tid) + assert got is not None, f'Missing required_target audit entry: {tid}' + assert got['flattened_hits'] >= int(req.get('min_flattened', 0)), f'{tid} flattened_hits failed: {got} vs {req}' + assert got['strings_encrypted_hits'] >= int(req.get('min_strings_encrypted', 0)), f'{tid} strings_encrypted_hits failed: {got} vs {req}' + if expect_l1_translation: + assert obf_audit.get('l1_translation_active') is True, f'Expected l1_translation_active=True in {audit_path}' + return obf_audit + + +def otool_cstring_bytes(obj_path: Path) -> bytes: + out = subprocess.check_output(['xcrun', 'otool', '-s', '__TEXT', '__cstring', str(obj_path)], text=True, errors='replace') + chunks = [] + for line in out.splitlines(): + parts = line.split('\t') + if len(parts) == 2 and parts[0].strip().endswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')): + hex_bytes = parts[1].strip().split() + try: + chunks.append(bytes(int(h, 16) for h in hex_bytes)) + except ValueError: + pass + return b''.join(chunks) + + +def audit_m3_static_clues(main_bin: Path, obj_base: Path, l1_repo: Path) -> dict: + fwd_map, _ = ig_toolchain_resolver.load_l1_forward_symbol_map(l1_repo) + logdiag_sym = fwd_map.get('logDiag', 'logDiag') + logdiag_mangled_sub = f'{len(logdiag_sym)}{logdiag_sym}' + + names = [ + 'RDSDKeyBox', 'RDSDPrivateKeyManager', 'RDSDAuthV32Signer', 'RDJWTPayloadParser', + 'RDBaseNetworkService', 'RDSecurityGuard', 'RDInjectionDetector', + 'RDIAPPurchaseManager', 'RDIAPHandler', 'STSIAPVerifyHandler', + 'STSIAPVerifyTask', 'STSIAPKeyChainHandler', + ] + swift_macho_dir = obj_base / 'ig-swift-macho' + objs = {} + for n in names: + cand_sw = sorted(swift_macho_dir.glob(f'*_{n}.o')) if swift_macho_dir.is_dir() else [] + cand_plain = obj_base / f'{n}.o' + objs[n] = cand_sw[0] if cand_sw else (cand_plain if cand_plain.is_file() else None) + + forbidden_clues = [ + b'readoor_sd_v32', b'KSDPrivateKeyPEM', b'encrypted_private_key', + b'rd_net_cfg_v1', b'rd_glyph_lut_v2', + b'cn.touchv.payment.models.keychain', b'[SDAuthV32]', b'[IAP]', + b'[Security]', b'Exception: No product matched', b'7ARrksiF7AoWXXBlmxfz9suSmTka7A', + ] + host_path_clue = b'/Users/shenlei/Work/ReadBook' + obj_hits = {} + for name, p in objs.items(): + if not p or not p.is_file(): + obj_hits[name] = {'missing': True} + continue + raw = p.read_bytes() + cstring_raw = otool_cstring_bytes(p) + hits = {} + for pat in forbidden_clues: + cnt = raw.count(pat) + if cnt > 0: + hits[pat.decode('ascii', errors='replace')] = cnt + hp_cnt = cstring_raw.count(host_path_clue) + if hp_cnt > 0: + hits['__cstring_host_path'] = hp_cnt + obj_hits[name] = hits + + main_raw = main_bin.read_bytes() + main_forbidden = {p.decode('ascii', errors='replace'): main_raw.count(p) for p in forbidden_clues} + + logdiag_swift_objs = [ + 'RDSDPrivateKeyManager', 'RDSDAuthV32Signer', 'RDSecurityGuard', + 'RDInjectionDetector', 'RDIAPPurchaseManager', 'RDIAPHandler', + ] + logdiag_linked = [] + for n in logdiag_swift_objs: + p = objs.get(n) + if p and p.is_file(): + nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(p)], text=True, errors='replace') + matched = logdiag_mangled_sub in nm_u or '7logDiag' in nm_u + if not matched: + swift_undef = [ + tok for ln in nm_u.splitlines() if ln.strip() + for tok in (ln.split()[-1],) if tok.startswith(('_$s', '$s')) + ] + if swift_undef: + dm_res = subprocess.run( + ['xcrun', 'swift-demangle', '--compact'], + input='\n'.join(swift_undef) + '\n', + capture_output=True, text=True, + ) + if dm_res.returncode == 0: + matched = any(logdiag_sym in dm or 'logDiag' in dm for dm in dm_res.stdout.splitlines()) + if matched: + logdiag_linked.append(n) + + return { + 'object_clue_hits': obj_hits, + 'main_binary_forbidden_counts': main_forbidden, + 'logDiag_translated_symbol': logdiag_mangled_sub, + 'logDiag_symbol_linked_objects': logdiag_linked, + 'logDiag_symbol_linked_objects_count': len(logdiag_linked), + } + + +def verify_m3_symbolication( + app_dir: Path, + bin_name: str, + dsyms_dir: Path, + symbol_map_path: Path, + method_map_path: Path, + l1_info: dict, +) -> dict: + main_bin = app_dir / bin_name + main_dwarf = dsyms_dir / f'{bin_name}.app.dSYM/Contents/Resources/DWARF/{bin_name}' + guard_bin = app_dir / 'Frameworks/RDCoreIO.framework/RDCoreIO' + guard_dwarf = dsyms_dir / 'RDCoreIO.framework.dSYM/Contents/Resources/DWARF/RDCoreIO' + + def find_sym(dwarf_p: Path, sub: str) -> int: + out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_p)], text=True).splitlines() + for l in out: + parts = l.strip().split(maxsplit=2) + if len(parts) == 3 and parts[1].lower() == 't' and sub in parts[2]: + return int(parts[0], 16) + raise RuntimeError(f'Symbol matching {sub} not found in {dwarf_p}') + + def text_vm(bin_p: Path) -> int: + out = subprocess.check_output(['otool', '-l', str(bin_p)], text=True).splitlines() + for i, l in enumerate(out): + if 'segname __TEXT' in l: + for j in range(i + 1, min(i + 6, len(out))): + if 'vmaddr' in out[j]: + return int(out[j].split()[1], 16) + return 0x100000000 + + obf_signer = l1_info['sample_type_mappings']['RDSDAuthV32Signer'] + obf_iap = l1_info['sample_type_mappings']['STSIAPVerifyHandler'] + + kb_vm = find_sym(main_dwarf, 'rd_sd_derive_aes256_key') + signer_vm = find_sym(main_dwarf, obf_signer) + iap_vm = find_sym(main_dwarf, obf_iap) + fw_vm = find_sym(guard_dwarf, 'rd_io_chk') + + main_uid = next(iter(uuids_of(main_bin))) + fw_uid = next(iter(uuids_of(guard_bin))) + main_base = text_vm(main_bin) + fw_base = text_vm(guard_bin) + main_load, fw_load = 0x104000000, 0x109000000 + kb_off = (kb_vm - main_base) + 4 + signer_off = (signer_vm - main_base) + 4 + iap_off = (iap_vm - main_base) + 4 + fw_off = (fw_vm - fw_base) + 4 + + with tempfile.TemporaryDirectory() as td: + p = Path(td) + ips_p = p / f'{bin_name}.ips' + ips_p.write_text( + json.dumps({'app_name': bin_name, 'bug_type': '309'}) + '\n' + + json.dumps({ + 'usedImages': [ + {'base': main_load, 'size': 0x4000000, 'uuid': main_uid, 'name': bin_name, 'arch': 'arm64', 'path': f'/private/var/{bin_name}.app/{bin_name}'}, + {'base': fw_load, 'size': 0x400000, 'uuid': fw_uid, 'name': 'RDCoreIO', 'arch': 'arm64', 'path': f'/private/var/{bin_name}.app/Frameworks/RDCoreIO.framework/RDCoreIO'}, + ], + 'threads': [{ + 'triggered': True, + 'frames': [ + {'imageIndex': 0, 'imageOffset': kb_off}, + {'imageIndex': 0, 'imageOffset': signer_off}, + {'imageIndex': 0, 'imageOffset': iap_off}, + {'imageIndex': 1, 'imageOffset': fw_off}, + ], + }], + }) + '\n', + encoding='utf-8', + ) + crash_p = p / f'{bin_name}.crash' + crash_p.write_text( + 'Thread 0 Crashed:\n' + f'0 {bin_name} {hex(main_load + kb_off)} {hex(main_load)} + {kb_off}\n' + f'1 {bin_name} {hex(main_load + signer_off)} {hex(main_load)} + {signer_off}\n' + f'2 {bin_name} {hex(main_load + iap_off)} {hex(main_load)} + {iap_off}\n' + f'3 RDCoreIO {hex(fw_load + fw_off)} {hex(fw_load)} + {fw_off}\n\n' + 'Binary Images:\n' + f' {hex(main_load)} - {hex(main_load + 0x4000000)} {bin_name} arm64 <{main_uid}> /private/var/{bin_name}.app/{bin_name}\n' + f' {hex(fw_load)} - {hex(fw_load + 0x400000)} RDCoreIO arm64 <{fw_uid}> /private/var/{bin_name}.app/Frameworks/RDCoreIO.framework/RDCoreIO\n', + encoding='utf-8', + ) + ips_res = restore_crash_report.restore_report(ips_p, dsyms_dir, symbol_map=symbol_map_path, method_map=method_map_path) + crash_res = restore_crash_report.restore_report(crash_p, dsyms_dir, symbol_map=symbol_map_path, method_map=method_map_path) + + for label, r in [('ips', ips_res), ('crash', crash_res)]: + raw_frames = (r.get('threads', [{}])[0].get('frames', []) if label == 'ips' else r.get('frames', [])) + raw_text = ' '.join(' '.join(f.get('raw_atos') or []) for f in raw_frames) + restored_text = ' '.join(' '.join(f.get('restored_frames') or []) for f in raw_frames) + assert obf_signer in raw_text, f'{label} raw_atos missing obfuscated signer {obf_signer}: {raw_frames}' + assert obf_iap in raw_text, f'{label} raw_atos missing obfuscated handler {obf_iap}: {raw_frames}' + assert 'RDSDAuthV32Signer' in restored_text, f'{label} failed to deobfuscate {obf_signer} -> RDSDAuthV32Signer: {restored_text}' + assert 'STSIAPVerifyHandler' in restored_text, f'{label} failed to deobfuscate {obf_iap} -> STSIAPVerifyHandler: {restored_text}' + assert 'rd_sd_derive_aes256_key' in restored_text, f'{label} missing rd_sd_derive_aes256_key: {restored_text}' + assert 'ig_archive_check' in restored_text, f'{label} missing ig_archive_check: {restored_text}' + + return {'ips': ips_res, 'crash': crash_res} + + +def prepare_signed_app(app_dir: Path, work_dir: Path, bundle_id: str, display_name: str) -> Path: + r_prof = subprocess.run( + ['openssl', 'smime', '-inform', 'der', '-verify', '-noverify', '-in', str(DEFAULT_PROFILE)], + capture_output=True, check=True, + ) + pdata = plistlib.loads(r_prof.stdout) + ent = pdata['Entitlements'] + prefix = pdata['ApplicationIdentifierPrefix'][0] + if ent['application-identifier'] != prefix + '.*' or not ent.get('get-task-allow'): + raise RuntimeError('Provisioning profile must be wildcard development profile') + if pdata['ExpirationDate'] <= datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None): + raise RuntimeError('Provisioning profile expired') + if DEFAULT_IDENTITY.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in pdata['DeveloperCertificates']}: + raise RuntimeError('Identity does not match provisioning profile') + + if work_dir.exists(): + shutil.rmtree(work_dir) + work_dir.mkdir(parents=True) + staged_app = work_dir / app_dir.name + subprocess.run(['ditto', str(app_dir), str(staged_app)], check=True) + + info_path = staged_app / 'Info.plist' + info = plistlib.loads(info_path.read_bytes()) + info['CFBundleIdentifier'] = bundle_id + info['CFBundleDisplayName'] = display_name + info.pop('CFBundleURLTypes', None) + info_path.write_bytes(plistlib.dumps(info)) + shutil.copy2(DEFAULT_PROFILE, staged_app / 'embedded.mobileprovision') + + # Handle any nested .appex plugins cleanly if present + appex_dirs = sorted( + {p for p in staged_app.rglob('*.appex') if not p.is_symlink()}, + key=lambda p: (-len(p.parts), str(p)), + ) + for appex in appex_dirs: + ext_info_p = appex / 'Info.plist' + ext_info = plistlib.loads(ext_info_p.read_bytes()) + ext_bid = f'{bundle_id}.{appex.stem}' + ext_info['CFBundleIdentifier'] = ext_bid + ext_info_p.write_bytes(plistlib.dumps(ext_info)) + shutil.copy2(DEFAULT_PROFILE, appex / 'embedded.mobileprovision') + ext_ent = dict(ent) + ext_ent['application-identifier'] = f'{prefix}.{ext_bid}' + ext_ent['keychain-access-groups'] = [f'{prefix}.{bundle_id}'] + ext_ent_p = work_dir / f'ent_{appex.stem}.plist' + ext_ent_p.write_bytes(plistlib.dumps(ext_ent)) + subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, '--entitlements', str(ext_ent_p), str(appex)], check=True) + + nested = sorted( + {p for p in staged_app.rglob('*') if not p.is_symlink() and p.suffix in ('.framework', '.dylib')}, + key=lambda p: (-len(p.parts), str(p)), + ) + for item in nested: + subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, str(item)], check=True) + + allowed = dict(ent) + allowed['application-identifier'] = f'{prefix}.{bundle_id}' + allowed['keychain-access-groups'] = [f'{prefix}.{bundle_id}'] + ent_path = work_dir / 'entitlements.plist' + ent_path.write_bytes(plistlib.dumps(allowed)) + subprocess.run( + ['codesign', '--force', '--sign', DEFAULT_IDENTITY, '--entitlements', str(ent_path), str(staged_app)], + check=True, + ) + subprocess.run(['codesign', '--verify', '--strict', str(staged_app)], check=True) + return staged_app + + +def run_device_stage(staged_app: Path, work_dir: Path, bundle_id: str, stage: str, do_install: bool = True) -> dict: + if do_install: + print(f'[device] installing {staged_app.name} ({bundle_id}) for stage={stage}...', flush=True) + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'install', 'app', + '--device', DEFAULT_DEVICE, '--timeout', '120', str(staged_app), + ], check=True) + + print(f'[device] launching {bundle_id} IG_M3_BENCH=1 IG_M3_STAGE={stage}...', flush=True) + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'process', 'launch', + '--device', DEFAULT_DEVICE, '--terminate-existing', + '-e', json.dumps({'IG_M3_BENCH': '1', 'IG_M3_STAGE': stage}), + bundle_id, + ], check=True) + + done_marker = work_dir / f'm3_eval_{stage}.done' + result_json = work_dir / f'm3_eval_{stage}.json' + + deadline = time.monotonic() + 120.0 + got_stage_done = False + while time.monotonic() < deadline: + if done_marker.is_file(): + done_marker.unlink() + elif done_marker.is_dir(): + shutil.rmtree(done_marker) + r = subprocess.run([ + 'xcrun', 'devicectl', 'device', 'copy', 'from', + '--device', DEFAULT_DEVICE, + '--domain-type', 'appDataContainer', + '--domain-identifier', bundle_id, + '--source', 'Documents/m3_eval.done', + '--destination', str(done_marker), + ], capture_output=True, text=True) + if r.returncode == 0 and done_marker.is_file(): + if done_marker.read_text(encoding='utf-8', errors='replace').strip() == stage: + got_stage_done = True + break + time.sleep(1.5) + if not got_stage_done: + raise RuntimeError(f'Timed out waiting for Documents/m3_eval.done == {stage!r} from {bundle_id}') + + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'copy', 'from', + '--device', DEFAULT_DEVICE, + '--domain-type', 'appDataContainer', + '--domain-identifier', bundle_id, + '--source', 'Documents/m3_eval.json', + '--destination', str(result_json), + ], check=True) + payload = json.loads(result_json.read_text(encoding='utf-8')) + assert payload.get('stage') == stage, f'Stage mismatch: expected {stage}, got {payload}' + assert payload.get('status') == 'ok', f'Device stage {stage} failed: {payload}' + return payload + + +def verify_host_rsa(sig_b64: str, sign_string: str, pem_bytes: bytes): + priv_key = load_pem_private_key(pem_bytes, password=None) + pub_key = priv_key.public_key() + pub_key.verify( + base64.b64decode(sig_b64), + sign_string.encode('utf-8'), + padding.PKCS1v15(), + hashes.SHA256(), + ) + + +def uninstall_app(bundle_id: str): + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'process', 'terminate', + '--device', DEFAULT_DEVICE, bundle_id, + ], capture_output=True, check=False) + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'uninstall', 'app', + '--device', DEFAULT_DEVICE, '--timeout', '60', bundle_id, + ], capture_output=True, check=False) + + +def run_regression(): + RESULTS_DIR.mkdir(parents=True, exist_ok=True) + sync_toolchain_and_integrate() + + policy_path = ROOT / 'config/ig_llvm_policy.json' + policy = json.loads(policy_path.read_text(encoding='utf-8')) + policy_stamp = sha256_bytes(policy_path.read_bytes())[:12] + + # Clear persistent L2 cache before cold archive measurement + if CACHE_ROOT.exists(): + shutil.rmtree(CACHE_ROOT) + CACHE_ROOT.mkdir(parents=True, exist_ok=True) + cleanup_build_artifacts() + + l1_info = create_clean_snapshot_and_apply_l1() + sym_map_path = Path(l1_info['symbol_map_path']) + meth_map_path = Path(l1_info['method_map_path']) + + obf_args = [ + 'IG_OBF_MODE=full', + 'IG_POLICY_PROFILE=default', + f'IG_POLICY_STAMP={policy_stamp}', + 'IG_RELEASE_SEED=m3_prod_seed_20261119', + 'IG_SWIFT_EXTRA_FLAGS=', + 'IG_C_EXTRA_FLAGS=', + ] + + # 1. Cold Cache Production Archive (readoor31, L1+L2+L3) + t_cold = run_archive( + SNAPSHOT_SRC, 'readoor31', 'm3_readoor31_cold', + obf_args, RESULTS_DIR / 'm3_readoor31_cold.log', + clean_first=True, use_cache=True, require_llvm_obf=True, + ) + app_31 = ARCHIVE_DIR / 'readoor31.xcarchive/Products/Applications/readoor31.app' + main_31 = app_31 / 'readoor31' + dsyms_31 = ARCHIVE_DIR / 'readoor31.xcarchive/dSYMs' + uuids_31_bin = uuids_of(main_31) + uuids_31_dsym = uuids_of(dsyms_31 / 'readoor31.app.dSYM') + assert uuids_31_bin and uuids_31_bin == uuids_31_dsym, (uuids_31_bin, uuids_31_dsym) + assert (app_31 / 'rd_glyph_lut_v2.dat').is_file() + r2_31 = inspect_app_route2(app_31, 'm3_readoor31_cold') + assert r2_31['binaries'] == 40 and r2_31['direct_call_total'] == 0, r2_31 + + interm_31 = target_interm_dir('readoor31') + audit_31 = verify_required_targets(interm_31 / 'ig-route2-audit/ig_obfuscation_audit.json', policy, expect_l1_translation=True) + clues_31 = audit_m3_static_clues(main_31, interm_31 / 'Objects-normal/arm64', SNAPSHOT_SRC) + for k, v in clues_31['main_binary_forbidden_counts'].items(): + assert v == 0, f'Forbidden string {k!r} found {v}x in L1+L2+L3 readoor31: {clues_31}' + for obj_name, obj_hits in clues_31['object_clue_hits'].items(): + assert not obj_hits, f'Clue hits in object {obj_name}: {obj_hits}' + assert clues_31['logDiag_symbol_linked_objects_count'] == 6, clues_31 + + sym_restore_31 = verify_m3_symbolication(app_31, 'readoor31', dsyms_31, sym_map_path, meth_map_path, l1_info) + size_31_bytes = main_31.stat().st_size + txt_31_bytes = text_section_bytes(main_31) + cold_cache_files = sum(1 for _ in CACHE_ROOT.rglob('*') if _.is_file()) + cleanup_build_artifacts() + + # 2. Warm Cache Production Archive (readoor31, L1+L2+L3, clean DD reusing L2 cache) + t_warm = run_archive( + SNAPSHOT_SRC, 'readoor31', 'm3_readoor31_warm', + obf_args, RESULTS_DIR / 'm3_readoor31_warm.log', + clean_first=True, use_cache=True, require_llvm_obf=True, + ) + app_31_warm = ARCHIVE_DIR / 'readoor31.xcarchive/Products/Applications/readoor31.app' + r2_31_warm = inspect_app_route2(app_31_warm, 'm3_readoor31_warm') + assert r2_31_warm['binaries'] == 40 and r2_31_warm['direct_call_total'] == 0, r2_31_warm + verify_required_targets(target_interm_dir('readoor31') / 'ig-route2-audit/ig_obfuscation_audit.json', policy, expect_l1_translation=True) + warm_cache_files = sum(1 for _ in CACHE_ROOT.rglob('*') if _.is_file()) + speedup = round(t_cold / t_warm, 2) if t_warm > 0 else 0.0 + cleanup_build_artifacts() + + # 3. Dual-Target Production Archive (readoor31OtherPay, L1+L2+L3) + t_otherpay = run_archive( + SNAPSHOT_SRC, 'readoor31OtherPay', 'm3_otherpay', + obf_args, RESULTS_DIR / 'm3_otherpay.log', + clean_first=True, use_cache=True, require_llvm_obf=True, + ) + app_op = ARCHIVE_DIR / 'readoor31OtherPay.xcarchive/Products/Applications/readoor31OtherPay.app' + main_op = app_op / 'readoor31OtherPay' + dsyms_op = ARCHIVE_DIR / 'readoor31OtherPay.xcarchive/dSYMs' + uuids_op_bin = uuids_of(main_op) + uuids_op_dsym = uuids_of(dsyms_op / 'readoor31OtherPay.app.dSYM') + assert uuids_op_bin and uuids_op_bin == uuids_op_dsym, (uuids_op_bin, uuids_op_dsym) + assert (app_op / 'rd_glyph_lut_v2.dat').is_file() + r2_op = inspect_app_route2(app_op, 'm3_otherpay') + assert r2_op['binaries'] == 44 and r2_op['direct_call_total'] == 0, r2_op + audit_op = verify_required_targets(target_interm_dir('readoor31OtherPay') / 'ig-route2-audit/ig_obfuscation_audit.json', policy, expect_l1_translation=True) + sym_restore_op = verify_m3_symbolication(app_op, 'readoor31OtherPay', dsyms_op, sym_map_path, meth_map_path, l1_info) + size_op_bytes = main_op.stat().st_size + txt_op_bytes = text_section_bytes(main_op) + cleanup_build_artifacts() + + # 4. Physical iPhone 16 Plus Over-Install (v1 clean -> v2 L1+L2+L3) + readoor31OtherPay (L1+L2+L3) + pem_bytes = (APP_REPO / 'AutoPacking/sd_priv_ios_v1.pem').read_bytes() + expected_pem_sha256 = sha256_bytes(pem_bytes) + bench_swift = 'IG_SWIFT_EXTRA_FLAGS=-DIG_ENABLE_M3_BENCH -Xcc -DIG_ENABLE_M3_BENCH=1' + bench_c = 'IG_C_EXTRA_FLAGS=-DIG_ENABLE_M3_BENCH=1' + + device_stages = {} + uninstall_app(BUNDLE_READOOR31) + uninstall_app(BUNDLE_OTHERPAY) + try: + # Stage 1: Clean un-obfuscated v1 seed + v1_args = [ + 'IG_ALL_GUARD_OFF=1', + 'IG_OBF_MODE=off', + bench_swift, + bench_c, + ] + t_bench_v1 = run_archive( + APP_REPO, 'readoor31', 'm3_bench_v1', + v1_args, RESULTS_DIR / 'm3_bench_v1.log', + clean_first=True, use_cache=False, require_llvm_obf=False, + ) + staged_v1 = prepare_signed_app(ARCHIVE_DIR / 'readoor31.xcarchive/Products/Applications/readoor31.app', STAGE_DIR, BUNDLE_READOOR31, 'M3Eval') + s1 = run_device_stage(staged_v1, STAGE_DIR, BUNDLE_READOOR31, 'seed_legacy_v1', do_install=True) + assert s1['keychain_present_before'] is False + assert s1['pem_sha256'] == expected_pem_sha256 + assert s1['login_view_class_obfuscated'] is False + verify_host_rsa(s1['x_sig'], s1['sign_string'], pem_bytes) + device_stages['seed_legacy_v1'] = s1 + cleanup_build_artifacts() + + # Stage 2: L1+L2+L3 v2 over-install WITHOUT uninstalling + v2_args = [ + 'IG_OBF_MODE=full', + 'IG_POLICY_PROFILE=default', + f'IG_POLICY_STAMP={policy_stamp}', + 'IG_RELEASE_SEED=m3_prod_seed_20261119', + bench_swift, + bench_c, + ] + t_bench_v2 = run_archive( + SNAPSHOT_SRC, 'readoor31', 'm3_bench_v2', + v2_args, RESULTS_DIR / 'm3_bench_v2.log', + clean_first=True, use_cache=True, require_llvm_obf=True, + ) + staged_v2 = prepare_signed_app(ARCHIVE_DIR / 'readoor31.xcarchive/Products/Applications/readoor31.app', STAGE_DIR, BUNDLE_READOOR31, 'M3Eval') + s2 = run_device_stage(staged_v2, STAGE_DIR, BUNDLE_READOOR31, 'verify_upgrade_l123', do_install=True) + assert s2['keychain_present_before'] is True, f'Over-install lost Keychain key: {s2}' + assert s2['pem_sha256'] == expected_pem_sha256 + assert s2['x_sig'] == s1['x_sig'] + assert s2['login_view_class_obfuscated'] is True + assert s2['iap_handler_class_obfuscated'] is True + assert s2['swift_media_cache_unarchive_ok'] is True + assert s2['guard_baseline_count'] >= 2 + assert s2['guard_eval_ok'] is True + assert s2['epub_decrypt_ok'] is True + verify_host_rsa(s2['x_sig'], s2['sign_string'], pem_bytes) + device_stages['verify_upgrade_l123'] = s2 + cleanup_build_artifacts() + + # Stage 3: L1+L2+L3 readoor31OtherPay device check + t_bench_op = run_archive( + SNAPSHOT_SRC, 'readoor31OtherPay', 'm3_bench_otherpay', + v2_args, RESULTS_DIR / 'm3_bench_otherpay.log', + clean_first=True, use_cache=True, require_llvm_obf=True, + ) + staged_op = prepare_signed_app(ARCHIVE_DIR / 'readoor31OtherPay.xcarchive/Products/Applications/readoor31OtherPay.app', STAGE_DIR, BUNDLE_OTHERPAY, 'M3OtherPay') + s3 = run_device_stage(staged_op, STAGE_DIR, BUNDLE_OTHERPAY, 'verify_otherpay_l123', do_install=True) + assert s3['pem_sha256'] == expected_pem_sha256 + assert s3['login_view_class_obfuscated'] is True + assert s3['iap_handler_class_obfuscated'] is True + assert s3['swift_media_cache_roundtrip_ok'] is True + assert s3['guard_baseline_count'] >= 2 + assert s3['guard_eval_ok'] is True + assert s3['epub_decrypt_ok'] is True + verify_host_rsa(s3['x_sig'], s3['sign_string'], pem_bytes) + device_stages['verify_otherpay_l123'] = s3 + cleanup_build_artifacts() + finally: + uninstall_app(BUNDLE_READOOR31) + uninstall_app(BUNDLE_OTHERPAY) + cleanup_build_artifacts() + if SNAPSHOT_SRC.exists(): + shutil.rmtree(SNAPSHOT_SRC) + if WORK_ROOT.exists(): + shutil.rmtree(WORK_ROOT) + if CACHE_ROOT.exists(): + shutil.rmtree(CACHE_ROOT) + + summary = { + 'milestone': 'M3', + 'l1_obfuscation': l1_info, + 'readoor31_production': { + 'cold_archive_elapsed_s': t_cold, + 'warm_archive_elapsed_s': t_warm, + 'cache_speedup_ratio': speedup, + 'cold_cache_files': cold_cache_files, + 'warm_cache_files': warm_cache_files, + 'main_binary_bytes': size_31_bytes, + 'main_text_bytes': txt_31_bytes, + 'size_delta_vs_m2_bytes': size_31_bytes - M2_MAIN_BYTES, + 'main_uuids': sorted(uuids_31_bin), + 'route2': r2_31, + 'obf_audit': { + 'l1_translation_active': audit_31.get('l1_translation_active'), + 'expected_swift_count': audit_31.get('expected_swift_count'), + 'converted_swift_count': audit_31.get('converted_swift_count'), + 'total_flattened': audit_31.get('total_flattened'), + 'total_strings_encrypted': audit_31.get('total_strings_encrypted'), + 'required_targets': audit_31.get('required_targets'), + }, + 'static_clues': clues_31, + 'symbolication_v2_restore': sym_restore_31, + }, + 'readoor31OtherPay_production': { + 'archive_elapsed_s': t_otherpay, + 'main_binary_bytes': size_op_bytes, + 'main_text_bytes': txt_op_bytes, + 'main_uuids': sorted(uuids_op_bin), + 'route2': r2_op, + 'obf_audit': { + 'l1_translation_active': audit_op.get('l1_translation_active'), + 'expected_swift_count': audit_op.get('expected_swift_count'), + 'converted_swift_count': audit_op.get('converted_swift_count'), + 'total_flattened': audit_op.get('total_flattened'), + 'total_strings_encrypted': audit_op.get('total_strings_encrypted'), + 'required_targets': audit_op.get('required_targets'), + }, + 'symbolication_v2_restore': sym_restore_op, + }, + 'device_verification': { + 'device_udid': DEFAULT_DEVICE, + 'bench_archive_timings_s': { + 'v1_clean': t_bench_v1, + 'v2_readoor31_l123': t_bench_v2, + 'v2_otherpay_l123': t_bench_op, + }, + 'expected_pem_sha256': expected_pem_sha256, + 'offline_host_rsa_verify_all_stages': True, + 'stages': device_stages, + }, + } + summary_path = RESULTS_DIR / 'm3_summary.json' + summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') + print(f'\n[M3] ALL CHECKS PASSED -> {summary_path}', flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.parse_args() + run_regression() + + +if __name__ == '__main__': + main() diff --git a/tools/llvm_obf/verify_m0_async_device.py b/tools/llvm_obf/verify_m0_async_device.py new file mode 100755 index 0000000..fb0de21 --- /dev/null +++ b/tools/llvm_obf/verify_m0_async_device.py @@ -0,0 +1,543 @@ +#!/usr/bin/env python3 +"""Physical-device M0-2/M0-3 verification: cross-file Swift async throws + ObjC + embedded framework + .ips/.crash restore.""" +import argparse +import datetime +import hashlib +import json +import os +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +TOOLS_ARCHIVE = ROOT / 'tools' / 'xcode_archive' +TOOLS_LLVM = ROOT / 'tools' / 'llvm_obf' +TOOLS_CRASH = ROOT / 'tools' / 'crash_restore' + +sys.path.insert(0, str(TOOLS_LLVM)) +sys.path.insert(0, str(TOOLS_ARCHIVE)) +sys.path.insert(0, str(TOOLS_CRASH)) + +from ig_ld_wrapper import verify_macho_object_platform # noqa: E402 +from ig_toolchain_resolver import detect_sdk_info, detect_stock_tool # noqa: E402 +import restore_crash_report # noqa: E402 + +DEFAULT_PROFILE = Path.home() / 'Library/Developer/Xcode/UserData/Provisioning Profiles/e0f18495-668f-4fb1-87e1-4e048fb48d11.mobileprovision' +DEFAULT_IDENTITY = '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8' +DEFAULT_DEVICE = '00008140-000960811493001C' +DEFAULT_BUNDLE_ID = 'cn.touchv.iosguard.hookpilot.m0async' + + +def run(cmd, env=None, cwd=None): + return subprocess.run(list(map(str, cmd)), env=env, cwd=cwd, capture_output=True, text=True) + + +def write_sources(src_dir): + src_dir.mkdir(parents=True, exist_ok=True) + # 1. Embedded framework (ObjC + C flattened & string-encrypted + captures live stack return addr) + fw_h = src_dir / 'IGM0ProbeKit.h' + fw_m = src_dir / 'M0Kit.m' + fw_h.write_text( + '#import \n' + '#include \n' + 'FOUNDATION_EXPORT uintptr_t ig_m0_kit_probe_address(int selector);\n', + encoding='utf-8', + ) + fw_m.write_text( + '#import "IGM0ProbeKit.h"\n' + '#include \n' + '#include \n' + '__attribute__((noinline)) static uintptr_t ig_m0_kit_leaf(void) {\n' + ' return (uintptr_t)__builtin_return_address(0) - 4;\n' + '}\n' + '__attribute__((noinline)) uintptr_t ig_m0_kit_probe_address(int selector) {\n' + ' const char *envv = getenv("IG_M0_NONEXISTENT_ENV_FLAG");\n' + ' int score = envv ? 99 : 0;\n' + ' if (selector == 1) score += 10;\n' + ' else if (selector == 2) score += 20;\n' + ' else score += 30;\n' + ' uintptr_t pc = ig_m0_kit_leaf();\n' + ' if (score == 10 || score == 20 || score == 30) {\n' + ' return pc;\n' + ' }\n' + ' return 0;\n' + '}\n', + encoding='utf-8', + ) + + # 2. ObjC main object (concurrent string decryption + multi-branch flattening) + objc_h = src_dir / 'ObjCBridge.h' + objc_m = src_dir / 'ObjCBridge.m' + objc_h.write_text( + '#import \n' + '#import "IGM0ProbeKit.h"\n' + 'FOUNDATION_EXPORT int ig_m0_objc_concurrent_check(int thread_idx);\n', + encoding='utf-8', + ) + objc_m.write_text( + '#import "ObjCBridge.h"\n' + '#include \n' + '#include \n' + '__attribute__((noinline)) static int ig_m0_branch_a(const char *s, int x) { return (int)s[x & 3] ^ x; }\n' + '__attribute__((noinline)) static int ig_m0_branch_b(const char *s, int x) { return (int)s[(x + 1) & 3] + x; }\n' + '__attribute__((noinline)) int ig_m0_objc_concurrent_check(int thread_idx) {\n' + ' const char *envv = getenv("M0_DEVICE_CONCURRENT_OBJC_SECRET");\n' + ' const char *secret = "M0_DEVICE_CONCURRENT_OBJC_SECRET";\n' + ' int base = envv ? 99 : 33;\n' + ' int r = 0;\n' + ' if (thread_idx == 0) { r = ig_m0_branch_a(secret, 1); }\n' + ' else if (thread_idx == 1) { r = ig_m0_branch_b(secret, 2); }\n' + ' else if (thread_idx == 2) { r = ig_m0_branch_a(secret, 3); }\n' + ' else { r = ig_m0_branch_b(secret, 4); }\n' + ' if (r == 0x7fffffff) return -1;\n' + ' return base + (thread_idx & 3);\n' + '}\n', + encoding='utf-8', + ) + + # 3. Cross-file Swift 1: AsyncWorker.swift + (src_dir / 'AsyncWorker.swift').write_text( + 'import Foundation\n' + '\n' + 'enum M0AsyncError: Error {\n' + ' case simulatedFailure(Int)\n' + '}\n' + '\n' + 'final class AsyncWorker {\n' + ' @inline(never)\n' + ' static func stepMix(_ tag: Int, _ val: UnsafePointer?) -> Int {\n' + ' let extra = (val != nil) ? Int(strlen(val!)) : 0\n' + ' return tag + extra + Int(ProcessInfo.processInfo.processIdentifier & 0)\n' + ' }\n' + '\n' + ' @inline(never)\n' + ' static func controlledEnvCheck(_ mode: Int) -> Int {\n' + ' let val = getenv("M0_DEVICE_SWIFT_CONTROLLED_VAR")\n' + ' var acc = 10\n' + ' if mode == 1 { acc += stepMix(7, val) }\n' + ' else if mode == 2 { acc += stepMix(14, val) }\n' + ' else { acc += stepMix(21, val) }\n' + ' if acc > 50 { acc += stepMix(1, val) }\n' + ' return acc\n' + ' }\n' + '\n' + ' static func computeAsync(value: Int, shouldThrow: Bool) async throws -> Int {\n' + ' try await Task.sleep(nanoseconds: 5_000_000)\n' + ' try Task.checkCancellation()\n' + ' let base = controlledEnvCheck(value)\n' + ' try await Task.sleep(nanoseconds: 3_000_000)\n' + ' if shouldThrow {\n' + ' throw M0AsyncError.simulatedFailure(base + 1)\n' + ' }\n' + ' return base * 2\n' + ' }\n' + '\n' + ' static func cancellableWork() async throws -> Int {\n' + ' while true {\n' + ' try Task.checkCancellation()\n' + ' try await Task.sleep(nanoseconds: 4_000_000)\n' + ' }\n' + ' }\n' + '}\n', + encoding='utf-8', + ) + + # 4. Cross-file Swift 2: AsyncCaller.swift (async @main calling AsyncWorker + IGM0ProbeKit + ObjCBridge) + (src_dir / 'AsyncCaller.swift').write_text( + 'import Foundation\n' + 'import MachO\n' + '\n' + '@main\n' + 'struct M0Entry {\n' + ' @inline(never)\n' + ' static func logLine(_ s: String) {\n' + ' NSLog("%@", s)\n' + ' fputs(s + "\\n", stderr)\n' + ' fflush(stderr)\n' + ' }\n' + '\n' + ' @inline(never)\n' + ' static func captureMainCallerFrame() -> UInt {\n' + ' let stack = Thread.callStackReturnAddresses\n' + ' let ra = stack.first?.uintValue ?? 0\n' + ' return ra > 4 ? (ra - 4) : 0\n' + ' }\n' + '\n' + ' static func imageInfoString(matching nameSuffix: String) -> String {\n' + ' for i in 0..<_dyld_image_count() {\n' + ' guard let cname = _dyld_get_image_name(i) else { continue }\n' + ' let path = String(cString: cname)\n' + ' if path.hasSuffix(nameSuffix), let hdr = _dyld_get_image_header(i) {\n' + ' let base = UInt(bitPattern: hdr)\n' + ' return "\\(nameSuffix)|0x\\(String(base, radix: 16))|\\(path)"\n' + ' }\n' + ' }\n' + ' return "\\(nameSuffix)|0x0|missing"\n' + ' }\n' + '\n' + ' static func main() async {\n' + ' // 1. Cross-file async normal resume\n' + ' do {\n' + ' let v = try await AsyncWorker.computeAsync(value: 2, shouldThrow: false)\n' + ' logLine("M0_DEV_CASE async_normal_resume \\(v == 48 ? "PASS" : "FAIL(\\(v))")")\n' + ' } catch {\n' + ' logLine("M0_DEV_CASE async_normal_resume FAIL(\\(error))")\n' + ' }\n' + ' // 2. Cross-file async throw/catch across suspension\n' + ' do {\n' + ' _ = try await AsyncWorker.computeAsync(value: 1, shouldThrow: true)\n' + ' logLine("M0_DEV_CASE async_throw_catch FAIL(no_throw)")\n' + ' } catch M0AsyncError.simulatedFailure(let code) {\n' + ' logLine("M0_DEV_CASE async_throw_catch \\(code == 18 ? "PASS" : "FAIL(\\(code))")")\n' + ' } catch {\n' + ' logLine("M0_DEV_CASE async_throw_catch FAIL(\\(error))")\n' + ' }\n' + ' // 3. Cross-file async cancellation\n' + ' let t = Task { try await AsyncWorker.cancellableWork() }\n' + ' try? await Task.sleep(nanoseconds: 12_000_000)\n' + ' t.cancel()\n' + ' do {\n' + ' _ = try await t.value\n' + ' logLine("M0_DEV_CASE async_cancellation FAIL(completed)")\n' + ' } catch is CancellationError {\n' + ' logLine("M0_DEV_CASE async_cancellation PASS")\n' + ' } catch {\n' + ' logLine("M0_DEV_CASE async_cancellation FAIL(\\(error))")\n' + ' }\n' + ' // 4. 8-thread concurrent flattened ObjC + encrypted string\n' + ' let grp = DispatchGroup()\n' + ' let q = DispatchQueue.global(qos: .userInitiated)\n' + ' let lock = NSLock()\n' + ' var ok = true\n' + ' for idx in 0..<8 {\n' + ' grp.enter()\n' + ' q.async {\n' + ' let r = ig_m0_objc_concurrent_check(Int32(idx % 4))\n' + ' let expected = Int32(33 + (idx % 4))\n' + ' if r != expected {\n' + ' lock.lock(); ok = false; lock.unlock()\n' + ' }\n' + ' grp.leave()\n' + ' }\n' + ' }\n' + ' grp.wait()\n' + ' logLine("M0_DEV_CASE objc_concurrent_str_flatten \\(ok ? "PASS" : "FAIL")")\n' + '\n' + ' // 5. Capture runtime addresses from main app & embedded framework\n' + ' let mainImg = imageInfoString(matching: "/IGM0AsyncPilot")\n' + ' let kitImg = imageInfoString(matching: "/IGM0ProbeKit")\n' + ' let kitAddr = ig_m0_kit_probe_address(2)\n' + ' let mainAddr = captureMainCallerFrame()\n' + ' logLine("M0_RUNTIME_IMG \\(mainImg)")\n' + ' logLine("M0_RUNTIME_IMG \\(kitImg)")\n' + ' logLine(String(format: "M0_RUNTIME_FRAME main=0x%lx kit=0x%lx", UInt(mainAddr), UInt(kitAddr)))\n' + ' }\n' + '}\n', + encoding='utf-8', + ) + + +def verify_and_run(device, profile, identity, bundle_id, output_dir): + output_dir = Path(output_dir).resolve() + if output_dir.exists(): + shutil.rmtree(output_dir) + output_dir.mkdir(parents=True) + + r_prof = subprocess.run(['openssl', 'smime', '-inform', 'der', '-verify', '-noverify', '-in', str(profile)], + capture_output=True, check=True) + pdata = plistlib.loads(r_prof.stdout) + ent = pdata['Entitlements'] + prefix = pdata['ApplicationIdentifierPrefix'][0] + if ent['application-identifier'] != prefix + '.*' or not ent.get('get-task-allow'): + raise RuntimeError('Provisioning profile must be wildcard development profile') + if pdata['ExpirationDate'] <= datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None): + raise RuntimeError('Provisioning profile expired') + if identity.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in pdata['DeveloperCertificates']}: + raise RuntimeError('Identity does not match provisioning profile') + + src_dir = output_dir / 'src' + write_sources(src_dir) + + policy_path = output_dir / 'm0_device_policy.json' + policy_path.write_text(json.dumps({ + 'exempt_path_substrings': [], + 'exempt_function_prefixes': [], + 'string_encrypt_targets': [ + {'path_contains': 'M0Kit.m'}, + {'path_contains': 'ObjCBridge.m'}, + {'path_contains': 'AsyncWorker.swift'}, + ], + 'flatten_targets': [ + {'path_contains': 'M0Kit.m', 'function_contains': 'ig_m0_kit_probe_address'}, + {'path_contains': 'ObjCBridge.m', 'function_contains': 'ig_m0_objc_concurrent_check'}, + {'path_contains': 'AsyncWorker.swift', 'function_contains': '18controlledEnvCheck'}, + ], + 'required_targets': [ + {'id': 'dev_objc', 'path_contains': 'ObjCBridge.m', 'symbol_contains': 'ig_m0_objc_concurrent_check', 'min_flattened': 1, 'min_strings_encrypted': 1}, + {'id': 'dev_swift', 'path_contains': 'AsyncWorker.swift', 'symbol_contains': '18controlledEnvCheck', 'min_flattened': 1, 'min_strings_encrypted': 1}, + ], + }, indent=2), encoding='utf-8') + + sdk_info = detect_sdk_info() + sdk = sdk_info['sdk_path'] + swiftc = detect_stock_tool('swiftc') + cc_wrapper = str(TOOLS_ARCHIVE / 'ig_cc_wrapper.py') + ld_wrapper = str(TOOLS_ARCHIVE / 'ig_ld_wrapper.py') + + env = dict(os.environ) + env['IG_LLVM_POLICY_PATH'] = str(policy_path) + env['IG_OBF_MODE'] = 'full' + env['IG_LLVM_PASS_FILTER'] = 'all' + env['IG_ROUTE2_MODE'] = 'off' + env['IG_ALL_GUARD_OFF'] = '0' + env['IG_RELEASE_SEED'] = 'm0_device_seed_1' + env['IG_REQUIRE_LLVM_OBF'] = '1' + env['CONFIGURATION'] = 'Release' + env['PLATFORM_NAME'] = 'iphoneos' + env['SRCROOT'] = str(src_dir) + env['TARGET_TEMP_DIR'] = str(output_dir / 'temp') + + app_dir = output_dir / 'IGM0AsyncPilot.app' + fw_dir = app_dir / 'Frameworks' / 'IGM0ProbeKit.framework' + dsym_dir = output_dir / 'dSYMs' + fw_dir.mkdir(parents=True) + dsym_dir.mkdir(parents=True) + + # Build embedded IGM0ProbeKit.framework via ig_cc_wrapper.py + fw_obj = output_dir / 'M0Kit.o' + p1 = run([ + cc_wrapper, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, + '-Os', '-g', '-fobjc-arc', '-fPIC', '-I', str(src_dir), + '-c', str(src_dir / 'M0Kit.m'), '-o', str(fw_obj), + ], env=env) + if p1.returncode != 0: + raise RuntimeError(f'M0Kit.m failed:\n{p1.stdout}\n{p1.stderr}') + + clang = detect_stock_tool('clang') + fw_bin = fw_dir / 'IGM0ProbeKit' + subprocess.run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, '-dynamiclib', + str(fw_obj), '-framework', 'Foundation', + '-Wl,-install_name,@rpath/IGM0ProbeKit.framework/IGM0ProbeKit', + '-o', str(fw_bin), + ], check=True) + subprocess.run(['xcrun', 'dsymutil', str(fw_bin), '-o', str(dsym_dir / 'IGM0ProbeKit.framework.dSYM')], check=True) + (fw_dir / 'Info.plist').write_bytes(plistlib.dumps({ + 'CFBundleExecutable': 'IGM0ProbeKit', + 'CFBundleIdentifier': bundle_id + '.probekit', + 'CFBundleInfoDictionaryVersion': '6.0', + 'CFBundleName': 'IGM0ProbeKit', + 'CFBundlePackageType': 'FMWK', + 'CFBundleShortVersionString': '1.0', + 'CFBundleSupportedPlatforms': ['iPhoneOS'], + 'CFBundleVersion': '1', + 'MinimumOSVersion': '15.0', + })) + + # Compile ObjCBridge.m via ig_cc_wrapper.py + obj_dir = output_dir / 'objs' + obj_dir.mkdir() + objc_obj = obj_dir / 'ObjCBridge.o' + p2 = run([ + cc_wrapper, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, + '-Os', '-g', '-fobjc-arc', '-I', str(src_dir), + '-c', str(src_dir / 'ObjCBridge.m'), '-o', str(objc_obj), + ], env=env) + if p2.returncode != 0: + raise RuntimeError(f'ObjCBridge.m failed:\n{p2.stdout}\n{p2.stderr}') + + # Compile cross-file Swift via stock swiftc -O -g -lto=llvm-thin using OutputFileMap.json (matching Xcode SWIFT_LTO=YES_THIN) + w_src = str(src_dir / 'AsyncWorker.swift') + c_src = str(src_dir / 'AsyncCaller.swift') + w_obj = obj_dir / 'AsyncWorker.o' + c_obj = obj_dir / 'AsyncCaller.o' + w_bc = obj_dir / 'AsyncWorker.bc' + c_bc = obj_dir / 'AsyncCaller.bc' + ofm_path = obj_dir / 'IGM0AsyncPilot-OutputFileMap.json' + ofm_path.write_text(json.dumps({ + '': {'swift-dependencies': str(obj_dir / 'master.swiftdeps')}, + w_src: {'object': str(w_obj), 'llvm-bc': str(w_bc)}, + c_src: {'object': str(c_obj), 'llvm-bc': str(c_bc)}, + }, indent=2), encoding='utf-8') + filelist_path = obj_dir / 'IGM0AsyncPilot.LinkFileList' + filelist_path.write_text('\n'.join([str(objc_obj), str(w_bc), str(c_bc)]) + '\n', encoding='utf-8') + + p_sw = run([ + swiftc, '-sdk', sdk, '-target', 'arm64-apple-ios15.0', + '-module-name', 'IGM0AsyncPilot', + '-O', '-g', '-lto=llvm-thin', + '-import-objc-header', str(src_dir / 'ObjCBridge.h'), + '-I', str(src_dir), + '-output-file-map', str(ofm_path), + '-c', w_src, c_src, + ], env=env) + if p_sw.returncode != 0: + raise RuntimeError(f'swiftc failed:\n{p_sw.stdout}\n{p_sw.stderr}') + + # Link main executable through real ig_ld_wrapper.py (--ld-path) + app_bin = app_dir / 'IGM0AsyncPilot' + linkmap_p = output_dir / 'temp' / 'IGM0AsyncPilot-LinkMap.txt' + linkmap_p.parent.mkdir(parents=True, exist_ok=True) + p_ld = run([ + clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, + f'--ld-path={ld_wrapper}', + '-Wl,-ig_stamp,ctl_full__all__off__0__m0_device_seed_1__devstamp1', + f'-Wl,-filelist,{filelist_path}', + f'-Wl,-map,{linkmap_p}', + '-Wl,-rpath,@executable_path/Frameworks', + str(fw_bin), + '-L', str(Path(swiftc).parents[1] / 'lib/swift/iphoneos'), + '-L', str(Path(sdk) / 'usr/lib/swift'), + '-framework', 'UIKit', '-framework', 'Foundation', '-lobjc', + '-o', str(app_bin), + ], env=env) + if p_ld.returncode != 0: + raise RuntimeError(f'ig_ld_wrapper link failed:\n{p_ld.stdout}\n{p_ld.stderr}') + + # Check converted Swift objects LC_BUILD_VERSION + swift_machos = sorted((obj_dir / 'ig-swift-macho').glob('*.o')) + assert len(swift_machos) == 2, f'Expected 2 converted Swift objects, got {swift_machos}' + lc_versions = {m.name: verify_macho_object_platform(m) for m in swift_machos} + + subprocess.run(['xcrun', 'dsymutil', str(app_bin), '-o', str(dsym_dir / 'IGM0AsyncPilot.app.dSYM')], check=True) + (app_dir / 'Info.plist').write_bytes(plistlib.dumps({ + 'CFBundleExecutable': 'IGM0AsyncPilot', + 'CFBundleIdentifier': bundle_id, + 'CFBundleName': 'IGM0AsyncPilot', + 'CFBundleDisplayName': 'IGM0AsyncPilot', + 'CFBundlePackageType': 'APPL', + 'CFBundleVersion': '1', + 'CFBundleShortVersionString': '1.0', + 'MinimumOSVersion': '15.0', + 'LSRequiresIPhoneOS': True, + 'UIDeviceFamily': [1, 2], + 'UILaunchScreen': {}, + })) + shutil.copy2(profile, app_dir / 'embedded.mobileprovision') + ent_plist = dict(ent) + ent_plist['application-identifier'] = f'{prefix}.{bundle_id}' + ent_plist['keychain-access-groups'] = [f'{prefix}.{bundle_id}'] + (output_dir / 'ent.plist').write_bytes(plistlib.dumps(ent_plist)) + + subprocess.run(['codesign', '--force', '--sign', identity, str(fw_dir)], check=True) + subprocess.run(['codesign', '--force', '--sign', identity, '--entitlements', str(output_dir / 'ent.plist'), str(app_dir)], check=True) + + # Install and launch on physical device; guarantee uninstall afterwards + installed = False + try: + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'install', 'app', + '--device', device, '--timeout', '60', str(app_dir), + ], check=True) + installed = True + launch = subprocess.run([ + 'xcrun', 'devicectl', 'device', 'process', 'launch', + '--device', device, '--console', '--timeout', '25', + '--terminate-existing', bundle_id, + ], capture_output=True, text=True) + console_log = launch.stdout + '\n' + launch.stderr + (output_dir / 'device-console.log').write_text(console_log, encoding='utf-8') + finally: + if installed: + subprocess.run([ + 'xcrun', 'devicectl', 'device', 'uninstall', 'app', + '--device', device, '--timeout', '60', bundle_id, + ], check=False) + + cases = {} + for m in re.finditer(r'M0_DEV_CASE\s+(\S+)\s+(PASS|FAIL(?:\([^)]*\))?)', console_log): + cases[m.group(1)] = m.group(2) + + img_bases = {} + for m in re.finditer(r'M0_RUNTIME_IMG\s+([^|\s]+)\|(0x[0-9a-fA-F]+)\|(\S+)', console_log): + img_bases[m.group(1)] = {'base': int(m.group(2), 16), 'path': m.group(3)} + + frame_m = re.search(r'M0_RUNTIME_FRAME\s+main=(0x[0-9a-fA-F]+)\s+kit=(0x[0-9a-fA-F]+)', console_log) + if not frame_m: + raise RuntimeError(f'Missing M0_RUNTIME_FRAME in device console:\n{console_log}') + + main_pc = int(frame_m.group(1), 16) + kit_pc = int(frame_m.group(2), 16) + main_base = img_bases['/IGM0AsyncPilot']['base'] + kit_base = img_bases['/IGM0ProbeKit']['base'] + + def uuid_of(path): + out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True) + return out.split()[1] + + main_uid = uuid_of(app_bin) + kit_uid = uuid_of(fw_bin) + + # Symbolicate live device addresses in BOTH .ips JSON and .crash text formats! + ips_p = output_dir / 'device_live.ips' + ips_p.write_text( + json.dumps({'app_name': 'IGM0AsyncPilot', 'bug_type': '309'}) + '\n' + + json.dumps({ + 'usedImages': [ + {'base': main_base, 'size': 0x40000, 'uuid': main_uid, 'name': 'IGM0AsyncPilot', 'arch': 'arm64', 'path': img_bases['/IGM0AsyncPilot']['path']}, + {'base': kit_base, 'size': 0x10000, 'uuid': kit_uid, 'name': 'IGM0ProbeKit', 'arch': 'arm64', 'path': img_bases['/IGM0ProbeKit']['path']}, + ], + 'threads': [{ + 'triggered': True, + 'frames': [ + {'imageIndex': 0, 'imageOffset': main_pc - main_base}, + {'imageIndex': 1, 'imageOffset': kit_pc - kit_base}, + ], + }], + }) + '\n', + encoding='utf-8', + ) + crash_p = output_dir / 'device_live.crash' + crash_p.write_text( + 'Thread 0 Crashed:\n' + f'0 IGM0AsyncPilot {hex(main_pc)} {hex(main_base)} + {main_pc - main_base}\n' + f'1 IGM0ProbeKit {hex(kit_pc)} {hex(kit_base)} + {kit_pc - kit_base}\n\n' + 'Binary Images:\n' + f' {hex(main_base)} - {hex(main_base + 0x40000)} IGM0AsyncPilot arm64 <{main_uid}> {img_bases["/IGM0AsyncPilot"]["path"]}\n' + f' {hex(kit_base)} - {hex(kit_base + 0x10000)} IGM0ProbeKit arm64 <{kit_uid}> {img_bases["/IGM0ProbeKit"]["path"]}\n', + encoding='utf-8', + ) + + sym_ips = restore_crash_report.restore_report(ips_p, dsym_dir) + sym_crash = restore_crash_report.restore_report(crash_p, dsym_dir) + + audit_file = output_dir / 'temp' / 'ig-route2-audit' / 'ig_obfuscation_audit.json' + audit = json.loads(audit_file.read_text(encoding='utf-8')) + + result = { + 'device': device, + 'lc_build_version': lc_versions, + 'cases': cases, + 'obf_audit': audit, + 'ips_restored': sym_ips, + 'crash_restored': sym_crash, + } + (output_dir / 'device-m0-verification.json').write_text( + json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8' + ) + + expected_cases = ('async_normal_resume', 'async_throw_catch', 'async_cancellation', 'objc_concurrent_str_flatten') + for cname in expected_cases: + if cases.get(cname) != 'PASS': + raise AssertionError(f'Device case {cname} did not PASS: {cases}') + return result + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--device', default=DEFAULT_DEVICE) + p.add_argument('--profile', type=Path, default=DEFAULT_PROFILE) + p.add_argument('--identity', default=DEFAULT_IDENTITY) + p.add_argument('--bundle-id', default=DEFAULT_BUNDLE_ID) + p.add_argument('--output', type=Path, default=Path('/tmp/ig-m0-async-device')) + a = p.parse_args() + res = verify_and_run(a.device, a.profile, a.identity, a.bundle_id, a.output) + print(json.dumps(res, ensure_ascii=False, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/llvm_obf/verify_macho_indirect_branches.py b/tools/llvm_obf/verify_macho_indirect_branches.py new file mode 100644 index 0000000..6460086 --- /dev/null +++ b/tools/llvm_obf/verify_macho_indirect_branches.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Verify that every indirect-branch obfuscated function emits ARM64 `br xN` instructions in Mach-O.""" +import argparse +from concurrent.futures import ThreadPoolExecutor +import json +from pathlib import Path +import subprocess + +from verify_macho_star_cfg import ( + JUMP_TABLE_BR_RE, + _candidate_symbol_keys, + parse_dwarf_text_ranges, +) + + +def _count_br_insns(main_bin: Path, start_addr: int, end_addr: int) -> dict: + dis = subprocess.check_output( + [ + 'xcrun', 'llvm-objdump', '--disassemble', + f'--start-address={hex(start_addr)}', + f'--stop-address={hex(end_addr)}', + str(main_bin), + ], + text=True, + ) + br_count = sum(1 for line in dis.splitlines() if JUMP_TABLE_BR_RE.search(line)) + return { + 'start_addr': hex(start_addr), + 'end_addr': hex(end_addr), + 'indirect_br_count': br_count, + } + + +def verify_binary_indirect_branches( + main_bin: Path, + dwarf_bin: Path, + obf_audit: dict, + *, + fail_on_missing: bool = False, +) -> dict: + """Disassemble every audited IBR function in main_bin and require >=1 `br xN`.""" + ranges_map = parse_dwarf_text_ranges(dwarf_bin) + verified = [] + failed = [] + dead_stripped = [] + + to_check: list[tuple[str, str, list[tuple[int, int]]]] = [] + for mod in obf_audit.get('module_audits') or []: + src_name = Path(mod.get('source_path') or 'unknown').name + for raw_name in mod.get('indirect_branches_functions') or []: + cand_ranges = [] + for key in _candidate_symbol_keys(raw_name): + if key in ranges_map: + cand_ranges = ranges_map[key] + break + if not cand_ranges: + rec = {'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'} + dead_stripped.append(rec) + if fail_on_missing: + failed.append(rec) + continue + to_check.append((src_name, raw_name, cand_ranges)) + + unique_ranges = sorted({se for _, _, rlist in to_check for se in rlist}) + inspected_by_range: dict[tuple[int, int], dict] = {} + if unique_ranges: + with ThreadPoolExecutor(max_workers=8) as pool: + results = pool.map(lambda se: _count_br_insns(main_bin, se[0], se[1]), unique_ranges) + for se, res in zip(unique_ranges, results): + inspected_by_range[se] = res + + for src_name, raw_name, cand_ranges in to_check: + range_results = [inspected_by_range[se] for se in cand_ranges] + bad = [r for r in range_results if r['indirect_br_count'] < 1] + if bad: + failed.append({ + 'source': src_name, + 'name': raw_name, + 'reason': 'missing_indirect_br_instruction', + 'range_results': range_results, + }) + else: + verified.append({ + 'source': src_name, + 'name': raw_name, + **range_results[0], + }) + + summary = { + 'total_audited': len(verified) + len(failed) + (0 if fail_on_missing else len(dead_stripped)), + 'linked_checked_count': len(verified) + len(failed), + 'verified_ibr_count': len(verified), + 'dead_stripped_count': len(dead_stripped), + 'failed_count': len(failed), + 'failed': failed, + 'sample_verified': verified[:12], + } + if failed: + preview = json.dumps(failed[:5], ensure_ascii=False, indent=2) + raise AssertionError( + f'[IndirectBranchGate] {len(failed)} function(s) failed br xN check:\n{preview}' + ) + return summary + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--binary', type=Path, required=True) + parser.add_argument('--dwarf', type=Path, required=True) + parser.add_argument('--audit', type=Path, required=True) + args = parser.parse_args() + + audit = json.loads(args.audit.read_text(encoding='utf-8')) + res = verify_binary_indirect_branches(args.binary, args.dwarf, audit) + print(json.dumps(res, ensure_ascii=False, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/llvm_obf/verify_macho_indirect_calls.py b/tools/llvm_obf/verify_macho_indirect_calls.py new file mode 100644 index 0000000..35de379 --- /dev/null +++ b/tools/llvm_obf/verify_macho_indirect_calls.py @@ -0,0 +1,470 @@ +#!/usr/bin/env python3 +"""Verify ARM64 direct BL/tail-B vs indirect BLR call-graph metrics in a linked Mach-O binary.""" +from __future__ import annotations + +import argparse +from array import array +import bisect +import json +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +MH_MAGIC_64 = 0xFEEDFACF +FAT_MAGIC = 0xCAFEBABE +FAT_CIGAM = 0xBEBAFECA +LC_SEGMENT_64 = 0x19 +CPU_TYPE_ARM64 = 0x0100000C + +KEYBOX_AND_BRIDGE_C_SYMBOLS = [ + '_rd_epub_derive_book_key', + '_rd_epub_derive_media_key', + '_rd_epub_legacy_url_prefix', + '_rd_epub_derive_book_key_ns', + '_rd_epub_derive_media_key_ns', + '_rd_epub_legacy_tag_prefix', + '_rd_epub_media_pwd_ns', + '_rd_epub_db_key_ns', + '_rd_epub_device_token_key_ns', + '_rd_epub_course_sign_prefix_ns', + '_rd_epub_wx_pay_secret_ns', + '_rd_content_decrypt_file', + '_rd_epub_key_transform', + '_rd_epub_poison_mark', + '_rd_sd_derive_aes256_key', + '_rd_sd_decrypt_bundled_asset', + '_rd_sd_keychain_slot_name', + '_rd_sd_bundle_asset_stem', + '_rd_iap_keychain_account_name', + '_rd_sd_media_decrypt_pwd', + '_rd_sd_db_secret_key', + '_rd_sd_device_token_key', + '_rd_sd_course_sign_prefix', + '_rd_sd_wx_pay_secret', + '_rd_sd_derive_v31_seed', + '_rd_sd_derive_v31_dt_pwd', + '_rd_sd_seckey_create_with_data', + '_rd_sd_seckey_create_signature', + '_rd_sd_cc_crypt', + '_rd_sd_cc_hmac', + '_rd_sd_is_traced', + '_rd_sd_sha256_init', + '_rd_sd_sha256_update', + '_rd_sd_sha256_final', + '_rd_sd_sha256_raw', + '_rd_sd_sha256_hex', + '_rd_sd_md5_hex', + '_rd_sec_bootstrap_launch', + '_rd_sd_probe_env_artifacts', +] + +TRACKED_CORE_TYPES = [ + 'RDEncryptedEpubResourceProvider', + 'EpubParser', + 'LoadEpub', + 'STSEpubWebResourceLoader', + 'RBCoreEpubLoadController', + 'STSRDFileManagerStorage', + 'RDPDFStsSimpleCryptBridge', + 'RDSDPrivateKeyManager', + 'RDSDAuthV32Signer', + 'RDBaseNetworkService', + 'RDKeyGenerator', + 'RDIAPHandler', + 'STSIAPVerifyHandler', +] + + +def _select_arm64_slice(data: bytes) -> memoryview: + magic = struct.unpack_from('I', data, 0)[0] + if be_magic == FAT_MAGIC: + nfat = struct.unpack_from('>I', data, 4)[0] + for idx in range(nfat): + cputype, _, offset, size, _ = struct.unpack_from('>IIIII', data, 8 + idx * 20) + if cputype == CPU_TYPE_ARM64: + return memoryview(data)[offset:offset + size] + raise ValueError(f'Unsupported Mach-O magic: 0x{magic:08x}') + + +def parse_macho_sections(binary_path: Path) -> dict[str, dict[str, int]]: + """Return mapping of 'SEGNAME,sectname' -> {'addr', 'size', 'offset'} for arm64 slice.""" + raw = binary_path.read_bytes() + mv = _select_arm64_slice(raw) + magic, _, _, _, ncmds, _, _, _ = struct.unpack_from(' tuple[list[int], list[int], list[list[str]], dict[str, list[tuple[int, int]]]]: + """Return sorted unique text symbol ranges and name -> [(start, end)] lookup.""" + out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_bin)], text=True) + addr_to_names: dict[int, list[str]] = {} + for line in out.splitlines(): + parts = line.strip().split(maxsplit=2) + if len(parts) == 3 and parts[1].lower() == 't': + try: + addr = int(parts[0], 16) + except ValueError: + continue + addr_to_names.setdefault(addr, []).append(parts[2]) + + starts = sorted(addr_to_names.keys()) + ends: list[int] = [] + names_at_idx: list[list[str]] = [] + by_name: dict[str, list[tuple[int, int]]] = {} + for idx, addr in enumerate(starts): + end = starts[idx + 1] if idx + 1 < len(starts) else addr + 0x400 + ends.append(end) + nlist = addr_to_names[addr] + names_at_idx.append(nlist) + for nm in nlist: + by_name.setdefault(nm, []).append((addr, end)) + return starts, ends, names_at_idx, by_name + + +def load_l1_type_map(symbol_map_path: Path | None) -> dict[str, str]: + if not symbol_map_path or not symbol_map_path.is_file(): + return {} + raw = json.loads(symbol_map_path.read_text(encoding='utf-8')) + mappings = raw.get('mappings') if isinstance(raw.get('mappings'), dict) else raw + out: dict[str, str] = {} + if isinstance(mappings, dict): + for orig, val in mappings.items(): + if isinstance(val, str): + out[orig] = val + elif isinstance(val, dict) and isinstance(val.get('obfuscated'), str): + out[orig] = val['obfuscated'] + return out + + +def analyze_macho_calls( + binary_path: Path, + dwarf_bin: Path, + symbol_map_path: Path | None = None, + require_zero_keybox_direct_bl: bool = False, +) -> dict: + raw = binary_path.read_bytes() + mv = _select_arm64_slice(raw) + sections = parse_macho_sections(binary_path) + if '__TEXT,__text' not in sections: + raise ValueError(f'Missing __TEXT,__text in {binary_path}') + + text_sec = sections['__TEXT,__text'] + text_va = text_sec['addr'] + text_size = text_sec['size'] + text_off = text_sec['offset'] + text_end_va = text_va + text_size + + stubs_va = sections.get('__TEXT,__stubs', {}).get('addr', 0) + stubs_end_va = stubs_va + sections.get('__TEXT,__stubs', {}).get('size', 0) + objc_stubs_va = sections.get('__TEXT,__objc_stubs', {}).get('addr', 0) + objc_stubs_end_va = objc_stubs_va + sections.get('__TEXT,__objc_stubs', {}).get('size', 0) + + starts, ends, names_at_idx, by_name = parse_dwarf_symbols(dwarf_bin) + start_to_idx = {addr: idx for idx, addr in enumerate(starts)} + l1_types = load_l1_type_map(symbol_map_path) + + words = array('I') + words.frombytes(mv[text_off:text_off + (text_size & ~3)]) + if sys.byteorder != 'little': + words.byteswap() + + total_bl = 0 + internal_text_bl = 0 + dylib_stub_bl = 0 + objc_stub_bl = 0 + other_bl = 0 + interproc_tail_b = 0 + blr_count = 0 + + # Track direct incoming calls (BL + inter-procedural tail B) keyed by target symbol index + direct_in_bl_by_idx: dict[int, int] = {} + direct_in_tail_b_by_idx: dict[int, int] = {} + # Track caller symbol index -> list of (pc, target_idx, kind) for KeyBox targets + keybox_indices: dict[str, list[int]] = {} + keybox_idx_set: set[int] = set() + for sym in KEYBOX_AND_BRIDGE_C_SYMBOLS: + idxs = [] + for s_addr, _ in by_name.get(sym, []): + if s_addr in start_to_idx: + idxs.append(start_to_idx[s_addr]) + keybox_idx_set.add(start_to_idx[s_addr]) + keybox_indices[sym] = idxs + + keybox_caller_samples: dict[int, list[dict]] = {} + + # Pre-classify symbol indices belonging to tracked core types (using both original & L1 token) + core_type_tokens: dict[str, tuple[str, ...]] = {} + for orig_type in TRACKED_CORE_TYPES: + obf_type = l1_types.get(orig_type) + toks = [orig_type] + if obf_type and obf_type != orig_type: + toks.append(obf_type) + core_type_tokens[orig_type] = tuple(toks) + + idx_to_core_types: dict[int, list[str]] = {} + for idx, nlist in enumerate(names_at_idx): + matched_types = [] + for orig_type, toks in core_type_tokens.items(): + if any(tok in nm for nm in nlist for tok in toks): + matched_types.append(orig_type) + if matched_types: + idx_to_core_types[idx] = matched_types + + core_outgoing_internal_bl: dict[str, int] = {t: 0 for t in TRACKED_CORE_TYPES} + core_outgoing_blr: dict[str, int] = {t: 0 for t in TRACKED_CORE_TYPES} + core_incoming_direct: dict[str, int] = {t: 0 for t in TRACKED_CORE_TYPES} + + # Walk linearly while maintaining current symbol cursor `cur_sym_idx` in O(1) amortized time! + num_syms = len(starts) + cur_sym_idx = 0 + + for i, insn in enumerate(words): + pc = text_va + (i << 2) + while cur_sym_idx + 1 < num_syms and pc >= ends[cur_sym_idx]: + cur_sym_idx += 1 + caller_idx = cur_sym_idx if (num_syms > 0 and starts[cur_sym_idx] <= pc < ends[cur_sym_idx]) else -1 + + op6 = insn & 0xFC000000 + if op6 == 0x94000000: # BL imm26 + total_bl += 1 + imm26 = insn & 0x03FFFFFF + if imm26 & 0x02000000: + imm26 -= 0x04000000 + tgt = pc + (imm26 << 2) + if stubs_va <= tgt < stubs_end_va: + dylib_stub_bl += 1 + elif objc_stubs_va <= tgt < objc_stubs_end_va: + objc_stub_bl += 1 + elif text_va <= tgt < text_end_va: + internal_text_bl += 1 + if caller_idx in idx_to_core_types: + for ct in idx_to_core_types[caller_idx]: + core_outgoing_internal_bl[ct] += 1 + t_idx = start_to_idx.get(tgt) + if t_idx is None: + pos = bisect.bisect_right(starts, tgt) - 1 + if 0 <= pos < num_syms and starts[pos] <= tgt < ends[pos]: + t_idx = pos + if t_idx is not None: + direct_in_bl_by_idx[t_idx] = direct_in_bl_by_idx.get(t_idx, 0) + 1 + if t_idx in idx_to_core_types: + for ct in idx_to_core_types[t_idx]: + core_incoming_direct[ct] += 1 + if t_idx in keybox_idx_set and len(keybox_caller_samples.get(t_idx, [])) < 8: + caller_name = names_at_idx[caller_idx][0] if caller_idx >= 0 else hex(pc) + keybox_caller_samples.setdefault(t_idx, []).append({ + 'pc': hex(pc), + 'kind': 'bl', + 'caller': caller_name, + }) + else: + other_bl += 1 + elif op6 == 0x14000000: # B imm26 (check inter-procedural tail-call to symbol entry) + imm26 = insn & 0x03FFFFFF + if imm26 & 0x02000000: + imm26 -= 0x04000000 + tgt = pc + (imm26 << 2) + if text_va <= tgt < text_end_va: + t_idx = start_to_idx.get(tgt) + if t_idx is not None and t_idx != caller_idx: + interproc_tail_b += 1 + direct_in_tail_b_by_idx[t_idx] = direct_in_tail_b_by_idx.get(t_idx, 0) + 1 + if caller_idx in idx_to_core_types: + for ct in idx_to_core_types[caller_idx]: + core_outgoing_internal_bl[ct] += 1 + if t_idx in idx_to_core_types: + for ct in idx_to_core_types[t_idx]: + core_incoming_direct[ct] += 1 + if t_idx in keybox_idx_set and len(keybox_caller_samples.get(t_idx, [])) < 8: + caller_name = names_at_idx[caller_idx][0] if caller_idx >= 0 else hex(pc) + keybox_caller_samples.setdefault(t_idx, []).append({ + 'pc': hex(pc), + 'kind': 'tail_b', + 'caller': caller_name, + }) + elif (insn & 0xFFFFFC1F) == 0xD63F0000 or (insn & 0xFEFFF800) == 0xD73F0800 or ( + (insn & 0xFFFFFC1F) in (0xD63F081F, 0xD63F0C1F) + ): + # BLR Xn or BLRAA/BLRAB/BLRAAZ/BLRABZ + blr_count += 1 + if caller_idx in idx_to_core_types: + for ct in idx_to_core_types[caller_idx]: + core_outgoing_blr[ct] += 1 + + keybox_report: dict[str, dict] = {} + keybox_total_direct_xrefs = 0 + violations = [] + for sym in KEYBOX_AND_BRIDGE_C_SYMBOLS: + idxs = keybox_indices[sym] + bl_cnt = sum(direct_in_bl_by_idx.get(ix, 0) for ix in idxs) + tb_cnt = sum(direct_in_tail_b_by_idx.get(ix, 0) for ix in idxs) + samples = [] + for ix in idxs: + samples.extend(keybox_caller_samples.get(ix, [])) + total_sym = bl_cnt + tb_cnt + keybox_total_direct_xrefs += total_sym + keybox_report[sym] = { + 'present_in_dwarf': len(idxs) > 0, + 'direct_bl': bl_cnt, + 'direct_tail_b': tb_cnt, + 'total_direct_call_xrefs': total_sym, + 'caller_samples': samples[:5], + } + if require_zero_keybox_direct_bl and total_sym > 0: + violations.append(f'{sym}: {total_sym} direct call xrefs ({samples[:3]})') + + core_types_report: dict[str, dict] = {} + for orig_type in TRACKED_CORE_TYPES: + core_types_report[orig_type] = { + 'l1_token': l1_types.get(orig_type, orig_type), + 'outgoing_internal_direct_calls': core_outgoing_internal_bl[orig_type], + 'outgoing_indirect_blr': core_outgoing_blr[orig_type], + 'incoming_direct_calls': core_incoming_direct[orig_type], + } + + data_const_bytes = sections.get('__DATA_CONST,__const', {}).get('size', 0) + text_const_bytes = sections.get('__TEXT,__const', {}).get('size', 0) + + result = { + 'binary_path': str(binary_path), + 'binary_bytes': binary_path.stat().st_size, + 'text_bytes': text_size, + 'text_const_bytes': text_const_bytes, + 'data_const_bytes': data_const_bytes, + 'text_call_summary': { + 'total_bl': total_bl, + 'internal_text_bl': internal_text_bl, + 'interproc_tail_b': interproc_tail_b, + 'internal_direct_calls_total': internal_text_bl + interproc_tail_b, + 'dylib_stub_bl': dylib_stub_bl, + 'objc_stub_bl': objc_stub_bl, + 'other_bl': other_bl, + 'indirect_blr_total': blr_count, + }, + 'keybox_and_bridge_15_symbols': { + 'total_direct_call_xrefs': keybox_total_direct_xrefs, + 'symbols': keybox_report, + }, + 'tracked_core_types': core_types_report, + 'gate_passed': len(violations) == 0, + 'violations': violations, + } + return result + + +def analyze_ipa_directory( + ipa_dir: Path, + scheme: str = 'readoor31OtherPay', + require_zero_keybox_direct_bl: bool = False, +) -> dict: + ipa_path = ipa_dir / f'{scheme}.ipa' + dsyms_zip = ipa_dir / 'dSYMs.zip' + maps_dir = ipa_dir / 'obfuscation_maps' + symbol_map = next(maps_dir.glob('*symbol_map*.json'), None) if maps_dir.is_dir() else None + if not ipa_path.is_file() or not dsyms_zip.is_file(): + raise FileNotFoundError(f'Missing {ipa_path} or {dsyms_zip}') + + with tempfile.TemporaryDirectory(prefix='ig-icall-verify-') as tmp: + tmp_path = Path(tmp) + app_extract = tmp_path / 'ipa' + dsym_extract = tmp_path / 'dsyms' + subprocess.run(['ditto', '-x', '-k', str(ipa_path), str(app_extract)], check=True) + subprocess.run(['ditto', '-x', '-k', str(dsyms_zip), str(dsym_extract)], check=True) + main_bin = app_extract / 'Payload' / f'{scheme}.app' / scheme + dwarf_bin = dsym_extract / f'{scheme}.app.dSYM' / 'Contents' / 'Resources' / 'DWARF' / scheme + res = analyze_macho_calls( + main_bin, + dwarf_bin, + symbol_map_path=symbol_map, + require_zero_keybox_direct_bl=require_zero_keybox_direct_bl, + ) + res['ipa_dir'] = str(ipa_dir) + res['ipa_bytes'] = ipa_path.stat().st_size + return res + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--ipa-dir', type=Path, help='Directory containing .ipa and dSYMs.zip') + parser.add_argument('--scheme', default='readoor31OtherPay') + parser.add_argument('--binary', type=Path, help='Path to linked Mach-O binary') + parser.add_argument('--dwarf', type=Path, help='Path to DWARF binary inside .dSYM') + parser.add_argument('--symbol-map', type=Path, help='Optional L1 symbol_map.json') + parser.add_argument('--require-zero-keybox-bl', action='store_true') + parser.add_argument('--out', type=Path, help='Optional output JSON path') + args = parser.parse_args() + + if args.ipa_dir: + report = analyze_ipa_directory( + args.ipa_dir, + scheme=args.scheme, + require_zero_keybox_direct_bl=args.require_zero_keybox_bl, + ) + elif args.binary and args.dwarf: + report = analyze_macho_calls( + args.binary, + args.dwarf, + symbol_map_path=args.symbol_map, + require_zero_keybox_direct_bl=args.require_zero_keybox_bl, + ) + else: + parser.error('Specify either --ipa-dir or both --binary and --dwarf') + + text = json.dumps(report, ensure_ascii=False, indent=2) + '\n' + if args.out: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(text, encoding='utf-8') + print( + json.dumps( + { + 'text_call_summary': report['text_call_summary'], + 'keybox_total_direct_call_xrefs': report['keybox_and_bridge_15_symbols']['total_direct_call_xrefs'], + 'gate_passed': report['gate_passed'], + 'violations': report['violations'], + }, + ensure_ascii=False, + indent=2, + ) + ) + return 0 if report['gate_passed'] else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/llvm_obf/verify_macho_star_cfg.py b/tools/llvm_obf/verify_macho_star_cfg.py new file mode 100644 index 0000000..3887815 --- /dev/null +++ b/tools/llvm_obf/verify_macho_star_cfg.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +"""Verify that every flattened function in linked Mach-O binary has a single-center star-switch CFG.""" +import argparse +import bisect +from concurrent.futures import ThreadPoolExecutor +import json +from pathlib import Path +import re +import subprocess +import sys + +INSN_PC_RE = re.compile(r'^\s*([0-9a-f]+):\s+[0-9a-f]+\s+(.*)$') +BRANCH_UNCOND_RE = re.compile(r'^\s*([0-9a-f]+):\s+[0-9a-f]+\s+b\s+(0x[0-9a-f]+)\b') +BRANCH_ANY_RE = re.compile( + r'^\s*([0-9a-f]+):\s+[0-9a-f]+\s+(b|b\.\w+|cbz|cbnz|tbz|tbnz)\s+.*?(0x[0-9a-f]+)\b' +) +JUMP_TABLE_BR_RE = re.compile(r'\bbr\s+x\d+\b') +RET_INSN_RE = re.compile(r'^\s*ret(?:aa|ab)?\b') + + +def parse_dwarf_text_ranges(dwarf_bin: Path) -> dict[str, list[tuple[int, int]]]: + """Return mapping of symbol name -> list of (start_addr, end_addr) ranges from DWARF nm.""" + out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_bin)], text=True) + syms: list[tuple[int, str]] = [] + for line in out.splitlines(): + parts = line.strip().split(maxsplit=2) + if len(parts) == 3 and parts[1].lower() == 't': + try: + syms.append((int(parts[0], 16), parts[2])) + except ValueError: + continue + syms.sort() + unique_addrs = sorted({addr for addr, _ in syms}) + ranges: dict[str, list[tuple[int, int]]] = {} + for addr, name in syms: + pos = bisect.bisect_right(unique_addrs, addr) + next_addr = unique_addrs[pos] if pos < len(unique_addrs) else addr + 0x400 + if next_addr > addr: + ranges.setdefault(name, []).append((addr, next_addr)) + return ranges + + +def _inspect_range(main_bin: Path, start_addr: int, end_addr: int) -> dict: + dis = subprocess.check_output( + [ + 'xcrun', 'llvm-objdump', '--disassemble', + f'--start-address={hex(start_addr)}', + f'--stop-address={hex(end_addr)}', + str(main_bin), + ], + text=True, + ) + insns: list[tuple[int, str, str]] = [] + uncond_in: dict[int, int] = {} + uncond_back_in: dict[int, int] = {} + func_back_edges = 0 + has_jump_table_br = False + indirect_br_count = 0 + + for line in dis.splitlines(): + mp = INSN_PC_RE.match(line) + if not mp: + continue + pc = int(mp.group(1), 16) + rest = mp.group(2).strip() + insns.append((pc, rest, line)) + if JUMP_TABLE_BR_RE.search(rest): + has_jump_table_br = True + indirect_br_count += 1 + + mu = BRANCH_UNCOND_RE.match(line) + if mu: + tgt = int(mu.group(2), 16) + if start_addr <= tgt < end_addr: + uncond_in[tgt] = uncond_in.get(tgt, 0) + 1 + if tgt < pc: + uncond_back_in[tgt] = uncond_back_in.get(tgt, 0) + 1 + ma = BRANCH_ANY_RE.match(line) + if ma: + tgt = int(ma.group(3), 16) + if start_addr <= tgt < pc: + func_back_edges += 1 + + # Single central dispatcher hub must have >=2 unconditional fan-in, continue dispatching + # before returning (not a shared ret epilogue), and participate in a loop back-edge or jump table. + best_hub = None + best_uncond = 0 + best_back = 0 + best_valid = False + has_cycle_or_jt = func_back_edges >= 1 or has_jump_table_br + for tgt, u_cnt in uncond_in.items(): + if u_cnt < 2: + continue + hub_continues_in_func = False + for pc, rest, raw_line in insns: + if pc < tgt: + continue + if RET_INSN_RE.match(rest): + break + if JUMP_TABLE_BR_RE.search(rest): + hub_continues_in_func = True + break + ma = BRANCH_ANY_RE.match(raw_line) + if ma: + b_tgt = int(ma.group(3), 16) + if start_addr <= b_tgt < end_addr: + hub_continues_in_func = True + break + + b_cnt = uncond_back_in.get(tgt, 0) + is_valid = hub_continues_in_func and (b_cnt >= 1 or has_cycle_or_jt) + score = (1 if is_valid else 0, b_cnt, u_cnt) + best_score = (1 if best_valid else 0, best_back, best_uncond) + if score > best_score: + best_hub = tgt + best_uncond = u_cnt + best_back = b_cnt + best_valid = is_valid + + reported_back = max(best_back, 1 if best_valid and has_cycle_or_jt else 0) + return { + 'start_addr': hex(start_addr), + 'end_addr': hex(end_addr), + 'insn_count': len(insns), + 'hub_addr': hex(best_hub) if best_hub is not None else None, + 'hub_uncond_fan_in': best_uncond, + 'hub_back_edges': reported_back, + 'indirect_br_count': indirect_br_count, + 'is_star_dispatcher': best_valid, + } + + +def _candidate_symbol_keys(raw_name: str) -> list[str]: + clean = raw_name.lstrip('\x01') + keys = [] + if clean.startswith('-') or clean.startswith('+'): + keys.append(clean) + else: + keys.append('_' + clean) + keys.append(clean) + return keys + + +def verify_binary_star_cfg( + main_bin: Path, + dwarf_bin: Path, + obf_audit: dict, + *, + require_topology: str = 'sparse_switch', + fail_on_missing: bool = False, +) -> dict: + """Disassemble every audited flattened function in main_bin and enforce 100% star-hub CFG.""" + ranges_map = parse_dwarf_text_ranges(dwarf_bin) + ibr_funcs = { + fn + for mod in (obf_audit.get('module_audits') or []) + for fn in (mod.get('indirect_branches_functions') or []) + } + + verified = [] + failed = [] + dead_stripped = [] + + to_check: list[tuple[str, dict, list[tuple[int, int]]]] = [] + for mod in obf_audit.get('module_audits') or []: + src_name = Path(mod.get('source_path') or 'unknown').name + for det in mod.get('functions_flattened_details') or []: + raw_name = det['name'] + topo = det.get('topology', '') + if require_topology and topo != require_topology: + failed.append({ + 'source': src_name, + 'name': raw_name, + 'reason': f'unexpected_topology:{topo}', + }) + continue + + cand_ranges = [] + for key in _candidate_symbol_keys(raw_name): + if key in ranges_map: + cand_ranges = ranges_map[key] + break + if not cand_ranges: + rec = {'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'} + dead_stripped.append(rec) + if fail_on_missing: + failed.append(rec) + continue + to_check.append((src_name, det, cand_ranges)) + + unique_ranges = sorted({se for _, _, rlist in to_check for se in rlist}) + inspected_by_range: dict[tuple[int, int], dict] = {} + if unique_ranges: + with ThreadPoolExecutor(max_workers=8) as pool: + results = pool.map(lambda se: _inspect_range(main_bin, se[0], se[1]), unique_ranges) + for se, res in zip(unique_ranges, results): + inspected_by_range[se] = res + + for src_name, det, cand_ranges in to_check: + raw_name = det['name'] + topo = det.get('topology', '') + has_ibr = raw_name in ibr_funcs + # If static C symbols have duplicates across TUs, require every linked copy to pass + range_results = [inspected_by_range[se] for se in cand_ranges] + bad = [ + r for r in range_results + if not (r['is_star_dispatcher'] or (has_ibr and r.get('indirect_br_count', 0) >= 2)) + ] + if bad: + failed.append({ + 'source': src_name, + 'name': raw_name, + 'topology': topo, + 'blocks': det.get('blocks'), + 'reason': 'missing_star_dispatcher_hub', + 'range_results': range_results, + }) + else: + verified.append({ + 'source': src_name, + 'name': raw_name, + 'topology': topo, + 'blocks': det.get('blocks'), + 'verified_via': ( + 'star_dispatcher' + if range_results[0]['is_star_dispatcher'] + else 'indirect_br' + ), + **range_results[0], + }) + + summary = { + 'total_audited': len(verified) + len(failed) + (0 if fail_on_missing else len(dead_stripped)), + 'linked_checked_count': len(verified) + len(failed), + 'verified_star_count': len(verified), + 'dead_stripped_count': len(dead_stripped), + 'failed_count': len(failed), + 'failed': failed, + 'sample_verified_hubs': verified[:12], + } + if failed: + preview = json.dumps(failed[:5], ensure_ascii=False, indent=2) + raise AssertionError(f'[StarCFGGate] {len(failed)} function(s) failed star-switch CFG check:\n{preview}') + return summary + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--binary', type=Path, required=True) + parser.add_argument('--dwarf', type=Path, required=True) + parser.add_argument('--audit', type=Path, required=True) + parser.add_argument('--require-topology', default='sparse_switch') + args = parser.parse_args() + + audit = json.loads(args.audit.read_text(encoding='utf-8')) + res = verify_binary_star_cfg( + args.binary, + args.dwarf, + audit, + require_topology=args.require_topology, + ) + print(json.dumps(res, ensure_ascii=False, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/macho_guard/attribute_callsites.py b/tools/macho_guard/attribute_callsites.py new file mode 100644 index 0000000..ca33dcf --- /dev/null +++ b/tools/macho_guard/attribute_callsites.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Attribute direct calls in a Mach-O to objects in its same-build Link Map.""" + +import argparse +from bisect import bisect_right +import csv +from pathlib import Path +import re + +from machox import Macho +from redirect_to_runtime import defined_symbols +from verify_baseline import inspect_binary + + +def load_link_map(path): + objects, symbols = {}, [] + section = '' + for line in path.read_text(errors='replace').splitlines(): + if line in ('# Object files:', '# Sections:', '# Symbols:', '# Dead Stripped Symbols:'): + section = line + elif line.startswith('# '): + continue + elif section == '# Object files:': + match = re.fullmatch(r'\[\s*(\d+)\]\s+(.+)', line) + if match: + objects[int(match[1])] = match[2] + elif section == '# Symbols:': + match = re.fullmatch(r'(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)\s+\[\s*(\d+)\]\s+(.+)', line) + if match and int(match[2], 16): + symbols.append((int(match[1], 16), int(match[2], 16), int(match[3]), match[4])) + if not objects or not symbols: + raise ValueError(f'Incomplete Link Map: {path}') + return objects, sorted(symbols) + + +def attribute(binary, link_map): + objects, entries = load_link_map(link_map) + defined = defined_symbols(Macho(binary.read_bytes())) + # Require matching named functions before trusting the object addresses. + common = [(address, defined[name]) for address, _, _, name in entries if name in defined] + if not common or any(mapped != actual for mapped, actual in common): + raise ValueError('Link Map symbols do not match executable') + _, calls = inspect_binary(binary) + starts = [entry[0] for entry in entries] + for call in calls: + site = int(call['site'], 16) + index = bisect_right(starts, site) - 1 + if index >= 0: + address, size, obj, name = entries[index] + if site < address + size and (index == 0 or starts[index - 1] != address): + call.update(caller=name, object=objects.get(obj, '')) + yield call + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('binary', type=Path) + parser.add_argument('link_map', type=Path) + parser.add_argument('output', type=Path) + args = parser.parse_args() + rows = list(attribute(args.binary, args.link_map)) + with args.output.open('x', newline='') as stream: + writer = csv.DictWriter(stream, fieldnames=['slice_offset', 'site', 'target', 'branch', 'symbol', 'caller', 'object']) + writer.writeheader() + writer.writerows(rows) diff --git a/tools/macho_guard/build_hook_device.py b/tools/macho_guard/build_hook_device.py index f4440eb..773c073 100644 --- a/tools/macho_guard/build_hook_device.py +++ b/tools/macho_guard/build_hook_device.py @@ -73,7 +73,7 @@ def build(profile, identity, bundle, output): (app / 'Info.plist').write_bytes(plistlib.dumps(info)) common = ['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', - '-miphoneos-version-min=15.0', '-O2', + '-miphoneos-version-min=15.0', '-O2', '-DIG_OBSERVATION=1', '-I', source / 'defender', '-I', source / 'defender/include'] modules = ['IGDefender.c', 'dispatch/IGDispatch.c', 'resolve/IGResolve.c', 'anti_hook/IGAntiHook.c', 'anti_hook/IGObjCBaseline.c', diff --git a/tools/macho_guard/link_with_sdk_inputs.py b/tools/macho_guard/link_with_sdk_inputs.py new file mode 100644 index 0000000..d0029d3 --- /dev/null +++ b/tools/macho_guard/link_with_sdk_inputs.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Relink one captured release command with hash-verified SDK candidate inputs.""" +import argparse +import hashlib +import json +from pathlib import Path +import shlex +import subprocess + +from redirect_to_runtime import patch + + +def sha(path): + with path.open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def relink(log, manifest_path, output, working_directory): + manifest = json.loads(manifest_path.read_text()) + root = manifest_path.parent + verified = set() + for record in manifest['files']: + path = (root / record['path']).resolve() + verified.add(path) + if sha(path) != record['sha256']: + raise ValueError(f'SDK candidate changed: {path}') + required = [(root / item).resolve() for item in manifest['objects']] + required += [(root / rule['file']).resolve() for rule in manifest['replacements']] + required.append((root / manifest['patch_profile']).resolve()) + if not set(required) <= verified: + raise ValueError('Candidate file missing from hash manifest') + commands = [] + for line in log.read_text(errors='replace').splitlines(): + if '/bin/clang++ ' in line: + argv = shlex.split(line) + if '-o' in argv and argv[argv.index('-o') + 1].endswith( + '.app/' + manifest['executable']): + commands.append(argv) + if len(commands) != 1: + raise ValueError('Need exactly one matching release link command') + argv = commands[0] + if any(arg.startswith(('-fprofile', '-fcoverage')) for arg in argv): + raise ValueError('Release link still enables coverage') + for rule in manifest['replacements']: + needle = rule['arguments'] + positions = [i for i in range(len(argv) - len(needle) + 1) + if argv[i:i + len(needle)] == needle] + if len(positions) != 1: + raise ValueError(f'Link input missing or duplicated: {needle}') + i = positions[0] + argv[i:i + len(needle)] = [str((root / rule['file']).resolve())] + prepend = [str((root / item).resolve()) for item in manifest['objects']] + prepend += ['-F' + str((root / item).resolve()) for item in manifest['framework_search']] + argv[1:1] = prepend + if output.exists(): + raise FileExistsError(output) + output.mkdir() + for key, name in [('-map', 'LinkMap.txt'), ('-object_path_lto', 'lto.o'), + ('-dependency_info', 'dependency_info.dat')]: + if key not in argv and key == '-map': + argv[1:1] = ['-Xlinker', '-map', '-Xlinker', str(output / name)] + continue + i = argv.index(key) + if argv[i + 1] != '-Xlinker': + raise ValueError(f'Unexpected linker argument layout: {key}') + argv[i + 2] = str(output / name) + binary = output / manifest['executable'] + argv[argv.index('-o') + 1] = str(output / 'unpatched') + (output / 'link-argv.json').write_text(json.dumps(argv, indent=2) + '\n') + with (output / 'link.log').open('w') as stream: + subprocess.run(argv, cwd=working_directory, stdout=stream, + stderr=subprocess.STDOUT, check=True) + profile = json.loads((root / manifest['patch_profile']).read_text()) + report = patch(output / 'unpatched', binary, output / 'LinkMap.txt', profile) + (output / 'patch.json').write_text(json.dumps(report, indent=2) + '\n') + (output / 'inputs.json').write_text(json.dumps(manifest, indent=2) + '\n') + return binary + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + for name in ('build_log', 'manifest', 'output', 'working_directory'): + parser.add_argument(name, type=Path) + args = parser.parse_args() + print(relink(args.build_log.resolve(), args.manifest.resolve(), + args.output.resolve(), args.working_directory.resolve())) diff --git a/tools/macho_guard/package_route2_app.py b/tools/macho_guard/package_route2_app.py new file mode 100644 index 0000000..3d45565 --- /dev/null +++ b/tools/macho_guard/package_route2_app.py @@ -0,0 +1,326 @@ +#!/usr/bin/env python3 +"""Package Route 2 hardened app bundle, build IGArchiveGuard, redirect all embedded frameworks, audit & sign.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import plistlib +import shutil +import subprocess +import sys +import tempfile + +from batch import arm64_slices, iter_macho_files, Slice +from machox import Macho, LC_DYLD_CHAINED_FIXUPS +from redirect_framework_imports import ( + DEPENDENCY, + detect_chained_target_mapping, + rewrite as rewrite_chained, +) +from redirect_legacy_imports import ( + detect_legacy_target_mapping, + rewrite as rewrite_legacy, +) +from verify_baseline import inspect_binary, scan + +EXTERNAL_SYMBOLS = ('_fopen', '_dlopen', '_dlsym') +SYSTEM_SYMBOLS = ('_write', '_read', '_open', '_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid') +FORBIDDEN_SYMBOLS = set(EXTERNAL_SYMBOLS) | set(SYSTEM_SYMBOLS) + +EXPECTED_ARCHIVE_EXPORTS = { + '_rd_a0', '_rd_f', '_rd_a1', '_rd_a2', '_rd_a3', '_rd_a4', + '_rd_u00', '_rd_o', '_rdo', '_rd_r', '_rdr', '_rd_w0', '_rd_w', + '_rd_c0', '_rd_c', '_rd_p00', '_rd_p0', '_rd_e', '_rd_k', + '_rd_l00', '_rd_s0', '_rd_s', + '_rd_io_cfg', '_rd_io_chk', '_rd_io_ev', +} + + +def sha256(path): + with Path(path).open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def run_cmd(*args, env=None, cwd=None): + return subprocess.check_output(list(map(str, args)), env=env, cwd=cwd, text=True) + + +def build_archive_guard(defender_dir, framework_dir): + if framework_dir.exists(): + shutil.rmtree(framework_dir) + framework_dir.mkdir(parents=True) + binary = framework_dir / 'RDCoreIO' + sources = [ + defender_dir / 'dispatch/IGArchiveGuard.c', + defender_dir / 'resolve/IGResolve.c', + defender_dir / 'anti_hook/IGAntiHook.c', + ] + subprocess.run([ + 'xcrun', '--sdk', 'iphoneos', 'clang', + '-arch', 'arm64', '-miphoneos-version-min=15.0', '-O2', + '-Wall', '-Wextra', '-Werror', '-fvisibility=hidden', '-dynamiclib', + '-DIG_ARCHIVE_INTERNAL_RESOLVE=1', + '-I', str(defender_dir), '-I', str(defender_dir / 'include'), + *map(str, sources), + '-Wl,-install_name,' + DEPENDENCY, + '-o', str(binary), + ], check=True) + + plist = { + 'CFBundleExecutable': 'RDCoreIO', + 'CFBundleIdentifier': 'cn.touchv.readoor.coreio', + 'CFBundleName': 'RDCoreIO', + 'CFBundlePackageType': 'FMWK', + 'CFBundleShortVersionString': '1.0', + 'CFBundleSupportedPlatforms': ['iPhoneOS'], + 'CFBundleVersion': '1', + 'MinimumOSVersion': '15.0', + } + with (framework_dir / 'Info.plist').open('wb') as stream: + plistlib.dump(plist, stream) + + exports_out = run_cmd('xcrun', 'nm', '-gU', binary) + exported = {line.split()[-1] for line in exports_out.splitlines() if line.split()} + missing = EXPECTED_ARCHIVE_EXPORTS - exported + if missing: + raise ValueError(f'RDCoreIO missing expected exports: {sorted(missing)}') + leaked_ig = sorted(s for s in exported if s.startswith('_ig_')) + if leaked_ig: + raise ValueError(f'RDCoreIO leaked _ig_* exports: {leaked_ig}') + + undef_out = run_cmd('xcrun', 'nm', '-u', binary) + undef = {line.split()[-1] for line in undef_out.splitlines() if line.split()} + forbidden_undef = undef & FORBIDDEN_SYMBOLS + if forbidden_undef: + raise ValueError(f'RDCoreIO has forbidden undefined imports: {sorted(forbidden_undef)}') + + info, sites = inspect_binary(binary) + if sites: + raise ValueError(f'RDCoreIO has direct target calls: {sites}') + return dict(sha256=sha256(binary), exported_count=len(exported), inspect=info) + + +def thin_if_fat(binary_path): + raw = binary_path.read_bytes() + if raw[:4] in (b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'): + with tempfile.NamedTemporaryFile(dir=binary_path.parent, delete=False) as tf: + tmp = Path(tf.name) + try: + subprocess.run(['xcrun', 'lipo', str(binary_path), '-thin', 'arm64', '-output', str(tmp)], check=True) + shutil.copymode(binary_path, tmp) + tmp.replace(binary_path) + return True + finally: + if tmp.exists(): + tmp.unlink() + return False + + +def process_framework(fw_dir): + name = fw_dir.stem + codesig = fw_dir / '_CodeSignature' + if codesig.exists(): + shutil.rmtree(codesig) + binary = fw_dir / name + if not binary.is_file(): + raise FileNotFoundError(binary) + + thinned = thin_if_fat(binary) + raw = binary.read_bytes() + slices = arm64_slices(raw) + if len(slices) != 1 or slices[0][0] != 0: + raise ValueError(f'{name}: expected single thin arm64 Mach-O') + m = Macho(raw) + has_chained = any(c == LC_DYLD_CHAINED_FIXUPS for c, _, _ in m.cmds) + has_dyld_info = any(c in (0x22, 0x80000022) for c, _, _ in m.cmds) + + include_stdio_rw = (name == 'SSZipArchive') + if has_chained: + mapping = detect_chained_target_mapping(raw, include_stdio_rw=include_stdio_rw) + mode = 'chained' + elif has_dyld_info: + mapping = detect_legacy_target_mapping(raw) + mode = 'legacy_dyld_info' + else: + mapping = {} + mode = 'none' + + before_info, _ = inspect_binary(binary) + if mapping: + in_sha = hashlib.sha256(raw).hexdigest() + if mode == 'chained': + out_bytes, report = rewrite_chained(raw, in_sha, mapping) + else: + out_bytes, report = rewrite_legacy(raw, in_sha, mapping) + binary.write_bytes(out_bytes) + after_info, after_sites = inspect_binary(binary) + if after_sites: + raise ValueError(f'{name}: remaining direct calls after rewrite: {after_sites}') + return dict( + framework=name, + mode=mode, + thinned=thinned, + before_total=sum(s['total'] for s in before_info['slices']), + after_total=sum(s['total'] for s in after_info['slices']), + symbols_redirected=len(mapping), + mapping=mapping, + output_sha256=report['output_sha256'], + ) + + if sum(s['total'] for s in before_info['slices']) > 0: + raise ValueError(f'{name}: has direct calls but empty mapping: {before_info}') + return dict( + framework=name, + mode='clean_no_change' if not thinned else 'thinned_clean', + thinned=thinned, + before_total=0, + after_total=0, + symbols_redirected=0, + ) + + +def regenerate_whitelist(app_repo, payload_dir, app_name): + script = app_repo / 'AutoPacking/obfuscation/generate_image_whitelist.py' + env = dict(os.environ) + env['TARGET_BUILD_DIR'] = str(payload_dir) + env['WRAPPER_NAME'] = app_name + env['EXECUTABLE_PATH'] = Path(app_name).stem + out = run_cmd(sys.executable, script, env=env, cwd=app_repo) + plist_path = payload_dir / app_name / 'RDKnownImages.plist' + data = plistlib.loads(plist_path.read_bytes()) + return dict(stdout=out.strip(), entry_count=len(data['known_images']), digest=data['digest']) + + +def adhoc_sign_and_verify(app_dir): + frameworks = sorted((app_dir / 'Frameworks').glob('*.framework')) + for fw in frameworks: + subprocess.run(['codesign', '--force', '--sign', '-', str(fw)], check=True) + subprocess.run(['codesign', '--force', '--sign', '-', str(app_dir)], check=True) + + verified = [] + for target in [*frameworks, app_dir]: + subprocess.run(['codesign', '--verify', '--strict', str(target)], check=True) + verified.append(str(target.relative_to(app_dir.parent))) + return verified + + +def package(source_app, relinked_main, app_repo, output): + if output.exists(): + raise FileExistsError(output) + output.mkdir(parents=True) + payload_dir = output / 'Payload' + payload_dir.mkdir() + app_dir = payload_dir / source_app.name + shutil.copytree(source_app, app_dir, symlinks=True) + + app_sig = app_dir / '_CodeSignature' + if app_sig.exists(): + shutil.rmtree(app_sig) + + main_bin = app_dir / relinked_main.name + shutil.copy2(relinked_main, main_bin) + main_bin.chmod(0o755) + + defender_dir = app_repo / 'readoor/3.0/Base/Security/IGDefender' + guard_report = build_archive_guard(defender_dir, app_dir / 'Frameworks/RDCoreIO.framework') + + fw_reports = [] + for fw_dir in sorted((app_dir / 'Frameworks').glob('*.framework')): + if fw_dir.name == 'RDCoreIO.framework': + continue + fw_reports.append(process_framework(fw_dir)) + (output / 'framework-rewrites.json').write_text(json.dumps(fw_reports, indent=2) + '\n') + + whitelist_report = regenerate_whitelist(app_repo, payload_dir, source_app.name) + + binaries, callsite_total = scan(app_dir, output, 'route2') + combined_counts = {} + for rel, info in binaries.items(): + for sl in info['slices']: + for sym, cnt in sl['counts'].items(): + combined_counts[sym] = combined_counts.get(sym, 0) + cnt + + external_call_total = sum(combined_counts.get(s, 0) for s in EXTERNAL_SYMBOLS) + system_call_total = sum(combined_counts.get(s, 0) for s in SYSTEM_SYMBOLS) + + if len(binaries) != 44: + raise ValueError(f'Expected 44 Mach-O binaries, got {len(binaries)}') + if external_call_total != 0 or system_call_total != 0 or callsite_total != 0: + raise ValueError( + f'Non-zero residual callsites: external={external_call_total}, ' + f'system={system_call_total}, total={callsite_total}, counts={combined_counts}' + ) + + variant_stubs = [] + for mpath in sorted(map(Path, iter_macho_files(str(app_dir)))): + mdata = mpath.read_bytes() + for off, _ in arm64_slices(mdata): + sl = Slice(mdata, off) + if not (sl.stubs and sl.symtab and sl.dysym): + continue + import struct + symoff, _, stroff, _ = sl.symtab + indoff = sl.dysym[12] + _, ssize, _, sr1, sr2 = sl.stubs + for idx_pos in range(ssize // sr2): + symi, = struct.unpack_from(' 0), + frameworks_thinned=sum(1 for r in fw_reports if r['thinned']), + whitelist=whitelist_report, + codesign_verified_count=len(verified_bundles), + ipa=str(ipa_path), + ipa_sha256=sha256(ipa_path), + ) + (output / 'route2-summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n') + return summary + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source-app', type=Path, required=True) + parser.add_argument('--relinked-main', type=Path, required=True) + parser.add_argument('--app-repo', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + result = package( + args.source_app.resolve(), + args.relinked_main.resolve(), + args.app_repo.resolve(), + args.output.resolve(), + ) + print(json.dumps(result, ensure_ascii=False, indent=2)) diff --git a/tools/macho_guard/profiles/alipay_fopen.json b/tools/macho_guard/profiles/alipay_fopen.json new file mode 100644 index 0000000..046397e --- /dev/null +++ b/tools/macho_guard/profiles/alipay_fopen.json @@ -0,0 +1,10 @@ +{ + "rules": [ + { + "caller": "__isJailbreak", + "symbol": "_fopen", + "destination": "_IG_dispatch_fopen", + "expected_count": 6 + } + ] +} diff --git a/tools/macho_guard/profiles/main_residual_dispatch.json b/tools/macho_guard/profiles/main_residual_dispatch.json new file mode 100644 index 0000000..50a7856 --- /dev/null +++ b/tools/macho_guard/profiles/main_residual_dispatch.json @@ -0,0 +1,70 @@ +{ + "rules": [ + { + "caller": "__isJailbreak", + "symbol": "_fopen", + "destination": "_IG_dispatch_fopen", + "expected_count": 6 + }, + { + "caller": "_SignalHandler", + "symbol": "_getpid", + "destination": "_IG_dispatch_getpid", + "expected_count": 1 + }, + { + "caller": "+[UMInternalUtil Value2]", + "symbol": "_getpid", + "destination": "_IG_dispatch_getpid", + "expected_count": 1 + }, + { + "caller": "__initializeAvailabilityCheck", + "symbol": "_fopen", + "destination": "_IG_dispatch_fopen", + "expected_count": 1 + }, + { + "caller": "__initializeAvailabilityCheck", + "symbol": "_dlsym", + "destination": "_IG_dispatch_dlsym", + "expected_count": 10 + }, + { + "caller": "__ZZZL25swift_voucher_needs_adoptP9voucher_sENKUlvE_clEvENUlPvE_8__invokeES2_", + "symbol": "_dlsym", + "destination": "_IG_dispatch_dlsym", + "expected_count": 1 + }, + { + "caller": "__ZZZN5swift19_swift_tsan_acquireEPvENK3$_0clEvENUlS0_E_8__invokeES0_", + "symbol": "_dlsym", + "destination": "_IG_dispatch_dlsym", + "expected_count": 1 + }, + { + "caller": "__ZZZN5swift19_swift_tsan_releaseEPvENK3$_0clEvENUlS0_E_8__invokeES0_", + "symbol": "_dlsym", + "destination": "_IG_dispatch_dlsym", + "expected_count": 1 + }, + { + "caller": "__ZZZN5swift31swift_task_escalateBackdeploy56EPNS_9AsyncTaskENS_11JobPriorityEENK3$_0clEvENUlPvE_8__invokeES4_", + "symbol": "_dlsym", + "destination": "_IG_dispatch_dlsym", + "expected_count": 1 + }, + { + "caller": "__ZZZN5swift45swift_task_exitThreadLocalContextBackdeploy56EPcENK3$_0clEvENUlPvE_8__invokeES2_", + "symbol": "_dlsym", + "destination": "_IG_dispatch_dlsym", + "expected_count": 1 + }, + { + "caller": "__ZZZN5swift46swift_task_enterThreadLocalContextBackdeploy56EPcENK3$_0clEvENUlPvE_8__invokeES2_", + "symbol": "_dlsym", + "destination": "_IG_dispatch_dlsym", + "expected_count": 1 + } + ] +} diff --git a/tools/macho_guard/redirect_framework_imports.py b/tools/macho_guard/redirect_framework_imports.py index 4448323..62e9f5c 100644 --- a/tools/macho_guard/redirect_framework_imports.py +++ b/tools/macho_guard/redirect_framework_imports.py @@ -8,8 +8,29 @@ import struct from machox import Macho, LC_SEGMENT_64, LC_SYMTAB, LC_DYLD_CHAINED_FIXUPS -DEPENDENCY = '@rpath/IGArchiveGuard.framework/IGArchiveGuard' -MAPPING = {'_fopen': '_ig_a0', '_fread': '_ig_a1', '_fwrite': '_ig_a2', '_fclose': '_ig_a3'} +GUARD_FRAMEWORK_NAME = 'RDCoreIO' +DEPENDENCY = '@rpath/RDCoreIO.framework/RDCoreIO' +MAPPING = {'_fopen': '_rd_a0', '_fread': '_rd_a1', '_fwrite': '_rd_a2', '_fclose': '_rd_a3'} +ALLOWED_MAPPING = { + '_fopen': '_rd_a0', + '_fread': '_rd_a1', + '_fwrite': '_rd_a2', + '_fclose': '_rd_a3', + '_unlink': '_rd_a4', + '_open': '_rd_o', + '_read': '_rd_r', + '_write': '_rd_w0', + '_close': '_rd_c0', + '_getpid': '_rd_p00', + '_exit': '_rd_e', + '_fork': '_rd_k', + '_dlopen': '_rd_l00', + '_dlsym': '_rd_s0', +} +REPORT_TARGET_SYMBOLS = { + '_fopen', '_dlopen', '_dlsym', '_write', '_read', '_open', + '_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid', +} LOADS = (0xc, 0x80000018, 0x8000001f, 0x80000023, 0x20) @@ -18,7 +39,45 @@ def require(value, message): raise ValueError(message) -def rewrite(data, expected_sha256): +def detect_chained_target_mapping(data, include_stdio_rw=False): + m = Macho(data) + deps = [] + for cmd, size, off in m.cmds: + if cmd in LOADS: + n = struct.unpack_from('> 9) + end = m.d.index(0, start, pool_end) + name = bytes(m.d[start:end]).decode('utf-8') + if name in wanted: + require(name in ALLOWED_MAPPING, f'缺少框架保护映射: {name}') + found[name] = ALLOWED_MAPPING[name] + return found + + +def rewrite(data, expected_sha256, mapping=None): + mapping = MAPPING if mapping is None else mapping + require(bool(mapping) and all(k in ALLOWED_MAPPING and ALLOWED_MAPPING[k] == v for k, v in mapping.items()), + '映射必须是已实现的保护入口子集') require(hashlib.sha256(data).hexdigest() == expected_sha256, 'SDK 哈希不匹配,须重新审核版本') m = Macho(data) require(m.filetype == 6 and m.flags & 0x80, '需要 two-level MH_DYLIB') @@ -66,17 +125,17 @@ def rewrite(data, expected_sha256): require(pool_start <= start < pool_end, '字符串索引越界') end = m.d.index(0, start, pool_end) name = bytes(m.d[start:end]).decode('utf-8') - require(name not in MAPPING.values(), '已改写或目标冲突') + require(name not in mapping.values(), '已改写或目标冲突') intervals.append((start, end + 1, name)) - if name in MAPPING: + if name in mapping: require(name not in selected and ordinal_value == old_ordinal, '重复导入或提供方不匹配') selected[name] = (entry, start, end) - require(set(selected) == set(MAPPING), '缺少预期四个文件函数') + require(set(selected) == set(mapping), '缺少配置的文件函数') for name, (entry, start, end) in selected.items(): require(all(other == name or finish <= start or begin >= end + 1 for begin, finish, other in intervals), '共享后缀字符串,拒绝原地改名') - encoded = MAPPING[name].encode() + encoded = mapping[name].encode() require(len(encoded) <= end - start, '新名称超出原字符串空间') write(start, encoded + bytes(end - start + 1 - len(encoded))) if kind == 'chained': @@ -87,7 +146,7 @@ def rewrite(data, expected_sha256): desc = struct.unpack_from('= 128: + result.append((value & 127) | 128) + value >>= 7 + result.append(value) + return bytes(result) + + +def rewrite(data, expected_sha): + require(hashlib.sha256(data).hexdigest() == expected_sha, 'Input hash changed') + m = Macho(data) + require(m.filetype == 6 and m.flags & 0x80, 'Expected two-level dylib') + deps, dyld, symtab, sections = [], [], [], [] + for cmd, size, off in m.cmds: + if cmd in LOADS: + nameoff = struct.unpack_from(' 0 and fileoff + length <= len(data), 'Invalid section') + sections.append((fileoff, length)) + require(len(dyld) == len(symtab) == 1 and sections, 'Missing tables') + require(DEPENDENCY not in deps and len(deps) < 0x7e, 'Dependency conflict') + old = deps.index('/usr/lib/libSystem.B.dylib') + 1 + new = len(deps) + 1 + fields = struct.unpack_from('<10I', m.d, dyld[0] + 8) + for i in (1, 2): + offset, size = fields[i * 2:i * 2 + 2] + require(SOURCE + b'\0' not in data[offset:offset + size], + 'fopen also appears in regular or weak binding') + offset, size = fields[6:8] + require(offset + size <= len(data), 'Lazy stream outside file') + pos, end, records = offset, offset + size, [] + record = {'symbols': [], 'ordinals': [], 'binds': 0} + while pos < end: + at = pos + opcode = data[pos] & 0xf0 + imm = data[pos] & 15 + pos += 1 + if opcode == 0: + require(imm == 0, 'Invalid DONE opcode') + if record['symbols']: + records.append(record) + record = {'symbols': [], 'ordinals': [], 'binds': 0} + elif opcode == 0x10: + record['ordinals'].append((at, pos, imm, False)) + elif opcode == 0x20: + value, pos, start = uleb(data, pos, end) + record['ordinals'].append((start, pos, value, True)) + elif opcode == 0x40: + finish = data.index(0, pos, end) + record['symbols'].append((pos, finish, data[pos:finish], imm)) + pos = finish + 1 + elif opcode in (0x60, 0x70, 0x80): + _, pos, _ = uleb(data, pos, end) + elif opcode == 0x50: + pass + elif opcode == 0x90: + record['binds'] += 1 + else: + raise ValueError(f'Unsupported lazy opcode {opcode:#x}') + require(not record['symbols'] and not record['ordinals'] and not record['binds'], 'Unterminated lazy record') + selected = [r for r in records if any(s[2] == SOURCE for s in r['symbols'])] + require(len(selected) == 1, 'Need exactly one fopen lazy record') + r = selected[0] + require(len(r['symbols']) == len(r['ordinals']) == r['binds'] == 1, + 'Shared or multi-bind lazy record') + start, finish, name, flags = r['symbols'][0] + require(flags == 0 and len(DESTINATION) == finish - start, 'Unsupported symbol flags/length') + at, stop, ordinal, extended = r['ordinals'][0] + require(ordinal == old, 'Unexpected provider') + encoded = encode(new) if extended else bytes([0x10 | new]) if new < 16 else b'' + require(len(encoded) == stop - at, 'Ordinal size would move lazy records') + allowed = set() + def write(at, content): + m.d[at:at + len(content)] = content + allowed.update(range(at, at + len(content))) + write(start, DESTINATION) + write(at, encoded) + + so, count, strings, stringsize = struct.unpack_from('<4I', data, symtab[0] + 8) + require(so + count * 16 <= len(data) and strings + stringsize <= len(data), 'Invalid symbol table') + matched = 0 + intervals = [] + for i in range(count): + entry = so + i * 16 + index, typ, _, desc, _ = struct.unpack_from('= stringsize: + raise ValueError('Symbol name outside pool') + nameend = data.index(0, strings + index, strings + stringsize) + intervals.append((strings + index, nameend + 1)) + if data[strings + index:nameend] != SOURCE: + continue + require(typ == 1 and desc >> 8 == old, 'Unexpected nlist provider') + symbol_span = (strings + index, nameend + 1) + write(strings + index, DESTINATION) + write(entry + 6, struct.pack('= symbol_span[1] + for span in intervals), 'Shared symbol-name suffix') + name = DEPENDENCY.encode() + b'\0' + length = (24 + len(name) + 7) & ~7 + at = 32 + m.sizeofcmds + require(at + length <= min(s[0] for s in sections), 'Insufficient header padding') + require(not any(data[at:at + length]), 'Nonzero header padding') + command = struct.pack('<6I', 0xc, length, 24, 0, 0x10000, 0x10000) + name + write(at, command + bytes(length - len(command))) + write(16, struct.pack('= 128: + result.append((value & 127) | 128) + value >>= 7 + result.append(value) + return bytes(result) + + +def parse_bind_symbols(data, offset, size): + if not size: + return set() + require(offset + size <= len(data), 'Bind stream outside file') + pos, end, symbols = offset, offset + size, set() + while pos < end: + opcode = data[pos] & 0xf0 + pos += 1 + if opcode in (0x00, 0x10, 0x30, 0x50, 0x90, 0xb0): + pass + elif opcode in (0x20, 0x70, 0x80, 0xa0): + _, pos, _ = uleb(data, pos, end) + elif opcode == 0x60: + pos = sleb_skip(data, pos, end) + elif opcode == 0xc0: + _, pos, _ = uleb(data, pos, end) + _, pos, _ = uleb(data, pos, end) + elif opcode == 0x40: + finish = data.index(0, pos, end) + symbols.add(data[pos:finish]) + pos = finish + 1 + else: + raise ValueError(f'Unsupported bind opcode {opcode:#x}') + return symbols + + +def parse_lazy_records(data, offset, size): + require(offset + size <= len(data), 'Lazy stream outside file') + pos, end, records = offset, offset + size, [] + record = {'symbols': [], 'ordinals': [], 'binds': 0} + while pos < end: + at = pos + opcode = data[pos] & 0xf0 + imm = data[pos] & 15 + pos += 1 + if opcode == 0: + require(imm == 0, 'Invalid DONE opcode') + if record['symbols']: + records.append(record) + record = {'symbols': [], 'ordinals': [], 'binds': 0} + elif opcode == 0x10: + record['ordinals'].append((at, pos, imm, False)) + elif opcode == 0x20: + value, pos, _ = uleb(data, pos, end) + record['ordinals'].append((at, pos, value, True)) + elif opcode == 0x40: + finish = data.index(0, pos, end) + record['symbols'].append((pos, finish, data[pos:finish], imm)) + pos = finish + 1 + elif opcode in (0x70, 0x80, 0xa0): + _, pos, _ = uleb(data, pos, end) + elif opcode == 0x60: + pos = sleb_skip(data, pos, end) + elif opcode == 0xc0: + _, pos, _ = uleb(data, pos, end) + _, pos, _ = uleb(data, pos, end) + elif opcode in (0x50, 0x90, 0xb0): + if opcode == 0x90: + record['binds'] += 1 + else: + raise ValueError(f'Unsupported lazy opcode {opcode:#x}') + require(not record['symbols'] and not record['ordinals'] and not record['binds'], + 'Unterminated lazy record') + return records + + +def detect_legacy_target_mapping(data): + m = Macho(data) + deps = [] + dyld_cmds = [] + for cmd, size, off in m.cmds: + if cmd in LOADS: + nameoff = struct.unpack_from(' 0 and fileoff + length <= len(data), 'Invalid section') + sections.append((fileoff, length)) + require(len(dyld) == len(symtab) == 1 and sections, 'Missing tables') + require(DEPENDENCY not in deps and len(deps) < 0x7e, 'Dependency conflict') + old = deps.index('/usr/lib/libSystem.B.dylib') + 1 + new = len(deps) + 1 + old_width = 1 if old < 16 else 2 + new_width = 1 if new < 16 else 2 + delta = new_width - old_width + allowed_table = EQUAL_LEN_MAPPING if delta == 0 else SHRINK1_MAPPING if delta == 1 else {} + require(bool(allowed_table), f'Unsupported ordinal width delta: {delta}') + + if mapping is None: + mapping = detect_legacy_target_mapping(data) + require(bool(mapping) and all(k in allowed_table and allowed_table[k] == v for k, v in mapping.items()), + 'Mapping must match allowed legacy wrapper table') + byte_mapping = {k.encode('ascii'): v.encode('ascii') for k, v in mapping.items()} + + fields = struct.unpack_from('<10I', m.d, dyld[0] + 8) + for i in (1, 2): + offset, size = fields[i * 2:i * 2 + 2] + bind_syms = parse_bind_symbols(data, offset, size) + for src in byte_mapping: + require(src not in bind_syms, + f'{src.decode()} appears in regular or weak binding') + + records = parse_lazy_records(data, fields[6], fields[7]) + selected = [] + for rec in records: + if any(s[2] in byte_mapping for s in rec['symbols']): + require(len(rec['symbols']) == len(rec['ordinals']) == rec['binds'] == 1, + 'Shared or multi-bind lazy record') + selected.append(rec) + require({r['symbols'][0][2] for r in selected} == set(byte_mapping), + 'Not all mapped symbols matched unique lazy records') + + allowed = set() + def write(at, content): + require(at >= 0 and at + len(content) <= len(m.d), 'Write out of range') + m.d[at:at + len(content)] = content + allowed.update(range(at, at + len(content))) + + new_ord_bytes = bytes([0x10 | new]) if new < 16 else b'\x20' + encode_uleb(new) + changes = [] + for rec in selected: + start, finish, src_sym, flags = rec['symbols'][0] + dst_sym = byte_mapping[src_sym] + ord_start, ord_stop, ordinal, _ = rec['ordinals'][0] + require(flags == 0 and ordinal == old, 'Unexpected symbol flags or provider') + sym_opcode_pos = start - 1 + require(data[sym_opcode_pos] == 0x40, 'Expected SET_SYMBOL_TRAILING_FLAGS_IMM(0) before symbol') + require(ord_stop == sym_opcode_pos, 'Expected ordinal opcode immediately before symbol opcode') + old_span = finish + 1 - ord_start + replacement = new_ord_bytes + b'\x40' + dst_sym + b'\0' + require(len(replacement) == old_span, 'Replacement size would shift lazy records') + write(ord_start, replacement) + changes.append(dict(table='lazy', source=src_sym.decode(), destination=dst_sym.decode(), + old_ordinal=old, new_ordinal=new)) + + so, count, strings, stringsize = struct.unpack_from('<4I', data, symtab[0] + 8) + require(so + count * 16 <= len(data) and strings + stringsize <= len(data), 'Invalid symbol table') + matched = {} + intervals = [] + target_spans = [] + for i in range(count): + entry = so + i * 16 + index, typ, _, desc, value = struct.unpack_from('> 8) == old and not (desc & 0x40), 'Unexpected nlist provider or weak symbol') + dst = byte_mapping[sym] + require(len(dst) <= len(sym), 'Destination longer than source in string pool') + span = (strings + index, nameend + 1, sym) + target_spans.append(span) + write(strings + index, dst + b'\0' * (len(sym) + 1 - len(dst))) + write(entry + 6, struct.pack('= e1 for b2, e2, n2 in intervals), + 'Shared symbol-name suffix') + + name = DEPENDENCY.encode() + b'\0' + length = (24 + len(name) + 7) & ~7 + at = 32 + m.sizeofcmds + require(at + length <= min(s[0] for s in sections), 'Insufficient header padding') + require(not any(data[at:at + length]), 'Nonzero header padding') + command = struct.pack('<6I', 0xc, length, 24, 0, 0x10000, 0x10000) + name + write(at, command + bytes(length - len(command))) + write(16, struct.pack(' address) + calls = [] + for site in range(address, end, 4): + word, = struct.unpack_from(' len(data): + raise ValueError('Invalid Mach-O load command') + if cmd == 0x19: + sections = struct.unpack_from(' 1: + if file_offset + length > len(data): + raise ValueError('Embedded bitcode outside object') + return data[file_offset:file_offset + length] + offset += size + return None + + +def rewrite(source, output, mapping, allow_darwin_extsn=False): + validate_mapping(mapping, allow_darwin_extsn=allow_darwin_extsn) + if output.exists() or output.is_symlink(): + raise FileExistsError(output) + if not source.read_bytes().startswith(ARCHIVE_MAGIC): + raise ValueError('Expected a thin arm64 archive') + if not mapping: + raise ValueError('Empty mapping') + report = [] + with tempfile.TemporaryDirectory(dir=output.parent, prefix='.bitcode-') as tmp: + work = Path(tmp) + data = source.read_bytes() + result = bytearray(ARCHIVE_MAGIC) + cursor = len(ARCHIVE_MAGIC) + while cursor < len(data): + header = data[cursor:cursor + 60] + if len(header) != 60 or header[58:] != b'`\n': + raise ValueError('Invalid archive header') + size = int(header[48:58]) + payload = data[cursor + 60:cursor + 60 + size] + if len(payload) != size: + raise ValueError('Truncated archive member') + name = header[:16].rstrip() + prefix = b'' + if name.startswith(b'#1/'): + length = int(name[3:]) + if not 0 < length <= len(payload): + raise ValueError('Invalid extended member name') + prefix, payload = payload[:length], payload[length:] + name = prefix.rstrip(b'\0') + name = name.rstrip(b'/') + if size % 2 and data[cursor + 60 + size:cursor + 61 + size] != b'\n': + raise ValueError('Invalid archive padding') + cursor += 60 + size + size % 2 + if name.startswith(b'__.SYMDEF'): + continue + member = work / 'member.o' + member.write_bytes(payload) + imports = {line.split()[-1] for line in run_tool('nm', '-u', member).decode().splitlines() if line.split()} + if imports & set(mapping): + before = collections.Counter(run_tool('nm', '-gjU', member).splitlines()) + embedded = embedded_bitcode(payload) + compiled = embedded is not None or payload[:4] in (b'\xde\xc0\x17\x0b', b'BC\xc0\xde') + if compiled: + if embedded is not None: + member.write_bytes(embedded) + native = work / 'native.o' + with (work / 'compile.log').open('wb') as log: + subprocess.run(['xcrun', '--sdk', 'iphoneos', 'clang', '-target', + 'arm64-apple-ios15.0', '-x', 'ir', '-c', str(member), + '-o', str(native)], check=True, stderr=log) + payload = native.read_bytes() + report_log = output.parent / (output.name + '.compile.log') + with report_log.open('ab') as log: + log.write(name + b'\n' + (work / 'compile.log').read_bytes()) + payload, count = redirect_object(payload, mapping, allow_darwin_extsn=allow_darwin_extsn) + member.write_bytes(payload) + if before != collections.Counter(run_tool('nm', '-gjU', member).splitlines()): + raise ValueError('Defined symbols changed') + report.append(dict(member=name.decode(), references=count, compiled_bitcode=compiled)) + body = prefix + payload + result.extend(header[:48] + str(len(body)).encode().ljust(10) + header[58:]) + result.extend(body) + if len(body) % 2: + result.extend(b'\n') + if not report: + raise ValueError('No matching imports') + candidate = work / 'candidate.a' + candidate.write_bytes(result) + run_tool('ranlib', candidate) + # Publish without overwriting an existing output. + import os + os.link(candidate, output) + return dict(source_sha256=hashlib.sha256(data).hexdigest(), + output_sha256=hashlib.sha256(output.read_bytes()).hexdigest(), + mapping=mapping, members=report) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('source', type=Path) + parser.add_argument('output', type=Path) + parser.add_argument('mapping', type=Path) + args = parser.parse_args() + print(json.dumps(rewrite(args.source, args.output, json.loads(args.mapping.read_text())), indent=2)) diff --git a/tools/static_sdk_redirect/redirect_symbols.py b/tools/static_sdk_redirect/redirect_symbols.py index 2f92263..b3ae46b 100644 --- a/tools/static_sdk_redirect/redirect_symbols.py +++ b/tools/static_sdk_redirect/redirect_symbols.py @@ -32,12 +32,14 @@ def bounds(data, offset, length): "数据范围越界") -def validate_mapping(mapping): +def validate_mapping(mapping, allow_darwin_extsn=False): require(isinstance(mapping, dict) and bool(mapping), "映射必须是非空 JSON 对象") + source_pattern = r"_[A-Za-z_][A-Za-z0-9_]*(\$DARWIN_EXTSN)?" if allow_darwin_extsn else r"_[A-Za-z_][A-Za-z0-9_]*" for source, target in mapping.items(): - for name in (source, target): - require(isinstance(name, str) and re.fullmatch(r"_[A-Za-z_][A-Za-z0-9_]*", name), - "映射须使用带下划线前缀的精确 Mach-O C 符号名") + require(isinstance(source, str) and re.fullmatch(source_pattern, source), + "映射须使用带下划线前缀的精确 Mach-O C 符号名") + require(isinstance(target, str) and re.fullmatch(r"_[A-Za-z_][A-Za-z0-9_]*", target), + "映射须使用带下划线前缀的精确 Mach-O C 符号名") require(len(set(mapping.values())) == len(mapping), "多个源符号不能共用一个目标") require(not set(mapping).intersection(mapping.values()), "不允许自映射、映射链或循环") return {source.encode("ascii"): target.encode("ascii") for source, target in mapping.items()} @@ -55,8 +57,10 @@ def load_mapping(path): return mapping -def redirect_object(data, mapping=None): - rewritten, counts = _redirect_object(data, validate_mapping(DEFAULT_MAPPING if mapping is None else mapping)) +def redirect_object(data, mapping=None, allow_darwin_extsn=False): + encoded = validate_mapping(DEFAULT_MAPPING if mapping is None else mapping, + allow_darwin_extsn=allow_darwin_extsn) + rewritten, counts = _redirect_object(data, encoded) return rewritten, sum(counts.values()) diff --git a/tools/xcode_archive/audit_exported_ipa.py b/tools/xcode_archive/audit_exported_ipa.py new file mode 100755 index 0000000..6d0b704 --- /dev/null +++ b/tools/xcode_archive/audit_exported_ipa.py @@ -0,0 +1,484 @@ +#!/usr/bin/env python3 +"""Audit exported IPA for Route 2 compliance, static hygiene, dSYM UUID consistency, and Mach-O hardening gates.""" +import argparse +from concurrent.futures import ThreadPoolExecutor +import json +from pathlib import Path +import plistlib +import re +import subprocess +import sys +from tempfile import TemporaryDirectory + +SCRIPT_DIR = Path(__file__).resolve().parent +TOOLS_DIR = SCRIPT_DIR.parent +TOOLCHAIN_ROOT = TOOLS_DIR.parent + +sys.path.insert(0, str(SCRIPT_DIR)) +sys.path.insert(0, str(TOOLS_DIR / 'macho_guard')) +sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf')) + +from route2_archive_common import ( # noqa: E402 + EXTERNAL_SYMBOLS, + GUARD_FRAMEWORK_NAME, + SYSTEM_SYMBOLS, + collect_variant_stubs, +) +from verify_baseline import scan, validate_zip # noqa: E402 +import verify_macho_indirect_branches # noqa: E402 +import verify_macho_indirect_calls # noqa: E402 +import verify_macho_star_cfg # noqa: E402 + +_ANTI_HOOK_OBJDUMP_RE = re.compile(r'^\s*([0-9a-fA-F]+):\s+([0-9a-fA-F]{8})\s+(.+?)\s*$') +_ANTI_HOOK_MOV_RE = re.compile(r'^(?:mov\s+(x1[67])\s*,\s*\1|orr\s+(x1[67])\s*,\s*xzr\s*,\s*\2)\b') +_ANTI_HOOK_OPCODES = {'aa1103f1': 'x17', 'aa1003f0': 'x16'} + +_FORBIDDEN_DEFENDER_CLUES = ( + b'IGDefender', + b'IGAntiHook', + b'IGAntiTamper', + b'IGArchiveGuard', + b'termination.jsonl', + b'"action":"terminate"', +) +_JAILBREAK_QUERY_SCHEMES = {'cydia', 'sileo', 'zebra', 'zbra', 'filza', 'undecimus'} + + +def _uuids_of(path): + out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True) + return {line.split()[1] for line in out.splitlines() if line.startswith('UUID:')} + + +def _inspect_anti_hook_range(main_bin, start_addr, end_addr): + if end_addr - start_addr < 8: + return { + 'start_addr': hex(start_addr), + 'end_addr': hex(end_addr), + 'ok': False, + 'insns': [], + 'reason': 'function_shorter_than_8_bytes', + } + dis = subprocess.check_output( + [ + 'xcrun', 'llvm-objdump', '--disassemble', + f'--start-address={hex(start_addr)}', + f'--stop-address={hex(start_addr + 8)}', + str(main_bin), + ], + text=True, + ) + insns = [] + seen_regs = set() + for line in dis.splitlines(): + m = _ANTI_HOOK_OBJDUMP_RE.match(line) + if not m: + continue + addr = int(m.group(1), 16) + ophex = m.group(2).lower() + text = ' '.join(m.group(3).split()) + reg = _ANTI_HOOK_OPCODES.get(ophex) + if reg is None: + mm = _ANTI_HOOK_MOV_RE.match(text) + if mm: + reg = mm.group(1) or mm.group(2) + insns.append({'addr': hex(addr), 'opcode': ophex, 'asm': text, 'reg': reg}) + if reg in ('x16', 'x17'): + seen_regs.add(reg) + ok = ( + len(insns) >= 2 + and insns[0]['addr'] == hex(start_addr) + and insns[1]['addr'] == hex(start_addr + 4) + and insns[0]['reg'] in ('x16', 'x17') + and insns[1]['reg'] in ('x16', 'x17') + and seen_regs == {'x16', 'x17'} + ) + return { + 'start_addr': hex(start_addr), + 'end_addr': hex(end_addr), + 'ok': ok, + 'insns': insns[:2], + } + + +def _verify_binary_anti_hook_prologues(main_bin, dwarf_bin, obf_audit): + ranges_map = verify_macho_star_cfg.parse_dwarf_text_ranges(dwarf_bin) + verified = [] + failed = [] + dead_stripped = [] + to_check = [] + + for mod in obf_audit.get('module_audits') or []: + src_name = Path(mod.get('source_path') or 'unknown').name + for raw_name in mod.get('anti_hook_functions') or []: + cand_ranges = [] + for key in verify_macho_star_cfg._candidate_symbol_keys(raw_name): + if key in ranges_map: + cand_ranges = ranges_map[key] + break + if not cand_ranges: + dead_stripped.append({'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'}) + continue + to_check.append((src_name, raw_name, cand_ranges)) + + unique_ranges = sorted({se for _, _, rlist in to_check for se in rlist}) + inspected_by_range = {} + if unique_ranges: + with ThreadPoolExecutor(max_workers=8) as pool: + results = pool.map(lambda se: _inspect_anti_hook_range(main_bin, se[0], se[1]), unique_ranges) + for se, res in zip(unique_ranges, results): + inspected_by_range[se] = res + + for src_name, raw_name, cand_ranges in to_check: + range_results = [inspected_by_range[se] for se in cand_ranges] + bad = [r for r in range_results if not r['ok']] + if bad: + failed.append({ + 'source': src_name, + 'name': raw_name, + 'reason': 'missing_anti_hook_x16_x17_prologue', + 'range_results': range_results, + }) + else: + verified.append({'source': src_name, 'name': raw_name, **range_results[0]}) + + summary = { + 'total_audited': len(verified) + len(failed) + len(dead_stripped), + 'linked_checked_count': len(verified) + len(failed), + 'verified_anti_hook_count': len(verified), + 'dead_stripped_count': len(dead_stripped), + 'failed_count': len(failed), + 'failed': failed, + 'sample_verified': verified[:12], + } + if failed: + preview = json.dumps(failed[:5], ensure_ascii=False, indent=2) + raise ValueError(f'[AntiHookGate] {len(failed)} function(s) failed x16/x17 prologue check:\n{preview}') + return summary + + +def _check_static_hygiene(app_dir, main_bin, info): + """Run static-hygiene checks on unpacked .app payload (zero hardcoded host paths).""" + main_raw = main_bin.read_bytes() + + fw_dir = app_dir / 'Frameworks' + rd_coreio_bin = fw_dir / f'{GUARD_FRAMEWORK_NAME}.framework' / GUARD_FRAMEWORK_NAME + rd_coreio_exists = rd_coreio_bin.is_file() + ig_archive_guard_absent = not (fw_dir / 'IGArchiveGuard.framework').exists() + + rd_coreio_ig_exports = [] + rd_coreio_ig_name_count = 0 + if rd_coreio_exists: + core_raw = rd_coreio_bin.read_bytes() + rd_coreio_ig_name_count = core_raw.count(b'IGArchiveGuard') + nm_core = subprocess.check_output(['xcrun', 'nm', '-gU', str(rd_coreio_bin)], text=True, errors='replace') + rd_coreio_ig_exports = sorted( + sym for ln in nm_core.splitlines() + if ln.strip() and (sym := ln.split()[-1]).startswith('_ig_') + ) + + staticized_framework_leaks = [ + name for name in ('RDEpubReaderView.framework', 'RDPDFReaderView.framework') + if (fw_dir / name).exists() + ] + + otool_l = subprocess.check_output(['xcrun', 'otool', '-L', str(main_bin)], text=True, errors='replace').splitlines() + cryptokit_load_cmds = [ln.strip() for ln in otool_l if 'CryptoKit' in ln] + + nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(main_bin)], text=True, errors='replace').splitlines() + cryptokit_imports = sorted({ + ln.strip() for ln in nm_u + if ln.strip() and ('CryptoKit' in ln or '9CryptoKit' in ln) + }) + + nm_gu = subprocess.check_output(['xcrun', 'nm', '-gU', str(main_bin)], text=True, errors='replace') + defined_exports = sorted({ln.split()[-1] for ln in nm_gu.splitlines() if ln.strip()}) + allowed_exports = {'_main', '__mh_execute_header'} + main_exports_locked = set(defined_exports).issubset(allowed_exports) + + forbidden_clue_counts = { + pat.decode('ascii', errors='replace'): main_raw.count(pat) + for pat in _FORBIDDEN_DEFENDER_CLUES + } + + ats = info.get('NSAppTransportSecurity') or {} + ats_arbitrary_disabled = ats.get('NSAllowsArbitraryLoads') is not True + schemes = {str(s).lower() for s in (info.get('LSApplicationQueriesSchemes') or [])} + jb_schemes_found = sorted(schemes & _JAILBREAK_QUERY_SCHEMES) + + checks = { + 'guard_framework_present': rd_coreio_exists, + 'ig_archive_guard_absent': ig_archive_guard_absent, + 'guard_no_ig_exports': not rd_coreio_ig_exports, + 'guard_no_ig_name_string': rd_coreio_ig_name_count == 0, + 'self_frameworks_staticized': not staticized_framework_leaks, + 'cryptokit_completely_absent': not cryptokit_load_cmds and not cryptokit_imports, + 'main_exports_locked': main_exports_locked, + 'defender_clues_absent': sum(forbidden_clue_counts.values()) == 0, + 'ats_arbitrary_loads_disabled': ats_arbitrary_disabled, + 'jailbreak_schemes_absent': not jb_schemes_found, + } + return { + 'passed': all(checks.values()), + 'checks': checks, + 'rd_coreio_ig_exports': rd_coreio_ig_exports, + 'rd_coreio_ig_name_count': rd_coreio_ig_name_count, + 'staticized_framework_leaks': staticized_framework_leaks, + 'cryptokit_load_cmds': cryptokit_load_cmds, + 'cryptokit_imports': cryptokit_imports, + 'main_defined_exports': defined_exports, + 'forbidden_clue_counts': forbidden_clue_counts, + 'jailbreak_schemes_found': jb_schemes_found, + } + + +def _check_obf_audit_counts(obf_audit, policy): + failures = [] + checks = [ + ('flatten_targets', 'total_flattened'), + ('opaque_const_targets', 'total_opaque_constants'), + ('arithmetic_targets', 'total_arithmetic_rewrites'), + ('indirect_branch_targets', 'total_indirect_branches'), + ('string_encrypt_stack_targets', 'total_strings_stack_encrypted'), + ('anti_hooking_targets', 'total_anti_hook_functions'), + ('function_outline_targets', 'total_functions_outlined'), + ('opaque_field_targets', 'total_opaque_field_access'), + ('bb_split_targets', 'total_bb_split_count'), + ] + for pol_key, audit_key in checks: + if policy.get(pol_key) and int(obf_audit.get(audit_key) or 0) <= 0: + failures.append(f'{audit_key} expected > 0') + + has_str = any( + policy.get(k) + for k in ('string_encrypt_targets', 'string_encrypt_objc_targets', 'string_encrypt_swift_targets') + ) + if has_str and int(obf_audit.get('total_strings_encrypted') or 0) <= 0: + failures.append('total_strings_encrypted expected > 0') + + if policy.get('arithmetic_nonlinear_mba') or any(r.get('nonlinear_mba') for r in (policy.get('arithmetic_targets') or [])): + if int(obf_audit.get('total_nonlinear_mba') or 0) <= 0: + failures.append('total_nonlinear_mba expected > 0') + + if policy.get('opaque_const_opaque_zero') or any(r.get('opaque_zero') for r in (policy.get('opaque_const_targets') or [])): + if int(obf_audit.get('total_opaque_zero') or 0) <= 0: + failures.append('total_opaque_zero expected > 0') + + policy_reqs = {r['id']: r for r in (policy.get('required_targets') or []) if isinstance(r, dict) and r.get('id')} + if policy_reqs and isinstance(obf_audit.get('required_targets'), list): + got_map = {r['id']: r for r in obf_audit['required_targets'] if isinstance(r, dict) and r.get('id')} + for tid, req in policy_reqs.items(): + got = got_map.get(tid) + if got is None: + failures.append(f'missing required_target: {tid}') + continue + if int(got.get('flattened_hits') or 0) < int(req.get('min_flattened', 0)): + failures.append(f'{tid} flattened_hits={got.get("flattened_hits")} < {req.get("min_flattened", 0)}') + if int(got.get('strings_encrypted_hits') or 0) < int(req.get('min_strings_encrypted', 0)): + failures.append( + f'{tid} strings_encrypted_hits={got.get("strings_encrypted_hits")} < {req.get("min_strings_encrypted", 0)}' + ) + + return failures + + +def _load_policy(policy_path=None): + cand = Path(policy_path) if policy_path else (TOOLCHAIN_ROOT / 'config' / 'ig_llvm_policy.json') + if cand.is_file(): + return json.loads(cand.read_text(encoding='utf-8')) + return {} + + +def _find_dwarf_in_archive(archive_path, app_name, exec_name): + dsyms_dir = Path(archive_path) / 'dSYMs' + if not dsyms_dir.is_dir(): + return None + for cand_name in (f'{app_name}.dSYM', f'{exec_name}.app.dSYM'): + dwarf_p = dsyms_dir / cand_name / 'Contents' / 'Resources' / 'DWARF' / exec_name + if dwarf_p.is_file(): + return dwarf_p + for dsym in sorted(dsyms_dir.glob('*.app.dSYM')): + dwarf_p = dsym / 'Contents' / 'Resources' / 'DWARF' / dsym.name.removesuffix('.app.dSYM') + if dwarf_p.is_file(): + return dwarf_p + return None + + +def audit_ipa( + ipa, + expected_bundle_id=None, + archive_path=None, + audit_json_path=None, + policy_path=None, + symbol_map_path=None, + skip_macho_gates=False, + report_out=None, +): + validate_zip(ipa) + report = { + 'ipa': str(ipa), + 'passed': False, + 'errors': [], + } + try: + with TemporaryDirectory(prefix='ig-export-audit-') as temporary_dir: + unpacked = Path(temporary_dir) + subprocess.run(['ditto', '-x', '-k', str(ipa), str(unpacked)], check=True) + apps = sorted((unpacked / 'Payload').glob('*.app')) + if len(apps) != 1: + raise ValueError(f'IPA 应包含一个主 App,实际找到 {len(apps)} 个') + + app = apps[0] + with (app / 'Info.plist').open('rb') as plist_file: + info = plistlib.load(plist_file) + bundle_id = info['CFBundleIdentifier'] + if expected_bundle_id and bundle_id != expected_bundle_id: + raise ValueError(f'IPA Bundle ID 为 {bundle_id},预期为 {expected_bundle_id}') + + exec_name = info['CFBundleExecutable'] + main_bin = app / exec_name + binaries, callsites = scan(app, unpacked, 'exported') + if exec_name not in binaries: + raise ValueError('IPA 主可执行文件未纳入 Mach-O 扫描') + + counts = dict.fromkeys(EXTERNAL_SYMBOLS | SYSTEM_SYMBOLS, 0) + invalid_images = [] + for relative_path, binary in binaries.items(): + if any(section['cryptid'] for section in binary['slices']): + raise ValueError(f'无法静态检查已加密的 Mach-O:{relative_path}') + for section in binary['slices']: + for symbol, count in section['counts'].items(): + counts[symbol] += count + variants = collect_variant_stubs(app / relative_path) + if variants: + invalid_images.append(f'{relative_path}: {", ".join(variants)}') + + external = sum(counts[symbol] for symbol in EXTERNAL_SYMBOLS) + system = sum(counts[symbol] for symbol in SYSTEM_SYMBOLS) + report['bundle_id'] = bundle_id + report['route2'] = { + 'binaries': len(binaries), + 'external_calls': external, + 'system_calls': system, + 'callsites_total': callsites, + 'variant_stubs': invalid_images, + } + if callsites or invalid_images: + raise ValueError( + f'IPA Route 2 审计失败:外部函数直接调用 {external},系统函数直接调用 {system},' + f'变体符号 {invalid_images}' + ) + + hygiene = _check_static_hygiene(app, main_bin, info) + report['static_hygiene'] = hygiene + if not hygiene['passed']: + failed_keys = [k for k, v in hygiene['checks'].items() if not v] + raise ValueError(f'IPA 静态卫生门禁失败: {failed_keys}') + + policy = _load_policy(policy_path) + obf_audit = None + if audit_json_path and Path(audit_json_path).is_file(): + obf_audit = json.loads(Path(audit_json_path).read_text(encoding='utf-8')) + audit_failures = _check_obf_audit_counts(obf_audit, policy) + report['obf_audit_summary'] = { + k: obf_audit.get(k) + for k in ( + 'total_flattened', 'total_strings_encrypted', 'total_strings_stack_encrypted', + 'total_indirect_calls', 'total_opaque_constants', 'total_arithmetic_rewrites', + 'total_nonlinear_mba', 'total_opaque_zero', 'total_indirect_branches', + 'total_anti_hook_functions', 'total_functions_outlined', + 'total_opaque_field_access', 'total_bb_split_count', 'static_frameworks_obfuscated', + ) + } + if audit_failures: + raise ValueError(f'LLVM 混淆审计计数不满足策略: {"; ".join(audit_failures)}') + + if archive_path and Path(archive_path).is_dir(): + dwarf_bin = _find_dwarf_in_archive(archive_path, app.name, exec_name) + if dwarf_bin is None: + raise ValueError(f'xcarchive 缺少 DWARF 文件: {archive_path}') + ipa_uuids = _uuids_of(main_bin) + dwarf_uuids = _uuids_of(dwarf_bin) + report['dsym_uuid_match'] = { + 'ipa_uuids': sorted(ipa_uuids), + 'dwarf_uuids': sorted(dwarf_uuids), + 'matched': bool(ipa_uuids) and ipa_uuids == dwarf_uuids, + } + if not report['dsym_uuid_match']['matched']: + raise ValueError(f'IPA 与 dSYM UUID 不一致: ipa={ipa_uuids}, dwarf={dwarf_uuids}') + + if obf_audit is not None and not skip_macho_gates: + star_gate = verify_macho_star_cfg.verify_binary_star_cfg( + main_bin, dwarf_bin, obf_audit, require_topology='sparse_switch' + ) + report['star_cfg_gate'] = star_gate + if policy.get('flatten_targets') and star_gate['verified_star_count'] <= 0: + raise ValueError('StarCFGGate verified_star_count 为 0') + + ibr_gate = verify_macho_indirect_branches.verify_binary_indirect_branches( + main_bin, dwarf_bin, obf_audit + ) + report['indirect_branch_gate'] = ibr_gate + if policy.get('indirect_branch_targets') and ibr_gate['verified_ibr_count'] <= 0: + raise ValueError('IndirectBranchGate verified_ibr_count 为 0') + + icall_gate = verify_macho_indirect_calls.analyze_macho_calls( + main_bin, + dwarf_bin, + symbol_map_path=Path(symbol_map_path) if symbol_map_path else None, + require_zero_keybox_direct_bl=bool(policy.get('indirect_call_targets')), + ) + report['indirect_call_gate'] = { + 'text_call_summary': icall_gate['text_call_summary'], + 'keybox_total_direct_call_xrefs': icall_gate['keybox_and_bridge_15_symbols']['total_direct_call_xrefs'], + 'gate_passed': icall_gate['gate_passed'], + 'violations': icall_gate['violations'], + } + if not icall_gate['gate_passed']: + raise ValueError(f"IndirectCallGate failed: {icall_gate['violations']}") + + anti_hook_gate = _verify_binary_anti_hook_prologues(main_bin, dwarf_bin, obf_audit) + report['anti_hook_gate'] = anti_hook_gate + if policy.get('anti_hooking_targets') and anti_hook_gate['verified_anti_hook_count'] <= 0: + raise ValueError('AntiHookGate verified_anti_hook_count 为 0') + + report['passed'] = True + print( + f'IPA 审计通过:{bundle_id},{len(binaries)} 个 Mach-O,' + f'外部函数直接调用 {external},系统函数直接调用 {system},' + f'StaticHygieneGate=PASS' + ) + return report + except Exception as exc: + report['errors'].append(str(exc)) + raise + finally: + if report_out: + out_p = Path(report_out) + out_p.parent.mkdir(parents=True, exist_ok=True) + out_p.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('ipa', type=Path) + parser.add_argument('--bundle-id') + parser.add_argument('--archive', type=Path, default=None) + parser.add_argument('--audit-json', type=Path, default=None) + parser.add_argument('--policy', type=Path, default=None) + parser.add_argument('--symbol-map', type=Path, default=None) + parser.add_argument('--report-out', type=Path, default=None) + parser.add_argument('--skip-macho-gates', action='store_true') + arguments = parser.parse_args() + try: + audit_ipa( + arguments.ipa, + expected_bundle_id=arguments.bundle_id, + archive_path=arguments.archive, + audit_json_path=arguments.audit_json, + policy_path=arguments.policy, + symbol_map_path=arguments.symbol_map, + skip_macho_gates=arguments.skip_macho_gates, + report_out=arguments.report_out, + ) + except (OSError, ValueError, AssertionError, subprocess.CalledProcessError) as error: + parser.exit(1, f'{error}\n') diff --git a/tools/xcode_archive/ig_cc_wrapper.py b/tools/xcode_archive/ig_cc_wrapper.py new file mode 100755 index 0000000..d70af92 --- /dev/null +++ b/tools/xcode_archive/ig_cc_wrapper.py @@ -0,0 +1,413 @@ +#!/usr/bin/env python3 +"""Xcode Release arm64 C/ObjC compiler wrapper (3-stage LLVM bitcode -> opt -> native Mach-O).""" +import hashlib +import json +import os +from pathlib import Path +import shlex +import shutil +import subprocess +import sys +import tempfile + +SCRIPT_DIR = Path(__file__).resolve().parent +TOOLS_DIR = SCRIPT_DIR.parent +TOOLCHAIN_ROOT = TOOLS_DIR.parent + +sys.path.insert(0, str(SCRIPT_DIR)) +sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf')) + +from ig_toolchain_resolver import ( # noqa: E402 + detect_sdk_info, + detect_stock_tool, + detect_xcode_info, + discover_active_app_repo, + file_sha256, + resolve_effective_policy, + resolve_opt, +) + +SOURCE_EXTENSIONS = {'.c', '.m', '.mm', '.cc', '.cpp', '.cxx', '.c++'} + + +def resolve_default_policy(profile='default'): + names = [f'ig_llvm_policy_{profile}.json'] if profile and profile != 'default' else [] + names.append('ig_llvm_policy.json') + for name in names: + for cand in ( + TOOLCHAIN_ROOT / 'config' / name, + TOOLCHAIN_ROOT / 'llvm_obf' / name, + ): + if cand.is_file(): + return str(cand) + return '' + + +def expand_response_files(args): + expanded = [] + for arg in args: + if arg.startswith('@') and len(arg) > 1: + resp = Path(arg[1:]) + if resp.is_file(): + text = resp.read_text(encoding='utf-8', errors='replace') + expanded.extend(shlex.split(text)) + continue + expanded.append(arg) + return expanded + + +def parse_control_token(expanded_args): + """Extract control tuple from `-DIG_OBF_CTL___________[__]=1`.""" + ctl = { + 'mode': 'full', + 'filter': 'all', + 'route2': 'on', + 'all_off': '0', + 'seed': 'm0_seed_20261119_v1', + 'stamp': 'default', + 'policy_profile': 'default', + } + prefix = '-DIG_OBF_CTL_' + for arg in expanded_args: + if arg.startswith(prefix): + body = arg[len(prefix):] + if '=' in body: + body = body.split('=', 1)[0] + parts = body.split('__') + if len(parts) >= 7: + ctl['mode'] = parts[0] or ctl['mode'] + ctl['filter'] = parts[1] or ctl['filter'] + ctl['route2'] = parts[2] or ctl['route2'] + ctl['all_off'] = parts[3] or ctl['all_off'] + ctl['seed'] = parts[4] or ctl['seed'] + ctl['stamp'] = parts[5] or ctl['stamp'] + ctl['policy_profile'] = '__'.join(parts[6:]) or ctl['policy_profile'] + elif len(parts) >= 6: + ctl['mode'] = parts[0] or ctl['mode'] + ctl['filter'] = parts[1] or ctl['filter'] + ctl['route2'] = parts[2] or ctl['route2'] + ctl['all_off'] = parts[3] or ctl['all_off'] + ctl['seed'] = parts[4] or ctl['seed'] + ctl['stamp'] = '__'.join(parts[5:]) or ctl['stamp'] + elif len(parts) >= 1 and parts[0]: + ctl['mode'] = parts[0] + + # Env overrides take precedence if explicitly set + if os.environ.get('IG_DISABLE_LLVM_OBF') == '1': + ctl['mode'] = 'off' + if os.environ.get('IG_ALL_GUARD_OFF') == '1': + ctl['all_off'] = '1' + ctl['mode'] = 'off' + if os.environ.get('IG_OBF_MODE'): + ctl['mode'] = os.environ['IG_OBF_MODE'] + if os.environ.get('IG_LLVM_PASS_FILTER'): + ctl['filter'] = os.environ['IG_LLVM_PASS_FILTER'] + if os.environ.get('IG_RELEASE_SEED'): + ctl['seed'] = os.environ['IG_RELEASE_SEED'] + if os.environ.get('IG_POLICY_PROFILE'): + ctl['policy_profile'] = os.environ['IG_POLICY_PROFILE'] + if ctl['all_off'] == '1': + ctl['mode'] = 'off' + return ctl + + +def parse_compile_metadata(raw_args, expanded_args): + has_c = '-c' in expanded_args + out_path = None + top_out_idx = None + for idx, arg in enumerate(raw_args): + if arg == '-o' and idx + 1 < len(raw_args): + top_out_idx = idx + 1 + out_path = raw_args[idx + 1] + + if out_path is None: + for idx, arg in enumerate(expanded_args): + if arg == '-o' and idx + 1 < len(expanded_args): + out_path = expanded_args[idx + 1] + + lang = None + isysroot = None + target = None + arch = None + min_ver_flag = None + opt_flag = None + debug_flags = [] + extra_codegen = [] + source_path = None + + i = 0 + skip_next_flags = { + '-o', '-I', '-isystem', '-iquote', '-F', '-iframework', '-include', + '-include-pch', '-MT', '-MF', '-MQ', '-D', '-U', '-x', '-target', + '-arch', '-isysroot', '-ivfsoverlay', '-index-store-path', + '-index-unit-output-path', '--serialize-diagnostics', '-dependency-info', + '-pch-output-dir', '-fmodule-map-file', '-Xclang', '-Xpreprocessor', + '-idirafter', '-iprefix', '-iwithprefix', '-iwithprefixbefore', '-B', + } + while i < len(expanded_args): + a = expanded_args[i] + nxt = expanded_args[i + 1] if i + 1 < len(expanded_args) else None + if a == '-x' and nxt is not None: + lang = nxt + i += 2 + continue + if a == '-target' and nxt is not None: + target = nxt + i += 2 + continue + if a.startswith('--target='): + target = a.split('=', 1)[1] + i += 1 + continue + if a == '-arch' and nxt is not None: + arch = nxt + i += 2 + continue + if a == '-isysroot' and nxt is not None: + isysroot = nxt + i += 2 + continue + if a.startswith('-miphoneos-version-min=') or a.startswith('-mllvm'): + if a.startswith('-miphoneos-version-min='): + min_ver_flag = a + elif nxt is not None: + i += 2 + continue + i += 1 + continue + if a in ('-O0', '-O1', '-O2', '-O3', '-Os', '-Oz', '-Ofast'): + opt_flag = a + i += 1 + continue + if a.startswith('-g') and not a.startswith('-gmodules') and a != '-g0': + debug_flags.append(a) + i += 1 + continue + if a in ('-fPIC', '-fpic', '-fno-common', '-fstrict-aliasing', '-fno-strict-aliasing') or ( + a.startswith('-fvisibility=') + or a.startswith('-fstack-protector') + or a.startswith('-ffile-prefix-map=') + or a.startswith('-fdebug-prefix-map=') + or a.startswith('-fembed-bitcode') + ): + extra_codegen.append(a) + i += 1 + continue + if a in skip_next_flags and nxt is not None: + i += 2 + continue + if not a.startswith('-'): + if Path(a).suffix.lower() in SOURCE_EXTENSIONS: + source_path = a + i += 1 + + return { + 'has_c': has_c, + 'out_path': out_path, + 'top_out_idx': top_out_idx, + 'lang': lang, + 'isysroot': isysroot, + 'target': target, + 'arch': arch, + 'min_ver_flag': min_ver_flag, + 'opt_flag': opt_flag or '-Os', + 'debug_flags': debug_flags, + 'extra_codegen': extra_codegen, + 'source_path': source_path, + } + + +def should_passthrough(meta, expanded_args, ctl, policy): + if ctl['all_off'] == '1' or ctl['mode'] == 'off': + return True, f"mode={ctl['mode']} all_off={ctl['all_off']}" + if os.environ.get('PLATFORM_NAME') and os.environ.get('PLATFORM_NAME') != 'iphoneos': + return True, f"platform={os.environ.get('PLATFORM_NAME')}" + if os.environ.get('CONFIGURATION') and os.environ.get('CONFIGURATION') != 'Release': + return True, f"config={os.environ.get('CONFIGURATION')}" + if not meta['has_c'] or not meta['out_path']: + return True, 'not single -c object compile' + if any(f in expanded_args for f in ('-E', '-M', '-MM', '-fsyntax-only', '--analyze', '-emit-llvm', '-S')): + return True, 'preprocess/syntax/emit-llvm/asm mode' + if meta['lang'] and (meta['lang'].endswith('-header') or meta['lang'] in ('ir', 'assembler', 'assembler-with-cpp')): + return True, f"lang={meta['lang']}" + out_suf = Path(meta['out_path']).suffix.lower() + if out_suf in ('.pch', '.gch', '.pcm'): + return True, f'precompiled header output {out_suf}' + if meta['arch'] and meta['arch'] != 'arm64': + return True, f"non-arm64 arch {meta['arch']}" + if meta['target'] and 'arm64' not in meta['target']: + return True, f"non-arm64 target {meta['target']}" + if meta['isysroot'] and 'iPhoneSimulator' in meta['isysroot']: + return True, 'simulator sdk' + src = meta['source_path'] or '' + if not src: + return True, 'no C/ObjC/C++ source path' + for ex in policy.get('exempt_path_substrings', []): + if ex in src: + return True, f'exempt path ({ex})' + return False, '' + + +def build_stage3_flags(meta): + flags = [] + if meta['target']: + flags.extend(['-target', meta['target']]) + else: + flags.extend(['-arch', meta['arch'] or 'arm64']) + if meta['min_ver_flag']: + flags.append(meta['min_ver_flag']) + if meta['isysroot']: + flags.extend(['-isysroot', meta['isysroot']]) + if meta['target'] and meta['min_ver_flag'] and 'ios' not in meta['target']: + flags.append(meta['min_ver_flag']) + flags.append(meta['opt_flag']) + flags.extend(meta['debug_flags']) + flags.extend(meta['extra_codegen']) + flags.extend(['-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c']) + return flags + + +def infer_obj_cache_dir(out_path): + env_dir = os.environ.get('IG_OBF_OBJ_CACHE_DIR') + if env_dir: + return Path(env_dir) + for parent in out_path.parents: + if parent.name in ('Intermediates.noindex', 'Build'): + return parent / 'ig-obf-obj-cache' + return out_path.parent / '.ig-obf-obj-cache' + + +def run_wrapper(argv=None, cxx=False): + raw_args = list(sys.argv[1:] if argv is None else argv) + tool_name = 'clang++' if cxx else 'clang' + real_cc = detect_stock_tool(tool_name) + expanded_args = expand_response_files(raw_args) + ctl = parse_control_token(expanded_args) + + policy_path = os.environ.get('IG_LLVM_POLICY_PATH') or resolve_default_policy(ctl.get('policy_profile', 'default')) + policy = {} + if policy_path and Path(policy_path).is_file(): + policy = json.loads(Path(policy_path).read_text(encoding='utf-8')) + + meta = parse_compile_metadata(raw_args, expanded_args) + passthrough, _ = should_passthrough(meta, expanded_args, ctl, policy) + if passthrough: + if meta.get('out_path'): + stale_audit = Path(str(meta['out_path']) + '.ig-audit.json') + if stale_audit.exists(): + try: + stale_audit.unlink() + except OSError: + pass + os.execv(real_cc, [real_cc, *raw_args]) + return 0 + + require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' or ctl['mode'] in ('full', 'str', 'noop') + tc = resolve_opt(require_obf=require_obf) + opt_path = tc.get('opt_path') + if not opt_path: + sys.stderr.write(f"[IGCC] WARNING: {tc.get('warning', 'opt unavailable')}; falling back to stock {tool_name}\n") + os.execv(real_cc, [real_cc, *raw_args]) + return 0 + + out_path = Path(meta['out_path']) + out_path.parent.mkdir(parents=True, exist_ok=True) + audit_sidecar = Path(str(out_path) + '.ig-audit.json') + + app_repo = discover_active_app_repo([meta.get('source_path') or '']) + eff_policy_path, _eff_policy = resolve_effective_policy(policy_path, app_repo, infer_obj_cache_dir(out_path)) + + stage3_prefix = build_stage3_flags(meta) + xc_build = tc['xcode']['xcode_build'] + sdk_info = detect_sdk_info(meta['isysroot']) if meta['isysroot'] else {'sdk_version': ''} + wrapper_sha = file_sha256(__file__) + policy_sha = file_sha256(eff_policy_path) if eff_policy_path and Path(eff_policy_path).is_file() else 'none' + + with tempfile.TemporaryDirectory(prefix='.ig-cc-', dir=out_path.parent) as td: + work = Path(td) + bc_path = work / 'stage1.bc' + obf_bc_path = work / 'stage2.obf.bc' + + # Stage 1: stock clang -> bitcode (preserving .pch, .d, .dia generation!) + s1_args = list(raw_args) + if meta['top_out_idx'] is not None: + s1_args[meta['top_out_idx']] = str(bc_path) + else: + s1_args.extend(['-o', str(bc_path)]) + s1_args.append('-emit-llvm') + + p1 = subprocess.run([real_cc, *s1_args]) + if p1.returncode != 0: + return p1.returncode + + bc_sha = file_sha256(bc_path) + key_hash = hashlib.sha256( + json.dumps( + { + 'kind': 'cc_v1', + 'bc_sha256': bc_sha, + 'xcode_build': xc_build, + 'sdk_version': sdk_info.get('sdk_version', ''), + 'opt_sha256': tc['opt_sha256'], + 'wrapper_sha256': wrapper_sha, + 'policy_sha256': policy_sha, + 'mode': ctl['mode'], + 'filter': ctl['filter'], + 'seed': ctl['seed'], + 'stamp': ctl['stamp'], + 'stage3': stage3_prefix, + }, + sort_keys=True, + ).encode('utf-8') + ).hexdigest()[:24] + + cache_dir = infer_obj_cache_dir(out_path) / key_hash[:2] + cached_obj = cache_dir / f'{key_hash}.o' + cached_audit = cache_dir / f'{key_hash}.audit.json' + + if cached_obj.is_file() and cached_audit.is_file(): + shutil.copy2(cached_obj, out_path) + shutil.copy2(cached_audit, audit_sidecar) + return 0 + + # Stage 2: standalone opt + opt_cmd = [ + opt_path, + '-passes=ig-obfuscate', + f'--ig-policy={eff_policy_path}', + f"--ig-mode={ctl['mode']}", + f"--ig-pass-filter={ctl['filter']}", + f"--ig-seed={ctl['seed']}", + f"--ig-source-path={meta['source_path'] or ''}", + f'--ig-audit-out={audit_sidecar}', + str(bc_path), + '-o', + str(obf_bc_path), + ] + p2 = subprocess.run(opt_cmd) + if p2.returncode != 0: + return p2.returncode + + # Stage 3: stock clang pure backend lowering (no duplicate middle-end IR passes) + s3_cmd = [real_cc, *stage3_prefix, str(obf_bc_path), '-o', str(out_path)] + p3 = subprocess.run(s3_cmd) + if p3.returncode != 0: + return p3.returncode + + # Atomic cache save (.o + .audit.json sidecar) + try: + cache_dir.mkdir(parents=True, exist_ok=True) + tmp_o = cache_dir / f'.tmp-{key_hash}-{os.getpid()}.o' + tmp_a = cache_dir / f'.tmp-{key_hash}-{os.getpid()}.audit.json' + shutil.copy2(out_path, tmp_o) + shutil.copy2(audit_sidecar, tmp_a) + tmp_o.replace(cached_obj) + tmp_a.replace(cached_audit) + except OSError: + pass + + return 0 + + +if __name__ == '__main__': + raise SystemExit(run_wrapper(cxx=False)) diff --git a/tools/xcode_archive/ig_cxx_wrapper.py b/tools/xcode_archive/ig_cxx_wrapper.py new file mode 100755 index 0000000..37d1644 --- /dev/null +++ b/tools/xcode_archive/ig_cxx_wrapper.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +"""Xcode Release arm64 C++/ObjC++ compiler wrapper.""" +from pathlib import Path +import sys + +SCRIPT_DIR = Path(__file__).resolve().parent +sys.path.insert(0, str(SCRIPT_DIR)) + +from ig_cc_wrapper import run_wrapper # noqa: E402 + +if __name__ == '__main__': + raise SystemExit(run_wrapper(cxx=True)) diff --git a/tools/xcode_archive/ig_guard_frameworks_phase.py b/tools/xcode_archive/ig_guard_frameworks_phase.py new file mode 100755 index 0000000..ddad122 --- /dev/null +++ b/tools/xcode_archive/ig_guard_frameworks_phase.py @@ -0,0 +1,599 @@ +#!/usr/bin/env python3 +"""Xcode Release arm64 Run Script phase for IGArchiveGuard, dynamic framework rebinding, and whole-app audit.""" +import hashlib +import json +import os +from pathlib import Path +import plistlib +import shutil +import struct +import subprocess +import sys +import tempfile + +SCRIPT_DIR = Path(__file__).resolve().parent +TOOLS_DIR = SCRIPT_DIR.parent +TOOLCHAIN_ROOT = TOOLS_DIR.parent + +sys.path.insert(0, str(SCRIPT_DIR)) +sys.path.insert(0, str(TOOLS_DIR / 'macho_guard')) +sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf')) + +from batch import arm64_slices, iter_macho_files # noqa: E402 +from machox import Macho, LC_DYLD_CHAINED_FIXUPS # noqa: E402 +from redirect_framework_imports import ( # noqa: E402 + DEPENDENCY, + detect_chained_target_mapping, + rewrite as rewrite_chained, +) +from redirect_legacy_imports import ( # noqa: E402 + detect_legacy_target_mapping, + rewrite as rewrite_legacy, +) +from route2_archive_common import ( # noqa: E402 + EXPECTED_ARCHIVE_EXPORTS, + EXTERNAL_SYMBOLS, + FORBIDDEN_SYMBOLS, + GUARD_BUNDLE_ID, + GUARD_FRAMEWORK_NAME, + SYSTEM_SYMBOLS, + collect_variant_stubs, + file_sha256, + resolve_app_repo, + resolve_defender_dir, +) +from verify_baseline import inspect_binary, scan # noqa: E402 +import ig_toolchain_resolver # noqa: E402 + +APPSTORE_PLIST_KEYS = ( + 'DTCompiler', 'DTPlatformBuild', 'DTPlatformName', 'DTPlatformVersion', + 'DTSDKBuild', 'DTSDKName', 'DTXcode', 'DTXcodeBuild', 'UIDeviceFamily', +) +DYLIB_LOAD_CMDS = {0x0c, 0x18, 0x1f, 0x80000018, 0x8000001f} + + +def run_cmd(*args, env=None, cwd=None): + return subprocess.check_output(list(map(str, args)), env=env, cwd=cwd, text=True) + + +def macho_load_dylibs(raw): + m = Macho(raw) + libs = [] + for cmd, cmdsize, off in m.cmds: + if cmd in DYLIB_LOAD_CMDS and cmdsize >= 24: + name_off, = struct.unpack_from(' 0: + raise ValueError(f'{name}: has direct calls but empty mapping: {before_info}') + + sign_status = 'preserved' + if thinned: + codesig = fw_dir / '_CodeSignature' + if codesig.exists(): + shutil.rmtree(codesig) + sign_status = codesign_framework(fw_dir, preserve_metadata=True) + return dict( + framework=name, + mode='clean_no_change' if not thinned else 'thinned_clean', + modified=thinned, + thinned=thinned, + before_total=0, + after_total=0, + symbols_redirected=0, + sign_status=sign_status, + ) + + +def run_phase(app_dir, main_bin, audit_dir, app_repo, defender_dir, dsym_folder=None, debug_info_format=''): + frameworks_dir = app_dir / 'Frameworks' + frameworks_dir.mkdir(parents=True, exist_ok=True) + + guard_report = build_archive_guard( + defender_dir, + frameworks_dir / f'{GUARD_FRAMEWORK_NAME}.framework', + app_plist_path=app_dir / 'Info.plist', + dsym_folder=dsym_folder, + debug_info_format=debug_info_format, + app_repo=app_repo, + ) + + orig_backup_dir = audit_dir / 'orig_frameworks' + fw_reports = [] + for fw_dir in sorted(frameworks_dir.glob('*.framework')): + if fw_dir.name == f'{GUARD_FRAMEWORK_NAME}.framework': + continue + fw_reports.append(process_framework(fw_dir, orig_backup_dir=orig_backup_dir)) + + # Incremental builds may already have a stale RDKnownImages.plist before Generate Image Whitelist runs. + whitelist_plist = app_dir / 'RDKnownImages.plist' + if whitelist_plist.exists(): + wl_script = app_repo / 'AutoPacking/obfuscation/generate_image_whitelist.py' + if wl_script.is_file(): + env = dict(os.environ) + env['TARGET_BUILD_DIR'] = str(app_dir.parent) + env['WRAPPER_NAME'] = app_dir.name + env.setdefault('EXECUTABLE_PATH', str(main_bin.relative_to(app_dir.parent))) + subprocess.run([sys.executable, str(wl_script)], env=env, cwd=app_repo, check=True) + + audit_dir.mkdir(parents=True, exist_ok=True) + (audit_dir / 'route2-frameworks.json').write_text(json.dumps(fw_reports, indent=2) + '\n') + + binaries, callsite_total = scan(app_dir, audit_dir, 'route2') + combined_counts = {} + for info in binaries.values(): + for sl in info['slices']: + for sym, cnt in sl['counts'].items(): + combined_counts[sym] = combined_counts.get(sym, 0) + cnt + + external_call_total = sum(combined_counts.get(s, 0) for s in EXTERNAL_SYMBOLS) + system_call_total = sum(combined_counts.get(s, 0) for s in SYSTEM_SYMBOLS) + if external_call_total != 0 or system_call_total != 0 or callsite_total != 0: + raise RuntimeError( + f'[IGRoute2] Non-zero residual callsites across {app_dir.name}: ' + f'external={external_call_total}, system={system_call_total}, total={callsite_total}, counts={combined_counts}' + ) + + variant_stubs = [] + for mpath in sorted(map(Path, iter_macho_files(str(app_dir)))): + found = collect_variant_stubs(mpath) + if found: + variant_stubs.append((str(mpath.relative_to(app_dir)), found)) + if variant_stubs: + raise RuntimeError(f'[IGRoute2] Found Darwin-variant stubs in {app_dir.name}: {variant_stubs}') + + main_undef_out = run_cmd('xcrun', 'nm', '-u', main_bin) + main_undef = {line.split()[-1] for line in main_undef_out.splitlines() if line.split()} + forbidden_main_undef = sorted(main_undef & FORBIDDEN_SYMBOLS) + forbidden_variant_undef = sorted(u for u in main_undef if any(u.startswith(f + '$') for f in FORBIDDEN_SYMBOLS)) + if forbidden_variant_undef: + raise RuntimeError( + f'[IGRoute2] Main binary {main_bin.name} still has Darwin-variant undefined imports: ' + f'{forbidden_variant_undef}' + ) + + summary = dict( + app=app_dir.name, + binaries=len(binaries), + external_call_total=external_call_total, + system_call_total=system_call_total, + direct_calls=combined_counts, + main_binary_forbidden_undef=forbidden_main_undef, + ig_archive_guard=guard_report, + frameworks_total=len(fw_reports), + frameworks_rewritten=sum(1 for r in fw_reports if r['symbols_redirected'] > 0), + frameworks_already_guarded=sum(1 for r in fw_reports if r['mode'] == 'already_guarded'), + frameworks_thinned=sum(1 for r in fw_reports if r['thinned']), + ) + (audit_dir / 'route2-summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n') + return summary + + +def restore_route2_off(app_dir, main_bin, audit_dir, app_repo, dsym_folder=None): + """Remove RDCoreIO.framework (and legacy IGArchiveGuard.framework) & restore pre-Route2 backups.""" + frameworks_dir = app_dir / 'Frameworks' + removed_guard = False + for fw_name in (GUARD_FRAMEWORK_NAME, 'IGArchiveGuard'): + guard_fw = frameworks_dir / f'{fw_name}.framework' + if guard_fw.exists(): + shutil.rmtree(guard_fw) + removed_guard = True + if dsym_folder: + guard_dsym = Path(dsym_folder) / f'{fw_name}.framework.dSYM' + if guard_dsym.exists(): + shutil.rmtree(guard_dsym) + + restored = [] + orig_backup_dir = audit_dir / 'orig_frameworks' + if frameworks_dir.is_dir() and orig_backup_dir.is_dir(): + for fw_dir in sorted(frameworks_dir.glob('*.framework')): + name = fw_dir.stem + binary = fw_dir / name + backup = orig_backup_dir / f'{name}.orig' + if binary.is_file() and backup.is_file(): + if DEPENDENCY in macho_load_dylibs(binary.read_bytes()): + shutil.copy2(backup, binary) + codesig = fw_dir / '_CodeSignature' + if codesig.exists(): + shutil.rmtree(codesig) + codesign_framework(fw_dir, preserve_metadata=True) + restored.append(name) + + whitelist_plist = app_dir / 'RDKnownImages.plist' + if (removed_guard or restored) and whitelist_plist.exists(): + wl_script = app_repo / 'AutoPacking/obfuscation/generate_image_whitelist.py' + if wl_script.is_file(): + env = dict(os.environ) + env['TARGET_BUILD_DIR'] = str(app_dir.parent) + env['WRAPPER_NAME'] = app_dir.name + env.setdefault('EXECUTABLE_PATH', str(main_bin.relative_to(app_dir.parent))) + subprocess.run([sys.executable, str(wl_script)], env=env, cwd=app_repo, check=True) + return removed_guard, restored + + +def main(): + off_reason = None + if os.environ.get('IG_DISABLE_ROUTE2_ARCHIVE') == '1': + off_reason = 'IG_DISABLE_ROUTE2_ARCHIVE=1' + elif os.environ.get('IG_ALL_GUARD_OFF') == '1': + off_reason = 'IG_ALL_GUARD_OFF=1' + elif os.environ.get('IG_ROUTE2_MODE') == 'off': + off_reason = 'IG_ROUTE2_MODE=off' + + config = os.environ.get('CONFIGURATION', '') + platform = os.environ.get('PLATFORM_NAME', '') + if config != 'Release' or platform != 'iphoneos': + print(f'[IGRoute2] frameworks phase skipped: CONFIGURATION={config} PLATFORM_NAME={platform}') + return 0 + + target_build_dir = Path(os.environ['TARGET_BUILD_DIR']) + wrapper_name = os.environ['WRAPPER_NAME'] + app_dir = target_build_dir / wrapper_name + exec_rel = os.environ.get('EXECUTABLE_PATH') or f'{wrapper_name}/{Path(wrapper_name).stem}' + main_bin = target_build_dir / exec_rel + target_temp_dir = Path(os.environ.get('TARGET_TEMP_DIR') or str(target_build_dir)) + audit_dir = target_temp_dir / 'ig-route2-audit' + app_repo = resolve_app_repo(TOOLCHAIN_ROOT) + + if off_reason: + removed_guard, restored = restore_route2_off( + app_dir, main_bin, audit_dir, app_repo, dsym_folder=os.environ.get('DWARF_DSYM_FOLDER_PATH') + ) + print( + f'[IGRoute2] frameworks phase off ({off_reason}): ' + f'removed_guard={removed_guard}, restored={len(restored)}' + ) + return 0 + + defender_dir = resolve_defender_dir(TOOLCHAIN_ROOT, app_repo) + summary = run_phase( + app_dir=app_dir, + main_bin=main_bin, + audit_dir=audit_dir, + app_repo=app_repo, + defender_dir=defender_dir, + dsym_folder=os.environ.get('DWARF_DSYM_FOLDER_PATH'), + debug_info_format=os.environ.get('DEBUG_INFORMATION_FORMAT', ''), + ) + print( + f'[IGRoute2] frameworks audit OK for {app_dir.name}: ' + f'binaries={summary["binaries"]}, rewritten={summary["frameworks_rewritten"]}, ' + f'already_guarded={summary["frameworks_already_guarded"]}, external=0, system=0' + ) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/xcode_archive/ig_ld_wrapper.py b/tools/xcode_archive/ig_ld_wrapper.py new file mode 100755 index 0000000..e801d16 --- /dev/null +++ b/tools/xcode_archive/ig_ld_wrapper.py @@ -0,0 +1,1452 @@ +#!/usr/bin/env python3 +"""Xcode Release arm64 linker wrapper (--ld-path) for Swift bitcode opt lowering, Route 2 SDKs, and audit.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +import fcntl +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +import tempfile + +SCRIPT_DIR = Path(__file__).resolve().parent +TOOLS_DIR = SCRIPT_DIR.parent +TOOLCHAIN_ROOT = TOOLS_DIR.parent + +sys.path.insert(0, str(SCRIPT_DIR)) +sys.path.insert(0, str(TOOLS_DIR / 'static_sdk_redirect')) +sys.path.insert(0, str(TOOLS_DIR / 'macho_guard')) +sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf')) + +from attribute_callsites import attribute # noqa: E402 +from ig_toolchain_resolver import ( # noqa: E402 + detect_sdk_info, + detect_stock_tool, + detect_xcode_info, + discover_active_app_repo, + file_sha256, + resolve_effective_policy, + resolve_opt, +) +from machox import Macho # noqa: E402 +from prepare_route2_sdks import ( # noqa: E402 + MAPPING_PATH, + PROFILE_PATH, + STATIC_INPUTS, + digest, + run_xcrun, + thin_arm64, + verify_no_target_imports, +) +from redirect_bitcode_members import rewrite as rewrite_bitcode # noqa: E402 +from redirect_to_runtime import defined_symbols, link_symbols, patch # noqa: E402 +from route2_archive_common import ( # noqa: E402 + EXPECTED_DISPATCH_SYMBOLS, + collect_variant_stubs, + resolve_app_repo, +) +from verify_baseline import inspect_binary # noqa: E402 + +PASSTHROUGH_FLAGS = {'-r', '-dylib', '-bundle', '-preload'} +BRIDGE_SOURCE_REL = 'readoor/3.0/Base/Security/IGDefender/call_bridge/IGThreadID.c' +BITCODE_MAGICS = (b'\xde\xc0\x17\x0b', b'BC\xc0\xde') +LC_BUILD_VERSION = 0x32 +PLATFORM_IOS = 2 + + +def strip_ig_stamp(args): + """Remove `-ig_stamp ` tokens injected via `-Wl,-ig_stamp,...` and return parsed control tuple.""" + clean = [] + stamp_val = '' + i = 0 + while i < len(args): + arg = args[i] + if arg == '-ig_stamp' and i + 1 < len(args): + stamp_val = args[i + 1] + i += 2 + continue + if arg.startswith('-ig_stamp='): + stamp_val = arg.split('=', 1)[1] + i += 1 + continue + clean.append(arg) + i += 1 + + ctl = { + 'mode': 'off', + 'filter': 'all', + 'route2': 'on', + 'all_off': '0', + 'seed': 'm0_seed_20261119_v1', + 'stamp': 'default', + 'policy_profile': 'default', + } + if stamp_val.startswith('ctl_'): + parts = stamp_val[len('ctl_'):].split('__') + if len(parts) >= 7: + ctl['mode'] = parts[0] or ctl['mode'] + ctl['filter'] = parts[1] or ctl['filter'] + ctl['route2'] = parts[2] or ctl['route2'] + ctl['all_off'] = parts[3] or ctl['all_off'] + ctl['seed'] = parts[4] or ctl['seed'] + ctl['stamp'] = parts[5] or ctl['stamp'] + ctl['policy_profile'] = '__'.join(parts[6:]) or ctl['policy_profile'] + elif len(parts) >= 6: + ctl['mode'] = parts[0] or ctl['mode'] + ctl['filter'] = parts[1] or ctl['filter'] + ctl['route2'] = parts[2] or ctl['route2'] + ctl['all_off'] = parts[3] or ctl['all_off'] + ctl['seed'] = parts[4] or ctl['seed'] + ctl['stamp'] = '__'.join(parts[5:]) or ctl['stamp'] + + if os.environ.get('IG_DISABLE_LLVM_OBF') == '1': + ctl['mode'] = 'off' + if os.environ.get('IG_DISABLE_ROUTE2_ARCHIVE') == '1': + ctl['route2'] = 'off' + if os.environ.get('IG_ALL_GUARD_OFF') == '1': + ctl['all_off'] = '1' + ctl['mode'] = 'off' + ctl['route2'] = 'off' + if os.environ.get('IG_OBF_MODE'): + ctl['mode'] = os.environ['IG_OBF_MODE'] + if os.environ.get('IG_LLVM_PASS_FILTER'): + ctl['filter'] = os.environ['IG_LLVM_PASS_FILTER'] + if os.environ.get('IG_ROUTE2_MODE'): + ctl['route2'] = os.environ['IG_ROUTE2_MODE'] + if os.environ.get('IG_RELEASE_SEED'): + ctl['seed'] = os.environ['IG_RELEASE_SEED'] + if os.environ.get('IG_POLICY_PROFILE'): + ctl['policy_profile'] = os.environ['IG_POLICY_PROFILE'] + if ctl['all_off'] == '1': + ctl['mode'] = 'off' + ctl['route2'] = 'off' + return clean, ctl + + +def resolve_default_policy(profile='default'): + names = [f'ig_llvm_policy_{profile}.json'] if profile and profile != 'default' else [] + names.append('ig_llvm_policy.json') + for name in names: + for cand in ( + TOOLCHAIN_ROOT / 'config' / name, + TOOLCHAIN_ROOT / 'llvm_obf' / name, + ): + if cand.is_file(): + return str(cand) + return '' + + +def resolve_real_ld(args): + """Locate the real Apple ld without hardcoding /Applications/Xcode.app paths.""" + for i, arg in enumerate(args): + if arg == '-lto_library' and i + 1 < len(args): + candidate = Path(args[i + 1]).resolve().parents[1] / 'bin/ld' + if candidate.is_file() and os.access(candidate, os.X_OK): + return str(candidate) + resolved = subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '-f', 'ld'], text=True).strip() + if resolved and Path(resolved).is_file(): + return resolved + fallback = shutil.which('ld') + if fallback: + return fallback + raise FileNotFoundError('Unable to locate real ld binary via -lto_library or xcrun') + + +def resolve_bridge_source(app_repo): + in_repo = app_repo / BRIDGE_SOURCE_REL + if in_repo.is_file(): + return in_repo + in_toolchain = TOOLCHAIN_ROOT / 'defender/call_bridge/IGThreadID.c' + if in_toolchain.is_file(): + return in_toolchain + raise FileNotFoundError(f'Missing IGThreadID.c at {in_repo} or {in_toolchain}') + + +def parse_flag_value(args, flag): + """Return last value for an exact `-flag val` pair (ignoring `-object_path_lto` etc.).""" + found = None + i = 0 + while i < len(args): + if args[i] == flag and i + 1 < len(args): + found = args[i + 1] + i += 2 + continue + i += 1 + return found + + +def infer_cache_root(output_path, linkmap_arg): + """Place shared SDK cache in IG_SDK_CACHE_DIR, Intermediates.noindex, or OBJROOT.""" + env_cache = os.environ.get('IG_SDK_CACHE_DIR') + if env_cache: + return Path(env_cache) + probe = Path(linkmap_arg) if linkmap_arg else output_path + for target_dir in ('Intermediates.noindex', 'Build'): + for parent in probe.parents: + if parent.name == target_dir: + return parent / 'ig-route2-sdk-cache' + env_objroot = os.environ.get('OBJROOT') + if env_objroot: + return Path(env_objroot) / 'ig-route2-sdk-cache' + return output_path.parent / 'ig-route2-sdk-cache' + + +def infer_obj_cache_dir(output_path, linkmap_arg): + env_dir = os.environ.get('IG_OBF_OBJ_CACHE_DIR') + if env_dir: + return Path(env_dir) + probe = Path(linkmap_arg) if linkmap_arg else output_path + for parent in probe.parents: + if parent.name in ('Intermediates.noindex', 'Build'): + return parent / 'ig-obf-obj-cache' + return output_path.parent / '.ig-obf-obj-cache' + + +def compute_sdk_fingerprint(app_repo, bridge_src): + """Hash Route 2 inputs, scripts, Xcode build, and SDK version for cache invalidation.""" + h = hashlib.sha256() + xc = detect_xcode_info() + sdk = detect_sdk_info() + h.update(f"{xc.get('xcode_build', '')}:{sdk.get('sdk_version', '')}:".encode('utf-8')) + tool_files = [ + Path(__file__), + MAPPING_PATH, + PROFILE_PATH, + bridge_src, + TOOLS_DIR / 'static_sdk_redirect/redirect_symbols.py', + TOOLS_DIR / 'static_sdk_redirect/redirect_bitcode_members.py', + TOOLS_DIR / 'static_sdk_redirect/prepare_route2_sdks.py', + ] + for path in tool_files: + h.update(str(path.name).encode()) + h.update(digest(path).encode()) + for entry in STATIC_INPUTS: + src = app_repo / entry['relative'] + h.update(entry['name'].encode()) + h.update(digest(src).encode() if src.is_file() else b'missing') + return h.hexdigest()[:20] + + +def prepare_entry_in_stage(entry, app_repo, base_mapping, work, stage): + source = (app_repo / entry['relative']).resolve() + if not source.is_file(): + return None + thin = work / f"{entry['name']}.thin.a" + thin_arm64(source, thin) + + dest = (stage / entry['dest']).resolve() + dest.parent.mkdir(parents=True, exist_ok=True) + if 'framework_dir' in entry: + fw_src = app_repo / entry['framework_dir'] + for sub in ('Headers', 'Modules'): + if (fw_src / sub).exists(): + shutil.copytree(fw_src / sub, dest.parent / sub, dirs_exist_ok=True) + if (fw_src / 'Info.plist').exists(): + shutil.copy2(fw_src / 'Info.plist', dest.parent / 'Info.plist') + + mapping = dict(base_mapping) + mapping.update(entry.get('extra_mapping', {})) + extra_passes = entry.get('extra_passes', []) + if extra_passes: + pass0 = work / f"{entry['name']}.pass0.a" + rewrite_bitcode(thin, pass0, mapping) + cur_input = pass0 + for idx, ex_map in enumerate(extra_passes): + is_last = (idx == len(extra_passes) - 1) + out_target = dest if is_last else (work / f"{entry['name']}.pass{idx + 1}.a") + rewrite_bitcode(cur_input, out_target, ex_map, allow_darwin_extsn=True) + cur_input = out_target + else: + rewrite_bitcode(thin, dest, mapping) + + verify_no_target_imports(dest, set(mapping) | {'_fopen$DARWIN_EXTSN'}) + return str(source) + + +def ensure_prepared_stage(cache_root, app_repo, bridge_src): + """Build or reuse process-locked cached static SDK candidates & IGThreadID.o.""" + fingerprint = compute_sdk_fingerprint(app_repo, bridge_src) + stage_dir = cache_root / fingerprint + marker = stage_dir / '.ready.json' + if marker.is_file(): + return stage_dir + + cache_root.mkdir(parents=True, exist_ok=True) + lock_path = cache_root / '.prepare.lock' + with lock_path.open('w') as lock_file: + fcntl.flock(lock_file, fcntl.LOCK_EX) + if marker.is_file(): + return stage_dir + + base_mapping = json.loads(MAPPING_PATH.read_text(encoding='utf-8')) + with tempfile.TemporaryDirectory(prefix=f'.tmp-{fingerprint}-', dir=cache_root) as tmp: + work = Path(tmp) + stage = work / 'stage' + stage.mkdir() + + available = {} + for entry in STATIC_INPUTS: + src_path = prepare_entry_in_stage(entry, app_repo, base_mapping, work, stage) + if src_path: + available[entry['name']] = dict(source=src_path, dest=entry['dest']) + + bridge_obj = stage / 'IGThreadID.o' + run_xcrun( + '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', + '-miphoneos-version-min=15.0', '-O2', '-Wall', '-Wextra', '-Werror', + '-c', bridge_src, '-o', bridge_obj, + ) + + if stage_dir.exists(): + shutil.rmtree(stage_dir) + stage.rename(stage_dir) + marker.write_text(json.dumps(dict(fingerprint=fingerprint, entries=available), indent=2) + '\n') + return stage_dir + + +def is_bitcode_wrapper(path): + try: + with Path(path).open('rb') as f: + return f.read(4) in BITCODE_MAGICS + except OSError: + return False + + +def verify_macho_object_platform(obj_path): + data = Path(obj_path).read_bytes() + if len(data) < 32: + raise RuntimeError(f'[IGObf] Truncated object file: {obj_path}') + magic, cputype, _cpusubtype, filetype, ncmds, _sizeofcmds, _flags, _reserved = struct.unpack_from('<8I', data, 0) + if magic != 0xFEEDFACF or cputype != 0x0100000C or filetype != 1: + raise RuntimeError(f'[IGObf] Converted object is not arm64 Mach-O MH_OBJECT (magic=0x{magic:x}, filetype={filetype}): {obj_path}') + off = 32 + for _ in range(ncmds): + cmd, cmdsize = struct.unpack_from('= 24: + plat, minos, sdk_ver, _ = struct.unpack_from('> 16) & 0xff}.{(minos >> 8) & 0xff}', + 'sdk': f'{(sdk_ver >> 16) & 0xff}.{(sdk_ver >> 8) & 0xff}', + } + off += cmdsize + return {'platform': 'missing_build_version'} + + +def extract_platform_flags(args): + """Inherit target triple & SDK path from ld command line.""" + min_os = os.environ.get('IPHONEOS_DEPLOYMENT_TARGET', '15.0') + syslibroot = None + i = 0 + while i < len(args): + if args[i] == '-platform_version' and i + 3 < len(args): + plat_name = args[i + 1] + raw_min = args[i + 2] + if plat_name in ('ios', '2'): + parts = raw_min.split('.') + min_os = f'{parts[0]}.{parts[1]}' if len(parts) >= 2 else raw_min + i += 4 + continue + if args[i] == '-syslibroot' and i + 1 < len(args): + syslibroot = args[i + 1] + i += 2 + continue + i += 1 + if not syslibroot: + syslibroot = detect_sdk_info().get('sdk_path') + return f'arm64-apple-ios{min_os}', syslibroot + + +def load_target_swift_output_map(filelist_path): + """Map normalized llvm-bc/object path -> Swift source path from OutputFileMap.json next to LinkFileList.""" + mapping = {} + parent = filelist_path.parent + ofms = sorted(parent.glob('*-OutputFileMap.json')) + sorted(parent.glob('OutputFileMap.json')) + for ofm_path in ofms: + try: + raw = json.loads(ofm_path.read_text(encoding='utf-8')) + except Exception: + continue + for src_key, entry in raw.items(): + if not isinstance(entry, dict): + continue + target_label = src_key if src_key.endswith('.swift') else ('' if src_key == '' else None) + if not target_label: + continue + for field in ('llvm-bc', 'object'): + out_file = entry.get(field) + if not out_file: + continue + norm_obj = os.path.normpath(out_file) + if norm_obj not in mapping or target_label != '': + mapping[norm_obj] = target_label + return mapping + + +def filelist_contains_bitcode(paths): + for p in paths: + if p and Path(p).is_file() and is_bitcode_wrapper(p): + return True + return False + + +def args_contain_remaining_bitcode(args, replaced_filelist_entries): + if filelist_contains_bitcode(replaced_filelist_entries): + return True + i = 0 + while i < len(args): + a = args[i] + if a in ('-o', '-map', '-filelist', '-object_path_lto', '-cache_path_lto', '-lto_library', '-syslibroot'): + i += 2 + continue + if not a.startswith('-') and a.endswith(('.o', '.bc')) and Path(a).is_file(): + if is_bitcode_wrapper(a): + return True + i += 1 + return False + + +def strip_lto_link_flags(args): + """Strip ThinLTO linker flags only when zero bitcode objects remain in link inputs.""" + out = [] + i = 0 + while i < len(args): + a = args[i] + if a in ('-cache_path_lto', '-object_path_lto') and i + 1 < len(args): + i += 2 + continue + if a.startswith('-flto') or a.startswith('-cache_path_lto=') or a.startswith('-object_path_lto='): + i += 1 + continue + out.append(a) + i += 1 + return out + + +def _lower_single_bitcode_object( + bc_path, + out_o, + out_a, + src_hint, + swift_mod_name, + backend_flags, + tc, + clang_bin, + sdk_info, + wrapper_sha, + policy_sha, + pipeline, + ctl, + policy_path, + cache_root, + cache_kind='swift_v1', + extra_cache_fields=None, + tmp_parent=None, +): + """Run opt + clang lowering on a single LLVM bitcode object with content-addressed caching.""" + bc_p = Path(bc_path) + out_o = Path(out_o) + out_a = Path(out_a) + bc_sha = file_sha256(bc_p) + xc_build = tc['xcode']['xcode_build'] + cache_payload = { + 'kind': cache_kind, + 'bc_sha256': bc_sha, + 'xcode_build': xc_build, + 'sdk_version': sdk_info.get('sdk_version', ''), + 'opt_sha256': tc['opt_sha256'], + 'wrapper_sha256': wrapper_sha, + 'policy_sha256': policy_sha, + 'pipeline': pipeline, + 'mode': ctl['mode'], + 'filter': ctl['filter'], + 'seed': ctl['seed'], + 'stamp': ctl['stamp'], + 'swift_module': swift_mod_name, + 'backend_flags': backend_flags, + } + if extra_cache_fields: + cache_payload.update(extra_cache_fields) + key_hash = hashlib.sha256(json.dumps(cache_payload, sort_keys=True).encode('utf-8')).hexdigest()[:24] + + c_dir = cache_root / key_hash[:2] + cached_o = c_dir / f'{key_hash}.o' + cached_a = c_dir / f'{key_hash}.audit.json' + + if cached_o.is_file() and cached_a.is_file(): + shutil.copy2(cached_o, out_o) + shutil.copy2(cached_a, out_a) + else: + opt_path = tc['opt_path'] + tmp_base = Path(tmp_parent) if tmp_parent else out_o.parent + with tempfile.TemporaryDirectory(prefix='.ig-sw-', dir=tmp_base) as swtmp: + obf_bc = Path(swtmp) / f'{bc_p.stem}.obf.bc' + p_opt = subprocess.run([ + opt_path, + f'-passes={pipeline}', + f'--ig-policy={policy_path}', + f"--ig-mode={ctl['mode']}", + f"--ig-pass-filter={ctl['filter']}", + f"--ig-seed={ctl['seed']}", + f'--ig-source-path={src_hint}', + f'--ig-swift-module={swift_mod_name}', + f'--ig-audit-out={out_a}', + str(bc_p), + '-o', str(obf_bc), + ], capture_output=True, text=True) + if p_opt.returncode != 0: + raise RuntimeError( + f'[IGObf] opt failed on Swift object {bc_p.name}: {p_opt.stderr.strip()}' + ) + p_cc = subprocess.run( + [clang_bin, *backend_flags, str(obf_bc), '-o', str(out_o)], + capture_output=True, + text=True, + ) + if p_cc.returncode != 0: + raise RuntimeError( + f'[IGObf] clang IR lowering failed on {bc_p.name}: {p_cc.stderr.strip()}' + ) + verify_macho_object_platform(out_o) + try: + c_dir.mkdir(parents=True, exist_ok=True) + tmp_o = c_dir / f'.tmp-{key_hash}-{os.getpid()}.o' + tmp_a = c_dir / f'.tmp-{key_hash}-{os.getpid()}.audit.json' + shutil.copy2(out_o, tmp_o) + shutil.copy2(out_a, tmp_a) + tmp_o.replace(cached_o) + tmp_a.replace(cached_a) + except OSError: + pass + + return json.loads(out_a.read_text(encoding='utf-8')) + + +def _parse_bsd_ar_members(archive_path): + """Parse BSD/Mach-O static archive members; return None if not an ar archive.""" + arch_p = Path(archive_path) + data = arch_p.read_bytes() + if len(data) >= 8 and data[:4] in (b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'): + with tempfile.NamedTemporaryFile(dir=arch_p.parent, suffix='.thin.a', delete=False) as tf: + thin_p = Path(tf.name) + try: + subprocess.run(['xcrun', 'lipo', str(arch_p), '-thin', 'arm64', '-output', str(thin_p)], check=True) + data = thin_p.read_bytes() + finally: + if thin_p.exists(): + thin_p.unlink() + if not data.startswith(b'!\n'): + return None + + members = [] + pos = 8 + total = len(data) + while pos + 60 <= total: + hdr = data[pos:pos + 60] + if hdr[58:60] != b'`\n': + raise RuntimeError(f'[IGObf] Corrupt ar member header in {arch_p} at offset {pos}') + raw_name = hdr[0:16].decode('latin1') + member_size = int(hdr[48:58].decode('ascii', errors='strict').strip()) + pos += 60 + payload = data[pos:pos + member_size] + pos += member_size + if member_size & 1: + pos += 1 + name = raw_name.rstrip(' ') + if name.startswith('#1/'): + name_len = int(name[3:]) + ext_name = payload[:name_len].rstrip(b'\x00').decode('utf-8', errors='replace') + payload = payload[name_len:] + name = ext_name + else: + name = name.rstrip('/') + if name.startswith('__.SYMDEF') or name in ('/', '//'): + continue + members.append((name, payload)) + return members + + +def _build_static_framework_source_map(fw_name, app_repo, anchor_path): + """Map object stem / basename -> repo-relative source path for a static Pod framework.""" + stem_map = {} + vendor_dir = app_repo / 'Vendor' / fw_name + if vendor_dir.is_dir(): + for src in sorted(vendor_dir.rglob('*')): + if src.is_file() and src.suffix in ('.swift', '.m', '.mm', '.c', '.cc', '.cpp'): + rel = str(src.relative_to(app_repo)).replace('\\', '/') + stem_map.setdefault(src.stem, rel) + stem_map.setdefault(src.name, rel) + + # Also check sibling Pods Intermediates OutputFileMap.json if available. + search_bases = [] + if anchor_path: + for parent in Path(anchor_path).parents: + if parent.name in ('Intermediates.noindex', 'ArchiveIntermediates', 'Build'): + search_bases.append(parent) + seen_ofm = set() + for base in search_bases: + if not base.is_dir(): + continue + for ofm_path in base.glob(f'**/{fw_name}.build/**/*-OutputFileMap.json'): + if ofm_path in seen_ofm: + continue + seen_ofm.add(ofm_path) + try: + raw = json.loads(ofm_path.read_text(encoding='utf-8')) + except Exception: + continue + for src_key, entry in raw.items(): + if not isinstance(entry, dict) or not src_key: + continue + norm_src = src_key.replace('\\', '/') + if app_repo: + repo_prefix = str(app_repo).replace('\\', '/').rstrip('/') + '/' + if norm_src.startswith(repo_prefix): + norm_src = norm_src[len(repo_prefix):] + for field in ('llvm-bc', 'object'): + out_file = entry.get(field) + if out_file: + stem = Path(out_file).stem + stem_map[stem] = norm_src + stem_map[Path(out_file).name] = norm_src + return stem_map + + +def convert_swift_objects(args, output_path, linkmap_arg, ctl, policy_path, policy, app_repo): + """Identify Target Swift bitcode objects via OutputFileMap ∩ LinkFileList, lower via opt + clang.""" + filelist_arg = parse_flag_value(args, '-filelist') + if not filelist_arg or not Path(filelist_arg).is_file(): + return args, { + 'expected_swift_count': 0, + 'converted_swift_count': 0, + 'skipped_swift_count': 0, + 'swift_audits': [], + 'objc_audits': [], + 'replaced_entries': [], + } + + filelist_path = Path(filelist_arg) + raw_entries = [line.strip() for line in filelist_path.read_text(encoding='utf-8').splitlines() if line.strip()] + swift_ofm = load_target_swift_output_map(filelist_path) + + target_triple, syslibroot = extract_platform_flags(args) + sdk_info = detect_sdk_info(syslibroot) if syslibroot else detect_sdk_info() + exempt_subs = policy.get('exempt_path_substrings', []) + + expected_indices = [] + skipped = [] + for idx, entry in enumerate(raw_entries): + norm = os.path.normpath(entry) + src_hint = swift_ofm.get(norm) + if src_hint is None: + continue + expected_indices.append((idx, entry, src_hint)) + + to_convert = [] + for idx, entry, src_hint in expected_indices: + if any(ex in src_hint or ex in entry for ex in exempt_subs): + skipped.append({'object': entry, 'source': src_hint, 'reason': 'exempt_path'}) + continue + if not Path(entry).is_file(): + skipped.append({'object': entry, 'source': src_hint, 'reason': 'missing_file'}) + continue + if not is_bitcode_wrapper(entry): + skipped.append({'object': entry, 'source': src_hint, 'reason': 'not_bitcode'}) + continue + to_convert.append((idx, entry, src_hint)) + + converted_map = {} + swift_audits = [] + new_entries = list(raw_entries) + + if to_convert: + require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' or ctl['mode'] in ('full', 'str', 'noop') + tc = resolve_opt(require_obf=require_obf) + if not tc.get('opt_path'): + raise RuntimeError(tc.get('warning', 'Verified opt binary unavailable for Swift bitcode lowering')) + + clang_bin = detect_stock_tool('clang') + wrapper_sha = file_sha256(__file__) + policy_sha = file_sha256(policy_path) if policy_path and Path(policy_path).is_file() else 'none' + pipeline = os.environ.get('IG_SWIFT_OPT_PIPELINE', 'default,ig-obfuscate') + cache_root = infer_obj_cache_dir(output_path, linkmap_arg) + swift_mod_name = os.environ.get('PRODUCT_MODULE_NAME') or re.sub( + r'[^A-Za-z0-9_]', '_', Path(output_path).stem + ) + + persistent_macho_dir = filelist_path.parent / 'ig-swift-macho' + persistent_macho_dir.mkdir(parents=True, exist_ok=True) + + backend_flags = [ + '-target', target_triple, + '-isysroot', syslibroot, + '-O2', + '-Xclang', '-disable-llvm-passes', + '-fno-builtin', + '-Wno-override-module', + '-g', + f'-ffile-prefix-map={app_repo}=.', + '-x', 'ir', '-c', + ] + + def worker(item): + idx, bc_str, src_hint = item + bc_p = Path(bc_str) + out_o = persistent_macho_dir / f'{idx:04d}_{bc_p.stem}.o' + out_a = persistent_macho_dir / f'{idx:04d}_{bc_p.stem}.o.ig-audit.json' + audit_data = _lower_single_bitcode_object( + bc_p, + out_o, + out_a, + src_hint, + swift_mod_name, + backend_flags, + tc, + clang_bin, + sdk_info, + wrapper_sha, + policy_sha, + pipeline, + ctl, + policy_path, + cache_root, + cache_kind='swift_v1', + tmp_parent=persistent_macho_dir, + ) + return idx, str(out_o), audit_data + + with ThreadPoolExecutor(max_workers=min(8, max(1, len(to_convert)))) as pool: + for idx, macho_out, audit_data in pool.map(worker, to_convert): + converted_map[idx] = macho_out + new_entries[idx] = macho_out + swift_audits.append(audit_data) + + ig_filelist = filelist_path.parent / f'{filelist_path.name}.ig' + ig_filelist.write_text('\n'.join(new_entries) + '\n', encoding='utf-8') + rewritten_args = [] + i = 0 + while i < len(args): + if args[i] == '-filelist' and i + 1 < len(args) and args[i + 1] == filelist_arg: + rewritten_args.extend(['-filelist', str(ig_filelist)]) + i += 2 + continue + rewritten_args.append(args[i]) + i += 1 + args = rewritten_args + + # Collect matching ObjC/C sidecar audits (ignoring stale/mismatched mode sidecars) + objc_audits = [] + converted_set = set(converted_map.values()) + for entry in new_entries: + if entry in converted_set: + continue + sidecar = Path(entry + '.ig-audit.json') + obj_p = Path(entry) + if not sidecar.is_file() or not obj_p.is_file(): + continue + try: + s_data = json.loads(sidecar.read_text(encoding='utf-8')) + if s_data.get('mode') != ctl['mode'] or s_data.get('pass_filter') != ctl['filter']: + continue + if abs(sidecar.stat().st_mtime_ns - obj_p.stat().st_mtime_ns) > 10_000_000_000 and sidecar.stat().st_mtime_ns + 5_000_000_000 < obj_p.stat().st_mtime_ns: + continue + objc_audits.append(s_data) + except Exception: + continue + + return args, { + 'expected_swift_count': len(expected_indices), + 'converted_swift_count': len(converted_map), + 'skipped_swift_count': len(skipped), + 'skipped_swift': skipped, + 'swift_audits': swift_audits, + 'objc_audits': objc_audits, + 'replaced_entries': new_entries, + 'static_frameworks_obfuscated': [], + } + + +def convert_static_framework_bitcode(args, output_path, linkmap_arg, ctl, policy_path, policy, app_repo, conv_report): + """Unpack target static framework archives containing Swift ThinLTO bitcode, obfuscate & repack.""" + target_fws = set(policy.get('obfuscate_static_frameworks') or []) + if not target_fws: + return args, conv_report + + search_dirs = [] + i = 0 + while i < len(args): + a = args[i] + if a == '-F' and i + 1 < len(args): + search_dirs.append(Path(args[i + 1])) + i += 2 + continue + if a.startswith('-F') and len(a) > 2: + search_dirs.append(Path(a[2:])) + i += 1 + continue + i += 1 + + def find_framework_archive(fw_name): + for sdir in search_dirs: + cand = sdir / f'{fw_name}.framework' / fw_name + if cand.is_file(): + members = _parse_bsd_ar_members(cand) + if members is not None: + return cand, sdir, members + return None, None, None + + filelist_arg = parse_flag_value(args, '-filelist') + work_root_parent = Path(filelist_arg).parent if filelist_arg else output_path.parent + target_triple, syslibroot = extract_platform_flags(args) + sdk_info = detect_sdk_info(syslibroot) if syslibroot else detect_sdk_info() + require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' or ctl['mode'] in ('full', 'str', 'noop') + tc = None + clang_bin = None + wrapper_sha = None + policy_sha = None + pipeline = None + cache_root = None + backend_flags = None + + replaced_fw_map = {} + fw_records = list(conv_report.get('static_frameworks_obfuscated') or []) + + i = 0 + while i < len(args): + if args[i] == '-framework' and i + 1 < len(args) and args[i + 1] in target_fws: + fw_name = args[i + 1] + if fw_name not in replaced_fw_map: + arch_p, sdir, members = find_framework_archive(fw_name) + if arch_p and members: + bc_indices = [idx for idx, (_, payload) in enumerate(members) if payload[:4] in BITCODE_MAGICS] + if bc_indices: + if tc is None: + tc = resolve_opt(require_obf=require_obf) + if not tc.get('opt_path'): + raise RuntimeError(tc.get('warning', 'Verified opt binary unavailable for static framework bitcode')) + clang_bin = detect_stock_tool('clang') + wrapper_sha = file_sha256(__file__) + policy_sha = file_sha256(policy_path) if policy_path and Path(policy_path).is_file() else 'none' + pipeline = os.environ.get('IG_SWIFT_OPT_PIPELINE', 'default,ig-obfuscate') + cache_root = infer_obj_cache_dir(output_path, linkmap_arg) + backend_flags = [ + '-target', target_triple, + '-isysroot', syslibroot, + '-O2', + '-Xclang', '-disable-llvm-passes', + '-fno-builtin', + '-Wno-override-module', + '-g', + f'-ffile-prefix-map={app_repo}=.', + '-x', 'ir', '-c', + ] + + fw_work = work_root_parent / 'ig-static-fw' / fw_name + if fw_work.exists(): + shutil.rmtree(fw_work) + fw_work.mkdir(parents=True, exist_ok=True) + stem_map = _build_static_framework_source_map(fw_name, app_repo, linkmap_arg or output_path) + + bc_jobs = [] + member_out_paths = [None] * len(members) + passthrough_count = 0 + for m_idx, (m_name, payload) in enumerate(members): + safe_name = re.sub(r'[^A-Za-z0-9_.-]', '_', Path(m_name).name or f'member_{m_idx}.o') + if not safe_name.endswith('.o'): + safe_name = f'{safe_name}.o' + if payload[:4] in BITCODE_MAGICS: + bc_file = fw_work / f'{m_idx:04d}_{safe_name}.bc' + bc_file.write_bytes(payload) + m_stem = Path(m_name).stem + src_hint = ( + stem_map.get(m_name) + or stem_map.get(m_stem) + or f'Vendor/{fw_name}/{m_name}' + ) + out_o = fw_work / f'{m_idx:04d}_{safe_name}' + out_a = fw_work / f'{m_idx:04d}_{safe_name}.ig-audit.json' + bc_jobs.append((m_idx, bc_file, out_o, out_a, src_hint)) + else: + raw_o = fw_work / f'{m_idx:04d}_{safe_name}' + raw_o.write_bytes(payload) + member_out_paths[m_idx] = raw_o + passthrough_count += 1 + + def fw_worker(job): + m_idx, bc_file, out_o, out_a, src_hint = job + audit_data = _lower_single_bitcode_object( + bc_file, + out_o, + out_a, + src_hint, + fw_name, + backend_flags, + tc, + clang_bin, + sdk_info, + wrapper_sha, + policy_sha, + pipeline, + ctl, + policy_path, + cache_root, + cache_kind='static_fw_v1', + extra_cache_fields={'source_path': src_hint}, + tmp_parent=fw_work, + ) + return m_idx, out_o, audit_data + + with ThreadPoolExecutor(max_workers=min(8, max(1, len(bc_jobs)))) as pool: + for m_idx, out_o, audit_data in pool.map(fw_worker, bc_jobs): + member_out_paths[m_idx] = out_o + conv_report['swift_audits'].append(audit_data) + + out_archive = fw_work / f'{fw_name}.obf.a' + subprocess.run( + ['xcrun', 'libtool', '-static', '-o', str(out_archive), *[str(p) for p in member_out_paths]], + check=True, + ) + conv_report['expected_swift_count'] += len(bc_jobs) + conv_report['converted_swift_count'] += len(bc_jobs) + replaced_fw_map[fw_name] = str(out_archive) + fw_records.append({ + 'framework': fw_name, + 'source_archive': str(arch_p), + 'bitcode_members': len(bc_jobs), + 'passthrough_members': passthrough_count, + 'output_archive': str(out_archive), + }) + i += 2 + continue + i += 1 + + conv_report['static_frameworks_obfuscated'] = fw_records + if not replaced_fw_map: + return args, conv_report + + new_args = [] + seen_replaced = set() + i = 0 + while i < len(args): + if args[i] == '-framework' and i + 1 < len(args) and args[i + 1] in replaced_fw_map: + fw_name = args[i + 1] + if fw_name not in seen_replaced: + new_args.append(replaced_fw_map[fw_name]) + seen_replaced.add(fw_name) + i += 2 + continue + new_args.append(args[i]) + i += 1 + return new_args, conv_report + + +def _bare_symbol_candidates(candidates): + out = [] + seen = set() + for sc in candidates: + if not sc: + continue + m = re.match(r'^(\d+)([A-Za-z_][A-Za-z0-9_]*)$', sc) + if m: + n = int(m.group(1)) + rest = m.group(2) + cand = rest[:n] if 0 < n <= len(rest) else sc + else: + cand = sc + if cand not in seen: + seen.add(cand) + out.append(cand) + return out + + +def _demangle_swift_symbols(symbols): + swift_syms = sorted({s for s in symbols if isinstance(s, str) and (s.startswith('$s') or s.startswith('_$s'))}) + if not swift_syms: + return {} + try: + res = subprocess.run( + ['xcrun', 'swift-demangle', '--compact'], + input='\n'.join(swift_syms) + '\n', + capture_output=True, + text=True, + ) + except OSError: + return {} + if res.returncode != 0: + return {} + out_lines = res.stdout.splitlines() + if len(out_lines) != len(swift_syms): + return {} + return dict(zip(swift_syms, out_lines)) + + +def evaluate_and_write_obf_audit(output_path, linkmap_arg, ctl, policy_path, policy, conv_report): + audit_root = ( + Path(linkmap_arg).parent + if linkmap_arg + else Path(os.environ.get('TARGET_TEMP_DIR') or str(output_path.parent)) + ) + audit_dir = audit_root / 'ig-route2-audit' + audit_dir.mkdir(parents=True, exist_ok=True) + + all_audits = conv_report['swift_audits'] + conv_report['objc_audits'] + demangled_map = _demangle_swift_symbols( + fn + for a in all_audits + for fn in ((a.get('functions_flattened') or []) + (a.get('strings_encrypted_functions') or [])) + ) + + def _matches_any(fn, raw_cands, bare_cands): + if any(sc in fn for sc in raw_cands): + return True + dm = demangled_map.get(fn) + return bool(dm and any(bc in dm for bc in bare_cands)) + + total_flattened = sum(len(a.get('functions_flattened') or []) for a in all_audits) + total_strings = sum(int(a.get('strings_encrypted_count') or 0) for a in all_audits) + total_strings_stack = sum(int(a.get('strings_stack_encrypted_count') or 0) for a in all_audits) + total_objc_strings = sum(int(a.get('objc_strings_encrypted_count') or 0) for a in all_audits) + total_swift_strings = sum(int(a.get('swift_strings_encrypted_count') or 0) for a in all_audits) + total_strings_replaced = sum(int(a.get('strings_replaced_count') or 0) for a in all_audits) + total_paths_scrubbed = sum(int(a.get('paths_scrubbed_count') or 0) for a in all_audits) + total_indirect_calls = sum(int(a.get('indirect_calls_count') or 0) for a in all_audits) + total_opaque_constants = sum(int(a.get('opaque_constants_count') or 0) for a in all_audits) + total_arithmetic_rewrites = sum(int(a.get('arithmetic_rewrites_count') or 0) for a in all_audits) + total_indirect_branches = sum(int(a.get('indirect_branches_count') or 0) for a in all_audits) + total_anti_hook_functions = sum(int(a.get('anti_hook_functions_count') or 0) for a in all_audits) + total_functions_outlined = sum(int(a.get('functions_outlined_count') or 0) for a in all_audits) + total_opaque_field_access = sum(int(a.get('opaque_field_access_count') or 0) for a in all_audits) + total_bb_split_count = sum(int(a.get('bb_split_count') or 0) for a in all_audits) + total_bb_split_functions = sum(len(a.get('bb_split_functions') or []) for a in all_audits) + total_nonlinear_mba = sum(int(a.get('nonlinear_mba_count') or 0) for a in all_audits) + total_opaque_zero = sum(int(a.get('opaque_zero_count') or 0) for a in all_audits) + + req_results = [] + failures = [] + mode = ctl['mode'] + filt = ctl['filter'] + + for req in policy.get('required_targets', []): + tid = req.get('id', 'unknown') + path_sub = req.get('path_contains', '') + sym_sub = req.get('symbol_contains', '') + str_sym_sub = req.get('str_symbol_contains', '') + sym_candidates = req.get('symbol_contains_any') or ([sym_sub] if sym_sub else []) + str_sym_candidates = req.get('str_symbol_contains_any') or ([str_sym_sub] if str_sym_sub else []) + sym_bare = _bare_symbol_candidates(sym_candidates) + str_sym_bare = _bare_symbol_candidates(str_sym_candidates) + + matched_recs = [] + for a in all_audits: + fns = (a.get('functions_flattened') or []) + (a.get('strings_encrypted_functions') or []) + if (path_sub and path_sub in (a.get('source_path') or '')) or any( + _matches_any(fn, sym_candidates, sym_bare) or _matches_any(fn, str_sym_candidates, str_sym_bare) + for fn in fns + ): + matched_recs.append(a) + + flat_hits = sum( + 1 + for a in matched_recs + for fn in (a.get('functions_flattened') or []) + if not sym_candidates or _matches_any(fn, sym_candidates, sym_bare) + ) + str_hits = sum(int(a.get('strings_encrypted_count') or 0) for a in matched_recs) + const_hits = sum(int(a.get('opaque_constants_count') or 0) for a in matched_recs) + arith_hits = sum(int(a.get('arithmetic_rewrites_count') or 0) for a in matched_recs) + ibr_hits = sum(int(a.get('indirect_branches_count') or 0) for a in matched_recs) + antihook_hits = sum(int(a.get('anti_hook_functions_count') or 0) for a in matched_recs) + + req_results.append({ + 'id': tid, + 'matched_modules': len(matched_recs), + 'flattened_hits': flat_hits, + 'strings_encrypted_hits': str_hits, + 'opaque_constants_hits': const_hits, + 'arithmetic_rewrites_hits': arith_hits, + 'indirect_branches_hits': ibr_hits, + 'anti_hook_functions_hits': antihook_hits, + }) + + if mode == 'full' and filt == 'all': + if flat_hits < int(req.get('min_flattened', 0)): + failures.append(f'{tid}: expected >= {req.get("min_flattened")} flattened hits, got {flat_hits}') + if str_hits < int(req.get('min_strings_encrypted', 0)): + failures.append(f'{tid}: expected >= {req.get("min_strings_encrypted")} encrypted strings, got {str_hits}') + if const_hits < int(req.get('min_opaque_constants', 0)): + failures.append(f'{tid}: expected >= {req.get("min_opaque_constants")} opaque constants, got {const_hits}') + if arith_hits < int(req.get('min_arithmetic_rewrites', 0)): + failures.append(f'{tid}: expected >= {req.get("min_arithmetic_rewrites")} arithmetic rewrites, got {arith_hits}') + if ibr_hits < int(req.get('min_indirect_branches', 0)): + failures.append(f'{tid}: expected >= {req.get("min_indirect_branches")} indirect branches, got {ibr_hits}') + if antihook_hits < int(req.get('min_anti_hook_functions', 0)): + failures.append(f'{tid}: expected >= {req.get("min_anti_hook_functions")} anti-hook functions, got {antihook_hits}') + elif mode == 'str' or (mode == 'full' and filt == 'str'): + if str_hits < int(req.get('min_strings_encrypted', 0)): + failures.append(f'{tid}: expected >= {req.get("min_strings_encrypted")} encrypted strings, got {str_hits}') + + if mode == 'str' or (mode == 'full' and filt == 'str'): + if ( + total_flattened != 0 or total_indirect_calls != 0 + or total_opaque_constants != 0 or total_arithmetic_rewrites != 0 + or total_indirect_branches != 0 or total_anti_hook_functions != 0 + or total_functions_outlined != 0 or total_opaque_field_access != 0 + or total_bb_split_count != 0 + ): + failures.append( + f'str mode expected total_flattened=0 and total_indirect_calls=0, ' + f'got flattened={total_flattened}, indirect_calls={total_indirect_calls}, ' + f'opaque_constants={total_opaque_constants}, arith={total_arithmetic_rewrites}, ' + f'ibr={total_indirect_branches}, antihook={total_anti_hook_functions}, ' + f'outline={total_functions_outlined}, field={total_opaque_field_access}, ' + f'bbsplit={total_bb_split_count}' + ) + elif mode == 'full' and filt == 'fla': + if ( + total_indirect_calls != 0 or total_strings != 0 or total_paths_scrubbed != 0 + or total_opaque_constants != 0 or total_arithmetic_rewrites != 0 + or total_indirect_branches != 0 or total_anti_hook_functions != 0 + or total_functions_outlined != 0 or total_opaque_field_access != 0 + or total_bb_split_count != 0 + ): + failures.append( + f'fla filter expected zero non-fla edits, ' + f'got indirect_calls={total_indirect_calls}, strings={total_strings}, paths={total_paths_scrubbed}' + ) + elif mode in ('noop', 'off'): + if ( + total_flattened != 0 or total_strings != 0 or total_indirect_calls != 0 + or total_paths_scrubbed != 0 or total_opaque_constants != 0 + or total_arithmetic_rewrites != 0 or total_indirect_branches != 0 + or total_anti_hook_functions != 0 or total_functions_outlined != 0 + or total_opaque_field_access != 0 or total_bb_split_count != 0 + ): + failures.append( + f'{mode} mode expected zero edits, got flattened={total_flattened}, ' + f'strings={total_strings}, indirect_calls={total_indirect_calls}, paths={total_paths_scrubbed}' + ) + + summary = { + 'target_binary': output_path.name, + 'mode': mode, + 'pass_filter': filt, + 'route2_mode': ctl['route2'], + 'all_off': ctl['all_off'], + 'seed': ctl['seed'], + 'stamp': ctl['stamp'], + 'policy_path': policy_path, + 'l1_translation_active': bool(policy.get('l1_translation_active')), + 'l1_map_digest': policy.get('l1_map_digest', ''), + 'expected_swift_count': conv_report['expected_swift_count'], + 'converted_swift_count': conv_report['converted_swift_count'], + 'skipped_swift_count': conv_report['skipped_swift_count'], + 'objc_audited_count': len(conv_report['objc_audits']), + 'total_flattened': total_flattened, + 'total_strings_encrypted': total_strings, + 'total_strings_stack_encrypted': total_strings_stack, + 'total_objc_strings_encrypted': total_objc_strings, + 'total_swift_strings_encrypted': total_swift_strings, + 'total_strings_replaced': total_strings_replaced, + 'total_paths_scrubbed': total_paths_scrubbed, + 'total_indirect_calls': total_indirect_calls, + 'total_opaque_constants': total_opaque_constants, + 'total_arithmetic_rewrites': total_arithmetic_rewrites, + 'total_indirect_branches': total_indirect_branches, + 'total_anti_hook_functions': total_anti_hook_functions, + 'total_functions_outlined': total_functions_outlined, + 'total_opaque_field_access': total_opaque_field_access, + 'total_bb_split_count': total_bb_split_count, + 'total_bb_split_functions': total_bb_split_functions, + 'total_nonlinear_mba': total_nonlinear_mba, + 'total_opaque_zero': total_opaque_zero, + 'required_targets': req_results, + 'static_frameworks_obfuscated': conv_report.get('static_frameworks_obfuscated', []), + 'module_audits': [ + { + 'source_path': a.get('source_path'), + 'strings_encrypted_count': a.get('strings_encrypted_count'), + 'strings_stack_encrypted_count': int(a.get('strings_stack_encrypted_count') or 0), + 'objc_strings_encrypted_count': int(a.get('objc_strings_encrypted_count') or 0), + 'swift_strings_encrypted_count': int(a.get('swift_strings_encrypted_count') or 0), + 'strings_replaced_count': int(a.get('strings_replaced_count') or 0), + 'indirect_calls_count': int(a.get('indirect_calls_count') or 0), + 'indirect_calls_functions': a.get('indirect_calls_functions') or [], + 'opaque_constants_count': int(a.get('opaque_constants_count') or 0), + 'arithmetic_rewrites_count': int(a.get('arithmetic_rewrites_count') or 0), + 'indirect_branches_count': int(a.get('indirect_branches_count') or 0), + 'indirect_branches_functions': a.get('indirect_branches_functions') or [], + 'anti_hook_functions_count': int(a.get('anti_hook_functions_count') or 0), + 'anti_hook_functions': a.get('anti_hook_functions') or [], + 'functions_outlined_count': int(a.get('functions_outlined_count') or 0), + 'outlined_functions': a.get('outlined_functions') or [], + 'opaque_field_access_count': int(a.get('opaque_field_access_count') or 0), + 'opaque_field_functions': a.get('opaque_field_functions') or [], + 'bb_split_count': int(a.get('bb_split_count') or 0), + 'bb_split_functions': a.get('bb_split_functions') or [], + 'nonlinear_mba_count': int(a.get('nonlinear_mba_count') or 0), + 'opaque_zero_count': int(a.get('opaque_zero_count') or 0), + 'functions_flattened': a.get('functions_flattened'), + 'functions_flattened_details': a.get('functions_flattened_details') or [], + 'strings_encrypted_functions': a.get('strings_encrypted_functions'), + } + for a in all_audits + if ( + a.get('functions_flattened') + or int(a.get('strings_encrypted_count') or 0) > 0 + or int(a.get('opaque_constants_count') or 0) > 0 + or int(a.get('arithmetic_rewrites_count') or 0) > 0 + or int(a.get('indirect_branches_count') or 0) > 0 + or int(a.get('anti_hook_functions_count') or 0) > 0 + or int(a.get('functions_outlined_count') or 0) > 0 + or int(a.get('opaque_field_access_count') or 0) > 0 + or int(a.get('bb_split_count') or 0) > 0 + ) + ], + } + (audit_dir / 'ig_obfuscation_audit.json').write_text( + json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8' + ) + if failures: + raise RuntimeError('[IGObf] Audit gate failed: ' + '; '.join(failures)) + return summary + + +def build_rewritten_ld_args(args, app_repo, stage_dir, unpatched_out, linkmap_out, has_map_flag): + """Rewrite SDK -l / -framework / direct path arguments and inject IGThreadID.o + -F stage_dir.""" + by_framework = {} + by_lib = {} + by_source = {} + for entry in STATIC_INPUTS: + cand = stage_dir / entry['dest'] + if not cand.is_file(): + continue + src = (app_repo / entry['relative']).resolve() + by_source[str(src)] = str(cand) + eargs = entry.get('arguments') or [] + if len(eargs) == 2 and eargs[0] == '-framework': + by_framework[eargs[1]] = str(cand) + elif len(eargs) == 1 and eargs[0].startswith('-l'): + by_lib[eargs[0][2:]] = str(cand) + + rewritten = [] + inserted_stage_f = False + replaced_sdks = [] + i = 0 + while i < len(args): + arg = args[i] + + if not inserted_stage_f and (arg == '-F' or (arg.startswith('-F') and len(arg) > 2)): + rewritten.extend(['-F', str(stage_dir)]) + inserted_stage_f = True + + if arg in ('-framework', '-weak_framework') and i + 1 < len(args): + fw_name = args[i + 1] + if fw_name in by_framework: + rewritten.append(by_framework[fw_name]) + replaced_sdks.append(f'{arg} {fw_name}') + i += 2 + continue + + if arg.startswith('-l') and len(arg) > 2 and arg[2:] in by_lib: + lib_name = arg[2:] + rewritten.append(by_lib[lib_name]) + replaced_sdks.append(f'-l{lib_name}') + i += 1 + continue + + if arg == '-l' and i + 1 < len(args) and args[i + 1] in by_lib: + lib_name = args[i + 1] + rewritten.append(by_lib[lib_name]) + replaced_sdks.append(f'-l {lib_name}') + i += 2 + continue + + if arg == '-o' and i + 1 < len(args): + if not inserted_stage_f: + rewritten.extend(['-F', str(stage_dir)]) + inserted_stage_f = True + rewritten.append(str(stage_dir / 'IGThreadID.o')) + if not has_map_flag: + rewritten.extend(['-map', str(linkmap_out)]) + rewritten.extend(['-o', str(unpatched_out)]) + i += 2 + continue + + if not arg.startswith('-'): + p = Path(arg) + if p.exists(): + resolved = str(p.resolve()) + if resolved in by_source: + rewritten.append(by_source[resolved]) + replaced_sdks.append(resolved) + i += 1 + continue + + rewritten.append(arg) + i += 1 + + return rewritten, replaced_sdks + + +def check_coverage_absent(args): + for arg in args: + if 'clang_rt.profile_' in arg: + raise RuntimeError( + f'[IGRoute2] Refusing Route 2 Release link because LLVM code coverage runtime ' + f'is linked ({arg}). Set ENABLE_CODE_COVERAGE=NO / CLANG_ENABLE_CODE_COVERAGE=NO.' + ) + + +def select_matching_rules(profile, attributed_sites, link_sym_map): + """Filter shared profile rules to (caller, symbol) pairs present in this target.""" + observed = Counter((s.get('caller'), s.get('symbol')) for s in attributed_sites if s.get('caller')) + selected = [] + for rule in profile['rules']: + key = (rule['caller'], rule['symbol']) + if observed.get(key, 0) > 0 and rule['caller'] in link_sym_map and rule['destination'] in link_sym_map: + selected.append(rule) + return dict(rules=selected) + + +def verify_patched_main(binary_path, linkmap_path): + m = Macho(binary_path.read_bytes()) + defined = defined_symbols(m) + missing_dispatch = sorted(EXPECTED_DISPATCH_SYMBOLS - set(defined)) + if missing_dispatch: + raise RuntimeError(f'[IGRoute2] Main binary missing _IG_dispatch_* symbols: {missing_dispatch}') + + variants = collect_variant_stubs(binary_path) + if variants: + raise RuntimeError(f'[IGRoute2] Main binary still has Darwin-variant stubs: {variants}') + + info, sites = inspect_binary(binary_path) + if sites: + attributed = list(attribute(Path(binary_path), Path(linkmap_path))) + details = [ + f"{s.get('symbol')} in {s.get('caller', '?')} ({s.get('object', '?')}) @ 0x{s['site']:x}" + for s in attributed[:20] + ] + raise RuntimeError( + f'[IGRoute2] {len(sites)} residual direct callsite(s) remain in {binary_path.name}: ' + + '; '.join(details) + ) + return info + + +def should_passthrough(args, out_arg, ctl=None): + if ctl and ctl.get('all_off') == '1' and ctl.get('route2') == 'off': + return True, 'IG_ALL_GUARD_OFF=1' + if (not ctl) and os.environ.get('IG_DISABLE_ROUTE2_ARCHIVE') == '1': + return True, 'IG_DISABLE_ROUTE2_ARCHIVE=1' + if any(flag in args for flag in PASSTHROUGH_FLAGS): + return True, 'non-executable link mode' + if not out_arg: + return True, 'no -o output' + out_path = Path(out_arg) + if out_path.parent.suffix != '.app': + return True, f'non-.app output ({out_path.parent.name})' + arch = parse_flag_value(args, '-arch') + if arch and arch != 'arm64': + return True, f'non-arm64 arch ({arch})' + return False, '' + + +def main(argv=None): + raw_args = list(sys.argv[1:] if argv is None else argv) + args, ctl = strip_ig_stamp(raw_args) + real_ld = resolve_real_ld(args) + out_arg = parse_flag_value(args, '-o') + passthrough, _ = should_passthrough(args, out_arg, ctl=ctl) + if passthrough: + os.execv(real_ld, [real_ld, *args]) + return 0 + + output_path = Path(out_arg) + map_arg = parse_flag_value(args, '-map') + filelist_arg = parse_flag_value(args, '-filelist') + swift_hints = [filelist_arg or '', out_arg or ''] + if filelist_arg and Path(filelist_arg).is_file(): + ofm_map = load_target_swift_output_map(Path(filelist_arg)) + for src_p in ofm_map.values(): + if src_p and src_p != '' and src_p.endswith('.swift'): + swift_hints.append(src_p) + break + app_repo = discover_active_app_repo(swift_hints, fallback_root=resolve_app_repo(TOOLCHAIN_ROOT)) + + policy_path = os.environ.get('IG_LLVM_POLICY_PATH') or resolve_default_policy(ctl.get('policy_profile', 'default')) + policy = {} + if policy_path and Path(policy_path).is_file(): + policy_path, policy = resolve_effective_policy( + policy_path, app_repo, infer_obj_cache_dir(output_path, map_arg) + ) + + if ctl['all_off'] != '1': + args, conv_report = convert_swift_objects( + args, output_path, map_arg, ctl, policy_path, policy, app_repo + ) + args, conv_report = convert_static_framework_bitcode( + args, output_path, map_arg, ctl, policy_path, policy, app_repo, conv_report + ) + if not args_contain_remaining_bitcode(args, conv_report.get('replaced_entries', [])): + args = strip_lto_link_flags(args) + obf_audit = evaluate_and_write_obf_audit(output_path, map_arg, ctl, policy_path, policy, conv_report) + else: + obf_audit = {'total_flattened': 0, 'total_strings_encrypted': 0, 'converted_swift_count': 0} + + if ctl['route2'] == 'off': + os.execv(real_ld, [real_ld, *args]) + return 0 + + check_coverage_absent(args) + bridge_src = resolve_bridge_source(app_repo) + cache_root = infer_cache_root(output_path, map_arg) + stage_dir = ensure_prepared_stage(cache_root, app_repo, bridge_src) + + with tempfile.TemporaryDirectory(prefix='.ig-ld-', dir=output_path.parent) as tmp: + work = Path(tmp) + unpatched = work / f'{output_path.name}.unpatched' + patched = work / f'{output_path.name}.patched' + linkmap = Path(map_arg) if map_arg else (work / f'{output_path.name}-LinkMap.txt') + linkmap.parent.mkdir(parents=True, exist_ok=True) + + ld_args, replaced_sdks = build_rewritten_ld_args( + args, app_repo, stage_dir, unpatched, linkmap, bool(map_arg), + ) + proc = subprocess.run([real_ld, *ld_args]) + if proc.returncode != 0: + return proc.returncode + + link_sym_map = link_symbols(linkmap) + attributed_sites = list(attribute(unpatched, linkmap)) + profile = json.loads(PROFILE_PATH.read_text(encoding='utf-8')) + filtered_profile = select_matching_rules(profile, attributed_sites, link_sym_map) + + if filtered_profile['rules']: + patch(unpatched, patched, linkmap, filtered_profile) + final_bin = patched + else: + final_bin = unpatched + + verify_patched_main(final_bin, linkmap) + output_path.parent.mkdir(parents=True, exist_ok=True) + final_bin.chmod(0o755) + shutil.copy2(final_bin, output_path) + output_path.chmod(0o755) + print( + f'[IGRoute2] ld OK for {output_path.name}: ' + f'sdk_inputs={len(replaced_sdks)}, residual_rules={len(filtered_profile["rules"])}, ' + f'swift_conv={obf_audit.get("converted_swift_count", 0)}, ' + f'flat={obf_audit.get("total_flattened", 0)}, str={obf_audit.get("total_strings_encrypted", 0)}' + ) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/xcode_archive/route2_archive_common.py b/tools/xcode_archive/route2_archive_common.py new file mode 100644 index 0000000..8115cd2 --- /dev/null +++ b/tools/xcode_archive/route2_archive_common.py @@ -0,0 +1,83 @@ +"""Shared constants and Mach-O helpers for Route 2 Xcode Archive integration.""" +import hashlib +import os +from pathlib import Path +import struct + +from batch import arm64_slices, Slice + +EXTERNAL_SYMBOLS = {'_fopen', '_dlopen', '_dlsym'} +SYSTEM_SYMBOLS = {'_write', '_read', '_open', '_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid'} +FORBIDDEN_SYMBOLS = EXTERNAL_SYMBOLS | SYSTEM_SYMBOLS + +EXPECTED_DISPATCH_SYMBOLS = { + '_IG_dispatch_fopen', '_IG_dispatch_dlopen', '_IG_dispatch_dlsym', + '_IG_dispatch_write', '_IG_dispatch_read', '_IG_dispatch_open', + '_IG_dispatch_close', '_IG_dispatch_exit', '_IG_dispatch_fork', + '_IG_dispatch_unlink', '_IG_dispatch_getpid', +} + +GUARD_FRAMEWORK_NAME = 'RDCoreIO' +GUARD_BUNDLE_ID = 'cn.touchv.readoor.coreio' + +EXPECTED_ARCHIVE_EXPORTS = { + '_rd_a0', '_rd_f', '_rd_a1', '_rd_a2', '_rd_a3', '_rd_a4', + '_rd_u00', '_rd_o', '_rdo', '_rd_r', '_rdr', '_rd_w0', '_rd_w', + '_rd_c0', '_rd_c', '_rd_p00', '_rd_p0', '_rd_e', '_rd_k', + '_rd_l00', '_rd_s0', '_rd_s', + '_rd_io_cfg', '_rd_io_chk', '_rd_io_ev', +} + + +def file_sha256(path): + h = hashlib.sha256() + with Path(path).open('rb') as stream: + for chunk in iter(lambda: stream.read(1 << 20), b''): + h.update(chunk) + return h.hexdigest() + + +def resolve_app_repo(toolchain_root): + """Resolve active readoor repository root, preferring SRCROOT for isolated build snapshots.""" + candidates = [] + srcroot = os.environ.get('SRCROOT') + if srcroot: + candidates.append(Path(srcroot).resolve()) + candidates.extend([ + (toolchain_root / 'readoor-test').resolve(), + toolchain_root.parent / 'readoor-test', + ]) + for candidate in candidates: + if (candidate / 'readoor.xcodeproj').exists(): + return candidate + raise FileNotFoundError(f'Unable to resolve readoor-test repository root from {toolchain_root}') + + +def resolve_defender_dir(toolchain_root, app_repo): + in_toolchain = (toolchain_root / 'defender').resolve() + if (in_toolchain / 'dispatch/IGArchiveGuard.c').is_file(): + return in_toolchain + in_repo = app_repo / 'readoor/3.0/Base/Security/IGDefender' + if (in_repo / 'dispatch/IGArchiveGuard.c').is_file(): + return in_repo + raise FileNotFoundError(f'Unable to resolve IGDefender directory under {toolchain_root} or {app_repo}') + + +def collect_variant_stubs(binary_path): + """Return any Darwin-suffixed stub imports (e.g. _fopen$DARWIN_EXTSN) for forbidden targets.""" + data = Path(binary_path).read_bytes() + found = set() + for off, _ in arm64_slices(data): + sl = Slice(data, off) + if not (sl.stubs and sl.symtab and sl.dysym): + continue + symoff, _, stroff, _ = sl.symtab + indoff = sl.dysym[12] + _, ssize, _, sr1, sr2 = sl.stubs + for idx_pos in range(ssize // sr2): + symi, = struct.unpack_from('