From d31e43af313321abdd1c681945e8d89b9e0ce15f Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sat, 24 Oct 2026 23:02:50 +0800 Subject: [PATCH] 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 --- .gitmodules | 3 - AGENTS.md | 1 + CMakeLists.txt | 5 +- includes/ptrace-inject-cpp/CMakeLists.txt | 27 +++ includes/ptrace-inject-cpp/LICENSE | 21 ++ .../ptrace-inject-cpp/include/ptrace_inject.h | 90 +++++++ includes/ptrace-inject-cpp/src/config.h | 25 ++ includes/ptrace-inject-cpp/src/inject.cpp | 219 ++++++++++++++++++ includes/ptrace-inject-cpp/src/inject.h | 20 ++ includes/ptrace-inject-cpp/src/library.cpp | 131 +++++++++++ includes/ptrace-inject-cpp/src/log.cpp | 19 ++ includes/ptrace-inject-cpp/src/log.h | 17 ++ includes/ptrace-inject-cpp/src/maps.cpp | 93 ++++++++ includes/ptrace-inject-cpp/src/maps.h | 38 +++ includes/ptrace-inject-cpp/src/memory.cpp | 69 ++++++ includes/ptrace-inject-cpp/src/memory.h | 17 ++ .../ptrace-inject-cpp/src/process_lookup.cpp | 46 ++++ .../ptrace-inject-cpp/src/process_lookup.h | 9 + .../ptrace-inject-cpp/src/ptrace_utils.cpp | 191 +++++++++++++++ includes/ptrace-inject-cpp/src/ptrace_utils.h | 37 +++ includes/ptrace-inject-cpp/src/symbols.cpp | 66 ++++++ includes/ptrace-inject-cpp/src/symbols.h | 20 ++ includes/ptrace-inject-cpp/src/util.cpp | 44 ++++ includes/ptrace-inject-cpp/src/util.h | 16 ++ ptrace-inject-cpp | 1 - 25 files changed, 1217 insertions(+), 8 deletions(-) delete mode 100644 .gitmodules create mode 100644 includes/ptrace-inject-cpp/CMakeLists.txt create mode 100644 includes/ptrace-inject-cpp/LICENSE create mode 100644 includes/ptrace-inject-cpp/include/ptrace_inject.h create mode 100644 includes/ptrace-inject-cpp/src/config.h create mode 100644 includes/ptrace-inject-cpp/src/inject.cpp create mode 100644 includes/ptrace-inject-cpp/src/inject.h create mode 100644 includes/ptrace-inject-cpp/src/library.cpp create mode 100644 includes/ptrace-inject-cpp/src/log.cpp create mode 100644 includes/ptrace-inject-cpp/src/log.h create mode 100644 includes/ptrace-inject-cpp/src/maps.cpp create mode 100644 includes/ptrace-inject-cpp/src/maps.h create mode 100644 includes/ptrace-inject-cpp/src/memory.cpp create mode 100644 includes/ptrace-inject-cpp/src/memory.h create mode 100644 includes/ptrace-inject-cpp/src/process_lookup.cpp create mode 100644 includes/ptrace-inject-cpp/src/process_lookup.h create mode 100644 includes/ptrace-inject-cpp/src/ptrace_utils.cpp create mode 100644 includes/ptrace-inject-cpp/src/ptrace_utils.h create mode 100644 includes/ptrace-inject-cpp/src/symbols.cpp create mode 100644 includes/ptrace-inject-cpp/src/symbols.h create mode 100644 includes/ptrace-inject-cpp/src/util.cpp create mode 100644 includes/ptrace-inject-cpp/src/util.h delete mode 160000 ptrace-inject-cpp diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 1267eea..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "ptrace-inject-cpp"] - path = ptrace-inject-cpp - url = https://github.com/xiaozhou233/ptrace-inject-cpp diff --git a/AGENTS.md b/AGENTS.md index 008e9bb..55f8d30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -159,6 +159,7 @@ src/libagent libagent.dll (JVMTI agent) includes/JuiceAgent Config.hpp / Logger.hpp / Utils.hpp / JuiceAgent.hpp (CONFIG_VERSION) includes/toml++ vendored includes/spdlog vendored +includes/ptrace-inject-cpp vendored Linux injector library (libptrace_inject.a) tests/ integration tests + run-tests.ps1 + copy-bin.bat docs/ config.md, advanced.md, Inject.md, update/ (release notes + changelog) examples/ runnable end-to-end examples (each has config.toml + HowToUse) diff --git a/CMakeLists.txt b/CMakeLists.txt index 36635ca..1dc6d01 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,10 +19,7 @@ endif() if (WIN32) add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection) else() - set(PTRACE_INJECT_BUILD_CLI OFF CACHE BOOL "" FORCE) - set(PTRACE_INJECT_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) - - add_subdirectory(ptrace-inject-cpp) + add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ptrace-inject-cpp) endif() # modules diff --git a/includes/ptrace-inject-cpp/CMakeLists.txt b/includes/ptrace-inject-cpp/CMakeLists.txt new file mode 100644 index 0000000..e78fe41 --- /dev/null +++ b/includes/ptrace-inject-cpp/CMakeLists.txt @@ -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 +) diff --git a/includes/ptrace-inject-cpp/LICENSE b/includes/ptrace-inject-cpp/LICENSE new file mode 100644 index 0000000..61f66ec --- /dev/null +++ b/includes/ptrace-inject-cpp/LICENSE @@ -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. diff --git a/includes/ptrace-inject-cpp/include/ptrace_inject.h b/includes/ptrace-inject-cpp/include/ptrace_inject.h new file mode 100644 index 0000000..7ca08e2 --- /dev/null +++ b/includes/ptrace-inject-cpp/include/ptrace_inject.h @@ -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 +#include + +#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 */ diff --git a/includes/ptrace-inject-cpp/src/config.h b/includes/ptrace-inject-cpp/src/config.h new file mode 100644 index 0000000..bf947a9 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/config.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +// 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 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//task while stopping threads. +inline constexpr int kMaxAttachRounds = 8; diff --git a/includes/ptrace-inject-cpp/src/inject.cpp b/includes/ptrace-inject-cpp/src/inject.cpp new file mode 100644 index 0000000..06d5229 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/inject.cpp @@ -0,0 +1,219 @@ +#include "inject.h" + +#include +#include + +#include +#include +#include +#include +#include +#include + +#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& threads) { + std::vector 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& 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 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"); +} diff --git a/includes/ptrace-inject-cpp/src/inject.h b/includes/ptrace-inject-cpp/src/inject.h new file mode 100644 index 0000000..64341a5 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/inject.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +#include +#include + +#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& threads, + const std::string& library, const LogSink* log); diff --git a/includes/ptrace-inject-cpp/src/library.cpp b/includes/ptrace-inject-cpp/src/library.cpp new file mode 100644 index 0000000..4e6208b --- /dev/null +++ b/includes/ptrace-inject-cpp/src/library.cpp @@ -0,0 +1,131 @@ +#include "ptrace_inject.h" + +#include + +#include +#include +#include +#include +#include +#include + +#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 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); +} diff --git a/includes/ptrace-inject-cpp/src/log.cpp b/includes/ptrace-inject-cpp/src/log.cpp new file mode 100644 index 0000000..93078ec --- /dev/null +++ b/includes/ptrace-inject-cpp/src/log.cpp @@ -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); +} diff --git a/includes/ptrace-inject-cpp/src/log.h b/includes/ptrace-inject-cpp/src/log.h new file mode 100644 index 0000000..b58cab0 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/log.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +#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); diff --git a/includes/ptrace-inject-cpp/src/maps.cpp b/includes/ptrace-inject-cpp/src/maps.cpp new file mode 100644 index 0000000..03ef1f2 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/maps.cpp @@ -0,0 +1,93 @@ +#include "maps.h" + +#include +#include +#include +#include +#include + +#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 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 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)); +} diff --git a/includes/ptrace-inject-cpp/src/maps.h b/includes/ptrace-inject-cpp/src/maps.h new file mode 100644 index 0000000..956ea3e --- /dev/null +++ b/includes/ptrace-inject-cpp/src/maps.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +#include +#include +#include + +// One line of /proc//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 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); diff --git a/includes/ptrace-inject-cpp/src/memory.cpp b/includes/ptrace-inject-cpp/src/memory.cpp new file mode 100644 index 0000000..014ae76 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/memory.cpp @@ -0,0 +1,69 @@ +#include "memory.h" + +#include +#include + +#include +#include +#include +#include + +#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(buffer); + std::size_t done = 0; + while (done < length) { + const ssize_t n = + pread(fd, out + done, length - done, static_cast(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(n); + } +} + +void write_memory(int fd, std::uint64_t address, const void* buffer, + std::size_t length) { + const auto* in = static_cast(buffer); + std::size_t done = 0; + while (done < length) { + const ssize_t n = pwrite(fd, in + done, length - done, + static_cast(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(n); + } +} diff --git a/includes/ptrace-inject-cpp/src/memory.h b/includes/ptrace-inject-cpp/src/memory.h new file mode 100644 index 0000000..ba42e46 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/memory.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +#include +#include + +// Open /proc//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); diff --git a/includes/ptrace-inject-cpp/src/process_lookup.cpp b/includes/ptrace-inject-cpp/src/process_lookup.cpp new file mode 100644 index 0000000..44641f9 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/process_lookup.cpp @@ -0,0 +1,46 @@ +#include "process_lookup.h" + +#include +#include + +#include +#include +#include + +#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(std::stoi(pid_text)); + } + } + return -1; +} diff --git a/includes/ptrace-inject-cpp/src/process_lookup.h b/includes/ptrace-inject-cpp/src/process_lookup.h new file mode 100644 index 0000000..0adb4f8 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/process_lookup.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +#include + +// 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); diff --git a/includes/ptrace-inject-cpp/src/ptrace_utils.cpp b/includes/ptrace-inject-cpp/src/ptrace_utils.cpp new file mode 100644 index 0000000..a96676e --- /dev/null +++ b/includes/ptrace-inject-cpp/src/ptrace_utils.cpp @@ -0,0 +1,191 @@ +#include "ptrace_utils.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#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 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 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(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& 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& 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& 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(static_cast(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(); +} diff --git a/includes/ptrace-inject-cpp/src/ptrace_utils.h b/includes/ptrace-inject-cpp/src/ptrace_utils.h new file mode 100644 index 0000000..25bb2b3 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/ptrace_utils.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +#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& attached, + const LogSink* log); + +// Detach all threads. If signal != 0, deliver it to signal_tid on detach. +void detach_all_threads(std::vector& attached, pid_t signal_tid, + int signal, const LogSink* log); diff --git a/includes/ptrace-inject-cpp/src/symbols.cpp b/includes/ptrace-inject-cpp/src/symbols.cpp new file mode 100644 index 0000000..69da318 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/symbols.cpp @@ -0,0 +1,66 @@ +#include "symbols.h" + +#include +#include + +#include +#include +#include + +#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(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), + }; +} diff --git a/includes/ptrace-inject-cpp/src/symbols.h b/includes/ptrace-inject-cpp/src/symbols.h new file mode 100644 index 0000000..8ac6765 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/symbols.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +#include + +// 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); diff --git a/includes/ptrace-inject-cpp/src/util.cpp b/includes/ptrace-inject-cpp/src/util.cpp new file mode 100644 index 0000000..e214872 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/util.cpp @@ -0,0 +1,44 @@ +#include "util.h" + +#include +#include +#include +#include +#include +#include + +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(); +} diff --git a/includes/ptrace-inject-cpp/src/util.h b/includes/ptrace-inject-cpp/src/util.h new file mode 100644 index 0000000..abb3c10 --- /dev/null +++ b/includes/ptrace-inject-cpp/src/util.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +// 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//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); diff --git a/ptrace-inject-cpp b/ptrace-inject-cpp deleted file mode 160000 index 9d419c7..0000000 --- a/ptrace-inject-cpp +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9d419c7a856119100464af525b17afe22f6f8c58