Writing a Self modifying code at runtime in C/C++

122 Views Asked by At

i have some questions,

is possible to make a programm in windows that modify itself?

i write this program that use the _asm{} function:


#include <iostream>

using namespace std;

void print() //FUNCTION TO MODIFY
{
    cout << "Hello, World!\n";
}

void Crypt(int adr)
{
    _asm {

        mov eax, adr

        xor_loop:
        xor byte ptr [eax], 0x24 
            inc eax
            cmp eax, 0xC3 //compare ret opcode
            jne xor_loop
    }

}

int main()
{
    print();

    void *ptr = print;  //address example : 003812E4

    cout << "Address : " << ptr << "\n";

    int mem;

    _asm {
        lea eax, print
        mov mem, eax
        call eax
    }

    cout << "EAX : " << mem << "\n";

    Crypt(mem);
    
    return 0;
}

but dosent work properly i dont why, any help?

pseudocode:

print function:
   mov eax, 0x80
   add eax, 0x02
   call eax
   ret

modify:
   lea eax, print
   xor byte ptr [eax], 0x24 //xor for modify opcode
   inc eax       //increase eax 1 byte
   cmp eax, 0xC3 //compare ret opcode
   jne modify

---------------------------------------------
modify print function example:
   mul eax
   mov eax, edx
   jnz ebx
   ret
1

There are 1 best solutions below

2
wangyunlai On

Perhaps you should save your code in the .data section that you can't change the code in the .code section as it is protected(readonly).

There is an idea:

  1. allocate a block of memory in the heap section to save function you want to change
  2. copy the function code bytes into that memory
  3. change the code and call the new function with the address you allocated.