AntiDebug(Swift)

为了防止App被别人动态调试(动态调试目的),可以在项目中进行动态调试检测或者禁止动态调试。 参考自庆哥的关于反调试&反反调试那些事

庆总写的方法实现以及方法的原理以及挺详细了,但是Swift项目中调用C的API还是不太方便,顾写了个Swift版的~
(记得方法调用的时候要区分是Release还得Debug版的,不然正常开发调试也会退出程序了)

ptrace

1
2
3
4
5
6
7
8
9
10
func diyPtrace() {  
// PT_DENY_ATTACH的值
let attach: CInt = 31
let handle = dlopen("/usr/lib/libc.dylib", RTLD_NOW)
let sym = dlsym(handle, "ptrace")
typealias PtraceAlias = @convention(c) (CInt, pid_t, CInt, CInt) -> CInt
let diyPtrace = unsafeBitCast(sym, to: PtraceAlias.self)
_ = diyPtrace(attach, 0, 0, 0)
dlclose(handle)
}

sysctl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func isDebugger() -> Bool {
var name = [Int32]()
name.append(CTL_KERN)
name.append(KERN_PROC)
name.append(KERN_PROC_PID)
name.append(getpid())

var info = kinfo_proc()
info.kp_proc.p_flag = 0
var infoSize = MemoryLayout.size(ofValue: info) as size_t
if sysctl(&name, 4, &info, &infoSize, nil, 0) == -1 {
return false
}
return (info.kp_proc.p_flag & P_TRACED) != 0
}

// 调用
if Debugger() {
exit(0)
}

GCD

1
2
3
4
5
6
7
8
private var stopSource: DispatchSourceSignal!
public func debugDetection3() {
stopSource = DispatchSource.makeSignalSource(signal: SIGSTOP, queue: DispatchQueue.main)
stopSource.setEventHandler(qos: .userInteractive) {
exit(0)
}
stopSource.resume()
}