messy-malloc
Last updated
Was this helpful?
Last updated
Was this helpful?
Can you take advantage of misused malloc calls to leak the secret through this service and get the flag? Connect with nc 2019shell1.picoctf.com 21899. Source.
nc 2019shell1.picoctf.com 21899
:
We need to login as a user which has an access code allowing them to print the flag. However, there is no API to set access codes. user
struct:
The program uses malloc
instead of calloc
. malloc
allocates memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc
doesn’t initialize the allocated memory. calloc
allocates the memory and also initializes the allocated memory block to zero. Therefore, the memory set in line 73 (char *username = malloc(username_len+1);
) can be reused. The values stored in the block of memory allocated by malloc
will persist when malloc
is called again since malloc
does not overwrite them. More info about .
malloc
in itself is not dangerous but this program has a vulnerability where it only initializes the username
field of the user
struct
, which means the other members of the struct
will contain leftover values from whatever the memory was previously used for.
Running the program allows us to create a user that has a username with the length of our choice. We can set the length of the username to sizeof(struct user)
, which is the length of the user
structure (32 bytes = 8 for username pointer + 16 for size 2 array + 8 for files pointer). We can set this allocated username field as if it were a user
structure. When we logout
, the allocation is freed. However, we can log back in and the heap manager will probably provide us with the same buffer we just freed since the requested buffer size is equal to a previously freed buffer size (an optimization to reduce memory fragmentation). This new user will have the "leftover" access code and will be able to access the flag. This is possible because the previous user's username memory was freed (and was the last chunk to be freed), but not cleared.
Visual Description:
Allocate the first user:
Free first user
Allocate second user (Heap Manager provides "username buffer" as buffer for user struct):
Run the python script.py USER=<username> PASSWORD=<password>
:
picoCTF{g0ttA_cl3aR_y0uR_m4110c3d_m3m0rY_ac0e0e6a}