Have you ever gotten tired of writing your name in the header of a letter? Well now there’s a program (source)to do it for you! Navigate to /problems/letter/ on the shell server to try your exploit out!

Let’s analyze the given binary first.

It is a 32-bit ELF executable with non-executable stack and a stack canary.

The program asks for the user’s name and then prints a card that includes the user’s name. Since, it only reads input once and prints it back one time with printf, I suspected that there could be a format string exploit.

Let’s test it using %x.

My guess was on the spot! Now, we can abuse %n to write some bytes to arbitrary memory addresses. First, we need to calculate the offset of our own input on the stack, because we will use our own buffer to target static addresses on the process’ memory.

Let’s put a breakpoint on the printf call that prints our name to analyze the stack offsets.

As you can see, our input’s buffer starts at offset 104 which is the 26th argument for the printf. We set the 26th and 27th arguments with the first 8 bytes of our payload to write to different BYTEs to the memory instead of writing a single WORD.

Now, we need to find a static and writable address to modify. Let’s disassemble the main function.

The program calls exit at the end of the main. Let’s modify exit’s GOT(Global Offset Table) entry.

0x804a030 is the address that stores the address of the real exit function.

Here are the 4 bytes that are stored at 0x804a030.

Let’s find the printFlag function’s address.

So we want to change the address from 0x080485c6 to 0x0804872b. We need to write 0x2b to 0x0804a030 and write 0x87 to 0x0804a031. Therefore, our first 8 bytes will be \x30\xA0\x04\x08\x31\xA0\x04\x08. Now, before using %26$hhn, we need to make sure that exactly 0x2b characters has been printed to stdout. The printf statement printed “|  Dear ” first which is 8 bytes and also it printed back the 8 bytes of our input. At total, it printed back 16 bytes and we need 27 more. We will use %27x to print those bytes. Then, we can use %26$hhn to write 0x2b to the 0x0804a030. Then, we need to print 92 bytes which we will achieve using %92x. Then, we will use %27$hhn to write 0x87 to 0x0804a031.

Let’s connect to the ssh and try our payload.

We got the flag actf{flags_are_fun}.