image.png

CTF competitions will often have a component where you connect to a remote service using netcat nc. The server expects some type of input and you get back output.

The challenges here are simple math problems. This challenge category is often exploitation, where you have to exploit a weakness in the code, or cryptography, where you have to exploit a weakness in the algorithm being used.

If you connect to the server, you’ll receive a simple math problem. You have one second to solve it to the nearest whole number.

image.png

I won’t explain the program below in detail, but in summary it:

from pwn import remote
import re

def solve_problem(problem):
    # Use regex to extract numbers and the operator
    match = re.match(r"Solve this: (\d+)\s*([+\-*/])\s*(\d+)", problem)
    if not match:
        return None  # Problem format unexpected
    
    num1, operator, num2 = match.groups()
    num1, num2 = int(num1), int(num2)
    
    # Calculate based on operator
    if operator == '+':
        answer = num1 + num2
    elif operator == '-':
        answer = num1 - num2
    elif operator == '*':
        answer = num1 * num2
    elif operator == '/':
        answer = num1 // num2  # Floor division to ignore decimals
    else:
        return None  # Unrecognized operator
    
    return str(answer)

def main():
    # Connect to the local server (change "localhost" and port if needed)
    conn = remote("ctf.local", 5555)
    
    try:
        for _ in range(20):
            # Receive the problem from the server
            problem = conn.recvline(timeout=1).decode().strip()
            print(f"Received problem: {problem}")
            
            # Solve the problem
            answer = solve_problem(problem)
            if answer is None:
                print("Failed to solve the problem.")
                break
            
            print(f"Sending answer: {answer}")
            conn.sendline(answer)
            
            # Receive the result
            result = conn.recvline(timeout=1).decode().strip()
            print(f"Received result: {result}")
            
            # If the result is not "Correct!", exit the loop
            if result != "Correct!":
                print("Incorrect answer or timeout.")
                break
        
        # Final message if all problems are solved correctly
        final_message = conn.recvline(timeout=1).decode().strip()
        print(f"Received final message: {final_message}")
        
    except Exception as e:
        print(f"Error: {e}")
    finally:
        conn.close()

if __name__ == "__main__":
    main()