mirror of
https://github.com/xiaozhou233/ptrace-inject-cpp.git
synced 2026-12-05 13:05:54 +08:00
Port ptrace library injection to C++ as a reusable library
Add a C ABI library (libptrace_inject), a thin CLI (ptrace-inject), and C/C++ examples that inject a .so into a running x86-64 Linux process. Injection flow: - stop every thread with PTRACE_ATTACH, re-scanning /proc/<pid>/task for threads created while attaching - patch a 6-byte shellcode (nop; nop; call r9; int3) into a private, file-backed executable mapping, then call target malloc/dlopen/free via PTRACE_SETREGS + PTRACE_CONT and read the result from rax - write the library path with /proc/<pid>/mem, free it, restore the original bytes and registers, then PTRACE_DETACH all threads Safety: - validate before modifying anything: library path, libc/libdl build identity via device:inode, relocated symbol addresses are executable, patch site avoids stopped threads' RIPs, stack pointer is writable - only accept the SIGTRAP whose RIP is shellcode+6 - forward unexpected signals back to the target on detach - best-effort rollback of code and registers on failure - shared library exports only the two public entry points API: ptrace_inject_by_pid() and ptrace_inject_by_name(), with an optional log callback and an error buffer; silent by default. Build with CMake (no install rules); docs in README.md (EN) and README.ZH.md (ZH).
This commit is contained in:
commit
b78aa07f78
27 files changed
+2141
No files matched your search
@@ -0,0 +1,8 @@
|
||||
build/
|
||||
build-*/
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
ptrace-inject
|
||||
example_by_pid
|
||||
example_by_name
|
||||
@@ -0,0 +1,72 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(ptrace_inject VERSION 1.0.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
|
||||
set(CMAKE_BUILD_TYPE Release)
|
||||
endif()
|
||||
|
||||
option(PTRACE_INJECT_BUILD_CLI "Build the command line tool" ON)
|
||||
option(PTRACE_INJECT_BUILD_EXAMPLES "Build the examples" ON)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Library
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
add_library(ptrace_inject
|
||||
src/library.cpp
|
||||
src/log.cpp
|
||||
src/util.cpp
|
||||
src/maps.cpp
|
||||
src/memory.cpp
|
||||
src/ptrace_utils.cpp
|
||||
src/symbols.cpp
|
||||
src/inject.cpp
|
||||
src/process_lookup.cpp
|
||||
)
|
||||
|
||||
add_library(ptrace_inject::ptrace_inject ALIAS ptrace_inject)
|
||||
|
||||
target_include_directories(ptrace_inject
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src
|
||||
)
|
||||
|
||||
target_compile_options(ptrace_inject PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_link_libraries(ptrace_inject PRIVATE dl)
|
||||
|
||||
set_target_properties(ptrace_inject PROPERTIES
|
||||
OUTPUT_NAME ptrace_inject
|
||||
VERSION ${PROJECT_VERSION}
|
||||
SOVERSION ${PROJECT_VERSION_MAJOR}
|
||||
CXX_VISIBILITY_PRESET hidden
|
||||
VISIBILITY_INLINES_HIDDEN ON
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI and examples
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
if(PTRACE_INJECT_BUILD_CLI)
|
||||
add_executable(ptrace_inject_cli src/main.cpp)
|
||||
set_target_properties(ptrace_inject_cli PROPERTIES OUTPUT_NAME ptrace-inject)
|
||||
target_link_libraries(ptrace_inject_cli PRIVATE ptrace_inject)
|
||||
endif()
|
||||
|
||||
if(PTRACE_INJECT_BUILD_EXAMPLES)
|
||||
add_executable(example_by_pid examples/inject_by_pid.c)
|
||||
set_target_properties(example_by_pid PROPERTIES LINKER_LANGUAGE CXX)
|
||||
target_link_libraries(example_by_pid PRIVATE ptrace_inject)
|
||||
|
||||
add_executable(example_by_name examples/inject_by_name.cpp)
|
||||
target_link_libraries(example_by_name PRIVATE ptrace_inject)
|
||||
|
||||
add_library(sample_library SHARED examples/sample_library.c)
|
||||
set_target_properties(sample_library PROPERTIES
|
||||
OUTPUT_NAME ptrace_inject_sample
|
||||
)
|
||||
endif()
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
# ptrace_inject
|
||||
|
||||
> English version: [README.md](README.md)
|
||||
|
||||
用 `ptrace` 把 `.so` 注入正在运行的 x86-64 Linux 进程。
|
||||
|
||||
提供两样东西:
|
||||
|
||||
- **一个 C ABI 库** `libptrace_inject`(实现是 C++,头文件可直接给 C/C++ 用);
|
||||
- **一个薄命令行工具** `ptrace-inject`,以及几个示例程序。
|
||||
|
||||
核心流程:attach 目标线程 → 在目标里远程调用
|
||||
`malloc` / `dlopen` / `free` → 恢复现场 → detach。没有 spawn 模式,也没有
|
||||
ELF 解析。
|
||||
|
||||
## 文件
|
||||
|
||||
```
|
||||
include/ptrace_inject.h # 公开 C API
|
||||
src/
|
||||
├── library.cpp # C ABI 实现、attach/inject/detach 编排
|
||||
├── log.cpp/.h # 内部日志回调
|
||||
├── inject.cpp/.h # 选补丁点、选栈、远程调用、注入流程
|
||||
├── ptrace_utils.cpp/.h # attach/detach、寄存器、wait_for_trap
|
||||
├── symbols.cpp/.h # malloc/dlopen/free 地址定位与换算
|
||||
├── maps.cpp/.h # /proc/<pid>/maps 解析、地址检查
|
||||
├── memory.cpp/.h # /proc/<pid>/mem 读写
|
||||
├── process_lookup.cpp/.h # 按名字找 PID
|
||||
├── util.cpp/.h # 错误、字符串工具
|
||||
├── config.h # shellcode、栈余量等常量
|
||||
└── main.cpp # CLI
|
||||
examples/
|
||||
├── inject_by_pid.c # C 调用示例
|
||||
├── inject_by_name.cpp # C++ 调用示例
|
||||
└── sample_library.c # 被注入的示例 .so
|
||||
CMakeLists.txt
|
||||
```
|
||||
|
||||
## 构建
|
||||
|
||||
```bash
|
||||
cd /home/xiaozhou/Development/inject
|
||||
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build -j
|
||||
```
|
||||
|
||||
默认生成静态库。要生成共享库:
|
||||
|
||||
```bash
|
||||
cmake -S . -B build-shared -DBUILD_SHARED_LIBS=ON -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build-shared -j
|
||||
```
|
||||
|
||||
可选开关:
|
||||
|
||||
```bash
|
||||
-DPTRACE_INJECT_BUILD_CLI=OFF # 不构建 ptrace-inject
|
||||
-DPTRACE_INJECT_BUILD_EXAMPLES=OFF # 不构建示例
|
||||
```
|
||||
|
||||
构建产物:
|
||||
|
||||
```
|
||||
build/libptrace_inject.a # 静态库(默认)
|
||||
build-shared/libptrace_inject.so # 共享库(BUILD_SHARED_LIBS=ON 时的目录)
|
||||
build/ptrace-inject # CLI
|
||||
build/example_by_pid # C 示例
|
||||
build/example_by_name # C++ 示例
|
||||
build/libptrace_inject_sample.so
|
||||
```
|
||||
|
||||
## 作为库使用
|
||||
|
||||
公开头文件是 C 兼容的,核心接口只有两个:
|
||||
|
||||
```c
|
||||
int ptrace_inject_by_pid(pid_t pid,
|
||||
const char *library_path,
|
||||
const ptrace_inject_options *options,
|
||||
char *error,
|
||||
size_t error_size);
|
||||
|
||||
int ptrace_inject_by_name(const char *process_name,
|
||||
const char *library_path,
|
||||
const ptrace_inject_options *options,
|
||||
pid_t *resolved_pid,
|
||||
char *error,
|
||||
size_t error_size);
|
||||
```
|
||||
|
||||
- 返回 `PTRACE_INJECT_OK`(0)或 `PTRACE_INJECT_ERROR`(-1)。
|
||||
- `options` 可以为 `NULL`(静默);`options.log_fn` 可接收调试/进度日志。
|
||||
- `error` 可以为 `NULL`;非空时失败会写入 NUL 结尾的错误信息。
|
||||
- `ptrace_inject_by_name` 的 `resolved_pid` 可以为 `NULL`。
|
||||
|
||||
最小调用示例:
|
||||
|
||||
```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;
|
||||
}
|
||||
```
|
||||
|
||||
### 链接构建产物
|
||||
|
||||
不做安装,直接指向本仓库的 `include/` 和 `build/` 即可。
|
||||
|
||||
C++ 程序:
|
||||
|
||||
```bash
|
||||
g++ app.cpp -I/path/to/inject/include \
|
||||
/path/to/inject/build/libptrace_inject.a -ldl -o app
|
||||
```
|
||||
|
||||
C 程序(静态库内部是 C++,用 g++ 链接最省事):
|
||||
|
||||
```bash
|
||||
gcc -c app.c -I/path/to/inject/include -o app.o
|
||||
g++ app.o /path/to/inject/build/libptrace_inject.a -ldl -o app
|
||||
```
|
||||
|
||||
共享库:
|
||||
|
||||
```bash
|
||||
gcc app.c -I/path/to/inject/include \
|
||||
-L/path/to/inject/build-shared -lptrace_inject -ldl -lstdc++ -o app
|
||||
LD_LIBRARY_PATH=/path/to/inject/build-shared ./app
|
||||
```
|
||||
|
||||
如果自己的项目也用 CMake,可以直接 `add_subdirectory`,不需要安装:
|
||||
|
||||
```cmake
|
||||
# 你的 project() 里要启用 CXX(库本身是 C++;这点在 add_subdirectory 时很关键)
|
||||
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/inject ptrace_inject)
|
||||
|
||||
add_executable(app app.c)
|
||||
target_link_libraries(app PRIVATE ptrace_inject)
|
||||
```
|
||||
|
||||
## 命令行工具
|
||||
|
||||
```bash
|
||||
# 按 PID
|
||||
./build/ptrace-inject -p <PID> /absolute/or/relative/path/to/library.so
|
||||
|
||||
# 按可执行文件名
|
||||
./build/ptrace-inject -n target-process ./library.so
|
||||
```
|
||||
|
||||
示例输出:
|
||||
|
||||
```
|
||||
[*] attached to 4 thread(s) of pid 12345
|
||||
[debug] remote malloc: 0x..., dlopen: 0x..., free: 0x...
|
||||
[debug] patched shellcode at 0x55...
|
||||
[debug] remote malloc(38) = 0x55...
|
||||
[debug] remote dlopen("./libhello.so") = 0x55...
|
||||
[debug] remote free() done
|
||||
[*] restored original code and registers
|
||||
[*] injected ./libhello.so into pid 12345
|
||||
```
|
||||
|
||||
## 示例程序
|
||||
|
||||
仓库里带了三个示例:
|
||||
|
||||
```bash
|
||||
# 1. 示例被注入库:constructor 会打印并写 /tmp/ptrace_inject_sample.txt
|
||||
./build/libptrace_inject_sample.so
|
||||
|
||||
# 2. 按 PID 注入(C 示例)
|
||||
./build/example_by_pid <PID> ./build/libptrace_inject_sample.so
|
||||
|
||||
# 3. 按进程名注入(C++ 示例)
|
||||
./build/example_by_name <process-name> ./build/libptrace_inject_sample.so
|
||||
```
|
||||
|
||||
`examples/inject_by_pid.c` 展示了最小 C 调用;`examples/inject_by_name.cpp`
|
||||
展示了 C++ 调用、日志回调以及 `resolved_pid` 的用法。
|
||||
|
||||
## 原理
|
||||
|
||||
### 1. 停住所有线程
|
||||
|
||||
`attach_all_threads()` 枚举 `/proc/<pid>/task`,对每个线程 `PTRACE_ATTACH` +
|
||||
`waitpid`。目标可能在我们 attach 期间新建线程,所以之后会重新枚举,把新线程
|
||||
也停住(最多 `kMaxAttachRounds` 轮)。
|
||||
|
||||
### 2. 找位置并写入 shellcode
|
||||
|
||||
在真正改写前先做完整校验(见「安全措施」),然后从 `/proc/<pid>/maps` 选一个
|
||||
private、file-backed、可执行的映射,按页对齐挑一个没有已停线程 RIP 落在其中的
|
||||
地址,保存原始 6 字节后通过 `/proc/<pid>/mem` 的 `pwrite` 写入:
|
||||
|
||||
```asm
|
||||
90 nop
|
||||
90 nop
|
||||
41 ff d1 call r9
|
||||
cc int3
|
||||
```
|
||||
|
||||
### 3. 计算目标进程里的函数地址
|
||||
|
||||
用 `dlsym(RTLD_DEFAULT, ...)` 拿到注入器进程里 `malloc`、`dlopen`、`free`
|
||||
的地址,再用 `dladdr` 确认每个符号属于哪个共享对象(新 glibc 里 `dlopen`
|
||||
在 `libc.so.6`,老 glibc 里可能在 `libdl.so.2`),然后按两边该对象的基址换算:
|
||||
|
||||
```text
|
||||
目标地址 = 本进程符号地址 - 该对象在本进程的基址 + 该对象在目标进程的基址
|
||||
```
|
||||
|
||||
换算后会校验:两边该对象的 `device:inode` 必须相同,且目标地址必须落在可执行
|
||||
映射内;否则直接拒绝。
|
||||
|
||||
### 4. 远程调用
|
||||
|
||||
`call_in_tracee()`:
|
||||
|
||||
```text
|
||||
PTRACE_GETREGS 保存原始寄存器(只做一次)
|
||||
设置 rip = shellcode + 2
|
||||
r9 = 目标函数
|
||||
rdi = 参数 1
|
||||
rsi = 参数 2
|
||||
rsp = (原始 rsp - 256) 按 16 字节对齐
|
||||
PTRACE_SETREGS
|
||||
PTRACE_CONT
|
||||
waitpid 等到 SIGTRAP,且 RIP 必须正好是 shellcode+6
|
||||
PTRACE_GETREGS 读 rax 作为返回值
|
||||
```
|
||||
|
||||
`rip = shellcode + 2` 跳过两个 `nop`。如果内核恢复线程时把 RIP 回退 2 字节,
|
||||
就会落到 `nop` 上,nop slide 仍然能走到 `call r9`。
|
||||
|
||||
### 5. 加载 `.so`
|
||||
|
||||
1. `canonicalize` 路径并补 `\0`;
|
||||
2. 远程 `malloc(path_len)`;
|
||||
3. 把路径写进目标进程那块内存;
|
||||
4. 远程 `dlopen(path_addr, RTLD_LAZY)`;
|
||||
5. 远程 `free(path_addr)`。
|
||||
|
||||
### 6. 恢复
|
||||
|
||||
把原始 6 字节写回,恢复完整寄存器,`PTRACE_DETACH` 所有线程。
|
||||
|
||||
## 安全措施
|
||||
|
||||
- **先校验,后改写**:库路径、libc 构建一致性、远程函数地址、补丁点、栈可写性
|
||||
全部在写入 shellcode 之前完成。失败时目标完全没有被修改。
|
||||
- **拒绝危险目标**:`pid <= 1`(init)以及注入器自身直接拒绝。
|
||||
- **补丁点避开执行流**:只选 private + file-backed + 可执行映射,并跳过任何
|
||||
已停线程当前 RIP 所在的那一页。
|
||||
- **栈不踩红区**:远程调用使用 `(rsp - 256) & ~0xf`,并确认落在可写映射中。
|
||||
- **只认自己的 SIGTRAP**:等待 `int3` 时同时校验 `RIP == shellcode + 6`。
|
||||
- **不吞信号**:shellcode 执行期间收到意外信号时,恢复代码/寄存器后通过
|
||||
`PTRACE_DETACH` 把信号回传给对应线程。
|
||||
- **出错也尽量恢复**:任何远程调用失败都会尝试写回原始字节和寄存器。
|
||||
- **库默认静默**:只有调用方传了 `log_fn` 才会输出日志;共享库只导出
|
||||
`ptrace_inject_by_pid` / `ptrace_inject_by_name` 两个符号。
|
||||
|
||||
## 测试
|
||||
|
||||
本机 `kernel.yama.ptrace_scope=1` 时,非父子进程 attach 会被拒绝。测试用的
|
||||
victim 可以自己调用:
|
||||
|
||||
```c
|
||||
prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
|
||||
```
|
||||
|
||||
然后:
|
||||
|
||||
```bash
|
||||
./victim &
|
||||
./build/example_by_pid $! ./build/libptrace_inject_sample.so
|
||||
cat /tmp/ptrace_inject_sample.txt
|
||||
```
|
||||
|
||||
如果 lib 的 constructor 往文件里写内容,就能确认它确实在目标进程里执行了。
|
||||
|
||||
## 局限
|
||||
|
||||
- **只支持 x86-64 Linux**。
|
||||
- **需要 ptrace 权限**:同 uid + `CAP_SYS_PTRACE`,或调整
|
||||
`/proc/sys/kernel/yama/ptrace_scope`,或目标自己调用 `PR_SET_PTRACER`。
|
||||
- **两边 libc 必须一致**:会用 `device:inode` 检测并拒绝不一致的
|
||||
`libc.so.6`/`libdl.so.2`,但仍要求两边是同一份构建。
|
||||
- **可能死锁**:注入时其他线程全部停住。如果某个线程正好持有
|
||||
`malloc`/动态链接器的锁,目标里的 `dlopen` 会卡住。
|
||||
- **仍然是临时改写代码**:补丁点避开了当前 RIP 并会立即恢复,但本质上还是
|
||||
改动目标代码段。
|
||||
- **信号转发是尽力而为**:意外信号会在 detach 时回传,但此时正在执行的
|
||||
libc 调用已被放弃,可能有半完成的状态。
|
||||
- **不 `dlclose`**:加载后的库会一直留在目标进程里,符合「注入」的预期。
|
||||
- **路径可见性**:`canonicalize` 发生在注入器进程,目标进程必须能访问同一路径
|
||||
(同一 mount namespace)。
|
||||
@@ -0,0 +1,355 @@
|
||||
# ptrace_inject
|
||||
|
||||
Inject a shared library (`.so`) into a running x86-64 Linux process with
|
||||
`ptrace`.
|
||||
|
||||
> Chinese version: [README.ZH.md](README.ZH.md)
|
||||
|
||||
This repository provides:
|
||||
|
||||
- **A C ABI library** `libptrace_inject` (implemented in C++, but the public
|
||||
header is directly usable from C and C++);
|
||||
- **A thin command line tool** `ptrace-inject`, plus a few example programs.
|
||||
|
||||
The core flow is: attach to the target threads → remotely call
|
||||
`malloc` / `dlopen` / `free` inside the target → restore the original state →
|
||||
detach. There is no spawn mode and no ELF parsing.
|
||||
|
||||
## Files
|
||||
|
||||
```
|
||||
include/ptrace_inject.h # public C API
|
||||
src/
|
||||
├── library.cpp # C ABI implementation, attach/inject/detach flow
|
||||
├── log.cpp/.h # internal logging callback
|
||||
├── inject.cpp/.h # patch-site/stack selection, remote calls
|
||||
├── ptrace_utils.cpp/.h # attach/detach, registers, wait_for_trap
|
||||
├── symbols.cpp/.h # locate and relocate malloc/dlopen/free
|
||||
├── maps.cpp/.h # /proc/<pid>/maps parsing, address checks
|
||||
├── memory.cpp/.h # /proc/<pid>/mem read/write
|
||||
├── process_lookup.cpp/.h # find a PID by executable name
|
||||
├── util.cpp/.h # error and string helpers
|
||||
├── config.h # shellcode, stack margin, etc.
|
||||
└── main.cpp # CLI
|
||||
examples/
|
||||
├── inject_by_pid.c # C usage example
|
||||
├── inject_by_name.cpp # C++ usage example
|
||||
└── sample_library.c # sample library to inject
|
||||
CMakeLists.txt
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
```bash
|
||||
cd /home/xiaozhou/Development/inject
|
||||
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build -j
|
||||
```
|
||||
|
||||
This builds a static library by default. To build a shared library instead:
|
||||
|
||||
```bash
|
||||
cmake -S . -B build-shared -DBUILD_SHARED_LIBS=ON -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build-shared -j
|
||||
```
|
||||
|
||||
Optional switches:
|
||||
|
||||
```bash
|
||||
-DPTRACE_INJECT_BUILD_CLI=OFF # do not build ptrace-inject
|
||||
-DPTRACE_INJECT_BUILD_EXAMPLES=OFF # do not build the examples
|
||||
```
|
||||
|
||||
Build artifacts:
|
||||
|
||||
```
|
||||
build/libptrace_inject.a # static library (default)
|
||||
build-shared/libptrace_inject.so # shared library (with BUILD_SHARED_LIBS=ON)
|
||||
build/ptrace-inject # CLI
|
||||
build/example_by_pid # C example
|
||||
build/example_by_name # C++ example
|
||||
build/libptrace_inject_sample.so
|
||||
```
|
||||
|
||||
There are intentionally **no install rules**; point your build at `include/`
|
||||
and `build/` directly (see below).
|
||||
|
||||
## Using it as a library
|
||||
|
||||
The public header is C-compatible. The core API is just two functions:
|
||||
|
||||
```c
|
||||
int ptrace_inject_by_pid(pid_t pid,
|
||||
const char *library_path,
|
||||
const ptrace_inject_options *options,
|
||||
char *error,
|
||||
size_t error_size);
|
||||
|
||||
int ptrace_inject_by_name(const char *process_name,
|
||||
const char *library_path,
|
||||
const ptrace_inject_options *options,
|
||||
pid_t *resolved_pid,
|
||||
char *error,
|
||||
size_t error_size);
|
||||
```
|
||||
|
||||
- Returns `PTRACE_INJECT_OK` (0) or `PTRACE_INJECT_ERROR` (-1).
|
||||
- `options` may be `NULL` (silent); `options.log_fn` receives debug/progress
|
||||
messages.
|
||||
- `error` may be `NULL`; when non-NULL, it receives a NUL-terminated error
|
||||
message on failure.
|
||||
- `resolved_pid` in `ptrace_inject_by_name` may be `NULL`.
|
||||
|
||||
Minimal example:
|
||||
|
||||
```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;
|
||||
}
|
||||
```
|
||||
|
||||
### Linking against the build tree
|
||||
|
||||
No installation is required; point the compiler at this repository's
|
||||
`include/` and `build/` directories.
|
||||
|
||||
C++ program:
|
||||
|
||||
```bash
|
||||
g++ app.cpp -I/path/to/inject/include \
|
||||
/path/to/inject/build/libptrace_inject.a -ldl -o app
|
||||
```
|
||||
|
||||
C program (the static library is C++ internally, so linking with `g++` is the
|
||||
easiest path):
|
||||
|
||||
```bash
|
||||
gcc -c app.c -I/path/to/inject/include -o app.o
|
||||
g++ app.o /path/to/inject/build/libptrace_inject.a -ldl -o app
|
||||
```
|
||||
|
||||
Shared library:
|
||||
|
||||
```bash
|
||||
gcc app.c -I/path/to/inject/include \
|
||||
-L/path/to/inject/build-shared -lptrace_inject -ldl -lstdc++ -o app
|
||||
LD_LIBRARY_PATH=/path/to/inject/build-shared ./app
|
||||
```
|
||||
|
||||
If your project also uses CMake, you can use `add_subdirectory`; no install
|
||||
step is needed:
|
||||
|
||||
```cmake
|
||||
# Your project() must enable CXX (the library is C++; this matters with
|
||||
# add_subdirectory).
|
||||
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/inject ptrace_inject)
|
||||
|
||||
add_executable(app app.c)
|
||||
target_link_libraries(app PRIVATE ptrace_inject)
|
||||
```
|
||||
|
||||
## Command line tool
|
||||
|
||||
```bash
|
||||
# By PID
|
||||
./build/ptrace-inject -p <PID> /absolute/or/relative/path/to/library.so
|
||||
|
||||
# By executable name
|
||||
./build/ptrace-inject -n target-process ./library.so
|
||||
```
|
||||
|
||||
Example output:
|
||||
|
||||
```
|
||||
[*] attached to 4 thread(s) of pid 12345
|
||||
[debug] remote malloc: 0x..., dlopen: 0x..., free: 0x...
|
||||
[debug] patched shellcode at 0x55...
|
||||
[debug] remote malloc(38) = 0x55...
|
||||
[debug] remote dlopen("./libhello.so") = 0x55...
|
||||
[debug] remote free() done
|
||||
[*] restored original code and registers
|
||||
[*] injected ./libhello.so into pid 12345
|
||||
```
|
||||
|
||||
## Example programs
|
||||
|
||||
The repository ships three examples:
|
||||
|
||||
```bash
|
||||
# 1. Sample library to inject: its constructor prints and writes
|
||||
# /tmp/ptrace_inject_sample.txt.
|
||||
./build/libptrace_inject_sample.so
|
||||
|
||||
# 2. Inject by PID (C example)
|
||||
./build/example_by_pid <PID> ./build/libptrace_inject_sample.so
|
||||
|
||||
# 3. Inject by process name (C++ example)
|
||||
./build/example_by_name <process-name> ./build/libptrace_inject_sample.so
|
||||
```
|
||||
|
||||
`examples/inject_by_pid.c` shows the minimal C call;
|
||||
`examples/inject_by_name.cpp` shows the C++ call, the log callback, and the
|
||||
`resolved_pid` output parameter.
|
||||
|
||||
## How it works
|
||||
|
||||
### 1. Stop every thread
|
||||
|
||||
`attach_all_threads()` walks `/proc/<pid>/task` and calls `PTRACE_ATTACH` +
|
||||
`waitpid` for each thread. The target may create new threads while we are
|
||||
attaching, so it re-scans and stops those too (up to `kMaxAttachRounds`
|
||||
rounds).
|
||||
|
||||
### 2. Choose a place and write the shellcode
|
||||
|
||||
Everything is validated first (see "Safety measures"). Then it picks a
|
||||
private, file-backed, executable mapping from `/proc/<pid>/maps`, chooses a
|
||||
page-aligned address in it that no stopped thread is currently executing at,
|
||||
saves the original 6 bytes, and writes the shellcode via `pwrite` on
|
||||
`/proc/<pid>/mem`:
|
||||
|
||||
```asm
|
||||
90 nop
|
||||
90 nop
|
||||
41 ff d1 call r9
|
||||
cc int3
|
||||
```
|
||||
|
||||
### 3. Compute the address of the functions in the target
|
||||
|
||||
`dlsym(RTLD_DEFAULT, ...)` gives the local addresses of `malloc`, `dlopen`,
|
||||
and `free`. `dladdr` tells us which shared object owns each symbol (on new
|
||||
glibc `dlopen` is in `libc.so.6`; on old glibc it may be in `libdl.so.2`).
|
||||
The target address is computed from the object's base in both processes:
|
||||
|
||||
```text
|
||||
target address = local symbol address
|
||||
- local object base
|
||||
+ target object base
|
||||
```
|
||||
|
||||
After relocation it verifies that both sides use the same `device:inode` for
|
||||
that object and that the resulting address is executable in the target.
|
||||
Otherwise it refuses to continue.
|
||||
|
||||
### 4. Remote calls
|
||||
|
||||
`call_in_tracee()` does this:
|
||||
|
||||
```text
|
||||
PTRACE_GETREGS save the original registers (once)
|
||||
set rip = shellcode + 2
|
||||
r9 = target function
|
||||
rdi = argument 1
|
||||
rsi = argument 2
|
||||
rsp = (original rsp - 256), 16-byte aligned
|
||||
PTRACE_SETREGS
|
||||
PTRACE_CONT
|
||||
waitpid until SIGTRAP, and RIP must be exactly shellcode + 6
|
||||
PTRACE_GETREGS, read rax as the return value
|
||||
```
|
||||
|
||||
`rip = shellcode + 2` skips the two `nop`s. If the kernel rewinds RIP by 2
|
||||
when resuming the thread, execution starts at the `nop`s instead, and the nop
|
||||
slide still reaches `call r9`.
|
||||
|
||||
### 5. Load the `.so`
|
||||
|
||||
1. Canonicalize the path and append `\0`;
|
||||
2. remotely call `malloc(path_len)`;
|
||||
3. write the path into that target memory;
|
||||
4. remotely call `dlopen(path_addr, RTLD_LAZY)`;
|
||||
5. remotely call `free(path_addr)`.
|
||||
|
||||
### 6. Restore
|
||||
|
||||
Write the original 6 bytes back, restore all registers, and `PTRACE_DETACH`
|
||||
every thread.
|
||||
|
||||
## Safety measures
|
||||
|
||||
- **Validate before modifying**: library path, libc build consistency, remote
|
||||
function addresses, patch site, and stack writability are all checked before
|
||||
the shellcode is written. On failure the target has not been modified at all.
|
||||
- **Refuse dangerous targets**: `pid <= 1` (init) and the injector itself are
|
||||
rejected.
|
||||
- **Keep the patch site away from executing code**: only private,
|
||||
file-backed, executable mappings are considered, and any page containing a
|
||||
stopped thread's current RIP is skipped.
|
||||
- **Do not clobber the red zone**: remote calls use `(rsp - 256) & ~0xf` and
|
||||
verify that the address is in a writable mapping.
|
||||
- **Only accept our own SIGTRAP**: when waiting for `int3`, it also checks
|
||||
`RIP == shellcode + 6`.
|
||||
- **Do not swallow signals**: if an unexpected signal arrives while the
|
||||
shellcode runs, the code/registers are restored and the signal is delivered
|
||||
back to the corresponding thread via `PTRACE_DETACH`.
|
||||
- **Best-effort recovery**: any failed remote call attempts to write the
|
||||
original bytes and registers back.
|
||||
- **The library is silent by default**: logs are emitted only when the caller
|
||||
provides `log_fn`; the shared library exports only
|
||||
`ptrace_inject_by_pid` and `ptrace_inject_by_name`.
|
||||
|
||||
## Testing
|
||||
|
||||
With `kernel.yama.ptrace_scope=1`, attaching to a non-child process is
|
||||
rejected. A test victim can opt in with:
|
||||
|
||||
```c
|
||||
prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
```bash
|
||||
./victim &
|
||||
./build/example_by_pid $! ./build/libptrace_inject_sample.so
|
||||
cat /tmp/ptrace_inject_sample.txt
|
||||
```
|
||||
|
||||
If the library's constructor writes to the file, the library really ran inside
|
||||
the target process.
|
||||
|
||||
## Limitations
|
||||
|
||||
- **x86-64 Linux only.**
|
||||
- **Requires ptrace permission**: same uid plus `CAP_SYS_PTRACE`, or adjust
|
||||
`/proc/sys/kernel/yama/ptrace_scope`, or have the target call
|
||||
`PR_SET_PTRACER`.
|
||||
- **Both sides must use the same libc**: inconsistent `libc.so.6` /
|
||||
`libdl.so.2` builds are detected and rejected via `device:inode`, but the
|
||||
two processes still need the same build.
|
||||
- **Possible deadlock**: all other threads are stopped during injection. If
|
||||
one of them holds the `malloc` or dynamic-linker lock, the remote `dlopen`
|
||||
can hang.
|
||||
- **It still temporarily modifies code**: the patch site avoids current RIPs
|
||||
and is restored immediately, but the target's code segment is modified.
|
||||
- **Signal forwarding is best-effort**: an unexpected signal is delivered on
|
||||
detach, but the interrupted libc call has already been abandoned and may
|
||||
have left partial state.
|
||||
- **No `dlclose`**: the loaded library stays in the target process, which is
|
||||
the expected behaviour for injection.
|
||||
- **Path visibility**: `canonicalize` runs in the injector process, so the
|
||||
target must be able to access the same path (same mount namespace).
|
||||
@@ -0,0 +1,47 @@
|
||||
// C++ example: inject a shared library into a process found by name and print
|
||||
// the resolved PID.
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#include "ptrace_inject.h"
|
||||
|
||||
static void on_log(int level, const char* message, void*) {
|
||||
const char* prefix = "[*]";
|
||||
switch (level) {
|
||||
case PTRACE_INJECT_LOG_DEBUG:
|
||||
prefix = "[debug]";
|
||||
break;
|
||||
case PTRACE_INJECT_LOG_WARN:
|
||||
prefix = "[!]";
|
||||
break;
|
||||
case PTRACE_INJECT_LOG_ERROR:
|
||||
prefix = "[error]";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
std::fprintf(stderr, "%s %s\n", prefix, message);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 3) {
|
||||
std::fprintf(stderr, "usage: %s <process-name> <library.so>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
ptrace_inject_options options{};
|
||||
options.log_fn = on_log;
|
||||
|
||||
pid_t resolved_pid = -1;
|
||||
char error[512] = {};
|
||||
|
||||
const int result = ptrace_inject_by_name(
|
||||
argv[1], argv[2], &options, &resolved_pid, error, sizeof(error));
|
||||
if (result != PTRACE_INJECT_OK) {
|
||||
std::fprintf(stderr, "inject failed: %s\n", error);
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::printf("injected into pid %d\n", static_cast<int>(resolved_pid));
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Minimal C example: inject a shared library into a PID.
|
||||
*
|
||||
* Build against the installed library:
|
||||
* cc inject_by_pid.c -lptrace_inject -o inject_by_pid
|
||||
*
|
||||
* Or against the build tree:
|
||||
* cc inject_by_pid.c -I../include ../build/libptrace_inject.a -ldl -lstdc++
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ptrace_inject.h"
|
||||
|
||||
static void on_log(int level, const char* message, void* user_data) {
|
||||
(void)user_data;
|
||||
const char* prefix = level >= PTRACE_INJECT_LOG_WARN ? "[!]" : "[*]";
|
||||
fprintf(stderr, "%s %s\n", prefix, message);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 3) {
|
||||
fprintf(stderr, "usage: %s <pid> <library.so>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
ptrace_inject_options options;
|
||||
memset(&options, 0, sizeof(options));
|
||||
options.log_fn = on_log;
|
||||
|
||||
const long pid = strtol(argv[1], NULL, 10);
|
||||
char error[512] = {0};
|
||||
|
||||
const int result =
|
||||
ptrace_inject_by_pid((pid_t)pid, argv[2], &options, error, sizeof(error));
|
||||
if (result != PTRACE_INJECT_OK) {
|
||||
fprintf(stderr, "inject failed: %s\n",
|
||||
error[0] != '\0' ? error : "(no error message)");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* A sample shared library to inject. Its constructor runs inside the target
|
||||
* process as soon as dlopen() loads it.
|
||||
*
|
||||
* Build (done automatically by the CMake examples target):
|
||||
* cc -shared -fPIC -o ptrace_inject_sample.so examples/sample_library.c
|
||||
*/
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define SAMPLE_OUTPUT_FILE "/tmp/ptrace_inject_sample.txt"
|
||||
|
||||
__attribute__((constructor)) static void on_load(void) {
|
||||
const char* message = "sample_library: constructor ran\n";
|
||||
|
||||
(void)!write(STDOUT_FILENO, message, strlen(message));
|
||||
|
||||
const int fd =
|
||||
open(SAMPLE_OUTPUT_FILE, O_WRONLY | O_CREAT | O_TRUNC, 0644);
|
||||
if (fd >= 0) {
|
||||
(void)!write(fd, message, strlen(message));
|
||||
close(fd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#ifndef PTRACE_INJECT_H
|
||||
#define PTRACE_INJECT_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define PTRACE_INJECT_VERSION_MAJOR 1
|
||||
#define PTRACE_INJECT_VERSION_MINOR 0
|
||||
#define PTRACE_INJECT_VERSION_PATCH 0
|
||||
#define PTRACE_INJECT_VERSION_STRING "1.0.0"
|
||||
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
#define PTRACE_INJECT_API __attribute__((visibility("default")))
|
||||
#else
|
||||
#define PTRACE_INJECT_API
|
||||
#endif
|
||||
|
||||
/* Return values. */
|
||||
enum ptrace_inject_result {
|
||||
PTRACE_INJECT_OK = 0,
|
||||
PTRACE_INJECT_ERROR = -1
|
||||
};
|
||||
|
||||
/* Log levels passed to ptrace_inject_log_fn. */
|
||||
enum ptrace_inject_log_level {
|
||||
PTRACE_INJECT_LOG_DEBUG = 0,
|
||||
PTRACE_INJECT_LOG_INFO = 1,
|
||||
PTRACE_INJECT_LOG_WARN = 2,
|
||||
PTRACE_INJECT_LOG_ERROR = 3
|
||||
};
|
||||
|
||||
/*
|
||||
* Optional logging callback.
|
||||
*
|
||||
* `message` is only valid for the duration of the call. Pass the same
|
||||
* `ptrace_inject_options` to every injection; the callback runs on the
|
||||
* thread that called ptrace_inject_*().
|
||||
*/
|
||||
typedef void (*ptrace_inject_log_fn)(int level, const char *message,
|
||||
void *user_data);
|
||||
|
||||
typedef struct ptrace_inject_options {
|
||||
ptrace_inject_log_fn log_fn; /* may be NULL */
|
||||
void *log_user_data; /* passed back to log_fn */
|
||||
} ptrace_inject_options;
|
||||
|
||||
/*
|
||||
* Inject `library_path` into the process `pid`.
|
||||
*
|
||||
* `options` may be NULL (silent). `error` may be NULL; when non-NULL and
|
||||
* `error_size > 0`, it receives a NUL-terminated error message on failure and
|
||||
* an empty string on success.
|
||||
*
|
||||
* Returns PTRACE_INJECT_OK on success, PTRACE_INJECT_ERROR on failure.
|
||||
*
|
||||
* The call is synchronous and blocks until the library has been dlopen()ed
|
||||
* (or the call failed). It is safe to call from multiple threads at the same
|
||||
* time as long as the targets are different.
|
||||
*/
|
||||
PTRACE_INJECT_API int
|
||||
ptrace_inject_by_pid(pid_t pid, const char *library_path,
|
||||
const ptrace_inject_options *options, char *error,
|
||||
size_t error_size);
|
||||
|
||||
/*
|
||||
* Same as ptrace_inject_by_pid(), but finds the target by executable path or
|
||||
* file name. `resolved_pid` may be NULL; when non-NULL it receives the PID
|
||||
* that was found (only on success).
|
||||
*/
|
||||
PTRACE_INJECT_API int
|
||||
ptrace_inject_by_name(const char *process_name, const char *library_path,
|
||||
const ptrace_inject_options *options,
|
||||
pid_t *resolved_pid, char *error, size_t error_size);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* PTRACE_INJECT_H */
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
|
||||
// The 6-byte shellcode patched into the tracee:
|
||||
//
|
||||
// 90 90 nop; nop
|
||||
// 41 ff d1 call r9
|
||||
// cc int3
|
||||
//
|
||||
// The tracer sets r9 to the function to call, rdi/rsi to its arguments, and
|
||||
// rip to kShellcode + 2 (the nop slide covers a possible RIP rewind).
|
||||
inline constexpr std::array<std::uint8_t, 6> kShellcode = {
|
||||
0x90, 0x90,
|
||||
0x41, 0xff, 0xd1,
|
||||
0xcc,
|
||||
};
|
||||
|
||||
// Keep this much free space below the target's rsp so we do not clobber the
|
||||
// 128-byte red zone of the function that was interrupted.
|
||||
inline constexpr std::uint64_t kStackMargin = 256;
|
||||
|
||||
// How many times to re-scan /proc/<pid>/task while stopping threads.
|
||||
inline constexpr int kMaxAttachRounds = 8;
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
#include "inject.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "config.h"
|
||||
#include "log.h"
|
||||
#include "maps.h"
|
||||
#include "memory.h"
|
||||
#include "ptrace_utils.h"
|
||||
#include "symbols.h"
|
||||
#include "util.h"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Choosing where to patch
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static bool overlaps(std::uint64_t address, std::uint64_t other,
|
||||
std::uint64_t length) {
|
||||
return address + length > other && address < other + length;
|
||||
}
|
||||
|
||||
// Pick a page-aligned spot in a private, file-backed executable mapping that
|
||||
// no stopped thread is currently sitting in.
|
||||
static std::uint64_t find_patch_site(pid_t pid,
|
||||
const std::vector<pid_t>& threads) {
|
||||
std::vector<std::uint64_t> instruction_pointers;
|
||||
instruction_pointers.reserve(threads.size());
|
||||
for (const pid_t tid : threads) {
|
||||
instruction_pointers.push_back(get_registers(tid).rip);
|
||||
}
|
||||
|
||||
for (const Mapping& map : read_maps(pid)) {
|
||||
if (!is_executable(map) || map.perms.size() < 4 || map.perms[3] != 'p') {
|
||||
continue;
|
||||
}
|
||||
if (map.path.empty() || map.path[0] == '[') {
|
||||
continue; // skip [vdso], [vsyscall], anonymous mappings
|
||||
}
|
||||
|
||||
for (std::uint64_t address = map.start;
|
||||
address + kShellcode.size() <= map.end; address += 0x1000) {
|
||||
bool busy = false;
|
||||
for (const std::uint64_t rip : instruction_pointers) {
|
||||
if (overlaps(address, rip, kShellcode.size())) {
|
||||
busy = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!busy) {
|
||||
return address;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw std::runtime_error("could not find a safe executable place to patch");
|
||||
}
|
||||
|
||||
// Use the target's own stack, but keep clear of the red zone below rsp. If
|
||||
// that region is not writable, fall back to the aligned rsp.
|
||||
static std::uint64_t choose_stack_pointer(pid_t pid, std::uint64_t saved_rsp) {
|
||||
if (saved_rsp > kStackMargin) {
|
||||
const std::uint64_t candidate =
|
||||
(saved_rsp - kStackMargin) & ~std::uint64_t{0xf};
|
||||
if (address_is_writable(pid, candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
const std::uint64_t fallback = saved_rsp & ~std::uint64_t{0xf};
|
||||
if (address_is_writable(pid, fallback)) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
throw std::runtime_error(
|
||||
"target stack is not writable; refusing to continue");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Remote calls
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static std::uint64_t call_in_tracee(pid_t tid,
|
||||
std::uint64_t shellcode_address,
|
||||
std::uint64_t stack_pointer,
|
||||
const user_regs_struct& saved_registers,
|
||||
std::uint64_t function, std::uint64_t rdi,
|
||||
std::uint64_t rsi) {
|
||||
user_regs_struct regs = saved_registers;
|
||||
|
||||
// +2 skips the two NOPs. If resuming rewinds RIP by 2, execution starts at
|
||||
// the NOPs instead, and the nop slide still reaches "call r9".
|
||||
regs.rip = shellcode_address + 2;
|
||||
regs.r9 = function;
|
||||
regs.rdi = rdi;
|
||||
regs.rsi = rsi;
|
||||
// rsp must be 16-byte aligned before the call (x86-64 SysV ABI).
|
||||
regs.rsp = stack_pointer;
|
||||
|
||||
set_registers(tid, regs);
|
||||
continue_tracee(tid);
|
||||
wait_for_trap(tid, shellcode_address + kShellcode.size());
|
||||
|
||||
return get_registers(tid).rax;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Top-level injection
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Validate the library path before anything in the target is modified.
|
||||
static std::string resolve_library_path(const std::string& library) {
|
||||
std::string path;
|
||||
try {
|
||||
path = std::filesystem::canonical(library).string();
|
||||
} catch (const std::filesystem::filesystem_error& error) {
|
||||
throw std::runtime_error("cannot resolve library path '" + library +
|
||||
"': " + error.what());
|
||||
}
|
||||
if (!std::filesystem::is_regular_file(path)) {
|
||||
throw std::runtime_error("'" + path + "' is not a regular file");
|
||||
}
|
||||
path.push_back('\0');
|
||||
return path;
|
||||
}
|
||||
|
||||
void inject_process(pid_t pid, pid_t tracee,
|
||||
const std::vector<pid_t>& threads,
|
||||
const std::string& library, const LogSink* log) {
|
||||
// Validate the library and the remote function addresses before patching.
|
||||
const std::string path = resolve_library_path(library);
|
||||
const LibcAddresses libc = find_libc_addresses(pid);
|
||||
const std::uint64_t shellcode_address = find_patch_site(pid, threads);
|
||||
|
||||
log_debug(log, "remote malloc: 0x" + hex_string(libc.malloc) +
|
||||
", dlopen: 0x" + hex_string(libc.dlopen) +
|
||||
", free: 0x" + hex_string(libc.free));
|
||||
|
||||
const int memory_fd = open_target_memory(pid);
|
||||
|
||||
user_regs_struct saved_registers{};
|
||||
std::array<std::uint8_t, kShellcode.size()> saved_bytes{};
|
||||
std::uint64_t stack_pointer = 0;
|
||||
bool patched = false;
|
||||
|
||||
try {
|
||||
saved_registers = get_registers(tracee);
|
||||
stack_pointer = choose_stack_pointer(pid, saved_registers.rsp);
|
||||
read_memory(memory_fd, shellcode_address, saved_bytes.data(),
|
||||
saved_bytes.size());
|
||||
|
||||
patched = true;
|
||||
write_memory(memory_fd, shellcode_address, kShellcode.data(),
|
||||
kShellcode.size());
|
||||
log_debug(log, "patched shellcode at 0x" + hex_string(shellcode_address));
|
||||
|
||||
// 1. malloc() space in the target for the path.
|
||||
const std::uint64_t remote_path =
|
||||
call_in_tracee(tracee, shellcode_address, stack_pointer,
|
||||
saved_registers, libc.malloc, path.size(), 0);
|
||||
if (remote_path == 0) {
|
||||
throw std::runtime_error("malloc inside tracee returned NULL");
|
||||
}
|
||||
log_debug(log, "remote malloc(" + std::to_string(path.size()) + ") = 0x" +
|
||||
hex_string(remote_path));
|
||||
write_memory(memory_fd, remote_path, path.data(), path.size());
|
||||
|
||||
// 2. dlopen(path, RTLD_LAZY).
|
||||
const std::uint64_t handle =
|
||||
call_in_tracee(tracee, shellcode_address, stack_pointer,
|
||||
saved_registers, libc.dlopen, remote_path, RTLD_LAZY);
|
||||
if (handle == 0) {
|
||||
throw std::runtime_error("dlopen inside tracee returned NULL");
|
||||
}
|
||||
log_debug(log, "remote dlopen(\"" + library + "\") = 0x" +
|
||||
hex_string(handle));
|
||||
|
||||
// 3. free() the path buffer. Failure is not fatal.
|
||||
call_in_tracee(tracee, shellcode_address, stack_pointer, saved_registers,
|
||||
libc.free, remote_path, 0);
|
||||
log_debug(log, "remote free() done");
|
||||
} catch (...) {
|
||||
// Best effort: write both the bytes and the registers back.
|
||||
if (patched) {
|
||||
try {
|
||||
write_memory(memory_fd, shellcode_address, saved_bytes.data(),
|
||||
saved_bytes.size());
|
||||
} catch (const std::exception& error) {
|
||||
log_warn(log, "failed to restore code: " + std::string(error.what()));
|
||||
}
|
||||
try {
|
||||
set_registers(tracee, saved_registers);
|
||||
} catch (const std::exception& error) {
|
||||
log_warn(log,
|
||||
"failed to restore registers: " + std::string(error.what()));
|
||||
}
|
||||
}
|
||||
close_target_memory(memory_fd);
|
||||
throw;
|
||||
}
|
||||
|
||||
try {
|
||||
write_memory(memory_fd, shellcode_address, saved_bytes.data(),
|
||||
saved_bytes.size());
|
||||
set_registers(tracee, saved_registers);
|
||||
} catch (...) {
|
||||
close_target_memory(memory_fd);
|
||||
throw;
|
||||
}
|
||||
close_target_memory(memory_fd);
|
||||
log_info(log, "restored original code and registers");
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "log.h"
|
||||
|
||||
// Load `library` into the already-stopped target process.
|
||||
//
|
||||
// `pid` is the target process, `tracee` is the specific (stopped) thread used
|
||||
// to execute the remote calls, and `threads` is the full list of stopped
|
||||
// threads (used to avoid patching code a thread is currently executing).
|
||||
//
|
||||
// Throws on failure. Any code/register modification is rolled back before the
|
||||
// exception leaves this function.
|
||||
void inject_process(pid_t pid, pid_t tracee,
|
||||
const std::vector<pid_t>& threads,
|
||||
const std::string& library, const LogSink* log);
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
#include "ptrace_inject.h"
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdio>
|
||||
#include <exception>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "inject.h"
|
||||
#include "log.h"
|
||||
#include "process_lookup.h"
|
||||
#include "ptrace_utils.h"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static void write_error(char* error, std::size_t error_size,
|
||||
const std::string& message) {
|
||||
if (error != nullptr && error_size > 0) {
|
||||
std::snprintf(error, error_size, "%s", message.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
static LogSink make_log_sink(const ptrace_inject_options* options) {
|
||||
LogSink sink;
|
||||
if (options != nullptr) {
|
||||
sink.fn = options->log_fn;
|
||||
sink.user_data = options->log_user_data;
|
||||
}
|
||||
return sink;
|
||||
}
|
||||
|
||||
// Shared implementation for both entry points. `pid` is already resolved.
|
||||
static int inject_impl(pid_t pid, const char* library_path,
|
||||
const ptrace_inject_options* options, char* error,
|
||||
std::size_t error_size) {
|
||||
if (library_path == nullptr || library_path[0] == '\0') {
|
||||
write_error(error, error_size, "library path is null or empty");
|
||||
return PTRACE_INJECT_ERROR;
|
||||
}
|
||||
if (pid <= 1) {
|
||||
write_error(error, error_size,
|
||||
"refusing to attach to pid " + std::to_string(pid));
|
||||
return PTRACE_INJECT_ERROR;
|
||||
}
|
||||
if (pid == getpid()) {
|
||||
write_error(error, error_size, "refusing to inject into the injector itself");
|
||||
return PTRACE_INJECT_ERROR;
|
||||
}
|
||||
|
||||
const LogSink log = make_log_sink(options);
|
||||
std::vector<pid_t> attached;
|
||||
|
||||
try {
|
||||
attach_all_threads(pid, attached, &log);
|
||||
|
||||
// Prefer the main thread, but any stopped thread works.
|
||||
pid_t tracee = pid;
|
||||
if (std::find(attached.begin(), attached.end(), tracee) ==
|
||||
attached.end()) {
|
||||
tracee = attached.front();
|
||||
}
|
||||
|
||||
inject_process(pid, tracee, attached, library_path, &log);
|
||||
detach_all_threads(attached, -1, 0, &log);
|
||||
|
||||
write_error(error, error_size, "");
|
||||
log_info(&log, "injected " + std::string(library_path) + " into pid " +
|
||||
std::to_string(pid));
|
||||
return PTRACE_INJECT_OK;
|
||||
} catch (const TraceeSignalError& caught) {
|
||||
// Give the pending signal back to the thread instead of swallowing it.
|
||||
detach_all_threads(attached, caught.tid, caught.signal, &log);
|
||||
write_error(error, error_size, caught.what());
|
||||
return PTRACE_INJECT_ERROR;
|
||||
} catch (const std::exception& caught) {
|
||||
detach_all_threads(attached, -1, 0, &log);
|
||||
write_error(error, error_size, caught.what());
|
||||
return PTRACE_INJECT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
extern "C" int ptrace_inject_by_pid(pid_t pid, const char* library_path,
|
||||
const ptrace_inject_options* options,
|
||||
char* error, std::size_t error_size) {
|
||||
return inject_impl(pid, library_path, options, error, error_size);
|
||||
}
|
||||
|
||||
extern "C" int ptrace_inject_by_name(const char* process_name,
|
||||
const char* library_path,
|
||||
const ptrace_inject_options* options,
|
||||
pid_t* resolved_pid, char* error,
|
||||
std::size_t error_size) {
|
||||
if (process_name == nullptr || process_name[0] == '\0') {
|
||||
write_error(error, error_size, "process name is null or empty");
|
||||
return PTRACE_INJECT_ERROR;
|
||||
}
|
||||
|
||||
const LogSink log = make_log_sink(options);
|
||||
|
||||
pid_t pid = -1;
|
||||
try {
|
||||
pid = find_pid_by_name(process_name);
|
||||
} catch (const std::exception& caught) {
|
||||
write_error(error, error_size, caught.what());
|
||||
return PTRACE_INJECT_ERROR;
|
||||
}
|
||||
|
||||
if (pid == -1) {
|
||||
write_error(error, error_size,
|
||||
"could not find process named '" + std::string(process_name) +
|
||||
"'");
|
||||
return PTRACE_INJECT_ERROR;
|
||||
}
|
||||
|
||||
if (resolved_pid != nullptr) {
|
||||
*resolved_pid = pid;
|
||||
}
|
||||
log_info(&log, "found pid " + std::to_string(pid) + " for name '" +
|
||||
std::string(process_name) + "'");
|
||||
|
||||
return inject_impl(pid, library_path, options, error, error_size);
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#include "log.h"
|
||||
|
||||
void log_message(const LogSink* sink, int level, const std::string& message) {
|
||||
if (sink != nullptr && sink->fn != nullptr) {
|
||||
sink->fn(level, message.c_str(), sink->user_data);
|
||||
}
|
||||
}
|
||||
|
||||
void log_debug(const LogSink* sink, const std::string& message) {
|
||||
log_message(sink, PTRACE_INJECT_LOG_DEBUG, message);
|
||||
}
|
||||
|
||||
void log_info(const LogSink* sink, const std::string& message) {
|
||||
log_message(sink, PTRACE_INJECT_LOG_INFO, message);
|
||||
}
|
||||
|
||||
void log_warn(const LogSink* sink, const std::string& message) {
|
||||
log_message(sink, PTRACE_INJECT_LOG_WARN, message);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "ptrace_inject.h"
|
||||
|
||||
// Internal representation of ptrace_inject_options.
|
||||
struct LogSink {
|
||||
ptrace_inject_log_fn fn = nullptr;
|
||||
void* user_data = nullptr;
|
||||
};
|
||||
|
||||
// All of these do nothing when `sink` is null or `sink->fn` is null.
|
||||
void log_message(const LogSink* sink, int level, const std::string& message);
|
||||
void log_debug(const LogSink* sink, const std::string& message);
|
||||
void log_info(const LogSink* sink, const std::string& message);
|
||||
void log_warn(const LogSink* sink, const std::string& message);
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
#include <limits.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "ptrace_inject.h"
|
||||
|
||||
static void print_log(int level, const char* message, void* /*user_data*/) {
|
||||
const char* prefix = "[*]";
|
||||
switch (level) {
|
||||
case PTRACE_INJECT_LOG_DEBUG:
|
||||
prefix = "[debug]";
|
||||
break;
|
||||
case PTRACE_INJECT_LOG_INFO:
|
||||
prefix = "[*]";
|
||||
break;
|
||||
case PTRACE_INJECT_LOG_WARN:
|
||||
prefix = "[!]";
|
||||
break;
|
||||
case PTRACE_INJECT_LOG_ERROR:
|
||||
prefix = "[error]";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
std::fprintf(stderr, "%s %s\n", prefix, message);
|
||||
}
|
||||
|
||||
static void usage(const char* program) {
|
||||
std::fprintf(stderr,
|
||||
"Usage: %s (-p PID | -n NAME) <library.so>\n"
|
||||
"\n"
|
||||
"Inject a shared library into a running x86-64 Linux process.\n"
|
||||
"\n"
|
||||
" -p PID attach to this PID\n"
|
||||
" -n NAME attach to the first process whose executable name\n"
|
||||
" or path matches NAME\n"
|
||||
" -h show this help\n"
|
||||
"\n"
|
||||
"Requires the same uid and CAP_SYS_PTRACE, or a suitable\n"
|
||||
"kernel.yama.ptrace_scope setting.\n",
|
||||
program);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
pid_t pid = -1;
|
||||
std::string name;
|
||||
|
||||
int option;
|
||||
while ((option = getopt(argc, argv, "p:n:h")) != -1) {
|
||||
switch (option) {
|
||||
case 'p': {
|
||||
try {
|
||||
const long value = std::stol(optarg);
|
||||
if (value <= 0 || value > INT_MAX) {
|
||||
throw std::out_of_range("pid");
|
||||
}
|
||||
pid = static_cast<pid_t>(value);
|
||||
} catch (const std::exception&) {
|
||||
std::fprintf(stderr, "error: invalid pid '%s'\n", optarg);
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'n':
|
||||
name = optarg;
|
||||
break;
|
||||
case 'h':
|
||||
usage(argv[0]);
|
||||
return 0;
|
||||
default:
|
||||
usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (optind + 1 != argc) {
|
||||
usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
const char* library = argv[optind];
|
||||
|
||||
if ((pid == -1) == name.empty()) {
|
||||
std::fprintf(stderr, "error: specify exactly one of -p PID or -n NAME\n");
|
||||
usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
ptrace_inject_options options{};
|
||||
options.log_fn = print_log;
|
||||
|
||||
char error[512] = {};
|
||||
int result;
|
||||
if (!name.empty()) {
|
||||
result = ptrace_inject_by_name(name.c_str(), library, &options, nullptr,
|
||||
error, sizeof(error));
|
||||
} else {
|
||||
result = ptrace_inject_by_pid(pid, library, &options, error, sizeof(error));
|
||||
}
|
||||
|
||||
if (result != PTRACE_INJECT_OK) {
|
||||
std::fprintf(stderr, "error: %s\n", error);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
#include "maps.h"
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "util.h"
|
||||
|
||||
bool is_executable(const Mapping& map) {
|
||||
return map.perms.size() >= 3 && map.perms[2] == 'x';
|
||||
}
|
||||
|
||||
bool is_writable(const Mapping& map) {
|
||||
return map.perms.size() >= 2 && map.perms[1] == 'w';
|
||||
}
|
||||
|
||||
std::vector<Mapping> read_maps(pid_t pid) {
|
||||
const std::string file = "/proc/" + std::to_string(pid) + "/maps";
|
||||
std::ifstream in(file);
|
||||
if (!in) {
|
||||
throw std::runtime_error("cannot open " + file);
|
||||
}
|
||||
|
||||
std::vector<Mapping> maps;
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
std::istringstream iss(line);
|
||||
std::string range;
|
||||
std::string offset;
|
||||
std::string dev;
|
||||
std::string inode;
|
||||
|
||||
Mapping map;
|
||||
if (!(iss >> range >> map.perms >> offset >> dev >> inode)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto dash = range.find('-');
|
||||
if (dash == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
map.start = std::stoull(range.substr(0, dash), nullptr, 16);
|
||||
map.end = std::stoull(range.substr(dash + 1), nullptr, 16);
|
||||
map.inode = std::stoull(inode, nullptr, 10);
|
||||
} catch (const std::exception&) {
|
||||
continue;
|
||||
}
|
||||
map.dev = dev;
|
||||
|
||||
// The file name may contain spaces, so take the rest of the line.
|
||||
std::string rest;
|
||||
std::getline(iss, rest);
|
||||
map.path = trim(rest);
|
||||
|
||||
maps.push_back(map);
|
||||
}
|
||||
return maps;
|
||||
}
|
||||
|
||||
std::string file_name_of(const std::string& path) {
|
||||
return std::filesystem::path(strip_deleted(path)).filename().string();
|
||||
}
|
||||
|
||||
bool address_is_executable(pid_t pid, std::uint64_t address) {
|
||||
for (const Mapping& map : read_maps(pid)) {
|
||||
if (address >= map.start && address < map.end) {
|
||||
return is_executable(map);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool address_is_writable(pid_t pid, std::uint64_t address) {
|
||||
for (const Mapping& map : read_maps(pid)) {
|
||||
if (address >= map.start && address < map.end) {
|
||||
return is_writable(map);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ObjectInfo find_object(pid_t pid, const std::string& object_name) {
|
||||
for (const Mapping& map : read_maps(pid)) {
|
||||
if (file_name_of(map.path) == object_name) {
|
||||
return ObjectInfo{map.start, map.dev, map.inode};
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("could not find " + object_name + " in process " +
|
||||
std::to_string(pid));
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// One line of /proc/<pid>/maps.
|
||||
struct Mapping {
|
||||
std::uint64_t start = 0;
|
||||
std::uint64_t end = 0;
|
||||
std::string dev;
|
||||
std::uint64_t inode = 0;
|
||||
std::string perms;
|
||||
std::string path;
|
||||
};
|
||||
|
||||
// Load base and file identity of a shared object in a given process.
|
||||
struct ObjectInfo {
|
||||
std::uint64_t base = 0;
|
||||
std::string dev;
|
||||
std::uint64_t inode = 0;
|
||||
};
|
||||
|
||||
std::vector<Mapping> read_maps(pid_t pid);
|
||||
|
||||
bool is_executable(const Mapping& map);
|
||||
bool is_writable(const Mapping& map);
|
||||
|
||||
std::string file_name_of(const std::string& path);
|
||||
|
||||
bool address_is_executable(pid_t pid, std::uint64_t address);
|
||||
bool address_is_writable(pid_t pid, std::uint64_t address);
|
||||
|
||||
// Find the first mapping (file offset 0, i.e. the load base) of a shared
|
||||
// object identified by its file name.
|
||||
ObjectInfo find_object(pid_t pid, const std::string& object_name);
|
||||
@@ -0,0 +1,69 @@
|
||||
#include "memory.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "util.h"
|
||||
|
||||
int open_target_memory(pid_t pid) {
|
||||
const std::string path = "/proc/" + std::to_string(pid) + "/mem";
|
||||
const int fd = open(path.c_str(), O_RDWR | O_CLOEXEC);
|
||||
if (fd == -1) {
|
||||
throw_errno("open " + path);
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
void close_target_memory(int fd) {
|
||||
if (fd >= 0) {
|
||||
close(fd);
|
||||
}
|
||||
}
|
||||
|
||||
void read_memory(int fd, std::uint64_t address, void* buffer,
|
||||
std::size_t length) {
|
||||
auto* out = static_cast<std::uint8_t*>(buffer);
|
||||
std::size_t done = 0;
|
||||
while (done < length) {
|
||||
const ssize_t n =
|
||||
pread(fd, out + done, length - done, static_cast<off_t>(address + done));
|
||||
if (n == -1) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
throw_errno("pread from target memory at 0x" +
|
||||
hex_string(address + done));
|
||||
}
|
||||
if (n == 0) {
|
||||
throw std::runtime_error("short read from target memory at 0x" +
|
||||
hex_string(address + done));
|
||||
}
|
||||
done += static_cast<std::size_t>(n);
|
||||
}
|
||||
}
|
||||
|
||||
void write_memory(int fd, std::uint64_t address, const void* buffer,
|
||||
std::size_t length) {
|
||||
const auto* in = static_cast<const std::uint8_t*>(buffer);
|
||||
std::size_t done = 0;
|
||||
while (done < length) {
|
||||
const ssize_t n = pwrite(fd, in + done, length - done,
|
||||
static_cast<off_t>(address + done));
|
||||
if (n == -1) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
throw_errno("pwrite to target memory at 0x" + hex_string(address + done));
|
||||
}
|
||||
if (n == 0) {
|
||||
throw std::runtime_error("short write to target memory at 0x" +
|
||||
hex_string(address + done));
|
||||
}
|
||||
done += static_cast<std::size_t>(n);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
// Open /proc/<pid>/mem for reading and writing.
|
||||
// The process must already be ptrace-stopped.
|
||||
int open_target_memory(pid_t pid);
|
||||
|
||||
void close_target_memory(int fd);
|
||||
|
||||
void read_memory(int fd, std::uint64_t address, void* buffer, std::size_t length);
|
||||
|
||||
void write_memory(int fd, std::uint64_t address, const void* buffer,
|
||||
std::size_t length);
|
||||
@@ -0,0 +1,46 @@
|
||||
#include "process_lookup.h"
|
||||
|
||||
#include <limits.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "util.h"
|
||||
|
||||
pid_t find_pid_by_name(const std::string& name) {
|
||||
std::error_code ec;
|
||||
std::filesystem::directory_iterator iterator("/proc", ec);
|
||||
const std::filesystem::directory_iterator end;
|
||||
if (ec) {
|
||||
throw std::runtime_error("cannot open /proc: " + ec.message());
|
||||
}
|
||||
|
||||
for (; iterator != end; iterator.increment(ec)) {
|
||||
if (ec) {
|
||||
break;
|
||||
}
|
||||
|
||||
const std::string pid_text = iterator->path().filename().string();
|
||||
if (!all_digits(pid_text)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
char buffer[PATH_MAX + 1] = {};
|
||||
const ssize_t length =
|
||||
readlink((iterator->path() / "exe").c_str(), buffer, PATH_MAX);
|
||||
if (length <= 0) {
|
||||
continue; // usually a permission problem
|
||||
}
|
||||
buffer[length] = '\0';
|
||||
|
||||
const std::string executable = strip_deleted(buffer);
|
||||
const std::string executable_name =
|
||||
std::filesystem::path(executable).filename().string();
|
||||
if (executable_name == name || executable == name) {
|
||||
return static_cast<pid_t>(std::stoi(pid_text));
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
// Return the PID of the first process whose executable path or file name is
|
||||
// `name`, or -1 if no process matches.
|
||||
pid_t find_pid_by_name(const std::string& name);
|
||||
@@ -0,0 +1,191 @@
|
||||
#include "ptrace_utils.h"
|
||||
|
||||
#include <sys/ptrace.h>
|
||||
#include <sys/wait.h>
|
||||
#include <signal.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "config.h"
|
||||
#include "log.h"
|
||||
#include "util.h"
|
||||
|
||||
#ifndef __WALL
|
||||
#define __WALL 0x40000000
|
||||
#endif
|
||||
|
||||
user_regs_struct get_registers(pid_t tid) {
|
||||
user_regs_struct regs{};
|
||||
if (ptrace(PTRACE_GETREGS, tid, nullptr, ®s) == -1) {
|
||||
throw_errno("PTRACE_GETREGS on tid " + std::to_string(tid));
|
||||
}
|
||||
return regs;
|
||||
}
|
||||
|
||||
void set_registers(pid_t tid, const user_regs_struct& regs) {
|
||||
user_regs_struct copy = regs;
|
||||
if (ptrace(PTRACE_SETREGS, tid, nullptr, ©) == -1) {
|
||||
throw_errno("PTRACE_SETREGS on tid " + std::to_string(tid));
|
||||
}
|
||||
}
|
||||
|
||||
void continue_tracee(pid_t tid) {
|
||||
// The last argument is the signal to deliver. 0 suppresses the SIGTRAP
|
||||
// from int3 (and the SIGSTOP from PTRACE_ATTACH).
|
||||
if (ptrace(PTRACE_CONT, tid, nullptr, nullptr) == -1) {
|
||||
throw_errno("PTRACE_CONT on tid " + std::to_string(tid));
|
||||
}
|
||||
}
|
||||
|
||||
void wait_for_trap(pid_t tid, std::uint64_t expected_rip) {
|
||||
int status = 0;
|
||||
for (;;) {
|
||||
pid_t waited;
|
||||
do {
|
||||
waited = waitpid(tid, &status, __WALL);
|
||||
} while (waited == -1 && errno == EINTR);
|
||||
|
||||
if (waited == -1) {
|
||||
throw_errno("waitpid on tid " + std::to_string(tid));
|
||||
}
|
||||
if (WIFEXITED(status)) {
|
||||
throw std::runtime_error("tracee exited with status " +
|
||||
std::to_string(WEXITSTATUS(status)));
|
||||
}
|
||||
if (WIFSIGNALED(status)) {
|
||||
throw std::runtime_error("tracee was killed by signal " +
|
||||
std::to_string(WTERMSIG(status)));
|
||||
}
|
||||
if (!WIFSTOPPED(status)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const int signal = WSTOPSIG(status);
|
||||
if (signal == SIGTRAP) {
|
||||
// Only accept the SIGTRAP generated by our own int3. On x86-64 RIP
|
||||
// points just past the int3 instruction at that stop.
|
||||
const user_regs_struct regs = get_registers(tid);
|
||||
if (regs.rip == expected_rip) {
|
||||
return;
|
||||
}
|
||||
throw TraceeSignalError(
|
||||
tid, signal,
|
||||
"unexpected SIGTRAP at rip=0x" + hex_string(regs.rip) +
|
||||
" (expected 0x" + hex_string(expected_rip) + ")");
|
||||
}
|
||||
|
||||
const user_regs_struct regs = get_registers(tid);
|
||||
throw TraceeSignalError(tid, signal,
|
||||
"shellcode in tracee received unexpected signal " +
|
||||
std::to_string(signal) + " (" +
|
||||
strsignal(signal) + ") at rip=0x" +
|
||||
hex_string(regs.rip));
|
||||
}
|
||||
}
|
||||
|
||||
static std::vector<pid_t> list_threads(pid_t pid) {
|
||||
const std::string directory = "/proc/" + std::to_string(pid) + "/task";
|
||||
std::error_code ec;
|
||||
std::filesystem::directory_iterator iterator(directory, ec);
|
||||
const std::filesystem::directory_iterator end;
|
||||
if (ec) {
|
||||
throw std::runtime_error("cannot list threads of pid " +
|
||||
std::to_string(pid) + ": " + ec.message());
|
||||
}
|
||||
|
||||
std::vector<pid_t> threads;
|
||||
for (; iterator != end; iterator.increment(ec)) {
|
||||
if (ec) {
|
||||
break;
|
||||
}
|
||||
const std::string name = iterator->path().filename().string();
|
||||
if (!all_digits(name)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
threads.push_back(static_cast<pid_t>(std::stoi(name)));
|
||||
} catch (const std::exception&) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
std::sort(threads.begin(), threads.end());
|
||||
return threads;
|
||||
}
|
||||
|
||||
static bool attach_one_thread(pid_t tid, std::vector<pid_t>& attached) {
|
||||
if (ptrace(PTRACE_ATTACH, tid, nullptr, nullptr) == -1) {
|
||||
if (errno == ESRCH) {
|
||||
return false; // thread exited while we were enumerating
|
||||
}
|
||||
throw_errno("PTRACE_ATTACH on tid " + std::to_string(tid));
|
||||
}
|
||||
|
||||
// Record it before waiting: if waitpid fails, the thread is still attached
|
||||
// and the caller must be able to detach it.
|
||||
attached.push_back(tid);
|
||||
|
||||
int status = 0;
|
||||
pid_t waited;
|
||||
do {
|
||||
waited = waitpid(tid, &status, __WALL);
|
||||
} while (waited == -1 && errno == EINTR);
|
||||
|
||||
if (waited == -1) {
|
||||
throw_errno("waitpid after attaching to tid " + std::to_string(tid));
|
||||
}
|
||||
if (!WIFSTOPPED(status)) {
|
||||
throw std::runtime_error("thread " + std::to_string(tid) +
|
||||
" did not stop after PTRACE_ATTACH");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void attach_all_threads(pid_t pid, std::vector<pid_t>& attached,
|
||||
const LogSink* log) {
|
||||
// A running target can create threads while we are attaching, so re-scan
|
||||
// until there is nothing new to attach.
|
||||
for (int round = 0; round < kMaxAttachRounds; ++round) {
|
||||
bool attached_anything = false;
|
||||
for (const pid_t tid : list_threads(pid)) {
|
||||
if (std::find(attached.begin(), attached.end(), tid) != attached.end()) {
|
||||
continue;
|
||||
}
|
||||
if (attach_one_thread(tid, attached)) {
|
||||
attached_anything = true;
|
||||
}
|
||||
}
|
||||
if (!attached_anything) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (attached.empty()) {
|
||||
throw std::runtime_error("could not attach to any thread");
|
||||
}
|
||||
log_info(log, "attached to " + std::to_string(attached.size()) +
|
||||
" thread(s) of pid " + std::to_string(pid));
|
||||
}
|
||||
|
||||
void detach_all_threads(std::vector<pid_t>& attached, pid_t signal_tid,
|
||||
int signal, const LogSink* log) {
|
||||
for (const pid_t tid : attached) {
|
||||
void* data = nullptr;
|
||||
if (tid == signal_tid && signal != 0) {
|
||||
data = reinterpret_cast<void*>(static_cast<intptr_t>(signal));
|
||||
}
|
||||
if (ptrace(PTRACE_DETACH, tid, nullptr, data) == -1 && errno != ESRCH) {
|
||||
const int err = errno;
|
||||
log_warn(log, "PTRACE_DETACH on tid " + std::to_string(tid) +
|
||||
" failed: " + std::strerror(err));
|
||||
}
|
||||
}
|
||||
attached.clear();
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/user.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "log.h"
|
||||
|
||||
// Thrown when the tracee stops with a signal that is not our int3 SIGTRAP.
|
||||
// main() uses it to deliver that signal back to the target on detach.
|
||||
struct TraceeSignalError : public std::runtime_error {
|
||||
TraceeSignalError(pid_t tracee, int signo, const std::string& what)
|
||||
: std::runtime_error(what), tid(tracee), signal(signo) {}
|
||||
|
||||
pid_t tid;
|
||||
int signal;
|
||||
};
|
||||
|
||||
user_regs_struct get_registers(pid_t tid);
|
||||
void set_registers(pid_t tid, const user_regs_struct& regs);
|
||||
|
||||
void continue_tracee(pid_t tid);
|
||||
|
||||
// Wait for our int3. expected_rip must be kShellcodeAddress + kShellcode.size().
|
||||
void wait_for_trap(pid_t tid, std::uint64_t expected_rip);
|
||||
|
||||
// Stop every thread of `pid`; on return all of them are ptrace-stopped.
|
||||
void attach_all_threads(pid_t pid, std::vector<pid_t>& attached,
|
||||
const LogSink* log);
|
||||
|
||||
// Detach all threads. If signal != 0, deliver it to signal_tid on detach.
|
||||
void detach_all_threads(std::vector<pid_t>& attached, pid_t signal_tid,
|
||||
int signal, const LogSink* log);
|
||||
@@ -0,0 +1,66 @@
|
||||
#include "symbols.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "maps.h"
|
||||
#include "util.h"
|
||||
|
||||
struct SymbolAddress {
|
||||
const char* name;
|
||||
std::uint64_t address;
|
||||
std::string object;
|
||||
};
|
||||
|
||||
static SymbolAddress resolve_symbol(const char* name) {
|
||||
dlerror(); // clear any previous error
|
||||
void* address = dlsym(RTLD_DEFAULT, name);
|
||||
if (const char* error = dlerror()) {
|
||||
throw std::runtime_error(std::string("dlsym(") + name + ") failed: " +
|
||||
error);
|
||||
}
|
||||
|
||||
Dl_info info{};
|
||||
if (dladdr(address, &info) == 0 || info.dli_fname == nullptr) {
|
||||
throw std::runtime_error(std::string("dladdr(") + name + ") failed");
|
||||
}
|
||||
|
||||
return SymbolAddress{name, reinterpret_cast<std::uint64_t>(address),
|
||||
file_name_of(info.dli_fname)};
|
||||
}
|
||||
|
||||
// Translate one local symbol address into the target's address space.
|
||||
//
|
||||
// malloc/free are in libc.so.6; dlopen is in libc.so.6 on new glibc and in
|
||||
// libdl.so.2 on old glibc. dladdr() tells us which object owns the symbol.
|
||||
static std::uint64_t relocate_symbol(const SymbolAddress& symbol,
|
||||
pid_t target_pid) {
|
||||
const ObjectInfo local = find_object(getpid(), symbol.object);
|
||||
const ObjectInfo target = find_object(target_pid, symbol.object);
|
||||
|
||||
if (local.dev != target.dev || local.inode != target.inode) {
|
||||
throw std::runtime_error(
|
||||
std::string("injector and target use different builds of ") +
|
||||
symbol.object + "; refusing to guess the address of " + symbol.name);
|
||||
}
|
||||
|
||||
const std::uint64_t address = symbol.address - local.base + target.base;
|
||||
if (!address_is_executable(target_pid, address)) {
|
||||
throw std::runtime_error(std::string("relocated ") + symbol.name +
|
||||
" is not executable in the target; refusing to "
|
||||
"continue");
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
LibcAddresses find_libc_addresses(pid_t target_pid) {
|
||||
return LibcAddresses{
|
||||
relocate_symbol(resolve_symbol("malloc"), target_pid),
|
||||
relocate_symbol(resolve_symbol("dlopen"), target_pid),
|
||||
relocate_symbol(resolve_symbol("free"), target_pid),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// Addresses of the libc functions we need, already relocated into the target.
|
||||
struct LibcAddresses {
|
||||
std::uint64_t malloc = 0;
|
||||
std::uint64_t dlopen = 0;
|
||||
std::uint64_t free = 0;
|
||||
};
|
||||
|
||||
// Resolve malloc/dlopen/free locally and translate their addresses into the
|
||||
// address space of `target_pid`.
|
||||
//
|
||||
// Refuses to continue (throws) if the injector and the target use different
|
||||
// builds of the owning shared object, or if a relocated address is not
|
||||
// executable there.
|
||||
LibcAddresses find_libc_addresses(pid_t target_pid);
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "util.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
void throw_errno(const std::string& what) {
|
||||
const int err = errno;
|
||||
throw std::runtime_error(what + ": " + std::strerror(err));
|
||||
}
|
||||
|
||||
bool all_digits(const std::string& text) {
|
||||
return !text.empty() &&
|
||||
std::all_of(text.begin(), text.end(), [](unsigned char c) {
|
||||
return std::isdigit(c) != 0;
|
||||
});
|
||||
}
|
||||
|
||||
std::string strip_deleted(std::string path) {
|
||||
static const std::string suffix = " (deleted)";
|
||||
if (path.size() > suffix.size() &&
|
||||
path.compare(path.size() - suffix.size(), suffix.size(), suffix) == 0) {
|
||||
path.resize(path.size() - suffix.size());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
std::string trim(std::string text) {
|
||||
const auto begin = text.find_first_not_of(" \t\r\n");
|
||||
if (begin == std::string::npos) {
|
||||
return {};
|
||||
}
|
||||
const auto end = text.find_last_not_of(" \t\r\n");
|
||||
return text.substr(begin, end - begin + 1);
|
||||
}
|
||||
|
||||
std::string hex_string(std::uint64_t value) {
|
||||
std::ostringstream out;
|
||||
out << std::hex << value;
|
||||
return out.str();
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
// Throw std::runtime_error with strerror(errno) appended.
|
||||
[[noreturn]] void throw_errno(const std::string& what);
|
||||
|
||||
bool all_digits(const std::string& text);
|
||||
|
||||
// Remove the " (deleted)" suffix that /proc/<pid>/maps adds to unlinked files.
|
||||
std::string strip_deleted(std::string path);
|
||||
|
||||
std::string trim(std::string text);
|
||||
|
||||
std::string hex_string(std::uint64_t value);
|
||||
Reference in new issue
Block a user