0

I have a C++ program with 2 labels. The code between these labels is encrypted in binary file (using 3rd party utils) and then decrypted in runtime. The code for decryption looks like following:

    int a = 0xBAD, b = 0xC0DE;
    std::cin >> a >> b;
    int c = static_cast<int>(pow(a, pow(b, b))) % static_cast<int>(pow(a, b));
    switch (c)
    {
    case 0:
        std::cout << "c = " << 0 << std::endl;
        break;
    case 1:
        std::cout << "c = " << 1 << std::endl;
        break;
    case 2:
        std::cout << "c = " << 2 << std::endl;
        break;
    case 3:
        std::cout << "c = " << 3 << std::endl;
        break;
    default:
        std::cout << "c = " << c << std::endl;
    }
_end:

Decryption process is following: I call VirtualAlloc to allocate a new memory buffer with PAGE_EXECUTE_READWRITE permissions. Then I copy the encrypted part to this buffer and decrypt it. And after that I just do a call of this buffer.

__asm
{
    lea eax, begin
    lea edx, _begin
    mov dword ptr[eax], edx
    lea eax, end
    lea edx, _end
    mov dword ptr[eax], edx
}
LPVOID ptr = VirtualAlloc(NULL, end - begin, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
memcpy(ptr, begin, end - begin);    
//decryption here
((void(*)(void))ptr)();

The problem is in that std::cin and std::cout calls have near call with relative offset which makes this offset absolutely incorrect in newly allocated memory block which I try to execute.

The question is how to calculate correct offset for decrypted code and use it there?

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
rudolfninja
  • 467
  • 7
  • 24
  • You'll need to locate each call to library routines and fix it up with the new call offset. The formula will be something like `new offset = old offset - (new code base - old code base)`. – 500 - Internal Server Error Apr 05 '21 at 17:23
  • But how to locate each library routine call during runtime? – rudolfninja Apr 05 '21 at 17:48
  • If you use 3rd party tools to do the encryption, what do they state is the proper way to decrypt code? – 1201ProgramAlarm Apr 05 '21 at 19:44
  • 3rd party tool is simple xor encryptor which encrypts specific bytes range with the a key specefied – rudolfninja Apr 05 '21 at 19:57
  • I'm not sure if your requirements allow for this but I'd be inclined to pass [the current] **cin** and **cout** addresses as arguments to the decrypted function. The resulting code that calls these function pointers will use the proper absolute addressing you need. – byteptr Apr 07 '21 at 19:11

0 Answers0