FastHook——如何使用FastHook免root hook微信

圖靈技師發表於2019-03-22

一、概述

本文介紹如何通過FastHook + VirtualApp實現免root hook。由於VirtualApp已經不更新了,所以本文只作為一個教程,並不主要解決一些相容和穩定性問題。

專案地址:VirtualFastHook:github.com/turing-tech…

二、實現原理

要實現應用hook,可以簡單的分為下面三個步驟: 1. 識別Hook外掛 2. 儲存Hook外掛資訊 3. 獲取Hook外掛資訊進行Hook

2.1 識別Hook外掛

規定Hook外掛須在AndroidManifest.xml裡定義三個meta-data

<meta-data
        android:name="fasthook.hook.plugin"
        android:value="true"/>
        
<meta-data
        android:name="fasthook.hook.process"
        android:value="XXX"/>
        
<meta-data
        android:name="fasthook.hook.info"
        android:value="XXX"/>
複製程式碼

1. fasthook.hook.plugin:表示這是一個Hook外掛

2. fasthook.hook.process:表示要Hook的程式

3. fasthook.hook.info:表示Hook資訊類名

可以在VirtualApp解析Apk時加上判斷是否為Hook外掛的程式碼,例如在AppRepository.java

private List<AppInfo> convertPackageInfoToAppData(Context context, List<PackageInfo> pkgList, boolean fastOpen) {
        PackageManager pm = context.getPackageManager();
        List<AppInfo> list = new ArrayList<>(pkgList.size());
        String hostPkg = VirtualCore.get().getHostPkg();
        for (PackageInfo pkg : pkgList) {
            // ignore the host package
            if (hostPkg.equals(pkg.packageName)) {
                continue;
            }
            // ignore the System package
            if (isSystemApplication(pkg)) {
                continue;
            }
            boolean isHookPlugin = false;
            //start 判斷是否是Hook外掛
            ApplicationInfo ai = null;
            try {
                ai = context.getPackageManager().getApplicationInfo(pkg.packageName,PackageManager.GET_META_DATA);
                if(ai.metaData != null) {
                    boolean enable = ai.metaData.getBoolean("fasthook.hook.plugin", false);
                    if(enable) {
                        String hookProcess = ai.metaData.getString("fasthook.hook.process","");
                        String hookInfo = ai.metaData.getString("fasthook.hook.info","");
                        if(!hookProcess.isEmpty() || !hookInfo.isEmpty()) {
                            isHookPlugin = true;
                        }
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
            //end 判斷是否是Hook外掛
            String path = ai.publicSourceDir != null ? ai.publicSourceDir : ai.sourceDir;
            if (path == null) {
                continue;
            }
            AppInfo info = new AppInfo();
            info.packageName = pkg.packageName;
            info.fastOpen = fastOpen;
            info.path = path;
            info.icon = ai.loadIcon(pm);
            info.name = ai.loadLabel(pm);
            info.isHook = isHookPlugin;
            InstalledAppInfo installedAppInfo = VirtualCore.get().getInstalledAppInfo(pkg.packageName, 0);
            if (installedAppInfo != null) {
                info.cloneCount = installedAppInfo.getInstalledUsers().length;
            }
            list.add(info);
        }
        return list;
    }
複製程式碼

2.2 如何獲取Hook外掛

在apk安裝時,可以把Hook外掛儲存起來,例如在VAppManagerService.java

public synchronized InstallResult installPackage(String path, int flags, boolean notify) {
        //無關程式碼
        boolean isHook = (flags & InstallStrategy.IS_HOOK) != 0;
        //無關程式碼
        if (res.isUpdate) {
            FileUtils.deleteDir(libDir);
            VEnvironment.getOdexFile(pkg.packageName).delete();
            if(isHook) {
                VActivityManagerService.get().killAllApps();
            }
            else {
                VActivityManagerService.get().killAppByPkg(pkg.packageName, VUserHandle.USER_ALL);
            }
        }
        //無關程式碼
        PackageSetting ps;
        if (existSetting != null) {
            ps = existSetting;
        } else {
            ps = new PackageSetting();
        }
        ps.isHook = isHook;
        ps.dependSystem = dependSystem;
        ps.apkPath = packageFile.getPath();
        ps.libPath = libDir.getPath();
        ps.packageName = pkg.packageName;
        ps.appId = VUserHandle.getAppId(mUidSystem.getOrCreateUid(pkg));
        if (res.isUpdate) {
            ps.lastUpdateTime = installTime;
        } else {
            ps.firstInstallTime = installTime;
            ps.lastUpdateTime = installTime;
            for (int userId : VUserManagerService.get().getUserIds()) {
                boolean installed = userId == 0;
                ps.setUserState(userId, false/*launched*/, false/*hidden*/, installed);
            }
        }
        //無關程式碼
        //儲存Hook外掛資訊
        if(isHook) {
            HookCacheManager.HookCacheInfo info = new HookCacheManager.HookCacheInfo(ps.packageName,(String)(pkg.mAppMetaData.get(HookCacheManager.HOOK_PROCESS)),(String)(pkg.mAppMetaData.get(HookCacheManager.HOOK_INFO)));
            HookCacheManager.put((String)(pkg.mAppMetaData.get(HookCacheManager.HOOK_PROCESS)),info);
        }
        else if (notify) {
            notifyAppInstalled(ps, -1);
        }
        res.isSuccess = true;
        return res;
    }
複製程式碼

2.3 如何Hook

實際可以在任意地方Hook,但為了更好的Hook,這裡在應用apk載入之後,attachBaseContext方法呼叫之前進行Hook,這樣便可以Hook所有應用的方法了。例如在VClientImpl.java

private void bindApplicationNoCheck(String packageName, String processName, ConditionVariable lock) {
        //無關程式碼
        NativeEngine.launchEngine();
        Object mainThread = VirtualCore.mainThread();
        NativeEngine.startDexOverride();
        Context context = createPackageContext(data.appInfo.packageName);
        System.setProperty("java.io.tmpdir", context.getCacheDir().getAbsolutePath());

	//無關程式碼

	Object boundApp = fixBoundApp(mBoundApplication);
        mBoundApplication.info = ContextImpl.mPackageInfo.get(context);
        mirror.android.app.ActivityThread.AppBindData.info.set(boundApp, data.info);
        VMRuntime.setTargetSdkVersion.call(VMRuntime.getRuntime.call(), data.appInfo.targetSdkVersion);

	//進行Hook
        try {
            tryHook(processName,context.getClassLoader());
        }catch (Exception e) {
            e.printStackTrace();
        }

	//無關程式碼

	VirtualCore.get().getComponentDelegate().beforeApplicationCreate(mInitialApplication);
	 try {
            mInstrumentation.callApplicationOnCreate(mInitialApplication);
            InvocationStubManager.getInstance().checkEnv(HCallbackStub.class);
            if (conflict) {
                InvocationStubManager.getInstance().checkEnv(AppInstrumentation.class);
            }
            Application createdApp = ActivityThread.mInitialApplication.get(mainThread);
            if (createdApp != null) {
                mInitialApplication = createdApp;
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(mInitialApplication, e)) {
                throw new RuntimeException(
                        "Unable to create application " + mInitialApplication.getClass().getName()
                                + ": " + e.toString(), e);
            }
        }
        VActivityManager.get().appDoneExecuting();
        VirtualCore.get().getComponentDelegate().afterApplicationCreate(mInitialApplication);
    }
   
    //根據程式名獲取Hook外掛並Hook
    private void tryHook(String process, ClassLoader apkClassLoader) {
        String[] infos = VPackageManager.get().getInstalledHookPlugins(process);
        if(infos != null) {
            for(String info : infos) {
                int size = info.charAt(0);
                String pluginName = info.substring(1,1 + size);
                String hookInfoName = info.substring(1 + size);

		DexClassLoader hookClassLoader = new DexClassLoader(VEnvironment.getPackageResourcePath(pluginName).getAbsolutePath(),
                        VEnvironment.getDalvikCacheDirectory().getAbsolutePath(),
                        VEnvironment.getPackageLibPath(pluginName).getAbsolutePath(),
                        apkClassLoader);

		FastHookManager.doHook(hookInfoName,hookClassLoader,apkClassLoader,hookClassLoader,hookClassLoader,false);
            }
        }
    }
複製程式碼

三、Hook微信

3.1 準備一個Hook外掛

根據FastHook框架要求,提供一下資訊:

1. HookMethodInfo.java(Hook方法、Forward方法具體實現)

public class HookMethodInfo {
    public static void hook(Object thiz, Context context) {
        Log.d("FastHookManager","hook attachBaseContext2");
        forward(thiz,context);
        Toast toast = Toast.makeText(context,"hook attachBaseContext2",Toast.LENGTH_LONG);
        toast.show();
    }
    
    public native static void forward(Object thiz, Context context);
}
複製程式碼

可以看到Hook方法的邏輯很簡單,只是彈出一個Toast,內容為hook attachBaseContext2

2. HookInfo.java(根據FastHook框架規定提供HOOK_ITEMS資訊)

public class HookInfo {
    public static String[][] HOOK_ITEMS = {
            {"1",
                    "com.tencent.tinker.loader.app.TinkerApplication","attachBaseContext","Landroid/content/Context;",
                    "com.example.fasthookplugin.HookMethodInfo","hook","Ljava/lang/Object;Landroid/content/Context;",
                    "com.example.fasthookplugin.HookMethodInfo","forward","Ljava/lang/Object;Landroid/content/Context;"}
    };
}
複製程式碼

使用的是Inline模式,Hook的是attachBaseContext方法,這是應用被系統呼叫的第一個方法。

3. 配置AndroidManifest.xml(配置Hook外掛資訊)

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="fasthook.hook.plugin"
            android:value="true"/>

	<meta-data
            android:name="fasthook.hook.process"
            android:value="com.tencent.mm"/>
	
	<meta-data
            android:name="fasthook.hook.info"
            android:value="com.example.fasthookplugin.HookInfo"/>
	<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

		<category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
複製程式碼

配置apk為Hook外掛,Hook的目標程式為com.tencent.mm即微信主程式,具體Hook資訊位於HookInfo類HOOK_ITEMS陣列。

三、實際效果

安裝上VirtualFastHook和Hook外掛後,執行看看實際效果

VirtualFastHook主介面.png
安裝Hook外掛.png

執行微信.png

Hook成功.png
所有的Hook外掛左上角都有一個紅色小圖示,代表該應用為Hook外掛

四、結語

上述只是一個基本Hook操作,實際還可以做出更多有用的功能,下面這個是我隨手做的7.0.3版本微信訊息防撤回

接受訊息.png
阻止對方撤回訊息.png

對方顯示訊息已撤回.png

參考

FastHook——一種高效穩定、簡潔易用的Android Hook框架

FastHook:github.com/turing-tech…

VirtualApp:github.com/asLody/Virt…

FastHook系列

  1. FastHook——一種高效穩定、簡潔易用的Android Hook框架
  2. FastHook——巧妙利用動態代理實現非侵入式AOP
  3. FastHook——遠超YAHFA的優異穩定性
  4. FastHook——實現.dynsym段和.symtab段符號查詢

相關文章