Android FileObserver 实现原理(inotify)

0x0前言

之前在分析某个Android平台加固壳子的时候就碰到过inotify,被用来监控/proc 文件系统,防止gdb调试器的附加,以达到反调试的目的。inotify机制是从linux kernel 2.6.13开始引入,Android 1.5对应的linux内核已经是2.6.26了。因此完全可以在Android上利用inotify达到反调试的目的。而且Android将inotify直接封装成了FileObserver类,可以直接在Java代码中使用。当然在jni中自己调用inotify也是很容易的。

0x01 FileObserver 使用实例

想要在Java层使用FileObserver,必须先继承FileObserver类,实现其onEvent()函数。作为目标文件发生变化时调用的方法。

  private class SingleFileObserver extends FileObserver{
        //......
        @Override
        public void onEvent(int i, String s) {
        //..... 
        }
    }

通过startWatching()开始监视,stopWatching()停止监视。
考虑到FileObserver不支持子目录的递归,将FileObserver封装了一层,以达到可以递归监视的目的。

public class RecursiveFileObserver{

    private ArrayList<SingleFileObserver> mSingleObservers = new ArrayList<SingleFileObserver>();


    public RecursiveFileObserver(String path){

        //解析子目录
        Stack<String> pathStack = new Stack<String>();
        pathStack.push(path);
        while (!pathStack.isEmpty()){
            String parentPath = pathStack.pop();
            if (mSingleObservers.add(new SingleFileObserver(parentPath))){
                Log.d("C&C","add observer success"+parentPath);
            }

            File parent = new File(parentPath);

            if (parent.isDirectory()){
                File[] files = parent.listFiles();
                for (int i =0;i<files.length;i++){
                    File f = files[i];
                    if (f.isDirectory() &&
                            (f.getName().equals(".") || f.getName().equals(".."))){
                        //跳过 "." ".." 目录
                    }else {
                        pathStack.push(f.toString());
                        //pathStack.push(f.getAbsolutePath());
                        Log.d("C&C","file list:"+f.toString());
                    }
                }
            }

        }

    }

    public void startWatching() {
       for (int i = 0;i<mSingleObservers.size();i++){
           mSingleObservers.get(i).startWatching();
       }

    }

    public void stopWatching() {
        for (int i = 0;i<mSingleObservers.size();i++){
            mSingleObservers.get(i).stopWatching();
        }
    }

    private class SingleFileObserver extends FileObserver{

        protected String mPath ;
        protected int mMask;
        public static final int DEFAULT_MASK = CREATE | MODIFY | DELETE;


        public SingleFileObserver(String path){
            this(path , DEFAULT_MASK);
        }

        public SingleFileObserver(String path , int mask){
            super(path , mask);
            mPath = path;
            mMask = mask;
        }

        @Override
        public void onEvent(int i, String s) {
            int event = i&FileObserver.ALL_EVENTS;
            switch (event){
                case MODIFY:
                    //查看是否被调试
                    if (isDebugged(s)){
                        Log.d("C&C","is debugged");
                    }
            }
        }
    }
}

0x02 FileObserver 实现原理

Android已经将linux下的inotify机制封装成了FileObserver抽象类,必须继承FileObserver类才能使用。

android.os.FileObserver
Monitors files (using inotify) to fire an event after files are accessed or changed by by any process on the device (including this one). FileObserver is an abstract class; subclasses must implement the event handler onEvent(int, String).
Each FileObserver instance monitors a single file or directory. If a directory is monitored, events will be triggered for all files and subdirectories inside the monitored directory.
An event mask is used to specify which changes or actions to report. Event type constants are used to describe the possible changes in the event mask as well as what actually happened in event callbacks.

Android sdk的官方文档说的是监视一个目录,则该目录下所有的文件和子目录的改变都会触发监听的事件。经过测试,其实对于监听目录的子目录的文件改动,FileObserver对象是无法接收到事件回调的。
FileObserver可以监听的类型:

  • ACCESS 访问文件
  • MODIFY 修改文件
  • ATTRIB 修改文件属性,例如chmod 、chown等
  • CLOSE_WRITE以可写属性打开的文件被关闭
  • CLOSE_NOWRITE 以不可写属性被打开的文件被关闭
  • OPEN 文件被打开
  • MOVED_FROM 文件被移走,例如mv
  • MOVED_TO 移入新文件,例如mv cp
  • CREATE 创建新文件
  • DELETE 删除文件,例如rm
  • DELETE_SELF 自删除,一个文件在执行时删除自己
  • MOVE_SELF 自移动,一个可执行文件在执行时移动自己
  • CLOSE 关闭文件 = (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)
  • ALL_EVENTS 上面所有的事件

要先继承FileObserver抽象类,实现其中的OnEvent()方法

public abstract void onEvent(int event, String path);

在FileObserver类中封装有一个static 的线程类

private static class ObserverThread extends Thread {
    ......
}
  • inotify初始化
    在ObserverThread类的构造方法中:
 public ObserverThread() {
      super("FileObserver");
      m_fd = init();
}

这里的init是native方法:

 private native int init();

/frameworks/base/core/jni/android_util_FileObserver.cpp

static jint android_os_fileobserver_init(JNIEnv* env, jobject object)
{
    return (jint)inotify_init();    
}

很明显,只是调用了inotify_init(),初始化inotify。

  • 开始监控
    使用要先调用FileObserver.startWatching()--->ObserverThread.startWatching()--->linux( inotify_add_watch() )
 public int startWatching(String path, int mask, FileObserver observer) {
    int wfd = startWatching(m_fd, path, ma
    Integer i = new Integer(wfd);
    if (wfd >= 0) {
        synchronized (m_observers) {
            m_observers.put(i, new WeakReference(observer));
        }      
    }
    return i;
}
static jint android_os_fileobserver_startWatching(JNIEnv* env, jobject object, jint fd, jstring pathString, jint mask)
{
    int res = -1;
    if (fd >= 0)
    {
        const char* path = env->GetStringUTFChars(pathString, NULL);    
        res = inotify_add_watch(fd, path, mask);   //返回监视器描述符
        env->ReleaseStringUTFChars(pathString, path);
    } 
    return res;
}
  • 监控过程
    在 ObserverThread 线程运行的run()方法中:
public void run() { 
    observe(m_fd);
}
static void android_os_fileobserver_observe(JNIEnv* env, jobject object, jint fd)
{
    char event_buf[512];
    struct inotify_event* event;      
    while (1)
    {
        int event_pos = 0;
        int num_bytes = read(fd, event_buf, sizeof(event_buf)); //读取事件
        if (num_bytes < (int)sizeof(*event))
        {
            if (errno == EINTR)
                continue;
            ALOGE("***** ERROR! android_os_fileobserver_observe() got a short event!");
            return;
        }
        
        while (num_bytes >= (int)sizeof(*event))
        {
            int event_size;
            event = (struct inotify_event *)(event_buf + event_pos);
            jstring path = NULL;
            if (event->len > 0)
            {
                path = env->NewStringUTF(event->name);
            }
	    //调用java层ObserverThread类的OnEvent方法
            env->CallVoidMethod(object, method_onEvent, event->wd, event->mask, path);
            if (env->ExceptionCheck()) { //异常处理
                env->ExceptionDescribe();
                env->ExceptionClear();
            }
            if (path != NULL)
            {
                env->DeleteLocalRef(path);
            }
	    //指向下一个inotify_event结构
            event_size = sizeof(*event) + event->len;
            num_bytes -= event_size;
            event_pos += event_size;
        }
    }
}

inotify_event的结构如下:

struct inotify_event {
 __s32 wd;           /* watch descriptor */
 __u32 mask;        /* watch mask */
 __u32 cookie;     /* cookie to synchronize two events */
 __u32 len;            /* length (including nulls) of name */
 char name[0];       /* stub for possible name */
};
  • wd: 被监视目标的 watch 描述符
  • mask : 事件掩码
  • name: 被监视目标的路径名,文件名被0填充,使得下一个事件结构能够以4字节对齐
  • len : name字符串的长度
    调用的onEvent()方法:
public void onEvent(int wfd, int mask, String path) {
    // look up our observer, fixing up the map if necessary...
    FileObserver observer = null;
    synchronized (m_observers) {  //同步代码块
        WeakReference weak = m_observers.get(wfd);
        if (weak != null) {  // can happen with lots of events from a dead wfd
            observer = (FileObserver) weak.get();
            if (observer == null) {
                m_observers.remove(wfd);
            }
        }
    }
    // ...then call out to the observer without the sync lock held
    if (observer != null) {  //为什么不使用同步代码块???
        try {
            observer.onEvent(mask, path); //调用FileObserver抽象类的OnEvent()方法,也就是自己实现的OnEvent()方法
        } catch (Throwable throwable) {
            Log.wtf(LOG_TAG, "Unhandled exception in FileObserver " + observer, throwable);
        }
    }
}
  • 停止监控
    FileObserver.stopWatching() --> ObserverThread.stopWatching()---> linux( inotify_rm_watch() )
static void android_os_fileobserver_stopWatching(JNIEnv* env, jobject object, jint fd, jint wfd)
{
    inotify_rm_watch((int)fd, (uint32_t)wfd);
}

0x04 完整Demo下载地址

https://github.com/ChengChengCC/Android-demo/tree/master/FileObserver

posted on 2016-05-28 11:55  _懒人  阅读(8823)  评论(0编辑  收藏  举报

导航