호그와트

happy monday

영웅*^%&$ 2024. 6. 24. 10:51
728x90
import socket
import binascii

def connect_and_get_flag(server_ip, server_port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((server_ip, server_port))
       
        # Read the welcome message with the encoded flag
        welcome_message = s.recv(1024).decode()
        print("Received:", welcome_message)
       
        # Extract the hex-encoded flag from the welcome message
        encoded_flag = welcome_message.split("flag 1: ")[1].split("\n")[0]
       
        # Known start of the flag
        known_start = "THM{"
       
        # Convert hex to ASCII
        ascii_str = binascii.unhexlify(encoded_flag).decode()
       
        # Derive the key using the known start of the flag
        key = ''.join([chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(known_start, ascii_str[:len(known_start)])])
        print("Derived key:", key)
       
        # Decrypt the entire message using the derived key
        decrypted_message = ''.join([chr(ord(c) ^ ord(key[i % len(key)])) for i, c in enumerate(ascii_str)])
        print("Decrypted message:", decrypted_message)
       
        # Send the derived key back to the server
        s.sendall(key.encode() + b'\n')
       
        # Read the server response with flag 2
        response = s.recv(1024).decode()
        print("Server response:", response)

# Replace with actual server IP and port
server_ip = "10.10.218.175"
server_port = 1337

connect_and_get_flag(server_ip, server_port)
728x90