前言
PackageManagerService(简称PMS),是Android系统核心服务之一,处理包管理相关的工作,常见的比如安装、卸载应用等。
使用PMS获取包签名信息
许多时候我们会使用到PMS,来获取apk的签名值。一般获取方式如下:
private void getSignature() {
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
Log.i(SHARK, "len:"+packageInfo.signatures.length);
if (packageInfo.signatures != null) {
Log.i(SHARK, "sig:"+packageInfo.signatures[0].toCharsString());
}
} catch (Exception e) {
}
}
源码分析
我们进入到getPackageManager()中
//ContextWrapper.java
@Override
public PackageManager getPackageManager() {
return mBase.getPackageManager();
}
这里是调用了mBase的getPackageManager方法,可是mBase是Context引用这个是一个抽象类,那么mBase是在什么时候设置进去的呢?
//ContextWrapper.java
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException("Base context already set");
}
mBase = base;
}
通过上面的代码可以知道mBase 是在attachBaseContext方法中设置进去的
查看方法的调用处可以看到是在我们的MainActivity的attachBaseContext方法中
//MainActivity.java
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
}
这个attachBaseContext方法是什么时候调用的呢?
//Activity.java
@UnsupportedAppUsage
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
//调用attachBaseContext
attachBaseContext(context);
...
}
这个就是在attach方法中调用的了,设置给mBase的值就是这上面传过来的
调用attach的地方是在ActivityThread的performLaunchActivity方法中
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
ContextImpl appContext = createBaseContextForActivity(r);
...
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback,
r.assistToken);
...
}
有上面的代码可以知道最终调用mBase.getPackageManager()的mBase是Context的子类ContextImpl
getPackageManager()的实现如下
//ContextImpl .java
@Override
public PackageManager getPackageManager() {
if (mPackageManager != null) {
return mPackageManager;
}
final IPackageManager pm = ActivityThread.getPackageManager();
final IPermissionManager permissionManager = ActivityThread.getPermissionManager();
if (pm != null && permissionManager != null) {
// Doesn't matter if we make more than one instance.
return (mPackageManager = new ApplicationPackageManager(this, pm, permissionManager));
}
return null;
}
因为PackageManager也是一个抽象类,所以这里使用的是他的继承类ApplicationPackageManager,我们在应用层获得的其实就是它。
可以看看getPackageInfo的具体实现
//ApplicationPackageManager.java
...
private final IPackageManager mPM;
...
@Override
public PackageInfo getPackageInfo(String packageName, int flags)
throws NameNotFoundException {
return getPackageInfoAsUser(packageName, flags, getUserId());
}
...
@Override
public PackageInfo getPackageInfoAsUser(String packageName, int flags, int userId)
throws NameNotFoundException {
try {
PackageInfo pi = mPM.getPackageInfo(packageName, flags, userId);
if (pi != null) {
return pi;
}
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
throw new NameNotFoundException(packageName);
}
可以知道其实最后是交给mPM去获得包的信息
所以我们需要将mPM替换掉就可以达到Hook的效果
那么mPM是什么时候设置进去的呢?
这就要回到ContextImpl的getPackageManager中了
这里是通过ActivityThread.getPackageManager获取到IPackageManager 构造出来的ApplicationPackageManager
所以我们关注一下这个方法
//ActivityThread.java
...
static volatile IPackageManager sPackageManager;
...
public static IPackageManager getPackageManager() {
if (sPackageManager != null) {
return sPackageManager;
}
final IBinder b = ServiceManager.getService("package");
sPackageManager = IPackageManager.Stub.asInterface(b);
return sPackageManager;
}
上面就是返回sPackageManager属性
而ApplicationPackageManager构造方法如下
//ApplicationPackageManager.java
...
private final IPackageManager mPM;
...
protected ApplicationPackageManager(ContextImpl context, IPackageManager pm,
IPermissionManager permissionManager) {
mContext = context;
mPM = pm;
mPermissionManager = permissionManager;
}
可以看到我们在最上层应用中调用的就是这个IPackageManager的方法,并且在ActivityThread的sPackageManager属性中有这样一个对象,在ApplicationPackageManager的mPM也有一个这个对象。
最后知道我们要使用动态代理的方式替换掉这里的两个属性
- ActivityThread的静态变量sPackageManager
- ApplicationPackageManager对象里面的mPM变量
HOOK PMS
这里我用了一个修改签名值为例子
Hook的方式主要使用了JDK动态代理,不了解的可以看看动态代理模式。
//ServiceManagerWraper.java
package com.shark.hookpms;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;
public class ServiceManagerWraper {
public final static String SHARK = "Shark";
public static void hookPMS(Context context, String signed, String appPkgName, int hashCode) {
try {
// 获取全局的ActivityThread对象
Class> activityThreadClass = Class.forName("android.app.ActivityThread");
Method currentActivityThreadMethod =
activityThreadClass.getDeclaredMethod("currentActivityThread");
Object currentActivityThread = currentActivityThreadMethod.invoke(null);
// 获取ActivityThread里面原始的sPackageManager
Field sPackageManagerField = activityThreadClass.getDeclaredField("sPackageManager");
sPackageManagerField.setAccessible(true);
Object sPackageManager = sPackageManagerField.get(currentActivityThread);
// 准备好代理对象, 用来替换原始的对象
Class> iPackageManagerInterface = Class.forName("android.content.pm.IPackageManager");
Object proxy = Proxy.newProxyInstance(
iPackageManagerInterface.getClassLoader(),
new Class>[]{iPackageManagerInterface},
new PmsHookBinderInvocationHandler(sPackageManager, signed, appPkgName, 0));
// 1. 替换掉ActivityThread里面的 sPackageManager 字段
sPackageManagerField.set(currentActivityThread, proxy);
// 2. 替换 ApplicationPackageManager里面的 mPM对象
PackageManager pm = context.getPackageManager();
Field mPmField = pm.getClass().getDeclaredField("mPM");
mPmField.setAccessible(true);
mPmField.set(pm, proxy);
} catch (Exception e) {
Log.d(SHARK, "hook pms error:" + Log.getStackTraceString(e));
}
}
public static void hookPMS(Context context) {
String qqSign = "30820253308201bca00302010202044bbb0361300d06092a864886f70d0101050500306d310e300c060355040613054368696e61310f300d06035504080c06e58c97e4baac310f300d06035504070c06e58c97e4baac310f300d060355040a0c06e885bee8aeaf311b3019060355040b0c12e697a0e7babfe4b89ae58aa1e7b3bbe7bb9f310b30090603550403130251513020170d3130303430363039343831375a180f32323834303132303039343831375a306d310e300c060355040613054368696e61310f300d06035504080c06e58c97e4baac310f300d06035504070c06e58c97e4baac310f300d060355040a0c06e885bee8aeaf311b3019060355040b0c12e697a0e7babfe4b89ae58aa1e7b3bbe7bb9f310b300906035504031302515130819f300d06092a864886f70d010101050003818d0030818902818100a15e9756216f694c5915e0b529095254367c4e64faeff07ae13488d946615a58ddc31a415f717d019edc6d30b9603d3e2a7b3de0ab7e0cf52dfee39373bc472fa997027d798d59f81d525a69ecf156e885fd1e2790924386b2230cc90e3b7adc95603ddcf4c40bdc72f22db0f216a99c371d3bf89cba6578c60699e8a0d536950203010001300d06092a864886f70d01010505000381810094a9b80e80691645dd42d6611775a855f71bcd4d77cb60a8e29404035a5e00b21bcc5d4a562482126bd91b6b0e50709377ceb9ef8c2efd12cc8b16afd9a159f350bb270b14204ff065d843832720702e28b41491fbc3a205f5f2f42526d67f17614d8a974de6487b2c866efede3b4e49a0f916baa3c1336fd2ee1b1629652049";
hookPMS(context, qqSign, "com.shark.hookpms", 0);
}
}
要想替换ActivityThread的静态变量sPackageManager,需要先调用ActivityThread的静态方法currentActivityThread获得当前的ActivityThread
替换ApplicationPackageManager对象里面的mPM变量,可以使用context.getPackageManager得到这个外层对象
这里我们得到了真正的sPackageManager,我们只需要使用JDK动态代理构建一个代理类就可以了
最后两者使用反射将属性替换成了我们构造出来的代理类
//PmsHookBinderInvocationHandler.java
package com.shark.hookpms;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Log;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class PmsHookBinderInvocationHandler implements InvocationHandler {
private Object base;
public final static String SHARK = "Shark";
//应用正确的签名信息
private String SIGN;
private String appPkgName = "";
public PmsHookBinderInvocationHandler(Object base, String sign, String appPkgName, int hashCode) {
try {
this.base = base;
this.SIGN = sign;
this.appPkgName = appPkgName;
} catch (Exception e) {
Log.d(SHARK, "error:"+Log.getStackTraceString(e));
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Log.i(SHARK, method.getName());
//查看是否是getPackageInfo方法
if("getPackageInfo".equals(method.getName())){
String pkgName = (String)args[0];
Integer flag = (Integer)args[1];
//是否是获取我们需要hook apk的签名
if(flag == PackageManager.GET_SIGNATURES && appPkgName.equals(pkgName)){
//将构造方法中传进来的新的签名覆盖掉原来的签名
Signature sign = new Signature(SIGN);
PackageInfo info = (PackageInfo) method.invoke(base, args);
info.signatures[0] = sign;
return info;
}
}
return method.invoke(base, args);
}
}
上面的代码主要是过滤到是否是我们需要hook apk调用了pms的getPackageInfo,并且获取签名信息
调用处
protected void attachBaseContext(Context newBase) {
ServiceManagerWraper.hookPMS(newBase);
super.attachBaseContext(newBase);
}