Debian Codegraph @

gallery_dl/cookies.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2022-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 # Adapted from yt-dlp's cookies module.
10 # https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/cookies.py
11
12 import binascii
13 import ctypes
14 import logging
15 import os
16 import shutil
17 import sqlite3
18 import struct
19 import subprocess
20 import sys
21 import tempfile
22 from hashlib import pbkdf2_hmac
23 from http.cookiejar import Cookie
24 from . import aes, text, util
25
26
27 SUPPORTED_BROWSERS_CHROMIUM = {
28 "brave", "chrome", "chromium", "edge", "opera", "thorium", "vivaldi"}
29 SUPPORTED_BROWSERS_FIREFOX = {"firefox", "librewolf", "zen", "floorp"}
30 SUPPORTED_BROWSERS_WEBKIT = {"safari", "orion"}
31 SUPPORTED_BROWSERS = \
32 SUPPORTED_BROWSERS_CHROMIUM \
33 | SUPPORTED_BROWSERS_FIREFOX \
34 | SUPPORTED_BROWSERS_WEBKIT
35
36 logger = logging.getLogger("cookies")
37
38
39 def load_cookies(browser_specification):
40 browser_name, profile, keyring, container, domain = \
41 _parse_browser_specification(*browser_specification)
42 if browser_name in SUPPORTED_BROWSERS_FIREFOX:
43 return load_cookies_firefox(browser_name, profile, container, domain)
44 elif browser_name in SUPPORTED_BROWSERS_WEBKIT:
45 return load_cookies_webkit(browser_name, profile, domain)
46 elif browser_name in SUPPORTED_BROWSERS_CHROMIUM:
47 return load_cookies_chromium(browser_name, profile, keyring, domain)
48 else:
49 raise ValueError(f"unknown browser '{browser_name}'")
50
51
52 def load_cookies_firefox(browser_name, profile=None,
53 container=None, domain=None):
54 path, container_id = _firefox_cookies_database(
55 browser_name, profile, container)
56
57 sql = ("SELECT name, value, host, path, isSecure, expiry "
58 "FROM moz_cookies")
59 conditions = []
60 parameters = []
61
62 if container_id is False:
63 conditions.append("NOT INSTR(originAttributes,'userContextId=')")
64 elif container_id:
65 uid = f"%userContextId={container_id}"
66 conditions.append("originAttributes LIKE ? OR originAttributes LIKE ?")
67 parameters += (uid, uid + "&%")
68
69 if domain:
70 if domain[0] == ".":
71 conditions.append("host == ? OR host LIKE ?")
72 parameters += (domain[1:], "%" + domain)
73 else:
74 conditions.append("host == ? OR host == ?")
75 parameters += (domain, "." + domain)
76
77 if conditions:
78 sql = f"{sql} WHERE ( {' ) AND ( '.join(conditions)} )"
79
80 with DatabaseConnection(path) as db:
81 cookies = [
82 Cookie(
83 0, name, value, None, False,
84 domain, True if domain else False,
85 domain[0] == "." if domain else False,
86 path, True if path else False, secure, expires,
87 False, None, None, {},
88 )
89 for name, value, domain, path, secure, expires in db.execute(
90 sql, parameters)
91 ]
92
93 _log_info("Extracted %s cookies from %s",
94 len(cookies), browser_name.capitalize())
95 return cookies
96
97
98 def load_cookies_webkit(browser_name, profile=None, domain=None):
99 """Ref.: https://github.com/libyal/dtformats/blob
100 /main/documentation/Safari%20Cookies.asciidoc
101 - This data appears to be out of date
102 but the important parts of the database structure is the same
103 - There are a few bytes here and there
104 which are skipped during parsing
105 """
106 if browser_name == "safari":
107 with _safari_cookies_database() as fp:
108 data = fp.read()
109 elif browser_name == "orion":
110 with _orion_cookies_database() as fp:
111 data = fp.read()
112 else:
113 raise ValueError(f"unknown webkit browser '{browser_name}'")
114
115 page_sizes, body_start = _webkit_parse_cookies_header(data)
116 p = DataParser(data[body_start:])
117
118 cookies = []
119 for page_size in page_sizes:
120 _webkit_parse_cookies_page(p.read_bytes(page_size), cookies)
121 _log_info("Extracted %s cookies from %s",
122 len(cookies), browser_name.capitalize())
123
124 return cookies
125
126
127 def load_cookies_chromium(browser_name, profile=None,
128 keyring=None, domain=None):
129 config = _chromium_browser_settings(browser_name)
130 path = _chromium_cookies_database(profile, config)
131 _log_debug("Extracting cookies from %s", path)
132
133 if domain:
134 if domain[0] == ".":
135 condition = " WHERE host_key == ? OR host_key LIKE ?"
136 parameters = (domain[1:], "%" + domain)
137 else:
138 condition = " WHERE host_key == ? OR host_key == ?"
139 parameters = (domain, "." + domain)
140 else:
141 condition = ""
142 parameters = ()
143
144 with DatabaseConnection(path) as db:
145 db.text_factory = bytes
146 cursor = db.cursor()
147
148 try:
149 meta_version = int(cursor.execute(
150 "SELECT value FROM meta WHERE key = 'version'").fetchone()[0])
151 except Exception as exc:
152 _log_warning("Failed to get cookie database meta version (%s: %s)",
153 exc.__class__.__name__, exc)
154 meta_version = 0
155
156 try:
157 rows = cursor.execute(
158 "SELECT host_key, name, value, encrypted_value, path, "
159 "expires_utc, is_secure FROM cookies" + condition, parameters)
160 except sqlite3.OperationalError:
161 rows = cursor.execute(
162 "SELECT host_key, name, value, encrypted_value, path, "
163 "expires_utc, secure FROM cookies" + condition, parameters)
164
165 failed_cookies = 0
166 unencrypted_cookies = 0
167 decryptor = _chromium_cookie_decryptor(
168 config["directory"], config["keyring"], keyring, meta_version)
169
170 cookies = []
171 for domain, name, value, enc_value, path, expires, secure in rows:
172
173 if not value and enc_value: # encrypted
174 value = decryptor.decrypt(enc_value)
175 if value is None:
176 failed_cookies += 1
177 continue
178 else:
179 value = value.decode()
180 unencrypted_cookies += 1
181
182 if expires:
183 # https://stackoverflow.com/a/43520042
184 expires = int(expires) // 1000000 - 11644473600
185 else:
186 expires = None
187
188 domain = domain.decode()
189 path = path.decode()
190 name = name.decode()
191
192 cookies.append(Cookie(
193 0, name, value, None, False,
194 domain, True if domain else False,
195 domain[0] == "." if domain else False,
196 path, True if path else False, secure, expires,
197 False, None, None, {},
198 ))
199
200 if failed_cookies > 0:
201 failed_message = f" ({failed_cookies} could not be decrypted)"
202 else:
203 failed_message = ""
204
205 _log_info("Extracted %s cookies from %s%s",
206 len(cookies), browser_name.capitalize(), failed_message)
207 counts = decryptor.cookie_counts
208 counts["unencrypted"] = unencrypted_cookies
209 _log_debug("version breakdown: %s", counts)
210 return cookies
211
212
213 # --------------------------------------------------------------------
214 # firefox
215
216 def _firefox_cookies_database(browser_name, profile=None, container=None):
217 if not profile:
218 search_root = _firefox_browser_directory(browser_name)
219 elif _is_path(profile):
220 search_root = profile
221 else:
222 search_root = _firefox_browser_directory(browser_name)
223 if isinstance(search_root, str):
224 search_root = os.path.join(search_root, profile)
225 else:
226 search_root = [os.path.join(dir, profile) for dir in search_root]
227
228 path = _find_most_recently_used_file(search_root, "cookies.sqlite")
229 if path is None:
230 raise FileNotFoundError(f"Unable to find {browser_name.capitalize()} "
231 f"cookies database")
232
233 _log_debug("Extracting cookies from %s", path)
234
235 if not container or container == "none":
236 container_id = False
237 _log_debug("Only loading cookies not belonging to any container")
238
239 elif container == "all":
240 container_id = None
241
242 else:
243 containers_path = os.path.join(
244 os.path.dirname(path), "containers.json")
245
246 try:
247 with open(containers_path, encoding="utf-8") as fp:
248 identities = util.json_loads(fp.read())["identities"]
249 except OSError:
250 _log_error("Unable to read Firefox container database at '%s'",
251 containers_path)
252 raise
253 except KeyError:
254 identities = ()
255
256 for context in identities:
257 if c := context.get("name"):
258 if c == container:
259 break
260 elif c := context.get("l10nId"):
261 if c.startswith("user-context-") and c[13:] == container:
262 break
263 if c.rpartition("-")[2] == container:
264 break
265 elif c := context.get("l10nID"):
266 if text.extr(c, "userContext", ".label") == container:
267 break
268 else:
269 raise ValueError(f"Unable to find Firefox container '{container}'")
270 container_id = context["userContextId"]
271 _log_debug("Only loading cookies from container '%s' (ID %s)",
272 container, container_id)
273
274 return path, container_id
275
276
277 def _firefox_browser_directory(browser_name):
278 join = os.path.join
279
280 if sys.platform in ("win32", "cygwin"):
281 appdata = os.path.expandvars("%APPDATA%")
282 return {
283 "firefox" : join(appdata, R"Mozilla\Firefox\Profiles"),
284 "librewolf": join(appdata, R"librewolf\Profiles"),
285 "zen" : join(appdata, R"zen\Profiles"),
286 "floorp" : join(appdata, R"Floorp\Profiles")
287 }[browser_name]
288 elif sys.platform == "darwin":
289 appdata = os.path.expanduser("~/Library/Application Support")
290 return {
291 "firefox" : join(appdata, R"Firefox/Profiles"),
292 "librewolf": join(appdata, R"librewolf/Profiles"),
293 "zen" : join(appdata, R"zen/Profiles"),
294 "floorp" : join(appdata, R"Floorp/Profiles")
295 }[browser_name]
296 else:
297 home = os.path.expanduser("~")
298 config = (os.environ.get("XDG_CONFIG_HOME") or
299 os.path.expanduser("~/.config"))
300 if browser_name == "firefox":
301 return (
302 # versions >= 147
303 join(config, "mozilla/firefox"),
304 # versions <= 146
305 home + "/.mozilla/firefox",
306 # Flatpak
307 home + "/.var/app/org.mozilla.firefox/config/mozilla/firefox",
308 home + "/.var/app/org.mozilla.firefox/.mozilla/firefox",
309 # Snap
310 home + "/snap/firefox/common/.mozilla/firefox",
311 )
312 return (
313 join(config, browser_name),
314 f"{home}/.{browser_name}",
315 )
316
317
318 # --------------------------------------------------------------------
319 # safari/orion/webkit
320
321
322 def _safari_cookies_database():
323 try:
324 path = os.path.expanduser("~/Library/Cookies/Cookies.binarycookies")
325 return open(path, "rb")
326 except FileNotFoundError:
327 _log_debug("Trying secondary cookie location")
328 path = os.path.expanduser("~/Library/Containers/com.apple.Safari/Data"
329 "/Library/Cookies/Cookies.binarycookies")
330 return open(path, "rb")
331
332
333 def _orion_cookies_database():
334 path = os.path.expanduser(
335 "~/Library/HTTPStorages/com.kagi.kagimacOS.binarycookies")
336 return open(path, "rb")
337
338
339 def _webkit_parse_cookies_header(data):
340 p = DataParser(data)
341 p.expect_bytes(b"cook", "database signature")
342 number_of_pages = p.read_uint(big_endian=True)
343 page_sizes = [p.read_uint(big_endian=True)
344 for _ in range(number_of_pages)]
345 return page_sizes, p.cursor
346
347
348 def _webkit_parse_cookies_page(data, cookies, domain=None):
349 p = DataParser(data)
350 p.expect_bytes(b"\x00\x00\x01\x00", "page signature")
351 number_of_cookies = p.read_uint()
352 record_offsets = [p.read_uint() for _ in range(number_of_cookies)]
353 if number_of_cookies == 0:
354 _log_debug("Cookies page of size %s has no cookies", len(data))
355 return
356
357 p.skip_to(record_offsets[0], "unknown page header field")
358
359 for i, record_offset in enumerate(record_offsets):
360 p.skip_to(record_offset, "space between records")
361 record_length = _webkit_parse_cookies_record(
362 data[record_offset:], cookies, domain)
363 p.read_bytes(record_length)
364 p.skip_to_end("space in between pages")
365
366
367 def _webkit_parse_cookies_record(data, cookies, host=None):
368 p = DataParser(data)
369 record_size = p.read_uint()
370 p.skip(4, "unknown record field 1")
371 flags = p.read_uint()
372 is_secure = True if (flags & 0x0001) else False
373 p.skip(4, "unknown record field 2")
374 domain_offset = p.read_uint()
375 name_offset = p.read_uint()
376 path_offset = p.read_uint()
377 value_offset = p.read_uint()
378 p.skip(8, "unknown record field 3")
379 expiration_date = _mac_absolute_time_to_posix(p.read_double())
380 _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841
381
382 try:
383 p.skip_to(domain_offset)
384 domain = p.read_cstring()
385
386 if host:
387 if host[0] == ".":
388 if host[1:] != domain and not domain.endswith(host):
389 return record_size
390 else:
391 if host != domain and ("." + host) != domain:
392 return record_size
393
394 p.skip_to(name_offset)
395 name = p.read_cstring()
396
397 p.skip_to(path_offset)
398 path = p.read_cstring()
399
400 p.skip_to(value_offset)
401 value = p.read_cstring()
402 except UnicodeDecodeError:
403 _log_warning("Failed to parse WebKit cookie")
404 return record_size
405
406 p.skip_to(record_size, "space at the end of the record")
407
408 cookies.append(Cookie(
409 0, name, value, None, False,
410 domain, True if domain else False,
411 domain[0] == "." if domain else False,
412 path, True if path else False, is_secure, expiration_date,
413 False, None, None, {},
414 ))
415
416 return record_size
417
418
419 # --------------------------------------------------------------------
420 # chromium
421
422 def _chromium_cookies_database(profile, config):
423 if profile is None:
424 search_root = config["directory"]
425 elif _is_path(profile):
426 search_root = profile
427 config["directory"] = (os.path.dirname(profile)
428 if config["profiles"] else profile)
429 elif config["profiles"]:
430 if isinstance(search_root := config["directory"], str):
431 search_root = os.path.join(search_root, profile)
432 else:
433 search_root = [os.path.join(dir, profile) for dir in search_root]
434 else:
435 _log_warning("%s does not support profiles", config["browser"])
436 search_root = config["directory"]
437
438 path = _find_most_recently_used_file(search_root, "Cookies")
439 if path is None:
440 raise FileNotFoundError(f"Unable to find {config['browser']} cookies "
441 f"database in '{search_root}'")
442 return path
443
444
445 def _chromium_browser_settings(browser_name):
446 # https://chromium.googlesource.com/chromium
447 # /src/+/HEAD/docs/user_data_dir.md
448 join = os.path.join
449
450 if sys.platform in ("win32", "cygwin"):
451 appdata_local = os.path.expandvars("%LOCALAPPDATA%")
452 appdata_roaming = os.path.expandvars("%APPDATA%")
453 browser_dir = {
454 "brave" : (join(appdata_local,
455 R"BraveSoftware\Brave-Browser\User Data"),
456 join(appdata_local,
457 R"BraveSoftware\Brave-Origin\User Data")),
458 "chrome" : join(appdata_local, R"Google\Chrome\User Data"),
459 "chromium": join(appdata_local, R"Chromium\User Data"),
460 "edge" : join(appdata_local, R"Microsoft\Edge\User Data"),
461 "opera" : join(appdata_roaming, R"Opera Software\Opera Stable"),
462 "thorium" : join(appdata_local, R"Thorium\User Data"),
463 "vivaldi" : join(appdata_local, R"Vivaldi\User Data"),
464 }[browser_name]
465
466 elif sys.platform == "darwin":
467 appdata = os.path.expanduser("~/Library/Application Support")
468 browser_dir = {
469 "brave" : (join(appdata, "BraveSoftware/Brave-Browser"),
470 join(appdata, "BraveSoftware/Brave-Origin")),
471 "chrome" : join(appdata, "Google/Chrome"),
472 "chromium": join(appdata, "Chromium"),
473 "edge" : join(appdata, "Microsoft Edge"),
474 "opera" : join(appdata, "com.operasoftware.Opera"),
475 "thorium" : join(appdata, "Thorium"),
476 "vivaldi" : join(appdata, "Vivaldi"),
477 }[browser_name]
478
479 else:
480 config = (os.environ.get("XDG_CONFIG_HOME") or
481 os.path.expanduser("~/.config"))
482 browser_dir = {
483 "brave" : (join(config, "BraveSoftware/Brave-Browser"),
484 join(config, "BraveSoftware/Brave-Origin")),
485 "chrome" : join(config, "google-chrome"),
486 "chromium": join(config, "chromium"),
487 "edge" : join(config, "microsoft-edge"),
488 "opera" : join(config, "opera"),
489 "thorium" : join(config, "Thorium"),
490 "vivaldi" : join(config, "vivaldi"),
491 }[browser_name]
492
493 # Linux keyring names can be determined by snooping on dbus
494 # while opening the browser in KDE:
495 # dbus-monitor "interface="org.kde.KWallet"" "type=method_return"
496 keyring_name = {
497 "brave" : "Brave",
498 "chrome" : "Chrome",
499 "chromium": "Chromium",
500 "edge" : "Microsoft Edge" if sys.platform == "darwin" else
501 "Chromium",
502 "opera" : "Opera" if sys.platform == "darwin" else "Chromium",
503 "thorium" : "Thorium",
504 "vivaldi" : "Vivaldi" if sys.platform == "darwin" else "Chrome",
505 }[browser_name]
506
507 browsers_without_profiles = {"opera"}
508
509 return {
510 "browser" : browser_name,
511 "directory": browser_dir,
512 "keyring" : keyring_name,
513 "profiles" : browser_name not in browsers_without_profiles
514 }
515
516
517 def _chromium_cookie_decryptor(
518 browser_root, browser_keyring_name, keyring=None, meta_version=0):
519 if sys.platform in ("win32", "cygwin"):
520 return WindowsChromiumCookieDecryptor(
521 browser_root, meta_version)
522 elif sys.platform == "darwin":
523 return MacChromiumCookieDecryptor(
524 browser_keyring_name, meta_version)
525 else:
526 return LinuxChromiumCookieDecryptor(
527 browser_keyring_name, keyring, meta_version)
528
529
530 class ChromiumCookieDecryptor:
531 """
532 Overview:
533
534 Linux:
535 - cookies are either v10 or v11
536 - v10: AES-CBC encrypted with a fixed key
537 - v11: AES-CBC encrypted with an OS protected key (keyring)
538 - v11 keys can be stored in various places depending on the
539 activate desktop environment [2]
540
541 Mac:
542 - cookies are either v10 or not v10
543 - v10: AES-CBC encrypted with an OS protected key (keyring)
544 and more key derivation iterations than linux
545 - not v10: "old data" stored as plaintext
546
547 Windows:
548 - cookies are either v10 or not v10
549 - v10: AES-GCM encrypted with a key which is encrypted with DPAPI
550 - not v10: encrypted with DPAPI
551
552 Sources:
553 - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads
554 /main/components/os_crypt/
555 - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads
556 /main/components/os_crypt/key_storage_linux.cc
557 - KeyStorageLinux::CreateService
558 """
559
560 def decrypt(self, encrypted_value):
561 raise NotImplementedError("Must be implemented by sub classes")
562
563 @property
564 def cookie_counts(self):
565 raise NotImplementedError("Must be implemented by sub classes")
566
567
568 class LinuxChromiumCookieDecryptor(ChromiumCookieDecryptor):
569 def __init__(self, browser_keyring_name, keyring=None, meta_version=0):
570 password = _get_linux_keyring_password(browser_keyring_name, keyring)
571 self._empty_key = self.derive_key(b"")
572 self._v10_key = self.derive_key(b"peanuts")
573 self._v11_key = None if password is None else self.derive_key(password)
574 self._cookie_counts = {"v10": 0, "v11": 0, "other": 0}
575 self._offset = (32 if meta_version >= 24 else 0)
576
577 def derive_key(self, password):
578 # values from
579 # https://chromium.googlesource.com/chromium/src/+/refs/heads
580 # /main/components/os_crypt/os_crypt_linux.cc
581 return pbkdf2_sha1(password, salt=b"saltysalt",
582 iterations=1, key_length=16)
583
584 @property
585 def cookie_counts(self):
586 return self._cookie_counts
587
588 def decrypt(self, encrypted_value):
589 version = encrypted_value[:3]
590 ciphertext = encrypted_value[3:]
591
592 if version == b"v10":
593 self._cookie_counts["v10"] += 1
594 value = _decrypt_aes_cbc(ciphertext, self._v10_key, self._offset)
595
596 elif version == b"v11":
597 self._cookie_counts["v11"] += 1
598 if self._v11_key is None:
599 _log_warning("Unable to decrypt v11 cookies: no key found")
600 return None
601 value = _decrypt_aes_cbc(ciphertext, self._v11_key, self._offset)
602
603 else:
604 self._cookie_counts["other"] += 1
605 return None
606
607 if value is None:
608 value = _decrypt_aes_cbc(ciphertext, self._empty_key, self._offset)
609 if value is None:
610 _log_warning("Failed to decrypt cookie (AES-CBC)")
611 return value
612
613
614 class MacChromiumCookieDecryptor(ChromiumCookieDecryptor):
615 def __init__(self, browser_keyring_name, meta_version=0):
616 password = _get_mac_keyring_password(browser_keyring_name)
617 self._v10_key = None if password is None else self.derive_key(password)
618 self._cookie_counts = {"v10": 0, "other": 0}
619 self._offset = (32 if meta_version >= 24 else 0)
620
621 def derive_key(self, password):
622 # values from
623 # https://chromium.googlesource.com/chromium/src/+/refs/heads
624 # /main/components/os_crypt/os_crypt_mac.mm
625 return pbkdf2_sha1(password, salt=b"saltysalt",
626 iterations=1003, key_length=16)
627
628 @property
629 def cookie_counts(self):
630 return self._cookie_counts
631
632 def decrypt(self, encrypted_value):
633 version = encrypted_value[:3]
634 ciphertext = encrypted_value[3:]
635
636 if version == b"v10":
637 self._cookie_counts["v10"] += 1
638 if self._v10_key is None:
639 _log_warning("Unable to decrypt v10 cookies: no key found")
640 return None
641 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._offset)
642
643 else:
644 self._cookie_counts["other"] += 1
645 # other prefixes are considered "old data",
646 # which were stored as plaintext
647 # https://chromium.googlesource.com/chromium/src/+/refs/heads
648 # /main/components/os_crypt/os_crypt_mac.mm
649 return encrypted_value
650
651
652 class WindowsChromiumCookieDecryptor(ChromiumCookieDecryptor):
653 def __init__(self, browser_root, meta_version=0):
654 self._v10_key = _get_windows_v10_key(browser_root)
655 self._cookie_counts = {"v10": 0, "other": 0}
656 self._offset = (32 if meta_version >= 24 else 0)
657
658 @property
659 def cookie_counts(self):
660 return self._cookie_counts
661
662 def decrypt(self, encrypted_value):
663 version = encrypted_value[:3]
664 ciphertext = encrypted_value[3:]
665
666 if version == b"v10":
667 self._cookie_counts["v10"] += 1
668 if self._v10_key is None:
669 _log_warning("Unable to decrypt v10 cookies: no key found")
670 return None
671
672 # https://chromium.googlesource.com/chromium/src/+/refs/heads
673 # /main/components/os_crypt/os_crypt_win.cc
674 # kNonceLength
675 nonce_length = 96 // 8
676 # boringssl
677 # EVP_AEAD_AES_GCM_TAG_LEN
678 authentication_tag_length = 16
679
680 raw_ciphertext = ciphertext
681 nonce = raw_ciphertext[:nonce_length]
682 ciphertext = raw_ciphertext[
683 nonce_length:-authentication_tag_length]
684 authentication_tag = raw_ciphertext[-authentication_tag_length:]
685
686 return _decrypt_aes_gcm(
687 ciphertext, self._v10_key, nonce, authentication_tag,
688 self._offset)
689
690 else:
691 self._cookie_counts["other"] += 1
692 # any other prefix means the data is DPAPI encrypted
693 # https://chromium.googlesource.com/chromium/src/+/refs/heads
694 # /main/components/os_crypt/os_crypt_win.cc
695 return _decrypt_windows_dpapi(encrypted_value).decode()
696
697
698 # --------------------------------------------------------------------
699 # keyring
700
701 def _choose_linux_keyring():
702 """
703 https://chromium.googlesource.com/chromium/src/+/refs/heads
704 /main/components/os_crypt/key_storage_util_linux.cc
705 SelectBackend
706 """
707 desktop_environment = _get_linux_desktop_environment(os.environ)
708 _log_debug("Detected desktop environment: %s", desktop_environment)
709 if desktop_environment == DE_KDE:
710 return KEYRING_KWALLET
711 if desktop_environment == DE_OTHER:
712 return KEYRING_BASICTEXT
713 return KEYRING_GNOMEKEYRING
714
715
716 def _get_kwallet_network_wallet():
717 """ The name of the wallet used to store network passwords.
718
719 https://chromium.googlesource.com/chromium/src/+/refs/heads
720 /main/components/os_crypt/kwallet_dbus.cc
721 KWalletDBus::NetworkWallet
722 which does a dbus call to the following function:
723 https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html
724 Wallet::NetworkWallet
725 """
726 default_wallet = "kdewallet"
727 try:
728 proc, stdout = Popen_communicate(
729 "dbus-send", "--session", "--print-reply=literal",
730 "--dest=org.kde.kwalletd5",
731 "/modules/kwalletd5",
732 "org.kde.KWallet.networkWallet"
733 )
734
735 if proc.returncode != 0:
736 _log_warning("Failed to read NetworkWallet")
737 return default_wallet
738 else:
739 network_wallet = stdout.decode().strip()
740 _log_debug("NetworkWallet = '%s'", network_wallet)
741 return network_wallet
742 except Exception as exc:
743 _log_warning("Error while obtaining NetworkWallet (%s: %s)",
744 exc.__class__.__name__, exc)
745 return default_wallet
746
747
748 def _get_kwallet_password(browser_keyring_name):
749 _log_debug("Using kwallet-query to obtain password from kwallet")
750
751 if shutil.which("kwallet-query") is None:
752 _log_error(
753 "kwallet-query command not found. KWallet and kwallet-query "
754 "must be installed to read from KWallet. kwallet-query should be "
755 "included in the kwallet package for your distribution")
756 return b""
757
758 network_wallet = _get_kwallet_network_wallet()
759
760 try:
761 proc, stdout = Popen_communicate(
762 "kwallet-query",
763 "--read-password", browser_keyring_name + " Safe Storage",
764 "--folder", browser_keyring_name + " Keys",
765 network_wallet,
766 )
767
768 if proc.returncode != 0:
769 _log_error(f"kwallet-query failed with return code "
770 f"{proc.returncode}. Please consult the kwallet-query "
771 f"man page for details")
772 return b""
773
774 if stdout.lower().startswith(b"failed to read"):
775 _log_debug("Failed to read password from kwallet. "
776 "Using empty string instead")
777 # This sometimes occurs in KDE because chrome does not check
778 # hasEntry and instead just tries to read the value (which
779 # kwallet returns "") whereas kwallet-query checks hasEntry.
780 # To verify this:
781 # dbus-monitor "interface="org.kde.KWallet"" "type=method_return"
782 # while starting chrome.
783 # This may be a bug, as the intended behaviour is to generate a
784 # random password and store it, but that doesn't matter here.
785 return b""
786 else:
787 if stdout[-1:] == b"\n":
788 stdout = stdout[:-1]
789 return stdout
790 except Exception as exc:
791 _log_warning("Error when running kwallet-query (%s: %s)",
792 exc.__class__.__name__, exc)
793 return b""
794
795
796 def _get_gnome_keyring_password(browser_keyring_name):
797 try:
798 import secretstorage
799 except ImportError:
800 _log_error("'secretstorage' Python package not available")
801 return b""
802
803 # Gnome keyring does not seem to organise keys in the same way as KWallet,
804 # using `dbus-monitor` during startup, it can be observed that chromium
805 # lists all keys and presumably searches for its key in the list.
806 # It appears that we must do the same.
807 # https://github.com/jaraco/keyring/issues/556
808 con = secretstorage.dbus_init()
809 try:
810 col = secretstorage.get_default_collection(con)
811 label = browser_keyring_name + " Safe Storage"
812 for item in col.get_all_items():
813 if item.get_label() == label:
814 return item.get_secret()
815 else:
816 _log_error("Failed to read from GNOME keyring")
817 return b""
818 finally:
819 con.close()
820
821
822 def _get_linux_keyring_password(browser_keyring_name, keyring):
823 # Note: chrome/chromium can be run with the following flags
824 # to determine which keyring backend it has chosen to use
825 # - chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_
826 #
827 # Chromium supports --password-store=<basic|gnome|kwallet>
828 # so the automatic detection will not be sufficient in all cases.
829
830 if not keyring:
831 keyring = _choose_linux_keyring()
832 _log_debug("Chosen keyring: %s", keyring)
833
834 if keyring == KEYRING_KWALLET:
835 return _get_kwallet_password(browser_keyring_name)
836 elif keyring == KEYRING_GNOMEKEYRING:
837 return _get_gnome_keyring_password(browser_keyring_name)
838 elif keyring == KEYRING_BASICTEXT:
839 # when basic text is chosen, all cookies are stored as v10
840 # so no keyring password is required
841 return None
842 assert False, "Unknown keyring " + keyring
843
844
845 def _get_mac_keyring_password(browser_keyring_name):
846 _log_debug("Using find-generic-password to obtain "
847 "password from OSX keychain")
848 try:
849 proc, stdout = Popen_communicate(
850 "security", "find-generic-password",
851 "-w", # write password to stdout
852 "-a", browser_keyring_name, # match "account"
853 "-s", browser_keyring_name + " Safe Storage", # match "service"
854 )
855
856 if stdout[-1:] == b"\n":
857 stdout = stdout[:-1]
858 return stdout
859 except Exception as exc:
860 _log_warning("Error when using find-generic-password (%s: %s)",
861 exc.__class__.__name__, exc)
862 return None
863
864
865 def _get_windows_v10_key(browser_root):
866 path = _find_most_recently_used_file(browser_root, "Local State")
867 if path is None:
868 _log_error("Unable to find Local State file")
869 return None
870 _log_debug("Found Local State file at '%s'", path)
871 with open(path, encoding="utf-8") as fp:
872 data = util.json_loads(fp.read())
873 try:
874 base64_key = data["os_crypt"]["encrypted_key"]
875 except KeyError:
876 _log_error("Unable to find encrypted key in Local State")
877 return None
878 encrypted_key = binascii.a2b_base64(base64_key)
879 prefix = b"DPAPI"
880 if not encrypted_key.startswith(prefix):
881 _log_error("Invalid Local State key")
882 return None
883 return _decrypt_windows_dpapi(encrypted_key[len(prefix):])
884
885
886 # --------------------------------------------------------------------
887 # utility
888
889 class ParserError(Exception):
890 pass
891
892
893 class DataParser:
894 def __init__(self, data):
895 self.cursor = 0
896 self._data = data
897
898 def read_bytes(self, num_bytes):
899 if num_bytes < 0:
900 raise ParserError(f"invalid read of {num_bytes} bytes")
901 end = self.cursor + num_bytes
902 if end > len(self._data):
903 raise ParserError("reached end of input")
904 data = self._data[self.cursor:end]
905 self.cursor = end
906 return data
907
908 def expect_bytes(self, expected_value, message):
909 value = self.read_bytes(len(expected_value))
910 if value != expected_value:
911 raise ParserError(f"unexpected value: {value} != {expected_value} "
912 f"({message})")
913
914 def read_uint(self, big_endian=False):
915 data_format = ">I" if big_endian else "<I"
916 return struct.unpack(data_format, self.read_bytes(4))[0]
917
918 def read_double(self, big_endian=False):
919 data_format = ">d" if big_endian else "<d"
920 return struct.unpack(data_format, self.read_bytes(8))[0]
921
922 def read_cstring(self):
923 buffer = []
924 while True:
925 c = self.read_bytes(1)
926 if c == b"\x00":
927 return b"".join(buffer).decode()
928 else:
929 buffer.append(c)
930
931 def skip(self, num_bytes, description="unknown"):
932 if num_bytes > 0:
933 _log_debug(f"Skipping {num_bytes} bytes ({description}): "
934 f"{self.read_bytes(num_bytes)!r}")
935 elif num_bytes < 0:
936 raise ParserError(f"Invalid skip of {num_bytes} bytes")
937
938 def skip_to(self, offset, description="unknown"):
939 self.skip(offset - self.cursor, description)
940
941 def skip_to_end(self, description="unknown"):
942 self.skip_to(len(self._data), description)
943
944
945 class DatabaseConnection():
946
947 def __init__(self, path):
948 self.path = path
949 self.database = None
950 self.directory = None
951
952 def __enter__(self):
953 try:
954 # https://www.sqlite.org/uri.html#the_uri_path
955 path = self.path.replace("?", "%3f").replace("#", "%23")
956 if util.WINDOWS:
957 path = "/" + os.path.abspath(path)
958
959 uri = f"file:{path}?mode=ro&immutable=1"
960 self.database = sqlite3.connect(
961 uri, uri=True, isolation_level=None, check_same_thread=False)
962 return self.database
963 except Exception as exc:
964 _log_debug("Falling back to temporary database copy (%s: %s)",
965 exc.__class__.__name__, exc)
966
967 try:
968 self.directory = tempfile.TemporaryDirectory(prefix="gallery-dl-")
969 path_copy = os.path.join(self.directory.name, "copy.sqlite")
970 shutil.copyfile(self.path, path_copy)
971 self.database = sqlite3.connect(
972 path_copy, isolation_level=None, check_same_thread=False)
973 return self.database
974 except BaseException:
975 if self.directory:
976 self.directory.cleanup()
977 raise
978
979 def __exit__(self, exc_type, exc_value, traceback):
980 self.database.close()
981 if self.directory:
982 self.directory.cleanup()
983
984
985 def Popen_communicate(*args):
986 proc = util.Popen(
987 args, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
988 try:
989 stdout, stderr = proc.communicate()
990 except BaseException: # Including KeyboardInterrupt
991 proc.kill()
992 proc.wait()
993 raise
994 return proc, stdout
995
996
997 """
998 https://chromium.googlesource.com/chromium/src/+/refs/heads
999 /main/base/nix/xdg_util.h - DesktopEnvironment
1000 """
1001 DE_OTHER = "other"
1002 DE_CINNAMON = "cinnamon"
1003 DE_GNOME = "gnome"
1004 DE_KDE = "kde"
1005 DE_PANTHEON = "pantheon"
1006 DE_UNITY = "unity"
1007 DE_XFCE = "xfce"
1008
1009
1010 """
1011 https://chromium.googlesource.com/chromium/src/+/refs/heads
1012 /main/components/os_crypt/key_storage_util_linux.h - SelectedLinuxBackend
1013 """
1014 KEYRING_KWALLET = "kwallet"
1015 KEYRING_GNOMEKEYRING = "gnomekeyring"
1016 KEYRING_BASICTEXT = "basictext"
1017 SUPPORTED_KEYRINGS = {"kwallet", "gnomekeyring", "basictext"}
1018
1019
1020 def _get_linux_desktop_environment(env):
1021 """
1022 Ref: https://chromium.googlesource.com/chromium/src/+/refs/heads
1023 /main/base/nix/xdg_util.cc - GetDesktopEnvironment
1024 """
1025 xdg_current_desktop = env.get("XDG_CURRENT_DESKTOP")
1026 desktop_session = env.get("DESKTOP_SESSION")
1027
1028 if xdg_current_desktop:
1029 xdg_current_desktop = (xdg_current_desktop.partition(":")[0]
1030 .strip().lower())
1031
1032 if xdg_current_desktop == "unity":
1033 if desktop_session and "gnome-fallback" in desktop_session:
1034 return DE_GNOME
1035 else:
1036 return DE_UNITY
1037 elif xdg_current_desktop == "gnome":
1038 return DE_GNOME
1039 elif xdg_current_desktop == "x-cinnamon":
1040 return DE_CINNAMON
1041 elif xdg_current_desktop == "kde":
1042 return DE_KDE
1043 elif xdg_current_desktop == "pantheon":
1044 return DE_PANTHEON
1045 elif xdg_current_desktop == "xfce":
1046 return DE_XFCE
1047
1048 if desktop_session:
1049 if desktop_session in ("mate", "gnome"):
1050 return DE_GNOME
1051 if "kde" in desktop_session:
1052 return DE_KDE
1053 if "xfce" in desktop_session:
1054 return DE_XFCE
1055
1056 if "GNOME_DESKTOP_SESSION_ID" in env:
1057 return DE_GNOME
1058 if "KDE_FULL_SESSION" in env:
1059 return DE_KDE
1060 return DE_OTHER
1061
1062
1063 def _mac_absolute_time_to_posix(timestamp):
1064 # 978307200 is timestamp of 2001-01-01 00:00:00
1065 return 978307200 + int(timestamp)
1066
1067
1068 def pbkdf2_sha1(password, salt, iterations, key_length):
1069 return pbkdf2_hmac("sha1", password, salt, iterations, key_length)
1070
1071
1072 def _decrypt_aes_cbc(ciphertext, key, offset=0,
1073 initialization_vector=b" " * 16):
1074 if not ciphertext:
1075 return ""
1076 plaintext = aes.unpad_pkcs7(aes.aes_cbc_decrypt_bytes(
1077 ciphertext, key, initialization_vector))
1078 if offset:
1079 plaintext = plaintext[offset:]
1080 try:
1081 return plaintext.decode()
1082 except UnicodeDecodeError:
1083 return None
1084
1085
1086 def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, offset=0):
1087 if not ciphertext:
1088 return ""
1089 try:
1090 plaintext = aes.aes_gcm_decrypt_and_verify_bytes(
1091 ciphertext, key, authentication_tag, nonce)
1092 if offset:
1093 plaintext = plaintext[offset:]
1094 return plaintext.decode()
1095 except UnicodeDecodeError:
1096 _log_warning("Failed to decrypt cookie (AES-GCM Unicode)")
1097 except ValueError:
1098 _log_warning("Failed to decrypt cookie (AES-GCM MAC)")
1099 return None
1100
1101
1102 def _decrypt_windows_dpapi(ciphertext):
1103 """
1104 References:
1105 - https://docs.microsoft.com/en-us/windows
1106 /win32/api/dpapi/nf-dpapi-cryptunprotectdata
1107 """
1108 from ctypes.wintypes import DWORD
1109
1110 class DATA_BLOB(ctypes.Structure):
1111 _fields_ = [("cbData", DWORD),
1112 ("pbData", ctypes.POINTER(ctypes.c_char))]
1113
1114 buffer = ctypes.create_string_buffer(ciphertext)
1115 blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer)
1116 blob_out = DATA_BLOB()
1117 ret = ctypes.windll.crypt32.CryptUnprotectData(
1118 ctypes.byref(blob_in), # pDataIn
1119 None, # ppszDataDescr: human readable description of pDataIn
1120 None, # pOptionalEntropy: salt?
1121 None, # pvReserved: must be NULL
1122 None, # pPromptStruct: information about prompts to display
1123 0, # dwFlags
1124 ctypes.byref(blob_out) # pDataOut
1125 )
1126 if not ret:
1127 _log_warning("Failed to decrypt cookie (DPAPI)")
1128 return None
1129
1130 result = ctypes.string_at(blob_out.pbData, blob_out.cbData)
1131 ctypes.windll.kernel32.LocalFree(blob_out.pbData)
1132 return result
1133
1134
1135 def _find_most_recently_used_file(roots, filename):
1136 if isinstance(roots, str):
1137 roots = (roots,)
1138
1139 # if the provided root points to an exact profile path
1140 # check if it contains the wanted filename
1141 for root in roots:
1142 first_choice = os.path.join(root, filename)
1143 if os.path.exists(first_choice):
1144 return first_choice
1145
1146 # if there are multiple browser profiles, take the most recently used one
1147 paths = []
1148 for root in roots:
1149 for curr_root, dirs, files in os.walk(root):
1150 for file in files:
1151 if file == filename:
1152 paths.append(os.path.join(curr_root, file))
1153 if not paths:
1154 return None
1155 return max(paths, key=lambda path: os.lstat(path).st_mtime)
1156
1157
1158 def _is_path(value):
1159 return os.path.sep in value
1160
1161
1162 def _parse_browser_specification(
1163 browser, profile=None, keyring=None, container=None, domain=None):
1164 browser = browser.lower()
1165 if browser not in SUPPORTED_BROWSERS:
1166 raise ValueError(f"Unsupported browser '{browser}'")
1167 if keyring and keyring not in SUPPORTED_KEYRINGS:
1168 raise ValueError(f"Unsupported keyring '{keyring}'")
1169 if profile and _is_path(profile):
1170 profile = os.path.expanduser(profile)
1171 return browser, profile, keyring, container, domain
1172
1173
1174 _log_cache = set()
1175 _log_debug = logger.debug
1176 _log_info = logger.info
1177
1178
1179 def _log_warning(msg, *args):
1180 if msg not in _log_cache:
1181 _log_cache.add(msg)
1182 logger.warning(msg, *args)
1183
1184
1185 def _log_error(msg, *args):
1186 if msg not in _log_cache:
1187 _log_cache.add(msg)
1188 logger.error(msg, *args)