The MSP Tech Club puts on an annual CTF, available here. I've worked on a solution but was wondering if there's a better way to write it or if I have any particular bad habits showing themselves?
The challenge is to write a script to connect to a server and answer math problems presented to it, it looks like this:
Answering 500 questions in a small enough timeframe reveals this:
I've left the netcat server in the code to allow for testing of changes. Since the CTF is public facing I don't think this poses an issue but feel free to remove if I'm breaking any S/O rules.
#!/usr/bin/python3
import socket
import re
if __name__ == '__main__':
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('195.154.53.62', 1337))
while True:
data = b''
while True:
chunk = client.recv(4096)
data += chunk
if len(chunk) < 4096:
break
# our flag contains ALEXCTF, once it's revealed print recevied data and exit
if 'ALEXCTF' in data.decode('utf-8'):
print(data.decode('utf-8'))
break
# \d+ matches a digit (equal to [0-9])
# .{3} matches any character, except line terminators exactly three times
m = re.search('\d+.{3}\d+', data.decode('utf-8'))
expression = m.group(0)
#properly handle division
if '/' in expression:
expression = expression.replace('/', '//')
result = eval(expression)
#print results to screen to see script progress
print(expression + ' = ' + str(result))
#encode and transfer
data = str(result).encode('utf-8') + b'\n'
client.send(data)