Files
2026-10-20 13:00:45 +08:00

383 lines
13 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# v1.0.0
Released 2026-10-20. This is the first public release of **ptrace-inject-cpp**, a
C++ port of [Artemis21/ptrace-inject](https://github.com/Artemis21/ptrace-inject).
`ptrace-inject-cpp` injects a shared library into a running x86-64 Linux process
using `ptrace`. The core flow is: attach to every thread of the target, remotely
call `malloc` / `dlopen` / `free` inside it, then restore the original code and
registers and detach. There is no ELF parsing and no spawn mode.
## Highlights
- **Stable C ABI.** `include/ptrace_inject.h` is directly usable from C and C++,
with two entry points: `ptrace_inject_by_pid()` and `ptrace_inject_by_name()`.
- **Static or shared.** `libptrace_inject.a` is built by default; pass
`-DBUILD_SHARED_LIBS=ON` for a versioned shared library (`SOVERSION` 1).
- **Thin CLI.** `ptrace-inject-cpp` injects by PID (`-p`) or by executable name
(`-n`).
- **Easy to embed.** No install rules: use `include/` and `build/` directly, or
`add_subdirectory()`. An alias target `ptrace_inject::ptrace_inject` is provided.
- **Silent by default.** Logs are emitted only through an optional caller-supplied
callback, and the shared library exports only the two API functions.
## What's included
| Path | Description |
| --- | --- |
| `include/ptrace_inject.h` | Public C-compatible API |
| `src/` | Library implementation plus the CLI entry point |
| `examples/inject_by_pid.c` | Minimal C usage example |
| `examples/inject_by_name.cpp` | C++ example using the log callback and `resolved_pid` |
| `examples/sample_library.c` | Sample library whose constructor writes a marker file |
| `CMakeLists.txt` | Build system (CMake >= 3.16, C++17) |
Build options:
- `-DCMAKE_BUILD_TYPE=Release` (the default when unset)
- `-DBUILD_SHARED_LIBS=ON` for a shared library
- `-DPTRACE_INJECT_BUILD_CLI=OFF` to skip the CLI
- `-DPTRACE_INJECT_BUILD_EXAMPLES=OFF` to skip the examples
## Usage
### Build from source
```bash
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --parallel
```
Artifacts: `build/libptrace_inject.a`, `build/ptrace-inject-cpp`,
`build/example_by_pid`, `build/example_by_name`,
`build/libptrace_inject_sample.so`.
Add `-DBUILD_SHARED_LIBS=ON` for `libptrace_inject.so*` instead of the static
archive.
### Command line
```bash
# By PID
./build/ptrace-inject-cpp -p <PID> /absolute/path/to/libfoo.so
# By executable name or path
./build/ptrace-inject-cpp -n <process-name> /absolute/path/to/libfoo.so
# Help
./build/ptrace-inject-cpp -h
```
The path is resolved in the injector's mount namespace, so the target must be
able to open the same path.
### Use as a library
```c
#include <stdio.h>
#include "ptrace_inject.h"
static void on_log(int level, const char *message, void *user_data) {
(void)level;
(void)user_data;
fprintf(stderr, "%s\n", message);
}
int main(void) {
ptrace_inject_options options = {0};
options.log_fn = on_log;
char error[512] = {0};
if (ptrace_inject_by_pid(1234, "/abs/path/libfoo.so", &options, error,
sizeof(error)) != PTRACE_INJECT_OK) {
fprintf(stderr, "inject failed: %s\n", error);
return 1;
}
return 0;
}
```
`options` and `error` may be `NULL`; `resolved_pid` in
`ptrace_inject_by_name()` may also be `NULL`. The call is synchronous and blocks
until `dlopen()` has run (or failed). Concurrent calls are safe as long as the
targets differ.
Link against the build tree (no installation step):
```bash
# C
gcc -c app.c -I/path/to/ptrace-inject-cpp/include -o app.o
g++ app.o /path/to/ptrace-inject-cpp/build/libptrace_inject.a -ldl -o app
# C++
g++ app.cpp -I/path/to/ptrace-inject-cpp/include \
/path/to/ptrace-inject-cpp/build/libptrace_inject.a -ldl -o app
```
With the shared library, link with `-Lbuild-shared -lptrace_inject -ldl` and set
`LD_LIBRARY_PATH` when running.
As a CMake subproject:
```cmake
project(consumer LANGUAGES C CXX)
set(PTRACE_INJECT_BUILD_CLI OFF CACHE BOOL "" FORCE)
set(PTRACE_INJECT_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
add_subdirectory(/path/to/ptrace-inject-cpp ptrace_inject)
add_executable(app app.c)
target_link_libraries(app PRIVATE ptrace_inject)
```
### Using the CI artifacts
Every CI run uploads one artifact per configuration, named
`ptrace-inject-<os>-<cc>-<build-type>-<static|shared>`. Each contains `build/`
(library, CLI, examples, sample library) and `include/ptrace_inject.h`, so it can
be used with the link commands above without rebuilding.
### Verify it worked
Pick a target that permits attaching: same uid plus `CAP_SYS_PTRACE`, a target
that called `prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY)`, or a suitable
`kernel.yama.ptrace_scope`.
```bash
rm -f /tmp/ptrace_inject_sample.txt
./build/example_by_pid <PID> ./build/libptrace_inject_sample.so
cat /tmp/ptrace_inject_sample.txt # written by the injected constructor
```
The marker file appears only if the library's constructor really ran inside the
target process.
## Safety measures
- Everything is validated before the target is modified: library path, libc
build consistency, relocated function addresses, patch site and stack
writability.
- `pid <= 1` (init) and the injector itself are refused.
- Only private, file-backed, executable mappings are used as patch sites, and
pages containing a stopped thread's current `RIP` are skipped.
- Remote calls use `(rsp - 256) & ~0xf`, keeping clear of the x86-64 red zone.
- Only a `SIGTRAP` whose `RIP` matches the patch site is accepted.
- Unexpected signals are handed back to the target thread on detach.
- Failed remote calls attempt to restore the original bytes and registers.
## Requirements
- x86-64 Linux only.
- ptrace permission: same uid plus `CAP_SYS_PTRACE`, target opting in via
`prctl(PR_SET_PTRACER, ...)`, or a suitable `kernel.yama.ptrace_scope`.
- Injector and target must use the same libc build; a mismatch is detected via
`device:inode` and rejected.
## Continuous integration
CI builds six configurations (Ubuntu 24.04 and 22.04, GCC and Clang, Release and
Debug, static and shared) with `-Wall -Wextra -Wpedantic -Werror`, and uploads the
resulting binaries as artifacts.
## Known limitations
- All other threads are stopped during injection; if one holds the malloc or
dynamic-linker lock, the remote `dlopen` can hang.
- The target's code segment is temporarily modified (restored immediately).
- Signal forwarding is best effort; an interrupted libc call may be left in a
partial state.
- There is no `dlclose`; the injected library stays loaded in the target.
- The library path must be visible in the target's mount namespace.
## Acknowledgements
The original idea, the shellcode-based injection approach, and much of the design
come from [Artemis21/ptrace-inject](https://github.com/Artemis21/ptrace-inject).
This project is a C++ port that turns it into a reusable C ABI library.
---
# v1.0.0
发布于 2026-10-20。这是 **ptrace-inject-cpp** 的首个公开发布版本,它是
[Artemis21/ptrace-inject](https://github.com/Artemis21/ptrace-inject) 的 C++ 移植。
`ptrace-inject-cpp` 使用 `ptrace` 向运行中的 x86-64 Linux 进程注入共享库。核心流程是:
附加目标进程的所有线程 → 在目标进程内远程调用 `malloc` / `dlopen` / `free` →
恢复原始代码和寄存器 → 全部 detach。不做 ELF 解析,也没有 spawn 模式。
## 主要特性
- **稳定的 C ABI。** `include/ptrace_inject.h` 可直接被 C 和 C++ 使用,只提供两个函数:
`ptrace_inject_by_pid()` 和 `ptrace_inject_by_name()`。
- **静态库 / 动态库。** 默认构建 `libptrace_inject.a`;传入 `-DBUILD_SHARED_LIBS=ON`
可得到带版本号的动态库(`SOVERSION` 为 1)。
- **轻量命令行工具。** `ptrace-inject-cpp` 支持按 PID(`-p`)或按可执行文件名(`-n`)注入。
- **易于集成。** 没有 install 规则,直接使用 `include/` 和 `build/` 目录,或通过
`add_subdirectory()` 引入;同时提供 `ptrace_inject::ptrace_inject` 别名目标。
- **库默认静默。** 只有调用方传入日志回调时才输出日志,动态库只导出上述两个 API 符号。
## 内容清单
| 路径 | 说明 |
| --- | --- |
| `include/ptrace_inject.h` | 对 C 兼容的公开 API |
| `src/` | 库实现及 CLI 入口 |
| `examples/inject_by_pid.c` | 最小 C 用法示例 |
| `examples/inject_by_name.cpp` | C++ 示例,演示日志回调与 `resolved_pid` |
| `examples/sample_library.c` | 示例库,构造函数会写入标记文件 |
| `CMakeLists.txt` | 构建系统(CMake >= 3.16,C++17) |
构建选项:
- `-DCMAKE_BUILD_TYPE=Release`(未指定时的默认值)
- `-DBUILD_SHARED_LIBS=ON` 构建动态库
- `-DPTRACE_INJECT_BUILD_CLI=OFF` 不构建 CLI
- `-DPTRACE_INJECT_BUILD_EXAMPLES=OFF` 不构建示例
## 使用方法
### 从源码构建
```bash
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --parallel
```
产物:`build/libptrace_inject.a`、`build/ptrace-inject-cpp`、`build/example_by_pid`、
`build/example_by_name`、`build/libptrace_inject_sample.so`。
加上 `-DBUILD_SHARED_LIBS=ON` 则改为生成 `libptrace_inject.so*`。
### 命令行
```bash
# 按 PID 注入
./build/ptrace-inject-cpp -p <PID> /absolute/path/to/libfoo.so
# 按可执行文件名或路径注入
./build/ptrace-inject-cpp -n <process-name> /absolute/path/to/libfoo.so
# 查看帮助
./build/ptrace-inject-cpp -h
```
库路径在注入器的 mount namespace 中解析,因此目标进程必须能打开同一路径。
### 作为库使用
```c
#include <stdio.h>
#include "ptrace_inject.h"
static void on_log(int level, const char *message, void *user_data) {
(void)level;
(void)user_data;
fprintf(stderr, "%s\n", message);
}
int main(void) {
ptrace_inject_options options = {0};
options.log_fn = on_log;
char error[512] = {0};
if (ptrace_inject_by_pid(1234, "/abs/path/libfoo.so", &options, error,
sizeof(error)) != PTRACE_INJECT_OK) {
fprintf(stderr, "inject failed: %s\n", error);
return 1;
}
return 0;
}
```
`options` 和 `error` 均可传 `NULL`;`ptrace_inject_by_name()` 的 `resolved_pid`
同样可以为 `NULL`。调用是同步的,会阻塞到 `dlopen()` 执行完成(或失败)为止。
只要目标进程不同,多线程并发调用是安全的。
直接链接构建目录中的库(无需安装):
```bash
# C
gcc -c app.c -I/path/to/ptrace-inject-cpp/include -o app.o
g++ app.o /path/to/ptrace-inject-cpp/build/libptrace_inject.a -ldl -o app
# C++
g++ app.cpp -I/path/to/ptrace-inject-cpp/include \
/path/to/ptrace-inject-cpp/build/libptrace_inject.a -ldl -o app
```
使用动态库时,链接改为 `-Lbuild-shared -lptrace_inject -ldl`,运行前设置
`LD_LIBRARY_PATH`。
作为 CMake 子项目引入:
```cmake
project(consumer LANGUAGES C CXX)
set(PTRACE_INJECT_BUILD_CLI OFF CACHE BOOL "" FORCE)
set(PTRACE_INJECT_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
add_subdirectory(/path/to/ptrace-inject-cpp ptrace_inject)
add_executable(app app.c)
target_link_libraries(app PRIVATE ptrace_inject)
```
### 使用 CI 产物
每次 CI 会为每种配置上传一个 artifact,命名为
`ptrace-inject-<os>-<cc>-<build-type>-<static|shared>`。其中包含 `build/`
(库、CLI、示例、示例库)和 `include/ptrace_inject.h`,可直接配合上面的链接命令使用,
无需重新构建。
### 验证注入是否成功
请先准备一个允许被 attach 的目标:同 uid 且具备 `CAP_SYS_PTRACE`,或目标调用了
`prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY)`,或调整过 `kernel.yama.ptrace_scope`。
```bash
rm -f /tmp/ptrace_inject_sample.txt
./build/example_by_pid <PID> ./build/libptrace_inject_sample.so
cat /tmp/ptrace_inject_sample.txt # 由被注入的构造函数写入
```
只有示例库的构造函数确实在目标进程内运行,标记文件才会出现。
## 安全措施
- 修改目标之前完成全部校验:库路径、两端 libc 构建一致性、重定位后的函数地址、
patch 位置以及栈的可写性。
- 拒绝 `pid <= 1`(init)以及注入器自身。
- 只在私有、文件映射、可执行的映射中选择 patch 位置,并跳过包含已停止线程当前
`RIP` 的页面。
- 远程调用使用 `(rsp - 256) & ~0xf`,避开 x86-64 红区。
- 只接受 `RIP` 与 patch 位置匹配的 `SIGTRAP`。
- 遇到意外信号时,在 detach 时把信号交还给对应线程。
- 远程调用失败时尽力回写原始字节和寄存器。
## 运行要求
- 仅支持 x86-64 Linux。
- 需要 ptrace 权限:同 uid 且具备 `CAP_SYS_PTRACE`,或目标通过
`prctl(PR_SET_PTRACER, ...)` 主动放行,或调整 `kernel.yama.ptrace_scope`。
- 注入器与目标必须使用同一份 libc 构建;不一致会通过 `device:inode` 检出并拒绝执行。
## 持续集成
CI 覆盖六种配置(Ubuntu 24.04 / 22.04、GCC / Clang、Release / Debug、静态 / 动态),
使用 `-Wall -Wextra -Wpedantic -Werror` 编译,并将构建产物作为 artifact 上传。
## 已知限制
- 注入期间目标的其他线程全部暂停;若其中某个线程持有 malloc 或动态链接器锁,
远程 `dlopen` 可能死锁。
- 目标的代码段会被临时修改(patch 位置随后立即恢复)。
- 信号转发是尽力而为;被中断的 libc 调用可能留下部分状态。
- 不提供 `dlclose`,注入的库会一直保留在目标进程中。
- 库路径必须在目标的 mount namespace 中可见。
## 致谢
原始思路、基于 shellcode 的注入方式以及大部分设计来自
[Artemis21/ptrace-inject](https://github.com/Artemis21/ptrace-inject)。
本项目是其 C++ 移植,并封装为可复用的 C ABI 库。