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:
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.
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!