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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容