identify memory code injection by memory dumping of process or dll - c++

In order to identify memory code injection (on windows systems), I want to a hash the memory of all processes on the system, for example, if the memory of calc.exe is always x and now it is y, I know that someone injected into calc.exe code.
1: Is this thinking correct? What part of the process memory always stays the same and what part is changing?
2: Dose dll have a separate memory, or it is in the memory of the exe? In other words, can i generate a hash for memory of a dll?
3: How can I dump the memory of a process or of a dll in c++?

Code is continually being injected in processes when running windows.
One example are delay loaded DLLs. When a process starts up, only the core DLLS are loaded. When certain features get exercised, the code first loads the new DLLs (code) from disk and then executes it.
Another example is .NET managed applications. Most code sits as uncompiled code on disk. When new parts of the application need to be run, the .NET runtime loads that uncompiled code, compiles it (aka JITs it) and then executes it.
The problem you are trying to solve is worthwhile, but extremely hard. The OS itself tries to solve this problem to protect your processes.
If you are trying to do something more advanced than what windows is doing for you behind the scenes, the first thing to do will be to understand all the steps windows takes to protect process and validate the code being injected in them, while still enabling processes to load code dynamically (which is a necessity).
Good luck.
Or maybe you have a more specific problem you are trying to solve?

1) The idea is nice. But as long as the process runs, they change their memory (or they do nothing) so it won't work. What you could do, is to hash the code part of the memory.
2) No, DLL are libraries linked to your code, not a separate process. They are just loaded dynamically instead of statically (http://msdn.microsoft.com/en-us/library/windows/desktop/ms681914%28v=vs.85%29.aspx)
3) Normally your OS prohibits you from accessing memory of neighbour processes. If it would allow it for your process, then it would be very easy for malware to propagate, and your system would be very instable, as one crashing process could crash all the others. So it'll be very very tricky to do such kind of dumps ! But if your process has the right priviledges, you could have a look at ReadProcessMemory()

I have just done something similar I basically c#'s these scripts:
http://www.exploit-monday.com/2012/03/powershell-live-memory-analysis-tools.html

Related

calling exe performance cost (compared to DLL)

We were discussing the possibility of using an exe instead of DLL inside a C or C++ code. The idea would be that in some cases to use an exe and pass arguments to it. (I guess its equivalent to somehow loading its main function as if it was a DLL).
The question we were wondering is does it imply a performance cost (especially in a loop with more than one iteration).
I tried to look in existing threads, while nobody answered this specific question. I saw that calling a function from DLL had an overhead for the first call, but then subsequent calls would only take 1 or 2 instructions.
For the exe case, it will each time need to create a separate process so it can run.(a second process if I need to open a shell that would open it, but from my research I can do it wihtout calling a shell). This process creation should cost some performance I'd guess. Moreover I think that the exe will each time be loaded into RAM, destroyed at the end of the process, then reloaded for next call and so on. A problem that is not present (?) with DLL.
PS: we were discussing this question more on a theoretical level than for implementing it, it's a question for the sake of learning.
The costs of running an exe are tremendous compared to calling a function from a DLL. If you can do it with a DLL, the you should if performance matters.
Of course, there may be other factors to consider: For example, when there is a bug in the code called, and crashes the process, in the case of an exe it is merely that exe that goes down, and the caller survives, but if the bug is in a DLL, the caller crashes, too.
Clearly, a DLL is going to get loaded, and if you call to it many times in a short time, it will have a benefit. If the time between calls is long enough, the DLL content may get evicted from RAM and have to be loaded from disk again (yes, that's hard to specify, and partly depends on the memory usage on the system).
However, executable files do get cached in memory, so the cost of "loading the executable" isn't that big. Yes, you have to create a new process and destroy it at the end, with all the related memory management code. For a small executable, this will be relatively light work, for a large, complex executable, it may be quite a long time.
Bear in mind that executing the same program many times isn't unusual - compiling a large project or running some sort of script on a large number of files, just to give a couple of simple examples. So the performance of this will be tuned by OS developers.
Obviously, the "retain stuff in RAM" applies to both DLL and EXE - it's basic file-caching done by the OS.

Getting access to any process's memory

I'm using Windows 8 64 bit. I know C++ and basics of assembly. If I were to write an anti-virus program, it should be able to access any process's memory, right? I have managed to write a program that is able to read most process's memory, using VirtualQueryEx and ReadProcessMemory. However, I've come across an application that doesn't let me use VirtualQueryEx. Even with debug privileges it fails with Access Denied error.
Is there anything I can do to enable myself the access to the process's memory using VirtualQueryEx? Or should I take other approach to access such hard accessible processes?
I've already done some research and wonder which approach should I follow:
I've come across an information that it's possible to read any memory in kernel mode without any restrictions. Is that true? But in kernel mode there is no functions such us VirtualQueryEx or ReadProcessMemory. I guess I need to implement them by myself? But I've seen opinions that such functions are very unstable and in the future I might get a BSOD or sth... Some say I shouldn't even use kernel mode for reading memory purposes. Could somebody give me an answer how it actually is with this kernel mode?
I heard that applications might hook some APIs so that it prevents other apps from using these functions. Might VirtualQueryEx be hooked in that process? and that's the reason I get access denied all the time? If that's the case how could I unhook this?
Anti-viruses are not likely to do this probably, but would simple DLL injection work? I mean, if I were able to inject dll to that process then inside my dll I would already be withing that process's virtual address space so reading its memory shouldn't be a problem then?
Another approach?
I would be really grateful for any tips and help in this matter!
Yes it's possible, but it will be very tedious and error prone. It will not be as easy as VirtualQueryEx/RPM. I would actually just ensure my user-mode application has enough rights to do the API calls and not read the memory in the kernel. Also you can't easily load a self made driver on a 64-bit Windows. You either need to sign your driver (costs money) or find some security hole in Windows (or start your machine in an unsafe mode).
Yes, that's possible. One way to hook APIs globally would be to write a driver that redirects the API calls. Another way would be global or targeted dll injection to hook the API calls. The latter you can check with a debugger. If the kernel redirects the calls, you can only detect that by being in the kernel yourself.
I doubt that this would work, because you'd need way more process rights to inject a dll than to query/read some memory. If you want to read a specific known application you could try to get the target to load your dll by writing a wrapper for some dll it loads and replace the original.
Are you sure you need to read memory from this process? Is it any of the System Process, Idle Process, CSRSS that cannot be opened from user mode? Have you lowered your requested rights as much as possible? It think you only need PROCESS_QUERY_INFORMATION and PROCESS_VM_READ.

Accessing Memory of other applications C++

I am thinking about a problem I have been having for some time now.. I would like to write a C/C++ program (under windows first) that can access(read/change values) the memory(stack, heap, everything) of other running programs. (Not like shared memory but any memory the computer has..) Without having to start the application from my own application..
I have seen something like this before but I just can't figure out how it's done.. If I were to access the memory of any running program I would get errors from the OS right?
Any help is appreciated!
As #sharptooth said, this requires support from the OS. Different OS does it differently. Since you are on Windows, there are a few steps you could follow:
Call OpenProcess, or CreateProcess to access, or launch a new process. In this call, you must request PROCESS_VM_READ access.
Call ReadProcessMemory to read a chunk of memory in that opened process.
If you want to change memory of another process, you then need PROCESS_VM_WRITE access and use WriteProcessMemory to achieve that.
In Linux, for example, you'd use ptrace to attach to a process and peek, poke its memory.
You can start a process (another program) from your own application, and access some of its information (especially shared memory). The contrary is very difficult, the CPU fakes the memory addresses so each process believes that it has the whole memory available...
You might be interested in taking a look at the Toolhelp32ReadProcessMemory function.

How to create binary/hex dump of another process's memory?

I am having trouble finding a reasonable way to dump another process's memory to a file.
After extensive searching, I've been able to find a nice article at CodeProject that has *most* of the functionality I want:
Performing a hex dump of another process's memory. This does a good job of addressing permission issues and sets a good foundation.
However, with this utility I've seen that even a small process, such as an clean Notepad.exe or Calc.exe instance, can generate a dump file over 24MB in size, while the process itself runs under 20KB in memory according to TaskManager.
The article has lead me to believe that perhaps it is also dumping things in shared memory, possibly DLL space and the like. For example, a dump of Calc.exe will include sections that include method names (and presumably memory) from Kernel32.dll:
²³´µKERNEL32.dll ActivateActCtx AddAtomA AddAtomW AddConsoleAliasA AddConsoleAliasW AddLocalAlternateComputerNameA AddLocalAlternateComputerNameW AddRefActCtx AddVectoredExceptionHandler AllocConsole AllocateUserPhysicalPages AreFileApisANSI AssignProcessToJobObject AttachConsole BackupRead BackupSeek BackupWrite BaseCheckAppcompatCache BaseCleanupAppcompatCache
Is there a better way to dump the memory of another process that doesn't lead to this overhead, or perhaps an improvement upon the linked article's code that solves this problem? I want to get the memory that actually belongs to the process itself. I'd be okay with dumping the memory space of functions that are actually used in DLLs, but it seems unnecessary to dump the *entire* contents of multiple DLLs to get the running memory of the process.
I'm looking for a way to get the 30-60KB of a 30KB process, rather than 25MB for a 30KB process. Or at least closer than I can get currently.
Thanks in advance for your suggestions and guidance, it is appreciated.
Note: This is for a console utility, so GUI elements like the ones in the CodeProject article are unimportant.
You're basically asking for a user process minidump. The Windows Debug Helper library has a ready made function for this, MiniDumpWriteDump.
There is a coarse control over the amount of the detail contained in the mini dump from the MINIDUMP_TYPE parameter passed in to the function. The most basic, MiniDumpNormal, will only capture the call stack of each thread in the process. The amount of memory gets progressively more detailed with the other mini dump types.
You can also fine control the amount of information to be written into the mini dump by providing a callback to the MiniDumpWriteDump function and in the callback set the flags on the MINIDUMP_CALLBACK_OUTPUT structure.
The resulted mini dumps can be read with a debugger like Windbg or Visual Studio, or they can be processed by the various functions in the dbghelp.dll library.
Not really a "how to program it" answer, but I just found your question while looking for a tool that could do that, when I ran into PMDump:
http://ntsecurity.nu/toolbox/pmdump/
It's dead easy and simple to use, and creates correct dumps (I just tried it with some programs).

CreateProcess from memory buffer

I can use CreateProcess to launch an EXE. I want to have the contents of an EXE in a memory buffer and do CreateProcess (or an equivalent) on it without having to write it to a file. Is there any way to do that?
The backstory : we make games. We send a plain EXE to our distributors, which then wrap it using their favorite DRM and sell it to their users. There have been instances where users find crashes. Most of the crashes take 5 minutes to fix, but the patch must go through the distributor and it may take several days, even weeks. I can't just send the patched EXE to the players because it wouldn't have the distributor's DRM. I'm thinking of distributing the real game EXE inside an encrypted datafile so what gets wrapped (the external EXE) just decrypts and launches the real EXE. This way I could safely distribute a fix without disabling the DRM.
It's actually quite easy. Similar technique has been described in a paper I read like 3 years ago.
Windows allow you to call the CreateProcess function with CREATE_SUSPENDED flag, that tells the API to keep the process suspended until the ResumeThread function is called.
This gives us time to grab the suspended thread's context using GetThreadContext function, then the EBX register will hold a pointer to the PBE(Process Enviroment Block) structure, which we need to determine the base address.
From the layout of the PBE structure we can see that the ImageBaseAddress is stored at the 8th byte, therefore [EBX+8] will give us actual base address of the process being suspended.
Now we need the in-memory EXE and do appropiate alignment if the alignment of memory and in-memory EXE differs.
If the base address of suspended process and in-memory exe matches, plus if the imageSize of the in-memory exe is lesser or equal to the suspended process' we can simply use WriteProcessMemory to write in-memory exe into the memory space of the suspended process.
But if the aforementioned conditions weren't met, we need a little more magic.
First, we need to unmap the original image using ZwUnmapViewOfSection, and then allocate enough memory using VirtualAllocEx within the memory space of the suspended process. Now we need to write the in-memory exe into the memory space of the suspended process using the WriteProcessMemory function.
Next, patch the BaseAddress of the in-memory exe into the PEB->ImageBaseAddress of the suspended process.
EAX register of the thread context holds EntryPoint address, which we need to rewrite with the EntryPoint address of the in-memory exe. Now we need to save the altered thread context using the SetThreadContext function.
Voila! We're ready to call the ResumeThread function on the suspended process to execute it!
You can compile the game as a DLL and put the DLL in the encrypted data file. A DLL can be loaded from memory without writing it to disk. Please see this tutorial (with sample code at the end): Loading a DLL From Memory
What you want to do requires NtCreateProcess, but it's undocumented and therefore brittle. This book apparently covers its use.
Perhaps you could build a patch system? E.g. on launch, program checks for patch DLL in same directory, and loads it if it exists.
Why do you need to create a new process? I would have thought you could run in the context of process which does the unpacking/decryption.
What you want can be achieved with something called a "Packer". Actually launching an exe from memory might be possible, but it's a lot harder than a packer ;)
One of the best known packers is UPX (google it). There are tools to decrypt it, but it should at least give you a starting point to work froim. I'm also fairly certain UPX is open-source.
Look at BoxedAppSDK
It supports launching exe from a memory buffer.
hope it helps.