mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 21:15:56 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63c9e55355 | ||
|
|
7f9e381bc3 | ||
|
|
e2a3119af6 | ||
|
|
681a86cb36 | ||
|
|
353fe3e5a5 | ||
|
|
ffaa234bbf | ||
|
|
76055183d2 | ||
|
|
80713ace68 | ||
|
|
01caa4c8cb | ||
|
|
07a71eab12 | ||
|
|
ad827fabff | ||
|
|
ebc557c2f2 | ||
|
|
c4bbbabe07 | ||
|
|
4c184cbb95 | ||
|
|
ffd42c5e30 | ||
|
|
6628b5bfd5 | ||
|
|
56cd994715 | ||
|
|
e3481d007c | ||
|
|
386dc14a01 | ||
|
|
c8c255b233 | ||
|
|
094e7bc0d4 | ||
|
|
acf2cd2c1d | ||
|
|
bd2e9ca730 | ||
|
|
7039e0f914 | ||
|
|
25153d2062 |
No files matched your search
@@ -1,5 +0,0 @@
|
|||||||
[Injection]
|
|
||||||
JuiceLoaderJarPath = "D:/Development/JuiceLoader/build/libs/JuiceLoader.jar"
|
|
||||||
EntryJarPath = "D:/Development/JuiceLoader/build/libs/Entry.jar"
|
|
||||||
EntryClass = "cn.xiaozhou233.juiceloader.entry.Entry"
|
|
||||||
EntryMethod = "start"
|
|
||||||
+6
-20
@@ -4,32 +4,18 @@ project(JuiceAgent LANGUAGES C CXX)
|
|||||||
set(CMAKE_CXX_STANDARD 17)
|
set(CMAKE_CXX_STANDARD 17)
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
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
|
# output directories
|
||||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||||
|
|
||||||
# includes
|
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
|
||||||
set(INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}/includes)
|
link_directories("$ENV{JAVA_HOME}/lib")
|
||||||
|
|
||||||
# libraries
|
# libraries
|
||||||
|
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||||
include(cmake/JuiceModule.cmake)
|
|
||||||
|
|
||||||
# modules
|
# modules
|
||||||
add_juice_module(agent)
|
add_subdirectory(${SRC_DIR}/libagent)
|
||||||
add_juice_module(injector)
|
add_subdirectory(${SRC_DIR}/libinjector)
|
||||||
add_subdirectory(${CMAKE_SOURCE_DIR}/src/executable)
|
add_subdirectory(${SRC_DIR}/libjuiceloader)
|
||||||
@@ -1,36 +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
|
|
||||||
jvm
|
|
||||||
)
|
|
||||||
|
|
||||||
add_subdirectory("${CMAKE_SOURCE_DIR}/src/${NAME}")
|
|
||||||
endfunction()
|
|
||||||
@@ -1,11 +1,7 @@
|
|||||||
#ifndef JUICEAGENT_H
|
#ifndef JUICEAGENT_H
|
||||||
#define JUICEAGENT_H
|
#define JUICEAGENT_H
|
||||||
|
|
||||||
#define INJECT_PATH_MAX 4096
|
#define INJECT_PATH_MAX 260
|
||||||
|
|
||||||
typedef struct InjectParams{
|
|
||||||
char ConfigDir[INJECT_PATH_MAX];
|
|
||||||
} InjectParams;
|
|
||||||
|
|
||||||
typedef struct _InjectionInfo {
|
typedef struct _InjectionInfo {
|
||||||
char BootstrapAPIPath[INJECT_PATH_MAX];
|
char BootstrapAPIPath[INJECT_PATH_MAX];
|
||||||
@@ -14,6 +10,7 @@ typedef struct _InjectionInfo {
|
|||||||
char EntryClass[INJECT_PATH_MAX];
|
char EntryClass[INJECT_PATH_MAX];
|
||||||
char EntryMethod[INJECT_PATH_MAX];
|
char EntryMethod[INJECT_PATH_MAX];
|
||||||
char InjectionDir[INJECT_PATH_MAX];
|
char InjectionDir[INJECT_PATH_MAX];
|
||||||
|
char JuiceLoaderLibraryPath[INJECT_PATH_MAX];
|
||||||
} InjectionInfoType;
|
} InjectionInfoType;
|
||||||
|
|
||||||
extern InjectionInfoType InjectionInfo;
|
extern InjectionInfoType InjectionInfo;
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
add_library(ReflectiveDLLInjection STATIC
|
||||||
|
GetProcAddressR.c
|
||||||
|
LoadLibraryR.c
|
||||||
|
ReflectiveLoader.c
|
||||||
|
)
|
||||||
|
|
||||||
|
target_include_directories(ReflectiveDLLInjection PUBLIC
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}
|
||||||
|
)
|
||||||
|
|
||||||
|
target_compile_definitions(ReflectiveDLLInjection PRIVATE REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR)
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
//===============================================================================================//
|
||||||
|
// 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 "GetProcAddressR.h"
|
||||||
|
#define WIN_X64
|
||||||
|
//===============================================================================================//
|
||||||
|
// We implement a minimal GetProcAddress to avoid using the native kernel32!GetProcAddress which
|
||||||
|
// wont be able to resolve exported addresses in reflectivly loaded librarys.
|
||||||
|
FARPROC WINAPI GetProcAddressR( HANDLE hModule, LPCSTR lpProcName )
|
||||||
|
{
|
||||||
|
UINT_PTR uiLibraryAddress = 0;
|
||||||
|
FARPROC fpResult = NULL;
|
||||||
|
|
||||||
|
if( hModule == NULL )
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
// a module handle is really its base address
|
||||||
|
uiLibraryAddress = (UINT_PTR)hModule;
|
||||||
|
UINT_PTR uiAddressArray = 0;
|
||||||
|
UINT_PTR uiNameArray = 0;
|
||||||
|
UINT_PTR uiNameOrdinals = 0;
|
||||||
|
PIMAGE_NT_HEADERS pNtHeaders = NULL;
|
||||||
|
PIMAGE_DATA_DIRECTORY pDataDirectory = NULL;
|
||||||
|
PIMAGE_EXPORT_DIRECTORY pExportDirectory = NULL;
|
||||||
|
|
||||||
|
// get the VA of the modules NT Header
|
||||||
|
pNtHeaders = (PIMAGE_NT_HEADERS)(uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew);
|
||||||
|
|
||||||
|
pDataDirectory = (PIMAGE_DATA_DIRECTORY)&pNtHeaders->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
|
||||||
|
|
||||||
|
// get the VA of the export directory
|
||||||
|
pExportDirectory = (PIMAGE_EXPORT_DIRECTORY)( uiLibraryAddress + pDataDirectory->VirtualAddress );
|
||||||
|
|
||||||
|
// get the VA for the array of addresses
|
||||||
|
uiAddressArray = ( uiLibraryAddress + pExportDirectory->AddressOfFunctions );
|
||||||
|
|
||||||
|
// get the VA for the array of name pointers
|
||||||
|
uiNameArray = ( uiLibraryAddress + pExportDirectory->AddressOfNames );
|
||||||
|
|
||||||
|
// get the VA for the array of name ordinals
|
||||||
|
uiNameOrdinals = ( uiLibraryAddress + pExportDirectory->AddressOfNameOrdinals );
|
||||||
|
|
||||||
|
// test if we are importing by name or by ordinal...
|
||||||
|
if( ((ULONG_PTR)lpProcName & 0xFFFF0000 ) == 0x00000000 )
|
||||||
|
{
|
||||||
|
// import by ordinal...
|
||||||
|
|
||||||
|
// use the import ordinal (- export ordinal base) as an index into the array of addresses
|
||||||
|
uiAddressArray += ( ( IMAGE_ORDINAL( (ULONG_PTR)lpProcName ) - pExportDirectory->Base ) * sizeof(DWORD) );
|
||||||
|
|
||||||
|
// resolve the address for this imported function
|
||||||
|
fpResult = (FARPROC)( uiLibraryAddress + DEREF_32(uiAddressArray) );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// import by name...
|
||||||
|
DWORD dwCounter = pExportDirectory->NumberOfNames;
|
||||||
|
while( dwCounter-- )
|
||||||
|
{
|
||||||
|
char * cpExportedFunctionName = (char *)(uiLibraryAddress + DEREF_32( uiNameArray ));
|
||||||
|
|
||||||
|
// test if we have a match...
|
||||||
|
if( strcmp( cpExportedFunctionName, lpProcName ) == 0 )
|
||||||
|
{
|
||||||
|
// use the functions name ordinal as an index into the array of name pointers
|
||||||
|
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
|
||||||
|
|
||||||
|
// calculate the virtual address for the function
|
||||||
|
fpResult = (FARPROC)(uiLibraryAddress + DEREF_32( uiAddressArray ));
|
||||||
|
|
||||||
|
// finish...
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// get the next exported function name
|
||||||
|
uiNameArray += sizeof(DWORD);
|
||||||
|
|
||||||
|
// get the next exported function name ordinal
|
||||||
|
uiNameOrdinals += sizeof(WORD);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fpResult;
|
||||||
|
}
|
||||||
|
//===============================================================================================//
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
//===============================================================================================//
|
||||||
|
// 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.
|
||||||
|
//===============================================================================================//
|
||||||
|
#ifndef _REFLECTIVEDLLINJECTION_GETPROCADDRESSR_H
|
||||||
|
#define _REFLECTIVEDLLINJECTION_GETPROCADDRESSR_H
|
||||||
|
//===============================================================================================//
|
||||||
|
#include "ReflectiveDLLInjection.h"
|
||||||
|
|
||||||
|
FARPROC WINAPI GetProcAddressR( HANDLE hModule, LPCSTR lpProcName );
|
||||||
|
//===============================================================================================//
|
||||||
|
#endif
|
||||||
|
//===============================================================================================//
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
//===============================================================================================//
|
||||||
|
// 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 "LoadLibraryR.h"
|
||||||
|
#include <stdio.h>
|
||||||
|
#define WIN_X64
|
||||||
|
|
||||||
|
//===============================================================================================//
|
||||||
|
DWORD Rva2Offset( DWORD dwRva, UINT_PTR uiBaseAddress )
|
||||||
|
{
|
||||||
|
WORD wIndex = 0;
|
||||||
|
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
|
||||||
|
PIMAGE_NT_HEADERS pNtHeaders = NULL;
|
||||||
|
|
||||||
|
pNtHeaders = (PIMAGE_NT_HEADERS)(uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew);
|
||||||
|
|
||||||
|
pSectionHeader = (PIMAGE_SECTION_HEADER)((UINT_PTR)(&pNtHeaders->OptionalHeader) + pNtHeaders->FileHeader.SizeOfOptionalHeader);
|
||||||
|
|
||||||
|
if( dwRva < pSectionHeader[0].PointerToRawData )
|
||||||
|
return dwRva;
|
||||||
|
|
||||||
|
for( wIndex=0 ; wIndex < pNtHeaders->FileHeader.NumberOfSections ; wIndex++ )
|
||||||
|
{
|
||||||
|
if( dwRva >= pSectionHeader[wIndex].VirtualAddress && dwRva < (pSectionHeader[wIndex].VirtualAddress + pSectionHeader[wIndex].SizeOfRawData) )
|
||||||
|
return ( dwRva - pSectionHeader[wIndex].VirtualAddress + pSectionHeader[wIndex].PointerToRawData );
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
//===============================================================================================//
|
||||||
|
DWORD GetReflectiveLoaderOffset( VOID * lpReflectiveDllBuffer )
|
||||||
|
{
|
||||||
|
UINT_PTR uiBaseAddress = 0;
|
||||||
|
UINT_PTR uiExportDir = 0;
|
||||||
|
UINT_PTR uiNameArray = 0;
|
||||||
|
UINT_PTR uiAddressArray = 0;
|
||||||
|
UINT_PTR uiNameOrdinals = 0;
|
||||||
|
DWORD dwCounter = 0;
|
||||||
|
#ifdef WIN_X64
|
||||||
|
DWORD dwCompiledArch = 2;
|
||||||
|
#else
|
||||||
|
// This will catch Win32 and WinRT.
|
||||||
|
DWORD dwCompiledArch = 1;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
uiBaseAddress = (UINT_PTR)lpReflectiveDllBuffer;
|
||||||
|
|
||||||
|
// get the File Offset of the modules NT Header
|
||||||
|
uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew;
|
||||||
|
|
||||||
|
// currenlty we can only process a PE file which is the same type as the one this fuction has
|
||||||
|
// been compiled as, due to various offset in the PE structures being defined at compile time.
|
||||||
|
if( ((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.Magic == 0x010B ) // PE32
|
||||||
|
{
|
||||||
|
if( dwCompiledArch != 1 )
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
else if( ((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.Magic == 0x020B ) // PE64
|
||||||
|
{
|
||||||
|
if( dwCompiledArch != 2 )
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// uiNameArray = the address of the modules export directory entry
|
||||||
|
uiNameArray = (UINT_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
|
||||||
|
|
||||||
|
// get the File Offset of the export directory
|
||||||
|
uiExportDir = uiBaseAddress + Rva2Offset( ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress, uiBaseAddress );
|
||||||
|
|
||||||
|
// get the File Offset for the array of name pointers
|
||||||
|
uiNameArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames, uiBaseAddress );
|
||||||
|
|
||||||
|
// get the File Offset for the array of addresses
|
||||||
|
uiAddressArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions, uiBaseAddress );
|
||||||
|
|
||||||
|
// get the File Offset for the array of name ordinals
|
||||||
|
uiNameOrdinals = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals, uiBaseAddress );
|
||||||
|
|
||||||
|
// get a counter for the number of exported functions...
|
||||||
|
dwCounter = ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->NumberOfNames;
|
||||||
|
|
||||||
|
// loop through all the exported functions to find the ReflectiveLoader
|
||||||
|
while( dwCounter-- )
|
||||||
|
{
|
||||||
|
char * cpExportedFunctionName = (char *)(uiBaseAddress + Rva2Offset( DEREF_32( uiNameArray ), uiBaseAddress ));
|
||||||
|
|
||||||
|
if( strstr( cpExportedFunctionName, "ReflectiveLoader" ) != NULL )
|
||||||
|
{
|
||||||
|
// get the File Offset for the array of addresses
|
||||||
|
uiAddressArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions, uiBaseAddress );
|
||||||
|
|
||||||
|
// use the functions name ordinal as an index into the array of name pointers
|
||||||
|
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
|
||||||
|
|
||||||
|
// return the File Offset to the ReflectiveLoader() functions code...
|
||||||
|
return Rva2Offset( DEREF_32( uiAddressArray ), uiBaseAddress );
|
||||||
|
}
|
||||||
|
// get the next exported function name
|
||||||
|
uiNameArray += sizeof(DWORD);
|
||||||
|
|
||||||
|
// get the next exported function name ordinal
|
||||||
|
uiNameOrdinals += sizeof(WORD);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
//===============================================================================================//
|
||||||
|
// Loads a DLL image from memory via its exported ReflectiveLoader function
|
||||||
|
HMODULE WINAPI LoadLibraryR( LPVOID lpBuffer, DWORD dwLength )
|
||||||
|
{
|
||||||
|
HMODULE hResult = NULL;
|
||||||
|
DWORD dwReflectiveLoaderOffset = 0;
|
||||||
|
DWORD dwOldProtect1 = 0;
|
||||||
|
DWORD dwOldProtect2 = 0;
|
||||||
|
REFLECTIVELOADER pReflectiveLoader = NULL;
|
||||||
|
DLLMAIN pDllMain = NULL;
|
||||||
|
|
||||||
|
if( lpBuffer == NULL || dwLength == 0 )
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
// check if the library has a ReflectiveLoader...
|
||||||
|
dwReflectiveLoaderOffset = GetReflectiveLoaderOffset( lpBuffer );
|
||||||
|
if( dwReflectiveLoaderOffset != 0 )
|
||||||
|
{
|
||||||
|
pReflectiveLoader = (REFLECTIVELOADER)((UINT_PTR)lpBuffer + dwReflectiveLoaderOffset);
|
||||||
|
|
||||||
|
// we must VirtualProtect the buffer to RWX so we can execute the ReflectiveLoader...
|
||||||
|
// this assumes lpBuffer is the base address of the region of pages and dwLength the size of the region
|
||||||
|
if( VirtualProtect( lpBuffer, dwLength, PAGE_EXECUTE_READWRITE, &dwOldProtect1 ) )
|
||||||
|
{
|
||||||
|
// call the librarys ReflectiveLoader...
|
||||||
|
pDllMain = (DLLMAIN)pReflectiveLoader();
|
||||||
|
if( pDllMain != NULL )
|
||||||
|
{
|
||||||
|
// call the loaded librarys DllMain to get its HMODULE
|
||||||
|
if( !pDllMain( NULL, DLL_QUERY_HMODULE, &hResult ) )
|
||||||
|
hResult = NULL;
|
||||||
|
}
|
||||||
|
// revert to the previous protection flags...
|
||||||
|
VirtualProtect( lpBuffer, dwLength, dwOldProtect1, &dwOldProtect2 );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return hResult;
|
||||||
|
}
|
||||||
|
//===============================================================================================//
|
||||||
|
// Loads a PE image from memory into the address space of a host process via the image's exported ReflectiveLoader function
|
||||||
|
// Note: You must compile whatever you are injecting with REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
|
||||||
|
// defined in order to use the correct RDI prototypes.
|
||||||
|
// Note: The hProcess handle must have these access rights: PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
|
||||||
|
// PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ
|
||||||
|
// Note: If you are passing in an lpParameter value, if it is a pointer, remember it is for a different address space.
|
||||||
|
// Note: This function currently cant inject accross architectures, but only to architectures which are the
|
||||||
|
// same as the arch this function is compiled as, e.g. x86->x86 and x64->x64 but not x64->x86 or x86->x64.
|
||||||
|
HANDLE WINAPI LoadRemoteLibraryR( HANDLE hProcess, LPVOID lpBuffer, DWORD dwLength, LPVOID lpParameter )
|
||||||
|
{
|
||||||
|
BOOL bSuccess = FALSE;
|
||||||
|
LPVOID lpRemoteLibraryBuffer = NULL;
|
||||||
|
LPTHREAD_START_ROUTINE lpReflectiveLoader = NULL;
|
||||||
|
HANDLE hThread = NULL;
|
||||||
|
DWORD dwReflectiveLoaderOffset = 0;
|
||||||
|
DWORD dwThreadId = 0;
|
||||||
|
|
||||||
|
do
|
||||||
|
{
|
||||||
|
if( !hProcess || !lpBuffer || !dwLength )
|
||||||
|
break;
|
||||||
|
|
||||||
|
// check if the library has a ReflectiveLoader...
|
||||||
|
dwReflectiveLoaderOffset = GetReflectiveLoaderOffset( lpBuffer );
|
||||||
|
if( !dwReflectiveLoaderOffset )
|
||||||
|
break;
|
||||||
|
|
||||||
|
// alloc memory (RWX) in the host process for the image...
|
||||||
|
lpRemoteLibraryBuffer = VirtualAllocEx( hProcess, NULL, dwLength, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
|
||||||
|
if( !lpRemoteLibraryBuffer )
|
||||||
|
break;
|
||||||
|
|
||||||
|
// write the image into the host process...
|
||||||
|
if( !WriteProcessMemory( hProcess, lpRemoteLibraryBuffer, lpBuffer, dwLength, NULL ) )
|
||||||
|
break;
|
||||||
|
|
||||||
|
// add the offset to ReflectiveLoader() to the remote library address...
|
||||||
|
lpReflectiveLoader = (LPTHREAD_START_ROUTINE)( (ULONG_PTR)lpRemoteLibraryBuffer + dwReflectiveLoaderOffset );
|
||||||
|
|
||||||
|
// create a remote thread in the host process to call the ReflectiveLoader!
|
||||||
|
hThread = CreateRemoteThread( hProcess, NULL, 1024*1024, lpReflectiveLoader, lpParameter, (DWORD_PTR)NULL, &dwThreadId );
|
||||||
|
|
||||||
|
} while( 0 );
|
||||||
|
|
||||||
|
return hThread;
|
||||||
|
}
|
||||||
|
//===============================================================================================//
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
//===============================================================================================//
|
||||||
|
// 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.
|
||||||
|
//===============================================================================================//
|
||||||
|
#ifndef _REFLECTIVEDLLINJECTION_LOADLIBRARYR_H
|
||||||
|
#define _REFLECTIVEDLLINJECTION_LOADLIBRARYR_H
|
||||||
|
//===============================================================================================//
|
||||||
|
#include "ReflectiveDLLInjection.h"
|
||||||
|
|
||||||
|
DWORD GetReflectiveLoaderOffset( VOID * lpReflectiveDllBuffer );
|
||||||
|
|
||||||
|
HMODULE WINAPI LoadLibraryR( LPVOID lpBuffer, DWORD dwLength );
|
||||||
|
|
||||||
|
HANDLE WINAPI LoadRemoteLibraryR( HANDLE hProcess, LPVOID lpBuffer, DWORD dwLength, LPVOID lpParameter );
|
||||||
|
|
||||||
|
//===============================================================================================//
|
||||||
|
#endif
|
||||||
|
//===============================================================================================//
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
//===============================================================================================//
|
||||||
|
// 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.
|
||||||
|
//===============================================================================================//
|
||||||
|
#ifndef _REFLECTIVEDLLINJECTION_REFLECTIVEDLLINJECTION_H
|
||||||
|
#define _REFLECTIVEDLLINJECTION_REFLECTIVEDLLINJECTION_H
|
||||||
|
//===============================================================================================//
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#include <windows.h>
|
||||||
|
|
||||||
|
// we declare some common stuff in here...
|
||||||
|
|
||||||
|
#define DLL_METASPLOIT_ATTACH 4
|
||||||
|
#define DLL_METASPLOIT_DETACH 5
|
||||||
|
#define DLL_QUERY_HMODULE 6
|
||||||
|
|
||||||
|
#define DEREF( name )*(UINT_PTR *)(name)
|
||||||
|
#define DEREF_64( name )*(DWORD64 *)(name)
|
||||||
|
#define DEREF_32( name )*(DWORD *)(name)
|
||||||
|
#define DEREF_16( name )*(WORD *)(name)
|
||||||
|
#define DEREF_8( name )*(BYTE *)(name)
|
||||||
|
|
||||||
|
typedef ULONG_PTR (WINAPI * REFLECTIVELOADER)( VOID );
|
||||||
|
typedef BOOL (WINAPI * DLLMAIN)( HINSTANCE, DWORD, LPVOID );
|
||||||
|
|
||||||
|
#define DLLEXPORT __declspec( dllexport )
|
||||||
|
|
||||||
|
//===============================================================================================//
|
||||||
|
#endif
|
||||||
|
//===============================================================================================//
|
||||||
@@ -0,0 +1,480 @@
|
|||||||
|
//===============================================================================================//
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
//===============================================================================================//
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
|
||||||
|
// 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.
|
||||||
|
|
||||||
|
#ifndef _REFLECTIVEDLLINJECTION_REFLECTIVELOADER_H
|
||||||
|
#define _REFLECTIVEDLLINJECTION_REFLECTIVELOADER_H
|
||||||
|
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
|
||||||
|
#include <Winsock2.h>
|
||||||
|
|
||||||
|
#include <windows.h>
|
||||||
|
#include <intrin.h>
|
||||||
|
#define WIN_X64
|
||||||
|
|
||||||
|
#include "ReflectiveDLLInjection.h"
|
||||||
|
|
||||||
|
typedef HMODULE (WINAPI *LOADLIBRARYA)(LPCSTR);
|
||||||
|
|
||||||
|
typedef FARPROC (WINAPI *GETPROCADDRESS)(HMODULE, LPCSTR);
|
||||||
|
|
||||||
|
typedef LPVOID (WINAPI *VIRTUALALLOC)(LPVOID, SIZE_T, DWORD, DWORD);
|
||||||
|
|
||||||
|
typedef DWORD (NTAPI *NTFLUSHINSTRUCTIONCACHE)(HANDLE, PVOID, ULONG);
|
||||||
|
|
||||||
|
#define KERNEL32DLL_HASH 0x6A4ABC5B
|
||||||
|
#define NTDLLDLL_HASH 0x3CFA685D
|
||||||
|
|
||||||
|
#define LOADLIBRARYA_HASH 0xEC0E4E8E
|
||||||
|
#define GETPROCADDRESS_HASH 0x7C0DFCAA
|
||||||
|
#define VIRTUALALLOC_HASH 0x91AFCA54
|
||||||
|
#define NTFLUSHINSTRUCTIONCACHE_HASH 0x534C0AB8
|
||||||
|
|
||||||
|
#define IMAGE_REL_BASED_ARM_MOV32A 5
|
||||||
|
#define IMAGE_REL_BASED_ARM_MOV32T 7
|
||||||
|
|
||||||
|
#define ARM_MOV_MASK (DWORD)(0xFBF08000)
|
||||||
|
#define ARM_MOV_MASK2 (DWORD)(0xFBF08F00)
|
||||||
|
#define ARM_MOVW 0xF2400000
|
||||||
|
#define ARM_MOVT 0xF2C00000
|
||||||
|
|
||||||
|
#define HASH_KEY 13
|
||||||
|
|
||||||
|
#pragma intrinsic( _rotr )
|
||||||
|
|
||||||
|
__forceinline DWORD ror(DWORD d) {
|
||||||
|
return _rotr(d, HASH_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
__forceinline DWORD hash(char *c) {
|
||||||
|
DWORD h = 0;
|
||||||
|
do {
|
||||||
|
h = ror(h);
|
||||||
|
h += *c;
|
||||||
|
} while (*++c);
|
||||||
|
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct _UNICODE_STR {
|
||||||
|
USHORT Length;
|
||||||
|
USHORT MaximumLength;
|
||||||
|
PWSTR pBuffer;
|
||||||
|
} UNICODE_STR, *PUNICODE_STR;
|
||||||
|
|
||||||
|
// WinDbg> dt -v ntdll!_LDR_DATA_TABLE_ENTRY
|
||||||
|
//__declspec( align(8) )
|
||||||
|
typedef struct _LDR_DATA_TABLE_ENTRY {
|
||||||
|
//LIST_ENTRY InLoadOrderLinks; // As we search from PPEB_LDR_DATA->InMemoryOrderModuleList we dont use the first entry.
|
||||||
|
LIST_ENTRY InMemoryOrderModuleList;
|
||||||
|
LIST_ENTRY InInitializationOrderModuleList;
|
||||||
|
PVOID DllBase;
|
||||||
|
PVOID EntryPoint;
|
||||||
|
ULONG SizeOfImage;
|
||||||
|
UNICODE_STR FullDllName;
|
||||||
|
UNICODE_STR BaseDllName;
|
||||||
|
ULONG Flags;
|
||||||
|
SHORT LoadCount;
|
||||||
|
SHORT TlsIndex;
|
||||||
|
LIST_ENTRY HashTableEntry;
|
||||||
|
ULONG TimeDateStamp;
|
||||||
|
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
|
||||||
|
|
||||||
|
// WinDbg> dt -v ntdll!_PEB_LDR_DATA
|
||||||
|
typedef struct _PEB_LDR_DATA //, 7 elements, 0x28 bytes
|
||||||
|
{
|
||||||
|
DWORD dwLength;
|
||||||
|
DWORD dwInitialized;
|
||||||
|
LPVOID lpSsHandle;
|
||||||
|
LIST_ENTRY InLoadOrderModuleList;
|
||||||
|
LIST_ENTRY InMemoryOrderModuleList;
|
||||||
|
LIST_ENTRY InInitializationOrderModuleList;
|
||||||
|
LPVOID lpEntryInProgress;
|
||||||
|
} PEB_LDR_DATA, *PPEB_LDR_DATA;
|
||||||
|
|
||||||
|
// WinDbg> dt -v ntdll!_PEB_FREE_BLOCK
|
||||||
|
typedef struct _PEB_FREE_BLOCK // 2 elements, 0x8 bytes
|
||||||
|
{
|
||||||
|
struct _PEB_FREE_BLOCK *pNext;
|
||||||
|
DWORD dwSize;
|
||||||
|
} PEB_FREE_BLOCK, *PPEB_FREE_BLOCK;
|
||||||
|
|
||||||
|
// struct _PEB is defined in Winternl.h but it is incomplete
|
||||||
|
// WinDbg> dt -v ntdll!_PEB
|
||||||
|
typedef struct __PEB // 65 elements, 0x210 bytes
|
||||||
|
{
|
||||||
|
BYTE bInheritedAddressSpace;
|
||||||
|
BYTE bReadImageFileExecOptions;
|
||||||
|
BYTE bBeingDebugged;
|
||||||
|
BYTE bSpareBool;
|
||||||
|
LPVOID lpMutant;
|
||||||
|
LPVOID lpImageBaseAddress;
|
||||||
|
PPEB_LDR_DATA pLdr;
|
||||||
|
LPVOID lpProcessParameters;
|
||||||
|
LPVOID lpSubSystemData;
|
||||||
|
LPVOID lpProcessHeap;
|
||||||
|
PRTL_CRITICAL_SECTION pFastPebLock;
|
||||||
|
LPVOID lpFastPebLockRoutine;
|
||||||
|
LPVOID lpFastPebUnlockRoutine;
|
||||||
|
DWORD dwEnvironmentUpdateCount;
|
||||||
|
LPVOID lpKernelCallbackTable;
|
||||||
|
DWORD dwSystemReserved;
|
||||||
|
DWORD dwAtlThunkSListPtr32;
|
||||||
|
PPEB_FREE_BLOCK pFreeList;
|
||||||
|
DWORD dwTlsExpansionCounter;
|
||||||
|
LPVOID lpTlsBitmap;
|
||||||
|
DWORD dwTlsBitmapBits[2];
|
||||||
|
LPVOID lpReadOnlySharedMemoryBase;
|
||||||
|
LPVOID lpReadOnlySharedMemoryHeap;
|
||||||
|
LPVOID lpReadOnlyStaticServerData;
|
||||||
|
LPVOID lpAnsiCodePageData;
|
||||||
|
LPVOID lpOemCodePageData;
|
||||||
|
LPVOID lpUnicodeCaseTableData;
|
||||||
|
DWORD dwNumberOfProcessors;
|
||||||
|
DWORD dwNtGlobalFlag;
|
||||||
|
LARGE_INTEGER liCriticalSectionTimeout;
|
||||||
|
DWORD dwHeapSegmentReserve;
|
||||||
|
DWORD dwHeapSegmentCommit;
|
||||||
|
DWORD dwHeapDeCommitTotalFreeThreshold;
|
||||||
|
DWORD dwHeapDeCommitFreeBlockThreshold;
|
||||||
|
DWORD dwNumberOfHeaps;
|
||||||
|
DWORD dwMaximumNumberOfHeaps;
|
||||||
|
LPVOID lpProcessHeaps;
|
||||||
|
LPVOID lpGdiSharedHandleTable;
|
||||||
|
LPVOID lpProcessStarterHelper;
|
||||||
|
DWORD dwGdiDCAttributeList;
|
||||||
|
LPVOID lpLoaderLock;
|
||||||
|
DWORD dwOSMajorVersion;
|
||||||
|
DWORD dwOSMinorVersion;
|
||||||
|
WORD wOSBuildNumber;
|
||||||
|
WORD wOSCSDVersion;
|
||||||
|
DWORD dwOSPlatformId;
|
||||||
|
DWORD dwImageSubsystem;
|
||||||
|
DWORD dwImageSubsystemMajorVersion;
|
||||||
|
DWORD dwImageSubsystemMinorVersion;
|
||||||
|
DWORD dwImageProcessAffinityMask;
|
||||||
|
DWORD dwGdiHandleBuffer[34];
|
||||||
|
LPVOID lpPostProcessInitRoutine;
|
||||||
|
LPVOID lpTlsExpansionBitmap;
|
||||||
|
DWORD dwTlsExpansionBitmapBits[32];
|
||||||
|
DWORD dwSessionId;
|
||||||
|
ULARGE_INTEGER liAppCompatFlags;
|
||||||
|
ULARGE_INTEGER liAppCompatFlagsUser;
|
||||||
|
LPVOID lppShimData;
|
||||||
|
LPVOID lpAppCompatInfo;
|
||||||
|
UNICODE_STR usCSDVersion;
|
||||||
|
LPVOID lpActivationContextData;
|
||||||
|
LPVOID lpProcessAssemblyStorageMap;
|
||||||
|
LPVOID lpSystemDefaultActivationContextData;
|
||||||
|
LPVOID lpSystemAssemblyStorageMap;
|
||||||
|
DWORD dwMinimumStackCommit;
|
||||||
|
} _PEB, *_PPEB;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
WORD offset: 12;
|
||||||
|
WORD type: 4;
|
||||||
|
} IMAGE_RELOC, *PIMAGE_RELOC;
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
/scanvalue
|
|
||||||
/scankey
|
|
||||||
/parser
|
|
||||||
/*.so.*
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
# includes/tomlc17/CMakeLists.txt
|
|
||||||
|
|
||||||
add_library(tomlc17 STATIC tomlc17.c)
|
|
||||||
set_target_properties(tomlc17 PROPERTIES
|
|
||||||
OUTPUT_NAME "tomlc17"
|
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(tomlc17 PUBLIC
|
|
||||||
${CMAKE_CURRENT_SOURCE_DIR}
|
|
||||||
)
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
HFILES = tomlc17.h
|
|
||||||
CFILES = tomlc17.c
|
|
||||||
OBJ = $(CFILES:.c=.o)
|
|
||||||
|
|
||||||
CFLAGS = -std=c17 -fpic -Wmissing-declarations -Wall -Wextra -MMD
|
|
||||||
LIB_VERSION = 1.0
|
|
||||||
LIB = libtomlc17.a
|
|
||||||
LIB_SHARED = libtomlc17.so.$(LIB_VERSION)
|
|
||||||
EXEC =
|
|
||||||
|
|
||||||
ifdef DEBUG
|
|
||||||
CFLAGS += -O0 -g
|
|
||||||
else
|
|
||||||
CFLAGS += -O3 -DNDEBUG
|
|
||||||
endif
|
|
||||||
|
|
||||||
all: $(EXEC) $(LIB) $(LIB_SHARED)
|
|
||||||
|
|
||||||
*.o: $(HFILES)
|
|
||||||
|
|
||||||
libtomlc17.a: tomlc17.o
|
|
||||||
ar -rcs $@ $^
|
|
||||||
|
|
||||||
$(LIB_SHARED): tomlc17.o
|
|
||||||
$(CC) -shared -o $@ $^
|
|
||||||
|
|
||||||
-include $(OBJ:%.o=%.d) $(EXEC:%=%.d)
|
|
||||||
|
|
||||||
test: all
|
|
||||||
|
|
||||||
clean:
|
|
||||||
rm -f *.o *.d *.a *.so.* $(EXEC)
|
|
||||||
|
|
||||||
distclean: clean
|
|
||||||
|
|
||||||
format:
|
|
||||||
clang-format -i *.[ch] *.hpp
|
|
||||||
|
|
||||||
|
|
||||||
.PHONY: all clean distclean format
|
|
||||||
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,190 +0,0 @@
|
|||||||
/* Copyright (c) 2024-2025, CK Tan.
|
|
||||||
* https://github.com/cktan/tomlc17/blob/main/LICENSE
|
|
||||||
*/
|
|
||||||
#ifndef TOMLC17_H
|
|
||||||
#define TOMLC17_H
|
|
||||||
|
|
||||||
/*
|
|
||||||
* USAGE:
|
|
||||||
*
|
|
||||||
* 1. Call toml_parse(), toml_parse_file(), or toml_parse_file_ex()
|
|
||||||
* 2. Check result.ok
|
|
||||||
* 3. Use toml_get() or toml_seek() to query and traverse the
|
|
||||||
* result.toptab
|
|
||||||
* 4. Call toml_free() to release resources.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <stdbool.h>
|
|
||||||
#include <stdint.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
#define TOML_EXTERN extern "C"
|
|
||||||
#else
|
|
||||||
#define TOML_EXTERN extern
|
|
||||||
#endif
|
|
||||||
|
|
||||||
enum toml_type_t {
|
|
||||||
TOML_UNKNOWN = 0,
|
|
||||||
TOML_STRING,
|
|
||||||
TOML_INT64,
|
|
||||||
TOML_FP64,
|
|
||||||
TOML_BOOLEAN,
|
|
||||||
TOML_DATE,
|
|
||||||
TOML_TIME,
|
|
||||||
TOML_DATETIME,
|
|
||||||
TOML_DATETIMETZ,
|
|
||||||
TOML_ARRAY,
|
|
||||||
TOML_TABLE,
|
|
||||||
};
|
|
||||||
typedef enum toml_type_t toml_type_t;
|
|
||||||
|
|
||||||
/* This is a Node in a Tree that represents a toml document rooted
|
|
||||||
* at toml_result_t::toptab.
|
|
||||||
*/
|
|
||||||
typedef struct toml_datum_t toml_datum_t;
|
|
||||||
struct toml_datum_t {
|
|
||||||
toml_type_t type;
|
|
||||||
uint32_t flag; // internal
|
|
||||||
union {
|
|
||||||
const char *s; // same as str.ptr; use if there are no NUL in string.
|
|
||||||
struct {
|
|
||||||
const char *ptr; // NUL terminated string
|
|
||||||
int len; // length excluding the terminating NUL.
|
|
||||||
} str;
|
|
||||||
int64_t int64; // integer
|
|
||||||
double fp64; // float
|
|
||||||
bool boolean;
|
|
||||||
struct { // date, time
|
|
||||||
int16_t year, month, day;
|
|
||||||
int16_t hour, minute, second;
|
|
||||||
int32_t usec;
|
|
||||||
int16_t tz; // in minutes
|
|
||||||
} ts;
|
|
||||||
struct { // array
|
|
||||||
int32_t size; // count elem
|
|
||||||
toml_datum_t *elem; // elem[]
|
|
||||||
} arr;
|
|
||||||
struct { // table
|
|
||||||
int32_t size; // count key
|
|
||||||
const char **key; // key[]
|
|
||||||
int *len; // len[]
|
|
||||||
toml_datum_t *value; // value[]
|
|
||||||
} tab;
|
|
||||||
} u;
|
|
||||||
};
|
|
||||||
|
|
||||||
/* Result returned by toml_parse() */
|
|
||||||
typedef struct toml_result_t toml_result_t;
|
|
||||||
struct toml_result_t {
|
|
||||||
bool ok; // success flag
|
|
||||||
toml_datum_t toptab; // valid if ok
|
|
||||||
char errmsg[200]; // valid if not ok
|
|
||||||
void *__internal; // do not use
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a toml document. Returns a toml_result which must be freed
|
|
||||||
* using toml_free() eventually.
|
|
||||||
*
|
|
||||||
* IMPORTANT: src[] must be a NUL terminated string! The len parameter
|
|
||||||
* does not include the NUL terminator.
|
|
||||||
*/
|
|
||||||
TOML_EXTERN toml_result_t toml_parse(const char *src, int len);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a toml file. Returns a toml_result which must be freed
|
|
||||||
* using toml_free() eventually.
|
|
||||||
*
|
|
||||||
* IMPORTANT: you are still responsible to fclose(fp).
|
|
||||||
*/
|
|
||||||
TOML_EXTERN toml_result_t toml_parse_file(FILE *fp);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a toml file. Returns a toml_result which must be freed
|
|
||||||
* using toml_free() eventually.
|
|
||||||
*/
|
|
||||||
TOML_EXTERN toml_result_t toml_parse_file_ex(const char *fname);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Release the result.
|
|
||||||
*/
|
|
||||||
TOML_EXTERN void toml_free(toml_result_t result);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Find a key in a toml_table. Return the value of the key if found,
|
|
||||||
* or a TOML_UNKNOWN otherwise.
|
|
||||||
*/
|
|
||||||
TOML_EXTERN toml_datum_t toml_get(toml_datum_t table, const char *key);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Locate a value starting from a toml_table. Return the value of the key if
|
|
||||||
* found, or a TOML_UNKNOWN otherwise.
|
|
||||||
*
|
|
||||||
* Note: the multipart-key is separated by DOT, and must not have any escape
|
|
||||||
* chars.
|
|
||||||
*/
|
|
||||||
TOML_EXTERN toml_datum_t toml_seek(toml_datum_t table,
|
|
||||||
const char *multipart_key);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* OBSOLETE: use toml_get() instead.
|
|
||||||
* Find a key in a toml_table. Return the value of the key if found,
|
|
||||||
* or a TOML_UNKNOWN otherwise. (
|
|
||||||
*/
|
|
||||||
static inline toml_datum_t toml_table_find(toml_datum_t table,
|
|
||||||
const char *key) {
|
|
||||||
return toml_get(table, key);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Override values in r1 using r2. Return a new result. All results
|
|
||||||
* (i.e., r1, r2 and the returned result) must be freed using toml_free()
|
|
||||||
* after use.
|
|
||||||
*
|
|
||||||
* LOGIC:
|
|
||||||
* ret = copy of r1
|
|
||||||
* for each item x in r2:
|
|
||||||
* if x is not in ret:
|
|
||||||
* override
|
|
||||||
* elif x in ret is NOT of the same type:
|
|
||||||
* override
|
|
||||||
* elif x is an array of tables:
|
|
||||||
* append r2.x to ret.x
|
|
||||||
* elif x is a table:
|
|
||||||
* merge r2.x to ret.x
|
|
||||||
* else:
|
|
||||||
* override
|
|
||||||
*/
|
|
||||||
TOML_EXTERN toml_result_t toml_merge(const toml_result_t *r1,
|
|
||||||
const toml_result_t *r2);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if two results are the same. Dictinary and array orders are
|
|
||||||
* sensitive.
|
|
||||||
*/
|
|
||||||
TOML_EXTERN bool toml_equiv(const toml_result_t *r1, const toml_result_t *r2);
|
|
||||||
|
|
||||||
/* Options that override tomlc17 defaults globally */
|
|
||||||
typedef struct toml_option_t toml_option_t;
|
|
||||||
struct toml_option_t {
|
|
||||||
bool check_utf8; // Check all chars are valid utf8; default: false.
|
|
||||||
void *(*mem_realloc)(void *ptr, size_t size); // default: realloc()
|
|
||||||
void (*mem_free)(void *ptr); // default: free()
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the default options. IF NECESSARY, use this to initialize
|
|
||||||
* toml_option_t and override values before calling
|
|
||||||
* toml_set_option().
|
|
||||||
*/
|
|
||||||
TOML_EXTERN toml_option_t toml_default_option(void);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set toml options globally. Do this ONLY IF you are not satisfied with the
|
|
||||||
* defaults.
|
|
||||||
*/
|
|
||||||
TOML_EXTERN void toml_set_option(toml_option_t opt);
|
|
||||||
|
|
||||||
#endif // TOMLC17_H
|
|
||||||
@@ -1,231 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#if !defined(__cplusplus) || __cplusplus < 202002L
|
|
||||||
#error "This code requires C++20 or later"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#include "tomlc17.h"
|
|
||||||
#include <chrono>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <optional>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace toml {
|
|
||||||
|
|
||||||
|
|
||||||
class Datum : public toml_datum_t {
|
|
||||||
public:
|
|
||||||
using datetime = std::chrono::sys_time<std::chrono::microseconds>;
|
|
||||||
using time = std::chrono::hh_mm_ss<std::chrono::microseconds>;
|
|
||||||
using date = std::chrono::year_month_day;
|
|
||||||
|
|
||||||
Datum(toml_datum_t dat = toml_datum_t{}) : toml_datum_t(dat) {}
|
|
||||||
bool is_table() const { return type == TOML_TABLE; }
|
|
||||||
bool is_array() const { return type == TOML_ARRAY; }
|
|
||||||
|
|
||||||
// Retrieve a string.
|
|
||||||
std::optional<std::string_view> as_str() const {
|
|
||||||
if (type != TOML_STRING)
|
|
||||||
return std::nullopt;
|
|
||||||
else
|
|
||||||
return std::string_view{u.str.ptr, (size_t)u.str.len};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve an int.
|
|
||||||
std::optional<std::int64_t> as_int() const {
|
|
||||||
if (type != TOML_INT64)
|
|
||||||
return std::nullopt;
|
|
||||||
else
|
|
||||||
return u.int64;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve a float.
|
|
||||||
std::optional<double> as_real() const {
|
|
||||||
if (type != TOML_FP64)
|
|
||||||
return std::nullopt;
|
|
||||||
else
|
|
||||||
return u.fp64;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve a boolean.
|
|
||||||
std::optional<bool> as_bool() const {
|
|
||||||
if (type != TOML_BOOLEAN)
|
|
||||||
return std::nullopt;
|
|
||||||
else
|
|
||||||
return !!u.boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve a date.
|
|
||||||
std::optional<date> as_date() const {
|
|
||||||
using namespace std::chrono;
|
|
||||||
if (type != TOML_DATE)
|
|
||||||
return std::nullopt;
|
|
||||||
else
|
|
||||||
return date{year(u.ts.year), month(u.ts.month), day(u.ts.day)};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve a time.
|
|
||||||
std::optional<time> as_time() const {
|
|
||||||
using namespace std::chrono;
|
|
||||||
if (type != TOML_TIME)
|
|
||||||
return std::nullopt;
|
|
||||||
else
|
|
||||||
return time{hours(u.ts.hour) + minutes(u.ts.minute) +
|
|
||||||
seconds(u.ts.second) + microseconds(u.ts.usec)};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve a datetime.
|
|
||||||
std::optional<datetime> as_datetime() const {
|
|
||||||
using namespace std::chrono;
|
|
||||||
if (type != TOML_DATETIME) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
year_month_day ymd{year{u.ts.year}, month{(unsigned)u.ts.month},
|
|
||||||
day{(unsigned)u.ts.day}};
|
|
||||||
auto tod = hours{u.ts.hour} + minutes{u.ts.minute} + seconds{u.ts.second} +
|
|
||||||
microseconds{u.ts.usec};
|
|
||||||
return datetime{sys_days{ymd} + tod};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve a datetime and minute offset from UTC.
|
|
||||||
std::optional<std::pair<datetime, int>> as_datetimetz() const {
|
|
||||||
using namespace std::chrono;
|
|
||||||
|
|
||||||
if (type != TOML_DATETIMETZ) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
year_month_day ymd{year{u.ts.year}, month{(unsigned)u.ts.month},
|
|
||||||
day{(unsigned)u.ts.day}};
|
|
||||||
auto tod = hours{u.ts.hour} + minutes{u.ts.minute} + seconds{u.ts.second} +
|
|
||||||
microseconds{u.ts.usec};
|
|
||||||
return std::pair{datetime{sys_days{ymd} + tod}, u.ts.tz};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve an array of Datum from this datum.
|
|
||||||
std::optional<std::vector<Datum>> as_vector() const {
|
|
||||||
if (type != TOML_ARRAY) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
std::vector<Datum> ret;
|
|
||||||
ret.assign(u.arr.elem, u.arr.elem + u.arr.size);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve an array of strings from this datum.
|
|
||||||
std::optional<std::vector<std::string_view>> as_strvec() const {
|
|
||||||
try {
|
|
||||||
auto vec = as_vector().value();
|
|
||||||
std::vector<std::string_view> ret;
|
|
||||||
ret.resize(vec.size());
|
|
||||||
for (size_t i = 0; i < vec.size(); i++) {
|
|
||||||
ret[i] = vec[i].as_str().value();
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
} catch (const std::bad_optional_access &ex) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve an array of ints from this datum
|
|
||||||
std::optional<std::vector<int64_t>> as_intvec() const {
|
|
||||||
try {
|
|
||||||
auto vec = as_vector().value();
|
|
||||||
std::vector<int64_t> ret;
|
|
||||||
ret.resize(vec.size());
|
|
||||||
for (size_t i = 0; i < vec.size(); i++) {
|
|
||||||
ret[i] = *vec[i].as_int();
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
} catch (const std::bad_optional_access &ex) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// For tables. Retrieve the value of a composite key from this datum
|
|
||||||
// (which is a table).
|
|
||||||
std::optional<Datum> get(std::initializer_list<std::string_view> keys) const {
|
|
||||||
Datum tab = *this;
|
|
||||||
Datum value;
|
|
||||||
for (auto key : keys) {
|
|
||||||
value = {};
|
|
||||||
if (tab.type != TOML_TABLE) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
for (int i = 0; i < tab.u.tab.size; i++) {
|
|
||||||
if (key ==
|
|
||||||
std::string_view{tab.u.tab.key[i], (size_t)tab.u.tab.len[i]}) {
|
|
||||||
value = tab.u.tab.value[i];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
tab = value;
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve the value of a key
|
|
||||||
std::optional<Datum> get(std::string_view key) const { return get({key}); }
|
|
||||||
|
|
||||||
// Retrieve the value of a multi-part key
|
|
||||||
std::optional<Datum> seek(const char *multipart_key) const {
|
|
||||||
auto ret = toml_seek(*this, multipart_key);
|
|
||||||
if (!ret.type) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
}; // class Datum
|
|
||||||
|
|
||||||
class Result : private toml_result_t {
|
|
||||||
public:
|
|
||||||
Result(const toml_result_t& result) : toml_result_t(result) {}
|
|
||||||
~Result() noexcept { toml_free(*this); }
|
|
||||||
|
|
||||||
// Disallow copying
|
|
||||||
Result(const Result&) = delete;
|
|
||||||
Result& operator=(const Result&) = delete;
|
|
||||||
|
|
||||||
// Allow moving
|
|
||||||
Result(Result&& other) noexcept : toml_result_t() {
|
|
||||||
swap(*this, other);
|
|
||||||
}
|
|
||||||
Result& operator=(Result&& other) noexcept {
|
|
||||||
swap(*this, other);
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Access methods
|
|
||||||
bool ok() const { return toml_result_t::ok; }
|
|
||||||
Datum toptab() const { return toml_result_t::toptab; }
|
|
||||||
const char* errmsg() const { return toml_result_t::errmsg; }
|
|
||||||
|
|
||||||
// Shortcuts
|
|
||||||
std::optional<Datum> get(std::initializer_list<std::string_view> keys) const {
|
|
||||||
return toptab().get(keys);
|
|
||||||
}
|
|
||||||
std::optional<Datum> seek(const char *multipart_key) const {
|
|
||||||
return toptab().seek(multipart_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
friend void swap(Result& a, Result& b) noexcept {
|
|
||||||
std::swap(static_cast<toml_result_t&>(a), static_cast<toml_result_t&>(b));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
static inline Result parse_file(FILE* fp) {
|
|
||||||
return Result{toml_parse_file(fp)};
|
|
||||||
}
|
|
||||||
|
|
||||||
static inline Result parse_file_ex(const char* fname) {
|
|
||||||
return Result{toml_parse_file_ex(fname)};
|
|
||||||
}
|
|
||||||
|
|
||||||
static inline Result parse(const std::string& s) {
|
|
||||||
return Result{toml_parse(s.data(), s.size())};
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}; // namespace toml
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
Copyright (c) 2011, 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.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
Copyright (c) 2014, MAYAH
|
||||||
|
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.
|
||||||
|
|
||||||
|
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 HOLDER 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.
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2024-2025, CK Tan
|
|
||||||
https://github.com/cktan/tomlc17
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# src/agent/CMakeLists.txt
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -1,478 +0,0 @@
|
|||||||
/*
|
|
||||||
Author: xiaozhou233 (xiaozhou233@vip.qq.com)
|
|
||||||
File: juiceloader.c
|
|
||||||
Desc: JuiceLoader Native, Provide jni function for JuiceLoader
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <windows.h>
|
|
||||||
#include "log.h"
|
|
||||||
#include "juiceloader.h"
|
|
||||||
#include "javautils.h"
|
|
||||||
|
|
||||||
JuiceLoaderNativeType JuiceLoaderNative;
|
|
||||||
RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
|
|
||||||
|
|
||||||
static const char* g_bytecodes_classname = NULL;
|
|
||||||
static unsigned char* g_bytecodes = NULL;
|
|
||||||
static jint g_bytecodes_len = 0;
|
|
||||||
|
|
||||||
static void initLogger() {
|
|
||||||
log_set_level(LOG_TRACE);
|
|
||||||
log_is_log_time(false);
|
|
||||||
log_set_name("juiceloader");
|
|
||||||
log_info("Logger initialized.");
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
|
||||||
|
|
||||||
// ---- get class bytecode ---- //
|
|
||||||
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;
|
|
||||||
|
|
||||||
log_trace("[Hook:get] Captured class bytes of %s, len=%d", name, class_data_len);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// ---- get class bytecode ---- //
|
|
||||||
|
|
||||||
// ---- set class bytecode ---- //
|
|
||||||
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 = NULL;
|
|
||||||
jvmtiError err = (*jvmti_env)->Allocate(jvmti_env, entry->len, &newBytes);
|
|
||||||
if (err != JVMTI_ERROR_NONE || newBytes == NULL) {
|
|
||||||
log_error("[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;
|
|
||||||
|
|
||||||
log_info("[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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// ---- set class bytecode ---- //
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti) {
|
|
||||||
log_info("[*] libjuiceloader Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
|
|
||||||
|
|
||||||
initLogger();
|
|
||||||
if (env == NULL) {
|
|
||||||
log_error("env is NULL! env=%p", env);
|
|
||||||
return JNI_ERR;
|
|
||||||
}
|
|
||||||
if (jvmti == NULL) {
|
|
||||||
log_error("jvmti is NULL! jvmti=%p", jvmti);
|
|
||||||
return JNI_ERR;
|
|
||||||
}
|
|
||||||
JuiceLoaderNative.jvmti = jvmti;
|
|
||||||
log_debug("[JuiceLoader] JuiceLoaderNative addr = %p", &JuiceLoaderNative);
|
|
||||||
log_debug("[JuiceLoader] JVMTI ptr = %p", JuiceLoaderNative.jvmti);
|
|
||||||
|
|
||||||
|
|
||||||
// Dynamic register jni functions
|
|
||||||
jclass clazz = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoader");
|
|
||||||
if (clazz == NULL) {
|
|
||||||
log_error("Cannot find JuiceLoader class!");
|
|
||||||
return JNI_ERR;
|
|
||||||
}
|
|
||||||
JNINativeMethod methods[] = {
|
|
||||||
// JuiceLoaderNative.init()
|
|
||||||
{"init", "()Z", (void *)&loader_init},
|
|
||||||
// JuiceLoaderNative.injectJar(String(jarPath));
|
|
||||||
{"injectJar", "(Ljava/lang/String;)Z", (void *)&loader_injectJar},
|
|
||||||
// JuiceLoaderNative.redefineClass(Class<?> clazz, byte[] classBytes, int length);
|
|
||||||
{"redefineClass", "(Ljava/lang/Class;[BI)Z", (void *)&loader_redefineClass_clazz},
|
|
||||||
// JuiceLoaderNative.redefineClassByName(String className, byte[] classBytes, int length);
|
|
||||||
{"redefineClassByName", "(Ljava/lang/String;[BI)Z", (void *)&loader_redefineClass_className},
|
|
||||||
// JuiceLoaderNative.getLoadedClasses();
|
|
||||||
{"getLoadedClasses", "()[Ljava/lang/Class;", (void *)&loader_getLoadedClasses},
|
|
||||||
// public static native byte[] getClassBytes(Class<?> clazz);
|
|
||||||
// public static native byte[] getClassBytesByName(String className);
|
|
||||||
{"getClassBytes", "(Ljava/lang/Class;)[B", (void *)&loader_getClassBytes},
|
|
||||||
{ "getClassBytesByName", "(Ljava/lang/String;)[B", (void *)&loader_getClassBytesByName},
|
|
||||||
// public static native boolean retransformClass(Class<?> clazz, byte[] classBytes, int length);
|
|
||||||
{"retransformClass", "(Ljava/lang/Class;[BI)Z", (void *)&loader_retransformClass},
|
|
||||||
// public static native boolean retransformClassByName(String className, byte[] classBytes, int length);
|
|
||||||
{"retransformClassByName", "(Ljava/lang/String;[BI)Z", (void *)&loader_retransformClassByName},
|
|
||||||
// public static native Class<?> getClassByName(String className);
|
|
||||||
{"getClassByName", "(Ljava/lang/String;)Ljava/lang/Class;", (void *)&loader_getClassByName}
|
|
||||||
};
|
|
||||||
jint result = (*env)->RegisterNatives(env, clazz, methods, sizeof(methods) / sizeof(methods[0]));
|
|
||||||
if (result != JNI_OK) {
|
|
||||||
log_error("Cannot register JNI methods for JuiceLoaderNative class! [result=%d]", result);
|
|
||||||
return JNI_ERR;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Init RetransformClassCache
|
|
||||||
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;
|
|
||||||
result = (*JuiceLoaderNative.jvmti)->AddCapabilities(JuiceLoaderNative.jvmti, &caps);
|
|
||||||
if (result != JNI_OK) {
|
|
||||||
log_error("Cannot add JVMTI capabilities! [result=%d]", result);
|
|
||||||
return JNI_ERR;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Register callbacks
|
|
||||||
jvmtiEventCallbacks callbacks;
|
|
||||||
memset(&callbacks, 0, sizeof(callbacks));
|
|
||||||
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
|
|
||||||
(*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks));
|
|
||||||
|
|
||||||
// Enable events
|
|
||||||
(*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
|
|
||||||
|
|
||||||
return JNI_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// ============ JNI Function ============ ///
|
|
||||||
|
|
||||||
// JuiceLoaderNative.init()
|
|
||||||
JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class) {
|
|
||||||
// Deprcated
|
|
||||||
log_warn("JuiceLoaderNative.init() is deprecated, init will be done automatically.");
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
// JuiceLoaderNative.injectJar(String)
|
|
||||||
JNIEXPORT jboolean JNICALL loader_injectJar(JNIEnv *env, jclass loader_class, jstring jarPath) {
|
|
||||||
log_info("injectJar Invoked!");
|
|
||||||
jboolean return_value = JNI_FALSE;
|
|
||||||
|
|
||||||
const char *pathStr = (*env)->GetStringUTFChars(env, jarPath, NULL);
|
|
||||||
if (pathStr == NULL) {
|
|
||||||
log_error("jar path is NULL!");
|
|
||||||
return_value = JNI_FALSE;
|
|
||||||
goto cleanup;
|
|
||||||
}
|
|
||||||
log_info("Injecting jar: %s", pathStr);
|
|
||||||
|
|
||||||
if (JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
|
||||||
return_value = JNI_FALSE;
|
|
||||||
goto cleanup;
|
|
||||||
}
|
|
||||||
|
|
||||||
jvmtiError result = (*JuiceLoaderNative.jvmti)->AddToSystemClassLoaderSearch(JuiceLoaderNative.jvmti, pathStr);
|
|
||||||
if (result != JNI_OK) {
|
|
||||||
log_error("Cannot inject jar [result=%d]", result);
|
|
||||||
return_value = JNI_FALSE;
|
|
||||||
goto cleanup;
|
|
||||||
}
|
|
||||||
|
|
||||||
return_value = JNI_TRUE;
|
|
||||||
|
|
||||||
cleanup:
|
|
||||||
if (pathStr != NULL)
|
|
||||||
(*env)->ReleaseStringUTFChars(env, jarPath, pathStr);
|
|
||||||
return return_value;
|
|
||||||
}
|
|
||||||
|
|
||||||
// JuiceLoaderNative.redefineClass(Class, byte[], int)
|
|
||||||
JNIEXPORT jboolean JNICALL loader_redefineClass_clazz(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
|
||||||
log_info("redefineClass_clazz Invoked!");
|
|
||||||
jboolean return_value = JNI_FALSE;
|
|
||||||
jbyte* buf = NULL;
|
|
||||||
|
|
||||||
if (JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
|
||||||
return_value = JNI_FALSE;
|
|
||||||
goto cleanup;
|
|
||||||
}
|
|
||||||
|
|
||||||
log_info("Creating class definition...");
|
|
||||||
log_trace("class: %p", clazz);
|
|
||||||
log_trace("Class bytes length: %d", length);
|
|
||||||
buf = (*env)->GetByteArrayElements(env, classBytes, NULL);
|
|
||||||
if (buf == NULL) {
|
|
||||||
log_error("Cannot get class bytes");
|
|
||||||
return_value = JNI_FALSE;
|
|
||||||
goto cleanup;
|
|
||||||
}
|
|
||||||
jvmtiClassDefinition defs[1];
|
|
||||||
defs[0].klass = clazz;
|
|
||||||
defs[0].class_byte_count = length;
|
|
||||||
defs[0].class_bytes = (const unsigned char*) buf;
|
|
||||||
|
|
||||||
jvmtiError result = (*JuiceLoaderNative.jvmti)->RedefineClasses(JuiceLoaderNative.jvmti, 1, defs);
|
|
||||||
if (result != JVMTI_ERROR_NONE) {
|
|
||||||
log_error("Cannot redefine class [result=%d]", result);
|
|
||||||
return_value = JNI_FALSE;
|
|
||||||
goto cleanup;
|
|
||||||
}
|
|
||||||
return_value = JNI_TRUE;
|
|
||||||
log_info("Class redefined successfully!");
|
|
||||||
|
|
||||||
cleanup:
|
|
||||||
if (buf != NULL) {
|
|
||||||
(*env)->ReleaseByteArrayElements(env, classBytes, buf, JNI_ABORT);
|
|
||||||
}
|
|
||||||
return return_value;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL loader_redefineClass_className(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
|
||||||
log_info("redefineClass_className Invoked!");
|
|
||||||
jboolean return_value = JNI_FALSE;
|
|
||||||
|
|
||||||
if (JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
|
||||||
return_value = JNI_FALSE;
|
|
||||||
goto cleanup;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* cname = (*env)->GetStringUTFChars(env, className, NULL);
|
|
||||||
log_info("Finding class %s", cname);
|
|
||||||
if (cname == NULL) {
|
|
||||||
log_error("Class name is NULL!");
|
|
||||||
return_value = JNI_FALSE;
|
|
||||||
goto cleanup;
|
|
||||||
}
|
|
||||||
|
|
||||||
jclass clazz = (*env)->FindClass(env, cname);
|
|
||||||
if (clazz == NULL) {
|
|
||||||
log_error("Class not found! [ClassName=%s, clazz=%p]", cname, clazz);
|
|
||||||
return_value = JNI_FALSE;
|
|
||||||
goto cleanup;
|
|
||||||
}
|
|
||||||
|
|
||||||
return_value = loader_redefineClass_clazz(env, loader_class, clazz, classBytes, length);
|
|
||||||
|
|
||||||
cleanup:
|
|
||||||
if (cname != NULL) {
|
|
||||||
(*env)->ReleaseStringUTFChars(env, className, cname);
|
|
||||||
}
|
|
||||||
|
|
||||||
return return_value;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loader_class) {
|
|
||||||
log_info("loader_getLoadedClasses invoked!");
|
|
||||||
|
|
||||||
if (JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debug
|
|
||||||
jvmtiPhase phase; (*JuiceLoaderNative.jvmti)->GetPhase(JuiceLoaderNative.jvmti, &phase);
|
|
||||||
log_debug("JVMTI Phase=%d [getLoadedClasses]", phase);
|
|
||||||
|
|
||||||
jint count = 0;
|
|
||||||
jclass* classes = NULL;
|
|
||||||
|
|
||||||
jvmtiError result = (*JuiceLoaderNative.jvmti)->GetLoadedClasses(JuiceLoaderNative.jvmti, &count, &classes);
|
|
||||||
if (result != JVMTI_ERROR_NONE || count == 0) {
|
|
||||||
(*JuiceLoaderNative.jvmti)->Deallocate(JuiceLoaderNative.jvmti, (unsigned char*)classes);
|
|
||||||
return (*env)->NewObjectArray(env, 0, (*env)->FindClass(env, "java/lang/Class"), NULL);
|
|
||||||
}
|
|
||||||
|
|
||||||
jclass classClass = (*env)->FindClass(env, "java/lang/Class");
|
|
||||||
jobjectArray classArray = (*env)->NewObjectArray(env, count, classClass, NULL);
|
|
||||||
|
|
||||||
for (int i = 0; i < count; i++) {
|
|
||||||
(*env)->SetObjectArrayElement(env, classArray, i, classes[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (classes != NULL) {
|
|
||||||
(*JuiceLoaderNative.jvmti)->Deallocate(JuiceLoaderNative.jvmti, (unsigned char*)classes);
|
|
||||||
}
|
|
||||||
return classArray;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz) {
|
|
||||||
log_info("getClassBytes Invoked!");
|
|
||||||
|
|
||||||
if (JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
char* className = get_class_name(env, clazz);
|
|
||||||
if (className == NULL) {
|
|
||||||
log_error("Failed to get class name!");
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
// JVM 内部使用路径名(. 替换为 /)
|
|
||||||
for (char* p = className; *p; p++) {
|
|
||||||
if (*p == '.') *p = '/';
|
|
||||||
}
|
|
||||||
|
|
||||||
g_bytecodes = NULL;
|
|
||||||
g_bytecodes_classname = className;
|
|
||||||
g_bytecodes_len = 0;
|
|
||||||
|
|
||||||
jclass classes[1] = { clazz };
|
|
||||||
jvmtiError err = (*JuiceLoaderNative.jvmti)->RetransformClasses(JuiceLoaderNative.jvmti, 1, classes);
|
|
||||||
if (err != JVMTI_ERROR_NONE) {
|
|
||||||
log_error("RetransformClasses failed: %d", err);
|
|
||||||
free((void*)className);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (g_bytecodes != NULL) {
|
|
||||||
jbyteArray result = (*env)->NewByteArray(env, g_bytecodes_len);
|
|
||||||
(*env)->SetByteArrayRegion(env, result, 0, g_bytecodes_len, (jbyte*)g_bytecodes);
|
|
||||||
|
|
||||||
free((void*)g_bytecodes);
|
|
||||||
free((void*)className);
|
|
||||||
g_bytecodes = NULL;
|
|
||||||
g_bytecodes_classname = NULL;
|
|
||||||
g_bytecodes_len = 0;
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
log_warn("No bytecode captured for class: %s", className);
|
|
||||||
free((void*)className);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className) {
|
|
||||||
log_info("getClassBytesByName Invoked!");
|
|
||||||
|
|
||||||
if (JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* cname = (*env)->GetStringUTFChars(env, className, NULL);
|
|
||||||
jclass clazz = (*env)->FindClass(env, cname);
|
|
||||||
(*env)->ReleaseStringUTFChars(env, className, cname);
|
|
||||||
|
|
||||||
if (clazz == NULL) {
|
|
||||||
log_error("Failed to find class %s", cname);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
return loader_getClassBytes(env, loader_class, clazz);
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL loader_retransformClass(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
|
||||||
if (JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("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 = '/';
|
|
||||||
}
|
|
||||||
|
|
||||||
// get class bytes
|
|
||||||
jbyte *bytes = (*env)->GetByteArrayElements(env, classBytes, NULL);
|
|
||||||
jint len = (*env)->GetArrayLength(env, classBytes);
|
|
||||||
|
|
||||||
if (RetransformClassCache.size >= RetransformClassCache.capacity) {
|
|
||||||
int new_capacity = RetransformClassCache.capacity == 0 ? 4 : RetransformClassCache.capacity * 2;
|
|
||||||
RetransformClassCache.arr = realloc(RetransformClassCache.arr, new_capacity * sizeof(ClassBytesCacheType));
|
|
||||||
RetransformClassCache.capacity = new_capacity;
|
|
||||||
}
|
|
||||||
|
|
||||||
// save class bytes to cache
|
|
||||||
ClassBytesCacheType *entry = &RetransformClassCache.arr[RetransformClassCache.size++];
|
|
||||||
entry->name = _strdup(name);
|
|
||||||
entry->bytes = malloc(len);
|
|
||||||
memcpy(entry->bytes, bytes, len);
|
|
||||||
entry->len = len;
|
|
||||||
|
|
||||||
// clean up
|
|
||||||
(*env)->ReleaseByteArrayElements(env, classBytes, bytes, JNI_ABORT);
|
|
||||||
|
|
||||||
// retransform classes
|
|
||||||
jclass classes[1] = { clazz };
|
|
||||||
jvmtiError err = (*JuiceLoaderNative.jvmti)->RetransformClasses(JuiceLoaderNative.jvmti, 1, classes);
|
|
||||||
if (err != JVMTI_ERROR_NONE) {
|
|
||||||
log_error("RetransformClasses failed! [err=%d]", err);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
log_info("[retransformClass] Class retransformed: %s (len=%d)", entry->name, entry->len);
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
|
||||||
const char *name_dot = (*env)->GetStringUTFChars(env, className, NULL);
|
|
||||||
char *name = strdup(name_dot);
|
|
||||||
for (char *p = name; *p; ++p) if (*p == '.') *p = '/';
|
|
||||||
(*env)->ReleaseStringUTFChars(env, className, name_dot);
|
|
||||||
|
|
||||||
jclass target = (*env)->FindClass(env, name);
|
|
||||||
free(name);
|
|
||||||
|
|
||||||
if (!target) {
|
|
||||||
log_error("FindClass failed in retransformClassByName");
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
return loader_retransformClass(env, loader_class, target, classBytes, length);
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jclass JNICALL loader_getClassByName(JNIEnv *env, jclass loader_class, jstring className) {
|
|
||||||
if (className == NULL) {
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
// jstring -> const char*
|
|
||||||
const char *name_utf = (*env)->GetStringUTFChars(env, className, NULL);
|
|
||||||
if (name_utf == NULL) {
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
// find class
|
|
||||||
jclass clazz = (*env)->FindClass(env, name_utf);
|
|
||||||
|
|
||||||
// clean up
|
|
||||||
(*env)->ReleaseStringUTFChars(env, className, name_utf);
|
|
||||||
|
|
||||||
if (clazz == NULL) {
|
|
||||||
log_error("Failed to find class %s", name_utf);
|
|
||||||
}
|
|
||||||
return clazz;
|
|
||||||
}
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
// JVM
|
|
||||||
#include <jni.h>
|
|
||||||
#include <jvmti.h>
|
|
||||||
#include <Logger.hpp>
|
|
||||||
#include <juiceloader.h>
|
|
||||||
|
|
||||||
JuiceLoaderNativeType JuiceLoaderNative;
|
|
||||||
|
|
||||||
static int RegisterNatives(JNIEnv *env) {
|
|
||||||
const char* native_class = "cn/xiaozhou233/juiceloader/JuiceLoader";
|
|
||||||
JNINativeMethod methods[] = {
|
|
||||||
{(char*)"init", (char*)"()Z", (void *)&loader_init},
|
|
||||||
{(char*)"injectJar", (char*)"(Ljava/lang/String;)Z", (void *)&loader_injectJar},
|
|
||||||
{(char*)"redefineClass", (char*)"(Ljava/lang/Class;[BI)Z", (void *)&loader_redefineClass_clazz},
|
|
||||||
{(char*)"redefineClassByName", (char*)"(Ljava/lang/String;[BI)Z", (void *)&loader_redefineClass_className},
|
|
||||||
{(char*)"getLoadedClasses", (char*)"()[Ljava/lang/Class;", (void *)&loader_getLoadedClasses},
|
|
||||||
{(char*)"getClassBytes", (char*)"(Ljava/lang/Class;)[B", (void *)&loader_getClassBytes},
|
|
||||||
{(char*)"getClassBytesByName", (char*)"(Ljava/lang/String;)[B", (void *)&loader_getClassBytesByName},
|
|
||||||
{(char*)"retransformClass", (char*)"(Ljava/lang/Class;[BI)Z", (void *)&loader_retransformClass},
|
|
||||||
{(char*)"retransformClassByName", (char*)"(Ljava/lang/String;[BI)Z", (void *)&loader_retransformClassByName},
|
|
||||||
{(char*)"getClassByName", (char*)"(Ljava/lang/String;)Ljava/lang/Class;", (void *)&loader_getClassByName}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Find Native(JNI) Class
|
|
||||||
jclass clazz = env->FindClass("cn/xiaozhou233/juiceloader/JuiceLoader");
|
|
||||||
if (clazz == NULL) {
|
|
||||||
if (env->ExceptionCheck()) {
|
|
||||||
env->ExceptionDescribe();
|
|
||||||
env->ExceptionClear();
|
|
||||||
}
|
|
||||||
PLOGE.printf("[-] Failed to initialize libjuiceloader: JuiceLoader class not found");
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dynamicly register native methods
|
|
||||||
jint result = env->RegisterNatives(clazz, methods, sizeof(methods) / sizeof(methods[0]));
|
|
||||||
if (result != JNI_OK) {
|
|
||||||
PLOGE << "Failed to register native methods: " << result;
|
|
||||||
return JNI_ERR;
|
|
||||||
}
|
|
||||||
|
|
||||||
return JNI_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
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: Register Native Methods
|
|
||||||
if (RegisterNatives(env) != JNI_OK) {
|
|
||||||
PLOGE.printf("[-] Failed to initialize libjuiceloader: RegisterNatives failed");
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 3: Configure JVMTI
|
|
||||||
if (ConfigureJVMTI(env, jvmti) != JNI_OK) {
|
|
||||||
PLOGE.printf("[-] Failed to initialize libjuiceloader: ConfigureJVMTI failed");
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,242 +0,0 @@
|
|||||||
/*
|
|
||||||
Author: xiaozhou233 (xiaozhou233@vip.qq.com)
|
|
||||||
File: libagent.c
|
|
||||||
Desc: Entry point for the agent
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "ReflectiveLoader.h"
|
|
||||||
#include "windows.h"
|
|
||||||
#include "unistd.h"
|
|
||||||
#include "stdio.h"
|
|
||||||
#include "jni.h"
|
|
||||||
#include "jvmti.h"
|
|
||||||
#include "InjectParameters.h"
|
|
||||||
#include "log.h"
|
|
||||||
#include "jvmutils.h"
|
|
||||||
#include "shlwapi.h"
|
|
||||||
#include "tomlc17.h"
|
|
||||||
#include "datautils.h"
|
|
||||||
#include "juiceloader.h"
|
|
||||||
|
|
||||||
#define WIN_X64
|
|
||||||
extern HINSTANCE hAppInstance;
|
|
||||||
|
|
||||||
InjectionInfoType InjectionInfo;
|
|
||||||
|
|
||||||
struct _JuiceAgent {
|
|
||||||
bool isAttached;
|
|
||||||
JavaVM *jvm;
|
|
||||||
jvmtiEnv *jvmti;
|
|
||||||
} JuiceAgent = {false, NULL, NULL};
|
|
||||||
|
|
||||||
static void initLogger() {
|
|
||||||
log_set_level(LOG_TRACE);
|
|
||||||
log_is_log_time(false);
|
|
||||||
log_set_name("libagent");
|
|
||||||
log_info("Logger initialized.");
|
|
||||||
}
|
|
||||||
|
|
||||||
DWORD WINAPI ThreadProc(LPVOID lpParam) {
|
|
||||||
log_trace("New thread started.");
|
|
||||||
|
|
||||||
memset(&InjectionInfo, 0, sizeof(InjectionInfo));
|
|
||||||
|
|
||||||
/// ======== Check Environment ======== ///
|
|
||||||
InjectParameters *param = (InjectParameters*)lpParam;
|
|
||||||
if (!param) {
|
|
||||||
log_error("ThreadProc got NULL param");
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
if (!param->ConfigDir || param->ConfigDir[0] == '\0') {
|
|
||||||
log_error("ThreadProc got NULL or empty ConfigPath");
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
char ConfigPath[INJECT_PATH_MAX];
|
|
||||||
snprintf(ConfigPath, sizeof(ConfigPath), "%s\\AgentConfig.toml", param->ConfigDir);
|
|
||||||
toml_result_t toml_result = toml_parse_file_ex(ConfigPath);
|
|
||||||
if (!toml_result.ok) {
|
|
||||||
log_error("ThreadProc failed to parse config file: %s", toml_result.errmsg);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
if (!ReadInjectionInfo(toml_result, param)) {
|
|
||||||
log_error("Failed to read injection info");
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
toml_free(toml_result);
|
|
||||||
|
|
||||||
// Check JuiceLoader.jar
|
|
||||||
|
|
||||||
log_trace("Checking JuiceLoader.jar");
|
|
||||||
if (GetFileAttributesA(InjectionInfo.JuiceLoaderJarPath) == INVALID_FILE_ATTRIBUTES) {
|
|
||||||
log_error("JuiceLoader.jar not found: %s", InjectionInfo.JuiceLoaderJarPath);
|
|
||||||
// MessageBoxA(NULL, "JuiceLoader.jar not found", "Error", MB_OK);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
/// ======== Check Environment ======== ///
|
|
||||||
|
|
||||||
// Init vars
|
|
||||||
jint result = JNI_ERR;
|
|
||||||
JavaVM *jvm = NULL;
|
|
||||||
JNIEnv *env = NULL;
|
|
||||||
jvmtiEnv *jvmti = NULL;
|
|
||||||
|
|
||||||
result = GetCreatedJVM(&jvm);
|
|
||||||
if (result != JNI_OK) {
|
|
||||||
log_error("Failed to get JVM (%d)", result);
|
|
||||||
MessageBoxA(NULL, "Failed to get JVM", "Error", MB_OK);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
log_info("Got JVM");
|
|
||||||
|
|
||||||
|
|
||||||
result = GetJNIEnv(jvm, &env);
|
|
||||||
if (result != JNI_OK) {
|
|
||||||
log_error("Failed to get JNIEnv (%d)", result);
|
|
||||||
// MessageBoxA(NULL, "Failed to get JNIEnv", "Error", MB_OK);
|
|
||||||
log_error("Maybe the JVM havent been init yet.");
|
|
||||||
JuiceAgent.isAttached = false;
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
log_info("Got JNIEnv");
|
|
||||||
|
|
||||||
// Debug: JVM version
|
|
||||||
jint version = (*env)->GetVersion(env);
|
|
||||||
log_trace("JVM version: 0x%x", version);
|
|
||||||
|
|
||||||
// Init and enable jvmti
|
|
||||||
result = GetJVMTI(jvm, &jvmti);
|
|
||||||
if (result != JNI_OK) {
|
|
||||||
log_error("Failed to get JVMTI (%d)", result);
|
|
||||||
// MessageBoxA(NULL, "Failed to get JVMTI", "Error", MB_OK);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
log_info("Enabled jvmti");
|
|
||||||
|
|
||||||
// Inject jars
|
|
||||||
|
|
||||||
log_info("injecting loader jar...");
|
|
||||||
(*jvmti)->AddToSystemClassLoaderSearch(jvmti, InjectionInfo.JuiceLoaderJarPath);
|
|
||||||
log_info("injected loader jar");
|
|
||||||
|
|
||||||
// init juiceloader
|
|
||||||
log_info("init juice loader...");
|
|
||||||
init_juiceloader(env, jvmti);
|
|
||||||
|
|
||||||
initLogger();
|
|
||||||
log_info("juice loader init done");
|
|
||||||
|
|
||||||
log_info("invoking loader init()...");
|
|
||||||
log_info("============ Loader Info ============\n");
|
|
||||||
jclass cls = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoaderBootstrap");
|
|
||||||
if (cls == NULL) {
|
|
||||||
log_error("FindClass JuiceLoaderBootstrap failed");
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
jmethodID mid = (*env)->GetStaticMethodID(env, cls, "init", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
|
|
||||||
if (mid == NULL) {
|
|
||||||
log_error("GetStaticMethodID init failed");
|
|
||||||
if ((*env)->ExceptionCheck(env)) {
|
|
||||||
(*env)->ExceptionDescribe(env);
|
|
||||||
(*env)->ExceptionClear(env);
|
|
||||||
}
|
|
||||||
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
(*env)->CallStaticVoidMethod(env, cls, mid,
|
|
||||||
(*env)->NewStringUTF(env, InjectionInfo.EntryJarPath),
|
|
||||||
(*env)->NewStringUTF(env, InjectionInfo.EntryClass),
|
|
||||||
(*env)->NewStringUTF(env, InjectionInfo.EntryMethod),
|
|
||||||
(*env)->NewStringUTF(env, InjectionInfo.InjectionDir));
|
|
||||||
log_info("============ Loader Info =============\n");
|
|
||||||
log_info("invoked. ");
|
|
||||||
log_info("done. cleaning up...");
|
|
||||||
|
|
||||||
// :(
|
|
||||||
// (*jvm)->DetachCurrentThread(jvm);
|
|
||||||
|
|
||||||
free(param);
|
|
||||||
log_info("exit.");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// =========================================================== ///
|
|
||||||
/// Function: DllMain
|
|
||||||
/// Description: DLL Injection Entry Point
|
|
||||||
/// Inject Method: A) ReflectiveDLLInjection B) LoadLibraryA+CreateRemoteThread
|
|
||||||
/// =========================================================== ///
|
|
||||||
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved){
|
|
||||||
BOOL bReturnValue = TRUE;
|
|
||||||
switch (dwReason){
|
|
||||||
case DLL_QUERY_HMODULE:
|
|
||||||
if (lpReserved != NULL)
|
|
||||||
*(HMODULE *)lpReserved = hAppInstance;
|
|
||||||
break;
|
|
||||||
|
|
||||||
case DLL_PROCESS_ATTACH:
|
|
||||||
hAppInstance = hinstDLL;
|
|
||||||
|
|
||||||
// Initialize log
|
|
||||||
initLogger();
|
|
||||||
log_info("DLL_PROCESS_ATTACH");
|
|
||||||
log_info("[*] JuiceAgent Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
|
|
||||||
|
|
||||||
DisableThreadLibraryCalls(hinstDLL);
|
|
||||||
|
|
||||||
// Allocate memory for local param
|
|
||||||
InjectParameters *localParm = (InjectParameters*)malloc(sizeof(InjectParameters));
|
|
||||||
if (localParm == NULL) {
|
|
||||||
log_error("malloc failed for InjectParameters");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
memset(localParm, 0, sizeof(InjectParameters));
|
|
||||||
|
|
||||||
// Check if lpReserved is not NULL
|
|
||||||
if (lpReserved != NULL) {
|
|
||||||
// Copy remote param to local param
|
|
||||||
InjectParameters *remoteParm = (InjectParameters*)lpReserved;
|
|
||||||
|
|
||||||
safe_copy(localParm->ConfigDir, remoteParm->ConfigDir, sizeof(localParm->ConfigDir));
|
|
||||||
} else {
|
|
||||||
log_info("RemoteParm is NULL!");
|
|
||||||
|
|
||||||
char DllDir[INJECT_PATH_MAX] = {0};
|
|
||||||
|
|
||||||
if (GetModuleFileNameA(hinstDLL, DllDir, INJECT_PATH_MAX) == 0) {
|
|
||||||
// Failed to get module file name
|
|
||||||
DWORD err = GetLastError();
|
|
||||||
if (err == ERROR_MOD_NOT_FOUND) {
|
|
||||||
// Reflective detected, lpReserved must be set.
|
|
||||||
log_fatal("Reflective load detected! Please set ConfigDir manually! Exit.");
|
|
||||||
} else {
|
|
||||||
log_error("Normal Inject: GetModuleFileNameA failed! Error: %lu", err);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
} else {
|
|
||||||
// Normal Inject(e.g. CreateRemoteThread+LoadLibraryA), lpReserved can be NULL.
|
|
||||||
PathRemoveFileSpecA(DllDir);
|
|
||||||
log_info("GetModuleFileNameA: %s", DllDir);
|
|
||||||
safe_copy(localParm->ConfigDir, DllDir, INJECT_PATH_MAX);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log_info("ConfigDir: %s", localParm->ConfigDir);
|
|
||||||
|
|
||||||
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, localParm, 0, NULL);
|
|
||||||
if (hThread) {
|
|
||||||
CloseHandle(hThread);
|
|
||||||
} else {
|
|
||||||
log_error("CreateThread failed %lu", GetLastError());
|
|
||||||
free(localParm);
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
|
||||||
case DLL_PROCESS_DETACH:
|
|
||||||
log_info("DLL_PROCESS_DETACH");
|
|
||||||
break;
|
|
||||||
case DLL_THREAD_ATTACH:
|
|
||||||
case DLL_THREAD_DETACH:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
return bReturnValue;
|
|
||||||
}
|
|
||||||
@@ -1,264 +0,0 @@
|
|||||||
#include <windows.h>
|
|
||||||
#include "Logger.hpp"
|
|
||||||
#include <JuiceAgent.h>
|
|
||||||
#include <juiceloader.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;
|
|
||||||
|
|
||||||
HINSTANCE hAppInstance = nullptr;
|
|
||||||
|
|
||||||
|
|
||||||
static int GetJavaEnv() {
|
|
||||||
jint res = JNI_ERR;
|
|
||||||
JavaVM *jvm = NULL;
|
|
||||||
jvmtiEnv *jvmti = NULL;
|
|
||||||
JNIEnv *env = NULL;
|
|
||||||
|
|
||||||
// Get the JVM
|
|
||||||
res = JNI_GetCreatedJavaVMs(&jvm, 1, NULL);
|
|
||||||
if (res != JNI_OK) {
|
|
||||||
PLOGE.printf("JNI_GetCreatedJavaVMs failed: %d", res);
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
JuiceAgent.jvm = jvm;
|
|
||||||
PLOGI << "Got the JVM";
|
|
||||||
|
|
||||||
// Get the JNIEnv
|
|
||||||
res = jvm->GetEnv((void**)&env, JNI_VERSION_1_8);
|
|
||||||
if (res != JNI_OK) {
|
|
||||||
PLOGI << "GetEnv failed, trying to attach.";
|
|
||||||
res = jvm->AttachCurrentThread((void**)&env, NULL);
|
|
||||||
if (res != JNI_OK) {
|
|
||||||
PLOGE.printf("AttachCurrentThread failed: %d", res);
|
|
||||||
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) {
|
|
||||||
PLOGE.printf("GetEnv failed: %d", res);
|
|
||||||
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 << "\n\n================ 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Invoke method
|
|
||||||
env->CallStaticVoidMethod(cls, mid, env->NewStringUTF(ConfigDir));
|
|
||||||
if (env->ExceptionCheck()) {
|
|
||||||
env->ExceptionDescribe();
|
|
||||||
env->ExceptionClear();
|
|
||||||
}
|
|
||||||
|
|
||||||
PLOGI << "================ JuiceLoader Init =================\n\n";
|
|
||||||
|
|
||||||
PLOGI << "Invoke JuiceLoader Init done";
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static int ReadConfig(const char* ConfigDir)
|
|
||||||
{
|
|
||||||
std::string path = std::string(ConfigDir) + "\\config.toml";
|
|
||||||
std::ifstream ifs(path);
|
|
||||||
if (!ifs) return -1;
|
|
||||||
|
|
||||||
toml::ParseResult pr = toml::parse(ifs);
|
|
||||||
if (!pr.valid()) return -2;
|
|
||||||
|
|
||||||
const toml::Value& tbl = pr.value;
|
|
||||||
|
|
||||||
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>();
|
|
||||||
strncpy(out, s.c_str(), INJECT_PATH_MAX - 1);
|
|
||||||
} else {
|
|
||||||
strncpy(out, def, INJECT_PATH_MAX - 1);
|
|
||||||
}
|
|
||||||
out[INJECT_PATH_MAX - 1] = '\0';
|
|
||||||
};
|
|
||||||
|
|
||||||
std::string defaultJuiceLoader = std::string(ConfigDir) + "\\JuiceLoader.jar";
|
|
||||||
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("InjectionDir", defaultInjectionDir.c_str(), InjectionInfo.InjectionDir);
|
|
||||||
get_str("EntryJarPath", defaultEntryJar.c_str(), InjectionInfo.EntryJarPath);
|
|
||||||
get_str("EntryClass", "cn.xiaozhou233.juicesky.LoaderEntry", InjectionInfo.EntryClass);
|
|
||||||
get_str("EntryMethod", "start", InjectionInfo.EntryMethod);
|
|
||||||
|
|
||||||
PLOGD << "JuiceLoaderJarPath: " << InjectionInfo.JuiceLoaderJarPath;
|
|
||||||
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 Native Init
|
|
||||||
if (InitJuiceLoader(JuiceAgent.env, JuiceAgent.jvmti) != JNI_OK) {
|
|
||||||
PLOGE << "Failed to invoke JuiceLoader Native Init: " << result;
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 4: Invoke JuiceLoader Init
|
|
||||||
if (InvokeJuiceLoaderInit(ConfigDir) != 0) {
|
|
||||||
PLOGE << "Failed to invoke JuiceLoader Init code=" << result;
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 5: 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: {
|
|
||||||
hAppInstance = hinstDLL;
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
# src/executable/CMakeLists.txt
|
|
||||||
|
|
||||||
add_executable(injector_executable injector.cpp)
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
// injector_client.cpp
|
|
||||||
// Console injector client - uses main() for maximum compatibility.
|
|
||||||
// Usage:
|
|
||||||
// injector_client.exe <pid> <dll_path_to_inject> [injector_lib_path]
|
|
||||||
//
|
|
||||||
// Notes:
|
|
||||||
// - injector library must export a C symbol: extern "C" __declspec(dllexport) int inject(int, const char*, void*);
|
|
||||||
// - This client calls inject(pid, dllPath, NULL).
|
|
||||||
|
|
||||||
#include <windows.h>
|
|
||||||
#include <iostream>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
int main(int argc, char** argv) {
|
|
||||||
if (argc < 3) {
|
|
||||||
std::cerr << "Usage: " << argv[0] << " <pid> <dll_path_to_inject> [injector_lib_path]\n";
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// parse pid
|
|
||||||
int pid = atoi(argv[1]);
|
|
||||||
if (pid <= 0) {
|
|
||||||
std::cerr << "Invalid PID: " << argv[1] << "\n";
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// dll path (UTF-8 or ANSI depending on environment)
|
|
||||||
const char* dllPath = argv[2];
|
|
||||||
std::string dllPathStr = dllPath;
|
|
||||||
|
|
||||||
// load injector library
|
|
||||||
HMODULE hLib = NULL;
|
|
||||||
if (argc >= 4) {
|
|
||||||
const char* libPath = argv[3];
|
|
||||||
hLib = LoadLibraryA(libPath);
|
|
||||||
if (!hLib) {
|
|
||||||
std::cerr << "[-] Failed to load injector library: " << libPath << ", Error=" << GetLastError() << "\n";
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// try to load from current dir / PATH by name
|
|
||||||
hLib = LoadLibraryA("libinjector.dll");
|
|
||||||
if (!hLib) {
|
|
||||||
std::cerr << "[-] Failed to load libinjector.dll by name. Error=" << GetLastError() << "\n";
|
|
||||||
std::cerr << " Provide full path as the 3rd argument if needed.\n";
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::cout << "[+] Loaded injector library\n";
|
|
||||||
|
|
||||||
// function pointer type: adjust calling convention if your DLL uses different one.
|
|
||||||
typedef int (__cdecl *inject_fn_t)(int, const char*, void*);
|
|
||||||
|
|
||||||
FARPROC p = GetProcAddress(hLib, "inject");
|
|
||||||
if (!p) {
|
|
||||||
// try some common alternatives
|
|
||||||
p = GetProcAddress(hLib, "Inject");
|
|
||||||
}
|
|
||||||
if (!p) {
|
|
||||||
std::cerr << "[-] GetProcAddress failed for 'inject'. Make sure your library exports 'inject' as C symbol.\n";
|
|
||||||
FreeLibrary(hLib);
|
|
||||||
return 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
inject_fn_t inject = reinterpret_cast<inject_fn_t>(p);
|
|
||||||
|
|
||||||
std::cout << "[*] Calling inject(pid, dllPath, NULL)\n";
|
|
||||||
int result = inject(pid, dllPathStr.c_str(), NULL);
|
|
||||||
|
|
||||||
if (result == 0) {
|
|
||||||
std::cout << "[+] inject returned success (0)\n";
|
|
||||||
} else {
|
|
||||||
std::cout << "[-] inject returned failure (" << result << ")\n";
|
|
||||||
}
|
|
||||||
|
|
||||||
FreeLibrary(hLib);
|
|
||||||
return (result == 0) ? 0 : 4;
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# src/injector/CMakeLists.txt
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -1,266 +0,0 @@
|
|||||||
#include <JuiceAgent.h>
|
|
||||||
#include <Logger.hpp>
|
|
||||||
#include <windows.h>
|
|
||||||
#include <InjectorUtils.h>
|
|
||||||
#include <jni.h>
|
|
||||||
#include <string.h>
|
|
||||||
|
|
||||||
#define BREAK_WITH_ERROR( e ) { PLOGE.printf("[-] %s. Error=%lu", e, GetLastError()); break; }
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Standard DLL injection:
|
|
||||||
* - write DLL path string into remote process memory
|
|
||||||
* - CreateRemoteThread with LoadLibraryA(remotePath)
|
|
||||||
* - wait, get exit code, clean up
|
|
||||||
*/
|
|
||||||
|
|
||||||
extern "C" __declspec(dllexport)
|
|
||||||
int inject(int pid, const char *path, InjectParams *params) {
|
|
||||||
HANDLE hFile = NULL;
|
|
||||||
HANDLE hRemoteThread = NULL;
|
|
||||||
HANDLE hProcess = NULL;
|
|
||||||
HANDLE hToken = NULL;
|
|
||||||
LPVOID lpBuffer = NULL; // local file buffer (optional, used for PE inspection)
|
|
||||||
LPVOID lpRemoteParam = NULL; // REMOTE memory for InjectParams (not used in standard injection)
|
|
||||||
LPVOID lpRemotePath = NULL; // REMOTE memory for path string (used)
|
|
||||||
DWORD dwLength = 0;
|
|
||||||
DWORD dwBytesRead = 0;
|
|
||||||
DWORD dwProcessId = (DWORD)pid;
|
|
||||||
TOKEN_PRIVILEGES priv = {0};
|
|
||||||
BOOL bSuccess = FALSE;
|
|
||||||
|
|
||||||
InitLogger();
|
|
||||||
|
|
||||||
PLOGI.printf("[*] libinjector Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
|
|
||||||
PLOGD << "[*] InjectParams pointer: " << ¶ms;
|
|
||||||
|
|
||||||
if (!path) {
|
|
||||||
PLOGE << "[!] Invalid path";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
|
||||||
/* optional: open DLL file to inspect PE info (kept for logging) */
|
|
||||||
hFile = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
|
|
||||||
if (hFile == INVALID_HANDLE_VALUE) {
|
|
||||||
PLOGW.printf("[!] Cannot open DLL for inspection: %s, Error=%lu -- will still try standard injection", path, GetLastError());
|
|
||||||
hFile = NULL; // continue without file buffer
|
|
||||||
} else {
|
|
||||||
/* get file size (use GetFileSize) */
|
|
||||||
dwLength = GetFileSize(hFile, NULL);
|
|
||||||
if (dwLength != INVALID_FILE_SIZE && dwLength > 0) {
|
|
||||||
lpBuffer = HeapAlloc(GetProcessHeap(), 0, dwLength);
|
|
||||||
if (lpBuffer) {
|
|
||||||
if (!ReadFile(hFile, lpBuffer, dwLength, &dwBytesRead, NULL) || dwBytesRead != dwLength) {
|
|
||||||
PLOGW.printf("[!] ReadFile incomplete or failed: %lu", GetLastError());
|
|
||||||
HeapFree(GetProcessHeap(), 0, lpBuffer);
|
|
||||||
lpBuffer = NULL;
|
|
||||||
} else {
|
|
||||||
WORD dllMachine = get_pe_machine(lpBuffer, dwLength);
|
|
||||||
PLOGD.printf("[*] DLL PE machine: %s (0x%04x)", machine_to_str(dllMachine), dllMachine);
|
|
||||||
BOOL hasRL = has_reflective_loader_export(lpBuffer, dwLength);
|
|
||||||
PLOGD.printf("[*] DLL has ReflectiveLoader export: %s", hasRL ? "YES" : "NO");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
PLOGW.printf("[!] HeapAlloc for file buffer failed: %lu", GetLastError());
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
PLOGW.printf("[!] GetFileSize returned invalid or zero size: %lu", GetLastError());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* try to 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 (logging only) */
|
|
||||||
BOOL targetIsWow64 = FALSE;
|
|
||||||
if (!IsWow64Process(hProcess, &targetIsWow64)) {
|
|
||||||
PLOGE.printf("IsWow64Process failed: %lu", GetLastError());
|
|
||||||
} else {
|
|
||||||
PLOGI.printf("Is target process wow64 = %d (TRUE means 32-bit process on 64-bit OS)", targetIsWow64);
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(_M_X64) || defined(__x86_64__) || defined(__amd64__)
|
|
||||||
PLOGI.printf("Injector compiled as: x64");
|
|
||||||
#else
|
|
||||||
PLOGI.printf("Injector compiled as: x86");
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* allocate remote memory for DLL path string */
|
|
||||||
size_t pathLen = strlen(path) + 1;
|
|
||||||
lpRemotePath = VirtualAllocEx(hProcess, NULL, pathLen, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
|
||||||
if (!lpRemotePath) {
|
|
||||||
BREAK_WITH_ERROR("VirtualAllocEx for remote path failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
PLOGD.printf("remote path addr = %p", lpRemotePath);
|
|
||||||
|
|
||||||
/* write DLL path into remote process */
|
|
||||||
SIZE_T written = 0;
|
|
||||||
if (!WriteProcessMemory(hProcess, lpRemotePath, path, pathLen, &written) || written != pathLen) {
|
|
||||||
BREAK_WITH_ERROR("WriteProcessMemory for remote path failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
/* create remote thread calling LoadLibraryA(remotePath) */
|
|
||||||
DWORD dwThreadId = 0;
|
|
||||||
hRemoteThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, lpRemotePath, 0, &dwThreadId);
|
|
||||||
if (!hRemoteThread) {
|
|
||||||
BREAK_WITH_ERROR("CreateRemoteThread failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
PLOGI.printf("[+] DLL injection thread created for '%s' into PID %d (threadId=%lu)", path, dwProcessId, dwThreadId);
|
|
||||||
|
|
||||||
/* wait for thread to finish */
|
|
||||||
WaitForSingleObject(hRemoteThread, INFINITE);
|
|
||||||
|
|
||||||
/* get remote thread exit code (module handle or 0) */
|
|
||||||
DWORD exitCode = 0;
|
|
||||||
if (GetExitCodeThread(hRemoteThread, &exitCode)) {
|
|
||||||
if (exitCode == 0) {
|
|
||||||
PLOGW.printf("[-] Remote LoadLibraryA returned NULL (failed to load).");
|
|
||||||
} else {
|
|
||||||
PLOGI.printf("[+] Remote LoadLibraryA returned module handle: 0x%08lx", exitCode);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
PLOGW.printf("[-] GetExitCodeThread failed: %lu", GetLastError());
|
|
||||||
}
|
|
||||||
|
|
||||||
bSuccess = TRUE;
|
|
||||||
|
|
||||||
/* cleanup remote thread handle */
|
|
||||||
CloseHandle(hRemoteThread);
|
|
||||||
hRemoteThread = NULL;
|
|
||||||
|
|
||||||
/* free remote path memory */
|
|
||||||
if (lpRemotePath) {
|
|
||||||
VirtualFreeEx(hProcess, lpRemotePath, 0, MEM_RELEASE);
|
|
||||||
lpRemotePath = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
} while (0);
|
|
||||||
|
|
||||||
/* cleanup local resources */
|
|
||||||
if (lpBuffer) {
|
|
||||||
HeapFree(GetProcessHeap(), 0, lpBuffer);
|
|
||||||
lpBuffer = NULL;
|
|
||||||
}
|
|
||||||
if (hFile && hFile != INVALID_HANDLE_VALUE) {
|
|
||||||
CloseHandle(hFile);
|
|
||||||
hFile = NULL;
|
|
||||||
}
|
|
||||||
if (hProcess) {
|
|
||||||
CloseHandle(hProcess);
|
|
||||||
hProcess = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
return bSuccess ? 0 : -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* JNI wrappers (unchanged except they call the above inject) */
|
|
||||||
|
|
||||||
/*
|
|
||||||
* JNI Function: inject(int pid, String path)
|
|
||||||
*/
|
|
||||||
extern "C" __declspec(dllexport)
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2
|
|
||||||
(JNIEnv *env, jobject obj, jint pid, jstring path) {
|
|
||||||
const char* InjectionDLL = env->GetStringUTFChars(path, NULL);
|
|
||||||
int ret = inject(pid, InjectionDLL, NULL);
|
|
||||||
env->ReleaseStringUTFChars(path, InjectionDLL);
|
|
||||||
return (ret == 0) ? JNI_TRUE : JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* JNI Function: inject(int pid, String path, String configDir)
|
|
||||||
*/
|
|
||||||
extern "C" __declspec(dllexport)
|
|
||||||
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){
|
|
||||||
const char* InjectionDLL = env->GetStringUTFChars(path, NULL);
|
|
||||||
const char* ConfigDir = env->GetStringUTFChars(configDir, NULL);
|
|
||||||
|
|
||||||
/* NOTE: Standard LoadLibrary injection cannot directly pass InjectParams.
|
|
||||||
If your DLL needs ConfigDir, it should read it from a known location (e.g. file, registry),
|
|
||||||
or you can implement an exported init function inside the DLL which you call later. */
|
|
||||||
|
|
||||||
int ret = inject(pid, InjectionDLL, NULL);
|
|
||||||
|
|
||||||
env->ReleaseStringUTFChars(path, InjectionDLL);
|
|
||||||
env->ReleaseStringUTFChars(configDir, ConfigDir);
|
|
||||||
|
|
||||||
return (ret == 0) ? JNI_TRUE : JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Find windows by title implementation (unchanged) */
|
|
||||||
|
|
||||||
#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;
|
|
||||||
|
|
||||||
extern "C" __declspec(dllexport)
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
extern "C" __declspec(dllexport)
|
|
||||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_findWindowsByTitle
|
|
||||||
(JNIEnv *env, jclass clazz, jstring keyword) {
|
|
||||||
|
|
||||||
const jchar *input = env->GetStringChars(keyword, NULL);
|
|
||||||
wcsncpy(g_keyword, (const wchar_t *)input, 255);
|
|
||||||
g_keyword[255] = L'\0';
|
|
||||||
env->ReleaseStringChars(keyword, input);
|
|
||||||
|
|
||||||
g_count = 0;
|
|
||||||
EnumWindows(EnumWindowsProc, 0);
|
|
||||||
|
|
||||||
jclass infoClass = env->FindClass("cn/xiaozhou233/juiceagent/injector/InjectorNative$WindowInfo");
|
|
||||||
if (!infoClass) return NULL;
|
|
||||||
|
|
||||||
jmethodID ctor = env->GetMethodID(infoClass, "<init>", "(Ljava/lang/String;I)V");
|
|
||||||
if (!ctor) return NULL;
|
|
||||||
|
|
||||||
jobjectArray array = env->NewObjectArray(g_count, infoClass, NULL);
|
|
||||||
|
|
||||||
for (int i = 0; i < g_count; i++) {
|
|
||||||
jstring title = env->NewString((jchar*)g_results[i].title, wcslen(g_results[i].title));
|
|
||||||
jobject obj = env->NewObject(infoClass, ctor, title, (jint)g_results[i].pid);
|
|
||||||
env->SetObjectArrayElement(array, i, obj);
|
|
||||||
}
|
|
||||||
|
|
||||||
return array;
|
|
||||||
}
|
|
||||||
@@ -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";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,480 @@
|
|||||||
|
//===============================================================================================//
|
||||||
|
// 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
|
||||||
|
#define REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
|
||||||
|
|
||||||
|
//===============================================================================================//
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
//===============================================================================================//
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
#include <jvm/jni.h>
|
||||||
|
#include <jvm/jvmti.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
#include <libagent.h>
|
||||||
|
#include <thread>
|
||||||
|
#include <tinytoml/toml.h>
|
||||||
|
#include <JuiceAgent/JuiceAgent.h>
|
||||||
|
|
||||||
|
struct _JuiceAgent {
|
||||||
|
bool isAttached;
|
||||||
|
JavaVM *jvm;
|
||||||
|
jvmtiEnv *jvmti;
|
||||||
|
JNIEnv *env;
|
||||||
|
} JuiceAgent = {false, NULL, NULL, NULL};
|
||||||
|
|
||||||
|
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;
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" __declspec(dllexport)
|
||||||
|
bool InitJuiceAgent(const char* runtime_path) {
|
||||||
|
PLOGI << "--------> InitJuiceAgent Invoke <--------";
|
||||||
|
PLOGD << "runtime_path: " << runtime_path;
|
||||||
|
|
||||||
|
// Read Config
|
||||||
|
PLOGI << "ReadConfig ...";
|
||||||
|
if (ReadConfig(runtime_path) != 0) {
|
||||||
|
PLOGE << "ReadConfig failed";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
PLOGI << "[OK] ReadConfig";
|
||||||
|
|
||||||
|
// Get JavaEnv
|
||||||
|
PLOGI << "Get JavaEnv ...";
|
||||||
|
if (GetJavaEnv() != 0) {
|
||||||
|
PLOGE << "GetJavaEnv failed";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
PLOGI << "[OK] Get JavaEnv";
|
||||||
|
|
||||||
|
// 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";
|
||||||
|
|
||||||
|
// Invoke JuiceLoader Init
|
||||||
|
PLOGI << "Invoke JuiceLoader Init ...";
|
||||||
|
if (InvokeJuiceLoaderInit(runtime_path) != 0) {
|
||||||
|
PLOGE << "Invoke JuiceLoader Init failed";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
PLOGI << "[OK] Invoke JuiceLoader Init";
|
||||||
|
|
||||||
|
// Load JuiceLoaderLibrary
|
||||||
|
|
||||||
|
PLOGI << "--------> InitJuiceAgent Succeed <--------";
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -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 <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include "LoadLibraryR.h"
|
#include <jni.h>
|
||||||
#include "InjectorNative.h"
|
#include <ReflectiveDLLInjection/LoadLibraryR.h>
|
||||||
#include "InjectParameters.h"
|
|
||||||
#include "log.c"
|
|
||||||
|
|
||||||
#define WIN_X64
|
#define WIN_X64
|
||||||
#define BREAK_WITH_ERROR( e ) { log_error("[-] %s. Error=%l", e, GetLastError()); break; }
|
#define BREAK_WITH_ERROR( e ) { printf("[-] %s. Error=%l", e, GetLastError()); break; }
|
||||||
|
#define MAX_PATH 260
|
||||||
|
|
||||||
int inject(int pid, char *path, InjectParameters *params){
|
__declspec(dllexport)
|
||||||
|
int inject(int pid, char *path, char *params){
|
||||||
HANDLE hFile = NULL;
|
HANDLE hFile = NULL;
|
||||||
HANDLE hRemoteThread = NULL;
|
HANDLE hRemoteThread = NULL;
|
||||||
HANDLE hProcess = NULL;
|
HANDLE hProcess = NULL;
|
||||||
@@ -24,18 +22,11 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
TOKEN_PRIVILEGES priv = {0};
|
TOKEN_PRIVILEGES priv = {0};
|
||||||
BOOL bSuccess = FALSE;
|
BOOL bSuccess = FALSE;
|
||||||
|
|
||||||
log_set_level(LOG_DEBUG);
|
printf("Injector process pointer size = %zu bytes\n", sizeof(void*));
|
||||||
log_is_log_filename(false);
|
|
||||||
log_is_log_line(false);
|
|
||||||
log_is_log_time(false);
|
|
||||||
|
|
||||||
log_info("[*] libinjector Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
|
|
||||||
|
|
||||||
log_debug("Injector process pointer size = %zu bytes", sizeof(void*));
|
|
||||||
|
|
||||||
do {
|
do {
|
||||||
if (!params) {
|
if (!params) {
|
||||||
log_warn("[!] No parameters provided");
|
printf("[!] No parameters provided\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
/* open DLL file */
|
/* open DLL file */
|
||||||
@@ -45,20 +36,20 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
/* Debug helper: print the path being opened and its absolute path */
|
/* Debug helper: print the path being opened and its absolute path */
|
||||||
char fullPath[MAX_PATH] = {0};
|
char fullPath[MAX_PATH] = {0};
|
||||||
if (GetFullPathNameA(path, MAX_PATH, fullPath, NULL) != 0) {
|
if (GetFullPathNameA(path, MAX_PATH, fullPath, NULL) != 0) {
|
||||||
log_debug("Injector GetFullPathNameA success: %s", fullPath);
|
printf("Injector GetFullPathNameA success: %s\n", fullPath);
|
||||||
} else {
|
} else {
|
||||||
log_error("[*] Injector GetFullPathNameA failed: %lu", GetLastError());
|
printf("[*] Injector GetFullPathNameA failed: %lu\n", GetLastError());
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Before CreateFileA, print which file we are about to open */
|
/* Before CreateFileA, print which file we are about to open */
|
||||||
log_debug("[*] About to open DLL: %s", path);
|
printf("[*] About to open DLL: %s\n", path);
|
||||||
|
|
||||||
/* after ReadFile (or after loading into lpBuffer), verify exports again on the buffer we actually read */
|
/* after ReadFile (or after loading into lpBuffer), verify exports again on the buffer we actually read */
|
||||||
|
|
||||||
/* get file size */
|
/* get file size */
|
||||||
dwLength = GetFileSize(hFile, NULL);
|
dwLength = GetFileSize(hFile, NULL);
|
||||||
if (dwLength == INVALID_FILE_SIZE || dwLength == 0)
|
if (dwLength == INVALID_FILE_SIZE || dwLength == 0)
|
||||||
BREAK_WITH_ERROR("Failed to get DLL file size");
|
BREAK_WITH_ERROR("Failed to get DLL file size\n");
|
||||||
|
|
||||||
/* alloc local buffer and read file */
|
/* alloc local buffer and read file */
|
||||||
lpBuffer = HeapAlloc(GetProcessHeap(), 0, dwLength);
|
lpBuffer = HeapAlloc(GetProcessHeap(), 0, dwLength);
|
||||||
@@ -68,14 +59,6 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
if (!ReadFile(hFile, lpBuffer, dwLength, &dwBytesRead, NULL) || dwBytesRead != dwLength)
|
if (!ReadFile(hFile, lpBuffer, dwLength, &dwBytesRead, NULL) || dwBytesRead != dwLength)
|
||||||
BREAK_WITH_ERROR("ReadFile failed or incomplete");
|
BREAK_WITH_ERROR("ReadFile failed or incomplete");
|
||||||
|
|
||||||
/* print machine type of DLL buffer */
|
|
||||||
WORD dllMachine = get_pe_machine(lpBuffer, dwLength);
|
|
||||||
log_debug("[*] DLL PE machine: %s (0x%04x)", machine_to_str(dllMachine), dllMachine);
|
|
||||||
|
|
||||||
/* check if DLL has ReflectiveLoader export */
|
|
||||||
BOOL hasRL = has_reflective_loader_export(lpBuffer, dwLength);
|
|
||||||
log_debug("[*] DLL has ReflectiveLoader export: %s", hasRL ? "YES" : "NO");
|
|
||||||
|
|
||||||
/* enable SeDebugPrivilege (best-effort) */
|
/* enable SeDebugPrivilege (best-effort) */
|
||||||
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
|
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
|
||||||
priv.PrivilegeCount = 1;
|
priv.PrivilegeCount = 1;
|
||||||
@@ -94,57 +77,42 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
/* detect target architecture */
|
/* detect target architecture */
|
||||||
BOOL targetIsWow64 = FALSE;
|
BOOL targetIsWow64 = FALSE;
|
||||||
if (!IsWow64Process(hProcess, &targetIsWow64)) {
|
if (!IsWow64Process(hProcess, &targetIsWow64)) {
|
||||||
log_error("IsWow64Process failed");
|
printf("IsWow64Process failed\n");
|
||||||
} else {
|
} else {
|
||||||
log_info("Is target process wow64 = %d (TRUE means 32-bit process on 64-bit OS)", targetIsWow64);
|
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__)
|
|
||||||
log_info("Injector compiled as: x64");
|
|
||||||
#else
|
|
||||||
log_info("Injector compiled as: x86");
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (dllMachine == IMAGE_FILE_MACHINE_AMD64) {
|
|
||||||
log_info("[*] DLL is x64");
|
|
||||||
#if !defined(_M_X64) && !defined(__x86_64__)
|
|
||||||
log_warn("[-] MISMATCH: injector is 32-bit but DLL is x64. This will fail.");
|
|
||||||
#endif
|
|
||||||
} else if (dllMachine == IMAGE_FILE_MACHINE_I386) {
|
|
||||||
log_info("[*] DLL is x86");
|
|
||||||
#if defined(_M_X64) || defined(__x86_64__)
|
|
||||||
log_warn("[-] MISMATCH: injector is 64-bit but DLL is x86. This will fail.");
|
|
||||||
#endif
|
|
||||||
} else {
|
|
||||||
log_error("Unknown DLL machine type; proceed with caution");
|
|
||||||
}
|
|
||||||
|
|
||||||
/* allocate remote memory for InjectParameters */
|
/* allocate remote memory for InjectParameters */
|
||||||
lpRemoteParam = VirtualAllocEx(hProcess, NULL, sizeof(InjectParameters), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
lpRemoteParam = VirtualAllocEx(hProcess, NULL, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||||
if (!lpRemoteParam)
|
if (!lpRemoteParam)
|
||||||
BREAK_WITH_ERROR("VirtualAllocEx for remote param failed");
|
BREAK_WITH_ERROR("VirtualAllocEx for remote param failed\n");
|
||||||
|
|
||||||
log_debug("remote param addr = %p", lpRemoteParam);
|
printf("remote param addr = %p\n", lpRemoteParam);
|
||||||
|
|
||||||
/* write params to remote memory */
|
/* write params to remote memory */
|
||||||
SIZE_T written = 0;
|
SIZE_T written = 0;
|
||||||
if (params) {
|
if (params) {
|
||||||
if (!WriteProcessMemory(hProcess, lpRemoteParam, params, sizeof(InjectParameters), &written) || written != sizeof(InjectParameters))
|
if (!WriteProcessMemory(hProcess, lpRemoteParam, params, MAX_PATH, &written) || written != MAX_PATH)
|
||||||
BREAK_WITH_ERROR("WriteProcessMemory for remote param failed");
|
BREAK_WITH_ERROR("WriteProcessMemory for remote param failed\n");
|
||||||
} else {
|
} else {
|
||||||
log_warn("No parameters provided; using null pointer");
|
printf("No parameters provided; using null pointer\n");
|
||||||
lpRemoteParam = NULL;
|
lpRemoteParam = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* read back some bytes to verify write */
|
/* read back some bytes to verify write */
|
||||||
{
|
{
|
||||||
InjectParameters verify;
|
char verify[MAX_PATH] = {0};
|
||||||
SIZE_T read = 0;
|
SIZE_T read = 0;
|
||||||
if (ReadProcessMemory(hProcess, lpRemoteParam, &verify, sizeof(InjectParameters), &read)) {
|
|
||||||
log_debug("[*] Read back remote param, ConfigDir=%.*s", (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 {
|
} else {
|
||||||
log_error("[-] ReadProcessMemory failed: %lu", GetLastError());
|
printf("[*] lpRemoteParam == NULL, skip verify\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,20 +120,18 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
hRemoteThread = LoadRemoteLibraryR(hProcess, lpBuffer, dwLength, lpRemoteParam);
|
hRemoteThread = LoadRemoteLibraryR(hProcess, lpBuffer, dwLength, lpRemoteParam);
|
||||||
if (!hRemoteThread) {
|
if (!hRemoteThread) {
|
||||||
/* library didn't set last error; print hint info we gathered */
|
/* library didn't set last error; print hint info we gathered */
|
||||||
log_error("[-] LoadRemoteLibraryR returned NULL. GetLastError=%lu", GetLastError());
|
printf("[-] LoadRemoteLibraryR returned NULL. GetLastError=%lu\n", GetLastError());
|
||||||
log_error("[-] Diagnostic summary: dllMachine=0x%04x, hasReflectiveLoader=%d, targetIsWow64=%d",
|
|
||||||
dllMachine, hasRL ? 1 : 0, targetIsWow64 ? 1 : 0);
|
|
||||||
BREAK_WITH_ERROR("LoadRemoteLibraryR returned NULL");
|
BREAK_WITH_ERROR("LoadRemoteLibraryR returned NULL");
|
||||||
}
|
}
|
||||||
|
|
||||||
log_info("[+] DLL injected: '%s' into PID %d, remote param at %p", path, dwProcessId, lpRemoteParam);
|
printf("[+] DLL injected: '%s' into PID %d, remote param at %p\n", path, dwProcessId, lpRemoteParam);
|
||||||
/* wait for reflective loader thread to complete */
|
/* wait for reflective loader thread to complete */
|
||||||
WaitForSingleObject(hRemoteThread, INFINITE);
|
WaitForSingleObject(hRemoteThread, INFINITE);
|
||||||
|
|
||||||
/* get remote thread exit code */
|
/* get remote thread exit code */
|
||||||
DWORD exitCode = 0;
|
DWORD exitCode = 0;
|
||||||
if (GetExitCodeThread(hRemoteThread, &exitCode))
|
if (GetExitCodeThread(hRemoteThread, &exitCode))
|
||||||
log_info("[+] Remote thread exit code: %lu", exitCode);
|
printf("[+] Remote thread exit code: %lu\n", exitCode);
|
||||||
|
|
||||||
bSuccess = TRUE;
|
bSuccess = TRUE;
|
||||||
|
|
||||||
@@ -215,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
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2Ljava_lang_String_2
|
||||||
(JNIEnv *env, jobject obj, jint pid , jstring path, jstring configDir){
|
(JNIEnv *env, jobject obj, jint pid , jstring path, jstring configDir){
|
||||||
// Injection Path
|
|
||||||
const char* InjectionDLL = (*env)->GetStringUTFChars(env, path, NULL);
|
const char* InjectionDLL = (*env)->GetStringUTFChars(env, path, NULL);
|
||||||
// Config Path
|
|
||||||
const char* ConfigDir = (*env)->GetStringUTFChars(env, configDir, NULL);
|
const char* ConfigDir = (*env)->GetStringUTFChars(env, configDir, NULL);
|
||||||
|
|
||||||
InjectParameters params;
|
char params[MAX_PATH] = {0}; /* use a real buffer */
|
||||||
memset(¶ms, 0, sizeof(params));
|
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, ¶ms);
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
(*env)->ReleaseStringUTFChars(env, path, InjectionDLL);
|
(*env)->ReleaseStringUTFChars(env, path, InjectionDLL);
|
||||||
(*env)->ReleaseStringUTFChars(env, configDir, ConfigDir);
|
(*env)->ReleaseStringUTFChars(env, configDir, ConfigDir);
|
||||||
|
|
||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
#include <juiceloader.h>
|
#include <juiceloader.h>
|
||||||
|
#include <cn_xiaozhou233_juiceloader_JuiceLoader.h>
|
||||||
#include <jni.h>
|
#include <jni.h>
|
||||||
#include <jvmti.h>
|
#include <jvmti.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <Logger.hpp>
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
|
||||||
RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
|
RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
|
||||||
|
|
||||||
@@ -25,6 +26,14 @@ char* get_class_name(JNIEnv* env, jclass clazz) {
|
|||||||
return result;
|
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 ================= ///
|
/// ================= ClassFileLoadHook ================= ///
|
||||||
|
|
||||||
void JNICALL ClassFileLoadHook(
|
void JNICALL ClassFileLoadHook(
|
||||||
@@ -89,12 +98,40 @@ void JNICALL ClassFileLoadHook(
|
|||||||
|
|
||||||
|
|
||||||
/// ============ JNI Function ============ ///
|
/// ============ JNI Function ============ ///
|
||||||
JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class) {
|
C_EXPORT
|
||||||
PLOGW << "JuiceLoaderNative.init() is deprecated, init will be done automatically.";
|
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;
|
return JNI_TRUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL loader_injectJar(JNIEnv *env, jclass loader_class, jstring jarPath) {
|
C_EXPORT
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar
|
||||||
|
(JNIEnv *env, jclass loader_class, jstring jarPath) {
|
||||||
PLOGI << "Invoked!";
|
PLOGI << "Invoked!";
|
||||||
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
|
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
|
||||||
if (!pathStr) {
|
if (!pathStr) {
|
||||||
@@ -119,7 +156,10 @@ JNIEXPORT jboolean JNICALL loader_injectJar(JNIEnv *env, jclass loader_class, js
|
|||||||
PLOGI << "Jar injected: " << pathStr;
|
PLOGI << "Jar injected: " << pathStr;
|
||||||
return JNI_TRUE;
|
return JNI_TRUE;
|
||||||
}
|
}
|
||||||
JNIEXPORT jboolean JNICALL loader_redefineClass_clazz(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
|
||||||
|
C_EXPORT
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass
|
||||||
|
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
||||||
PLOGI << "Invoked!";
|
PLOGI << "Invoked!";
|
||||||
if (!JuiceLoaderNative.jvmti) {
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||||
@@ -149,7 +189,9 @@ JNIEXPORT jboolean JNICALL loader_redefineClass_clazz(JNIEnv *env, jclass loader
|
|||||||
return JNI_TRUE;
|
return JNI_TRUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL loader_redefineClass_className(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
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!";
|
PLOGI << "redefineClass_className Invoked!";
|
||||||
if (!JuiceLoaderNative.jvmti) {
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||||
@@ -169,12 +211,14 @@ JNIEXPORT jboolean JNICALL loader_redefineClass_className(JNIEnv *env, jclass lo
|
|||||||
return JNI_FALSE;
|
return JNI_FALSE;
|
||||||
}
|
}
|
||||||
|
|
||||||
jboolean ret = loader_redefineClass_clazz(env, loader_class, clazz, classBytes, length);
|
jboolean ret = Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass(env, loader_class, clazz, classBytes, length);
|
||||||
env->ReleaseStringUTFChars(className, cname);
|
env->ReleaseStringUTFChars(className, cname);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loader_class) {
|
C_EXPORT
|
||||||
|
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses
|
||||||
|
(JNIEnv *env, jclass loader_class) {
|
||||||
PLOGI << "loader_getLoadedClasses invoked!";
|
PLOGI << "loader_getLoadedClasses invoked!";
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti) {
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
@@ -201,7 +245,9 @@ JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loade
|
|||||||
return classArray;
|
return classArray;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz) {
|
C_EXPORT
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes
|
||||||
|
(JNIEnv *env, jclass loader_class, jclass clazz) {
|
||||||
PLOGI << "getClassBytes Invoked!";
|
PLOGI << "getClassBytes Invoked!";
|
||||||
if (!JuiceLoaderNative.jvmti) {
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
||||||
@@ -246,7 +292,9 @@ JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_cla
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className) {
|
C_EXPORT
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName
|
||||||
|
(JNIEnv *env, jclass loader_class, jstring className) {
|
||||||
PLOGI << "getClassBytesByName Invoked!";
|
PLOGI << "getClassBytesByName Invoked!";
|
||||||
if (!JuiceLoaderNative.jvmti) {
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
||||||
@@ -262,9 +310,12 @@ JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass load
|
|||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
return loader_getClassBytes(env, loader_class, clazz);
|
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes(env, loader_class, clazz);
|
||||||
}
|
}
|
||||||
JNIEXPORT jboolean JNICALL loader_retransformClass(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
|
||||||
|
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) {
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
PLOGE << "JuiceLoaderNative.jvmti is NULL! (retransformClass)";
|
PLOGE << "JuiceLoaderNative.jvmti is NULL! (retransformClass)";
|
||||||
return JNI_FALSE;
|
return JNI_FALSE;
|
||||||
@@ -304,7 +355,9 @@ JNIEXPORT jboolean JNICALL loader_retransformClass(JNIEnv *env, jclass loader_cl
|
|||||||
return JNI_TRUE;
|
return JNI_TRUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
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);
|
const char *name_dot = env->GetStringUTFChars(className, NULL);
|
||||||
char *name = _strdup(name_dot);
|
char *name = _strdup(name_dot);
|
||||||
for (char *p = name; *p; ++p) if (*p == '.') *p = '/';
|
for (char *p = name; *p; ++p) if (*p == '.') *p = '/';
|
||||||
@@ -318,10 +371,12 @@ JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loa
|
|||||||
return JNI_FALSE;
|
return JNI_FALSE;
|
||||||
}
|
}
|
||||||
|
|
||||||
return loader_retransformClass(env, loader_class, target, classBytes, length);
|
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass(env, loader_class, target, classBytes, length);
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jclass JNICALL loader_getClassByName(JNIEnv *env, jclass loader_class, jstring className) {
|
C_EXPORT
|
||||||
|
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName
|
||||||
|
(JNIEnv *env, jclass loader_class, jstring className) {
|
||||||
|
|
||||||
if (className == NULL) {
|
if (className == NULL) {
|
||||||
return NULL;
|
return NULL;
|
||||||
@@ -344,3 +399,132 @@ JNIEXPORT jclass JNICALL loader_getClassByName(JNIEnv *env, jclass loader_class,
|
|||||||
}
|
}
|
||||||
return clazz;
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||||
|
#include <jni.h>
|
||||||
|
/* Header for class cn_xiaozhou233_juiceloader_JuiceLoader */
|
||||||
|
|
||||||
|
#ifndef _Included_cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
#define _Included_cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: init
|
||||||
|
* Signature: ()Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
|
||||||
|
(JNIEnv *, jclass);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: injectJar
|
||||||
|
* Signature: (Ljava/lang/String;)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: redefineClass
|
||||||
|
* Signature: (Ljava/lang/Class;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass
|
||||||
|
(JNIEnv *, jclass, jclass, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: redefineClassByName
|
||||||
|
* Signature: (Ljava/lang/String;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClassByName
|
||||||
|
(JNIEnv *, jclass, jstring, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: getLoadedClasses
|
||||||
|
* Signature: ()[Ljava/lang/Class;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses
|
||||||
|
(JNIEnv *, jclass);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: getClassBytes
|
||||||
|
* Signature: (Ljava/lang/Class;)[B
|
||||||
|
*/
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes
|
||||||
|
(JNIEnv *, jclass, jclass);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: getClassBytesByName
|
||||||
|
* Signature: (Ljava/lang/String;)[B
|
||||||
|
*/
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: retransformClass
|
||||||
|
* Signature: (Ljava/lang/Class;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass
|
||||||
|
(JNIEnv *, jclass, jclass, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: retransformClassByName
|
||||||
|
* Signature: (Ljava/lang/String;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName
|
||||||
|
(JNIEnv *, jclass, jstring, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: getClassByName
|
||||||
|
* Signature: (Ljava/lang/String;)Ljava/lang/Class;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: nativeGetThreadByName
|
||||||
|
* Signature: (Ljava/lang/String;)Ljava/lang/Thread;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeGetThreadByName
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: nativeInjectJarToThread
|
||||||
|
* Signature: (Ljava/lang/Thread;Ljava/lang/String;)Ljava/lang/ClassLoader;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeInjectJarToThread
|
||||||
|
(JNIEnv *, jclass, jobject, jstring);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
@@ -23,7 +23,9 @@ typedef struct {
|
|||||||
|
|
||||||
extern RetransformClassCacheType RetransformClassCache;
|
extern RetransformClassCacheType RetransformClassCache;
|
||||||
|
|
||||||
|
#define C_EXPORT extern "C" __declspec(dllexport)
|
||||||
|
|
||||||
|
extern "C" __declspec(dllexport)
|
||||||
int InitJuiceLoader(JNIEnv *env, jvmtiEnv *jvmti);
|
int InitJuiceLoader(JNIEnv *env, jvmtiEnv *jvmti);
|
||||||
|
|
||||||
void JNICALL ClassFileLoadHook(
|
void JNICALL ClassFileLoadHook(
|
||||||
@@ -59,4 +61,6 @@ JNIEXPORT jboolean JNICALL loader_retransformClass(JNIEnv *env, jclass loader_cl
|
|||||||
JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
|
JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
|
||||||
// public static native Class<?> getClassByName(String className);
|
// public static native Class<?> getClassByName(String className);
|
||||||
JNIEXPORT jclass JNICALL loader_getClassByName(JNIEnv *env, jclass loader_class, jstring 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
|
#endif
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// JVM
|
||||||
|
#include <jni.h>
|
||||||
|
#include <jvmti.h>
|
||||||
|
#include <JuiceAgent/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;
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" __declspec(dllexport)
|
||||||
|
int InitJuiceLoader(JNIEnv *env, _jvmtiEnv *jvmti) {
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
Reference in new issue
Block a user