2023 Cyber Apocalypse: Remote Computation

Challenge Information

AttributeDetails
Event2023 Cyber Apocalypse
CategoryMisc
ChallengeRemote Computation

Summary

This challenge requires connecting to a remote server that presents mathematical expressions and expects computed answers. The server presents 500+ questions and evaluates responses for correctness. Success requires automating expression parsing and calculation with proper error handling.


Analysis

The server presents questions in a format that requires:

  1. Extracting the arithmetic expression from the question
  2. Evaluating the expression
  3. Handling special error cases (division by zero, syntax errors, memory errors)
  4. Returning the computed result

Error handling requirements:

  • DIV0_ERR - Division by zero
  • SYNTAX_ERR - Invalid expression syntax
  • MEM_ERR - Result out of memory range (-1337 to 1337)

Question format: Questions contain expressions that need to be extracted via regex pattern matching.


Solution

import socket
import re
IP = '64.227.41.83'
PORT = 31524
BUFFER_SIZE = 1024
def evaluate_expression(expression: str) -> str:
try:
result = eval(expression)
# Check if result is within valid range
if -1337 <= result <= 1337:
return round(result, 2)
else:
return 'MEM_ERR'
except ZeroDivisionError:
return 'DIV0_ERR'
except SyntaxError:
return 'SYNTAX_ERR'
def main():
# Create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
# Receive initial menu
data = s.recv(BUFFER_SIZE)
print(data)
# Send '1' to start
s.sendall(b'1\n')
# Answer 501 questions
for i in range(501):
# Receive question
data = s.recv(BUFFER_SIZE)
print(data)
question = data.decode('utf-8').strip()
# Extract arithmetic expression using regex
# Pattern matches arithmetic operations like "123 + 456 ="
expression = re.search(r'([\d\s\+\-\*/]+)=', question).group(1)
print(f"Expression: {expression}")
# Evaluate and get answer
answer = evaluate_expression(expression)
print(f"Answer: {answer}")
# Send answer
s.sendall(f'{answer}\n'.encode('utf-8'))
print(f"Iteration {i + 1}: {question} -> {answer}\n")
# Close socket
s.close()
if __name__ == "__main__":
main()

Key features:

  • Regex extraction of arithmetic expressions
  • Python’s eval() for expression evaluation
  • Exception handling for various error conditions
  • Proper rounding and range checking
  • Socket-based communication

Key Takeaways

  • Automating repetitive tasks is essential in CTFs
  • Regular expressions help extract structured data
  • Python’s eval() can execute expressions but requires careful error handling
  • Exception handling is critical for robust automation
  • Socket programming enables interaction with network services
  • Understanding the exact response format is necessary for success