11 from datetime
import datetime
, timedelta
, timezone
12 from enum
import Enum
, auto
13 from hashlib
import pbkdf2_hmac
16 aes_cbc_decrypt_bytes
,
17 aes_gcm_decrypt_and_verify_bytes
,
20 from .compat
import compat_b64decode
, compat_cookiejar_Cookie
21 from .dependencies
import (
22 _SECRETSTORAGE_UNAVAILABLE_REASON
,
26 from .minicurses
import MultilinePrinter
, QuietMultilinePrinter
27 from .utils
import Popen
, YoutubeDLCookieJar
, error_to_str
, expand_path
29 CHROMIUM_BASED_BROWSERS
= {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'}
30 SUPPORTED_BROWSERS
= CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'}
34 def __init__(self
, ydl
=None):
37 def debug(self
, message
):
39 self
._ydl
.write_debug(message
)
41 def info(self
, message
):
43 self
._ydl
.to_screen(f
'[Cookies] {message}')
45 def warning(self
, message
, only_once
=False):
47 self
._ydl
.report_warning(message
, only_once
)
49 def error(self
, message
):
51 self
._ydl
.report_error(message
)
53 class ProgressBar(MultilinePrinter
):
54 _DELAY
, _timer
= 0.1, 0
56 def print(self
, message
):
57 if time
.time() - self
._timer
> self
._DELAY
:
58 self
.print_at_line(f
'[Cookies] {message}', 0)
59 self
._timer
= time
.time()
61 def progress_bar(self
):
62 """Return a context manager with a print method. (Optional)"""
63 # Do not print to files/pipes, loggers, or when --no-progress is used
64 if not self
._ydl
or self
._ydl
.params
.get('noprogress') or self
._ydl
.params
.get('logger'):
66 file = self
._ydl
._out
_files
.error
72 return self
.ProgressBar(file, preserve_output
=False)
75 def _create_progress_bar(logger
):
76 if hasattr(logger
, 'progress_bar'):
77 printer
= logger
.progress_bar()
80 printer
= QuietMultilinePrinter()
81 printer
.print = lambda _
: None
85 def load_cookies(cookie_file
, browser_specification
, ydl
):
87 if browser_specification
is not None:
88 browser_name
, profile
, keyring
= _parse_browser_specification(*browser_specification
)
89 cookie_jars
.append(extract_cookies_from_browser(browser_name
, profile
, YDLLogger(ydl
), keyring
=keyring
))
91 if cookie_file
is not None:
92 is_filename
= YoutubeDLCookieJar
.is_path(cookie_file
)
94 cookie_file
= expand_path(cookie_file
)
96 jar
= YoutubeDLCookieJar(cookie_file
)
97 if not is_filename
or os
.access(cookie_file
, os
.R_OK
):
98 jar
.load(ignore_discard
=True, ignore_expires
=True)
99 cookie_jars
.append(jar
)
101 return _merge_cookie_jars(cookie_jars
)
104 def extract_cookies_from_browser(browser_name
, profile
=None, logger
=YDLLogger(), *, keyring
=None):
105 if browser_name
== 'firefox':
106 return _extract_firefox_cookies(profile
, logger
)
107 elif browser_name
== 'safari':
108 return _extract_safari_cookies(profile
, logger
)
109 elif browser_name
in CHROMIUM_BASED_BROWSERS
:
110 return _extract_chrome_cookies(browser_name
, profile
, keyring
, logger
)
112 raise ValueError(f
'unknown browser: {browser_name}')
115 def _extract_firefox_cookies(profile
, logger
):
116 logger
.info('Extracting cookies from firefox')
118 logger
.warning('Cannot extract cookies from firefox without sqlite3 support. '
119 'Please use a python interpreter compiled with sqlite3 support')
120 return YoutubeDLCookieJar()
123 search_root
= _firefox_browser_dir()
124 elif _is_path(profile
):
125 search_root
= profile
127 search_root
= os
.path
.join(_firefox_browser_dir(), profile
)
129 cookie_database_path
= _find_most_recently_used_file(search_root
, 'cookies.sqlite', logger
)
130 if cookie_database_path
is None:
131 raise FileNotFoundError(f
'could not find firefox cookies database in {search_root}')
132 logger
.debug(f
'Extracting cookies from: "{cookie_database_path}"')
134 with tempfile
.TemporaryDirectory(prefix
='yt_dlp') as tmpdir
:
137 cursor
= _open_database_copy(cookie_database_path
, tmpdir
)
138 cursor
.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies')
139 jar
= YoutubeDLCookieJar()
140 with _create_progress_bar(logger
) as progress_bar
:
141 table
= cursor
.fetchall()
142 total_cookie_count
= len(table
)
143 for i
, (host
, name
, value
, path
, expiry
, is_secure
) in enumerate(table
):
144 progress_bar
.print(f
'Loading cookie {i: 6d}/{total_cookie_count: 6d}')
145 cookie
= compat_cookiejar_Cookie(
146 version
=0, name
=name
, value
=value
, port
=None, port_specified
=False,
147 domain
=host
, domain_specified
=bool(host
), domain_initial_dot
=host
.startswith('.'),
148 path
=path
, path_specified
=bool(path
), secure
=is_secure
, expires
=expiry
, discard
=False,
149 comment
=None, comment_url
=None, rest
={})
150 jar
.set_cookie(cookie
)
151 logger
.info(f
'Extracted {len(jar)} cookies from firefox')
154 if cursor
is not None:
155 cursor
.connection
.close()
158 def _firefox_browser_dir():
159 if sys
.platform
in ('cygwin', 'win32'):
160 return os
.path
.expandvars(R
'%APPDATA%\Mozilla\Firefox\Profiles')
161 elif sys
.platform
== 'darwin':
162 return os
.path
.expanduser('~/Library/Application Support/Firefox')
163 return os
.path
.expanduser('~/.mozilla/firefox')
166 def _get_chromium_based_browser_settings(browser_name
):
167 # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md
168 if sys
.platform
in ('cygwin', 'win32'):
169 appdata_local
= os
.path
.expandvars('%LOCALAPPDATA%')
170 appdata_roaming
= os
.path
.expandvars('%APPDATA%')
172 'brave': os
.path
.join(appdata_local
, R
'BraveSoftware\Brave-Browser\User Data'),
173 'chrome': os
.path
.join(appdata_local
, R
'Google\Chrome\User Data'),
174 'chromium': os
.path
.join(appdata_local
, R
'Chromium\User Data'),
175 'edge': os
.path
.join(appdata_local
, R
'Microsoft\Edge\User Data'),
176 'opera': os
.path
.join(appdata_roaming
, R
'Opera Software\Opera Stable'),
177 'vivaldi': os
.path
.join(appdata_local
, R
'Vivaldi\User Data'),
180 elif sys
.platform
== 'darwin':
181 appdata
= os
.path
.expanduser('~/Library/Application Support')
183 'brave': os
.path
.join(appdata
, 'BraveSoftware/Brave-Browser'),
184 'chrome': os
.path
.join(appdata
, 'Google/Chrome'),
185 'chromium': os
.path
.join(appdata
, 'Chromium'),
186 'edge': os
.path
.join(appdata
, 'Microsoft Edge'),
187 'opera': os
.path
.join(appdata
, 'com.operasoftware.Opera'),
188 'vivaldi': os
.path
.join(appdata
, 'Vivaldi'),
192 config
= _config_home()
194 'brave': os
.path
.join(config
, 'BraveSoftware/Brave-Browser'),
195 'chrome': os
.path
.join(config
, 'google-chrome'),
196 'chromium': os
.path
.join(config
, 'chromium'),
197 'edge': os
.path
.join(config
, 'microsoft-edge'),
198 'opera': os
.path
.join(config
, 'opera'),
199 'vivaldi': os
.path
.join(config
, 'vivaldi'),
202 # Linux keyring names can be determined by snooping on dbus while opening the browser in KDE:
203 # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
207 'chromium': 'Chromium',
208 'edge': 'Microsoft Edge' if sys
.platform
== 'darwin' else 'Chromium',
209 'opera': 'Opera' if sys
.platform
== 'darwin' else 'Chromium',
210 'vivaldi': 'Vivaldi' if sys
.platform
== 'darwin' else 'Chrome',
213 browsers_without_profiles
= {'opera'}
216 'browser_dir': browser_dir
,
217 'keyring_name': keyring_name
,
218 'supports_profiles': browser_name
not in browsers_without_profiles
222 def _extract_chrome_cookies(browser_name
, profile
, keyring
, logger
):
223 logger
.info(f
'Extracting cookies from {browser_name}')
226 logger
.warning(f
'Cannot extract cookies from {browser_name} without sqlite3 support. '
227 'Please use a python interpreter compiled with sqlite3 support')
228 return YoutubeDLCookieJar()
230 config
= _get_chromium_based_browser_settings(browser_name
)
233 search_root
= config
['browser_dir']
234 elif _is_path(profile
):
235 search_root
= profile
236 config
['browser_dir'] = os
.path
.dirname(profile
) if config
['supports_profiles'] else profile
238 if config
['supports_profiles']:
239 search_root
= os
.path
.join(config
['browser_dir'], profile
)
241 logger
.error(f
'{browser_name} does not support profiles')
242 search_root
= config
['browser_dir']
244 cookie_database_path
= _find_most_recently_used_file(search_root
, 'Cookies', logger
)
245 if cookie_database_path
is None:
246 raise FileNotFoundError(f
'could not find {browser_name} cookies database in "{search_root}"')
247 logger
.debug(f
'Extracting cookies from: "{cookie_database_path}"')
249 decryptor
= get_cookie_decryptor(config
['browser_dir'], config
['keyring_name'], logger
, keyring
=keyring
)
251 with tempfile
.TemporaryDirectory(prefix
='yt_dlp') as tmpdir
:
254 cursor
= _open_database_copy(cookie_database_path
, tmpdir
)
255 cursor
.connection
.text_factory
= bytes
256 column_names
= _get_column_names(cursor
, 'cookies')
257 secure_column
= 'is_secure' if 'is_secure' in column_names
else 'secure'
258 cursor
.execute(f
'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies')
259 jar
= YoutubeDLCookieJar()
261 unencrypted_cookies
= 0
262 with _create_progress_bar(logger
) as progress_bar
:
263 table
= cursor
.fetchall()
264 total_cookie_count
= len(table
)
265 for i
, line
in enumerate(table
):
266 progress_bar
.print(f
'Loading cookie {i: 6d}/{total_cookie_count: 6d}')
267 is_encrypted
, cookie
= _process_chrome_cookie(decryptor
, *line
)
271 elif not is_encrypted
:
272 unencrypted_cookies
+= 1
273 jar
.set_cookie(cookie
)
274 if failed_cookies
> 0:
275 failed_message
= f
' ({failed_cookies} could not be decrypted)'
278 logger
.info(f
'Extracted {len(jar)} cookies from {browser_name}{failed_message}')
279 counts
= decryptor
._cookie
_counts
.copy()
280 counts
['unencrypted'] = unencrypted_cookies
281 logger
.debug(f
'cookie version breakdown: {counts}')
284 if cursor
is not None:
285 cursor
.connection
.close()
288 def _process_chrome_cookie(decryptor
, host_key
, name
, value
, encrypted_value
, path
, expires_utc
, is_secure
):
289 host_key
= host_key
.decode()
291 value
= value
.decode()
293 is_encrypted
= not value
and encrypted_value
296 value
= decryptor
.decrypt(encrypted_value
)
298 return is_encrypted
, None
300 return is_encrypted
, compat_cookiejar_Cookie(
301 version
=0, name
=name
, value
=value
, port
=None, port_specified
=False,
302 domain
=host_key
, domain_specified
=bool(host_key
), domain_initial_dot
=host_key
.startswith('.'),
303 path
=path
, path_specified
=bool(path
), secure
=is_secure
, expires
=expires_utc
, discard
=False,
304 comment
=None, comment_url
=None, rest
={})
307 class ChromeCookieDecryptor
:
312 - cookies are either v10 or v11
313 - v10: AES-CBC encrypted with a fixed key
314 - v11: AES-CBC encrypted with an OS protected key (keyring)
315 - v11 keys can be stored in various places depending on the activate desktop environment [2]
318 - cookies are either v10 or not v10
319 - v10: AES-CBC encrypted with an OS protected key (keyring) and more key derivation iterations than linux
320 - not v10: 'old data' stored as plaintext
323 - cookies are either v10 or not v10
324 - v10: AES-GCM encrypted with a key which is encrypted with DPAPI
325 - not v10: encrypted with DPAPI
328 - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/
329 - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc
330 - KeyStorageLinux::CreateService
335 def decrypt(self
, encrypted_value
):
336 raise NotImplementedError('Must be implemented by sub classes')
339 def get_cookie_decryptor(browser_root
, browser_keyring_name
, logger
, *, keyring
=None):
340 if sys
.platform
== 'darwin':
341 return MacChromeCookieDecryptor(browser_keyring_name
, logger
)
342 elif sys
.platform
in ('win32', 'cygwin'):
343 return WindowsChromeCookieDecryptor(browser_root
, logger
)
344 return LinuxChromeCookieDecryptor(browser_keyring_name
, logger
, keyring
=keyring
)
347 class LinuxChromeCookieDecryptor(ChromeCookieDecryptor
):
348 def __init__(self
, browser_keyring_name
, logger
, *, keyring
=None):
349 self
._logger
= logger
350 self
._v
10_key
= self
.derive_key(b
'peanuts')
351 password
= _get_linux_keyring_password(browser_keyring_name
, keyring
, logger
)
352 self
._v
11_key
= None if password
is None else self
.derive_key(password
)
353 self
._cookie
_counts
= {'v10': 0, 'v11': 0, 'other': 0}
356 def derive_key(password
):
358 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc
359 return pbkdf2_sha1(password
, salt
=b
'saltysalt', iterations
=1, key_length
=16)
361 def decrypt(self
, encrypted_value
):
362 version
= encrypted_value
[:3]
363 ciphertext
= encrypted_value
[3:]
365 if version
== b
'v10':
366 self
._cookie
_counts
['v10'] += 1
367 return _decrypt_aes_cbc(ciphertext
, self
._v
10_key
, self
._logger
)
369 elif version
== b
'v11':
370 self
._cookie
_counts
['v11'] += 1
371 if self
._v
11_key
is None:
372 self
._logger
.warning('cannot decrypt v11 cookies: no key found', only_once
=True)
374 return _decrypt_aes_cbc(ciphertext
, self
._v
11_key
, self
._logger
)
377 self
._cookie
_counts
['other'] += 1
381 class MacChromeCookieDecryptor(ChromeCookieDecryptor
):
382 def __init__(self
, browser_keyring_name
, logger
):
383 self
._logger
= logger
384 password
= _get_mac_keyring_password(browser_keyring_name
, logger
)
385 self
._v
10_key
= None if password
is None else self
.derive_key(password
)
386 self
._cookie
_counts
= {'v10': 0, 'other': 0}
389 def derive_key(password
):
391 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm
392 return pbkdf2_sha1(password
, salt
=b
'saltysalt', iterations
=1003, key_length
=16)
394 def decrypt(self
, encrypted_value
):
395 version
= encrypted_value
[:3]
396 ciphertext
= encrypted_value
[3:]
398 if version
== b
'v10':
399 self
._cookie
_counts
['v10'] += 1
400 if self
._v
10_key
is None:
401 self
._logger
.warning('cannot decrypt v10 cookies: no key found', only_once
=True)
404 return _decrypt_aes_cbc(ciphertext
, self
._v
10_key
, self
._logger
)
407 self
._cookie
_counts
['other'] += 1
408 # other prefixes are considered 'old data' which were stored as plaintext
409 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm
410 return encrypted_value
413 class WindowsChromeCookieDecryptor(ChromeCookieDecryptor
):
414 def __init__(self
, browser_root
, logger
):
415 self
._logger
= logger
416 self
._v
10_key
= _get_windows_v10_key(browser_root
, logger
)
417 self
._cookie
_counts
= {'v10': 0, 'other': 0}
419 def decrypt(self
, encrypted_value
):
420 version
= encrypted_value
[:3]
421 ciphertext
= encrypted_value
[3:]
423 if version
== b
'v10':
424 self
._cookie
_counts
['v10'] += 1
425 if self
._v
10_key
is None:
426 self
._logger
.warning('cannot decrypt v10 cookies: no key found', only_once
=True)
429 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc
431 nonce_length
= 96 // 8
433 # EVP_AEAD_AES_GCM_TAG_LEN
434 authentication_tag_length
= 16
436 raw_ciphertext
= ciphertext
437 nonce
= raw_ciphertext
[:nonce_length
]
438 ciphertext
= raw_ciphertext
[nonce_length
:-authentication_tag_length
]
439 authentication_tag
= raw_ciphertext
[-authentication_tag_length
:]
441 return _decrypt_aes_gcm(ciphertext
, self
._v
10_key
, nonce
, authentication_tag
, self
._logger
)
444 self
._cookie
_counts
['other'] += 1
445 # any other prefix means the data is DPAPI encrypted
446 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc
447 return _decrypt_windows_dpapi(encrypted_value
, self
._logger
).decode()
450 def _extract_safari_cookies(profile
, logger
):
451 if profile
is not None:
452 logger
.error('safari does not support profiles')
453 if sys
.platform
!= 'darwin':
454 raise ValueError(f
'unsupported platform: {sys.platform}')
456 cookies_path
= os
.path
.expanduser('~/Library/Cookies/Cookies.binarycookies')
458 if not os
.path
.isfile(cookies_path
):
459 logger
.debug('Trying secondary cookie location')
460 cookies_path
= os
.path
.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies')
461 if not os
.path
.isfile(cookies_path
):
462 raise FileNotFoundError('could not find safari cookies database')
464 with open(cookies_path
, 'rb') as f
:
465 cookies_data
= f
.read()
467 jar
= parse_safari_cookies(cookies_data
, logger
=logger
)
468 logger
.info(f
'Extracted {len(jar)} cookies from safari')
472 class ParserError(Exception):
477 def __init__(self
, data
, logger
):
480 self
._logger
= logger
482 def read_bytes(self
, num_bytes
):
484 raise ParserError(f
'invalid read of {num_bytes} bytes')
485 end
= self
.cursor
+ num_bytes
486 if end
> len(self
._data
):
487 raise ParserError('reached end of input')
488 data
= self
._data
[self
.cursor
:end
]
492 def expect_bytes(self
, expected_value
, message
):
493 value
= self
.read_bytes(len(expected_value
))
494 if value
!= expected_value
:
495 raise ParserError(f
'unexpected value: {value} != {expected_value} ({message})')
497 def read_uint(self
, big_endian
=False):
498 data_format
= '>I' if big_endian
else '<I'
499 return struct
.unpack(data_format
, self
.read_bytes(4))[0]
501 def read_double(self
, big_endian
=False):
502 data_format
= '>d' if big_endian
else '<d'
503 return struct
.unpack(data_format
, self
.read_bytes(8))[0]
505 def read_cstring(self
):
508 c
= self
.read_bytes(1)
510 return b
''.join(buffer).decode()
514 def skip(self
, num_bytes
, description
='unknown'):
516 self
._logger
.debug(f
'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}')
518 raise ParserError(f
'invalid skip of {num_bytes} bytes')
520 def skip_to(self
, offset
, description
='unknown'):
521 self
.skip(offset
- self
.cursor
, description
)
523 def skip_to_end(self
, description
='unknown'):
524 self
.skip_to(len(self
._data
), description
)
527 def _mac_absolute_time_to_posix(timestamp
):
528 return int((datetime(2001, 1, 1, 0, 0, tzinfo
=timezone
.utc
) + timedelta(seconds
=timestamp
)).timestamp())
531 def _parse_safari_cookies_header(data
, logger
):
532 p
= DataParser(data
, logger
)
533 p
.expect_bytes(b
'cook', 'database signature')
534 number_of_pages
= p
.read_uint(big_endian
=True)
535 page_sizes
= [p
.read_uint(big_endian
=True) for _
in range(number_of_pages
)]
536 return page_sizes
, p
.cursor
539 def _parse_safari_cookies_page(data
, jar
, logger
):
540 p
= DataParser(data
, logger
)
541 p
.expect_bytes(b
'\x00\x00\x01\x00', 'page signature')
542 number_of_cookies
= p
.read_uint()
543 record_offsets
= [p
.read_uint() for _
in range(number_of_cookies
)]
544 if number_of_cookies
== 0:
545 logger
.debug(f
'a cookies page of size {len(data)} has no cookies')
548 p
.skip_to(record_offsets
[0], 'unknown page header field')
550 with _create_progress_bar(logger
) as progress_bar
:
551 for i
, record_offset
in enumerate(record_offsets
):
552 progress_bar
.print(f
'Loading cookie {i: 6d}/{number_of_cookies: 6d}')
553 p
.skip_to(record_offset
, 'space between records')
554 record_length
= _parse_safari_cookies_record(data
[record_offset
:], jar
, logger
)
555 p
.read_bytes(record_length
)
556 p
.skip_to_end('space in between pages')
559 def _parse_safari_cookies_record(data
, jar
, logger
):
560 p
= DataParser(data
, logger
)
561 record_size
= p
.read_uint()
562 p
.skip(4, 'unknown record field 1')
563 flags
= p
.read_uint()
564 is_secure
= bool(flags
& 0x0001)
565 p
.skip(4, 'unknown record field 2')
566 domain_offset
= p
.read_uint()
567 name_offset
= p
.read_uint()
568 path_offset
= p
.read_uint()
569 value_offset
= p
.read_uint()
570 p
.skip(8, 'unknown record field 3')
571 expiration_date
= _mac_absolute_time_to_posix(p
.read_double())
572 _creation_date
= _mac_absolute_time_to_posix(p
.read_double()) # noqa: F841
575 p
.skip_to(domain_offset
)
576 domain
= p
.read_cstring()
578 p
.skip_to(name_offset
)
579 name
= p
.read_cstring()
581 p
.skip_to(path_offset
)
582 path
= p
.read_cstring()
584 p
.skip_to(value_offset
)
585 value
= p
.read_cstring()
586 except UnicodeDecodeError:
587 logger
.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once
=True)
590 p
.skip_to(record_size
, 'space at the end of the record')
592 cookie
= compat_cookiejar_Cookie(
593 version
=0, name
=name
, value
=value
, port
=None, port_specified
=False,
594 domain
=domain
, domain_specified
=bool(domain
), domain_initial_dot
=domain
.startswith('.'),
595 path
=path
, path_specified
=bool(path
), secure
=is_secure
, expires
=expiration_date
, discard
=False,
596 comment
=None, comment_url
=None, rest
={})
597 jar
.set_cookie(cookie
)
601 def parse_safari_cookies(data
, jar
=None, logger
=YDLLogger()):
604 - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc
605 - this data appears to be out of date but the important parts of the database structure is the same
606 - there are a few bytes here and there which are skipped during parsing
609 jar
= YoutubeDLCookieJar()
610 page_sizes
, body_start
= _parse_safari_cookies_header(data
, logger
)
611 p
= DataParser(data
[body_start
:], logger
)
612 for page_size
in page_sizes
:
613 _parse_safari_cookies_page(p
.read_bytes(page_size
), jar
, logger
)
614 p
.skip_to_end('footer')
618 class _LinuxDesktopEnvironment(Enum
):
620 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h
632 class _LinuxKeyring(Enum
):
634 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h
638 GNOMEKEYRING
= auto()
642 SUPPORTED_KEYRINGS
= _LinuxKeyring
.__members
__.keys()
645 def _get_linux_desktop_environment(env
):
647 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc
648 GetDesktopEnvironment
650 xdg_current_desktop
= env
.get('XDG_CURRENT_DESKTOP', None)
651 desktop_session
= env
.get('DESKTOP_SESSION', None)
652 if xdg_current_desktop
is not None:
653 xdg_current_desktop
= xdg_current_desktop
.split(':')[0].strip()
655 if xdg_current_desktop
== 'Unity':
656 if desktop_session
is not None and 'gnome-fallback' in desktop_session
:
657 return _LinuxDesktopEnvironment
.GNOME
659 return _LinuxDesktopEnvironment
.UNITY
660 elif xdg_current_desktop
== 'GNOME':
661 return _LinuxDesktopEnvironment
.GNOME
662 elif xdg_current_desktop
== 'X-Cinnamon':
663 return _LinuxDesktopEnvironment
.CINNAMON
664 elif xdg_current_desktop
== 'KDE':
665 return _LinuxDesktopEnvironment
.KDE
666 elif xdg_current_desktop
== 'Pantheon':
667 return _LinuxDesktopEnvironment
.PANTHEON
668 elif xdg_current_desktop
== 'XFCE':
669 return _LinuxDesktopEnvironment
.XFCE
670 elif desktop_session
is not None:
671 if desktop_session
in ('mate', 'gnome'):
672 return _LinuxDesktopEnvironment
.GNOME
673 elif 'kde' in desktop_session
:
674 return _LinuxDesktopEnvironment
.KDE
675 elif 'xfce' in desktop_session
:
676 return _LinuxDesktopEnvironment
.XFCE
678 if 'GNOME_DESKTOP_SESSION_ID' in env
:
679 return _LinuxDesktopEnvironment
.GNOME
680 elif 'KDE_FULL_SESSION' in env
:
681 return _LinuxDesktopEnvironment
.KDE
682 return _LinuxDesktopEnvironment
.OTHER
685 def _choose_linux_keyring(logger
):
687 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc
690 desktop_environment
= _get_linux_desktop_environment(os
.environ
)
691 logger
.debug(f
'detected desktop environment: {desktop_environment.name}')
692 if desktop_environment
== _LinuxDesktopEnvironment
.KDE
:
693 linux_keyring
= _LinuxKeyring
.KWALLET
694 elif desktop_environment
== _LinuxDesktopEnvironment
.OTHER
:
695 linux_keyring
= _LinuxKeyring
.BASICTEXT
697 linux_keyring
= _LinuxKeyring
.GNOMEKEYRING
701 def _get_kwallet_network_wallet(logger
):
702 """ The name of the wallet used to store network passwords.
704 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc
705 KWalletDBus::NetworkWallet
706 which does a dbus call to the following function:
707 https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html
708 Wallet::NetworkWallet
710 default_wallet
= 'kdewallet'
712 stdout
, _
, returncode
= Popen
.run([
713 'dbus-send', '--session', '--print-reply=literal',
714 '--dest=org.kde.kwalletd5',
715 '/modules/kwalletd5',
716 'org.kde.KWallet.networkWallet'
717 ], text
=True, stdout
=subprocess
.PIPE
, stderr
=subprocess
.DEVNULL
)
720 logger
.warning('failed to read NetworkWallet')
721 return default_wallet
723 logger
.debug(f
'NetworkWallet = "{stdout.strip()}"')
724 return stdout
.strip()
725 except Exception as e
:
726 logger
.warning(f
'exception while obtaining NetworkWallet: {e}')
727 return default_wallet
730 def _get_kwallet_password(browser_keyring_name
, logger
):
731 logger
.debug('using kwallet-query to obtain password from kwallet')
733 if shutil
.which('kwallet-query') is None:
734 logger
.error('kwallet-query command not found. KWallet and kwallet-query '
735 'must be installed to read from KWallet. kwallet-query should be'
736 'included in the kwallet package for your distribution')
739 network_wallet
= _get_kwallet_network_wallet(logger
)
742 stdout
, _
, returncode
= Popen
.run([
744 '--read-password', f
'{browser_keyring_name} Safe Storage',
745 '--folder', f
'{browser_keyring_name} Keys',
747 ], stdout
=subprocess
.PIPE
, stderr
=subprocess
.DEVNULL
)
750 logger
.error(f
'kwallet-query failed with return code {returncode}. '
751 'Please consult the kwallet-query man page for details')
754 if stdout
.lower().startswith(b
'failed to read'):
755 logger
.debug('failed to read password from kwallet. Using empty string instead')
756 # this sometimes occurs in KDE because chrome does not check hasEntry and instead
757 # just tries to read the value (which kwallet returns "") whereas kwallet-query
758 # checks hasEntry. To verify this:
759 # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
760 # while starting chrome.
761 # this may be a bug as the intended behaviour is to generate a random password and store
762 # it, but that doesn't matter here.
765 logger
.debug('password found')
766 return stdout
.rstrip(b
'\n')
767 except Exception as e
:
768 logger
.warning(f
'exception running kwallet-query: {error_to_str(e)}')
772 def _get_gnome_keyring_password(browser_keyring_name
, logger
):
773 if not secretstorage
:
774 logger
.error(f
'secretstorage not available {_SECRETSTORAGE_UNAVAILABLE_REASON}')
776 # the Gnome keyring does not seem to organise keys in the same way as KWallet,
777 # using `dbus-monitor` during startup, it can be observed that chromium lists all keys
778 # and presumably searches for its key in the list. It appears that we must do the same.
779 # https://github.com/jaraco/keyring/issues/556
780 with contextlib
.closing(secretstorage
.dbus_init()) as con
:
781 col
= secretstorage
.get_default_collection(con
)
782 for item
in col
.get_all_items():
783 if item
.get_label() == f
'{browser_keyring_name} Safe Storage':
784 return item
.get_secret()
786 logger
.error('failed to read from keyring')
790 def _get_linux_keyring_password(browser_keyring_name
, keyring
, logger
):
791 # note: chrome/chromium can be run with the following flags to determine which keyring backend
792 # it has chosen to use
793 # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_
794 # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection
795 # will not be sufficient in all cases.
797 keyring
= _LinuxKeyring
[keyring
] if keyring
else _choose_linux_keyring(logger
)
798 logger
.debug(f
'Chosen keyring: {keyring.name}')
800 if keyring
== _LinuxKeyring
.KWALLET
:
801 return _get_kwallet_password(browser_keyring_name
, logger
)
802 elif keyring
== _LinuxKeyring
.GNOMEKEYRING
:
803 return _get_gnome_keyring_password(browser_keyring_name
, logger
)
804 elif keyring
== _LinuxKeyring
.BASICTEXT
:
805 # when basic text is chosen, all cookies are stored as v10 (so no keyring password is required)
807 assert False, f
'Unknown keyring {keyring}'
810 def _get_mac_keyring_password(browser_keyring_name
, logger
):
811 logger
.debug('using find-generic-password to obtain password from OSX keychain')
813 stdout
, _
, _
= Popen
.run(
814 ['security', 'find-generic-password',
815 '-w', # write password to stdout
816 '-a', browser_keyring_name
, # match 'account'
817 '-s', f
'{browser_keyring_name} Safe Storage'], # match 'service'
818 stdout
=subprocess
.PIPE
, stderr
=subprocess
.DEVNULL
)
819 return stdout
.rstrip(b
'\n')
820 except Exception as e
:
821 logger
.warning(f
'exception running find-generic-password: {error_to_str(e)}')
825 def _get_windows_v10_key(browser_root
, logger
):
826 path
= _find_most_recently_used_file(browser_root
, 'Local State', logger
)
828 logger
.error('could not find local state file')
830 logger
.debug(f
'Found local state file at "{path}"')
831 with open(path
, encoding
='utf8') as f
:
834 base64_key
= data
['os_crypt']['encrypted_key']
836 logger
.error('no encrypted key in Local State')
838 encrypted_key
= compat_b64decode(base64_key
)
840 if not encrypted_key
.startswith(prefix
):
841 logger
.error('invalid key')
843 return _decrypt_windows_dpapi(encrypted_key
[len(prefix
):], logger
)
846 def pbkdf2_sha1(password
, salt
, iterations
, key_length
):
847 return pbkdf2_hmac('sha1', password
, salt
, iterations
, key_length
)
850 def _decrypt_aes_cbc(ciphertext
, key
, logger
, initialization_vector
=b
' ' * 16):
851 plaintext
= unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext
, key
, initialization_vector
))
853 return plaintext
.decode()
854 except UnicodeDecodeError:
855 logger
.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once
=True)
859 def _decrypt_aes_gcm(ciphertext
, key
, nonce
, authentication_tag
, logger
):
861 plaintext
= aes_gcm_decrypt_and_verify_bytes(ciphertext
, key
, authentication_tag
, nonce
)
863 logger
.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?', only_once
=True)
867 return plaintext
.decode()
868 except UnicodeDecodeError:
869 logger
.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?', only_once
=True)
873 def _decrypt_windows_dpapi(ciphertext
, logger
):
876 - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata
878 from ctypes
.wintypes
import DWORD
880 class DATA_BLOB(ctypes
.Structure
):
881 _fields_
= [('cbData', DWORD
),
882 ('pbData', ctypes
.POINTER(ctypes
.c_char
))]
884 buffer = ctypes
.create_string_buffer(ciphertext
)
885 blob_in
= DATA_BLOB(ctypes
.sizeof(buffer), buffer)
886 blob_out
= DATA_BLOB()
887 ret
= ctypes
.windll
.crypt32
.CryptUnprotectData(
888 ctypes
.byref(blob_in
), # pDataIn
889 None, # ppszDataDescr: human readable description of pDataIn
890 None, # pOptionalEntropy: salt?
891 None, # pvReserved: must be NULL
892 None, # pPromptStruct: information about prompts to display
894 ctypes
.byref(blob_out
) # pDataOut
897 logger
.warning('failed to decrypt with DPAPI', only_once
=True)
900 result
= ctypes
.string_at(blob_out
.pbData
, blob_out
.cbData
)
901 ctypes
.windll
.kernel32
.LocalFree(blob_out
.pbData
)
906 return os
.environ
.get('XDG_CONFIG_HOME', os
.path
.expanduser('~/.config'))
909 def _open_database_copy(database_path
, tmpdir
):
910 # cannot open sqlite databases if they are already in use (e.g. by the browser)
911 database_copy_path
= os
.path
.join(tmpdir
, 'temporary.sqlite')
912 shutil
.copy(database_path
, database_copy_path
)
913 conn
= sqlite3
.connect(database_copy_path
)
917 def _get_column_names(cursor
, table_name
):
918 table_info
= cursor
.execute(f
'PRAGMA table_info({table_name})').fetchall()
919 return [row
[1].decode() for row
in table_info
]
922 def _find_most_recently_used_file(root
, filename
, logger
):
923 # if there are multiple browser profiles, take the most recently used one
925 with _create_progress_bar(logger
) as progress_bar
:
926 for curr_root
, dirs
, files
in os
.walk(root
):
929 progress_bar
.print(f
'Searching for "{filename}": {i: 6d} files searched')
931 paths
.append(os
.path
.join(curr_root
, file))
932 return None if not paths
else max(paths
, key
=lambda path
: os
.lstat(path
).st_mtime
)
935 def _merge_cookie_jars(jars
):
936 output_jar
= YoutubeDLCookieJar()
939 output_jar
.set_cookie(cookie
)
940 if jar
.filename
is not None:
941 output_jar
.filename
= jar
.filename
946 return os
.path
.sep
in value
949 def _parse_browser_specification(browser_name
, profile
=None, keyring
=None):
950 if browser_name
not in SUPPORTED_BROWSERS
:
951 raise ValueError(f
'unsupported browser: "{browser_name}"')
952 if keyring
not in (None, *SUPPORTED_KEYRINGS
):
953 raise ValueError(f
'unsupported keyring: "{keyring}"')
954 if profile
is not None and _is_path(profile
):
955 profile
= os
.path
.expanduser(profile
)
956 return browser_name
, profile
, keyring