DEF CON 2015 Quals - mathwhiz (1pt) writeup

The challenge description was: mathwhiz_c951d46fed68687ad93a84e702800b7a.quals.shallweplayaga.me:21249

This was a programming challenge, when connecting the server would ask us to solve some basic mathematic operations such as: 1 + 2

If you know how to parse data it is pretty straight forward, after a couple attempt to see where the script would fail (such as when the server would ask to solve ONE + TWO instead of 1 + 2 for example) I ended with the following script:

#!/usr/bin/env python

import socket, re

def solve(data):
result = 0
NUMSTR = [['ZERO', '0'],
['ONE', '1'],
['TWO', '2'],
['THREE', '3'],
['FOUR', '4'],
['FIVE', '5'],
['SIX', '6'],
['SEVEN', '7'],
['EIGHT', '8'],
['NINE', '9']]

# this is math ^ symbol is exponent not xor
data = re.sub('\^', '**', data)

# calculate values inside parentheses first (wasn't necessary apparently)
parenth = re.findall(r'\(([^\)]+)\)', data)
if len(parenth) > 0:
for grp in parenth:
data = data.replace(grp, str(solve(grp)))

# replace written number in string into numerical numbers
for num in NUMSTR:
if num[0] in data:
data = re.sub(num[0], num[1], data)

# clear odd characters [] {} and =
data = re.sub('[\[\]{}=]', '', data)
result = eval(data)
return result

def mathwhiz():
HOST = 'mathwhiz_c951d46fed68687ad93a84e702800b7a.quals.shallweplayaga.me'
PORT = 21249

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while 1:
data = s.recv(512)[:-1]
answer = ''
try:
answer = str(solve(data))
except:
print data
exit(0)
print '%s %s' % (data, answer)
s.send(answer+'\n')

mathwhiz()

The server asked for maybe more than 300 operations to solve and eventually:

...
1 - 1 + 1 + 1 = 2
3^2 - 2 - ( 3 + 1) = 3
1 + 2 = 3
3 + 2 - 2 - 2 = 1
3 - (3 + 1) + 2 = 1
2 + 1 + 2 - 3 = 2
1 + 3 - 1 = 3
1 + 1 + 1 - 1 = 2
1 + 2 - 2 = 1
3 - 3 + 1 = 1
2 - 3 + 2 + 1 = 2
3 + 1 - 1 - 1 = 2
3 - 2 = 1
3 - 3 + 2 = 2
THREE - TWO = 1
2 + 1 + 1 - 3 = 1
3 - 1 - 1 = 1
3 + 3 - 3 - 2 = 1
2 + 2 - 2 = 2
2 + 2 - 1 = 3
You won!!!
The flag is: Farva says you are a FickenChucker and you'd better watch Super Troopers 2

We got our flag:

Farva says you are a FickenChucker and you'd better watch Super Troopers 2