App security - prevent debugger attach

Photo by Arget / Unsplash

Our applications aggregate more and more private data that belong to users. We should make everything we can to make out users secure and safe.

The first step to make the app more secure is to prevent a debugger from attaching to the running application. This will make "hacker" work a bit harder.

In the iOS application project, add a file named premain.c. Xcode will ask if You want to create a bridging header and header file for our C file. You can skip these steps if you don't plan to add more Obj-C or C code to the application. Remember to add the .c file to target!

#include "TargetConditionals.h" // contains TARGET_CPU_ARM64 symbol
#import <sys/syscall.h> // contains SYS_ptrace symbol

#if TARGET_CPU_ARM64 && !(DEBUG) // We should only run this for iPhone and in release build

void __attribute__ ((constructor)) premain(void)

        // we are make not possible capturing symbolic breakpoint through b ptrace
        // System calls run in kernel space, hence a bp there is not possible.
        register long x0 asm("x0") = 0x1f; //PT_DENY_ATTACH 31
        register long x1 asm("x1") = 0;
        register long x16 asm("x16") = SYS_ptrace; //ptrace syscall number
        asm volatile(//all args prepared, make the syscall
                     "svc #0x80"
                     :"=r"(x0),"=r"(x1) //mark x0 & x1 as syscall outputs
                     :"r"(x0), "r"(x16): //mark the inputs
                     //inform the compiler we clobber carry flag (during the syscall itself)


The magic here is: void attribute ((constructor)) premain(void) will be called BEFORE application main function! This makes perfect sense because we want to run this code before any shared and dynamic framework is linked to the application.

To test the solution, remove && !(DEBUG) from the top, Xcode will launch the app and as soon as it launches, debugging will be cut off, as expected.

I think this neat code should be in all iOS apps as a basic security measure, whatever your app does. Enjoy!

Artur Gruchała

Artur Gruchała

I started learning iOS development when Swift was introduced. Since then I've tried Xamarin, Flutter, and React Native. Nothing is better than native code:)