[Update&BugFix] parameters, debug info, bugfix

1. allow injected parameters
2. add print debug info
3. some logic error
This commit is contained in:
xiaozhou233 committed 2025-10-06 22:38:33 +08:00
1 parent e4501f1cf1
commit 71c96b1333
7 files changed
+361 -82

No files matched your search

+10 -6
View File
@@ -17,11 +17,15 @@ add_library(ReflectiveDLLInjection STATIC
# libagent
link_directories("$ENV{JAVA_HOME}/lib")
add_library(agent SHARED ${SRC}/libagent.c)
add_library(agent SHARED
${SRC}/libagent.c
${INCLUDES}/ReflectiveDLLInjection/ReflectiveLoader.c)
target_include_directories(agent PRIVATE
${INCLUDES}/ReflectiveDLLInjection
${INCLUDES}/jvm
${INCLUDES}/jvm/win32)
${INCLUDES}/jvm/win32
${INCLUDES}/JuiceLoader)
target_compile_definitions(agent PRIVATE REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR)
target_link_libraries(agent PRIVATE ReflectiveDLLInjection)
target_link_libraries(agent PRIVATE jvm)
@@ -36,11 +40,11 @@ target_link_libraries(juiceloader PRIVATE jvm)
# libinjector
link_directories("$ENV{JAVA_HOME}/lib")
add_library(libinjector SHARED ${SRC}/libinjector.c)
target_include_directories(libinjector PRIVATE
add_library(injector SHARED ${SRC}/libinjector.c )
target_include_directories(injector PRIVATE
${INCLUDES}/ReflectiveDLLInjection
${INCLUDES}/jvm
${INCLUDES}/jvm/win32
${INCLUDES}/JuiceLoader)
target_link_libraries(libinjector PRIVATE jvm)
target_link_libraries(libinjector PRIVATE ReflectiveDLLInjection)
target_link_libraries(injector PRIVATE jvm)
target_link_libraries(injector PRIVATE ReflectiveDLLInjection)
+10
View File
@@ -0,0 +1,10 @@
#ifndef INJECTPARAMETERS_H
#define INJECTPARAMETERS_H
#include <windows.h>
typedef struct InjectParameters{
char loaderDir[MAX_PATH];
} InjectParameters;
#endif
+1 -1
View File
@@ -13,7 +13,7 @@ extern "C" {
* Signature: (ILjava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_orangex_injector_InjectorNative_inject
(JNIEnv *, jobject, jint, jstring);
(JNIEnv *, jobject, jint, jstring, jstring);
#ifdef __cplusplus
}
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -1,5 +1,5 @@
public class loop {
public static void main(String[] args) {
public static void main(String[] args) throws Exception {
try {
while (true) {
try{
+44 -11
View File
@@ -4,6 +4,7 @@
#include "stdio.h"
#include "jni.h"
#include "jvmti.h"
#include "InjectParameters.h"
#define WIN_X64
extern HINSTANCE hAppInstance;
@@ -11,13 +12,19 @@ extern HINSTANCE hAppInstance;
DWORD WINAPI ThreadProc(LPVOID lpParam) {
printf("libagent: New thread created\n");
// Get environment variable JuiceAgent_Dir
printf("libagent: Get Env JuiceAgent_Dir");
const char* dir = getenv("JuiceAgent_Dir");
printf("libagent: JuiceAgent_Dir: %s\n", dir);
InjectParameters *param = (InjectParameters*)lpParam;
if (!param) {
printf("libagent: ThreadProc got NULL param\n");
return 1;
}
printf("libagent: ThreadProc got param: %s\n", param->loaderDir);
const char* dir = param->loaderDir;
printf("libagent: LoaderDir: %s\n", dir);
if (dir == NULL) {
printf("libagent: JuiceAgent_Dir is not set\n");
MessageBoxA(NULL, "JuiceAgent_Dir is not set", "Error", MB_OK);
printf("libagent: LoaderDir is not set\n");
MessageBoxA(NULL, "LoaderDir is not set", "Error", MB_OK);
return 1;
}
@@ -76,7 +83,9 @@ DWORD WINAPI ThreadProc(LPVOID lpParam) {
jmethodID mid = (*env)->GetStaticMethodID(env, cls, "init", "(Ljava/lang/String;)V");
(*env)->CallStaticVoidMethod(env, cls, mid, (*env)->NewStringUTF(env, dir));
printf("done\n");
free(param);
return 0;
}
@@ -91,9 +100,33 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved){
case DLL_PROCESS_ATTACH:
hAppInstance = hinstDLL;
printf("libagent: DLL_PROCESS_ATTACH\n");
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
if (hThread)
CloseHandle(hThread);
DisableThreadLibraryCalls(hinstDLL);
if (lpReserved != NULL) {
InjectParameters *remoteParm = (InjectParameters*)lpReserved;
InjectParameters *localParm = (InjectParameters*)malloc(sizeof(InjectParameters));
if (localParm == NULL) {
printf("libagent: malloc failed for InjectParameters\n");
break;
}
memset(localParm, 0, sizeof(InjectParameters));
strncpy(localParm->loaderDir, remoteParm->loaderDir, sizeof(localParm->loaderDir) - 1);
localParm->loaderDir[sizeof(localParm->loaderDir)-1] = '\0';
printf("libagent: Loader Dir = %s\n", localParm->loaderDir);
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, localParm, 0, NULL);
if (hThread) {
CloseHandle(hThread);
} else {
printf("libagent: CreateThread failed %lu\n", GetLastError());
free(localParm);
}
}
break;
case DLL_PROCESS_DETACH:
@@ -104,4 +137,4 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved){
break;
}
return bReturnValue;
}
}
+295 -63
View File
@@ -1,93 +1,325 @@
// injector_debug.c
#include "windows.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LoadLibraryR.h"
#include "InjectorNative.h"
#include "InjectParameters.h"
#define WIN_X64
#define BREAK_WITH_ERROR( e ) { printf( "[-] %s. Error=%d", e, GetLastError() ); break; }
#define BREAK_WITH_ERROR( e ) { printf("[-] %s. Error=%lu\n", e, GetLastError()); break; }
int inject(int pid, char *path){
/* Helpers: parse PE header to get Machine and check for ReflectiveLoader export */
/* return IMAGE_FILE_MACHINE_* value or 0 on error */
static 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" */
static 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 */
static 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";
}
}
/* Debug-enhanced inject */
int inject(int pid, char *path, InjectParameters *params){
HANDLE hFile = NULL;
HANDLE hModule = NULL;
HANDLE hProcess = NULL;
HANDLE hToken = NULL;
LPVOID lpBuffer = NULL;
DWORD dwLength = 0;
DWORD dwBytesRead = 0;
DWORD dwProcessId = 0;
TOKEN_PRIVILEGES priv = {0};
char * cpDllFile = NULL;
HANDLE hRemoteThread = NULL;
HANDLE hProcess = NULL;
HANDLE hToken = NULL;
LPVOID lpBuffer = NULL;
LPVOID lpRemoteParam = NULL;
DWORD dwLength = 0;
DWORD dwBytesRead = 0;
DWORD dwProcessId = (DWORD)pid;
TOKEN_PRIVILEGES priv = {0};
BOOL bSuccess = FALSE;
cpDllFile = path;
dwProcessId = pid;
printf("[*] Injector process pointer size = %zu bytes\n", sizeof(void*));
do {
hFile = CreateFileA( cpDllFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if( hFile == INVALID_HANDLE_VALUE )
BREAK_WITH_ERROR( "Failed to open the DLL file" );
if (!params) {
printf("[-] params is NULL\n");
BREAK_WITH_ERROR("Invalid parameters");
}
dwLength = GetFileSize( hFile, NULL );
if( dwLength == INVALID_FILE_SIZE || dwLength == 0 )
BREAK_WITH_ERROR( "Failed to get the DLL file size" );
lpBuffer = HeapAlloc( GetProcessHeap(), 0, dwLength );
if( !lpBuffer )
BREAK_WITH_ERROR( "Failed to get the DLL file size" );
if( ReadFile( hFile, lpBuffer, dwLength, &dwBytesRead, NULL ) == FALSE )
BREAK_WITH_ERROR( "Failed to alloc a buffer!" );
if( OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) )
{
priv.PrivilegeCount = 1;
priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if( LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid ) )
AdjustTokenPrivileges( hToken, FALSE, &priv, 0, NULL, NULL );
CloseHandle( hToken );
/* 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 will open DLL path: %s\n", fullPath);
} else {
printf("[*] Injector GetFullPathNameA failed: %lu\n", GetLastError());
}
hProcess = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, dwProcessId );
if( !hProcess )
BREAK_WITH_ERROR( "Failed to open the target process" );
/* Before CreateFileA, print which file we are about to open */
printf("[*] About to open DLL: %s\n", path);
hModule = LoadRemoteLibraryR( hProcess, lpBuffer, dwLength, NULL );
if( !hModule )
BREAK_WITH_ERROR( "Failed to inject the DLL" );
/* after ReadFile (or after loading into lpBuffer), verify exports again on the buffer we actually read */
printf( "[+] Injected the '%s' DLL into process %d.", cpDllFile, dwProcessId );
WaitForSingleObject( hModule, -1 );
/* get file size */
dwLength = GetFileSize(hFile, NULL);
if (dwLength == INVALID_FILE_SIZE || dwLength == 0)
BREAK_WITH_ERROR("Failed to get DLL file size");
} while( 0 );
/* alloc local buffer and read file */
lpBuffer = HeapAlloc(GetProcessHeap(), 0, dwLength);
if (!lpBuffer)
BREAK_WITH_ERROR("HeapAlloc failed");
if( lpBuffer )
HeapFree( GetProcessHeap(), 0, lpBuffer );
if (!ReadFile(hFile, lpBuffer, dwLength, &dwBytesRead, NULL) || dwBytesRead != dwLength)
BREAK_WITH_ERROR("ReadFile failed or incomplete");
if( hProcess )
CloseHandle( hProcess );
/* 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);
return 0;
/* 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;
priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid))
AdjustTokenPrivileges(hToken, FALSE, &priv, 0, NULL, NULL);
CloseHandle(hToken);
hToken = NULL;
}
/* open target process */
hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, dwProcessId);
if (!hProcess)
BREAK_WITH_ERROR("Failed to open target process");
/* detect target architecture */
BOOL targetIsWow64 = FALSE;
if (!IsWow64Process(hProcess, &targetIsWow64)) {
printf("[!] IsWow64Process failed: %lu\n", GetLastError());
} else {
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.\n");
#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(InjectParameters), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!lpRemoteParam)
BREAK_WITH_ERROR("VirtualAllocEx for remote param failed");
printf("[*] remote param addr = %p\n", lpRemoteParam);
/* write params to remote memory */
SIZE_T written = 0;
if (!WriteProcessMemory(hProcess, lpRemoteParam, params, sizeof(InjectParameters), &written) || written != sizeof(InjectParameters))
BREAK_WITH_ERROR("WriteProcessMemory for remote param failed");
/* read back some bytes to verify write */
{
InjectParameters verify;
SIZE_T read = 0;
if (ReadProcessMemory(hProcess, lpRemoteParam, &verify, sizeof(InjectParameters), &read)) {
printf("[*] Read back remote param, loaderDir=%.*s\n", (int)sizeof(verify.loaderDir), verify.loaderDir);
} else {
printf("[-] ReadProcessMemory failed: %lu\n", GetLastError());
}
}
/* 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());
printf("[-] Diagnostic summary: dllMachine=0x%04x, hasReflectiveLoader=%d, targetIsWow64=%d\n",
dllMachine, hasRL ? 1 : 0, targetIsWow64 ? 1 : 0);
BREAK_WITH_ERROR("LoadRemoteLibraryR returned NULL");
}
printf("[+] DLL injected: '%s' into PID %d, remote param at %p\n", path, dwProcessId, lpRemoteParam);
/* wait for reflective loader thread to complete */
WaitForSingleObject(hRemoteThread, INFINITE);
/* get remote thread exit code */
DWORD exitCode = 0;
if (GetExitCodeThread(hRemoteThread, &exitCode))
printf("[+] Remote thread exit code: %lu\n", exitCode);
bSuccess = TRUE;
CloseHandle(hRemoteThread);
hRemoteThread = NULL;
} while (0);
/* cleanup */
if (lpBuffer) {
HeapFree(GetProcessHeap(), 0, lpBuffer);
lpBuffer = NULL;
}
if (hFile && hFile != INVALID_HANDLE_VALUE) {
CloseHandle(hFile);
hFile = NULL;
}
if (hProcess) {
/* do not free remote param here unless you know DLL copied it */
CloseHandle(hProcess);
hProcess = NULL;
}
return bSuccess ? 0 : -1;
}
/* wrapper using HOME */
int inject_pid(int pid){
const char* dir = getenv("JuiceAgent_Dir");
if(!dir) return -1;
const char* home = getenv("HOME");
if (!home) return -1;
char dir[MAX_PATH];
snprintf(dir, sizeof(dir), "%s\\JuiceAgent\\", home);
char path[MAX_PATH];
sprintf(path, "%s\\libagent.dll", dir);
return inject(pid, path);
snprintf(path, sizeof(path), "%s\\libagent.dll", dir);
InjectParameters params;
memset(&params, 0, sizeof(params));
strncpy(params.loaderDir, dir, sizeof(params.loaderDir)-1);
params.loaderDir[sizeof(params.loaderDir)-1] = '\0';
return inject(pid, path, &params);
}
/* JNI interface */
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_orangex_injector_InjectorNative_inject
(JNIEnv *env, jobject obj, jint pid, jstring path){
const char* nativePath = (*env)->GetStringUTFChars(env, path, 0);
int ret = inject(pid, (char*)nativePath);
(*env)->ReleaseStringUTFChars(env, path, nativePath);
(JNIEnv *env, jobject obj, jint pid, jstring path, jstring loaderDir) {
if(ret == 0)
return JNI_TRUE;
return JNI_FALSE;
const char* nativePath = (*env)->GetStringUTFChars(env, path, 0);
const char* nativeLoaderDir = (*env)->GetStringUTFChars(env, loaderDir, 0);
InjectParameters params;
memset(&params, 0, sizeof(params));
strncpy(params.loaderDir, nativeLoaderDir, sizeof(params.loaderDir)-1);
params.loaderDir[sizeof(params.loaderDir)-1] = '\0';
int ret = inject(pid, (char*)nativePath, &params);
(*env)->ReleaseStringUTFChars(env, path, nativePath);
(*env)->ReleaseStringUTFChars(env, loaderDir, nativeLoaderDir);
return (ret == 0) ? JNI_TRUE : JNI_FALSE;
}