文件重定位簡單實現和對抗

文件重定向是一個文件重定位到另外一個文件。重定向後,當一個文件的發生打開,讀寫這些行爲,就會變成另外一個文件的打開,讀寫。

文件重定向多用於過風控,改機,多開等場景中。

實現

作爲實現重定向的一方,有許多實現方式,下面的例子是用frida腳本hook libc.so下的open函數,在open函數被調用的時候,根據文件名來判斷是否對打開的重定向,最後將文件描述符返回。

function strcmp(str1,str2){
    let ret = -1;

	for(let i = 0; ;i++){
		let ch1 = str1.add(i).readU8();
		let ch2 = str2.add(i).readU8();
		
		if(ch1 == 0 && ch2 == 0){
		    ret = 0;
			break;
		}
		
		if(ch1 != ch2){
		    ret = -1;
		    break;
		}
		
	}
	
	return ret;
}


function redirect(src,dest){
    const openPtr = Module.getExportByName('libc.so', 'open');
    const open = new NativeFunction(openPtr, 'int', ['pointer', 'int']);
    Interceptor.replace(openPtr, new NativeCallback((pathPtr, flags) => {
        const path = pathPtr.readUtf8String();
        
        const originPath = Memory.allocUtf8String(src)
        let currentPath = Memory.allocUtf8String(path)
        let fd = -1
        if(strcmp(currentPath,originPath) == 0){
           console.warn('redirect file "' + path + '" to "' + dest + '"');
           let targetPath = Memory.allocUtf8String(dest)
           fd = open(targetPath, flags);
        }
        else{
            console.log('open file "' + path + '"');
            fd = open(pathPtr, flags);
        }
        return fd;
    }, 'int', ['pointer', 'int']));

}

redirect("/proc/cpuinfo","/data/data/com.luoye.fileredirectdetect/cpuinfo")

經過hook之後,當app打開/proc/cpuinfo,文件路徑就被重定向到了自定義的文件路徑。open函數返回的是新的文件的文件描述符。

對抗

既然hook之後返回的是新的文件的文件描述符,那麼,對抗方就可以打開需要檢測的文件,然後調用readlink函數反推文件路徑,如果readlink返回的文件路徑和打開的文件不一致,那麼說明打開的文件被重定位到其他文件去了。

/**
 * 檢查文件是否被重定位
 * @src_path 要檢查的文件
 * @new_path 被重定位到的路徑
 * @return 0 沒有重定位;1 被重定位
 */
int checkFileRedirect(const char *src_path,char *new_path,size_t max_len) {
    int src_fd = open(src_path,O_RDONLY);
    if(src_fd < 0){
        return 0;
    }
    int ret = 0;
    char link_path[128] = {0};
    snprintf(link_path, sizeof(link_path), "/proc/%d/fd/%d", getpid(), src_fd);
    char fd_path[256] = {0};
    int link = readlink(link_path, fd_path, sizeof(fd_path));

    if(link < 0){
        return 0;
    }

    size_t len = strnlen(fd_path,256);

    if(len && strncmp(fd_path,src_path,256) != 0) {
        strncpy(new_path, fd_path,max_len);

        ret = 1;
    }

    if(src_fd > 0) {
        close(src_fd);
    }

    return ret;
}

下圖是在多開軟件中檢測到的路徑重定向結果:

當然這只是提供的一個思路,文件重定位可以有其他實現,對抗也可以有其他實現,想要做得更好,需要更多的想象力。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章