Refactor: Vendor ptrace-inject-cpp into includes

- ptrace-inject-cpp: remove the submodule, its .gitmodules entry and config section
- includes/ptrace-inject-cpp: add the injection library sources, public header and LICENSE
- includes/ptrace-inject-cpp: add CMakeLists defining the ptrace_inject static library
- cmake: build includes/ptrace-inject-cpp on non-Windows instead of the submodule
- docs: list the vendored library in the AGENTS.md layout
This commit is contained in:
xiaozhou233 committed 2026-10-24 23:02:50 +08:00
1 parent 4b1ca5a490
commit d31e43af31
25 files changed
+1217 -8

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
[submodule "ptrace-inject-cpp"]
path = ptrace-inject-cpp
url = https://github.com/xiaozhou233/ptrace-inject-cpp
+1
View File
@@ -159,6 +159,7 @@ src/libagent libagent.dll (JVMTI agent)
includes/JuiceAgent Config.hpp / Logger.hpp / Utils.hpp / JuiceAgent.hpp (CONFIG_VERSION) includes/JuiceAgent Config.hpp / Logger.hpp / Utils.hpp / JuiceAgent.hpp (CONFIG_VERSION)
includes/toml++ vendored includes/toml++ vendored
includes/spdlog vendored includes/spdlog vendored
includes/ptrace-inject-cpp vendored Linux injector library (libptrace_inject.a)
tests/ integration tests + run-tests.ps1 + copy-bin.bat tests/ integration tests + run-tests.ps1 + copy-bin.bat
docs/ config.md, advanced.md, Inject.md, update/ (release notes + changelog) docs/ config.md, advanced.md, Inject.md, update/ (release notes + changelog)
examples/ runnable end-to-end examples (each has config.toml + HowToUse) examples/ runnable end-to-end examples (each has config.toml + HowToUse)
+1 -4
View File
@@ -19,10 +19,7 @@ endif()
if (WIN32) if (WIN32)
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection) add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
else() else()
set(PTRACE_INJECT_BUILD_CLI OFF CACHE BOOL "" FORCE) add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ptrace-inject-cpp)
set(PTRACE_INJECT_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
add_subdirectory(ptrace-inject-cpp)
endif() endif()
# modules # modules
+27
View File
@@ -0,0 +1,27 @@
add_library(ptrace_inject STATIC
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
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN ON
POSITION_INDEPENDENT_CODE ON
)
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 xiaozhou233
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,90 @@
/*
* ptrace_inject - C ABI for injecting shared libraries with ptrace.
*
* Part of ptrace-inject-cpp, a C++ port of the original Rust project:
* https://github.com/Artemis21/ptrace-inject
*/
#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 */
+25
View File
@@ -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
View File
@@ -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");
}
+20
View File
@@ -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
View File
@@ -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
View File
@@ -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);
}
+17
View File
@@ -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);
+93
View File
@@ -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
View File
@@ -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);
+69
View File
@@ -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);
}
}
+17
View File
@@ -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, &regs) == -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, &copy) == -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),
};
}
+20
View File
@@ -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);
+44
View File
@@ -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
View File
@@ -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);