Call function from executable - c++

I want to call a function from an executable. The only way to reach that process is to inject a dll in the parent process. I can inject a dll in the parent process but how do I call a function from the child process?
Something like
_asm
{
call/jmp address
}
doesnt work. I hope you understand what I mean.

If you are running inside the process, you need to know the offset of the function you want to call from the base of the module (the exe) which contains the function. Then, you just need to make a function pointer and call it.
// assuming the function you're calling returns void and takes 0 params
typedef void(__stdcall * voidf_t)();
// make sure func_offset is the offset of the function when the module is loaded
voidf_t func = (voidf_t) (((uint8_t *)GetModuleHandle('module_name')) + func_offset);
func(); // the function you located is called here
The solution you have will work on 32bit systems (inline assembly is not permitted in 64 bit) if you know the address of the function, but you'll need to make sure you implement the calling convention properly. The code above uses GetModuleHandle to resolve the currently loaded base of the module whose function you want to call.
Once you've injected your module into the running process ASLR isn't really an issue, since you can just ask windows for the base of the module containing the code you wish to call. If you want to find the base of the exe running the current process, you can call GetModuleHandle with a parameter of NULL. If you are confident that the function offset is not going to change, you can hard code the offset of the function you wish to call, after you've found the offset in a disassembler or other tool. Assuming the exe containing the function isn't altered, that offset will be constant.
As mentioned in the comments, the calling convention is important in the function typedef, make sure it matches the calling convention of the function you're calling.

Execution Fundamentals
To call a function you need an address or a interrupt number. The address is loaded into the Program Counter register and execution is transferred. Some processors allow for "Software Interrupts", in which the program executes a special instruction that invokes the software interrupt. This is the foundation for executing functions.
More Background -- Relative Addresses
There are two common forms of executables: Absolute Addressing and Relative (or Position Independ Code,PIC). In absolute addressing, the functions are at hard-coded addresses. The functions won't move. Usually used in embedded systems.
In the relative addressing model, the addresses are relative to the value in the Program Counter register. For example, your function may be 1024 bytes away, so the compiler would emit a relative branch instruction for 1024 bytes (away).
Operating Systems and Moving Targets
Many operating systems load programs in different places for each invocation. This means your executable may start at address 1000, and the next time at address 127654. In these operating systems, there is no guarantee that an executable will be launched at the same location each time.
Executing within your program
Executing functions within your program is easy. The linker decides where all the functions will be located and determines how to execute them; whether to use absolute addressing, PIC or a mixture.
Executing Functions in another Executable
With the above knowledge, there are issues with executing functions in another program:
Location of the Function in the external executable
Determining if the executable is active
Calling protocol for the executable
Most executables do not contain any information about where their functions are, so you will need to know where it is. You will also need to know if the function is absolute addressing or PIC. You will also need to know if the function is in memory when you need it or if the OS has paged the function to the hard drive.
Knowing the function location is necessary. However, the location is of no use if the OS has not loaded the executable. Before you call a function in another executable, you will need to know if it is present in memory when the call is executed.
Lastly, you will need to know the protocol used for the external function. For example, are the values passed by register? Are they on the stack? Are they passed by pointer (address)?
A Solution: Shared Libraries
Operating systems (OS) have evolved to allow for dynamically sharing of functions. These functions exist in Dynamically Linked Libraries (DLL) or Shared Library(.SO). Your program tells the OS to load the library into memory, then you tell the OS to execute the function by giving it the name of the function.
The caveat is that the function you desire must be in a library. If the executable doesn't use a shared library or the function you need is not in a library, then your mission is more difficult.

Related

How to call functions in a DLL that is currently load in another process? [duplicate]

I have a DLL that I inject into another process but I want to be able to call the exports on that DLL from my application. I've read elsewhere that you have to the SendMessage API but I have no idea what to do. Is there any example code on how this is done?
While it is not possible to directly call a function in another process, you can do it indirectly pretty easily with a few steps and the Windows API.
Get the addresses of LoadLibrary and GetProcAddress from your own process. kernel32.dll should be loaded at the same address in every process, so you can rely on them being present in the process into which you are injecting
Create a struct that will hold all the arguments you want to pass to your function that will call the functions in the other process (because CreateRemoteThread can only pass one argument to a function, so we'll use it to pass a pointer to the structure) which at least contains member function pointers to hold the addresses of LoadLibrary and GetProcAddress
Allocate enough memory for a struct in the remote process via VirtualAllocEx, then fill it with the correct information with WriteProcessMemory
Write a function, taking a pointer to the struct you wrote, that uses LoadLibrary/GetProcAddress to call the function you want. Remember to use the pointers to those functions in the struct you are passing the function, not the names.
Allocate enough memory in the remote process to hold the function with VirtualAllocEx, making sure to pass VAX the PAGE_EXECUTE_READWRITE flag so that it can hold executable code
Read and write the function's code from your process to the other process via Read/WriteProcessMemory
Call the function in the remote process (which is at the address returned by the VirtualAllocEx) by using CreateRemoteThread.
Make sure that all the data you pass to the function is either stored inside the struct and/or resides in the remote process's address space (get it there with VirtualAllocEx/WriteProcessMemory.
It may look a little involved, but it's not really that complicated. If you need some help with it, feel free to ask in a comment.
You can't directly call functions in another process, in general. There are, however, some workarounds you can use.
First, if you know the address of the export (which isn't the case a lot of the time), and the function you call uses the __stdcall calling convention, takes a pointer-sized integer as an argument, and returns a DWORD, you can use CreateRemoteThread to execute it in a thread in the remote process. This is often used to run LoadLibrary to inject a DLL into a target process, since LoadLibrary is loaded in the same address on all processes on a given computer.
Otherwise, the DLL you inject will need to do some sort of RPC with the process that called it. For example, you could have your injected DLL spawn a thread in its DLL_PROCESS_ATTACH handler, which in turn connects to a named pipe, or connects over COM or something to the master process.
SendMessage would need a window handle (hidden or visible), and a message-pump associated with it, that can handle the custom message. As with UAC/Windows-7, the integrity levels of applications may prevent other applications to send/post messages from other processes having low integrity.
It is better to have another thread that waits for these custom messages. For this, you may use pipes (named or unnamed), sockets, mail-slots, shared memory (along with mutex/event for triggering). The another processes would send the message using same protocol.
But before implementing this custom messaging/protocol/IPC mechanism, I suggest you to first determine the exact need.

Call external function(from one exe to another)

Lets say the process 1 is the main process and the process 2 is the target process(i can't edit it by the way), i want to be able to call a function from the process 2 in the process 1, anyone have a nice way to do that?I was thinking in inject a dll with exports that calls that function and use GetProcAddress externally...Is that possible?Is that the best way to do it?
Thanks for the time.
The title and body of your question ask two subtly different questions.
Having one executable call a function that's contained in another executable is quite easy, at least if the name of the function in question has been exported. You can use LoadLibrary to load an executable just like you would a DLL, then use GetProcAddress to get the address of the function you want to call, and call it normally. Keep in mind, however, that the function may not work correctly without other initialization that happens before it's called inside its own executable.
Calling a function in the context of another process (not just in another executable) is considerably more work. The basic idea is to have a function that makes the call and (for example) writes a result to some memory shared with the process making the call. You then use CreateRemoteThread to have that function execute in the context of the process containing the function you need to call.
If the target process has been written to support it there are other methods such as COM that are intended to support this type of capability much more cleanly. They're generally preferable if available.

Real Starting Address Of A Process in Memory / Win32 Debug APIs

At first, I'm a newbie on c++ and debuging. I use CreateProcess api with DEBUG_ONLY_THIS_PROCESS parameter, then wait for CREATE_PROCESS_DEBUG_EVENT. When recived, i check for the Eip register to get the address of the point. And i tought that this point is the Main function's address.
To verify this idea i used ollydbg to see the starting address of the exe. But it wasn't same with mine. The one i found with debug apis is 0x77a364d8, but olly says that it's 0x00401000. Then i didn't stop and checked for the address 0x77a364d8 in olly. I found the address and set a breakpoint there.
Then I reloaded the olly and saw that olly firstly goes 0x77a364d8 address and loades the process and then goes to the 0x00401000 address and waits there. 0x77a364d8 address points some ntdll functions to load process to memory as i see.
If it's true, how can i get the 0x00401000 address by code( c++, i'm a newbie and please cross the t's :) ), and is it the Main function's address or what?
After you receive the CREATE_PROCESS_DEBUG_EVENT you should be able to access the CREATE_PROCESS_DEBUG_INFO member of the union. It has a member called lpStartAddress.
Your debugging event loop should look something like:
DWORD dwContinueDebugStatus = DBG_CONTINUE;
while(dwContinueDebugStatus)
{
DEBUG_EVENT debugEvt;
WaitForDebugEvent(&debugEvt, INFINITE);
switch(debugEvt.dwDebugEventCode)
{
case CREATE_PROCESS_DEBUG_EVENT:
// Grab the main thread entry point.
LPTHREAD_START_ROUTINE exentry = debugEvt.u.CreateProcessInfo.lpStartAddress;
break;
/* Handle the rest of your debug events here. */
}
ContinueDebugEvent(debugEvt.dwProcessId, debugEvt.dwThreadId, dwContinueDebugStatus);
}
Edit:
A couple things I forgot to mention...
Getting the entry point by any of these means will likely be the CRT function that calls your main(). There isn't a reliable way to get the main() without symbol lookups in using dbghelp.dll.
Also, the book Debugging Applications by John Robbins has a chapter about creating a small debugger with some example code. It is probably the best documentation/example I've found (but I wish it were better). It can be had pretty cheap so it might be worth looking at.
The entry point will not (at least normally) be the same as main. The signature for the entry point is void entrypoint(void);. That has to retrieve the command line, parse it into individual arguments, etc., in preparation for calling main (and there's an entirely separate one that retrieves the rather different "stuff" necessary before calling WinMain in a GUI program).
If you want the actual address of main, you might want to at least try using SymFromName for the names _main and/or _wmain (or, if you might be dealing with a GUI program, WinMain/wWinmain) to get to code that's really part of the target program instead of something from a library module almost nobody has ever even seen.
This is all from memory, so it might contain a few mistakes.
In order to find the entry point address of the EXE in a new process, you need to read this process's PEB field ImageBaseAddress. The PEB is always at a fixed address, but it depends on if your EXE is 32 or 64-bit, which you'll have to determine beforehand (there is a 32-bit PEB for WOW64 but I think it may not be initialized yet at that point).
Note that you can't just fetch this from the EXE because it might be relocated due to ASLR. Once you have this, you can read PE header of the EXE using ReadProcessMemory and get the AddressOfEntryPoint field from the IMAGE_OPTIONAL_HEADER struct. It's an RVA so add it to the base address found earlier, and voila, you have your entry point address.

Converting a string into a function in c++

I have been looking for a way to dynamically load functions into c++ for some time now, and I think I have finally figure it out. Here is the plan:
Pass the function as a string into C++ (via a socket connection, a file, or something).
Write the string into file.
Have the C++ program compile the file and execute it. If there are any errors, catch them and return it.
Have the newly executed program with the new function pass the memory location of the function to the currently running program.
Save the location of the function to a function pointer variable (the function will always have the same return type and arguments, so
this simplifies the declaration of the pointer).
Run the new function with the function pointer.
The issue is that after step 4, I do not want to keep the new program running since if I do this very often, many running programs will suck up threads. Is there some way to close the new program, but preserve the memory location where the new function is stored? I do not want it being overwritten or made available to other programs while it is still in use.
If you guys have any suggestions for the other steps as well, that would be appreciated as well. There might be other libraries that do things similar to this, and it is fine to recommend them, but this is the approach I want to look into — if not for the accomplishment of it, then for the knowledge of knowing how to do so.
Edit: I am aware of dynamically linked libraries. This is something I am largely looking into to gain a better understanding of how things work in C++.
I can't see how this can work. When you run the new program it'll be a separate process and so any addresses in its process space have no meaning in the original process.
And not just that, but the code you want to call doesn't even exist in the original process, so there's no way to call it in the original process.
As Nick says in his answer, you need either a DLL/shared library or you have to set up some form of interprocess communication so the original process can send data to the new process to be operated on by the function in question and then sent back to the original process.
How about a Dynamic Link Library?
These can be linked/unlinked/replaced at runtime.
Or, if you really want to communicated between processes, you could use a named pipe.
edit- you can also create named shared memory.
for the step 4. we can't directly pass the memory location(address) from one process to another process because the two process use the different virtual memory space. One process can't use memory in other process.
So you need create a shared memory through two processes. and copy your function to this memory, then you can close the newly process.
for shared memory, if in windows, looks Creating Named Shared Memory
http://msdn.microsoft.com/en-us/library/windows/desktop/aa366551(v=vs.85).aspx
after that, you still create another memory space to copy function to it again.
The idea is that the normal memory allocated only has read/write properties, if execute the programmer on it, the CPU will generate the exception.
So, if in windows, you need use VirtualAlloc to allocate the memory with the flag,PAGE_EXECUTE_READWRITE (http://msdn.microsoft.com/en-us/library/windows/desktop/aa366887(v=vs.85).aspx)
void* address = NULL;
address= VirtualAlloc(NULL,
sizeof(emitcode),
MEM_COMMIT|MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
After copy the function to address, you can call the function in address, but need be very careful to keep the stack balance.
Dynamic library are best suited for your problem. Also forget about launching a different process, it's another problem by itself, but in addition to the post above, provided that you did the virtual alloc correctly, just call your function within the same "loadder", then you shouldn't have to worry since you will be running the same RAM size bound stack.
The real problems are:
1 - Compiling the function you want to load, offline from the main program.
2 - Extract the relevant code from the binary produced by the compiler.
3 - Load the string.
1 and 2 require deep understanding of the entire compiler suite, including compiler flag options, linker, etc ... not just the IDE's push buttons ...
If you are OK, with 1 and 2, you should know why using a std::string or anything but pure char *, is an harmfull.
I could continue the entire story but it definitely deserve it's book, since this is Hacker/Cracker way of doing things I strongly recommand to the normal user the use of dynamic library, this is why they exists.
Usually we call this code injection ...
Basically it is forbidden by any modern operating system to access something for exceution after the initial loading has been done for sake of security, so we must fall back to OS wide validated dynamic libraries.
That's said, one you have valid compiled code, if you realy want to achieve that effect you must load your function into memory then define it as executable ( clear the NX bit ) in a system specific way.
But let's be clear, your function must be code position independant and you have no help from the dynamic linker in order to resolve symbol ... that's the hard part of the job.

Calling functions in a DLL loaded by another process

I have a DLL that I inject into another process but I want to be able to call the exports on that DLL from my application. I've read elsewhere that you have to the SendMessage API but I have no idea what to do. Is there any example code on how this is done?
While it is not possible to directly call a function in another process, you can do it indirectly pretty easily with a few steps and the Windows API.
Get the addresses of LoadLibrary and GetProcAddress from your own process. kernel32.dll should be loaded at the same address in every process, so you can rely on them being present in the process into which you are injecting
Create a struct that will hold all the arguments you want to pass to your function that will call the functions in the other process (because CreateRemoteThread can only pass one argument to a function, so we'll use it to pass a pointer to the structure) which at least contains member function pointers to hold the addresses of LoadLibrary and GetProcAddress
Allocate enough memory for a struct in the remote process via VirtualAllocEx, then fill it with the correct information with WriteProcessMemory
Write a function, taking a pointer to the struct you wrote, that uses LoadLibrary/GetProcAddress to call the function you want. Remember to use the pointers to those functions in the struct you are passing the function, not the names.
Allocate enough memory in the remote process to hold the function with VirtualAllocEx, making sure to pass VAX the PAGE_EXECUTE_READWRITE flag so that it can hold executable code
Read and write the function's code from your process to the other process via Read/WriteProcessMemory
Call the function in the remote process (which is at the address returned by the VirtualAllocEx) by using CreateRemoteThread.
Make sure that all the data you pass to the function is either stored inside the struct and/or resides in the remote process's address space (get it there with VirtualAllocEx/WriteProcessMemory.
It may look a little involved, but it's not really that complicated. If you need some help with it, feel free to ask in a comment.
You can't directly call functions in another process, in general. There are, however, some workarounds you can use.
First, if you know the address of the export (which isn't the case a lot of the time), and the function you call uses the __stdcall calling convention, takes a pointer-sized integer as an argument, and returns a DWORD, you can use CreateRemoteThread to execute it in a thread in the remote process. This is often used to run LoadLibrary to inject a DLL into a target process, since LoadLibrary is loaded in the same address on all processes on a given computer.
Otherwise, the DLL you inject will need to do some sort of RPC with the process that called it. For example, you could have your injected DLL spawn a thread in its DLL_PROCESS_ATTACH handler, which in turn connects to a named pipe, or connects over COM or something to the master process.
SendMessage would need a window handle (hidden or visible), and a message-pump associated with it, that can handle the custom message. As with UAC/Windows-7, the integrity levels of applications may prevent other applications to send/post messages from other processes having low integrity.
It is better to have another thread that waits for these custom messages. For this, you may use pipes (named or unnamed), sockets, mail-slots, shared memory (along with mutex/event for triggering). The another processes would send the message using same protocol.
But before implementing this custom messaging/protocol/IPC mechanism, I suggest you to first determine the exact need.