Memory Scan in c++ - c++

I am working on a WIN32 project in Visual Studio 2010. I am trying to Scan my main memory through the ClamAV(open source antivirus) Engine for searching a malicious/infected file in main memory.
The code i have written so far creates a snapshot of the whole main memory by using the windows function CreateToolhelp32Snapshot
Then i open a specific process from the snapshot, and pass this to the ClamAV engine, the engine then decides whether it is malicious or not. and i repeat the whole mechanism after every 10seconds. But i think this is not an efficient way,
What i want to do is to scan my whole memory once, and after this i scan only those process which is newly created in the main memory. Kindly guide me is there any way to get newly created methods from the memory only and not the whole memory

I think it cannot be done purely in user space program.
I am not very familiar with Windows API but I can give you some rough hint on how to do it.
You should scan every program BEFORE it is executed.
Make all the memory a program allocated later non-executable (NX bit)
The program will trigger a page-fault when it try to execute it, scan it now !!
Make the scanned memory read-only, and then go on to execute it
Make it non-executable again once a program tries to write this area.
NOTE: If you want to ensure security, a memory area can NEVER become executable and writable at the same time.
In this way you need only check those memory being executed. And it should be very efficient.

Related

Do pictures ever get stored in RAM?

I am a beginner C++ programmer.
I wrote a simple program that creates a char array (the size is user's choice) and reads what previous information was in it. Often you can find something that makes sense but most of it is just strange characters. I made it output into a binary file.
Why do I often find multiple copies of the alphabet?
Is it possible to find a picture inside of the RAM chunk I retrieved?
I heard about file signatures (headers), which goes before any of the data in a file, but do "trailers" go in the back after all the data?
When you read uninitialized data from memory that you allocated, you'll never see any data from another process. You only ever see data that your own process has written. That is: your code plus all the libraries that you called.
This is a security feature of your kernel: It never leaks information from a process unless it's specifically asked to transfer that information.
If you didn't load a picture in memory, you'll never see one using this method.
Assumning your computer runs Linux, Windows, MacOS or something like that, there will NEVER be any pictures in the memory your process uses - unless you loaded them into your process. For security reasons, the memory used by other processes is cleared before it gets given to YOUR process. This is the case for all modern OS's, and has been the case for multi-user OS's (Unix, VAX-VMS, etc) more or less since they were first invented in the late 1950's or early 1960's - because someone figured out that it's kind of unfun when "your" data is found by someone else who is just out there fishing for it.
Even a process that has ended will have it's memory cleared - how would you like it if your password was still stored in memory for someone to find when the program that reads the password ended? [Programs that hold highly sensitive data, such as encryption keys or passwords, often manually (as in using code, but not waiting until the OS clears it when the process ends) clear the memory used to store such, because of the below debug functionally allowing the memory content to be inspected at any time, and the shorter time, the less likely a leak of sensitive information]
Once memory has been allocated to your process, and freed again, it will contain whatever happens to be in that memory, as clearing it takes extra time, and most of the time, you'd want to fill it with something else anyway. So it contains whatever it happens to contain, and if you poke around it, you will potentially "find stuff". But it's all your own processes work.
Most OS's have a way to read what another process is doing as part of the debug functionality (if you run the "debugger" in your system, it will of course run as a separate process, but needs to be able to access your program when you debug it, so there needs to be ways to read the memory of that process), but that requires a little more effort than just calling new or malloc (and you either will need to have extra permissions (superuser, adminstrator, etc), or be the owner of the other process too).
Of course, if your computer is running DOS or CP/M, it has no such security features, and you get whatever happens to be in the memory (and you could also just make up a pointer to an arbitrary address and read it, as long as you stay within the memory range of the system).

Identify non released memory during runtime

How does one best identify memory not released properly during run time? I know of several programs that identifies allocated and non freed (leaked) memory when the application closes. But my issue seems to be that during the program execution (possibly a thread) creates some objects that are not freed, although they should be after the system is done with the "work".
Keeping the system running this builds up over time. But when the program shuts down the memory seems to be freed correctly and thus never reported as a leak in MadExcept that I use at the moment.
How do I best go about to detect what is allocating this memory every time the "work" is run and not freeing it until program termination? This is in quite a large server system with around 1 million lines of code, several DLL sub projects and multiple threads running (40-50).
Perhaps there is some system that could identify allocated objects that have been alive for longer than X min. Let's say 60 min is selected and the system left running. Then this information could be used to locate many of these long living objects and investigate those?
if you are using c++ and visual studio, I think this link is helpful. You can _CrtMemCheckpoint and CrtMemDumpStatistics when you need.
I ended up trying the evaluation version of Softwareverify's C++ Memory Validator.
It worked just like what I wanted and was able to provide a time line of memory allocations etc to allow me to identify what had been accumulating over time and how long it had been alive. Using that I was able to identify the problem and fix it.

identify memory code injection by memory dumping of process or dll

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

How can I scan another process memory to find what follows a specific string?

I want to scan the entire heap of a currently running native application through another process.
For example, I want to know what follows all the instances of the ASCII sequence "test" in this process memory (in this case I would scan for "test" and keep reading after it).
I tried to google for more information but didn't find much: I found ReadProcessMemory which looked interesting, but how can I know the memory addresses a process has allocated?
Try VirtualQueryEx.
If you're finding that you're accessing a lot of memory in the other process, consider using CreateRemoveThread (sample code). This will allow you to inject your own DLL into the other process and run code there directly. Once you're running code in the other process, you'll be able to access memory as normal, without needing to use ReadProcessMemory. (You'll still need VirtualQuery to determine the process's memory layout.)

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.