13 from datetime
import datetime
, timedelta
, timezone
14 from enum
import Enum
, auto
15 from hashlib
import pbkdf2_hmac
18 aes_cbc_decrypt_bytes
,
19 aes_gcm_decrypt_and_verify_bytes
,
22 from .dependencies
import (
23 _SECRETSTORAGE_UNAVAILABLE_REASON
,
27 from .minicurses
import MultilinePrinter
, QuietMultilinePrinter
28 from .utils
import Popen
, YoutubeDLCookieJar
, error_to_str
, expand_path
30 CHROMIUM_BASED_BROWSERS
= {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'}
31 SUPPORTED_BROWSERS
= CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'}
35 def __init__(self
, ydl
=None):
38 def debug(self
, message
):
40 self
._ydl
.write_debug(message
)
42 def info(self
, message
):
44 self
._ydl
.to_screen(f
'[Cookies] {message}')
46 def warning(self
, message
, only_once
=False):
48 self
._ydl
.report_warning(message
, only_once
)
50 def error(self
, message
):
52 self
._ydl
.report_error(message
)
54 class ProgressBar(MultilinePrinter
):
55 _DELAY
, _timer
= 0.1, 0
57 def print(self
, message
):
58 if time
.time() - self
._timer
> self
._DELAY
:
59 self
.print_at_line(f
'[Cookies] {message}', 0)
60 self
._timer
= time
.time()
62 def progress_bar(self
):
63 """Return a context manager with a print method. (Optional)"""
64 # Do not print to files/pipes, loggers, or when --no-progress is used
65 if not self
._ydl
or self
._ydl
.params
.get('noprogress') or self
._ydl
.params
.get('logger'):
67 file = self
._ydl
._out
_files
.error
73 return self
.ProgressBar(file, preserve_output
=False)
76 def _create_progress_bar(logger
):
77 if hasattr(logger
, 'progress_bar'):
78 printer
= logger
.progress_bar()
81 printer
= QuietMultilinePrinter()
82 printer
.print = lambda _
: None
86 def load_cookies(cookie_file
, browser_specification
, ydl
):
88 if browser_specification
is not None:
89 browser_name
, profile
, keyring
= _parse_browser_specification(*browser_specification
)
90 cookie_jars
.append(extract_cookies_from_browser(browser_name
, profile
, YDLLogger(ydl
), keyring
=keyring
))
92 if cookie_file
is not None:
93 is_filename
= YoutubeDLCookieJar
.is_path(cookie_file
)
95 cookie_file
= expand_path(cookie_file
)
97 jar
= YoutubeDLCookieJar(cookie_file
)
98 if not is_filename
or os
.access(cookie_file
, os
.R_OK
):
99 jar
.load(ignore_discard
=True, ignore_expires
=True)
100 cookie_jars
.append(jar
)
102 return _merge_cookie_jars(cookie_jars
)
105 def extract_cookies_from_browser(browser_name
, profile
=None, logger
=YDLLogger(), *, keyring
=None):
106 if browser_name
== 'firefox':
107 return _extract_firefox_cookies(profile
, logger
)
108 elif browser_name
== 'safari':
109 return _extract_safari_cookies(profile
, logger
)
110 elif browser_name
in CHROMIUM_BASED_BROWSERS
:
111 return _extract_chrome_cookies(browser_name
, profile
, keyring
, logger
)
113 raise ValueError(f
'unknown browser: {browser_name}')
116 def _extract_firefox_cookies(profile
, logger
):
117 logger
.info('Extracting cookies from firefox')
119 logger
.warning('Cannot extract cookies from firefox without sqlite3 support. '
120 'Please use a python interpreter compiled with sqlite3 support')
121 return YoutubeDLCookieJar()
124 search_root
= _firefox_browser_dir()
125 elif _is_path(profile
):
126 search_root
= profile
128 search_root
= os
.path
.join(_firefox_browser_dir(), profile
)
130 cookie_database_path
= _find_most_recently_used_file(search_root
, 'cookies.sqlite', logger
)
131 if cookie_database_path
is None:
132 raise FileNotFoundError(f
'could not find firefox cookies database in {search_root}')
133 logger
.debug(f
'Extracting cookies from: "{cookie_database_path}"')
135 with tempfile
.TemporaryDirectory(prefix
='yt_dlp') as tmpdir
:
138 cursor
= _open_database_copy(cookie_database_path
, tmpdir
)
139 cursor
.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies')
140 jar
= YoutubeDLCookieJar()
141 with _create_progress_bar(logger
) as progress_bar
:
142 table
= cursor
.fetchall()
143 total_cookie_count
= len(table
)
144 for i
, (host
, name
, value
, path
, expiry
, is_secure
) in enumerate(table
):
145 progress_bar
.print(f
'Loading cookie {i: 6d}/{total_cookie_count: 6d}')
146 cookie
= http
.cookiejar
.Cookie(
147 version
=0, name
=name
, value
=value
, port
=None, port_specified
=False,
148 domain
=host
, domain_specified
=bool(host
), domain_initial_dot
=host
.startswith('.'),
149 path
=path
, path_specified
=bool(path
), secure
=is_secure
, expires
=expiry
, discard
=False,
150 comment
=None, comment_url
=None, rest
={})
151 jar
.set_cookie(cookie
)
152 logger
.info(f
'Extracted {len(jar)} cookies from firefox')
155 if cursor
is not None:
156 cursor
.connection
.close()
159 def _firefox_browser_dir():
160 if sys
.platform
in ('cygwin', 'win32'):
161 return os
.path
.expandvars(R
'%APPDATA%\Mozilla\Firefox\Profiles')
162 elif sys
.platform
== 'darwin':
163 return os
.path
.expanduser('~/Library/Application Support/Firefox')
164 return os
.path
.expanduser('~/.mozilla/firefox')
167 def _get_chromium_based_browser_settings(browser_name
):
168 # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md
169 if sys
.platform
in ('cygwin', 'win32'):
170 appdata_local
= os
.path
.expandvars('%LOCALAPPDATA%')
171 appdata_roaming
= os
.path
.expandvars('%APPDATA%')
173 'brave': os
.path
.join(appdata_local
, R
'BraveSoftware\Brave-Browser\User Data'),
174 'chrome': os
.path
.join(appdata_local
, R
'Google\Chrome\User Data'),
175 'chromium': os
.path
.join(appdata_local
, R
'Chromium\User Data'),
176 'edge': os
.path
.join(appdata_local
, R
'Microsoft\Edge\User Data'),
177 'opera': os
.path
.join(appdata_roaming
, R
'Opera Software\Opera Stable'),
178 'vivaldi': os
.path
.join(appdata_local
, R
'Vivaldi\User Data'),
181 elif sys
.platform
== 'darwin':
182 appdata
= os
.path
.expanduser('~/Library/Application Support')
184 'brave': os
.path
.join(appdata
, 'BraveSoftware/Brave-Browser'),
185 'chrome': os
.path
.join(appdata
, 'Google/Chrome'),
186 'chromium': os
.path
.join(appdata
, 'Chromium'),
187 'edge': os
.path
.join(appdata
, 'Microsoft Edge'),
188 'opera': os
.path
.join(appdata
, 'com.operasoftware.Opera'),
189 'vivaldi': os
.path
.join(appdata
, 'Vivaldi'),
193 config
= _config_home()
195 'brave': os
.path
.join(config
, 'BraveSoftware/Brave-Browser'),
196 'chrome': os
.path
.join(config
, 'google-chrome'),
197 'chromium': os
.path
.join(config
, 'chromium'),
198 'edge': os
.path
.join(config
, 'microsoft-edge'),
199 'opera': os
.path
.join(config
, 'opera'),
200 'vivaldi': os
.path
.join(config
, 'vivaldi'),
203 # Linux keyring names can be determined by snooping on dbus while opening the browser in KDE:
204 # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
208 'chromium': 'Chromium',
209 'edge': 'Microsoft Edge' if sys
.platform
== 'darwin' else 'Chromium',
210 'opera': 'Opera' if sys
.platform
== 'darwin' else 'Chromium',
211 'vivaldi': 'Vivaldi' if sys
.platform
== 'darwin' else 'Chrome',
214 browsers_without_profiles
= {'opera'}
217 'browser_dir': browser_dir
,
218 'keyring_name': keyring_name
,
219 'supports_profiles': browser_name
not in browsers_without_profiles
223 def _extract_chrome_cookies(browser_name
, profile
, keyring
, logger
):
224 logger
.info(f
'Extracting cookies from {browser_name}')
227 logger
.warning(f
'Cannot extract cookies from {browser_name} without sqlite3 support. '
228 'Please use a python interpreter compiled with sqlite3 support')
229 return YoutubeDLCookieJar()
231 config
= _get_chromium_based_browser_settings(browser_name
)
234 search_root
= config
['browser_dir']
235 elif _is_path(profile
):
236 search_root
= profile
237 config
['browser_dir'] = os
.path
.dirname(profile
) if config
['supports_profiles'] else profile
239 if config
['supports_profiles']:
240 search_root
= os
.path
.join(config
['browser_dir'], profile
)
242 logger
.error(f
'{browser_name} does not support profiles')
243 search_root
= config
['browser_dir']
245 cookie_database_path
= _find_most_recently_used_file(search_root
, 'Cookies', logger
)
246 if cookie_database_path
is None:
247 raise FileNotFoundError(f
'could not find {browser_name} cookies database in "{search_root}"')
248 logger
.debug(f
'Extracting cookies from: "{cookie_database_path}"')
250 decryptor
= get_cookie_decryptor(config
['browser_dir'], config
['keyring_name'], logger
, keyring
=keyring
)
252 with tempfile
.TemporaryDirectory(prefix
='yt_dlp') as tmpdir
:
255 cursor
= _open_database_copy(cookie_database_path
, tmpdir
)
256 cursor
.connection
.text_factory
= bytes
257 column_names
= _get_column_names(cursor
, 'cookies')
258 secure_column
= 'is_secure' if 'is_secure' in column_names
else 'secure'
259 cursor
.execute(f
'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies')
260 jar
= YoutubeDLCookieJar()
262 unencrypted_cookies
= 0
263 with _create_progress_bar(logger
) as progress_bar
:
264 table
= cursor
.fetchall()
265 total_cookie_count
= len(table
)
266 for i
, line
in enumerate(table
):
267 progress_bar
.print(f
'Loading cookie {i: 6d}/{total_cookie_count: 6d}')
268 is_encrypted
, cookie
= _process_chrome_cookie(decryptor
, *line
)
272 elif not is_encrypted
:
273 unencrypted_cookies
+= 1
274 jar
.set_cookie(cookie
)
275 if failed_cookies
> 0:
276 failed_message
= f
' ({failed_cookies} could not be decrypted)'
279 logger
.info(f
'Extracted {len(jar)} cookies from {browser_name}{failed_message}')
280 counts
= decryptor
._cookie
_counts
.copy()
281 counts
['unencrypted'] = unencrypted_cookies
282 logger
.debug(f
'cookie version breakdown: {counts}')
285 if cursor
is not None:
286 cursor
.connection
.close()
289 def _process_chrome_cookie(decryptor
, host_key
, name
, value
, encrypted_value
, path
, expires_utc
, is_secure
):
290 host_key
= host_key
.decode()
292 value
= value
.decode()
294 is_encrypted
= not value
and encrypted_value
297 value
= decryptor
.decrypt(encrypted_value
)
299 return is_encrypted
, None
301 return is_encrypted
, http
.cookiejar
.Cookie(
302 version
=0, name
=name
, value
=value
, port
=None, port_specified
=False,
303 domain
=host_key
, domain_specified
=bool(host_key
), domain_initial_dot
=host_key
.startswith('.'),
304 path
=path
, path_specified
=bool(path
), secure
=is_secure
, expires
=expires_utc
, discard
=False,
305 comment
=None, comment_url
=None, rest
={})
308 class ChromeCookieDecryptor
:
313 - cookies are either v10 or v11
314 - v10: AES-CBC encrypted with a fixed key
315 - v11: AES-CBC encrypted with an OS protected key (keyring)
316 - v11 keys can be stored in various places depending on the activate desktop environment [2]
319 - cookies are either v10 or not v10
320 - v10: AES-CBC encrypted with an OS protected key (keyring) and more key derivation iterations than linux
321 - not v10: 'old data' stored as plaintext
324 - cookies are either v10 or not v10
325 - v10: AES-GCM encrypted with a key which is encrypted with DPAPI
326 - not v10: encrypted with DPAPI
329 - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/
330 - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc
331 - KeyStorageLinux::CreateService
336 def decrypt(self
, encrypted_value
):
337 raise NotImplementedError('Must be implemented by sub classes')
340 def get_cookie_decryptor(browser_root
, browser_keyring_name
, logger
, *, keyring
=None):
341 if sys
.platform
== 'darwin':
342 return MacChromeCookieDecryptor(browser_keyring_name
, logger
)
343 elif sys
.platform
in ('win32', 'cygwin'):
344 return WindowsChromeCookieDecryptor(browser_root
, logger
)
345 return LinuxChromeCookieDecryptor(browser_keyring_name
, logger
, keyring
=keyring
)
348 class LinuxChromeCookieDecryptor(ChromeCookieDecryptor
):
349 def __init__(self
, browser_keyring_name
, logger
, *, keyring
=None):
350 self
._logger
= logger
351 self
._v
10_key
= self
.derive_key(b
'peanuts')
352 password
= _get_linux_keyring_password(browser_keyring_name
, keyring
, logger
)
353 self
._v
11_key
= None if password
is None else self
.derive_key(password
)
354 self
._cookie
_counts
= {'v10': 0, 'v11': 0, 'other': 0}
357 def derive_key(password
):
359 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc
360 return pbkdf2_sha1(password
, salt
=b
'saltysalt', iterations
=1, key_length
=16)
362 def decrypt(self
, encrypted_value
):
363 version
= encrypted_value
[:3]
364 ciphertext
= encrypted_value
[3:]
366 if version
== b
'v10':
367 self
._cookie
_counts
['v10'] += 1
368 return _decrypt_aes_cbc(ciphertext
, self
._v
10_key
, self
._logger
)
370 elif version
== b
'v11':
371 self
._cookie
_counts
['v11'] += 1
372 if self
._v
11_key
is None:
373 self
._logger
.warning('cannot decrypt v11 cookies: no key found', only_once
=True)
375 return _decrypt_aes_cbc(ciphertext
, self
._v
11_key
, self
._logger
)
378 self
._cookie
_counts
['other'] += 1
382 class MacChromeCookieDecryptor(ChromeCookieDecryptor
):
383 def __init__(self
, browser_keyring_name
, logger
):
384 self
._logger
= logger
385 password
= _get_mac_keyring_password(browser_keyring_name
, logger
)
386 self
._v
10_key
= None if password
is None else self
.derive_key(password
)
387 self
._cookie
_counts
= {'v10': 0, 'other': 0}
390 def derive_key(password
):
392 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm
393 return pbkdf2_sha1(password
, salt
=b
'saltysalt', iterations
=1003, key_length
=16)
395 def decrypt(self
, encrypted_value
):
396 version
= encrypted_value
[:3]
397 ciphertext
= encrypted_value
[3:]
399 if version
== b
'v10':
400 self
._cookie
_counts
['v10'] += 1
401 if self
._v
10_key
is None:
402 self
._logger
.warning('cannot decrypt v10 cookies: no key found', only_once
=True)
405 return _decrypt_aes_cbc(ciphertext
, self
._v
10_key
, self
._logger
)
408 self
._cookie
_counts
['other'] += 1
409 # other prefixes are considered 'old data' which were stored as plaintext
410 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm
411 return encrypted_value
414 class WindowsChromeCookieDecryptor(ChromeCookieDecryptor
):
415 def __init__(self
, browser_root
, logger
):
416 self
._logger
= logger
417 self
._v
10_key
= _get_windows_v10_key(browser_root
, logger
)
418 self
._cookie
_counts
= {'v10': 0, 'other': 0}
420 def decrypt(self
, encrypted_value
):
421 version
= encrypted_value
[:3]
422 ciphertext
= encrypted_value
[3:]
424 if version
== b
'v10':
425 self
._cookie
_counts
['v10'] += 1
426 if self
._v
10_key
is None:
427 self
._logger
.warning('cannot decrypt v10 cookies: no key found', only_once
=True)
430 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc
432 nonce_length
= 96 // 8
434 # EVP_AEAD_AES_GCM_TAG_LEN
435 authentication_tag_length
= 16
437 raw_ciphertext
= ciphertext
438 nonce
= raw_ciphertext
[:nonce_length
]
439 ciphertext
= raw_ciphertext
[nonce_length
:-authentication_tag_length
]
440 authentication_tag
= raw_ciphertext
[-authentication_tag_length
:]
442 return _decrypt_aes_gcm(ciphertext
, self
._v
10_key
, nonce
, authentication_tag
, self
._logger
)
445 self
._cookie
_counts
['other'] += 1
446 # any other prefix means the data is DPAPI encrypted
447 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc
448 return _decrypt_windows_dpapi(encrypted_value
, self
._logger
).decode()
451 def _extract_safari_cookies(profile
, logger
):
452 if profile
is not None:
453 logger
.error('safari does not support profiles')
454 if sys
.platform
!= 'darwin':
455 raise ValueError(f
'unsupported platform: {sys.platform}')
457 cookies_path
= os
.path
.expanduser('~/Library/Cookies/Cookies.binarycookies')
459 if not os
.path
.isfile(cookies_path
):
460 logger
.debug('Trying secondary cookie location')
461 cookies_path
= os
.path
.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies')
462 if not os
.path
.isfile(cookies_path
):
463 raise FileNotFoundError('could not find safari cookies database')
465 with open(cookies_path
, 'rb') as f
:
466 cookies_data
= f
.read()
468 jar
= parse_safari_cookies(cookies_data
, logger
=logger
)
469 logger
.info(f
'Extracted {len(jar)} cookies from safari')
473 class ParserError(Exception):
478 def __init__(self
, data
, logger
):
481 self
._logger
= logger
483 def read_bytes(self
, num_bytes
):
485 raise ParserError(f
'invalid read of {num_bytes} bytes')
486 end
= self
.cursor
+ num_bytes
487 if end
> len(self
._data
):
488 raise ParserError('reached end of input')
489 data
= self
._data
[self
.cursor
:end
]
493 def expect_bytes(self
, expected_value
, message
):
494 value
= self
.read_bytes(len(expected_value
))
495 if value
!= expected_value
:
496 raise ParserError(f
'unexpected value: {value} != {expected_value} ({message})')
498 def read_uint(self
, big_endian
=False):
499 data_format
= '>I' if big_endian
else '<I'
500 return struct
.unpack(data_format
, self
.read_bytes(4))[0]
502 def read_double(self
, big_endian
=False):
503 data_format
= '>d' if big_endian
else '<d'
504 return struct
.unpack(data_format
, self
.read_bytes(8))[0]
506 def read_cstring(self
):
509 c
= self
.read_bytes(1)
511 return b
''.join(buffer).decode()
515 def skip(self
, num_bytes
, description
='unknown'):
517 self
._logger
.debug(f
'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}')
519 raise ParserError(f
'invalid skip of {num_bytes} bytes')
521 def skip_to(self
, offset
, description
='unknown'):
522 self
.skip(offset
- self
.cursor
, description
)
524 def skip_to_end(self
, description
='unknown'):
525 self
.skip_to(len(self
._data
), description
)
528 def _mac_absolute_time_to_posix(timestamp
):
529 return int((datetime(2001, 1, 1, 0, 0, tzinfo
=timezone
.utc
) + timedelta(seconds
=timestamp
)).timestamp())
532 def _parse_safari_cookies_header(data
, logger
):
533 p
= DataParser(data
, logger
)
534 p
.expect_bytes(b
'cook', 'database signature')
535 number_of_pages
= p
.read_uint(big_endian
=True)
536 page_sizes
= [p
.read_uint(big_endian
=True) for _
in range(number_of_pages
)]
537 return page_sizes
, p
.cursor
540 def _parse_safari_cookies_page(data
, jar
, logger
):
541 p
= DataParser(data
, logger
)
542 p
.expect_bytes(b
'\x00\x00\x01\x00', 'page signature')
543 number_of_cookies
= p
.read_uint()
544 record_offsets
= [p
.read_uint() for _
in range(number_of_cookies
)]
545 if number_of_cookies
== 0:
546 logger
.debug(f
'a cookies page of size {len(data)} has no cookies')
549 p
.skip_to(record_offsets
[0], 'unknown page header field')
551 with _create_progress_bar(logger
) as progress_bar
:
552 for i
, record_offset
in enumerate(record_offsets
):
553 progress_bar
.print(f
'Loading cookie {i: 6d}/{number_of_cookies: 6d}')
554 p
.skip_to(record_offset
, 'space between records')
555 record_length
= _parse_safari_cookies_record(data
[record_offset
:], jar
, logger
)
556 p
.read_bytes(record_length
)
557 p
.skip_to_end('space in between pages')
560 def _parse_safari_cookies_record(data
, jar
, logger
):
561 p
= DataParser(data
, logger
)
562 record_size
= p
.read_uint()
563 p
.skip(4, 'unknown record field 1')
564 flags
= p
.read_uint()
565 is_secure
= bool(flags
& 0x0001)
566 p
.skip(4, 'unknown record field 2')
567 domain_offset
= p
.read_uint()
568 name_offset
= p
.read_uint()
569 path_offset
= p
.read_uint()
570 value_offset
= p
.read_uint()
571 p
.skip(8, 'unknown record field 3')
572 expiration_date
= _mac_absolute_time_to_posix(p
.read_double())
573 _creation_date
= _mac_absolute_time_to_posix(p
.read_double()) # noqa: F841
576 p
.skip_to(domain_offset
)
577 domain
= p
.read_cstring()
579 p
.skip_to(name_offset
)
580 name
= p
.read_cstring()
582 p
.skip_to(path_offset
)
583 path
= p
.read_cstring()
585 p
.skip_to(value_offset
)
586 value
= p
.read_cstring()
587 except UnicodeDecodeError:
588 logger
.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once
=True)
591 p
.skip_to(record_size
, 'space at the end of the record')
593 cookie
= http
.cookiejar
.Cookie(
594 version
=0, name
=name
, value
=value
, port
=None, port_specified
=False,
595 domain
=domain
, domain_specified
=bool(domain
), domain_initial_dot
=domain
.startswith('.'),
596 path
=path
, path_specified
=bool(path
), secure
=is_secure
, expires
=expiration_date
, discard
=False,
597 comment
=None, comment_url
=None, rest
={})
598 jar
.set_cookie(cookie
)
602 def parse_safari_cookies(data
, jar
=None, logger
=YDLLogger()):
605 - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc
606 - this data appears to be out of date but the important parts of the database structure is the same
607 - there are a few bytes here and there which are skipped during parsing
610 jar
= YoutubeDLCookieJar()
611 page_sizes
, body_start
= _parse_safari_cookies_header(data
, logger
)
612 p
= DataParser(data
[body_start
:], logger
)
613 for page_size
in page_sizes
:
614 _parse_safari_cookies_page(p
.read_bytes(page_size
), jar
, logger
)
615 p
.skip_to_end('footer')
619 class _LinuxDesktopEnvironment(Enum
):
621 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h
633 class _LinuxKeyring(Enum
):
635 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h
639 GNOMEKEYRING
= auto()
643 SUPPORTED_KEYRINGS
= _LinuxKeyring
.__members
__.keys()
646 def _get_linux_desktop_environment(env
):
648 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc
649 GetDesktopEnvironment
651 xdg_current_desktop
= env
.get('XDG_CURRENT_DESKTOP', None)
652 desktop_session
= env
.get('DESKTOP_SESSION', None)
653 if xdg_current_desktop
is not None:
654 xdg_current_desktop
= xdg_current_desktop
.split(':')[0].strip()
656 if xdg_current_desktop
== 'Unity':
657 if desktop_session
is not None and 'gnome-fallback' in desktop_session
:
658 return _LinuxDesktopEnvironment
.GNOME
660 return _LinuxDesktopEnvironment
.UNITY
661 elif xdg_current_desktop
== 'GNOME':
662 return _LinuxDesktopEnvironment
.GNOME
663 elif xdg_current_desktop
== 'X-Cinnamon':
664 return _LinuxDesktopEnvironment
.CINNAMON
665 elif xdg_current_desktop
== 'KDE':
666 return _LinuxDesktopEnvironment
.KDE
667 elif xdg_current_desktop
== 'Pantheon':
668 return _LinuxDesktopEnvironment
.PANTHEON
669 elif xdg_current_desktop
== 'XFCE':
670 return _LinuxDesktopEnvironment
.XFCE
671 elif desktop_session
is not None:
672 if desktop_session
in ('mate', 'gnome'):
673 return _LinuxDesktopEnvironment
.GNOME
674 elif 'kde' in desktop_session
:
675 return _LinuxDesktopEnvironment
.KDE
676 elif 'xfce' in desktop_session
:
677 return _LinuxDesktopEnvironment
.XFCE
679 if 'GNOME_DESKTOP_SESSION_ID' in env
:
680 return _LinuxDesktopEnvironment
.GNOME
681 elif 'KDE_FULL_SESSION' in env
:
682 return _LinuxDesktopEnvironment
.KDE
683 return _LinuxDesktopEnvironment
.OTHER
686 def _choose_linux_keyring(logger
):
688 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc
691 desktop_environment
= _get_linux_desktop_environment(os
.environ
)
692 logger
.debug(f
'detected desktop environment: {desktop_environment.name}')
693 if desktop_environment
== _LinuxDesktopEnvironment
.KDE
:
694 linux_keyring
= _LinuxKeyring
.KWALLET
695 elif desktop_environment
== _LinuxDesktopEnvironment
.OTHER
:
696 linux_keyring
= _LinuxKeyring
.BASICTEXT
698 linux_keyring
= _LinuxKeyring
.GNOMEKEYRING
702 def _get_kwallet_network_wallet(logger
):
703 """ The name of the wallet used to store network passwords.
705 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc
706 KWalletDBus::NetworkWallet
707 which does a dbus call to the following function:
708 https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html
709 Wallet::NetworkWallet
711 default_wallet
= 'kdewallet'
713 stdout
, _
, returncode
= Popen
.run([
714 'dbus-send', '--session', '--print-reply=literal',
715 '--dest=org.kde.kwalletd5',
716 '/modules/kwalletd5',
717 'org.kde.KWallet.networkWallet'
718 ], text
=True, stdout
=subprocess
.PIPE
, stderr
=subprocess
.DEVNULL
)
721 logger
.warning('failed to read NetworkWallet')
722 return default_wallet
724 logger
.debug(f
'NetworkWallet = "{stdout.strip()}"')
725 return stdout
.strip()
726 except Exception as e
:
727 logger
.warning(f
'exception while obtaining NetworkWallet: {e}')
728 return default_wallet
731 def _get_kwallet_password(browser_keyring_name
, logger
):
732 logger
.debug('using kwallet-query to obtain password from kwallet')
734 if shutil
.which('kwallet-query') is None:
735 logger
.error('kwallet-query command not found. KWallet and kwallet-query '
736 'must be installed to read from KWallet. kwallet-query should be'
737 'included in the kwallet package for your distribution')
740 network_wallet
= _get_kwallet_network_wallet(logger
)
743 stdout
, _
, returncode
= Popen
.run([
745 '--read-password', f
'{browser_keyring_name} Safe Storage',
746 '--folder', f
'{browser_keyring_name} Keys',
748 ], stdout
=subprocess
.PIPE
, stderr
=subprocess
.DEVNULL
)
751 logger
.error(f
'kwallet-query failed with return code {returncode}. '
752 'Please consult the kwallet-query man page for details')
755 if stdout
.lower().startswith(b
'failed to read'):
756 logger
.debug('failed to read password from kwallet. Using empty string instead')
757 # this sometimes occurs in KDE because chrome does not check hasEntry and instead
758 # just tries to read the value (which kwallet returns "") whereas kwallet-query
759 # checks hasEntry. To verify this:
760 # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
761 # while starting chrome.
762 # this may be a bug as the intended behaviour is to generate a random password and store
763 # it, but that doesn't matter here.
766 logger
.debug('password found')
767 return stdout
.rstrip(b
'\n')
768 except Exception as e
:
769 logger
.warning(f
'exception running kwallet-query: {error_to_str(e)}')
773 def _get_gnome_keyring_password(browser_keyring_name
, logger
):
774 if not secretstorage
:
775 logger
.error(f
'secretstorage not available {_SECRETSTORAGE_UNAVAILABLE_REASON}')
777 # the Gnome keyring does not seem to organise keys in the same way as KWallet,
778 # using `dbus-monitor` during startup, it can be observed that chromium lists all keys
779 # and presumably searches for its key in the list. It appears that we must do the same.
780 # https://github.com/jaraco/keyring/issues/556
781 with contextlib
.closing(secretstorage
.dbus_init()) as con
:
782 col
= secretstorage
.get_default_collection(con
)
783 for item
in col
.get_all_items():
784 if item
.get_label() == f
'{browser_keyring_name} Safe Storage':
785 return item
.get_secret()
787 logger
.error('failed to read from keyring')
791 def _get_linux_keyring_password(browser_keyring_name
, keyring
, logger
):
792 # note: chrome/chromium can be run with the following flags to determine which keyring backend
793 # it has chosen to use
794 # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_
795 # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection
796 # will not be sufficient in all cases.
798 keyring
= _LinuxKeyring
[keyring
] if keyring
else _choose_linux_keyring(logger
)
799 logger
.debug(f
'Chosen keyring: {keyring.name}')
801 if keyring
== _LinuxKeyring
.KWALLET
:
802 return _get_kwallet_password(browser_keyring_name
, logger
)
803 elif keyring
== _LinuxKeyring
.GNOMEKEYRING
:
804 return _get_gnome_keyring_password(browser_keyring_name
, logger
)
805 elif keyring
== _LinuxKeyring
.BASICTEXT
:
806 # when basic text is chosen, all cookies are stored as v10 (so no keyring password is required)
808 assert False, f
'Unknown keyring {keyring}'
811 def _get_mac_keyring_password(browser_keyring_name
, logger
):
812 logger
.debug('using find-generic-password to obtain password from OSX keychain')
814 stdout
, _
, _
= Popen
.run(
815 ['security', 'find-generic-password',
816 '-w', # write password to stdout
817 '-a', browser_keyring_name
, # match 'account'
818 '-s', f
'{browser_keyring_name} Safe Storage'], # match 'service'
819 stdout
=subprocess
.PIPE
, stderr
=subprocess
.DEVNULL
)
820 return stdout
.rstrip(b
'\n')
821 except Exception as e
:
822 logger
.warning(f
'exception running find-generic-password: {error_to_str(e)}')
826 def _get_windows_v10_key(browser_root
, logger
):
827 path
= _find_most_recently_used_file(browser_root
, 'Local State', logger
)
829 logger
.error('could not find local state file')
831 logger
.debug(f
'Found local state file at "{path}"')
832 with open(path
, encoding
='utf8') as f
:
835 base64_key
= data
['os_crypt']['encrypted_key']
837 logger
.error('no encrypted key in Local State')
839 encrypted_key
= base64
.b64decode(base64_key
)
841 if not encrypted_key
.startswith(prefix
):
842 logger
.error('invalid key')
844 return _decrypt_windows_dpapi(encrypted_key
[len(prefix
):], logger
)
847 def pbkdf2_sha1(password
, salt
, iterations
, key_length
):
848 return pbkdf2_hmac('sha1', password
, salt
, iterations
, key_length
)
851 def _decrypt_aes_cbc(ciphertext
, key
, logger
, initialization_vector
=b
' ' * 16):
852 plaintext
= unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext
, key
, initialization_vector
))
854 return plaintext
.decode()
855 except UnicodeDecodeError:
856 logger
.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once
=True)
860 def _decrypt_aes_gcm(ciphertext
, key
, nonce
, authentication_tag
, logger
):
862 plaintext
= aes_gcm_decrypt_and_verify_bytes(ciphertext
, key
, authentication_tag
, nonce
)
864 logger
.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?', only_once
=True)
868 return plaintext
.decode()
869 except UnicodeDecodeError:
870 logger
.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?', only_once
=True)
874 def _decrypt_windows_dpapi(ciphertext
, logger
):
877 - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata
879 from ctypes
.wintypes
import DWORD
881 class DATA_BLOB(ctypes
.Structure
):
882 _fields_
= [('cbData', DWORD
),
883 ('pbData', ctypes
.POINTER(ctypes
.c_char
))]
885 buffer = ctypes
.create_string_buffer(ciphertext
)
886 blob_in
= DATA_BLOB(ctypes
.sizeof(buffer), buffer)
887 blob_out
= DATA_BLOB()
888 ret
= ctypes
.windll
.crypt32
.CryptUnprotectData(
889 ctypes
.byref(blob_in
), # pDataIn
890 None, # ppszDataDescr: human readable description of pDataIn
891 None, # pOptionalEntropy: salt?
892 None, # pvReserved: must be NULL
893 None, # pPromptStruct: information about prompts to display
895 ctypes
.byref(blob_out
) # pDataOut
898 logger
.warning('failed to decrypt with DPAPI', only_once
=True)
901 result
= ctypes
.string_at(blob_out
.pbData
, blob_out
.cbData
)
902 ctypes
.windll
.kernel32
.LocalFree(blob_out
.pbData
)
907 return os
.environ
.get('XDG_CONFIG_HOME', os
.path
.expanduser('~/.config'))
910 def _open_database_copy(database_path
, tmpdir
):
911 # cannot open sqlite databases if they are already in use (e.g. by the browser)
912 database_copy_path
= os
.path
.join(tmpdir
, 'temporary.sqlite')
913 shutil
.copy(database_path
, database_copy_path
)
914 conn
= sqlite3
.connect(database_copy_path
)
918 def _get_column_names(cursor
, table_name
):
919 table_info
= cursor
.execute(f
'PRAGMA table_info({table_name})').fetchall()
920 return [row
[1].decode() for row
in table_info
]
923 def _find_most_recently_used_file(root
, filename
, logger
):
924 # if there are multiple browser profiles, take the most recently used one
926 with _create_progress_bar(logger
) as progress_bar
:
927 for curr_root
, dirs
, files
in os
.walk(root
):
930 progress_bar
.print(f
'Searching for "{filename}": {i: 6d} files searched')
932 paths
.append(os
.path
.join(curr_root
, file))
933 return None if not paths
else max(paths
, key
=lambda path
: os
.lstat(path
).st_mtime
)
936 def _merge_cookie_jars(jars
):
937 output_jar
= YoutubeDLCookieJar()
940 output_jar
.set_cookie(cookie
)
941 if jar
.filename
is not None:
942 output_jar
.filename
= jar
.filename
947 return os
.path
.sep
in value
950 def _parse_browser_specification(browser_name
, profile
=None, keyring
=None):
951 if browser_name
not in SUPPORTED_BROWSERS
:
952 raise ValueError(f
'unsupported browser: "{browser_name}"')
953 if keyring
not in (None, *SUPPORTED_KEYRINGS
):
954 raise ValueError(f
'unsupported keyring: "{keyring}"')
955 if profile
is not None and _is_path(profile
):
956 profile
= os
.path
.expanduser(profile
)
957 return browser_name
, profile
, keyring