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

1、概述

本文介紹如何經過FastHook + VirtualApp實現免root hook。因爲VirtualApp已經不更新了,因此本文只做爲一個教程,並不主要解決一些兼容和穩定性問題。java

項目地址:VirtualFastHook:github.com/turing-tech…android

2、實現原理

要實現應用hook,能夠簡單的分爲下面三個步驟: 1. 識別Hook插件 2. 保存Hook插件信息 3. 獲取Hook插件信息進行Hookgit

2.1 識別Hook插件

規定Hook插件須在AndroidManifest.xml裏定義三個meta-datagithub

<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的進程bash

3. fasthook.hook.info:表示Hook信息類名微信

能夠在VirtualApp解析Apk時加上判斷是否爲Hook插件的代碼,例如在AppRepository.javaapp

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.javaide

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);
            }
        }
    }
複製代碼

3、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數組。

3、實際效果

安裝上VirtualFastHook和Hook插件後,運行看看實際效果

VirtualFastHook主界面.png
安裝Hook插件.png

運行微信.png

Hook成功.png
全部的Hook插件左上角都有一個紅色小圖標,表明該應用爲Hook插件

4、結語

上述只是一個基本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段符號查詢
相關文章
相關標籤/搜索