After almost one and half year AFK, play CTF again.
The vulnerability is easy to locate as given below. Function alloca alloccates 4*n bytes on stack, but the long-type number inserted on stack is 8-byte long.
And it is easy to detect that there is something wrong.
Since the variables from top to bottom is i, array, sum, the picture above overwrites i in stack resulting the end of the program.
The whole idea of the exploit is to use the sum of the array to leak the information on stack, and the exploit is divided into two steps:
Step1: Overwrite i to skipping overwriting array in stack, leak the value of $rbp. Due to the limit of n, we can only overwrite return address main+92
Step2: Overwrite array to enable overwriting more data on stack as following:
The value in red is the array to overwrite.
To leak the base address of libc, my initial idea is to leak the value in blue (__libc_start_main+240) directly. After struggling with the logic of the code for some time, I found that it is impossible to leak the value in blue while keeping that unchanged in stack. Therefore, I decided to change the value in blue back to 0x400a10 again. Meanwhile, change the return value of calc_sum to 0x400a10.
After operations above, we will get two chances to call function calc_sum. Use the first chance to leak the base address of libc by overwriting array to 0x6010a0. Take the second chance to overwrite firstname.lastname@example.org to get the shell.
The final exploit is given on my github repo: