It's possible read memory address without readprocessmemory - c++

It's possible read memory address without readprocessmemory same as dll injection:
Ex:
In dll injection:
int main()
{
char SomeAnyValue = *(char*)0x00001; // address of sample
}
In an extern process I need the Handle process, Fine until now...
but is it possible read the value like in dll injection without using of readprocessmemory?
Edit:
The original question was about if it was possible to read memory from any process remotely without an handle or dynamic link library injected on it. Has been some years since I made the question. To clarify I solved the problem using an driver and yeah, it is possible.

DLL injection works by injecting code into the target process! Once the code has been injected, it runs in the address space of the target process, and as such has direct access to the target process's memory addresses.
If you do not inject your code into the target process, it does not have direct access to the target process's address space, and as such it must use ReadProcessMemory() instead.

Related

Passing Arguments to Dll entry Point

I want to pass a structure to my dll's main thats in my injector so basically I want to do this:
struct structure{
char text[1024];
};
int DllMain(structure arg1,uintptr_t arg2,uintptr_t arg3);
Yet I want to know how I can make my injector pass the struct. Im manual mapping the dll by the way.
You can't pass custom parameters to DllMain(). The signature is fixed, and besides that, you don't call DllMain() directly anyway, only the OS does.
Your options are to either:
have the DLL export a separate function that you call after injecting the DLL into a process.
store the data in a block of shared memory that the DLL can access after being injected.
setup an interprocess communication channel between the DLL and injector, such as with a named pipe or a socket.
Add a resource to your DLL that is the size of your structure or a larger fixed size, the contents do not matter, you will overwrite it later, it's basically a stub.
Load the DLL into local memory in your injector before you manually map it
Overwrite this resource with your data.
Manual Map your DLL into the target process
Access the resource to get the data you needed

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.

Injecting thread with codecave

By using 'codecave' technique to inject code into another process; is it possible to inject code to create a new thread (and also inject the code for the new thread) and let that thread execute parallel with the target process main thread?
I can manage this with dll injection but I want to know if it is possible with just pure code injection.
The intention is first of all to learn about different injection techniques but in the end create a heartbeat feature for random processes in order to supervise execution (High Availability). Windows is the target OS and language is C/C++ (with inline ASM when required).
Thanks.
There is CreateRemoteThread function.
When using a DLL injection loader such as "Winject (the one that calls CreateRemoteThread) it is very easy to create Threads that remain until the target process closes.
Just create the Thread within the function:
void run_thread(void* ass)
{
// do stuff until process terminates
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD result, LPVOID lpReserved)
{
HANDLE handle = (HANDLE)_beginthread(run_thread, 0, 0);
}
regards,
michael
Sure, but you would have to also inject the code for the remote thread into the process (e.g. a function). Injecting an entire function into a remote process is a pain because there is no clear-cut way to determine the size of a function. This approach would be far more effective if the injected code was small, in which case you would just inject a short assembly stub, then call CreateRemoteThread.
Really though, what would be a benefit of doing this over just straight-up DLL injection? Your 'heartbeat' feature could be implemented just as easily with an injected DLL. (unless someone is going to tell me there's significant overhead?)
The problem is, even if you inject your code into the process, unless you create a thread at the start of your injected code, it will still not run. Typically, to do code injection you would inject a full DLL. One of popular ways of injecting DLLs is to:
Get a handle to the target process (EnumProcesses, CreateTool32Snapshot/Process32First/Process32Next, FindWindow/GetWindowThreadProcessId/OpenProcess, etc.)
Allocate memory in the target process that is the same length as a string pointing to the path of your DLL (VirtualAllocEx)
Write a string pointing to the path of your DLL to this allocated memory (WriteProcessMemory)
Create a remote thread at the LoadLibrary routine (get the address by GetModuleHandle/GetProcAddress) and pass the pointer to the allocated memory as a parameter (CreateRemoteThread)
Release the allocated memory (VirtualFreeEx)
Close any opened handles (process handles, snapshot handles, etc. with CloseHandle)
Unless there is a particular reason you want to avoid this method, it is by far preferable to copying in the code yourself (WriteProcessMemory and probably setting up page protections (VirtualProtectEx)). Without loading a library you will need to manually map variables, relocate function pointers and all the other work LoadLibrary does.
You asked earlier about the semantics of CreateRemoteThread. It will create a thread in another process which will keep going until it terminates itself or something else does (someone calls TerminateThread or the process terminates and calls ExitProcess, etc.). The thread will run as parallel in the same way a thread that was legitimately created would (context switching).
You can also use the RtlCreateUserThread function to create the remote thread.

How applications can be protected from errors in DLL module

I have DLL and application that will call some function in this dll. For example...
DLL function:
char const* func1()
{
return reinterpret_cast<char const*>(0x11223344);
}
Application code:
func1 = reinterpret_cast<Func1Callback>(::GetProcAddress(hDll, "func1"));
blablabla
char const* ptr = func1();
cout << ptr;
That DLL is not under my control (plugin)..
Same code will cause access violation in my application, so... Is there any mechanism that will allow to determine such errors?
Since the DLL can do anything your program could do the only reliable way is to load it into a separate worker lightweight process and once anything bad happens just restart the process. You'll need some protocol to pass data into the worker process and receive results.
The dll is loaded into your process address space. If it accesses some invalid memory location your process will crash. I don't see any way around it other than not using this dll at all.
If a DLL is returning junk memory addresses to your application, I'd say you shouldn't be using it, because it isn't performing its intended/desired function.
Also, don't try to guard against it by using the Win32 IsBad*Ptr class of functions, as the MSDN documentation states (see also this post by Raymond Chen for a good description of why not).
You can enclose function call into try catch block, it'll help not to crush entire application right at function call, but nobody can garantee, that dll loaded will not alter memory somwhere in your code, in this case yo'll get hard to debug crash in other place. So you can probably raise some protection for just access violation, but anyway cannot fully protext you application for some side effects.

CreateRemoteThread, LoadLibrary, and PostThreadMessage. What's the proper IPC method?

Alright, I'm injecting some code into another process using the CreateRemoteThread/LoadLibrary "trick".
I end up with a thread id, and a process with a DLL of my choice spinning up. At least in theory, the DLL does nothing at the moment so verifying this is a little tricky. For the time being I'm willing to accept it on faith alone. Besides, this question needs to be answered before I push to hard in this direction.
Basically, you can't block in DllMain. However, all I've got to communicate with the remote thread is its id. This practically begs for PostThreadMessage/GetMessage shenanigans which block. I could spin up another thread in DllMain, but I have no way of communicating its id back to the creating thread and no way of passing the another thread's id to the remote one.
In a nutshell, if I'm creating a remote thread in a process how should I be communicating with the original process?
Step zero; the injected DLL should have an entry point, lets call it Init() that takes a LPCWSTR as its single parameter and returns an int; i.e. the same signature as LoadLibrary() and therefore equally valid as a thread start function address...
Step one; inject using load library and a remote thread. Do nothing clever in the injected DLLs DLLMain(). Store the HMODULE that is returned as the exit code of the injecting thread, this is the HMODULE of the injected DLL and the return value of LoadLibrary().
Note that this is no longer a reliable approach on x64 if /DYNAMICBASE and ASLR (Address space layout randomisation) is enabled as the HMODULE on x64 is larger than the DWORD value returned from GetThreadExitCode() and the address space changes mean that it's no longer as likely that the HMODULE's value is small enough to fit into the DWORD. See the comments below and the linked question (here) for a work around using shared memory to communicate the HMODULE
Step two; load the injected DLL using LoadLibrary into the process that is doing the injecting. Then find the offset of your Init() entrypoint in your address space and subtract from it the HMODULE of your injected DLL in your address space. You now have the relative offset of the Init() function. Take the HMODULE of the injected DLL in the target process (i.e. the value you saved in step one) and add the relative address of Init() to it. You now have the address of Init() in your target process.
Step three; call Init() in the target process using the same 'remote thread' approach that you used to call LoadLibrary(). You can pass a string to the Init() call, this can be anything you fancy.
What I tend to do is pass a unique string key that I use as part of a named pipe name. The Injected DLL and the injecting process now both know the name of a named pipe and you can communicate between them. The Init() function isn't DLLMain() and doesn't suffer from the restrictions that affect DLLMain() (as it's not called from within LoadLibrary, etc) and so you can do normal stuff in it. Once the injected DLL and the injecting process are connected via a named pipe you can pass commands and data results back and forth as you like. Since you pass the Init() function a string you can make sure that the named pipe is unique for this particular instance of your injecting process and this particular injected DLL which means you can run multiple instances of the injecting process at the same time and each process can inject into multiple target processes and all of these communication channels are unique and controllable.
You don't have the thread id of a thread in the remote process, because the one you used to load the dll exited when your module was successfully loaded into the address space of your process.
You can easily use the normal interprocess communication methods like named sections/pipes/creating a named window/etc. to communicate with your 'injecting' process.