Search code examples
cmemorymallocmemcpyshellcode

Why am I receiving an "Access Violation" Error on this memcpy function?


When running this program in Visual Studio, I receive an "Access Violation" error when the program reaches the memcpy function. No matter what size I make this buffer, it always throws this read access violation error. I've set breakpoints at the memcpy function and as soon as I continue the execution, it throws this error:

snip of error

char data[DATA_SIZE] = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
#define DATA_SIZE 27136

void spawn(void * buffer, int length, char * key);

typedef struct {
    int  offset;
    int  length;
    char key[4];
    int  gmh_offset;
    int  gpa_offset;
    char payload[DATA_SIZE];
} phear;

extern char data[DATA_SIZE];
void start(HINSTANCE mhandle) {
    
    phear * payload = (phear *)data;
    char * buffer;

    buffer = (char *)malloc(payload->length);
    memcpy(buffer, payload->payload, payload->length);

    /* execute our code */
    spawn(buffer, payload->length, payload->key);

    /* clean up after ourselves */
    free(buffer);
}

Solution

  • There's several problems here:

    • data might not be correctly aligned for phear. See What is aligned memory allocation?
    • payload->length is a strict aliasing violation: this is defined as (*payload).length and the expression *payload accesses memory through an expression of type phear but there is no object of type phear at that location.
    • (If we ignore the above two problems for a moment) The memcpy reads out of bounds because sizeof data < sizeof(phear).

    A simple solution would be to use extern phear data; instead of the char array. If you really want to use the char array then copy data in and out of it with memcpy instead of struct access.