CREDS >>
TryHackMe – https://tryhackme.com/p/TheSysRat
HackTheBox – https://app.hackthebox.com/profile/1298347
TryHackMe >>
https://tryhackme.com/r/room/w1seguy
Recon >>>
We get this script >
import random
import socketserver
import socket, os
import string
flag = open('flag.txt','r').read().strip()
def send_message(server, message):
enc = message.encode()
server.send(enc)
def setup(server, key):
flag = 'THM{thisisafakeflag}'
xored = ""
for i in range(0,len(flag)):
xored += chr(ord(flag[i]) ^ ord(key[i%len(key)]))
hex_encoded = xored.encode().hex()
return hex_encoded
def start(server):
res = ''.join(random.choices(string.ascii_letters + string.digits, k=5))
key = str(res)
hex_encoded = setup(server, key)
send_message(server, "This XOR encoded text has flag 1: " + hex_encoded + "\n")
send_message(server,"What is the encryption key? ")
key_answer = server.recv(4096).decode().strip()
try:
if key_answer == key:
send_message(server, "Congrats! That is the correct key! Here is flag 2: " + flag + "\n")
server.close()
else:
send_message(server, 'Close but no cigar' + "\n")
server.close()
except:
send_message(server, "Something went wrong. Please try again. :)\n")
server.close()
class RequestHandler(socketserver.BaseRequestHandler):
def handle(self):
start(self.request)
if __name__ == '__main__':
socketserver.ThreadingTCPServer.allow_reuse_address = True
server = socketserver.ThreadingTCPServer(('0.0.0.0', 1337), RequestHandler)
server.serve_forever()
Solution >>>
What is wrong with this script? We should focus on this part >>
res = ''.join(random.choices(string.ascii_letters + string.digits, k=5))
For decrypt we need find XOR key of lenght 5 random chars digits and letters 🙂 it is looks like bruteforcing action, because we know that message starts by string ‘THM{‘ and end by char ‘}’
OK lets write decryptor for this action >>
or github https://github.com/TheSysRat/W1seGuy–THM
import binascii
def xor_decrypt(hex_string, key):
encrypted_bytes = binascii.unhexlify(hex_string)
repeated_key = (key * (len(encrypted_bytes) // len(key) + 1))[:len(encrypted_bytes)]
decrypted_bytes = bytes([b ^ ord(repeated_key[i]) for i, b in enumerate(encrypted_bytes)])
decrypted_message = decrypted_bytes.decode('utf-8')
return decrypted_message
hex_encoded_message = input('Tell me hex to brute-forcing >> ')
encrypted_bytes = binascii.unhexlify(hex_encoded_message)
known_plaintext_start = "THM{"
known_plaintext_end = "}"
key = [encrypted_bytes[i] ^ ord(known_plaintext_start[i]) for i in range(len(known_plaintext_start))]
for i in range(1, len(known_plaintext_end) + 1):
key.append(encrypted_bytes[-i] ^ ord(known_plaintext_end[-i]))
key = ''.join([chr(k) for k in key[:5]])
decrypted_message = xor_decrypt(hex_encoded_message, key)
print(f"Decrypted message: {decrypted_message}")
print(f"Encryption key: {key}")
And we will test it >>