I am starting to learn the basics of buffer overflows. I came across a code where the function call which is supposed to happen once can be made to happen twice by modifying the flow that instead of pointing return address at the end of execution of the function, the code points to the beginning address of the function. Here's the code:
int main()
{
int i=0; char buf[44];
for (i=0;i<=40;i+=4)
*(long *) &buf[i] = 0x80484cb;
puts(buf);
}
What does *(long *) &buf[i] mean? I know its the very basics of C but need little help over here.
The code is a mess and the behaviour undefined due to casting of unrelated types. (Although you can always cast to
char*, the converse is not necessarily true sincebuf[0]might not be aligned correctly for along.)In short, each iteration of the loop is an attempt to cast a pointer to
charto a pointer tolong, pretenting that there is anlongat that location to which0x80484cbcan be assigned.It is also assuming that
sizeof(long)is 4 which is dubious to say the least.The behaviour of
putswill be undefined sincebufdoesn't necessarily point to the start of achararray that contains the null-terminator\0.A far safer way would be to perform the pointer arithmetic directly on the
chararray, assigning portions of0x80484cbas you go.