C Shellcode 32位与64位

问题描述

我编写了一个程序,该程序将功能写入文件,然后加载该文件并执行该功能。当我为32位编译时,此代码可以正常工作,但是当我将编译器设置为64位时,程序崩溃。

    #include <stdio.h>
    #include <windows.h>
    #include <Filez.h>

    void shellc(FARPROC p,char* x)
    {
    (int (WINAPI *)(HWND,LPCSTR,UINT))p(NULL,x,MB_OK);
    }
    void stub()
    {
    
    }
    
    int main(int argc,char **argv)
    {
    int size = stub - shellc;
    CryptMemoryToFile(shellc,size,"somepassword","shellcodefile");
    int sz;
    char * x = DeCryptFiletoMemory("shellcodefile",&sz);
    void (*shellcode)(FARPROC,char*) = x;
    FARPROC p = GetProcAddress(LoadLibraryA("user32.dll"),"MessageBoxA");
    shellcode(p,"test");
    
    getchar();
    }

Filez.h中定义的2个(解密)加密功能

    char * DeCryptFiletoMemory(char * File,char * Pw,int * Size)
    {
    int PWL = strlen(Pw);
    char * Data = LoadFile(File,Size);
    if (Data == NULL) return 0;

    int y = 0;
    for (int x = 0; x <= *Size;x++)
    {
    Data[x] = Data[x] - Pw[y];
    y++;
    if (y > PWL) y = 0;
    }

    return Data;
    }

    int CryptMemoryToFile(char * Memory,int Size,char *                 File)
    {
    int PWL = strlen(Pw);
    char * Memory2 = malloc(Size);
    memcpy(Memory2,Memory,Size);
        
    if (Memory2 == NULL) return 0;
    
    int y = 0;
    for (int x = 0; x <= Size;x++)
    {
    Memory2[x] = Memory2[x] + Pw[y];
    y++;
    if (y > PWL) y = 0;
    }
    
    FILE * f = fopen(File,"wb");
    if (f == NULL) return 0;
    int w = fwrite(Memory2,1,Size,f); 
    if (w != Size) return 0;
    fclose(f);
    free(Memory2);
    return 1;
    
    }

解决方法

您不能仅仅使用x86 shellcode将其移动到x64并期望它正常工作。 x86程序集和x64程序集之间有很多区别。专门与如何在堆栈/寄存器上传递参数以及使用哪些寄存器有关。

您的shellcode在x64中不起作用的原因可能与堆栈的错误分配或不正确的寄存器用法有关。您可能要保存x86部分,然后尝试在x64中使用相同的shellcode。您可能还试图执行不可执行的内存区域。可能有很多原因。

我在x64中为您编写了一个简单的shellcode。第一个参数是地址,第二个参数是要显示的消息。请注意,这在x86中不起作用。

unsigned char shellcode[] = {
0x56,0x48,0x8B,0xF1,0xC7,0xC1,0x00,0x4C,0xC2,0x49,0x83,0xEC,0x20,0xFF,0xD6,0xC4,0x5E,0xC3
};
void CallMB(FARPROC MessageBoxAddress,char* Message){
//here make a function pointer to shellcode which takes two argumenst
//the address and the buffer.
//call the pointer
}

我也不知道您是如何将Shell代码保存到文件中的。如果是二进制文件或文本文件。但是只要内存区域是可执行的,也可以在代码中直接调用该Shellcode。