返回 last30days-skill
chrome_cookies.py
根目录 / skills / last30days / scripts / lib / chrome_cookies.py
1 """Chromium-family cookie extraction for macOS.
2
3 Extracts cookies from Chromium-based browser SQLite databases using only
4 stdlib modules and in-process AES-128-CBC decryption (macOS CommonCrypto via
5 ctypes, with a pure-Python fallback). Zero pip dependencies and zero key
6 exposure on subprocess argv.
7
8 Chromium on macOS uses v10 encryption (AES-128-CBC with Keychain-stored key).
9 Every Chromium-based browser (Chrome, Brave, Edge, Vivaldi, Opera, Arc, Dia,
10 Chromium) shares the same algorithm; only the profile directory and Keychain
11 service name differ, so they all run through the same decryption core.
12 This is NOT affected by Windows App-Bound Encryption (v20).
13 """
14
15 import ctypes
16 import hashlib
17 import logging
18 import os
19 import sqlite3
20 import subprocess
21 import sys
22 import tempfile
23 import time
24 from pathlib import Path
25 from typing import Any, Optional
26
27 from .cookie_paths import path_exists, path_is_dir
28 from .sqlite_snapshot import copy_snapshot
29
30 logger = logging.getLogger(__name__)
31
32 _SECURITY_BIN = "/usr/bin/security"
33 _COMMONCRYPTO_LIB_PATH = "/usr/lib/system/libcommonCrypto.dylib"
34 _KCC_DECRYPT = 1
35 _KCC_ALG_AES128 = 0
36 _KCC_OPT_PKCS7_PADDING = 1
37 _KCC_SUCCESS = 0
38 _CHROME_EPOCH_OFFSET_SECONDS = 11644473600
39 _SQLITE_TEMP_SIDECARS = ("", "-wal", "-shm", "-journal")
40
41
42 def _lock_temp_cookie_copy(path: str) -> None:
43 """Restrict copied cookie DB temp files to the current user on POSIX."""
44 if os.name == "nt":
45 return
46 Path(path).chmod(0o600)
47
48
49 def _unlink_sqlite_temp_files(path: Optional[str]) -> None:
50 """Remove a temporary SQLite copy and any WAL/SHM/journal sidecars."""
51 if not path:
52 return
53 for suffix in _SQLITE_TEMP_SIDECARS:
54 try:
55 Path(path + suffix).unlink(missing_ok=True)
56 except OSError:
57 pass
58
59 # Cookie DB locations on macOS
60 _APP_SUPPORT = Path.home() / "Library" / "Application Support"
61 CHROME_BASE_DIR = _APP_SUPPORT / "Google" / "Chrome"
62 # Kept for backward compatibility; resolution now goes through the profile
63 # finder (which also handles the modern Network/Cookies layout).
64 CHROME_COOKIES_DB = CHROME_BASE_DIR / "Default" / "Cookies"
65 BRAVE_BASE_DIR = _APP_SUPPORT / "BraveSoftware" / "Brave-Browser"
66
67 # Other Chromium-based browsers, keyed by FROM_BROWSER name. Each maps to
68 # (profile base directory, macOS Keychain service name). Chrome and Brave keep
69 # their dedicated helpers below for backward compatibility; everything here is
70 # resolved generically by extract_chromium_browser_cookies_macos(). Keychain
71 # service names follow Chromium's "<Browser> Safe Storage" convention.
72 CHROMIUM_BROWSER_PROFILES: dict[str, tuple[Path, str]] = {
73 "edge": (_APP_SUPPORT / "Microsoft Edge", "Microsoft Edge Safe Storage"),
74 "vivaldi": (_APP_SUPPORT / "Vivaldi", "Vivaldi Safe Storage"),
75 "opera": (_APP_SUPPORT / "com.operasoftware.Opera", "Opera Safe Storage"),
76 "arc": (_APP_SUPPORT / "Arc" / "User Data", "Arc Safe Storage"),
77 "dia": (_APP_SUPPORT / "Dia" / "User Data", "Dia Safe Storage"),
78 "ardia": (_APP_SUPPORT / "com.ardia.browser" / "Chromium", "Ardia Safe Storage"),
79 "chromium": (_APP_SUPPORT / "Chromium", "Chromium Safe Storage"),
80 }
81
82 # Chromium v10 encryption constants (shared by Chrome and Brave)
83 CHROME_SALT = b"saltysalt"
84 CHROME_PBKDF2_ITERATIONS = 1003
85 CHROME_KEY_LENGTH = 16
86 # IV is 16 space characters (0x20)
87 CHROME_IV = b" " * 16
88 CHROME_IV_HEX = "20" * 16
89
90
91 def _gf_mul(a: int, b: int) -> int:
92 res = 0
93 while b:
94 if b & 1:
95 res ^= a
96 hi = a & 0x80
97 a = (a << 1) & 0xFF
98 if hi:
99 a ^= 0x1B
100 b >>= 1
101 return res
102
103
104 def _gf_inv(a: int) -> int:
105 if a == 0:
106 return 0
107 res = 1
108 base = a
109 exp = 254
110 while exp:
111 if exp & 1:
112 res = _gf_mul(res, base)
113 base = _gf_mul(base, base)
114 exp >>= 1
115 return res
116
117
118 def _rotl8(value: int, shift: int) -> int:
119 return ((value << shift) | (value >> (8 - shift))) & 0xFF
120
121
122 def _build_aes_tables() -> tuple[tuple[int, ...], tuple[int, ...]]:
123 sbox = [0] * 256
124 inv_sbox = [0] * 256
125 for x in range(256):
126 inv = _gf_inv(x)
127 sub = (
128 inv
129 ^ _rotl8(inv, 1)
130 ^ _rotl8(inv, 2)
131 ^ _rotl8(inv, 3)
132 ^ _rotl8(inv, 4)
133 ^ 0x63
134 )
135 sbox[x] = sub
136 inv_sbox[sub] = x
137 return tuple(sbox), tuple(inv_sbox)
138
139
140 _AES_SBOX, _AES_INV_SBOX = _build_aes_tables()
141 _AES_RCON = (0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36)
142 _AES_MUL9 = tuple(_gf_mul(x, 0x09) for x in range(256))
143 _AES_MUL11 = tuple(_gf_mul(x, 0x0B) for x in range(256))
144 _AES_MUL13 = tuple(_gf_mul(x, 0x0D) for x in range(256))
145 _AES_MUL14 = tuple(_gf_mul(x, 0x0E) for x in range(256))
146
147
148 def _aes128_expand_key(key: bytes) -> list[bytes]:
149 words = [list(key[i : i + 4]) for i in range(0, 16, 4)]
150 for i in range(4, 44):
151 temp = list(words[i - 1])
152 if i % 4 == 0:
153 temp = [_AES_SBOX[b] for b in (temp[1], temp[2], temp[3], temp[0])]
154 temp[0] ^= _AES_RCON[i // 4 - 1]
155 prev = words[i - 4]
156 words.append([prev[j] ^ temp[j] for j in range(4)])
157 return [
158 bytes(words[4 * r] + words[4 * r + 1] + words[4 * r + 2] + words[4 * r + 3])
159 for r in range(11)
160 ]
161
162
163 def _aes128_decrypt_block(block: bytes, round_keys: list[bytes]) -> bytes:
164 rk = round_keys[10]
165 s = [block[i] ^ rk[i] for i in range(16)]
166 for rnd in range(9, 0, -1):
167 s[1], s[5], s[9], s[13] = s[13], s[1], s[5], s[9]
168 s[2], s[6], s[10], s[14] = s[10], s[14], s[2], s[6]
169 s[3], s[7], s[11], s[15] = s[7], s[11], s[15], s[3]
170 rk = round_keys[rnd]
171 s = [_AES_INV_SBOX[s[i]] ^ rk[i] for i in range(16)]
172 for c in (0, 4, 8, 12):
173 a0, a1, a2, a3 = s[c], s[c + 1], s[c + 2], s[c + 3]
174 s[c] = _AES_MUL14[a0] ^ _AES_MUL11[a1] ^ _AES_MUL13[a2] ^ _AES_MUL9[a3]
175 s[c + 1] = _AES_MUL9[a0] ^ _AES_MUL14[a1] ^ _AES_MUL11[a2] ^ _AES_MUL13[a3]
176 s[c + 2] = _AES_MUL13[a0] ^ _AES_MUL9[a1] ^ _AES_MUL14[a2] ^ _AES_MUL11[a3]
177 s[c + 3] = _AES_MUL11[a0] ^ _AES_MUL13[a1] ^ _AES_MUL9[a2] ^ _AES_MUL14[a3]
178 s[1], s[5], s[9], s[13] = s[13], s[1], s[5], s[9]
179 s[2], s[6], s[10], s[14] = s[10], s[14], s[2], s[6]
180 s[3], s[7], s[11], s[15] = s[7], s[11], s[15], s[3]
181 rk0 = round_keys[0]
182 return bytes(_AES_INV_SBOX[s[i]] ^ rk0[i] for i in range(16))
183
184
185 def _decrypt_aes128_cbc_pure(ciphertext: bytes, aes_key: bytes, iv: bytes) -> Optional[bytes]:
186 """Decrypt AES-128-CBC with PKCS7 padding in pure Python (no subprocesses)."""
187 round_keys = _aes128_expand_key(aes_key)
188 out = bytearray()
189 prev = iv
190 for offset in range(0, len(ciphertext), 16):
191 block = ciphertext[offset : offset + 16]
192 plain = _aes128_decrypt_block(block, round_keys)
193 out.extend(plain[i] ^ prev[i] for i in range(16))
194 prev = block
195 return _remove_pkcs7_padding(bytes(out))
196
197
198 _COMMONCRYPTO_FUNC: Any = None
199 _COMMONCRYPTO_LOADED = False
200
201
202 def _load_commoncrypto() -> Any:
203 """Load macOS CommonCrypto's CCCrypt symbol in-process, or return None."""
204 global _COMMONCRYPTO_FUNC, _COMMONCRYPTO_LOADED
205 if _COMMONCRYPTO_LOADED:
206 return _COMMONCRYPTO_FUNC
207 cc_crypt: Any = None
208 if sys.platform == "darwin":
209 try:
210 lib = ctypes.CDLL(_COMMONCRYPTO_LIB_PATH)
211 candidate = lib.CCCrypt
212 candidate.argtypes = [
213 ctypes.c_uint32,
214 ctypes.c_uint32,
215 ctypes.c_uint32,
216 ctypes.c_void_p,
217 ctypes.c_size_t,
218 ctypes.c_void_p,
219 ctypes.c_void_p,
220 ctypes.c_size_t,
221 ctypes.c_void_p,
222 ctypes.c_size_t,
223 ctypes.POINTER(ctypes.c_size_t),
224 ]
225 candidate.restype = ctypes.c_int32
226 cc_crypt = candidate
227 except (OSError, AttributeError):
228 cc_crypt = None
229 _COMMONCRYPTO_FUNC = cc_crypt
230 _COMMONCRYPTO_LOADED = True
231 return _COMMONCRYPTO_FUNC
232
233
234 def _decrypt_aes128_cbc_commoncrypto(
235 ciphertext: bytes, aes_key: bytes, iv: bytes, cc_crypt: Any
236 ) -> Optional[bytes]:
237 """Decrypt AES-128-CBC with PKCS7 padding in-process via macOS CommonCrypto."""
238 out_buf = ctypes.create_string_buffer(len(ciphertext) + 16)
239 out_len = ctypes.c_size_t(0)
240 status = cc_crypt(
241 _KCC_DECRYPT,
242 _KCC_ALG_AES128,
243 _KCC_OPT_PKCS7_PADDING,
244 aes_key,
245 len(aes_key),
246 iv,
247 ciphertext,
248 len(ciphertext),
249 out_buf,
250 len(out_buf),
251 ctypes.byref(out_len),
252 )
253 if status != _KCC_SUCCESS:
254 return None
255 return out_buf.raw[: out_len.value]
256
257
258 def _decrypt_aes128_cbc(
259 ciphertext: bytes, aes_key: bytes, iv: bytes = CHROME_IV
260 ) -> Optional[bytes]:
261 """Decrypt AES-128-CBC ciphertext in-process without exposing key material."""
262 if (
263 len(aes_key) != CHROME_KEY_LENGTH
264 or len(iv) != 16
265 or not ciphertext
266 or len(ciphertext) % 16 != 0
267 ):
268 return None
269 cc_crypt = _load_commoncrypto()
270 if cc_crypt is not None:
271 return _decrypt_aes128_cbc_commoncrypto(ciphertext, aes_key, iv, cc_crypt)
272 return _decrypt_aes128_cbc_pure(ciphertext, aes_key, iv)
273
274
275 def _get_chromium_encryption_key(service_name: str) -> Optional[bytes]:
276 """Retrieve the encryption passphrase for a Chromium-based browser from macOS Keychain.
277
278 Calls `/usr/bin/security find-generic-password` which may trigger a system dialog
279 on first access.
280
281 Returns the raw passphrase bytes, or None on failure.
282 """
283 try:
284 result = subprocess.run(
285 [_SECURITY_BIN, "find-generic-password", "-w", "-s", service_name],
286 capture_output=True,
287 text=True,
288 timeout=10,
289 )
290 if result.returncode != 0:
291 logger.info("%s Keychain access denied or browser not installed: %s", service_name, result.stderr.strip())
292 return None
293 passphrase = result.stdout.strip()
294 if not passphrase:
295 logger.info("%s Keychain returned empty passphrase", service_name)
296 return None
297 return passphrase.encode("utf-8")
298 except FileNotFoundError:
299 logger.info("'%s' command not found — not on macOS?", _SECURITY_BIN)
300 return None
301 except subprocess.TimeoutExpired:
302 logger.info("%s Keychain access timed out", service_name)
303 return None
304 except Exception as e:
305 logger.info("Failed to get %s encryption key: %s", service_name, e)
306 return None
307
308
309 def _get_chrome_encryption_key() -> Optional[bytes]:
310 return _get_chromium_encryption_key("Chrome Safe Storage")
311
312
313 def _derive_aes_key(passphrase: bytes) -> bytes:
314 """Derive 16-byte AES key from Chrome's Keychain passphrase via PBKDF2."""
315 return hashlib.pbkdf2_hmac(
316 "sha1",
317 passphrase,
318 CHROME_SALT,
319 CHROME_PBKDF2_ITERATIONS,
320 dklen=CHROME_KEY_LENGTH,
321 )
322
323
324 def _decrypt_v10_value(encrypted_value: bytes, aes_key: bytes, db_version: int) -> Optional[str]:
325 """Decrypt a Chrome v10-encrypted cookie value in-process (zero subprocesses).
326
327 Uses macOS CommonCrypto via ctypes on Darwin (with a pure-Python fallback)
328 so ``aes_key`` never leaves process memory.
329 For Chrome 130+ (db_version >= 24), strips 32-byte SHA-256 prefix after decryption.
330
331 Returns decrypted string or None on failure.
332 """
333 if not isinstance(encrypted_value, (bytes, bytearray, memoryview)):
334 return None
335 raw_bytes = bytes(encrypted_value)
336 if not raw_bytes.startswith(b"v10"):
337 return None
338 ciphertext = raw_bytes[3:]
339 if not ciphertext:
340 return None
341
342 try:
343 decrypted = _decrypt_aes128_cbc(ciphertext, aes_key, CHROME_IV)
344 if decrypted is None:
345 return None
346
347 # Chrome 130+ (db version >= 24): strip 32-byte SHA-256 prefix
348 if db_version >= 24 and len(decrypted) >= 32:
349 decrypted = decrypted[32:]
350
351 return decrypted.decode("utf-8", errors="replace")
352 except Exception as e:
353 logger.debug("Chrome cookie decryption error: %s", e)
354 return None
355
356
357 def _remove_pkcs7_padding(data: bytes) -> Optional[bytes]:
358 """Remove PKCS7 padding from decrypted data.
359
360 The last byte indicates the number of padding bytes added.
361 All padding bytes must have the same value.
362
363 Returns unpadded data or None if padding is invalid.
364 """
365 if not data:
366 return None
367 pad_len = data[-1]
368 if pad_len < 1 or pad_len > 16:
369 return None
370 # Verify all padding bytes match
371 if data[-pad_len:] != bytes([pad_len]) * pad_len:
372 return None
373 return data[:-pad_len]
374
375
376 def _get_db_version(cursor: sqlite3.Cursor) -> int:
377 """Get Chrome cookie database version from the meta table.
378
379 Returns 0 if meta table doesn't exist or version can't be read.
380 """
381 try:
382 cursor.execute("SELECT value FROM meta WHERE key = 'version'")
383 row = cursor.fetchone()
384 if row:
385 return int(row[0])
386 except Exception:
387 pass
388 return 0
389
390
391 def _extract_chromium_cookies_macos(
392 db_path: Path,
393 keychain_service: str,
394 domain: str,
395 cookie_names: list[str],
396 key_cache: Optional[dict[str, Optional[bytes]]] = None,
397 ) -> Optional[dict[str, str]]:
398 """Extract cookies from any Chromium-based browser on macOS.
399
400 Snapshots committed Cookies database state to a temp file, reads specified cookies
401 from a single non-expired scope, and decrypts v10-encrypted values in-process using
402 the Keychain-stored key.
403
404 Args:
405 db_path: Path to the browser's Cookies SQLite file.
406 keychain_service: macOS Keychain service name (e.g. "Chrome Safe Storage").
407 domain: Cookie domain to match (e.g., ".twitter.com", ".x.com").
408 cookie_names: List of cookie names to extract.
409
410 Returns:
411 Dict mapping cookie name to decrypted value from one scope, or None on failure.
412 Only includes cookies that were successfully found and decrypted.
413 """
414 try:
415 db_path.stat()
416 except PermissionError:
417 raise
418 except OSError:
419 logger.info("%s cookies database not found at %s", keychain_service, db_path)
420 return None
421
422 wanted = domain.strip().lstrip(".").lower()
423 if not wanted or not cookie_names:
424 return None
425 preferred_host = domain.strip().lower()
426 if preferred_host not in (wanted, f".{wanted}"):
427 preferred_host = f".{wanted}"
428
429 # The backup includes committed WAL updates while the browser is running.
430 tmp_path = None
431 try:
432 tmp_fd, tmp_path = tempfile.mkstemp(suffix=".sqlite")
433 os.close(tmp_fd)
434 # Snapshot content only; preserve mkstemp's 0600 permissions.
435 copy_snapshot(db_path, tmp_path)
436 _lock_temp_cookie_copy(tmp_path)
437 except Exception as e:
438 browser_read_denied = isinstance(e, PermissionError) and e.filename == str(db_path)
439 if browser_read_denied:
440 logger.info("Permission denied reading %s cookies database", keychain_service)
441 else:
442 logger.info("Failed to copy %s cookies database: %s", keychain_service, e)
443 _unlink_sqlite_temp_files(tmp_path)
444 if browser_read_denied:
445 raise
446 return None
447
448 conn = None
449 try:
450 conn = sqlite3.connect(tmp_path)
451 cursor = conn.cursor()
452
453 db_version = _get_db_version(cursor)
454 logger.debug("%s cookie DB version: %d", keychain_service, db_version)
455
456 cursor.execute("PRAGMA table_info(cookies)")
457 col_map = {str(row[1]).lower(): str(row[1]) for row in cursor.fetchall()}
458 if not {"name", "value", "encrypted_value", "host_key"}.issubset(col_map):
459 logger.info("%s cookies table missing required columns", keychain_service)
460 return None
461
462 path_expr = col_map["path"] if "path" in col_map else "'/'"
463 expires_expr = col_map["expires_utc"] if "expires_utc" in col_map else "0"
464 secure_expr = col_map["is_secure"] if "is_secure" in col_map else "1"
465 httponly_expr = col_map["is_httponly"] if "is_httponly" in col_map else "1"
466 partition_expr = (
467 col_map["top_frame_site_key"] if "top_frame_site_key" in col_map else "''"
468 )
469 cross_site_expr = (
470 col_map["has_cross_site_ancestor"]
471 if "has_cross_site_ancestor" in col_map
472 else "0"
473 )
474
475 placeholders = ",".join("?" for _ in cookie_names)
476 query = (
477 f"SELECT name, value, encrypted_value, host_key, "
478 f"{path_expr}, {expires_expr}, {secure_expr}, {httponly_expr}, "
479 f"{partition_expr}, {cross_site_expr} "
480 f"FROM cookies "
481 f"WHERE LOWER(host_key) IN (?, ?) AND name IN ({placeholders})"
482 )
483 params = [wanted, f".{wanted}"] + list(cookie_names)
484 cursor.execute(query, params)
485
486 now_chrome_utc = (int(time.time()) + _CHROME_EPOCH_OFFSET_SECONDS) * 1_000_000
487 allowed_hosts = (wanted, f".{wanted}")
488 scopes: dict[
489 tuple[str, str, tuple[str, int]],
490 dict[str, list[tuple[int, int, bool, int, Any, Any]]],
491 ] = {}
492 for (
493 name,
494 value,
495 encrypted_value,
496 host_key,
497 path,
498 expires_utc,
499 is_secure,
500 is_httponly,
501 top_frame_site_key,
502 has_cross_site_ancestor,
503 ) in cursor.fetchall():
504 try:
505 expires_val = int(expires_utc) if expires_utc is not None else 0
506 except (TypeError, ValueError):
507 continue
508 if expires_val != 0 and expires_val <= now_chrome_utc:
509 continue
510 host_norm = str(host_key or "").strip().lower()
511 if host_norm not in allowed_hosts:
512 continue
513 path_norm = path if isinstance(path, str) and path else "/"
514 partition_site = str(top_frame_site_key or "").strip()
515 cross_site_flag = 1 if has_cross_site_ancestor else 0
516 partition_key = (partition_site, cross_site_flag)
517 secure_flag = 1 if is_secure else 0
518 httponly_flag = 1 if is_httponly else 0
519 # Host-only (x.com) and domain (.x.com) cookies apply to the same
520 # apex origin per RFC 6265; pair them within one (path, partition).
521 # Chromium CHIPS partitions are keyed by (top_frame_site_key, has_cross_site_ancestor).
522 scope_key = (host_norm.lstrip("."), path_norm, partition_key)
523 scopes.setdefault(scope_key, {}).setdefault(str(name), []).append(
524 (
525 secure_flag,
526 httponly_flag,
527 host_norm == preferred_host,
528 expires_val,
529 value,
530 encrypted_value,
531 )
532 )
533
534 if not scopes:
535 logger.info("No matching cookies found in %s for domain %s", keychain_service, domain)
536 return None
537
538 requested = list(dict.fromkeys(cookie_names))
539 for by_name in scopes.values():
540 for candidates in by_name.values():
541 candidates.sort(
542 key=lambda item: (
543 item[0] == 0,
544 item[1] == 0,
545 not item[2],
546 0 if item[3] == 0 else -item[3],
547 )
548 )
549
550 def _scope_sort_key(
551 item: tuple[
552 tuple[str, str, tuple[str, int]],
553 dict[str, list[tuple[int, int, bool, int, Any, Any]]],
554 ]
555 ) -> tuple[Any, ...]:
556 (host_base, path_norm, (partition_site, cross_site_flag)), by_name = item
557 has_all_names = all(name in by_name for name in requested)
558 all_secure = all(cands[0][0] == 1 for cands in by_name.values())
559 all_httponly = all(cands[0][1] == 1 for cands in by_name.values())
560 return (
561 not has_all_names,
562 partition_site != "",
563 cross_site_flag != 0,
564 path_norm != "/",
565 not all_secure,
566 not all_httponly,
567 path_norm,
568 host_base,
569 partition_site,
570 cross_site_flag,
571 )
572
573 aes_key = None
574 key_fetched = False
575 best_partial: Optional[dict[str, str]] = None
576
577 for _scope_key, by_name in sorted(scopes.items(), key=_scope_sort_key):
578 scope_results: dict[str, str] = {}
579 for name, candidates in by_name.items():
580 for _sec, _http, _pref, _exp, value, encrypted_value in candidates:
581 if isinstance(value, str) and value:
582 scope_results[name] = value
583 break
584
585 if isinstance(encrypted_value, (bytes, bytearray, memoryview)):
586 enc_bytes = bytes(encrypted_value)
587 if enc_bytes[:3] == b"v10":
588 if not key_fetched:
589 # Fetch the Keychain key lazily — only once we actually have
590 # a non-expired encrypted cookie to decrypt.
591 if key_cache is not None and keychain_service in key_cache:
592 aes_key = key_cache[keychain_service]
593 else:
594 passphrase = _get_chromium_encryption_key(keychain_service)
595 aes_key = _derive_aes_key(passphrase) if passphrase else None
596 if key_cache is not None:
597 key_cache[keychain_service] = aes_key
598 key_fetched = True
599 if aes_key is None:
600 logger.debug("Skipping encrypted cookie %s — no Keychain access", name)
601 continue
602 decrypted = _decrypt_v10_value(enc_bytes, aes_key, db_version)
603 if decrypted:
604 scope_results[name] = decrypted
605 break
606 logger.debug("Failed to decrypt cookie %s", name)
607 elif enc_bytes:
608 logger.debug(
609 "Unknown encryption for cookie %s (prefix: %r)",
610 name,
611 enc_bytes[:3],
612 )
613 elif encrypted_value:
614 logger.debug("Malformed encrypted cookie %s", name)
615
616 if scope_results:
617 if all(name in scope_results for name in requested):
618 return scope_results
619 if best_partial is None:
620 best_partial = scope_results
621
622 if not best_partial:
623 logger.info("No matching cookies found in %s for domain %s", keychain_service, domain)
624 return None
625
626 return best_partial
627
628 except sqlite3.Error as e:
629 logger.info("Failed to read %s cookies database: %s", keychain_service, e)
630 return None
631 except Exception as e:
632 logger.info("Unexpected error reading %s cookies: %s", keychain_service, e)
633 return None
634 finally:
635 if conn is not None:
636 conn.close()
637 _unlink_sqlite_temp_files(tmp_path)
638
639
640 def extract_chrome_cookies_macos(domain: str, cookie_names: list[str]) -> Optional[dict[str, str]]:
641 """Extract cookies from Chrome on macOS.
642
643 Resolves the cookie DB through the shared profile finder so Chrome gets the
644 same modern ``Default/Network/Cookies`` (Chromium >= 96) and legacy
645 ``Default/Cookies`` probing as the rest of the Chromium family.
646 """
647 return _extract_chromium_cookies_any_profile(
648 CHROME_BASE_DIR, "Chrome Safe Storage", domain, cookie_names
649 )
650
651
652 def _profile_cookie_db(
653 profile_dir: Path, denials: Optional[list[PermissionError]] = None
654 ) -> Optional[Path]:
655 """Return the Cookies DB inside a profile dir, or None.
656
657 Prefers the modern ``Network/Cookies`` location (Chromium >= 96 moved the
658 cookie store into a per-profile ``Network/`` subdirectory) and falls back
659 to the legacy flat ``Cookies`` file. Different browsers and versions use
660 different layouts, so both are probed.
661 """
662 denied: list[PermissionError] = []
663 for rel in ("Network/Cookies", "Cookies"):
664 candidate = profile_dir / rel
665 try:
666 if path_exists(candidate):
667 if denials is not None:
668 denials.extend(denied)
669 return candidate
670 except PermissionError as exc:
671 denied.append(exc)
672 if denials is not None:
673 denials.extend(denied)
674 elif denied:
675 raise denied[0]
676 return None
677
678
679 def _find_chromium_cookies_db(base_dir: Path) -> Optional[Path]:
680 """Find a Chromium-based browser's Cookies database under base_dir.
681
682 Checks the Default profile first, then the base dir itself (Opera's flat
683 layout), then numbered "Profile N" directories by most-recently-modified.
684 Each location is probed for both the modern ``Network/Cookies`` and legacy
685 ``Cookies`` paths (see _profile_cookie_db). Chromium browsers create extra
686 profiles as "Profile 1", "Profile 2", etc. alongside Default; the most
687 recently used one is the likeliest to hold current cookies. Lexicographic
688 sort would visit "Profile 10" before "Profile 2", which can return the
689 wrong profile, so we sort by mtime.
690
691 Kept for backward compatibility; new code should use
692 _find_all_chromium_cookies_dbs() to search across all profiles.
693 """
694 dbs = _find_all_chromium_cookies_dbs(base_dir)
695 return dbs[0] if dbs else None
696
697
698 def _find_all_chromium_cookies_dbs(
699 base_dir: Path, denials: Optional[list[PermissionError]] = None
700 ) -> list[Path]:
701 """Return ALL candidate Cookies DBs under base_dir, best-guess order first.
702
703 Order: Default, the base dir itself (Opera's flat layout), then numbered
704 "Profile N" dirs by most-recently-modified. Unlike _find_chromium_cookies_db
705 (which returns the first DB that merely EXISTS), this returns every profile
706 so the caller can pick the one that actually holds the target domain's
707 cookies. Needed because a logged-in session often lives in a non-Default
708 profile while Default still has a (guest-only) cookie DB.
709 """
710 paths: list[Path] = []
711 seen: set[Path] = set()
712 denied: list[PermissionError] = []
713
714 def add(p: Optional[Path]) -> None:
715 if p is not None and p not in seen:
716 seen.add(p)
717 paths.append(p)
718
719 add(_profile_cookie_db(base_dir / "Default", denied))
720 add(_profile_cookie_db(base_dir, denied))
721 try:
722 candidates = []
723 for child in base_dir.iterdir():
724 if not child.name.startswith("Profile "):
725 continue
726 try:
727 if path_is_dir(child):
728 candidates.append((child.stat().st_mtime, child))
729 except PermissionError as exc:
730 denied.append(exc)
731 for _, child in sorted(candidates, reverse=True):
732 add(_profile_cookie_db(child, denied))
733 except PermissionError as exc:
734 denied.append(exc)
735 except OSError:
736 pass
737 if denials is not None:
738 denials.extend(denied)
739 elif denied and not paths:
740 raise denied[0]
741 return paths
742
743
744 def _extract_chromium_cookies_any_profile(
745 base_dir: Path, keychain_service: str, domain: str, cookie_names: list[str]
746 ) -> Optional[dict[str, str]]:
747 """Try every profile under base_dir and return the best cookie match.
748
749 Returns the first profile that yields ALL requested cookie_names. If no
750 profile has the complete set, returns the first partial match found, or
751 None if no profile yielded any. This fixes the single-profile limitation
752 where a guest-only Default profile shadowed a logged-in "Profile N".
753 """
754 denials: list[PermissionError] = []
755 db_paths = _find_all_chromium_cookies_dbs(base_dir, denials)
756 if not db_paths:
757 if denials:
758 raise denials[0]
759 logger.info("%s cookies database not found under %s", keychain_service, base_dir)
760 return None
761 best: Optional[dict[str, str]] = None
762 key_cache: dict[str, Optional[bytes]] = {}
763 for db_path in db_paths:
764 try:
765 got = _extract_chromium_cookies_macos(
766 db_path, keychain_service, domain, cookie_names, key_cache=key_cache
767 )
768 except PermissionError as exc:
769 denials.append(exc)
770 continue
771 if got:
772 if all(name in got for name in cookie_names):
773 logger.debug("Found complete cookie set for %s in %s", domain, db_path)
774 return got
775 if best is None:
776 best = got
777 if denials:
778 raise denials[0]
779 return best
780
781
782 def _find_brave_cookies_db() -> Optional[Path]:
783 """Find Brave's Cookies database on macOS (Default, then Profile N)."""
784 return _find_chromium_cookies_db(BRAVE_BASE_DIR)
785
786
787 def extract_brave_cookies_macos(domain: str, cookie_names: list[str]) -> Optional[dict[str, str]]:
788 """Extract cookies from Brave on macOS.
789
790 Brave uses the same v10 AES-128-CBC encryption as Chrome; only the DB
791 path and Keychain service name differ.
792 """
793 return _extract_chromium_cookies_any_profile(
794 BRAVE_BASE_DIR, "Brave Safe Storage", domain, cookie_names
795 )
796
797
798 def extract_chromium_browser_cookies_macos(
799 browser: str, domain: str, cookie_names: list[str]
800 ) -> Optional[dict[str, str]]:
801 """Extract cookies from a registry-defined Chromium browser on macOS.
802
803 Covers every browser in CHROMIUM_BROWSER_PROFILES (Edge, Vivaldi, Opera,
804 Arc, Dia, Chromium). They all reuse Chrome's v10 AES-128-CBC encryption; only
805 the profile directory and Keychain service name differ.
806 """
807 spec = CHROMIUM_BROWSER_PROFILES.get(browser)
808 if spec is None:
809 logger.debug("Unknown Chromium browser: %s", browser)
810 return None
811 base_dir, keychain_service = spec
812 return _extract_chromium_cookies_any_profile(
813 base_dir, keychain_service, domain, cookie_names
814 )
815
815 lines PYTHON