yannickwe87 yannickwe87 - 1 month ago 12
C++ Question

C++ Strange memcpy behaviour

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!

Answer

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.