How do I run some code in memory?

I have a compiler that compiles assembly language to machine language (in memory). My project is in C # .net. Is there a way to run memory on a thread? How can DEP prevent this?

byte[] a:  
01010101 10111010 00111010 10101011 ...

      

+2


source to share


4 answers


I doubt it is supported there. I don't know and haven't researched it, but here are some guesses:

The easiest way is to start it as a process: write it to *. com file and then tell O / S to run that executable.



Alternatively, pass memory as a function parameter CreateThread

(but you will need to crossover code that has the correct calling conventions, waiting for the specified parameters, keeping registers and executing in memory).

Another possibility is to write opcodes to memory that is already known, which will already be executed (for example, overwrite existing code in a recently loaded DLL).

+2


source


The key is to put the executable code in a block of memory allocated in VirtualAlloc so 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 to mark the memory as executable so that it doesn't trigger DEP checks.

+7


source


One can execute bytes as code:

Inline x86 ASM in C #

This requires the use of code unsafe

.

I thought it was just a fun fact, but it's useless in practice, but maybe your application actually uses this :)

+3


source


You can redirect your app from the control panel http://ask-leo.com/how_do_i_turn_off_data_execution_prevention_errors.html

I doubt you can whitelist it, but certainly not without admin access - that might trump the purpose of this security feature.

+1


source







All Articles