How can I get a function entry point in PE file - c

If I have exampleA.exe process and I use the FindEntryPointAddress() function to get the main() entry point of exampleB.exe process
FindEntryPointAddress() is a function of exampleA.exe
DWORD FindEntryPointAddress( TCHAR *exeFile )
{
BY_HANDLE_FILE_INFORMATION bhfi;
HANDLE hMapping;
char *lpBase;
HANDLE hFile = CreateFile(exeFile, GENERIC_READ, FILE_SHARE_READ, NULL,OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
;
if (!GetFileInformationByHandle(hFile, &bhfi))
;
hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, bhfi.nFileSizeHigh, bhfi.nFileSizeLow, NULL);
if (!hMapping)
;
lpBase = (char *)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, bhfi.nFileSizeLow);
if (!lpBase)
;
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpBase;
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) // 0x00004550(IMAGE_NT_SIGNATURE)
;
PIMAGE_NT_HEADERS32 ntHeader = (PIMAGE_NT_HEADERS32)(lpBase + dosHeader->e_lfanew);
if (ntHeader->Signature != IMAGE_NT_SIGNATURE)
;
DWORD pEntryPoint = ntHeader->OptionalHeader.ImageBase + ntHeader->OptionalHeader.AddressOfEntryPoint;
UnmapViewOfFile((LPCVOID)lpBase);
CloseHandle(hMapping);
CloseHandle(hFile);
printf( "test.exe entry point: %p\n", pEntryPoint );
return pEntryPoint;
} // FindEntryPointAddress()
Know I have a question is how can I edit the FindEntryPointAddress() to get the func() entrypoint of exampleB.exe
exampleB.exe
void func()
{
char str[10];
strcpy( str, "iambuffer\n" );
printf( "%s", str );
} // func()
int main()
{
func();
return 0;
} // main()
thanks a lot

Unless the function is exported (see e.g. __declspec(dllexport)) you're out of luck. Without an entry in the export table, it's not possible to get the address of a function other than the entry point.
Moreover, even if you find some data related to the function elsewhere (for example, in the debugging symbols) you might be still unable to get the address, as it's possible that the function got inlined everywhere or was eliminated for whatever other reason and its related data were not. Exported functions are not affected by that, due to the fact that the compiler and linker are careful enough to always emit them.

If you are looking into making a custom GetProcAddress, look here, however, unless you have pdb's or the functions symbol is in the EAT (export address table), you'll be unable to find it.

Related

Execute PE from memory

I tried to write LoadLibrary function in C.
The function gets a path to a DLL file which, normally, pops up message box when it loads (I tried to run that DLL file using the original LoadLibrary function and it works).
Basically, the DLL content is loaded into a buffer, parsed and runs from entry point.
In VirtualAllocEx function, I use PAGE_READWRITE protection mode. Then, when running the line f(nth->OptionalHeader.ImageBase, DLL_PROCESS_ATTACH, NULL), I get the following error message: Exception thrown at 0x10011032 in PE.exe: 0xC0000005: Access violation executing location 0x10011032. (0x10011032 is entry point address).
If I change the mode to PAGE_EXECUTE_READWRITE, the error message is: Exception thrown at 0x00019644 in PE.exe: 0xC0000005: Access violation executing location 0x00019644. (No idea what is that address).
I think that it's clear why it's not smart to allow execution in all sectors of the PE, but I did it for testing purposes only. In the final code, I'll need to write it properly.
My code is attached.
(BTW, if you have other suggestions that are not related to my question - I'll glad to know).
#include <Windows.h>
typedef HMODULE func(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved);
HMODULE LoadLibraryFromMem(char* dllPath)
{
DWORD read;
HANDLE handle;
handle = CreateFileA(dllPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD size = GetFileSize(handle, NULL);
PVOID vDll = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
BOOL r = ReadFile(handle, vDll, size, &read, NULL);
CloseHandle(handle);
PIMAGE_DOS_HEADER dosh = (PIMAGE_DOS_HEADER)vDll;
PIMAGE_NT_HEADERS nth = (PIMAGE_NT_HEADERS)((PBYTE)vDll + dosh->e_lfanew);
handle = GetCurrentProcess();
PVOID vImg = VirtualAllocEx(
handle,
nth->OptionalHeader.ImageBase,
nth->OptionalHeader.SizeOfImage,
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE
); // HERE --> PAGE_EXECUTE_READWRITE
WriteProcessMemory(
handle,
vImg,
vDll,
nth->OptionalHeader.SizeOfHeaders,
0
);
PIMAGE_SECTION_HEADER sech = IMAGE_FIRST_SECTION(nth);
for (size_t i = 0; i < nth->FileHeader.NumberOfSections; i++)
WriteProcessMemory(
handle,
(PBYTE)vImg + sech[i].VirtualAddress,
(PBYTE)vDll + sech[i].PointerToRawData,
sech[i].SizeOfRawData,
0
);
PIMAGE_IMPORT_DESCRIPTOR impd = nth->OptionalHeader.ImageBase + nth->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
HANDLE proc;
while (((PIMAGE_IMPORT_DESCRIPTOR)impd)->Name)
{
LPSTR dllName = (nth->OptionalHeader.ImageBase + ((PIMAGE_IMPORT_DESCRIPTOR)impd)->Name);
HMODULE dllAdr = LoadLibraryA(dllName);
PDWORD iat = nth->OptionalHeader.ImageBase + ((PIMAGE_IMPORT_DESCRIPTOR)impd)->FirstThunk;
while (*iat)
{
LPSTR funcName = ((PIMAGE_IMPORT_BY_NAME)(nth->OptionalHeader.ImageBase + *iat))->Name;
proc = GetProcAddress(dllAdr, funcName);
if (!proc)
return NULL;
impd->FirstThunk = proc;
iat++;
}
impd++;
}
func* f = (func*)(nth->OptionalHeader.ImageBase + nth->OptionalHeader.AddressOfEntryPoint);
f(nth->OptionalHeader.ImageBase, DLL_PROCESS_ATTACH, NULL);
}
int main()
{
LoadLibraryFromMem("mydll.dll");
return 0;
}
Thanks in advance!

getting a list of kernel objects windows

HI!
I bet more than a week and I can not form a complete picture of how you can get a list of kernel objects .My algorithm is as follows :
1) Connecting NTDLL.dll (LoadLibrary)
2) GetProcAddress (variable_Library_name, "NtQueryDirectoryObject")
and the pre-announcement structures : _OBJDIR_INFORMATION,
_OBJECT_ATTRIBUTES
3) Trying to apply a function NtOpenDirectoryObject for a list of
objects
Here is a piece of code that is responsible for the use of the function NtOpenDirectoryObject:
OBJDIR_INFORMATION *ssinfo =(OBJDIR_INFORMATION* ) HeapAlloc(GetProcessHeap(), 0, 0x800);
///////////////////////
HANDLE hFile,hThread,hMapFile;
HMODULE hNtdll ,hKernel;
DWORD dwThreadId;
OBJECT_ATTRIBUTES obj;
WCHAR * uString=L"\\BaseNamedObjects";
UNICODE_STRING str;
DWORD i,a,iStrLen,b=0;
char sObjName[30],sTmp[50];
LPVOID lpMapAddress;
FARPROC pWinExec,pExitThread;
bool bFound;
char* sCommand;
/////////////////////////////////////////////////////////////////
NtQueryDirectoryObject = (NTQUERYDIRECTORYOBJECT )GetProcAddress(hinstLib,"NtQueryDirectoryObject");
InitializeObjectAttributes (&obj, &str, 0, 0, 00);
NtOpenDirectoryObject(&hFile,0x20001,&obj);
The full code (including struct definitions) is at: http://pastebin.com/pDNb3GTn
When calling a function with parameters NtOpenDirectoryObject get an exception c0000005, which means that access is blocked .
tell me please, am I doing smth wrong, and where is my mistake. Is it possible to not to use the native api? Thank you for your help
Exception c0000005 is an Access Violation. That does not mean that access was blocked. It means invalid memory was accessed, such as if a NULL/uninitialized pointer were accessed, or if you are not aligning data correctly and accessing something out of bounds of what you have allocated.
As Andrew mentioned, you are not initializing the UNICODE_STRING at all. Try this instead:
hNtdll = LoadLibrary("ntdll.dll");
NtOpenDirectoryObject = (NTOPENDIRECTORYOBJECT) GetProcAddress(hNtdll, "NtOpenDirectoryObject");
...
if (NtOpenDirectoryObject)
{
// add these three lines
str.Length = lstrlenW(uString) * sizeof(WCHAR);
str.MaximumLength = str.Length;
str.Buffer = uString;
InitializeObjectAttributes (&obj, &str, 0, NULL, NULL);
NtOpenDirectoryObject(&hFile, 0x20001, &obj);
}

How to know the address range when searching for a function by its signature?

I'm trying to search for a function by its "signature".
However I can't figure out what address range I'm supposed to be searching?
I've had a look at VirtualQuery() and GetNativeSystemInfo() but I'm not if I'm on the right path or not.
Edit: Question re-attempt.
Using Win32 API I'm trying to find out how to get the start and end address of the executable pages of the process my code is executing in.
This is what I've tried:
SYSTEM_INFO info;
ZeroMemory( &info, sizeof( SYSTEM_INFO ) );
GetNativeSystemInfo( &info ); // GetSystemInfo() might be wrong on WOW64.
info.lpMinimumApplicationAddress;
info.lpMaximumApplicationAddress;
HANDLE thisProcess = GetCurrentProcess();
MEMORY_BASIC_INFORMATION memInfo;
ZeroMemory( &memInfo, sizeof( memInfo ) );
DWORD addr = (DWORD)info.lpMinimumApplicationAddress;
do
{
if ( VirtualQueryEx( thisProcess, (LPVOID)addr, &memInfo, sizeof( memInfo ) ) == 0 )
{
DWORD gle = GetLastError();
if ( gle != ERROR_INVALID_PARAMETER )
{
std::stringstream str;
str << "VirtualQueryEx failed with: " << gle;
MessageBoxA( NULL, str.str().c_str(), "Error", MB_OK );
}
break;
}
if ( memInfo.Type == MEM_IMAGE )
{
// TODO: Scan this memory block for the the sigature
}
addr += info.dwPageSize;
}
while ( addr < (DWORD)info.lpMaximumApplicationAddress );
The reason for doing this is that I'm looking for an un-exported function by its signature as asked here:
Find a function by it signature in Windows DLL
See the answer about "code signature scanning".
While this is enumerating an address range I don't know if this is correct or not since I don't know what the expected range should be. Its just the best I could come up with from looking around MSDN.
the address range when signature scanning a module is from the start of the code section to the start + the section size. the start of the code section and its size are in the PE. most tools take the lazy route and scan the entire module (again using the PE to get the size, but with the module handle as the start address).

How do I embed and use resource files in a C program using VS11?

This is my first attempt at using a resource file. I have seen a lot of answers that apply to C# but not C. Any suggestions?
Assuming you mean the method used by Sysinternals and others to carry the drivers or needed DLLs (or even the x64 version of the program itself) in the resource section of a program (e.g. Sysinternals' Process Explorer), using Microsoft Visual C you can use this code:
BOOL ExtractResTo(HINSTANCE Instance, LPCTSTR BinResName, LPCTSTR NewPath, LPCTSTR ResType)
{
BOOL bResult = FALSE;
HRSRC hRsrc;
if(hRsrc = FindResource(HMODULE(Instance), BinResName, ResType))
{
HGLOBAL hGlob
if(HGLOBAL hGlob = LoadResource(Instance, hRsrc))
{
DWORD dwResSize = SizeofResource(Instance, hRsrc);
HANDLE hFileWrite = CreateFile(NewPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_ARCHIVE, 0);
if(hFileWrite != INVALID_HANDLE_VALUE)
__try
{
DWORD dwSizeWritten = 0;
bResult = (WriteFile(hFileWrite, LockResource(hGlob), dwResSize, &dwSizeWritten, NULL) && (dwSizeWritten == dwResSize));
}
__finally
{
CloseHandle(hFileWrite);
}
}
}
return bResult;
}
This saves the given resource (BinResName) of resource type (ResType) from the module (e.g. a DLL) Instance to file NewPath. Obviously if your C doesn't understand __try and __finally you'll have to adjust the code accordingly.
Taken from here (in SIDT.rar) and adjusted for C. The code is under the liberal BSD license according to the website.
Now if you wanted to get the pointer to the data (ppRes) and its size (pwdResSize):
BOOL GetResourcePointer(HINSTANCE Instance, LPCTSTR ResName, LPCTSTR ResType, LPVOID* ppRes, DWORD* pdwResSize)
{
// Check the pointers to which we want to write
if(ppRes && pdwResSize)
{
HRSRC hRsrc;
// Find the resource ResName of type ResType in the DLL/EXE described by Instance
if(hRsrc = FindResource((HMODULE)Instance, ResName, ResType))
{
HGLOBAL hGlob;
// Make sure it's in memory ...
if(hGlob = LoadResource(Instance, hRsrc))
{
// Now lock it to get a pointer
*ppRes = LockResource(hGlob);
// Also retrieve the size of the resource
*pdwResSize = SizeofResource(Instance, hRsrc);
// Return TRUE only if both succeeded
return (*ppRes && *pdwResSize);
}
}
}
// Failure means don't use the values in *ppRes and *pdwResSize
return FALSE;
}
Call like this:
LPVOID pResource;
DWORD pResourceSize;
if(GetResourcePointer(hInstance, _T("somename"), _T("sometype"), &pResource, &pResourceSize))
{
// use pResource and pResourceSize
// e.g. store into a string buffer or whatever you want to do with it ...
}
Note, this also works for resources with integer IDs. You can detect these by using the macro IS_INTRESOURCE.
The resource script, e.g. myresources.rc, itself is trivial:
#include <winnt.rh>
"somename" "sometype" "path\to\file\to\embed"
RCDATA instead of sometype is a reasonable choice
#include <winnt.rh> // for RCDATA to be known to rc.exe
"somename" RCDATA "path\to\file\to\embed"
... in which case you would adjust the above call to be:
GetResourcePointer(hInstance, _T("somename"), RT_RCDATA, &pResource, &pResourceSize)
Complete example making use of GetResourcePointer above. Let's say you have a pointer variable char* buf and you know your resource is actual text, then you need to make sure that it is zero-terminated when used as a string, that's all.
Resource script:
#include <winnt.rh>
"test" RCDATA "Test.txt"
The code accessing it
char* buf = NULL;
LPVOID pResource;
DWORD pResourceSize;
if(GetResourcePointer(hInstance, _T("test"), RT_RCDATA, &pResource, &pResourceSize))
{
if(buf = calloc(pResourceSize+1, sizeof(char)))
{
memcpy(buf, pResource, pResourceSize);
// Now use buf
free(buf);
}
}
Unless, of course you meant to simply link a .res file which works by passing it to the linker command line.

Win32 - Backtrace from C code

I'm currently looking for a way to get backtrace information under Windows, from C code (no C++).
I'm building a cross-platform C library, with reference-counting memory management. It also have an integrated memory debugger that provides informations about memory mistakes (XEOS C Foundation Library).
When a fault occurs, the debugger is launched, providing information about the fault, and the memory record involved.
On Linux or Mac OS X, I can look for execinfo.h in order to use the backtrace function, so I can display additional infos about the memory fault.
I'm looking for the same thing on Windows.
I've seen How can one grab a stack trace in C? on Stack Overflow. I don't want to use a third-party library, so the CaptureStackBackTrace or StackWalk functions looks good.
The only problem is that I just don't get how to use them, even with the Microsoft documentation.
I'm not used to Windows programming, as I usually work on POSIX compliant systems.
What are some explanations for those functions, and maybe some examples?
EDIT
I'm now considering using the CaptureStackBackTrace function from DbgHelp.lib, as is seems there's a little less overhead...
Here's what I've tried so far:
unsigned int i;
void * stack[ 100 ];
unsigned short frames;
SYMBOL_INFO symbol;
HANDLE process;
process = GetCurrentProcess();
SymInitialize( process, NULL, TRUE );
frames = CaptureStackBackTrace( 0, 100, stack, NULL );
for( i = 0; i < frames; i++ )
{
SymFromAddr( process, ( DWORD64 )( stack[ i ] ), 0, &symbol );
printf( "%s\n", symbol.Name );
}
I'm just getting junk. I guess I should use something else than SymFromAddr.
Alright, now I got it. : )
The problem was in the SYMBOL_INFO structure. It needs to be allocated on the heap, reserving space for the symbol name, and initialized properly.
Here's the final code:
void printStack( void );
void printStack( void )
{
unsigned int i;
void * stack[ 100 ];
unsigned short frames;
SYMBOL_INFO * symbol;
HANDLE process;
process = GetCurrentProcess();
SymInitialize( process, NULL, TRUE );
frames = CaptureStackBackTrace( 0, 100, stack, NULL );
symbol = ( SYMBOL_INFO * )calloc( sizeof( SYMBOL_INFO ) + 256 * sizeof( char ), 1 );
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof( SYMBOL_INFO );
for( i = 0; i < frames; i++ )
{
SymFromAddr( process, ( DWORD64 )( stack[ i ] ), 0, symbol );
printf( "%i: %s - 0x%0X\n", frames - i - 1, symbol->Name, symbol->Address );
}
free( symbol );
}
Output is:
6: printStack - 0xD2430
5: wmain - 0xD28F0
4: __tmainCRTStartup - 0xE5010
3: wmainCRTStartup - 0xE4FF0
2: BaseThreadInitThunk - 0x75BE3665
1: RtlInitializeExceptionChain - 0x770F9D0F
0: RtlInitializeExceptionChain - 0x770F9D0F
Here's my super-low-fi alternative, as used for reading stacks from a C++ Builder app. This code is executed within the process itself when it crashes and gets a stack into the cs array.
int cslev = 0;
void* cs[300];
void* it = <ebp at time of crash>;
void* rm[2];
while(it && cslev<300)
{
/* Could just memcpy instead of ReadProcessMemory, but who knows if
the stack's valid? If it's invalid, memcpy could cause an AV, which is
pretty much exactly what we don't want
*/
err=ReadProcessMemory(GetCurrentProcess(),it,(LPVOID)rm,sizeof(rm),NULL);
if(!err)
break;
it=rm[0];
cs[cslev++]=(void*)rm[1];
}
UPDATE
Once I've got the stack, I then go about translating it into names. I do this by cross-referencing with the .map file that C++Builder outputs. The same thing could be done with a map file from another compiler, although the formatting would be somewhat different. The following code works for C++Builder maps. This is again quite low-fi and probably not the canonical MS way of doing things, but it works in my situation. The code below isn't delivered to end users.
char linbuf[300];
char *pars;
unsigned long coff,lngth,csect;
unsigned long thisa,sect;
char *fns[300];
unsigned int maxs[300];
FILE *map;
map = fopen(mapname, "r");
if (!map)
{
...Add error handling for missing map...
}
do
{
fgets(linbuf,300,map);
} while (!strstr(linbuf,"CODE"));
csect=strtoul(linbuf,&pars,16); /* Find out code segment number */
pars++; /* Skip colon */
coff=strtoul(pars,&pars,16); /* Find out code offset */
lngth=strtoul(pars,NULL,16); /* Find out code length */
do
{
fgets(linbuf,300,map);
} while (!strstr(linbuf,"Publics by Name"));
for(lop=0;lop!=cslev;lop++)
{
fns[lop] = NULL;
maxs[lop] = 0;
}
do
{
fgets(linbuf,300,map);
sect=strtoul(linbuf,&pars,16);
if(sect!=csect)
continue;
pars++;
thisa=strtoul(pars,&pars,16);
for(lop=0;lop!=cslev;lop++)
{
if(cs[lop]<coff || cs[lop]>coff+lngth)
continue;
if(thisa<cs[lop]-coff && thisa>maxs[lop])
{
maxs[lop]=thisa;
while(*pars==' ')
pars++;
fns[lop] = fnsbuf+(100*lop);
fnlen = strlen(pars);
if (fnlen>100)
fnlen = 100;
strncpy(fns[lop], pars, 99);
fns[lop][fnlen-1]='\0';
}
}
} while (!feof(map));
fclose(map);
After running this code, the fns array contains the best-matching function from the .map file.
In my situation, I actually have the call stack as produced by the first piece of code submitting to a PHP script - I do the equivalent of the C code above using a piece of PHP. This first bit parses the map file (Again, this works with C++Builder maps but could be easily adapted to other map file formats):
$file = fopen($mapdir.$app."-".$appversion.".map","r");
if (!$file)
... Error handling for missing map ...
do
{
$mapline = fgets($file);
} while (!strstr($mapline,"CODE"));
$tokens = split("[[:space:]\:]", $mapline);
$codeseg = $tokens[1];
$codestart = intval($tokens[2],16);
$codelen = intval($tokens[3],16);
do
{
$mapline = fgets($file);
} while (!strstr($mapline,"Publics by Value"));
fgets($file); // Blank
$addrnum = 0;
$lastaddr = 0;
while (1)
{
if (feof($file))
break;
$mapline = fgets($file);
$tokens = split("[[:space:]\:]", $mapline);
$thisseg = $tokens[1];
if ($thisseg!=$codeseg)
break;
$addrs[$addrnum] = intval($tokens[2],16);
if ($addrs[$addrnum]==$lastaddr)
continue;
$lastaddr = $addrs[$addrnum];
$funcs[$addrnum] = trim(substr($mapline, 16));
$addrnum++;
}
fclose($file);
Then this bit translates an address (in $rowaddr) into a given function (as well as the offset after the function):
$thisaddr = intval($rowaddr,16);
$thisaddr -= $codestart;
if ($thisaddr>=0 && $thisaddr<=$codelen)
{
for ($lop=0; $lop!=$addrnum; $lop++)
if ($thisaddr<$addrs[$lop])
break;
}
else
$lop = $addrnum;
if ($lop!=$addrnum)
{
$lop--;
$lines[$ix] = substr($line,0,13).$rowaddr." : ".$funcs[$lop]." (+".sprintf("%04X",$thisaddr-$addrs[$lop]).")";
$stack .= $rowaddr;
}
else
{
$lines[$ix] = substr($line,0,13).$rowaddr." : external";
}
#Jon Bright: You say "who known whether the stack is valid...": Well there's a way to find out, as the stack addresses are known. Assuming you need a trace in the current thread, of course:
NT_TIB* pTEB = GetTEB();
UINT_PTR ebp = GetEBPForStackTrace();
HANDLE hCurProc = ::GetCurrentProcess();
while (
((ebp & 3) == 0) &&
ebp + 2*sizeof(VOID*) < (UINT_PTR)pTEB->StackBase &&
ebp >= (UINT_PTR)pTEB->StackLimit &&
nAddresses < nTraceBuffers)
{
pTraces[nAddresses++]._EIP = ((UINT_PTR*)ebp)[1];
ebp = ((UINT_PTR*)ebp)[0];
}
My "GetTEB()" is NtCurrentTeb() from NTDLL.DLL - and it is not only Windows 7 and above as stated in the current MSDN. MS junks up the documentation. It was there for a long time. Using the ThreadEnvironment Block (TEB), you do not need ReadProcessMemory() as you know the stack's lower and upper limit. I assume this is the fastest way to do it.
Using the MS compiler, GetEBPForStackTrace() can be
inline __declspec(naked) UINT_PTR GetEBPForStackTrace()
{
__asm
{
mov eax, ebp
ret
}
}
as easy way to get EBP of the current thread (but you can pass any valid EBP to this loop as long as it is for the current thread).
Limitation: This is valid for x86 under Windows.

Resources