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
in ('linux', 'linux2'):
341 return LinuxChromeCookieDecryptor(browser_keyring_name
, logger
, keyring
=keyring
)
342 elif sys
.platform
== 'darwin':
343 return MacChromeCookieDecryptor(browser_keyring_name
, logger
)
344 elif sys
.platform
== 'win32':
345 return WindowsChromeCookieDecryptor(browser_root
, logger
)
347 raise NotImplementedError(f
'Chrome cookie decryption is not supported on this platform: {sys.platform}')
350 class LinuxChromeCookieDecryptor(ChromeCookieDecryptor
):
351 def __init__(self
, browser_keyring_name
, logger
, *, keyring
=None):
352 self
._logger
= logger
353 self
._v
10_key
= self
.derive_key(b
'peanuts')
354 password
= _get_linux_keyring_password(browser_keyring_name
, keyring
, logger
)
355 self
._v
11_key
= None if password
is None else self
.derive_key(password
)
356 self
._cookie
_counts
= {'v10': 0, 'v11': 0, 'other': 0}
359 def derive_key(password
):
361 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc
362 return pbkdf2_sha1(password
, salt
=b
'saltysalt', iterations
=1, key_length
=16)
364 def decrypt(self
, encrypted_value
):
365 version
= encrypted_value
[:3]
366 ciphertext
= encrypted_value
[3:]
368 if version
== b
'v10':
369 self
._cookie
_counts
['v10'] += 1
370 return _decrypt_aes_cbc(ciphertext
, self
._v
10_key
, self
._logger
)
372 elif version
== b
'v11':
373 self
._cookie
_counts
['v11'] += 1
374 if self
._v
11_key
is None:
375 self
._logger
.warning('cannot decrypt v11 cookies: no key found', only_once
=True)
377 return _decrypt_aes_cbc(ciphertext
, self
._v
11_key
, self
._logger
)
380 self
._cookie
_counts
['other'] += 1
384 class MacChromeCookieDecryptor(ChromeCookieDecryptor
):
385 def __init__(self
, browser_keyring_name
, logger
):
386 self
._logger
= logger
387 password
= _get_mac_keyring_password(browser_keyring_name
, logger
)
388 self
._v
10_key
= None if password
is None else self
.derive_key(password
)
389 self
._cookie
_counts
= {'v10': 0, 'other': 0}
392 def derive_key(password
):
394 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm
395 return pbkdf2_sha1(password
, salt
=b
'saltysalt', iterations
=1003, key_length
=16)
397 def decrypt(self
, encrypted_value
):
398 version
= encrypted_value
[:3]
399 ciphertext
= encrypted_value
[3:]
401 if version
== b
'v10':
402 self
._cookie
_counts
['v10'] += 1
403 if self
._v
10_key
is None:
404 self
._logger
.warning('cannot decrypt v10 cookies: no key found', only_once
=True)
407 return _decrypt_aes_cbc(ciphertext
, self
._v
10_key
, self
._logger
)
410 self
._cookie
_counts
['other'] += 1
411 # other prefixes are considered 'old data' which were stored as plaintext
412 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm
413 return encrypted_value
416 class WindowsChromeCookieDecryptor(ChromeCookieDecryptor
):
417 def __init__(self
, browser_root
, logger
):
418 self
._logger
= logger
419 self
._v
10_key
= _get_windows_v10_key(browser_root
, logger
)
420 self
._cookie
_counts
= {'v10': 0, 'other': 0}
422 def decrypt(self
, encrypted_value
):
423 version
= encrypted_value
[:3]
424 ciphertext
= encrypted_value
[3:]
426 if version
== b
'v10':
427 self
._cookie
_counts
['v10'] += 1
428 if self
._v
10_key
is None:
429 self
._logger
.warning('cannot decrypt v10 cookies: no key found', only_once
=True)
432 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc
434 nonce_length
= 96 // 8
436 # EVP_AEAD_AES_GCM_TAG_LEN
437 authentication_tag_length
= 16
439 raw_ciphertext
= ciphertext
440 nonce
= raw_ciphertext
[:nonce_length
]
441 ciphertext
= raw_ciphertext
[nonce_length
:-authentication_tag_length
]
442 authentication_tag
= raw_ciphertext
[-authentication_tag_length
:]
444 return _decrypt_aes_gcm(ciphertext
, self
._v
10_key
, nonce
, authentication_tag
, self
._logger
)
447 self
._cookie
_counts
['other'] += 1
448 # any other prefix means the data is DPAPI encrypted
449 # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc
450 return _decrypt_windows_dpapi(encrypted_value
, self
._logger
).decode()
453 def _extract_safari_cookies(profile
, logger
):
454 if profile
is not None:
455 logger
.error('safari does not support profiles')
456 if sys
.platform
!= 'darwin':
457 raise ValueError(f
'unsupported platform: {sys.platform}')
459 cookies_path
= os
.path
.expanduser('~/Library/Cookies/Cookies.binarycookies')
461 if not os
.path
.isfile(cookies_path
):
462 logger
.debug('Trying secondary cookie location')
463 cookies_path
= os
.path
.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies')
464 if not os
.path
.isfile(cookies_path
):
465 raise FileNotFoundError('could not find safari cookies database')
467 with open(cookies_path
, 'rb') as f
:
468 cookies_data
= f
.read()
470 jar
= parse_safari_cookies(cookies_data
, logger
=logger
)
471 logger
.info(f
'Extracted {len(jar)} cookies from safari')
475 class ParserError(Exception):
480 def __init__(self
, data
, logger
):
483 self
._logger
= logger
485 def read_bytes(self
, num_bytes
):
487 raise ParserError(f
'invalid read of {num_bytes} bytes')
488 end
= self
.cursor
+ num_bytes
489 if end
> len(self
._data
):
490 raise ParserError('reached end of input')
491 data
= self
._data
[self
.cursor
:end
]
495 def expect_bytes(self
, expected_value
, message
):
496 value
= self
.read_bytes(len(expected_value
))
497 if value
!= expected_value
:
498 raise ParserError(f
'unexpected value: {value} != {expected_value} ({message})')
500 def read_uint(self
, big_endian
=False):
501 data_format
= '>I' if big_endian
else '<I'
502 return struct
.unpack(data_format
, self
.read_bytes(4))[0]
504 def read_double(self
, big_endian
=False):
505 data_format
= '>d' if big_endian
else '<d'
506 return struct
.unpack(data_format
, self
.read_bytes(8))[0]
508 def read_cstring(self
):
511 c
= self
.read_bytes(1)
513 return b
''.join(buffer).decode()
517 def skip(self
, num_bytes
, description
='unknown'):
519 self
._logger
.debug(f
'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}')
521 raise ParserError(f
'invalid skip of {num_bytes} bytes')
523 def skip_to(self
, offset
, description
='unknown'):
524 self
.skip(offset
- self
.cursor
, description
)
526 def skip_to_end(self
, description
='unknown'):
527 self
.skip_to(len(self
._data
), description
)
530 def _mac_absolute_time_to_posix(timestamp
):
531 return int((datetime(2001, 1, 1, 0, 0, tzinfo
=timezone
.utc
) + timedelta(seconds
=timestamp
)).timestamp())
534 def _parse_safari_cookies_header(data
, logger
):
535 p
= DataParser(data
, logger
)
536 p
.expect_bytes(b
'cook', 'database signature')
537 number_of_pages
= p
.read_uint(big_endian
=True)
538 page_sizes
= [p
.read_uint(big_endian
=True) for _
in range(number_of_pages
)]
539 return page_sizes
, p
.cursor
542 def _parse_safari_cookies_page(data
, jar
, logger
):
543 p
= DataParser(data
, logger
)
544 p
.expect_bytes(b
'\x00\x00\x01\x00', 'page signature')
545 number_of_cookies
= p
.read_uint()
546 record_offsets
= [p
.read_uint() for _
in range(number_of_cookies
)]
547 if number_of_cookies
== 0:
548 logger
.debug(f
'a cookies page of size {len(data)} has no cookies')
551 p
.skip_to(record_offsets
[0], 'unknown page header field')
553 with _create_progress_bar(logger
) as progress_bar
:
554 for i
, record_offset
in enumerate(record_offsets
):
555 progress_bar
.print(f
'Loading cookie {i: 6d}/{number_of_cookies: 6d}')
556 p
.skip_to(record_offset
, 'space between records')
557 record_length
= _parse_safari_cookies_record(data
[record_offset
:], jar
, logger
)
558 p
.read_bytes(record_length
)
559 p
.skip_to_end('space in between pages')
562 def _parse_safari_cookies_record(data
, jar
, logger
):
563 p
= DataParser(data
, logger
)
564 record_size
= p
.read_uint()
565 p
.skip(4, 'unknown record field 1')
566 flags
= p
.read_uint()
567 is_secure
= bool(flags
& 0x0001)
568 p
.skip(4, 'unknown record field 2')
569 domain_offset
= p
.read_uint()
570 name_offset
= p
.read_uint()
571 path_offset
= p
.read_uint()
572 value_offset
= p
.read_uint()
573 p
.skip(8, 'unknown record field 3')
574 expiration_date
= _mac_absolute_time_to_posix(p
.read_double())
575 _creation_date
= _mac_absolute_time_to_posix(p
.read_double()) # noqa: F841
578 p
.skip_to(domain_offset
)
579 domain
= p
.read_cstring()
581 p
.skip_to(name_offset
)
582 name
= p
.read_cstring()
584 p
.skip_to(path_offset
)
585 path
= p
.read_cstring()
587 p
.skip_to(value_offset
)
588 value
= p
.read_cstring()
589 except UnicodeDecodeError:
590 logger
.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once
=True)
593 p
.skip_to(record_size
, 'space at the end of the record')
595 cookie
= compat_cookiejar_Cookie(
596 version
=0, name
=name
, value
=value
, port
=None, port_specified
=False,
597 domain
=domain
, domain_specified
=bool(domain
), domain_initial_dot
=domain
.startswith('.'),
598 path
=path
, path_specified
=bool(path
), secure
=is_secure
, expires
=expiration_date
, discard
=False,
599 comment
=None, comment_url
=None, rest
={})
600 jar
.set_cookie(cookie
)
604 def parse_safari_cookies(data
, jar
=None, logger
=YDLLogger()):
607 - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc
608 - this data appears to be out of date but the important parts of the database structure is the same
609 - there are a few bytes here and there which are skipped during parsing
612 jar
= YoutubeDLCookieJar()
613 page_sizes
, body_start
= _parse_safari_cookies_header(data
, logger
)
614 p
= DataParser(data
[body_start
:], logger
)
615 for page_size
in page_sizes
:
616 _parse_safari_cookies_page(p
.read_bytes(page_size
), jar
, logger
)
617 p
.skip_to_end('footer')
621 class _LinuxDesktopEnvironment(Enum
):
623 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h
635 class _LinuxKeyring(Enum
):
637 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h
641 GNOMEKEYRING
= auto()
645 SUPPORTED_KEYRINGS
= _LinuxKeyring
.__members
__.keys()
648 def _get_linux_desktop_environment(env
):
650 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc
651 GetDesktopEnvironment
653 xdg_current_desktop
= env
.get('XDG_CURRENT_DESKTOP', None)
654 desktop_session
= env
.get('DESKTOP_SESSION', None)
655 if xdg_current_desktop
is not None:
656 xdg_current_desktop
= xdg_current_desktop
.split(':')[0].strip()
658 if xdg_current_desktop
== 'Unity':
659 if desktop_session
is not None and 'gnome-fallback' in desktop_session
:
660 return _LinuxDesktopEnvironment
.GNOME
662 return _LinuxDesktopEnvironment
.UNITY
663 elif xdg_current_desktop
== 'GNOME':
664 return _LinuxDesktopEnvironment
.GNOME
665 elif xdg_current_desktop
== 'X-Cinnamon':
666 return _LinuxDesktopEnvironment
.CINNAMON
667 elif xdg_current_desktop
== 'KDE':
668 return _LinuxDesktopEnvironment
.KDE
669 elif xdg_current_desktop
== 'Pantheon':
670 return _LinuxDesktopEnvironment
.PANTHEON
671 elif xdg_current_desktop
== 'XFCE':
672 return _LinuxDesktopEnvironment
.XFCE
673 elif desktop_session
is not None:
674 if desktop_session
in ('mate', 'gnome'):
675 return _LinuxDesktopEnvironment
.GNOME
676 elif 'kde' in desktop_session
:
677 return _LinuxDesktopEnvironment
.KDE
678 elif 'xfce' in desktop_session
:
679 return _LinuxDesktopEnvironment
.XFCE
681 if 'GNOME_DESKTOP_SESSION_ID' in env
:
682 return _LinuxDesktopEnvironment
.GNOME
683 elif 'KDE_FULL_SESSION' in env
:
684 return _LinuxDesktopEnvironment
.KDE
685 return _LinuxDesktopEnvironment
.OTHER
688 def _choose_linux_keyring(logger
):
690 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc
693 desktop_environment
= _get_linux_desktop_environment(os
.environ
)
694 logger
.debug(f
'detected desktop environment: {desktop_environment.name}')
695 if desktop_environment
== _LinuxDesktopEnvironment
.KDE
:
696 linux_keyring
= _LinuxKeyring
.KWALLET
697 elif desktop_environment
== _LinuxDesktopEnvironment
.OTHER
:
698 linux_keyring
= _LinuxKeyring
.BASICTEXT
700 linux_keyring
= _LinuxKeyring
.GNOMEKEYRING
704 def _get_kwallet_network_wallet(logger
):
705 """ The name of the wallet used to store network passwords.
707 https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc
708 KWalletDBus::NetworkWallet
709 which does a dbus call to the following function:
710 https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html
711 Wallet::NetworkWallet
713 default_wallet
= 'kdewallet'
716 'dbus-send', '--session', '--print-reply=literal',
717 '--dest=org.kde.kwalletd5',
718 '/modules/kwalletd5',
719 'org.kde.KWallet.networkWallet'
720 ], stdout
=subprocess
.PIPE
, stderr
=subprocess
.DEVNULL
)
722 stdout
, stderr
= proc
.communicate_or_kill()
723 if proc
.returncode
!= 0:
724 logger
.warning('failed to read NetworkWallet')
725 return default_wallet
727 network_wallet
= stdout
.decode().strip()
728 logger
.debug(f
'NetworkWallet = "{network_wallet}"')
729 return network_wallet
730 except Exception as e
:
731 logger
.warning(f
'exception while obtaining NetworkWallet: {e}')
732 return default_wallet
735 def _get_kwallet_password(browser_keyring_name
, logger
):
736 logger
.debug('using kwallet-query to obtain password from kwallet')
738 if shutil
.which('kwallet-query') is None:
739 logger
.error('kwallet-query command not found. KWallet and kwallet-query '
740 'must be installed to read from KWallet. kwallet-query should be'
741 'included in the kwallet package for your distribution')
744 network_wallet
= _get_kwallet_network_wallet(logger
)
749 '--read-password', f
'{browser_keyring_name} Safe Storage',
750 '--folder', f
'{browser_keyring_name} Keys',
752 ], stdout
=subprocess
.PIPE
, stderr
=subprocess
.DEVNULL
)
754 stdout
, stderr
= proc
.communicate_or_kill()
755 if proc
.returncode
!= 0:
756 logger
.error(f
'kwallet-query failed with return code {proc.returncode}. Please consult '
757 'the kwallet-query man page for details')
760 if stdout
.lower().startswith(b
'failed to read'):
761 logger
.debug('failed to read password from kwallet. Using empty string instead')
762 # this sometimes occurs in KDE because chrome does not check hasEntry and instead
763 # just tries to read the value (which kwallet returns "") whereas kwallet-query
764 # checks hasEntry. To verify this:
765 # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
766 # while starting chrome.
767 # this may be a bug as the intended behaviour is to generate a random password and store
768 # it, but that doesn't matter here.
771 logger
.debug('password found')
772 if stdout
[-1:] == b
'\n':
775 except Exception as e
:
776 logger
.warning(f
'exception running kwallet-query: {error_to_str(e)}')
780 def _get_gnome_keyring_password(browser_keyring_name
, logger
):
781 if not secretstorage
:
782 logger
.error(f
'secretstorage not available {_SECRETSTORAGE_UNAVAILABLE_REASON}')
784 # the Gnome keyring does not seem to organise keys in the same way as KWallet,
785 # using `dbus-monitor` during startup, it can be observed that chromium lists all keys
786 # and presumably searches for its key in the list. It appears that we must do the same.
787 # https://github.com/jaraco/keyring/issues/556
788 with contextlib
.closing(secretstorage
.dbus_init()) as con
:
789 col
= secretstorage
.get_default_collection(con
)
790 for item
in col
.get_all_items():
791 if item
.get_label() == f
'{browser_keyring_name} Safe Storage':
792 return item
.get_secret()
794 logger
.error('failed to read from keyring')
798 def _get_linux_keyring_password(browser_keyring_name
, keyring
, logger
):
799 # note: chrome/chromium can be run with the following flags to determine which keyring backend
800 # it has chosen to use
801 # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_
802 # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection
803 # will not be sufficient in all cases.
805 keyring
= _LinuxKeyring
[keyring
] if keyring
else _choose_linux_keyring(logger
)
806 logger
.debug(f
'Chosen keyring: {keyring.name}')
808 if keyring
== _LinuxKeyring
.KWALLET
:
809 return _get_kwallet_password(browser_keyring_name
, logger
)
810 elif keyring
== _LinuxKeyring
.GNOMEKEYRING
:
811 return _get_gnome_keyring_password(browser_keyring_name
, logger
)
812 elif keyring
== _LinuxKeyring
.BASICTEXT
:
813 # when basic text is chosen, all cookies are stored as v10 (so no keyring password is required)
815 assert False, f
'Unknown keyring {keyring}'
818 def _get_mac_keyring_password(browser_keyring_name
, logger
):
819 logger
.debug('using find-generic-password to obtain password from OSX keychain')
822 ['security', 'find-generic-password',
823 '-w', # write password to stdout
824 '-a', browser_keyring_name
, # match 'account'
825 '-s', f
'{browser_keyring_name} Safe Storage'], # match 'service'
826 stdout
=subprocess
.PIPE
, stderr
=subprocess
.DEVNULL
)
828 stdout
, stderr
= proc
.communicate_or_kill()
829 if stdout
[-1:] == b
'\n':
832 except Exception as e
:
833 logger
.warning(f
'exception running find-generic-password: {error_to_str(e)}')
837 def _get_windows_v10_key(browser_root
, logger
):
838 path
= _find_most_recently_used_file(browser_root
, 'Local State', logger
)
840 logger
.error('could not find local state file')
842 logger
.debug(f
'Found local state file at "{path}"')
843 with open(path
, encoding
='utf8') as f
:
846 base64_key
= data
['os_crypt']['encrypted_key']
848 logger
.error('no encrypted key in Local State')
850 encrypted_key
= compat_b64decode(base64_key
)
852 if not encrypted_key
.startswith(prefix
):
853 logger
.error('invalid key')
855 return _decrypt_windows_dpapi(encrypted_key
[len(prefix
):], logger
)
858 def pbkdf2_sha1(password
, salt
, iterations
, key_length
):
859 return pbkdf2_hmac('sha1', password
, salt
, iterations
, key_length
)
862 def _decrypt_aes_cbc(ciphertext
, key
, logger
, initialization_vector
=b
' ' * 16):
863 plaintext
= unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext
, key
, initialization_vector
))
865 return plaintext
.decode()
866 except UnicodeDecodeError:
867 logger
.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once
=True)
871 def _decrypt_aes_gcm(ciphertext
, key
, nonce
, authentication_tag
, logger
):
873 plaintext
= aes_gcm_decrypt_and_verify_bytes(ciphertext
, key
, authentication_tag
, nonce
)
875 logger
.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?', only_once
=True)
879 return plaintext
.decode()
880 except UnicodeDecodeError:
881 logger
.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?', only_once
=True)
885 def _decrypt_windows_dpapi(ciphertext
, logger
):
888 - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata
890 from ctypes
.wintypes
import DWORD
892 class DATA_BLOB(ctypes
.Structure
):
893 _fields_
= [('cbData', DWORD
),
894 ('pbData', ctypes
.POINTER(ctypes
.c_char
))]
896 buffer = ctypes
.create_string_buffer(ciphertext
)
897 blob_in
= DATA_BLOB(ctypes
.sizeof(buffer), buffer)
898 blob_out
= DATA_BLOB()
899 ret
= ctypes
.windll
.crypt32
.CryptUnprotectData(
900 ctypes
.byref(blob_in
), # pDataIn
901 None, # ppszDataDescr: human readable description of pDataIn
902 None, # pOptionalEntropy: salt?
903 None, # pvReserved: must be NULL
904 None, # pPromptStruct: information about prompts to display
906 ctypes
.byref(blob_out
) # pDataOut
909 logger
.warning('failed to decrypt with DPAPI', only_once
=True)
912 result
= ctypes
.string_at(blob_out
.pbData
, blob_out
.cbData
)
913 ctypes
.windll
.kernel32
.LocalFree(blob_out
.pbData
)
918 return os
.environ
.get('XDG_CONFIG_HOME', os
.path
.expanduser('~/.config'))
921 def _open_database_copy(database_path
, tmpdir
):
922 # cannot open sqlite databases if they are already in use (e.g. by the browser)
923 database_copy_path
= os
.path
.join(tmpdir
, 'temporary.sqlite')
924 shutil
.copy(database_path
, database_copy_path
)
925 conn
= sqlite3
.connect(database_copy_path
)
929 def _get_column_names(cursor
, table_name
):
930 table_info
= cursor
.execute(f
'PRAGMA table_info({table_name})').fetchall()
931 return [row
[1].decode() for row
in table_info
]
934 def _find_most_recently_used_file(root
, filename
, logger
):
935 # if there are multiple browser profiles, take the most recently used one
937 with _create_progress_bar(logger
) as progress_bar
:
938 for curr_root
, dirs
, files
in os
.walk(root
):
941 progress_bar
.print(f
'Searching for "{filename}": {i: 6d} files searched')
943 paths
.append(os
.path
.join(curr_root
, file))
944 return None if not paths
else max(paths
, key
=lambda path
: os
.lstat(path
).st_mtime
)
947 def _merge_cookie_jars(jars
):
948 output_jar
= YoutubeDLCookieJar()
951 output_jar
.set_cookie(cookie
)
952 if jar
.filename
is not None:
953 output_jar
.filename
= jar
.filename
958 return os
.path
.sep
in value
961 def _parse_browser_specification(browser_name
, profile
=None, keyring
=None):
962 if browser_name
not in SUPPORTED_BROWSERS
:
963 raise ValueError(f
'unsupported browser: "{browser_name}"')
964 if keyring
not in (None, *SUPPORTED_KEYRINGS
):
965 raise ValueError(f
'unsupported keyring: "{keyring}"')
966 if profile
is not None and _is_path(profile
):
967 profile
= os
.path
.expanduser(profile
)
968 return browser_name
, profile
, keyring