Skip to content

Instantly share code, notes, and snippets.

@knightsc
Last active April 17, 2022 01:04
Show Gist options
  • Save knightsc/06a1b74b779690e8e491c21a3883c7a7 to your computer and use it in GitHub Desktop.
Save knightsc/06a1b74b779690e8e491c21a3883c7a7 to your computer and use it in GitHub Desktop.
Loops through all running processes and prints out ones that have had threads injected or hijacked
#include <stdio.h>
#include <stdlib.h>
#include <libproc.h>
#include <mach/mach.h>
bool
has_modifications(struct task_extmod_info *info)
{
if ((info->extmod_statistics.thread_creation_count > 0) ||
(info->extmod_statistics.thread_set_state_count > 0)) {
return true;
}
return false;
}
void
print_process_info(pid_t pid, struct proc_taskallinfo *pidinfo, struct task_extmod_info *info)
{
printf("PID: %d\n", pid);
printf("Name: %s\n", pidinfo->pbsd.pbi_name);
printf("External Modification Summary:\n");
printf(" Calls made by other processes targeting this process:\n");
printf(" task_for_pid: %lld\n", info->extmod_statistics.task_for_pid_count);
printf(" thread_create: %lld\n", info->extmod_statistics.thread_creation_count);
printf(" thread_set_state: %lld\n\n", info->extmod_statistics.thread_set_state_count);
}
int
task_extmod_info_for_pid(pid_t pid, struct task_extmod_info *info)
{
task_name_t task;
mach_msg_type_number_t count = TASK_EXTMOD_INFO_COUNT;
kern_return_t kr;
kr = task_name_for_pid(mach_task_self(), pid, &task);
if (kr != KERN_SUCCESS) {
return kr;
}
kr = task_info(task, TASK_EXTMOD_INFO, (task_info_t)info, &count);
if (kr != KERN_SUCCESS) {
fprintf(stderr, "Error getting info from task 0x%x: %s\n", task, mach_error_string(kr));
return kr;
}
kr = mach_port_deallocate(mach_task_self(), task);
if (kr != KERN_SUCCESS) {
fprintf(stderr, "Error deallocating task: %s\n", mach_error_string(kr));
return kr;
}
return 0;
}
int
main(int argc, char *argv[])
{
int num_pids;
pid_t *pids;
struct proc_taskallinfo pidinfo;
struct task_extmod_info info;
int i;
num_pids = proc_listallpids(NULL, 0);
pids = calloc(num_pids, sizeof(pid_t));
num_pids = proc_listallpids(pids, num_pids * sizeof(pids));
for (i = 0; i < num_pids; i++) {
memset(&pidinfo, 0, sizeof(pidinfo));
memset(&info, 0, sizeof(info));
proc_pidinfo(pids[i], PROC_PIDTASKALLINFO, 0, &pidinfo, sizeof(pidinfo));
if (task_extmod_info_for_pid(pids[i], &info) != 0) {
// No need to log, if we're not root then we can't scan all processes
continue;
}
if (has_modifications(&info)) {
print_process_info(pids[i], &pidinfo, &info);
}
}
free(pids);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment