Contribute  :  Web Resources  :  Past Polls  :  Site Statistics  :  Downloads  :  Forum  
    BiW ReversingThe challenge is yours    
 Welcome to BiW Reversing
 Wednesday, June 28 2017 @ 07:16 AM CEST

Basic self modifying code

   

TutorialsEarlier 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 :

.data?
Old dw ?
AddrToChange LPVOID ?

.code
;-------SNIP---------
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
;-------SNIP---------

infinite:
ADD EBX, EAX
INC EAX
codeToChange:
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)




What's Related

Story Options

Basic self modifying code | 0 comments | Create New Account
The following comments are owned by whomever posted them. This site is not responsible for what they say.
 Copyright © 2017 BiW Reversing
 All trademarks and copyrights on this page are owned by their respective owners.
Powered By Geeklog 
Created this page in 0.05 seconds