#!/usr/bin/python3
import socket
import random
from random import randint
from socket import AF_INET, socket, SOCK_STREAM
import re

'''
    The objective of this task is to match the session key provided by
    a webserver running on port 5000.

    Create a connection to the server using the IP and port number (5000).
    Once connected, you will recieve a message back from the server. ie. "SERVER>>> Connection successful"
    You will then recieve a hex value from the server.
    You will need to "decrypt" that hex value by XOR'ing it with the appropriate key from the session_keys array
    The decrypted value is going to match one of keys from the server XOR'ed with a random hex number
    You will then send that "decrypted" value back to the server to see if it matches the hex value generated by the server
'''

serverName = ""
serverPort = 5000

session_keys = ["aa072fbbf5f408d81c78033dd560d4f6",
                "bb072fbbf5f408d81c78033dd560f6d4",
                "f5072fbbf5f408d81c78033dd5f6d460",
                "408df5072fbbf5f81c3dd5f6d4607803",
                "dd5f408df5072fbbfc36d46078035f81",
                "c36d408df5072fbbf46078035f81dd5f",
                "35f8c36df5072fbbf4607801dd5fd408",
                "2f07aaf408d81c78033dd560d4f6bbf5",
                "80332ff408d81c7dd560d4f6bbf507aa",
                "560d4f8033281c7dd6bbf507aaff408d",
               ]

# step 1: create socket

# Setting buffer size for socket
BUFSIZE = 1024

print("Attempting connection")
sock = socket(AF_INET, SOCK_STREAM)
addr = (serverName, serverPort)
sock.connect(addr)

def receive(sock):
    while True:
        try:
            msg = sock.recv(BUFSIZE)
            return msg
        except OSError:
            break

msg = receive(sock)
if (msg.decode("utf-8") == "SERVER>>> Connection successful"):
    encoded = receive(sock).decode("utf-8")

print(encoded) # see the value of server msg
print(int(encoded,16))

#setting empty string to store server response
response = ""

i=0
while True:

    decoded  = hex(int(session_keys[i], 16)^int(encoded,16))
    print("Trying key {}".format(session_keys[i]))
    # print(type(decoded.encode()))
    # print(decoded)
    # print(int(decoded,16))

    sock.send(decoded.encode())
    ## Recv key match status
    response = receive(sock)
    if ("Success! You found the key:" in response.decode()):
        successMessage = response.decode()
        print("Success! You found the key!")
        break

    if ('INVALID' in response.decode()):
        print("Invalid Key\n")
    
    ## Connection success message
    response = receive(sock)
    if ('Connection Successful' in response.decode()):
        print("Next Try..")
    encoded = ""
    while ("0x" not in encoded):
        encoded = receive(sock).decode("utf-8")
    i += 1
    if (i % 3 == 0):
        sock.close()
        sock = socket(AF_INET, SOCK_STREAM)
        sock.connect(addr)
    if (i == len(session_keys)):
        i=0


'''
    Message recieved from server:
    Success = "SUCCESS, you found the key"
    Incorrect = "INVALID KEY"
'''








# ======= SAVE MESSAGE TO 'successMessage'. DO NOT CHANGE!!! ===========
f = open('unittest.xml', 'w')
successMessage = re.findall("[/<].*", successMessage)
print("\n".join(successMessage), file=f)
f.close()
# ===========================================================================

