10老Android开发谈:Android-Hook-机制连简单实战都不会凭什么拿高薪?

if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}

static class ListenerInfo {


ListenerInfo getListenerInfo() {
if (mListenerInfo != null) {
return mListenerInfo;
}
mListenerInfo = new ListenerInfo();
return mListenerInfo;
}


}

接下来,让我们一起来看一下怎样 Hook View.OnClickListener 事件?

大概分为三步:

  • 第一步:获取 ListenerInfo 对象

从 View 的源代码,我们可以知道我们可以通过 getListenerInfo 方法获取,于是,我们利用反射得到 ListenerInfo 对象

  • 第二步:获取原始的 OnClickListener事件方法

从上面的分析,我们知道 OnClickListener 事件被保存在 ListenerInfo 里面,同理我们利用反射获取

  • 第三步:偷梁换柱,用 Hook代理类 替换原始的 OnClickListener

public static void hookOnClickListener(View view) throws Exception {
// 第一步:反射得到 ListenerInfo 对象
Method getListenerInfo = View.class.getDeclaredMethod(“getListenerInfo”);
getListenerInfo.setAccessible(true);
Object listenerInfo = getListenerInfo.invoke(view);
// 第二步:得到原始的 OnClickListener事件方法
Class<?> listenerInfoClz = Class.forName(“android.view.View$ListenerInfo”);
Field mOnClickListener = listenerInfoClz.getDeclaredField(“mOnClickListener”);
mOnClickListener.setAccessible(true);
View.OnClickListener originOnClickListener = (View.OnClickListener) mOnClickListener.get(listenerInfo);
// 第三步:用 Hook代理类 替换原始的 OnClickListener
View.OnClickListener hookedOnClickListener = new HookedClickListenerProxy(originOnClickListener);
mOnClickListener.set(listenerInfo, hookedOnClickListener);
}

public class HookedClickListenerProxy implements View.OnClickListener {

private View.OnClickListener origin;

public HookedClickListenerProxy(View.OnClickListener origin) {
this.origin = origin;
}

@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), “Hook Click Listener”, Toast.LENGTH_SHORT).show();
if (origin != null) {
origin.onClick(v);
}
}

}

执行以下代码,将会看到当我们点击该按钮的时候,会弹出 toast “Hook Click Listener”

mBtn1 = (Button) findViewById(R.id.btn_1);
mBtn1.setOnClickListener(this);
try {
HookHelper.hookOnClickListener(mBtn1);
} catch (Exception e) {
e.printStackTrace(

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

浏览器打开:qq.cn.hn/FTe 免费领取

);
}

简单案例二: HooK Notification

发送消息到通知栏的核心代码如下:

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, builder.build());

跟踪 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);

}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1JFZ2TxF-1636332604609)(//upload-images.jianshu.io/upload_images/2050203-2182b90f3d1607c2.gif?imageMogr2/auto-orient/strip|imageView2/2/w/439/format/webp)]

第二种方法

对 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对象

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

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值