Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android6.0 X86 ARM64位可用的注入Inject

Android6.0 X86 ARM64位可用的注入Inject

編輯:關於Android編程

最近在網上搜索Android的Inject與Hook,發現很多都因為時間久遠而失效了,試了很多方案,最終找到了一個,特地來轉載分享一下,本人的三星S6 6.0.1系統測試可用,另外4.2 4.4也都測試通過。

1.inject.c

#include     
#include     
#include     
#include     
#include     
#include     
#include     
#include     
#include     
#include     
#include     
#include     
#include     
#include 
    
#if defined(__i386__)    
#define pt_regs         user_regs_struct    
#elif defined(__aarch64__)
#define pt_regs         user_pt_regs  
#define uregs	regs
#define ARM_pc	pc
#define ARM_sp	sp
#define ARM_cpsr	pstate
#define ARM_lr		regs[30]
#define ARM_r0		regs[0]  
#define PTRACE_GETREGS PTRACE_GETREGSET
#define PTRACE_SETREGS PTRACE_SETREGSET
#endif    
    
#define ENABLE_DEBUG 1    
    
#if ENABLE_DEBUG    
#define  LOG_TAG "INJECT"    
#define  LOGD(fmt, args...)  __android_log_print(ANDROID_LOG_DEBUG,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 )    
    
#if defined(__aarch64__)    
const char *libc_path = "/system/lib64/libc.so";    
const char *linker_path = "/system/bin/linker64";    
#else
const char *libc_path = "/system/lib/libc.so";    
const char *linker_path = "/system/bin/linker";    
#endif
    
int ptrace_readdata(pid_t pid,  uint8_t *src, uint8_t *buf, size_t size)    
{    
    long i, j, remain;    
    uint8_t *laddr;       
    size_t bytes_width = sizeof(long);
	
    union u {    
        long val;    
        char chars[bytes_width];    
    } d;    
    
    j = size / bytes_width;    
    remain = size % bytes_width;    
    
    laddr = buf;    
    
    for (i = 0; i < j; i ++) {    
        d.val = ptrace(PTRACE_PEEKTEXT, pid, src, 0);    
        memcpy(laddr, d.chars, bytes_width);    
        src += bytes_width;    
        laddr += bytes_width;    
    }    
    
    if (remain > 0) {    
        d.val = ptrace(PTRACE_PEEKTEXT, pid, src, 0);    
        memcpy(laddr, d.chars, remain);    
    }    
    
    return 0;    
}    

/*
Func : 將size字節的data數據寫入到pid進程的dest地址處
@param dest: 目的進程的棧地址
@param data: 需要寫入的數據的起始地址
@param size: 需要寫入的數據的大小,以字節為單位
*/
int ptrace_writedata(pid_t pid, uint8_t *dest, uint8_t *data, size_t size)    
{    
    long i, j, remain;    
    uint8_t *laddr;    
    size_t bytes_width = sizeof(long);
	
	//很巧妙的聯合體,這樣就可以方便的以字節為單位寫入4字節數據,再以long為單位ptrace_poketext到棧中  
    union u {    
        long val;    
        char chars[bytes_width];    
    } d;    
    
    j = size / bytes_width;    
    remain = size % bytes_width;    
    
    laddr = data;

	//先以4字節為單位進行數據寫入
    
    for (i = 0; i < j; i ++) {    
        memcpy(d.chars, laddr, bytes_width);    
        ptrace(PTRACE_POKETEXT, pid, dest, d.val);    
    
        dest  += bytes_width;    
        laddr += bytes_width;    
    }    
    
    if (remain > 0) {
		//為了最大程度的保持原棧的數據,先讀取dest的long數據,然後只更改其中的前remain字節,再寫回
        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;    
}    

/*
功能總結:
1,將要執行的指令寫入寄存器中,指令長度大於4個long的話,需要將剩余的指令通過ptrace_writedata函數寫入棧中;
2,使用ptrace_continue函數運行目的進程,直到目的進程返回狀態值0xb7f(對該值的分析見後面紅字);
3,函數執行完之後,目標進程掛起,使用ptrace_getregs函數獲取當前的所有寄存器值,方便後面使用ptrace_retval函數獲取函數的返回值。
*/
#if defined(__arm__) || defined(__aarch64__)
int ptrace_call(pid_t pid, uintptr_t addr, long *params, int num_params, struct pt_regs* regs)    
{    
    int i;   
#if defined(__arm__) 
    int num_param_registers = 4;
#elif defined(__aarch64__) 
    int num_param_registers = 8;
#endif

    for (i = 0; i < num_params && i < num_param_registers; 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 *)& params[i], (num_params - i) * sizeof(long));    
    }    
    //將PC寄存器值設為目標函數的地址
    regs->ARM_pc = addr; 
	//進行指令集判斷 
    if (regs->ARM_pc & 1) {    
        /* thumb */    
        regs->ARM_pc &= (~1u);    
		// #define CPSR_T_MASK  ( 1u << 5 )  CPSR為程序狀態寄存器
        regs->ARM_cpsr |= CPSR_T_MASK;    
    } else {    
        /* arm */    
        regs->ARM_cpsr &= ~CPSR_T_MASK;    
    }    
	
    //設置子程序的返回地址為空,以便函數執行完後,返回到null地址,產生SIGSEGV錯誤,詳細作用見後面的紅字分析
    regs->ARM_lr = 0;    
    
	/*
    *Ptrace_setregs就是將修改後的regs寫入寄存器中,然後調用ptrace_continue來執行我們指定的代碼
    */
    if (ptrace_setregs(pid, regs) == -1     
            || ptrace_continue(pid) == -1) {    
        printf("error\n");    
        return -1;    
    }    
    
    int stat = 0;  
    waitpid(pid, &stat, WUNTRACED);  
	/* WUNTRACED告訴waitpid,如果子進程進入暫停狀態,那麼就立即返回。如果是被ptrace的子進程,那麼即使不提供WUNTRACED參數,也會在子進程進入暫停狀態的時候立即返回。
	對於使用ptrace_cont運行的子進程,它會在3種情況下進入暫停狀態:①下一次系統調用;②子進程退出;③子進程的執行發生錯誤。這裡的0xb7f就表示子進程進入了暫停狀態,且發送的錯誤信號為11(SIGSEGV),它表示試圖訪問未分配給自己的內存, 或試圖往沒有寫權限的內存地址寫數據。那麼什麼時候會發生這種錯誤呢?顯然,當子進程執行完注入的函數後,由於我們在前面設置了regs->ARM_lr = 0,它就會返回到0地址處繼續執行,這樣就會產生SIGSEGV了!*/
    
	//這個循環是否必須我還不確定。因為目前每次ptrace_call調用必定會返回0xb7f,不過在這也算是增加容錯性吧~
	
	//通過看ndk的源碼sys/wait.h以及man waitpid可以知道這個0xb7f的具體作用。首先說一下stat的值:高2字節用於表示導致子進程的退出或暫停狀態信號值,低2字節表示子進程是退出(0x0)還是暫停(0x7f)狀態。0xb7f就表示子進程為暫停狀態,導致它暫停的信號量為11即sigsegv錯誤。
	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, uintptr_t addr, long *params, int 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 defined (__aarch64__)
		int regset = NT_PRSTATUS;
		struct iovec ioVec;
		
		ioVec.iov_base = regs;
		ioVec.iov_len = sizeof(*regs);
    if (ptrace(PTRACE_GETREGSET, pid, (void*)regset, &ioVec) < 0) {    
        perror("ptrace_getregs: Can not get register values");   
        printf(" io %llx, %d", ioVec.iov_base, ioVec.iov_len); 
        return -1;    
    }    
    
    return 0;   
#else
    if (ptrace(PTRACE_GETREGS, pid, NULL, regs) < 0) {    
        perror("ptrace_getregs: Can not get register values");    
        return -1;    
    }    
    
    return 0;   
#endif     
}    
    
int ptrace_setregs(pid_t pid, struct pt_regs * regs)    
{     
#if defined (__aarch64__)
		int regset = NT_PRSTATUS;
		struct iovec ioVec;
		
		ioVec.iov_base = regs;
		ioVec.iov_len = sizeof(*regs);
    if (ptrace(PTRACE_SETREGSET, pid, (void*)regset, &ioVec) < 0) {    
        perror("ptrace_setregs: Can not get register values");    
        return -1;    
    }    
    
    return 0;   
#else
    if (ptrace(PTRACE_SETREGS, pid, NULL, regs) < 0) {    
        perror("ptrace_setregs: Can not set register values");    
        return -1;    
    }    
    
    return 0;   
#endif     
}    
    
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;    
}


//顯然,這裡面核心的就是get_module_base函數:
/*
此函數的功能就是通過遍歷/proc/pid/maps文件,來找到目的module_name的內存映射起始地址。
由於內存地址的表達方式是startAddrxxxxxxx-endAddrxxxxxxx的,所以會在後面使用strtok(line,"-")來分割字符串
如果pid = -1,表示獲取本地進程的某個模塊的地址,
否則就是pid進程的某個模塊的地址。
*/    
    
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)) {
				//分解字符串為一組字符串。line為要分解的字符串,"-"為分隔符字符串。
                pch = strtok( line, "-" );
				//將參數pch字符串根據參數base(表示進制)來轉換成無符號的長整型數  
                addr = strtoull( pch, NULL, 16 );   
    
                if (addr == 0x8000)    
                    addr = 0;    
    
                break;    
            }    
        }    
    
        fclose(fp) ;    
    }    
    
    return (void *)addr;    
}    

/*
該函數為一個封裝函數,通過調用get_module_base函數來獲取目的進程的某個模塊的起始地址,然後通過公式計算出指定函數在目的進程的起始地址。
*/
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);
    //獲取遠程pid的某個模塊的起始地址
    remote_handle = get_module_base(target_pid, module_name);    
    
    DEBUG_PRINT("[+] get_remote_addr: local[%llx], remote[%llx]\n", local_handle, remote_handle);    
    /*這需要我們好好理解:local_addr - local_handle的值為指定函數(如mmap)在該模塊中的偏移量,然後再加上rempte_handle,結果就為指定函數在目的進程的虛擬地址*/
    void * ret_addr = (void *)((uintptr_t)local_addr + (uintptr_t)remote_handle - (uintptr_t)local_handle);    
    
#if defined(__i386__)    
    if (!strcmp(module_name, libc_path)) {    
        ret_addr += 2;    
    }    
#endif    
    return ret_addr;    
}    

//根據name找到pid
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;    
}    
    
uint64_t ptrace_retval(struct pt_regs * regs)    
{    
#if defined(__arm__) || defined(__aarch64__)
    return regs->ARM_r0;    
#elif defined(__i386__)    
    return regs->eax;    
#else    
#error "Not supported"    
#endif    
}    
    
uint64_t ptrace_ip(struct pt_regs * regs)    
{    
#if defined(__arm__) || defined(__aarch64__) 
    return regs->ARM_pc;   
#elif defined(__i386__)    
    return regs->eip;    
#else    
#error "Not supported"    
#endif    
}    

//總結一下ptrace_call_wrapper,它的完成兩個功能:
//一是調用ptrace_call函數來執行指定函數,執行完後將子進程掛起;
//二是調用ptrace_getregs函數獲取所有寄存器的值,主要是為了獲取r0即函數的返回值。  
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, (uintptr_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=%llx, pc=%llx \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;     
    long parameters[10];    
    
    DEBUG_PRINT("[+] Injecting process: %d\n", target_pid);    
	
    //①ATTATCH,指定目標進程,開始調試
    if (ptrace_attach(target_pid) == -1)    
        goto exit;   
	
    //②GETREGS,獲取目標進程的寄存器,保存現場
    if (ptrace_getregs(target_pid, ®s) == -1)    
        goto exit;    
    
    /* save original registers */    
    memcpy(&original_regs, ®s, sizeof(regs));    
	
	//③通過get_remote_addr函數獲取目的進程的mmap函數的地址,以便為libxxx.so分配內存
    
	/*
		需要對(void*)mmap進行說明:這是取得inject本身進程的mmap函數的地址,由於mmap函數在libc.so  
		庫中,為了將libxxx.so加載到目的進程中,就需要使用目的進程的mmap函數,所以需要查找到libc.so庫在目的進程的起始地址。
	*/
    mmap_addr = get_remote_addr(target_pid, libc_path, (void *)mmap);    
    DEBUG_PRINT("[+] Remote mmap address: %llx\n", mmap_addr);

	/* call mmap (null, 0x4000, PROT_READ | PROT_WRITE | PROT_EXEC,
	                         MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
	匿名申請一塊0x4000大小的內存
	*/
    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    
    
    if (ptrace_call_wrapper(target_pid, "mmap", mmap_addr, parameters, 6, ®s) == -1)    
        goto exit;    
    
	//⑤從寄存器中獲取mmap函數的返回值,即申請的內存首地址:
    map_base = ptrace_retval(®s);  
    
	//⑥依次獲取linker中dlopen、dlsym、dlclose、dlerror函數的地址:
    dlopen_addr = get_remote_addr( target_pid, linker_path, (void *)dlopen );    
    dlsym_addr = get_remote_addr( target_pid, linker_path, (void *)dlsym );    
    dlclose_addr = get_remote_addr( target_pid, linker_path, (void *)dlclose );    
    dlerror_addr = get_remote_addr( target_pid, linker_path, (void *)dlerror );    
    
    DEBUG_PRINT("[+] Get imports: dlopen: %llx, dlsym: %llx, dlclose: %llx, dlerror: %llx\n",    
            dlopen_addr, dlsym_addr, dlclose_addr, dlerror_addr);    
    
    printf("library path = %s\n", library_path);    
	//⑦調用dlopen函數:
	/*
	①將要注入的so名寫入前面mmap出來的內存
	②寫入dlopen代碼
	③執行dlopen("libxxx.so", RTLD_NOW ! RTLD_GLOBAL) 
	RTLD_NOW之類的參數作用可參考:
	http://baike.baidu.com/view/2907309.htm?fr=aladdin 
	④取得dlopen的返回值,存放在sohandle變量中
	*/
    ptrace_writedata(target_pid, map_base, library_path, strlen(library_path) + 1);  
        
    parameters[0] = map_base;       
    parameters[1] = RTLD_NOW| RTLD_GLOBAL;     
    
    if (ptrace_call_wrapper(target_pid, "dlopen", dlopen_addr, parameters, 2, ®s) == -1)    
        goto exit;    
    
    void * sohandle = ptrace_retval(®s);    
    if(!sohandle) {
    		if (ptrace_call_wrapper(target_pid, "dlerror", dlerror_addr, 0, 0, ®s) == -1)    
      	  goto exit;    
        
    		uint8_t *errret = ptrace_retval(®s);  
    		uint8_t errbuf[100];
    		ptrace_readdata(target_pid, errret, errbuf, 100);
  	}
    
    //⑧調用dlsym函數
	/*
	等同於hook_entry_addr = (void *)dlsym(sohandle, "hook_entry");
	*/ 
#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;     
    
    if (ptrace_call_wrapper(target_pid, "dlsym", dlsym_addr, parameters, 2, ®s) == -1)    
        goto exit;    
    
    void * hook_entry_addr = ptrace_retval(®s);    
    DEBUG_PRINT("hook_entry_addr = %p\n", hook_entry_addr);    
    
	//⑨調用hook_entry函數:
#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;      
  
    if (ptrace_call_wrapper(target_pid, "hook_entry", hook_entry_addr, parameters, 1, ®s) == -1)    
        goto exit;        
    
    printf("Press enter to dlclose and detach\n");    
    getchar();    
    parameters[0] = sohandle;       
    
	//⑩調用dlclose關閉lib:
    if (ptrace_call_wrapper(target_pid, "dlclose", dlclose, parameters, 1, ®s) == -1)    
        goto exit;    
    
    /* restore */    
	//?恢復現場並退出ptrace:
    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("system_server");
    if (-1 == target_pid) {  
        printf("Can't find the process\n");  
        return -1;  
    }  
    //target_pid = find_pid_of("/data/test");    
    inject_remote_process(target_pid, "/data/libhello.so", "hook_entry",  "I'm parameter!", strlen("I'm parameter!"));    
    return 0;  
}

Android.mk application.mk

 

 

APP_ABI :=arm64-v8a armeabi-v7a

 

 

LOCAL_PATH := $(call my-dir)  
  
include $(CLEAR_VARS)  
LOCAL_MODULE := inject   
LOCAL_SRC_FILES := inject.c   
  
#shellcode.s  
  
LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog  
  
#LOCAL_FORCE_STATIC_EXECUTABLE := true  
  
include $(BUILD_EXECUTABLE)  

2.inject的測試so

 

#include   
#include   
#include   
#include   
#include   
#include   
  
#define LOG_TAG "DEBUG"  
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt, ##args)    
  
int hook_entry(char * a){  
    LOGD("Hook success, pid = %d\n", getpid());  
    LOGD("Hello %s\n", a);  
    return 0;  
}  
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved