android 进程注入流程

概述

我们平时所说的代码注入,主要静态和动态两种方式:

静态注入,针对是可执行文件,比如修改ELF,DEX文件等,相关的辅助工具也很多,比如IDA、ApkTool等;

动态注入,也可以叫进程注入,针对是进程,比如修改进程的寄存器、内存值等;

动态跟静态最大的区别是,动态不需要改动源文件,但需要高权限(通常是root权限),而且所需的技术含量更高。

基本思路

关键点在于让目标进加载自定义的动态库so,当so被加载后,so就可以加载其他模块、dex文件等,

具体的注入过程大致如下:

1) attach上目标进程;

2) 让目标进程的执行流程跳转到mmap函数来分配内存空间;

3) 加载注入so;

4) 最后让目标进程的执行流程跳转到注入的代码执行。让目标进程跳转到注入so中的代码执行。

参考:

http://ele7enxxh.com/Android-Shared-Library-Injection.html

http://ele7enxxh.com/Android-Shared-Library-Hook-With-GOT.html

//获取目标进程模块基址

void* get_module_base(pid_t pid, const char* module_name);

//获取远程模块基址

void* get_remote_addr(pid_t target_pid, const char* module_name, void* local_addr);

//根据进程名查找进程id  读取/proc/%d/cmdline获取进程名

int find_pid_of(const char *process_name);

//root inject注入远程进程流程

首先挂载到目标进程 ptrace_attach(target_pid)

读取目标进程寄存器数据 ptrace_getregs(target_pid, &regs)

保存原来的寄存器数据 memcpy(&original_regs, &regs, sizeof(regs));

获取目标进程mmap函数的地址,get_remote_addr(target_pid, libc_path, (void *)mmap);

在目标进程中调用mmap函数,来分配内存空间; ptrace_call_wrapper(target_pid, "mmap", mmap_addr, parameters, 6, &regs)

获取目标进程 dlopen 函数的地址 get_remote_addr( target_pid, linker_path, (void *)dlopen );

获取目标进程 dlsym 函数的地址 get_remote_addr( target_pid, linker_path, (void *)dlsym );

获取目标进程 dlclose 函数的地址 get_remote_addr( target_pid, linker_path, (void *)dlclose );

获取目标进程 dlerror 函数的地址 get_remote_addr( target_pid, linker_path, (void *)dlerror );

往目标进程写入library_path数据 ptrace_writedata(target_pid, map_base, library_path, strlen(library_path) + 1);

让目标进程调用 dlopen 函数 (ptrace_call_wrapper(target_pid, "dlopen", dlopen_addr, parameters, 2, &regs)

让目标进程调用 dlsym 函数 ptrace_call_wrapper(target_pid, "dlsym", dlsym_addr, parameters, 2, &regs)

让目标进程调用 hook_entry 函数 ptrace_call_wrapper(target_pid, function_name, hook_entry_addr, parameters, 1, &regs)

让目标进程调用 dlclose 函数 ptrace_call_wrapper(target_pid, "dlclose", dlclose, parameters, 1, &regs)

恢复寄存器

ptrace_setregs(target_pid, &original_regs);

从目标进程中卸载

ptrace_detach(target_pid);

#include <stdio.h>
#include <stdlib.h>
#include <asm/user.h>
#include <asm/ptrace.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <dlfcn.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <elf.h>
#include <android/log.h>

#if defined(__i386__)
#define pt_regs         user_regs_struct
#endif

#define ENABLE_DEBUG 1

#if ENABLE_DEBUG
#define  LOG_TAG "inject"
#define  LOGD(fmt, args...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG, fmt, ##args)
#define DEBUG_PRINT(format,args...)     LOGD(format, ##args)
#else
#define DEBUG_PRINT(format,args...)
#endif

#define CPSR_T_MASK     ( 1u << 5 )

const char *libc_path = "/system/lib/libc.so";
const char *linker_path = "/system/bin/linker";

//读取进程数据
int ptrace_readdata(pid_t pid,  uint8_t *src, uint8_t *buf, size_t size)
{
    uint32_t i, j, remain;
    uint8_t *laddr;

    union u {
        long val;
        char chars[sizeof(long)];
    } d;

    j = size / 4;
    remain = size % 4;

    laddr = buf;

    for (i = 0; i < j; i ++) {
    	//拷贝src指向的数据
        d.val = ptrace(PTRACE_PEEKTEXT, pid, src, 0);
        memcpy(laddr, d.chars, 4);
        src += 4;
        laddr += 4;
    }

    if (remain > 0) {
        d.val = ptrace(PTRACE_PEEKTEXT, pid, src, 0);
        memcpy(laddr, d.chars, remain);
    }

    return 0;
}

//往进程写入数据
int ptrace_writedata(pid_t pid, uint8_t *dest, uint8_t *data, size_t size)
{
    uint32_t i, j, remain;
    uint8_t *laddr;

    union u {
        long val;
        char chars[sizeof(long)];
    } d;

    j = size / 4;
    remain = size % 4;

    laddr = data;

    for (i = 0; i < j; i ++) {
        memcpy(d.chars, laddr, 4);
        ptrace(PTRACE_POKETEXT, pid, dest, d.val);

        dest  += 4;
        laddr += 4;
    }

    if (remain > 0) {
        d.val = ptrace(PTRACE_PEEKTEXT, pid, dest, 0);
        for (i = 0; i < remain; i ++) {
            d.chars[i] = *laddr ++;
        }

        ptrace(PTRACE_POKETEXT, pid, dest, d.val);
    }

    return 0;
}

#if defined(__arm__)
int ptrace_call(pid_t pid, uint32_t addr, long *params, uint32_t num_params, struct pt_regs* regs)
{
    uint32_t i;
    for (i = 0; i < num_params && i < 4; i ++) {
        regs->uregs[i] = params[i];
    }

    //
    // push remained params onto stack
    //
    if (i < num_params) {
        regs->ARM_sp -= (num_params - i) * sizeof(long) ;
        ptrace_writedata(pid, (void *)regs->ARM_sp, (uint8_t *)¶ms[i], (num_params - i) * sizeof(long));
    }

    regs->ARM_pc = addr;
    if (regs->ARM_pc & 1) {
        /* thumb */
        regs->ARM_pc &= (~1u);
        regs->ARM_cpsr |= CPSR_T_MASK;
    } else {
        /* arm */
        regs->ARM_cpsr &= ~CPSR_T_MASK;
    }

    regs->ARM_lr = 0;

    if (ptrace_setregs(pid, regs) == -1
            || ptrace_continue(pid) == -1) {
        printf("error\n");
        return -1;
    }

    int stat = 0;
    waitpid(pid, &stat, WUNTRACED);
    while (stat != 0xb7f) {
        if (ptrace_continue(pid) == -1) {
            printf("error\n");
            return -1;
        }
        waitpid(pid, &stat, WUNTRACED);
    }

    return 0;
}

#elif defined(__i386__)
long ptrace_call(pid_t pid, uint32_t addr, long *params, uint32_t num_params, struct user_regs_struct * regs)
{
    regs->esp -= (num_params) * sizeof(long) ;
    ptrace_writedata(pid, (void *)regs->esp, (uint8_t *)params, (num_params) * sizeof(long));

    long tmp_addr = 0x00;
    regs->esp -= sizeof(long);
    ptrace_writedata(pid, regs->esp, (char *)&tmp_addr, sizeof(tmp_addr));

    regs->eip = addr;

    if (ptrace_setregs(pid, regs) == -1
            || ptrace_continue( pid) == -1) {
        printf("error\n");
        return -1;
    }

    int stat = 0;
    waitpid(pid, &stat, WUNTRACED);
    while (stat != 0xb7f) {
        if (ptrace_continue(pid) == -1) {
            printf("error\n");
            return -1;
        }
        waitpid(pid, &stat, WUNTRACED);
    }

    return 0;
}
#else
#error "Not supported"
#endif

//读取进程寄存器数据
int ptrace_getregs(pid_t pid, struct pt_regs * regs)
{
    if (ptrace(PTRACE_GETREGS, pid, NULL, regs) < 0) {
        perror("ptrace_getregs: Can not get register values");
        return -1;
    }

    return 0;
}

//设置进程寄存器
int ptrace_setregs(pid_t pid, struct pt_regs * regs)
{
    if (ptrace(PTRACE_SETREGS, pid, NULL, regs) < 0) {
        perror("ptrace_setregs: Can not set register values");
        return -1;
    }

    return 0;
}
//进程继续指向
int ptrace_continue(pid_t pid)
{
    if (ptrace(PTRACE_CONT, pid, NULL, 0) < 0) {
        perror("ptrace_cont");
        return -1;
    }

    return 0;
}
//挂载到目标进程
int ptrace_attach(pid_t pid)
{
    if (ptrace(PTRACE_ATTACH, pid, NULL, 0) < 0) {
        perror("ptrace_attach");
        return -1;
    }

    int status = 0;
    waitpid(pid, &status , WUNTRACED);

    return 0;
}
//从目标进程中卸载
int ptrace_detach(pid_t pid)
{
    if (ptrace(PTRACE_DETACH, pid, NULL, 0) < 0) {
        perror("ptrace_detach");
        return -1;
    }

    return 0;
}

//获取目标进程模块基址
void* get_module_base(pid_t pid, const char* module_name)
{
    FILE *fp;
    long addr = 0;
    char *pch;
    char filename[32];
    char line[1024];

    if (pid < 0) {
        /* self process */
        snprintf(filename, sizeof(filename), "/proc/self/maps", pid);
    } else {
        snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
    }

    fp = fopen(filename, "r");

    if (fp != NULL) {
        while (fgets(line, sizeof(line), fp)) {
            if (strstr(line, module_name)) {
                pch = strtok( line, "-" );
                addr = strtoul( pch, NULL, 16 );

                if (addr == 0x8000)
                    addr = 0;

                break;
            }
        }

        fclose(fp) ;
    }

    return (void *)addr;
}

//获取远程模块基址
void* get_remote_addr(pid_t target_pid, const char* module_name, void* local_addr)
{
    void* local_handle, *remote_handle;

    local_handle = get_module_base(-1, module_name);
    remote_handle = get_module_base(target_pid, module_name);

    DEBUG_PRINT("[+] get_remote_addr: local[%x], remote[%x]\n", local_handle, remote_handle);

    void * ret_addr = (void *)((uint32_t)local_addr + (uint32_t)remote_handle - (uint32_t)local_handle);

#if defined(__i386__)
    if (!strcmp(module_name, libc_path)) {
        ret_addr += 2;
    }
#endif
    return ret_addr;
}
//根据进程名查找进程id  读取/proc/%d/cmdline获取进程名
int find_pid_of(const char *process_name)
{
    int id;
    pid_t pid = -1;
    DIR* dir;
    FILE *fp;
    char filename[32];
    char cmdline[256];

    struct dirent * entry;

    if (process_name == NULL)
        return -1;

    dir = opendir("/proc");
    if (dir == NULL)
        return -1;

    while((entry = readdir(dir)) != NULL) {
        id = atoi(entry->d_name);
        if (id != 0) {
            sprintf(filename, "/proc/%d/cmdline", id);
            fp = fopen(filename, "r");
            if (fp) {
                fgets(cmdline, sizeof(cmdline), fp);
                fclose(fp);

                if (strcmp(process_name, cmdline) == 0) {
                    /* process found */
                    pid = id;
                    break;
                }
            }
        }
    }

    closedir(dir);
    return pid;
}

long ptrace_retval(struct pt_regs * regs)
{
#if defined(__arm__)
    return regs->ARM_r0;
#elif defined(__i386__)
    return regs->eax;
#else
#error "Not supported"
#endif
}

long ptrace_ip(struct pt_regs * regs)
{
#if defined(__arm__)
    return regs->ARM_pc;
#elif defined(__i386__)
    return regs->eip;
#else
#error "Not supported"
#endif
}

int ptrace_call_wrapper(pid_t target_pid, const char * func_name, void * func_addr, long * parameters, int param_num, struct pt_regs * regs)
{
    DEBUG_PRINT("[+] Calling %s in target process.\n", func_name);
    if (ptrace_call(target_pid, (uint32_t)func_addr, parameters, param_num, regs) == -1)
        return -1;

    if (ptrace_getregs(target_pid, regs) == -1)
        return -1;
    DEBUG_PRINT("[+] Target process returned from %s, return value=%x, pc=%x \n",
            func_name, ptrace_retval(regs), ptrace_ip(regs));
    return 0;
}

//注入远程进程数据
int inject_remote_process(pid_t target_pid, const char *library_path, const char *function_name, const char *param, size_t param_size)
{
    int ret = -1;
    void *mmap_addr, *dlopen_addr, *dlsym_addr, *dlclose_addr, *dlerror_addr;
    void *local_handle, *remote_handle, *dlhandle;
    uint8_t *map_base = 0;
    uint8_t *dlopen_param1_ptr, *dlsym_param2_ptr, *saved_r0_pc_ptr, *inject_param_ptr, *remote_code_ptr, *local_code_ptr;

    struct pt_regs regs, original_regs;
    extern uint32_t _dlopen_addr_s, _dlopen_param1_s, _dlopen_param2_s, _dlsym_addr_s,         _dlsym_param2_s, _dlclose_addr_s, _inject_start_s, _inject_end_s, _inject_function_param_s,         _saved_cpsr_s, _saved_r0_pc_s;

    uint32_t code_length;
    long parameters[10];

    DEBUG_PRINT("[+] Injecting process: %d\n", target_pid);
    //首先挂载到目标进程
    if (ptrace_attach(target_pid) == -1)
        goto exit;
    //读取目标进程寄存器数据
    if (ptrace_getregs(target_pid, &regs) == -1)
        goto exit;

    /* save original registers 保存原来的寄存器数据*/
    memcpy(&original_regs, &regs, sizeof(regs));
    //获取目标进程mmap函数的地址
    mmap_addr = get_remote_addr(target_pid, libc_path, (void *)mmap);
    DEBUG_PRINT("[+] Remote mmap address: %x\n", mmap_addr);

    /* call mmap */
    parameters[0] = 0;  // addr
    parameters[1] = 0x4000; // size
    parameters[2] = PROT_READ | PROT_WRITE | PROT_EXEC;  // prot
    parameters[3] =  MAP_ANONYMOUS | MAP_PRIVATE; // flags
    parameters[4] = 0; //fd
    parameters[5] = 0; //offset

    //在目标进程中调用mmap函数
    if (ptrace_call_wrapper(target_pid, "mmap", mmap_addr, parameters, 6, &regs) == -1)
        goto exit;

    map_base = ptrace_retval(&regs);
    //获取目标进程 dlopen 函数的地址
    dlopen_addr = get_remote_addr( target_pid, linker_path, (void *)dlopen );
     //获取目标进程 dlsym 函数的地址
    dlsym_addr = get_remote_addr( target_pid, linker_path, (void *)dlsym );
     //获取目标进程 dlclose 函数的地址
    dlclose_addr = get_remote_addr( target_pid, linker_path, (void *)dlclose );
    //获取目标进程 dlerror 函数的地址
    dlerror_addr = get_remote_addr( target_pid, linker_path, (void *)dlerror );

    DEBUG_PRINT("[+] Get imports: dlopen: %x, dlsym: %x, dlclose: %x, dlerror: %x\n",
            dlopen_addr, dlsym_addr, dlclose_addr, dlerror_addr);

    printf("library path = %s\n", library_path);
    //往目标进程写入library_path数据
    ptrace_writedata(target_pid, map_base, library_path, strlen(library_path) + 1);

    parameters[0] = map_base;
    parameters[1] = RTLD_NOW| RTLD_GLOBAL;
    //让目标进程调用 dlopen 函数
    if (ptrace_call_wrapper(target_pid, "dlopen", dlopen_addr, parameters, 2, &regs) == -1)
        goto exit;

    void * sohandle = ptrace_retval(&regs);

#define FUNCTION_NAME_ADDR_OFFSET       0x100
    ptrace_writedata(target_pid, map_base + FUNCTION_NAME_ADDR_OFFSET, function_name, strlen(function_name) + 1);
    parameters[0] = sohandle;
    parameters[1] = map_base + FUNCTION_NAME_ADDR_OFFSET;
    //让目标进程调用 dlsym 函数
    if (ptrace_call_wrapper(target_pid, "dlsym", dlsym_addr, parameters, 2, &regs) == -1)
        goto exit;

    void * hook_entry_addr = ptrace_retval(&regs);
    DEBUG_PRINT("hook_entry_addr = %p\n", hook_entry_addr);

#define FUNCTION_PARAM_ADDR_OFFSET      0x200
    ptrace_writedata(target_pid, map_base + FUNCTION_PARAM_ADDR_OFFSET, param, strlen(param) + 1);
    parameters[0] = map_base + FUNCTION_PARAM_ADDR_OFFSET;

    ////让目标进程调用 hook_entry 函数
    if (ptrace_call_wrapper(target_pid, function_name, hook_entry_addr, parameters, 1, &regs) == -1)
        goto exit;

    printf("Press enter to dlclose and detach\n");

    //getchar();
    parameters[0] = sohandle;

   // if (ptrace_call_wrapper(target_pid, "dlclose", dlclose, parameters, 1, &regs) == -1)
     //   goto exit;

    /* restore 恢复寄存器*/
    ptrace_setregs(target_pid, &original_regs);
    //卸载目标进程
    ptrace_detach(target_pid);
    ret = 0;

exit:
    return ret;
}

int main(int argc, char** argv) {
    pid_t target_pid;
    target_pid = find_pid_of("com.estoty.game2048");//also can pass target pid or target process by param
    if (-1 == target_pid) {
        printf("Can't find the process\n");
        return -1;
    }
	printf("target_pid=%d argc=%d\n ",target_pid,argc);
	char* sopath="/data/local/tmp/libpackage.so";
	if(argc>1)
	{
		sopath=argv[1];
	}
	char* main_entry="main_entry";
	if(argc>2)
	{
		main_entry=argv[2];
	}
	char* parameter="parameter";
	if(argc>3)
	{
		parameter=argv[3];
	}

	printf("inject_remote_process start\n");
    inject_remote_process(target_pid, sopath, main_entry,  parameter, strlen(parameter));
    return 0;
}

注入目标进程,执行注入代码

1.attach上目标进程

ptrace_attach(target_pid)

2.获取目标进程寄存器,并复制一份保存,以便在注入完成后恢复目标进程

ptrace_getregs(target_pid, &regs)

3.取目标进程mmap函数地址

get_remote_func_address(target_pid, libc_path, (void *) mmap);

4.调用目标进程mmap函数分配一块内存

ptrace_call_wrapper(target_pid, "mmap", target_mmap_addr, parameters, 6, &regs)

得到mmap分配的内存地址

uint8_t *target_mmap_base = ptrace_retval(&regs);

5.调用目标进程dlopen函数加载注入so

取目标进程dlopen函数地址

get_remote_func_address(target_pid, linker_path, (void *) dlopen);

把注入so地址写入目标进程

ptrace_writedata(target_pid, target_mmap_base, library_path,strlen(library_path) + 1);

//通过ptrace调用函数

(ptrace_call_wrapper(target_pid, "dlopen", target_dlopen_addr, parameters, 2,&regs)

6.调用dlsym取注入so库执行函数的地址

取目标进程dlsym函数的地址

get_remote_func_address(target_pid, linker_path, (void *) dlsym);

//把函数名称字符串写进目标进程

ptrace_writedata(target_pid, target_mmap_base + FUNCTION_NAME_ADDR_OFFSET,function_name, strlen(function_name) + 1);

7.调用hook函数

写入函数需要的参数

ptrace_writedata(target_pid, target_mmap_base + FUNCTION_PARAM_ADDR_OFFSET, param,strlen(param) + 1);

8.调用dlclose卸载注入so

get_remote_func_address(target_pid, linker_path, (void *) dlclose);

9.恢复现场

ptrace_setregs(target_pid, &original_regs);

10.detach

ptrace_detach(target_pid);

时间: 2024-10-15 03:42:27

android 进程注入流程的相关文章

Android进程注入

全部代码在这里下载:http://download.csdn.net/detail/a345017062/8133239 里面有两个exe.inj是一个C层进程注入的样例.inj_dalvik是我写的Java注入.C层的进程注入借直接拉的洗大师的开源项目(https://code.google.com/p/libandroidinjector/) Android的基础服务大部分都是使用Java写的,仅仅是C层的注入,想要直接訪问的话还是比較麻烦.所以须要在远端载入一个dex包(代码中写死了载入/

理解Android进程创建流程(转)

/frameworks/base/core/java/com/android/internal/os/ - ZygoteInit.java - ZygoteConnection.java - RuntimeInit.java - Zygote.java /frameworks/base/core/java/android/os/Process.java /frameworks/base/core/jni/com_android_internal_os_Zygote.cpp /frameworks

Android中通过进程注入技术修改系统返回的Mac地址

致谢 感谢看雪论坛中的这位大神,分享了这个技术:http://bbs.pediy.com/showthread.php?t=186054,从这篇文章中学习到了很多内容,如果没有这篇好文章,我在研究的过程中会遇到很多困难,说不定我就放弃了~~在此感谢他. 前言 之前的几篇文章都是在介绍了OC的相关知识,之前的半个月也都是在搞IOS的相关东西,白天上班做Android工作,晚上回家还有弄IOS,感觉真的很伤了.不过OC的知识也学习了差不多了.不过在这段时间遗留了很多Android方面的问题都没有进行

Android中通过进程注入技术修改广播接收器的优先级

前言 这个周末又没有吊事,在家研究了如何通过进程的注入技术修改广播接收器的优先级,关于这个应用场景是很多的,而且也很重要,所以就很急的去fixed了. Android中的四大组件中有一个广播:Broadcast 关于它的相关知识可以转战:http://blog.csdn.net/jiangwei0910410003/article/details/19150705 我们这里就不做太多解释了,现在来看一下问题: 知识前提 这篇文章和我之前介绍一篇文章: Andrdoid中对应用程序的行为拦截实现方

android源码解析之(八)--&gt;Zygote进程启动流程

大家都知道android系统的Zygote进程是所有的android进程的父进程,包括SystemServer和各种应用进程都是通过Zygote进程fork出来的.Zygote(孵化)进程相当于是android系统的根进程,后面所有的进程都是通过这个进程fork出来的,而Zygote进程则是通过linux系统的init进程启动的,也就是说,android系统中各种进程的启动方式 init进程 –> Zygote进程 –> SystemServer进程 –>各种应用进程 init进程:li

Android so注入( inject)和Hook技术学习(一)

以前对Android so的注入只是通过现有的框架,并没有去研究so注入原理,趁现在有时间正好拿出来研究一下. 首先来看注入流程.Android so的注入流程如下: attach到远程进程 -> 保存寄存器环境 -> 获取目标程序的mmap, dlopen, dlsym, dlclose 地址 -> 远程调用mmap函数申请内存空间用来保存参数信息 -> 向远程进程内存空间写入加载模块名和调用函数->远程调用dlopen函数加载so文件 -> 远程调用dlsym函数获

Android so注入(inject)和Hook技术学习(三)——Got表hook之导出表hook

前文介绍了导入表hook,现在来说下导出表的hook.导出表的hook的流程如下.1.获取动态库基值 1 void* get_module_base(pid_t pid, const char* module_name){ 2 FILE* fp; 3 long addr = 0; 4 char* pch; 5 char filename[32]; 6 char line[1024]; 7 8 // 格式化字符串得到 "/proc/pid/maps" 9 if(pid < 0){

Android进程与线程基本知识

Android进程与线程基本知识 本文介绍Android平台中进程与线程的基本知识. 很早的时候就想介绍一下Android中的进程和线程,但由于其他的事情一直给耽搁了,直到现在才能和大家一起分享下. 1.Android进程基本知识: 我们先来了解下Android中的进程基本知识. 当一个程序第一次启动的时候,Android会启动一个LINUX进程和一个主线程.默认的情况下,所有该程序的组件都将在该进程和线程中运行. 同时,Android会为每个应用程序分配一个单独的LINUX用户.Android

Android -- Wifi连接流程分析

Android -- Wifi连接流程分析 当我们在Android手机上连接一个AP时,间接调用WifiManager的connect()方法: /** * Connect to a network with the given configuration. The network also * gets added to the supplicant configuration. * * For a new network, this function is used instead of a