cookies.py 55 KB

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