10

I'm trying to call a function on ptrace like thisptrace(PT_DENY_ATTACH, 0, 0, 0); But when I try to import it using #include <sys/ptrace.h>Xcode gives me an error 'sys/ptrace.h' file not found. Am I missing something, do I need to import a library or is this simply unavailable on iOS?

imas145
  • 1,959
  • 1
  • 23
  • 32

2 Answers2

4

The problem here is that Xcode is prepending its SDK base path to all system header paths (e.g., /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk/usr/include/). Unfortunately, ptrace.h is not there but is found in /usr/include/sys/. So, to solve this, you need to change your include statement to be:

#include </usr/include/sys/ptrace.h>

I have no idea why ptrace.h is not included in the SDK but the functionality you're looking for does work when it's running on the phone.

Update: While this does allow you to use the ptrace functionality, uploading to Apple will result in app rejection due to:

Non-public API usage:

The app references non-public symbols in <app name>: _ptrace
mcsheffrey
  • 508
  • 4
  • 16
2

This seems to be working for me and will prevent attaching the debugger. I have not tested the #ifdef OPTIMIZE if it works in distribution, so let me know if you find any problems.

//#include <sys/ptrace.h>
#import <dlfcn.h>
#import <sys/types.h>

typedef int (*ptrace_ptr_t)(int _request, pid_t _pid, caddr_t _addr, int _data);
#if !defined(PT_DENY_ATTACH)
#define PT_DENY_ATTACH 31
#endif  // !defined(PT_DENY_ATTACH)

void disable_gdb() {
    void* handle = dlopen(0, RTLD_GLOBAL | RTLD_NOW);
    ptrace_ptr_t ptrace_ptr = dlsym(handle, "ptrace");
    ptrace_ptr(PT_DENY_ATTACH, 0, 0, 0);
    dlclose(handle);
}

int main(int argc, char *argv[]) {

//#ifndef DEBUG => use the following instead.
 #ifdef __OPTIMIZE__
    //ptrace(PT_DENY_ATTACH, 0, 0, 0);
    disable_gdb();
#endif
Nikolay DS
  • 1,367
  • 1
  • 8
  • 8
  • The code compiles, but it still doesn't work as expected (deny the attachment of a debugger). I created a single-view iOS test app and only modified the main.m file. If I'm not completely mistaken, Xcode (or any debugger) shouldn't be able to attach to it. In case of Xcode, it shouldn't even launch. But the app runs fine... To further test this, I placed an NSLog inside disable_gdb method, and it never got printed. Is there something I need to do to make the #ifndef DEBUG work? – imas145 May 22 '15 at 17:21
  • Yes, I am manually putting DEBUG in my project as precompile definition for DEBUG builds. There are other newer ways (usinf DEBUG_BUILD = 1) or __OPTIMIZE__, but my is older code. – Nikolay DS May 22 '15 at 17:38
  • this code works but it is relatively easy to bypass... – rustyMagnet Oct 01 '20 at 12:52