messy-malloc
Problem
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.
Solution
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 ofcalloc
.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 bymalloc
will persist whenmalloc
is called again sincemalloc
does not overwrite them. More info about malloc vs calloc.malloc
in itself is not dangerous but this program has a vulnerability where it only initializes theusername
field of theuser
struct
, which means the other members of thestruct
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 theuser
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 auser
structure. When welogout
, 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 script.py
python script.py USER=<username> PASSWORD=<password>
:
Flag
picoCTF{g0ttA_cl3aR_y0uR_m4110c3d_m3m0rY_ac0e0e6a}
Last updated