Refactor: simplify injector/libinject/loader code

- libinject: drop debug cruft, dedup JNI overloads into jni_inject, const-correct inject()
- loader: reuse Utils::call_java_impl for JNI bootstrap
- JvmAttach: collapse acquire_jvm/env/jvmti retry loops into one template
- injector: remove redundant copy_arg wrapper
- DllMain: remove no-op DLL_THREAD cases, merge attach logs
- libagent: guard add_library so empty source dir does not break configure
This commit is contained in:
xiaozhou233 committed 2026-08-15 12:55:27 +08:00
1 parent a251b8996e
commit bcc1ecbf0e
6 files changed
+82 -181

No files matched your search

+3 -12
View File
@@ -23,15 +23,6 @@ static void execute_jps(void)
_pclose(pipe);
}
static void copy_arg(char* dst, size_t dst_size, const char* src)
{
int written = snprintf(dst, dst_size, "%s", src ? src : "");
if (written < 0 || (size_t)written >= dst_size)
{
printf("[-] Argument truncated to fit buffer.\n");
}
}
static int run(int argc, char** argv)
{
int pid = 0;
@@ -42,10 +33,10 @@ static int run(int argc, char** argv)
if (argc >= 3)
{
pid = atoi(argv[1]);
copy_arg(dll_path, sizeof(dll_path), argv[2]);
snprintf(dll_path, sizeof(dll_path), "%s", argv[2]);
if (argc >= 4)
{
copy_arg(injector_lib_path, sizeof(injector_lib_path), argv[3]);
snprintf(injector_lib_path, sizeof(injector_lib_path), "%s", argv[3]);
}
}
else
@@ -64,7 +55,7 @@ static int run(int argc, char** argv)
if (!GetCurrentDirectoryA(sizeof(cwd), cwd))
{
printf("[-] GetCurrentDirectory failed, using '.'\n");
copy_arg(cwd, sizeof(cwd), ".");
snprintf(cwd, sizeof(cwd), ".");
}
snprintf(dll_path, sizeof(dll_path), "%s\\libloader.dll", cwd);
printf("[*] Using DLL path: %s\n", dll_path);
+12 -10
View File
@@ -5,15 +5,17 @@ file(
${CMAKE_CURRENT_SOURCE_DIR}/*.c
)
add_library(agent SHARED ${agent_sources})
if (agent_sources)
add_library(agent SHARED ${agent_sources})
target_include_directories(agent PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_CURRENT_SOURCE_DIR}/includes
)
target_include_directories(agent PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_CURRENT_SOURCE_DIR}/includes
)
target_link_libraries(agent PRIVATE
jvm
)
target_link_libraries(agent PRIVATE
jvm
)
endif()
+39 -86
View File
@@ -1,14 +1,14 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <jni.h>
#include <ReflectiveDLLInjection/LoadLibraryR.h>
#define WIN_X64
#define BREAK_WITH_ERROR(e) { printf("[-] %s. Error=%lu\n", e, GetLastError()); break; }
__declspec(dllexport)
int inject(int pid, char *path, char *params){
int inject(int pid, const char *path, const char *params){
HANDLE hFile = NULL;
HANDLE hRemoteThread = NULL;
HANDLE hProcess = NULL;
@@ -21,34 +21,16 @@ int inject(int pid, char *path, char *params){
TOKEN_PRIVILEGES priv = {0};
BOOL bSuccess = FALSE;
printf("Injector process pointer size = %zu bytes\n", sizeof(void*));
do {
if (!params) {
printf("[!] No parameters provided\n");
}
/* open DLL file */
hFile = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
BREAK_WITH_ERROR("Failed to open DLL file");
/* Debug helper: print the path being opened and its absolute path */
char fullPath[MAX_PATH] = {0};
if (GetFullPathNameA(path, MAX_PATH, fullPath, NULL) != 0) {
printf("Injector GetFullPathNameA success: %s\n", fullPath);
} else {
printf("[*] Injector GetFullPathNameA failed: %lu\n", GetLastError());
}
/* Before CreateFileA, print which file we are about to open */
printf("[*] About to open DLL: %s\n", path);
/* after ReadFile (or after loading into lpBuffer), verify exports again on the buffer we actually read */
/* get file size */
dwLength = GetFileSize(hFile, NULL);
if (dwLength == INVALID_FILE_SIZE || dwLength == 0)
BREAK_WITH_ERROR("Failed to get DLL file size\n");
BREAK_WITH_ERROR("Failed to get DLL file size");
/* alloc local buffer and read file */
lpBuffer = HeapAlloc(GetProcessHeap(), 0, dwLength);
@@ -73,57 +55,27 @@ int inject(int pid, char *path, char *params){
if (!hProcess)
BREAK_WITH_ERROR("Failed to open target process");
/* detect target architecture */
BOOL targetIsWow64 = FALSE;
if (!IsWow64Process(hProcess, &targetIsWow64)) {
printf("IsWow64Process failed\n");
} else {
printf("Is target process wow64 = %d (TRUE means 32-bit process on 64-bit OS)\n", targetIsWow64);
}
/* write params to remote memory */
SIZE_T written = 0;
if (params) {
/* allocate remote memory for params */
lpRemoteParam = VirtualAllocEx(hProcess, NULL, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!lpRemoteParam)
BREAK_WITH_ERROR("VirtualAllocEx for remote param failed");
printf("remote param addr = %p\n", lpRemoteParam);
SIZE_T param_len = strlen(params) + 1;
if (param_len > MAX_PATH)
param_len = MAX_PATH;
if (!WriteProcessMemory(hProcess, lpRemoteParam, params, param_len, &written) || written != param_len)
BREAK_WITH_ERROR("WriteProcessMemory for remote param failed");
} else {
printf("No parameters provided; using null pointer\n");
}
/* read back some bytes to verify write */
{
char verify[MAX_PATH] = {0};
SIZE_T read = 0;
if (lpRemoteParam) {
if (ReadProcessMemory(hProcess, lpRemoteParam, verify, MAX_PATH, &read)) {
printf("[*] Read back remote param, ConfigDir=%s\n", verify);
} else {
printf("[-] ReadProcessMemory failed: %lu\n", GetLastError());
}
} else {
printf("[*] lpRemoteParam == NULL, skip verify\n");
}
}
/* call LoadRemoteLibraryR */
hRemoteThread = LoadRemoteLibraryR(hProcess, lpBuffer, dwLength, lpRemoteParam);
if (!hRemoteThread) {
/* library didn't set last error; print hint info we gathered */
printf("[-] LoadRemoteLibraryR returned NULL. GetLastError=%lu\n", GetLastError());
if (!hRemoteThread)
BREAK_WITH_ERROR("LoadRemoteLibraryR returned NULL");
}
printf("[+] DLL injected: '%s' into PID %lu, remote param at %p\n", path, dwProcessId, lpRemoteParam);
printf("[+] DLL injected: '%s' into PID %lu\n", path, dwProcessId);
/* wait for reflective loader thread to complete */
WaitForSingleObject(hRemoteThread, INFINITE);
@@ -157,47 +109,48 @@ int inject(int pid, char *path, char *params){
return bSuccess ? 0 : -1;
}
static jboolean jni_inject(JNIEnv* env, jint pid, jstring path, const char* config_dir) {
const char* dll_path = (*env)->GetStringUTFChars(env, path, NULL);
if (!dll_path)
return JNI_FALSE;
char params[MAX_PATH] = {0};
const char* inject_params = NULL;
if (config_dir) {
strncpy(params, config_dir, MAX_PATH - 1);
params[MAX_PATH - 1] = '\0';
inject_params = params;
}
int ret = inject(pid, dll_path, inject_params);
(*env)->ReleaseStringUTFChars(env, path, dll_path);
return (ret == 0) ? JNI_TRUE : JNI_FALSE;
}
/*
* JNI Function: inject(int pid)
* Note:
* JNI Function: inject(int pid, String path)
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2
(JNIEnv *env, jobject obj, jint pid, jstring path) {
(void)obj;
// Injection Path
const char* InjectionDLL = (*env)->GetStringUTFChars(env, path, NULL);
int ret = inject(pid, (char*)InjectionDLL, NULL);
(*env)->ReleaseStringUTFChars(env, path, InjectionDLL);
return (ret == 0) ? JNI_TRUE : JNI_FALSE;
return jni_inject(env, pid, path, NULL);
}
/*
* JNI Function: inject(int pid, String path)
* Param pid: target process id
* Param path: path of inject dll
* Param configDir: path of config file (toml)
* JNI Function: inject(int pid, String path, String configDir)
* configDir: path of config file (toml)
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2Ljava_lang_String_2
(JNIEnv *env, jobject obj, jint pid , jstring path, jstring configDir){
(JNIEnv *env, jobject obj, jint pid, jstring path, jstring configDir) {
(void)obj;
const char* InjectionDLL = (*env)->GetStringUTFChars(env, path, NULL);
const char* ConfigDir = (*env)->GetStringUTFChars(env, configDir, NULL);
char params[MAX_PATH] = {0}; /* use a real buffer */
strncpy(params, ConfigDir ? ConfigDir : "", MAX_PATH - 1);
params[MAX_PATH - 1] = '\0';
int ret = inject(pid, (char*)InjectionDLL, params);
(*env)->ReleaseStringUTFChars(env, path, InjectionDLL);
(*env)->ReleaseStringUTFChars(env, configDir, ConfigDir);
return (ret == 0) ? JNI_TRUE : JNI_FALSE;
const char* config_dir = (*env)->GetStringUTFChars(env, configDir, NULL);
jboolean result = jni_inject(env, pid, path, config_dir);
(*env)->ReleaseStringUTFChars(env, configDir, config_dir);
return result;
}
/// ================ FindWindowsByTitle =================
/* ================ FindWindowsByTitle ================= */
#define MAX_RESULTS 128
typedef struct {
@@ -209,7 +162,6 @@ static wchar_t g_keyword[256];
static WindowData g_results[MAX_RESULTS];
static int g_count = 0;
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
(void)lParam;
wchar_t title[256];
@@ -222,6 +174,7 @@ BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
if (g_count < MAX_RESULTS && pid) {
wcsncpy(g_results[g_count].title, title, 255);
g_results[g_count].title[255] = L'\0';
g_results[g_count].pid = pid;
g_count++;
}
@@ -256,4 +209,4 @@ JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorN
return array;
}
/// ===============================================================================
/* ====================================================== */
+2 -30
View File
@@ -11,40 +11,12 @@ namespace JuiceAgent::Loader {
static bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& config) {
const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap";
const char* method_name = "start";
const char* method_desc = "(Ljava/lang/String;)V";
using JuiceAgent::Utils::check_and_clear_exception;
// Find Java class
JuiceAgent::Utils::LocalRef<jclass> cls(env, env->FindClass(bootstrap_class));
if (!cls.get() || check_and_clear_exception(env, "FindClass")) {
spdlog::error("Failed to find class: {}", bootstrap_class);
return false;
}
// Find static method
jmethodID method_id = env->GetStaticMethodID(cls, method_name, method_desc);
if (!method_id || check_and_clear_exception(env, "GetStaticMethodID")) {
spdlog::error("Failed to find method: {}", method_name);
return false;
}
// Serialize InjectionInfo to string
std::string args = JuiceAgent::Config::Utils::serialize_loader_config(config);
spdlog::debug("Invoke args: {}", args);
// Create Java string
jstring jArgs = env->NewStringUTF(args.c_str());
if (!jArgs || check_and_clear_exception(env, "NewStringUTF")) {
spdlog::error("Failed to create jstring");
return false;
}
// Call the static method
env->CallStaticVoidMethod(cls, method_id, jArgs);
// Check for exceptions
if (check_and_clear_exception(env, "CallStaticVoidMethod")) {
if (!JuiceAgent::Utils::call_java_impl(env, bootstrap_class, method_name, args.c_str())) {
spdlog::error("Failed to init JuiceAgent!");
return false;
}
+23 -29
View File
@@ -61,53 +61,47 @@ private:
std::this_thread::sleep_for(std::chrono::milliseconds(retry_delay_ms_));
}
bool acquire_jvm() {
template<typename Fn>
bool acquire(const char* what, Fn&& attempt) {
for (int i = 1; i <= max_try_; i++) {
jint status = JNI_GetCreatedJavaVMs(&jvm_, 1, nullptr);
if (status == JNI_OK && jvm_ != nullptr) {
spdlog::debug("Got JavaVM");
if (attempt()) {
return true;
}
retry("JavaVM", i);
retry(what, i);
}
return false;
}
bool acquire_jvm() {
return acquire("JavaVM", [this] {
jvm_ = nullptr;
return JNI_GetCreatedJavaVMs(&jvm_, 1, nullptr) == JNI_OK && jvm_ != nullptr;
});
}
bool acquire_env() {
for (int i = 1; i <= max_try_; i++) {
jint status = jvm_->GetEnv(reinterpret_cast<void**>(&env_), JNI_VERSION_1_6);
if (status == JNI_OK && env_ != nullptr) {
spdlog::debug("Got JNIEnv (already attached)");
return acquire("JNIEnv", [this] {
env_ = nullptr;
if (jvm_->GetEnv(reinterpret_cast<void**>(&env_), JNI_VERSION_1_6) == JNI_OK && env_ != nullptr) {
return true;
}
status = jvm_->AttachCurrentThread(reinterpret_cast<void**>(&env_), nullptr);
if (status == JNI_OK && env_ != nullptr) {
env_ = nullptr;
if (jvm_->AttachCurrentThread(reinterpret_cast<void**>(&env_), nullptr) == JNI_OK && env_ != nullptr) {
attached_ = true;
spdlog::debug("Attached current thread");
return true;
}
retry("JNIEnv attach", i);
}
return false;
env_ = nullptr;
return false;
});
}
bool acquire_jvmti() {
for (int i = 1; i <= max_try_; i++) {
jint status = jvm_->GetEnv(reinterpret_cast<void**>(&jvmti_), JVMTI_VERSION_1_2);
if (status == JNI_OK && jvmti_ != nullptr) {
spdlog::debug("Got JVMTI");
return true;
}
retry("JVMTI", i);
}
return false;
return acquire("JVMTI", [this] {
jvmti_ = nullptr;
return jvm_->GetEnv(reinterpret_cast<void**>(&jvmti_), JVMTI_VERSION_1_2) == JNI_OK && jvmti_ != nullptr;
});
}
};
+3 -14
View File
@@ -9,22 +9,11 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) {
DisableThreadLibraryCalls(hinstDLL);
Logger::init("libloader.log");
spdlog::info("DllMain: DLL_PROCESS_ATTACH");
// Get the runtime directory from the lpReserved parameter
const char* runtime_dir = (const char*)lpReserved;
spdlog::info("DllMain: runtime_dir: {}", runtime_dir);
// lpReserved carries the runtime directory from the reflective loader
const char* runtime_dir = (const char*)lpReserved;
spdlog::info("DllMain: DLL_PROCESS_ATTACH, runtime_dir: {}", runtime_dir);
JuiceAgent::Loader::entrypoint(runtime_dir);
break;
}
case DLL_THREAD_ATTACH: {
break;
}
case DLL_THREAD_DETACH: {
break;
}