Detecting memory access to a process - c#

I'm trying to check if an application tries to manipulate a particular process (for ex. hooks itself to it). I couldn't find a proper approach to accomplish this. Is computing checksum over running process possible? If it's not how can i detect this situation?

Other process can't make hooks in your process, can modify memory but to make hooks this code must be in your address space, this can be done to injecting DLL to your process when is starting (at runtime inject dll is a hard one), you can easy check this by listing DLL's in your process and searching some ReadProcessMemory, WriteProcessMemory, OpenProcess, CallNextHookEx functions calls in their code. To do that get address (GetProcAddress) of function and search value in code (you can add some asm call predictions for that for tight range result).
You can check what is wrong with your PE file in disk and in memory, when DLL injection at startup time was occurrence then your PE file after was copied to memory from file should be corrupted, after last dll library you should have overwritten debug symbols with additional dll import. This modification can be done on file same as in memory.
The best method but probably will not easy for you when you are using C# language is obfuscate your code. I think this is a good method because you don't hook something that you don't know how work, because you don't know what hook you must do and where. But for good obfuscate C# code you must find good software for that and probably pay not low price.

Related

Packing a .NET executable inside a C/C++ executable

I built a C# WPF (.NET Core 3.1) application using that has got some interest and I'm about to monetize it.
However, building any kind of license check in C# is pretty much useless, and any user would be able to use a decompiler such as ILSpy to crack it, thus rendering my work pretty much useless.
I took a long hard look on the .NET obfuscators, but ultimately concluded they did not fit my requirements because there are decompilers that can still retrieve the code from Dotfuscator, Babel, Obfuscar, etc. Simply obfuscating names and whatnot isn't really useful, as one could simple debug the code to the point where a license is required.
What I'm trying to do now is build a C/C++ launcher that will execute my .NET from memory.
My plan is to stream the bytes from a server, load them in memory, and run the program. I, however, don't know a whole lot about how I could achieve this.
I've tried VirtualAlloc to allocate all the bytes and changed set memory page to be executable, but it didn't work.
I've tried adjustments based on a few pieces of code that run PE from memory:
https://github.com/aaaddress1/RunPE-In-Memory
https://github.com/codecrack3/Run-PE---Run-Portable-Executable-From-Memory/blob/master/RunPE.cpp
https://www.codeproject.com/Articles/13897/Load-an-EXE-File-and-Run-It-from-Memory
The closes I got was a 0xc0000005 error when trying to run the executable from memory (an array of bytes that makeup my program).
How can this be done? I'd really like to avoid having to rewrite the whole thing in C/C++, specially because of the complex UI.

Watch resources that are used by exe\dll

How can I watch a specific process to know what resources it uses at runtime (such as sounds, pictures, cursors, and registry keys)?
I have to do that programmatically using C# (e.g. using the Windows API or any third party library).
Any help is appreciated. Thanks.
I would stick to performance counters. There are ones for
Memory
GDI Handles (Bitmap, Font, ...)
Handles (File, Registry Key, Event, Mutex, Socket, Process, ...)
Windows (User Objects)
The exact type cannot be determined by using performance counters but it can give you a hint if you are leaking something. If you want to know which handles you can use handles from SysInternals which will give you a nice per process output which you can parse.
If you want to fix the handle leaks then you need to use a debugger (Windbbg) and use the !handle extension to start tracking all aquire/release call stacks for each handle so you can get latter a statistics which handles have been allocated but not freed yet.
Your question is a little to broad because the exact tactic to nail a resource leakage is dependant on the nature of the leak. EasyHook is a good solution to track all resource aquire/release calls and record them automatically.
If you want to automate a debugger with e.g. C# you can use http://wmemoryprofiler.codeplex.com/ which is bascially a managed wrapper around Windbg which even allows you to self debug your application.
When you just want to learn the principles how to get your hands on scattered data for various resources you should read the code of Process Hacker.
Do you want the GDI objects or Win32 handles?
Win32 handles can be obtained using the NtQuerySystemInformation WinAPI function. You can find the C# code for handle-related tasks in these ProcessHacker sources: http://sourceforge.net/p/processhacker/code/HEAD/tree/1.x/trunk/ProcessHacker.Native/Windows.cs
EasyHook will allow you to intercept Windows API calls. Here's a simple example for all file accesses made by a process. Registry calls also seem to be supported.

C# or C++ sandboxed assembly

I'm thinking of writing a program that involves including super fast Assembly or as it dosn't have to be human readable it could be Machine Code in C++ or C#. However I also have other possibly more troublesome requirements.
I would need to be able to:
Store machine code programs in normal variables / object instances, for example strings "40 9B 7F 5F ..." to edit and run them.
Have the programs able to output data. I saw an example where one had a pointer to an int that it could use.
Have the programs not able to output data anywhere else. For example to not be able to perform such actions as to delete files, view the system spec or change the state of the memory of the C++ or C# program they are contained within.
For example, it could be something like this:
machine n;
n = "40 9B 7F";
n[1] = "5F";
// 'n' is now "40 5F 7F"
unsigned short s = 2;
n.run(&s);
// while 'n' was running it may have changed 's' but would not have been able to
// change anything else anywhere on the system including in this C++ / C# program
According to the wiki link Michael Dorgan posted "asm(std::string);" runs the String as assembler and it's also easy to referance variables from the C++ part of the program. Editing a std::String is easy and Alex has noted that I can ensure that the code is safe by not allowing unsafe commands.
Sandboxing native machine code is non-trivial. If you really want that take a look at NACL from google which implements a machine code sandbox for browsers.
What is more practical is to use .NET IL instead of machine code and use a sandboxed (or hosted) AppDomain. This comes much closer and still is fast due to the dynamically jit-compilation to machine code.
An alternative you have is to use Windows builtin rights management and spawn a new process with restricted rights. Never done that so I don't know if you can reduce the target processes rights as much as you want. Anyways that would be a pure win32 process just running machine code, so you lose any ability of using .NET in the sandboxed process.
If you want to include assembler in your C/C++ code, consider either inline assembly routines, or compiling seperate full on assembler files and linking them back in. Inline assembler syntax is kinda weird, but I believe it is probably the best choice for you from what I've read.
Wikipedia to the rescue for some samples:
Inline assembler examples
Update based on comments:
This is far from a trivial task. You have to implement a linker, assembler (to scan and sandbox) and loader.
I wonder what the use case is -- for my example I'll assume you want to to have an assembly contest where people submit solutions to problems and you "test" them.
This is the best solution I can think of:
Have a hosting program that takes as input assembly language.
Invoke the assembler to compile and link the assembly program.
Create a protected virtual environment for the program to run in (how you do this depends on the platform) which runs as a user that has no rights to the system.
Capture the results
This solution allows you to leverage existing assemblers, loaders and security without having to re-implement them.
The best example code of dynamically loading, running and sandboxing C# code I know of is the terrarium game at http://terrarium2.codeplex.com/
However, you might consider something better suited to this job, like a scripting system. Lua comes to mind as a popular one. Using Lua users will only be able to perform the actions you allow. http://www.lua.org/
If you restrict the subset of supported instructions, you can do what you want more or less easily.
First, you have to parse and decode an input instruction to see if it's in the supported subset (most of parsing/decoding can be done just once). Then you need to execute it.
But before executing, there's one important thing to take care of. Based on the decoded details of the instruction and the CPU registers state, you have to calculate the memory addresses that the instruction is going to access as data (including on-stack locations) or transfer control to. If any of those are outside of the established limits, fire alarm. Otherwise, if it's a control transferring instruction (e.g. jmp, jz), you must additionally ensure that the address it passes control to is not only within the memory, where all these instructions lie, but also is the address of one of those instructions and not an address inside of any of them (e.g. 1 or 2 bytes from the beginning of a 3+ bytes long instruction). Passing control anywhere else is a no-no. You do not want these instructions to pass control to any standard library functions either because you won't be able to control execution there and they're not always safe when supplied with bogus/malicious inputs. Also, these instructions must not be able to modify themselves.
If all is clear, you can either emulate the instruction or more or less directly execute it (control passing instructions will likely have to be always emulated because you want to stop execution after every instruction). For the latter you can create a modifiable function containing these things:
Code to save CPU registers of the caller and load them with the state for the instruction being executed.
The instruction.
The reverse of step 1: code to save post-execution register state and restore the caller's register state.
You can try this approach.

Wrap and Protect executable

I'm working on a copy protection software and I'm trying to create a wrapper around any kind of executables (managed and unmanaged). This wrapper will then try to execute the wrapped executable without writing it to the disc like normal, and execute it with Process.Start().
I used .Net 4.0 Assembly and Appdomain to get it working, but as I've read and tested, it will only work with .Net executables. How would I go around and execute any kind of executable without writing it "naked" to the drive?
Can I execute it from within an encrypted compressed file for example?
or MemoryMappedFile?
Really you are wasting your time. You CANNOT stop someone from copying your executable, getting your code, or anything else. Even if you can perfectly protect the executable file on disk, the moment it starts running, someone can use a debugger to make a dump of the executable, even from a memory mapped file. This is how products like Xenocode, or .NET Reactor, or any other packer for that matter, are defeated.
The better option for you is to stop and think about what it is that you are really trying to achieve. Are you concerned about people violating a license agreement? Are you worried about your software appearing on The Pirate Bay? If you make useful software, both of these things are eventualities, not possibilities. Protect your software with copyright, and your algorithms with patents, if appropriate. Then you have legal recourse to go after violators.
Sorry to burst your bubble, but there is no technical solution that cannot be defeated. Dongles can be emulated, web services can be patched around, encryption keys can be sniffed, etc. Spend your time making your software great, not trying to protect what cannot be protected.

how to run some code in memory?

I have a compiler which compiles assembly language to machine language (in memory).
My project is in C# .net.
Is there any way to run the memory on a thread?
How can DEP prevent it?
byte[] a:
01010101 10111010 00111010 10101011 ...
The key is to put the executable code into a block of memory allocated with VirtualAlloc such that the buffer is marked as executable.
IntPtr pExecutableBuffer = VirtualAlloc(
IntPtr.Zero,
new IntPtr(byteCount),
AllocationType.MEM_COMMIT | AllocationType.MEM_RESERVE,
MemoryProtection.PAGE_EXECUTE_READWRITE);
(then use VirtualFree to clean up after yourself).
This tells Windows that the memory should be marked as executable code so that it won't trigger a DEP check.
I doubt there's a supported way. I don't know and haven't researched it, but here are some guesses:
The easiest way might be to launch it as a process: write it into a *.com file and then tell the O/S to run that executable.
Alternatively, pass the memory as a parameter to the CreateThread function (but you'll need to wrorry about the code having the right calling conventions, expecting the specified parameters, preserving registers, and being in memory which is executable).
Another possibility is to write the opcodes into memory which is know is already going to be executed (e.g. overwrite existing code in a recently-loaded DLL).
It's possible to execute bytes as code:
Inline x86 ASM in C#
It does require the use of unsafe code.
I thought that this was just a fun fact but useless in practice, but perhaps your application actually has a use for this :)
You can whitelist your application from the control panel
http://ask-leo.com/how_do_i_turn_off_data_execution_prevention_errors.html
I doubt you can whitelist it programattically, but certainly not without admin access - that would defeat the purpose of this security feature.

Categories