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理解

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容