get_session.py
1 #!/usr/bin/env python 2 3 import os 4 import re 5 import shutil 6 import sqlite3 7 import tempfile 8 from pathlib import Path 9 10 import requests 11 from Crypto.Cipher import AES 12 from Crypto.Protocol.KDF import PBKDF2 13 14 key = PBKDF2("peanuts", b"saltysalt", 16, 1) 15 16 17 def expand_path(path): 18 return Path(path).expanduser().absolute() 19 20 21 def chrome_decrypt(encrypted_value): 22 dec = AES.new(key, AES.MODE_CBC, IV=b" " * 16).decrypt(encrypted_value[3:]) 23 decrypted = dec[32 : -dec[-1]].decode() 24 return decrypted 25 26 27 def get_chrome_cookie(path): 28 conn = sqlite3.connect(str(expand_path(path))) 29 return chrome_decrypt( 30 conn.execute( 31 "select encrypted_value from cookies where host_key=? and name=?;", [".adventofcode.com", "session"] 32 ).fetchone()[0] 33 ) 34 35 36 def get_firefox_cookie(path): 37 (_, tmp) = tempfile.mkstemp() 38 try: 39 shutil.copy(str(expand_path(path)), tmp) 40 conn = sqlite3.connect(tmp) 41 return conn.execute( 42 "select value from moz_cookies where host=? and name=?;", [".adventofcode.com", "session"] 43 ).fetchone()[0] 44 finally: 45 os.remove(tmp) 46 47 48 def firefox_get_default_profile_path(path): 49 path = expand_path(path) 50 profile = next(f for f in os.listdir(path) if f.endswith(".default")) 51 return path / profile 52 53 54 # session = get_chrome_cookie("~/.config/BraveSoftware/Brave-Browser/Default/Cookies") 55 session = get_firefox_cookie(firefox_get_default_profile_path("~/.librewolf") / "cookies.sqlite") 56 57 print(session) 58 if not os.path.isdir(".cache"): 59 os.mkdir(".cache") 60 with open(".cache/session", "w") as file: 61 file.write(session) 62 63 if match := re.search( 64 r'<div class="user">([^<]+)', requests.get("https://adventofcode.com", cookies={"session": session}).text 65 ): 66 print("logged in as", match[1].strip()) 67 else: 68 print("invalid token")