# Pwntools 用法整理
###### tags: `pwn` `CTF`
```python
'''連接遠端主機'''
r = remote('140.115.59.7', 11001) # usage : remote(host,port)
# exploit code
r.interactive() # 取得shell後可將command傳到terminal上
'''本地端process'''
p = process('./demo') # usage : process(binary, env)
context.terminal = ['tmux', 'splitw', '-h'] # 在tmux下可以切出視窗跑gdb
gdb.attach(p) # attach到gdb
# explot code
p.interactive()
'''recv'''
r.recv()
r.recvline() # 接收一行
r.recvlines(num) # 接收(num)行
r.recvuntil(str) # 接收直到碰到(str)
'''send'''
r.send(payload)
r.sendline(payload) # 會在最後面加一個空字符
'''pack & unpack'''
p32(0xdeadbeef) #'\xef\xbe\xad\xde'
p64(0xdeadbeef) #'\xef\xbe\xad\xde\x00\x00\x00\x00'
hex(u32('\xef\xbe\xad\xde')) # 0xdeadbeef
hex(u64('\xef\xbe\xad\xde\x00\x00\x00\x00')) # 0xdeadbeef
'''payload可以用flat接起來'''
flat('a'*5, p32(0xdeadbeef)) # b'aaaaa\xef\xbe\xad\xde'
'''context'''
context.arch = "amd64"
context.os = 'linux'
context.endian = 'little' # little endian
'''shellcode & asm'''
asm('mov rax,0; syscall') # b'H\xc7\xc0\x00\x00\x00\x00\x0f\x05'
asm('mov eax, SYS_execve', arch='i386') # b'\xb8\x03\x00\x00\x00'
asm(shellcraft.sh())
shellcraft.i386.mov('eax', 0x20)
# print: push 0x20; pop eax
disas()
'''ELF'''
e = ELF(elf_file) # 也可以丟libc.so進去
e.symbols['main'] # main函數的地址
e.got['puts'] # puts在got的地址
e.plt['puts'] # puts在plt的地址
e.search('/bin/sh')
e.address # base address
e.entry # entry point
e.asm(e.address, 'pop edx;ret') # 把e的base address上的內容改成指定的machine code
# usage : asm(addr, assembly)
e.disasm(e.entry, 10) # 在entry進行10byte的disasseble
e.section('.bss') # dump出bss段的內容
'''ELF'''
e = ELF(elf_file)
e.got['put'] # puts在got的地址
e.plt['puts'] # puts在plt的地址
'''libc'''
lib = ELF('libc.so.6')
lib.symbols['system'] # 找system的offset
lib.search('/bin/sh') # 找'/bin/sh' offset
'''ROP'''
rop = ROP(elf_file) # 產生一個空的rop鏈
rop.chain() # 印出目前chain
rop.dump() # dump出chain在stack的樣子
rop.read(0, elf.bss(0x80)) # 如果存在可組成read(0, .bss+0x80)的gadgets,
# 就加入rop chain
rop.raw('/bin/sh') # 將'/bin/sh'字串直接加入rop chain
```
{"metaMigratedAt":"2023-06-15T15:06:55.788Z","metaMigratedFrom":"Content","title":"Pwntools 用法整理","breaks":true,"contributors":"[{\"id\":\"f3dfbea6-7d10-449b-9606-49eccdb144d9\",\"add\":3976,\"del\":1913}]"}