目標(biāo):對(duì) ClipBoard服務(wù)進(jìn)行HOOK,復(fù)制黏貼內(nèi)容自動(dòng)加上標(biāo)簽"[Hooked]"
分析
1.我們調(diào)研黏貼板服務(wù)的時(shí)候,是通過(guò):
private void initClipService() {
if (mClipService == null) {
mClipService = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
mClipService.addPrimaryClipChangedListener(this);
}
}
private void setClipContent(){
initClipService();
ClipData data = ClipData.newPlainText("消息", "今天是2月14日");
mClipService.setPrimaryClip(data);
}
這時(shí)候我們復(fù)制黏貼會(huì)顯示原始的"今天2月14日"
2.過(guò)程跟蹤
我們通過(guò)Context.getSystemService(name)拿到具體的服務(wù)對(duì)象,具體實(shí)現(xiàn)在ContextImpl.java里面,如下:
@Override
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
獲取到的服務(wù),預(yù)先存放在SystemServiceRegistry.java,代碼如下:
public static String getSystemServiceName(Class<?> serviceClass) {
return SYSTEM_SERVICE_NAMES.get(serviceClass);
}
而SYSTEM_SERVICE_NAMES就算一個(gè)Map,存放了所有系統(tǒng)服務(wù)的獲取方式工廠類(lèi),在static靜態(tài)代碼塊里面初始化,如下:
static{
...
registerService(Context.CLIPBOARD_SERVICE, ClipboardManager.class,
new CachedServiceFetcher<ClipboardManager>() {
@Override
public ClipboardManager createService(ContextImpl ctx) {
return new ClipboardManager(ctx.getOuterContext(),
ctx.mMainThread.getHandler());
}});
}
然后,我們看ClipBoardManager里面就包含了真正的ClipService,代碼如下:
static private IClipboard getService() {
synchronized (sStaticLock) {
if (sService != null) {
return sService;
}
IBinder b = ServiceManager.getService("clipboard");
sService = IClipboard.Stub.asInterface(b);
return sService;
}
}
/** {@hide} */
public ClipboardManager(Context context, Handler handler) {
mContext = context;
}
public void setPrimaryClip(ClipData clip) {
try {
if (clip != null) {
clip.prepareToLeaveProcess(true);
}
getService().setPrimaryClip(clip, mContext.getOpPackageName());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
真正獲取到ClipService服務(wù),就是如下兩句:
IBinder b = ServiceManager.getService("clipboard");//獲取到遠(yuǎn)程對(duì)象
sService = IClipboard.Stub.asInterface(b);//獲取到實(shí)體對(duì)象,如果是跨進(jìn)程,拿到代理對(duì)象
/**
* ServiceManager查找服務(wù)的具體實(shí)現(xiàn),會(huì)去sCache里面拿去一次,如果沒(méi)有直接問(wèn)IServiceManager獲取
*/
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;
}
//對(duì)IBinder有一定了解,就知道,Stub是生成遠(yuǎn)程代理的地方
public static abstract class Stub extends android.os.Binder implements IClipboard{
...
/**
* generating a proxy if needed.
*/
public static IClipboard asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
//查詢(xún)本地,如果是跨進(jìn)程這個(gè)一定為空
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof IClipboard ))) {
return ((IClipboard ) iin);
}
//準(zhǔn)備跨進(jìn)程的proxy類(lèi)實(shí)例
return new IClipboard .Stub.Proxy(obj);
}
}
所以正常獲取到黏貼板服務(wù),流程如下:

所以通過(guò)流程我們可以知道,關(guān)于Clipboard service:
a. ContextImpl 會(huì)緩存第一次獲取生成的ClipboardManager,這里會(huì)問(wèn)ServiceManager拿去Clipboard service IBinder引用
b. ServiceManager 服務(wù)的sCache,打印了下,沒(méi)有緩存過(guò)ClipboardService,應(yīng)該是每次請(qǐng)求都會(huì)直接獲取IBinder引用,打印原始sCache,如下:
02-14 14:49:57.030 13199-13199/qiu.myaidls_server I/HOOK: 拿到原始的Service代理[android.os.BinderProxy@1f15a7f]
02-14 14:49:57.030 13199-13199/qiu.myaidls_server I/HOOK: scache Name[package]
02-14 14:49:57.030 13199-13199/qiu.myaidls_server I/HOOK: scache Name[alarm]
02-14 14:49:57.030 13199-13199/qiu.myaidls_server I/HOOK: scache Name[window]
所以我們一個(gè)可行思路,如下:
1.在sCache里面存放我們生成的 Myproxy_IBinder 代理接口
2.而 Myproxy_IBinder接口再攔截本地查詢(xún)的時(shí)候,返回我們的Myproxy_IClipboard實(shí)例
3.Myproxy_IClipboard包含有Raw_IClipboard_proxy,它有能力和真正的服務(wù)交流,
所以Myproxy_IClipboard操作Raw_IClipboard_proxy得到結(jié)果,并且修改結(jié)果為我們需要的內(nèi)容,
再返回給上層,完成Hook功能
代碼如下:
private String mHookServiceName;//要HOOK的服務(wù)名稱(chēng)
private String mHookServiceInterface;//要HOOK的服務(wù)的Iinterface,Ibinder里面的概念
private Class<?> mHookInterfaceClz;//Iinterface clz
private Class<?> mHookInterfaceStubClz;//IInterface.Stub
private IBinder mRawServiceIBinder;//要Hook的服務(wù)原始IBinder引用
private Object mRawServiceProxyBinder;//代理
private void hookInner() {
try {
hookLog("HOOK>>>START");
Class<?> clz_ServiceManager = Class.forName(SMGR_NAME);
//拿到原始服務(wù)的IBinder引用
Method method_getService = clz_ServiceManager.getDeclaredMethod("getService", String.class);
method_getService.setAccessible(true);
mRawServiceIBinder = (IBinder) method_getService.invoke(null, mHookServiceName);
Method method_stub_asInterface = mHookInterfaceStubClz.getDeclaredMethod("asInterface", IBinder.class);
mRawServiceProxyBinder = method_stub_asInterface.invoke(null, mRawServiceIBinder);
hookLog("拿到原始的Service IBinder[%s_%s]", mHookServiceName, mRawServiceIBinder);
hookLog("拿到原始的Service ProxyBinder[%s_%s]", mHookServiceName, mRawServiceProxyBinder);
//生成我們自己的IBinder代理
IBinder my_proxy_ibinder = (IBinder) Proxy.newProxyInstance(mRawServiceIBinder.getClass().getClassLoader(),
new Class[]{IBinder.class},
new MyiBinderInvocationHandler());
//替換ServiceManager.sCache里面的clipboard的value為我們Hooked代理服務(wù)
Field field_service_cache = clz_ServiceManager.getDeclaredField("sCache");
field_service_cache.setAccessible(true);
Map<String, IBinder> map = (Map<String, IBinder>) field_service_cache.get(null);
map.put(mHookServiceName, my_proxy_ibinder);
hookLog("HOOK<<<END");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 對(duì)binder進(jìn)行hook
*/
private class MyiBinderInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("queryLocalInterface")) {//查詢(xún)本地的時(shí)候,返回我們的代理IBinder
return Proxy.newProxyInstance(proxy.getClass().getClassLoader(),
new Class[]{mHookInterfaceClz},
new MyServiceInvocationHandler());
}
return method.invoke(proxy, args);
}
}
/**
* 對(duì)具體服務(wù)進(jìn)行HOOK
*/
private class MyServiceInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (mHookCallback != null && mHookCallback.needHookMethod(method.getName())) {
return mHookCallback.hookMethod(mRawServiceProxyBinder, method, args);
}
return method.invoke(mRawServiceProxyBinder, args);
}
}
private static void hookLog(String format, Object... argus) {
Log.i("HOOK", String.format(format, argus));
}
主頁(yè)代碼,如下:
mHook = new ServiceHooker(this);
mHook.setHookCallback(new ServiceHooker.IHookCallback() {
@Override
public boolean needHookMethod(String method) {
if ("getPrimaryClip".equals(method)) {
return true;
}
return false;
}
@Override
public Object hookMethod(Object raw_service, Method method, Object[] args) throws Throwable {
ClipData data = (ClipData) method.invoke(raw_service, args);
return ClipData.newPlainText("新消息", String.format("%s[一朵玫瑰花]", data.getItemAt(0).getText()));
}
});
mHook.setHookServiceName(Context.CLIPBOARD_SERVICE);
mHook.setHookServiceInterface("android.content.IClipboard");
mHook.hook();
效果如下:

完成添加自己要的效果,
這個(gè)只是練手,沒(méi)有多大實(shí)際意義,加深了對(duì)IBinder理解
參考文章:
插件化分析全面的系列文章