task_for_pid error 5

I'm trying to use task_for_pid in a project but I keep getting error code 5 signaling some kind of signing error. Even with this script I cant seem to get it to work.

#include <mach/mach_types.h>
#include <stdlib.h>
#include <mach/mach.h>
#include <mach/mach_error.h>
#include <mach/mach_traps.h>
#include <stdio.h>

int main(int argc, const char * argv[]) {
  task_t task;
  pid_t pid = argc >= 2 ? atoi(argv[1]) : 1;
  kern_return_t error = task_for_pid(mach_task_self(), pid, &task);
  printf("%d -> %x [%d - %s]\n", pid, task, error, mach_error_string(error));
  return error;
}

I've tried signing my executables using codesign and also tried building with Xcode with the "Debugging Tool" box checked under hardened runtime. My Info.plist file includes the SecTaskAccess key with the values "allowed" and "debug." Hoping someone can point me towards what I'm missing here. Thanks!

Replies

task_for_pid is a security vulnerability looking for a place to be exploited, and so modern versions of macOS increasingly restrict its use. This has change so much that I’m a little hazy on the details however, it’s still possible to make it work in certain circumstances AFAIK.

Try this:

  • Make sure that the target process is running an executable with the com.apple.security.get-task-allow entitlement.

  • Make sure the source process is running as root.

Does that work?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"