Merge pull request #2 from xiaozhou233/dev

[Dev -> Main] Refactor Code
This commit is contained in:
xiaozhou233 authored and GitHub committed 2025-11-21 23:32:35 +08:00
commit 63c9e55355
31 files changed
+231 -727

No files matched your search

+6 -22
View File
@@ -4,34 +4,18 @@ project(JuiceAgent LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# version
set(PROJECT_VERSION_MAJOR 2)
set(PROJECT_VERSION_MINOR 0)
set(PROJECT_BUILD_NUMBER 1)
set(PROJECT_VERSION_STRING "v${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}-b${PROJECT_BUILD_NUMBER}")
message(STATUS " ======== Build version: ${PROJECT_VERSION_STRING} ======== ")
add_compile_definitions(
PROJECT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
PROJECT_VERSION_MINOR=${PROJECT_VERSION_MINOR}
PROJECT_BUILD_NUMBER=${PROJECT_BUILD_NUMBER}
PROJECT_VERSION_STRING=\"${PROJECT_VERSION_STRING}\")
# output directories
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
# includes
set(INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}/includes)
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
link_directories("$ENV{JAVA_HOME}/lib")
# libraries
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/includes/ReflectiveDLLInjection)
include(cmake/JuiceModule.cmake)
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
# modules
add_juice_module(agent)
add_juice_module(injector)
add_juice_module(juiceloader)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/executable)
add_subdirectory(${SRC_DIR}/libagent)
add_subdirectory(${SRC_DIR}/libinjector)
add_subdirectory(${SRC_DIR}/libjuiceloader)
-37
View File
@@ -1,37 +0,0 @@
# JuiceModule.cmake
# Function to add a JuiceAgent module (agent, injector, juiceloader)
function(add_juice_module NAME)
link_directories("$ENV{JAVA_HOME}/lib")
# Collect all source files in module src and utils
file(GLOB MODULE_SOURCES
"${CMAKE_SOURCE_DIR}/src/${NAME}/*.c"
"${CMAKE_SOURCE_DIR}/src/${NAME}/*.cpp"
"${CMAKE_SOURCE_DIR}/src/${NAME}/utils/*.c"
"${CMAKE_SOURCE_DIR}/src/${NAME}/utils/*.cpp"
)
# Create shared library
add_library(${NAME} SHARED ${MODULE_SOURCES})
# Include directories
target_include_directories(${NAME} PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_SOURCE_DIR}/includes/JuiceAgent
${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection
${CMAKE_SOURCE_DIR}/includes/log.c
"${CMAKE_SOURCE_DIR}/src/${NAME}/utils"
"${CMAKE_SOURCE_DIR}/src/${NAME}/include"
)
# Link common libraries
target_link_libraries(${NAME} PRIVATE
ReflectiveDLLInjection
jvm
)
add_subdirectory("${CMAKE_SOURCE_DIR}/src/${NAME}")
endfunction()
-8
View File
@@ -1,8 +0,0 @@
# config.toml
JuiceLoaderJarPath = "D:\\Development\\JuiceLoader\\JuiceLoader.jar"
JuiceLoaderLibraryPath = ""
InjectionDir = "D:\\Development\\JuiceLoader\\injection"
EntryJarPath = "D:\\Development\\JuiceLoader\\Entry.jar"
EntryClass = "cn.xiaozhou233.test.Entry"
EntryMethod = "start"
+1 -5
View File
@@ -1,11 +1,7 @@
#ifndef JUICEAGENT_H
#define JUICEAGENT_H
#define INJECT_PATH_MAX 4096
typedef struct InjectParams{
char ConfigDir[INJECT_PATH_MAX];
} InjectParams;
#define INJECT_PATH_MAX 260
typedef struct _InjectionInfo {
char BootstrapAPIPath[INJECT_PATH_MAX];
-33
View File
@@ -1,33 +0,0 @@
package cn.xiaozhou233.juiceloader;
public class JuiceLoader {
// Init jni/jvmti, and register events
public static native boolean init();
// Add jar to Bootstrap ClassLoader
public static native boolean injectJar(String jarPath);
// Redefine class
// Notice: classname is the full name of the class, e.g. "java/lang/String"
public static native boolean redefineClass(Class<?> clazz, byte[] classBytes, int length);
public static native boolean redefineClassByName(String className, byte[] classBytes, int length);
// Get Classes
public static native Class<?>[] getLoadedClasses();
// Get ClassBytes
public static native byte[] getClassBytes(Class<?> clazz);
public static native byte[] getClassBytesByName(String className);
// Retransform
public static native boolean retransformClass(Class<?> clazz, byte[] classBytes, int length);
public static native boolean retransformClassByName(String className, byte[] classBytes, int length);
// Get Class
public static native Class<?> getClassByName(String className);
// Thread/Inject
public static native Thread nativeGetThreadByName(String name);
public static native ClassLoader nativeInjectJarToThread(Thread thread, String jarPath);
}
+1 -1
View File
@@ -20,4 +20,4 @@ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-1
View File
@@ -1 +0,0 @@
# src/agent/CMakeLists.txt
-22
View File
@@ -1,22 +0,0 @@
#ifndef DATAUTILS_H
#define DATAUTILS_H
#include <string.h>
#include "InjectParameters.h"
#include "tomlc17.h"
#include "log.h"
typedef struct _InjectionInfo {
char BootstrapAPIPath[INJECT_PATH_MAX];
char JuiceLoaderJarPath[INJECT_PATH_MAX];
char EntryJarPath[INJECT_PATH_MAX];
char EntryClass[INJECT_PATH_MAX];
char EntryMethod[INJECT_PATH_MAX];
char InjectionDir[INJECT_PATH_MAX];
} InjectionInfoType;
extern InjectionInfoType InjectionInfo;
void safe_copy(char *dest, const char *src, size_t dest_size);
bool ReadInjectionInfo(toml_result_t result, InjectParameters* params);
#endif // DATAUTILS_H
-9
View File
@@ -1,9 +0,0 @@
#ifndef JAVAUTILS_H
#define JAVAUTILS_H
#include <jni.h>
#include <jvmti.h>
char* get_class_name(JNIEnv* env, jclass clazz);
#endif //JAVAUTILS_H
-13
View File
@@ -1,13 +0,0 @@
#ifndef GLOBALUTILS_H
#define GLOBALUTILS_H
#include "windows.h"
#include "stdio.h"
#include "jni.h"
#include "jvmti.h"
jint GetCreatedJVM(JavaVM**);
jint GetJNIEnv(JavaVM*, JNIEnv**);
jint GetJVMTI(JavaVM*, jvmtiEnv**);
#endif
-53
View File
@@ -1,53 +0,0 @@
/*
Author: xiaozhou233 (xiaozhou233@vip.qq.com)
File: datautils.c
Desc: data utils
*/
#include "datautils.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "tomlc17.h"
#include "juiceloader.h"
void safe_copy(char *dest, const char *src, size_t dest_size) {
if (!dest || dest_size == 0) return;
strncpy(dest, src, dest_size - 1);
dest[dest_size - 1] = '\0';
}
static void GetTomlStringOrDefault(toml_datum_t tableDatum, const char* key, const char* defaultVal, char* outBuf, size_t bufSize) {
toml_datum_t datum = toml_seek(tableDatum, key);
if (datum.type != TOML_STRING || !datum.u.s || datum.u.s[0] == '\0') {
safe_copy(outBuf, defaultVal, bufSize);
} else {
safe_copy(outBuf, datum.u.s, bufSize);
}
}
bool ReadInjectionInfo(toml_result_t result, InjectParameters* params) {
if (!result.ok) return false;
toml_datum_t InjectionTree = toml_seek(result.toptab, "Injection");
if (InjectionTree.type != TOML_TABLE) {
log_error("Injection section missing");
return false;
}
char tmp[INJECT_PATH_MAX];
snprintf(tmp, sizeof(tmp), "%s\\JuiceLoader.jar", params->ConfigDir);
GetTomlStringOrDefault(InjectionTree, "JuiceLoaderJarPath", tmp, InjectionInfo.JuiceLoaderJarPath, INJECT_PATH_MAX);
snprintf(tmp, sizeof(tmp), "%s\\entry.jar", params->ConfigDir);
GetTomlStringOrDefault(InjectionTree, "EntryJarPath", tmp, InjectionInfo.EntryJarPath, INJECT_PATH_MAX);
GetTomlStringOrDefault(InjectionTree, "EntryClass", "cn.xiaozhou233.juiceloader.entry.Entry", InjectionInfo.EntryClass, INJECT_PATH_MAX);
GetTomlStringOrDefault(InjectionTree, "EntryMethod", "start", InjectionInfo.EntryMethod, INJECT_PATH_MAX);
snprintf(tmp, sizeof(tmp), "%s\\injection", params->ConfigDir);
GetTomlStringOrDefault(InjectionTree, "InjectionDir", tmp, InjectionInfo.InjectionDir, INJECT_PATH_MAX);
return true;
}
-16
View File
@@ -1,16 +0,0 @@
#include "javautils.h"
#include <jni.h>
#include <jvmti.h>
#include <string.h>
char* get_class_name(JNIEnv* env, jclass clazz) {
jclass clsClass = (*env)->FindClass(env, "java/lang/Class");
jmethodID mid_getName = (*env)->GetMethodID(env, clsClass, "getName", "()Ljava/lang/String;");
jstring nameStr = (jstring)(*env)->CallObjectMethod(env, clazz, mid_getName);
const char* temp = (*env)->GetStringUTFChars(env, nameStr, NULL);
char* result = strdup(temp);
(*env)->ReleaseStringUTFChars(env, nameStr, temp);
(*env)->DeleteLocalRef(env, nameStr);
return result;
}
-8
View File
@@ -1,8 +0,0 @@
# src/executable/CMakeLists.txt
add_executable(injector_executable injector.c)
target_include_directories(injector_executable PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/JuiceAgent
)
-117
View File
@@ -1,117 +0,0 @@
/* injector_client.c
Console injector client in C.
Usage:
injector_client.exe <pid> <dll_path_to_inject> [injector_lib_path]
If pid not provided, program runs "jps -l" and prompts for PID.
*/
/* Comments in code are in English as requested. */
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PATH_LEN 4096
/* Execute "jps -l" to help find JVM PIDs. */
static void ExecuteJps(void) {
/* Use _popen to run jps -l and print output */
FILE *pipe = _popen("jps -l", "r");
if (!pipe) {
printf("Error: failed to run jps -l (is JDK's bin on PATH?).\n");
return;
}
printf("=== jps -l output ===\n");
char buf[256];
while (fgets(buf, sizeof(buf), pipe) != NULL) {
fputs(buf, stdout);
}
printf("=====================\n");
_pclose(pipe);
}
int main(int argc, char **argv) {
int pid = 0;
char dll_path[MAX_PATH_LEN] = {0};
char injector_lib_path[MAX_PATH_LEN] = {0};
char cwd[MAX_PATH_LEN] = {0};
/* If user provided pid and dll path as arguments, use them. */
if (argc >= 3) {
pid = atoi(argv[1]);
strncpy(dll_path, argv[2], MAX_PATH_LEN - 1);
if (argc >= 4) {
strncpy(injector_lib_path, argv[3], MAX_PATH_LEN - 1);
}
} else {
/* Show jps output to help user find JVM PID */
ExecuteJps();
printf("Input PID: ");
if (scanf("%d", &pid) != 1 || pid <= 0) {
printf("Invalid PID input.\n");
return 1;
}
/* Default dll_path = currentdir\\libagent.dll */
if (!GetCurrentDirectoryA(MAX_PATH_LEN, cwd)) {
printf("Warning: GetCurrentDirectory failed, using '.'\n");
strncpy(cwd, ".", MAX_PATH_LEN - 1);
}
snprintf(dll_path, MAX_PATH_LEN, "%s\\libagent.dll", cwd);
printf("Using DLL path: %s\n", dll_path);
}
if (pid <= 0) {
printf("Invalid or missing PID.\n");
return 1;
}
/* Load injector library */
HMODULE hLib = NULL;
if (injector_lib_path[0] != '\0') {
hLib = LoadLibraryA(injector_lib_path);
if (!hLib) {
printf("[-] Failed to load injector library: %s (Error=%lu)\n", injector_lib_path, GetLastError());
return 2;
}
} else {
/* Try to load by name from current dir / PATH */
hLib = LoadLibraryA("libinjector.dll");
if (!hLib) {
printf("[-] Failed to load libinjector.dll by name (Error=%lu).\n", GetLastError());
printf(" Provide full path as the 3rd argument if needed.\n");
return 2;
}
}
printf("[+] Loaded injector library.\n");
/* Define function pointer type (cdecl) - match the DLL export */
typedef int (__cdecl *inject_fn_t)(int, const char*, void*);
/* GetProcAddress for 'inject' */
FARPROC proc = GetProcAddress(hLib, "inject");
if (!proc) {
/* Try common alternative name */
proc = GetProcAddress(hLib, "Inject");
}
if (!proc) {
printf("[-] GetProcAddress failed for 'inject' (Error=%lu). Make sure your injector exports C symbol 'inject'.\n", GetLastError());
FreeLibrary(hLib);
return 3;
}
inject_fn_t inject = (inject_fn_t)proc;
printf("[*] Calling inject(pid=%d, dllPath=\"%s\", NULL)\n", pid, dll_path);
int ret = inject(pid, dll_path, NULL);
if (ret == 0) {
printf("[+] inject returned success (0)\n");
} else {
printf("[-] inject returned failure (%d)\n", ret);
}
FreeLibrary(hLib);
return (ret == 0) ? 0 : 4;
}
-1
View File
@@ -1 +0,0 @@
# src/injector/CMakeLists.txt
-37
View File
@@ -1,37 +0,0 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class cn_xiaozhou233_juiceagent_injector_InjectorNative */
#ifndef _Included_cn_xiaozhou233_juiceagent_injector_InjectorNative
#define _Included_cn_xiaozhou233_juiceagent_injector_InjectorNative
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: cn_xiaozhou233_juiceagent_injector_InjectorNative
* Method: inject
* Signature: (ILjava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2
(JNIEnv *, jobject, jint, jstring);
/*
* Class: cn_xiaozhou233_juiceagent_injector_InjectorNative
* Method: inject
* Signature: (ILjava/lang/String;Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2Ljava_lang_String_2
(JNIEnv *, jobject, jint, jstring, jstring);
/*
* Class: cn_xiaozhou233_juiceagent_injector_InjectorNative
* Method: findWindowsByTitle
* Signature: (Ljava/lang/String;)[Lcn/xiaozhou233/juiceagent/injector/InjectorNative/WindowInfo;
*/
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_findWindowsByTitle
(JNIEnv *, jclass, jstring);
#ifdef __cplusplus
}
#endif
#endif
-10
View File
@@ -1,10 +0,0 @@
#ifndef INJECTOR_UTILS_H
#define INJECTOR_UTILS_H
#include "windows.h"
WORD get_pe_machine(LPVOID, DWORD);
BOOL has_reflective_loader_export(LPVOID, DWORD);
const char* machine_to_str(WORD);
#endif
-104
View File
@@ -1,104 +0,0 @@
#include "InjectorUtils.h"
/* Helpers: parse PE header to get Machine and check for ReflectiveLoader export */
/* return IMAGE_FILE_MACHINE_* value or 0 on error */
WORD get_pe_machine(LPVOID buffer, DWORD length) {
if (!buffer || length < sizeof(IMAGE_DOS_HEADER)) return 0;
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)buffer;
if (dos->e_magic != IMAGE_DOS_SIGNATURE) return 0;
if ((DWORD)dos->e_lfanew + sizeof(IMAGE_NT_HEADERS) > length) return 0;
PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)((BYTE*)buffer + dos->e_lfanew);
if (nt->Signature != IMAGE_NT_SIGNATURE) return 0;
return nt->FileHeader.Machine;
}
/* return TRUE if export table contains "ReflectiveLoader" */
BOOL has_reflective_loader_export(LPVOID buffer, DWORD length) {
if (!buffer || length < sizeof(IMAGE_DOS_HEADER)) return FALSE;
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)buffer;
if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)((BYTE*)buffer + dos->e_lfanew);
if (nt->Signature != IMAGE_NT_SIGNATURE) return FALSE;
DWORD exportRVA = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
DWORD exportSize = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
if (!exportRVA || exportSize == 0) return FALSE;
// Need to convert RVA -> raw offset: iterate sections
PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(nt);
WORD numberOfSections = nt->FileHeader.NumberOfSections;
DWORD exportOffset = 0;
for (WORD i = 0; i < numberOfSections; ++i) {
DWORD va = section[i].VirtualAddress;
DWORD vs = section[i].Misc.VirtualSize;
DWORD ptr = section[i].PointerToRawData;
DWORD size = section[i].SizeOfRawData;
if (exportRVA >= va && exportRVA < va + vs) {
exportOffset = ptr + (exportRVA - va);
break;
}
}
if (!exportOffset) return FALSE;
if ((DWORD)exportOffset + sizeof(IMAGE_EXPORT_DIRECTORY) > length) return FALSE;
PIMAGE_EXPORT_DIRECTORY exp = (PIMAGE_EXPORT_DIRECTORY)((BYTE*)buffer + exportOffset);
if (exp->NumberOfNames == 0) return FALSE;
// locate arrays
DWORD addrOfNamesRVA = exp->AddressOfNames;
DWORD addrOfNameOrdinalsRVA = exp->AddressOfNameOrdinals;
if (!addrOfNamesRVA || !addrOfNameOrdinalsRVA) return FALSE;
// find raw offsets for these arrays
DWORD namesOffset = 0;
DWORD ordinalsOffset = 0;
for (WORD i = 0; i < numberOfSections; ++i) {
DWORD va = section[i].VirtualAddress;
DWORD vs = section[i].Misc.VirtualSize;
DWORD ptr = section[i].PointerToRawData;
if (addrOfNamesRVA >= va && addrOfNamesRVA < va + vs) {
namesOffset = ptr + (addrOfNamesRVA - va);
}
if (addrOfNameOrdinalsRVA >= va && addrOfNameOrdinalsRVA < va + vs) {
ordinalsOffset = ptr + (addrOfNameOrdinalsRVA - va);
}
}
if (!namesOffset || !ordinalsOffset) return FALSE;
if ((DWORD)namesOffset + exp->NumberOfNames * sizeof(DWORD) > length) return FALSE;
if ((DWORD)ordinalsOffset + exp->NumberOfNames * sizeof(WORD) > length) return FALSE;
// iterate names
for (DWORD i = 0; i < exp->NumberOfNames; ++i) {
DWORD nameRVA = *(DWORD*)((BYTE*)buffer + namesOffset + i * sizeof(DWORD));
// convert nameRVA to raw offset
DWORD nameOffset = 0;
for (WORD s = 0; s < numberOfSections; ++s) {
DWORD va = section[s].VirtualAddress;
DWORD vs = section[s].Misc.VirtualSize;
DWORD ptr = section[s].PointerToRawData;
if (nameRVA >= va && nameRVA < va + vs) {
nameOffset = ptr + (nameRVA - va);
break;
}
}
if (!nameOffset) continue;
if ((DWORD)nameOffset >= length) continue;
char *name = (char*)((BYTE*)buffer + nameOffset);
// safe compare - ensure string is within buffer
size_t maxlen = length - nameOffset;
if (strncasecmp(name, "ReflectiveLoader", maxlen) == 0) return TRUE;
}
return FALSE;
}
/* Pretty-print machine */
const char* machine_to_str(WORD machine) {
switch(machine) {
case IMAGE_FILE_MACHINE_I386: return "x86 (IMAGE_FILE_MACHINE_I386)";
case IMAGE_FILE_MACHINE_AMD64: return "x64 (IMAGE_FILE_MACHINE_AMD64)";
case IMAGE_FILE_MACHINE_ARM: return "ARM";
case IMAGE_FILE_MACHINE_ARM64: return "ARM64";
default: return "Unknown";
}
}
-1
View File
@@ -1 +0,0 @@
# src/juiceloader/CMakeLists.txt
+20
View File
@@ -0,0 +1,20 @@
file(
GLOB_RECURSE
agent_sources
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/*.c
)
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_link_libraries(agent PRIVATE
ReflectiveDLLInjection
jvm
)
+37
View File
@@ -0,0 +1,37 @@
#include <windows.h>
#include <JuiceAgent/Logger.hpp>
#include <libagent.h>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
switch( fdwReason )
{
case DLL_PROCESS_ATTACH: {
InitLogger();
PLOGI << "DllMain: DLL_PROCESS_ATTACH";
PLOGD.printf("lpReserved: %p", lpReserved);
const char* runtime_dir = (const char*)lpReserved;
PLOGD << "runtime_dir: " << runtime_dir;
InitJuiceAgent(runtime_dir);
break;
}
case DLL_THREAD_ATTACH: {
break;
}
case DLL_THREAD_DETACH: {
break;
}
case DLL_PROCESS_DETACH: {
PLOGI << "DllMain: DLL_PROCESS_DETACH";
PLOGD.printf("lpReserved: %p", lpReserved);
break;
}
}
return TRUE;
}
@@ -28,7 +28,7 @@
#include "ReflectiveLoader.h"
#define WIN_X64
#define REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
//===============================================================================================//
// Our loader will set this to a pseudo correct HINSTANCE/HMODULE value
+10
View File
@@ -0,0 +1,10 @@
#ifndef LIBAGENT_H
#define LIBAGENT_H
#include <stdbool.h>
extern "C" __declspec(dllexport)
bool InitJuiceAgent(const char* runtime_path);
#endif // LIBAGENT_H
@@ -1,11 +1,11 @@
#include <windows.h>
#include "Logger.hpp"
#include <JuiceAgent.h>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
#include <stdio.h>
#include <JuiceAgent/Logger.hpp>
#include <libagent.h>
#include <thread>
#include <tinytoml/toml.h>
// For Java VM
#include <jni.h>
#include <jvmti.h>
#include <JuiceAgent/JuiceAgent.h>
struct _JuiceAgent {
bool isAttached;
@@ -16,6 +16,60 @@ struct _JuiceAgent {
InjectionInfoType InjectionInfo;
static int ReadConfig(const char* ConfigDir)
{
// ConfigDir/config.toml
std::string path = std::string(ConfigDir) + "\\config.toml";
std::ifstream ifs(path);
if (!ifs) return -1;
// Parse toml
toml::ParseResult pr = toml::parse(ifs);
if (!pr.valid()) return -2;
const toml::Value& tbl = pr.value;
// Helper function: get string from toml
auto get_str = [&](const char* key, const char* def, char* out) {
const toml::Value* v = tbl.find(key);
if (v && v->is<std::string>()) {
std::string s = v->as<std::string>();
if (!s.empty()) {
strncpy(out, s.c_str(), INJECT_PATH_MAX - 1);
PLOGD << "Found parameter: " << key << " = " << s.c_str();
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Parameter " << key << " is empty, use default: " << def;
}
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Not found parameter: " << key << ", use default: " << def;
}
out[INJECT_PATH_MAX - 1] = '\0';
};
// Default values
std::string defaultJuiceLoader = std::string(ConfigDir) + "\\JuiceLoader.jar";
std::string defaultJuiceLoaderLibrary = std::string(ConfigDir) + "\\libjuiceloader.dll";
std::string defaultEntryJar = std::string(ConfigDir) + "\\Entry.jar";
std::string defaultInjectionDir = std::string(ConfigDir) + "\\injection";
get_str("JuiceLoaderJarPath", defaultJuiceLoader.c_str(), InjectionInfo.JuiceLoaderJarPath);
get_str("JuiceLoaderLibraryPath", defaultJuiceLoaderLibrary.c_str(), InjectionInfo.JuiceLoaderLibraryPath);
get_str("InjectionDir", defaultInjectionDir.c_str(), InjectionInfo.InjectionDir);
get_str("EntryJarPath", defaultEntryJar.c_str(), InjectionInfo.EntryJarPath);
get_str("EntryClass", "cn.xiaozhou233.test.Entry", InjectionInfo.EntryClass);
get_str("EntryMethod", "start", InjectionInfo.EntryMethod);
PLOGD << "JuiceLoaderJarPath: " << InjectionInfo.JuiceLoaderJarPath;
PLOGD << "JuiceLoaderLibraryPath: " << InjectionInfo.JuiceLoaderLibraryPath;
PLOGD << "InjectionDir: " << InjectionInfo.InjectionDir;
PLOGD << "EntryJarPath: " << InjectionInfo.EntryJarPath;
PLOGD << "EntryClass: " << InjectionInfo.EntryClass;
PLOGD << "EntryMethod: " << InjectionInfo.EntryMethod;
return 0;
}
static int GetJavaEnv() {
jint res = JNI_ERR;
@@ -32,7 +86,7 @@ static int GetJavaEnv() {
PLOGE.printf("JNI_GetCreatedJavaVMs failed: %d", res);
PLOGD << "JVM NULL: " << (jvm == NULL);
}
Sleep(1000);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (jvm != NULL) {
break;
@@ -61,7 +115,7 @@ static int GetJavaEnv() {
return res;
}
}
Sleep(1000);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (env != NULL) {
break;
@@ -152,176 +206,46 @@ static int InvokeJuiceLoaderInit(const char* ConfigDir) {
return 0;
}
static int ReadConfig(const char* ConfigDir)
{
// ConfigDir/config.toml
std::string path = std::string(ConfigDir) + "\\config.toml";
std::ifstream ifs(path);
if (!ifs) return -1;
extern "C" __declspec(dllexport)
bool InitJuiceAgent(const char* runtime_path) {
PLOGI << "--------> InitJuiceAgent Invoke <--------";
PLOGD << "runtime_path: " << runtime_path;
// Parse toml
toml::ParseResult pr = toml::parse(ifs);
if (!pr.valid()) return -2;
const toml::Value& tbl = pr.value;
// Helper function: get string from toml
auto get_str = [&](const char* key, const char* def, char* out) {
const toml::Value* v = tbl.find(key);
if (v && v->is<std::string>()) {
std::string s = v->as<std::string>();
if (!s.empty()) {
strncpy(out, s.c_str(), INJECT_PATH_MAX - 1);
PLOGD << "Found parameter: " << key << " = " << s.c_str();
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Parameter " << key << " is empty, use default: " << def;
}
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Not found parameter: " << key << ", use default: " << def;
}
out[INJECT_PATH_MAX - 1] = '\0';
};
// Default values
std::string defaultJuiceLoader = std::string(ConfigDir) + "\\JuiceLoader.jar";
std::string defaultJuiceLoaderLibrary = std::string(ConfigDir) + "\\libjuiceloader.dll";
std::string defaultEntryJar = std::string(ConfigDir) + "\\Entry.jar";
std::string defaultInjectionDir = std::string(ConfigDir) + "\\injection";
get_str("JuiceLoaderJarPath", defaultJuiceLoader.c_str(), InjectionInfo.JuiceLoaderJarPath);
get_str("JuiceLoaderLibraryPath", defaultJuiceLoaderLibrary.c_str(), InjectionInfo.JuiceLoaderLibraryPath);
get_str("InjectionDir", defaultInjectionDir.c_str(), InjectionInfo.InjectionDir);
get_str("EntryJarPath", defaultEntryJar.c_str(), InjectionInfo.EntryJarPath);
get_str("EntryClass", "cn.xiaozhou233.test.Entry", InjectionInfo.EntryClass);
get_str("EntryMethod", "start", InjectionInfo.EntryMethod);
PLOGD << "JuiceLoaderJarPath: " << InjectionInfo.JuiceLoaderJarPath;
PLOGD << "JuiceLoaderLibraryPath: " << InjectionInfo.JuiceLoaderLibraryPath;
PLOGD << "InjectionDir: " << InjectionInfo.InjectionDir;
PLOGD << "EntryJarPath: " << InjectionInfo.EntryJarPath;
PLOGD << "EntryClass: " << InjectionInfo.EntryClass;
PLOGD << "EntryMethod: " << InjectionInfo.EntryMethod;
return 0;
}
int InitJuiceAgent(const char* ConfigDir) {
// Variables
int result = JNI_ERR;
// Step 0: Read Config
if (ReadConfig(ConfigDir) != 0) {
PLOGE << "Failed to read config";
return 1;
// Read Config
PLOGI << "ReadConfig ...";
if (ReadConfig(runtime_path) != 0) {
PLOGE << "ReadConfig failed";
return false;
}
PLOGI << "[OK] ReadConfig";
// Step 1: Get the Java environment
// Get JavaEnv
PLOGI << "Get JavaEnv ...";
if (GetJavaEnv() != 0) {
PLOGE << "Failed to get Java environment code=" << result;
return 1;
PLOGE << "GetJavaEnv failed";
return false;
}
PLOGI << "[OK] Get JavaEnv";
// Step 2: Inject JuiceLoader.jar
result = JuiceAgent.jvmti->AddToSystemClassLoaderSearch(InjectionInfo.JuiceLoaderJarPath);
if (result != JNI_OK) {
PLOGE.printf("AddToSystemClassLoaderSearch failed: %d", result);
return 1;
// Inject JuiceLoader jar
PLOGI << "Inject JuiceLoader jar ...";
if (JuiceAgent.jvmti->AddToSystemClassLoaderSearch(InjectionInfo.JuiceLoaderJarPath) != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed";
return false;
}
PLOGI << "[OK] Inject JuiceLoader jar";
// Step 3: Invoke JuiceLoader Init
if (InvokeJuiceLoaderInit(ConfigDir) != 0) {
PLOGE << "Failed to invoke JuiceLoader Init code=" << result;
return 1;
// Invoke JuiceLoader Init
PLOGI << "Invoke JuiceLoader Init ...";
if (InvokeJuiceLoaderInit(runtime_path) != 0) {
PLOGE << "Invoke JuiceLoader Init failed";
return false;
}
PLOGI << "[OK] Invoke JuiceLoader Init";
// Step 4: Done, cleanup
// Load JuiceLoaderLibrary
return 0;
}
DWORD WINAPI ThreadProc(LPVOID lpParam) {
PLOGD << "ThreadProc";
PLOGD.printf("Recieved lpParam: %p");
if (lpParam == nullptr) {
PLOGE << "lpParam is NULL";
return 1;
}
InjectParams* pParams = (InjectParams*)lpParam;
PLOGD << "ConfigDir: " << pParams->ConfigDir;
PLOGI << "Init JuiceAgent...";
int result = InitJuiceAgent(pParams->ConfigDir);
PLOGI.printf("Init JuiceAgent result: %d", result);
PLOGI << "Exit ThreadProc";
return 0;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH: {
InitLogger();
PLOGI << "DLL_PROCESS_ATTACH";
PLOGI.printf("[*] JuiceAgent Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
DisableThreadLibraryCalls(hinstDLL);
// TODO: ReflectiveLoader Params
InjectParams *testParams = (InjectParams*)malloc(sizeof(InjectParams));
strcpy(testParams->ConfigDir, "C:\\Users\\xiaozhou\\Desktop\\Inject_V1.0_b1");
lpReserved = (void*)testParams;
// Check if lpReserved is NULL
if (lpReserved == nullptr) {
PLOGE << "lpReserved is NULL";
return FALSE;
}
// Allocate memory for local param
InjectParams* pParams = (InjectParams*)malloc(sizeof(InjectParams));
if (pParams == nullptr) {
PLOGE << "Failed to allocate memory for local param";
return FALSE;
}
// Copy lpReserved to local param
memcpy(pParams, lpReserved, sizeof(InjectParams));
// Create a thread to handle the injection
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, pParams, 0, NULL);
if (hThread) {
CloseHandle(hThread);
} else {
PLOGE << "Failed to create thread";
free(pParams);
}
break;
}
case DLL_PROCESS_DETACH:
PLOGI << "DLL_PROCESS_DETACH";
break;
}
return TRUE;
}
extern "C" __declspec(dllexport)
JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM* vm, char *options, void *reserved) {
return JNI_OK;
}
extern "C" __declspec(dllexport)
JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM* vm, char *options, void *reserved) {
return JNI_OK;
PLOGI << "--------> InitJuiceAgent Succeed <--------";
return true;
}
+17
View File
@@ -0,0 +1,17 @@
file(
GLOB_RECURSE
libinjector_sources
${CMAKE_CURRENT_SOURCE_DIR}/*.c
)
add_library(injector SHARED ${libinjector_sources})
target_include_directories(injector PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
)
target_link_libraries(injector PRIVATE
ReflectiveDLLInjection
)
@@ -1,17 +1,15 @@
// injector_debug.c
#include "InjectorUtils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LoadLibraryR.h"
#include "InjectorNative.h"
#include "JuiceAgent.h"
#include <jni.h>
#include <ReflectiveDLLInjection/LoadLibraryR.h>
#define WIN_X64
#define BREAK_WITH_ERROR( e ) { printf("[-] %s. Error=%l", e, GetLastError()); break; }
#define MAX_PATH 260
__declspec(dllexport)
int inject(int pid, char *path, InjectParams *params){
int inject(int pid, char *path, char *params){
HANDLE hFile = NULL;
HANDLE hRemoteThread = NULL;
HANDLE hProcess = NULL;
@@ -24,9 +22,6 @@ int inject(int pid, char *path, InjectParams *params){
TOKEN_PRIVILEGES priv = {0};
BOOL bSuccess = FALSE;
printf("[*] libinjector Version %d.%d Build %d\n", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
printf("Injector process pointer size = %zu bytes\n", sizeof(void*));
do {
@@ -64,14 +59,6 @@ int inject(int pid, char *path, InjectParams *params){
if (!ReadFile(hFile, lpBuffer, dwLength, &dwBytesRead, NULL) || dwBytesRead != dwLength)
BREAK_WITH_ERROR("ReadFile failed or incomplete");
/* print machine type of DLL buffer */
WORD dllMachine = get_pe_machine(lpBuffer, dwLength);
printf("[*] DLL PE machine: %s (0x%04x)\n", machine_to_str(dllMachine), dllMachine);
/* check if DLL has ReflectiveLoader export */
BOOL hasRL = has_reflective_loader_export(lpBuffer, dwLength);
printf("[*] DLL has ReflectiveLoader export: %s\n", hasRL ? "YES" : "NO");
/* enable SeDebugPrivilege (best-effort) */
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
priv.PrivilegeCount = 1;
@@ -95,29 +82,9 @@ int inject(int pid, char *path, InjectParams *params){
printf("Is target process wow64 = %d (TRUE means 32-bit process on 64-bit OS)\n", targetIsWow64);
}
/* compare architectures */
#if defined(_M_X64) || defined(__x86_64__) || defined(__amd64__)
printf("Injector compiled as: x64\n");
#else
printf("Injector compiled as: x86\n");
#endif
if (dllMachine == IMAGE_FILE_MACHINE_AMD64) {
printf("[*] DLL is x64\n");
#if !defined(_M_X64) && !defined(__x86_64__)
printf("[-] MISMATCH: injector is 32-bit but DLL is x64. This will fail.");
#endif
} else if (dllMachine == IMAGE_FILE_MACHINE_I386) {
printf("[*] DLL is x86\n");
#if defined(_M_X64) || defined(__x86_64__)
printf("[-] MISMATCH: injector is 64-bit but DLL is x86. This will fail.\n");
#endif
} else {
printf("Unknown DLL machine type; proceed with caution\n");
}
/* allocate remote memory for InjectParameters */
lpRemoteParam = VirtualAllocEx(hProcess, NULL, sizeof(InjectParams), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
lpRemoteParam = VirtualAllocEx(hProcess, NULL, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!lpRemoteParam)
BREAK_WITH_ERROR("VirtualAllocEx for remote param failed\n");
@@ -126,7 +93,7 @@ int inject(int pid, char *path, InjectParams *params){
/* write params to remote memory */
SIZE_T written = 0;
if (params) {
if (!WriteProcessMemory(hProcess, lpRemoteParam, params, sizeof(InjectParams), &written) || written != sizeof(InjectParams))
if (!WriteProcessMemory(hProcess, lpRemoteParam, params, MAX_PATH, &written) || written != MAX_PATH)
BREAK_WITH_ERROR("WriteProcessMemory for remote param failed\n");
} else {
printf("No parameters provided; using null pointer\n");
@@ -135,12 +102,17 @@ int inject(int pid, char *path, InjectParams *params){
/* read back some bytes to verify write */
{
InjectParams verify;
char verify[MAX_PATH] = {0};
SIZE_T read = 0;
if (ReadProcessMemory(hProcess, lpRemoteParam, &verify, sizeof(InjectParams), &read)) {
printf("[*] Read back remote param, ConfigDir=%.*s\n", (int)sizeof(verify.ConfigDir), verify.ConfigDir);
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("[-] ReadProcessMemory failed: %lu\n", GetLastError());
printf("[*] lpRemoteParam == NULL, skip verify\n");
}
}
@@ -149,8 +121,6 @@ int inject(int pid, char *path, InjectParams *params){
if (!hRemoteThread) {
/* library didn't set last error; print hint info we gathered */
printf("[-] LoadRemoteLibraryR returned NULL. GetLastError=%lu\n", GetLastError());
printf("[-] Diagnostic summary: dllMachine=0x%04x, hasReflectiveLoader=%d, targetIsWow64=%d\n",
dllMachine, hasRL ? 1 : 0, targetIsWow64 ? 1 : 0);
BREAK_WITH_ERROR("LoadRemoteLibraryR returned NULL");
}
@@ -211,19 +181,15 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNativ
*/
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){
// Injection Path
const char* InjectionDLL = (*env)->GetStringUTFChars(env, path, NULL);
// Config Path
const char* ConfigDir = (*env)->GetStringUTFChars(env, configDir, NULL);
InjectParams params;
memset(&params, 0, sizeof(params));
char params[MAX_PATH] = {0}; /* use a real buffer */
strncpy(params, ConfigDir ? ConfigDir : "", MAX_PATH - 1);
strncpy(params.ConfigDir, ConfigDir ? ConfigDir : "", sizeof(params.ConfigDir)-1);
int ret = inject(pid, (char*)InjectionDLL, params);
int ret = inject(pid, (char*)InjectionDLL, &params);
// Clean up
(*env)->ReleaseStringUTFChars(env, path, InjectionDLL);
(*env)->ReleaseStringUTFChars(env, configDir, ConfigDir);
+20
View File
@@ -0,0 +1,20 @@
file(
GLOB_RECURSE
libjuiceloader_sources
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/*.c
)
add_library(juiceloader SHARED ${libjuiceloader_sources})
target_include_directories(juiceloader PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_CURRENT_SOURCE_DIR}/includes
)
target_link_libraries(juiceloader PRIVATE
ReflectiveDLLInjection
jvm
)
@@ -4,7 +4,7 @@
#include <jvmti.h>
#include <string.h>
#include <stdlib.h>
#include <Logger.hpp>
#include <JuiceAgent/Logger.hpp>
RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
@@ -25,6 +25,7 @@ extern RetransformClassCacheType RetransformClassCache;
#define C_EXPORT extern "C" __declspec(dllexport)
extern "C" __declspec(dllexport)
int InitJuiceLoader(JNIEnv *env, jvmtiEnv *jvmti);
void JNICALL ClassFileLoadHook(
@@ -1,7 +1,7 @@
// JVM
#include <jni.h>
#include <jvmti.h>
#include <Logger.hpp>
#include <JuiceAgent/Logger.hpp>
#include <juiceloader.h>
JuiceLoaderNativeType JuiceLoaderNative;
@@ -30,7 +30,7 @@ static int ConfigureJVMTI(JNIEnv *env, _jvmtiEnv *jvmti) {
// Register callbacks
jvmtiEventCallbacks callbacks;
memset(&callbacks, 0, sizeof(callbacks));
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
// callbacks.ClassFileLoadHook = &ClassFileLoadHook;
jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
// Enable events
@@ -39,8 +39,8 @@ static int ConfigureJVMTI(JNIEnv *env, _jvmtiEnv *jvmti) {
return JNI_OK;
}
extern "C" __declspec(dllexport)
int InitJuiceLoader(JNIEnv *env, _jvmtiEnv *jvmti) {
PLOGI.printf("[*] libjuiceloader Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
// Step 1: Check if env/jvmti is null
PLOGD.printf("env: %p, jvmti: %p", env, jvmti);
if (env == nullptr) {
@@ -63,4 +63,3 @@ int InitJuiceLoader(JNIEnv *env, _jvmtiEnv *jvmti) {
return 0;
}