Connections with pwntools

Pwntools, in case you don't know is a CTF framework and exploit development library for Python 3.

It is designed for rapid prototyping and development and it will make our jobs with connections much simpler.

Making Connections

In most of the pwning challenges in CTF the binary is hosted remotely, so we connect to it using netcat, sockets or pwntools. For that, pwntools has the pwntools.tubes module, that will help us connect to a server.

For example, if you want to connect to a remote ftp server, using the pwnlib.tubes.remote

from pwn import *
conn = remote('ftp.ubuntu.com',21)
conn.recvline()
#'220 FTP server (vsftpd)'
conn.send('USER anonymous\r\n')
conn.recvuntil(' ', drop=True)
#'331'
conn.recvline()
#'Please specify the password.\r\n'
conn.close()

In this case, at the first line we create the socket using remote, at the ip address of the domain ftp.ubuntu.com and port 21. The first command receives a line that was sent by the server. It returns the line as a string format. In the code above the return is written as comments. Then, it send some information with send, without the need to specify amount of bytes to be sent. Another method that's pretty useful is the recvuntil, that will receive data until the string specified is found.

Setting up a listener

In order to setup a listener it is as simple as with the client.

from pwn import *
l = listen(9999)
r = remote('localhost', 9999)
svr = l.wait_for_connection()
r.send('hello')
print(svr.recv())

The code above sets up a listener l and a client r at the port 9999, or l.lport in this case.

Then, the server sets up the listener to wait for the connection, then the remote client sends a hello, which is echoed by the server.