Basic self modifying code

Thursday, January 15 2009 @ 10:06 PM CET

Contributed by: detten

Earlier today I was asked for a way how to write self modifying code. I remember I had once written a small crackme using this technique, and against all odds I was able to digg up the source code :)

So without further delay, a very small example of how you can write self modifying code :

The example is in MASM syntax, but can be used in any programming language.
If you try to change the code of a program this will lead to a memory exception. The reason is simple, code sections are read and execute only, they are not writable. Fortunatly you can easily change the protection on a region of committed pages in the virtual address space of the calling process using the VirtualProtect API.

So to write some self-modifying code you need to change the protection option to read/write, change the code, then restore the protection to execute option. This could be code like this :

Old dw ?
AddrToChange LPVOID ?

mov AddrToChange, offset codeToChange
invoke VirtualProtect, AddrToChange,2000,PAGE_READWRITE,offset Old
mov word ptr [AddrToChange], 9090h
Invoke VirtualProtect, AddrToChange,4,PAGE_EXECUTE,offset Old

JMP infinite

The above example runs in an infinite loop if the self modifying code isn't executed. The JMP infinite is changed to 'NOP NOP' (no operation) by the code within the 'SNIP' region.

If you want to see this in action have a look at crackme8 by me (here : Crackme 8)