Android Hook 机制之简单实战

跟踪 notify 方法发现最终会调用到 notifyAsUser 方法

public void notify(String tag, int id, Notification notification)

{

notifyAsUser(tag, id, notification, new UserHandle(UserHandle.myUserId()));

}

而在 notifyAsUser 方法中,我们惊喜地发现 service 是一个单例,因此,我们可以想方法 hook 住这个 service,而 notifyAsUser 最终会调用到 service 的 enqueueNotificationWithTag 方法。因此 hook 住 service 的 enqueueNotificationWithTag 方法即可

public void notifyAsUser(String tag, int id, Notification notification, UserHandle user)

{

//

INotificationManager service = getService();

String pkg = mContext.getPackageName();

// Fix the notification as best we can.

Notification.addFieldsFromContext(mContext, notification);

if (notification.sound != null) {

notification.sound = notification.sound.getCanonicalUri();

if (StrictMode.vmFileUriExposureEnabled()) {

notification.sound.checkFileUriExposed(“Notification.sound”);

}

}

fixLegacySmallIcon(notification, pkg);

if (mContext.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {

if (notification.getSmallIcon() == null) {

throw new IllegalArgumentException("Invalid notification (no valid small icon): "

  • notification);

}

}

if (localLOGV) Log.v(TAG, pkg + “: notify(” + id + ", " + notification + “)”);

final Notification copy = Builder.maybeCloneStrippedForDelivery(notification);

try {

service.enqueueNotificationWithTag(pkg, mContext.getOpPackageName(), tag, id,

copy, user.getIdentifier());

} catch (RemoteException e) {

throw e.rethrowFromSystemServer();

}

}

private static INotificationManager sService;

static public INotificationManager getService()

{

if (sService != null) {

return sService;

}

IBinder b = ServiceManager.getService(“notification”);

sService = INotificationManager.Stub.asInterface(b);

return sService;

}

综上,要 Hook Notification,大概需要三步:

  • 第一步:得到 NotificationManager 的 sService

  • 第二步:因为 sService 是接口,所以我们可以使用动态代理,获取动态代理对象

  • 第三步:偷梁换柱,使用动态代理对象 proxyNotiMng 替换系统的 sService

于是,我们可以写出如下的代码

public static void hookNotificationManager(final Context context) throws Exception {

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

Method getService = NotificationManager.class.getDeclaredMethod(“getService”);

getService.setAccessible(true);

// 第一步:得到系统的 sService

final Object sOriginService = getService.invoke(notificationManager);

Class iNotiMngClz = Class.forName(“android.app.INotificationManager”);

// 第二步:得到我们的动态代理对象

Object proxyNotiMng = Proxy.newProxyInstance(context.getClass().getClassLoader(), new

Class[]{iNotiMngClz}, new InvocationHandler() {

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

Log.d(TAG, “invoke(). method:” + method);

String name = method.getName();

Log.d(TAG, “invoke: name=” + name);

if (args != null && args.length > 0) {

for (Object arg : args) {

Log.d(TAG, “invoke: arg=” + arg);

}

}

Toast.makeText(context.getApplicationContext(), “检测到有人发通知了”, Toast.LENGTH_SHORT).show();

// 操作交由 sOriginService 处理,不拦截通知

return method.invoke(sOriginService, args);

// 拦截通知,什么也不做

// return null;

// 或者是根据通知的 Tag 和 ID 进行筛选

}

});

// 第三步:偷梁换柱,使用 proxyNotiMng 替换系统的 sService

Field sServiceField = NotificationManager.class.getDeclaredField(“sService”);

sServiceField.setAccessible(true);

sServiceField.set(notificationManager, proxyNotiMng);

}


Hook 使用进阶


Hook ClipboardManager

第一种方法

从上面的 hook NotificationManager 例子中,我们可以得知 NotificationManager 中有一个静态变量 sService,这个变量是远端的 service。因此,我们尝试查找 ClipboardManager 中是不是也存在相同的类似静态变量。

查看它的源码发现它存在 mService 变量,该变量是在 ClipboardManager 构造函数中初始化的,而 ClipboardManager 的构造方法用 @hide 标记,表明该方法对调用者不可见。

而我们知道 ClipboardManager,NotificationManager 其实这些都是单例的,即系统只会创建一次。因此我们也可以认为

ClipboardManager 的 mService 是单例的。因此 mService 应该是可以考虑 hook 的一个点。

public class ClipboardManager extends android.text.ClipboardManager {

private final Context mContext;

private final IClipboard mService;

/** {@hide} */

public ClipboardManager(Context context, Handler handler) throws ServiceNotFoundException {

mContext = context;

mService = IClipboard.Stub.asInterface(

ServiceManager.getServiceOrThrow(Context.CLIPBOARD_SERVICE));

}

}

接下来,我们再来一个看一下 ClipboardManager 的相关方法 setPrimaryClip , getPrimaryClip

public void setPrimaryClip(ClipData clip) {

try {

if (clip != null) {

clip.prepareToLeaveProcess(true);

}

mService.setPrimaryClip(clip, mContext.getOpPackageName());

} catch (RemoteException e) {

throw e.rethrowFromSystemServer();

}

}

/**

  • Returns the current primary clip on the clipboard.

*/

public ClipData getPrimaryClip() {

try {

return mService.getPrimaryClip(mContext.getOpPackageName());

} catch (RemoteException e) {

throw e.rethrowFromSystemServer();

}

}

可以发现这些方法最终都会调用到 mService 的相关方法。因此,ClipboardManager 的 mService 确实是一个可以 hook 的一个点。

hook ClipboardManager.mService 的实现

大概需要三个步骤

  • 第一步:得到 ClipboardManager 的 mService

  • 第二步:初始化动态代理对象

  • 第三步:偷梁换柱,使用 proxyNotiMng 替换系统的 mService

public static void hookClipboardService(final Context context) throws Exception {

ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);

Field mServiceFiled = ClipboardManager.class.getDeclaredField(“mService”);

mServiceFiled.setAccessible(true);

// 第一步:得到系统的 mService

final Object mService = mServiceFiled.get(clipboardManager);

// 第二步:初始化动态代理对象

Class aClass = Class.forName(“android.content.IClipboard”);

Object proxyInstance = Proxy.newProxyInstance(context.getClass().getClassLoader(), new

Class[]{aClass}, new InvocationHandler() {

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

Log.d(TAG, “invoke(). method:” + method);

String name = method.getName();

if (args != null && args.length > 0) {

for (Object arg : args) {

Log.d(TAG, “invoke: arg=” + arg);

}

}

if (“setPrimaryClip”.equals(name)) {

Object arg = args[0];

if (arg instanceof ClipData) {

ClipData clipData = (ClipData) arg;

int itemCount = clipData.getItemCount();

for (int i = 0; i < itemCount; i++) {

ClipData.Item item = clipData.getItemAt(i);

Log.i(TAG, “invoke: item=” + item);

}

}

Toast.makeText(context, “检测到有人设置粘贴板内容”, Toast.LENGTH_SHORT).show();

} else if (“getPrimaryClip”.equals(name)) {

Toast.makeText(context, “检测到有人要获取粘贴板的内容”, Toast.LENGTH_SHORT).show();

}

// 操作交由 sOriginService 处理,不拦截通知

return method.invoke(mService, args);

}

});

// 第三步:偷梁换柱,使用 proxyNotiMng 替换系统的 mService

Field sServiceField = ClipboardManager.class.getDeclaredField(“mService”);

sServiceField.setAccessible(true);

sServiceField.set(clipboardManager, proxyInstance);

}

第二种方法

对 Android 源码有基本了解的人都知道,Android 中的各种 Manager 都是通过 ServiceManager 获取的。因此,我们可以通过 ServiceManager hook 所有系统 Manager,ClipboardManager 当然也不例外。

public final class ServiceManager {

/**

  • Returns a reference to a service with the given name.

  • @param name the name of the service to get

  • @return a reference to the service, or null if the service doesn’t exist

*/

public static IBinder getService(String name) {

try {

IBinder service = sCache.get(name);

if (service != null) {

return service;

} else {

return getIServiceManager().getService(name);

}

} catch (RemoteException e) {

Log.e(TAG, “error in getService”, e);

}

return null;

}

}

老套路

  • 第一步:通过反射获取剪切板服务的远程Binder对象,这里我们可以通过 ServiceManager getService 方法获得

  • 第二步:创建我们的动态代理对象,动态代理原来的Binder对象

  • 第三步:偷梁换柱,把我们的动态代理对象设置进去

public static void hookClipboardService() throws Exception {

//通过反射获取剪切板服务的远程Binder对象

Class serviceManager = Class.forName(“android.os.ServiceManager”);

Method getServiceMethod = serviceManager.getMethod(“getService”, String.class);

IBinder remoteBinder = (IBinder) getServiceMethod.invoke(null, Context.CLIPBOARD_SERVICE);

//新建一个我们需要的Binder,动态代理原来的Binder对象

IBinder hookBinder = (IBinder) Proxy.newProxyInstance(serviceManager.getClassLoader(),

new Class[]{IBinder.class}, new ClipboardHookRemoteBinderHandler(remoteBinder));

//通过反射获取ServiceManger存储Binder对象的缓存集合,把我们新建的代理Binder放进缓存

Field sCacheField = serviceManager.getDeclaredField(“sCache”);

sCacheField.setAccessible(true);

Map<String, IBinder> sCache = (Map<String, IBinder>) sCacheField.get(null);

sCache.put(Context.CLIPBOARD_SERVICE, hookBinder);

}

public class ClipboardHookRemoteBinderHandler implements InvocationHandler {

private IBinder remoteBinder;

private Class iInterface;

private Class stubClass;

public ClipboardHookRemoteBinderHandler(IBinder remoteBinder) {

this.remoteBinder = remoteBinder;

try {

this.iInterface = Class.forName(“android.content.IClipboard”);

this.stubClass = Class.forName(“android.content.IClipboard$Stub”);

} catch (Exception e) {

e.printStackTrace();

}

}

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

Log.d(“RemoteBinderHandler”, method.getName() + “() is invoked”);

if (“queryLocalInterface”.equals(method.getName())) {

//这里不能拦截具体的服务的方法,因为这是一个远程的Binder,还没有转化为本地Binder对象

//所以先拦截我们所知的queryLocalInterface方法,返回一个本地Binder对象的代理

return Proxy.newProxyInstance(remoteBinder.getClass().getClassLoader(),

new Class[]{this.iInterface},

new ClipboardHookLocalBinderHandler(remoteBinder, stubClass));

}

return method.invoke(remoteBinder, args);

}

}

最后

愿你有一天,真爱自己,善待自己。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 30
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值