宇郑 发表于 2023-11-29 12:05

用C++写一个OD反附加函数LD_PRELOAD劫持示例

在Linux中,我们可以使用LD_PRELOAD环境变量来预加载一些动态链接库,这样当程序运行时,就会先加载这些动态链接库。这种方式常被用来进行程序的调试或者功能扩展。

下面是一个简单的C++示例,我们将创建一个动态链接库libtest.so,然后在这个库中定义一个printf函数的替代版本。当我们运行main.cpp时,会先加载libtest.so,并使用其中的printf函数。

首先,我们创建一个名为libtest.c的文件:

```c
#include <stdio.h>

void __attribute__((constructor)) my_init(void) {
    puts("Constructor called");
}

void __attribute__((destructor)) my_fini(void) {
    puts("Destructor called");
}

int printf(const char *format, ...) {
    va_list arg;
    va_start(arg, format);
    vfprintf(stderr, format, arg);// 打印到stderr而不是stdout
    va_end(arg);

    return 0;// 返回0表示成功
}
```

这个文件中的my_init和my_fini函数会在动态链接库加载和卸载时自动调用。我们重写了printf函数,使其将输出打印到stderr而不是stdout。

然后,我们需要编译这个文件为动态链接库:

```bash
gcc -shared -o libtest.so libtest.c
```

接下来,我们创建一个main.cpp文件来测试我们的动态链接库:

```cpp
#include <iostream>
#include <cstdio>

int main() {
    std::cout << "Hello, World!" << std::endl;
    printf("This should be printed to stderr\n");
    return 0;
}
```

最后,我们通过设置LD_PRELOAD环境变量来运行main.cpp,使其加载我们的动态链接库:

```bash
LD_PRELOAD=./libtest.so ./a.out
```

运行结果如下:

```shell
Constructor called
Hello, World!
This should be printed to stderr
Destructor called
```

这就是一个简单的OD反附加函数LD_PRELOAD劫持示例。

boot 发表于 2023-11-29 17:01

学习一下。{:5_116:}

fyh505099 发表于 2023-11-30 00:02

学习学习~宇哥YYDS!
页: [1]
查看完整版本: 用C++写一个OD反附加函数LD_PRELOAD劫持示例