简体   繁体   中英

Intercepting stat call with LD_PRELOAD

I'm trying to write a shared object that intercepts some filesystem API calls such as open, close, read, write etc., that originate from an application. Interception is done using LD_PRELOAD. I've used strace methodically to find out the APIs called by the application and implement them in the shared library loaded by LD_PRELOAD. When it comes to stat, I found that __xstat and __xstat64 is called instead of stat and I've overridden these two functions. I'm able to trap these API calls. However, in one particular environment, when I use strace I see direct calls to the stat() itself. Like below

25083 03:11:28.424859 close(13)         = 0 <0.000045>
>> 25083 03:11:28.424966 stat("/somedir/somefile", 0x7ffe751d2430) = -1 ENOENT (No such file or directory) <0.000050>
25083 03:11:28.425067 clock_gettime(CLOCK_MONOTONIC, {786855, 130369007}) = 0 <0.000029>

The difference I note is that stat is called directly which I don't see in other environments. It is possible that the application calls stat() however I see that stat internally calls __xstat or __xstat64. Another thing I noticed is that stat() isn't even implemented in libc.so library. So this stat() appears to be a direct invocation of the stat() system call. How do I confirm this? And how would an application directly invoke stat() system call?

So this stat() appears to be a direct invocation of the stat() system call. How do I confirm this?

Run the program inside of gdb with catch syscall stat . When the syscall happens, check the call stack with bt and take note of whether you're in libc.so.

And how would an application directly invoke stat() system call?

With inline assembly. Here's an example of it for :

#include <stdio.h>
#include <sys/stat.h>
#include <sys/syscall.h>

int main(int argc, char **argv) {
    if(argc < 2) return 1;
    struct stat s;
    long rv;
    __asm__ volatile(
        "syscall"
        : "=a"(rv)
        : "a"(SYS_stat), "D"(argv[1]), "S"(&s)
        : "rcx", "r11", "memory"
    );
    if(rv) return 1;
    printf("%zu\n", s.st_size);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM