Frida--Android逆向之动态加载dex Hook(上)

admin 2022年1月6日01:09:45安全博客 CTF专场评论14 views26282字阅读87分36秒阅读模式

基础环境

Mac Os 10.15.5
Python 3.9
jeb
jadx
frida
apktool
MUMU模拟器

文章使用的是DDCTF2018的android逆向第二题Hello Baby Dex

示例地址:[下载](https://github.com/ghostmaze/Android-Reverse/blob/master/Hello Baby Dex/app-release.apk)

知识点

Robust热修复框架原理
Java 反射
Robust类 hook
frida基础hook

APK安装

image-20210105160817336

输入字符并验证,错误会Toast出一些信息,可能输入正确的值才能过获取flag直接进入分析

静态代码分析

导入jeb中查看AndroidManifest.xml 找到程序的入口MainActivity

 <activity android:name="cn.chaitin.geektan.crackme.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

在命令行中使用apktool d xx.apk,将APK文件反编译出来

image-20210105162802636

接下来定位到MainActivity的onCreate()方法,可以看到一些可以的变量和方法比如~~上PatchProxychangeQuickRedirectd

image-20210105170653328

同时看到在else中调用了this.runRobust()方法,并且在每个类中都会存在一些changeQuickRedirect变量,以及isSupport(),accessDispatch()方法。

private void runRobust() {
int v4 = 4;
Object[] v0 = new Object[0];
ChangeQuickRedirect v2 = MainActivity.changeQuickRedirect;
Class[] v5 = new Class[0];
Class v6 = Void.TYPE;
MainActivity v1 = this;
boolean v0_1 = PatchProxy.isSupport(v0, v1, v2, false, v4, v5, v6);
if(v0_1) {
v0 = new Object[0];
v2 = MainActivity.changeQuickRedirect;
v5 = new Class[0];
v6 = Void.TYPE;
v1 = this;
PatchProxy.accessDispatch(v0, v1, v2, false, v4, v5, v6);
}
else {
Context v1_1 = this.getApplicationContext();
//实例化PatchManipulateImp类
PatchManipulateImp v2_1 = new PatchManipulateImp();
//实例化PatchExecutor类
PatchExecutor v0_2 = new PatchExecutor(v1_1, ((PatchManipulate)v2_1), new GeekTanCallBack());
v0_2.start();
}
}

在runRobust()方法的else中实例化了两个对象跟进第一个PatchMainpulateImp中

image-20210105171302097

发现在fetchPatchList()方法中 调用了arg17.getAssets().open(**"GeekTan.BMP"**);从资源文件夹中,还在了一个BMP的的图片文件,并将BMP文件内容写入GeekTan.jar中

具体代码如下:

 try {
v10 = arg17.getAssets().open("GeekTan.BMP");
v8 = new File(arg17.getCacheDir() + File.separator + "GeekTan" + File.separator + "GeekTan.jar");
if(!v8.getParentFile().exists()) {
v8.getParentFile().mkdirs();
}
}
catch(Exception v9) {
goto label_171;
}
//将v8通过FileOutputStream方法赋值v12
try {
v12 = new FileOutputStream(v8);
}
catch(Throwable v0_3) {
goto label_17;
}

int v0_4 = 0x400;
try {
byte[] v7 = new byte[v0_4];
while(true) {
//v10给v11赋值 v10是GeekTan.BMP
int v11 = v10.read(v7);
if(v11 <= 0) {
break;
}
//最终写入到v12中,而v12是new FileOutputStream(v8);
((OutputStream)v12).write(v7, 0, v11);
}
}
catch(Throwable v0_3) {
goto label_88;
}

查看对应的BMP文件发现是一个压缩包,里面存在一个dex文件

╰─$ file GeekTan.BMP
GeekTan.BMP: Zip archive data, at least v2.0 to extract
╰─$ binwalk GeekTan.BMP

DECIMAL HEXADECIMAL DESCRIPTION
--------------------------------------------------------------------------------
0 0x0 Zip archive data, at least v2.0 to extract, name: classes.dex
11635 0x2D73 End of Zip archive, footer length: 22

同时在fetchPatchList()方法中实例化一个Patch对象

Patch v13 = new Patch();

在方法的最后调用

v0_6 = "cn.chaitin.geektan.crackme.PatchesInfoImpl";
v13.setPatchesInfoImplClassFullName(v0_6);

然后到runRobust(),接下来实例化了PatchExecutor类,可以看到第二个参数就是PatchManipulateImp类的实例

Context v1_1 = this.getApplicationContext();
//实例化PatchManipulateImp类
PatchManipulateImp v2_1 = new PatchManipulateImp();
//实例化PatchExecutor类
PatchExecutor v0_2 = new PatchExecutor(v1_1, ((PatchManipulate)v2_1), new GeekTanCallBack());

这个PatchExecutor类是在com.meituan.robust包下的,是一个第三方包,目前美团官方已经将其开源,在此暂停上面的分析,简单学习一下Robust。

image-20210105172538245

Robust热修复框架原理

Robust是美团推出的一款热修复框架,可以在github上面下载它的最新的源码

Robust的基本原理,主要从下面4个步骤进行学习

1.将APK代码中每个函数都在编译打包阶段自动插入一段代码

例如,原函数:

public long getIndex(){
return 100;
}

他会被处理成这样:

//在该类中声明一个接口变量changeQuickRedirect
public static ChangeQuickRedirect changeQuickRedirect;
//在要修复的方法中添加以下逻辑代码
public long getIndex() {
if(changeQuickRedirect != null) {
//PatchProxy中封装了获取当前className和methodName的逻辑,并在其内部最终调用了changeQuickRedirect的对应函数
if(PatchProxy.isSupport(new Object[0], this, changeQuickRedirect, false)) {
return ((Long)PatchProxy.accessDispatch(new Object[0], this, changeQuickRedirect, false)).longValue();
}
}
return 100L;
}
  • Robust为每个class增加了个类型为ChangeQuickRedirect的静态成员
  • 每个方法前都插入了使用changeQuickRedirect相关的逻辑
  • 当changeQuickRedirect不为null时,会执行到accessDispatch方法从而替换掉之前老的逻辑,达到修复的目的。

2.生成需要修复的类及方法的类文件并打包成dex

接下来你可能已经将需要修复的类及方法写好了,这个时候调用Robust的autopatch文件夹中的类及方法会生成如下主要文件:PatchesInfoImpl.java,xxxPatchControl.java(其中xxx为原类的名字)。

PatchesInfoImpl.java的内是由PatchesInfoFactory类的createPatchesInfoClass生成的,这是它生成PatchesInfoImpl逻辑,可以看到,这个类其实是用拼接得到的。

image-20210105175948713

具体代码如下

private CtClass creatxePatchesInfoClass() {
try {
//创建PatchesInfoImpl类
CtClass ctPatchesInfoImpl = classPool.makeClass(Config.patchPackageName + ".PatchesInfoImpl");
ctPatchesInfoImpl.getClassFile().setMajorVersion(ClassFile.JAVA_7);
ctPatchesInfoImpl.setInterfaces(new CtClass[]{classPool.get("com.meituan.robust.PatchesInfo")});
StringBuilder methodBody = new StringBuilder();
//拼接类中的内容
methodBody.append("public java.util.List getPatchedClassesInfo() {");
methodBody.append(" java.util.List patchedClassesInfos = new java.util.ArrayList();");
for (int i = 0; i < Config.modifiedClassNameList.size(); i++) {
if (Constants.OBSCURE) {
methodBody.append("com.meituan.robust.PatchedClassInfo patchedClass" + i + " = new com.meituan.robust.PatchedClassInfo(\"" + ReadMapping.getInstance().getClassMappingOrDefault(Config.modifiedClassNameList.get(i)).getValueName() + "\",\"" + NameManger.getInstance().getPatchControlName(Config.modifiedClassNameList.get(i).substring(Config.modifiedClassNameList.get(i).lastIndexOf('.') + 1)) + "\");");
} else {
methodBody.append("com.meituan.robust.PatchedClassInfo patchedClass" + i + " = new com.meituan.robust.PatchedClassInfo(\"" + Config.modifiedClassNameList.get(i) + "\",\"" + NameManger.getInstance().getPatchControlName(Config.modifiedClassNameList.get(i).substring(Config.modifiedClassNameList.get(i).lastIndexOf('.') + 1)) + "\");");
}
methodBody.append("patchedClassesInfos.add(patchedClass" + i + ");");
}
methodBody.append(Constants.ROBUST_UTILS_FULL_NAME + ".isThrowable=!" + Config.catchReflectException + ";");
methodBody.append("return patchedClassesInfos;\n" +
" }");
CtMethod m = make(methodBody.toString(), ctPatchesInfoImpl);
ctPatchesInfoImpl.addMethod(m);
return ctPatchesInfoImpl;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}

生成的PatchesInfoImpl类型及类内容如下

public class PatchesInfoImpl implements PatchesInfo {
public List getPatchedClassesInfo() {
List arrayList = new ArrayList();
//PatchedClassInfo("原来的类","修复后的类control");
arrayList.add(new PatchedClassInfo("cn.chaitin.geektan.crackme.MainActivity", "cn.chaitin.geektan.crackme.MainActivityPatchControl"));
arrayList.add(new PatchedClassInfo("cn.chaitin.geektan.crackme.MainActivity$1", "cn.chaitin.geektan.crackme.MainActivity$1PatchControl"));
EnhancedRobustUtils.isThrowable = false;
return arrayList;
}
}

另外还会生成一个xxxPatchControl类,通过PatchesControlFactorycreateControlClass()方法生成,具体的逻辑和生成PatchesInfoImpl类类似,其中每个Control类中都存在以下静态成员变量和方法。

private CtClass createControlClass(CtClass modifiedClass) throws Exception {
CtClass patchClass = classPool.get(NameManger.getInstance().getPatchName(modifiedClass.getName()));
patchClass.defrost();
CtClass controlClass = classPool.getAndRename(Constants.PATCH_TEMPLATE_FULL_NAME, NameManger.getInstance().getPatchControlName(modifiedClass.getSimpleName()));
StringBuilder getRealParameterMethodBody = new StringBuilder();
getRealParameterMethodBody.append("public Object getRealParameter(Object parameter) {");
getRealParameterMethodBody.append("if(parameter instanceof " + modifiedClass.getName() + "){");
getRealParameterMethodBody.
append("return new " + patchClass.getName() + "(parameter);");
getRealParameterMethodBody.append("}");
getRealParameterMethodBody.append("return parameter;}");
controlClass.addMethod(CtMethod.make(getRealParameterMethodBody.toString(), controlClass));
controlClass.getDeclaredMethod("accessDispatch").insertBefore(getAccessDispatchMethodBody(patchClass, modifiedClass.getName()));
controlClass.getDeclaredMethod("isSupport").insertBefore(getIsSupportMethodBody(patchClass, modifiedClass.getName()));
controlClass.defrost();
return controlClass;
}

将含有PatchesInfoImpl.java和xxxPatchControl.java,以及xxxPatch.java(具体修复的类)打包成dex文件。

public class xxxPatchControl implements ChangeQuickRedirect
{

public static final String MATCH_ALL_PARAMETER = "(\\w*\\.)*\\w*";

private static final Map<Object, Object> keyToValueRelation = new WeakHashMap();

//获取函数的参数的方法
public Object getRealParameter(Object obj){..具体逻辑..}

//判断是否支持修复
public boolean isSupport(String methodName, Object[] paramArrayOfObject)
{..具体逻辑.}

//执行到accessDispatch方法替换旧的类方法
public Object accessDispatch(String methodName, Object[] paramArrayOfObject) {.具体逻辑..}
}

//解决boolean被优化成byte的问题
private static Object fixObj(Object booleanObj) {.具体逻辑..}

}

3.加载动态dex文件,以反射的方式修改替换旧类

回到我们刚刚分析的地方,跟进PatchExecutor类看看。

public void run() {
try {
//拉取补丁列表
List<Patch> patches = fetchPatchList();
//应用补丁列表
applyPatchList(patches);
} catch (Throwable t) {
Log.e("robust", "PatchExecutor run", t);
robustCallBack.exceptionNotify(t, "class:PatchExecutor,method:run,line:36");
}
}
...
}

在run方法中,主要做了2件事。

1.获取补丁列表

ist<Patch> patches = fetchPatchList();
//PatchManipulateImp类的fetchPatchList方法
protected List<Patch> fetchPatchList() {
return patchManipulate.fetchPatchList(context);
}

2.应用补丁

applyPatchList(patches);

protected void applyPatchList(List<Patch> patches) {
if (null == patches || patches.isEmpty()) {
return;
}
Log.d("robust", " patchManipulate list size is " + patches.size());
for (Patch p : patches) {
if (p.isAppliedSuccess()) {
Log.d("robust", "p.isAppliedSuccess() skip " + p.getLocalPath());
continue;
}
if (patchManipulate.ensurePatchExist(p)) {
boolean currentPatchResult = false;
try {
//真正应用补丁的方法patch()
currentPatchResult = patch(context, p);
} catch (Throwable t) {
robustCallBack.exceptionNotify(t, "class:PatchExecutor method:applyPatchList line:69");
}
if (currentPatchResult) {
//设置patch 状态为成功
p.setAppliedSuccess(true);
//统计PATCH成功率 PATCH成功
robustCallBack.onPatchApplied(true, p);

} else {
//统计PATCH成功率 PATCH失败
robustCallBack.onPatchApplied(false, p);
}

Log.d("robust", "patch LocalPath:" + p.getLocalPath() + ",apply result " + currentPatchResult);

}
}
}

跟进patch()进行分析

protected boolean patch(Context context, Patch patch) {
//验证patch的hash
if (!patchManipulate.verifyPatch(context, patch)) {
robustCallBack.logNotify("verifyPatch failure, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:107");
return false;
}
//调用DexClassLoader动态加载dex
DexClassLoader classLoader = new DexClassLoader(patch.getTempPath(), context.getCacheDir().getAbsolutePath(),
null, PatchExecutor.class.getClassLoader());
patch.delete(patch.getTempPath());

Class patchClass, oldClass;

Class patchsInfoClass;
PatchesInfo patchesInfo = null;
try {
//动态加载PatchesInfoImpl,获取要patch的类
patchsInfoClass = classLoader.loadClass(patch.getPatchesInfoImplClassFullName());
patchesInfo = (PatchesInfo) patchsInfoClass.newInstance();
Log.d("robust", "PatchsInfoImpl ok");
} catch (Throwable t) {
robustCallBack.exceptionNotify(t, "class:PatchExecutor method:patch line:108");
Log.e("robust", "PatchsInfoImpl failed,cause of" + t.toString());
t.printStackTrace();
}

if (patchesInfo == null) {
robustCallBack.logNotify("patchesInfo is null, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:114");
return false;
}

//classes need to patch

//获取要打补丁的类patchedClasses
List<PatchedClassInfo> patchedClasses = patchesInfo.getPatchedClassesInfo();
if (null == patchedClasses || patchedClasses.isEmpty()) {
robustCallBack.logNotify("patchedClasses is null or empty, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:122");
return false;
}

//循环类名,将patchedClasses中的类打补丁
for (PatchedClassInfo patchedClassInfo : patchedClasses) {
String patchedClassName = patchedClassInfo.patchedClassName;
String patchClassName = patchedClassInfo.patchClassName;
if (TextUtils.isEmpty(patchedClassName) || TextUtils.isEmpty(patchClassName)) {
robustCallBack.logNotify("patchedClasses or patchClassName is empty, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:131");
continue;
}
Log.d("robust", "current path:" + patchedClassName);
try {
//将oldClass的changeQuickRedirectField的值设置为null
oldClass = classLoader.loadClass(patchedClassName.trim());
Field[] fields = oldClass.getDeclaredFields();
Log.d("robust", "oldClass :" + oldClass + " fields " + fields.length);
Field changeQuickRedirectField = null;
for (Field field : fields) {
if (TextUtils.equals(field.getType().getCanonicalName(), ChangeQuickRedirect.class.getCanonicalName()) && TextUtils.equals(field.getDeclaringClass().getCanonicalName(), oldClass.getCanonicalName())) {
changeQuickRedirectField = field;
break;
}
}
if (changeQuickRedirectField == null) {
robustCallBack.logNotify("changeQuickRedirectField is null, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:147");
Log.d("robust", "current path:" + patchedClassName + " something wrong !! can not find:ChangeQuickRedirect in" + patchClassName);
continue;
}
Log.d("robust", "current path:" + patchedClassName + " find:ChangeQuickRedirect " + patchClassName);
try {
//动态加载补丁类
patchClass = classLoader.loadClass(patchClassName);
Object patchObject = patchClass.newInstance();
changeQuickRedirectField.setAccessible(true);
//将它的changeQuickRedirectField设置为patchObject实例。
changeQuickRedirectField.set(null, patchObject);
Log.d("robust", "changeQuickRedirectField set sucess " + patchClassName);
} catch (Throwable t) {
Log.e("robust", "patch failed! ");
t.printStackTrace();
robustCallBack.exceptionNotify(t, "class:PatchExecutor method:patch line:163");
}
} catch (Throwable t) {
Log.e("robust", "patch failed! ");
t.printStackTrace();
robustCallBack.exceptionNotify(t, "class:PatchExecutor method:patch line:169");
}
}
Log.d("robust", "patch finished ");
return true;
}

4.isSupport和accessDispatch

我们再来看看onCreate()中的代码,虽然混淆后代码看起来很冗长,但是通过刚刚对Robust原理的简单分析,现在已经可以清晰的知道,这其实就是isSupport()和accessDispatch()。

public void onCreate(Bundle arg13) {
int v4 = 3;
Object[] v0 = new Object[1];
v0[0] = arg13;
ChangeQuickRedirect v2 = MainActivity.changeQuickRedirect;
Class[] v5 = new Class[1];
Class v1 = Bundle.class;
v5[0] = v1;
Class v6 = Void.TYPE;
MainActivity v1_1 = this;
boolean v0_1 = PatchProxy.isSupport(v0, v1_1, v2, false, v4, v5, v6);
if(v0_1) {
v0 = new Object[1];
v0[0] = arg13;
v2 = MainActivity.changeQuickRedirect;
v5 = new Class[1];
v1 = Bundle.class;
v5[0] = v1;
v6 = Void.TYPE;
v1_1 = this;
PatchProxy.accessDispatch(v0, v1_1, v2, false, v4, v5, v6);
}
else {

.....
}

image-20210105185712828

public static boolean isSupport(Object[] paramsArray, Object current, ChangeQuickRedirect changeQuickRedirect, boolean isStatic, int methodNumber, Class[] paramsClassTypes, Class returnType) {
//Robust补丁优先执行,其他功能靠后
if (changeQuickRedirect == null) {
//不执行补丁,轮询其他监听者
if (registerExtensionList == null || registerExtensionList.isEmpty()) {
return false;
}
for (RobustExtension robustExtension : registerExtensionList) {
if (robustExtension.isSupport(new RobustArguments(paramsArray, current, isStatic, methodNumber, paramsClassTypes, returnType))) {
robustExtensionThreadLocal.set(robustExtension);
return true;
}
}
return false;
}
//获取 classMethod = className + ":" + methodName + ":" + isStatic + ":" + methodNumber;
String classMethod = getClassMethod(isStatic, methodNumber);
if (TextUtils.isEmpty(classMethod)) {
return false;
}
Object[] objects = getObjects(paramsArray, current, isStatic);
try {
/*调用changeQuickRedirect.isSupport,还记得这个changeQuickRedirect
吗,他是在第3步中changeQuickRedirectField.set(null, patchObject);
得到的补丁类的实例。*/
return changeQuickRedirect.isSupport(classMethod, objects);
} catch (Throwable t) {
return false;
}
}

通过上面的分析,可以知道只有当存在补丁的类changeQuickRedirect.isSupport()才会返回值。这个时候我们把刚刚第二步打包的dex反编译看看,我们可以看到在xxxPatchControl类中存在isSupport,它返回的值其实就是methodNumber。

public boolean isSupport(String methodName, Object[] paramArrayOfObject) {
return "18:".contains(methodName.split(":")[3]);
}

accessDispatch()方法,替换原方法。

public static Object accessDispatch(Object[] paramsArray, Object current, ChangeQuickRedirect changeQuickRedirect, boolean isStatic, int methodNumber, Class[] paramsClassTypes, Class returnType) {

//如果changeQuickRedirect为null...
if (changeQuickRedirect == null) {
RobustExtension robustExtension = robustExtensionThreadLocal.get();
robustExtensionThreadLocal.remove();
if (robustExtension != null) {
notify(robustExtension.describeSelfFunction());
return robustExtension.accessDispatch(new RobustArguments(paramsArray, current, isStatic, methodNumber, paramsClassTypes, returnType));
}
return null;
}
//同样获取 classMethod = className + ":" + methodName + ":" + isStatic + ":" + methodNumber;
String classMethod = getClassMethod(isStatic, methodNumber);
if (TextUtils.isEmpty(classMethod)) {
return null;
}
notify(Constants.PATCH_EXECUTE);

Object[] objects = getObjects(paramsArray, current, isStatic);

//返回changeQuickRedirect.accessDispatch。
return changeQuickRedirect.accessDispatch(classMethod, objects);
}

具体看看PatchControl类中的accessDispatch。

public Object accessDispatch(String methodName, Object[] paramArrayOfObject) {
try {
MainActivityPatch mainActivityPatch;
//判断classMethod的isStatic是否为false,其实在调用accessDispatch传递的就是false。
if (methodName.split(":")[2].equals("false")) {
MainActivityPatch mainActivityPatch2;
if (keyToValueRelation.get(paramArrayOfObject[paramArrayOfObject.length - 1]) == null) {
mainActivityPatch2 = new MainActivityPatch(paramArrayOfObject[paramArrayOfObject.length - 1]);
keyToValueRelation.put(paramArrayOfObject[paramArrayOfObject.length - 1], null);
} else {
mainActivityPatch2 = (MainActivityPatch) keyToValueRelation.get(paramArrayOfObject[paramArrayOfObject.length - 1]);
}
mainActivityPatch = mainActivityPatch2;
} else {
mainActivityPatch = new MainActivityPatch(null);
}
//根据methodNumber,选取要执行的patch方法。
Object obj = methodName.split(":")[3];
if ("3".equals(obj)) {
mainActivityPatch.onCreate((Bundle) paramArrayOfObject[0]);
}
if ("6".equals(obj)) {
return mainActivityPatch.Joseph(((Integer) paramArrayOfObject[0]).intValue(), ((Integer) paramArrayOfObject[1]).intValue());
}
} catch (Throwable th) {
th.printStackTrace();
}
return null;
}

Robust的基本原理就是这些了

hook点分析

我们对Robust进行分析,现在已经比较清晰的知道了我们需要攻克的难点,它是通过Robust热修复框架将一些方法热修复了,所以我们这里必须知道,它修复了哪些类及方法。

foremost提取assets文件夹下的GeekTan.BMP,得到dex文件直接扔到jadx中进行分析。

─$ foremost GeekTan.BMP
foremost: /usr/local/etc/foremost.conf: No such file or directory
Processing: GeekTan.BMP
|foundat=classes.dex�,�dex
035
*|

在PatchesInfoImpl类中可以看到2个要被修复的类信息。

image-20210105190528663

MainActivityPatchControl类,我们看到在accessDispatch(),onCreate()和Joseph()方法将会通过判断ethodNumber来选取。

image-20210105190724026

继续查看MainActivity$1PatchControl类,同样发现onClick被修复了。

image-20210105190859996

所以这个时候,我们必须知道onClick真正执行的逻辑是什么。查看MainActivity$1Patch类中的真正的onClick方法。

package cn.chaitin.geektan.crackme;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import cn.chaitin.geektan.crackme.MainActivity;
import com.meituan.robust.patch.RobustModify;
import com.meituan.robust.utils.EnhancedRobustUtils;

public class MainActivity$1Patch {
MainActivity.1 originClass;

public MainActivity$1Patch(Object obj) {
this.originClass = (MainActivity.1) obj;
}

public Object[] getRealParameter(Object[] objArr) {
if (objArr == null || objArr.length < 1) {
return objArr;
}
Object[] objArr2 = new Object[objArr.length];
for (int i = 0; i < objArr.length; i++) {
if (objArr[i] == this) {
objArr2[i] = this.originClass;
} else {
objArr2[i] = objArr[i];
}
}
return objArr2;
}

public void onClick(View view) {
MainActivity$1Patch mainActivity$1Patch;
EnhancedRobustUtils.invokeReflectStaticMethod("modify", RobustModify.class, getRealParameter(new Object[0]), (Class[]) null);
MainActivity.1 r0 = (EditText) EnhancedRobustUtils.getFieldValue("val$input_text", this instanceof MainActivity$1Patch ? this.originClass : this, MainActivity.1.class);
if (r0 == this) {
r0 = ((MainActivity$1Patch) r0).originClass;
}
if (!((Boolean) EnhancedRobustUtils.invokeReflectStaticMethod("isEmpty", TextUtils.class, getRealParameter(new Object[]{(Editable) EnhancedRobustUtils.invokeReflectMethod("getText", r0, new Object[0], (Class[]) null, EditText.class)}), new Class[]{CharSequence.class})).booleanValue()) {
MainActivity.1 r02 = (EditText) EnhancedRobustUtils.getFieldValue("val$input_text", this instanceof MainActivity$1Patch ? this.originClass : this, MainActivity.1.class);
if (r02 == this) {
r02 = ((MainActivity$1Patch) r02).originClass;
}
MainActivity.1 r03 = (Editable) EnhancedRobustUtils.invokeReflectMethod("getText", r02, new Object[0], (Class[]) null, EditText.class);
if (r03 == this) {
r03 = ((MainActivity$1Patch) r03).originClass;
}
MainActivity.1 r04 = (String) EnhancedRobustUtils.invokeReflectMethod("toString", r03, new Object[0], (Class[]) null, Object.class);
MainActivity.1 r1 = (StringBuilder) EnhancedRobustUtils.invokeReflectConstruct("java.lang.StringBuilder", new Object[0], (Class[]) null);
if (r1 == this) {
r1 = ((MainActivity$1Patch) r1).originClass;
}
MainActivity.1 r12 = (StringBuilder) EnhancedRobustUtils.invokeReflectMethod("append", r1, getRealParameter(new Object[]{"DDCTF{"}), new Class[]{String.class}, StringBuilder.class);
MainActivity.1 r2 = (MainActivity) EnhancedRobustUtils.getFieldValue("this$0", this instanceof MainActivity$1Patch ? this.originClass : this, MainActivity.1.class);
if (r2 == this) {
r2 = ((MainActivity$1Patch) r2).originClass;
}
String str = (String) EnhancedRobustUtils.invokeReflectMethod("Joseph", r2, getRealParameter(new Object[]{new Integer(5), new Integer(6)}), new Class[]{Integer.TYPE, Integer.TYPE}, MainActivity.class);
if (r12 == this) {
r12 = ((MainActivity$1Patch) r12).originClass;
}
MainActivity.1 r13 = (StringBuilder) EnhancedRobustUtils.invokeReflectMethod("append", r12, getRealParameter(new Object[]{str}), new Class[]{String.class}, StringBuilder.class);
MainActivity.1 r22 = (MainActivity) EnhancedRobustUtils.getFieldValue("this$0", this instanceof MainActivity$1Patch ? this.originClass : this, MainActivity.1.class);
if (r22 == this) {
r22 = ((MainActivity$1Patch) r22).originClass;
}
String str2 = (String) EnhancedRobustUtils.invokeReflectMethod("Joseph", r22, getRealParameter(new Object[]{new Integer(7), new Integer(8)}), new Class[]{Integer.TYPE, Integer.TYPE}, MainActivity.class);
if (r13 == this) {
r13 = ((MainActivity$1Patch) r13).originClass;
}
MainActivity.1 r14 = (StringBuilder) EnhancedRobustUtils.invokeReflectMethod("append", r13, getRealParameter(new Object[]{str2}), new Class[]{String.class}, StringBuilder.class);
if (r14 == this) {
r14 = ((MainActivity$1Patch) r14).originClass;
}
MainActivity.1 r15 = (StringBuilder) EnhancedRobustUtils.invokeReflectMethod("append", r14, getRealParameter(new Object[]{"}"}), new Class[]{String.class}, StringBuilder.class);
if (r15 == this) {
r15 = ((MainActivity$1Patch) r15).originClass;
}
String str3 = (String) EnhancedRobustUtils.invokeReflectMethod("toString", r15, new Object[0], (Class[]) null, StringBuilder.class);
if (r04 == this) {
r04 = ((MainActivity$1Patch) r04).originClass;
}
if (((Boolean) EnhancedRobustUtils.invokeReflectMethod("equals", r04, getRealParameter(new Object[]{str3}), new Class[]{Object.class}, String.class)).booleanValue()) {
if (this instanceof MainActivity$1Patch) {
mainActivity$1Patch = this.originClass;
} else {
mainActivity$1Patch = this;
}
MainActivity.1 r05 = (Toast) EnhancedRobustUtils.invokeReflectStaticMethod("makeText", Toast.class, getRealParameter(new Object[]{(MainActivity) EnhancedRobustUtils.getFieldValue("this$0", mainActivity$1Patch, MainActivity.1.class), "恭喜大佬!密码正确!", new Integer(0)}), new Class[]{Context.class, CharSequence.class, Integer.TYPE});
if (r05 == this) {
r05 = ((MainActivity$1Patch) r05).originClass;
}
EnhancedRobustUtils.invokeReflectMethod("show", r05, new Object[0], (Class[]) null, Toast.class);
return;
}
}
MainActivity.1 r06 = (Toast) EnhancedRobustUtils.invokeReflectStaticMethod("makeText", Toast.class, getRealParameter(new Object[]{(MainActivity) EnhancedRobustUtils.getFieldValue("this$0", this instanceof MainActivity$1Patch ? this.originClass : this, MainActivity.1.class), "大佬莫急!再试试!", new Integer(0)}), new Class[]{Context.class, CharSequence.class, Integer.TYPE});
if (r06 == this) {
r06 = ((MainActivity$1Patch) r06).originClass;
}
EnhancedRobustUtils.invokeReflectMethod("show", r06, new Object[0], (Class[]) null, Toast.class);
}
}

分析onClick方法,可以发现很多invokeReflectStaticMethodgetFieldValueinvokeReflectMethod方法,同样我们还能发现flag就在这里面。

//flag是通过append将字符串以及Joseph(int,int)的返回值拼接构成的。
String str = "DDCTF{";
str = (String) EnhancedRobustUtils.invokeReflectMethod("Joseph", obj2, getRealParameter(new Object[]{new Integer(5), new Integer(6)}), new Class[]{Integer.TYPE, Integer.TYPE}, MainActivity.class);
str = (String) EnhancedRobustUtils.invokeReflectMethod("Joseph", obj2, getRealParameter(new Object[]{new Integer(7), new Integer(8)}), new Class[]{Integer.TYPE, Integer.TYPE}, MainActivity.class);
str = "}";
//最终将我们输入的值与上面构造的equals比较,判断是否准确。
if (((Boolean) EnhancedRobustUtils.invokeReflectMethod("equals", obj, getRealParameter(new Object[]{str2}), new Class[]{Object.class}, String.class)).booleanValue()) {...}

通过上面的分析,可以发现hook有2个思路:

1.hook EnhancedRobustUtils类下的方法获取方法执行的返回值。
2.hook 动态加载的类MainActivityPatchJoseph方法,直接调用它获取返回值。(下篇)

代码构造

先来看看EnhancedRobustUtils类下的方法invokeReflectMethod

public static Object invokeReflectMethod(String methodName, Object targetObject, Object[] parameters, Class[] args, Class declaringClass) {
try {
//可以看到这里是通过反射的方法拿到类实例
Method method = getDeclaredMethod(targetObject, methodName, args, declaringClass);
//代入参数,调用方法
return method.invoke(targetObject, parameters);
} catch (Exception e) {
e.printStackTrace();
}
if (isThrowable) {
throw new RuntimeException("invokeReflectMethod error " + methodName + " parameter " + parameters + " targetObject " + targetObject.toString() + " args " + args);
}
return null;
}

invokeReflectConstruct

public static Object invokeReflectConstruct(String className, Object[] parameter, Class[] args) {
try {
//通过Class.forName(className)反射得到一个Class对象
Class clazz = Class.forName(className);
//获得构造器
Constructor constructor = clazz.getDeclaredConstructor(args);
constructor.setAccessible(true);
//返回该类的实例
return constructor.newInstance(parameter);
} catch (Exception e) {
e.printStackTrace();
}
if (isThrowable) {
throw new RuntimeException("invokeReflectConstruct error " + className + " parameter " + parameter);
}
return null;
}

很简单,通过反射得到类的实例及方法,最终通过invoke代入参数执行方法。这里很幸运,我们发现这个EnhancedRobustUtils 是Robust自带的类,并不是动态加载的。
那hook就非常简单了,我们只需要简单的hook invokeReflectMethod获取Joseph的返回值,以及equals的参数即可。

image-20210105192047314

Java.perform(function(){
//获得EnhancedRobustUtils类的wapper
var robust = Java.use("com.meituan.robust.utils.EnhancedRobustUtils");
//hook invokeReflectMethod方法
robust.invokeReflectMethod.implementation = function(v1,v2,v3,v4,v5){
//不破坏原来的逻辑,只在原来的逻辑中打印出Joseph,equals的值
var result = this.invokeReflectMethod(v1,v2,v3,v4,v5);
if(v1=="Joseph"){
console.log("functionName:"+v1);
console.log("functionArg3:"+v3);
console.log("functionArg4:"+v4);
send(v4);
console.log("return:"+result);
console.log("-----------------------------------------------------")
}

else if(v1=="equals"){
console.log("functionName:"+v1);
console.log("functionArg3:"+v3);
console.log("functionArg4:"+v4);
send(v4);
console.log("return:"+result);
}
return result;
}
});

完整代码:

# -*- coding: UTF-8 -*-
import frida,sys

def on_message(message, data):
if message['type'] == 'send':
print("[*] {0}".format(message['payload']))
else:
print(message)


js_code = '''
Java.perform(function(){
var robust = Java.use("com.meituan.robust.utils.EnhancedRobustUtils");
robust.invokeReflectMethod.implementation = function(v1,v2,v3,v4,v5){
var result = this.invokeReflectMethod(v1,v2,v3,v4,v5);
if(v1=="Joseph"){
console.log("functionName:"+v1);
console.log("functionArg3:"+v3);
console.log("functionArg4:"+v4);
send(v4);
console.log("return:"+result);
console.log("-----------------------------------------------------")
}

else if(v1=="equals"){
console.log("functionName:"+v1);
console.log("functionArg3:"+v3);
console.log("functionArg4:"+v4);
send(v4);
console.log("return:"+result);
}
return result;
}
});
'''
session = frida.get_usb_device().attach("cn.chaitin.geektan.crackme")
script = session.create_script(js_code)
script.on('message',on_message)
script.load()
sys.stdin.read()

运行脚本 点击Onclick

image-20210105200059163

参考链接

https://bbs.pediy.com/thread-229597.htm

FROM :ol4three.com | Author:ol4three

特别标注: 本站(CN-SEC.COM)所有文章仅供技术研究,若将其信息做其他用途,由用户承担全部法律及连带责任,本站不承担任何法律及连带责任,请遵守中华人民共和国安全法.
  • 我的微信
  • 微信扫一扫
  • weinxin
  • 我的微信公众号
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年1月6日01:09:45
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                  Frida--Android逆向之动态加载dex Hook(上) http://cn-sec.com/archives/721206.html

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: