0

For a CTF I'm trying to build a WinSock application vulnerable to a simple buffer overflow, however I came across a, for me at least, very strange behaviour of memcpy. All security measures in visual studio have been disabled.

char recvbuf[1024];
char sendbuf[300];
int recvbuflen=1024;
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
memcpy(sendbuf, recvbuf, recvbuflen);
if (iResult > 0) {
    printf("Bytes received: %d\n", iResult);

    // Echo the buffer back to the sender
    iSendResult = send(ClientSocket, sendbuf,sizeof(sendbuf) , 0);

    .........

As you can see from above code snippet, this is a very simple application that just replies with the bytes received. Now I have two questions concerning memcpy's behavior:

  1. Why does this not trigger a buffer overflow? It looks to me I'm trying to copy a buffer that is 1024 chars long to a buffer that is 300 chars long. When trying the same using a char*, it does trigger a buffer overflow.

  2. iSendResult = send(ClientSocket, sendbuf,sizeof(sendbuf) , 0); When I change the size to iResult (this are the total of received bytes) the application does correctly answer with all the chars received, yet I have selected sendbuf to be sent which is only 300 chars long, where does he get the remaining characters from (some sort of temp buffer?)

So these are two behaviors I'm not sure how to explain. It would be great if somebody could somebody shed some light onto this.

Best regards!

yannickwe87
  • 105
  • 7
  • 3
    [*Undefined Behaviour*](http://en.cppreference.com/w/cpp/language/ub) includes appearing to work. I would guess when you overflow `sendbuf`, you are actually writing back into part of `recvbuf` you are no long using, which is why it appears to work. This is very bad. – BoBTFish Oct 20 '16 at 11:00

1 Answers1

2

You are overflowing the buffer. What do you expect to happen? A buffer overflow is a case of undefined behavior. In a very simple program such as this, undefined behavior has a habit of working fine. That is what makes undefined behavior so insidious.

When your program is run, it writes 300 bytes to sendbuf and the remaining bytes to whatever follows sendbuf in memory. My guess is that recvbuflen contains bytes 300 through 304. If you add a new variable char unused[1024] = {0} after sendbuf you might be able to see where the bytes are being written to by examining it's contents after the memcpy.

D.Shawley
  • 58,213
  • 10
  • 98
  • 113
  • Thanks, indeed, because I defined the char[300] after the char[1024] it get pushed 'above' the char[1024] on memory, thus indeed overwrting a big part of the char[1024]. – yannickwe87 Oct 20 '16 at 11:09