cookies.py 55 KB

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