cookies.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  1. import base64
  2. import collections
  3. import contextlib
  4. import datetime as dt
  5. import functools
  6. import glob
  7. import hashlib
  8. import http.cookiejar
  9. import http.cookies
  10. import io
  11. import json
  12. import os
  13. import re
  14. import shutil
  15. import struct
  16. import subprocess
  17. import sys
  18. import tempfile
  19. import time
  20. import urllib.request
  21. from enum import Enum, auto
  22. from .aes import (
  23. aes_cbc_decrypt_bytes,
  24. aes_gcm_decrypt_and_verify_bytes,
  25. unpad_pkcs7,
  26. )
  27. from .compat import compat_os_name
  28. from .dependencies import (
  29. _SECRETSTORAGE_UNAVAILABLE_REASON,
  30. secretstorage,
  31. sqlite3,
  32. )
  33. from .minicurses import MultilinePrinter, QuietMultilinePrinter
  34. from .utils import (
  35. DownloadError,
  36. YoutubeDLError,
  37. Popen,
  38. error_to_str,
  39. expand_path,
  40. is_path_like,
  41. sanitize_url,
  42. str_or_none,
  43. try_call,
  44. write_string,
  45. )
  46. from .utils._utils import _YDLLogger
  47. from .utils.networking import normalize_url
  48. CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi', 'whale'}
  49. SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'}
  50. class YDLLogger(_YDLLogger):
  51. def warning(self, message, only_once=False): # compat
  52. return super().warning(message, once=only_once)
  53. class ProgressBar(MultilinePrinter):
  54. _DELAY, _timer = 0.1, 0
  55. def print(self, message):
  56. if time.time() - self._timer > self._DELAY:
  57. self.print_at_line(f'[Cookies] {message}', 0)
  58. self._timer = time.time()
  59. def progress_bar(self):
  60. """Return a context manager with a print method. (Optional)"""
  61. # Do not print to files/pipes, loggers, or when --no-progress is used
  62. if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'):
  63. return
  64. file = self._ydl._out_files.error
  65. try:
  66. if not file.isatty():
  67. return
  68. except BaseException:
  69. return
  70. return self.ProgressBar(file, preserve_output=False)
  71. def _create_progress_bar(logger):
  72. if hasattr(logger, 'progress_bar'):
  73. printer = logger.progress_bar()
  74. if printer:
  75. return printer
  76. printer = QuietMultilinePrinter()
  77. printer.print = lambda _: None
  78. return printer
  79. class CookieLoadError(YoutubeDLError):
  80. pass
  81. def load_cookies(cookie_file, browser_specification, ydl):
  82. try:
  83. cookie_jars = []
  84. if browser_specification is not None:
  85. browser_name, profile, keyring, container = _parse_browser_specification(*browser_specification)
  86. cookie_jars.append(
  87. extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring, container=container))
  88. if cookie_file is not None:
  89. is_filename = is_path_like(cookie_file)
  90. if is_filename:
  91. cookie_file = expand_path(cookie_file)
  92. jar = YoutubeDLCookieJar(cookie_file)
  93. if not is_filename or os.access(cookie_file, os.R_OK):
  94. jar.load()
  95. cookie_jars.append(jar)
  96. return _merge_cookie_jars(cookie_jars)
  97. except Exception:
  98. raise CookieLoadError('failed to load cookies')
  99. def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None, container=None):
  100. if browser_name == 'firefox':
  101. return _extract_firefox_cookies(profile, container, logger)
  102. elif browser_name == 'safari':
  103. return _extract_safari_cookies(profile, logger)
  104. elif browser_name in CHROMIUM_BASED_BROWSERS:
  105. return _extract_chrome_cookies(browser_name, profile, keyring, logger)
  106. else:
  107. raise ValueError(f'unknown browser: {browser_name}')
  108. def _extract_firefox_cookies(profile, container, logger):
  109. logger.info('Extracting cookies from firefox')
  110. if not sqlite3:
  111. logger.warning('Cannot extract cookies from firefox without sqlite3 support. '
  112. 'Please use a Python interpreter compiled with sqlite3 support')
  113. return YoutubeDLCookieJar()
  114. if profile is None:
  115. search_roots = list(_firefox_browser_dirs())
  116. elif _is_path(profile):
  117. search_roots = [profile]
  118. else:
  119. search_roots = [os.path.join(path, profile) for path in _firefox_browser_dirs()]
  120. search_root = ', '.join(map(repr, search_roots))
  121. cookie_database_path = _newest(_firefox_cookie_dbs(search_roots))
  122. if cookie_database_path is None:
  123. raise FileNotFoundError(f'could not find firefox cookies database in {search_root}')
  124. logger.debug(f'Extracting cookies from: "{cookie_database_path}"')
  125. container_id = None
  126. if container not in (None, 'none'):
  127. containers_path = os.path.join(os.path.dirname(cookie_database_path), 'containers.json')
  128. if not os.path.isfile(containers_path) or not os.access(containers_path, os.R_OK):
  129. raise FileNotFoundError(f'could not read containers.json in {search_root}')
  130. with open(containers_path, encoding='utf8') as containers:
  131. identities = json.load(containers).get('identities', [])
  132. container_id = next((context.get('userContextId') for context in identities if container in (
  133. context.get('name'),
  134. try_call(lambda: re.fullmatch(r'userContext([^\.]+)\.label', context['l10nID']).group()),
  135. )), None)
  136. if not isinstance(container_id, int):
  137. raise ValueError(f'could not find firefox container "{container}" in containers.json')
  138. with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:
  139. cursor = None
  140. try:
  141. cursor = _open_database_copy(cookie_database_path, tmpdir)
  142. if isinstance(container_id, int):
  143. logger.debug(
  144. f'Only loading cookies from firefox container "{container}", ID {container_id}')
  145. cursor.execute(
  146. 'SELECT host, name, value, path, expiry, isSecure FROM moz_cookies WHERE originAttributes LIKE ? OR originAttributes LIKE ?',
  147. (f'%userContextId={container_id}', f'%userContextId={container_id}&%'))
  148. elif container == 'none':
  149. logger.debug('Only loading cookies not belonging to any container')
  150. cursor.execute(
  151. 'SELECT host, name, value, path, expiry, isSecure FROM moz_cookies WHERE NOT INSTR(originAttributes,"userContextId=")')
  152. else:
  153. cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies')
  154. jar = YoutubeDLCookieJar()
  155. with _create_progress_bar(logger) as progress_bar:
  156. table = cursor.fetchall()
  157. total_cookie_count = len(table)
  158. for i, (host, name, value, path, expiry, is_secure) in enumerate(table):
  159. progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}')
  160. cookie = http.cookiejar.Cookie(
  161. version=0, name=name, value=value, port=None, port_specified=False,
  162. domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'),
  163. path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False,
  164. comment=None, comment_url=None, rest={})
  165. jar.set_cookie(cookie)
  166. logger.info(f'Extracted {len(jar)} cookies from firefox')
  167. return jar
  168. finally:
  169. if cursor is not None:
  170. cursor.connection.close()
  171. def _firefox_browser_dirs():
  172. if sys.platform in ('cygwin', 'win32'):
  173. yield os.path.expandvars(R'%APPDATA%\Mozilla\Firefox\Profiles')
  174. elif sys.platform == 'darwin':
  175. yield os.path.expanduser('~/Library/Application Support/Firefox/Profiles')
  176. else:
  177. yield from map(os.path.expanduser, (
  178. '~/.mozilla/firefox',
  179. '~/snap/firefox/common/.mozilla/firefox',
  180. '~/.var/app/org.mozilla.firefox/.mozilla/firefox',
  181. ))
  182. def _firefox_cookie_dbs(roots):
  183. for root in map(os.path.abspath, roots):
  184. for pattern in ('', '*/', 'Profiles/*/'):
  185. yield from glob.iglob(os.path.join(root, pattern, 'cookies.sqlite'))
  186. def _get_chromium_based_browser_settings(browser_name):
  187. # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md
  188. if sys.platform in ('cygwin', 'win32'):
  189. appdata_local = os.path.expandvars('%LOCALAPPDATA%')
  190. appdata_roaming = os.path.expandvars('%APPDATA%')
  191. browser_dir = {
  192. 'brave': os.path.join(appdata_local, R'BraveSoftware\Brave-Browser\User Data'),
  193. 'chrome': os.path.join(appdata_local, R'Google\Chrome\User Data'),
  194. 'chromium': os.path.join(appdata_local, R'Chromium\User Data'),
  195. 'edge': os.path.join(appdata_local, R'Microsoft\Edge\User Data'),
  196. 'opera': os.path.join(appdata_roaming, R'Opera Software\Opera Stable'),
  197. 'vivaldi': os.path.join(appdata_local, R'Vivaldi\User Data'),
  198. 'whale': os.path.join(appdata_local, R'Naver\Naver Whale\User Data'),
  199. }[browser_name]
  200. elif sys.platform == 'darwin':
  201. appdata = os.path.expanduser('~/Library/Application Support')
  202. browser_dir = {
  203. 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'),
  204. 'chrome': os.path.join(appdata, 'Google/Chrome'),
  205. 'chromium': os.path.join(appdata, 'Chromium'),
  206. 'edge': os.path.join(appdata, 'Microsoft Edge'),
  207. 'opera': os.path.join(appdata, 'com.operasoftware.Opera'),
  208. 'vivaldi': os.path.join(appdata, 'Vivaldi'),
  209. 'whale': os.path.join(appdata, 'Naver/Whale'),
  210. }[browser_name]
  211. else:
  212. config = _config_home()
  213. browser_dir = {
  214. 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'),
  215. 'chrome': os.path.join(config, 'google-chrome'),
  216. 'chromium': os.path.join(config, 'chromium'),
  217. 'edge': os.path.join(config, 'microsoft-edge'),
  218. 'opera': os.path.join(config, 'opera'),
  219. 'vivaldi': os.path.join(config, 'vivaldi'),
  220. 'whale': os.path.join(config, 'naver-whale'),
  221. }[browser_name]
  222. # Linux keyring names can be determined by snooping on dbus while opening the browser in KDE:
  223. # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
  224. keyring_name = {
  225. 'brave': 'Brave',
  226. 'chrome': 'Chrome',
  227. 'chromium': 'Chromium',
  228. 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium',
  229. 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium',
  230. 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome',
  231. 'whale': 'Whale',
  232. }[browser_name]
  233. browsers_without_profiles = {'opera'}
  234. return {
  235. 'browser_dir': browser_dir,
  236. 'keyring_name': keyring_name,
  237. 'supports_profiles': browser_name not in browsers_without_profiles,
  238. }
  239. def _extract_chrome_cookies(browser_name, profile, keyring, logger):
  240. logger.info(f'Extracting cookies from {browser_name}')
  241. if not sqlite3:
  242. logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. '
  243. 'Please use a Python interpreter compiled with sqlite3 support')
  244. return YoutubeDLCookieJar()
  245. config = _get_chromium_based_browser_settings(browser_name)
  246. if profile is None:
  247. search_root = config['browser_dir']
  248. elif _is_path(profile):
  249. search_root = profile
  250. config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile
  251. else:
  252. if config['supports_profiles']:
  253. search_root = os.path.join(config['browser_dir'], profile)
  254. else:
  255. logger.error(f'{browser_name} does not support profiles')
  256. search_root = config['browser_dir']
  257. cookie_database_path = _newest(_find_files(search_root, 'Cookies', logger))
  258. if cookie_database_path is None:
  259. raise FileNotFoundError(f'could not find {browser_name} cookies database in "{search_root}"')
  260. logger.debug(f'Extracting cookies from: "{cookie_database_path}"')
  261. decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring)
  262. with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:
  263. cursor = None
  264. try:
  265. cursor = _open_database_copy(cookie_database_path, tmpdir)
  266. cursor.connection.text_factory = bytes
  267. column_names = _get_column_names(cursor, 'cookies')
  268. secure_column = 'is_secure' if 'is_secure' in column_names else 'secure'
  269. cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies')
  270. jar = YoutubeDLCookieJar()
  271. failed_cookies = 0
  272. unencrypted_cookies = 0
  273. with _create_progress_bar(logger) as progress_bar:
  274. table = cursor.fetchall()
  275. total_cookie_count = len(table)
  276. for i, line in enumerate(table):
  277. progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}')
  278. is_encrypted, cookie = _process_chrome_cookie(decryptor, *line)
  279. if not cookie:
  280. failed_cookies += 1
  281. continue
  282. elif not is_encrypted:
  283. unencrypted_cookies += 1
  284. jar.set_cookie(cookie)
  285. if failed_cookies > 0:
  286. failed_message = f' ({failed_cookies} could not be decrypted)'
  287. else:
  288. failed_message = ''
  289. logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}')
  290. counts = decryptor._cookie_counts.copy()
  291. counts['unencrypted'] = unencrypted_cookies
  292. logger.debug(f'cookie version breakdown: {counts}')
  293. return jar
  294. except PermissionError as error:
  295. if compat_os_name == 'nt' and error.errno == 13:
  296. message = 'Could not copy Chrome cookie database. See https://github.com/yt-dlp/yt-dlp/issues/7271 for more info'
  297. logger.error(message)
  298. raise DownloadError(message) # force exit
  299. raise
  300. finally:
  301. if cursor is not None:
  302. cursor.connection.close()
  303. def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure):
  304. host_key = host_key.decode()
  305. name = name.decode()
  306. value = value.decode()
  307. path = path.decode()
  308. is_encrypted = not value and encrypted_value
  309. if is_encrypted:
  310. value = decryptor.decrypt(encrypted_value)
  311. if value is None:
  312. return is_encrypted, None
  313. # In chrome, session cookies have expires_utc set to 0
  314. # In our cookie-store, cookies that do not expire should have expires set to None
  315. if not expires_utc:
  316. expires_utc = None
  317. return is_encrypted, http.cookiejar.Cookie(
  318. version=0, name=name, value=value, port=None, port_specified=False,
  319. domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'),
  320. path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False,
  321. comment=None, comment_url=None, rest={})
  322. class ChromeCookieDecryptor:
  323. """
  324. Overview:
  325. Linux:
  326. - cookies are either v10 or v11
  327. - v10: AES-CBC encrypted with a fixed key
  328. - also attempts empty password if decryption fails
  329. - v11: AES-CBC encrypted with an OS protected key (keyring)
  330. - also attempts empty password if decryption fails
  331. - v11 keys can be stored in various places depending on the activate desktop environment [2]
  332. Mac:
  333. - cookies are either v10 or not v10
  334. - v10: AES-CBC encrypted with an OS protected key (keyring) and more key derivation iterations than linux
  335. - not v10: 'old data' stored as plaintext
  336. Windows:
  337. - cookies are either v10 or not v10
  338. - v10: AES-GCM encrypted with a key which is encrypted with DPAPI
  339. - not v10: encrypted with DPAPI
  340. Sources:
  341. - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/
  342. - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_linux.cc
  343. - KeyStorageLinux::CreateService
  344. """
  345. _cookie_counts = {}
  346. def decrypt(self, encrypted_value):
  347. raise NotImplementedError('Must be implemented by sub classes')
  348. def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None):
  349. if sys.platform == 'darwin':
  350. return MacChromeCookieDecryptor(browser_keyring_name, logger)
  351. elif sys.platform in ('win32', 'cygwin'):
  352. return WindowsChromeCookieDecryptor(browser_root, logger)
  353. return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring)
  354. class LinuxChromeCookieDecryptor(ChromeCookieDecryptor):
  355. def __init__(self, browser_keyring_name, logger, *, keyring=None):
  356. self._logger = logger
  357. self._v10_key = self.derive_key(b'peanuts')
  358. self._empty_key = self.derive_key(b'')
  359. self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0}
  360. self._browser_keyring_name = browser_keyring_name
  361. self._keyring = keyring
  362. @functools.cached_property
  363. def _v11_key(self):
  364. password = _get_linux_keyring_password(self._browser_keyring_name, self._keyring, self._logger)
  365. return None if password is None else self.derive_key(password)
  366. @staticmethod
  367. def derive_key(password):
  368. # values from
  369. # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_linux.cc
  370. return pbkdf2_sha1(password, salt=b'saltysalt', iterations=1, key_length=16)
  371. def decrypt(self, encrypted_value):
  372. """
  373. following the same approach as the fix in [1]: if cookies fail to decrypt then attempt to decrypt
  374. with an empty password. The failure detection is not the same as what chromium uses so the
  375. results won't be perfect
  376. References:
  377. - [1] https://chromium.googlesource.com/chromium/src/+/bbd54702284caca1f92d656fdcadf2ccca6f4165%5E%21/
  378. - a bugfix to try an empty password as a fallback
  379. """
  380. version = encrypted_value[:3]
  381. ciphertext = encrypted_value[3:]
  382. if version == b'v10':
  383. self._cookie_counts['v10'] += 1
  384. return _decrypt_aes_cbc_multi(ciphertext, (self._v10_key, self._empty_key), self._logger)
  385. elif version == b'v11':
  386. self._cookie_counts['v11'] += 1
  387. if self._v11_key is None:
  388. self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True)
  389. return None
  390. return _decrypt_aes_cbc_multi(ciphertext, (self._v11_key, self._empty_key), self._logger)
  391. else:
  392. self._logger.warning(f'unknown cookie version: "{version}"', only_once=True)
  393. self._cookie_counts['other'] += 1
  394. return None
  395. class MacChromeCookieDecryptor(ChromeCookieDecryptor):
  396. def __init__(self, browser_keyring_name, logger):
  397. self._logger = logger
  398. password = _get_mac_keyring_password(browser_keyring_name, logger)
  399. self._v10_key = None if password is None else self.derive_key(password)
  400. self._cookie_counts = {'v10': 0, 'other': 0}
  401. @staticmethod
  402. def derive_key(password):
  403. # values from
  404. # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm
  405. return pbkdf2_sha1(password, salt=b'saltysalt', iterations=1003, key_length=16)
  406. def decrypt(self, encrypted_value):
  407. version = encrypted_value[:3]
  408. ciphertext = encrypted_value[3:]
  409. if version == b'v10':
  410. self._cookie_counts['v10'] += 1
  411. if self._v10_key is None:
  412. self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True)
  413. return None
  414. return _decrypt_aes_cbc_multi(ciphertext, (self._v10_key,), self._logger)
  415. else:
  416. self._cookie_counts['other'] += 1
  417. # other prefixes are considered 'old data' which were stored as plaintext
  418. # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm
  419. return encrypted_value
  420. class WindowsChromeCookieDecryptor(ChromeCookieDecryptor):
  421. def __init__(self, browser_root, logger):
  422. self._logger = logger
  423. self._v10_key = _get_windows_v10_key(browser_root, logger)
  424. self._cookie_counts = {'v10': 0, 'other': 0}
  425. def decrypt(self, encrypted_value):
  426. version = encrypted_value[:3]
  427. ciphertext = encrypted_value[3:]
  428. if version == b'v10':
  429. self._cookie_counts['v10'] += 1
  430. if self._v10_key is None:
  431. self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True)
  432. return None
  433. # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_win.cc
  434. # kNonceLength
  435. nonce_length = 96 // 8
  436. # boringssl
  437. # EVP_AEAD_AES_GCM_TAG_LEN
  438. 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:]
  443. return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger)
  444. else:
  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/sync/os_crypt_win.cc
  448. return _decrypt_windows_dpapi(encrypted_value, self._logger).decode()
  449. def _extract_safari_cookies(profile, logger):
  450. if sys.platform != 'darwin':
  451. raise ValueError(f'unsupported platform: {sys.platform}')
  452. if profile:
  453. cookies_path = os.path.expanduser(profile)
  454. if not os.path.isfile(cookies_path):
  455. raise FileNotFoundError('custom safari cookies database not found')
  456. else:
  457. 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')
  463. with open(cookies_path, 'rb') as f:
  464. cookies_data = f.read()
  465. jar = parse_safari_cookies(cookies_data, logger=logger)
  466. logger.info(f'Extracted {len(jar)} cookies from safari')
  467. return jar
  468. class ParserError(Exception):
  469. pass
  470. class DataParser:
  471. def __init__(self, data, logger):
  472. self._data = data
  473. self.cursor = 0
  474. self._logger = logger
  475. def read_bytes(self, num_bytes):
  476. if num_bytes < 0:
  477. raise ParserError(f'invalid read of {num_bytes} bytes')
  478. end = self.cursor + num_bytes
  479. if end > len(self._data):
  480. raise ParserError('reached end of input')
  481. data = self._data[self.cursor:end]
  482. self.cursor = end
  483. return data
  484. def expect_bytes(self, expected_value, message):
  485. value = self.read_bytes(len(expected_value))
  486. if value != expected_value:
  487. raise ParserError(f'unexpected value: {value} != {expected_value} ({message})')
  488. def read_uint(self, big_endian=False):
  489. data_format = '>I' if big_endian else '<I'
  490. return struct.unpack(data_format, self.read_bytes(4))[0]
  491. def read_double(self, big_endian=False):
  492. data_format = '>d' if big_endian else '<d'
  493. return struct.unpack(data_format, self.read_bytes(8))[0]
  494. def read_cstring(self):
  495. buffer = []
  496. while True:
  497. c = self.read_bytes(1)
  498. if c == b'\x00':
  499. return b''.join(buffer).decode()
  500. else:
  501. buffer.append(c)
  502. def skip(self, num_bytes, description='unknown'):
  503. if num_bytes > 0:
  504. self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}')
  505. elif num_bytes < 0:
  506. raise ParserError(f'invalid skip of {num_bytes} bytes')
  507. def skip_to(self, offset, description='unknown'):
  508. self.skip(offset - self.cursor, description)
  509. def skip_to_end(self, description='unknown'):
  510. self.skip_to(len(self._data), description)
  511. def _mac_absolute_time_to_posix(timestamp):
  512. return int((dt.datetime(2001, 1, 1, 0, 0, tzinfo=dt.timezone.utc) + dt.timedelta(seconds=timestamp)).timestamp())
  513. def _parse_safari_cookies_header(data, logger):
  514. p = DataParser(data, logger)
  515. p.expect_bytes(b'cook', 'database signature')
  516. number_of_pages = p.read_uint(big_endian=True)
  517. page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)]
  518. return page_sizes, p.cursor
  519. def _parse_safari_cookies_page(data, jar, logger):
  520. p = DataParser(data, logger)
  521. p.expect_bytes(b'\x00\x00\x01\x00', 'page signature')
  522. number_of_cookies = p.read_uint()
  523. record_offsets = [p.read_uint() for _ in range(number_of_cookies)]
  524. if number_of_cookies == 0:
  525. logger.debug(f'a cookies page of size {len(data)} has no cookies')
  526. return
  527. p.skip_to(record_offsets[0], 'unknown page header field')
  528. with _create_progress_bar(logger) as progress_bar:
  529. for i, record_offset in enumerate(record_offsets):
  530. progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}')
  531. p.skip_to(record_offset, 'space between records')
  532. record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger)
  533. p.read_bytes(record_length)
  534. p.skip_to_end('space in between pages')
  535. def _parse_safari_cookies_record(data, jar, logger):
  536. p = DataParser(data, logger)
  537. record_size = p.read_uint()
  538. p.skip(4, 'unknown record field 1')
  539. flags = p.read_uint()
  540. is_secure = bool(flags & 0x0001)
  541. p.skip(4, 'unknown record field 2')
  542. domain_offset = p.read_uint()
  543. name_offset = p.read_uint()
  544. path_offset = p.read_uint()
  545. value_offset = p.read_uint()
  546. p.skip(8, 'unknown record field 3')
  547. expiration_date = _mac_absolute_time_to_posix(p.read_double())
  548. _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841
  549. try:
  550. p.skip_to(domain_offset)
  551. domain = p.read_cstring()
  552. p.skip_to(name_offset)
  553. name = p.read_cstring()
  554. p.skip_to(path_offset)
  555. path = p.read_cstring()
  556. p.skip_to(value_offset)
  557. value = p.read_cstring()
  558. except UnicodeDecodeError:
  559. logger.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once=True)
  560. return record_size
  561. p.skip_to(record_size, 'space at the end of the record')
  562. cookie = http.cookiejar.Cookie(
  563. version=0, name=name, value=value, port=None, port_specified=False,
  564. domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'),
  565. path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False,
  566. comment=None, comment_url=None, rest={})
  567. jar.set_cookie(cookie)
  568. return record_size
  569. def parse_safari_cookies(data, jar=None, logger=YDLLogger()):
  570. """
  571. References:
  572. - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc
  573. - this data appears to be out of date but the important parts of the database structure is the same
  574. - there are a few bytes here and there which are skipped during parsing
  575. """
  576. if jar is None:
  577. jar = YoutubeDLCookieJar()
  578. page_sizes, body_start = _parse_safari_cookies_header(data, logger)
  579. p = DataParser(data[body_start:], logger)
  580. for page_size in page_sizes:
  581. _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger)
  582. p.skip_to_end('footer')
  583. return jar
  584. class _LinuxDesktopEnvironment(Enum):
  585. """
  586. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h
  587. DesktopEnvironment
  588. """
  589. OTHER = auto()
  590. CINNAMON = auto()
  591. DEEPIN = auto()
  592. GNOME = auto()
  593. KDE3 = auto()
  594. KDE4 = auto()
  595. KDE5 = auto()
  596. KDE6 = auto()
  597. PANTHEON = auto()
  598. UKUI = auto()
  599. UNITY = auto()
  600. XFCE = auto()
  601. LXQT = auto()
  602. class _LinuxKeyring(Enum):
  603. """
  604. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_util_linux.h
  605. SelectedLinuxBackend
  606. """
  607. KWALLET = auto() # KDE4
  608. KWALLET5 = auto()
  609. KWALLET6 = auto()
  610. GNOMEKEYRING = auto()
  611. BASICTEXT = auto()
  612. SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys()
  613. def _get_linux_desktop_environment(env, logger):
  614. """
  615. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc
  616. GetDesktopEnvironment
  617. """
  618. xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None)
  619. desktop_session = env.get('DESKTOP_SESSION', None)
  620. if xdg_current_desktop is not None:
  621. for part in map(str.strip, xdg_current_desktop.split(':')):
  622. if part == 'Unity':
  623. if desktop_session is not None and 'gnome-fallback' in desktop_session:
  624. return _LinuxDesktopEnvironment.GNOME
  625. else:
  626. return _LinuxDesktopEnvironment.UNITY
  627. elif part == 'Deepin':
  628. return _LinuxDesktopEnvironment.DEEPIN
  629. elif part == 'GNOME':
  630. return _LinuxDesktopEnvironment.GNOME
  631. elif part == 'X-Cinnamon':
  632. return _LinuxDesktopEnvironment.CINNAMON
  633. elif part == 'KDE':
  634. kde_version = env.get('KDE_SESSION_VERSION', None)
  635. if kde_version == '5':
  636. return _LinuxDesktopEnvironment.KDE5
  637. elif kde_version == '6':
  638. return _LinuxDesktopEnvironment.KDE6
  639. elif kde_version == '4':
  640. return _LinuxDesktopEnvironment.KDE4
  641. else:
  642. logger.info(f'unknown KDE version: "{kde_version}". Assuming KDE4')
  643. return _LinuxDesktopEnvironment.KDE4
  644. elif part == 'Pantheon':
  645. return _LinuxDesktopEnvironment.PANTHEON
  646. elif part == 'XFCE':
  647. return _LinuxDesktopEnvironment.XFCE
  648. elif part == 'UKUI':
  649. return _LinuxDesktopEnvironment.UKUI
  650. elif part == 'LXQt':
  651. return _LinuxDesktopEnvironment.LXQT
  652. logger.info(f'XDG_CURRENT_DESKTOP is set to an unknown value: "{xdg_current_desktop}"')
  653. elif desktop_session is not None:
  654. if desktop_session == 'deepin':
  655. return _LinuxDesktopEnvironment.DEEPIN
  656. elif desktop_session in ('mate', 'gnome'):
  657. return _LinuxDesktopEnvironment.GNOME
  658. elif desktop_session in ('kde4', 'kde-plasma'):
  659. return _LinuxDesktopEnvironment.KDE4
  660. elif desktop_session == 'kde':
  661. if 'KDE_SESSION_VERSION' in env:
  662. return _LinuxDesktopEnvironment.KDE4
  663. else:
  664. return _LinuxDesktopEnvironment.KDE3
  665. elif 'xfce' in desktop_session or desktop_session == 'xubuntu':
  666. return _LinuxDesktopEnvironment.XFCE
  667. elif desktop_session == 'ukui':
  668. return _LinuxDesktopEnvironment.UKUI
  669. else:
  670. logger.info(f'DESKTOP_SESSION is set to an unknown value: "{desktop_session}"')
  671. else:
  672. if 'GNOME_DESKTOP_SESSION_ID' in env:
  673. return _LinuxDesktopEnvironment.GNOME
  674. elif 'KDE_FULL_SESSION' in env:
  675. if 'KDE_SESSION_VERSION' in env:
  676. return _LinuxDesktopEnvironment.KDE4
  677. else:
  678. return _LinuxDesktopEnvironment.KDE3
  679. return _LinuxDesktopEnvironment.OTHER
  680. def _choose_linux_keyring(logger):
  681. """
  682. SelectBackend in [1]
  683. There is currently support for forcing chromium to use BASIC_TEXT by creating a file called
  684. `Disable Local Encryption` [1] in the user data dir. The function to write this file (`WriteBackendUse()` [1])
  685. does not appear to be called anywhere other than in tests, so the user would have to create this file manually
  686. and so would be aware enough to tell yt-dlp to use the BASIC_TEXT keyring.
  687. References:
  688. - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_util_linux.cc
  689. """
  690. desktop_environment = _get_linux_desktop_environment(os.environ, logger)
  691. logger.debug(f'detected desktop environment: {desktop_environment.name}')
  692. if desktop_environment == _LinuxDesktopEnvironment.KDE4:
  693. linux_keyring = _LinuxKeyring.KWALLET
  694. elif desktop_environment == _LinuxDesktopEnvironment.KDE5:
  695. linux_keyring = _LinuxKeyring.KWALLET5
  696. elif desktop_environment == _LinuxDesktopEnvironment.KDE6:
  697. linux_keyring = _LinuxKeyring.KWALLET6
  698. elif desktop_environment in (
  699. _LinuxDesktopEnvironment.KDE3, _LinuxDesktopEnvironment.LXQT, _LinuxDesktopEnvironment.OTHER,
  700. ):
  701. linux_keyring = _LinuxKeyring.BASICTEXT
  702. else:
  703. linux_keyring = _LinuxKeyring.GNOMEKEYRING
  704. return linux_keyring
  705. def _get_kwallet_network_wallet(keyring, logger):
  706. """ The name of the wallet used to store network passwords.
  707. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/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
  712. """
  713. default_wallet = 'kdewallet'
  714. try:
  715. if keyring == _LinuxKeyring.KWALLET:
  716. service_name = 'org.kde.kwalletd'
  717. wallet_path = '/modules/kwalletd'
  718. elif keyring == _LinuxKeyring.KWALLET5:
  719. service_name = 'org.kde.kwalletd5'
  720. wallet_path = '/modules/kwalletd5'
  721. elif keyring == _LinuxKeyring.KWALLET6:
  722. service_name = 'org.kde.kwalletd6'
  723. wallet_path = '/modules/kwalletd6'
  724. else:
  725. raise ValueError(keyring)
  726. stdout, _, returncode = Popen.run([
  727. 'dbus-send', '--session', '--print-reply=literal',
  728. f'--dest={service_name}',
  729. wallet_path,
  730. 'org.kde.KWallet.networkWallet',
  731. ], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  732. if returncode:
  733. logger.warning('failed to read NetworkWallet')
  734. return default_wallet
  735. else:
  736. logger.debug(f'NetworkWallet = "{stdout.strip()}"')
  737. return stdout.strip()
  738. except Exception as e:
  739. logger.warning(f'exception while obtaining NetworkWallet: {e}')
  740. return default_wallet
  741. def _get_kwallet_password(browser_keyring_name, keyring, logger):
  742. logger.debug(f'using kwallet-query to obtain password from {keyring.name}')
  743. if shutil.which('kwallet-query') is None:
  744. logger.error('kwallet-query command not found. KWallet and kwallet-query '
  745. 'must be installed to read from KWallet. kwallet-query should be'
  746. 'included in the kwallet package for your distribution')
  747. return b''
  748. network_wallet = _get_kwallet_network_wallet(keyring, logger)
  749. try:
  750. stdout, _, returncode = Popen.run([
  751. 'kwallet-query',
  752. '--read-password', f'{browser_keyring_name} Safe Storage',
  753. '--folder', f'{browser_keyring_name} Keys',
  754. network_wallet,
  755. ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  756. if returncode:
  757. logger.error(f'kwallet-query failed with return code {returncode}. '
  758. 'Please consult the kwallet-query man page for details')
  759. return b''
  760. else:
  761. if stdout.lower().startswith(b'failed to read'):
  762. logger.debug('failed to read password from kwallet. Using empty string instead')
  763. # this sometimes occurs in KDE because chrome does not check hasEntry and instead
  764. # just tries to read the value (which kwallet returns "") whereas kwallet-query
  765. # checks hasEntry. To verify this:
  766. # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
  767. # while starting chrome.
  768. # this was identified as a bug later and fixed in
  769. # https://chromium.googlesource.com/chromium/src/+/bbd54702284caca1f92d656fdcadf2ccca6f4165%5E%21/#F0
  770. # https://chromium.googlesource.com/chromium/src/+/5463af3c39d7f5b6d11db7fbd51e38cc1974d764
  771. return b''
  772. else:
  773. logger.debug('password found')
  774. return stdout.rstrip(b'\n')
  775. except Exception as e:
  776. logger.warning(f'exception running kwallet-query: {error_to_str(e)}')
  777. return b''
  778. def _get_gnome_keyring_password(browser_keyring_name, logger):
  779. if not secretstorage:
  780. logger.error(f'secretstorage not available {_SECRETSTORAGE_UNAVAILABLE_REASON}')
  781. return b''
  782. # the Gnome keyring does not seem to organise keys in the same way as KWallet,
  783. # using `dbus-monitor` during startup, it can be observed that chromium lists all keys
  784. # and presumably searches for its key in the list. It appears that we must do the same.
  785. # https://github.com/jaraco/keyring/issues/556
  786. with contextlib.closing(secretstorage.dbus_init()) as con:
  787. col = secretstorage.get_default_collection(con)
  788. for item in col.get_all_items():
  789. if item.get_label() == f'{browser_keyring_name} Safe Storage':
  790. return item.get_secret()
  791. logger.error('failed to read from keyring')
  792. return b''
  793. def _get_linux_keyring_password(browser_keyring_name, keyring, logger):
  794. # note: chrome/chromium can be run with the following flags to determine which keyring backend
  795. # it has chosen to use
  796. # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_
  797. # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection
  798. # will not be sufficient in all cases.
  799. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger)
  800. logger.debug(f'Chosen keyring: {keyring.name}')
  801. if keyring in (_LinuxKeyring.KWALLET, _LinuxKeyring.KWALLET5, _LinuxKeyring.KWALLET6):
  802. return _get_kwallet_password(browser_keyring_name, keyring, 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)
  807. return None
  808. assert False, f'Unknown keyring {keyring}'
  809. def _get_mac_keyring_password(browser_keyring_name, logger):
  810. logger.debug('using find-generic-password to obtain password from OSX keychain')
  811. try:
  812. stdout, _, returncode = Popen.run(
  813. ['security', 'find-generic-password',
  814. '-w', # write password to stdout
  815. '-a', browser_keyring_name, # match 'account'
  816. '-s', f'{browser_keyring_name} Safe Storage'], # match 'service'
  817. stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  818. if returncode:
  819. logger.warning('find-generic-password failed')
  820. return None
  821. return stdout.rstrip(b'\n')
  822. except Exception as e:
  823. logger.warning(f'exception running find-generic-password: {error_to_str(e)}')
  824. return None
  825. def _get_windows_v10_key(browser_root, logger):
  826. """
  827. References:
  828. - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_win.cc
  829. """
  830. path = _newest(_find_files(browser_root, 'Local State', logger))
  831. if path is None:
  832. logger.error('could not find local state file')
  833. return None
  834. logger.debug(f'Found local state file at "{path}"')
  835. with open(path, encoding='utf8') as f:
  836. data = json.load(f)
  837. try:
  838. # kOsCryptEncryptedKeyPrefName in [1]
  839. base64_key = data['os_crypt']['encrypted_key']
  840. except KeyError:
  841. logger.error('no encrypted key in Local State')
  842. return None
  843. encrypted_key = base64.b64decode(base64_key)
  844. # kDPAPIKeyPrefix in [1]
  845. prefix = b'DPAPI'
  846. if not encrypted_key.startswith(prefix):
  847. logger.error('invalid key')
  848. return None
  849. return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger)
  850. def pbkdf2_sha1(password, salt, iterations, key_length):
  851. return hashlib.pbkdf2_hmac('sha1', password, salt, iterations, key_length)
  852. def _decrypt_aes_cbc_multi(ciphertext, keys, logger, initialization_vector=b' ' * 16):
  853. for key in keys:
  854. plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector))
  855. try:
  856. return plaintext.decode()
  857. except UnicodeDecodeError:
  858. pass
  859. logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True)
  860. return None
  861. def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger):
  862. try:
  863. plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce)
  864. except ValueError:
  865. logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?', only_once=True)
  866. return None
  867. try:
  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)
  871. return None
  872. def _decrypt_windows_dpapi(ciphertext, logger):
  873. """
  874. References:
  875. - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata
  876. """
  877. import ctypes
  878. import ctypes.wintypes
  879. class DATA_BLOB(ctypes.Structure):
  880. _fields_ = [('cbData', ctypes.wintypes.DWORD),
  881. ('pbData', ctypes.POINTER(ctypes.c_char))]
  882. buffer = ctypes.create_string_buffer(ciphertext)
  883. blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer)
  884. blob_out = DATA_BLOB()
  885. ret = ctypes.windll.crypt32.CryptUnprotectData(
  886. ctypes.byref(blob_in), # pDataIn
  887. None, # ppszDataDescr: human readable description of pDataIn
  888. None, # pOptionalEntropy: salt?
  889. None, # pvReserved: must be NULL
  890. None, # pPromptStruct: information about prompts to display
  891. 0, # dwFlags
  892. ctypes.byref(blob_out), # pDataOut
  893. )
  894. if not ret:
  895. message = 'Failed to decrypt with DPAPI. See https://github.com/yt-dlp/yt-dlp/issues/10927 for more info'
  896. logger.error(message)
  897. raise DownloadError(message) # force exit
  898. result = ctypes.string_at(blob_out.pbData, blob_out.cbData)
  899. ctypes.windll.kernel32.LocalFree(blob_out.pbData)
  900. return result
  901. def _config_home():
  902. return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
  903. def _open_database_copy(database_path, tmpdir):
  904. # cannot open sqlite databases if they are already in use (e.g. by the browser)
  905. database_copy_path = os.path.join(tmpdir, 'temporary.sqlite')
  906. shutil.copy(database_path, database_copy_path)
  907. conn = sqlite3.connect(database_copy_path)
  908. return conn.cursor()
  909. def _get_column_names(cursor, table_name):
  910. table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall()
  911. return [row[1].decode() for row in table_info]
  912. def _newest(files):
  913. return max(files, key=lambda path: os.lstat(path).st_mtime, default=None)
  914. def _find_files(root, filename, logger):
  915. # if there are multiple browser profiles, take the most recently used one
  916. i = 0
  917. with _create_progress_bar(logger) as progress_bar:
  918. for curr_root, _, files in os.walk(root):
  919. for file in files:
  920. i += 1
  921. progress_bar.print(f'Searching for "{filename}": {i: 6d} files searched')
  922. if file == filename:
  923. yield os.path.join(curr_root, file)
  924. def _merge_cookie_jars(jars):
  925. output_jar = YoutubeDLCookieJar()
  926. for jar in jars:
  927. for cookie in jar:
  928. output_jar.set_cookie(cookie)
  929. if jar.filename is not None:
  930. output_jar.filename = jar.filename
  931. return output_jar
  932. def _is_path(value):
  933. return any(sep in value for sep in (os.path.sep, os.path.altsep) if sep)
  934. def _parse_browser_specification(browser_name, profile=None, keyring=None, container=None):
  935. if browser_name not in SUPPORTED_BROWSERS:
  936. raise ValueError(f'unsupported browser: "{browser_name}"')
  937. if keyring not in (None, *SUPPORTED_KEYRINGS):
  938. raise ValueError(f'unsupported keyring: "{keyring}"')
  939. if profile is not None and _is_path(expand_path(profile)):
  940. profile = expand_path(profile)
  941. return browser_name, profile, keyring, container
  942. class LenientSimpleCookie(http.cookies.SimpleCookie):
  943. """More lenient version of http.cookies.SimpleCookie"""
  944. # From https://github.com/python/cpython/blob/v3.10.7/Lib/http/cookies.py
  945. # We use Morsel's legal key chars to avoid errors on setting values
  946. _LEGAL_KEY_CHARS = r'\w\d' + re.escape('!#$%&\'*+-.:^_`|~')
  947. _LEGAL_VALUE_CHARS = _LEGAL_KEY_CHARS + re.escape('(),/<=>?@[]{}')
  948. _RESERVED = {
  949. 'expires',
  950. 'path',
  951. 'comment',
  952. 'domain',
  953. 'max-age',
  954. 'secure',
  955. 'httponly',
  956. 'version',
  957. 'samesite',
  958. }
  959. _FLAGS = {'secure', 'httponly'}
  960. # Added 'bad' group to catch the remaining value
  961. _COOKIE_PATTERN = re.compile(r'''
  962. \s* # Optional whitespace at start of cookie
  963. (?P<key> # Start of group 'key'
  964. [''' + _LEGAL_KEY_CHARS + r''']+?# Any word of at least one letter
  965. ) # End of group 'key'
  966. ( # Optional group: there may not be a value.
  967. \s*=\s* # Equal Sign
  968. ( # Start of potential value
  969. (?P<val> # Start of group 'val'
  970. "(?:[^\\"]|\\.)*" # Any doublequoted string
  971. | # or
  972. \w{3},\s[\w\d\s-]{9,11}\s[\d:]{8}\sGMT # Special case for "expires" attr
  973. | # or
  974. [''' + _LEGAL_VALUE_CHARS + r''']* # Any word or empty string
  975. ) # End of group 'val'
  976. | # or
  977. (?P<bad>(?:\\;|[^;])*?) # 'bad' group fallback for invalid values
  978. ) # End of potential value
  979. )? # End of optional value group
  980. \s* # Any number of spaces.
  981. (\s+|;|$) # Ending either at space, semicolon, or EOS.
  982. ''', re.ASCII | re.VERBOSE)
  983. def load(self, data):
  984. # Workaround for https://github.com/yt-dlp/yt-dlp/issues/4776
  985. if not isinstance(data, str):
  986. return super().load(data)
  987. morsel = None
  988. for match in self._COOKIE_PATTERN.finditer(data):
  989. if match.group('bad'):
  990. morsel = None
  991. continue
  992. key, value = match.group('key', 'val')
  993. is_attribute = False
  994. if key.startswith('$'):
  995. key = key[1:]
  996. is_attribute = True
  997. lower_key = key.lower()
  998. if lower_key in self._RESERVED:
  999. if morsel is None:
  1000. continue
  1001. if value is None:
  1002. if lower_key not in self._FLAGS:
  1003. morsel = None
  1004. continue
  1005. value = True
  1006. else:
  1007. value, _ = self.value_decode(value)
  1008. morsel[key] = value
  1009. elif is_attribute:
  1010. morsel = None
  1011. elif value is not None:
  1012. morsel = self.get(key, http.cookies.Morsel())
  1013. real_value, coded_value = self.value_decode(value)
  1014. morsel.set(key, real_value, coded_value)
  1015. self[key] = morsel
  1016. else:
  1017. morsel = None
  1018. class YoutubeDLCookieJar(http.cookiejar.MozillaCookieJar):
  1019. """
  1020. See [1] for cookie file format.
  1021. 1. https://curl.haxx.se/docs/http-cookies.html
  1022. """
  1023. _HTTPONLY_PREFIX = '#HttpOnly_'
  1024. _ENTRY_LEN = 7
  1025. _HEADER = '''# Netscape HTTP Cookie File
  1026. # This file is generated by yt-dlp. Do not edit.
  1027. '''
  1028. _CookieFileEntry = collections.namedtuple(
  1029. 'CookieFileEntry',
  1030. ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
  1031. def __init__(self, filename=None, *args, **kwargs):
  1032. super().__init__(None, *args, **kwargs)
  1033. if is_path_like(filename):
  1034. filename = os.fspath(filename)
  1035. self.filename = filename
  1036. @staticmethod
  1037. def _true_or_false(cndn):
  1038. return 'TRUE' if cndn else 'FALSE'
  1039. @contextlib.contextmanager
  1040. def open(self, file, *, write=False):
  1041. if is_path_like(file):
  1042. with open(file, 'w' if write else 'r', encoding='utf-8') as f:
  1043. yield f
  1044. else:
  1045. if write:
  1046. file.truncate(0)
  1047. yield file
  1048. def _really_save(self, f, ignore_discard, ignore_expires):
  1049. now = time.time()
  1050. for cookie in self:
  1051. if (not ignore_discard and cookie.discard
  1052. or not ignore_expires and cookie.is_expired(now)):
  1053. continue
  1054. name, value = cookie.name, cookie.value
  1055. if value is None:
  1056. # cookies.txt regards 'Set-Cookie: foo' as a cookie
  1057. # with no name, whereas http.cookiejar regards it as a
  1058. # cookie with no value.
  1059. name, value = '', name
  1060. f.write('{}\n'.format('\t'.join((
  1061. cookie.domain,
  1062. self._true_or_false(cookie.domain.startswith('.')),
  1063. cookie.path,
  1064. self._true_or_false(cookie.secure),
  1065. str_or_none(cookie.expires, default=''),
  1066. name, value,
  1067. ))))
  1068. def save(self, filename=None, ignore_discard=True, ignore_expires=True):
  1069. """
  1070. Save cookies to a file.
  1071. Code is taken from CPython 3.6
  1072. https://github.com/python/cpython/blob/8d999cbf4adea053be6dbb612b9844635c4dfb8e/Lib/http/cookiejar.py#L2091-L2117 """
  1073. if filename is None:
  1074. if self.filename is not None:
  1075. filename = self.filename
  1076. else:
  1077. raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)
  1078. # Store session cookies with `expires` set to 0 instead of an empty string
  1079. for cookie in self:
  1080. if cookie.expires is None:
  1081. cookie.expires = 0
  1082. with self.open(filename, write=True) as f:
  1083. f.write(self._HEADER)
  1084. self._really_save(f, ignore_discard, ignore_expires)
  1085. def load(self, filename=None, ignore_discard=True, ignore_expires=True):
  1086. """Load cookies from a file."""
  1087. if filename is None:
  1088. if self.filename is not None:
  1089. filename = self.filename
  1090. else:
  1091. raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)
  1092. def prepare_line(line):
  1093. if line.startswith(self._HTTPONLY_PREFIX):
  1094. line = line[len(self._HTTPONLY_PREFIX):]
  1095. # comments and empty lines are fine
  1096. if line.startswith('#') or not line.strip():
  1097. return line
  1098. cookie_list = line.split('\t')
  1099. if len(cookie_list) != self._ENTRY_LEN:
  1100. raise http.cookiejar.LoadError(f'invalid length {len(cookie_list)}')
  1101. cookie = self._CookieFileEntry(*cookie_list)
  1102. if cookie.expires_at and not cookie.expires_at.isdigit():
  1103. raise http.cookiejar.LoadError(f'invalid expires at {cookie.expires_at}')
  1104. return line
  1105. cf = io.StringIO()
  1106. with self.open(filename) as f:
  1107. for line in f:
  1108. try:
  1109. cf.write(prepare_line(line))
  1110. except http.cookiejar.LoadError as e:
  1111. if f'{line.strip()} '[0] in '[{"':
  1112. raise http.cookiejar.LoadError(
  1113. 'Cookies file must be Netscape formatted, not JSON. See '
  1114. 'https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp')
  1115. write_string(f'WARNING: skipping cookie file entry due to {e}: {line!r}\n')
  1116. continue
  1117. cf.seek(0)
  1118. self._really_load(cf, filename, ignore_discard, ignore_expires)
  1119. # Session cookies are denoted by either `expires` field set to
  1120. # an empty string or 0. MozillaCookieJar only recognizes the former
  1121. # (see [1]). So we need force the latter to be recognized as session
  1122. # cookies on our own.
  1123. # Session cookies may be important for cookies-based authentication,
  1124. # e.g. usually, when user does not check 'Remember me' check box while
  1125. # logging in on a site, some important cookies are stored as session
  1126. # cookies so that not recognizing them will result in failed login.
  1127. # 1. https://bugs.python.org/issue17164
  1128. for cookie in self:
  1129. # Treat `expires=0` cookies as session cookies
  1130. if cookie.expires == 0:
  1131. cookie.expires = None
  1132. cookie.discard = True
  1133. def get_cookie_header(self, url):
  1134. """Generate a Cookie HTTP header for a given url"""
  1135. cookie_req = urllib.request.Request(normalize_url(sanitize_url(url)))
  1136. self.add_cookie_header(cookie_req)
  1137. return cookie_req.get_header('Cookie')
  1138. def get_cookies_for_url(self, url):
  1139. """Generate a list of Cookie objects for a given url"""
  1140. # Policy `_now` attribute must be set before calling `_cookies_for_request`
  1141. # Ref: https://github.com/python/cpython/blob/3.7/Lib/http/cookiejar.py#L1360
  1142. self._policy._now = self._now = int(time.time())
  1143. return self._cookies_for_request(urllib.request.Request(normalize_url(sanitize_url(url))))
  1144. def clear(self, *args, **kwargs):
  1145. with contextlib.suppress(KeyError):
  1146. return super().clear(*args, **kwargs)