0×04 迈开第三步,实现hook操作的具体代码
4、在“施展刀法”(编写hook代码)之前,我们先要立一个靶子。在界面上画一个按钮,并在MainAcitiviy里写代码如下:
package com.example.root.xposd_hook_new; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity {undefined private Button button; @Override protected void onCreate(Bundle savedInstanceState) {undefined super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() {undefined public void onClick(View v) {undefined Toast.makeText(MainActivity.this, toastMessage(), Toast.LENGTH_SHORT).show(); } }); } public String toastMessage() {undefined return "我未被劫持"; } }
这个靶子很简单:MainActivity界面有个按钮,点击按钮后会弹出一个toast提示,该提示的内容由 toastMessage() 方法提供,而toastMessage()的返回值为“我未被劫持”:
下面我们正式开始“施展刀法”(编写hook代码) 来hook我们的MainActivity并修改这个类的toastMessage()方法,让它的返回值为“你已被劫持”:
5、在MainActivity的同级路径下新建一个类“HookTest.java”,代码如下:
package com.example.root.xposd_hook_new; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage; public class HookTest implements IXposedHookLoadPackage {undefined public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {undefined if (loadPackageParam.packageName.equals("com.example.root.xposd_hook_new")) {undefined XposedBridge.log(" has Hooked!"); Class clazz = loadPackageParam.classLoader.loadClass( "com.example.root.xposd_hook_new.MainActivity"); XposedHelpers.findAndHookMethod(clazz, "toastMessage", new XC_MethodHook() {undefined protected void beforeHookedMethod(MethodHookParam param) throws Throwable {undefined super.beforeHookedMethod(param); //XposedBridge.log(" has Hooked!"); } protected void afterHookedMethod(MethodHookParam param) throws Throwable {undefined param.setResult("你已被劫持"); } }); } } }
由代码可知,我们是通过IXposedHookLoadPackage接口中的handleLoadPackage方法来实现Hook并篡改程序的输出结果的。代码中“com.example.root.xposd_hook_new ”是目标程序的包名,”com.example.root.xposd_hook_new.MainActivity” 是想要Hook的类, “toastMessage”是想要Hook的方法。我们在afterHookedMethod方法(用来定义Hook了目标方法之后的操作)中,修改了toastMessage()方法的返回值为“你已被劫持”。
OK,以上用来hook的代码编写完毕,让我们进行下一步操作。