fix(defender): ObjC 方法基线改用构建期签名清单,修复误报 110 导致的延迟闪退
- 构建期生成随包签名的 IGMethods.bin(仅主程序),运行时按镜像 UUID、 入口偏移与函数边界内指令摘要校验;导出审计复核清单与最终镜像一致 - 系统函数、调度与解包保护的代码前缀按 LC_FUNCTION_STARTS 限定在函数边界内 - 边界内识别 B / LDR+BR / ADRP+ADD+BR / MOVK+BR 蹦床并确认目标归属,避免系统尾调用误报 - 登记前 IMP 已落入匿名内存判为改写;清单读取改走 IG_dispatch_open - 函数边界长度按入口缓存;镜像未重新链接时复用基线;Debug 附加调试器时不按入口摘要判定改写 - 补充宿主测试;删除已过时的 README 与 docs 历史文档,保留 THIRD_PARTY_NOTICES
This commit is contained in:
Vendored
+4
-3
@@ -153,14 +153,15 @@ int main(int argc, char **argv) {
|
||||
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。 */
|
||||
/* 无法解析的观察项独立报告 unavailable。 */
|
||||
const IGObjCWatch none[] = { { "IGClassThatNeverExists123", "x" } };
|
||||
ig_objc_baseline_capture(none,1);
|
||||
if (ig_objc_baseline_check(collect,&f)!=0) return 11; /* 类不可解析不登记 → 仍 no-op */
|
||||
if (ig_objc_baseline_check(collect,&f)!=0 || f.unavailable!=1) return 11;
|
||||
f.unavailable=0;
|
||||
ig_objc_baseline_capture(watch,1);
|
||||
ig_objc_baseline_append(cls_watch,1);
|
||||
int hits=ig_objc_baseline_check(collect,&f);
|
||||
return hits!=0 || f.detected || f.unavailable;
|
||||
return hits!=0 || f.detected || f.unavailable!=2; /* 动态创建的类没有构建基线。 */
|
||||
}
|
||||
if (!strcmp(argv[1],"objc-swap")) {
|
||||
Class c=make_fixture_class();
|
||||
|
||||
Vendored
+26
-1
@@ -190,7 +190,7 @@ int main(int argc,char **argv) {
|
||||
assert(ig_verify_function((void *)1,"invalid",collect,NULL)==IG_UNAVAILABLE);
|
||||
assert(reasons[IG_REASON_VERIFICATION_UNAVAILABLE]==1);
|
||||
} else if (!strcmp(argv[1],"prologue")) {
|
||||
assert(ig_arm64_suspicious_prologue(0x14000001,0));
|
||||
assert(!ig_arm64_suspicious_prologue(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));
|
||||
@@ -216,6 +216,31 @@ int main(int argc,char **argv) {
|
||||
0xd61f0200u, 0xd503201fu, 0xd503201fu, 0xd503201fu
|
||||
};
|
||||
assert(ig_arm64_suspicious_window(mid_ldr_win, 8));
|
||||
#if defined(__arm64__) || defined(__aarch64__)
|
||||
void *sys_getpid = dlsym(RTLD_DEFAULT, "getpid");
|
||||
void *sys_ftell = dlsym(RTLD_DEFAULT, "ftell");
|
||||
assert(sys_getpid != NULL && sys_ftell != NULL);
|
||||
const uint32_t local_b[1] = {0x14000000u};
|
||||
assert(ig_arm64_trampoline_to_foreign(local_b, local_b, 1));
|
||||
assert(ig_verify_function(sys_ftell, "ftell", collect, NULL) == IG_CLEAR);
|
||||
struct { uint32_t ins[2]; uint64_t dst; } __attribute__((aligned(8))) ldr_tramp = {
|
||||
{0x58000050u, 0xd61f0200u}, (uint64_t)(uintptr_t)collect
|
||||
};
|
||||
assert(ig_arm64_trampoline_to_foreign(ldr_tramp.ins, ldr_tramp.ins, 2));
|
||||
ldr_tramp.dst = (uint64_t)(uintptr_t)sys_getpid;
|
||||
assert(!ig_arm64_trampoline_to_foreign(ldr_tramp.ins, ldr_tramp.ins, 2));
|
||||
uintptr_t foreign_dst = (uintptr_t)collect;
|
||||
uint32_t adrp_foreign[3];
|
||||
intptr_t page_delta = ((intptr_t)(foreign_dst & ~(uintptr_t)0xfffu) -
|
||||
(intptr_t)((uintptr_t)adrp_foreign & ~(uintptr_t)0xfffu)) >> 12;
|
||||
uint32_t imm21 = (uint32_t)page_delta & 0x1fffffu;
|
||||
adrp_foreign[0] = 0x90000010u | ((imm21 & 3u) << 29) | ((imm21 >> 2) << 5);
|
||||
adrp_foreign[1] = 0x91000210u | ((uint32_t)(foreign_dst & 0xfffu) << 10);
|
||||
adrp_foreign[2] = 0xd61f0200u;
|
||||
assert(ig_arm64_trampoline_to_foreign(adrp_foreign, adrp_foreign, 3));
|
||||
assert(ig_arm64_trampoline_to_foreign(movk_win, movk_win, 8));
|
||||
assert(!ig_arm64_trampoline_to_foreign(clean_win, clean_win, 8));
|
||||
#endif
|
||||
} else return 2;
|
||||
return 0;
|
||||
}
|
||||
|
||||
Vendored
+83
@@ -0,0 +1,83 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <dlfcn.h>
|
||||
#import <objc/runtime.h>
|
||||
#import <sys/mman.h>
|
||||
#import <sys/ptrace.h>
|
||||
#include "anti_hook/IGObjCBaseline.h"
|
||||
|
||||
// 优化器能把实例方法编译成一条合法的尾调用。
|
||||
__attribute__((noinline)) static int readValue(void) {
|
||||
static volatile int value = 7;
|
||||
return value;
|
||||
}
|
||||
|
||||
@interface IGManifestParent : NSObject
|
||||
- (int)value;
|
||||
+ (int)classValue;
|
||||
- (int)other;
|
||||
@end
|
||||
@implementation IGManifestParent
|
||||
- (int)value { return readValue(); }
|
||||
+ (int)classValue { return readValue(); }
|
||||
- (int)other { return 42; }
|
||||
@end
|
||||
@interface IGManifestChild : IGManifestParent
|
||||
@end
|
||||
@implementation IGManifestChild
|
||||
@end
|
||||
@interface IGManifestChild (Extra)
|
||||
- (int)extra;
|
||||
@end
|
||||
@implementation IGManifestChild (Extra)
|
||||
- (int)extra { return readValue(); }
|
||||
@end
|
||||
|
||||
typedef struct { int changed, unavailable; } Counts;
|
||||
static int collect(const IGFinding *finding, void *ctx) {
|
||||
Counts *counts = ctx;
|
||||
counts->changed += finding->status == IG_DETECTED;
|
||||
counts->unavailable += finding->status == IG_UNAVAILABLE;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, const char **argv) {
|
||||
if (argc != 2) return 1;
|
||||
// 强制 dyld 装入 Swift 类,与真实应用一致地通过运行时名称登记。
|
||||
extern void ig_load_swift_fixture(void);
|
||||
extern const char *ig_swift_nested_name(void);
|
||||
extern const char *ig_swift_private_name(void);
|
||||
ig_load_swift_fixture();
|
||||
IGObjCWatch watches[] = {
|
||||
{"IGManifestChild", "-value"}, {"IGManifestChild", "+classValue"},
|
||||
{"IGManifestChild", "extra"}, {"Fixture.SwiftProbe", "swiftValue"},
|
||||
{ig_swift_nested_name(), "nestedValue"}, {ig_swift_private_name(), "privateValue"},
|
||||
};
|
||||
Method method = class_getInstanceMethod(IGManifestParent.class, @selector(value));
|
||||
IMP other = class_getMethodImplementation(IGManifestParent.class, @selector(other));
|
||||
BOOL before = !strcmp(argv[1], "before"), after = !strcmp(argv[1], "after");
|
||||
BOOL before_block = !strcmp(argv[1], "before-block"), before_anon = !strcmp(argv[1], "before-anon");
|
||||
void *anon = NULL;
|
||||
if (before) method_setImplementation(method, other);
|
||||
if (before_block) {
|
||||
IMP blk = imp_implementationWithBlock(^int(id self) { (void)self; return 99; });
|
||||
method_setImplementation(method, blk);
|
||||
}
|
||||
if (before_anon) {
|
||||
anon = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANON, -1, 0);
|
||||
if (anon == MAP_FAILED) return 3;
|
||||
Dl_info di;
|
||||
if (dladdr(anon, &di)) return 4;
|
||||
method_setImplementation(method, (IMP)anon);
|
||||
}
|
||||
if (ig_objc_baseline_capture(watches, 6) != 6) return 2;
|
||||
if (after) method_setImplementation(method, other);
|
||||
BOOL traced = !strcmp(argv[1], "different-bytes-traced");
|
||||
if (traced && ptrace(PT_TRACE_ME, 0, NULL, 0) != 0) return 5;
|
||||
Counts counts = {0};
|
||||
ig_objc_baseline_check(collect, &counts);
|
||||
if (anon) munmap(anon, 4096);
|
||||
fprintf(stderr, "changed=%d unavailable=%d\n", counts.changed, counts.unavailable);
|
||||
int expect_changed = before || before_block || before_anon || after || !strcmp(argv[1], "different-bytes");
|
||||
return counts.changed != expect_changed ||
|
||||
counts.unavailable != (!strcmp(argv[1], "unavailable") ? 6 : 0);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
"""用真实的 arm64 Mach-O 对照构建器输出和 Objective-C 运行时。"""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tools/xcode_archive'))
|
||||
from objc_method_baseline import generate, image_uuid, NAME, ROW
|
||||
|
||||
FIXTURE_SWIFT = (
|
||||
'import Foundation\n'
|
||||
'class SwiftProbe: NSObject {\n'
|
||||
' @objc func swiftValue() {}\n'
|
||||
' class Nested: NSObject { @objc func nestedValue() {} }\n'
|
||||
'}\n'
|
||||
'private class PrivateProbe: NSObject { @objc func privateValue() {} }\n'
|
||||
'@_cdecl("ig_load_swift_fixture") public func loadFixture() { _ = SwiftProbe.self }\n'
|
||||
'@_cdecl("ig_swift_nested_name") public func nestedName() -> UnsafePointer<CChar> { class_getName(SwiftProbe.Nested.self) }\n'
|
||||
'@_cdecl("ig_swift_private_name") public func privateName() -> UnsafePointer<CChar> { class_getName(PrivateProbe.self) }\n'
|
||||
)
|
||||
FRAMEWORK_OBJC = (
|
||||
'#import <Foundation/Foundation.h>\n'
|
||||
'@interface IGFrameworkOnly : NSObject\n- (int)value;\n@end\n'
|
||||
'@implementation IGFrameworkOnly\n- (int)value { return 1; }\n@end\n'
|
||||
)
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin' and platform.machine() == 'arm64', '需要 arm64 macOS')
|
||||
class MethodBaselineTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
app = cls.app = Path(cls.tmp.name)
|
||||
frameworks = app / 'Frameworks'
|
||||
frameworks.mkdir()
|
||||
# Framework 中的方法不进入基线。
|
||||
other = app / 'Other.m'
|
||||
other.write_text(FRAMEWORK_OBJC)
|
||||
subprocess.run(['xcrun', 'clang', '-dynamiclib', str(other), '-framework', 'Foundation',
|
||||
'-o', str(frameworks / 'Other.dylib')], check=True)
|
||||
# 受监控的 ObjC 与 Swift 类都链接进主程序,与真实应用一致。
|
||||
defender = ROOT / 'defender'
|
||||
sources = [ROOT / 'tests/fixtures/objc_manifest_host.m', defender / 'anti_hook/IGObjCBaseline.c',
|
||||
defender / 'anti_hook/IGAntiHook.c', defender / 'resolve/IGResolve.c',
|
||||
defender / 'dispatch/IGDispatch.c']
|
||||
objects = []
|
||||
for i, source in enumerate(sources):
|
||||
obj = app / f'{i}.o'
|
||||
# DEBUG=1 覆盖 Debug 构建中的调试器分支。
|
||||
subprocess.run(['xcrun', 'clang', '-O2', '-DDEBUG=1', '-I', str(defender), '-I', str(defender / 'include'),
|
||||
'-c', str(source), '-o', str(obj)], check=True)
|
||||
objects.append(str(obj))
|
||||
swift = app / 'Fixture.swift'
|
||||
swift.write_text(FIXTURE_SWIFT)
|
||||
cls.exe = app / 'probe'
|
||||
subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-module-name', 'Fixture', str(swift), *objects,
|
||||
'-framework', 'Foundation', '-o', str(cls.exe)], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_mode(self, mode):
|
||||
subprocess.run([str(self.exe), mode], check=True)
|
||||
|
||||
def test_signed_resource_contract(self):
|
||||
manifest = self.app / NAME
|
||||
generate(self.app, self.exe, manifest)
|
||||
blob = manifest.read_bytes()
|
||||
self.assertEqual(blob[8:24], image_uuid(self.exe))
|
||||
rows = {row[0]: row for row in ROW.iter_unpack(blob[24:])}
|
||||
self.assertNotIn(hashlib.sha256(b'-IGFrameworkOnly value').digest(), rows)
|
||||
tail = rows[hashlib.sha256(b'-IGManifestParent value').digest()]
|
||||
self.assertEqual(tail[3], 4)
|
||||
entry = self.exe.read_bytes()[tail[2]:tail[2] + 4]
|
||||
self.assertEqual(int.from_bytes(entry, 'little') >> 26, 0b000101)
|
||||
self.assertEqual(tail[4], hashlib.sha256(entry).digest())
|
||||
for mode in ('clean', 'before', 'before-block', 'before-anon', 'after'):
|
||||
self.run_mode(mode)
|
||||
# 只更改测试基线中的指令摘要,验证地址不变时代码差异也可被发现。
|
||||
altered = bytearray(blob)
|
||||
altered[blob.index(tail[0], 24) + 60] ^= 1
|
||||
manifest.write_bytes(altered)
|
||||
self.run_mode('different-bytes')
|
||||
# 调试器附加时(Debug),软断点导致的摘要差异不判定为改写。
|
||||
self.run_mode('different-bytes-traced')
|
||||
manifest.write_bytes(blob[:8] + bytes(16) + blob[24:])
|
||||
self.run_mode('unavailable')
|
||||
manifest.unlink()
|
||||
self.run_mode('unavailable')
|
||||
|
||||
def test_phase_reuses_unchanged_baseline(self):
|
||||
import ig_guard_frameworks_phase as phase
|
||||
audit = self.app / 'audit'
|
||||
manifest = self.app / NAME
|
||||
manifest.unlink(missing_ok=True)
|
||||
phase.write_method_baseline(self.app, self.exe, audit)
|
||||
original = manifest.read_bytes()
|
||||
stamp = audit / 'objc-method-baseline.stamp'
|
||||
self.assertTrue(stamp.is_file())
|
||||
mtime = manifest.stat().st_mtime_ns
|
||||
phase.write_method_baseline(self.app, self.exe, audit)
|
||||
self.assertEqual(manifest.stat().st_mtime_ns, mtime)
|
||||
# 资源被改动时不复用,重新生成。
|
||||
manifest.write_bytes(b'tampered')
|
||||
phase.write_method_baseline(self.app, self.exe, audit)
|
||||
self.assertEqual(manifest.read_bytes(), original)
|
||||
Reference in New Issue
Block a user