feat(defender): 可集成静态库 + readoor 接入方案(检测→分级→数据毒化闭环)
在 iOSGuard 侧产出可集成产物与接入文档,不修改 readoor 代码。 - defender/: anti_hook/anti_frida/anti_debug/anti_jailbreak 探针 + syscall 直发、 policy 分级层、poison 数据依赖毒化、dispatch/resolve/call_bridge 等子模块 - poison: 三副本冗余、无分支掩码;健康恒等、毒化破坏 key(替代 if-exit 处置) - policy: STRONG/MEDIUM/WEAK 分级,守误报底线,仅 DETECTED 参与、组合命中才毒化 - anti_jailbreak: IGSyscall 直发 svc 检测越狱文件(400)/沙盒逃逸(401),绕 libc hook - tools/build_defender_lib.sh: 一键交叉编译打包 libIGDefender.a(arm64) + umbrella 头 - docs/18_READOOR_DEFENDER_INTEGRATION.md: 精确到文件/bridging/替换点/代码片段 - docs/05-17 + evidence + tests + macho_guard/static_sdk_redirect 工具链 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
ff0aee7f47
commit
599e1da5ce
@@ -0,0 +1,231 @@
|
||||
import XCTest
|
||||
import UIKit
|
||||
|
||||
/// 访问真实观察包;不使用 --UITesting,不注入 token,不调用购买接口。
|
||||
final class IGBusinessRegressionTests: XCTestCase {
|
||||
private let bundleID = "cn.touchv.iosguard.observe.20261110"
|
||||
|
||||
override func setUpWithError() throws { continueAfterFailure = false }
|
||||
|
||||
private func capture(_ app: XCUIApplication, _ name: String) {
|
||||
// 截图遮盖输入框,文本树移除输入值,避免登录排查留存凭证。
|
||||
let source = app.screenshot().image
|
||||
let fields = app.textFields.allElementsBoundByIndex + app.secureTextFields.allElementsBoundByIndex
|
||||
let screenshotImage = UIGraphicsImageRenderer(size: source.size).image { context in
|
||||
source.draw(at: .zero)
|
||||
UIColor.lightGray.setFill()
|
||||
let sx = source.size.width / app.frame.width
|
||||
let sy = source.size.height / app.frame.height
|
||||
for field in fields {
|
||||
let frame = field.frame
|
||||
context.fill(CGRect(x: frame.minX * sx, y: frame.minY * sy,
|
||||
width: frame.width * sx, height: frame.height * sy))
|
||||
}
|
||||
}
|
||||
let screenshot = XCTAttachment(image: screenshotImage)
|
||||
screenshot.name = name
|
||||
screenshot.lifetime = .keepAlways
|
||||
add(screenshot)
|
||||
let redactedTree = app.debugDescription.components(separatedBy: "\n").map { line in
|
||||
guard line.contains("TextField"), let value = line.range(of: ", value:") else { return line }
|
||||
return String(line[..<value.lowerBound]) + ", value: [redacted]"
|
||||
}.joined(separator: "\n")
|
||||
let tree = XCTAttachment(string: redactedTree)
|
||||
tree.name = name + "-accessibility"
|
||||
tree.lifetime = .keepAlways
|
||||
add(tree)
|
||||
}
|
||||
|
||||
func testInspectLaunch() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.launch()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 30))
|
||||
capture(app, "observation-launch")
|
||||
}
|
||||
|
||||
func testInspectCurrentPage() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
capture(app, "observation-current")
|
||||
}
|
||||
|
||||
func testAllowWifiAndInspect() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
|
||||
let wifi = springboard.buttons["仅限无线局域网"]
|
||||
if wifi.waitForExistence(timeout: 5) { wifi.tap() }
|
||||
app.activate()
|
||||
_ = app.images["splash"].waitForNonExistence(timeout: 20)
|
||||
capture(app, "after-network-permission")
|
||||
}
|
||||
|
||||
func testHomeResourceAndForeground() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let home = app.otherElements["home_page_anchor"]
|
||||
XCTAssertTrue(home.waitForExistence(timeout: 30), "需先完成真实登录与启动流程")
|
||||
// 实际首页资源由 TableCell 内自绘卡片承载,使用已观察到的资源标题。
|
||||
let resource = app.staticTexts["[pdf]MW书籍测试读"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 20))
|
||||
capture(app, "home-before-resource")
|
||||
resource.tap()
|
||||
let detail = app.otherElements["detail_page_anchor"]
|
||||
XCTAssertTrue(detail.waitForExistence(timeout: 20), "首个首页卡片未进入商品详情")
|
||||
capture(app, "resource-detail")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(detail.waitForExistence(timeout: 10))
|
||||
capture(app, "resource-after-foreground")
|
||||
}
|
||||
|
||||
func testTrialResourceAndInspect() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let trial = app.buttons["试读"].firstMatch
|
||||
XCTAssertTrue(trial.waitForExistence(timeout: 15))
|
||||
trial.tap()
|
||||
// 入口可能先展示课件/规格选择,先留存真实页面再决定下一步。
|
||||
capture(app, "after-trial-entry")
|
||||
}
|
||||
|
||||
func testColdRestartAndInspect() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 30))
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
capture(app, "after-cold-restart")
|
||||
}
|
||||
|
||||
func testPDFTrialAndPageTurn() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
let resource = app.staticTexts["[pdf]MW书籍测试读"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 15))
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
let trial = app.buttons["试读"].firstMatch
|
||||
XCTAssertTrue(trial.waitForExistence(timeout: 15))
|
||||
trial.tap()
|
||||
XCTAssertTrue(app.buttons["titlebar return phone"].waitForExistence(timeout: 20))
|
||||
_ = app.progressIndicators["进度"].waitForNonExistence(timeout: 30)
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 5))
|
||||
capture(app, "pdf-before-page-turn")
|
||||
app.swipeLeft()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 5), "PDF 翻页后进程退出")
|
||||
capture(app, "pdf-after-page-turn")
|
||||
}
|
||||
|
||||
func testEPUBResourceAndForeground() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
let resource = app.staticTexts["【epub】会员免费书籍"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 15))
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
capture(app, "epub-detail")
|
||||
let read = app.buttons["开始阅读"].firstMatch
|
||||
let trial = app.buttons["试读"].firstMatch
|
||||
if read.exists { read.tap() }
|
||||
else {
|
||||
XCTAssertTrue(trial.waitForExistence(timeout: 10), "本账号没有可用阅读入口")
|
||||
trial.tap()
|
||||
}
|
||||
capture(app, "epub-entry")
|
||||
XCTAssertTrue(app.webViews.firstMatch.waitForExistence(timeout: 30), "尚未出现 EPUB 内容视图")
|
||||
capture(app, "epub-content")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(app.webViews.firstMatch.waitForExistence(timeout: 15))
|
||||
capture(app, "epub-after-foreground")
|
||||
}
|
||||
func testWordbookOpenAndInspect() {
|
||||
openWordbook(replayStyle: true)
|
||||
}
|
||||
|
||||
private func openWordbook(replayStyle: Bool) {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.launchArguments = replayStyle ? ["--IGArchiveReplayStyle"] : []
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
let popupClose = app.buttons["rd pop close"]
|
||||
if popupClose.waitForExistence(timeout: 5) { popupClose.tap() }
|
||||
capture(app, "wordbook-home")
|
||||
let resource = app.staticTexts["31单词书(稳操胜券)-勿动"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 20))
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
capture(app, "wordbook-detail")
|
||||
}
|
||||
|
||||
func testWordbookReadAndForeground() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let read = app.buttons["开始阅读"].firstMatch
|
||||
let section = app.staticTexts["稳操胜券"].firstMatch
|
||||
XCTAssertTrue(section.waitForExistence(timeout: 20), "需先打开指定单词书详情")
|
||||
capture(app, "wordbook-loaded-detail")
|
||||
if read.exists { read.tap() } else { section.tap() }
|
||||
capture(app, "wordbook-after-read-entry")
|
||||
let ready = app.staticTexts["今日学习单词了吗?"].firstMatch
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 120), "单词书未准备完成")
|
||||
XCTAssertTrue(ready.isHittable, "单词书就绪内容不可见")
|
||||
capture(app, "wordbook-ready")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 15))
|
||||
capture(app, "wordbook-after-foreground")
|
||||
}
|
||||
|
||||
func testWordbookReentryAndCache() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let back = app.buttons["mw backBar img"].firstMatch
|
||||
XCTAssertTrue(back.waitForExistence(timeout: 10))
|
||||
back.tap()
|
||||
let section = app.staticTexts["稳操胜券"].firstMatch
|
||||
XCTAssertTrue(section.waitForExistence(timeout: 15))
|
||||
section.tap()
|
||||
let ready = app.staticTexts["今日学习单词了吗?"].firstMatch
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 60))
|
||||
XCTAssertTrue(ready.isHittable)
|
||||
capture(app, "wordbook-reentry-cache")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 15))
|
||||
capture(app, "wordbook-reentry-foreground")
|
||||
}
|
||||
|
||||
func testWordbookFreshExtraction() {
|
||||
testWordbookOpenAndInspect()
|
||||
testWordbookReadAndForeground()
|
||||
}
|
||||
|
||||
func testWordbookCachedEntryAndReentry() {
|
||||
// 由单独无参数启动步骤进入首页,避免将短暂营销弹窗的自动消失误记为业务失败。
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 20))
|
||||
let resource = app.staticTexts["31单词书(稳操胜券)-勿动"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 15))
|
||||
XCTAssertTrue(resource.isHittable)
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
testWordbookReadAndForeground()
|
||||
testWordbookReentryAndCache()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
import XCTest
|
||||
import UIKit
|
||||
|
||||
/// 反 Hook 门禁按钮级回归(强制模式 dev 包 cn.touchv.a4YX061)。
|
||||
///
|
||||
/// 相位(按方法名字典序执行):
|
||||
/// A1 干净启动勘察;A2 登出到登录页(个人中心 退出登录);
|
||||
/// B1 注入启动·密码登录门禁;B2 注入启动·第三方登录门禁;
|
||||
/// C1 干净启动·密码登录放行(DEBUG 预填测试账号真实登录);
|
||||
/// D1 注入启动·VIP 购买门禁(会员页);E1 注入启动·激活码门禁(我的页探测入口)。
|
||||
///
|
||||
/// 注入:编排器(run_gate_regression.sh)以 devicectl `-e DYLD_INSERT_LIBRARIES`
|
||||
/// 调试启动通道预先注入启动(空壳 libfrida-sim.dylib),注入相位测试仅 activate()
|
||||
/// attach 到该进程——v4 教训:XCUITest launchEnvironment 的 DYLD_INSERT 经
|
||||
/// SpringBoard 启动链被剥离,门禁不触发。各相位以 -only-testing 分批执行(v6 序,
|
||||
/// XCUITest↔devicectl 切换仅 2 次):干净批 A1/A2(游客态)→ 注入批 B1/B2(游客)
|
||||
/// → 干净批 C1(放行证明)→ 注入批 D1/E1(登录态,未登成则游客守卫跳过)。
|
||||
/// v5e 教训:devicectl `--console` 通道在连续会话后整体卡死(零输出+进程即死),
|
||||
/// 注入启动不用 console,注入生效由测试内门禁 toast 端到端自证。
|
||||
/// 教训(B2 首版崩溃):营销弹窗自动消失瞬间盲点「rd pop close」会落到其下方的
|
||||
/// 首页搜索按钮,触发路由重复注册 assertion 崩溃(业务既有 bug)——先等自然消失再点,
|
||||
/// 且点击前复核存在与可点性。
|
||||
/// 凭证不入日志:截图遮盖输入框、文本树脱敏(沿用业务观察 Runner 做法)。
|
||||
final class IGGateRegressionTests: XCTestCase {
|
||||
private let bundleID = "cn.touchv.a4YX061"
|
||||
private var injectLib: String? { ProcessInfo.processInfo.environment["INJECT_LIB"] }
|
||||
private let blockLoginToast = "当前环境暂时无法登录,请稍后重试"
|
||||
private let blockVipToast = "当前环境暂时无法购买,请稍后重试"
|
||||
private let blockActivationToast = "当前环境暂时无法激活,请稍后重试"
|
||||
|
||||
override func setUpWithError() throws { continueAfterFailure = false }
|
||||
|
||||
// MARK: - 工具
|
||||
|
||||
/// 脱敏截图(遮盖输入框)+ 脱敏文本树,全部 keepAlways 留证。
|
||||
private func capture(_ app: XCUIApplication, _ name: String) {
|
||||
let source = app.screenshot().image
|
||||
let fields = app.textFields.allElementsBoundByIndex + app.secureTextFields.allElementsBoundByIndex
|
||||
let screenshotImage = UIGraphicsImageRenderer(size: source.size).image { context in
|
||||
source.draw(at: .zero)
|
||||
UIColor.lightGray.setFill()
|
||||
let sx = source.size.width / app.frame.width
|
||||
let sy = source.size.height / app.frame.height
|
||||
for field in fields {
|
||||
let frame = field.frame
|
||||
context.fill(CGRect(x: frame.minX * sx, y: frame.minY * sy,
|
||||
width: frame.width * sx, height: frame.height * sy))
|
||||
}
|
||||
}
|
||||
let screenshot = XCTAttachment(image: screenshotImage)
|
||||
screenshot.name = name
|
||||
screenshot.lifetime = .keepAlways
|
||||
add(screenshot)
|
||||
let redactedTree = app.debugDescription.components(separatedBy: "\n").map { line in
|
||||
guard line.contains("TextField"), let value = line.range(of: ", value:") else { return line }
|
||||
return String(line[..<value.lowerBound]) + ", value: [redacted]"
|
||||
}.joined(separator: "\n")
|
||||
let tree = XCTAttachment(string: redactedTree)
|
||||
tree.name = name + "-accessibility"
|
||||
tree.lifetime = .keepAlways
|
||||
add(tree)
|
||||
}
|
||||
|
||||
private func step(_ message: String) {
|
||||
NSLog("[GateRegression] %@", message)
|
||||
}
|
||||
|
||||
private func launchApp(_ app: XCUIApplication, injected: Bool) throws {
|
||||
if injected {
|
||||
// v4 教训:XCUITest launchEnvironment 的 DYLD_INSERT_LIBRARIES 经 SpringBoard
|
||||
// 启动链被剥离(B1 门禁 toast 不出现)——注入进程由编排器以 devicectl
|
||||
// `-e` 调试启动通道预先启动,测试只 attach(activate 不重启,注入保持)。
|
||||
guard app.state == .runningForeground || app.state == .runningBackground else {
|
||||
try skipAndCapture("注入进程未运行(编排器须先 devicectl 注入启动本 App)")
|
||||
}
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 30), "注入进程未进前台")
|
||||
return
|
||||
}
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 40), "应用未进入前台")
|
||||
}
|
||||
|
||||
private func skipAndCapture(_ reason: String) throws -> Never {
|
||||
step("SKIP: \(reason)")
|
||||
throw XCTSkip(reason)
|
||||
}
|
||||
|
||||
/// 等待登录页或首页锚点,返回 "login" / "home" / "unknown"。
|
||||
private func waitLoginOrHome(_ app: XCUIApplication, timeout: TimeInterval = 25) -> String {
|
||||
if app.otherElements["login_page_anchor"].waitForExistence(timeout: timeout) { return "login" }
|
||||
if app.otherElements["home_page_anchor"].waitForExistence(timeout: 10) { return "home" }
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
/// 关闭可能遮挡的营销弹窗:先等自然消失(约 6 秒),仍在且可点才点关闭。
|
||||
/// 不盲点:弹窗消失瞬间点击会落到其下方控件(首版曾误触首页搜索引发路由崩溃)。
|
||||
private func dismissPopups(_ app: XCUIApplication) {
|
||||
let popupClose = app.buttons["rd pop close"]
|
||||
if popupClose.waitForNonExistence(timeout: 6) { return }
|
||||
if popupClose.exists && popupClose.isHittable {
|
||||
popupClose.tap()
|
||||
_ = popupClose.waitForNonExistence(timeout: 3)
|
||||
}
|
||||
}
|
||||
|
||||
/// 勾选登录协议(v3 登录页树:勾选框暴露 identifier login_agreement_checkbox)。
|
||||
private func selectAgreementIfNeeded(_ app: XCUIApplication) {
|
||||
let agreement = app.otherElements["login_agreement_view"]
|
||||
_ = agreement.waitForExistence(timeout: 10)
|
||||
let checkbox = app.buttons["login_agreement_checkbox"].firstMatch
|
||||
if checkbox.exists {
|
||||
if checkbox.isHittable { checkbox.tap() }
|
||||
step("已点击协议勾选框")
|
||||
} else {
|
||||
let fallback = agreement.buttons.firstMatch
|
||||
if fallback.exists, fallback.isHittable {
|
||||
fallback.tap()
|
||||
step("勾选框无 identifier,已点协议视图内按钮")
|
||||
} else {
|
||||
step("协议勾选框未暴露,跳过勾选")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 断言门禁 toast 出现并等其消失。
|
||||
private func assertToast(_ app: XCUIApplication, text: String, label: String) {
|
||||
let toast = app.staticTexts[text].firstMatch
|
||||
XCTAssertTrue(toast.waitForExistence(timeout: 6), "\(label):未出现门禁 toast「\(text)」")
|
||||
capture(app, label + "-toast")
|
||||
_ = toast.waitForNonExistence(timeout: 8)
|
||||
}
|
||||
|
||||
/// 首页就绪并稳定(弹窗处理完成)。
|
||||
private func waitHomeStable(_ app: XCUIApplication, timeout: TimeInterval = 30) throws {
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: timeout), "未进入首页")
|
||||
dismissPopups(app)
|
||||
}
|
||||
|
||||
/// 游客态从首页导航到登录页:「我的」页「登录/注册」按钮(v2 勘察树确认)。
|
||||
/// 返回 false 表示入口不可达(多为已登录态),由调用方决定跳过或走既有会话判定。
|
||||
/// v3 教训:启动偶发落在无 tab bar 的推广落地页(AllTypes 书城页)——
|
||||
/// 先等待/返回自救,仍无 tab 则重启一次重抽落地页。
|
||||
private func navigateToLoginFromHome(_ app: XCUIApplication, allowRelaunch: Bool = true) -> Bool {
|
||||
func attempt() -> Bool {
|
||||
let mineTab = app.tabBars.buttons["我的"].firstMatch
|
||||
if !mineTab.waitForExistence(timeout: 12) {
|
||||
// 落地页自救:点导航返回键(若在二级页)后再等 tab。
|
||||
let back = app.buttons["nav black goback"].firstMatch
|
||||
if back.exists, back.isHittable {
|
||||
back.tap()
|
||||
step("落地页无 tab,已点返回")
|
||||
}
|
||||
if !mineTab.waitForExistence(timeout: 12) { return false }
|
||||
}
|
||||
mineTab.tap()
|
||||
_ = app.otherElements["personal_center_page_anchor"].waitForExistence(timeout: 10)
|
||||
dismissPopups(app)
|
||||
let guestEntry = app.buttons["登录/注册"].firstMatch
|
||||
guard guestEntry.waitForExistence(timeout: 8), guestEntry.isHittable else { return false }
|
||||
guestEntry.tap()
|
||||
return app.otherElements["login_page_anchor"].waitForExistence(timeout: 20)
|
||||
}
|
||||
if attempt() { return true }
|
||||
guard allowRelaunch else { return false }
|
||||
step("首轮导航失败,重启重抽落地页")
|
||||
app.terminate()
|
||||
app.launch()
|
||||
guard app.wait(for: .runningForeground, timeout: 40) else { return false }
|
||||
_ = app.otherElements["home_page_anchor"].waitForExistence(timeout: 25)
|
||||
dismissPopups(app)
|
||||
return attempt()
|
||||
}
|
||||
|
||||
// MARK: - A 勘察与登出
|
||||
|
||||
func testA1InspectCleanState() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("A1 干净启动勘察开始,INJECT_LIB=\(injectLib ?? "未传入")")
|
||||
try launchApp(app, injected: false)
|
||||
let state = waitLoginOrHome(app)
|
||||
step("A1 启动状态=\(state)")
|
||||
if state == "home" { dismissPopups(app) }
|
||||
capture(app, "a1-clean-\(state)")
|
||||
}
|
||||
|
||||
func testA2LogoutIfNeeded() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("A2 确保登录页可达(游客直进;登录态经设置页登出)")
|
||||
try launchApp(app, injected: false)
|
||||
let state = waitLoginOrHome(app)
|
||||
if state == "login" {
|
||||
step("A2 已在登录页")
|
||||
capture(app, "a2-already-login")
|
||||
return
|
||||
}
|
||||
guard state == "home" else { try skipAndCapture("A2 首页不可达(状态 \(state))") }
|
||||
dismissPopups(app)
|
||||
let mineTab = app.tabBars.buttons["我的"].firstMatch
|
||||
XCTAssertTrue(mineTab.waitForExistence(timeout: 10), "未找到「我的」页签")
|
||||
mineTab.tap()
|
||||
_ = app.otherElements["personal_center_page_anchor"].waitForExistence(timeout: 10)
|
||||
sleep(2)
|
||||
dismissPopups(app)
|
||||
capture(app, "a2-mine-page")
|
||||
// 游客态(v2 树:登录/注册按钮)直接进登录页,B 阶段即可测登录门禁。
|
||||
let guestEntry = app.buttons["登录/注册"].firstMatch
|
||||
if guestEntry.exists, guestEntry.isHittable {
|
||||
guestEntry.tap()
|
||||
XCTAssertTrue(app.otherElements["login_page_anchor"].waitForExistence(timeout: 20), "游客点「登录/注册」未进入登录页")
|
||||
step("A2 游客态进入登录页")
|
||||
capture(app, "a2-guest-login-page")
|
||||
return
|
||||
}
|
||||
// 登录态:右上角设置图标(v2 树:personalCenter setting)→ 设置页底部「退出登录」。
|
||||
let settingIcon = app.buttons["personalCenter setting"].firstMatch
|
||||
XCTAssertTrue(settingIcon.exists && settingIcon.isHittable, "未找到设置入口(见 a2 勘察树)")
|
||||
settingIcon.tap()
|
||||
sleep(2)
|
||||
capture(app, "a2-settings-page")
|
||||
// 退出登录在设置列表尾部,滚动查找(cell 标签为文本)。
|
||||
var confirmedLogout = false
|
||||
for _ in 0..<4 where !confirmedLogout {
|
||||
let logoutBtn = app.buttons.containing(NSPredicate(format: "label CONTAINS '退出登录'")).firstMatch
|
||||
let logoutText = app.staticTexts.containing(NSPredicate(format: "label CONTAINS '退出登录'")).firstMatch
|
||||
if logoutBtn.exists { logoutBtn.tap(); confirmedLogout = true }
|
||||
else if logoutText.exists { logoutText.tap(); confirmedLogout = true }
|
||||
else { app.swipeUp() }
|
||||
}
|
||||
XCTAssertTrue(confirmedLogout, "设置页未找到退出登录入口(见 a2-settings-page 树)")
|
||||
sleep(1)
|
||||
capture(app, "a2-logout-confirm")
|
||||
// 确认弹窗(自定义两键弹窗,右侧确认键常见文案逐个尝试)。
|
||||
for confirm in ["确定", "退出", "确认", "退出登录"] {
|
||||
let button = app.buttons[confirm].firstMatch
|
||||
if button.waitForExistence(timeout: 2) && button.isHittable {
|
||||
button.tap()
|
||||
step("A2 确认退出(「\(confirm)」)")
|
||||
break
|
||||
}
|
||||
}
|
||||
let back = waitLoginOrHome(app, timeout: 30)
|
||||
step("A2 登出后状态=\(back)")
|
||||
capture(app, "a2-after-logout-\(back)")
|
||||
XCTAssertEqual(back, "login", "登出后未回到登录页")
|
||||
}
|
||||
|
||||
// MARK: - B 拦截相位(注入启动·登录入口)
|
||||
|
||||
func testB1BlockPasswordLogin() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("B1 注入启动·密码登录门禁")
|
||||
try launchApp(app, injected: true)
|
||||
// 注入相位严禁 clean 重启(activate 之外的 launch 会丢 DYLD 注入),
|
||||
// navigate 不带 relaunch 自救;导航失败即跳过留证。
|
||||
var state = waitLoginOrHome(app)
|
||||
if state == "home", navigateToLoginFromHome(app, allowRelaunch: false) { state = "login" }
|
||||
capture(app, "b1-inject-\(state)")
|
||||
guard state == "login" else {
|
||||
try skipAndCapture("B1 登录页不可达(状态 \(state),游客入口缺失)")
|
||||
}
|
||||
capture(app, "b1-login-page")
|
||||
// 门禁在输入校验之前:空输入点击提交也必须先命中门禁 toast。
|
||||
let submit = app.buttons["login_submit_button"]
|
||||
XCTAssertTrue(submit.waitForExistence(timeout: 10), "未找到登录提交按钮")
|
||||
submit.tap()
|
||||
assertToast(app, text: blockLoginToast, label: "b1-block-password-login")
|
||||
// 门禁 toast 之外不应出现协议弹窗(出现说明执行越过了门禁)。
|
||||
let agreementAlert = app.alerts["请先阅读并同意协议"]
|
||||
XCTAssertFalse(agreementAlert.waitForExistence(timeout: 2), "点击越过了门禁(出现协议弹窗)")
|
||||
capture(app, "b1-block-after")
|
||||
}
|
||||
|
||||
func testB2BlockOtherLogins() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("B2 注入启动·第三方登录门禁(微信/QQ/Apple/Weread)")
|
||||
try launchApp(app, injected: true)
|
||||
var state = waitLoginOrHome(app)
|
||||
if state == "home", navigateToLoginFromHome(app, allowRelaunch: false) { state = "login" }
|
||||
guard state == "login" else {
|
||||
try skipAndCapture("B2 登录页不可达(状态 \(state),游客入口缺失)")
|
||||
}
|
||||
selectAgreementIfNeeded(app)
|
||||
capture(app, "b2-login-page")
|
||||
// v3 登录页树:第三方按钮为纯图片,label 即图片名(rd login wechat/qq/apple/wjOauth2)。
|
||||
var tapped = 0
|
||||
for label in ["rd login wechat", "rd login qq", "rd login apple", "rd login wjOauth2"] {
|
||||
let entry = app.buttons[label].firstMatch
|
||||
guard entry.waitForExistence(timeout: 3), entry.isHittable else { continue }
|
||||
entry.tap()
|
||||
tapped += 1
|
||||
step("B2 点击第三方入口「\(label)」")
|
||||
assertToast(app, text: blockLoginToast, label: "b2-block-\(label)")
|
||||
}
|
||||
if tapped == 0 {
|
||||
capture(app, "b2-no-third-party-buttons")
|
||||
try skipAndCapture("登录页未暴露可识别的第三方登录按钮(见 b2-login-page 树)")
|
||||
}
|
||||
step("B2 完成,拦截入口数=\(tapped)")
|
||||
}
|
||||
|
||||
// MARK: - C 放行相位(干净启动·真实登录)
|
||||
|
||||
func testC1AllowPasswordLogin() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("C1 干净启动·密码登录放行")
|
||||
try launchApp(app, injected: false)
|
||||
let bootState = waitLoginOrHome(app)
|
||||
var loginReached = bootState == "login"
|
||||
if !loginReached, bootState == "home" {
|
||||
// 游客态(home ≠ 已登录)也从「我的」页进入登录页做真实登录。
|
||||
loginReached = navigateToLoginFromHome(app)
|
||||
}
|
||||
if !loginReached {
|
||||
step("C1 登录页不可达且我的页无「登录/注册」(已登录态),放行以启动期零拦截与既有会话为证")
|
||||
capture(app, "c1-already-home")
|
||||
return
|
||||
}
|
||||
capture(app, "c1-login-page")
|
||||
selectAgreementIfNeeded(app)
|
||||
let submit = app.buttons["login_submit_button"]
|
||||
XCTAssertTrue(submit.waitForExistence(timeout: 10), "未找到登录提交按钮")
|
||||
if !submit.isEnabled {
|
||||
// 提交钮不可用才尝试补输入(v5d 教训:验证码框存在不代表必填,
|
||||
// 盲填占位值反而制造服务端拒绝)。先补图形验证码占位值,再退化到账号框刷新。
|
||||
let captcha = app.textFields.containing(NSPredicate(format: "placeholderValue CONTAINS '验证码'")).firstMatch
|
||||
if captcha.exists {
|
||||
captcha.tap()
|
||||
captcha.typeText("1111")
|
||||
step("C1 提交钮不可用,已补图形验证码占位值 isEnabled=\(submit.isEnabled)")
|
||||
}
|
||||
if !submit.isEnabled {
|
||||
let account = app.textFields["login_phone_input"].firstMatch
|
||||
if account.exists { account.tap(); account.typeText("1") }
|
||||
step("C1 仍不可用,已触发账号输入刷新 isEnabled=\(submit.isEnabled)")
|
||||
}
|
||||
}
|
||||
capture(app, "c1-before-submit")
|
||||
submit.tap()
|
||||
// 放行判定(v6 修订):核心断言 = 门禁 toast 不出现(门禁放行)。
|
||||
// 业务进展尽力而为留证:DEBUG 预填账号的图形验证码无法自动识别,服务端
|
||||
// 拒绝时停留登录页属业务侧限制而非门禁问题(v5e 留证:干净提交后门禁
|
||||
// toast 与协议弹窗均未出现)。登录态若未建立,D1/E1 以游客守卫跳过。
|
||||
let gateToast = app.staticTexts[blockLoginToast].firstMatch
|
||||
XCTAssertFalse(gateToast.waitForExistence(timeout: 6), "干净环境出现门禁 toast(误拦截)")
|
||||
let home = app.otherElements["home_page_anchor"]
|
||||
let agreementAlert = app.alerts["请先阅读并同意协议"]
|
||||
let progress = home.waitForExistence(timeout: 45)
|
||||
|| agreementAlert.waitForExistence(timeout: 5)
|
||||
step("C1 门禁放行成立;业务进展标记=\(progress)(验证码服务端拒绝属业务侧限制)")
|
||||
capture(app, "c1-after-login-attempt")
|
||||
}
|
||||
|
||||
// MARK: - D/E 拦截相位(注入启动·VIP 与激活入口)
|
||||
|
||||
func testD1BlockVipPurchase() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("D1 注入启动·VIP 购买门禁")
|
||||
try launchApp(app, injected: true)
|
||||
try waitHomeStable(app, timeout: 90)
|
||||
let vipTab = app.tabBars.buttons["会员"].firstMatch
|
||||
XCTAssertTrue(vipTab.waitForExistence(timeout: 10), "未找到「会员」页签")
|
||||
vipTab.tap()
|
||||
// v3 树:会员页用户区游客显示「游客」——登录态缺失时购买被业务游客检查
|
||||
// 拦在 sendPayVip 门禁之前,skip 留证而不误判门禁失效。
|
||||
_ = app.staticTexts["游客"].waitForExistence(timeout: 5)
|
||||
if app.staticTexts["游客"].firstMatch.exists {
|
||||
capture(app, "d1-guest-state")
|
||||
try skipAndCapture("会员页为游客态(C1 未建立登录态),VIP 门禁需登录后重跑")
|
||||
}
|
||||
// v2 树:购买按钮为富文本 label(如「立即购买 · ¥6.00 100.00」),已会员时为「立即续费 …」。
|
||||
let buyPred = NSPredicate(format: "label BEGINSWITH '立即购买' OR label BEGINSWITH '立即续费'")
|
||||
let buyBtn = app.buttons.containing(buyPred).firstMatch
|
||||
XCTAssertTrue(buyBtn.waitForExistence(timeout: 15), "会员页未出现购买按钮(见 d1 勘察树)")
|
||||
sleep(2)
|
||||
dismissPopups(app)
|
||||
capture(app, "d1-vip-page")
|
||||
// 先勾选 VIP 协议(未勾选时点购买先弹协议提示,越不过门禁汇合点)。
|
||||
let checkbox = app.buttons["rd vip checkbox unselect"].firstMatch
|
||||
if checkbox.exists, checkbox.isHittable {
|
||||
checkbox.tap()
|
||||
step("D1 已勾选 VIP 协议")
|
||||
} else {
|
||||
capture(app, "d1-checkbox-missing")
|
||||
}
|
||||
buyBtn.tap()
|
||||
step("D1 点击购买按钮「\(buyBtn.label)」")
|
||||
assertToast(app, text: blockVipToast, label: "d1-block-vip")
|
||||
}
|
||||
|
||||
func testE1BlockActivation() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("E1 注入启动·激活码门禁")
|
||||
try launchApp(app, injected: true)
|
||||
try waitHomeStable(app, timeout: 90)
|
||||
let mineTab = app.tabBars.buttons["我的"].firstMatch
|
||||
XCTAssertTrue(mineTab.waitForExistence(timeout: 10), "未找到「我的」页签")
|
||||
mineTab.tap()
|
||||
sleep(2)
|
||||
dismissPopups(app)
|
||||
capture(app, "e1-mine-page")
|
||||
// 激活入口探测(标签以勘察树为准)。
|
||||
var activationEntered = false
|
||||
for keyword in ["激活码", "激活"] {
|
||||
let entryBtn = app.buttons.containing(NSPredicate(format: "label CONTAINS %@", keyword)).firstMatch
|
||||
let entryText = app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", keyword)).firstMatch
|
||||
if entryBtn.exists { entryBtn.tap(); activationEntered = true; step("E1 点击「\(keyword)」按钮入口"); break }
|
||||
if entryText.exists { entryText.tap(); activationEntered = true; step("E1 点击「\(keyword)」文本入口"); break }
|
||||
}
|
||||
guard activationEntered else {
|
||||
capture(app, "e1-no-activation-entry")
|
||||
try skipAndCapture("「我的」页未找到激活入口,需按勘察树修正导航")
|
||||
}
|
||||
sleep(2)
|
||||
// v3 教训:游客点「激活码」被带到登录页(激活需登录态)——先判定落点。
|
||||
if app.otherElements["login_page_anchor"].waitForExistence(timeout: 5) {
|
||||
capture(app, "e1-guest-to-login")
|
||||
try skipAndCapture("激活入口要求登录态(C1 未建立登录会话),激活门禁需登录后重跑")
|
||||
}
|
||||
capture(app, "e1-activation-page")
|
||||
// 激活码输入(被拦截环境填占位值即可,请求不会发出)。
|
||||
let codeField = (app.textFields.firstMatch.exists ? app.textFields : app.secureTextFields).firstMatch
|
||||
if codeField.exists {
|
||||
codeField.tap()
|
||||
codeField.typeText("1")
|
||||
}
|
||||
var activated = false
|
||||
for label in ["立即激活", "激活", "确定"] {
|
||||
let button = app.buttons[label].firstMatch
|
||||
if button.exists, button.isHittable { button.tap(); activated = true; step("E1 点击激活按钮「\(label)」"); break }
|
||||
}
|
||||
XCTAssertTrue(activated, "激活页未找到激活按钮(见 e1-activation-page 树)")
|
||||
assertToast(app, text: blockActivationToast, label: "e1-block-activation")
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 3);
|
||||
void *sdk = dlopen(argv[1], RTLD_NOW); if (!sdk) { puts(dlerror()); return 1; }
|
||||
int (*io)(const char *,const char *,size_t) = dlsym(sdk,"archive_fixture_io");
|
||||
int (*check)(void) = dlsym(sdk,"ig_archive_check");
|
||||
uint64_t (*counter)(unsigned) = dlsym(sdk,"ig_archive_counter");
|
||||
assert(io && check && counter && check() == 0);
|
||||
assert(!io(argv[2],"abcdef",6));
|
||||
for (unsigned i=0;i<4;i++) assert(counter(i*3)>0 && counter(i*3)==counter(i*3+1) && !counter(i*3+2));
|
||||
const struct mach_header_64 *header = NULL;
|
||||
intptr_t slide = 0;
|
||||
for (uint32_t i=0;i<_dyld_image_count();i++) {
|
||||
const char *name = _dyld_get_image_name(i);
|
||||
if (name && strstr(name,"/SSZipArchive.framework/SSZipArchive")) {
|
||||
header=(const void *)_dyld_get_image_header(i); slide=_dyld_get_image_vmaddr_slide(i); break;
|
||||
}
|
||||
}
|
||||
assert(header);
|
||||
const struct symtab_command *symtab=NULL;
|
||||
const struct dysymtab_command *dysymtab=NULL;
|
||||
uintptr_t base=0;
|
||||
const uint8_t *command=(const void *)(header+1);
|
||||
for (uint32_t i=0;i<header->ncmds;i++) {
|
||||
const struct load_command *lc=(const void *)command;
|
||||
if (lc->cmd==LC_SYMTAB) symtab=(const void *)lc;
|
||||
if (lc->cmd==LC_DYSYMTAB) dysymtab=(const void *)lc;
|
||||
if (lc->cmd==LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg=(const void *)lc;
|
||||
if (!strcmp(seg->segname,SEG_LINKEDIT)) base=slide+seg->vmaddr-seg->fileoff;
|
||||
}
|
||||
command+=lc->cmdsize;
|
||||
}
|
||||
assert(base && symtab && dysymtab);
|
||||
const struct nlist_64 *symbols=(const void *)(base+symtab->symoff);
|
||||
const char *strings=(const void *)(base+symtab->stroff);
|
||||
const uint32_t *indirect=(const void *)(base+dysymtab->indirectsymoff);
|
||||
uintptr_t *slot=NULL;
|
||||
command=(const void *)(header+1);
|
||||
for (uint32_t i=0;i<header->ncmds;i++) {
|
||||
const struct load_command *lc=(const void *)command;
|
||||
if (lc->cmd==LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg=(const void *)lc;
|
||||
const struct section_64 *sections=(const void *)(seg+1);
|
||||
for (uint32_t j=0;j<seg->nsects;j++) {
|
||||
const struct section_64 *s=sections+j;
|
||||
if ((s->flags&SECTION_TYPE)!=S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
for (uint64_t k=0;k<s->size/8;k++) {
|
||||
uint32_t n=indirect[s->reserved1+k];
|
||||
if (n&(INDIRECT_SYMBOL_LOCAL|INDIRECT_SYMBOL_ABS)) continue;
|
||||
if (!strcmp(strings+symbols[n].n_un.n_strx,"_ig_a0")) slot=(void *)(slide+s->addr+k*8);
|
||||
}
|
||||
}
|
||||
}
|
||||
command+=lc->cmdsize;
|
||||
}
|
||||
assert(slot);
|
||||
uintptr_t original=*slot;
|
||||
vm_address_t page=(uintptr_t)slot & ~((uintptr_t)vm_page_size-1);
|
||||
assert(vm_protect(mach_task_self(),page,vm_page_size,0,VM_PROT_READ|VM_PROT_WRITE|VM_PROT_COPY)==KERN_SUCCESS);
|
||||
*slot=(uintptr_t)dlsym(RTLD_DEFAULT,"fopen");
|
||||
assert(check()==1);
|
||||
FILE *(*close_entry)(const char *,const char *) = dlsym(sdk,"ig_a0");
|
||||
assert(close_entry && !close_entry("unused","rb") && errno==EACCES);
|
||||
*slot=original;
|
||||
assert(check()==0);
|
||||
assert(!io(argv[2],"ghijkl",6)); unlink(argv[2]);
|
||||
puts("真实 chained binding 转发、GOT 篡改检测及拒绝、恢复均通过");
|
||||
return 0;
|
||||
}
|
||||
Vendored
+59
@@ -0,0 +1,59 @@
|
||||
#include "dispatch/IGArchiveGuard.h"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static unsigned fake_calls;
|
||||
static FILE *fake_open(const char *a, const char *b) { (void)a; (void)b; fake_calls++; return NULL; }
|
||||
static void semantics(void) {
|
||||
char path[] = "/tmp/ig-archive-XXXXXX";
|
||||
int fd = mkstemp(path); assert(fd >= 0); close(fd);
|
||||
errno = EDOM;
|
||||
FILE *out = ig_a0(path, "wb"); assert(out && errno == EDOM);
|
||||
assert(ig_a2("abcdef", 2, 3, out) == 3);
|
||||
assert(ig_a2("", 0, 4, out) == 0);
|
||||
assert(ig_a3(out) == 0);
|
||||
FILE *in = ig_a0(path, "rb"); assert(in);
|
||||
char buffer[16] = {0};
|
||||
assert(ig_a1(buffer, 2, 4, in) == 3);
|
||||
assert(!memcmp(buffer, "abcdef", 6) && feof(in) && !ferror(in));
|
||||
assert(ig_a1(buffer, 1, 1, in) == 0);
|
||||
assert(ig_a3(in) == 0); unlink(path);
|
||||
errno = 0; assert(!ig_a0(path, "rb") && errno == ENOENT);
|
||||
FILE *system = tmpfile(); assert(system);
|
||||
assert(ig_a2("abc", 1, 3, system) == 3);
|
||||
rewind(system); assert(ig_a1(buffer, 1, 3, system) == 3); assert(ig_a3(system) == 0);
|
||||
assert(ig_archive_check() == 0);
|
||||
}
|
||||
static void *thread_run(void *ctx) { (void)ctx; semantics(); return NULL; }
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
if (!strcmp(argv[1], "semantics")) semantics();
|
||||
else if (!strcmp(argv[1], "threads")) {
|
||||
pthread_t t[6];
|
||||
for (unsigned i=0;i<6;i++) assert(!pthread_create(t+i,NULL,thread_run,NULL));
|
||||
for (unsigned i=0;i<6;i++) assert(!pthread_join(t[i],NULL));
|
||||
} else if (!strcmp(argv[1], "tamper")) {
|
||||
ig_archive_test_override(0, (void *)fake_open);
|
||||
assert(ig_a0("unused", "rb") == NULL && errno == EACCES && !fake_calls);
|
||||
errno = EDOM; assert(ig_archive_check() == 1 && errno == EDOM);
|
||||
assert(ig_archive_counter(0) == 1 && ig_archive_counter(1) == 0 && ig_archive_counter(2) == 1);
|
||||
} else if (!strcmp(argv[1], "reentry")) {
|
||||
ig_archive_test_reentry(1);
|
||||
assert(!ig_a0("unused", "rb") && errno == EDEADLK);
|
||||
assert(ig_archive_check() == -1);
|
||||
ig_archive_test_reentry(0); semantics();
|
||||
} else if (!strcmp(argv[1], "rejection")) {
|
||||
FILE *f = tmpfile(); assert(f);
|
||||
char b;
|
||||
for (unsigned i=1;i<4;i++) ig_archive_test_override(i, (void *)fake_open);
|
||||
assert(ig_a1(&b,1,1,f)==0 && errno==EACCES);
|
||||
assert(ig_a2(&b,1,1,f)==0 && errno==EACCES);
|
||||
assert(ig_a3(f)==EOF && errno==EACCES);
|
||||
assert(!fake_calls); fclose(f);
|
||||
} else assert(0);
|
||||
return 0;
|
||||
}
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
/* 动态 SDK fixture:必须通过真实的四个导入完成一次 stdio 往返。 */
|
||||
int archive_fixture_io(const char *path, const char *bytes, size_t count) {
|
||||
FILE *file = fopen(path, "wb");
|
||||
if (!file) return 1;
|
||||
size_t written = fwrite(bytes, 1, count, file);
|
||||
if (fclose(file) || written != count) return 2;
|
||||
file = fopen(path, "rb");
|
||||
if (!file) return 3;
|
||||
char buffer[64] = {0};
|
||||
size_t read = fread(buffer, 1, sizeof(buffer), file);
|
||||
int closed = fclose(file);
|
||||
return closed || read != count || memcmp(bytes, buffer, count) ? 4 : 0;
|
||||
}
|
||||
Vendored
+159
@@ -0,0 +1,159 @@
|
||||
/* 仅宿主测试进程内操作;不修改系统函数代码。 */
|
||||
#include "IGDefender.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include "anti_hook/IGObjCBaseline.h"
|
||||
#include "anti_debug/IGAntiDebug.h"
|
||||
#include "anti_frida/IGAntiInject.h"
|
||||
#include <dlfcn.h>
|
||||
#include <objc/objc.h>
|
||||
#include <objc/runtime.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
|
||||
typedef struct { int reasons[256]; int detected; int unavailable; } Findings;
|
||||
static int collect(const IGFinding *f, void *context) {
|
||||
Findings *out = context;
|
||||
if (f->reason >= 0 && f->reason < 256) out->reasons[f->reason]++;
|
||||
if (f->status == IG_DETECTED) out->detected++;
|
||||
if (f->status == IG_UNAVAILABLE) out->unavailable++;
|
||||
printf("status=%d reason=%d subject=%s evidence=%s\n",
|
||||
f->status, f->reason, f->subject, f->evidence);
|
||||
return 0;
|
||||
}
|
||||
static int fake_getpid(void) { return 123; }
|
||||
/* 函数地址表达式确保本测试镜像包含 getpid 的 GOT 引用。 */
|
||||
__attribute__((noinline)) static void *getpid_address(void) { return (void *)getpid; }
|
||||
|
||||
/* ---- ObjC IMP 基线 fixture:运行期创建类,两条实现可互换 ---- */
|
||||
static int imp_original(void *self, SEL _cmd) { (void)self; (void)_cmd; return 1; }
|
||||
static int imp_replaced(void *self, SEL _cmd) { (void)self; (void)_cmd; return 2; }
|
||||
static Class make_fixture_class(void) {
|
||||
Class 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;
|
||||
}
|
||||
objc_registerClassPair(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
static void **getpid_slot(void) {
|
||||
const struct mach_header_64 *h = (const void *)_dyld_get_image_header(0);
|
||||
intptr_t slide = _dyld_get_image_vmaddr_slide(0);
|
||||
const struct segment_command_64 *le = NULL;
|
||||
const struct symtab_command *sy = NULL;
|
||||
const struct dysymtab_command *dy = NULL;
|
||||
const unsigned char *p = (const void *)(h+1);
|
||||
for (unsigned i=0; i<h->ncmds; i++) {
|
||||
const struct load_command *lc=(const void *)p;
|
||||
if (lc->cmd==LC_SEGMENT_64 && !strcmp(((const struct segment_command_64 *)p)->segname,"__LINKEDIT")) le=(const void *)p;
|
||||
if (lc->cmd==LC_SYMTAB) sy=(const void *)p;
|
||||
if (lc->cmd==LC_DYSYMTAB) dy=(const void *)p;
|
||||
p+=lc->cmdsize;
|
||||
}
|
||||
if (!le || !sy || !dy) return NULL;
|
||||
uintptr_t base=slide+le->vmaddr-le->fileoff;
|
||||
const struct nlist_64 *symbols=(const void *)(base+sy->symoff);
|
||||
const char *strings=(const void *)(base+sy->stroff);
|
||||
const uint32_t *indirect=(const void *)(base+dy->indirectsymoff);
|
||||
p=(const void *)(h+1);
|
||||
for (unsigned i=0; i<h->ncmds; i++) {
|
||||
const struct load_command *lc=(const void *)p;
|
||||
if (lc->cmd==LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg=(const void *)p;
|
||||
const struct section_64 *s=(const void *)(seg+1);
|
||||
for (unsigned j=0; j<seg->nsects; j++) {
|
||||
if ((s[j].flags & SECTION_TYPE)!=S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
for (unsigned k=0; k<s[j].size/sizeof(void *); k++) {
|
||||
uint32_t n=indirect[s[j].reserved1+k];
|
||||
if (n & (INDIRECT_SYMBOL_LOCAL|INDIRECT_SYMBOL_ABS)) continue;
|
||||
if (!strcmp(strings+symbols[n].n_un.n_strx,"_getpid"))
|
||||
return (void **)(slide+s[j].addr)+k;
|
||||
}
|
||||
}
|
||||
}
|
||||
p+=lc->cmdsize;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc<2) return 2;
|
||||
Findings f={0};
|
||||
if (!strcmp(argv[1],"clean")) {
|
||||
int hits=ig_defender_scan(NULL,0,collect,&f);
|
||||
return hits!=f.detected || f.detected || f.unavailable;
|
||||
}
|
||||
if (!strcmp(argv[1],"unresolved")) {
|
||||
const char *names[]={"IG_fixture_symbol_that_does_not_exist_123"};
|
||||
int hits=ig_anti_hook_check(names,1,collect,&f);
|
||||
return hits || f.unavailable!=1 || f.reasons[IG_REASON_SYMBOL_UNRESOLVED]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"verify")) {
|
||||
if (ig_verify_function(NULL,"null",collect,&f)!=IG_UNAVAILABLE) return 3;
|
||||
if (ig_verify_function(getpid_address(),"getpid",collect,&f)!=IG_CLEAR) return 4;
|
||||
return ig_verify_function((void *)fake_getpid,"local_fixture",collect,&f)!=IG_DETECTED
|
||||
|| f.reasons[IG_REASON_SYMBOL_PROVENANCE]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"env")) {
|
||||
setenv("DYLD_INSERT_LIBRARIES","/tmp/ig_fixture_a:/tmp/ig_fixture_b",1);
|
||||
ig_anti_inject_check(NULL,collect,&f);
|
||||
unsetenv("DYLD_INSERT_LIBRARIES");
|
||||
return f.reasons[IG_REASON_DYLD_INSERT]!=2;
|
||||
}
|
||||
if (!strcmp(argv[1],"image")) {
|
||||
if (argc<3 || !dlopen(argv[2],RTLD_NOW)) return 5;
|
||||
ig_anti_inject_check(NULL,collect,&f);
|
||||
return f.reasons[IG_REASON_INJECTED_IMAGE]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"got")) {
|
||||
const char *names[]={"getpid"};
|
||||
if (!getpid_address() || ig_anti_hook_check(names,1,collect,&f)!=0) return 6;
|
||||
void **slot=getpid_slot();
|
||||
if (!slot) { fprintf(stderr,"未找到测试 GOT 槽\n"); return 7; }
|
||||
void *original=*slot;
|
||||
vm_size_t size=getpagesize();
|
||||
vm_address_t page=(uintptr_t)slot & ~(size-1);
|
||||
if (vm_protect(mach_task_self(),page,size,0,VM_PROT_READ|VM_PROT_WRITE|VM_PROT_COPY)!=KERN_SUCCESS) return 8;
|
||||
*slot=(void *)fake_getpid;
|
||||
int hits=ig_anti_hook_check(names,1,collect,&f);
|
||||
*slot=original;
|
||||
return hits!=1 || f.reasons[IG_REASON_GOT_REBIND]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"debugger")) {
|
||||
/* 正常(无调试器)环境:clear 且 sysctl 可判定。
|
||||
* 正向(P_TRACED 命中)由 lldb 场景验证,docs/12 已实测。 */
|
||||
ig_anti_debug_check(collect,&f);
|
||||
return f.detected || f.unavailable;
|
||||
}
|
||||
if (!strcmp(argv[1],"objc-clean")) {
|
||||
if (!make_fixture_class()) return 9;
|
||||
const IGObjCWatch watch[] = { { "IGFixtureHookTarget", "value" } };
|
||||
if (ig_objc_baseline_capture(watch,1)!=1) return 10;
|
||||
/* 未登记的方法在 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);
|
||||
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)。 */
|
||||
class_replaceMethod(c, sel_registerName("value"), (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 2;
|
||||
}
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
/* 独立诊断进程:只在自身进程测试,不连接业务、不改系统代码。 */
|
||||
#import <Foundation/Foundation.h>
|
||||
#include "IGDefender.h"
|
||||
#include <stdio.h>
|
||||
|
||||
int ig_dispatch_fixture_main(int argc, char **argv);
|
||||
static int findings, unavailable;
|
||||
static int collect(const IGFinding *f, void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->status==IG_DETECTED) findings++;
|
||||
if (f->status==IG_UNAVAILABLE) unavailable++;
|
||||
NSLog(@"IG_DEVICE_FINDING status=%d reason=%d subject=%s evidence=%s",
|
||||
f->status,f->reason,f->subject,f->evidence);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc,char **argv) {
|
||||
(void)argc;(void)argv;
|
||||
@autoreleasepool {
|
||||
NSLog(@"IG_DEVICE_MAIN");
|
||||
const char *modes[]={"semantics","short-write","eintr","threads","reentry","resolver","prologue","tamper"};
|
||||
int hits=ig_defender_scan(NSBundle.mainBundle.bundlePath.UTF8String,0,collect,NULL);
|
||||
NSLog(@"IG_DEVICE_BASELINE detected=%d unavailable=%d hits=%d",findings,unavailable,hits);
|
||||
for (unsigned i=0;i<sizeof(modes)/sizeof(modes[0]);i++) {
|
||||
char *args[]={"dispatch-device",(char *)modes[i],NULL};
|
||||
int rc=ig_dispatch_fixture_main(2,args);
|
||||
NSLog(@"IG_DEVICE_CASE %s %s",modes[i],rc==0 ? "PASS" : "FAIL");
|
||||
if (rc) return rc;
|
||||
}
|
||||
NSLog(@"IG_DEVICE_SUITE PASS cases=8 baseline_detected=%d baseline_unavailable=%d",findings,unavailable);
|
||||
/* 诊断进程退出便于 console 收集退出码;不编入业务 App。 */
|
||||
return findings || unavailable ? 3 : 0;
|
||||
}
|
||||
}
|
||||
Vendored
+131
@@ -0,0 +1,131 @@
|
||||
#include "dispatch/IGDispatch.h"
|
||||
#include "resolve/IGResolve.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int early_ok;
|
||||
__attribute__((constructor)) static void early(void) {
|
||||
#ifdef IG_EXPECT_INIT_FAILURE
|
||||
early_ok=1;
|
||||
#else
|
||||
int fd=open("/dev/null",O_WRONLY);
|
||||
early_ok=fd>=0 && IG_dispatch_write(fd,"early",5)==5 && IG_dispatch_close(fd)==0;
|
||||
#endif
|
||||
}
|
||||
void *ig_fixture_missing_resolve(void *handle, const char *name) { (void)handle; (void)name; return NULL; }
|
||||
static int reasons[256], unavailable;
|
||||
static int collect(const IGFinding *f,void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->reason>=0 && f->reason<256) reasons[f->reason]++;
|
||||
if (f->status==IG_UNAVAILABLE) unavailable++;
|
||||
return 0;
|
||||
}
|
||||
static int fake_close(int fd) { (void)fd; abort(); }
|
||||
static void *writer(void *ctx) {
|
||||
(void)ctx;
|
||||
int fd=open("/dev/null",O_WRONLY);
|
||||
assert(fd>=0);
|
||||
for (int i=0;i<100;i++) assert(IG_dispatch_write(fd,"abc",3)==3);
|
||||
assert(IG_dispatch_close(fd)==0);
|
||||
return NULL;
|
||||
}
|
||||
static void signal_handler(int sig) { (void)sig; }
|
||||
static pthread_t main_thread;
|
||||
static void *interruptor(void *ctx) { (void)ctx; usleep(30000); pthread_kill(main_thread,SIGUSR1); return NULL; }
|
||||
|
||||
int main(int argc,char **argv) {
|
||||
assert(argc==2 && early_ok);
|
||||
if (!strcmp(argv[1],"observation")) {
|
||||
#ifdef IG_OBSERVATION
|
||||
IGDispatchObservation before=ig_dispatch_observation();
|
||||
errno=0; assert(IG_dispatch_write(-1,"x",1)==-1 && errno==EBADF);
|
||||
errno=0; assert(IG_dispatch_close(-1)==-1 && errno==EBADF);
|
||||
IGDispatchObservation after=ig_dispatch_observation();
|
||||
assert(after.write_attempted==before.write_attempted+1);
|
||||
assert(after.write_dispatched==before.write_dispatched+1);
|
||||
assert(after.close_attempted==before.close_attempted+1);
|
||||
assert(after.close_dispatched==before.close_dispatched+1);
|
||||
ig_dispatch_test_override(1,(void *)fake_close);
|
||||
assert(IG_dispatch_close(-1)==-1 && errno==EACCES);
|
||||
IGDispatchObservation rejected=ig_dispatch_observation();
|
||||
assert(rejected.close_attempted==after.close_attempted+1);
|
||||
assert(rejected.close_dispatched==after.close_dispatched);
|
||||
#else
|
||||
return 2;
|
||||
#endif
|
||||
} else if (!strcmp(argv[1],"init-failure")) {
|
||||
assert(IG_dispatch_write(-1,"x",1)==-1 && errno==ENOSYS);
|
||||
assert(IG_dispatch_close(-1)==-1 && errno==ENOSYS);
|
||||
assert(ig_dispatch_check(collect,NULL)==0 && unavailable==2);
|
||||
assert(reasons[IG_REASON_DISPATCH_UNAVAILABLE]==2);
|
||||
} else if (!strcmp(argv[1],"semantics")) {
|
||||
assert(ig_dispatch_check(collect,NULL)==0 && unavailable==0);
|
||||
errno=0; assert(IG_dispatch_write(-1,"x",1)==-1 && errno==EBADF);
|
||||
errno=0; assert(IG_dispatch_close(-1)==-1 && errno==EBADF);
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
errno=EDOM; assert(IG_dispatch_write(p[1],"abc",3)==3 && errno==EDOM);
|
||||
char b[4]={0}; assert(read(p[0],b,3)==3 && !memcmp(b,"abc",3));
|
||||
assert(IG_dispatch_close(p[1])==0 && IG_dispatch_close(p[0])==0);
|
||||
} else if (!strcmp(argv[1],"short-write")) {
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
assert(fcntl(p[1],F_SETFL,O_NONBLOCK)==0);
|
||||
const size_t count=1024*1024;
|
||||
char *bytes=calloc(count,1);assert(bytes);
|
||||
ssize_t n=IG_dispatch_write(p[1],bytes,count);
|
||||
assert(n>0 && n<(ssize_t)count);
|
||||
while (IG_dispatch_write(p[1],bytes,count)>0) {}
|
||||
assert(errno==EAGAIN);
|
||||
IG_dispatch_close(p[1]); IG_dispatch_close(p[0]);
|
||||
free(bytes);
|
||||
} else if (!strcmp(argv[1],"eintr")) {
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
assert(fcntl(p[1],F_SETFL,O_NONBLOCK)==0);
|
||||
char bytes[4096]={0}; while (write(p[1],bytes,sizeof(bytes))>0) {}
|
||||
assert(errno==EAGAIN && fcntl(p[1],F_SETFL,0)==0);
|
||||
struct sigaction action={0};action.sa_handler=signal_handler;sigemptyset(&action.sa_mask);
|
||||
assert(sigaction(SIGUSR1,&action,NULL)==0);
|
||||
main_thread=pthread_self();pthread_t thread;
|
||||
assert(pthread_create(&thread,NULL,interruptor,NULL)==0);
|
||||
assert(IG_dispatch_write(p[1],bytes,sizeof(bytes))==-1 && errno==EINTR);
|
||||
pthread_join(thread,NULL);IG_dispatch_close(p[1]);IG_dispatch_close(p[0]);
|
||||
} else if (!strcmp(argv[1],"threads")) {
|
||||
pthread_t threads[8];
|
||||
for (unsigned i=0;i<8;i++) assert(pthread_create(&threads[i],NULL,writer,NULL)==0);
|
||||
for (unsigned i=0;i<8;i++) pthread_join(threads[i],NULL);
|
||||
} else if (!strcmp(argv[1],"tamper")) {
|
||||
ig_dispatch_test_override(1,(void *)fake_close);
|
||||
errno=0; assert(IG_dispatch_close(-1)==-1 && errno==EACCES);
|
||||
assert(ig_dispatch_check(collect,NULL)==1 && reasons[IG_REASON_DISPATCH_TAMPER]==1);
|
||||
} else if (!strcmp(argv[1],"reentry")) {
|
||||
ig_dispatch_test_reentry(1);
|
||||
assert(IG_dispatch_close(-1)==-1 && errno==EDEADLK);
|
||||
ig_dispatch_test_reentry(0);
|
||||
} else if (!strcmp(argv[1],"resolver")) {
|
||||
unsigned char encoded[300];memset(encoded,'x',sizeof(encoded));char out[4];
|
||||
assert(!ig_decrypt(encoded,1,out,0));assert(!ig_decrypt(NULL,1,out,sizeof(out)));
|
||||
assert(!ig_decrypt(encoded,4,out,sizeof(out)) && out[0]==0);
|
||||
encoded[0]=IG_ENC_KEY;assert(!ig_decrypt(encoded,1,out,sizeof(out)));
|
||||
assert(ig_resolve_verified(NULL,encoded,300,NULL,NULL).status==IG_UNAVAILABLE);
|
||||
const char *name="IG_missing_symbol_774444";
|
||||
for (unsigned i=0;i<strlen(name);i++) encoded[i]=name[i]^IG_ENC_KEY;
|
||||
assert(ig_resolve_verified(NULL,encoded,strlen(name),collect,NULL).status==IG_UNAVAILABLE);
|
||||
assert(reasons[IG_REASON_SYMBOL_UNRESOLVED]==1);
|
||||
assert(ig_verify_function((void *)1,"invalid",collect,NULL)==IG_UNAVAILABLE);
|
||||
assert(reasons[IG_REASON_VERIFICATION_UNAVAILABLE]==1);
|
||||
} else if (!strcmp(argv[1],"prologue")) {
|
||||
assert(ig_arm64_suspicious_prologue(0x14000001,0));
|
||||
assert(ig_arm64_suspicious_prologue(0x58000050,0xd61f0200));
|
||||
assert(!ig_arm64_suspicious_prologue(0x58000050,0xd61f0220));
|
||||
assert(!ig_arm64_suspicious_prologue(0x18000050,0xd61f0200));
|
||||
assert(!ig_arm64_suspicious_prologue(0xd503245f,0xd65f03c0));
|
||||
} else return 2;
|
||||
return 0;
|
||||
}
|
||||
Vendored
+112
@@ -0,0 +1,112 @@
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern FILE *sdk_open(const char *path, const char *mode);
|
||||
|
||||
#ifdef IG_TEST_ALL_BRIDGES
|
||||
extern int sdk_fclose(FILE *);
|
||||
extern size_t sdk_fread(void *, size_t, size_t, FILE *);
|
||||
extern size_t sdk_fwrite(const void *, size_t, size_t, FILE *);
|
||||
extern ssize_t sdk_read(int, void *, size_t);
|
||||
extern ssize_t sdk_write(int, const void *, size_t);
|
||||
extern int sdk_close(int);
|
||||
#define fclose sdk_fclose
|
||||
#define fread sdk_fread
|
||||
#define fwrite sdk_fwrite
|
||||
|
||||
static void exercise_posix(void) {
|
||||
int descriptors[2];
|
||||
char buffer[4096] = {0};
|
||||
assert(pipe(descriptors) == 0);
|
||||
assert(sdk_write(descriptors[1], "X", 1) == 1);
|
||||
assert(sdk_read(descriptors[0], buffer, sizeof(buffer)) == 1);
|
||||
assert(buffer[0] == 'X');
|
||||
assert(sdk_write(descriptors[1], buffer, 0) == 0);
|
||||
assert(sdk_read(descriptors[0], buffer, 0) == 0);
|
||||
assert(sdk_close(descriptors[1]) == 0);
|
||||
assert(sdk_read(descriptors[0], buffer, sizeof(buffer)) == 0);
|
||||
assert(sdk_close(descriptors[0]) == 0);
|
||||
assert(sdk_close(-1) == -1 && errno == EBADF);
|
||||
assert(sdk_read(-1, buffer, 1) == -1 && errno == EBADF);
|
||||
assert(sdk_write(-1, buffer, 1) == -1 && errno == EBADF);
|
||||
|
||||
assert(pipe(descriptors) == 0);
|
||||
int flags = fcntl(descriptors[1], F_GETFL);
|
||||
assert(flags >= 0 && fcntl(descriptors[1], F_SETFL, flags | O_NONBLOCK) == 0);
|
||||
ssize_t result = 0;
|
||||
for (int i = 0; i < 1024; ++i) {
|
||||
result = sdk_write(descriptors[1], buffer, sizeof(buffer));
|
||||
if (result < 0) break;
|
||||
}
|
||||
assert(result == -1 && (errno == EAGAIN || errno == EWOULDBLOCK));
|
||||
assert(sdk_close(descriptors[0]) == 0);
|
||||
assert(sdk_close(descriptors[1]) == 0);
|
||||
}
|
||||
#endif
|
||||
|
||||
static void exercise(const char *path) {
|
||||
FILE *file = sdk_open(path, "wb");
|
||||
assert(file != NULL);
|
||||
const unsigned char payload[] = {0, 1, 255, 10};
|
||||
assert(fwrite(payload, 1, sizeof(payload), file) == sizeof(payload));
|
||||
assert(fclose(file) == 0);
|
||||
|
||||
file = sdk_open(path, "ab");
|
||||
assert(file != NULL);
|
||||
assert(fwrite("X", 1, 1, file) == 1);
|
||||
assert(fclose(file) == 0);
|
||||
|
||||
file = sdk_open(path, "rb");
|
||||
assert(file != NULL);
|
||||
unsigned char result[8] = {0};
|
||||
assert(fread(result, 1, sizeof(result), file) == 5);
|
||||
assert(memcmp(result, payload, sizeof(payload)) == 0);
|
||||
assert(result[4] == 'X');
|
||||
assert(feof(file));
|
||||
assert(fclose(file) == 0);
|
||||
|
||||
file = sdk_open(path, "wb");
|
||||
assert(file != NULL);
|
||||
assert(fclose(file) == 0);
|
||||
file = sdk_open(path, "rb");
|
||||
assert(file != NULL);
|
||||
assert(fgetc(file) == EOF);
|
||||
assert(fclose(file) == 0);
|
||||
assert(unlink(path) == 0);
|
||||
|
||||
FILE *system_result = fopen(path, "rb");
|
||||
int system_error = errno;
|
||||
assert(system_result == NULL);
|
||||
errno = 0;
|
||||
FILE *bridge_result = sdk_open(path, "rb");
|
||||
int bridge_error = errno;
|
||||
assert(bridge_result == NULL);
|
||||
assert(bridge_error == system_error && bridge_error == ENOENT);
|
||||
}
|
||||
|
||||
static void *thread_test(void *path) {
|
||||
for (int i = 0; i < 20; ++i) exercise(path);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
#ifdef IG_TEST_ALL_BRIDGES
|
||||
exercise_posix();
|
||||
#endif
|
||||
pthread_t threads[4];
|
||||
char paths[4][4096];
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
int length = snprintf(paths[i], sizeof(paths[i]), "%s/文件-%d.bin", argv[1], i);
|
||||
assert(length > 0 && (size_t)length < sizeof(paths[i]));
|
||||
assert(pthread_create(&threads[i], NULL, thread_test, paths[i]) == 0);
|
||||
}
|
||||
for (int i = 0; i < 4; ++i) assert(pthread_join(threads[i], NULL) == 0);
|
||||
puts("file semantics: passed");
|
||||
return 0;
|
||||
}
|
||||
Vendored
+393
@@ -0,0 +1,393 @@
|
||||
/*
|
||||
* hook_device.m — 真机 HOOK 正向验证诊断进程(step11)。
|
||||
*
|
||||
* 目的:在非越狱真机的自身进程内构造四种受控攻击形态,验证 Defender 探针
|
||||
* 在真机环境(真实 dyld、真实内存权限、真实线程/镜像枚举)下能命中对应 reason:
|
||||
* 1. GOT 重绑定(fishhook 同款页权限改写自身 __got 槽)→ 期望 reason=102
|
||||
* 2. 蹦床序言(导出符号首指令为 B / LDR-literal+BR x16)→ 期望 reason=100+101
|
||||
* 3. frida 特征线程名(gum-js-loop)→ 期望 reason=203
|
||||
* 4. 容器外注入 dylib(Documents 下 dlopen;或宿主以 DYLD_INSERT_LIBRARIES 启动)
|
||||
* → 期望 reason=200(+201)(dlopen 路径)/ reason=202(插入库路径)
|
||||
*
|
||||
* 边界(如实声明):
|
||||
* - 不修改任何系统代码页(非越狱不可行):inline-hook 用例针对受控导出符号的
|
||||
* 真实代码字节验证「读取+分类」,不等同于对系统函数的真实 patch。
|
||||
* - 攻击操作(可写 GOT、装载模拟 dylib、特征线程名)只存在于本诊断源码,
|
||||
* 绝不编入业务库;诊断进程结束即退出,不触碰业务 App。
|
||||
*/
|
||||
#import <Foundation/Foundation.h>
|
||||
#include "IGDefender.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include "anti_hook/IGObjCBaseline.h"
|
||||
#include "anti_frida/IGAntiInject.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach/mach_time.h>
|
||||
#include <objc/objc.h>
|
||||
#include <objc/runtime.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* ---------- 发现收集:只记 DETECTED,逐条打日志 ---------- */
|
||||
|
||||
#define IG_MAXF 64
|
||||
static IGFinding g_findings[IG_MAXF];
|
||||
static int g_nfindings;
|
||||
|
||||
static int collect(const IGFinding *f, void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->status == IG_DETECTED && g_nfindings < IG_MAXF)
|
||||
g_findings[g_nfindings++] = *f;
|
||||
NSLog(@"IG_HOOK_FINDING status=%d reason=%d subject=%s evidence=%s",
|
||||
f->status, f->reason, f->subject, f->evidence);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void reset_findings(void) { g_nfindings = 0; }
|
||||
static const IGFinding *first_reason(int reason) {
|
||||
for (int i = 0; i < g_nfindings; ++i)
|
||||
if (g_findings[i].reason == reason) return &g_findings[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static const char *g_bundle; /* 主 bundle 路径,供各探针使用 */
|
||||
|
||||
/* 完整聚合扫描(anti_hook + 注入 + frida 线程)。 */
|
||||
static int scan_all(void) {
|
||||
reset_findings();
|
||||
return ig_defender_scan(g_bundle, 0, collect, NULL);
|
||||
}
|
||||
|
||||
/* ---------- 用例 1:GOT 重绑定(102)----------
|
||||
* fishhook 同款走法:定位主可执行文件 __got 中绑定 getpid 的槽,
|
||||
* 临时以 VM_PROT_COPY 改页为可写,写入本进程函数地址,恢复只读。
|
||||
* 只写自身进程数据页,不改任何代码。 */
|
||||
|
||||
static int ig_rebind_stub(void) { return 4242; } /* 指给 GOT 的假实现 */
|
||||
|
||||
static void **find_main_got_slot(const char *bare_name) {
|
||||
const struct mach_header_64 *mh =
|
||||
(const struct mach_header_64 *)_dyld_get_image_header(0);
|
||||
if (!mh || mh->magic != MH_MAGIC_64) return NULL;
|
||||
intptr_t slide = _dyld_get_image_vmaddr_slide(0);
|
||||
const struct segment_command_64 *linkedit = NULL;
|
||||
const struct symtab_command *symtab = NULL;
|
||||
const struct dysymtab_command *dysymtab = NULL;
|
||||
const uint8_t *cmd = (const uint8_t *)(mh + 1);
|
||||
for (uint32_t i = 0; i < mh->ncmds; ++i, cmd += ((const struct load_command *)cmd)->cmdsize) {
|
||||
const struct load_command *lc = (const struct load_command *)cmd;
|
||||
if (lc->cmd == LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;
|
||||
if (strcmp(seg->segname, SEG_LINKEDIT) == 0) linkedit = seg;
|
||||
} else if (lc->cmd == LC_SYMTAB) {
|
||||
symtab = (const struct symtab_command *)lc;
|
||||
} else if (lc->cmd == LC_DYSYMTAB) {
|
||||
dysymtab = (const struct dysymtab_command *)lc;
|
||||
}
|
||||
}
|
||||
if (!linkedit || !symtab || !dysymtab) return NULL;
|
||||
uintptr_t le_base = (uintptr_t)slide + linkedit->vmaddr - linkedit->fileoff;
|
||||
const struct nlist_64 *syms = (const struct nlist_64 *)(le_base + symtab->symoff);
|
||||
const char *strtab = (const char *)(le_base + symtab->stroff);
|
||||
const uint32_t *indirect = (const uint32_t *)(le_base + dysymtab->indirectsymoff);
|
||||
size_t nlen = strlen(bare_name);
|
||||
cmd = (const uint8_t *)(mh + 1);
|
||||
for (uint32_t i = 0; i < mh->ncmds; ++i, cmd += ((const struct load_command *)cmd)->cmdsize) {
|
||||
const struct load_command *lc = (const struct load_command *)cmd;
|
||||
if (lc->cmd != LC_SEGMENT_64) continue;
|
||||
const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;
|
||||
const struct section_64 *sect = (const struct section_64 *)(seg + 1);
|
||||
for (uint32_t s = 0; s < seg->nsects; ++s) {
|
||||
if ((sect[s].flags & SECTION_TYPE) != S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
size_t n = sect[s].size / sizeof(void *);
|
||||
const uint32_t *idxs = indirect + sect[s].reserved1;
|
||||
void **slots = (void **)((uintptr_t)slide + sect[s].addr);
|
||||
for (size_t k = 0; k < n; ++k) {
|
||||
uint32_t si = idxs[k];
|
||||
if (si == INDIRECT_SYMBOL_ABS || si == INDIRECT_SYMBOL_LOCAL) continue;
|
||||
const char *sym = strtab + syms[si].n_un.n_strx;
|
||||
/* sym 形如 "_getpid":比较去下划线后的部分 */
|
||||
if (sym[0] == '_' && strncmp(sym + 1, bare_name, nlen) == 0 &&
|
||||
sym[1 + nlen] == '\0')
|
||||
return &slots[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* 改写自身 GOT 槽:VM_PROT_COPY 写副本页,写完恢复只读。返回 0 成功。 */
|
||||
static int rebind_got_slot(void **slot, void *to) {
|
||||
vm_address_t page = (vm_address_t)(uintptr_t)slot & ~0xfffull;
|
||||
if (vm_protect(mach_task_self(), page, 0x1000, 0,
|
||||
VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY) != KERN_SUCCESS)
|
||||
return -1;
|
||||
*slot = to;
|
||||
vm_protect(mach_task_self(), page, 0x1000, 0, VM_PROT_READ);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---------- 用例 2:蹦床序言导出符号(100+101)----------
|
||||
* 两个文件级汇编符号,首指令分别是「无条件 B」与「LDR-literal x16 + BR x16」,
|
||||
* 与 Frida/Dobby 蹦床形态一致。仅被 dlsym 解析和字节读取,从不执行。 */
|
||||
|
||||
asm(".globl _ig_hook_target_b\n"
|
||||
".align 2\n"
|
||||
"_ig_hook_target_b:\n"
|
||||
" b .+64\n"
|
||||
" ret\n");
|
||||
|
||||
asm(".globl _ig_hook_target_lb\n"
|
||||
".align 2\n"
|
||||
"_ig_hook_target_lb:\n"
|
||||
" ldr x16, #8\n"
|
||||
" br x16\n"
|
||||
" .quad 0\n");
|
||||
|
||||
/* ---------- 用例 3:frida 特征线程名(203)---------- */
|
||||
|
||||
static void *gum_thread(void *arg) {
|
||||
(void)arg;
|
||||
pthread_setname_np("gum-js-loop");
|
||||
usleep(600000); /* 确保扫描期间线程存活 */
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ---------- 用例 6:ObjC 方法 IMP 基线(110)----------
|
||||
* 运行期创建类并采集基线,class_replaceMethod 换实现后扫描 → 期望 110。 */
|
||||
|
||||
static int ig_objc_imp_original(void *self, SEL _cmd) { (void)self; (void)_cmd; return 1; }
|
||||
static int ig_objc_imp_swapped(void *self, SEL _cmd) { (void)self; (void)_cmd; return 2; }
|
||||
|
||||
static Class make_objc_fixture_class(void) {
|
||||
Class c = objc_allocateClassPair(objc_getClass("NSObject"), "IGHookFixtureTarget", 0);
|
||||
if (!c) return NULL;
|
||||
if (!class_addMethod(c, sel_registerName("value"), (IMP)ig_objc_imp_original, "i16@0:8")) {
|
||||
objc_disposeClassPair(c);
|
||||
return NULL;
|
||||
}
|
||||
objc_registerClassPair(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
/* ---------- 输出协议(宿主 run_hook_device.py 解析)---------- */
|
||||
|
||||
static int g_pass = 0, g_fail = 0;
|
||||
static void mark(const char *name, int pass, const char *detail) {
|
||||
NSLog(@"IG_HOOK_CASE %s %s%s%s", name, pass ? "PASS" : "FAIL",
|
||||
detail && *detail ? " detail=" : "", detail ? detail : "");
|
||||
if (pass) ++g_pass; else ++g_fail;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
(void)argc; (void)argv;
|
||||
@autoreleasepool {
|
||||
NSLog(@"IG_HOOK_MAIN");
|
||||
g_bundle = NSBundle.mainBundle.bundlePath.UTF8String;
|
||||
const char *insert = getenv("DYLD_INSERT_LIBRARIES");
|
||||
|
||||
if (insert && insert[0]) {
|
||||
/* 相位 B:宿主经 DYLD_INSERT_LIBRARIES 启动本进程 → 真实 dyld 注入。 */
|
||||
NSLog(@"IG_HOOK_INSERT_MODE value=%s", insert);
|
||||
int hits = scan_all();
|
||||
int r202 = first_reason(IG_REASON_DYLD_INSERT) != NULL;
|
||||
int r200 = first_reason(IG_REASON_INJECTED_IMAGE) != NULL;
|
||||
NSLog(@"IG_HOOK_INSERT_SUMMARY detected=%d hits=%d reason202=%d reason200=%d",
|
||||
g_nfindings, hits, r202, r200);
|
||||
mark("dyld_insert", r202 || r200,
|
||||
r202 ? "202+环境注入命中" : (r200 ? "200(插入镜像命中特征名)" : "未命中"));
|
||||
NSLog(@"IG_HOOK_SUITE %s cases=1", g_fail ? "FAIL" : "PASS");
|
||||
return g_fail ? 4 : 0;
|
||||
}
|
||||
|
||||
/* ---- 相位 A:干净进程内的受控攻击形态 ---- */
|
||||
|
||||
/* 0. 基线:干净环境 0 命中。 */
|
||||
int base = scan_all();
|
||||
int base_unavail = 0; /* unavailable 已在 sink 日志逐条体现,不判失败 */
|
||||
NSLog(@"IG_HOOK_BASELINE detected=%d", base);
|
||||
mark("baseline_clean", g_nfindings == 0,
|
||||
g_nfindings ? "干净环境出现 DETECTED(误报)" : "");
|
||||
|
||||
/* 1. 耗时小样本(5 次完整聚合扫描)。 */
|
||||
{
|
||||
mach_timebase_info_data_t tb;
|
||||
mach_timebase_info(&tb);
|
||||
double scale = (double)tb.numer / (double)tb.denom / 1e6; /* → ms */
|
||||
double total = 0, best = 1e9;
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
uint64_t t0 = mach_absolute_time();
|
||||
scan_all();
|
||||
double ms = (mach_absolute_time() - t0) * scale;
|
||||
total += ms;
|
||||
if (ms < best) best = ms;
|
||||
}
|
||||
NSLog(@"IG_HOOK_TIMING n=5 avg_ms=%.2f min_ms=%.2f", total / 5.0, best);
|
||||
}
|
||||
|
||||
/* 2. GOT 重绑定 → 102;恢复 → 干净。 */
|
||||
{
|
||||
/* 确保可执行文件真实导入 getpid(否则 __got 无该槽)。 */
|
||||
if (getpid() == -7) NSLog(@"unreachable");
|
||||
void **slot = find_main_got_slot("getpid");
|
||||
if (!slot) {
|
||||
mark("got_rebind", 0, "未找到主程序 getpid 的 __got 槽(构建异常)");
|
||||
} else {
|
||||
void *orig = *slot;
|
||||
NSLog(@"IG_HOOK_GOT slot=%p orig=%p", (void *)slot, orig);
|
||||
if (rebind_got_slot(slot, (void *)ig_rebind_stub) != 0) {
|
||||
mark("got_rebind", 0, "vm_protect 改写失败");
|
||||
} else {
|
||||
scan_all();
|
||||
const IGFinding *f = first_reason(IG_REASON_GOT_REBIND);
|
||||
int hit = f && strstr(f->subject, "getpid") != NULL;
|
||||
mark("got_rebind", hit, f ? f->evidence : "未命中 102");
|
||||
rebind_got_slot(slot, orig); /* 恢复,双写均经同一权限路径 */
|
||||
int again = scan_all();
|
||||
int clean = g_nfindings == 0;
|
||||
NSLog(@"IG_HOOK_GOT_RESTORE detected=%d hits=%d", g_nfindings, again);
|
||||
if (!clean)
|
||||
mark("got_restore_clean", 0, "恢复后仍有 DETECTED");
|
||||
else
|
||||
mark("got_restore_clean", 1, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 3. 蹦床序言(经 dlsym+vm_read_overwrite 的完整探针链)→ 100+101。 */
|
||||
{
|
||||
const char *const names[] = {"ig_hook_target_b", "ig_hook_target_lb"};
|
||||
reset_findings();
|
||||
ig_anti_hook_check(names, 2, collect, NULL);
|
||||
int b100 = 0, b101 = 0, lb100 = 0, lb101 = 0;
|
||||
for (int i = 0; i < g_nfindings; ++i) {
|
||||
const char *subj = g_findings[i].subject;
|
||||
if (strstr(subj, "ig_hook_target_b")) {
|
||||
b100 |= g_findings[i].reason == IG_REASON_SYMBOL_PROVENANCE;
|
||||
b101 |= g_findings[i].reason == IG_REASON_INLINE_HOOK;
|
||||
} else if (strstr(subj, "ig_hook_target_lb")) {
|
||||
lb100 |= g_findings[i].reason == IG_REASON_SYMBOL_PROVENANCE;
|
||||
lb101 |= g_findings[i].reason == IG_REASON_INLINE_HOOK;
|
||||
}
|
||||
}
|
||||
mark("prologue_b_branch", b100 && b101, b101 ? "首指令 B 被识别" : "未命中 101");
|
||||
mark("prologue_ldr_br", lb100 && lb101, lb101 ? "LDR+BR 蹦床被识别" : "未命中 101");
|
||||
}
|
||||
|
||||
/* 4. frida 特征线程名 → 203;join 后 → 干净。
|
||||
* join 后内核回收线程对象存在延迟(task_threads 短期内仍可能列出已终止
|
||||
* 线程),在 2s 窗口内轮询重扫:既能容忍回收延迟,又验证探针无粘滞缓存。 */
|
||||
{
|
||||
pthread_t t;
|
||||
pthread_create(&t, NULL, gum_thread, NULL);
|
||||
usleep(200000); /* 等线程命名完成 */
|
||||
reset_findings();
|
||||
ig_anti_frida_check(0, collect, NULL);
|
||||
mark("frida_thread", first_reason(IG_REASON_FRIDA_THREAD) != NULL, "");
|
||||
pthread_join(t, NULL);
|
||||
int clean = 0;
|
||||
for (int i = 0; i < 10 && !clean; ++i) {
|
||||
usleep(200000);
|
||||
reset_findings();
|
||||
ig_anti_frida_check(0, collect, NULL);
|
||||
clean = (g_nfindings == 0);
|
||||
}
|
||||
mark("frida_thread_gone", clean,
|
||||
clean ? "join 后 2s 内恢复干净" : "join 后 2s 仍残留线程名(回收异常缓慢)");
|
||||
}
|
||||
|
||||
/* 5. 注入证据两种形态:
|
||||
* a) Documents/libfrida-sim.dylib —— 文件名命中注入特征 → 期望 200;
|
||||
* (探针对命中特征的镜像即上报 200,不再重复报 Bundle 外,故不期望 201)
|
||||
* b) Documents/libiosutil-sim.dylib —— 无特征命名的 Bundle 外镜像 → 期望 201。
|
||||
* 相位 A 成功路径回显给宿主,供相位 B 的 DYLD_INSERT 使用。 */
|
||||
{
|
||||
NSString *res = [[NSBundle mainBundle] pathForResource:@"libfrida-sim"
|
||||
ofType:@"dylib"];
|
||||
NSString *docs = [NSHomeDirectory()
|
||||
stringByAppendingPathComponent:@"Documents"];
|
||||
NSString *dstA = [docs stringByAppendingPathComponent:@"libfrida-sim.dylib"];
|
||||
NSString *dstB = [docs stringByAppendingPathComponent:@"libiosutil-sim.dylib"];
|
||||
const char *chosen = NULL;
|
||||
NSFileManager *fm = [NSFileManager defaultManager];
|
||||
if (res) {
|
||||
[fm removeItemAtPath:dstA error:nil];
|
||||
[fm removeItemAtPath:dstB error:nil];
|
||||
if ([fm copyItemAtPath:res toPath:dstA error:nil] &&
|
||||
[fm copyItemAtPath:res toPath:dstB error:nil]) {
|
||||
void *ha = dlopen(dstA.fileSystemRepresentation, RTLD_LOCAL);
|
||||
if (ha) {
|
||||
chosen = dstA.fileSystemRepresentation;
|
||||
reset_findings();
|
||||
ig_anti_inject_check(g_bundle, collect, NULL);
|
||||
mark("injected_image",
|
||||
first_reason(IG_REASON_INJECTED_IMAGE) != NULL,
|
||||
"Documents 特征名装载命中 200");
|
||||
} else {
|
||||
const char *e = dlerror();
|
||||
NSLog(@"IG_HOOK_DLOPEN_DOC_FAIL %s", e ? e : "?");
|
||||
}
|
||||
void *hb = dlopen(dstB.fileSystemRepresentation, RTLD_LOCAL);
|
||||
if (hb) {
|
||||
reset_findings();
|
||||
ig_anti_inject_check(g_bundle, collect, NULL);
|
||||
mark("foreign_image",
|
||||
first_reason(IG_REASON_FOREIGN_IMAGE) != NULL,
|
||||
"Documents 无特征名装载命中 201(弱信号)");
|
||||
}
|
||||
} else {
|
||||
NSLog(@"IG_HOOK_COPY_FAIL %@", docs);
|
||||
}
|
||||
}
|
||||
if (!chosen) {
|
||||
/* 回退:从 .app 内 dlopen(Bundle 内只应命中 200)。 */
|
||||
void *h = dlopen(res.fileSystemRepresentation, RTLD_LOCAL);
|
||||
if (h) {
|
||||
chosen = res.fileSystemRepresentation;
|
||||
reset_findings();
|
||||
ig_anti_inject_check(g_bundle, collect, NULL);
|
||||
int r200 = first_reason(IG_REASON_INJECTED_IMAGE) != NULL;
|
||||
int r201 = first_reason(IG_REASON_FOREIGN_IMAGE) != NULL;
|
||||
mark("injected_image", r200 && !r201,
|
||||
"容器外装载不可用,回退 Bundle 内(200 命中、201 不应命中)");
|
||||
} else {
|
||||
const char *e = dlerror();
|
||||
mark("injected_image", 0, e ? e : "装载失败");
|
||||
}
|
||||
}
|
||||
NSLog(@"IG_HOOK_DYLIB_PATH %s", chosen ? chosen : "none");
|
||||
}
|
||||
|
||||
/* 6. ObjC IMP 基线:采集 → class_replaceMethod → 期望 110;未接入时聚合为 no-op。 */
|
||||
{
|
||||
Class c = make_objc_fixture_class();
|
||||
if (!c) {
|
||||
mark("objc_imp_baseline", 0, "运行期建类失败");
|
||||
} else {
|
||||
const IGObjCWatch watch[] = { { "IGHookFixtureTarget", "value" } };
|
||||
size_t n = ig_objc_baseline_capture(watch, 1);
|
||||
reset_findings();
|
||||
int before = ig_objc_baseline_check(collect, NULL);
|
||||
class_replaceMethod(c, sel_registerName("value"),
|
||||
(IMP)ig_objc_imp_swapped, "i16@0:8");
|
||||
reset_findings();
|
||||
int after = ig_objc_baseline_check(collect, NULL);
|
||||
mark("objc_imp_baseline", n == 1 && before == 0 && after == 1 &&
|
||||
first_reason(IG_REASON_OBJC_IMP_CHANGED) != NULL,
|
||||
after == 1 ? "替换后命中 110" : "未命中 110");
|
||||
}
|
||||
}
|
||||
|
||||
NSLog(@"IG_HOOK_SUITE %s cases=%d baseline_unavailable_logged=%d",
|
||||
g_fail ? "FAIL" : "PASS", g_pass + g_fail, base_unavail);
|
||||
/* 诊断进程退出便于 console 收集退出码;不编入业务 App。 */
|
||||
return g_fail ? 4 : 0;
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* hook_sim_dylib.c — 空壳模拟 dylib(step11 诊断专用)。
|
||||
*
|
||||
* 唯一用途:被诊断进程 dlopen / 被 DYLD_INSERT_LIBRARIES 加载,构成
|
||||
* 「注入镜像 / Bundle 外镜像 / 插入库」探针的受控证据源。不实现任何业务功能,
|
||||
* 不导出会被业务引用的符号。仅用于诊断 App,绝不编入业务库。
|
||||
*/
|
||||
#include <stddef.h>
|
||||
|
||||
__attribute__((visibility("default")))
|
||||
int ig_frida_sim_marker(void) { return 0x46726461; /* "Frda" */ }
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
/* 无 SDK 头依赖的 iOS 链接样本:两个外部调用和一个本地改写目标。 */
|
||||
extern int getpid(void);
|
||||
extern long write(int, const void *, unsigned long);
|
||||
int fixture_calls(void) { return getpid() + (int)write(-1, "x", 1); }
|
||||
int fixture_redirect(void) { return 123; }
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
FILE *sdk_open(const char *path, const char *mode) { return fopen(path, mode); }
|
||||
int sdk_fclose(FILE *stream) { return fclose(stream); }
|
||||
size_t sdk_fread(void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
return fread(buffer, size, count, stream);
|
||||
}
|
||||
size_t sdk_fwrite(const void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
return fwrite(buffer, size, count, stream);
|
||||
}
|
||||
ssize_t sdk_read(int fd, void *buffer, size_t count) { return read(fd, buffer, count); }
|
||||
ssize_t sdk_write(int fd, const void *buffer, size_t count) { return write(fd, buffer, count); }
|
||||
int sdk_close(int fd) { return close(fd); }
|
||||
@@ -0,0 +1,125 @@
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import os
|
||||
import platform
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'tools/macho_guard'))
|
||||
from redirect_framework_imports import rewrite, DEPENDENCY
|
||||
from machox import Macho, LC_DYLD_CHAINED_FIXUPS
|
||||
|
||||
SDK = ROOT/'readoor-test/readoor/BookShelf/Classes/Factorys/SSZipArchive/SSZipArchive.framework/SSZipArchive'
|
||||
SHA = '485c0c95b4701a4e51625e16b6c2a9781c1a8a6f6c9b9cbe392709ecfc95191a'
|
||||
|
||||
|
||||
@unittest.skipUnless(SDK.exists(), '需要已审核 SDK 副本')
|
||||
class FrameworkRewriteTests(unittest.TestCase):
|
||||
def setUp(self): self.data = SDK.read_bytes()
|
||||
def rejected(self, data):
|
||||
with self.assertRaises((ValueError, struct.error)):
|
||||
rewrite(data, hashlib.sha256(data).hexdigest())
|
||||
def test_real_sdk(self):
|
||||
data, report = rewrite(self.data, SHA)
|
||||
self.assertEqual(len(data), len(self.data))
|
||||
self.assertEqual(len(report['changes']), 8)
|
||||
self.assertTrue(report['machine_code_unchanged'])
|
||||
self.assertIn(DEPENDENCY.encode(), data[:32768])
|
||||
m = Macho(data)
|
||||
self.assertEqual(m.ncmds, Macho(self.data).ncmds+1)
|
||||
self.assertEqual(data[32768:212992], self.data[32768:212992])
|
||||
def test_wrong_hash(self):
|
||||
with self.assertRaises(ValueError): rewrite(self.data, '0'*64)
|
||||
def test_repeat_rejected(self):
|
||||
data, _ = rewrite(self.data, SHA); self.rejected(data)
|
||||
def test_no_padding(self):
|
||||
data = bytearray(self.data); data[32+Macho(data).sizeofcmds] = 1; self.rejected(data)
|
||||
def test_unsupported_import_format(self):
|
||||
data = bytearray(self.data); m = Macho(data)
|
||||
off = next(o for c,_,o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS)
|
||||
fixoff = struct.unpack_from('<I',data,off+8)[0]
|
||||
struct.pack_into('<I',data,fixoff+20,3); self.rejected(data)
|
||||
def test_wrong_provider_and_weak(self):
|
||||
m = Macho(self.data); off = next(o for c,_,o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS)
|
||||
fixoff = struct.unpack_from('<I',self.data,off+8)[0]
|
||||
imports = struct.unpack_from('<I',self.data,fixoff+8)[0]
|
||||
for mask in (0x100, 1):
|
||||
with self.subTest(mask=mask):
|
||||
data = bytearray(self.data); pos = fixoff+imports+43*4
|
||||
word = struct.unpack_from('<I',data,pos)[0]
|
||||
struct.pack_into('<I',data,pos,word^mask); self.rejected(data)
|
||||
def test_truncated(self): self.rejected(self.data[:3000])
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin', '需要 Apple 工具链')
|
||||
class ArchiveABITests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory(); cls.exe = Path(cls.tmp.name)/'archive-host'
|
||||
cls.env = dict(os.environ); cls.env.pop('DYLD_INSERT_LIBRARIES',None)
|
||||
cls.sources = [str(ROOT/'defender'/s) for s in
|
||||
('dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c')]
|
||||
command = ['xcrun','--sdk','macosx','clang','-O2','-Wall','-Wextra','-Werror',
|
||||
'-DIG_ARCHIVE_TESTING','-DIG_OBSERVATION','-I',str(ROOT/'defender'),
|
||||
'-I',str(ROOT/'defender/include'),str(ROOT/'tests/fixtures/archive_host.c'),
|
||||
*cls.sources,'-o',str(cls.exe)]
|
||||
r = subprocess.run(command,capture_output=True,text=True,env=cls.env)
|
||||
if r.returncode: raise RuntimeError(r.stderr)
|
||||
@classmethod
|
||||
def tearDownClass(cls): cls.tmp.cleanup()
|
||||
def run_mode(self,mode):
|
||||
r = subprocess.run([self.exe,mode],capture_output=True,text=True,env=self.env,timeout=30)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
def test_stdio_semantics(self): self.run_mode('semantics')
|
||||
def test_concurrent_initialization(self): self.run_mode('threads')
|
||||
def test_tamper_refuses_before_call(self): self.run_mode('tamper')
|
||||
def test_reentry(self): self.run_mode('reentry')
|
||||
def test_read_write_close_reject(self): self.run_mode('rejection')
|
||||
def test_release_has_no_test_or_observation_api(self):
|
||||
output = Path(self.tmp.name)/'release.dylib'
|
||||
r = subprocess.run(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-O2','-fvisibility=hidden','-dynamiclib',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),*self.sources,
|
||||
'-o',str(output)],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
nm = subprocess.run(['xcrun','nm','-g',output],capture_output=True,text=True,check=True).stdout
|
||||
self.assertNotIn('ig_archive_test_',nm); self.assertNotIn('_ig_archive_counter',nm)
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin' and platform.machine() == 'arm64', '需要 Apple Silicon')
|
||||
class ArchiveBindingIntegrationTests(unittest.TestCase):
|
||||
def test_real_dyld_binding_and_got_tamper(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
guard = root/'IGArchiveGuard.framework/IGArchiveGuard'
|
||||
sdk = root/'SSZipArchive.framework/SSZipArchive'
|
||||
guard.parent.mkdir(); sdk.parent.mkdir()
|
||||
common = ['xcrun','--sdk','macosx','clang','-arch','arm64','-mmacosx-version-min=13.0','-O2']
|
||||
env = dict(os.environ); env.pop('DYLD_INSERT_LIBRARIES',None)
|
||||
def command(args):
|
||||
r = subprocess.run(args,capture_output=True,text=True,env=env,timeout=40)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
return r
|
||||
command(common+['-dynamiclib','-DIG_OBSERVATION','-fvisibility=hidden',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
*(str(ROOT/'defender'/s) for s in
|
||||
('dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c')),
|
||||
'-Wl,-install_name,'+DEPENDENCY,'-o',str(guard)])
|
||||
command(common+['-dynamiclib',str(ROOT/'tests/fixtures/archive_sdk.c'),
|
||||
'-Wl,-install_name,@rpath/SSZipArchive.framework/SSZipArchive',
|
||||
'-Wl,-headerpad,0x4000','-Wl,-rpath,@loader_path/..','-o',str(sdk)])
|
||||
data = sdk.read_bytes(); changed, _ = rewrite(data,hashlib.sha256(data).hexdigest())
|
||||
sdk.write_bytes(changed)
|
||||
command(['codesign','--force','--sign','-',str(guard)])
|
||||
command(['codesign','--force','--sign','-',str(sdk)])
|
||||
exe = root/'binding-test'
|
||||
command(common+[str(ROOT/'tests/fixtures/archive_binding_host.c'),'-o',str(exe)])
|
||||
result = command([str(exe),str(sdk),str(root/'stdio.bin')])
|
||||
self.assertIn('均通过',result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""宿主探针正反例与 iOS 编译验证;不替代真机 inline Hook 测试。"""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCES = ['IGDefender.c','anti_hook/IGAntiHook.c','anti_hook/IGObjCBaseline.c',
|
||||
'anti_frida/IGAntiInject.c','anti_debug/IGAntiDebug.c',
|
||||
'syscall/IGSyscall.c','resolve/IGResolve.c','dispatch/IGDispatch.c']
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform=='darwin' and shutil.which('xcrun'), '需要 Xcode/macOS')
|
||||
class DefenderTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.folder = Path(cls.tmp.name)
|
||||
cls.exe = cls.folder/'defender-host'
|
||||
cls.env = dict(os.environ)
|
||||
cls.env.pop('DYLD_INSERT_LIBRARIES', None)
|
||||
cls.compile(['xcrun','--sdk','macosx','clang','-O2',
|
||||
'-I',str(ROOT/'defender/include'),'-I',str(ROOT/'defender'),
|
||||
str(ROOT/'tests/fixtures/defender_host.c'),
|
||||
*(str(ROOT/'defender'/p) for p in SOURCES),
|
||||
'-lobjc','-o',str(cls.exe)])
|
||||
fixture = cls.folder/'empty.c'
|
||||
fixture.write_text('int ig_fixture_marker(void) { return 1; }\n')
|
||||
cls.image = cls.folder/'fixture_frida.dylib'
|
||||
cls.compile(['xcrun','--sdk','macosx','clang','-dynamiclib',str(fixture),'-o',str(cls.image)])
|
||||
|
||||
@classmethod
|
||||
def compile(cls, args):
|
||||
p = subprocess.run(args,capture_output=True,text=True,env=cls.env)
|
||||
if p.returncode:
|
||||
raise RuntimeError(p.stdout+p.stderr)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def check_mode(self, mode, *args):
|
||||
p = subprocess.run([str(self.exe),mode,*map(str,args)],
|
||||
capture_output=True,text=True,env=self.env)
|
||||
self.assertEqual(p.returncode,0,p.stdout+p.stderr)
|
||||
# 保留各探针证据到 unittest 日志。
|
||||
print(mode+': '+p.stdout.strip(), flush=True)
|
||||
|
||||
def test_clean(self): self.check_mode('clean')
|
||||
def test_unavailable(self): self.check_mode('unresolved')
|
||||
def test_function_provenance(self): self.check_mode('verify')
|
||||
def test_environment_entries(self): self.check_mode('env')
|
||||
def test_loaded_image(self): self.check_mode('image',self.image)
|
||||
def test_got_rebinding(self): self.check_mode('got')
|
||||
def test_debugger_clean(self): self.check_mode('debugger')
|
||||
def test_objc_baseline_clean(self): self.check_mode('objc-clean')
|
||||
def test_objc_baseline_swap(self): self.check_mode('objc-swap')
|
||||
|
||||
def test_iphoneos_cross_compile(self):
|
||||
for i, source in enumerate(SOURCES):
|
||||
self.compile(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-O2',
|
||||
'-I',str(ROOT/'defender/include'),'-I',str(ROOT/'defender'),
|
||||
'-c',str(ROOT/'defender'/source),'-o',str(self.folder/f'{i}.o')])
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,70 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
SOURCES=['dispatch/IGDispatch.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c']
|
||||
|
||||
@unittest.skipUnless(sys.platform=='darwin','需要 Apple 工具链')
|
||||
class DispatchTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp=tempfile.TemporaryDirectory()
|
||||
cls.exe=Path(cls.tmp.name)/'dispatch-test'
|
||||
cls.env=dict(os.environ);cls.env.pop('DYLD_INSERT_LIBRARIES',None)
|
||||
p=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-Wall','-Wextra','-Werror',
|
||||
'-DIG_DISPATCH_TESTING','-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
str(ROOT/'tests/fixtures/dispatch_host.c'),*(str(ROOT/'defender'/p) for p in SOURCES),
|
||||
'-o',str(cls.exe)],capture_output=True,text=True,env=cls.env)
|
||||
if p.returncode:raise RuntimeError(p.stderr)
|
||||
@classmethod
|
||||
def tearDownClass(cls):cls.tmp.cleanup()
|
||||
def run_mode(self,mode):
|
||||
p=subprocess.run([str(self.exe),mode],capture_output=True,text=True,env=self.env,timeout=30)
|
||||
self.assertEqual(p.returncode,0,p.stdout+p.stderr)
|
||||
def test_semantics(self):self.run_mode('semantics')
|
||||
def test_short_write(self):self.run_mode('short-write')
|
||||
def test_eintr(self):self.run_mode('eintr')
|
||||
def test_concurrency(self):self.run_mode('threads')
|
||||
def test_tamper_rejected(self):self.run_mode('tamper')
|
||||
def test_reentry(self):self.run_mode('reentry')
|
||||
def test_resolver_errors(self):self.run_mode('resolver')
|
||||
def test_prologue_patterns(self):self.run_mode('prologue')
|
||||
def test_observation_counters_and_release_exclusion(self):
|
||||
exe=Path(self.tmp.name)/'observation'
|
||||
r=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-Wall','-Wextra','-Werror',
|
||||
'-DIG_DISPATCH_TESTING','-DIG_OBSERVATION',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
str(ROOT/'tests/fixtures/dispatch_host.c'),*(str(ROOT/'defender'/p) for p in SOURCES),
|
||||
'-o',str(exe)],capture_output=True,text=True,env=self.env)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
r=subprocess.run([str(exe),'observation'],capture_output=True,text=True,env=self.env,timeout=30)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
r=subprocess.run(['xcrun','nm',str(self.exe)],capture_output=True,text=True,check=True)
|
||||
self.assertNotIn('_ig_dispatch_observation',r.stdout)
|
||||
def test_ios_compile(self):
|
||||
for i,p in enumerate(SOURCES):
|
||||
r=subprocess.run(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-O2','-I',str(ROOT/'defender/include'),
|
||||
'-c',str(ROOT/'defender'/p),'-o',str(Path(self.tmp.name)/f'{i}.o')],
|
||||
capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
def test_initialization_failure(self):
|
||||
obj=Path(self.tmp.name)/'missing-resolver.o'
|
||||
exe=Path(self.tmp.name)/'init-failure'
|
||||
r=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-Ddlsym=ig_fixture_missing_resolve',
|
||||
'-I',str(ROOT/'defender/include'),
|
||||
'-c',str(ROOT/'defender/resolve/IGResolve.c'),'-o',str(obj)],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
r=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-DIG_DISPATCH_TESTING','-DIG_EXPECT_INIT_FAILURE',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
str(ROOT/'tests/fixtures/dispatch_host.c'),str(ROOT/'defender/dispatch/IGDispatch.c'),
|
||||
str(ROOT/'defender/anti_hook/IGAntiHook.c'),str(obj),'-o',str(exe)],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
r=subprocess.run([str(exe),'init-failure'],capture_output=True,text=True,timeout=30)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,168 @@
|
||||
"""用真实 Apple 链接器生成样本,验证注入、指令及拒绝路径。"""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'tools/macho_guard'))
|
||||
import batch
|
||||
import macho_guard as guard
|
||||
from machox import Macho
|
||||
from verify_baseline import inspect_binary, validate_zip
|
||||
from redirect_to_runtime import patch, trace_calls
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin' and shutil.which('xcrun'), '需要 Xcode')
|
||||
class MachoTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.src = Path(cls.tmp.name)/'fixture.dylib'
|
||||
cls.linkmap = Path(cls.tmp.name)/'fixture.map'
|
||||
subprocess.run(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-dynamiclib',
|
||||
'-Wl,-headerpad,0x1000',
|
||||
'-Wl,-map,'+str(cls.linkmap),
|
||||
str(ROOT/'tests/fixtures/macho_calls.c'),'-o',str(cls.src)],
|
||||
check=True, capture_output=True)
|
||||
cls.original = cls.src.read_bytes()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def test_rewrite_preserves_got_and_branch_targets(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
dst = Path(td)/'guarded'
|
||||
before, sites = inspect_binary(self.src)
|
||||
self.assertEqual({s['symbol'] for s in sites}, {'_getpid','_write'})
|
||||
count, n, _, va = guard.harden_thin(self.src, dst)
|
||||
after, remaining = inspect_binary(dst)
|
||||
self.assertEqual(sum(count.values()),len(sites))
|
||||
self.assertEqual(remaining, [])
|
||||
m = Macho(dst.read_bytes())
|
||||
self.assertEqual(m.segs['__IGUARD']['initprot'],5)
|
||||
self.assertEqual(guard.find_stub_got_slots(m),
|
||||
guard.find_stub_got_slots(Macho(self.original)))
|
||||
view = batch.Slice(dst.read_bytes(),0)
|
||||
old_view = batch.Slice(self.original,0)
|
||||
addr, length, off = view.text
|
||||
old_off = old_view.text[2]
|
||||
changes = []
|
||||
for i in range(0,length,4):
|
||||
old, = struct.unpack_from('<I',self.original,old_off+i)
|
||||
new, = struct.unpack_from('<I',m.d,off+i)
|
||||
if old==new:
|
||||
continue
|
||||
changes.append(i)
|
||||
self.assertEqual(old & 0xfc000000,new & 0xfc000000)
|
||||
imm = new & 0x3ffffff
|
||||
if imm & (1<<25): imm -= 1<<26
|
||||
self.assertTrue(va <= addr+i+imm*4 < va+n*12)
|
||||
self.assertEqual(len(changes),len(sites))
|
||||
self.assertEqual(self.src.read_bytes(),self.original)
|
||||
self.assertEqual(before['slices'][0]['uuid'],after['slices'][0]['uuid'])
|
||||
|
||||
def test_reject_duplicate_injection_and_input_overwrite(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
dst = Path(td)/'out'
|
||||
guard.inject(self.src,dst)
|
||||
with self.assertRaisesRegex(ValueError,'重复'):
|
||||
guard.inject(dst,Path(td)/'again')
|
||||
with self.assertRaisesRegex(ValueError,'覆盖'):
|
||||
guard.inject(self.src,self.src)
|
||||
|
||||
def test_reject_unsupported_architecture_and_truncation(self):
|
||||
for offset, value in [(4,0x01000007),(8,2)]:
|
||||
data = bytearray(self.original)
|
||||
struct.pack_into('<I',data,offset,value)
|
||||
with self.assertRaises(ValueError): Macho(data)
|
||||
for size in (0,4,31,64,len(self.original)-1):
|
||||
with self.subTest(size=size), self.assertRaises(ValueError):
|
||||
Macho(self.original[:size])
|
||||
|
||||
def test_reject_encrypted_image(self):
|
||||
data = bytearray(self.original)
|
||||
m = Macho(data)
|
||||
# 在已有 padding 中追加 encryption_info_command_64。
|
||||
end = 32+m.sizeofcmds
|
||||
data[end:end+24] = struct.pack('<6I',0x2c,24,0,0,1,0)
|
||||
struct.pack_into('<II',data,16,m.ncmds+1,m.sizeofcmds+24)
|
||||
with self.assertRaisesRegex(ValueError,'加密'): Macho(data)
|
||||
|
||||
def test_reject_insufficient_header_space(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
data = bytearray(self.original)
|
||||
m = Macho(data)
|
||||
# 保留现有命令,用合法空命令填满 padding,只剩不足 72B。
|
||||
end = 32+m.sizeofcmds
|
||||
first = guard._first_section_fileoff(m)
|
||||
size = (first-end)//8*8
|
||||
struct.pack_into('<II',data,end,0x7777,size)
|
||||
struct.pack_into('<II',data,16,m.ncmds+1,m.sizeofcmds+size)
|
||||
src,dst = Path(td)/'src',Path(td)/'dst'
|
||||
src.write_bytes(data)
|
||||
with self.assertRaisesRegex(AssertionError,'空间不足'):
|
||||
guard.inject(src,dst)
|
||||
self.assertFalse(dst.exists())
|
||||
|
||||
def test_targeted_rewrite_and_trace(self):
|
||||
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
|
||||
destination='_fixture_redirect',expected_count=1)]}
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
dst=Path(td)/'patched'
|
||||
report=patch(self.src,dst,self.linkmap,profile)
|
||||
self.assertEqual(report['total'],1)
|
||||
rows=trace_calls(dst,self.linkmap,['_fixture_calls'])
|
||||
self.assertNotIn('_getpid',{r.get('symbol') for r in rows})
|
||||
self.assertIn('_write',{r.get('symbol') for r in rows})
|
||||
with self.assertRaises(ValueError):patch(self.src,dst,self.linkmap,profile)
|
||||
|
||||
def test_targeted_reject_stale_map(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
lm=Path(td)/'bad.map'
|
||||
lm.write_text('0x1 0x4 [1] _fixture_calls\n0x2 0x4 [1] _fixture_redirect\n')
|
||||
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
|
||||
destination='_fixture_redirect',expected_count=1)]}
|
||||
with self.assertRaisesRegex(ValueError,'不匹配'):
|
||||
patch(self.src,Path(td)/'out',lm,profile)
|
||||
|
||||
def test_map_with_non_utf8_sdk_symbol(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
lm=Path(td)/'sdk.map'
|
||||
lm.write_bytes(b'0x1 0x4 [1] sdk_\xf0\xff\n'+self.linkmap.read_bytes())
|
||||
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
|
||||
destination='_fixture_redirect',expected_count=1)]}
|
||||
report=patch(self.src,Path(td)/'out',lm,profile)
|
||||
self.assertEqual(report['total'],1)
|
||||
|
||||
def test_targeted_reject_wrong_count(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
|
||||
destination='_fixture_redirect',expected_count=2)]}
|
||||
with self.assertRaises(ValueError):patch(self.src,Path(td)/'out',self.linkmap,profile)
|
||||
|
||||
def test_trace_recovers_injected_got_bridge(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
dst=Path(td)/'bridge'
|
||||
guard.harden_thin(self.src,dst)
|
||||
rows=trace_calls(dst,self.linkmap,['_fixture_calls'])
|
||||
self.assertEqual({r.get('symbol') for r in rows if r['kind']=='got_bridge'},
|
||||
{'_getpid','_write'})
|
||||
|
||||
|
||||
class ArchiveTests(unittest.TestCase):
|
||||
def test_reject_zip_escape(self):
|
||||
import zipfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = Path(td)/'bad.ipa'
|
||||
with zipfile.ZipFile(path,'w') as z: z.writestr('../escape','bad')
|
||||
with self.assertRaises(ValueError): validate_zip(path)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""用真实策略源码做宿主测试,覆盖观察/强制模式和 unavailable。"""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
POLICY=ROOT/'readoor-test/readoor/3.0/Base/Security/RDSecurityPolicy.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
|
||||
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
|
||||
}
|
||||
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))
|
||||
''')
|
||||
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)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,188 @@
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location("redirect_symbols", ROOT / "tools/static_sdk_redirect/redirect_symbols.py")
|
||||
redirect = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(redirect)
|
||||
|
||||
|
||||
def object_bytes(name=b"_fopen", ntype=1):
|
||||
strings = b"\0" + name + b"\0"
|
||||
header = struct.pack("<8I", 0xFEEDFACF, redirect.CPU_ARM64, 0, 1, 1, 24, 0, 0)
|
||||
command = struct.pack("<6I", 2, 24, 56, 1, 72, len(strings))
|
||||
symbol = struct.pack("<IBBHQ", 1, ntype, 0, 0, 0)
|
||||
return header + command + symbol + strings
|
||||
|
||||
|
||||
def llvm_object(payload):
|
||||
segment = bytearray(152)
|
||||
struct.pack_into("<II", segment, 0, 0x19, 152)
|
||||
struct.pack_into("<I", segment, 64, 1)
|
||||
segment[72:88] = b"__bitcode".ljust(16, b"\0")
|
||||
segment[88:104] = b"__LLVM".ljust(16, b"\0")
|
||||
struct.pack_into("<QI", segment, 112, len(payload), 208)
|
||||
strings = b"\0_fopen\0"
|
||||
header = struct.pack("<8I", 0xFEEDFACF, redirect.CPU_ARM64, 0, 1, 2, 176, 0, 0)
|
||||
command = struct.pack("<6I", 2, 24, 216, 1, 232, len(strings))
|
||||
symbol = struct.pack("<IBBHQ", 1, 1, 0, 0, 0)
|
||||
return header + segment + command + payload.ljust(8, b"\0") + symbol + strings
|
||||
|
||||
|
||||
class FormatTests(unittest.TestCase):
|
||||
def test_invalid_mappings(self):
|
||||
invalid = [{}, [], {"fopen": "_IG_fopen"}, {"_a": "_a"},
|
||||
{"_a": "_b", "_b": "_c"}, {"_a": "_x", "_b": "_x"},
|
||||
{"_a": 3}, {"_a": "_x\u0000"}]
|
||||
for mapping in invalid:
|
||||
with self.subTest(mapping=mapping), self.assertRaises(ValueError):
|
||||
redirect.validate_mapping(mapping)
|
||||
|
||||
def test_duplicate_json_key(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "mapping.json"
|
||||
path.write_text('{"_a":"_x", "_a":"_y"}')
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.load_mapping(path)
|
||||
|
||||
def test_custom_mapping(self):
|
||||
result, count = redirect.redirect_object(object_bytes(b"_my_function"),
|
||||
{"_my_function": "_custom_bridge"})
|
||||
self.assertEqual(count, 1)
|
||||
self.assertIn(b"_custom_bridge\0", result)
|
||||
|
||||
def test_relocation_index_unchanged(self):
|
||||
original = object_bytes()
|
||||
result, count = redirect.redirect_object(original)
|
||||
self.assertEqual(count, 1)
|
||||
self.assertEqual(result[:52], original[:52])
|
||||
self.assertEqual(result[60:72], original[60:72])
|
||||
index = struct.unpack_from("<I", result, 56)[0]
|
||||
self.assertEqual(result[72 + index:].split(b"\0")[0], b"_IG_fopen")
|
||||
|
||||
def test_unrelated_symbol_unchanged(self):
|
||||
data = object_bytes(b"_fclose")
|
||||
self.assertEqual(redirect.redirect_object(data), (data, 0))
|
||||
|
||||
def test_reject_defined_source(self):
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(object_bytes(ntype=0x0F))
|
||||
|
||||
def test_reject_existing_destination(self):
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(object_bytes(b"_IG_fopen"))
|
||||
|
||||
def test_reject_truncation(self):
|
||||
data = object_bytes()
|
||||
for size in (0, 4, 31, 40, 60, len(data) - 1):
|
||||
with self.subTest(size=size), self.assertRaises(ValueError):
|
||||
redirect.redirect_object(data[:size])
|
||||
|
||||
def test_archive_padding(self):
|
||||
data = object_bytes()
|
||||
self.assertEqual(redirect.redirect_object(data + b"\n" * 4)[1], 1)
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(data + b"ABCD")
|
||||
|
||||
def test_reject_malformed_archive(self):
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_archive(b"!<arch>\ntruncated")
|
||||
|
||||
def test_preserve_empty_bitcode_marker(self):
|
||||
data = llvm_object(b"\0")
|
||||
result, count = redirect.redirect_object(data)
|
||||
self.assertEqual(count, 1)
|
||||
self.assertEqual(result[208:216], data[208:216])
|
||||
|
||||
def test_reject_real_bitcode(self):
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(llvm_object(b"BC\xc0\xde"))
|
||||
|
||||
def test_reject_dylib(self):
|
||||
data = bytearray(object_bytes())
|
||||
struct.pack_into("<I", data, 12, 6)
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(data)
|
||||
|
||||
|
||||
@unittest.skipUnless(platform.system() == "Darwin" and platform.machine() == "arm64", "需要 ARM64 Mac + Xcode")
|
||||
class NativeTests(unittest.TestCase):
|
||||
def test_multiple_symbols_and_cli(self):
|
||||
with tempfile.TemporaryDirectory(prefix="iosguard-multi-") as folder:
|
||||
root = Path(folder)
|
||||
obj, library, output = root / "sdk.o", root / "sdk.a", root / "protected.a"
|
||||
subprocess.run(["xcrun", "clang", "-O2", "-c", str(ROOT / "tests/fixtures/sdk_io.c"),
|
||||
"-o", str(obj)], check=True)
|
||||
subprocess.run(["xcrun", "ar", "rcs", str(library), str(obj)], check=True)
|
||||
mapping = redirect.load_mapping(ROOT / "tools/static_sdk_redirect/mappings/stdio.json")
|
||||
mapping.update(redirect.load_mapping(ROOT / "tools/static_sdk_redirect/mappings/posix_io.json"))
|
||||
config = root / "mapping.json"
|
||||
config.write_text(json.dumps(mapping))
|
||||
command = [sys.executable, str(ROOT / "tools/static_sdk_redirect/redirect_symbols.py"),
|
||||
str(library), str(output), "--mapping", str(config), "--require-all"]
|
||||
report = json.loads(subprocess.check_output(command, text=True))
|
||||
self.assertEqual(report["references_redirected"], 7)
|
||||
self.assertEqual(report["symbol_counts"], {name: 1 for name in mapping})
|
||||
self.assertEqual(report["unmatched_symbols"], [])
|
||||
symbols = {s.strip() for s in subprocess.check_output(["xcrun", "nm", "-u", str(output)], text=True).splitlines()}
|
||||
self.assertTrue(set(mapping.values()) <= symbols)
|
||||
self.assertFalse(set(mapping) & symbols)
|
||||
for name, archive, extra in (("baseline", library, []),
|
||||
("redirected", output, [str(ROOT / "defender/call_bridge/IGFileBridge.c")])):
|
||||
binary = root / name
|
||||
subprocess.run(["xcrun", "clang", "-O2", "-Wall", "-Wextra", "-Werror", "-DIG_TEST_ALL_BRIDGES",
|
||||
str(ROOT / "tests/fixtures/file_semantics.c"), str(archive), *extra,
|
||||
"-o", str(binary)], check=True)
|
||||
subprocess.run([str(binary), str(root)], check=True)
|
||||
missing = {**mapping, "_absent": "_IG_absent"}
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.run(library, root / "strict.a", missing, require_all=True)
|
||||
self.assertFalse((root / "strict.a").exists())
|
||||
partial = redirect.run(library, root / "partial.a", missing)
|
||||
self.assertEqual(partial["unmatched_symbols"], ["_absent"])
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.run(library, root / "none.a", {"_absent": "_IG_absent"})
|
||||
self.assertFalse((root / "none.a").exists())
|
||||
legacy = json.loads(subprocess.check_output([sys.executable,
|
||||
str(ROOT / "tools/static_sdk_redirect/redirect_fopen.py"),
|
||||
str(library), str(root / "legacy.a")], text=True))
|
||||
self.assertEqual(legacy["references_redirected"], 1)
|
||||
|
||||
def test_link_and_file_semantics(self):
|
||||
with tempfile.TemporaryDirectory(prefix="iosguard-test-") as folder:
|
||||
root = Path(folder)
|
||||
source = root / "sdk.c"
|
||||
source.write_text('#include <stdio.h>\nFILE *sdk_open(const char *p, const char *m) { return fopen(p,m); }\n')
|
||||
obj, library, output = root / "sdk.o", root / "sdk.a", root / "protected.a"
|
||||
subprocess.run(["xcrun", "clang", "-O2", "-c", str(source), "-o", str(obj)], check=True)
|
||||
subprocess.run(["xcrun", "ar", "rcs", str(library), str(obj)], check=True)
|
||||
original = library.read_bytes()
|
||||
report = redirect.run(library, output)
|
||||
self.assertEqual(report["references_redirected"], 1)
|
||||
self.assertEqual(library.read_bytes(), original)
|
||||
symbols = subprocess.check_output(["xcrun", "nm", "-u", str(output)], text=True).splitlines()
|
||||
self.assertIn("_IG_fopen", [s.strip() for s in symbols])
|
||||
self.assertNotIn("_fopen", [s.strip() for s in symbols])
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.run(library, output)
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.run(output, root / "twice.a")
|
||||
# 同一行为测试分别链接原始归档和改写后的归档。
|
||||
for name, archive, extra in (("baseline", library, []),
|
||||
("redirected", output, [str(ROOT / "defender/call_bridge/IGFileBridge.c")])):
|
||||
binary = root / name
|
||||
subprocess.run(["xcrun", "clang", "-O2", "-Wall", "-Wextra", "-Werror",
|
||||
str(ROOT / "tests/fixtures/file_semantics.c"), str(archive),
|
||||
*extra, "-o", str(binary)], check=True)
|
||||
subprocess.run([str(binary), str(root)], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user