#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h>

#define BUF_SIZE 1024

void hook_read(int fd, void *buf, size_t count) { printf("Process %d read %ld bytes from file descriptor %d\n", getpid(), count, fd); }

void hook_write(int fd, const void *buf, size_t count) { printf("Process %d write %ld bytes to file descriptor %d\n", getpid(), count, fd); }

ssize_t (real_read)(int, void, size_t); ssize_t (real_write)(int, const void, size_t);

ssize_t hooked_read(int fd, void *buf, size_t count) { hook_read(fd, buf, count); return real_read(fd, buf, count); }

ssize_t hooked_write(int fd, const void *buf, size_t count) { hook_write(fd, buf, count); return real_write(fd, buf, count); }

int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s \n", argv[0]); exit(1); }

int fd = open(argv[1], O_RDWR);
if (fd == -1) {
    perror("open");
    exit(1);
}

void *addr = mmap(NULL, BUF_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
    perror("mmap");
    exit(1);
}

real_read = dlsym(RTLD_NEXT, "read");
real_write = dlsym(RTLD_NEXT, "write");

printf("Hooked process %d\n", getpid());

while (1) {
    char buf[BUF_SIZE];
    printf("Enter something: ");
    fflush(stdout);
    fgets(buf, BUF_SIZE, stdin);
    strncpy(addr, buf, BUF_SIZE);
    msync(addr, BUF_SIZE, MS_SYNC);
}

return 0;

}

写一个利用钩子监控进程文件读写操作的代码 用c语言

原文地址: https://www.cveoy.top/t/topic/MYK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录