Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Anti-piracy in Swift

Tags:

ios

swift

First, let me say that I understand that using PT_DENY_ATTACH as described at: Bugging Debuggers is pretty useless.

However, for the sake of understanding how iOS works, I would still like to know: Is it possible to do something similar when working on a Swift project? Since Objective-C is built upon C, there is a main(int argc, char *argv[]) function that can be leveraged to prevent gdb from attaching to the process.

How would this be done in Swift? I'm mostly trying to understand the application lifecycle in Swift, however, most of the explanations I can find are for ObjC.

like image 317
Stephen Avatar asked Apr 23 '15 14:04

Stephen


1 Answers

Thanks to user ahruss's very helpful link, here's the solution I landed on:

I used the method referenced in this question to create a main.swift file. I then created a c file (and header) containing this method definition:

typedef int (*command_ptr_t)(int _request, pid_t _pid, caddr_t _addr, int _data);

#if !defined(PT_DENY_ATTACH)
#define PT_DENY_ATTACH 31
#endif

//Anti-debug method
void disable_attach() {
    void* handle = dlopen(0, RTLD_GLOBAL | RTLD_NOW);
    command_ptr_t command_ptr = dlsym(handle, "ptrace");
    command_ptr(PT_DENY_ATTACH, 0, 0, 0);
    dlclose(handle);
}

I added the disableAttach.h header file in my bridging header, then called disable_attach() directly above my UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate)) call in main.swift.

You should end up with a main.swift file similar to this:

import Foundation
import UIKit

disable_attach()
UIApplicationMain(
    CommandLine.argc,
    UnsafeMutableRawPointer(CommandLine.unsafeArgv)
        .bindMemory(
            to: UnsafeMutablePointer<Int8>.self,
            capacity: Int(CommandLine.argc)),
    nil,
    NSStringFromClass(AppDelegate.self)
)

As I stated previously in a comment, it seems that the lifecycle is the same, but that the @UIApplicationMain directive hides the main file itself.

UPDATE: As of Xcode 10 \ iOS 12, the main.swift file should look like this:

UIApplicationMain(
    CommandLine.argc, CommandLine.unsafeArgv, 
    nil, NSStringFromClass(AppDelegate.self)
)

Thanks to the answers here and here

like image 125
Stephen Avatar answered Sep 24 '22 21:09

Stephen