3

I am looking for a few lines long example demonstrating a self-modifying code in x86 assembler for educational purpose (does not need to do something meaningful but needs to clearly write his own code and then execute it when you read the code itself).

I did browse a bit the Web, but all the examples are either way too complex or just not really self-explanatory. I might have missed the right place to go, so feel free to suggest links or code.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
perror
  • 7,071
  • 16
  • 58
  • 85
  • The EICAR antivirus test file uses SMC to decode its code. That way, the file uses only ASCII printable characters. – ninjalj Aug 29 '12 at 16:34
  • the biggest issue is the operating system and protections used by the operating system. what operating system are you running this on? – old_timer Aug 29 '12 at 17:08
  • dwelch: I am running Linux, but I don't want to fuzz the example with rights management (when you need to set up the 'write' flag from the source, it might be quite misleading). We can handle this from the outside through compiler options. So, I supposed that the rights are handled ok. – perror Aug 29 '12 at 17:13

1 Answers1

6

Many processors cannot see modifications to code immediately after it gets changed, and execute the old bytes instead. For example the following code will still (most of the time) increment eax, even after the 'inc' instruction is overwritten with the 'nop'-s. You should almost always see eax=1, and get eax=0 if an exception happened after the 'mov'.

; Intel syntax

.arch   i386
.text
start:
        xor     %eax, %eax
        mov     word ptr change, 0x9090
change: inc     %eax
        nop
        ret

If EFLAGS.TF=1 eax will always be 0. Whether this is useful is another story. Long time ago a friend used self-modifying code for obfuscation purposes, and had several traps as above that relied on the processor to actually ignore the change.

NonNumeric
  • 1,079
  • 7
  • 19