first glance of alloca in ctf
0x1 background
when I was doing zeropts CTF 2022, I found a pwn question called accountant.
There is a line of code that use alloca
to allocate memory. However, at that time, I didn't know that alloca
allocate the memory on the stack. so I simply thought there is no bug... :(
later, Super Guesser publish their writeup on accountant that point out that alloca
allocate space on the stack.
So I could have a chance of looking at alloca.
0x2 basic idea
The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.
https://www.mkssoftware.com/docs/man3/alloca.3.asp
Basically, alloca
allocate a space on the stack instead of heap.
Lets do some code to find out what alloca
do. above is a example program.
1 | #include <stdio.h> |
firstly, in assemble code alloca
didn't appear to be a function. Instead, it appear with a set of instruction. So, the asm will not have any instruction like call alloca
.
Before alloca is called, the stack looks very normal
1 | :> pxr @ rsp |
After program execute *ptr = 0x2001
. Comparing with previous stack frame, We notice that that stack alloca extra 16 bytes above the initial stack.
1 | :> pxr @ rsp |
If we continue and execute *ptr = 0x2002
. The it will also allocate 16 bytes of memory above the stack. This is because the stack need to be aligned with 0x10
. Since we only allocate 8 bytes, there need to be an extra 8 bytes padding in order to make the stack aligned.
Now, lets look what happens if we alloc(0)
.
After execute *ptr2 = 0x2003
. We found the value 0x2002
is replaced by 0x2003
. ptr1
and ptr2
are now pointing to a same address. Since
alloc(0)
actually return the current rsp
address!
1 | :> pxr @ rsp |
0x3 Some thoughts
it is pretty interesting that there is a function that allocate memory on the stack. It seems very convenient compare to malloc
if we just want use a memory space temporaryly. Since it will automatically freed after function exists, we don't need to worry about dangling pointer or memory leak.
But it is also kind of dangerous to use. For example, If we allocate 0 bytes, it would return current rsp address.
Also, when allocate larger space, we may run out of stack address if we use alloca
.