Hook黏贴板服务,练手

目标:对 ClipBoard服务进行HOOK,复制黏贴内容自动加上标签"[Hooked]"
分析

1.我们调研黏贴板服务的时候,是通过:

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

这时候我们复制黏贴会显示原始的"今天2月14日"

2.过程跟踪
我们通过Context.getSystemService(name)拿到具体的服务对象,具体实现在ContextImpl.java里面,如下:

    @Override
    public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }

获取到的服务,预先存放在SystemServiceRegistry.java,代码如下:

    public static String getSystemServiceName(Class<?> serviceClass) {
        return SYSTEM_SERVICE_NAMES.get(serviceClass);
    }

而SYSTEM_SERVICE_NAMES就算一个Map,存放了所有系统服务的获取方式工厂类,在static静态代码块里面初始化,如下:

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服务,就是如下两句:

  IBinder b = ServiceManager.getService("clipboard");//获取到远程对象
  sService = IClipboard.Stub.asInterface(b);//获取到实体对象,如果是跨进程,拿到代理对象

    /**
     * ServiceManager查找服务的具体实现,会去sCache里面拿去一次,如果没有直接问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;
  }

//对IBinder有一定了解,就知道,Stub是生成远程代理的地方
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;
            }
            //查询本地,如果是跨进程这个一定为空
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof IClipboard ))) {
                return ((IClipboard ) iin);
            }
            //准备跨进程的proxy类实例
            return new IClipboard .Stub.Proxy(obj);
        }
}

所以正常获取到黏贴板服务,流程如下:

Paste_Image.png

所以通过流程我们可以知道,关于Clipboard service:
a. ContextImpl 会缓存第一次获取生成的ClipboardManager,这里会问ServiceManager拿去Clipboard service IBinder引用
b. ServiceManager 服务的sCache,打印了下,没有缓存过ClipboardService,应该是每次请求都会直接获取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]

所以我们一个可行思路,如下:

1.在sCache里面存放我们生成的 Myproxy_IBinder 代理接口
2.而 Myproxy_IBinder接口再拦截本地查询的时候,返回我们的Myproxy_IClipboard实例
3.Myproxy_IClipboard包含有Raw_IClipboard_proxy,它有能力和真正的服务交流,
  所以Myproxy_IClipboard操作Raw_IClipboard_proxy得到结果,并且修改结果为我们需要的内容,
  再返回给上层,完成Hook功能

代码如下:

private String mHookServiceName;//要HOOK的服务名称
    private String mHookServiceInterface;//要HOOK的服务的Iinterface,Ibinder里面的概念
    private Class<?> mHookInterfaceClz;//Iinterface clz
    private Class<?> mHookInterfaceStubClz;//IInterface.Stub
    private IBinder mRawServiceIBinder;//要Hook的服务原始IBinder引用
    private Object mRawServiceProxyBinder;//代理

    private void hookInner() {
        try {
            hookLog("HOOK>>>START");
            Class<?> clz_ServiceManager = Class.forName(SMGR_NAME);
            //拿到原始服务的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代理服务
            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();
        }
    }

    /**
     * 对binder进行hook
     */
    private class MyiBinderInvocationHandler implements InvocationHandler {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("queryLocalInterface")) {//查询本地的时候,返回我们的代理IBinder
                return Proxy.newProxyInstance(proxy.getClass().getClassLoader(),
                        new Class[]{mHookInterfaceClz},
                        new MyServiceInvocationHandler());
            }
            return method.invoke(proxy, args);
        }
    }

    /**
     * 对具体服务进行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));
    }

主页代码,如下:

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

效果如下:

Paste_Image.png

完成添加自己要的效果,
这个只是练手,没有多大实际意义,加深了对IBinder理解

参考文章:
插件化分析全面的系列文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容