[python]pwntools 사용법
해당 게시글은 dreamhack.io를 참고하여 작성한 게시글입니다.
해킹할 때 nc와 더불어 가장 많이 사용하는 api이다.
python -c perl -e 같은 옵션으로 ; cat | ./hack.o
의 실행파일 등으로 커맨드 shell에서 이용할 수는 있지만 dreamhack에서 했을 때 이상하게 잘 안된다.
payload가 복잡해질수록 쓰기 힘들기 때문이다.
이것을 시스템 해커가 집대성하여 만든 것이 바로 pwntools이다.
https://github.com/Gallopsled/pwntools
GitHub - Gallopsled/pwntools: CTF framework and exploit development library
CTF framework and exploit development library. Contribute to Gallopsled/pwntools development by creating an account on GitHub.
github.com
먼저 pwntools 부터 설치하자
$ apt-get update
$ apt-get install python3 python3-pip python3-dev git libssl-dev libffi-dev build-essential
$ python3 -m pip install --upgrade pip
$ python3 -m pip install --upgrade pwntools
여기서 커맨드 shell에서 python3 을 쳐서 작성해도 좋지만
vi 에디터, vim 같은 곳에서 작성하면 더욱 편하다.
from pwn import *
p = process('./test') #현재위치에 있는 test를 대상으로 익스플로잇
p = remote('url.com', 80 ) #'url.com'의 port number(80)에서 실행 중인 프로세스를 대상으로 익스플로잇
#send
#여기서 p는 위에서 remote 또는 process해서 나온 object p
p.send('A') # 프로세스에 'A'를 입력
p.sendline('A') # 프로세스에 'A'+'\n'을 입력
p.sendafter('hello','A') # 프로세스가 'hello'를 출력하면, 'A'를 입력
p.sendlineafter('hello','A') # 프로세스가 'hello'를 출력하면, 'A' + '\n'을 입력
#recv
data = p.recv(1024) # p가 출력하는 데이터를 최대 1024byte 받아서 data에 저장
data = p.recvline() # p가 출력하는 데이터를 개행문자를 만날 때까지 받아서 data에 저장
data = p.recvn(5) #p가 출력하는 데이터를 5바이트만 받아서 data에 저장
data = p.recvuntil('hello') #p가 출력하는 데이터를 'hello'가 출력될 때까지 받아서 data에 저장
data = p.recvall() #p가 출력하는 데이터를 프로세스가 종료될 때까지 받아서 data에 저장
packing
p32('41414141')
p64('4141414141414141')
-> AAAA / AAAAAAAA
32비트, 64비트 환경 16진수를아스키코드로 변경
hex(u32('AAAA'))
hex(u64('AAAAAAAA'))
-> 41414141 / 4141414141414141
interactive
셸을 획득한 상황이라면 터미널 이용하면서 입출력확인 가능
p.interactive()
elf
elf(linux 실행파일)의 헤더정보를 손쉽게 참조 가능
from pwn import *
e= ELF('./test')
puts_plt = e.plt['puts'] # ./test에서 puts()의 PLT주소를 찾아서 puts_plt에 저장
read_got = e.got['read'] # ./test에서 read()의 GOT주소를 찾아서 read_got에 저장
shellcraft
자주 쓰는 shellcode 저장
from pwn import *
context.arch = 'amd64' # 대상 아키텍처 x86-64
code = shellcraft.sh() # 셸을 실행하는 셸 코드
print(code)
https://docs.pwntools.com/en/stable/shellcraft/amd64.html
pwnlib.shellcraft.amd64 — Shellcode for AMD64 — pwntools 4.8.0 documentation
Parameters: key (int,str) – XOR key either as a 8-byte integer, If a string, length must be a power of two, and not longer than 8 bytes. Alternately, may be a register. address (int) – Address of the data (e.g. 0xdead0000, ‘esp’) count (int) – Nu
docs.pwntools.com
참조
asm
셸코드를 기계어로 변경해줌 (b'~~~~~~')
from pwn import *
context.arch = 'amd64' # 익스플로잇 대상 아키텍처 'x86-64'
code = shellcraft.sh() # 셸을 실행하는 셸 코드
code = asm(code) # 셸 코드를 기계어로 어셈블
print(code)