"""用真实策略源码做宿主测试,覆盖观察/强制模式和 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): def test_decisions(self): with tempfile.TemporaryDirectory() as td: 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 } var isUnavailable: Bool { status == 2 } } 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) assert(clean.action == .none && !clean.shouldRestrict(in:.enforce)) let unknown=policy.evaluate(findings:[RDDefenderFinding(status:2,reason:104)],legacy:legacy) assert(unknown.action == .monitor && unknown.unavailableReasons == [104]) assert(!unknown.shouldRestrict(in:.observe) && unknown.shouldRestrict(in:.enforce)) let tamper=policy.evaluate(findings:[RDDefenderFinding(status:1,reason:105)],legacy:legacy) 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()