动态注入并执行Android代码到进程


layout: post
title: 动态注入并执行Android代码到进程
categories: Android
description: 动态注入并执行Android代码到进程
keywords: Inject
url: https://lichao890427.github.io/ https://github.com/lichao890427/


动态注入并执行Android代码到进程

背景

  网上可以见到很多帖子是如何注入进程并钩取c层api的例子,而动态的让目标进程加载一个dex并执行这个dex却没看到,c层的注入很简单,可以参考adbi,ptrace进去修改当前指令指针寄存器,构造一个dlopen的指令并调用,类似于win上getcontext修改eip, java层稍复杂一些,加载dex->解析dex->查找目标类->调用函数,下面是测试用例,我们的目标是打log

代码

import android.util.Log;
public class injectjava {
    static void initialize(){
        Log.i("INJECTJAVA","injectava called");
    }
}

#define LOGI(...)  __android_log_print(ANDROID_LOG_ERROR, "INJECTJAVA", __VA_ARGS__)
#define DEXNAME "/data/local/tmp/inject.dex"

typedef void Object;
typedef void ClassObject;
typedef void Thread;
typedef uint8_t u1;
typedef uint32_t u4;
struct JNIEnvExt
{
    const struct JNINativeInterface* funcTable;
    const struct JNINativeInterface* baseFuncTable;
    u4      envThreadId;
    Thread* self;
};

typedef void DexOptHeader;
typedef void DexStringId;
typedef void DexTypeId;
typedef void DexFieldId;
typedef void DexMethodId;
typedef void DexProtoId;
typedef void DexLink;
typedef void DexClassLookup;

struct DexHeader
{
    u1  magic[8];           /* includes version number */
    u4  checksum;           /* adler32 checksum */
    u1  signature[20];       /* SHA-1 hash */
    u4  fileSize;           /* length of entire file */
    u4  headerSize;         /* offset to start of next section */
    u4  endianTag;
    u4  linkSize;
    u4  linkOff;
    u4  mapOff;
    u4  stringIdsSize;
    u4  stringIdsOff;
    u4  typeIdsSize;
    u4  typeIdsOff;
    u4  protoIdsSize;
    u4  protoIdsOff;
    u4  fieldIdsSize;
    u4  fieldIdsOff;
    u4  methodIdsSize;
    u4  methodIdsOff;
    u4  classDefsSize;
    u4  classDefsOff;
    u4  dataSize;
    u4  dataOff;
};

struct DexClassDef
{
    u4  classIdx;           /* index into typeIds for this class */
    u4  accessFlags;
    u4  superclassIdx;      /* index into typeIds for superclass */
    u4  interfacesOff;      /* file offset to DexTypeList */
    u4  sourceFileIdx;      /* index into stringIds for source file name */
    u4  annotationsOff;     /* file offset to annotations_directory_item */
    u4  classDataOff;       /* file offset to class_data_item */
    u4  staticValuesOff;    /* file offset to DexEncodedArray */
};

struct DexFile
{
    DexOptHeader *pOptHeader;
    DexHeader *pHeader;
    DexStringId *pStringIds;
    DexTypeId *pTypeIds;
    DexFieldId *pFieldIds;
    DexMethodId *pMethodIds;
    DexProtoId *pProtoIds;
    DexClassDef *pClassDefs;
    DexLink *pLinkData;
    DexClassLookup *pClassLookup;
};

struct DvmDex
{
    DexFile*            pDexFile;
};

int (*dvmDexFileOpenPartial)(const void* addr, int len, DvmDex** ppDvmDex)=0;
int (*dexSwapAndVerify)(void* addr, int len)=0;
JNIEnv* (*dvmGetJNIEnvForThread)()=0;
Object* (*dvmDecodeIndirectRef)(JNIEnv* env, jobject jobj)=0;
Object* (*dvmDecodeIndirectRef_)(Thread* self, jobject jobj)=0;
ClassObject* (*dvmDefineClass)(DvmDex* pDvmDex, const char* descriptor, Object* classLoader)=0;
DexClassLookup* (*dexCreateClassLookup)(DexFile* pDexFile)=0;

void inject()
{
    /*
     * C层hook
     */
    /*
     * JAVA层hook
     */
    //获取关键函数指针
    do
    {
        void* hdvm = dlopen("libdvm.so", RTLD_LAZY | RTLD_GLOBAL);
        if(!hdvm)
        {
            LOGI("libdvm not exist!");
            break;
        }
        dvmDexFileOpenPartial = (typeof(dvmDexFileOpenPartial))dlsym(hdvm, "dvmDexFileOpenPartial");
        if(!dvmDexFileOpenPartial)
        {
            dvmDexFileOpenPartial = (typeof(dvmDexFileOpenPartial))dlsym(hdvm, "_Z21dvmDexFileOpenPartialPKviPP6DvmDex");
            if(!dvmDexFileOpenPartial)
                LOGI("dvmDexFileOpenPartial not exist!");
        }
        dexSwapAndVerify = (typeof(dexSwapAndVerify))dlsym(hdvm, "dexSwapAndVerify");
        if(!dexSwapAndVerify)
        {
            dexSwapAndVerify = (typeof(dexSwapAndVerify))dlsym(hdvm, "_Z16dexSwapAndVerifyPhi");
            if(!dexSwapAndVerify)
                LOGI("dexSwapAndVerify not exist!");
        }
        dvmGetJNIEnvForThread = (typeof(dvmGetJNIEnvForThread))dlsym(hdvm, "dvmGetJNIEnvForThread");
        if(!dvmGetJNIEnvForThread)
        {
            dvmGetJNIEnvForThread = (typeof(dvmGetJNIEnvForThread))dlsym(hdvm, "_Z21dvmGetJNIEnvForThreadv");
            if(!dvmGetJNIEnvForThread)
                LOGI("dvmGetJNIEnvForThread not exist!");
        }
        dvmDecodeIndirectRef = (typeof(dvmDecodeIndirectRef))dlsym(hdvm, "dvmDecodeIndirectRef");
        if(!dvmDecodeIndirectRef)
        {
            dvmDecodeIndirectRef = (typeof(dvmDecodeIndirectRef))dlsym(hdvm, "_Z20dvmDecodeIndirectRefP7_JNIEnvP8_jobject");
            if(!dvmDecodeIndirectRef)
            {
                dvmDecodeIndirectRef_ = (typeof(dvmDecodeIndirectRef_))dlsym(hdvm, "_Z20dvmDecodeIndirectRefP6ThreadP8_jobject");
                if(!dvmDecodeIndirectRef_)
                    LOGI("dvmDecodeIndirectRef_ not exist!");
            }
        }
        dvmDefineClass = (typeof(dvmDefineClass))dlsym(hdvm, "dvmDefineClass");
        if(!dvmDefineClass)
        {
            dvmDefineClass = (typeof(dvmDefineClass))dlsym(hdvm, "_Z14dvmDefineClassP6DvmDexPKcP6Object");
            if(!dvmDefineClass)
                LOGI("dvmDefineClass not exist!");
        }
        dexCreateClassLookup = (typeof(dexCreateClassLookup))dlsym(hdvm, "dexCreateClassLookup");
        if(!dexCreateClassLookup)
        {
            dexCreateClassLookup = (typeof(dexCreateClassLookup))dlsym(hdvm, "_Z20dexCreateClassLookupP7DexFile");
            if(!dexCreateClassLookup)
                LOGI("dexCreateClassLookup not exist!");
        }
        if(!dvmDexFileOpenPartial || !dexSwapAndVerify || !dvmGetJNIEnvForThread || !dvmDefineClass || !dexCreateClassLookup || (!dvmDecodeIndirectRef && !dvmDecodeIndirectRef_))
            break;
        LOGI("InitOk");
        //读取dex以便动态加载
        char* dexdata = 0;
        int dexlen;
        int dexfd = open(DEXNAME, O_RDONLY);
        if(dexfd == -1)
        {
            LOGI("can't open inject.dex!");
            break;
        }
        struct stat st = {0};
        fstat(dexfd , &st);
        if(st.st_size)
        {
            dexlen = st.st_size;
            dexdata = (char*)malloc(st.st_size);
            if(dexdata)
                read(dexfd, dexdata, st.st_size);
        }
        close(dexfd);
        if(!dexdata)
        {
            LOGI("read inject.dex fail!");
            break;
        }
        int result;
        DvmDex* dvmDex = 0;
        JNIEnv* env =0;
        jclass java_lang_Class =0;
        jmethodID java_lang_Class_forName =0;
        jclass java_lang_ClassLoader =0;
        jmethodID java_lang_ClassLoader_getSystemClassLoader =0;
        jobject jSystemClassLoader =0;
        Object* SystemClassLoader =0;
        jstring com_injectjava_str =0;
        jclass com_injectjava =0;
        jmethodID com_injectjava_initialize =0;
        DexFile* pDexFile = 0;
        int csize,i;
        dexSwapAndVerify(dexdata, dexlen);
        result = dvmDexFileOpenPartial(dexdata, dexlen, &dvmDex);
        if(result != 0)
        {
            LOGI("dvmDexFileOpenPartial fail!");
            goto END1;
        }
        env = dvmGetJNIEnvForThread();
        if(!env)
        {
            LOGI("dvmGetJNIEnvForThread fail!");
            goto END1;
        }
        java_lang_Class = env->FindClass("java/lang/Class");
        if(!java_lang_Class)
        {
            LOGI("java_lang_Class null!");
            goto END1;
        }
        java_lang_Class_forName = env->GetStaticMethodID(java_lang_Class, "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;");
        if(!java_lang_Class_forName)
        {
            LOGI("java_lang_Class_forName null!");
            goto END1;
        }
        java_lang_ClassLoader = env->FindClass("java/lang/ClassLoader");
        if(!java_lang_ClassLoader)
        {
            LOGI("java_lang_ClassLoader null!");
            goto END1;
        }
        java_lang_ClassLoader_getSystemClassLoader = env->GetStaticMethodID(java_lang_ClassLoader, "getSystemClassLoader", "()Ljava/lang/ClassLoader;");
        if(!java_lang_ClassLoader_getSystemClassLoader)
        {
            LOGI("java_lang_ClassLoader_getSystemClassLoader null!");
            goto END1;
        }
        jSystemClassLoader = env->CallStaticObjectMethod(java_lang_ClassLoader, java_lang_ClassLoader_getSystemClassLoader, "()Ljava/lang/ClassLoader;");
        if(!jSystemClassLoader)
        {
            LOGI("jSystemClassLoader null!");
            goto END1;
        }
        LOGI("InitOk1");
        if(dvmDecodeIndirectRef)
            SystemClassLoader = dvmDecodeIndirectRef(env, jSystemClassLoader);
        else
            SystemClassLoader = dvmDecodeIndirectRef_(((JNIEnvExt*)env)->self, jSystemClassLoader);
        if(!SystemClassLoader)
        {
            LOGI("SystemClassLoader null!");
            goto END1;
        }
        pDexFile = dvmDex->pDexFile;
        pDexFile->pClassLookup = dexCreateClassLookup(dvmDex->pDexFile);
        csize = pDexFile->pHeader->classDefsSize;
        for(i=0;i<csize;i++)
        {
            pDexFile->pClassDefs[i].accessFlags | 0x10000;
        }
        dvmDefineClass(dvmDex, "Lcom/injectjava;", SystemClassLoader);
        com_injectjava_str = env->NewStringUTF("com.injectjava");
        if(!com_injectjava_str)
        {
            LOGI("com_injectjava null!");
            goto END1;
        }
        com_injectjava = (jclass)env->CallStaticObjectMethod(java_lang_Class, java_lang_Class_forName, com_injectjava_str, true, jSystemClassLoader);
        if(!com_injectjava)
        {
            LOGI("com_injectjava null!");
            goto END1;
        }
        com_injectjava_initialize = env->GetStaticMethodID(com_injectjava, "initialize", "()V");
        if(!com_injectjava_initialize)
        {
            LOGI("com_injectjava_initialize null!");
            goto END1;
        }
        env->CallStaticVoidMethod(com_injectjava, com_injectjava_initialize);
        LOGI("InitOk2");
        END1:
        free(dexdata);
    }
    while(false);
}

结论

  将要执行的dex放到/data/local/tmp/inject.dex即可

06-03 15:47:34.984 16197-16197/com.example.hellojni E/INJECTJAVA: InitOk
06-03 15:47:35.074 16197-16197/com.example.hellojni E/INJECTJAVA: InitOk1
06-03 15:54:08.304 16197-16197/com.example.hellojni I/INJECTJAVA: injectava called

  这里只是做实验验证Java代码的注入原理分析,Frida注入框架是这类动态注入的最佳实践框架

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容