拦截 open
gcc -shared -fPIC -o libintercept.so intercept.c -ldl
LD_PRELOAD=./libintercept.so ./processA
在Linux中,我们可以使用LD_PRELOAD环境变量来拦截并替换系统调用,如open函数。这是一个简单的示例,展示了如何创建一个新的open函数来替换系统的open函数:
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
// 定义原始的open函数
static int (*original_open)(const char*, int, ...);
// 我们的新open函数
int open(const char *pathname, int flags, ...) {
printf("Intercepted open call for %s\n", pathname);
// 获取原始的open函数
original_open = dlsym(RTLD_NEXT, "open");
// 调用原始的open函数
return original_open(pathname, flags);
}
~~~
你可以将这段代码保存为一个.c文件,然后使用以下命令编译为共享库:
gcc -shared -fPIC -o libintercept.so intercept.c -ldl
然后,你可以使用LD_PRELOAD环境变量来运行你的程序,如下所示:
```bash
LD_PRELOAD=./libintercept.so your_program
这样,每当你的程序调用open函数时,都会调用我们的新open函数,而不是系统的open函数。
请注意,这只是一个基本的示例,你可能需要根据你的具体需求来修改这个新的open函数。此外,使用LD_PRELOAD拦截系统调用应该谨慎进行,因为它可能会影响到其他库的行为。
第一个需求
第一个需求
1.白名单进程 保存在 进程白名单文件 , 受保护文件的文件名保存在 文件白名单文件 中,
2.白名单 进程 能访问 所有文件(受保护文件和非保护文件)
3.对所有进程访问文件的 过程进行日志记录.(进程名,文件名,访问时间,成功与否)
文件结构
.
├── Files
│ ├── t1
│ ├── t2
│ ├── t3
│ ├── t4
│ ├── t5
│ ├── t6
│ ├── t7
│ ├── t8
│ └── t9
├── WHITELIST
│ ├── file_whitelist
│ ├── file_whitelist_backup
│ └── process_whitelist
├── intercept.c
├── libintercept.so
├── log.txt
├── p1
└── p1.c
进程白名单
白名单文件的路径名是/home/xxx/Test/WHITELIST/process_whitelist
/home/xxx/Test/p1
/home/xxx/Test/p2
/home/xxx/Test/p3
/home/xxx/Test/p4
/home/xxx/Test/p5
文件白名单
非白名单文件的路径名是/home/xxx/Test/WHITELIST/file_whitelist
/home/xxx/Test/Files/t1
/home/xxx/Test/Files/t2
/home/xxx/Test/Files/t3
/home/xxx/Test/Files/t4
/home/xxx/Test/Files/t5
测试代码
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main() {
DIR *dir;
struct dirent *entry;
int fd;
// 打开目录
dir = opendir("/home/xxx/Test/Files");
if (dir == NULL) {
perror("无法打开目录");
return 1;
}
// 遍历目录中的每个文件
while ((entry = readdir(dir)) != NULL) {
// 检查文件名是否以"t"开头
if (strncmp(entry->d_name, "t", 1) == 0) {
char filepath[1024];
// 构造文件路径
snprintf(filepath, sizeof(filepath), "/home/xxx/Test/Files/%s", entry->d_name);
// 使用open函数打开文件
fd = open(filepath, O_RDWR);
if (fd == -1) {
perror("无法打开文件");
continue;
}
printf("打开文件: %s\n", filepath);
// 写入文件
const char *message = "我访问了这个文件\n";
if (write(fd, message, strlen(message)) == -1) {
perror("无法写入文件");
}
// 关闭文件
if (close(fd) == -1) {
perror("无法关闭文件");
}
}
}
// 关闭目录
if (closedir(dir) == -1) {
perror("无法关闭目录");
}
return 0;
}
第一个版本
gcc -shared -fPIC -o libintercept.so intercept.c -ldl
当然,这是修改后的完整代码:
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
// 定义原始的open函数
static int (*original_open)(const char*, int, ...);
// 根据进程ID获取进程名
char *get_process_name(pid_t pid) {
char path[256