Elevating rights to use mach_inject
You don't need to be root to use mach_inject; instead, you need to sign your code. For testing purposes only (and in 10.4/10.5) you can also make your application setgid procmod.
See TN2206 for more information.
Old question, but incorrect answer:
Unless you own the pid/task, you actually do need to EITHER be root or be a member of procmod. In OS X, this has little to do with code signing. Mach_inject/Mach_star use by the Mach trap task_for_pid(), which requires the above privileges. In iOS , you also need the corresponding entitlement (task_for_pid-allow), which is where code signing would come in handy (using ldid for self signing).
For those who wish to use mach_inject (which uses task_for_pid() internally) for macOS 10.11 and above, you will need to add the proper entitlement for this to work. Then run with sudo. See the example below: https://gist.github.com/attilathedud/e58917c9fd095a84fd5bbfb31674be05
/*
Full explanation is available here: http://attilathedud.me/mac-os-x-el-capitan-10-11-and-task_for_pid/
*/
/*
To compile, create a file called Info.plist with the following content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SecTaskAccess</key>
<array>
<string>allowed</string>
</array>
</dict>
</plist>
When compiling, use -sectcreate to create a section for the plist:
gcc task_for_pid.c -sectcreate __TEXT __info_plist ./Info.plist -o task_for_pid
Run using sudo ./task_for_pid _some_pid
*/
/*!
* task_for_pid.c: Given a pid in argv[ 1 ], return the mach task port.
*/
#include <stdio.h>
#include <stdlib.h>
#include <mach/mach.h>
int main( int argc, char** argv )
{
kern_return_t kern_return = 0;
mach_port_t task = 0;
long int pid = 0;
char *endptr = NULL;
if( argc < 2 )
{
return 0;
}
pid = strtol( argv[ 1 ], &endptr, 10 );
kern_return = task_for_pid( mach_task_self(), pid, &task );
if( kern_return != KERN_SUCCESS )
{
printf( "task_for_pid failed: %s\n", mach_error_string( kern_return ) );
return 0;
}
printf( "%u\n", task );
return 0;
}
You can do this with both terminal programs and cocoa apps as long as at least that entitlement is set and you have the right privileges.