这个问题的一个解决方法是使用沙盒环境来注入代码。下面是一个示例代码:
#include
#include
#include
#include
#include
#include
#include
#define PATH_MAX 1024
static char *resolve_binary_path(pid_t pid, char *buff, int len)
{
int mib[4];
size_t size;
int ret;
mib[0] = CTL_KERN;
mib[1] = KERN_PROCARGS2;
mib[2] = pid;
mib[3] = ARG_MAX;
size = len;
ret = sysctl(mib, 4, buff, &size, NULL, 0);
if (ret < 0) {
perror("sysctl KERN_PROCARGS2");
return NULL;
}
return buff + sizeof(int);
}
int inject_with_sandbox(char *proc_path, char *shared_obj_path,
char *class_hash, int hash_len)
{
pid_t pid = getpid();
char buff[PATH_MAX];
char *binary_path = resolve_binary_path(pid, buff, PATH_MAX);
if (binary_path == NULL) {
printf("Error: could not resolve binary path\n");
return -1;
}
printf("Binary path: %s\n", binary_path);
mach_port_t task;
mach_error_t error = task_for_pid(current_task(), pid, &task);
if (error != KERN_SUCCESS) {
printf("Error: could not get task for pid %d (error %s)\n", pid,
mach_error_string(error));
return -1;
}
vm_offset_t target_addr;
error = vm_map_find(target_task, VM_OBJECT_NULL, 0, &target_addr, PAGE_SIZE,
TRUE, VM_PROT_READ | VM_PROT_WRITE, VM_PROT_READ | VM_PROT_WRITE,
VM_INHERIT_DEFAULT);
if (error != KERN_SUCCESS) {
printf("Error: could not allocate target memory (error %s)\n",
mach_error_string(error));
return -1;
}
vm_size_t size;
int fd = open(shared_obj_path, O_RDONLY);
if (fd < 0) {
printf("Error: could not open shared object file %s\n", shared_obj_path);
return -1;
}
struct stat stbuf;
if (fstat(fd, &stbuf) != 0) {
printf("Error: could not determine size of shared object file %s\n", shared_obj_path);
return -1;
}
size = stbuf.st_size;
void *mapping = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapping == MAP_FAILED) {
printf("Error: could not map shared object file %s\n", shared_obj_path);
return -1;
}
memcpy((void *)target_addr, mapping, size);
munmap(mapping, size);
close(fd);
error = mach_vm_write(task, (vm_address_t)binary_path, (vm_offset_t)class_hash,
(mach_msg_size_t)hash_len);
if (error != KERN_SUCCESS) {
printf("Error: could not write to binary path %s (error %s)\n",
binary_path, mach_error_string(error));
return -1;
}
printf("Class hash injected\n");
return 0