Dex加密(下)—替換Application

dex加密中我們使用了解密的ProxyApplication作為了application的name碴萧,但是通常我們都會在主App中自定義一個MyApplication肝箱,并在其中做一些初始化工作,這個時候我們就需要把ProxyApplication替換成原本的MyApplication扛稽。

在替換之前瓮孙,我們先看看Application在系統(tǒng)中是什么時候開始創(chuàng)建的盗尸。
ActivityThread的main方法是一個進(jìn)程的入口谜疤,這里會調(diào)用attach()方法佃延,從而通過binder機(jī)制調(diào)用ActivityManagerService的attachApplication()方法,然后這個方法又反過來調(diào)用ActivityThread的bindApplication()方法现诀,接著發(fā)Handler調(diào)用handleBindApplication()方法。

private void handleBindApplication(AppBindData data) {
          Application app = data.info.makeApplication(data.restrictedBackupMode, null);
            mInitialApplication = app;
            // don't bring up providers in restricted mode; they may depend on the
            // app's custom Application class
            if (!data.restrictedBackupMode) {
                if (!ArrayUtils.isEmpty(data.providers)) {
                    installContentProviders(app, data.providers);
                    // For process that contains content providers, we want to
                    // ensure that the JIT is enabled "at some point".
                    mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
                }
            }
    .......
            mInstrumentation.callApplicationOnCreate(app);
}

在handleBindApplication方法中調(diào)用makeApplication去創(chuàng)建一個Application對象履肃。


    public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        if (mApplication != null) {
            return mApplication;
        }
Application app = null;
String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }
        try {
            java.lang.ClassLoader cl = getClassLoader();
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {}
mActivityThread.mAllApplications.add(app);
        mApplication = app;
    ..........
        return app;

在newApplication()中才是真的去創(chuàng)建一個新的Application赶盔。

    public Application newApplication(ClassLoader cl, String className, Context context)
            throws InstantiationException, IllegalAccessException, 
            ClassNotFoundException {
        return newApplication(cl.loadClass(className), context);
    }
static public Application newApplication(Class<?> clazz, Context context)
            throws InstantiationException, IllegalAccessException, 
            ClassNotFoundException {
        Application app = (Application)clazz.newInstance();
        app.attach(context);
        return app;
    }

回過頭來看看實(shí)例化完Application之后在哪些地方用到了這個Application。

  • 實(shí)例化完成立馬調(diào)用Application的attach方法榆浓。
  • appContext.setOuterContext(app)
  • mActivityThread.mAllApplications.add(app)
  • 賦值給mApplication
  • mInitialApplication = app
  • String appClass = mApplicationInfo.className獲得Application的類名。
    在做完上述的操作之后會調(diào)用Application的onCreate方法撕攒,所以就在onCreate中我們把上面的所有用到Application的地方替換成主App中真實(shí)的Application陡鹃。
public void bindRealApplication() throws Exception {
        if (isBindReal){
            return;
        }
        //如果用戶(使用這個庫的開發(fā)者) 沒有配置Application 就不用管了
        if (TextUtils.isEmpty(app_name)) {
            return;
        }
        //這個就是attachBaseContext傳進(jìn)來的 ContextImpl
        Context baseContext = getBaseContext();
        //反射創(chuàng)建出真實(shí)的 用戶 配置的Application
        Class<?> delegateClass = Class.forName(app_name);
        delegate = (Application) delegateClass.newInstance();
        //反射獲得 attach函數(shù)
        Method attach = Application.class.getDeclaredMethod("attach", Context.class);
        //設(shè)置允許訪問
        attach.setAccessible(true);
        attach.invoke(delegate, baseContext);

        /**
         *  替換
         *  ContextImpl -> mOuterContext ProxyApplication->MyApplication
         */
        Class<?> contextImplClass = Class.forName("android.app.ContextImpl");
        //獲得 mOuterContext 屬性
        Field mOuterContextField = contextImplClass.getDeclaredField("mOuterContext");
        mOuterContextField.setAccessible(true);
        mOuterContextField.set(baseContext, delegate);


        /**
         * ActivityThread  mAllApplications 與 mInitialApplication
         */
        //獲得ActivityThread對象 ActivityThread 可以通過 ContextImpl 的 mMainThread 屬性獲得
        Field mMainThreadField = contextImplClass.getDeclaredField("mMainThread");
        mMainThreadField.setAccessible(true);
        Object mMainThread = mMainThreadField.get(baseContext);

        //替換 mInitialApplication
        Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
        Field mInitialApplicationField = activityThreadClass.getDeclaredField
                ("mInitialApplication");
        mInitialApplicationField.setAccessible(true);
        mInitialApplicationField.set(mMainThread,delegate);

        //替換 mAllApplications
        Field mAllApplicationsField = activityThreadClass.getDeclaredField
                ("mAllApplications");
        mAllApplicationsField.setAccessible(true);
        ArrayList<Application> mAllApplications = (ArrayList<Application>) mAllApplicationsField.get(mMainThread);
        mAllApplications.remove(this);
        mAllApplications.add(delegate);


        /**
         * LoadedApk -> mApplication ProxyApplication
         */
        //LoadedApk 可以通過 ContextImpl 的 mPackageInfo 屬性獲得
        Field mPackageInfoField = contextImplClass.getDeclaredField("mPackageInfo");
        mPackageInfoField.setAccessible(true);
        Object mPackageInfo = mPackageInfoField.get(baseContext);

        Class<?> loadedApkClass = Class.forName("android.app.LoadedApk");
        Field mApplicationField = loadedApkClass.getDeclaredField("mApplication");
        mApplicationField.setAccessible(true);
        mApplicationField.set(mPackageInfo,delegate);

        //修改ApplicationInfo className LoadedApk
        Field mApplicationInfoField = loadedApkClass.getDeclaredField("mApplicationInfo");
        mApplicationInfoField.setAccessible(true);
        ApplicationInfo mApplicationInfo = (ApplicationInfo) mApplicationInfoField.get(mPackageInfo);
        mApplicationInfo.className = app_name;

        delegate.onCreate();
        isBindReal = true;
    }

替換完成之后看看四大組件中Application是否改動:



Activity和service已經(jīng)修改成功,Provider修改失敗了抖坪,BroadCastReciver有點(diǎn)不同是個ReceiverRestrictedContext萍鲸。

先看看BroadCastReciver:
在ActivityThread中的handleReceiver方法創(chuàng)建一個BroadCastReciver

    private void handleReceiver(ReceiverData data) {
        ......
            receiver.onReceive(context.getReceiverRestrictedContext(),
                    data.intent);
......
}
   final Context getReceiverRestrictedContext() {
        if (mReceiverRestrictedContext != null) {
            return mReceiverRestrictedContext;
        }
        return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
    }

在new ReceiverRestrictedContext的時候傳入的是getOuterContext(),

   final Context getOuterContext() {
        return mOuterContext;
    }

也就是我們之前替換過的mOuterContext擦俐,所以BroadCastReciver我們是替換成功的脊阴。

Provider:
從打印log可以看出先調(diào)用了Provider的onCreate然后在調(diào)用Application的onCreate,在handleBindApplication方法中還有個if語句在Application的onCreate之前執(zhí)行蚯瞧。

            if (!ArrayUtils.isEmpty(data.providers)) {
                    installContentProviders(app, data.providers);
                    // For process that contains content providers, we want to
                    // ensure that the JIT is enabled "at some point".
                    mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
                }
    private ContentProviderHolder installProvider(Context context,
            ContentProviderHolder holder, ProviderInfo info,
            boolean noisy, boolean noReleaseNeeded, boolean stable) {
            Context c = null;
            ApplicationInfo ai = info.applicationInfo;
            if (context.getPackageName().equals(ai.packageName)) {
                c = context;
            } else if (mInitialApplication != null &&
                    mInitialApplication.getPackageName().equals(ai.packageName)) {
                c = mInitialApplication;
            } else {
                try {
                    c = context.createPackageContext(ai.packageName,
                            Context.CONTEXT_INCLUDE_CODE);
                } catch (PackageManager.NameNotFoundException e) {
                    // Ignore
                }
            }
            ......

            try {
                final java.lang.ClassLoader cl = c.getClassLoader();
                localProvider = (ContentProvider)cl.
                    loadClass(info.name).newInstance();
                provider = localProvider.getIContentProvider();
                if (provider == null) {
                    Slog.e(TAG, "Failed to instantiate class " +
                          info.name + " from sourceDir " +
                          info.applicationInfo.sourceDir);
                    return null;
                }
                if (DEBUG_PROVIDER) Slog.v(
                    TAG, "Instantiating local provider " + info.name);
                // XXX Need to create the correct context for this provider.
                localProvider.attachInfo(c, info);
            } catch (java.lang.Exception e) {}

創(chuàng)建完P(guān)rovider之后調(diào)用attachInfo嘿期,傳入的Context 是c。

 public void attachInfo(Context context, ProviderInfo info) {
        attachInfo(context, info, false);
    }

    private void attachInfo(Context context, ProviderInfo info, boolean testing) {
        mNoPerms = testing;

        /*
         * Only allow it to be set once, so after the content service gives
         * this to us clients can't change it.
         */
        if (mContext == null) {
            mContext = context;
            }
  }

mContext 就是我們在Provider中g(shù)etContext()所獲得的Context埋合,所以要想替換這個mContext备徐,就得改c。c會通過if else來確定c的值甚颂,通常context.getPackageName()和應(yīng)用的包名都是一致的所以c就是我們替換之前的Application蜜猾,第二個if中的mInitialApplication在上面也提到了,其實(shí)個替換之前的Application是同一個振诬,所以只有else中才又可能滿足我們的需求蹭睡。如果要執(zhí)行else我們首先需要修改一下context.getPackageName()返回的包名

 @Override
    public String getPackageName() {
        //如果meta-data 設(shè)置了 application
        //讓ContentProvider創(chuàng)建的時候使用的上下文 在ActivityThread中的installProvider函數(shù)
        //命中else
        if (!TextUtils.isEmpty(app_name)){
            return "";
        }
        return super.getPackageName();
    }

接著修改context.createPackageContext返回的值

   @Override
    public Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException {
        if (TextUtils.isEmpty(app_name)){
            return super.createPackageContext(packageName, flags);
        }
        try {
            bindRealApplication();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return delegate;
    }


到此已經(jīng)全部替換成功
demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市赶么,隨后出現(xiàn)的幾起案子肩豁,更是在濱河造成了極大的恐慌,老刑警劉巖禽绪,帶你破解...
    沈念sama閱讀 216,744評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蓖救,死亡現(xiàn)場離奇詭異,居然都是意外死亡印屁,警方通過查閱死者的電腦和手機(jī)循捺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來雄人,“玉大人从橘,你說我怎么就攤上這事念赶。” “怎么了恰力?”我有些...
    開封第一講書人閱讀 163,105評論 0 353
  • 文/不壞的土叔 我叫張陵叉谜,是天一觀的道長。 經(jīng)常有香客問我踩萎,道長停局,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,242評論 1 292
  • 正文 為了忘掉前任香府,我火速辦了婚禮董栽,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘企孩。我一直安慰自己锭碳,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,269評論 6 389
  • 文/花漫 我一把揭開白布勿璃。 她就那樣靜靜地躺著擒抛,像睡著了一般。 火紅的嫁衣襯著肌膚如雪补疑。 梳的紋絲不亂的頭發(fā)上歧沪,一...
    開封第一講書人閱讀 51,215評論 1 299
  • 那天,我揣著相機(jī)與錄音癣丧,去河邊找鬼槽畔。 笑死,一個胖子當(dāng)著我的面吹牛胁编,可吹牛的內(nèi)容都是我干的厢钧。 我是一名探鬼主播,決...
    沈念sama閱讀 40,096評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼嬉橙,長吁一口氣:“原來是場噩夢啊……” “哼早直!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起市框,我...
    開封第一講書人閱讀 38,939評論 0 274
  • 序言:老撾萬榮一對情侶失蹤霞扬,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后枫振,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體喻圃,經(jīng)...
    沈念sama閱讀 45,354評論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,573評論 2 333
  • 正文 我和宋清朗相戀三年粪滤,在試婚紗的時候發(fā)現(xiàn)自己被綠了斧拍。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,745評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡杖小,死狀恐怖肆汹,靈堂內(nèi)的尸體忽然破棺而出愚墓,到底是詐尸還是另有隱情,我是刑警寧澤昂勉,帶...
    沈念sama閱讀 35,448評論 5 344
  • 正文 年R本政府宣布浪册,位于F島的核電站,受9級特大地震影響岗照,放射性物質(zhì)發(fā)生泄漏村象。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,048評論 3 327
  • 文/蒙蒙 一攒至、第九天 我趴在偏房一處隱蔽的房頂上張望煞肾。 院中可真熱鬧,春花似錦嗓袱、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至闪萄,卻和暖如春梧却,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背败去。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評論 1 269
  • 我被黑心中介騙來泰國打工放航, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人圆裕。 一個月前我還...
    沈念sama閱讀 47,776評論 2 369
  • 正文 我出身青樓广鳍,卻偏偏與公主長得像,于是被迫代替她去往敵國和親吓妆。 傳聞我的和親對象是個殘疾皇子赊时,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,652評論 2 354