#!/usr/bin/env python3
# remote_exploit.py
import json,requests

# Make cookie and plaintext
plaintext_dict = {}
plaintext_dict["access_level"] = "User"
plaintext = json.dumps(plaintext_dict).encode()

cookie = "" # Change me to the cookie from the server

# Convert cookie to bytes (hex -> bytes)
cookie = bytes.fromhex(cookie)

print(f"Plaintext (bytes): {plaintext}")
print(f"Plaintext (hex): {plaintext.hex()}")
print(f"Encrypted Cookie (hex): {cookie.hex()}")

# Calculate the keystream used in xor
keystream = []

print("\nCalculating keystream...")
for pt, ct in zip(plaintext, cookie):
    s = pt ^ ct
    keystream.append(s)
    print(f"{pt:02x} ^ {ct:02x} = {v:02x}")

# Encrypt new plaintext
new_dict = {}
new_dict["access_level"] = "Admin"
new_plaintext = json.dumps(new_dict).encode()

print(f"\nNew plaintext (bytes): {new_plaintext}")
print(f"\nNew plaintext (hex): {new_plaintext.hex()}")

new_ciphertext = ""

print("\nEncrypting new plaintext...")
for s, pt in zip(keystream, new_plaintext):
    ct = s ^ pt
    new_ciphertext += f"{ct:02x}"
    print(f"{s:02x} ^ {pt:02x} = {ct:02x}")

print(f"New Ciphertext (hex): {new_ciphertext}")

# Bruteforce the last (extra) byte
print("\nBruteforcing the last (extra) byte")
for i in range(2**8):
    ct = new_ciphertext + f"{i:02x}"

    # Bruteforce by using requests to the /flag path on the server
    print(f"Trying {ct}", end="...")
    r = requests.get("http://privilege.hkn/flag", cookies={"permissions": ct})
    # Look for "cookie" in the response, since the error message is:
    # "Something went wrong with your cookie" 
    if "cookie" not in r.text:
        print("Correct")
        new_ciphertext = ct
        break
    else:
        print("Wrong")

print(f"\nNew Ciphertext with correct extra byte (hex): {new_ciphertext}")
