Delete Code

This commit is contained in:
xiaozhou233 committed 2025-11-21 16:55:40 +08:00
1 parent ad827fabff
commit 07a71eab12
47 files changed
-14754

No files matched your search

-1
View File
@@ -1 +0,0 @@
# src/agent/CMakeLists.txt
-480
View File
@@ -1,480 +0,0 @@
//===============================================================================================//
// Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Harmony Security nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL 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.
//===============================================================================================//
#include "ReflectiveLoader.h"
#define WIN_X64
//===============================================================================================//
// Our loader will set this to a pseudo correct HINSTANCE/HMODULE value
HINSTANCE hAppInstance = NULL;
//===============================================================================================//
#pragma intrinsic( _ReturnAddress )
// This function can not be inlined by the compiler or we will not get the address we expect. Ideally
// this code will be compiled with the /O2 and /Ob1 switches. Bonus points if we could take advantage of
// RIP relative addressing in this instance but I dont believe we can do so with the compiler intrinsics
// available (and no inline asm available under x64).
// __declspec(noinline) ULONG_PTR caller( VOID ) { return (ULONG_PTR)_ReturnAddress(); }
// OK, it's will be fine :/
__declspec(noinline) ULONG_PTR caller( VOID ) { return (ULONG_PTR) __builtin_return_address(0); }
//===============================================================================================//
// Note 1: If you want to have your own DllMain, define REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN,
// otherwise the DllMain at the end of this file will be used.
// Note 2: If you are injecting the DLL via LoadRemoteLibraryR, define REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR,
// otherwise it is assumed you are calling the ReflectiveLoader via a stub.
// This is our position independent reflective DLL loader/injector
#ifdef REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
DLLEXPORT ULONG_PTR WINAPI ReflectiveLoader( LPVOID lpParameter )
#else
DLLEXPORT ULONG_PTR WINAPI ReflectiveLoader( VOID )
#endif
{
// the functions we need
LOADLIBRARYA pLoadLibraryA = NULL;
GETPROCADDRESS pGetProcAddress = NULL;
VIRTUALALLOC pVirtualAlloc = NULL;
NTFLUSHINSTRUCTIONCACHE pNtFlushInstructionCache = NULL;
USHORT usCounter;
// the initial location of this image in memory
ULONG_PTR uiLibraryAddress;
// the kernels base address and later this images newly loaded base address
ULONG_PTR uiBaseAddress;
// variables for processing the kernels export table
ULONG_PTR uiAddressArray;
ULONG_PTR uiNameArray;
ULONG_PTR uiExportDir;
ULONG_PTR uiNameOrdinals;
DWORD dwHashValue;
// variables for loading this image
ULONG_PTR uiHeaderValue;
ULONG_PTR uiValueA;
ULONG_PTR uiValueB;
ULONG_PTR uiValueC;
ULONG_PTR uiValueD;
ULONG_PTR uiValueE;
// STEP 0: calculate our images current base address
// we will start searching backwards from our callers return address.
uiLibraryAddress = caller();
// loop through memory backwards searching for our images base address
// we dont need SEH style search as we shouldnt generate any access violations with this
while( TRUE )
{
if( ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_magic == IMAGE_DOS_SIGNATURE )
{
uiHeaderValue = ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew;
// some x64 dll's can trigger a bogus signature (IMAGE_DOS_SIGNATURE == 'POP r10'),
// we sanity check the e_lfanew with an upper threshold value of 1024 to avoid problems.
if( uiHeaderValue >= sizeof(IMAGE_DOS_HEADER) && uiHeaderValue < 1024 )
{
uiHeaderValue += uiLibraryAddress;
// break if we have found a valid MZ/PE header
if( ((PIMAGE_NT_HEADERS)uiHeaderValue)->Signature == IMAGE_NT_SIGNATURE )
break;
}
}
uiLibraryAddress--;
}
// STEP 1: process the kernels exports for the functions our loader needs...
// get the Process Enviroment Block
#ifdef WIN_X64
uiBaseAddress = __readgsqword( 0x60 );
#else
#ifdef WIN_X86
uiBaseAddress = __readfsdword( 0x30 );
#else WIN_ARM
uiBaseAddress = *(DWORD *)( (BYTE *)_MoveFromCoprocessor( 15, 0, 13, 0, 2 ) + 0x30 );
#endif
#endif
// get the processes loaded modules. ref: http://msdn.microsoft.com/en-us/library/aa813708(VS.85).aspx
uiBaseAddress = (ULONG_PTR)((_PPEB)uiBaseAddress)->pLdr;
// get the first entry of the InMemoryOrder module list
uiValueA = (ULONG_PTR)((PPEB_LDR_DATA)uiBaseAddress)->InMemoryOrderModuleList.Flink;
while( uiValueA )
{
// get pointer to current modules name (unicode string)
uiValueB = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->BaseDllName.pBuffer;
// set bCounter to the length for the loop
usCounter = ((PLDR_DATA_TABLE_ENTRY)uiValueA)->BaseDllName.Length;
// clear uiValueC which will store the hash of the module name
uiValueC = 0;
// compute the hash of the module name...
do
{
uiValueC = ror( (DWORD)uiValueC );
// normalize to uppercase if the madule name is in lowercase
if( *((BYTE *)uiValueB) >= 'a' )
uiValueC += *((BYTE *)uiValueB) - 0x20;
else
uiValueC += *((BYTE *)uiValueB);
uiValueB++;
} while( --usCounter );
// compare the hash with that of kernel32.dll
if( (DWORD)uiValueC == KERNEL32DLL_HASH )
{
// get this modules base address
uiBaseAddress = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->DllBase;
// get the VA of the modules NT Header
uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew;
// uiNameArray = the address of the modules export directory entry
uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
// get the VA of the export directory
uiExportDir = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress );
// get the VA for the array of name pointers
uiNameArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames );
// get the VA for the array of name ordinals
uiNameOrdinals = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals );
usCounter = 3;
// loop while we still have imports to find
while( usCounter > 0 )
{
// compute the hash values for this function name
dwHashValue = hash( (char *)( uiBaseAddress + DEREF_32( uiNameArray ) ) );
// if we have found a function we want we get its virtual address
if( dwHashValue == LOADLIBRARYA_HASH || dwHashValue == GETPROCADDRESS_HASH || dwHashValue == VIRTUALALLOC_HASH )
{
// get the VA for the array of addresses
uiAddressArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions );
// use this functions name ordinal as an index into the array of name pointers
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
// store this functions VA
if( dwHashValue == LOADLIBRARYA_HASH )
pLoadLibraryA = (LOADLIBRARYA)( uiBaseAddress + DEREF_32( uiAddressArray ) );
else if( dwHashValue == GETPROCADDRESS_HASH )
pGetProcAddress = (GETPROCADDRESS)( uiBaseAddress + DEREF_32( uiAddressArray ) );
else if( dwHashValue == VIRTUALALLOC_HASH )
pVirtualAlloc = (VIRTUALALLOC)( uiBaseAddress + DEREF_32( uiAddressArray ) );
// decrement our counter
usCounter--;
}
// get the next exported function name
uiNameArray += sizeof(DWORD);
// get the next exported function name ordinal
uiNameOrdinals += sizeof(WORD);
}
}
else if( (DWORD)uiValueC == NTDLLDLL_HASH )
{
// get this modules base address
uiBaseAddress = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->DllBase;
// get the VA of the modules NT Header
uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew;
// uiNameArray = the address of the modules export directory entry
uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
// get the VA of the export directory
uiExportDir = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress );
// get the VA for the array of name pointers
uiNameArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames );
// get the VA for the array of name ordinals
uiNameOrdinals = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals );
usCounter = 1;
// loop while we still have imports to find
while( usCounter > 0 )
{
// compute the hash values for this function name
dwHashValue = hash( (char *)( uiBaseAddress + DEREF_32( uiNameArray ) ) );
// if we have found a function we want we get its virtual address
if( dwHashValue == NTFLUSHINSTRUCTIONCACHE_HASH )
{
// get the VA for the array of addresses
uiAddressArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions );
// use this functions name ordinal as an index into the array of name pointers
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
// store this functions VA
if( dwHashValue == NTFLUSHINSTRUCTIONCACHE_HASH )
pNtFlushInstructionCache = (NTFLUSHINSTRUCTIONCACHE)( uiBaseAddress + DEREF_32( uiAddressArray ) );
// decrement our counter
usCounter--;
}
// get the next exported function name
uiNameArray += sizeof(DWORD);
// get the next exported function name ordinal
uiNameOrdinals += sizeof(WORD);
}
}
// we stop searching when we have found everything we need.
if( pLoadLibraryA && pGetProcAddress && pVirtualAlloc && pNtFlushInstructionCache )
break;
// get the next entry
uiValueA = DEREF( uiValueA );
}
// STEP 2: load our image into a new permanent location in memory...
// get the VA of the NT Header for the PE to be loaded
uiHeaderValue = uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew;
// allocate all the memory for the DLL to be loaded into. we can load at any address because we will
// relocate the image. Also zeros all memory and marks it as READ, WRITE and EXECUTE to avoid any problems.
uiBaseAddress = (ULONG_PTR)pVirtualAlloc( NULL, ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.SizeOfImage, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
// we must now copy over the headers
uiValueA = ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.SizeOfHeaders;
uiValueB = uiLibraryAddress;
uiValueC = uiBaseAddress;
while( uiValueA-- )
*(BYTE *)uiValueC++ = *(BYTE *)uiValueB++;
// STEP 3: load in all of our sections...
// uiValueA = the VA of the first section
uiValueA = ( (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader + ((PIMAGE_NT_HEADERS)uiHeaderValue)->FileHeader.SizeOfOptionalHeader );
// itterate through all sections, loading them into memory.
uiValueE = ((PIMAGE_NT_HEADERS)uiHeaderValue)->FileHeader.NumberOfSections;
while( uiValueE-- )
{
// uiValueB is the VA for this section
uiValueB = ( uiBaseAddress + ((PIMAGE_SECTION_HEADER)uiValueA)->VirtualAddress );
// uiValueC if the VA for this sections data
uiValueC = ( uiLibraryAddress + ((PIMAGE_SECTION_HEADER)uiValueA)->PointerToRawData );
// copy the section over
uiValueD = ((PIMAGE_SECTION_HEADER)uiValueA)->SizeOfRawData;
while( uiValueD-- )
*(BYTE *)uiValueB++ = *(BYTE *)uiValueC++;
// get the VA of the next section
uiValueA += sizeof( IMAGE_SECTION_HEADER );
}
// STEP 4: process our images import table...
// uiValueB = the address of the import directory
uiValueB = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_IMPORT ];
// we assume their is an import table to process
// uiValueC is the first entry in the import table
uiValueC = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiValueB)->VirtualAddress );
// itterate through all imports
while( ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->Name )
{
// use LoadLibraryA to load the imported module into memory
uiLibraryAddress = (ULONG_PTR)pLoadLibraryA( (LPCSTR)( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->Name ) );
// uiValueD = VA of the OriginalFirstThunk
uiValueD = ( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->OriginalFirstThunk );
// uiValueA = VA of the IAT (via first thunk not origionalfirstthunk)
uiValueA = ( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->FirstThunk );
// itterate through all imported functions, importing by ordinal if no name present
while( DEREF(uiValueA) )
{
// sanity check uiValueD as some compilers only import by FirstThunk
if( uiValueD && ((PIMAGE_THUNK_DATA)uiValueD)->u1.Ordinal & IMAGE_ORDINAL_FLAG )
{
// get the VA of the modules NT Header
uiExportDir = uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew;
// uiNameArray = the address of the modules export directory entry
uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
// get the VA of the export directory
uiExportDir = ( uiLibraryAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress );
// get the VA for the array of addresses
uiAddressArray = ( uiLibraryAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions );
// use the import ordinal (- export ordinal base) as an index into the array of addresses
uiAddressArray += ( ( IMAGE_ORDINAL( ((PIMAGE_THUNK_DATA)uiValueD)->u1.Ordinal ) - ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->Base ) * sizeof(DWORD) );
// patch in the address for this imported function
DEREF(uiValueA) = ( uiLibraryAddress + DEREF_32(uiAddressArray) );
}
else
{
// get the VA of this functions import by name struct
uiValueB = ( uiBaseAddress + DEREF(uiValueA) );
// use GetProcAddress and patch in the address for this imported function
DEREF(uiValueA) = (ULONG_PTR)pGetProcAddress( (HMODULE)uiLibraryAddress, (LPCSTR)((PIMAGE_IMPORT_BY_NAME)uiValueB)->Name );
}
// get the next imported function
uiValueA += sizeof( ULONG_PTR );
if( uiValueD )
uiValueD += sizeof( ULONG_PTR );
}
// get the next import
uiValueC += sizeof( IMAGE_IMPORT_DESCRIPTOR );
}
// STEP 5: process all of our images relocations...
// calculate the base address delta and perform relocations (even if we load at desired image base)
uiLibraryAddress = uiBaseAddress - ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.ImageBase;
// uiValueB = the address of the relocation directory
uiValueB = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_BASERELOC ];
// check if their are any relocations present
if( ((PIMAGE_DATA_DIRECTORY)uiValueB)->Size )
{
// uiValueC is now the first entry (IMAGE_BASE_RELOCATION)
uiValueC = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiValueB)->VirtualAddress );
// and we itterate through all entries...
while( ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock )
{
// uiValueA = the VA for this relocation block
uiValueA = ( uiBaseAddress + ((PIMAGE_BASE_RELOCATION)uiValueC)->VirtualAddress );
// uiValueB = number of entries in this relocation block
uiValueB = ( ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION) ) / sizeof( IMAGE_RELOC );
// uiValueD is now the first entry in the current relocation block
uiValueD = uiValueC + sizeof(IMAGE_BASE_RELOCATION);
// we itterate through all the entries in the current block...
while( uiValueB-- )
{
// perform the relocation, skipping IMAGE_REL_BASED_ABSOLUTE as required.
// we dont use a switch statement to avoid the compiler building a jump table
// which would not be very position independent!
if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_DIR64 )
*(ULONG_PTR *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += uiLibraryAddress;
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_HIGHLOW )
*(DWORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += (DWORD)uiLibraryAddress;
#ifdef WIN_ARM
// Note: On ARM, the compiler optimization /O2 seems to introduce an off by one issue, possibly a code gen bug. Using /O1 instead avoids this problem.
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_ARM_MOV32T )
{
register DWORD dwInstruction;
register DWORD dwAddress;
register WORD wImm;
// get the MOV.T instructions DWORD value (We add 4 to the offset to go past the first MOV.W which handles the low word)
dwInstruction = *(DWORD *)( uiValueA + ((PIMAGE_RELOC)uiValueD)->offset + sizeof(DWORD) );
// flip the words to get the instruction as expected
dwInstruction = MAKELONG( HIWORD(dwInstruction), LOWORD(dwInstruction) );
// sanity chack we are processing a MOV instruction...
if( (dwInstruction & ARM_MOV_MASK) == ARM_MOVT )
{
// pull out the encoded 16bit value (the high portion of the address-to-relocate)
wImm = (WORD)( dwInstruction & 0x000000FF);
wImm |= (WORD)((dwInstruction & 0x00007000) >> 4);
wImm |= (WORD)((dwInstruction & 0x04000000) >> 15);
wImm |= (WORD)((dwInstruction & 0x000F0000) >> 4);
// apply the relocation to the target address
dwAddress = ( (WORD)HIWORD(uiLibraryAddress) + wImm ) & 0xFFFF;
// now create a new instruction with the same opcode and register param.
dwInstruction = (DWORD)( dwInstruction & ARM_MOV_MASK2 );
// patch in the relocated address...
dwInstruction |= (DWORD)(dwAddress & 0x00FF);
dwInstruction |= (DWORD)(dwAddress & 0x0700) << 4;
dwInstruction |= (DWORD)(dwAddress & 0x0800) << 15;
dwInstruction |= (DWORD)(dwAddress & 0xF000) << 4;
// now flip the instructions words and patch back into the code...
*(DWORD *)( uiValueA + ((PIMAGE_RELOC)uiValueD)->offset + sizeof(DWORD) ) = MAKELONG( HIWORD(dwInstruction), LOWORD(dwInstruction) );
}
}
#endif
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_HIGH )
*(WORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += HIWORD(uiLibraryAddress);
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_LOW )
*(WORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += LOWORD(uiLibraryAddress);
// get the next entry in the current relocation block
uiValueD += sizeof( IMAGE_RELOC );
}
// get the next entry in the relocation directory
uiValueC = uiValueC + ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock;
}
}
// STEP 6: call our images entry point
// uiValueA = the VA of our newly loaded DLL/EXE's entry point
uiValueA = ( uiBaseAddress + ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.AddressOfEntryPoint );
// We must flush the instruction cache to avoid stale code being used which was updated by our relocation processing.
pNtFlushInstructionCache( (HANDLE)-1, NULL, 0 );
// call our respective entry point, fudging our hInstance value
#ifdef REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
// if we are injecting a DLL via LoadRemoteLibraryR we call DllMain and pass in our parameter (via the DllMain lpReserved parameter)
((DLLMAIN)uiValueA)( (HINSTANCE)uiBaseAddress, DLL_PROCESS_ATTACH, lpParameter );
#else
// if we are injecting an DLL via a stub we call DllMain with no parameter
((DLLMAIN)uiValueA)( (HINSTANCE)uiBaseAddress, DLL_PROCESS_ATTACH, NULL );
#endif
// STEP 8: return our new entry point address so whatever called us can call DllMain() if needed.
return uiValueA;
}
//===============================================================================================//
-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
-327
View File
@@ -1,327 +0,0 @@
#include <windows.h>
#include "Logger.hpp"
#include <JuiceAgent.h>
#include <tinytoml/toml.h>
// For Java VM
#include <jni.h>
#include <jvmti.h>
struct _JuiceAgent {
bool isAttached;
JavaVM *jvm;
jvmtiEnv *jvmti;
JNIEnv *env;
} JuiceAgent = {false, NULL, NULL, NULL};
InjectionInfoType InjectionInfo;
static int GetJavaEnv() {
jint res = JNI_ERR;
JavaVM *jvm = NULL;
jvmtiEnv *jvmti = NULL;
JNIEnv *env = NULL;
int max_try = 30;
// Get the JVM
max_try = 30;
do {
res = JNI_GetCreatedJavaVMs(&jvm, 1, NULL);
if (res != JNI_OK || jvm == NULL) {
PLOGE.printf("JNI_GetCreatedJavaVMs failed: %d", res);
PLOGD << "JVM NULL: " << (jvm == NULL);
}
Sleep(1000);
max_try--;
if (jvm != NULL) {
break;
} else {
PLOGI.printf("Waiting for JVM... (%d)", max_try);
}
} while (jvm == NULL && max_try > 0);
if (jvm == NULL) {
PLOGE << "GetJavaEnv failed";
return res;
}
JuiceAgent.jvm = jvm;
PLOGI << "Got the JVM";
// Get the JNIEnv
max_try = 30;
do {
res = jvm->GetEnv((void**)&env, JNI_VERSION_1_8);
if (res != JNI_OK || env == NULL) {
PLOGI << "GetEnv failed, trying to attach.";
PLOGD << "env NULL: " << (env == NULL);
res = jvm->AttachCurrentThread((void**)&env, NULL);
if (res != JNI_OK || env == NULL) {
PLOGE.printf("AttachCurrentThread failed: %d", res);
PLOGD << "env NULL: " << (env == NULL);
return res;
}
}
Sleep(1000);
max_try--;
if (env != NULL) {
break;
} else {
PLOGI.printf("Waiting for JNI... (%d)", max_try);
}
} while (env == NULL && max_try > 0);
if (env == NULL) {
PLOGE << "Get JNI failed";
return res;
}
JuiceAgent.env = env;
PLOGI << "Got the JNIEnv";
// Get the JVMTI
res = jvm->GetEnv((void**)&jvmti, JVMTI_VERSION_1_2);
if (res != JNI_OK || jvmti == NULL) {
PLOGE.printf("GetEnv failed: %d", res);
PLOGD << "jvmti NULL: " << (jvmti == NULL);
return res;
}
JuiceAgent.jvmti = jvmti;
PLOGI << "Got the JVMTI";
return 0;
}
static int InvokeJuiceLoaderInit(const char* ConfigDir) {
// Variables
int result = JNI_ERR;
JNIEnv *env = JuiceAgent.env;
jvmtiEnv *jvmti = JuiceAgent.jvmti;
const char *bootstrap_class = "cn/xiaozhou233/juiceloader/JuiceLoaderBootstrap";
const char *method_name = "init";
const char *method_signature = "([Ljava/lang/String;)V";
PLOGI << "Invoke JuiceLoader Init";
PLOGI << "================ JuiceLoader Init =================";
// Find class
jclass cls = env->FindClass(bootstrap_class);
if (cls == NULL) {
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGE << "FindClass failed";
return 1;
}
// Find method
jmethodID mid = env->GetStaticMethodID(cls, method_name, method_signature);
if (mid == NULL) {
PLOGE << "GetStaticMethodID failed";
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
return 1;
}
// arguments array
const char* args[] = {
InjectionInfo.EntryJarPath,
InjectionInfo.EntryClass,
InjectionInfo.EntryMethod,
InjectionInfo.InjectionDir,
InjectionInfo.JuiceLoaderLibraryPath
};
int argCount = sizeof(args)/sizeof(args[0]);
jclass stringCls = env->FindClass("java/lang/String");
jobjectArray jArgs = env->NewObjectArray(argCount, stringCls, nullptr);
for (int i = 0; i < argCount; i++) {
env->SetObjectArrayElement(jArgs, i, env->NewStringUTF(args[i]));
}
// Invoke method
env->CallStaticVoidMethod(cls, mid, jArgs);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGI << "================ JuiceLoader Init =================";
PLOGI << "Invoke JuiceLoader Init done";
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;
// 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;
}
// Step 1: Get the Java environment
if (GetJavaEnv() != 0) {
PLOGE << "Failed to get Java environment code=" << result;
return 1;
}
// Step 2: Inject JuiceLoader.jar
result = JuiceAgent.jvmti->AddToSystemClassLoaderSearch(InjectionInfo.JuiceLoaderJarPath);
if (result != JNI_OK) {
PLOGE.printf("AddToSystemClassLoaderSearch failed: %d", result);
return 1;
}
// Step 3: Invoke JuiceLoader Init
if (InvokeJuiceLoaderInit(ConfigDir) != 0) {
PLOGE << "Failed to invoke JuiceLoader Init code=" << result;
return 1;
}
// Step 4: Done, cleanup
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;
}
-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
-291
View File
@@ -1,291 +0,0 @@
// injector_debug.c
#include "InjectorUtils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LoadLibraryR.h"
#include "InjectorNative.h"
#include "JuiceAgent.h"
#define WIN_X64
#define BREAK_WITH_ERROR( e ) { printf("[-] %s. Error=%l", e, GetLastError()); break; }
__declspec(dllexport)
int inject(int pid, char *path, InjectParams *params){
HANDLE hFile = 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;
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 {
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");
/* alloc local buffer and read file */
lpBuffer = HeapAlloc(GetProcessHeap(), 0, dwLength);
if (!lpBuffer)
BREAK_WITH_ERROR("HeapAlloc failed");
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;
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\n");
} 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.");
#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);
if (!lpRemoteParam)
BREAK_WITH_ERROR("VirtualAllocEx for remote param failed\n");
printf("remote param addr = %p\n", lpRemoteParam);
/* write params to remote memory */
SIZE_T written = 0;
if (params) {
if (!WriteProcessMemory(hProcess, lpRemoteParam, params, sizeof(InjectParams), &written) || written != sizeof(InjectParams))
BREAK_WITH_ERROR("WriteProcessMemory for remote param failed\n");
} else {
printf("No parameters provided; using null pointer\n");
lpRemoteParam = NULL;
}
/* read back some bytes to verify write */
{
InjectParams verify;
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);
} 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;
}
/*
* JNI Function: inject(int pid)
* Note:
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2
(JNIEnv *env, jobject obj, jint pid, jstring path) {
// 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;
}
/*
* 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)
*/
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));
strncpy(params.ConfigDir, ConfigDir ? ConfigDir : "", sizeof(params.ConfigDir)-1);
int ret = inject(pid, (char*)InjectionDLL, &params);
// Clean up
(*env)->ReleaseStringUTFChars(env, path, InjectionDLL);
(*env)->ReleaseStringUTFChars(env, configDir, ConfigDir);
return (ret == 0) ? JNI_TRUE : JNI_FALSE;
}
/// ================ FindWindowsByTitle =================
#define MAX_RESULTS 128
typedef struct {
wchar_t title[256];
DWORD pid;
} WindowData;
static wchar_t g_keyword[256];
static WindowData g_results[MAX_RESULTS];
static int g_count = 0;
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
wchar_t title[256];
GetWindowTextW(hwnd, title, 256);
if (wcslen(title) == 0) return TRUE;
if (wcsstr(title, g_keyword)) {
DWORD pid = 0;
GetWindowThreadProcessId(hwnd, &pid);
if (g_count < MAX_RESULTS && pid) {
wcsncpy(g_results[g_count].title, title, 255);
g_results[g_count].pid = pid;
g_count++;
}
}
return TRUE;
}
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_findWindowsByTitle
(JNIEnv *env, jclass clazz, jstring keyword) {
const jchar *input = (*env)->GetStringChars(env, keyword, NULL);
wcsncpy(g_keyword, (const wchar_t *)input, 255);
g_keyword[255] = L'\0';
(*env)->ReleaseStringChars(env, keyword, input);
g_count = 0;
EnumWindows(EnumWindowsProc, 0);
jclass infoClass = (*env)->FindClass(env, "cn/xiaozhou233/juiceagent/injector/InjectorNative$WindowInfo");
if (!infoClass) return NULL;
jmethodID ctor = (*env)->GetMethodID(env, infoClass, "<init>", "(Ljava/lang/String;I)V");
if (!ctor) return NULL;
jobjectArray array = (*env)->NewObjectArray(env, g_count, infoClass, NULL);
for (int i = 0; i < g_count; i++) {
jstring title = (*env)->NewString(env, (jchar*)g_results[i].title, wcslen(g_results[i].title));
jobject obj = (*env)->NewObject(env, infoClass, ctor, title, (jint)g_results[i].pid);
(*env)->SetObjectArrayElement(env, array, i, obj);
}
return array;
}
/// ===============================================================================
-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
-530
View File
@@ -1,530 +0,0 @@
#include <juiceloader.h>
#include <cn_xiaozhou233_juiceloader_JuiceLoader.h>
#include <jni.h>
#include <jvmti.h>
#include <string.h>
#include <stdlib.h>
#include <Logger.hpp>
RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
static const char* g_bytecodes_classname = NULL;
static unsigned char* g_bytecodes = NULL;
static jint g_bytecodes_len = 0;
/// ================= Utility ================= ///
char* get_class_name(JNIEnv* env, jclass clazz) {
jclass clsClass = env->FindClass("java/lang/Class");
jmethodID mid_getName = env->GetMethodID(clsClass, "getName", "()Ljava/lang/String;");
jstring nameStr = (jstring)env->CallObjectMethod(clazz, mid_getName);
const char* temp = env->GetStringUTFChars(nameStr, NULL);
char* result = _strdup(temp);
env->ReleaseStringUTFChars(nameStr, temp);
env->DeleteLocalRef(nameStr);
return result;
}
// Helper: macro to throw RuntimeException with message
static void throwRuntimeException(JNIEnv *env, const char *msg) {
jclass rte = env->FindClass("java/lang/RuntimeException");
if (rte != NULL) {
env->ThrowNew(rte, msg);
}
}
/// ================= ClassFileLoadHook ================= ///
void JNICALL ClassFileLoadHook(
jvmtiEnv* jvmti_env,
JNIEnv* jni_env,
jclass class_being_redefined,
jobject loader,
const char* name,
jobject protection_domain,
jint class_data_len,
const unsigned char* classbytes,
jint* new_class_data_len,
unsigned char** new_classbytes) {
// ---- capture class bytes ---- //
if (g_bytecodes_classname != NULL && g_bytecodes == NULL) {
if (strcmp(name, g_bytecodes_classname) == 0) {
g_bytecodes_len = class_data_len;
g_bytecodes = (unsigned char*)malloc(class_data_len);
memcpy(g_bytecodes, classbytes, class_data_len);
*new_classbytes = NULL;
*new_class_data_len = 0;
PLOGD.printf("[Hook:get] Captured class bytes of %s, len=%d", name, class_data_len);
return;
}
}
// ---- set class bytes from cache ---- //
if (RetransformClassCache.size == 0) {
return;
}
for (int i = 0; i < RetransformClassCache.size; i++) {
ClassBytesCacheType *entry = &RetransformClassCache.arr[i];
if (strcmp(entry->name, name) == 0) {
unsigned char *newBytes = nullptr;
jvmtiError err = jvmti_env->Allocate(entry->len, &newBytes);
if (err != JVMTI_ERROR_NONE || newBytes == nullptr) {
PLOGE.printf("[Hook:set] jvmti->Allocate failed for class %s, err=%d", name, err);
return;
}
memcpy(newBytes, entry->bytes, entry->len);
*new_classbytes = newBytes;
*new_class_data_len = entry->len;
PLOGI.printf("[Hook:set] Patched class: %s, new_len=%d", name, entry->len);
free(entry->name);
free(entry->bytes);
for (int j = i; j < RetransformClassCache.size - 1; j++) {
RetransformClassCache.arr[j] = RetransformClassCache.arr[j + 1];
}
RetransformClassCache.size--;
break;
}
}
}
/// ============ JNI Function ============ ///
C_EXPORT
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
(JNIEnv *env, jclass loader_class) {
PLOGI << "Invoked!";
// Get JavaVM
JavaVM* jvm = nullptr;
env->GetJavaVM(&jvm);
if (jvm == nullptr) {
PLOGE << "Failed to get JavaVM instance";
return JNI_FALSE;
}
// Get JVMTI
jvmtiEnv* jvmti = nullptr;
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
PLOGE << "Failed to get JVMTI environment, error: " << err;
return JNI_FALSE;
}
int result = InitJuiceLoader(env, jvmti);
if (result != 0) {
PLOGE << "Failed to initialize JuiceLoader, error code: " << result;
return JNI_FALSE;
}
PLOGI << "JuiceLoader initialized successfully";
return JNI_TRUE;
}
C_EXPORT
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar
(JNIEnv *env, jclass loader_class, jstring jarPath) {
PLOGI << "Invoked!";
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
if (!pathStr) {
PLOGE << "Path is NULL!";
return JNI_FALSE;
}
if (!JuiceLoaderNative.jvmti) {
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
env->ReleaseStringUTFChars(jarPath, pathStr);
return JNI_FALSE;
}
jvmtiError result = JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(pathStr);
if (result != JVMTI_ERROR_NONE) {
PLOGE.printf("Cannot inject jar [result=%d]", result);
env->ReleaseStringUTFChars(jarPath, pathStr);
return JNI_FALSE;
}
env->ReleaseStringUTFChars(jarPath, pathStr);
PLOGI << "Jar injected: " << pathStr;
return JNI_TRUE;
}
C_EXPORT
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
PLOGI << "Invoked!";
if (!JuiceLoaderNative.jvmti) {
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
return JNI_FALSE;
}
jbyte* buf = env->GetByteArrayElements(classBytes, NULL);
if (!buf) {
PLOGE << "Cannot get class bytes";
return JNI_FALSE;
}
jvmtiClassDefinition defs[1];
defs[0].klass = clazz;
defs[0].class_byte_count = length;
defs[0].class_bytes = reinterpret_cast<const unsigned char*>(buf);
jvmtiError result = JuiceLoaderNative.jvmti->RedefineClasses(1, defs);
env->ReleaseByteArrayElements(classBytes, buf, JNI_ABORT);
if (result != JVMTI_ERROR_NONE) {
PLOGE.printf("Cannot redefine class [result=%d]", result);
return JNI_FALSE;
}
PLOGI.printf("Class redefined successfully!");
return JNI_TRUE;
}
C_EXPORT
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClassByName
(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
PLOGI << "redefineClass_className Invoked!";
if (!JuiceLoaderNative.jvmti) {
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
return JNI_FALSE;
}
const char* cname = env->GetStringUTFChars(className, NULL);
if (!cname) {
PLOGE << "Class name is NULL!";
return JNI_FALSE;
}
jclass clazz = env->FindClass(cname);
if (!clazz) {
PLOGE.printf("Class not found! [ClassName=%s]", cname);
env->ReleaseStringUTFChars(className, cname);
return JNI_FALSE;
}
jboolean ret = Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass(env, loader_class, clazz, classBytes, length);
env->ReleaseStringUTFChars(className, cname);
return ret;
}
C_EXPORT
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses
(JNIEnv *env, jclass loader_class) {
PLOGI << "loader_getLoadedClasses invoked!";
if (!JuiceLoaderNative.jvmti) {
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
return NULL;
}
jint count = 0;
jclass* classes = NULL;
jvmtiError result = JuiceLoaderNative.jvmti->GetLoadedClasses(&count, &classes);
if (result != JVMTI_ERROR_NONE || count == 0) {
if (classes) JuiceLoaderNative.jvmti->Deallocate((unsigned char*)classes);
return env->NewObjectArray(0, env->FindClass("java/lang/Class"), NULL);
}
jclass classClass = env->FindClass("java/lang/Class");
jobjectArray classArray = env->NewObjectArray(count, classClass, NULL);
for (int i = 0; i < count; i++) {
env->SetObjectArrayElement(classArray, i, classes[i]);
}
if (classes) JuiceLoaderNative.jvmti->Deallocate((unsigned char*)classes);
return classArray;
}
C_EXPORT
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes
(JNIEnv *env, jclass loader_class, jclass clazz) {
PLOGI << "getClassBytes Invoked!";
if (!JuiceLoaderNative.jvmti) {
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
return NULL;
}
char* className = get_class_name(env, clazz);
if (!className) {
PLOGE << "Failed to get class name!";
return NULL;
}
for (char* p = className; *p; ++p) if (*p == '.') *p = '/';
g_bytecodes_classname = className;
g_bytecodes = NULL;
g_bytecodes_len = 0;
jclass classes[1] = { clazz };
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, classes);
if (err != JVMTI_ERROR_NONE) {
PLOGE.printf("RetransformClasses failed: %d", err);
free(className);
return NULL;
}
if (!g_bytecodes) {
PLOGW.printf("No bytecode captured for class: %s", className);
free(className);
return NULL;
}
jbyteArray result = env->NewByteArray(g_bytecodes_len);
env->SetByteArrayRegion(result, 0, g_bytecodes_len, (jbyte*)g_bytecodes);
free(g_bytecodes);
free(className);
g_bytecodes = NULL;
g_bytecodes_classname = NULL;
g_bytecodes_len = 0;
return result;
}
C_EXPORT
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName
(JNIEnv *env, jclass loader_class, jstring className) {
PLOGI << "getClassBytesByName Invoked!";
if (!JuiceLoaderNative.jvmti) {
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
return NULL;
}
const char* cname = env->GetStringUTFChars(className, NULL);
jclass clazz = env->FindClass(cname);
env->ReleaseStringUTFChars(className, cname);
if (!clazz) {
PLOGE.printf("Failed to find class %s", cname);
return NULL;
}
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes(env, loader_class, clazz);
}
C_EXPORT
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
if (!JuiceLoaderNative.jvmti) {
PLOGE << "JuiceLoaderNative.jvmti is NULL! (retransformClass)";
return JNI_FALSE;
}
const char *name_dot = get_class_name(env, clazz);
char* name = _strdup(name_dot);
for (char* p = name; *p; ++p) if (*p == '.') *p = '/';
jbyte* bytes = env->GetByteArrayElements(classBytes, NULL);
jint len = env->GetArrayLength(classBytes);
if (RetransformClassCache.size >= RetransformClassCache.capacity) {
int new_capacity = RetransformClassCache.capacity == 0 ? 4 : RetransformClassCache.capacity * 2;
RetransformClassCache.arr = (ClassBytesCacheType*)realloc(RetransformClassCache.arr, new_capacity * sizeof(ClassBytesCacheType));
RetransformClassCache.capacity = new_capacity;
}
ClassBytesCacheType *entry = &RetransformClassCache.arr[RetransformClassCache.size++];
entry->name = _strdup(name);
entry->bytes = (unsigned char*)malloc(len);
memcpy(entry->bytes, bytes, len);
entry->len = len;
env->ReleaseByteArrayElements(classBytes, bytes, JNI_ABORT);
jclass classes[1] = { clazz };
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, classes);
if (err != JVMTI_ERROR_NONE) {
PLOGE.printf("RetransformClasses failed! [err=%d]", err);
free(name);
return JNI_FALSE;
}
PLOGI.printf("[retransformClass] Class retransformed: %s (len=%d)", entry->name, entry->len);
free(name);
return JNI_TRUE;
}
C_EXPORT
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName
(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
const char *name_dot = env->GetStringUTFChars(className, NULL);
char *name = _strdup(name_dot);
for (char *p = name; *p; ++p) if (*p == '.') *p = '/';
env->ReleaseStringUTFChars(className, name_dot);
jclass target = env->FindClass(name);
free(name);
if (!target) {
PLOGE << "FindClass failed in retransformClassByName";
return JNI_FALSE;
}
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass(env, loader_class, target, classBytes, length);
}
C_EXPORT
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName
(JNIEnv *env, jclass loader_class, jstring className) {
if (className == NULL) {
return NULL;
}
// jstring -> const char*
const char *name_utf = env->GetStringUTFChars(className, NULL);
if (name_utf == NULL) {
return NULL;
}
// find class
jclass clazz = env->FindClass(name_utf);
// clean up
env->ReleaseStringUTFChars(className, name_utf);
if (clazz == NULL) {
PLOGE.printf("Failed to find class %s", name_utf);
}
return clazz;
}
// static native Thread getThreadByName(String name)
C_EXPORT
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeGetThreadByName
(JNIEnv* env, jclass, jstring jName)
{
// Convert jstring to std::string
const char* cName = env->GetStringUTFChars(jName, nullptr);
std::string targetName = cName;
env->ReleaseStringUTFChars(jName, cName);
// Thread class
jclass threadClass = env->FindClass("java/lang/Thread");
// Call Thread.getAllStackTraces(), signature: ()Ljava/util/Map;
jmethodID midGetAll = env->GetStaticMethodID(
threadClass,
"getAllStackTraces",
"()Ljava/util/Map;"
);
jobject mapObj = env->CallStaticObjectMethod(threadClass, midGetAll);
// Map.keySet() -> Set
jclass mapClass = env->FindClass("java/util/Map");
jmethodID midKeySet = env->GetMethodID(
mapClass,
"keySet",
"()Ljava/util/Set;"
);
jobject setObj = env->CallObjectMethod(mapObj, midKeySet);
// Set.iterator() -> Iterator
jclass setClass = env->FindClass("java/util/Set");
jmethodID midIterator = env->GetMethodID(
setClass,
"iterator",
"()Ljava/util/Iterator;"
);
jobject iteratorObj = env->CallObjectMethod(setObj, midIterator);
// Iterator.hasNext() / next()
jclass iteratorClass = env->FindClass("java/util/Iterator");
jmethodID midHasNext = env->GetMethodID(iteratorClass, "hasNext", "()Z");
jmethodID midNext = env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;");
// Thread.getName()
jmethodID midGetName = env->GetMethodID(threadClass, "getName", "()Ljava/lang/String;");
while (env->CallBooleanMethod(iteratorObj, midHasNext)) {
jobject threadObj = env->CallObjectMethod(iteratorObj, midNext);
jstring jThreadName = (jstring)env->CallObjectMethod(threadObj, midGetName);
const char* cThreadName = env->GetStringUTFChars(jThreadName, nullptr);
bool match = (targetName == cThreadName);
env->ReleaseStringUTFChars(jThreadName, cThreadName);
if (match) {
return threadObj; // Found target
}
}
return nullptr; // Not found
}
// static native ClassLoader injectJarToThread(Thread thread, String jarPath)
C_EXPORT
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeInjectJarToThread
(JNIEnv* env, jclass, jobject threadObj, jstring jJarPath)
{
// Convert jstring -> std::string
const char* cJarPath = env->GetStringUTFChars(jJarPath, nullptr);
// new File(jarPath)
jclass fileClass = env->FindClass("java/io/File");
jmethodID fileCtor = env->GetMethodID(fileClass, "<init>", "(Ljava/lang/String;)V");
jstring jPathCopy = env->NewStringUTF(cJarPath);
jobject fileObj = env->NewObject(fileClass, fileCtor, jPathCopy);
// File.toURI()
jmethodID midToURI = env->GetMethodID(fileClass, "toURI", "()Ljava/net/URI;");
jobject uriObj = env->CallObjectMethod(fileObj, midToURI);
// URI.toURL()
jclass uriClass = env->FindClass("java/net/URI");
jmethodID midToURL = env->GetMethodID(uriClass, "toURL", "()Ljava/net/URL;");
jobject urlObj = env->CallObjectMethod(uriObj, midToURL);
// Thread.getContextClassLoader()
jclass threadClass = env->FindClass("java/lang/Thread");
jmethodID midGetCL = env->GetMethodID(
threadClass, "getContextClassLoader", "()Ljava/lang/ClassLoader;"
);
jobject originalCL = env->CallObjectMethod(threadObj, midGetCL);
// URLClassLoader(URL[] urls, ClassLoader parent)
jclass urlClassLoaderClass = env->FindClass("java/net/URLClassLoader");
jmethodID urlCLCtor = env->GetMethodID(
urlClassLoaderClass,
"<init>",
"([Ljava/net/URL;Ljava/lang/ClassLoader;)V"
);
// Create URL[] array with 1 element
jobjectArray urlArray = env->NewObjectArray(1, env->FindClass("java/net/URL"), nullptr);
env->SetObjectArrayElement(urlArray, 0, urlObj);
// Create new URLClassLoader
jobject newClassLoader = env->NewObject(
urlClassLoaderClass,
urlCLCtor,
urlArray,
originalCL
);
// thread.setContextClassLoader(newCL)
jmethodID midSetCL = env->GetMethodID(
threadClass,
"setContextClassLoader",
"(Ljava/lang/ClassLoader;)V"
);
env->CallVoidMethod(threadObj, midSetCL, newClassLoader);
env->ReleaseStringUTFChars(jJarPath, cJarPath);
return newClassLoader;
}
-65
View File
@@ -1,65 +0,0 @@
#ifndef JUICELOADER_H
#define JUICELOADER_H
#include <jni.h>
#include <jvmti.h>
typedef struct _JuiceLoaderNative {
jvmtiEnv *jvmti;
} JuiceLoaderNativeType;
extern JuiceLoaderNativeType JuiceLoaderNative;
typedef struct {
char *name;
unsigned char *bytes;
int len;
} ClassBytesCacheType;
typedef struct {
ClassBytesCacheType *arr;
int size;
int capacity;
} RetransformClassCacheType;
extern RetransformClassCacheType RetransformClassCache;
#define C_EXPORT extern "C" __declspec(dllexport)
int InitJuiceLoader(JNIEnv *env, jvmtiEnv *jvmti);
void JNICALL ClassFileLoadHook(
jvmtiEnv* jvmti_env,
JNIEnv* jni_env,
jclass class_being_redefined,
jobject loader,
const char* name,
jobject protection_domain,
jint class_data_len,
const unsigned char* classbytes,
jint* new_class_data_len,
unsigned char** new_classbytes);
// JNI Functions
// public native static boolean init();
JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class);
// public native static boolean injectJar(String jarPath);
JNIEXPORT jboolean JNICALL loader_injectJar(JNIEnv *env, jclass loader_class, jstring jarPath);
// public native static boolean redefineClass(Class<?> clazz, byte[] classBytes, int length);
JNIEXPORT jboolean JNICALL loader_redefineClass_clazz(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length);
// public native static boolean redefineClass(String className, byte[] classBytes, int length);
JNIEXPORT jboolean JNICALL loader_redefineClass_className(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
// public native static Class<?>[] getLoadedClasses();
JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loader_class);
// public static native byte[] getClassBytes(Class<?> clazz);
JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz);
// public static native byte[] getClassBytesByName(String className);
JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className);
// public static native boolean retransformClass(Class<?> clazz, byte[] classBytes, int length);
JNIEXPORT jboolean JNICALL loader_retransformClass(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length);
// public static native boolean retransformClassByName(String className, byte[] classBytes, int length);
JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
// public static native Class<?> getClassByName(String className);
JNIEXPORT jclass JNICALL loader_getClassByName(JNIEnv *env, jclass loader_class, jstring className);
JNIEXPORT jobject JNICALL loader_nativeGetThreadByName (JNIEnv* env, jclass, jstring jName);
JNIEXPORT jobject JNICALL loader_nativeInjectJarToThread (JNIEnv* env, jclass, jobject threadObj, jstring jJarPath);
#endif
-66
View File
@@ -1,66 +0,0 @@
// JVM
#include <jni.h>
#include <jvmti.h>
#include <Logger.hpp>
#include <juiceloader.h>
JuiceLoaderNativeType JuiceLoaderNative;
static int ConfigureJVMTI(JNIEnv *env, _jvmtiEnv *jvmti) {
// Retransform Class Cache : to store classes that need to be retransformed
RetransformClassCache.arr = NULL;
RetransformClassCache.size = 0;
RetransformClassCache.capacity = 0;
// Application ability
jvmtiCapabilities caps;
memset(&caps, 0, sizeof(caps));
caps.can_get_bytecodes = 1;
caps.can_redefine_classes = 1;
caps.can_redefine_any_class = 1;
caps.can_retransform_classes = 1;
caps.can_retransform_any_class = 1;
caps.can_generate_all_class_hook_events = 1;
jint result = jvmti->AddCapabilities(&caps);
if (result != JNI_OK) {
PLOGE << "Failed to add capabilities: " << result;
return JNI_ERR;
}
// Register callbacks
jvmtiEventCallbacks callbacks;
memset(&callbacks, 0, sizeof(callbacks));
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
// Enable events
jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
return JNI_OK;
}
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) {
PLOGE.printf("[-] Failed to initialize libjuiceloader: env is null");
return -1;
}
if (jvmti == nullptr) {
PLOGE.printf("[-] Failed to initialize libjuiceloader: jvmti is null");
return -1;
}
JuiceLoaderNative.jvmti = jvmti;
// Step 2: Configure JVMTI
if (ConfigureJVMTI(env, jvmti) != JNI_OK) {
PLOGE.printf("[-] Failed to initialize libjuiceloader: ConfigureJVMTI failed");
return -1;
}
return 0;
}