cast from char to long

608 Views Asked by At

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.

1

There are 1 best solutions below

1
Bathsheba On

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 since buf[0] might not be aligned correctly for a long.)

In short, each iteration of the loop is an attempt to cast a pointer to char to a pointer to long, pretenting that there is an long at that location to which 0x80484cb can be assigned.

It is also assuming that sizeof(long) is 4 which is dubious to say the least.

The behaviour of puts will be undefined since buf doesn't necessarily point to the start of a char array that contains the null-terminator \0.

A far safer way would be to perform the pointer arithmetic directly on the char array, assigning portions of 0x80484cb as you go.