cookies.py 54 KB

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